UNPKG

40.1 kBJavaScriptView Raw
1'use strict'
2
3var http = require('http')
4 , https = require('https')
5 , url = require('url')
6 , util = require('util')
7 , stream = require('stream')
8 , zlib = require('zlib')
9 , bl = require('bl')
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 , helpers = require('./lib/helpers')
19 , cookies = require('./lib/cookies')
20 , getProxyFromURI = require('./lib/getProxyFromURI')
21 , Querystring = require('./lib/querystring').Querystring
22 , Har = require('./lib/har').Har
23 , Auth = require('./lib/auth').Auth
24 , OAuth = require('./lib/oauth').OAuth
25 , Multipart = require('./lib/multipart').Multipart
26 , Redirect = require('./lib/redirect').Redirect
27 , Tunnel = require('./lib/tunnel').Tunnel
28
29var safeStringify = helpers.safeStringify
30 , isReadStream = helpers.isReadStream
31 , toBase64 = helpers.toBase64
32 , defer = helpers.defer
33 , copy = helpers.copy
34 , version = helpers.version
35 , globalCookieJar = cookies.jar()
36
37
38var globalPool = {}
39
40function filterForNonReserved(reserved, options) {
41 // Filter out properties that are not reserved.
42 // Reserved values are passed in at call site.
43
44 var object = {}
45 for (var i in options) {
46 var notReserved = (reserved.indexOf(i) === -1)
47 if (notReserved) {
48 object[i] = options[i]
49 }
50 }
51 return object
52}
53
54function filterOutReservedFunctions(reserved, options) {
55 // Filter out properties that are functions and are reserved.
56 // Reserved values are passed in at call site.
57
58 var object = {}
59 for (var i in options) {
60 var isReserved = !(reserved.indexOf(i) === -1)
61 var isFunction = (typeof options[i] === 'function')
62 if (!(isReserved && isFunction)) {
63 object[i] = options[i]
64 }
65 }
66 return object
67
68}
69
70// Function for properly handling a connection error
71function connectionErrorHandler(error) {
72 var socket = this
73 if (socket.res) {
74 if (socket.res.request) {
75 socket.res.request.emit('error', error)
76 } else {
77 socket.res.emit('error', error)
78 }
79 } else {
80 socket._httpMessage.emit('error', error)
81 }
82}
83
84// Return a simpler request object to allow serialization
85function requestToJSON() {
86 var self = this
87 return {
88 uri: self.uri,
89 method: self.method,
90 headers: self.headers
91 }
92}
93
94// Return a simpler response object to allow serialization
95function responseToJSON() {
96 var self = this
97 return {
98 statusCode: self.statusCode,
99 body: self.body,
100 headers: self.headers,
101 request: requestToJSON.call(self.request)
102 }
103}
104
105function Request (options) {
106 // if given the method property in options, set property explicitMethod to true
107
108 // extend the Request instance with any non-reserved properties
109 // remove any reserved functions from the options object
110 // set Request instance to be readable and writable
111 // call init
112
113 var self = this
114
115 // start with HAR, then override with additional options
116 if (options.har) {
117 self._har = new Har(self)
118 options = self._har.options(options)
119 }
120
121 stream.Stream.call(self)
122 var reserved = Object.keys(Request.prototype)
123 var nonReserved = filterForNonReserved(reserved, options)
124
125 stream.Stream.call(self)
126 util._extend(self, nonReserved)
127 options = filterOutReservedFunctions(reserved, options)
128
129 self.readable = true
130 self.writable = true
131 if (options.method) {
132 self.explicitMethod = true
133 }
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)
140 self.init(options)
141}
142
143util.inherits(Request, stream.Stream)
144
145// Debugging
146Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
147function debug() {
148 if (Request.debug) {
149 console.error('REQUEST %s', util.format.apply(util, arguments))
150 }
151}
152Request.prototype.debug = debug
153
154Request.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.
158 var self = this
159 if (!options) {
160 options = {}
161 }
162 self.headers = self.headers ? copy(self.headers) : {}
163
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]
169 }
170 }
171
172 caseless.httpify(self, self.headers)
173
174 if (!self.method) {
175 self.method = options.method || 'GET'
176 }
177 if (!self.localAddress) {
178 self.localAddress = options.localAddress
179 }
180
181 self._qs.init(options)
182
183 debug(options)
184 if (!self.pool && self.pool !== false) {
185 self.pool = globalPool
186 }
187 self.dests = self.dests || []
188 self.__isRequestRequest = true
189
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?
196 }
197 self._callbackCalled = true
198 self._callback.apply(self, arguments)
199 }
200 self.on('error', self.callback.bind())
201 self.on('complete', self.callback.bind(self, null))
202 }
203
204 // People use this property instead all the time, so support it
205 if (!self.uri && self.url) {
206 self.uri = self.url
207 delete self.url
208 }
209
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).
212 if (self.baseUrl) {
213 if (typeof self.baseUrl !== 'string') {
214 return self.emit('error', new Error('options.baseUrl must be a string'))
215 }
216
217 if (typeof self.uri !== 'string') {
218 return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'))
219 }
220
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'))
223 }
224
225 // Handle all cases to make sure that there's only one slash between
226 // baseUrl and uri.
227 var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1
228 var uriStartsWithSlash = self.uri.indexOf('/') === 0
229
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
236 } else {
237 self.uri = self.baseUrl + '/' + self.uri
238 }
239 delete self.baseUrl
240 }
241
242 // A URI is needed by this point, emit error if we haven't been able to get one
243 if (!self.uri) {
244 return self.emit('error', new Error('options.uri is a required argument'))
245 }
246
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)
250 }
251
252 // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme
253 if (self.uri.protocol === 'unix:') {
254 return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'))
255 }
256
257 // Support Unix Sockets
258 if (self.uri.host === 'unix') {
259 self.enableUnixSocket()
260 }
261
262 if (self.strictSSL === false) {
263 self.rejectUnauthorized = false
264 }
265
266 if (!self.uri.pathname) {self.uri.pathname = '/'}
267
268 if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
269 // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
270 // Detect and reject it as soon as possible
271 var faultyUri = url.format(self.uri)
272 var message = 'Invalid URI "' + faultyUri + '"'
273 if (Object.keys(options).length === 0) {
274 // No option ? This can be the sign of a redirect
275 // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
276 // they should be warned that it can be caused by a redirection (can save some hair)
277 message += '. This can be caused by a crappy redirection.'
278 }
279 // This error was fatal
280 return self.emit('error', new Error(message))
281 }
282
283 if (!self.hasOwnProperty('proxy')) {
284 self.proxy = getProxyFromURI(self.uri)
285 }
286
287 self.tunnel = self._tunnel.isEnabled(options)
288 if (self.proxy) {
289 self._tunnel.setup(options)
290 }
291
292 self._redirect.onRequest(options)
293
294 self.setHost = false
295 if (!self.hasHeader('host')) {
296 var hostHeaderName = self.originalHostHeaderName || 'host'
297 self.setHeader(hostHeaderName, self.uri.hostname)
298 if (self.uri.port) {
299 if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') &&
300 !(self.uri.port === 443 && self.uri.protocol === 'https:') ) {
301 self.setHeader(hostHeaderName, self.getHeader('host') + (':' + self.uri.port) )
302 }
303 }
304 self.setHost = true
305 }
306
307 self.jar(self._jar || options.jar)
308
309 if (!self.uri.port) {
310 if (self.uri.protocol === 'http:') {self.uri.port = 80}
311 else if (self.uri.protocol === 'https:') {self.uri.port = 443}
312 }
313
314 if (self.proxy && !self.tunnel) {
315 self.port = self.proxy.port
316 self.host = self.proxy.hostname
317 } else {
318 self.port = self.uri.port
319 self.host = self.uri.hostname
320 }
321
322 if (options.form) {
323 self.form(options.form)
324 }
325
326 if (options.formData) {
327 var formData = options.formData
328 var requestForm = self.form()
329 var appendFormValue = function (key, value) {
330 if (value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
331 requestForm.append(key, value.value, value.options)
332 } else {
333 requestForm.append(key, value)
334 }
335 }
336 for (var formKey in formData) {
337 if (formData.hasOwnProperty(formKey)) {
338 var formValue = formData[formKey]
339 if (formValue instanceof Array) {
340 for (var j = 0; j < formValue.length; j++) {
341 appendFormValue(formKey, formValue[j])
342 }
343 } else {
344 appendFormValue(formKey, formValue)
345 }
346 }
347 }
348 }
349
350 if (options.qs) {
351 self.qs(options.qs)
352 }
353
354 if (self.uri.path) {
355 self.path = self.uri.path
356 } else {
357 self.path = self.uri.pathname + (self.uri.search || '')
358 }
359
360 if (self.path.length === 0) {
361 self.path = '/'
362 }
363
364 // Auth must happen last in case signing is dependent on other headers
365 if (options.aws) {
366 self.aws(options.aws)
367 }
368
369 if (options.hawk) {
370 self.hawk(options.hawk)
371 }
372
373 if (options.httpSignature) {
374 self.httpSignature(options.httpSignature)
375 }
376
377 if (options.auth) {
378 if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
379 options.auth.user = options.auth.username
380 }
381 if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
382 options.auth.pass = options.auth.password
383 }
384
385 self.auth(
386 options.auth.user,
387 options.auth.pass,
388 options.auth.sendImmediately,
389 options.auth.bearer
390 )
391 }
392
393 if (self.gzip && !self.hasHeader('accept-encoding')) {
394 self.setHeader('accept-encoding', 'gzip')
395 }
396
397 if (self.uri.auth && !self.hasHeader('authorization')) {
398 var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
399 self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
400 }
401
402 if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
403 var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
404 var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
405 self.setHeader('proxy-authorization', authHeader)
406 }
407
408 if (self.proxy && !self.tunnel) {
409 self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
410 }
411
412 if (options.json) {
413 self.json(options.json)
414 }
415 if (options.multipart) {
416 self.multipart(options.multipart)
417 }
418
419 if (options.time) {
420 self.timing = true
421 self.elapsedTime = self.elapsedTime || 0
422 }
423
424 function setContentLength () {
425 if (!self.hasHeader('content-length')) {
426 var length
427 if (typeof self.body === 'string') {
428 length = Buffer.byteLength(self.body)
429 }
430 else if (Array.isArray(self.body)) {
431 length = self.body.reduce(function (a, b) {return a + b.length}, 0)
432 }
433 else {
434 length = self.body.length
435 }
436
437 if (length) {
438 self.setHeader('content-length', length)
439 } else {
440 self.emit('error', new Error('Argument error, options.body.'))
441 }
442 }
443 }
444 if (self.body) {
445 setContentLength()
446 }
447
448 if (options.oauth) {
449 self.oauth(options.oauth)
450 } else if (self._oauth.params && self.hasHeader('authorization')) {
451 self.oauth(self._oauth.params)
452 }
453
454 var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
455 , defaultModules = {'http:':http, 'https:':https}
456 , httpModules = self.httpModules || {}
457
458 self.httpModule = httpModules[protocol] || defaultModules[protocol]
459
460 if (!self.httpModule) {
461 return self.emit('error', new Error('Invalid protocol: ' + protocol))
462 }
463
464 if (options.ca) {
465 self.ca = options.ca
466 }
467
468 if (!self.agent) {
469 if (options.agentOptions) {
470 self.agentOptions = options.agentOptions
471 }
472
473 if (options.agentClass) {
474 self.agentClass = options.agentClass
475 } else if (options.forever) {
476 var v = version()
477 // use ForeverAgent in node 0.10- only
478 if (v.major === 0 && v.minor <= 10) {
479 self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
480 } else {
481 self.agentClass = self.httpModule.Agent
482 self.agentOptions = self.agentOptions || {}
483 self.agentOptions.keepAlive = true
484 }
485 } else {
486 self.agentClass = self.httpModule.Agent
487 }
488 }
489
490 if (self.pool === false) {
491 self.agent = false
492 } else {
493 self.agent = self.agent || self.getNewAgent()
494 }
495
496 self.on('pipe', function (src) {
497 if (self.ntick && self._started) {
498 self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'))
499 }
500 self.src = src
501 if (isReadStream(src)) {
502 if (!self.hasHeader('content-type')) {
503 self.setHeader('content-type', mime.lookup(src.path))
504 }
505 } else {
506 if (src.headers) {
507 for (var i in src.headers) {
508 if (!self.hasHeader(i)) {
509 self.setHeader(i, src.headers[i])
510 }
511 }
512 }
513 if (self._json && !self.hasHeader('content-type')) {
514 self.setHeader('content-type', 'application/json')
515 }
516 if (src.method && !self.explicitMethod) {
517 self.method = src.method
518 }
519 }
520
521 // self.on('pipe', function () {
522 // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
523 // })
524 })
525
526 defer(function () {
527 if (self._aborted) {
528 return
529 }
530
531 var end = function () {
532 if (self._form) {
533 if (!self._auth.hasAuth) {
534 self._form.pipe(self)
535 }
536 else if (self._auth.hasAuth && self._auth.sentAuth) {
537 self._form.pipe(self)
538 }
539 }
540 if (self._multipart && self._multipart.chunked) {
541 self._multipart.body.pipe(self)
542 }
543 if (self.body) {
544 setContentLength()
545 if (Array.isArray(self.body)) {
546 self.body.forEach(function (part) {
547 self.write(part)
548 })
549 } else {
550 self.write(self.body)
551 }
552 self.end()
553 } else if (self.requestBodyStream) {
554 console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
555 self.requestBodyStream.pipe(self)
556 } else if (!self.src) {
557 if (self._auth.hasAuth && !self._auth.sentAuth) {
558 self.end()
559 return
560 }
561 if (self.method !== 'GET' && typeof self.method !== 'undefined') {
562 self.setHeader('content-length', 0)
563 }
564 self.end()
565 }
566 }
567
568 if (self._form && !self.hasHeader('content-length')) {
569 // Before ending the request, we had to compute the length of the whole form, asyncly
570 self.setHeader(self._form.getHeaders(), true)
571 self._form.getLength(function (err, length) {
572 if (!err) {
573 self.setHeader('content-length', length)
574 }
575 end()
576 })
577 } else {
578 end()
579 }
580
581 self.ntick = true
582 })
583
584}
585
586// Must call this when following a redirect from https to http or vice versa
587// Attempts to keep everything as identical as possible, but update the
588// httpModule, Tunneling agent, and/or Forever Agent in use.
589Request.prototype._updateProtocol = function () {
590 var self = this
591 var protocol = self.uri.protocol
592
593 if (protocol === 'https:' || self.tunnel) {
594 // previously was doing http, now doing https
595 // if it's https, then we might need to tunnel now.
596 if (self.proxy) {
597 if (self._tunnel.setup()) {
598 return
599 }
600 }
601
602 self.httpModule = https
603 switch (self.agentClass) {
604 case ForeverAgent:
605 self.agentClass = ForeverAgent.SSL
606 break
607 case http.Agent:
608 self.agentClass = https.Agent
609 break
610 default:
611 // nothing we can do. Just hope for the best.
612 return
613 }
614
615 // if there's an agent, we need to get a new one.
616 if (self.agent) {
617 self.agent = self.getNewAgent()
618 }
619
620 } else {
621 // previously was doing https, now doing http
622 self.httpModule = http
623 switch (self.agentClass) {
624 case ForeverAgent.SSL:
625 self.agentClass = ForeverAgent
626 break
627 case https.Agent:
628 self.agentClass = http.Agent
629 break
630 default:
631 // nothing we can do. just hope for the best
632 return
633 }
634
635 // if there's an agent, then get a new one.
636 if (self.agent) {
637 self.agent = null
638 self.agent = self.getNewAgent()
639 }
640 }
641}
642
643Request.prototype.getNewAgent = function () {
644 var self = this
645 var Agent = self.agentClass
646 var options = {}
647 if (self.agentOptions) {
648 for (var i in self.agentOptions) {
649 options[i] = self.agentOptions[i]
650 }
651 }
652 if (self.ca) {
653 options.ca = self.ca
654 }
655 if (self.ciphers) {
656 options.ciphers = self.ciphers
657 }
658 if (self.secureProtocol) {
659 options.secureProtocol = self.secureProtocol
660 }
661 if (self.secureOptions) {
662 options.secureOptions = self.secureOptions
663 }
664 if (typeof self.rejectUnauthorized !== 'undefined') {
665 options.rejectUnauthorized = self.rejectUnauthorized
666 }
667
668 if (self.cert && self.key) {
669 options.key = self.key
670 options.cert = self.cert
671 }
672
673 if (self.pfx) {
674 options.pfx = self.pfx
675 }
676
677 if (self.passphrase) {
678 options.passphrase = self.passphrase
679 }
680
681 var poolKey = ''
682
683 // different types of agents are in different pools
684 if (Agent !== self.httpModule.Agent) {
685 poolKey += Agent.name
686 }
687
688 // ca option is only relevant if proxy or destination are https
689 var proxy = self.proxy
690 if (typeof proxy === 'string') {
691 proxy = url.parse(proxy)
692 }
693 var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
694
695 if (isHttps) {
696 if (options.ca) {
697 if (poolKey) {
698 poolKey += ':'
699 }
700 poolKey += options.ca
701 }
702
703 if (typeof options.rejectUnauthorized !== 'undefined') {
704 if (poolKey) {
705 poolKey += ':'
706 }
707 poolKey += options.rejectUnauthorized
708 }
709
710 if (options.cert) {
711 if (poolKey) {
712 poolKey += ':'
713 }
714 poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
715 }
716
717 if (options.pfx) {
718 if (poolKey) {
719 poolKey += ':'
720 }
721 poolKey += options.pfx.toString('ascii')
722 }
723
724 if (options.ciphers) {
725 if (poolKey) {
726 poolKey += ':'
727 }
728 poolKey += options.ciphers
729 }
730
731 if (options.secureProtocol) {
732 if (poolKey) {
733 poolKey += ':'
734 }
735 poolKey += options.secureProtocol
736 }
737
738 if (options.secureOptions) {
739 if (poolKey) {
740 poolKey += ':'
741 }
742 poolKey += options.secureOptions
743 }
744 }
745
746 if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
747 // not doing anything special. Use the globalAgent
748 return self.httpModule.globalAgent
749 }
750
751 // we're using a stored agent. Make sure it's protocol-specific
752 poolKey = self.uri.protocol + poolKey
753
754 // generate a new agent for this setting if none yet exists
755 if (!self.pool[poolKey]) {
756 self.pool[poolKey] = new Agent(options)
757 // properly set maxSockets on new agents
758 if (self.pool.maxSockets) {
759 self.pool[poolKey].maxSockets = self.pool.maxSockets
760 }
761 }
762
763 return self.pool[poolKey]
764}
765
766Request.prototype.start = function () {
767 // start() is called once we are ready to send the outgoing HTTP request.
768 // this is usually called on the first write(), end() or on nextTick()
769 var self = this
770
771 if (self._aborted) {
772 return
773 }
774
775 self._started = true
776 self.method = self.method || 'GET'
777 self.href = self.uri.href
778
779 if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
780 self.setHeader('content-length', self.src.stat.size)
781 }
782 if (self._aws) {
783 self.aws(self._aws, true)
784 }
785
786 // We have a method named auth, which is completely different from the http.request
787 // auth option. If we don't remove it, we're gonna have a bad time.
788 var reqOptions = copy(self)
789 delete reqOptions.auth
790
791 debug('make request', self.uri.href)
792
793 self.req = self.httpModule.request(reqOptions)
794
795 if (self.timing) {
796 self.startTime = new Date().getTime()
797 }
798
799 if (self.timeout && !self.timeoutTimer) {
800 var timeout = self.timeout < 0 ? 0 : self.timeout
801 // Set a timeout in memory - this block will throw if the server takes more
802 // than `timeout` to write the HTTP status and headers (corresponding to
803 // the on('response') event on the client). NB: this measures wall-clock
804 // time, not the time between bytes sent by the server.
805 self.timeoutTimer = setTimeout(function () {
806 var connectTimeout = self.req.socket && self.req.socket.readable === false
807 self.abort()
808 var e = new Error('ETIMEDOUT')
809 e.code = 'ETIMEDOUT'
810 e.connect = connectTimeout
811 self.emit('error', e)
812 }, timeout)
813
814 if (self.req.setTimeout) { // only works on node 0.6+
815 // Set an additional timeout on the socket, via the `setsockopt` syscall.
816 // This timeout sets the amount of time to wait *between* bytes sent
817 // from the server, and may or may not correspond to the wall-clock time
818 // elapsed from the start of the request.
819 //
820 // In particular, it's useful for erroring if the server fails to send
821 // data halfway through streaming a response.
822 self.req.setTimeout(timeout, function () {
823 if (self.req) {
824 self.req.abort()
825 var e = new Error('ESOCKETTIMEDOUT')
826 e.code = 'ESOCKETTIMEDOUT'
827 e.connect = false
828 self.emit('error', e)
829 }
830 })
831 }
832 }
833
834 self.req.on('response', self.onRequestResponse.bind(self))
835 self.req.on('error', self.onRequestError.bind(self))
836 self.req.on('drain', function() {
837 self.emit('drain')
838 })
839 self.req.on('socket', function(socket) {
840 self.emit('socket', socket)
841 })
842
843 self.on('end', function() {
844 if ( self.req.connection ) {
845 self.req.connection.removeListener('error', connectionErrorHandler)
846 }
847 })
848 self.emit('request', self.req)
849}
850
851Request.prototype.onRequestError = function (error) {
852 var self = this
853 if (self._aborted) {
854 return
855 }
856 if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
857 && self.agent.addRequestNoreuse) {
858 self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
859 self.start()
860 self.req.end()
861 return
862 }
863 if (self.timeout && self.timeoutTimer) {
864 clearTimeout(self.timeoutTimer)
865 self.timeoutTimer = null
866 }
867 self.emit('error', error)
868}
869
870Request.prototype.onRequestResponse = function (response) {
871 var self = this
872 debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
873 response.on('end', function() {
874 if (self.timing) {
875 self.elapsedTime += (new Date().getTime() - self.startTime)
876 debug('elapsed time', self.elapsedTime)
877 response.elapsedTime = self.elapsedTime
878 }
879 debug('response end', self.uri.href, response.statusCode, response.headers)
880 })
881
882 // The check on response.connection is a workaround for browserify.
883 if (response.connection && response.connection.listeners('error').indexOf(connectionErrorHandler) === -1) {
884 response.connection.setMaxListeners(0)
885 response.connection.once('error', connectionErrorHandler)
886 }
887 if (self._aborted) {
888 debug('aborted', self.uri.href)
889 response.resume()
890 return
891 }
892
893 self.response = response
894 response.request = self
895 response.toJSON = responseToJSON
896
897 // XXX This is different on 0.10, because SSL is strict by default
898 if (self.httpModule === https &&
899 self.strictSSL && (!response.hasOwnProperty('socket') ||
900 !response.socket.authorized)) {
901 debug('strict ssl error', self.uri.href)
902 var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
903 self.emit('error', new Error('SSL Error: ' + sslErr))
904 return
905 }
906
907 // Save the original host before any redirect (if it changes, we need to
908 // remove any authorization headers). Also remember the case of the header
909 // name because lots of broken servers expect Host instead of host and we
910 // want the caller to be able to specify this.
911 self.originalHost = self.getHeader('host')
912 if (!self.originalHostHeaderName) {
913 self.originalHostHeaderName = self.hasHeader('host')
914 }
915 if (self.setHost) {
916 self.removeHeader('host')
917 }
918 if (self.timeout && self.timeoutTimer) {
919 clearTimeout(self.timeoutTimer)
920 self.timeoutTimer = null
921 }
922
923 var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
924 var addCookie = function (cookie) {
925 //set the cookie if it's domain in the href's domain.
926 try {
927 targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
928 } catch (e) {
929 self.emit('error', e)
930 }
931 }
932
933 response.caseless = caseless(response.headers)
934
935 if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
936 var headerName = response.caseless.has('set-cookie')
937 if (Array.isArray(response.headers[headerName])) {
938 response.headers[headerName].forEach(addCookie)
939 } else {
940 addCookie(response.headers[headerName])
941 }
942 }
943
944 if (self._redirect.onResponse(response)) {
945 return // Ignore the rest of the response
946 } else {
947 // Be a good stream and emit end when the response is finished.
948 // Hack to emit end on close because of a core bug that never fires end
949 response.on('close', function () {
950 if (!self._ended) {
951 self.response.emit('end')
952 }
953 })
954
955 response.on('end', function () {
956 self._ended = true
957 })
958
959 var responseContent
960 if (self.gzip) {
961 var contentEncoding = response.headers['content-encoding'] || 'identity'
962 contentEncoding = contentEncoding.trim().toLowerCase()
963
964 if (contentEncoding === 'gzip') {
965 responseContent = zlib.createGunzip()
966 response.pipe(responseContent)
967 } else {
968 // Since previous versions didn't check for Content-Encoding header,
969 // ignore any invalid values to preserve backwards-compatibility
970 if (contentEncoding !== 'identity') {
971 debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
972 }
973 responseContent = response
974 }
975 } else {
976 responseContent = response
977 }
978
979 if (self.encoding) {
980 if (self.dests.length !== 0) {
981 console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
982 } else if (responseContent.setEncoding) {
983 responseContent.setEncoding(self.encoding)
984 } else {
985 // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with
986 // zlib streams.
987 // If/When support for 0.9.4 is dropped, this should be unnecessary.
988 responseContent = responseContent.pipe(stringstream(self.encoding))
989 }
990 }
991
992 if (self._paused) {
993 responseContent.pause()
994 }
995
996 self.responseContent = responseContent
997
998 self.emit('response', response)
999
1000 self.dests.forEach(function (dest) {
1001 self.pipeDest(dest)
1002 })
1003
1004 responseContent.on('data', function (chunk) {
1005 self._destdata = true
1006 self.emit('data', chunk)
1007 })
1008 responseContent.on('end', function (chunk) {
1009 self.emit('end', chunk)
1010 })
1011 responseContent.on('error', function (error) {
1012 self.emit('error', error)
1013 })
1014 responseContent.on('close', function () {self.emit('close')})
1015
1016 if (self.callback) {
1017 var buffer = bl()
1018 , strings = []
1019
1020 self.on('data', function (chunk) {
1021 if (Buffer.isBuffer(chunk)) {
1022 buffer.append(chunk)
1023 } else {
1024 strings.push(chunk)
1025 }
1026 })
1027 self.on('end', function () {
1028 debug('end event', self.uri.href)
1029 if (self._aborted) {
1030 debug('aborted', self.uri.href)
1031 return
1032 }
1033
1034 if (buffer.length) {
1035 debug('has body', self.uri.href, buffer.length)
1036 if (self.encoding === null) {
1037 // response.body = buffer
1038 // can't move to this until https://github.com/rvagg/bl/issues/13
1039 response.body = buffer.slice()
1040 } else {
1041 response.body = buffer.toString(self.encoding)
1042 }
1043 } else if (strings.length) {
1044 // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
1045 // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
1046 if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
1047 strings[0] = strings[0].substring(1)
1048 }
1049 response.body = strings.join('')
1050 }
1051
1052 if (self._json) {
1053 try {
1054 response.body = JSON.parse(response.body, self._jsonReviver)
1055 } catch (e) {
1056 debug('invalid JSON received', self.uri.href)
1057 }
1058 }
1059 debug('emitting complete', self.uri.href)
1060 if (typeof response.body === 'undefined' && !self._json) {
1061 response.body = self.encoding === null ? new Buffer(0) : ''
1062 }
1063 self.emit('complete', response, response.body)
1064 })
1065 }
1066 //if no callback
1067 else {
1068 self.on('end', function () {
1069 if (self._aborted) {
1070 debug('aborted', self.uri.href)
1071 return
1072 }
1073 self.emit('complete', response)
1074 })
1075 }
1076 }
1077 debug('finish init function', self.uri.href)
1078}
1079
1080Request.prototype.abort = function () {
1081 var self = this
1082 self._aborted = true
1083
1084 if (self.req) {
1085 self.req.abort()
1086 }
1087 else if (self.response) {
1088 self.response.abort()
1089 }
1090
1091 self.emit('abort')
1092}
1093
1094Request.prototype.pipeDest = function (dest) {
1095 var self = this
1096 var response = self.response
1097 // Called after the response is received
1098 if (dest.headers && !dest.headersSent) {
1099 if (response.caseless.has('content-type')) {
1100 var ctname = response.caseless.has('content-type')
1101 if (dest.setHeader) {
1102 dest.setHeader(ctname, response.headers[ctname])
1103 }
1104 else {
1105 dest.headers[ctname] = response.headers[ctname]
1106 }
1107 }
1108
1109 if (response.caseless.has('content-length')) {
1110 var clname = response.caseless.has('content-length')
1111 if (dest.setHeader) {
1112 dest.setHeader(clname, response.headers[clname])
1113 } else {
1114 dest.headers[clname] = response.headers[clname]
1115 }
1116 }
1117 }
1118 if (dest.setHeader && !dest.headersSent) {
1119 for (var i in response.headers) {
1120 // If the response content is being decoded, the Content-Encoding header
1121 // of the response doesn't represent the piped content, so don't pass it.
1122 if (!self.gzip || i !== 'content-encoding') {
1123 dest.setHeader(i, response.headers[i])
1124 }
1125 }
1126 dest.statusCode = response.statusCode
1127 }
1128 if (self.pipefilter) {
1129 self.pipefilter(response, dest)
1130 }
1131}
1132
1133Request.prototype.qs = function (q, clobber) {
1134 var self = this
1135 var base
1136 if (!clobber && self.uri.query) {
1137 base = self._qs.parse(self.uri.query)
1138 } else {
1139 base = {}
1140 }
1141
1142 for (var i in q) {
1143 base[i] = q[i]
1144 }
1145
1146 if (self._qs.stringify(base) === '') {
1147 return self
1148 }
1149
1150 var qs = self._qs.stringify(base)
1151
1152 self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
1153 self.url = self.uri
1154 self.path = self.uri.path
1155
1156 if (self.uri.host === 'unix') {
1157 self.enableUnixSocket()
1158 }
1159
1160 return self
1161}
1162Request.prototype.form = function (form) {
1163 var self = this
1164 if (form) {
1165 if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
1166 self.setHeader('content-type', 'application/x-www-form-urlencoded')
1167 }
1168 self.body = (typeof form === 'string')
1169 ? self._qs.rfc3986(form.toString('utf8'))
1170 : self._qs.stringify(form).toString('utf8')
1171 return self
1172 }
1173 // create form-data object
1174 self._form = new FormData()
1175 self._form.on('error', function(err) {
1176 err.message = 'form-data: ' + err.message
1177 self.emit('error', err)
1178 self.abort()
1179 })
1180 return self._form
1181}
1182Request.prototype.multipart = function (multipart) {
1183 var self = this
1184
1185 self._multipart.onRequest(multipart)
1186
1187 if (!self._multipart.chunked) {
1188 self.body = self._multipart.body
1189 }
1190
1191 return self
1192}
1193Request.prototype.json = function (val) {
1194 var self = this
1195
1196 if (!self.hasHeader('accept')) {
1197 self.setHeader('accept', 'application/json')
1198 }
1199
1200 self._json = true
1201 if (typeof val === 'boolean') {
1202 if (self.body !== undefined) {
1203 if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
1204 self.body = safeStringify(self.body)
1205 } else {
1206 self.body = self._qs.rfc3986(self.body)
1207 }
1208 if (!self.hasHeader('content-type')) {
1209 self.setHeader('content-type', 'application/json')
1210 }
1211 }
1212 } else {
1213 self.body = safeStringify(val)
1214 if (!self.hasHeader('content-type')) {
1215 self.setHeader('content-type', 'application/json')
1216 }
1217 }
1218
1219 if (typeof self.jsonReviver === 'function') {
1220 self._jsonReviver = self.jsonReviver
1221 }
1222
1223 return self
1224}
1225Request.prototype.getHeader = function (name, headers) {
1226 var self = this
1227 var result, re, match
1228 if (!headers) {
1229 headers = self.headers
1230 }
1231 Object.keys(headers).forEach(function (key) {
1232 if (key.length !== name.length) {
1233 return
1234 }
1235 re = new RegExp(name, 'i')
1236 match = key.match(re)
1237 if (match) {
1238 result = headers[key]
1239 }
1240 })
1241 return result
1242}
1243Request.prototype.enableUnixSocket = function () {
1244 // Get the socket & request paths from the URL
1245 var unixParts = this.uri.path.split(':')
1246 , host = unixParts[0]
1247 , path = unixParts[1]
1248 // Apply unix properties to request
1249 this.socketPath = host
1250 this.uri.pathname = path
1251 this.uri.path = path
1252 this.uri.host = host
1253 this.uri.hostname = host
1254 this.uri.isUnix = true
1255}
1256
1257
1258Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
1259 var self = this
1260
1261 self._auth.onRequest(user, pass, sendImmediately, bearer)
1262
1263 return self
1264}
1265Request.prototype.aws = function (opts, now) {
1266 var self = this
1267
1268 if (!now) {
1269 self._aws = opts
1270 return self
1271 }
1272 var date = new Date()
1273 self.setHeader('date', date.toUTCString())
1274 var auth =
1275 { key: opts.key
1276 , secret: opts.secret
1277 , verb: self.method.toUpperCase()
1278 , date: date
1279 , contentType: self.getHeader('content-type') || ''
1280 , md5: self.getHeader('content-md5') || ''
1281 , amazonHeaders: aws.canonicalizeHeaders(self.headers)
1282 }
1283 var path = self.uri.path
1284 if (opts.bucket && path) {
1285 auth.resource = '/' + opts.bucket + path
1286 } else if (opts.bucket && !path) {
1287 auth.resource = '/' + opts.bucket
1288 } else if (!opts.bucket && path) {
1289 auth.resource = path
1290 } else if (!opts.bucket && !path) {
1291 auth.resource = '/'
1292 }
1293 auth.resource = aws.canonicalizeResource(auth.resource)
1294 self.setHeader('authorization', aws.authorization(auth))
1295
1296 return self
1297}
1298Request.prototype.httpSignature = function (opts) {
1299 var self = this
1300 httpSignature.signRequest({
1301 getHeader: function(header) {
1302 return self.getHeader(header, self.headers)
1303 },
1304 setHeader: function(header, value) {
1305 self.setHeader(header, value)
1306 },
1307 method: self.method,
1308 path: self.path
1309 }, opts)
1310 debug('httpSignature authorization', self.getHeader('authorization'))
1311
1312 return self
1313}
1314Request.prototype.hawk = function (opts) {
1315 var self = this
1316 self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field)
1317}
1318Request.prototype.oauth = function (_oauth) {
1319 var self = this
1320
1321 self._oauth.onRequest(_oauth)
1322
1323 return self
1324}
1325
1326Request.prototype.jar = function (jar) {
1327 var self = this
1328 var cookies
1329
1330 if (self._redirect.redirectsFollowed === 0) {
1331 self.originalCookieHeader = self.getHeader('cookie')
1332 }
1333
1334 if (!jar) {
1335 // disable cookies
1336 cookies = false
1337 self._disableCookies = true
1338 } else {
1339 var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
1340 var urihref = self.uri.href
1341 //fetch cookie in the Specified host
1342 if (targetCookieJar) {
1343 cookies = targetCookieJar.getCookieString(urihref)
1344 }
1345 }
1346
1347 //if need cookie and cookie is not empty
1348 if (cookies && cookies.length) {
1349 if (self.originalCookieHeader) {
1350 // Don't overwrite existing Cookie header
1351 self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
1352 } else {
1353 self.setHeader('cookie', cookies)
1354 }
1355 }
1356 self._jar = jar
1357 return self
1358}
1359
1360
1361// Stream API
1362Request.prototype.pipe = function (dest, opts) {
1363 var self = this
1364
1365 if (self.response) {
1366 if (self._destdata) {
1367 self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
1368 } else if (self._ended) {
1369 self.emit('error', new Error('You cannot pipe after the response has been ended.'))
1370 } else {
1371 stream.Stream.prototype.pipe.call(self, dest, opts)
1372 self.pipeDest(dest)
1373 return dest
1374 }
1375 } else {
1376 self.dests.push(dest)
1377 stream.Stream.prototype.pipe.call(self, dest, opts)
1378 return dest
1379 }
1380}
1381Request.prototype.write = function () {
1382 var self = this
1383 if (!self._started) {
1384 self.start()
1385 }
1386 return self.req.write.apply(self.req, arguments)
1387}
1388Request.prototype.end = function (chunk) {
1389 var self = this
1390 if (chunk) {
1391 self.write(chunk)
1392 }
1393 if (!self._started) {
1394 self.start()
1395 }
1396 self.req.end()
1397}
1398Request.prototype.pause = function () {
1399 var self = this
1400 if (!self.responseContent) {
1401 self._paused = true
1402 } else {
1403 self.responseContent.pause.apply(self.responseContent, arguments)
1404 }
1405}
1406Request.prototype.resume = function () {
1407 var self = this
1408 if (!self.responseContent) {
1409 self._paused = false
1410 } else {
1411 self.responseContent.resume.apply(self.responseContent, arguments)
1412 }
1413}
1414Request.prototype.destroy = function () {
1415 var self = this
1416 if (!self._ended) {
1417 self.end()
1418 } else if (self.response) {
1419 self.response.destroy()
1420 }
1421}
1422
1423Request.defaultProxyHeaderWhiteList =
1424 Tunnel.defaultProxyHeaderWhiteList.slice()
1425
1426Request.defaultProxyHeaderExclusiveList =
1427 Tunnel.defaultProxyHeaderExclusiveList.slice()
1428
1429// Exports
1430
1431Request.prototype.toJSON = requestToJSON
1432module.exports = Request