3 var http = require('http')
4 , https = require('https')
6 , util = require('util')
7 , stream = require('stream')
8 , zlib = require('zlib')
10 , hawk = require('hawk')
11 , aws = require('aws-sign2')
12 , httpSignature = require('http-signature')
13 , mime = require('mime-types')
14 , stringstream = require('stringstream')
15 , caseless = require('caseless')
16 , ForeverAgent = require('forever-agent')
17 , FormData = require('form-data')
18 , isTypedArray = require('is-typedarray').strict
19 , helpers = require('./lib/helpers')
20 , cookies = require('./lib/cookies')
21 , getProxyFromURI = require('./lib/getProxyFromURI')
22 , Querystring = require('./lib/querystring').Querystring
23 , Har = require('./lib/har').Har
24 , Auth = require('./lib/auth').Auth
25 , OAuth = require('./lib/oauth').OAuth
26 , Multipart = require('./lib/multipart').Multipart
27 , Redirect = require('./lib/redirect').Redirect
28 , Tunnel = require('./lib/tunnel').Tunnel
30 var safeStringify = helpers.safeStringify
31 , isReadStream = helpers.isReadStream
32 , toBase64 = helpers.toBase64
33 , defer = helpers.defer
35 , version = helpers.version
36 , globalCookieJar = cookies.jar()
41 function filterForNonReserved(reserved, options) {
42 // Filter out properties that are not reserved.
43 // Reserved values are passed in at call site.
46 for (var i in options) {
47 var notReserved = (reserved.indexOf(i) === -1)
49 object[i] = options[i]
55 function filterOutReservedFunctions(reserved, options) {
56 // Filter out properties that are functions and are reserved.
57 // Reserved values are passed in at call site.
60 for (var i in options) {
61 var isReserved = !(reserved.indexOf(i) === -1)
62 var isFunction = (typeof options[i] === 'function')
63 if (!(isReserved && isFunction)) {
64 object[i] = options[i]
71 // Function for properly handling a connection error
72 function connectionErrorHandler(error) {
75 if (socket.res.request) {
76 socket.res.request.emit('error', error)
78 socket.res.emit('error', error)
81 socket._httpMessage.emit('error', error)
85 // Return a simpler request object to allow serialization
86 function requestToJSON() {
95 // Return a simpler response object to allow serialization
96 function responseToJSON() {
99 statusCode: self.statusCode,
101 headers: self.headers,
102 request: requestToJSON.call(self.request)
106 function Request (options) {
107 // if given the method property in options, set property explicitMethod to true
109 // extend the Request instance with any non-reserved properties
110 // remove any reserved functions from the options object
111 // set Request instance to be readable and writable
116 // start with HAR, then override with additional options
118 self._har = new Har(self)
119 options = self._har.options(options)
122 stream.Stream.call(self)
123 var reserved = Object.keys(Request.prototype)
124 var nonReserved = filterForNonReserved(reserved, options)
126 util._extend(self, nonReserved)
127 options = filterOutReservedFunctions(reserved, options)
131 if (options.method) {
132 self.explicitMethod = true
134 self._qs = new Querystring(self)
135 self._auth = new Auth(self)
136 self._oauth = new OAuth(self)
137 self._multipart = new Multipart(self)
138 self._redirect = new Redirect(self)
139 self._tunnel = new Tunnel(self)
143 util.inherits(Request, stream.Stream)
146 Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
149 console.error('REQUEST %s', util.format.apply(util, arguments))
152 Request.prototype.debug = debug
154 Request.prototype.init = function (options) {
155 // init() contains all the code to setup the request object.
156 // the actual outgoing request is not started until start() is called
157 // this function is called from both the constructor and on redirect.
162 self.headers = self.headers ? copy(self.headers) : {}
164 // Delete headers with value undefined since they break
165 // ClientRequest.OutgoingMessage.setHeader in node 0.12
166 for (var headerName in self.headers) {
167 if (typeof self.headers[headerName] === 'undefined') {
168 delete self.headers[headerName]
172 caseless.httpify(self, self.headers)
175 self.method = options.method || 'GET'
177 if (!self.localAddress) {
178 self.localAddress = options.localAddress
181 self._qs.init(options)
184 if (!self.pool && self.pool !== false) {
185 self.pool = globalPool
187 self.dests = self.dests || []
188 self.__isRequestRequest = true
190 // Protect against double callback
191 if (!self._callback && self.callback) {
192 self._callback = self.callback
193 self.callback = function () {
194 if (self._callbackCalled) {
195 return // Print a warning maybe?
197 self._callbackCalled = true
198 self._callback.apply(self, arguments)
200 self.on('error', self.callback.bind())
201 self.on('complete', self.callback.bind(self, null))
204 // People use this property instead all the time, so support it
205 if (!self.uri && self.url) {
210 // If there's a baseUrl, then use it as the base URL (i.e. uri must be
211 // specified as a relative path and is appended to baseUrl).
213 if (typeof self.baseUrl !== 'string') {
214 return self.emit('error', new Error('options.baseUrl must be a string'))
217 if (typeof self.uri !== 'string') {
218 return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'))
221 if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) {
222 return self.emit('error', new Error('options.uri must be a path when using options.baseUrl'))
225 // Handle all cases to make sure that there's only one slash between
227 var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1
228 var uriStartsWithSlash = self.uri.indexOf('/') === 0
230 if (baseUrlEndsWithSlash && uriStartsWithSlash) {
231 self.uri = self.baseUrl + self.uri.slice(1)
232 } else if (baseUrlEndsWithSlash || uriStartsWithSlash) {
233 self.uri = self.baseUrl + self.uri
234 } else if (self.uri === '') {
235 self.uri = self.baseUrl
237 self.uri = self.baseUrl + '/' + self.uri
242 // A URI is needed by this point, emit error if we haven't been able to get one
244 return self.emit('error', new Error('options.uri is a required argument'))
247 // If a string URI/URL was given, parse it into a URL object
248 if (typeof self.uri === 'string') {
249 self.uri = url.parse(self.uri)
252 // Some URL objects are not from a URL parsed string and need href added
253 if (!self.uri.href) {
254 self.uri.href = url.format(self.uri)
257 // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme
258 if (self.uri.protocol === 'unix:') {
259 return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'))
262 // Support Unix Sockets
263 if (self.uri.host === 'unix') {
264 self.enableUnixSocket()
267 if (self.strictSSL === false) {
268 self.rejectUnauthorized = false
271 if (!self.uri.pathname) {self.uri.pathname = '/'}
273 if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
274 // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
275 // Detect and reject it as soon as possible
276 var faultyUri = url.format(self.uri)
277 var message = 'Invalid URI "' + faultyUri + '"'
278 if (Object.keys(options).length === 0) {
279 // No option ? This can be the sign of a redirect
280 // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
281 // they should be warned that it can be caused by a redirection (can save some hair)
282 message += '. This can be caused by a crappy redirection.'
284 // This error was fatal
286 return self.emit('error', new Error(message))
289 if (!self.hasOwnProperty('proxy')) {
290 self.proxy = getProxyFromURI(self.uri)
293 self.tunnel = self._tunnel.isEnabled()
295 self._tunnel.setup(options)
298 self._redirect.onRequest(options)
301 if (!self.hasHeader('host')) {
302 var hostHeaderName = self.originalHostHeaderName || 'host'
303 self.setHeader(hostHeaderName, self.uri.hostname)
305 if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') &&
306 !(self.uri.port === 443 && self.uri.protocol === 'https:') ) {
307 self.setHeader(hostHeaderName, self.getHeader('host') + (':' + self.uri.port) )
313 self.jar(self._jar || options.jar)
315 if (!self.uri.port) {
316 if (self.uri.protocol === 'http:') {self.uri.port = 80}
317 else if (self.uri.protocol === 'https:') {self.uri.port = 443}
320 if (self.proxy && !self.tunnel) {
321 self.port = self.proxy.port
322 self.host = self.proxy.hostname
324 self.port = self.uri.port
325 self.host = self.uri.hostname
329 self.form(options.form)
332 if (options.formData) {
333 var formData = options.formData
334 var requestForm = self.form()
335 var appendFormValue = function (key, value) {
336 if (value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
337 requestForm.append(key, value.value, value.options)
339 requestForm.append(key, value)
342 for (var formKey in formData) {
343 if (formData.hasOwnProperty(formKey)) {
344 var formValue = formData[formKey]
345 if (formValue instanceof Array) {
346 for (var j = 0; j < formValue.length; j++) {
347 appendFormValue(formKey, formValue[j])
350 appendFormValue(formKey, formValue)
361 self.path = self.uri.path
363 self.path = self.uri.pathname + (self.uri.search || '')
366 if (self.path.length === 0) {
370 // Auth must happen last in case signing is dependent on other headers
372 self.aws(options.aws)
376 self.hawk(options.hawk)
379 if (options.httpSignature) {
380 self.httpSignature(options.httpSignature)
384 if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
385 options.auth.user = options.auth.username
387 if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
388 options.auth.pass = options.auth.password
394 options.auth.sendImmediately,
399 if (self.gzip && !self.hasHeader('accept-encoding')) {
400 self.setHeader('accept-encoding', 'gzip')
403 if (self.uri.auth && !self.hasHeader('authorization')) {
404 var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
405 self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
408 if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
409 var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
410 var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
411 self.setHeader('proxy-authorization', authHeader)
414 if (self.proxy && !self.tunnel) {
415 self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
419 self.json(options.json)
421 if (options.multipart) {
422 self.multipart(options.multipart)
427 self.elapsedTime = self.elapsedTime || 0
430 function setContentLength () {
431 if (isTypedArray(self.body)) {
432 self.body = new Buffer(self.body)
435 if (!self.hasHeader('content-length')) {
437 if (typeof self.body === 'string') {
438 length = Buffer.byteLength(self.body)
440 else if (Array.isArray(self.body)) {
441 length = self.body.reduce(function (a, b) {return a + b.length}, 0)
444 length = self.body.length
448 self.setHeader('content-length', length)
450 self.emit('error', new Error('Argument error, options.body.'))
459 self.oauth(options.oauth)
460 } else if (self._oauth.params && self.hasHeader('authorization')) {
461 self.oauth(self._oauth.params)
464 var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
465 , defaultModules = {'http:':http, 'https:':https}
466 , httpModules = self.httpModules || {}
468 self.httpModule = httpModules[protocol] || defaultModules[protocol]
470 if (!self.httpModule) {
471 return self.emit('error', new Error('Invalid protocol: ' + protocol))
479 if (options.agentOptions) {
480 self.agentOptions = options.agentOptions
483 if (options.agentClass) {
484 self.agentClass = options.agentClass
485 } else if (options.forever) {
487 // use ForeverAgent in node 0.10- only
488 if (v.major === 0 && v.minor <= 10) {
489 self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
491 self.agentClass = self.httpModule.Agent
492 self.agentOptions = self.agentOptions || {}
493 self.agentOptions.keepAlive = true
496 self.agentClass = self.httpModule.Agent
500 if (self.pool === false) {
503 self.agent = self.agent || self.getNewAgent()
506 self.on('pipe', function (src) {
507 if (self.ntick && self._started) {
508 self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'))
511 if (isReadStream(src)) {
512 if (!self.hasHeader('content-type')) {
513 self.setHeader('content-type', mime.lookup(src.path))
517 for (var i in src.headers) {
518 if (!self.hasHeader(i)) {
519 self.setHeader(i, src.headers[i])
523 if (self._json && !self.hasHeader('content-type')) {
524 self.setHeader('content-type', 'application/json')
526 if (src.method && !self.explicitMethod) {
527 self.method = src.method
531 // self.on('pipe', function () {
532 // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
541 var end = function () {
543 if (!self._auth.hasAuth) {
544 self._form.pipe(self)
546 else if (self._auth.hasAuth && self._auth.sentAuth) {
547 self._form.pipe(self)
550 if (self._multipart && self._multipart.chunked) {
551 self._multipart.body.pipe(self)
555 if (Array.isArray(self.body)) {
556 self.body.forEach(function (part) {
560 self.write(self.body)
563 } else if (self.requestBodyStream) {
564 console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
565 self.requestBodyStream.pipe(self)
566 } else if (!self.src) {
567 if (self._auth.hasAuth && !self._auth.sentAuth) {
571 if (self.method !== 'GET' && typeof self.method !== 'undefined') {
572 self.setHeader('content-length', 0)
578 if (self._form && !self.hasHeader('content-length')) {
579 // Before ending the request, we had to compute the length of the whole form, asyncly
580 self.setHeader(self._form.getHeaders(), true)
581 self._form.getLength(function (err, length) {
583 self.setHeader('content-length', length)
596 Request.prototype.getNewAgent = function () {
598 var Agent = self.agentClass
600 if (self.agentOptions) {
601 for (var i in self.agentOptions) {
602 options[i] = self.agentOptions[i]
609 options.ciphers = self.ciphers
611 if (self.secureProtocol) {
612 options.secureProtocol = self.secureProtocol
614 if (self.secureOptions) {
615 options.secureOptions = self.secureOptions
617 if (typeof self.rejectUnauthorized !== 'undefined') {
618 options.rejectUnauthorized = self.rejectUnauthorized
621 if (self.cert && self.key) {
622 options.key = self.key
623 options.cert = self.cert
627 options.pfx = self.pfx
630 if (self.passphrase) {
631 options.passphrase = self.passphrase
636 // different types of agents are in different pools
637 if (Agent !== self.httpModule.Agent) {
638 poolKey += Agent.name
641 // ca option is only relevant if proxy or destination are https
642 var proxy = self.proxy
643 if (typeof proxy === 'string') {
644 proxy = url.parse(proxy)
646 var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
653 poolKey += options.ca
656 if (typeof options.rejectUnauthorized !== 'undefined') {
660 poolKey += options.rejectUnauthorized
667 poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
674 poolKey += options.pfx.toString('ascii')
677 if (options.ciphers) {
681 poolKey += options.ciphers
684 if (options.secureProtocol) {
688 poolKey += options.secureProtocol
691 if (options.secureOptions) {
695 poolKey += options.secureOptions
699 if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
700 // not doing anything special. Use the globalAgent
701 return self.httpModule.globalAgent
704 // we're using a stored agent. Make sure it's protocol-specific
705 poolKey = self.uri.protocol + poolKey
707 // generate a new agent for this setting if none yet exists
708 if (!self.pool[poolKey]) {
709 self.pool[poolKey] = new Agent(options)
710 // properly set maxSockets on new agents
711 if (self.pool.maxSockets) {
712 self.pool[poolKey].maxSockets = self.pool.maxSockets
716 return self.pool[poolKey]
719 Request.prototype.start = function () {
720 // start() is called once we are ready to send the outgoing HTTP request.
721 // this is usually called on the first write(), end() or on nextTick()
729 self.method = self.method || 'GET'
730 self.href = self.uri.href
732 if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
733 self.setHeader('content-length', self.src.stat.size)
736 self.aws(self._aws, true)
739 // We have a method named auth, which is completely different from the http.request
740 // auth option. If we don't remove it, we're gonna have a bad time.
741 var reqOptions = copy(self)
742 delete reqOptions.auth
744 debug('make request', self.uri.href)
746 self.req = self.httpModule.request(reqOptions)
749 self.startTime = new Date().getTime()
752 if (self.timeout && !self.timeoutTimer) {
753 var timeout = self.timeout < 0 ? 0 : self.timeout
754 // Set a timeout in memory - this block will throw if the server takes more
755 // than `timeout` to write the HTTP status and headers (corresponding to
756 // the on('response') event on the client). NB: this measures wall-clock
757 // time, not the time between bytes sent by the server.
758 self.timeoutTimer = setTimeout(function () {
759 var connectTimeout = self.req.socket && self.req.socket.readable === false
761 var e = new Error('ETIMEDOUT')
763 e.connect = connectTimeout
764 self.emit('error', e)
767 if (self.req.setTimeout) { // only works on node 0.6+
768 // Set an additional timeout on the socket, via the `setsockopt` syscall.
769 // This timeout sets the amount of time to wait *between* bytes sent
770 // from the server, and may or may not correspond to the wall-clock time
771 // elapsed from the start of the request.
773 // In particular, it's useful for erroring if the server fails to send
774 // data halfway through streaming a response.
775 self.req.setTimeout(timeout, function () {
778 var e = new Error('ESOCKETTIMEDOUT')
779 e.code = 'ESOCKETTIMEDOUT'
781 self.emit('error', e)
787 self.req.on('response', self.onRequestResponse.bind(self))
788 self.req.on('error', self.onRequestError.bind(self))
789 self.req.on('drain', function() {
792 self.req.on('socket', function(socket) {
793 self.emit('socket', socket)
796 self.on('end', function() {
797 if ( self.req.connection ) {
798 self.req.connection.removeListener('error', connectionErrorHandler)
801 self.emit('request', self.req)
804 Request.prototype.onRequestError = function (error) {
809 if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
810 && self.agent.addRequestNoreuse) {
811 self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
816 if (self.timeout && self.timeoutTimer) {
817 clearTimeout(self.timeoutTimer)
818 self.timeoutTimer = null
820 self.emit('error', error)
823 Request.prototype.onRequestResponse = function (response) {
825 debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
826 response.on('end', function() {
828 self.elapsedTime += (new Date().getTime() - self.startTime)
829 debug('elapsed time', self.elapsedTime)
830 response.elapsedTime = self.elapsedTime
832 debug('response end', self.uri.href, response.statusCode, response.headers)
835 // The check on response.connection is a workaround for browserify.
836 if (response.connection && response.connection.listeners('error').indexOf(connectionErrorHandler) === -1) {
837 response.connection.setMaxListeners(0)
838 response.connection.once('error', connectionErrorHandler)
841 debug('aborted', self.uri.href)
846 self.response = response
847 response.request = self
848 response.toJSON = responseToJSON
850 // XXX This is different on 0.10, because SSL is strict by default
851 if (self.httpModule === https &&
852 self.strictSSL && (!response.hasOwnProperty('socket') ||
853 !response.socket.authorized)) {
854 debug('strict ssl error', self.uri.href)
855 var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
856 self.emit('error', new Error('SSL Error: ' + sslErr))
860 // Save the original host before any redirect (if it changes, we need to
861 // remove any authorization headers). Also remember the case of the header
862 // name because lots of broken servers expect Host instead of host and we
863 // want the caller to be able to specify this.
864 self.originalHost = self.getHeader('host')
865 if (!self.originalHostHeaderName) {
866 self.originalHostHeaderName = self.hasHeader('host')
869 self.removeHeader('host')
871 if (self.timeout && self.timeoutTimer) {
872 clearTimeout(self.timeoutTimer)
873 self.timeoutTimer = null
876 var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
877 var addCookie = function (cookie) {
878 //set the cookie if it's domain in the href's domain.
880 targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
882 self.emit('error', e)
886 response.caseless = caseless(response.headers)
888 if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
889 var headerName = response.caseless.has('set-cookie')
890 if (Array.isArray(response.headers[headerName])) {
891 response.headers[headerName].forEach(addCookie)
893 addCookie(response.headers[headerName])
897 if (self._redirect.onResponse(response)) {
898 return // Ignore the rest of the response
900 // Be a good stream and emit end when the response is finished.
901 // Hack to emit end on close because of a core bug that never fires end
902 response.on('close', function () {
904 self.response.emit('end')
908 response.on('end', function () {
914 var contentEncoding = response.headers['content-encoding'] || 'identity'
915 contentEncoding = contentEncoding.trim().toLowerCase()
917 if (contentEncoding === 'gzip') {
918 responseContent = zlib.createGunzip()
919 response.pipe(responseContent)
921 // Since previous versions didn't check for Content-Encoding header,
922 // ignore any invalid values to preserve backwards-compatibility
923 if (contentEncoding !== 'identity') {
924 debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
926 responseContent = response
929 responseContent = response
933 if (self.dests.length !== 0) {
934 console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
935 } else if (responseContent.setEncoding) {
936 responseContent.setEncoding(self.encoding)
938 // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with
940 // If/When support for 0.9.4 is dropped, this should be unnecessary.
941 responseContent = responseContent.pipe(stringstream(self.encoding))
946 responseContent.pause()
949 self.responseContent = responseContent
951 self.emit('response', response)
953 self.dests.forEach(function (dest) {
957 responseContent.on('data', function (chunk) {
958 self._destdata = true
959 self.emit('data', chunk)
961 responseContent.on('end', function (chunk) {
962 self.emit('end', chunk)
964 responseContent.on('error', function (error) {
965 self.emit('error', error)
967 responseContent.on('close', function () {self.emit('close')})
970 self.readResponseBody(response)
974 self.on('end', function () {
976 debug('aborted', self.uri.href)
979 self.emit('complete', response)
983 debug('finish init function', self.uri.href)
986 Request.prototype.readResponseBody = function (response) {
988 debug('reading response\'s body')
992 self.on('data', function (chunk) {
993 if (Buffer.isBuffer(chunk)) {
999 self.on('end', function () {
1000 debug('end event', self.uri.href)
1001 if (self._aborted) {
1002 debug('aborted', self.uri.href)
1006 if (buffer.length) {
1007 debug('has body', self.uri.href, buffer.length)
1008 if (self.encoding === null) {
1009 // response.body = buffer
1010 // can't move to this until https://github.com/rvagg/bl/issues/13
1011 response.body = buffer.slice()
1013 response.body = buffer.toString(self.encoding)
1015 } else if (strings.length) {
1016 // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
1017 // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
1018 if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
1019 strings[0] = strings[0].substring(1)
1021 response.body = strings.join('')
1026 response.body = JSON.parse(response.body, self._jsonReviver)
1028 debug('invalid JSON received', self.uri.href)
1031 debug('emitting complete', self.uri.href)
1032 if (typeof response.body === 'undefined' && !self._json) {
1033 response.body = self.encoding === null ? new Buffer(0) : ''
1035 self.emit('complete', response, response.body)
1039 Request.prototype.abort = function () {
1041 self._aborted = true
1046 else if (self.response) {
1047 self.response.abort()
1053 Request.prototype.pipeDest = function (dest) {
1055 var response = self.response
1056 // Called after the response is received
1057 if (dest.headers && !dest.headersSent) {
1058 if (response.caseless.has('content-type')) {
1059 var ctname = response.caseless.has('content-type')
1060 if (dest.setHeader) {
1061 dest.setHeader(ctname, response.headers[ctname])
1064 dest.headers[ctname] = response.headers[ctname]
1068 if (response.caseless.has('content-length')) {
1069 var clname = response.caseless.has('content-length')
1070 if (dest.setHeader) {
1071 dest.setHeader(clname, response.headers[clname])
1073 dest.headers[clname] = response.headers[clname]
1077 if (dest.setHeader && !dest.headersSent) {
1078 for (var i in response.headers) {
1079 // If the response content is being decoded, the Content-Encoding header
1080 // of the response doesn't represent the piped content, so don't pass it.
1081 if (!self.gzip || i !== 'content-encoding') {
1082 dest.setHeader(i, response.headers[i])
1085 dest.statusCode = response.statusCode
1087 if (self.pipefilter) {
1088 self.pipefilter(response, dest)
1092 Request.prototype.qs = function (q, clobber) {
1095 if (!clobber && self.uri.query) {
1096 base = self._qs.parse(self.uri.query)
1105 var qs = self._qs.stringify(base)
1111 self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
1113 self.path = self.uri.path
1115 if (self.uri.host === 'unix') {
1116 self.enableUnixSocket()
1121 Request.prototype.form = function (form) {
1124 if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
1125 self.setHeader('content-type', 'application/x-www-form-urlencoded')
1127 self.body = (typeof form === 'string')
1128 ? self._qs.rfc3986(form.toString('utf8'))
1129 : self._qs.stringify(form).toString('utf8')
1132 // create form-data object
1133 self._form = new FormData()
1134 self._form.on('error', function(err) {
1135 err.message = 'form-data: ' + err.message
1136 self.emit('error', err)
1141 Request.prototype.multipart = function (multipart) {
1144 self._multipart.onRequest(multipart)
1146 if (!self._multipart.chunked) {
1147 self.body = self._multipart.body
1152 Request.prototype.json = function (val) {
1155 if (!self.hasHeader('accept')) {
1156 self.setHeader('accept', 'application/json')
1160 if (typeof val === 'boolean') {
1161 if (self.body !== undefined) {
1162 if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
1163 self.body = safeStringify(self.body)
1165 self.body = self._qs.rfc3986(self.body)
1167 if (!self.hasHeader('content-type')) {
1168 self.setHeader('content-type', 'application/json')
1172 self.body = safeStringify(val)
1173 if (!self.hasHeader('content-type')) {
1174 self.setHeader('content-type', 'application/json')
1178 if (typeof self.jsonReviver === 'function') {
1179 self._jsonReviver = self.jsonReviver
1184 Request.prototype.getHeader = function (name, headers) {
1186 var result, re, match
1188 headers = self.headers
1190 Object.keys(headers).forEach(function (key) {
1191 if (key.length !== name.length) {
1194 re = new RegExp(name, 'i')
1195 match = key.match(re)
1197 result = headers[key]
1202 Request.prototype.enableUnixSocket = function () {
1203 // Get the socket & request paths from the URL
1204 var unixParts = this.uri.path.split(':')
1205 , host = unixParts[0]
1206 , path = unixParts[1]
1207 // Apply unix properties to request
1208 this.socketPath = host
1209 this.uri.pathname = path
1210 this.uri.path = path
1211 this.uri.host = host
1212 this.uri.hostname = host
1213 this.uri.isUnix = true
1217 Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
1220 self._auth.onRequest(user, pass, sendImmediately, bearer)
1224 Request.prototype.aws = function (opts, now) {
1231 var date = new Date()
1232 self.setHeader('date', date.toUTCString())
1235 , secret: opts.secret
1236 , verb: self.method.toUpperCase()
1238 , contentType: self.getHeader('content-type') || ''
1239 , md5: self.getHeader('content-md5') || ''
1240 , amazonHeaders: aws.canonicalizeHeaders(self.headers)
1242 var path = self.uri.path
1243 if (opts.bucket && path) {
1244 auth.resource = '/' + opts.bucket + path
1245 } else if (opts.bucket && !path) {
1246 auth.resource = '/' + opts.bucket
1247 } else if (!opts.bucket && path) {
1248 auth.resource = path
1249 } else if (!opts.bucket && !path) {
1252 auth.resource = aws.canonicalizeResource(auth.resource)
1253 self.setHeader('authorization', aws.authorization(auth))
1257 Request.prototype.httpSignature = function (opts) {
1259 httpSignature.signRequest({
1260 getHeader: function(header) {
1261 return self.getHeader(header, self.headers)
1263 setHeader: function(header, value) {
1264 self.setHeader(header, value)
1266 method: self.method,
1269 debug('httpSignature authorization', self.getHeader('authorization'))
1273 Request.prototype.hawk = function (opts) {
1275 self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field)
1277 Request.prototype.oauth = function (_oauth) {
1280 self._oauth.onRequest(_oauth)
1285 Request.prototype.jar = function (jar) {
1289 if (self._redirect.redirectsFollowed === 0) {
1290 self.originalCookieHeader = self.getHeader('cookie')
1296 self._disableCookies = true
1298 var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
1299 var urihref = self.uri.href
1300 //fetch cookie in the Specified host
1301 if (targetCookieJar) {
1302 cookies = targetCookieJar.getCookieString(urihref)
1306 //if need cookie and cookie is not empty
1307 if (cookies && cookies.length) {
1308 if (self.originalCookieHeader) {
1309 // Don't overwrite existing Cookie header
1310 self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
1312 self.setHeader('cookie', cookies)
1321 Request.prototype.pipe = function (dest, opts) {
1324 if (self.response) {
1325 if (self._destdata) {
1326 self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
1327 } else if (self._ended) {
1328 self.emit('error', new Error('You cannot pipe after the response has been ended.'))
1330 stream.Stream.prototype.pipe.call(self, dest, opts)
1335 self.dests.push(dest)
1336 stream.Stream.prototype.pipe.call(self, dest, opts)
1340 Request.prototype.write = function () {
1342 if (self._aborted) {return}
1344 if (!self._started) {
1347 return self.req.write.apply(self.req, arguments)
1349 Request.prototype.end = function (chunk) {
1351 if (self._aborted) {return}
1356 if (!self._started) {
1361 Request.prototype.pause = function () {
1363 if (!self.responseContent) {
1366 self.responseContent.pause.apply(self.responseContent, arguments)
1369 Request.prototype.resume = function () {
1371 if (!self.responseContent) {
1372 self._paused = false
1374 self.responseContent.resume.apply(self.responseContent, arguments)
1377 Request.prototype.destroy = function () {
1381 } else if (self.response) {
1382 self.response.destroy()
1386 Request.defaultProxyHeaderWhiteList =
1387 Tunnel.defaultProxyHeaderWhiteList.slice()
1389 Request.defaultProxyHeaderExclusiveList =
1390 Tunnel.defaultProxyHeaderExclusiveList.slice()
1394 Request.prototype.toJSON = requestToJSON
1395 module.exports = Request