request.js 41 KB

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