request.js 43 KB

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