1 var http = require('http')
5 , util = require('util')
6 , stream = require('stream')
8 , querystring = require('querystring')
9 , crypto = require('crypto')
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')
20 , ForeverAgent = require('forever-agent')
21 , FormData = require('form-data')
23 , Cookie = require('cookie-jar')
24 , CookieJar = Cookie.Jar
25 , cookieJar = new CookieJar
27 , copy = require('./lib/copy')
28 , debug = require('./lib/debug')
29 , getSafe = require('./lib/getSafe')
32 function safeStringify (obj) {
34 try { ret = JSON.stringify(obj) }
35 catch (e) { ret = _safeStringify(obj) }
40 var isUrl = /^https?:/i
43 https = require('https')
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)
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?
67 function isReadStream (rs) {
68 if (rs.readable && rs.path && rs.mode) {
73 function toBase64 (str) {
74 return (new Buffer(str || "", "ascii")).toString("base64")
78 return crypto.createHash('md5').update(str).digest('hex')
81 function Request (options) {
82 stream.Stream.call(this)
86 if (typeof options === 'string') {
87 options = {uri:options}
90 var reserved = Object.keys(Request.prototype)
91 for (var i in options) {
92 if (reserved.indexOf(i) === -1) {
95 if (typeof options[i] === 'function') {
101 if (options.method) {
102 this.explicitMethod = true
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.
113 if (!options) options = {}
115 if (!self.method) self.method = options.method || 'GET'
116 self.localAddress = options.localAddress
119 if (!self.pool && self.pool !== false) self.pool = globalPool
120 self.dests = self.dests || []
121 self.__isRequestRequest = true
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)
131 self.on('error', self.callback.bind())
132 self.on('complete', self.callback.bind(self, null))
135 if (self.url && !self.uri) {
136 // People use this property instead all the time so why not just support it.
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"))
145 if (typeof self.uri == "string") self.uri = url.parse(self.uri)
148 if (self.strictSSL === false) {
149 self.rejectUnauthorized = false
153 if (typeof self.proxy == 'string') self.proxy = url.parse(self.proxy)
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
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
168 self.agent = tunnelFn(tunnelOptions)
173 if (!self.uri.pathname) {self.uri.pathname = '/'}
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.'
186 self.emit('error', new Error(message))
187 return // This error was fatal
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 || []
197 self.headers = self.headers ? copy(self.headers) : {}
200 if (!self.hasHeader('host')) {
201 self.setHeader('host', self.uri.hostname)
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) )
210 self.jar(self._jar || options.jar)
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}
217 if (self.proxy && !self.tunnel) {
218 self.port = self.proxy.port
219 self.host = self.proxy.hostname
221 self.port = self.uri.port
222 self.host = self.uri.hostname
225 self.clientErrorHandler = function (error) {
226 if (self._aborted) return
228 if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
229 && self.agent.addRequestNoreuse) {
230 self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
235 if (self.timeout && self.timeoutTimer) {
236 clearTimeout(self.timeoutTimer)
237 self.timeoutTimer = null
239 self.emit('error', error)
242 self._parserErrorHandler = function (error) {
244 if (this.res.request) {
245 this.res.request.emit('error', error)
247 this.res.emit('error', error)
250 this._httpMessage.emit('error', error)
255 self.form(options.form)
258 if (options.qs) self.qs(options.qs)
261 self.path = self.uri.path
263 self.path = self.uri.pathname + (self.uri.search || "")
266 if (self.path.length === 0) self.path = '/'
269 // Auth must happen last in case signing is dependent on other headers
271 self.oauth(options.oauth)
275 self.aws(options.aws)
279 self.hawk(options.hawk)
282 if (options.httpSignature) {
283 self.httpSignature(options.httpSignature)
288 (options.auth.user==="") ? options.auth.user : (options.auth.user || options.auth.username ),
289 options.auth.pass || options.auth.password,
290 options.auth.sendImmediately)
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)
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(':')))
302 if (self.proxy && !self.tunnel) self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
305 self.json(options.json)
306 } else if (options.multipart) {
307 self.boundary = uuid()
308 self.multipart(options.multipart)
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
319 self.body = new Buffer(self.body)
320 length = self.body.length
323 length = self.body.length
326 if (!self.hasHeader('content-length')) self.setHeader('content-length', length)
328 throw new Error('Argument error, options.body.')
332 var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
333 , defaultModules = {'http:':http, 'https:':https}
334 , httpModules = self.httpModules || {}
336 self.httpModule = httpModules[protocol] || defaultModules[protocol]
338 if (!self.httpModule) return this.emit('error', new Error("Invalid protocol"))
340 if (options.ca) self.ca = options.ca
343 if (options.agentOptions) self.agentOptions = options.agentOptions
345 if (options.agentClass) {
346 self.agentClass = options.agentClass
347 } else if (options.forever) {
348 self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
350 self.agentClass = self.httpModule.Agent
354 if (self.pool === false) {
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
362 if (self.pool.maxSockets) {
363 // Don't use our pooling if node has the refactored client
364 self.agent.maxSockets = self.pool.maxSockets
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.")
371 if (isReadStream(src)) {
372 if (!self.hasHeader('content-type')) self.setHeader('content-type', mime.lookup(src.path))
375 for (var i in src.headers) {
376 if (!self.hasHeader(i)) {
377 self.setHeader(i, src.headers[i])
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
388 // self.on('pipe', function () {
389 // console.error("You have already piped to this stream. Pipeing twice is likely to break the request.")
393 process.nextTick(function () {
394 if (self._aborted) return
397 self.setHeaders(self._form.getHeaders())
398 self._form.pipe(self)
401 if (Array.isArray(self.body)) {
402 self.body.forEach(function (part) {
406 self.write(self.body)
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)
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 () {
427 var protocol = self.uri.protocol
429 if (protocol === 'https:') {
430 // previously was doing http, now doing https
431 // if it's https, then we might need to tunnel now.
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
441 self.agent = tunnelFn(tunnelOptions)
445 self.httpModule = https
446 switch (self.agentClass) {
448 self.agentClass = ForeverAgent.SSL
451 self.agentClass = https.Agent
454 // nothing we can do. Just hope for the best.
458 // if there's an agent, we need to get a new one.
459 if (self.agent) self.agent = self.getAgent()
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
471 self.agentClass = http.Agent
474 // nothing we can do. just hope for the best
478 // if there's an agent, then get a new one.
481 self.agent = self.getAgent()
486 Request.prototype.getAgent = function () {
487 var Agent = this.agentClass
489 if (this.agentOptions) {
490 for (var i in this.agentOptions) {
491 options[i] = this.agentOptions[i]
494 if (this.ca) options.ca = this.ca
495 if (typeof this.rejectUnauthorized !== 'undefined') options.rejectUnauthorized = this.rejectUnauthorized
497 if (this.cert && this.key) {
498 options.key = this.key
499 options.cert = this.cert
504 // different types of agents are in different pools
505 if (Agent !== this.httpModule.Agent) {
506 poolKey += Agent.name
509 if (!this.httpModule.globalAgent) {
511 options.host = this.host
512 options.port = this.port
513 if (poolKey) poolKey += ':'
514 poolKey += this.host + ':' + this.port
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:'
523 if (poolKey) poolKey += ':'
524 poolKey += options.ca
527 if (typeof options.rejectUnauthorized !== 'undefined') {
528 if (poolKey) poolKey += ':'
529 poolKey += options.rejectUnauthorized
533 poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
535 if (options.ciphers) {
536 if (poolKey) poolKey += ':'
537 poolKey += options.ciphers
540 if (options.secureOptions) {
541 if (poolKey) poolKey += ':'
542 poolKey += options.secureOptions
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
551 // we're using a stored agent. Make sure it's protocol-specific
552 poolKey = this.uri.protocol + poolKey
554 // already generated an agent for this setting
555 if (this.pool[poolKey]) return this.pool[poolKey]
557 return this.pool[poolKey] = new Agent(options)
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()
565 if (self._aborted) return
568 self.method = self.method || 'GET'
569 self.href = self.uri.href
571 if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
572 self.setHeader('content-length', self.src.stat.size)
575 self.aws(self._aws, true)
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
583 debug('make request', self.uri.href)
584 self.req = self.httpModule.request(reqOptions, self.onResponse.bind(self))
586 if (self.timeout && !self.timeoutTimer) {
587 self.timeoutTimer = setTimeout(function () {
589 var e = new Error("ETIMEDOUT")
591 self.emit("error", e)
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 () {
600 var e = new Error("ESOCKETTIMEDOUT")
601 e.code = "ESOCKETTIMEDOUT"
602 self.emit("error", e)
608 self.req.on('error', self.clientErrorHandler)
609 self.req.on('drain', function() {
612 self.on('end', function() {
613 if ( self.req.connection ) self.req.connection.removeListener('error', self._parserErrorHandler)
615 self.emit('request', self.req)
617 Request.prototype.onResponse = function (response) {
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)
624 if (response.connection.listeners('error').indexOf(self._parserErrorHandler) === -1) {
625 response.connection.once('error', self._parserErrorHandler)
628 debug('aborted', self.uri.href)
632 if (self._paused) response.pause()
633 else response.resume()
635 self.response = response
636 response.request = self
637 response.toJSON = toJSON
639 // XXX This is different on 0.10, because SSL is strict by default
640 if (self.httpModule === https &&
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))
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
655 var addCookie = function (cookie) {
658 self._jar.add(new Cookie(cookie))
660 else cookieJar.add(new Cookie(cookie))
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])
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)
676 if (self.followAllRedirects) {
677 redirectTo = location
678 } else if (self.followRedirect) {
679 switch (self.method) {
684 // Do not follow redirects
687 redirectTo = location
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)
698 self.auth(self._user, self._pass, true)
699 redirectTo = self.uri
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
707 var matches = authHeader.match(/([a-z0-9_-]+)="([^"]+)"/gi)
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)
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)
721 username: self._user,
722 realm: challenge.realm,
723 nonce: challenge.nonce,
726 response: digestResponse,
732 for (var k in authValues) {
733 authHeader.push(k + '="' + authValues[k] + '"')
735 authHeader = 'Digest ' + authHeader.join(', ')
736 self.setHeader('authorization', authHeader)
737 self._sentAuth = true
739 redirectTo = self.uri
745 debug('redirect to', redirectTo)
747 // ignore any potential response body. it cannot possibly be useful
748 // to us at this point.
749 if (self._paused) response.resume()
751 if (self._redirectsFollowed >= self.maxRedirects) {
752 self.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop "+self.uri.href))
755 self._redirectsFollowed += 1
757 if (!isUrl.test(redirectTo)) {
758 redirectTo = url.resolve(self.uri.href, redirectTo)
761 var uriPrev = self.uri
762 self.uri = url.parse(redirectTo)
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()
770 { statusCode : response.statusCode
771 , redirectUri: redirectTo
774 if (self.followAllRedirects && response.statusCode != 401) self.method = 'GET'
775 // self.method = 'GET' // Force all redirects to use GET || commented out fixes #215
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.
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')]
792 self.emit('redirect');
795 return // Ignore the rest of the response
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')
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.")
808 response.setEncoding(self.encoding)
812 self.emit('response', response)
814 self.dests.forEach(function (dest) {
818 response.on("data", function (chunk) {
819 self._destdata = true
820 self.emit("data", chunk)
822 response.on("end", function (chunk) {
824 self.emit("end", chunk)
826 response.on("close", function () {self.emit("close")})
831 self.on("data", function (chunk) {
833 bodyLen += chunk.length
835 self.on("end", function () {
836 debug('end event', self.uri.href)
838 debug('aborted', self.uri.href)
842 if (buffer.length && Buffer.isBuffer(buffer[0])) {
843 debug('has body', self.uri.href, bodyLen)
844 var body = new Buffer(bodyLen)
846 buffer.forEach(function (chunk) {
847 chunk.copy(body, i, 0, chunk.length)
850 if (self.encoding === null) {
853 response.body = body.toString(self.encoding)
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)
861 response.body = buffer.join('')
866 response.body = JSON.parse(response.body)
869 debug('emitting complete', self.uri.href)
870 if(response.body == undefined && !self._json) {
873 self.emit('complete', response, response.body)
878 self.on("end", function () {
880 debug('aborted', self.uri.href)
883 self.emit('complete', response);
887 debug('finish init function', self.uri.href)
890 Request.prototype.abort = function () {
896 else if (this.response) {
897 this.response.abort()
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]
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]
919 if (dest.setHeader && !dest.headersSent) {
920 for (var i in response.headers) {
921 dest.setHeader(i, response.headers[i])
923 dest.statusCode = response.statusCode
925 if (this.pipefilter) this.pipefilter(response, dest)
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
935 Request.prototype.setHeaders = function (headers) {
936 for (var i in headers) {this.setHeader(i, headers[i])}
939 Request.prototype.hasHeader = function (header, headers) {
940 var headers = Object.keys(headers || this.headers)
941 , lheaders = headers.map(function (h) {return h.toLowerCase()})
943 header = header.toLowerCase()
944 for (var i=0;i<lheaders.length;i++) {
945 if (lheaders[i] === header) return headers[i]
950 var hasHeader = Request.prototype.hasHeader
952 Request.prototype.qs = function (q, clobber) {
954 if (!clobber && this.uri.query) base = qs.parse(this.uri.query)
961 if (qs.stringify(base) === ''){
965 this.uri = url.parse(this.uri.href.split('?')[0] + '?' + qs.stringify(base))
967 this.path = this.uri.path
971 Request.prototype.form = function (form) {
973 this.setHeader('content-type', 'application/x-www-form-urlencoded; charset=utf-8')
974 this.body = qs.stringify(form).toString('utf8')
977 // create form-data object
978 this._form = new FormData()
981 Request.prototype.multipart = function (multipart) {
985 if (!self.hasHeader('content-type')) {
986 self.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
988 self.setHeader('content-type', self.headers['content-type'].split(';')[0] + '; boundary=' + self.boundary)
991 if (!multipart.forEach) throw new Error('Argument error, options.multipart.')
993 if (self.preambleCRLF) {
994 self.body.push(new Buffer('\r\n'))
997 multipart.forEach(function (part) {
999 if(body == null) throw Error('Body attribute missing in multipart.')
1001 var preamble = '--' + self.boundary + '\r\n'
1002 Object.keys(part).forEach(function (key) {
1003 preamble += key + ': ' + part[key] + '\r\n'
1006 self.body.push(new Buffer(preamble))
1007 self.body.push(new Buffer(body))
1008 self.body.push(new Buffer('\r\n'))
1010 self.body.push(new Buffer('--' + self.boundary + '--'))
1013 Request.prototype.json = function (val) {
1016 if (!self.hasHeader('accept')) self.setHeader('accept', 'application/json')
1019 if (typeof val === 'boolean') {
1020 if (typeof this.body === 'object') {
1021 this.body = safeStringify(this.body)
1022 self.setHeader('content-type', 'application/json')
1025 this.body = safeStringify(val)
1026 self.setHeader('content-type', 'application/json')
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]
1040 var getHeader = Request.prototype.getHeader
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')
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
1056 Request.prototype.aws = function (opts, now) {
1061 var date = new Date()
1062 this.setHeader('date', date.toUTCString())
1065 , secret: opts.secret
1066 , verb: this.method.toUpperCase()
1068 , contentType: this.getHeader('content-type') || ''
1069 , md5: this.getHeader('content-md5') || ''
1070 , amazonHeaders: aws.canonicalizeHeaders(this.headers)
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) {
1081 auth.resource = aws.canonicalizeResource(auth.resource)
1082 this.setHeader('authorization', aws.authorization(auth))
1086 Request.prototype.httpSignature = function (opts) {
1088 httpSignature.signRequest({
1089 getHeader: function(header) {
1090 return getHeader(header, req.headers)
1092 setHeader: function(header, value) {
1093 req.setHeader(header, value)
1095 method: this.method,
1098 debug('httpSignature authorization', this.getHeader('authorization'))
1103 Request.prototype.hawk = function (opts) {
1104 this.setHeader('Authorization', hawk.client.header(this.uri, this.method, opts).field)
1107 Request.prototype.oauth = function (_oauth) {
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'
1113 form = qs.parse(this.body)
1115 if (this.uri.query) {
1116 form = qs.parse(this.uri.query)
1118 if (!form) form = {}
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, '')
1126 oa.oauth_signature_method = 'HMAC-SHA1'
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
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)
1137 // oa.oauth_signature = signature
1138 for (var i in form) {
1139 if ( i.slice(0, 'oauth_') in _oauth) {
1142 delete oa['oauth_'+i]
1143 if (i !== 'x_auth_mode') delete oa[i]
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)
1152 Request.prototype.jar = function (jar) {
1155 if (this._redirectsFollowed === 0) {
1156 this.originalCookieHeader = this.getHeader('cookie')
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 })
1167 // fetch cookie from the global cookie jar
1168 cookies = cookieJar.get({ url: this.uri.href })
1171 if (cookies && cookies.length) {
1172 var cookieString = cookies.map(function (c) {
1173 return c.name + "=" + c.value
1176 if (this.originalCookieHeader) {
1177 // Don't overwrite existing Cookie header
1178 this.setHeader('cookie', this.originalCookieHeader + '; ' + cookieString)
1180 this.setHeader('cookie', cookieString)
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.")
1196 stream.Stream.prototype.pipe.call(this, dest, opts)
1201 this.dests.push(dest)
1202 stream.Stream.prototype.pipe.call(this, dest, opts)
1206 Request.prototype.write = function () {
1207 if (!this._started) this.start()
1208 return this.req.write.apply(this.req, arguments)
1210 Request.prototype.end = function (chunk) {
1211 if (chunk) this.write(chunk)
1212 if (!this._started) this.start()
1215 Request.prototype.pause = function () {
1216 if (!this.response) this._paused = true
1217 else this.response.pause.apply(this.response, arguments)
1219 Request.prototype.resume = function () {
1220 if (!this.response) this._paused = false
1221 else this.response.resume.apply(this.response, arguments)
1223 Request.prototype.destroy = function () {
1224 if (!this._ended) this.end()
1225 else if (this.response) this.response.destroy()
1228 function toJSON () {
1229 return getSafe(this, '__' + (((1+Math.random())*0x10000)|0).toString(16))
1232 Request.prototype.toJSON = toJSON
1235 module.exports = Request