request.js 43 KB

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