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 | , hawk = require('hawk')
|
10 | , aws2 = require('aws-sign2')
|
11 | , aws4 = require('aws4')
|
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 | , extend = require('extend')
|
19 | , isstream = require('isstream')
|
20 | , isTypedArray = require('is-typedarray').strict
|
21 | , helpers = require('./lib/helpers')
|
22 | , cookies = require('./lib/cookies')
|
23 | , getProxyFromURI = require('./lib/getProxyFromURI')
|
24 | , Querystring = require('./lib/querystring').Querystring
|
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 | , Tunnel = require('./lib/tunnel').Tunnel
|
31 | , now = require('performance-now')
|
32 | , Buffer = require('safe-buffer').Buffer
|
33 |
|
34 | var safeStringify = helpers.safeStringify
|
35 | , isReadStream = helpers.isReadStream
|
36 | , toBase64 = helpers.toBase64
|
37 | , defer = helpers.defer
|
38 | , copy = helpers.copy
|
39 | , version = helpers.version
|
40 | , globalCookieJar = cookies.jar()
|
41 |
|
42 |
|
43 | var globalPool = {}
|
44 |
|
45 | function filterForNonReserved(reserved, options) {
|
46 |
|
47 |
|
48 |
|
49 | var object = {}
|
50 | for (var i in options) {
|
51 | var notReserved = (reserved.indexOf(i) === -1)
|
52 | if (notReserved) {
|
53 | object[i] = options[i]
|
54 | }
|
55 | }
|
56 | return object
|
57 | }
|
58 |
|
59 | function filterOutReservedFunctions(reserved, options) {
|
60 |
|
61 |
|
62 |
|
63 | var object = {}
|
64 | for (var i in options) {
|
65 | var isReserved = !(reserved.indexOf(i) === -1)
|
66 | var isFunction = (typeof options[i] === 'function')
|
67 | if (!(isReserved && isFunction)) {
|
68 | object[i] = options[i]
|
69 | }
|
70 | }
|
71 | return object
|
72 |
|
73 | }
|
74 |
|
75 |
|
76 | function requestToJSON() {
|
77 | var self = this
|
78 | return {
|
79 | uri: self.uri,
|
80 | method: self.method,
|
81 | headers: self.headers
|
82 | }
|
83 | }
|
84 |
|
85 |
|
86 | function responseToJSON() {
|
87 | var self = this
|
88 | return {
|
89 | statusCode: self.statusCode,
|
90 | body: self.body,
|
91 | headers: self.headers,
|
92 | request: requestToJSON.call(self.request)
|
93 | }
|
94 | }
|
95 |
|
96 | function Request (options) {
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 | var self = this
|
105 |
|
106 |
|
107 | if (options.har) {
|
108 | self._har = new Har(self)
|
109 | options = self._har.options(options)
|
110 | }
|
111 |
|
112 | stream.Stream.call(self)
|
113 | var reserved = Object.keys(Request.prototype)
|
114 | var nonReserved = filterForNonReserved(reserved, options)
|
115 |
|
116 | extend(self, nonReserved)
|
117 | options = filterOutReservedFunctions(reserved, options)
|
118 |
|
119 | self.readable = true
|
120 | self.writable = true
|
121 | if (options.method) {
|
122 | self.explicitMethod = true
|
123 | }
|
124 | self._qs = new Querystring(self)
|
125 | self._auth = new Auth(self)
|
126 | self._oauth = new OAuth(self)
|
127 | self._multipart = new Multipart(self)
|
128 | self._redirect = new Redirect(self)
|
129 | self._tunnel = new Tunnel(self)
|
130 | self.init(options)
|
131 | }
|
132 |
|
133 | util.inherits(Request, stream.Stream)
|
134 |
|
135 |
|
136 | Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
|
137 | function debug() {
|
138 | if (Request.debug) {
|
139 | console.error('REQUEST %s', util.format.apply(util, arguments))
|
140 | }
|
141 | }
|
142 | Request.prototype.debug = debug
|
143 |
|
144 | Request.prototype.init = function (options) {
|
145 |
|
146 |
|
147 |
|
148 | var self = this
|
149 | if (!options) {
|
150 | options = {}
|
151 | }
|
152 | self.headers = self.headers ? copy(self.headers) : {}
|
153 |
|
154 |
|
155 |
|
156 | for (var headerName in self.headers) {
|
157 | if (typeof self.headers[headerName] === 'undefined') {
|
158 | delete self.headers[headerName]
|
159 | }
|
160 | }
|
161 |
|
162 | caseless.httpify(self, self.headers)
|
163 |
|
164 | if (!self.method) {
|
165 | self.method = options.method || 'GET'
|
166 | }
|
167 | if (!self.localAddress) {
|
168 | self.localAddress = options.localAddress
|
169 | }
|
170 |
|
171 | self._qs.init(options)
|
172 |
|
173 | debug(options)
|
174 | if (!self.pool && self.pool !== false) {
|
175 | self.pool = globalPool
|
176 | }
|
177 | self.dests = self.dests || []
|
178 | self.__isRequestRequest = true
|
179 |
|
180 |
|
181 | if (!self._callback && self.callback) {
|
182 | self._callback = self.callback
|
183 | self.callback = function () {
|
184 | if (self._callbackCalled) {
|
185 | return
|
186 | }
|
187 | self._callbackCalled = true
|
188 | self._callback.apply(self, arguments)
|
189 | }
|
190 | self.on('error', self.callback.bind())
|
191 | self.on('complete', self.callback.bind(self, null))
|
192 | }
|
193 |
|
194 |
|
195 | if (!self.uri && self.url) {
|
196 | self.uri = self.url
|
197 | delete self.url
|
198 | }
|
199 |
|
200 |
|
201 |
|
202 | if (self.baseUrl) {
|
203 | if (typeof self.baseUrl !== 'string') {
|
204 | return self.emit('error', new Error('options.baseUrl must be a string'))
|
205 | }
|
206 |
|
207 | if (typeof self.uri !== 'string') {
|
208 | return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'))
|
209 | }
|
210 |
|
211 | if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) {
|
212 | return self.emit('error', new Error('options.uri must be a path when using options.baseUrl'))
|
213 | }
|
214 |
|
215 |
|
216 |
|
217 | var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1
|
218 | var uriStartsWithSlash = self.uri.indexOf('/') === 0
|
219 |
|
220 | if (baseUrlEndsWithSlash && uriStartsWithSlash) {
|
221 | self.uri = self.baseUrl + self.uri.slice(1)
|
222 | } else if (baseUrlEndsWithSlash || uriStartsWithSlash) {
|
223 | self.uri = self.baseUrl + self.uri
|
224 | } else if (self.uri === '') {
|
225 | self.uri = self.baseUrl
|
226 | } else {
|
227 | self.uri = self.baseUrl + '/' + self.uri
|
228 | }
|
229 | delete self.baseUrl
|
230 | }
|
231 |
|
232 |
|
233 | if (!self.uri) {
|
234 | return self.emit('error', new Error('options.uri is a required argument'))
|
235 | }
|
236 |
|
237 |
|
238 | if (typeof self.uri === 'string') {
|
239 | self.uri = url.parse(self.uri)
|
240 | }
|
241 |
|
242 |
|
243 | if (!self.uri.href) {
|
244 | self.uri.href = url.format(self.uri)
|
245 | }
|
246 |
|
247 |
|
248 | if (self.uri.protocol === 'unix:') {
|
249 | return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'))
|
250 | }
|
251 |
|
252 |
|
253 | if (self.uri.host === 'unix') {
|
254 | self.enableUnixSocket()
|
255 | }
|
256 |
|
257 | if (self.strictSSL === false) {
|
258 | self.rejectUnauthorized = false
|
259 | }
|
260 |
|
261 | if (!self.uri.pathname) {self.uri.pathname = '/'}
|
262 |
|
263 | if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
|
264 |
|
265 |
|
266 | var faultyUri = url.format(self.uri)
|
267 | var message = 'Invalid URI "' + faultyUri + '"'
|
268 | if (Object.keys(options).length === 0) {
|
269 |
|
270 |
|
271 |
|
272 | message += '. This can be caused by a crappy redirection.'
|
273 | }
|
274 |
|
275 | self.abort()
|
276 | return self.emit('error', new Error(message))
|
277 | }
|
278 |
|
279 | if (!self.hasOwnProperty('proxy')) {
|
280 | self.proxy = getProxyFromURI(self.uri)
|
281 | }
|
282 |
|
283 | self.tunnel = self._tunnel.isEnabled()
|
284 | if (self.proxy) {
|
285 | self._tunnel.setup(options)
|
286 | }
|
287 |
|
288 | self._redirect.onRequest(options)
|
289 |
|
290 | self.setHost = false
|
291 | if (!self.hasHeader('host')) {
|
292 | var hostHeaderName = self.originalHostHeaderName || 'host'
|
293 |
|
294 |
|
295 |
|
296 | self.setHeader(hostHeaderName, self.uri.host)
|
297 | self.setHost = true
|
298 | }
|
299 |
|
300 | self.jar(self._jar || options.jar)
|
301 |
|
302 | if (!self.uri.port) {
|
303 | if (self.uri.protocol === 'http:') {self.uri.port = 80}
|
304 | else if (self.uri.protocol === 'https:') {self.uri.port = 443}
|
305 | }
|
306 |
|
307 | if (self.proxy && !self.tunnel) {
|
308 | self.port = self.proxy.port
|
309 | self.host = self.proxy.hostname
|
310 | } else {
|
311 | self.port = self.uri.port
|
312 | self.host = self.uri.hostname
|
313 | }
|
314 |
|
315 | if (options.form) {
|
316 | self.form(options.form)
|
317 | }
|
318 |
|
319 | if (options.formData) {
|
320 | var formData = options.formData
|
321 | var requestForm = self.form()
|
322 | var appendFormValue = function (key, value) {
|
323 | if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
|
324 | requestForm.append(key, value.value, value.options)
|
325 | } else {
|
326 | requestForm.append(key, value)
|
327 | }
|
328 | }
|
329 | for (var formKey in formData) {
|
330 | if (formData.hasOwnProperty(formKey)) {
|
331 | var formValue = formData[formKey]
|
332 | if (formValue instanceof Array) {
|
333 | for (var j = 0; j < formValue.length; j++) {
|
334 | appendFormValue(formKey, formValue[j])
|
335 | }
|
336 | } else {
|
337 | appendFormValue(formKey, formValue)
|
338 | }
|
339 | }
|
340 | }
|
341 | }
|
342 |
|
343 | if (options.qs) {
|
344 | self.qs(options.qs)
|
345 | }
|
346 |
|
347 | if (self.uri.path) {
|
348 | self.path = self.uri.path
|
349 | } else {
|
350 | self.path = self.uri.pathname + (self.uri.search || '')
|
351 | }
|
352 |
|
353 | if (self.path.length === 0) {
|
354 | self.path = '/'
|
355 | }
|
356 |
|
357 |
|
358 | if (options.aws) {
|
359 | self.aws(options.aws)
|
360 | }
|
361 |
|
362 | if (options.hawk) {
|
363 | self.hawk(options.hawk)
|
364 | }
|
365 |
|
366 | if (options.httpSignature) {
|
367 | self.httpSignature(options.httpSignature)
|
368 | }
|
369 |
|
370 | if (options.auth) {
|
371 | if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
|
372 | options.auth.user = options.auth.username
|
373 | }
|
374 | if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
|
375 | options.auth.pass = options.auth.password
|
376 | }
|
377 |
|
378 | self.auth(
|
379 | options.auth.user,
|
380 | options.auth.pass,
|
381 | options.auth.sendImmediately,
|
382 | options.auth.bearer
|
383 | )
|
384 | }
|
385 |
|
386 | if (self.gzip && !self.hasHeader('accept-encoding')) {
|
387 | self.setHeader('accept-encoding', 'gzip, deflate')
|
388 | }
|
389 |
|
390 | if (self.uri.auth && !self.hasHeader('authorization')) {
|
391 | var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
|
392 | self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
|
393 | }
|
394 |
|
395 | if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
|
396 | var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
|
397 | var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
|
398 | self.setHeader('proxy-authorization', authHeader)
|
399 | }
|
400 |
|
401 | if (self.proxy && !self.tunnel) {
|
402 | self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
|
403 | }
|
404 |
|
405 | if (options.json) {
|
406 | self.json(options.json)
|
407 | }
|
408 | if (options.multipart) {
|
409 | self.multipart(options.multipart)
|
410 | }
|
411 |
|
412 | if (options.time) {
|
413 | self.timing = true
|
414 |
|
415 |
|
416 | self.elapsedTime = self.elapsedTime || 0
|
417 | }
|
418 |
|
419 | function setContentLength () {
|
420 | if (isTypedArray(self.body)) {
|
421 | self.body = Buffer.from(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 |
|
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 |
|
521 |
|
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 |
|
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 |
|
630 | if (Agent !== self.httpModule.Agent) {
|
631 | poolKey += Agent.name
|
632 | }
|
633 |
|
634 |
|
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 |
|
694 | return self.httpModule.globalAgent
|
695 | }
|
696 |
|
697 |
|
698 | poolKey = self.uri.protocol + poolKey
|
699 |
|
700 |
|
701 | if (!self.pool[poolKey]) {
|
702 | self.pool[poolKey] = new Agent(options)
|
703 |
|
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 |
|
714 |
|
715 | var self = this
|
716 |
|
717 | if (self.timing) {
|
718 |
|
719 |
|
720 |
|
721 |
|
722 |
|
723 | var startTime = new Date().getTime()
|
724 | var startTimeNow = now()
|
725 | }
|
726 |
|
727 | if (self._aborted) {
|
728 | return
|
729 | }
|
730 |
|
731 | self._started = true
|
732 | self.method = self.method || 'GET'
|
733 | self.href = self.uri.href
|
734 |
|
735 | if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
|
736 | self.setHeader('content-length', self.src.stat.size)
|
737 | }
|
738 | if (self._aws) {
|
739 | self.aws(self._aws, true)
|
740 | }
|
741 |
|
742 |
|
743 |
|
744 | var reqOptions = copy(self)
|
745 | delete reqOptions.auth
|
746 |
|
747 | debug('make request', self.uri.href)
|
748 |
|
749 |
|
750 |
|
751 |
|
752 | delete reqOptions.timeout
|
753 |
|
754 | try {
|
755 | self.req = self.httpModule.request(reqOptions)
|
756 | } catch (err) {
|
757 | self.emit('error', err)
|
758 | return
|
759 | }
|
760 |
|
761 | if (self.timing) {
|
762 | self.startTime = startTime
|
763 | self.startTimeNow = startTimeNow
|
764 |
|
765 |
|
766 |
|
767 | self.timings = {}
|
768 | }
|
769 |
|
770 | var timeout
|
771 | if (self.timeout && !self.timeoutTimer) {
|
772 | if (self.timeout < 0) {
|
773 | timeout = 0
|
774 | } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) {
|
775 | timeout = self.timeout
|
776 | }
|
777 | }
|
778 |
|
779 | self.req.on('response', self.onRequestResponse.bind(self))
|
780 | self.req.on('error', self.onRequestError.bind(self))
|
781 | self.req.on('drain', function() {
|
782 | self.emit('drain')
|
783 | })
|
784 | self.req.on('socket', function(socket) {
|
785 |
|
786 | var isConnecting = socket._connecting || socket.connecting
|
787 | if (self.timing) {
|
788 | self.timings.socket = now() - self.startTimeNow
|
789 |
|
790 | if (isConnecting) {
|
791 | var onLookupTiming = function() {
|
792 | self.timings.lookup = now() - self.startTimeNow
|
793 | }
|
794 |
|
795 | var onConnectTiming = function() {
|
796 | self.timings.connect = now() - self.startTimeNow
|
797 | }
|
798 |
|
799 | socket.once('lookup', onLookupTiming)
|
800 | socket.once('connect', onConnectTiming)
|
801 |
|
802 |
|
803 | self.req.once('error', function() {
|
804 | socket.removeListener('lookup', onLookupTiming)
|
805 | socket.removeListener('connect', onConnectTiming)
|
806 | })
|
807 | }
|
808 | }
|
809 |
|
810 | var setReqTimeout = function() {
|
811 |
|
812 |
|
813 |
|
814 |
|
815 |
|
816 | self.req.setTimeout(timeout, function () {
|
817 | if (self.req) {
|
818 | self.abort()
|
819 | var e = new Error('ESOCKETTIMEDOUT')
|
820 | e.code = 'ESOCKETTIMEDOUT'
|
821 | e.connect = false
|
822 | self.emit('error', e)
|
823 | }
|
824 | })
|
825 | }
|
826 | if (timeout !== undefined) {
|
827 |
|
828 |
|
829 |
|
830 |
|
831 | if (isConnecting) {
|
832 | var onReqSockConnect = function() {
|
833 | socket.removeListener('connect', onReqSockConnect)
|
834 | clearTimeout(self.timeoutTimer)
|
835 | self.timeoutTimer = null
|
836 | setReqTimeout()
|
837 | }
|
838 |
|
839 | socket.on('connect', onReqSockConnect)
|
840 |
|
841 | self.req.on('error', function(err) {
|
842 | socket.removeListener('connect', onReqSockConnect)
|
843 | })
|
844 |
|
845 |
|
846 |
|
847 |
|
848 |
|
849 | self.timeoutTimer = setTimeout(function () {
|
850 | socket.removeListener('connect', onReqSockConnect)
|
851 | self.abort()
|
852 | var e = new Error('ETIMEDOUT')
|
853 | e.code = 'ETIMEDOUT'
|
854 | e.connect = true
|
855 | self.emit('error', e)
|
856 | }, timeout)
|
857 | } else {
|
858 |
|
859 | setReqTimeout()
|
860 | }
|
861 | }
|
862 | self.emit('socket', socket)
|
863 | })
|
864 |
|
865 | self.emit('request', self.req)
|
866 | }
|
867 |
|
868 | Request.prototype.onRequestError = function (error) {
|
869 | var self = this
|
870 | if (self._aborted) {
|
871 | return
|
872 | }
|
873 | if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
|
874 | && self.agent.addRequestNoreuse) {
|
875 | self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
|
876 | self.start()
|
877 | self.req.end()
|
878 | return
|
879 | }
|
880 | if (self.timeout && self.timeoutTimer) {
|
881 | clearTimeout(self.timeoutTimer)
|
882 | self.timeoutTimer = null
|
883 | }
|
884 | self.emit('error', error)
|
885 | }
|
886 |
|
887 | Request.prototype.onRequestResponse = function (response) {
|
888 | var self = this
|
889 |
|
890 | if (self.timing) {
|
891 | self.timings.response = now() - self.startTimeNow
|
892 | }
|
893 |
|
894 | debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
|
895 | response.on('end', function() {
|
896 | if (self.timing) {
|
897 | self.timings.end = now() - self.startTimeNow
|
898 | response.timingStart = self.startTime
|
899 |
|
900 |
|
901 |
|
902 | if (!self.timings.socket) {
|
903 | self.timings.socket = 0
|
904 | }
|
905 | if (!self.timings.lookup) {
|
906 | self.timings.lookup = self.timings.socket
|
907 | }
|
908 | if (!self.timings.connect) {
|
909 | self.timings.connect = self.timings.lookup
|
910 | }
|
911 | if (!self.timings.response) {
|
912 | self.timings.response = self.timings.connect
|
913 | }
|
914 |
|
915 | debug('elapsed time', self.timings.end)
|
916 |
|
917 |
|
918 | self.elapsedTime += Math.round(self.timings.end)
|
919 |
|
920 |
|
921 | response.elapsedTime = self.elapsedTime
|
922 |
|
923 |
|
924 | response.timings = self.timings
|
925 |
|
926 |
|
927 | response.timingPhases = {
|
928 | wait: self.timings.socket,
|
929 | dns: self.timings.lookup - self.timings.socket,
|
930 | tcp: self.timings.connect - self.timings.lookup,
|
931 | firstByte: self.timings.response - self.timings.connect,
|
932 | download: self.timings.end - self.timings.response,
|
933 | total: self.timings.end
|
934 | }
|
935 | }
|
936 | debug('response end', self.uri.href, response.statusCode, response.headers)
|
937 | })
|
938 |
|
939 | if (self._aborted) {
|
940 | debug('aborted', self.uri.href)
|
941 | response.resume()
|
942 | return
|
943 | }
|
944 |
|
945 | self.response = response
|
946 | response.request = self
|
947 | response.toJSON = responseToJSON
|
948 |
|
949 |
|
950 | if (self.httpModule === https &&
|
951 | self.strictSSL && (!response.hasOwnProperty('socket') ||
|
952 | !response.socket.authorized)) {
|
953 | debug('strict ssl error', self.uri.href)
|
954 | var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
|
955 | self.emit('error', new Error('SSL Error: ' + sslErr))
|
956 | return
|
957 | }
|
958 |
|
959 |
|
960 |
|
961 |
|
962 |
|
963 | self.originalHost = self.getHeader('host')
|
964 | if (!self.originalHostHeaderName) {
|
965 | self.originalHostHeaderName = self.hasHeader('host')
|
966 | }
|
967 | if (self.setHost) {
|
968 | self.removeHeader('host')
|
969 | }
|
970 | if (self.timeout && self.timeoutTimer) {
|
971 | clearTimeout(self.timeoutTimer)
|
972 | self.timeoutTimer = null
|
973 | }
|
974 |
|
975 | var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
|
976 | var addCookie = function (cookie) {
|
977 |
|
978 | try {
|
979 | targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
|
980 | } catch (e) {
|
981 | self.emit('error', e)
|
982 | }
|
983 | }
|
984 |
|
985 | response.caseless = caseless(response.headers)
|
986 |
|
987 | if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
|
988 | var headerName = response.caseless.has('set-cookie')
|
989 | if (Array.isArray(response.headers[headerName])) {
|
990 | response.headers[headerName].forEach(addCookie)
|
991 | } else {
|
992 | addCookie(response.headers[headerName])
|
993 | }
|
994 | }
|
995 |
|
996 | if (self._redirect.onResponse(response)) {
|
997 | return
|
998 | } else {
|
999 |
|
1000 |
|
1001 | response.on('close', function () {
|
1002 | if (!self._ended) {
|
1003 | self.response.emit('end')
|
1004 | }
|
1005 | })
|
1006 |
|
1007 | response.once('end', function () {
|
1008 | self._ended = true
|
1009 | })
|
1010 |
|
1011 | var noBody = function (code) {
|
1012 | return (
|
1013 | self.method === 'HEAD'
|
1014 |
|
1015 | || (code >= 100 && code < 200)
|
1016 |
|
1017 | || code === 204
|
1018 |
|
1019 | || code === 304
|
1020 | )
|
1021 | }
|
1022 |
|
1023 | var responseContent
|
1024 | if (self.gzip && !noBody(response.statusCode)) {
|
1025 | var contentEncoding = response.headers['content-encoding'] || 'identity'
|
1026 | contentEncoding = contentEncoding.trim().toLowerCase()
|
1027 |
|
1028 |
|
1029 |
|
1030 |
|
1031 |
|
1032 | var zlibOptions = {
|
1033 | flush: zlib.Z_SYNC_FLUSH
|
1034 | , finishFlush: zlib.Z_SYNC_FLUSH
|
1035 | }
|
1036 |
|
1037 | if (contentEncoding === 'gzip') {
|
1038 | responseContent = zlib.createGunzip(zlibOptions)
|
1039 | response.pipe(responseContent)
|
1040 | } else if (contentEncoding === 'deflate') {
|
1041 | responseContent = zlib.createInflate(zlibOptions)
|
1042 | response.pipe(responseContent)
|
1043 | } else {
|
1044 |
|
1045 |
|
1046 | if (contentEncoding !== 'identity') {
|
1047 | debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
|
1048 | }
|
1049 | responseContent = response
|
1050 | }
|
1051 | } else {
|
1052 | responseContent = response
|
1053 | }
|
1054 |
|
1055 | if (self.encoding) {
|
1056 | if (self.dests.length !== 0) {
|
1057 | console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
|
1058 | } else if (responseContent.setEncoding) {
|
1059 | responseContent.setEncoding(self.encoding)
|
1060 | } else {
|
1061 |
|
1062 |
|
1063 |
|
1064 | responseContent = responseContent.pipe(stringstream(self.encoding))
|
1065 | }
|
1066 | }
|
1067 |
|
1068 | if (self._paused) {
|
1069 | responseContent.pause()
|
1070 | }
|
1071 |
|
1072 | self.responseContent = responseContent
|
1073 |
|
1074 | self.emit('response', response)
|
1075 |
|
1076 | self.dests.forEach(function (dest) {
|
1077 | self.pipeDest(dest)
|
1078 | })
|
1079 |
|
1080 | responseContent.on('data', function (chunk) {
|
1081 | if (self.timing && !self.responseStarted) {
|
1082 | self.responseStartTime = (new Date()).getTime()
|
1083 |
|
1084 |
|
1085 | response.responseStartTime = self.responseStartTime
|
1086 | }
|
1087 | self._destdata = true
|
1088 | self.emit('data', chunk)
|
1089 | })
|
1090 | responseContent.once('end', function (chunk) {
|
1091 | self.emit('end', chunk)
|
1092 | })
|
1093 | responseContent.on('error', function (error) {
|
1094 | self.emit('error', error)
|
1095 | })
|
1096 | responseContent.on('close', function () {self.emit('close')})
|
1097 |
|
1098 | if (self.callback) {
|
1099 | self.readResponseBody(response)
|
1100 | }
|
1101 |
|
1102 | else {
|
1103 | self.on('end', function () {
|
1104 | if (self._aborted) {
|
1105 | debug('aborted', self.uri.href)
|
1106 | return
|
1107 | }
|
1108 | self.emit('complete', response)
|
1109 | })
|
1110 | }
|
1111 | }
|
1112 | debug('finish init function', self.uri.href)
|
1113 | }
|
1114 |
|
1115 | Request.prototype.readResponseBody = function (response) {
|
1116 | var self = this
|
1117 | debug('reading response\'s body')
|
1118 | var buffers = []
|
1119 | , bufferLength = 0
|
1120 | , strings = []
|
1121 |
|
1122 | self.on('data', function (chunk) {
|
1123 | if (!Buffer.isBuffer(chunk)) {
|
1124 | strings.push(chunk)
|
1125 | } else if (chunk.length) {
|
1126 | bufferLength += chunk.length
|
1127 | buffers.push(chunk)
|
1128 | }
|
1129 | })
|
1130 | self.on('end', function () {
|
1131 | debug('end event', self.uri.href)
|
1132 | if (self._aborted) {
|
1133 | debug('aborted', self.uri.href)
|
1134 |
|
1135 |
|
1136 | buffers = []
|
1137 | bufferLength = 0
|
1138 | return
|
1139 | }
|
1140 |
|
1141 | if (bufferLength) {
|
1142 | debug('has body', self.uri.href, bufferLength)
|
1143 | response.body = Buffer.concat(buffers, bufferLength)
|
1144 | if (self.encoding !== null) {
|
1145 | response.body = response.body.toString(self.encoding)
|
1146 | }
|
1147 |
|
1148 |
|
1149 | buffers = []
|
1150 | bufferLength = 0
|
1151 | } else if (strings.length) {
|
1152 |
|
1153 |
|
1154 | if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
|
1155 | strings[0] = strings[0].substring(1)
|
1156 | }
|
1157 | response.body = strings.join('')
|
1158 | }
|
1159 |
|
1160 | if (self._json) {
|
1161 | try {
|
1162 | response.body = JSON.parse(response.body, self._jsonReviver)
|
1163 | } catch (e) {
|
1164 | debug('invalid JSON received', self.uri.href)
|
1165 | }
|
1166 | }
|
1167 | debug('emitting complete', self.uri.href)
|
1168 | if (typeof response.body === 'undefined' && !self._json) {
|
1169 | response.body = self.encoding === null ? Buffer.alloc(0) : ''
|
1170 | }
|
1171 | self.emit('complete', response, response.body)
|
1172 | })
|
1173 | }
|
1174 |
|
1175 | Request.prototype.abort = function () {
|
1176 | var self = this
|
1177 | self._aborted = true
|
1178 |
|
1179 | if (self.req) {
|
1180 | self.req.abort()
|
1181 | }
|
1182 | else if (self.response) {
|
1183 | self.response.destroy()
|
1184 | }
|
1185 |
|
1186 | self.emit('abort')
|
1187 | }
|
1188 |
|
1189 | Request.prototype.pipeDest = function (dest) {
|
1190 | var self = this
|
1191 | var response = self.response
|
1192 |
|
1193 | if (dest.headers && !dest.headersSent) {
|
1194 | if (response.caseless.has('content-type')) {
|
1195 | var ctname = response.caseless.has('content-type')
|
1196 | if (dest.setHeader) {
|
1197 | dest.setHeader(ctname, response.headers[ctname])
|
1198 | }
|
1199 | else {
|
1200 | dest.headers[ctname] = response.headers[ctname]
|
1201 | }
|
1202 | }
|
1203 |
|
1204 | if (response.caseless.has('content-length')) {
|
1205 | var clname = response.caseless.has('content-length')
|
1206 | if (dest.setHeader) {
|
1207 | dest.setHeader(clname, response.headers[clname])
|
1208 | } else {
|
1209 | dest.headers[clname] = response.headers[clname]
|
1210 | }
|
1211 | }
|
1212 | }
|
1213 | if (dest.setHeader && !dest.headersSent) {
|
1214 | for (var i in response.headers) {
|
1215 |
|
1216 |
|
1217 | if (!self.gzip || i !== 'content-encoding') {
|
1218 | dest.setHeader(i, response.headers[i])
|
1219 | }
|
1220 | }
|
1221 | dest.statusCode = response.statusCode
|
1222 | }
|
1223 | if (self.pipefilter) {
|
1224 | self.pipefilter(response, dest)
|
1225 | }
|
1226 | }
|
1227 |
|
1228 | Request.prototype.qs = function (q, clobber) {
|
1229 | var self = this
|
1230 | var base
|
1231 | if (!clobber && self.uri.query) {
|
1232 | base = self._qs.parse(self.uri.query)
|
1233 | } else {
|
1234 | base = {}
|
1235 | }
|
1236 |
|
1237 | for (var i in q) {
|
1238 | base[i] = q[i]
|
1239 | }
|
1240 |
|
1241 | var qs = self._qs.stringify(base)
|
1242 |
|
1243 | if (qs === '') {
|
1244 | return self
|
1245 | }
|
1246 |
|
1247 | self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
|
1248 | self.url = self.uri
|
1249 | self.path = self.uri.path
|
1250 |
|
1251 | if (self.uri.host === 'unix') {
|
1252 | self.enableUnixSocket()
|
1253 | }
|
1254 |
|
1255 | return self
|
1256 | }
|
1257 | Request.prototype.form = function (form) {
|
1258 | var self = this
|
1259 | if (form) {
|
1260 | if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
|
1261 | self.setHeader('content-type', 'application/x-www-form-urlencoded')
|
1262 | }
|
1263 | self.body = (typeof form === 'string')
|
1264 | ? self._qs.rfc3986(form.toString('utf8'))
|
1265 | : self._qs.stringify(form).toString('utf8')
|
1266 | return self
|
1267 | }
|
1268 |
|
1269 | self._form = new FormData()
|
1270 | self._form.on('error', function(err) {
|
1271 | err.message = 'form-data: ' + err.message
|
1272 | self.emit('error', err)
|
1273 | self.abort()
|
1274 | })
|
1275 | return self._form
|
1276 | }
|
1277 | Request.prototype.multipart = function (multipart) {
|
1278 | var self = this
|
1279 |
|
1280 | self._multipart.onRequest(multipart)
|
1281 |
|
1282 | if (!self._multipart.chunked) {
|
1283 | self.body = self._multipart.body
|
1284 | }
|
1285 |
|
1286 | return self
|
1287 | }
|
1288 | Request.prototype.json = function (val) {
|
1289 | var self = this
|
1290 |
|
1291 | if (!self.hasHeader('accept')) {
|
1292 | self.setHeader('accept', 'application/json')
|
1293 | }
|
1294 |
|
1295 | if (typeof self.jsonReplacer === 'function') {
|
1296 | self._jsonReplacer = self.jsonReplacer
|
1297 | }
|
1298 |
|
1299 | self._json = true
|
1300 | if (typeof val === 'boolean') {
|
1301 | if (self.body !== undefined) {
|
1302 | if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
|
1303 | self.body = safeStringify(self.body, self._jsonReplacer)
|
1304 | } else {
|
1305 | self.body = self._qs.rfc3986(self.body)
|
1306 | }
|
1307 | if (!self.hasHeader('content-type')) {
|
1308 | self.setHeader('content-type', 'application/json')
|
1309 | }
|
1310 | }
|
1311 | } else {
|
1312 | self.body = safeStringify(val, self._jsonReplacer)
|
1313 | if (!self.hasHeader('content-type')) {
|
1314 | self.setHeader('content-type', 'application/json')
|
1315 | }
|
1316 | }
|
1317 |
|
1318 | if (typeof self.jsonReviver === 'function') {
|
1319 | self._jsonReviver = self.jsonReviver
|
1320 | }
|
1321 |
|
1322 | return self
|
1323 | }
|
1324 | Request.prototype.getHeader = function (name, headers) {
|
1325 | var self = this
|
1326 | var result, re, match
|
1327 | if (!headers) {
|
1328 | headers = self.headers
|
1329 | }
|
1330 | Object.keys(headers).forEach(function (key) {
|
1331 | if (key.length !== name.length) {
|
1332 | return
|
1333 | }
|
1334 | re = new RegExp(name, 'i')
|
1335 | match = key.match(re)
|
1336 | if (match) {
|
1337 | result = headers[key]
|
1338 | }
|
1339 | })
|
1340 | return result
|
1341 | }
|
1342 | Request.prototype.enableUnixSocket = function () {
|
1343 |
|
1344 | var unixParts = this.uri.path.split(':')
|
1345 | , host = unixParts[0]
|
1346 | , path = unixParts[1]
|
1347 |
|
1348 | this.socketPath = host
|
1349 | this.uri.pathname = path
|
1350 | this.uri.path = path
|
1351 | this.uri.host = host
|
1352 | this.uri.hostname = host
|
1353 | this.uri.isUnix = true
|
1354 | }
|
1355 |
|
1356 |
|
1357 | Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
|
1358 | var self = this
|
1359 |
|
1360 | self._auth.onRequest(user, pass, sendImmediately, bearer)
|
1361 |
|
1362 | return self
|
1363 | }
|
1364 | Request.prototype.aws = function (opts, now) {
|
1365 | var self = this
|
1366 |
|
1367 | if (!now) {
|
1368 | self._aws = opts
|
1369 | return self
|
1370 | }
|
1371 |
|
1372 | if (opts.sign_version == 4 || opts.sign_version == '4') {
|
1373 |
|
1374 | var options = {
|
1375 | host: self.uri.host,
|
1376 | path: self.uri.path,
|
1377 | method: self.method,
|
1378 | headers: {
|
1379 | 'content-type': self.getHeader('content-type') || ''
|
1380 | },
|
1381 | body: self.body
|
1382 | }
|
1383 | var signRes = aws4.sign(options, {
|
1384 | accessKeyId: opts.key,
|
1385 | secretAccessKey: opts.secret,
|
1386 | sessionToken: opts.session
|
1387 | })
|
1388 | self.setHeader('authorization', signRes.headers.Authorization)
|
1389 | self.setHeader('x-amz-date', signRes.headers['X-Amz-Date'])
|
1390 | if (signRes.headers['X-Amz-Security-Token']) {
|
1391 | self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
|
1392 | }
|
1393 | }
|
1394 | else {
|
1395 |
|
1396 | var date = new Date()
|
1397 | self.setHeader('date', date.toUTCString())
|
1398 | var auth =
|
1399 | { key: opts.key
|
1400 | , secret: opts.secret
|
1401 | , verb: self.method.toUpperCase()
|
1402 | , date: date
|
1403 | , contentType: self.getHeader('content-type') || ''
|
1404 | , md5: self.getHeader('content-md5') || ''
|
1405 | , amazonHeaders: aws2.canonicalizeHeaders(self.headers)
|
1406 | }
|
1407 | var path = self.uri.path
|
1408 | if (opts.bucket && path) {
|
1409 | auth.resource = '/' + opts.bucket + path
|
1410 | } else if (opts.bucket && !path) {
|
1411 | auth.resource = '/' + opts.bucket
|
1412 | } else if (!opts.bucket && path) {
|
1413 | auth.resource = path
|
1414 | } else if (!opts.bucket && !path) {
|
1415 | auth.resource = '/'
|
1416 | }
|
1417 | auth.resource = aws2.canonicalizeResource(auth.resource)
|
1418 | self.setHeader('authorization', aws2.authorization(auth))
|
1419 | }
|
1420 |
|
1421 | return self
|
1422 | }
|
1423 | Request.prototype.httpSignature = function (opts) {
|
1424 | var self = this
|
1425 | httpSignature.signRequest({
|
1426 | getHeader: function(header) {
|
1427 | return self.getHeader(header, self.headers)
|
1428 | },
|
1429 | setHeader: function(header, value) {
|
1430 | self.setHeader(header, value)
|
1431 | },
|
1432 | method: self.method,
|
1433 | path: self.path
|
1434 | }, opts)
|
1435 | debug('httpSignature authorization', self.getHeader('authorization'))
|
1436 |
|
1437 | return self
|
1438 | }
|
1439 | Request.prototype.hawk = function (opts) {
|
1440 | var self = this
|
1441 | self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field)
|
1442 | }
|
1443 | Request.prototype.oauth = function (_oauth) {
|
1444 | var self = this
|
1445 |
|
1446 | self._oauth.onRequest(_oauth)
|
1447 |
|
1448 | return self
|
1449 | }
|
1450 |
|
1451 | Request.prototype.jar = function (jar) {
|
1452 | var self = this
|
1453 | var cookies
|
1454 |
|
1455 | if (self._redirect.redirectsFollowed === 0) {
|
1456 | self.originalCookieHeader = self.getHeader('cookie')
|
1457 | }
|
1458 |
|
1459 | if (!jar) {
|
1460 |
|
1461 | cookies = false
|
1462 | self._disableCookies = true
|
1463 | } else {
|
1464 | var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
|
1465 | var urihref = self.uri.href
|
1466 |
|
1467 | if (targetCookieJar) {
|
1468 | cookies = targetCookieJar.getCookieString(urihref)
|
1469 | }
|
1470 | }
|
1471 |
|
1472 |
|
1473 | if (cookies && cookies.length) {
|
1474 | if (self.originalCookieHeader) {
|
1475 |
|
1476 | self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
|
1477 | } else {
|
1478 | self.setHeader('cookie', cookies)
|
1479 | }
|
1480 | }
|
1481 | self._jar = jar
|
1482 | return self
|
1483 | }
|
1484 |
|
1485 |
|
1486 |
|
1487 | Request.prototype.pipe = function (dest, opts) {
|
1488 | var self = this
|
1489 |
|
1490 | if (self.response) {
|
1491 | if (self._destdata) {
|
1492 | self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
|
1493 | } else if (self._ended) {
|
1494 | self.emit('error', new Error('You cannot pipe after the response has been ended.'))
|
1495 | } else {
|
1496 | stream.Stream.prototype.pipe.call(self, dest, opts)
|
1497 | self.pipeDest(dest)
|
1498 | return dest
|
1499 | }
|
1500 | } else {
|
1501 | self.dests.push(dest)
|
1502 | stream.Stream.prototype.pipe.call(self, dest, opts)
|
1503 | return dest
|
1504 | }
|
1505 | }
|
1506 | Request.prototype.write = function () {
|
1507 | var self = this
|
1508 | if (self._aborted) {return}
|
1509 |
|
1510 | if (!self._started) {
|
1511 | self.start()
|
1512 | }
|
1513 | if (self.req) {
|
1514 | return self.req.write.apply(self.req, arguments)
|
1515 | }
|
1516 | }
|
1517 | Request.prototype.end = function (chunk) {
|
1518 | var self = this
|
1519 | if (self._aborted) {return}
|
1520 |
|
1521 | if (chunk) {
|
1522 | self.write(chunk)
|
1523 | }
|
1524 | if (!self._started) {
|
1525 | self.start()
|
1526 | }
|
1527 | if (self.req) {
|
1528 | self.req.end()
|
1529 | }
|
1530 | }
|
1531 | Request.prototype.pause = function () {
|
1532 | var self = this
|
1533 | if (!self.responseContent) {
|
1534 | self._paused = true
|
1535 | } else {
|
1536 | self.responseContent.pause.apply(self.responseContent, arguments)
|
1537 | }
|
1538 | }
|
1539 | Request.prototype.resume = function () {
|
1540 | var self = this
|
1541 | if (!self.responseContent) {
|
1542 | self._paused = false
|
1543 | } else {
|
1544 | self.responseContent.resume.apply(self.responseContent, arguments)
|
1545 | }
|
1546 | }
|
1547 | Request.prototype.destroy = function () {
|
1548 | var self = this
|
1549 | if (!self._ended) {
|
1550 | self.end()
|
1551 | } else if (self.response) {
|
1552 | self.response.destroy()
|
1553 | }
|
1554 | }
|
1555 |
|
1556 | Request.defaultProxyHeaderWhiteList =
|
1557 | Tunnel.defaultProxyHeaderWhiteList.slice()
|
1558 |
|
1559 | Request.defaultProxyHeaderExclusiveList =
|
1560 | Tunnel.defaultProxyHeaderExclusiveList.slice()
|
1561 |
|
1562 |
|
1563 |
|
1564 | Request.prototype.toJSON = requestToJSON
|
1565 | module.exports = Request
|