request.js 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  1. 'use strict'
  2. var http = require('http')
  3. , https = require('https')
  4. , url = require('url')
  5. , util = require('util')
  6. , stream = require('stream')
  7. , zlib = require('zlib')
  8. , hawk = require('hawk')
  9. , aws2 = require('aws-sign2')
  10. , aws4 = require('aws4')
  11. , httpSignature = require('http-signature')
  12. , mime = require('mime-types')
  13. , stringstream = require('stringstream')
  14. , caseless = require('caseless')
  15. , ForeverAgent = require('forever-agent')
  16. , FormData = require('form-data')
  17. , extend = require('extend')
  18. , isstream = require('isstream')
  19. , isTypedArray = require('is-typedarray').strict
  20. , helpers = require('./lib/helpers')
  21. , cookies = require('./lib/cookies')
  22. , getProxyFromURI = require('./lib/getProxyFromURI')
  23. , Querystring = require('./lib/querystring').Querystring
  24. , Har = require('./lib/har').Har
  25. , Auth = require('./lib/auth').Auth
  26. , OAuth = require('./lib/oauth').OAuth
  27. , Multipart = require('./lib/multipart').Multipart
  28. , Redirect = require('./lib/redirect').Redirect
  29. , Tunnel = require('./lib/tunnel').Tunnel
  30. , now = require('performance-now')
  31. , Buffer = require('safe-buffer').Buffer
  32. var safeStringify = helpers.safeStringify
  33. , isReadStream = helpers.isReadStream
  34. , toBase64 = helpers.toBase64
  35. , defer = helpers.defer
  36. , copy = helpers.copy
  37. , version = helpers.version
  38. , 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}
  257. else if (self.uri.protocol === 'https:') {self.uri.port = 443}
  258. }
  259. if (self.proxy && !self.tunnel) {
  260. self.port = self.proxy.port
  261. self.host = self.proxy.hostname
  262. } else {
  263. self.port = self.uri.port
  264. self.host = self.uri.hostname
  265. }
  266. if (options.form) {
  267. self.form(options.form)
  268. }
  269. if (options.formData) {
  270. var formData = options.formData
  271. var requestForm = self.form()
  272. var appendFormValue = function (key, value) {
  273. if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
  274. requestForm.append(key, value.value, value.options)
  275. } else {
  276. requestForm.append(key, value)
  277. }
  278. }
  279. for (var formKey in formData) {
  280. if (formData.hasOwnProperty(formKey)) {
  281. var formValue = formData[formKey]
  282. if (formValue instanceof Array) {
  283. for (var j = 0; j < formValue.length; j++) {
  284. appendFormValue(formKey, formValue[j])
  285. }
  286. } else {
  287. appendFormValue(formKey, formValue)
  288. }
  289. }
  290. }
  291. }
  292. if (options.qs) {
  293. self.qs(options.qs)
  294. }
  295. if (self.uri.path) {
  296. self.path = self.uri.path
  297. } else {
  298. self.path = self.uri.pathname + (self.uri.search || '')
  299. }
  300. if (self.path.length === 0) {
  301. self.path = '/'
  302. }
  303. // Auth must happen last in case signing is dependent on other headers
  304. if (options.aws) {
  305. self.aws(options.aws)
  306. }
  307. if (options.hawk) {
  308. self.hawk(options.hawk)
  309. }
  310. if (options.httpSignature) {
  311. self.httpSignature(options.httpSignature)
  312. }
  313. if (options.auth) {
  314. if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
  315. options.auth.user = options.auth.username
  316. }
  317. if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
  318. options.auth.pass = options.auth.password
  319. }
  320. self.auth(
  321. options.auth.user,
  322. options.auth.pass,
  323. options.auth.sendImmediately,
  324. options.auth.bearer
  325. )
  326. }
  327. if (self.gzip && !self.hasHeader('accept-encoding')) {
  328. self.setHeader('accept-encoding', 'gzip, deflate')
  329. }
  330. if (self.uri.auth && !self.hasHeader('authorization')) {
  331. var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
  332. self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
  333. }
  334. if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
  335. var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
  336. var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
  337. self.setHeader('proxy-authorization', authHeader)
  338. }
  339. if (self.proxy && !self.tunnel) {
  340. self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
  341. }
  342. if (options.json) {
  343. self.json(options.json)
  344. }
  345. if (options.multipart) {
  346. self.multipart(options.multipart)
  347. }
  348. if (options.time) {
  349. self.timing = true
  350. // NOTE: elapsedTime is deprecated in favor of .timings
  351. self.elapsedTime = self.elapsedTime || 0
  352. }
  353. function setContentLength () {
  354. if (isTypedArray(self.body)) {
  355. self.body = Buffer.from(self.body)
  356. }
  357. if (!self.hasHeader('content-length')) {
  358. var length
  359. if (typeof self.body === 'string') {
  360. length = Buffer.byteLength(self.body)
  361. }
  362. else if (Array.isArray(self.body)) {
  363. length = self.body.reduce(function (a, b) {return a + b.length}, 0)
  364. }
  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. , defaultModules = {'http:':http, 'https:':https}
  385. , 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. }
  455. else if (self._auth.hasAuth && self._auth.sentAuth) {
  456. self._form.pipe(self)
  457. }
  458. }
  459. if (self._multipart && self._multipart.chunked) {
  460. self._multipart.body.pipe(self)
  461. }
  462. if (self.body) {
  463. if (isstream(self.body)) {
  464. self.body.pipe(self)
  465. } else {
  466. setContentLength()
  467. if (Array.isArray(self.body)) {
  468. self.body.forEach(function (part) {
  469. self.write(part)
  470. })
  471. } else {
  472. self.write(self.body)
  473. }
  474. self.end()
  475. }
  476. } else if (self.requestBodyStream) {
  477. console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
  478. self.requestBodyStream.pipe(self)
  479. } else if (!self.src) {
  480. if (self._auth.hasAuth && !self._auth.sentAuth) {
  481. self.end()
  482. return
  483. }
  484. if (self.method !== 'GET' && typeof self.method !== 'undefined') {
  485. self.setHeader('content-length', 0)
  486. }
  487. self.end()
  488. }
  489. }
  490. if (self._form && !self.hasHeader('content-length')) {
  491. // Before ending the request, we had to compute the length of the whole form, asyncly
  492. self.setHeader(self._form.getHeaders(), true)
  493. self._form.getLength(function (err, length) {
  494. if (!err && !isNaN(length)) {
  495. self.setHeader('content-length', length)
  496. }
  497. end()
  498. })
  499. } else {
  500. end()
  501. }
  502. self.ntick = true
  503. })
  504. }
  505. Request.prototype.getNewAgent = function () {
  506. var self = this
  507. var Agent = self.agentClass
  508. var options = {}
  509. if (self.agentOptions) {
  510. for (var i in self.agentOptions) {
  511. options[i] = self.agentOptions[i]
  512. }
  513. }
  514. if (self.ca) {
  515. options.ca = self.ca
  516. }
  517. if (self.ciphers) {
  518. options.ciphers = self.ciphers
  519. }
  520. if (self.secureProtocol) {
  521. options.secureProtocol = self.secureProtocol
  522. }
  523. if (self.secureOptions) {
  524. options.secureOptions = self.secureOptions
  525. }
  526. if (typeof self.rejectUnauthorized !== 'undefined') {
  527. options.rejectUnauthorized = self.rejectUnauthorized
  528. }
  529. if (self.cert && self.key) {
  530. options.key = self.key
  531. options.cert = self.cert
  532. }
  533. if (self.pfx) {
  534. options.pfx = self.pfx
  535. }
  536. if (self.passphrase) {
  537. options.passphrase = self.passphrase
  538. }
  539. var poolKey = ''
  540. // different types of agents are in different pools
  541. if (Agent !== self.httpModule.Agent) {
  542. poolKey += Agent.name
  543. }
  544. // ca option is only relevant if proxy or destination are https
  545. var proxy = self.proxy
  546. if (typeof proxy === 'string') {
  547. proxy = url.parse(proxy)
  548. }
  549. var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
  550. if (isHttps) {
  551. if (options.ca) {
  552. if (poolKey) {
  553. poolKey += ':'
  554. }
  555. poolKey += options.ca
  556. }
  557. if (typeof options.rejectUnauthorized !== 'undefined') {
  558. if (poolKey) {
  559. poolKey += ':'
  560. }
  561. poolKey += options.rejectUnauthorized
  562. }
  563. if (options.cert) {
  564. if (poolKey) {
  565. poolKey += ':'
  566. }
  567. poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
  568. }
  569. if (options.pfx) {
  570. if (poolKey) {
  571. poolKey += ':'
  572. }
  573. poolKey += options.pfx.toString('ascii')
  574. }
  575. if (options.ciphers) {
  576. if (poolKey) {
  577. poolKey += ':'
  578. }
  579. poolKey += options.ciphers
  580. }
  581. if (options.secureProtocol) {
  582. if (poolKey) {
  583. poolKey += ':'
  584. }
  585. poolKey += options.secureProtocol
  586. }
  587. if (options.secureOptions) {
  588. if (poolKey) {
  589. poolKey += ':'
  590. }
  591. poolKey += options.secureOptions
  592. }
  593. }
  594. if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
  595. // not doing anything special. Use the globalAgent
  596. return self.httpModule.globalAgent
  597. }
  598. // we're using a stored agent. Make sure it's protocol-specific
  599. poolKey = self.uri.protocol + poolKey
  600. // generate a new agent for this setting if none yet exists
  601. if (!self.pool[poolKey]) {
  602. self.pool[poolKey] = new Agent(options)
  603. // properly set maxSockets on new agents
  604. if (self.pool.maxSockets) {
  605. self.pool[poolKey].maxSockets = self.pool.maxSockets
  606. }
  607. }
  608. return self.pool[poolKey]
  609. }
  610. Request.prototype.start = function () {
  611. // start() is called once we are ready to send the outgoing HTTP request.
  612. // this is usually called on the first write(), end() or on nextTick()
  613. var self = this
  614. if (self.timing) {
  615. // All timings will be relative to this request's startTime. In order to do this,
  616. // we need to capture the wall-clock start time (via Date), immediately followed
  617. // by the high-resolution timer (via now()). While these two won't be set
  618. // at the _exact_ same time, they should be close enough to be able to calculate
  619. // high-resolution, monotonically non-decreasing timestamps relative to startTime.
  620. var startTime = new Date().getTime()
  621. var startTimeNow = now()
  622. }
  623. if (self._aborted) {
  624. return
  625. }
  626. self._started = true
  627. self.method = self.method || 'GET'
  628. self.href = self.uri.href
  629. if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
  630. self.setHeader('content-length', self.src.stat.size)
  631. }
  632. if (self._aws) {
  633. self.aws(self._aws, true)
  634. }
  635. // We have a method named auth, which is completely different from the http.request
  636. // auth option. If we don't remove it, we're gonna have a bad time.
  637. var reqOptions = copy(self)
  638. delete reqOptions.auth
  639. debug('make request', self.uri.href)
  640. // node v6.8.0 now supports a `timeout` value in `http.request()`, but we
  641. // should delete it for now since we handle timeouts manually for better
  642. // consistency with node versions before v6.8.0
  643. delete reqOptions.timeout
  644. try {
  645. self.req = self.httpModule.request(reqOptions)
  646. } catch (err) {
  647. self.emit('error', err)
  648. return
  649. }
  650. if (self.timing) {
  651. self.startTime = startTime
  652. self.startTimeNow = startTimeNow
  653. // Timing values will all be relative to startTime (by comparing to startTimeNow
  654. // so we have an accurate clock)
  655. self.timings = {}
  656. }
  657. var timeout
  658. if (self.timeout && !self.timeoutTimer) {
  659. if (self.timeout < 0) {
  660. timeout = 0
  661. } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) {
  662. timeout = self.timeout
  663. }
  664. }
  665. self.req.on('response', self.onRequestResponse.bind(self))
  666. self.req.on('error', self.onRequestError.bind(self))
  667. self.req.on('drain', function() {
  668. self.emit('drain')
  669. })
  670. self.req.on('socket', function(socket) {
  671. // `._connecting` was the old property which was made public in node v6.1.0
  672. var isConnecting = socket._connecting || socket.connecting
  673. if (self.timing) {
  674. self.timings.socket = now() - self.startTimeNow
  675. if (isConnecting) {
  676. var onLookupTiming = function() {
  677. self.timings.lookup = now() - self.startTimeNow
  678. }
  679. var onConnectTiming = function() {
  680. self.timings.connect = now() - self.startTimeNow
  681. }
  682. socket.once('lookup', onLookupTiming)
  683. socket.once('connect', onConnectTiming)
  684. // clean up timing event listeners if needed on error
  685. self.req.once('error', function() {
  686. socket.removeListener('lookup', onLookupTiming)
  687. socket.removeListener('connect', onConnectTiming)
  688. })
  689. }
  690. }
  691. var setReqTimeout = function() {
  692. // This timeout sets the amount of time to wait *between* bytes sent
  693. // from the server once connected.
  694. //
  695. // In particular, it's useful for erroring if the server fails to send
  696. // data halfway through streaming a response.
  697. self.req.setTimeout(timeout, function () {
  698. if (self.req) {
  699. self.abort()
  700. var e = new Error('ESOCKETTIMEDOUT')
  701. e.code = 'ESOCKETTIMEDOUT'
  702. e.connect = false
  703. self.emit('error', e)
  704. }
  705. })
  706. }
  707. if (timeout !== undefined) {
  708. // Only start the connection timer if we're actually connecting a new
  709. // socket, otherwise if we're already connected (because this is a
  710. // keep-alive connection) do not bother. This is important since we won't
  711. // get a 'connect' event for an already connected socket.
  712. if (isConnecting) {
  713. var onReqSockConnect = function() {
  714. socket.removeListener('connect', onReqSockConnect)
  715. clearTimeout(self.timeoutTimer)
  716. self.timeoutTimer = null
  717. setReqTimeout()
  718. }
  719. socket.on('connect', onReqSockConnect)
  720. self.req.on('error', function(err) {
  721. socket.removeListener('connect', onReqSockConnect)
  722. })
  723. // Set a timeout in memory - this block will throw if the server takes more
  724. // than `timeout` to write the HTTP status and headers (corresponding to
  725. // the on('response') event on the client). NB: this measures wall-clock
  726. // time, not the time between bytes sent by the server.
  727. self.timeoutTimer = setTimeout(function () {
  728. socket.removeListener('connect', onReqSockConnect)
  729. self.abort()
  730. var e = new Error('ETIMEDOUT')
  731. e.code = 'ETIMEDOUT'
  732. e.connect = true
  733. self.emit('error', e)
  734. }, timeout)
  735. } else {
  736. // We're already connected
  737. setReqTimeout()
  738. }
  739. }
  740. self.emit('socket', socket)
  741. })
  742. self.emit('request', self.req)
  743. }
  744. Request.prototype.onRequestError = function (error) {
  745. var self = this
  746. if (self._aborted) {
  747. return
  748. }
  749. if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
  750. && self.agent.addRequestNoreuse) {
  751. self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
  752. self.start()
  753. self.req.end()
  754. return
  755. }
  756. if (self.timeout && self.timeoutTimer) {
  757. clearTimeout(self.timeoutTimer)
  758. self.timeoutTimer = null
  759. }
  760. self.emit('error', error)
  761. }
  762. Request.prototype.onRequestResponse = function (response) {
  763. var self = this
  764. if (self.timing) {
  765. self.timings.response = now() - self.startTimeNow
  766. }
  767. debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
  768. response.on('end', function() {
  769. if (self.timing) {
  770. self.timings.end = now() - self.startTimeNow
  771. response.timingStart = self.startTime
  772. // fill in the blanks for any periods that didn't trigger, such as
  773. // no lookup or connect due to keep alive
  774. if (!self.timings.socket) {
  775. self.timings.socket = 0
  776. }
  777. if (!self.timings.lookup) {
  778. self.timings.lookup = self.timings.socket
  779. }
  780. if (!self.timings.connect) {
  781. self.timings.connect = self.timings.lookup
  782. }
  783. if (!self.timings.response) {
  784. self.timings.response = self.timings.connect
  785. }
  786. debug('elapsed time', self.timings.end)
  787. // elapsedTime includes all redirects
  788. self.elapsedTime += Math.round(self.timings.end)
  789. // NOTE: elapsedTime is deprecated in favor of .timings
  790. response.elapsedTime = self.elapsedTime
  791. // timings is just for the final fetch
  792. response.timings = self.timings
  793. // pre-calculate phase timings as well
  794. response.timingPhases = {
  795. wait: self.timings.socket,
  796. dns: self.timings.lookup - self.timings.socket,
  797. tcp: self.timings.connect - self.timings.lookup,
  798. firstByte: self.timings.response - self.timings.connect,
  799. download: self.timings.end - self.timings.response,
  800. total: self.timings.end
  801. }
  802. }
  803. debug('response end', self.uri.href, response.statusCode, response.headers)
  804. })
  805. if (self._aborted) {
  806. debug('aborted', self.uri.href)
  807. response.resume()
  808. return
  809. }
  810. self.response = response
  811. response.request = self
  812. response.toJSON = responseToJSON
  813. // XXX This is different on 0.10, because SSL is strict by default
  814. if (self.httpModule === https &&
  815. self.strictSSL && (!response.hasOwnProperty('socket') ||
  816. !response.socket.authorized)) {
  817. debug('strict ssl error', self.uri.href)
  818. var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
  819. self.emit('error', new Error('SSL Error: ' + sslErr))
  820. return
  821. }
  822. // Save the original host before any redirect (if it changes, we need to
  823. // remove any authorization headers). Also remember the case of the header
  824. // name because lots of broken servers expect Host instead of host and we
  825. // want the caller to be able to specify this.
  826. self.originalHost = self.getHeader('host')
  827. if (!self.originalHostHeaderName) {
  828. self.originalHostHeaderName = self.hasHeader('host')
  829. }
  830. if (self.setHost) {
  831. self.removeHeader('host')
  832. }
  833. if (self.timeout && self.timeoutTimer) {
  834. clearTimeout(self.timeoutTimer)
  835. self.timeoutTimer = null
  836. }
  837. var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
  838. var addCookie = function (cookie) {
  839. //set the cookie if it's domain in the href's domain.
  840. try {
  841. targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
  842. } catch (e) {
  843. self.emit('error', e)
  844. }
  845. }
  846. response.caseless = caseless(response.headers)
  847. if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
  848. var headerName = response.caseless.has('set-cookie')
  849. if (Array.isArray(response.headers[headerName])) {
  850. response.headers[headerName].forEach(addCookie)
  851. } else {
  852. addCookie(response.headers[headerName])
  853. }
  854. }
  855. if (self._redirect.onResponse(response)) {
  856. return // Ignore the rest of the response
  857. } else {
  858. // Be a good stream and emit end when the response is finished.
  859. // Hack to emit end on close because of a core bug that never fires end
  860. response.on('close', function () {
  861. if (!self._ended) {
  862. self.response.emit('end')
  863. }
  864. })
  865. response.once('end', function () {
  866. self._ended = true
  867. })
  868. var noBody = function (code) {
  869. return (
  870. self.method === 'HEAD'
  871. // Informational
  872. || (code >= 100 && code < 200)
  873. // No Content
  874. || code === 204
  875. // Not Modified
  876. || code === 304
  877. )
  878. }
  879. var responseContent
  880. if (self.gzip && !noBody(response.statusCode)) {
  881. var contentEncoding = response.headers['content-encoding'] || 'identity'
  882. contentEncoding = contentEncoding.trim().toLowerCase()
  883. // Be more lenient with decoding compressed responses, since (very rarely)
  884. // servers send slightly invalid gzip responses that are still accepted
  885. // by common browsers.
  886. // Always using Z_SYNC_FLUSH is what cURL does.
  887. var zlibOptions = {
  888. flush: zlib.Z_SYNC_FLUSH
  889. , finishFlush: zlib.Z_SYNC_FLUSH
  890. }
  891. if (contentEncoding === 'gzip') {
  892. responseContent = zlib.createGunzip(zlibOptions)
  893. response.pipe(responseContent)
  894. } else if (contentEncoding === 'deflate') {
  895. responseContent = zlib.createInflate(zlibOptions)
  896. response.pipe(responseContent)
  897. } else {
  898. // Since previous versions didn't check for Content-Encoding header,
  899. // ignore any invalid values to preserve backwards-compatibility
  900. if (contentEncoding !== 'identity') {
  901. debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
  902. }
  903. responseContent = response
  904. }
  905. } else {
  906. responseContent = response
  907. }
  908. if (self.encoding) {
  909. if (self.dests.length !== 0) {
  910. console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
  911. } else if (responseContent.setEncoding) {
  912. responseContent.setEncoding(self.encoding)
  913. } else {
  914. // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with
  915. // zlib streams.
  916. // If/When support for 0.9.4 is dropped, this should be unnecessary.
  917. responseContent = responseContent.pipe(stringstream(self.encoding))
  918. }
  919. }
  920. if (self._paused) {
  921. responseContent.pause()
  922. }
  923. self.responseContent = responseContent
  924. self.emit('response', response)
  925. self.dests.forEach(function (dest) {
  926. self.pipeDest(dest)
  927. })
  928. responseContent.on('data', function (chunk) {
  929. if (self.timing && !self.responseStarted) {
  930. self.responseStartTime = (new Date()).getTime()
  931. // NOTE: responseStartTime is deprecated in favor of .timings
  932. response.responseStartTime = self.responseStartTime
  933. }
  934. self._destdata = true
  935. self.emit('data', chunk)
  936. })
  937. responseContent.once('end', function (chunk) {
  938. self.emit('end', chunk)
  939. })
  940. responseContent.on('error', function (error) {
  941. self.emit('error', error)
  942. })
  943. responseContent.on('close', function () {self.emit('close')})
  944. if (self.callback) {
  945. self.readResponseBody(response)
  946. }
  947. //if no callback
  948. else {
  949. self.on('end', function () {
  950. if (self._aborted) {
  951. debug('aborted', self.uri.href)
  952. return
  953. }
  954. self.emit('complete', response)
  955. })
  956. }
  957. }
  958. debug('finish init function', self.uri.href)
  959. }
  960. Request.prototype.readResponseBody = function (response) {
  961. var self = this
  962. debug('reading response\'s body')
  963. var buffers = []
  964. , bufferLength = 0
  965. , strings = []
  966. self.on('data', function (chunk) {
  967. if (!Buffer.isBuffer(chunk)) {
  968. strings.push(chunk)
  969. } else if (chunk.length) {
  970. bufferLength += chunk.length
  971. buffers.push(chunk)
  972. }
  973. })
  974. self.on('end', function () {
  975. debug('end event', self.uri.href)
  976. if (self._aborted) {
  977. debug('aborted', self.uri.href)
  978. // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request.
  979. // This can lead to leaky behavior if the user retains a reference to the request object.
  980. buffers = []
  981. bufferLength = 0
  982. return
  983. }
  984. if (bufferLength) {
  985. debug('has body', self.uri.href, bufferLength)
  986. response.body = Buffer.concat(buffers, bufferLength)
  987. if (self.encoding !== null) {
  988. response.body = response.body.toString(self.encoding)
  989. }
  990. // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
  991. // This can lead to leaky behavior if the user retains a reference to the request object.
  992. buffers = []
  993. bufferLength = 0
  994. } else if (strings.length) {
  995. // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
  996. // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
  997. if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
  998. strings[0] = strings[0].substring(1)
  999. }
  1000. response.body = strings.join('')
  1001. }
  1002. if (self._json) {
  1003. try {
  1004. response.body = JSON.parse(response.body, self._jsonReviver)
  1005. } catch (e) {
  1006. debug('invalid JSON received', self.uri.href)
  1007. }
  1008. }
  1009. debug('emitting complete', self.uri.href)
  1010. if (typeof response.body === 'undefined' && !self._json) {
  1011. response.body = self.encoding === null ? Buffer.alloc(0) : ''
  1012. }
  1013. self.emit('complete', response, response.body)
  1014. })
  1015. }
  1016. Request.prototype.abort = function () {
  1017. var self = this
  1018. self._aborted = true
  1019. if (self.req) {
  1020. self.req.abort()
  1021. }
  1022. else if (self.response) {
  1023. self.response.destroy()
  1024. }
  1025. self.emit('abort')
  1026. }
  1027. Request.prototype.pipeDest = function (dest) {
  1028. var self = this
  1029. var response = self.response
  1030. // Called after the response is received
  1031. if (dest.headers && !dest.headersSent) {
  1032. if (response.caseless.has('content-type')) {
  1033. var ctname = response.caseless.has('content-type')
  1034. if (dest.setHeader) {
  1035. dest.setHeader(ctname, response.headers[ctname])
  1036. }
  1037. else {
  1038. dest.headers[ctname] = response.headers[ctname]
  1039. }
  1040. }
  1041. if (response.caseless.has('content-length')) {
  1042. var clname = response.caseless.has('content-length')
  1043. if (dest.setHeader) {
  1044. dest.setHeader(clname, response.headers[clname])
  1045. } else {
  1046. dest.headers[clname] = response.headers[clname]
  1047. }
  1048. }
  1049. }
  1050. if (dest.setHeader && !dest.headersSent) {
  1051. for (var i in response.headers) {
  1052. // If the response content is being decoded, the Content-Encoding header
  1053. // of the response doesn't represent the piped content, so don't pass it.
  1054. if (!self.gzip || i !== 'content-encoding') {
  1055. dest.setHeader(i, response.headers[i])
  1056. }
  1057. }
  1058. dest.statusCode = response.statusCode
  1059. }
  1060. if (self.pipefilter) {
  1061. self.pipefilter(response, dest)
  1062. }
  1063. }
  1064. Request.prototype.qs = function (q, clobber) {
  1065. var self = this
  1066. var base
  1067. if (!clobber && self.uri.query) {
  1068. base = self._qs.parse(self.uri.query)
  1069. } else {
  1070. base = {}
  1071. }
  1072. for (var i in q) {
  1073. base[i] = q[i]
  1074. }
  1075. var qs = self._qs.stringify(base)
  1076. if (qs === '') {
  1077. return self
  1078. }
  1079. self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
  1080. self.url = self.uri
  1081. self.path = self.uri.path
  1082. if (self.uri.host === 'unix') {
  1083. self.enableUnixSocket()
  1084. }
  1085. return self
  1086. }
  1087. Request.prototype.form = function (form) {
  1088. var self = this
  1089. if (form) {
  1090. if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
  1091. self.setHeader('content-type', 'application/x-www-form-urlencoded')
  1092. }
  1093. self.body = (typeof form === 'string')
  1094. ? self._qs.rfc3986(form.toString('utf8'))
  1095. : self._qs.stringify(form).toString('utf8')
  1096. return self
  1097. }
  1098. // create form-data object
  1099. self._form = new FormData()
  1100. self._form.on('error', function(err) {
  1101. err.message = 'form-data: ' + err.message
  1102. self.emit('error', err)
  1103. self.abort()
  1104. })
  1105. return self._form
  1106. }
  1107. Request.prototype.multipart = function (multipart) {
  1108. var self = this
  1109. self._multipart.onRequest(multipart)
  1110. if (!self._multipart.chunked) {
  1111. self.body = self._multipart.body
  1112. }
  1113. return self
  1114. }
  1115. Request.prototype.json = function (val) {
  1116. var self = this
  1117. if (!self.hasHeader('accept')) {
  1118. self.setHeader('accept', 'application/json')
  1119. }
  1120. if (typeof self.jsonReplacer === 'function') {
  1121. self._jsonReplacer = self.jsonReplacer
  1122. }
  1123. self._json = true
  1124. if (typeof val === 'boolean') {
  1125. if (self.body !== undefined) {
  1126. if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
  1127. self.body = safeStringify(self.body, self._jsonReplacer)
  1128. } else {
  1129. self.body = self._qs.rfc3986(self.body)
  1130. }
  1131. if (!self.hasHeader('content-type')) {
  1132. self.setHeader('content-type', 'application/json')
  1133. }
  1134. }
  1135. } else {
  1136. self.body = safeStringify(val, self._jsonReplacer)
  1137. if (!self.hasHeader('content-type')) {
  1138. self.setHeader('content-type', 'application/json')
  1139. }
  1140. }
  1141. if (typeof self.jsonReviver === 'function') {
  1142. self._jsonReviver = self.jsonReviver
  1143. }
  1144. return self
  1145. }
  1146. Request.prototype.getHeader = function (name, headers) {
  1147. var self = this
  1148. var result, re, match
  1149. if (!headers) {
  1150. headers = self.headers
  1151. }
  1152. Object.keys(headers).forEach(function (key) {
  1153. if (key.length !== name.length) {
  1154. return
  1155. }
  1156. re = new RegExp(name, 'i')
  1157. match = key.match(re)
  1158. if (match) {
  1159. result = headers[key]
  1160. }
  1161. })
  1162. return result
  1163. }
  1164. Request.prototype.enableUnixSocket = function () {
  1165. // Get the socket & request paths from the URL
  1166. var unixParts = this.uri.path.split(':')
  1167. , host = unixParts[0]
  1168. , path = unixParts[1]
  1169. // Apply unix properties to request
  1170. this.socketPath = host
  1171. this.uri.pathname = path
  1172. this.uri.path = path
  1173. this.uri.host = host
  1174. this.uri.hostname = host
  1175. this.uri.isUnix = true
  1176. }
  1177. Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
  1178. var self = this
  1179. self._auth.onRequest(user, pass, sendImmediately, bearer)
  1180. return self
  1181. }
  1182. Request.prototype.aws = function (opts, now) {
  1183. var self = this
  1184. if (!now) {
  1185. self._aws = opts
  1186. return self
  1187. }
  1188. if (opts.sign_version == 4 || opts.sign_version == '4') {
  1189. // use aws4
  1190. var options = {
  1191. host: self.uri.host,
  1192. path: self.uri.path,
  1193. method: self.method,
  1194. headers: {
  1195. 'content-type': self.getHeader('content-type') || ''
  1196. },
  1197. body: self.body
  1198. }
  1199. var signRes = aws4.sign(options, {
  1200. accessKeyId: opts.key,
  1201. secretAccessKey: opts.secret,
  1202. sessionToken: opts.session
  1203. })
  1204. self.setHeader('authorization', signRes.headers.Authorization)
  1205. self.setHeader('x-amz-date', signRes.headers['X-Amz-Date'])
  1206. if (signRes.headers['X-Amz-Security-Token']) {
  1207. self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
  1208. }
  1209. }
  1210. else {
  1211. // default: use aws-sign2
  1212. var date = new Date()
  1213. self.setHeader('date', date.toUTCString())
  1214. var auth =
  1215. { key: opts.key
  1216. , secret: opts.secret
  1217. , verb: self.method.toUpperCase()
  1218. , date: date
  1219. , contentType: self.getHeader('content-type') || ''
  1220. , md5: self.getHeader('content-md5') || ''
  1221. , amazonHeaders: aws2.canonicalizeHeaders(self.headers)
  1222. }
  1223. var path = self.uri.path
  1224. if (opts.bucket && path) {
  1225. auth.resource = '/' + opts.bucket + path
  1226. } else if (opts.bucket && !path) {
  1227. auth.resource = '/' + opts.bucket
  1228. } else if (!opts.bucket && path) {
  1229. auth.resource = path
  1230. } else if (!opts.bucket && !path) {
  1231. auth.resource = '/'
  1232. }
  1233. auth.resource = aws2.canonicalizeResource(auth.resource)
  1234. self.setHeader('authorization', aws2.authorization(auth))
  1235. }
  1236. return self
  1237. }
  1238. Request.prototype.httpSignature = function (opts) {
  1239. var self = this
  1240. httpSignature.signRequest({
  1241. getHeader: function(header) {
  1242. return self.getHeader(header, self.headers)
  1243. },
  1244. setHeader: function(header, value) {
  1245. self.setHeader(header, value)
  1246. },
  1247. method: self.method,
  1248. path: self.path
  1249. }, opts)
  1250. debug('httpSignature authorization', self.getHeader('authorization'))
  1251. return self
  1252. }
  1253. Request.prototype.hawk = function (opts) {
  1254. var self = this
  1255. self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field)
  1256. }
  1257. Request.prototype.oauth = function (_oauth) {
  1258. var self = this
  1259. self._oauth.onRequest(_oauth)
  1260. return self
  1261. }
  1262. Request.prototype.jar = function (jar) {
  1263. var self = this
  1264. var cookies
  1265. if (self._redirect.redirectsFollowed === 0) {
  1266. self.originalCookieHeader = self.getHeader('cookie')
  1267. }
  1268. if (!jar) {
  1269. // disable cookies
  1270. cookies = false
  1271. self._disableCookies = true
  1272. } else {
  1273. var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
  1274. var urihref = self.uri.href
  1275. //fetch cookie in the Specified host
  1276. if (targetCookieJar) {
  1277. cookies = targetCookieJar.getCookieString(urihref)
  1278. }
  1279. }
  1280. //if need cookie and cookie is not empty
  1281. if (cookies && cookies.length) {
  1282. if (self.originalCookieHeader) {
  1283. // Don't overwrite existing Cookie header
  1284. self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
  1285. } else {
  1286. self.setHeader('cookie', cookies)
  1287. }
  1288. }
  1289. self._jar = jar
  1290. return self
  1291. }
  1292. // Stream API
  1293. Request.prototype.pipe = function (dest, opts) {
  1294. var self = this
  1295. if (self.response) {
  1296. if (self._destdata) {
  1297. self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
  1298. } else if (self._ended) {
  1299. self.emit('error', new Error('You cannot pipe after the response has been ended.'))
  1300. } else {
  1301. stream.Stream.prototype.pipe.call(self, dest, opts)
  1302. self.pipeDest(dest)
  1303. return dest
  1304. }
  1305. } else {
  1306. self.dests.push(dest)
  1307. stream.Stream.prototype.pipe.call(self, dest, opts)
  1308. return dest
  1309. }
  1310. }
  1311. Request.prototype.write = function () {
  1312. var self = this
  1313. if (self._aborted) {return}
  1314. if (!self._started) {
  1315. self.start()
  1316. }
  1317. if (self.req) {
  1318. return self.req.write.apply(self.req, arguments)
  1319. }
  1320. }
  1321. Request.prototype.end = function (chunk) {
  1322. var self = this
  1323. if (self._aborted) {return}
  1324. if (chunk) {
  1325. self.write(chunk)
  1326. }
  1327. if (!self._started) {
  1328. self.start()
  1329. }
  1330. if (self.req) {
  1331. self.req.end()
  1332. }
  1333. }
  1334. Request.prototype.pause = function () {
  1335. var self = this
  1336. if (!self.responseContent) {
  1337. self._paused = true
  1338. } else {
  1339. self.responseContent.pause.apply(self.responseContent, arguments)
  1340. }
  1341. }
  1342. Request.prototype.resume = function () {
  1343. var self = this
  1344. if (!self.responseContent) {
  1345. self._paused = false
  1346. } else {
  1347. self.responseContent.resume.apply(self.responseContent, arguments)
  1348. }
  1349. }
  1350. Request.prototype.destroy = function () {
  1351. var self = this
  1352. if (!self._ended) {
  1353. self.end()
  1354. } else if (self.response) {
  1355. self.response.destroy()
  1356. }
  1357. }
  1358. Request.defaultProxyHeaderWhiteList =
  1359. Tunnel.defaultProxyHeaderWhiteList.slice()
  1360. Request.defaultProxyHeaderExclusiveList =
  1361. Tunnel.defaultProxyHeaderExclusiveList.slice()
  1362. // Exports
  1363. Request.prototype.toJSON = requestToJSON
  1364. module.exports = Request