UNPKG

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