request.js 39 KB

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