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 , aws2 = require('aws-sign2')
12 , aws4 = require('aws4')
13 , httpSignature = require('http-signature')
14 , mime = require('mime-types')
15 , stringstream = require('stringstream')
16 , caseless = require('caseless')
17 , ForeverAgent = require('forever-agent')
18 , FormData = require('form-data')
19 , extend = require('extend')
20 , isstream = require('isstream')
21 , isTypedArray = require('is-typedarray').strict
22 , helpers = require('./lib/helpers')
23 , cookies = require('./lib/cookies')
24 , getProxyFromURI = require('./lib/getProxyFromURI')
25 , Querystring = require('./lib/querystring').Querystring
26 , Har = require('./lib/har').Har
27 , Auth = require('./lib/auth').Auth
28 , OAuth = require('./lib/oauth').OAuth
29 , Multipart = require('./lib/multipart').Multipart
30 , Redirect = require('./lib/redirect').Redirect
31 , Tunnel = require('./lib/tunnel').Tunnel
33 var safeStringify = helpers.safeStringify
34 , isReadStream = helpers.isReadStream
35 , toBase64 = helpers.toBase64
36 , defer = helpers.defer
38 , version = helpers.version
39 , globalCookieJar = cookies.jar()
44 function filterForNonReserved(reserved, options) {
45 // Filter out properties that are not reserved.
46 // Reserved values are passed in at call site.
49 for (var i in options) {
50 var notReserved = (reserved.indexOf(i) === -1)
52 object[i] = options[i]
58 function filterOutReservedFunctions(reserved, options) {
59 // Filter out properties that are functions and are reserved.
60 // Reserved values are passed in at call site.
63 for (var i in options) {
64 var isReserved = !(reserved.indexOf(i) === -1)
65 var isFunction = (typeof options[i] === 'function')
66 if (!(isReserved && isFunction)) {
67 object[i] = options[i]
74 // Return a simpler request object to allow serialization
75 function requestToJSON() {
84 // Return a simpler response object to allow serialization
85 function responseToJSON() {
88 statusCode: self.statusCode,
90 headers: self.headers,
91 request: requestToJSON.call(self.request)
95 function Request (options) {
96 // if given the method property in options, set property explicitMethod to true
98 // extend the Request instance with any non-reserved properties
99 // remove any reserved functions from the options object
100 // set Request instance to be readable and writable
105 // start with HAR, then override with additional options
107 self._har = new Har(self)
108 options = self._har.options(options)
111 stream.Stream.call(self)
112 var reserved = Object.keys(Request.prototype)
113 var nonReserved = filterForNonReserved(reserved, options)
115 extend(self, nonReserved)
116 options = filterOutReservedFunctions(reserved, options)
120 if (options.method) {
121 self.explicitMethod = true
123 self._qs = new Querystring(self)
124 self._auth = new Auth(self)
125 self._oauth = new OAuth(self)
126 self._multipart = new Multipart(self)
127 self._redirect = new Redirect(self)
128 self._tunnel = new Tunnel(self)
132 util.inherits(Request, stream.Stream)
135 Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
138 console.error('REQUEST %s', util.format.apply(util, arguments))
141 Request.prototype.debug = debug
143 Request.prototype.init = function (options) {
144 // init() contains all the code to setup the request object.
145 // the actual outgoing request is not started until start() is called
146 // this function is called from both the constructor and on redirect.
151 self.headers = self.headers ? copy(self.headers) : {}
153 // Delete headers with value undefined since they break
154 // ClientRequest.OutgoingMessage.setHeader in node 0.12
155 for (var headerName in self.headers) {
156 if (typeof self.headers[headerName] === 'undefined') {
157 delete self.headers[headerName]
161 caseless.httpify(self, self.headers)
164 self.method = options.method || 'GET'
166 if (!self.localAddress) {
167 self.localAddress = options.localAddress
170 self._qs.init(options)
173 if (!self.pool && self.pool !== false) {
174 self.pool = globalPool
176 self.dests = self.dests || []
177 self.__isRequestRequest = true
179 // Protect against double callback
180 if (!self._callback && self.callback) {
181 self._callback = self.callback
182 self.callback = function () {
183 if (self._callbackCalled) {
184 return // Print a warning maybe?
186 self._callbackCalled = true
187 self._callback.apply(self, arguments)
189 self.on('error', self.callback.bind())
190 self.on('complete', self.callback.bind(self, null))
193 // People use this property instead all the time, so support it
194 if (!self.uri && self.url) {
199 // If there's a baseUrl, then use it as the base URL (i.e. uri must be
200 // specified as a relative path and is appended to baseUrl).
202 if (typeof self.baseUrl !== 'string') {
203 return self.emit('error', new Error('options.baseUrl must be a string'))
206 if (typeof self.uri !== 'string') {
207 return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'))
210 if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) {
211 return self.emit('error', new Error('options.uri must be a path when using options.baseUrl'))
214 // Handle all cases to make sure that there's only one slash between
216 var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1
217 var uriStartsWithSlash = self.uri.indexOf('/') === 0
219 if (baseUrlEndsWithSlash && uriStartsWithSlash) {
220 self.uri = self.baseUrl + self.uri.slice(1)
221 } else if (baseUrlEndsWithSlash || uriStartsWithSlash) {
222 self.uri = self.baseUrl + self.uri
223 } else if (self.uri === '') {
224 self.uri = self.baseUrl
226 self.uri = self.baseUrl + '/' + self.uri
231 // A URI is needed by this point, emit error if we haven't been able to get one
233 return self.emit('error', new Error('options.uri is a required argument'))
236 // If a string URI/URL was given, parse it into a URL object
237 if (typeof self.uri === 'string') {
238 self.uri = url.parse(self.uri)
241 // Some URL objects are not from a URL parsed string and need href added
242 if (!self.uri.href) {
243 self.uri.href = url.format(self.uri)
246 // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme
247 if (self.uri.protocol === 'unix:') {
248 return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'))
251 // Support Unix Sockets
252 if (self.uri.host === 'unix') {
253 self.enableUnixSocket()
256 if (self.strictSSL === false) {
257 self.rejectUnauthorized = false
260 if (!self.uri.pathname) {self.uri.pathname = '/'}
262 if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
263 // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
264 // Detect and reject it as soon as possible
265 var faultyUri = url.format(self.uri)
266 var message = 'Invalid URI "' + faultyUri + '"'
267 if (Object.keys(options).length === 0) {
268 // No option ? This can be the sign of a redirect
269 // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
270 // they should be warned that it can be caused by a redirection (can save some hair)
271 message += '. This can be caused by a crappy redirection.'
273 // This error was fatal
275 return self.emit('error', new Error(message))
278 if (!self.hasOwnProperty('proxy')) {
279 self.proxy = getProxyFromURI(self.uri)
282 self.tunnel = self._tunnel.isEnabled()
284 self._tunnel.setup(options)
287 self._redirect.onRequest(options)
290 if (!self.hasHeader('host')) {
291 var hostHeaderName = self.originalHostHeaderName || 'host'
292 self.setHeader(hostHeaderName, self.uri.hostname)
294 if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') &&
295 !(self.uri.port === 443 && self.uri.protocol === 'https:') ) {
296 self.setHeader(hostHeaderName, self.getHeader('host') + (':' + self.uri.port) )
302 self.jar(self._jar || options.jar)
304 if (!self.uri.port) {
305 if (self.uri.protocol === 'http:') {self.uri.port = 80}
306 else if (self.uri.protocol === 'https:') {self.uri.port = 443}
309 if (self.proxy && !self.tunnel) {
310 self.port = self.proxy.port
311 self.host = self.proxy.hostname
313 self.port = self.uri.port
314 self.host = self.uri.hostname
318 self.form(options.form)
321 if (options.formData) {
322 var formData = options.formData
323 var requestForm = self.form()
324 var appendFormValue = function (key, value) {
325 if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
326 requestForm.append(key, value.value, value.options)
328 requestForm.append(key, value)
331 for (var formKey in formData) {
332 if (formData.hasOwnProperty(formKey)) {
333 var formValue = formData[formKey]
334 if (formValue instanceof Array) {
335 for (var j = 0; j < formValue.length; j++) {
336 appendFormValue(formKey, formValue[j])
339 appendFormValue(formKey, formValue)
350 self.path = self.uri.path
352 self.path = self.uri.pathname + (self.uri.search || '')
355 if (self.path.length === 0) {
359 // Auth must happen last in case signing is dependent on other headers
361 self.aws(options.aws)
365 self.hawk(options.hawk)
368 if (options.httpSignature) {
369 self.httpSignature(options.httpSignature)
373 if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
374 options.auth.user = options.auth.username
376 if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
377 options.auth.pass = options.auth.password
383 options.auth.sendImmediately,
388 if (self.gzip && !self.hasHeader('accept-encoding')) {
389 self.setHeader('accept-encoding', 'gzip, deflate')
392 if (self.uri.auth && !self.hasHeader('authorization')) {
393 var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
394 self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
397 if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
398 var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
399 var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
400 self.setHeader('proxy-authorization', authHeader)
403 if (self.proxy && !self.tunnel) {
404 self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
408 self.json(options.json)
410 if (options.multipart) {
411 self.multipart(options.multipart)
416 self.elapsedTime = self.elapsedTime || 0
419 function setContentLength () {
420 if (isTypedArray(self.body)) {
421 self.body = new Buffer(self.body)
424 if (!self.hasHeader('content-length')) {
426 if (typeof self.body === 'string') {
427 length = Buffer.byteLength(self.body)
429 else if (Array.isArray(self.body)) {
430 length = self.body.reduce(function (a, b) {return a + b.length}, 0)
433 length = self.body.length
437 self.setHeader('content-length', length)
439 self.emit('error', new Error('Argument error, options.body.'))
443 if (self.body && !isstream(self.body)) {
448 self.oauth(options.oauth)
449 } else if (self._oauth.params && self.hasHeader('authorization')) {
450 self.oauth(self._oauth.params)
453 var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
454 , defaultModules = {'http:':http, 'https:':https}
455 , httpModules = self.httpModules || {}
457 self.httpModule = httpModules[protocol] || defaultModules[protocol]
459 if (!self.httpModule) {
460 return self.emit('error', new Error('Invalid protocol: ' + protocol))
468 if (options.agentOptions) {
469 self.agentOptions = options.agentOptions
472 if (options.agentClass) {
473 self.agentClass = options.agentClass
474 } else if (options.forever) {
476 // use ForeverAgent in node 0.10- only
477 if (v.major === 0 && v.minor <= 10) {
478 self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
480 self.agentClass = self.httpModule.Agent
481 self.agentOptions = self.agentOptions || {}
482 self.agentOptions.keepAlive = true
485 self.agentClass = self.httpModule.Agent
489 if (self.pool === false) {
492 self.agent = self.agent || self.getNewAgent()
495 self.on('pipe', function (src) {
496 if (self.ntick && self._started) {
497 self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'))
500 if (isReadStream(src)) {
501 if (!self.hasHeader('content-type')) {
502 self.setHeader('content-type', mime.lookup(src.path))
506 for (var i in src.headers) {
507 if (!self.hasHeader(i)) {
508 self.setHeader(i, src.headers[i])
512 if (self._json && !self.hasHeader('content-type')) {
513 self.setHeader('content-type', 'application/json')
515 if (src.method && !self.explicitMethod) {
516 self.method = src.method
520 // self.on('pipe', function () {
521 // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
530 var end = function () {
532 if (!self._auth.hasAuth) {
533 self._form.pipe(self)
535 else if (self._auth.hasAuth && self._auth.sentAuth) {
536 self._form.pipe(self)
539 if (self._multipart && self._multipart.chunked) {
540 self._multipart.body.pipe(self)
543 if (isstream(self.body)) {
547 if (Array.isArray(self.body)) {
548 self.body.forEach(function (part) {
552 self.write(self.body)
556 } else if (self.requestBodyStream) {
557 console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
558 self.requestBodyStream.pipe(self)
559 } else if (!self.src) {
560 if (self._auth.hasAuth && !self._auth.sentAuth) {
564 if (self.method !== 'GET' && typeof self.method !== 'undefined') {
565 self.setHeader('content-length', 0)
571 if (self._form && !self.hasHeader('content-length')) {
572 // Before ending the request, we had to compute the length of the whole form, asyncly
573 self.setHeader(self._form.getHeaders(), true)
574 self._form.getLength(function (err, length) {
575 if (!err && !isNaN(length)) {
576 self.setHeader('content-length', length)
589 Request.prototype.getNewAgent = function () {
591 var Agent = self.agentClass
593 if (self.agentOptions) {
594 for (var i in self.agentOptions) {
595 options[i] = self.agentOptions[i]
602 options.ciphers = self.ciphers
604 if (self.secureProtocol) {
605 options.secureProtocol = self.secureProtocol
607 if (self.secureOptions) {
608 options.secureOptions = self.secureOptions
610 if (typeof self.rejectUnauthorized !== 'undefined') {
611 options.rejectUnauthorized = self.rejectUnauthorized
614 if (self.cert && self.key) {
615 options.key = self.key
616 options.cert = self.cert
620 options.pfx = self.pfx
623 if (self.passphrase) {
624 options.passphrase = self.passphrase
629 // different types of agents are in different pools
630 if (Agent !== self.httpModule.Agent) {
631 poolKey += Agent.name
634 // ca option is only relevant if proxy or destination are https
635 var proxy = self.proxy
636 if (typeof proxy === 'string') {
637 proxy = url.parse(proxy)
639 var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
646 poolKey += options.ca
649 if (typeof options.rejectUnauthorized !== 'undefined') {
653 poolKey += options.rejectUnauthorized
660 poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
667 poolKey += options.pfx.toString('ascii')
670 if (options.ciphers) {
674 poolKey += options.ciphers
677 if (options.secureProtocol) {
681 poolKey += options.secureProtocol
684 if (options.secureOptions) {
688 poolKey += options.secureOptions
692 if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
693 // not doing anything special. Use the globalAgent
694 return self.httpModule.globalAgent
697 // we're using a stored agent. Make sure it's protocol-specific
698 poolKey = self.uri.protocol + poolKey
700 // generate a new agent for this setting if none yet exists
701 if (!self.pool[poolKey]) {
702 self.pool[poolKey] = new Agent(options)
703 // properly set maxSockets on new agents
704 if (self.pool.maxSockets) {
705 self.pool[poolKey].maxSockets = self.pool.maxSockets
709 return self.pool[poolKey]
712 Request.prototype.start = function () {
713 // start() is called once we are ready to send the outgoing HTTP request.
714 // this is usually called on the first write(), end() or on nextTick()
722 self.method = self.method || 'GET'
723 self.href = self.uri.href
725 if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
726 self.setHeader('content-length', self.src.stat.size)
729 self.aws(self._aws, true)
732 // We have a method named auth, which is completely different from the http.request
733 // auth option. If we don't remove it, we're gonna have a bad time.
734 var reqOptions = copy(self)
735 delete reqOptions.auth
737 debug('make request', self.uri.href)
740 self.req = self.httpModule.request(reqOptions)
742 self.emit('error', err)
747 self.startTime = new Date().getTime()
750 if (self.timeout && !self.timeoutTimer) {
751 var timeout = self.timeout < 0 ? 0 : self.timeout
752 // Set a timeout in memory - this block will throw if the server takes more
753 // than `timeout` to write the HTTP status and headers (corresponding to
754 // the on('response') event on the client). NB: this measures wall-clock
755 // time, not the time between bytes sent by the server.
756 self.timeoutTimer = setTimeout(function () {
757 var connectTimeout = self.req.socket && self.req.socket.readable === false
759 var e = new Error('ETIMEDOUT')
761 e.connect = connectTimeout
762 self.emit('error', e)
765 if (self.req.setTimeout) { // only works on node 0.6+
766 // Set an additional timeout on the socket, via the `setsockopt` syscall.
767 // This timeout sets the amount of time to wait *between* bytes sent
768 // from the server, and may or may not correspond to the wall-clock time
769 // elapsed from the start of the request.
771 // In particular, it's useful for erroring if the server fails to send
772 // data halfway through streaming a response.
773 self.req.setTimeout(timeout, function () {
776 var e = new Error('ESOCKETTIMEDOUT')
777 e.code = 'ESOCKETTIMEDOUT'
779 self.emit('error', e)
785 self.req.on('response', self.onRequestResponse.bind(self))
786 self.req.on('error', self.onRequestError.bind(self))
787 self.req.on('drain', function() {
790 self.req.on('socket', function(socket) {
791 self.emit('socket', socket)
794 self.emit('request', self.req)
797 Request.prototype.onRequestError = function (error) {
802 if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
803 && self.agent.addRequestNoreuse) {
804 self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
809 if (self.timeout && self.timeoutTimer) {
810 clearTimeout(self.timeoutTimer)
811 self.timeoutTimer = null
813 self.emit('error', error)
816 Request.prototype.onRequestResponse = function (response) {
818 debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
819 response.on('end', function() {
821 self.elapsedTime += (new Date().getTime() - self.startTime)
822 debug('elapsed time', self.elapsedTime)
823 response.elapsedTime = self.elapsedTime
825 debug('response end', self.uri.href, response.statusCode, response.headers)
829 debug('aborted', self.uri.href)
834 self.response = response
835 response.request = self
836 response.toJSON = responseToJSON
838 // XXX This is different on 0.10, because SSL is strict by default
839 if (self.httpModule === https &&
840 self.strictSSL && (!response.hasOwnProperty('socket') ||
841 !response.socket.authorized)) {
842 debug('strict ssl error', self.uri.href)
843 var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
844 self.emit('error', new Error('SSL Error: ' + sslErr))
848 // Save the original host before any redirect (if it changes, we need to
849 // remove any authorization headers). Also remember the case of the header
850 // name because lots of broken servers expect Host instead of host and we
851 // want the caller to be able to specify this.
852 self.originalHost = self.getHeader('host')
853 if (!self.originalHostHeaderName) {
854 self.originalHostHeaderName = self.hasHeader('host')
857 self.removeHeader('host')
859 if (self.timeout && self.timeoutTimer) {
860 clearTimeout(self.timeoutTimer)
861 self.timeoutTimer = null
864 var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
865 var addCookie = function (cookie) {
866 //set the cookie if it's domain in the href's domain.
868 targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
870 self.emit('error', e)
874 response.caseless = caseless(response.headers)
876 if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
877 var headerName = response.caseless.has('set-cookie')
878 if (Array.isArray(response.headers[headerName])) {
879 response.headers[headerName].forEach(addCookie)
881 addCookie(response.headers[headerName])
885 if (self._redirect.onResponse(response)) {
886 return // Ignore the rest of the response
888 // Be a good stream and emit end when the response is finished.
889 // Hack to emit end on close because of a core bug that never fires end
890 response.on('close', function () {
892 self.response.emit('end')
896 response.on('end', function () {
900 var noBody = function (code) {
902 self.method === 'HEAD'
904 || (code >= 100 && code < 200)
913 if (self.gzip && !noBody(response.statusCode)) {
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)
920 } else if (contentEncoding === 'deflate') {
921 responseContent = zlib.createInflate()
922 response.pipe(responseContent)
924 // Since previous versions didn't check for Content-Encoding header,
925 // ignore any invalid values to preserve backwards-compatibility
926 if (contentEncoding !== 'identity') {
927 debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
929 responseContent = response
932 responseContent = response
936 if (self.dests.length !== 0) {
937 console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
938 } else if (responseContent.setEncoding) {
939 responseContent.setEncoding(self.encoding)
941 // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with
943 // If/When support for 0.9.4 is dropped, this should be unnecessary.
944 responseContent = responseContent.pipe(stringstream(self.encoding))
949 responseContent.pause()
952 self.responseContent = responseContent
954 self.emit('response', response)
956 self.dests.forEach(function (dest) {
960 responseContent.on('data', function (chunk) {
961 self._destdata = true
962 self.emit('data', chunk)
964 responseContent.on('end', function (chunk) {
965 self.emit('end', chunk)
967 responseContent.on('error', function (error) {
968 self.emit('error', error)
970 responseContent.on('close', function () {self.emit('close')})
973 self.readResponseBody(response)
977 self.on('end', function () {
979 debug('aborted', self.uri.href)
982 self.emit('complete', response)
986 debug('finish init function', self.uri.href)
989 Request.prototype.readResponseBody = function (response) {
991 debug('reading response\'s body')
995 self.on('data', function (chunk) {
996 if (Buffer.isBuffer(chunk)) {
1002 self.on('end', function () {
1003 debug('end event', self.uri.href)
1004 if (self._aborted) {
1005 debug('aborted', self.uri.href)
1006 // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request.
1007 // This can lead to leaky behavior if the user retains a reference to the request object.
1012 if (buffer.length) {
1013 debug('has body', self.uri.href, buffer.length)
1014 if (self.encoding === null) {
1015 // response.body = buffer
1016 // can't move to this until https://github.com/rvagg/bl/issues/13
1017 response.body = buffer.slice()
1019 response.body = buffer.toString(self.encoding)
1021 // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
1022 // This can lead to leaky behavior if the user retains a reference to the request object.
1024 } else if (strings.length) {
1025 // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
1026 // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
1027 if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
1028 strings[0] = strings[0].substring(1)
1030 response.body = strings.join('')
1035 response.body = JSON.parse(response.body, self._jsonReviver)
1037 debug('invalid JSON received', self.uri.href)
1040 debug('emitting complete', self.uri.href)
1041 if (typeof response.body === 'undefined' && !self._json) {
1042 response.body = self.encoding === null ? new Buffer(0) : ''
1044 self.emit('complete', response, response.body)
1048 Request.prototype.abort = function () {
1050 self._aborted = true
1055 else if (self.response) {
1056 self.response.destroy()
1062 Request.prototype.pipeDest = function (dest) {
1064 var response = self.response
1065 // Called after the response is received
1066 if (dest.headers && !dest.headersSent) {
1067 if (response.caseless.has('content-type')) {
1068 var ctname = response.caseless.has('content-type')
1069 if (dest.setHeader) {
1070 dest.setHeader(ctname, response.headers[ctname])
1073 dest.headers[ctname] = response.headers[ctname]
1077 if (response.caseless.has('content-length')) {
1078 var clname = response.caseless.has('content-length')
1079 if (dest.setHeader) {
1080 dest.setHeader(clname, response.headers[clname])
1082 dest.headers[clname] = response.headers[clname]
1086 if (dest.setHeader && !dest.headersSent) {
1087 for (var i in response.headers) {
1088 // If the response content is being decoded, the Content-Encoding header
1089 // of the response doesn't represent the piped content, so don't pass it.
1090 if (!self.gzip || i !== 'content-encoding') {
1091 dest.setHeader(i, response.headers[i])
1094 dest.statusCode = response.statusCode
1096 if (self.pipefilter) {
1097 self.pipefilter(response, dest)
1101 Request.prototype.qs = function (q, clobber) {
1104 if (!clobber && self.uri.query) {
1105 base = self._qs.parse(self.uri.query)
1114 var qs = self._qs.stringify(base)
1120 self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
1122 self.path = self.uri.path
1124 if (self.uri.host === 'unix') {
1125 self.enableUnixSocket()
1130 Request.prototype.form = function (form) {
1133 if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
1134 self.setHeader('content-type', 'application/x-www-form-urlencoded')
1136 self.body = (typeof form === 'string')
1137 ? self._qs.rfc3986(form.toString('utf8'))
1138 : self._qs.stringify(form).toString('utf8')
1141 // create form-data object
1142 self._form = new FormData()
1143 self._form.on('error', function(err) {
1144 err.message = 'form-data: ' + err.message
1145 self.emit('error', err)
1150 Request.prototype.multipart = function (multipart) {
1153 self._multipart.onRequest(multipart)
1155 if (!self._multipart.chunked) {
1156 self.body = self._multipart.body
1161 Request.prototype.json = function (val) {
1164 if (!self.hasHeader('accept')) {
1165 self.setHeader('accept', 'application/json')
1168 if (typeof self.jsonReplacer === 'function') {
1169 self._jsonReplacer = self.jsonReplacer
1173 if (typeof val === 'boolean') {
1174 if (self.body !== undefined) {
1175 if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
1176 self.body = safeStringify(self.body, self._jsonReplacer)
1178 self.body = self._qs.rfc3986(self.body)
1180 if (!self.hasHeader('content-type')) {
1181 self.setHeader('content-type', 'application/json')
1185 self.body = safeStringify(val, self._jsonReplacer)
1186 if (!self.hasHeader('content-type')) {
1187 self.setHeader('content-type', 'application/json')
1191 if (typeof self.jsonReviver === 'function') {
1192 self._jsonReviver = self.jsonReviver
1197 Request.prototype.getHeader = function (name, headers) {
1199 var result, re, match
1201 headers = self.headers
1203 Object.keys(headers).forEach(function (key) {
1204 if (key.length !== name.length) {
1207 re = new RegExp(name, 'i')
1208 match = key.match(re)
1210 result = headers[key]
1215 Request.prototype.enableUnixSocket = function () {
1216 // Get the socket & request paths from the URL
1217 var unixParts = this.uri.path.split(':')
1218 , host = unixParts[0]
1219 , path = unixParts[1]
1220 // Apply unix properties to request
1221 this.socketPath = host
1222 this.uri.pathname = path
1223 this.uri.path = path
1224 this.uri.host = host
1225 this.uri.hostname = host
1226 this.uri.isUnix = true
1230 Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
1233 self._auth.onRequest(user, pass, sendImmediately, bearer)
1237 Request.prototype.aws = function (opts, now) {
1245 if (opts.sign_version == 4 || opts.sign_version == '4') {
1248 host: self.uri.host,
1249 path: self.uri.path,
1250 method: self.method,
1252 'content-type': self.getHeader('content-type') || ''
1256 var signRes = aws4.sign(options, {
1257 accessKeyId: opts.key,
1258 secretAccessKey: opts.secret
1260 self.setHeader('authorization', signRes.headers.Authorization)
1261 self.setHeader('x-amz-date', signRes.headers['X-Amz-Date'])
1264 // default: use aws-sign2
1265 var date = new Date()
1266 self.setHeader('date', date.toUTCString())
1269 , secret: opts.secret
1270 , verb: self.method.toUpperCase()
1272 , contentType: self.getHeader('content-type') || ''
1273 , md5: self.getHeader('content-md5') || ''
1274 , amazonHeaders: aws2.canonicalizeHeaders(self.headers)
1276 var path = self.uri.path
1277 if (opts.bucket && path) {
1278 auth.resource = '/' + opts.bucket + path
1279 } else if (opts.bucket && !path) {
1280 auth.resource = '/' + opts.bucket
1281 } else if (!opts.bucket && path) {
1282 auth.resource = path
1283 } else if (!opts.bucket && !path) {
1286 auth.resource = aws2.canonicalizeResource(auth.resource)
1287 self.setHeader('authorization', aws2.authorization(auth))
1292 Request.prototype.httpSignature = function (opts) {
1294 httpSignature.signRequest({
1295 getHeader: function(header) {
1296 return self.getHeader(header, self.headers)
1298 setHeader: function(header, value) {
1299 self.setHeader(header, value)
1301 method: self.method,
1304 debug('httpSignature authorization', self.getHeader('authorization'))
1308 Request.prototype.hawk = function (opts) {
1310 self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field)
1312 Request.prototype.oauth = function (_oauth) {
1315 self._oauth.onRequest(_oauth)
1320 Request.prototype.jar = function (jar) {
1324 if (self._redirect.redirectsFollowed === 0) {
1325 self.originalCookieHeader = self.getHeader('cookie')
1331 self._disableCookies = true
1333 var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
1334 var urihref = self.uri.href
1335 //fetch cookie in the Specified host
1336 if (targetCookieJar) {
1337 cookies = targetCookieJar.getCookieString(urihref)
1341 //if need cookie and cookie is not empty
1342 if (cookies && cookies.length) {
1343 if (self.originalCookieHeader) {
1344 // Don't overwrite existing Cookie header
1345 self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
1347 self.setHeader('cookie', cookies)
1356 Request.prototype.pipe = function (dest, opts) {
1359 if (self.response) {
1360 if (self._destdata) {
1361 self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
1362 } else if (self._ended) {
1363 self.emit('error', new Error('You cannot pipe after the response has been ended.'))
1365 stream.Stream.prototype.pipe.call(self, dest, opts)
1370 self.dests.push(dest)
1371 stream.Stream.prototype.pipe.call(self, dest, opts)
1375 Request.prototype.write = function () {
1377 if (self._aborted) {return}
1379 if (!self._started) {
1383 return self.req.write.apply(self.req, arguments)
1386 Request.prototype.end = function (chunk) {
1388 if (self._aborted) {return}
1393 if (!self._started) {
1400 Request.prototype.pause = function () {
1402 if (!self.responseContent) {
1405 self.responseContent.pause.apply(self.responseContent, arguments)
1408 Request.prototype.resume = function () {
1410 if (!self.responseContent) {
1411 self._paused = false
1413 self.responseContent.resume.apply(self.responseContent, arguments)
1416 Request.prototype.destroy = function () {
1420 } else if (self.response) {
1421 self.response.destroy()
1425 Request.defaultProxyHeaderWhiteList =
1426 Tunnel.defaultProxyHeaderWhiteList.slice()
1428 Request.defaultProxyHeaderExclusiveList =
1429 Tunnel.defaultProxyHeaderExclusiveList.slice()
1433 Request.prototype.toJSON = requestToJSON
1434 module.exports = Request