Initial commit
[yaffs-website] / node_modules / request / request.js
1 'use strict'
2
3 var http = require('http')
4   , https = require('https')
5   , url = require('url')
6   , util = require('util')
7   , stream = require('stream')
8   , zlib = require('zlib')
9   , hawk = require('hawk')
10   , aws2 = require('aws-sign2')
11   , aws4 = require('aws4')
12   , httpSignature = require('http-signature')
13   , mime = require('mime-types')
14   , stringstream = require('stringstream')
15   , caseless = require('caseless')
16   , ForeverAgent = require('forever-agent')
17   , FormData = require('form-data')
18   , extend = require('extend')
19   , isstream = require('isstream')
20   , isTypedArray = require('is-typedarray').strict
21   , helpers = require('./lib/helpers')
22   , cookies = require('./lib/cookies')
23   , getProxyFromURI = require('./lib/getProxyFromURI')
24   , Querystring = require('./lib/querystring').Querystring
25   , Har = require('./lib/har').Har
26   , Auth = require('./lib/auth').Auth
27   , OAuth = require('./lib/oauth').OAuth
28   , Multipart = require('./lib/multipart').Multipart
29   , Redirect = require('./lib/redirect').Redirect
30   , Tunnel = require('./lib/tunnel').Tunnel
31   , now = require('performance-now')
32
33 var safeStringify = helpers.safeStringify
34   , isReadStream = helpers.isReadStream
35   , toBase64 = helpers.toBase64
36   , defer = helpers.defer
37   , copy = helpers.copy
38   , version = helpers.version
39   , globalCookieJar = cookies.jar()
40
41
42 var globalPool = {}
43
44 function filterForNonReserved(reserved, options) {
45   // Filter out properties that are not reserved.
46   // Reserved values are passed in at call site.
47
48   var object = {}
49   for (var i in options) {
50     var notReserved = (reserved.indexOf(i) === -1)
51     if (notReserved) {
52       object[i] = options[i]
53     }
54   }
55   return object
56 }
57
58 function filterOutReservedFunctions(reserved, options) {
59   // Filter out properties that are functions and are reserved.
60   // Reserved values are passed in at call site.
61
62   var object = {}
63   for (var i in options) {
64     var isReserved = !(reserved.indexOf(i) === -1)
65     var isFunction = (typeof options[i] === 'function')
66     if (!(isReserved && isFunction)) {
67       object[i] = options[i]
68     }
69   }
70   return object
71
72 }
73
74 // Return a simpler request object to allow serialization
75 function requestToJSON() {
76   var self = this
77   return {
78     uri: self.uri,
79     method: self.method,
80     headers: self.headers
81   }
82 }
83
84 // Return a simpler response object to allow serialization
85 function responseToJSON() {
86   var self = this
87   return {
88     statusCode: self.statusCode,
89     body: self.body,
90     headers: self.headers,
91     request: requestToJSON.call(self.request)
92   }
93 }
94
95 function Request (options) {
96   // if given the method property in options, set property explicitMethod to true
97
98   // extend the Request instance with any non-reserved properties
99   // remove any reserved functions from the options object
100   // set Request instance to be readable and writable
101   // call init
102
103   var self = this
104
105   // start with HAR, then override with additional options
106   if (options.har) {
107     self._har = new Har(self)
108     options = self._har.options(options)
109   }
110
111   stream.Stream.call(self)
112   var reserved = Object.keys(Request.prototype)
113   var nonReserved = filterForNonReserved(reserved, options)
114
115   extend(self, nonReserved)
116   options = filterOutReservedFunctions(reserved, options)
117
118   self.readable = true
119   self.writable = true
120   if (options.method) {
121     self.explicitMethod = true
122   }
123   self._qs = new Querystring(self)
124   self._auth = new Auth(self)
125   self._oauth = new OAuth(self)
126   self._multipart = new Multipart(self)
127   self._redirect = new Redirect(self)
128   self._tunnel = new Tunnel(self)
129   self.init(options)
130 }
131
132 util.inherits(Request, stream.Stream)
133
134 // Debugging
135 Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
136 function debug() {
137   if (Request.debug) {
138     console.error('REQUEST %s', util.format.apply(util, arguments))
139   }
140 }
141 Request.prototype.debug = debug
142
143 Request.prototype.init = function (options) {
144   // init() contains all the code to setup the request object.
145   // the actual outgoing request is not started until start() is called
146   // this function is called from both the constructor and on redirect.
147   var self = this
148   if (!options) {
149     options = {}
150   }
151   self.headers = self.headers ? copy(self.headers) : {}
152
153   // Delete headers with value undefined since they break
154   // ClientRequest.OutgoingMessage.setHeader in node 0.12
155   for (var headerName in self.headers) {
156     if (typeof self.headers[headerName] === 'undefined') {
157       delete self.headers[headerName]
158     }
159   }
160
161   caseless.httpify(self, self.headers)
162
163   if (!self.method) {
164     self.method = options.method || 'GET'
165   }
166   if (!self.localAddress) {
167     self.localAddress = options.localAddress
168   }
169
170   self._qs.init(options)
171
172   debug(options)
173   if (!self.pool && self.pool !== false) {
174     self.pool = globalPool
175   }
176   self.dests = self.dests || []
177   self.__isRequestRequest = true
178
179   // Protect against double callback
180   if (!self._callback && self.callback) {
181     self._callback = self.callback
182     self.callback = function () {
183       if (self._callbackCalled) {
184         return // Print a warning maybe?
185       }
186       self._callbackCalled = true
187       self._callback.apply(self, arguments)
188     }
189     self.on('error', self.callback.bind())
190     self.on('complete', self.callback.bind(self, null))
191   }
192
193   // People use this property instead all the time, so support it
194   if (!self.uri && self.url) {
195     self.uri = self.url
196     delete self.url
197   }
198
199   // If there's a baseUrl, then use it as the base URL (i.e. uri must be
200   // specified as a relative path and is appended to baseUrl).
201   if (self.baseUrl) {
202     if (typeof self.baseUrl !== 'string') {
203       return self.emit('error', new Error('options.baseUrl must be a string'))
204     }
205
206     if (typeof self.uri !== 'string') {
207       return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'))
208     }
209
210     if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) {
211       return self.emit('error', new Error('options.uri must be a path when using options.baseUrl'))
212     }
213
214     // Handle all cases to make sure that there's only one slash between
215     // baseUrl and uri.
216     var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1
217     var uriStartsWithSlash = self.uri.indexOf('/') === 0
218
219     if (baseUrlEndsWithSlash && uriStartsWithSlash) {
220       self.uri = self.baseUrl + self.uri.slice(1)
221     } else if (baseUrlEndsWithSlash || uriStartsWithSlash) {
222       self.uri = self.baseUrl + self.uri
223     } else if (self.uri === '') {
224       self.uri = self.baseUrl
225     } else {
226       self.uri = self.baseUrl + '/' + self.uri
227     }
228     delete self.baseUrl
229   }
230
231   // A URI is needed by this point, emit error if we haven't been able to get one
232   if (!self.uri) {
233     return self.emit('error', new Error('options.uri is a required argument'))
234   }
235
236   // If a string URI/URL was given, parse it into a URL object
237   if (typeof self.uri === 'string') {
238     self.uri = url.parse(self.uri)
239   }
240
241   // Some URL objects are not from a URL parsed string and need href added
242   if (!self.uri.href) {
243     self.uri.href = url.format(self.uri)
244   }
245
246   // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme
247   if (self.uri.protocol === 'unix:') {
248     return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'))
249   }
250
251   // Support Unix Sockets
252   if (self.uri.host === 'unix') {
253     self.enableUnixSocket()
254   }
255
256   if (self.strictSSL === false) {
257     self.rejectUnauthorized = false
258   }
259
260   if (!self.uri.pathname) {self.uri.pathname = '/'}
261
262   if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
263     // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
264     // Detect and reject it as soon as possible
265     var faultyUri = url.format(self.uri)
266     var message = 'Invalid URI "' + faultyUri + '"'
267     if (Object.keys(options).length === 0) {
268       // No option ? This can be the sign of a redirect
269       // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
270       // they should be warned that it can be caused by a redirection (can save some hair)
271       message += '. This can be caused by a crappy redirection.'
272     }
273     // This error was fatal
274     self.abort()
275     return self.emit('error', new Error(message))
276   }
277
278   if (!self.hasOwnProperty('proxy')) {
279     self.proxy = getProxyFromURI(self.uri)
280   }
281
282   self.tunnel = self._tunnel.isEnabled()
283   if (self.proxy) {
284     self._tunnel.setup(options)
285   }
286
287   self._redirect.onRequest(options)
288
289   self.setHost = false
290   if (!self.hasHeader('host')) {
291     var hostHeaderName = self.originalHostHeaderName || 'host'
292     // When used with an IPv6 address, `host` will provide
293     // the correct bracketed format, unlike using `hostname` and
294     // optionally adding the `port` when necessary.
295     self.setHeader(hostHeaderName, self.uri.host)
296     self.setHost = true
297   }
298
299   self.jar(self._jar || options.jar)
300
301   if (!self.uri.port) {
302     if (self.uri.protocol === 'http:') {self.uri.port = 80}
303     else if (self.uri.protocol === 'https:') {self.uri.port = 443}
304   }
305
306   if (self.proxy && !self.tunnel) {
307     self.port = self.proxy.port
308     self.host = self.proxy.hostname
309   } else {
310     self.port = self.uri.port
311     self.host = self.uri.hostname
312   }
313
314   if (options.form) {
315     self.form(options.form)
316   }
317
318   if (options.formData) {
319     var formData = options.formData
320     var requestForm = self.form()
321     var appendFormValue = function (key, value) {
322       if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
323         requestForm.append(key, value.value, value.options)
324       } else {
325         requestForm.append(key, value)
326       }
327     }
328     for (var formKey in formData) {
329       if (formData.hasOwnProperty(formKey)) {
330         var formValue = formData[formKey]
331         if (formValue instanceof Array) {
332           for (var j = 0; j < formValue.length; j++) {
333             appendFormValue(formKey, formValue[j])
334           }
335         } else {
336           appendFormValue(formKey, formValue)
337         }
338       }
339     }
340   }
341
342   if (options.qs) {
343     self.qs(options.qs)
344   }
345
346   if (self.uri.path) {
347     self.path = self.uri.path
348   } else {
349     self.path = self.uri.pathname + (self.uri.search || '')
350   }
351
352   if (self.path.length === 0) {
353     self.path = '/'
354   }
355
356   // Auth must happen last in case signing is dependent on other headers
357   if (options.aws) {
358     self.aws(options.aws)
359   }
360
361   if (options.hawk) {
362     self.hawk(options.hawk)
363   }
364
365   if (options.httpSignature) {
366     self.httpSignature(options.httpSignature)
367   }
368
369   if (options.auth) {
370     if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
371       options.auth.user = options.auth.username
372     }
373     if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
374       options.auth.pass = options.auth.password
375     }
376
377     self.auth(
378       options.auth.user,
379       options.auth.pass,
380       options.auth.sendImmediately,
381       options.auth.bearer
382     )
383   }
384
385   if (self.gzip && !self.hasHeader('accept-encoding')) {
386     self.setHeader('accept-encoding', 'gzip, deflate')
387   }
388
389   if (self.uri.auth && !self.hasHeader('authorization')) {
390     var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
391     self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
392   }
393
394   if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
395     var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
396     var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
397     self.setHeader('proxy-authorization', authHeader)
398   }
399
400   if (self.proxy && !self.tunnel) {
401     self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
402   }
403
404   if (options.json) {
405     self.json(options.json)
406   }
407   if (options.multipart) {
408     self.multipart(options.multipart)
409   }
410
411   if (options.time) {
412     self.timing = true
413
414     // NOTE: elapsedTime is deprecated in favor of .timings
415     self.elapsedTime = self.elapsedTime || 0
416   }
417
418   function setContentLength () {
419     if (isTypedArray(self.body)) {
420       self.body = new Buffer(self.body)
421     }
422
423     if (!self.hasHeader('content-length')) {
424       var length
425       if (typeof self.body === 'string') {
426         length = Buffer.byteLength(self.body)
427       }
428       else if (Array.isArray(self.body)) {
429         length = self.body.reduce(function (a, b) {return a + b.length}, 0)
430       }
431       else {
432         length = self.body.length
433       }
434
435       if (length) {
436         self.setHeader('content-length', length)
437       } else {
438         self.emit('error', new Error('Argument error, options.body.'))
439       }
440     }
441   }
442   if (self.body && !isstream(self.body)) {
443     setContentLength()
444   }
445
446   if (options.oauth) {
447     self.oauth(options.oauth)
448   } else if (self._oauth.params && self.hasHeader('authorization')) {
449     self.oauth(self._oauth.params)
450   }
451
452   var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
453     , defaultModules = {'http:':http, 'https:':https}
454     , httpModules = self.httpModules || {}
455
456   self.httpModule = httpModules[protocol] || defaultModules[protocol]
457
458   if (!self.httpModule) {
459     return self.emit('error', new Error('Invalid protocol: ' + protocol))
460   }
461
462   if (options.ca) {
463     self.ca = options.ca
464   }
465
466   if (!self.agent) {
467     if (options.agentOptions) {
468       self.agentOptions = options.agentOptions
469     }
470
471     if (options.agentClass) {
472       self.agentClass = options.agentClass
473     } else if (options.forever) {
474       var v = version()
475       // use ForeverAgent in node 0.10- only
476       if (v.major === 0 && v.minor <= 10) {
477         self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
478       } else {
479         self.agentClass = self.httpModule.Agent
480         self.agentOptions = self.agentOptions || {}
481         self.agentOptions.keepAlive = true
482       }
483     } else {
484       self.agentClass = self.httpModule.Agent
485     }
486   }
487
488   if (self.pool === false) {
489     self.agent = false
490   } else {
491     self.agent = self.agent || self.getNewAgent()
492   }
493
494   self.on('pipe', function (src) {
495     if (self.ntick && self._started) {
496       self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'))
497     }
498     self.src = src
499     if (isReadStream(src)) {
500       if (!self.hasHeader('content-type')) {
501         self.setHeader('content-type', mime.lookup(src.path))
502       }
503     } else {
504       if (src.headers) {
505         for (var i in src.headers) {
506           if (!self.hasHeader(i)) {
507             self.setHeader(i, src.headers[i])
508           }
509         }
510       }
511       if (self._json && !self.hasHeader('content-type')) {
512         self.setHeader('content-type', 'application/json')
513       }
514       if (src.method && !self.explicitMethod) {
515         self.method = src.method
516       }
517     }
518
519     // self.on('pipe', function () {
520     //   console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
521     // })
522   })
523
524   defer(function () {
525     if (self._aborted) {
526       return
527     }
528
529     var end = function () {
530       if (self._form) {
531         if (!self._auth.hasAuth) {
532           self._form.pipe(self)
533         }
534         else if (self._auth.hasAuth && self._auth.sentAuth) {
535           self._form.pipe(self)
536         }
537       }
538       if (self._multipart && self._multipart.chunked) {
539         self._multipart.body.pipe(self)
540       }
541       if (self.body) {
542         if (isstream(self.body)) {
543           self.body.pipe(self)
544         } else {
545           setContentLength()
546           if (Array.isArray(self.body)) {
547             self.body.forEach(function (part) {
548               self.write(part)
549             })
550           } else {
551             self.write(self.body)
552           }
553           self.end()
554         }
555       } else if (self.requestBodyStream) {
556         console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
557         self.requestBodyStream.pipe(self)
558       } else if (!self.src) {
559         if (self._auth.hasAuth && !self._auth.sentAuth) {
560           self.end()
561           return
562         }
563         if (self.method !== 'GET' && typeof self.method !== 'undefined') {
564           self.setHeader('content-length', 0)
565         }
566         self.end()
567       }
568     }
569
570     if (self._form && !self.hasHeader('content-length')) {
571       // Before ending the request, we had to compute the length of the whole form, asyncly
572       self.setHeader(self._form.getHeaders(), true)
573       self._form.getLength(function (err, length) {
574         if (!err && !isNaN(length)) {
575           self.setHeader('content-length', length)
576         }
577         end()
578       })
579     } else {
580       end()
581     }
582
583     self.ntick = true
584   })
585
586 }
587
588 Request.prototype.getNewAgent = function () {
589   var self = this
590   var Agent = self.agentClass
591   var options = {}
592   if (self.agentOptions) {
593     for (var i in self.agentOptions) {
594       options[i] = self.agentOptions[i]
595     }
596   }
597   if (self.ca) {
598     options.ca = self.ca
599   }
600   if (self.ciphers) {
601     options.ciphers = self.ciphers
602   }
603   if (self.secureProtocol) {
604     options.secureProtocol = self.secureProtocol
605   }
606   if (self.secureOptions) {
607     options.secureOptions = self.secureOptions
608   }
609   if (typeof self.rejectUnauthorized !== 'undefined') {
610     options.rejectUnauthorized = self.rejectUnauthorized
611   }
612
613   if (self.cert && self.key) {
614     options.key = self.key
615     options.cert = self.cert
616   }
617
618   if (self.pfx) {
619     options.pfx = self.pfx
620   }
621
622   if (self.passphrase) {
623     options.passphrase = self.passphrase
624   }
625
626   var poolKey = ''
627
628   // different types of agents are in different pools
629   if (Agent !== self.httpModule.Agent) {
630     poolKey += Agent.name
631   }
632
633   // ca option is only relevant if proxy or destination are https
634   var proxy = self.proxy
635   if (typeof proxy === 'string') {
636     proxy = url.parse(proxy)
637   }
638   var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
639
640   if (isHttps) {
641     if (options.ca) {
642       if (poolKey) {
643         poolKey += ':'
644       }
645       poolKey += options.ca
646     }
647
648     if (typeof options.rejectUnauthorized !== 'undefined') {
649       if (poolKey) {
650         poolKey += ':'
651       }
652       poolKey += options.rejectUnauthorized
653     }
654
655     if (options.cert) {
656       if (poolKey) {
657         poolKey += ':'
658       }
659       poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
660     }
661
662     if (options.pfx) {
663       if (poolKey) {
664         poolKey += ':'
665       }
666       poolKey += options.pfx.toString('ascii')
667     }
668
669     if (options.ciphers) {
670       if (poolKey) {
671         poolKey += ':'
672       }
673       poolKey += options.ciphers
674     }
675
676     if (options.secureProtocol) {
677       if (poolKey) {
678         poolKey += ':'
679       }
680       poolKey += options.secureProtocol
681     }
682
683     if (options.secureOptions) {
684       if (poolKey) {
685         poolKey += ':'
686       }
687       poolKey += options.secureOptions
688     }
689   }
690
691   if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
692     // not doing anything special.  Use the globalAgent
693     return self.httpModule.globalAgent
694   }
695
696   // we're using a stored agent.  Make sure it's protocol-specific
697   poolKey = self.uri.protocol + poolKey
698
699   // generate a new agent for this setting if none yet exists
700   if (!self.pool[poolKey]) {
701     self.pool[poolKey] = new Agent(options)
702     // properly set maxSockets on new agents
703     if (self.pool.maxSockets) {
704       self.pool[poolKey].maxSockets = self.pool.maxSockets
705     }
706   }
707
708   return self.pool[poolKey]
709 }
710
711 Request.prototype.start = function () {
712   // start() is called once we are ready to send the outgoing HTTP request.
713   // this is usually called on the first write(), end() or on nextTick()
714   var self = this
715
716   if (self.timing) {
717     var startTime = now()
718   }
719
720   if (self._aborted) {
721     return
722   }
723
724   self._started = true
725   self.method = self.method || 'GET'
726   self.href = self.uri.href
727
728   if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
729     self.setHeader('content-length', self.src.stat.size)
730   }
731   if (self._aws) {
732     self.aws(self._aws, true)
733   }
734
735   // We have a method named auth, which is completely different from the http.request
736   // auth option.  If we don't remove it, we're gonna have a bad time.
737   var reqOptions = copy(self)
738   delete reqOptions.auth
739
740   debug('make request', self.uri.href)
741
742   // node v6.8.0 now supports a `timeout` value in `http.request()`, but we
743   // should delete it for now since we handle timeouts manually for better
744   // consistency with node versions before v6.8.0
745   delete reqOptions.timeout
746
747   try {
748     self.req = self.httpModule.request(reqOptions)
749   } catch (err) {
750     self.emit('error', err)
751     return
752   }
753
754   if (self.timing) {
755     self.startTime = new Date().getTime()
756     self.timings = {
757       start: startTime
758     }
759   }
760
761   var timeout
762   if (self.timeout && !self.timeoutTimer) {
763     if (self.timeout < 0) {
764       timeout = 0
765     } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) {
766       timeout = self.timeout
767     }
768   }
769
770   self.req.on('response', self.onRequestResponse.bind(self))
771   self.req.on('error', self.onRequestError.bind(self))
772   self.req.on('drain', function() {
773     self.emit('drain')
774   })
775   self.req.on('socket', function(socket) {
776     if (self.timing) {
777       self.timings.socket = now()
778       socket.on('connect', function() {
779         self.timings.connect = now()
780       })
781     }
782
783     var setReqTimeout = function() {
784       // This timeout sets the amount of time to wait *between* bytes sent
785       // from the server once connected.
786       //
787       // In particular, it's useful for erroring if the server fails to send
788       // data halfway through streaming a response.
789       self.req.setTimeout(timeout, function () {
790         if (self.req) {
791           self.abort()
792           var e = new Error('ESOCKETTIMEDOUT')
793           e.code = 'ESOCKETTIMEDOUT'
794           e.connect = false
795           self.emit('error', e)
796         }
797       })
798     }
799     // `._connecting` was the old property which was made public in node v6.1.0
800     var isConnecting = socket._connecting || socket.connecting
801     if (timeout !== undefined) {
802       // Only start the connection timer if we're actually connecting a new
803       // socket, otherwise if we're already connected (because this is a
804       // keep-alive connection) do not bother. This is important since we won't
805       // get a 'connect' event for an already connected socket.
806       if (isConnecting) {
807         var onReqSockConnect = function() {
808           socket.removeListener('connect', onReqSockConnect)
809           clearTimeout(self.timeoutTimer)
810           self.timeoutTimer = null
811           setReqTimeout()
812         }
813
814         socket.on('connect', onReqSockConnect)
815
816         self.req.on('error', function(err) {
817           socket.removeListener('connect', onReqSockConnect)
818         })
819
820         // Set a timeout in memory - this block will throw if the server takes more
821         // than `timeout` to write the HTTP status and headers (corresponding to
822         // the on('response') event on the client). NB: this measures wall-clock
823         // time, not the time between bytes sent by the server.
824         self.timeoutTimer = setTimeout(function () {
825           socket.removeListener('connect', onReqSockConnect)
826           self.abort()
827           var e = new Error('ETIMEDOUT')
828           e.code = 'ETIMEDOUT'
829           e.connect = true
830           self.emit('error', e)
831         }, timeout)
832       } else {
833         // We're already connected
834         setReqTimeout()
835       }
836     }
837     self.emit('socket', socket)
838   })
839
840   self.emit('request', self.req)
841 }
842
843 Request.prototype.onRequestError = function (error) {
844   var self = this
845   if (self._aborted) {
846     return
847   }
848   if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
849       && self.agent.addRequestNoreuse) {
850     self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
851     self.start()
852     self.req.end()
853     return
854   }
855   if (self.timeout && self.timeoutTimer) {
856     clearTimeout(self.timeoutTimer)
857     self.timeoutTimer = null
858   }
859   self.emit('error', error)
860 }
861
862 Request.prototype.onRequestResponse = function (response) {
863   var self = this
864
865   if (self.timing) {
866     self.timings.response = now()
867   }
868
869   debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
870   response.on('end', function() {
871     if (self.timing) {
872       self.timings.end = now()
873
874       self.timings.dns = self.timings.socket - self.timings.start
875       self.timings.tcp = self.timings.connect - self.timings.socket
876       self.timings.firstByte = self.timings.response - self.timings.connect
877       self.timings.download = self.timings.end - self.timings.response
878       self.timings.total = self.timings.end - self.timings.start
879
880       debug('elapsed time', self.timings.total)
881
882       // elapsedTime includes all redirects
883       self.elapsedTime += Math.round(self.timings.total)
884
885       // NOTE: elapsedTime is deprecated in favor of .timings
886       response.elapsedTime = self.elapsedTime
887
888       // timings is just for the final fetch
889       response.timings = self.timings
890     }
891     debug('response end', self.uri.href, response.statusCode, response.headers)
892   })
893
894   if (self._aborted) {
895     debug('aborted', self.uri.href)
896     response.resume()
897     return
898   }
899
900   self.response = response
901   response.request = self
902   response.toJSON = responseToJSON
903
904   // XXX This is different on 0.10, because SSL is strict by default
905   if (self.httpModule === https &&
906       self.strictSSL && (!response.hasOwnProperty('socket') ||
907       !response.socket.authorized)) {
908     debug('strict ssl error', self.uri.href)
909     var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
910     self.emit('error', new Error('SSL Error: ' + sslErr))
911     return
912   }
913
914   // Save the original host before any redirect (if it changes, we need to
915   // remove any authorization headers).  Also remember the case of the header
916   // name because lots of broken servers expect Host instead of host and we
917   // want the caller to be able to specify this.
918   self.originalHost = self.getHeader('host')
919   if (!self.originalHostHeaderName) {
920     self.originalHostHeaderName = self.hasHeader('host')
921   }
922   if (self.setHost) {
923     self.removeHeader('host')
924   }
925   if (self.timeout && self.timeoutTimer) {
926     clearTimeout(self.timeoutTimer)
927     self.timeoutTimer = null
928   }
929
930   var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
931   var addCookie = function (cookie) {
932     //set the cookie if it's domain in the href's domain.
933     try {
934       targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
935     } catch (e) {
936       self.emit('error', e)
937     }
938   }
939
940   response.caseless = caseless(response.headers)
941
942   if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
943     var headerName = response.caseless.has('set-cookie')
944     if (Array.isArray(response.headers[headerName])) {
945       response.headers[headerName].forEach(addCookie)
946     } else {
947       addCookie(response.headers[headerName])
948     }
949   }
950
951   if (self._redirect.onResponse(response)) {
952     return // Ignore the rest of the response
953   } else {
954     // Be a good stream and emit end when the response is finished.
955     // Hack to emit end on close because of a core bug that never fires end
956     response.on('close', function () {
957       if (!self._ended) {
958         self.response.emit('end')
959       }
960     })
961
962     response.once('end', function () {
963       self._ended = true
964     })
965
966     var noBody = function (code) {
967       return (
968         self.method === 'HEAD'
969         // Informational
970         || (code >= 100 && code < 200)
971         // No Content
972         || code === 204
973         // Not Modified
974         || code === 304
975       )
976     }
977
978     var responseContent
979     if (self.gzip && !noBody(response.statusCode)) {
980       var contentEncoding = response.headers['content-encoding'] || 'identity'
981       contentEncoding = contentEncoding.trim().toLowerCase()
982
983       // Be more lenient with decoding compressed responses, since (very rarely)
984       // servers send slightly invalid gzip responses that are still accepted
985       // by common browsers.
986       // Always using Z_SYNC_FLUSH is what cURL does.
987       var zlibOptions = {
988         flush: zlib.Z_SYNC_FLUSH
989       , finishFlush: zlib.Z_SYNC_FLUSH
990       }
991
992       if (contentEncoding === 'gzip') {
993         responseContent = zlib.createGunzip(zlibOptions)
994         response.pipe(responseContent)
995       } else if (contentEncoding === 'deflate') {
996         responseContent = zlib.createInflate(zlibOptions)
997         response.pipe(responseContent)
998       } else {
999         // Since previous versions didn't check for Content-Encoding header,
1000         // ignore any invalid values to preserve backwards-compatibility
1001         if (contentEncoding !== 'identity') {
1002           debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
1003         }
1004         responseContent = response
1005       }
1006     } else {
1007       responseContent = response
1008     }
1009
1010     if (self.encoding) {
1011       if (self.dests.length !== 0) {
1012         console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
1013       } else if (responseContent.setEncoding) {
1014         responseContent.setEncoding(self.encoding)
1015       } else {
1016         // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with
1017         // zlib streams.
1018         // If/When support for 0.9.4 is dropped, this should be unnecessary.
1019         responseContent = responseContent.pipe(stringstream(self.encoding))
1020       }
1021     }
1022
1023     if (self._paused) {
1024       responseContent.pause()
1025     }
1026
1027     self.responseContent = responseContent
1028
1029     self.emit('response', response)
1030
1031     self.dests.forEach(function (dest) {
1032       self.pipeDest(dest)
1033     })
1034
1035     responseContent.on('data', function (chunk) {
1036       if (self.timing && !self.responseStarted) {
1037         self.responseStartTime = (new Date()).getTime()
1038
1039         // NOTE: responseStartTime is deprecated in favor of .timings
1040         response.responseStartTime = self.responseStartTime
1041       }
1042       self._destdata = true
1043       self.emit('data', chunk)
1044     })
1045     responseContent.once('end', function (chunk) {
1046       self.emit('end', chunk)
1047     })
1048     responseContent.on('error', function (error) {
1049       self.emit('error', error)
1050     })
1051     responseContent.on('close', function () {self.emit('close')})
1052
1053     if (self.callback) {
1054       self.readResponseBody(response)
1055     }
1056     //if no callback
1057     else {
1058       self.on('end', function () {
1059         if (self._aborted) {
1060           debug('aborted', self.uri.href)
1061           return
1062         }
1063         self.emit('complete', response)
1064       })
1065     }
1066   }
1067   debug('finish init function', self.uri.href)
1068 }
1069
1070 Request.prototype.readResponseBody = function (response) {
1071   var self = this
1072   debug('reading response\'s body')
1073   var buffers = []
1074     , bufferLength = 0
1075     , strings = []
1076
1077   self.on('data', function (chunk) {
1078     if (!Buffer.isBuffer(chunk)) {
1079       strings.push(chunk)
1080     } else if (chunk.length) {
1081       bufferLength += chunk.length
1082       buffers.push(chunk)
1083     }
1084   })
1085   self.on('end', function () {
1086     debug('end event', self.uri.href)
1087     if (self._aborted) {
1088       debug('aborted', self.uri.href)
1089       // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request.
1090       // This can lead to leaky behavior if the user retains a reference to the request object.
1091       buffers = []
1092       bufferLength = 0
1093       return
1094     }
1095
1096     if (bufferLength) {
1097       debug('has body', self.uri.href, bufferLength)
1098       response.body = Buffer.concat(buffers, bufferLength)
1099       if (self.encoding !== null) {
1100         response.body = response.body.toString(self.encoding)
1101       }
1102       // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
1103       // This can lead to leaky behavior if the user retains a reference to the request object.
1104       buffers = []
1105       bufferLength = 0
1106     } else if (strings.length) {
1107       // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
1108       // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
1109       if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
1110         strings[0] = strings[0].substring(1)
1111       }
1112       response.body = strings.join('')
1113     }
1114
1115     if (self._json) {
1116       try {
1117         response.body = JSON.parse(response.body, self._jsonReviver)
1118       } catch (e) {
1119         debug('invalid JSON received', self.uri.href)
1120       }
1121     }
1122     debug('emitting complete', self.uri.href)
1123     if (typeof response.body === 'undefined' && !self._json) {
1124       response.body = self.encoding === null ? new Buffer(0) : ''
1125     }
1126     self.emit('complete', response, response.body)
1127   })
1128 }
1129
1130 Request.prototype.abort = function () {
1131   var self = this
1132   self._aborted = true
1133
1134   if (self.req) {
1135     self.req.abort()
1136   }
1137   else if (self.response) {
1138     self.response.destroy()
1139   }
1140
1141   self.emit('abort')
1142 }
1143
1144 Request.prototype.pipeDest = function (dest) {
1145   var self = this
1146   var response = self.response
1147   // Called after the response is received
1148   if (dest.headers && !dest.headersSent) {
1149     if (response.caseless.has('content-type')) {
1150       var ctname = response.caseless.has('content-type')
1151       if (dest.setHeader) {
1152         dest.setHeader(ctname, response.headers[ctname])
1153       }
1154       else {
1155         dest.headers[ctname] = response.headers[ctname]
1156       }
1157     }
1158
1159     if (response.caseless.has('content-length')) {
1160       var clname = response.caseless.has('content-length')
1161       if (dest.setHeader) {
1162         dest.setHeader(clname, response.headers[clname])
1163       } else {
1164         dest.headers[clname] = response.headers[clname]
1165       }
1166     }
1167   }
1168   if (dest.setHeader && !dest.headersSent) {
1169     for (var i in response.headers) {
1170       // If the response content is being decoded, the Content-Encoding header
1171       // of the response doesn't represent the piped content, so don't pass it.
1172       if (!self.gzip || i !== 'content-encoding') {
1173         dest.setHeader(i, response.headers[i])
1174       }
1175     }
1176     dest.statusCode = response.statusCode
1177   }
1178   if (self.pipefilter) {
1179     self.pipefilter(response, dest)
1180   }
1181 }
1182
1183 Request.prototype.qs = function (q, clobber) {
1184   var self = this
1185   var base
1186   if (!clobber && self.uri.query) {
1187     base = self._qs.parse(self.uri.query)
1188   } else {
1189     base = {}
1190   }
1191
1192   for (var i in q) {
1193     base[i] = q[i]
1194   }
1195
1196   var qs = self._qs.stringify(base)
1197
1198   if (qs === '') {
1199     return self
1200   }
1201
1202   self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
1203   self.url = self.uri
1204   self.path = self.uri.path
1205
1206   if (self.uri.host === 'unix') {
1207     self.enableUnixSocket()
1208   }
1209
1210   return self
1211 }
1212 Request.prototype.form = function (form) {
1213   var self = this
1214   if (form) {
1215     if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
1216       self.setHeader('content-type', 'application/x-www-form-urlencoded')
1217     }
1218     self.body = (typeof form === 'string')
1219       ? self._qs.rfc3986(form.toString('utf8'))
1220       : self._qs.stringify(form).toString('utf8')
1221     return self
1222   }
1223   // create form-data object
1224   self._form = new FormData()
1225   self._form.on('error', function(err) {
1226     err.message = 'form-data: ' + err.message
1227     self.emit('error', err)
1228     self.abort()
1229   })
1230   return self._form
1231 }
1232 Request.prototype.multipart = function (multipart) {
1233   var self = this
1234
1235   self._multipart.onRequest(multipart)
1236
1237   if (!self._multipart.chunked) {
1238     self.body = self._multipart.body
1239   }
1240
1241   return self
1242 }
1243 Request.prototype.json = function (val) {
1244   var self = this
1245
1246   if (!self.hasHeader('accept')) {
1247     self.setHeader('accept', 'application/json')
1248   }
1249
1250   if (typeof self.jsonReplacer === 'function') {
1251     self._jsonReplacer = self.jsonReplacer
1252   }
1253
1254   self._json = true
1255   if (typeof val === 'boolean') {
1256     if (self.body !== undefined) {
1257       if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
1258         self.body = safeStringify(self.body, self._jsonReplacer)
1259       } else {
1260         self.body = self._qs.rfc3986(self.body)
1261       }
1262       if (!self.hasHeader('content-type')) {
1263         self.setHeader('content-type', 'application/json')
1264       }
1265     }
1266   } else {
1267     self.body = safeStringify(val, self._jsonReplacer)
1268     if (!self.hasHeader('content-type')) {
1269       self.setHeader('content-type', 'application/json')
1270     }
1271   }
1272
1273   if (typeof self.jsonReviver === 'function') {
1274     self._jsonReviver = self.jsonReviver
1275   }
1276
1277   return self
1278 }
1279 Request.prototype.getHeader = function (name, headers) {
1280   var self = this
1281   var result, re, match
1282   if (!headers) {
1283     headers = self.headers
1284   }
1285   Object.keys(headers).forEach(function (key) {
1286     if (key.length !== name.length) {
1287       return
1288     }
1289     re = new RegExp(name, 'i')
1290     match = key.match(re)
1291     if (match) {
1292       result = headers[key]
1293     }
1294   })
1295   return result
1296 }
1297 Request.prototype.enableUnixSocket = function () {
1298   // Get the socket & request paths from the URL
1299   var unixParts = this.uri.path.split(':')
1300     , host = unixParts[0]
1301     , path = unixParts[1]
1302   // Apply unix properties to request
1303   this.socketPath = host
1304   this.uri.pathname = path
1305   this.uri.path = path
1306   this.uri.host = host
1307   this.uri.hostname = host
1308   this.uri.isUnix = true
1309 }
1310
1311
1312 Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
1313   var self = this
1314
1315   self._auth.onRequest(user, pass, sendImmediately, bearer)
1316
1317   return self
1318 }
1319 Request.prototype.aws = function (opts, now) {
1320   var self = this
1321
1322   if (!now) {
1323     self._aws = opts
1324     return self
1325   }
1326
1327   if (opts.sign_version == 4 || opts.sign_version == '4') {
1328     // use aws4
1329     var options = {
1330       host: self.uri.host,
1331       path: self.uri.path,
1332       method: self.method,
1333       headers: {
1334         'content-type': self.getHeader('content-type') || ''
1335       },
1336       body: self.body
1337     }
1338     var signRes = aws4.sign(options, {
1339       accessKeyId: opts.key,
1340       secretAccessKey: opts.secret,
1341       sessionToken: opts.session
1342     })
1343     self.setHeader('authorization', signRes.headers.Authorization)
1344     self.setHeader('x-amz-date', signRes.headers['X-Amz-Date'])
1345     if (signRes.headers['X-Amz-Security-Token']) {
1346       self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
1347     }
1348   }
1349   else {
1350     // default: use aws-sign2
1351     var date = new Date()
1352     self.setHeader('date', date.toUTCString())
1353     var auth =
1354       { key: opts.key
1355       , secret: opts.secret
1356       , verb: self.method.toUpperCase()
1357       , date: date
1358       , contentType: self.getHeader('content-type') || ''
1359       , md5: self.getHeader('content-md5') || ''
1360       , amazonHeaders: aws2.canonicalizeHeaders(self.headers)
1361       }
1362     var path = self.uri.path
1363     if (opts.bucket && path) {
1364       auth.resource = '/' + opts.bucket + path
1365     } else if (opts.bucket && !path) {
1366       auth.resource = '/' + opts.bucket
1367     } else if (!opts.bucket && path) {
1368       auth.resource = path
1369     } else if (!opts.bucket && !path) {
1370       auth.resource = '/'
1371     }
1372     auth.resource = aws2.canonicalizeResource(auth.resource)
1373     self.setHeader('authorization', aws2.authorization(auth))
1374   }
1375
1376   return self
1377 }
1378 Request.prototype.httpSignature = function (opts) {
1379   var self = this
1380   httpSignature.signRequest({
1381     getHeader: function(header) {
1382       return self.getHeader(header, self.headers)
1383     },
1384     setHeader: function(header, value) {
1385       self.setHeader(header, value)
1386     },
1387     method: self.method,
1388     path: self.path
1389   }, opts)
1390   debug('httpSignature authorization', self.getHeader('authorization'))
1391
1392   return self
1393 }
1394 Request.prototype.hawk = function (opts) {
1395   var self = this
1396   self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field)
1397 }
1398 Request.prototype.oauth = function (_oauth) {
1399   var self = this
1400
1401   self._oauth.onRequest(_oauth)
1402
1403   return self
1404 }
1405
1406 Request.prototype.jar = function (jar) {
1407   var self = this
1408   var cookies
1409
1410   if (self._redirect.redirectsFollowed === 0) {
1411     self.originalCookieHeader = self.getHeader('cookie')
1412   }
1413
1414   if (!jar) {
1415     // disable cookies
1416     cookies = false
1417     self._disableCookies = true
1418   } else {
1419     var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
1420     var urihref = self.uri.href
1421     //fetch cookie in the Specified host
1422     if (targetCookieJar) {
1423       cookies = targetCookieJar.getCookieString(urihref)
1424     }
1425   }
1426
1427   //if need cookie and cookie is not empty
1428   if (cookies && cookies.length) {
1429     if (self.originalCookieHeader) {
1430       // Don't overwrite existing Cookie header
1431       self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
1432     } else {
1433       self.setHeader('cookie', cookies)
1434     }
1435   }
1436   self._jar = jar
1437   return self
1438 }
1439
1440
1441 // Stream API
1442 Request.prototype.pipe = function (dest, opts) {
1443   var self = this
1444
1445   if (self.response) {
1446     if (self._destdata) {
1447       self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
1448     } else if (self._ended) {
1449       self.emit('error', new Error('You cannot pipe after the response has been ended.'))
1450     } else {
1451       stream.Stream.prototype.pipe.call(self, dest, opts)
1452       self.pipeDest(dest)
1453       return dest
1454     }
1455   } else {
1456     self.dests.push(dest)
1457     stream.Stream.prototype.pipe.call(self, dest, opts)
1458     return dest
1459   }
1460 }
1461 Request.prototype.write = function () {
1462   var self = this
1463   if (self._aborted) {return}
1464
1465   if (!self._started) {
1466     self.start()
1467   }
1468   if (self.req) {
1469     return self.req.write.apply(self.req, arguments)
1470   }
1471 }
1472 Request.prototype.end = function (chunk) {
1473   var self = this
1474   if (self._aborted) {return}
1475
1476   if (chunk) {
1477     self.write(chunk)
1478   }
1479   if (!self._started) {
1480     self.start()
1481   }
1482   if (self.req) {
1483     self.req.end()
1484   }
1485 }
1486 Request.prototype.pause = function () {
1487   var self = this
1488   if (!self.responseContent) {
1489     self._paused = true
1490   } else {
1491     self.responseContent.pause.apply(self.responseContent, arguments)
1492   }
1493 }
1494 Request.prototype.resume = function () {
1495   var self = this
1496   if (!self.responseContent) {
1497     self._paused = false
1498   } else {
1499     self.responseContent.resume.apply(self.responseContent, arguments)
1500   }
1501 }
1502 Request.prototype.destroy = function () {
1503   var self = this
1504   if (!self._ended) {
1505     self.end()
1506   } else if (self.response) {
1507     self.response.destroy()
1508   }
1509 }
1510
1511 Request.defaultProxyHeaderWhiteList =
1512   Tunnel.defaultProxyHeaderWhiteList.slice()
1513
1514 Request.defaultProxyHeaderExclusiveList =
1515   Tunnel.defaultProxyHeaderExclusiveList.slice()
1516
1517 // Exports
1518
1519 Request.prototype.toJSON = requestToJSON
1520 module.exports = Request