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