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