request.js 43 KB

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