0311f743dd49a4f5c3ae650696feb2e00a51ffcf
[platform/upstream/nodejs.git] / deps / npm / node_modules / request / request.js
1 var http = require('http')
2   , https = false
3   , tls = false
4   , url = require('url')
5   , util = require('util')
6   , stream = require('stream')
7   , qs = require('qs')
8   , querystring = require('querystring')
9   , crypto = require('crypto')
10
11   , oauth = require('oauth-sign')
12   , hawk = require('hawk')
13   , aws = require('aws-sign')
14   , httpSignature = require('http-signature')
15   , uuid = require('node-uuid')
16   , mime = require('mime')
17   , tunnel = require('tunnel-agent')
18   , _safeStringify = require('json-stringify-safe')
19
20   , ForeverAgent = require('forever-agent')
21   , FormData = require('form-data')
22
23   , Cookie = require('cookie-jar')
24   , CookieJar = Cookie.Jar
25   , cookieJar = new CookieJar
26
27   , copy = require('./lib/copy')
28   , debug = require('./lib/debug')
29   , getSafe = require('./lib/getSafe')
30   ;
31
32 function safeStringify (obj) {
33   var ret
34   try { ret = JSON.stringify(obj) }
35   catch (e) { ret = _safeStringify(obj) }
36   return ret
37 }
38
39 var globalPool = {}
40 var isUrl = /^https?:/i
41
42 try {
43   https = require('https')
44 } catch (e) {}
45
46 try {
47   tls = require('tls')
48 } catch (e) {}
49
50
51
52 // Hacky fix for pre-0.4.4 https
53 if (https && !https.Agent) {
54   https.Agent = function (options) {
55     http.Agent.call(this, options)
56   }
57   util.inherits(https.Agent, http.Agent)
58   https.Agent.prototype._getConnection = function (host, port, cb) {
59     var s = tls.connect(port, host, this.options, function () {
60       // do other checks here?
61       if (cb) cb()
62     })
63     return s
64   }
65 }
66
67 function isReadStream (rs) {
68   if (rs.readable && rs.path && rs.mode) {
69     return true
70   }
71 }
72
73 function toBase64 (str) {
74   return (new Buffer(str || "", "ascii")).toString("base64")
75 }
76
77 function md5 (str) {
78   return crypto.createHash('md5').update(str).digest('hex')
79 }
80
81 function Request (options) {
82   stream.Stream.call(this)
83   this.readable = true
84   this.writable = true
85
86   if (typeof options === 'string') {
87     options = {uri:options}
88   }
89
90   var reserved = Object.keys(Request.prototype)
91   for (var i in options) {
92     if (reserved.indexOf(i) === -1) {
93       this[i] = options[i]
94     } else {
95       if (typeof options[i] === 'function') {
96         delete options[i]
97       }
98     }
99   }
100
101   if (options.method) {
102     this.explicitMethod = true
103   }
104
105   this.init(options)
106 }
107 util.inherits(Request, stream.Stream)
108 Request.prototype.init = function (options) {
109   // init() contains all the code to setup the request object.
110   // the actual outgoing request is not started until start() is called
111   // this function is called from both the constructor and on redirect.
112   var self = this
113   if (!options) options = {}
114
115   if (!self.method) self.method = options.method || 'GET'
116   self.localAddress = options.localAddress
117
118   debug(options)
119   if (!self.pool && self.pool !== false) self.pool = globalPool
120   self.dests = self.dests || []
121   self.__isRequestRequest = true
122
123   // Protect against double callback
124   if (!self._callback && self.callback) {
125     self._callback = self.callback
126     self.callback = function () {
127       if (self._callbackCalled) return // Print a warning maybe?
128       self._callbackCalled = true
129       self._callback.apply(self, arguments)
130     }
131     self.on('error', self.callback.bind())
132     self.on('complete', self.callback.bind(self, null))
133   }
134
135   if (self.url && !self.uri) {
136     // People use this property instead all the time so why not just support it.
137     self.uri = self.url
138     delete self.url
139   }
140
141   if (!self.uri) {
142     // this will throw if unhandled but is handleable when in a redirect
143     return self.emit('error', new Error("options.uri is a required argument"))
144   } else {
145     if (typeof self.uri == "string") self.uri = url.parse(self.uri)
146   }
147
148   if (self.strictSSL === false) {
149     self.rejectUnauthorized = false
150   }
151
152   if (self.proxy) {
153     if (typeof self.proxy == 'string') self.proxy = url.parse(self.proxy)
154
155     // do the HTTP CONNECT dance using koichik/node-tunnel
156     if (http.globalAgent && self.uri.protocol === "https:") {
157       var tunnelFn = self.proxy.protocol === "http:"
158                    ? tunnel.httpsOverHttp : tunnel.httpsOverHttps
159
160       var tunnelOptions = { proxy: { host: self.proxy.hostname
161                                    , port: +self.proxy.port
162                                    , proxyAuth: self.proxy.auth
163                                    , headers: { Host: self.uri.hostname + ':' +
164                                         (self.uri.port || self.uri.protocol === 'https:' ? 443 : 80) }}
165                           , rejectUnauthorized: self.rejectUnauthorized
166                           , ca: this.ca }
167
168       self.agent = tunnelFn(tunnelOptions)
169       self.tunnel = true
170     }
171   }
172
173   if (!self.uri.pathname) {self.uri.pathname = '/'}
174
175   if (!self.uri.host) {
176     // Invalid URI: it may generate lot of bad errors, like "TypeError: Cannot call method 'indexOf' of undefined" in CookieJar
177     // Detect and reject it as soon as possible
178     var faultyUri = url.format(self.uri)
179     var message = 'Invalid URI "' + faultyUri + '"'
180     if (Object.keys(options).length === 0) {
181       // No option ? This can be the sign of a redirect
182       // As this is a case where the user cannot do anything (he didn't call request directly with this URL)
183       // he should be warned that it can be caused by a redirection (can save some hair)
184       message += '. This can be caused by a crappy redirection.'
185     }
186     self.emit('error', new Error(message))
187     return // This error was fatal
188   }
189
190   self._redirectsFollowed = self._redirectsFollowed || 0
191   self.maxRedirects = (self.maxRedirects !== undefined) ? self.maxRedirects : 10
192   self.followRedirect = (self.followRedirect !== undefined) ? self.followRedirect : true
193   self.followAllRedirects = (self.followAllRedirects !== undefined) ? self.followAllRedirects : false
194   if (self.followRedirect || self.followAllRedirects)
195     self.redirects = self.redirects || []
196
197   self.headers = self.headers ? copy(self.headers) : {}
198
199   self.setHost = false
200   if (!self.hasHeader('host')) {
201     self.setHeader('host', self.uri.hostname)
202     if (self.uri.port) {
203       if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') &&
204            !(self.uri.port === 443 && self.uri.protocol === 'https:') )
205       self.setHeader('host', self.getHeader('host') + (':'+self.uri.port) )
206     }
207     self.setHost = true
208   }
209
210   self.jar(self._jar || options.jar)
211
212   if (!self.uri.port) {
213     if (self.uri.protocol == 'http:') {self.uri.port = 80}
214     else if (self.uri.protocol == 'https:') {self.uri.port = 443}
215   }
216
217   if (self.proxy && !self.tunnel) {
218     self.port = self.proxy.port
219     self.host = self.proxy.hostname
220   } else {
221     self.port = self.uri.port
222     self.host = self.uri.hostname
223   }
224
225   self.clientErrorHandler = function (error) {
226     if (self._aborted) return
227
228     if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
229         && self.agent.addRequestNoreuse) {
230       self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
231       self.start()
232       self.req.end()
233       return
234     }
235     if (self.timeout && self.timeoutTimer) {
236       clearTimeout(self.timeoutTimer)
237       self.timeoutTimer = null
238     }
239     self.emit('error', error)
240   }
241
242   self._parserErrorHandler = function (error) {
243     if (this.res) {
244       if (this.res.request) {
245         this.res.request.emit('error', error)
246       } else {
247         this.res.emit('error', error)
248       }
249     } else {
250       this._httpMessage.emit('error', error)
251     }
252   }
253
254   if (options.form) {
255     self.form(options.form)
256   }
257
258   if (options.qs) self.qs(options.qs)
259
260   if (self.uri.path) {
261     self.path = self.uri.path
262   } else {
263     self.path = self.uri.pathname + (self.uri.search || "")
264   }
265
266   if (self.path.length === 0) self.path = '/'
267
268
269   // Auth must happen last in case signing is dependent on other headers
270   if (options.oauth) {
271     self.oauth(options.oauth)
272   }
273
274   if (options.aws) {
275     self.aws(options.aws)
276   }
277
278   if (options.hawk) {
279     self.hawk(options.hawk)
280   }
281
282   if (options.httpSignature) {
283     self.httpSignature(options.httpSignature)
284   }
285
286   if (options.auth) {
287     self.auth(
288       (options.auth.user==="") ? options.auth.user : (options.auth.user || options.auth.username ),
289       options.auth.pass || options.auth.password,
290       options.auth.sendImmediately)
291   }
292
293   if (self.uri.auth && !self.hasHeader('authorization')) {
294     var authPieces = self.uri.auth.split(':').map(function(item){ return querystring.unescape(item) })
295     self.auth(authPieces[0], authPieces.slice(1).join(':'), true)
296   }
297   if (self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization') && !self.tunnel) {
298     self.setHeader('proxy-authorization', "Basic " + toBase64(self.proxy.auth.split(':').map(function(item){ return querystring.unescape(item)}).join(':')))
299   }
300
301
302   if (self.proxy && !self.tunnel) self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
303
304   if (options.json) {
305     self.json(options.json)
306   } else if (options.multipart) {
307     self.boundary = uuid()
308     self.multipart(options.multipart)
309   }
310
311   if (self.body) {
312     var length = 0
313     if (!Buffer.isBuffer(self.body)) {
314       if (Array.isArray(self.body)) {
315         for (var i = 0; i < self.body.length; i++) {
316           length += self.body[i].length
317         }
318       } else {
319         self.body = new Buffer(self.body)
320         length = self.body.length
321       }
322     } else {
323       length = self.body.length
324     }
325     if (length) {
326       if (!self.hasHeader('content-length')) self.setHeader('content-length', length)
327     } else {
328       throw new Error('Argument error, options.body.')
329     }
330   }
331
332   var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
333     , defaultModules = {'http:':http, 'https:':https}
334     , httpModules = self.httpModules || {}
335     ;
336   self.httpModule = httpModules[protocol] || defaultModules[protocol]
337
338   if (!self.httpModule) return this.emit('error', new Error("Invalid protocol"))
339
340   if (options.ca) self.ca = options.ca
341
342   if (!self.agent) {
343     if (options.agentOptions) self.agentOptions = options.agentOptions
344
345     if (options.agentClass) {
346       self.agentClass = options.agentClass
347     } else if (options.forever) {
348       self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
349     } else {
350       self.agentClass = self.httpModule.Agent
351     }
352   }
353
354   if (self.pool === false) {
355     self.agent = false
356   } else {
357     self.agent = self.agent || self.getAgent()
358     if (self.maxSockets) {
359       // Don't use our pooling if node has the refactored client
360       self.agent.maxSockets = self.maxSockets
361     }
362     if (self.pool.maxSockets) {
363       // Don't use our pooling if node has the refactored client
364       self.agent.maxSockets = self.pool.maxSockets
365     }
366   }
367
368   self.on('pipe', function (src) {
369     if (self.ntick && self._started) throw new Error("You cannot pipe to this stream after the outbound request has started.")
370     self.src = src
371     if (isReadStream(src)) {
372       if (!self.hasHeader('content-type')) self.setHeader('content-type', mime.lookup(src.path))
373     } else {
374       if (src.headers) {
375         for (var i in src.headers) {
376           if (!self.hasHeader(i)) {
377             self.setHeader(i, src.headers[i])
378           }
379         }
380       }
381       if (self._json && !self.hasHeader('content-type'))
382         self.setHeader('content-type', 'application/json')
383       if (src.method && !self.explicitMethod) {
384         self.method = src.method
385       }
386     }
387
388     // self.on('pipe', function () {
389     //   console.error("You have already piped to this stream. Pipeing twice is likely to break the request.")
390     // })
391   })
392
393   process.nextTick(function () {
394     if (self._aborted) return
395
396     if (self._form) {
397       self.setHeaders(self._form.getHeaders())
398       self._form.pipe(self)
399     }
400     if (self.body) {
401       if (Array.isArray(self.body)) {
402         self.body.forEach(function (part) {
403           self.write(part)
404         })
405       } else {
406         self.write(self.body)
407       }
408       self.end()
409     } else if (self.requestBodyStream) {
410       console.warn("options.requestBodyStream is deprecated, please pass the request object to stream.pipe.")
411       self.requestBodyStream.pipe(self)
412     } else if (!self.src) {
413       if (self.method !== 'GET' && typeof self.method !== 'undefined') {
414         self.setHeader('content-length', 0)
415       }
416       self.end()
417     }
418     self.ntick = true
419   })
420 }
421
422 // Must call this when following a redirect from https to http or vice versa
423 // Attempts to keep everything as identical as possible, but update the
424 // httpModule, Tunneling agent, and/or Forever Agent in use.
425 Request.prototype._updateProtocol = function () {
426   var self = this
427   var protocol = self.uri.protocol
428
429   if (protocol === 'https:') {
430     // previously was doing http, now doing https
431     // if it's https, then we might need to tunnel now.
432     if (self.proxy) {
433       self.tunnel = true
434       var tunnelFn = self.proxy.protocol === 'http:'
435                    ? tunnel.httpsOverHttp : tunnel.httpsOverHttps
436       var tunnelOptions = { proxy: { host: self.proxy.hostname
437                                    , port: +self.proxy.port
438                                    , proxyAuth: self.proxy.auth }
439                           , rejectUnauthorized: self.rejectUnauthorized
440                           , ca: self.ca }
441       self.agent = tunnelFn(tunnelOptions)
442       return
443     }
444
445     self.httpModule = https
446     switch (self.agentClass) {
447       case ForeverAgent:
448         self.agentClass = ForeverAgent.SSL
449         break
450       case http.Agent:
451         self.agentClass = https.Agent
452         break
453       default:
454         // nothing we can do.  Just hope for the best.
455         return
456     }
457
458     // if there's an agent, we need to get a new one.
459     if (self.agent) self.agent = self.getAgent()
460
461   } else {
462     // previously was doing https, now doing http
463     // stop any tunneling.
464     if (self.tunnel) self.tunnel = false
465     self.httpModule = http
466     switch (self.agentClass) {
467       case ForeverAgent.SSL:
468         self.agentClass = ForeverAgent
469         break
470       case https.Agent:
471         self.agentClass = http.Agent
472         break
473       default:
474         // nothing we can do.  just hope for the best
475         return
476     }
477
478     // if there's an agent, then get a new one.
479     if (self.agent) {
480       self.agent = null
481       self.agent = self.getAgent()
482     }
483   }
484 }
485
486 Request.prototype.getAgent = function () {
487   var Agent = this.agentClass
488   var options = {}
489   if (this.agentOptions) {
490     for (var i in this.agentOptions) {
491       options[i] = this.agentOptions[i]
492     }
493   }
494   if (this.ca) options.ca = this.ca
495   if (typeof this.rejectUnauthorized !== 'undefined') options.rejectUnauthorized = this.rejectUnauthorized
496
497   if (this.cert && this.key) {
498     options.key = this.key
499     options.cert = this.cert
500   }
501
502   var poolKey = ''
503
504   // different types of agents are in different pools
505   if (Agent !== this.httpModule.Agent) {
506     poolKey += Agent.name
507   }
508
509   if (!this.httpModule.globalAgent) {
510     // node 0.4.x
511     options.host = this.host
512     options.port = this.port
513     if (poolKey) poolKey += ':'
514     poolKey += this.host + ':' + this.port
515   }
516
517   // ca option is only relevant if proxy or destination are https
518   var proxy = this.proxy
519   if (typeof proxy === 'string') proxy = url.parse(proxy)
520   var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
521   if (isHttps) {
522     if (options.ca) {
523       if (poolKey) poolKey += ':'
524       poolKey += options.ca
525     }
526
527     if (typeof options.rejectUnauthorized !== 'undefined') {
528       if (poolKey) poolKey += ':'
529       poolKey += options.rejectUnauthorized
530     }
531
532     if (options.cert)
533       poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
534
535     if (options.ciphers) {
536       if (poolKey) poolKey += ':'
537       poolKey += options.ciphers
538     }
539
540     if (options.secureOptions) {
541       if (poolKey) poolKey += ':'
542       poolKey += options.secureOptions
543     }
544   }
545
546   if (this.pool === globalPool && !poolKey && Object.keys(options).length === 0 && this.httpModule.globalAgent) {
547     // not doing anything special.  Use the globalAgent
548     return this.httpModule.globalAgent
549   }
550
551   // we're using a stored agent.  Make sure it's protocol-specific
552   poolKey = this.uri.protocol + poolKey
553
554   // already generated an agent for this setting
555   if (this.pool[poolKey]) return this.pool[poolKey]
556
557   return this.pool[poolKey] = new Agent(options)
558 }
559
560 Request.prototype.start = function () {
561   // start() is called once we are ready to send the outgoing HTTP request.
562   // this is usually called on the first write(), end() or on nextTick()
563   var self = this
564
565   if (self._aborted) return
566
567   self._started = true
568   self.method = self.method || 'GET'
569   self.href = self.uri.href
570
571   if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
572     self.setHeader('content-length', self.src.stat.size)
573   }
574   if (self._aws) {
575     self.aws(self._aws, true)
576   }
577
578   // We have a method named auth, which is completely different from the http.request
579   // auth option.  If we don't remove it, we're gonna have a bad time.
580   var reqOptions = copy(self)
581   delete reqOptions.auth
582
583   debug('make request', self.uri.href)
584   self.req = self.httpModule.request(reqOptions, self.onResponse.bind(self))
585
586   if (self.timeout && !self.timeoutTimer) {
587     self.timeoutTimer = setTimeout(function () {
588       self.req.abort()
589       var e = new Error("ETIMEDOUT")
590       e.code = "ETIMEDOUT"
591       self.emit("error", e)
592     }, self.timeout)
593
594     // Set additional timeout on socket - in case if remote
595     // server freeze after sending headers
596     if (self.req.setTimeout) { // only works on node 0.6+
597       self.req.setTimeout(self.timeout, function () {
598         if (self.req) {
599           self.req.abort()
600           var e = new Error("ESOCKETTIMEDOUT")
601           e.code = "ESOCKETTIMEDOUT"
602           self.emit("error", e)
603         }
604       })
605     }
606   }
607
608   self.req.on('error', self.clientErrorHandler)
609   self.req.on('drain', function() {
610     self.emit('drain')
611   })
612   self.on('end', function() {
613     if ( self.req.connection ) self.req.connection.removeListener('error', self._parserErrorHandler)
614   })
615   self.emit('request', self.req)
616 }
617 Request.prototype.onResponse = function (response) {
618   var self = this
619   debug('onResponse', self.uri.href, response.statusCode, response.headers)
620   response.on('end', function() {
621     debug('response end', self.uri.href, response.statusCode, response.headers)
622   });
623
624   if (response.connection.listeners('error').indexOf(self._parserErrorHandler) === -1) {
625     response.connection.once('error', self._parserErrorHandler)
626   }
627   if (self._aborted) {
628     debug('aborted', self.uri.href)
629     response.resume()
630     return
631   }
632   if (self._paused) response.pause()
633   else response.resume()
634
635   self.response = response
636   response.request = self
637   response.toJSON = toJSON
638
639   // XXX This is different on 0.10, because SSL is strict by default
640   if (self.httpModule === https &&
641       self.strictSSL &&
642       !response.client.authorized) {
643     debug('strict ssl error', self.uri.href)
644     var sslErr = response.client.authorizationError
645     self.emit('error', new Error('SSL Error: '+ sslErr))
646     return
647   }
648
649   if (self.setHost && self.hasHeader('host')) delete self.headers[self.hasHeader('host')]
650   if (self.timeout && self.timeoutTimer) {
651     clearTimeout(self.timeoutTimer)
652     self.timeoutTimer = null
653   }
654
655   var addCookie = function (cookie) {
656     if (self._jar){
657       if(self._jar.add){
658         self._jar.add(new Cookie(cookie))
659       }
660       else cookieJar.add(new Cookie(cookie))
661     }
662
663   }
664
665   if (hasHeader('set-cookie', response.headers) && (!self._disableCookies)) {
666     var headerName = hasHeader('set-cookie', response.headers)
667     if (Array.isArray(response.headers[headerName])) response.headers[headerName].forEach(addCookie)
668     else addCookie(response.headers[headerName])
669   }
670
671   var redirectTo = null
672   if (response.statusCode >= 300 && response.statusCode < 400 && hasHeader('location', response.headers)) {
673     var location = response.headers[hasHeader('location', response.headers)]
674     debug('redirect', location)
675
676     if (self.followAllRedirects) {
677       redirectTo = location
678     } else if (self.followRedirect) {
679       switch (self.method) {
680         case 'PATCH':
681         case 'PUT':
682         case 'POST':
683         case 'DELETE':
684           // Do not follow redirects
685           break
686         default:
687           redirectTo = location
688           break
689       }
690     }
691   } else if (response.statusCode == 401 && self._hasAuth && !self._sentAuth) {
692     var authHeader = response.headers[hasHeader('www-authenticate', response.headers)]
693     var authVerb = authHeader && authHeader.split(' ')[0]
694     debug('reauth', authVerb)
695
696     switch (authVerb) {
697       case 'Basic':
698         self.auth(self._user, self._pass, true)
699         redirectTo = self.uri
700         break
701
702       case 'Digest':
703         // TODO: More complete implementation of RFC 2617.  For reference:
704         // http://tools.ietf.org/html/rfc2617#section-3
705         // https://github.com/bagder/curl/blob/master/lib/http_digest.c
706
707         var matches = authHeader.match(/([a-z0-9_-]+)="([^"]+)"/gi)
708         var challenge = {}
709
710         for (var i = 0; i < matches.length; i++) {
711           var eqPos = matches[i].indexOf('=')
712           var key = matches[i].substring(0, eqPos)
713           var quotedValue = matches[i].substring(eqPos + 1)
714           challenge[key] = quotedValue.substring(1, quotedValue.length - 1)
715         }
716
717         var ha1 = md5(self._user + ':' + challenge.realm + ':' + self._pass)
718         var ha2 = md5(self.method + ':' + self.uri.path)
719         var digestResponse = md5(ha1 + ':' + challenge.nonce + ':1::auth:' + ha2)
720         var authValues = {
721           username: self._user,
722           realm: challenge.realm,
723           nonce: challenge.nonce,
724           uri: self.uri.path,
725           qop: challenge.qop,
726           response: digestResponse,
727           nc: 1,
728           cnonce: ''
729         }
730
731         authHeader = []
732         for (var k in authValues) {
733           authHeader.push(k + '="' + authValues[k] + '"')
734         }
735         authHeader = 'Digest ' + authHeader.join(', ')
736         self.setHeader('authorization', authHeader)
737         self._sentAuth = true
738
739         redirectTo = self.uri
740         break
741     }
742   }
743
744   if (redirectTo) {
745     debug('redirect to', redirectTo)
746
747     // ignore any potential response body.  it cannot possibly be useful
748     // to us at this point.
749     if (self._paused) response.resume()
750
751     if (self._redirectsFollowed >= self.maxRedirects) {
752       self.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop "+self.uri.href))
753       return
754     }
755     self._redirectsFollowed += 1
756
757     if (!isUrl.test(redirectTo)) {
758       redirectTo = url.resolve(self.uri.href, redirectTo)
759     }
760
761     var uriPrev = self.uri
762     self.uri = url.parse(redirectTo)
763
764     // handle the case where we change protocol from https to http or vice versa
765     if (self.uri.protocol !== uriPrev.protocol) {
766       self._updateProtocol()
767     }
768
769     self.redirects.push(
770       { statusCode : response.statusCode
771       , redirectUri: redirectTo
772       }
773     )
774     if (self.followAllRedirects && response.statusCode != 401) self.method = 'GET'
775     // self.method = 'GET' // Force all redirects to use GET || commented out fixes #215
776     delete self.src
777     delete self.req
778     delete self.agent
779     delete self._started
780     if (response.statusCode != 401) {
781       // Remove parameters from the previous response, unless this is the second request
782       // for a server that requires digest authentication.
783       delete self.body
784       delete self._form
785       if (self.headers) {
786         if (self.hasHeader('host')) delete self.headers[self.hasHeader('host')]
787         if (self.hasHeader('content-type')) delete self.headers[self.hasHeader('content-type')]
788         if (self.hasHeader('content-length')) delete self.headers[self.hasHeader('content-length')]
789       }
790     }
791
792     self.emit('redirect');
793
794     self.init()
795     return // Ignore the rest of the response
796   } else {
797     self._redirectsFollowed = self._redirectsFollowed || 0
798     // Be a good stream and emit end when the response is finished.
799     // Hack to emit end on close because of a core bug that never fires end
800     response.on('close', function () {
801       if (!self._ended) self.response.emit('end')
802     })
803
804     if (self.encoding) {
805       if (self.dests.length !== 0) {
806         console.error("Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.")
807       } else {
808         response.setEncoding(self.encoding)
809       }
810     }
811
812     self.emit('response', response)
813
814     self.dests.forEach(function (dest) {
815       self.pipeDest(dest)
816     })
817
818     response.on("data", function (chunk) {
819       self._destdata = true
820       self.emit("data", chunk)
821     })
822     response.on("end", function (chunk) {
823       self._ended = true
824       self.emit("end", chunk)
825     })
826     response.on("close", function () {self.emit("close")})
827
828     if (self.callback) {
829       var buffer = []
830       var bodyLen = 0
831       self.on("data", function (chunk) {
832         buffer.push(chunk)
833         bodyLen += chunk.length
834       })
835       self.on("end", function () {
836         debug('end event', self.uri.href)
837         if (self._aborted) {
838           debug('aborted', self.uri.href)
839           return
840         }
841
842         if (buffer.length && Buffer.isBuffer(buffer[0])) {
843           debug('has body', self.uri.href, bodyLen)
844           var body = new Buffer(bodyLen)
845           var i = 0
846           buffer.forEach(function (chunk) {
847             chunk.copy(body, i, 0, chunk.length)
848             i += chunk.length
849           })
850           if (self.encoding === null) {
851             response.body = body
852           } else {
853             response.body = body.toString(self.encoding)
854           }
855         } else if (buffer.length) {
856           // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
857           // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
858           if (self.encoding === 'utf8' && buffer[0].length > 0 && buffer[0][0] === "\uFEFF") {
859             buffer[0] = buffer[0].substring(1)
860           }
861           response.body = buffer.join('')
862         }
863
864         if (self._json) {
865           try {
866             response.body = JSON.parse(response.body)
867           } catch (e) {}
868         }
869         debug('emitting complete', self.uri.href)
870         if(response.body == undefined && !self._json) {
871           response.body = "";
872         }
873         self.emit('complete', response, response.body)
874       })
875     }
876     //if no callback
877     else{
878       self.on("end", function () {
879         if (self._aborted) {
880           debug('aborted', self.uri.href)
881           return
882         }
883         self.emit('complete', response);
884       });
885     }
886   }
887   debug('finish init function', self.uri.href)
888 }
889
890 Request.prototype.abort = function () {
891   this._aborted = true
892
893   if (this.req) {
894     this.req.abort()
895   }
896   else if (this.response) {
897     this.response.abort()
898   }
899
900   this.emit("abort")
901 }
902
903 Request.prototype.pipeDest = function (dest) {
904   var response = this.response
905   // Called after the response is received
906   if (dest.headers && !dest.headersSent) {
907     if (hasHeader('content-type', response.headers)) {
908       var ctname = hasHeader('content-type', response.headers)
909       if (dest.setHeader) dest.setHeader(ctname, response.headers[ctname])
910       else dest.headers[ctname] = response.headers[ctname]
911     }
912
913     if (hasHeader('content-length', response.headers)) {
914       var clname = hasHeader('content-length', response.headers)
915       if (dest.setHeader) dest.setHeader(clname, response.headers[clname])
916       else dest.headers[clname] = response.headers[clname]
917     }
918   }
919   if (dest.setHeader && !dest.headersSent) {
920     for (var i in response.headers) {
921       dest.setHeader(i, response.headers[i])
922     }
923     dest.statusCode = response.statusCode
924   }
925   if (this.pipefilter) this.pipefilter(response, dest)
926 }
927
928 // Composable API
929 Request.prototype.setHeader = function (name, value, clobber) {
930   if (clobber === undefined) clobber = true
931   if (clobber || !this.hasHeader(name)) this.headers[name] = value
932   else this.headers[this.hasHeader(name)] += ',' + value
933   return this
934 }
935 Request.prototype.setHeaders = function (headers) {
936   for (var i in headers) {this.setHeader(i, headers[i])}
937   return this
938 }
939 Request.prototype.hasHeader = function (header, headers) {
940   var headers = Object.keys(headers || this.headers)
941     , lheaders = headers.map(function (h) {return h.toLowerCase()})
942     ;
943   header = header.toLowerCase()
944   for (var i=0;i<lheaders.length;i++) {
945     if (lheaders[i] === header) return headers[i]
946   }
947   return false
948 }
949
950 var hasHeader = Request.prototype.hasHeader
951
952 Request.prototype.qs = function (q, clobber) {
953   var base
954   if (!clobber && this.uri.query) base = qs.parse(this.uri.query)
955   else base = {}
956
957   for (var i in q) {
958     base[i] = q[i]
959   }
960
961   if (qs.stringify(base) === ''){
962     return this
963   }
964
965   this.uri = url.parse(this.uri.href.split('?')[0] + '?' + qs.stringify(base))
966   this.url = this.uri
967   this.path = this.uri.path
968
969   return this
970 }
971 Request.prototype.form = function (form) {
972   if (form) {
973     this.setHeader('content-type', 'application/x-www-form-urlencoded; charset=utf-8')
974     this.body = qs.stringify(form).toString('utf8')
975     return this
976   }
977   // create form-data object
978   this._form = new FormData()
979   return this._form
980 }
981 Request.prototype.multipart = function (multipart) {
982   var self = this
983   self.body = []
984
985   if (!self.hasHeader('content-type')) {
986     self.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
987   } else {
988     self.setHeader('content-type', self.headers['content-type'].split(';')[0] + '; boundary=' + self.boundary)
989   }
990
991   if (!multipart.forEach) throw new Error('Argument error, options.multipart.')
992
993   if (self.preambleCRLF) {
994     self.body.push(new Buffer('\r\n'))
995   }
996
997   multipart.forEach(function (part) {
998     var body = part.body
999     if(body == null) throw Error('Body attribute missing in multipart.')
1000     delete part.body
1001     var preamble = '--' + self.boundary + '\r\n'
1002     Object.keys(part).forEach(function (key) {
1003       preamble += key + ': ' + part[key] + '\r\n'
1004     })
1005     preamble += '\r\n'
1006     self.body.push(new Buffer(preamble))
1007     self.body.push(new Buffer(body))
1008     self.body.push(new Buffer('\r\n'))
1009   })
1010   self.body.push(new Buffer('--' + self.boundary + '--'))
1011   return self
1012 }
1013 Request.prototype.json = function (val) {
1014   var self = this
1015
1016   if (!self.hasHeader('accept')) self.setHeader('accept', 'application/json')
1017
1018   this._json = true
1019   if (typeof val === 'boolean') {
1020     if (typeof this.body === 'object') {
1021       this.body = safeStringify(this.body)
1022       self.setHeader('content-type', 'application/json')
1023     }
1024   } else {
1025     this.body = safeStringify(val)
1026     self.setHeader('content-type', 'application/json')
1027   }
1028   return this
1029 }
1030 Request.prototype.getHeader = function (name, headers) {
1031   var result, re, match
1032   if (!headers) headers = this.headers
1033   Object.keys(headers).forEach(function (key) {
1034     re = new RegExp(name, 'i')
1035     match = key.match(re)
1036     if (match) result = headers[key]
1037   })
1038   return result
1039 }
1040 var getHeader = Request.prototype.getHeader
1041
1042 Request.prototype.auth = function (user, pass, sendImmediately) {
1043   if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
1044     throw new Error('auth() received invalid user or password')
1045   }
1046   this._user = user
1047   this._pass = pass
1048   this._hasAuth = true
1049   var header = typeof pass !== 'undefined' ? user + ':' + pass : user
1050   if (sendImmediately || typeof sendImmediately == 'undefined') {
1051     this.setHeader('authorization', 'Basic ' + toBase64(header))
1052     this._sentAuth = true
1053   }
1054   return this
1055 }
1056 Request.prototype.aws = function (opts, now) {
1057   if (!now) {
1058     this._aws = opts
1059     return this
1060   }
1061   var date = new Date()
1062   this.setHeader('date', date.toUTCString())
1063   var auth =
1064     { key: opts.key
1065     , secret: opts.secret
1066     , verb: this.method.toUpperCase()
1067     , date: date
1068     , contentType: this.getHeader('content-type') || ''
1069     , md5: this.getHeader('content-md5') || ''
1070     , amazonHeaders: aws.canonicalizeHeaders(this.headers)
1071     }
1072   if (opts.bucket && this.path) {
1073     auth.resource = '/' + opts.bucket + this.path
1074   } else if (opts.bucket && !this.path) {
1075     auth.resource = '/' + opts.bucket
1076   } else if (!opts.bucket && this.path) {
1077     auth.resource = this.path
1078   } else if (!opts.bucket && !this.path) {
1079     auth.resource = '/'
1080   }
1081   auth.resource = aws.canonicalizeResource(auth.resource)
1082   this.setHeader('authorization', aws.authorization(auth))
1083
1084   return this
1085 }
1086 Request.prototype.httpSignature = function (opts) {
1087   var req = this
1088   httpSignature.signRequest({
1089     getHeader: function(header) {
1090       return getHeader(header, req.headers)
1091     },
1092     setHeader: function(header, value) {
1093       req.setHeader(header, value)
1094     },
1095     method: this.method,
1096     path: this.path
1097   }, opts)
1098   debug('httpSignature authorization', this.getHeader('authorization'))
1099
1100   return this
1101 }
1102
1103 Request.prototype.hawk = function (opts) {
1104   this.setHeader('Authorization', hawk.client.header(this.uri, this.method, opts).field)
1105 }
1106
1107 Request.prototype.oauth = function (_oauth) {
1108   var form
1109   if (this.hasHeader('content-type') &&
1110       this.getHeader('content-type').slice(0, 'application/x-www-form-urlencoded'.length) ===
1111         'application/x-www-form-urlencoded'
1112      ) {
1113     form = qs.parse(this.body)
1114   }
1115   if (this.uri.query) {
1116     form = qs.parse(this.uri.query)
1117   }
1118   if (!form) form = {}
1119   var oa = {}
1120   for (var i in form) oa[i] = form[i]
1121   for (var i in _oauth) oa['oauth_'+i] = _oauth[i]
1122   if (!oa.oauth_version) oa.oauth_version = '1.0'
1123   if (!oa.oauth_timestamp) oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
1124   if (!oa.oauth_nonce) oa.oauth_nonce = uuid().replace(/-/g, '')
1125
1126   oa.oauth_signature_method = 'HMAC-SHA1'
1127
1128   var consumer_secret = oa.oauth_consumer_secret
1129   delete oa.oauth_consumer_secret
1130   var token_secret = oa.oauth_token_secret
1131   delete oa.oauth_token_secret
1132   var timestamp = oa.oauth_timestamp
1133
1134   var baseurl = this.uri.protocol + '//' + this.uri.host + this.uri.pathname
1135   var signature = oauth.hmacsign(this.method, baseurl, oa, consumer_secret, token_secret)
1136
1137   // oa.oauth_signature = signature
1138   for (var i in form) {
1139     if ( i.slice(0, 'oauth_') in _oauth) {
1140       // skip
1141     } else {
1142       delete oa['oauth_'+i]
1143       if (i !== 'x_auth_mode') delete oa[i]
1144     }
1145   }
1146   oa.oauth_timestamp = timestamp
1147   var authHeader = 'OAuth '+Object.keys(oa).sort().map(function (i) {return i+'="'+oauth.rfc3986(oa[i])+'"'}).join(',')
1148   authHeader += ',oauth_signature="' + oauth.rfc3986(signature) + '"'
1149   this.setHeader('Authorization', authHeader)
1150   return this
1151 }
1152 Request.prototype.jar = function (jar) {
1153   var cookies
1154
1155   if (this._redirectsFollowed === 0) {
1156     this.originalCookieHeader = this.getHeader('cookie')
1157   }
1158
1159   if (!jar) {
1160     // disable cookies
1161     cookies = false
1162     this._disableCookies = true
1163   } else if (jar && jar.get) {
1164     // fetch cookie from the user defined cookie jar
1165     cookies = jar.get({ url: this.uri.href })
1166   } else {
1167     // fetch cookie from the global cookie jar
1168     cookies = cookieJar.get({ url: this.uri.href })
1169   }
1170
1171   if (cookies && cookies.length) {
1172     var cookieString = cookies.map(function (c) {
1173       return c.name + "=" + c.value
1174     }).join("; ")
1175
1176     if (this.originalCookieHeader) {
1177       // Don't overwrite existing Cookie header
1178       this.setHeader('cookie', this.originalCookieHeader + '; ' + cookieString)
1179     } else {
1180       this.setHeader('cookie', cookieString)
1181     }
1182   }
1183   this._jar = jar
1184   return this
1185 }
1186
1187
1188 // Stream API
1189 Request.prototype.pipe = function (dest, opts) {
1190   if (this.response) {
1191     if (this._destdata) {
1192       throw new Error("You cannot pipe after data has been emitted from the response.")
1193     } else if (this._ended) {
1194       throw new Error("You cannot pipe after the response has been ended.")
1195     } else {
1196       stream.Stream.prototype.pipe.call(this, dest, opts)
1197       this.pipeDest(dest)
1198       return dest
1199     }
1200   } else {
1201     this.dests.push(dest)
1202     stream.Stream.prototype.pipe.call(this, dest, opts)
1203     return dest
1204   }
1205 }
1206 Request.prototype.write = function () {
1207   if (!this._started) this.start()
1208   return this.req.write.apply(this.req, arguments)
1209 }
1210 Request.prototype.end = function (chunk) {
1211   if (chunk) this.write(chunk)
1212   if (!this._started) this.start()
1213   this.req.end()
1214 }
1215 Request.prototype.pause = function () {
1216   if (!this.response) this._paused = true
1217   else this.response.pause.apply(this.response, arguments)
1218 }
1219 Request.prototype.resume = function () {
1220   if (!this.response) this._paused = false
1221   else this.response.resume.apply(this.response, arguments)
1222 }
1223 Request.prototype.destroy = function () {
1224   if (!this._ended) this.end()
1225   else if (this.response) this.response.destroy()
1226 }
1227
1228 function toJSON () {
1229   return getSafe(this, '__' + (((1+Math.random())*0x10000)|0).toString(16))
1230 }
1231
1232 Request.prototype.toJSON = toJSON
1233
1234
1235 module.exports = Request