request.js 43 KB

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