source: Dev/trunk/src/node_modules/request/index.js @ 484

Last change on this file since 484 was 484, checked in by hendrikvanantwerpen, 11 years ago

Commit node_modules, to make checkouts and builds more deterministic.

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