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