request.js 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. var optional = require('./lib/optional')
  2. , http = require('http')
  3. , https = optional('https')
  4. , tls = optional('tls')
  5. , url = require('url')
  6. , util = require('util')
  7. , stream = require('stream')
  8. , qs = require('qs')
  9. , querystring = require('querystring')
  10. , crypto = require('crypto')
  11. , zlib = require('zlib')
  12. , oauth = optional('oauth-sign')
  13. , hawk = optional('hawk')
  14. , aws = optional('aws-sign2')
  15. , httpSignature = optional('http-signature')
  16. , uuid = require('node-uuid')
  17. , mime = require('mime-types')
  18. , tunnel = optional('tunnel-agent')
  19. , _safeStringify = require('json-stringify-safe')
  20. , stringstream = optional('stringstream')
  21. , ForeverAgent = require('forever-agent')
  22. , FormData = optional('form-data')
  23. , cookies = require('./lib/cookies')
  24. , globalCookieJar = cookies.jar()
  25. , copy = require('./lib/copy')
  26. , debug = require('./lib/debug')
  27. , getSafe = require('./lib/getSafe')
  28. , net = require('net')
  29. ;
  30. function safeStringify (obj) {
  31. var ret
  32. try { ret = JSON.stringify(obj) }
  33. catch (e) { ret = _safeStringify(obj) }
  34. return ret
  35. }
  36. var globalPool = {}
  37. var isUrl = /^https?:|^unix:/
  38. // Hacky fix for pre-0.4.4 https
  39. if (https && !https.Agent) {
  40. https.Agent = function (options) {
  41. http.Agent.call(this, options)
  42. }
  43. util.inherits(https.Agent, http.Agent)
  44. https.Agent.prototype._getConnection = function (host, port, cb) {
  45. var s = tls.connect(port, host, this.options, function () {
  46. // do other checks here?
  47. if (cb) cb()
  48. })
  49. return s
  50. }
  51. }
  52. function isReadStream (rs) {
  53. return rs.readable && rs.path && rs.mode;
  54. }
  55. function toBase64 (str) {
  56. return (new Buffer(str || "", "ascii")).toString("base64")
  57. }
  58. function md5 (str) {
  59. return crypto.createHash('md5').update(str).digest('hex')
  60. }
  61. function Request (options) {
  62. stream.Stream.call(this)
  63. this.readable = true
  64. this.writable = true
  65. if (typeof options === 'string') {
  66. options = {uri:options}
  67. }
  68. var reserved = Object.keys(Request.prototype)
  69. for (var i in options) {
  70. if (reserved.indexOf(i) === -1) {
  71. this[i] = options[i]
  72. } else {
  73. if (typeof options[i] === 'function') {
  74. delete options[i]
  75. }
  76. }
  77. }
  78. if (options.method) {
  79. this.explicitMethod = true
  80. }
  81. this.canTunnel = options.tunnel !== false && tunnel;
  82. this.init(options)
  83. }
  84. util.inherits(Request, stream.Stream)
  85. Request.prototype.init = function (options) {
  86. // init() contains all the code to setup the request object.
  87. // the actual outgoing request is not started until start() is called
  88. // this function is called from both the constructor and on redirect.
  89. var self = this
  90. if (!options) options = {}
  91. if (!self.method) self.method = options.method || 'GET'
  92. self.localAddress = options.localAddress
  93. debug(options)
  94. if (!self.pool && self.pool !== false) self.pool = globalPool
  95. self.dests = self.dests || []
  96. self.__isRequestRequest = true
  97. // Protect against double callback
  98. if (!self._callback && self.callback) {
  99. self._callback = self.callback
  100. self.callback = function () {
  101. if (self._callbackCalled) return // Print a warning maybe?
  102. self._callbackCalled = true
  103. self._callback.apply(self, arguments)
  104. }
  105. self.on('error', self.callback.bind())
  106. self.on('complete', self.callback.bind(self, null))
  107. }
  108. if (self.url && !self.uri) {
  109. // People use this property instead all the time so why not just support it.
  110. self.uri = self.url
  111. delete self.url
  112. }
  113. if (!self.uri) {
  114. // this will throw if unhandled but is handleable when in a redirect
  115. return self.emit('error', new Error("options.uri is a required argument"))
  116. } else {
  117. if (typeof self.uri == "string") self.uri = url.parse(self.uri)
  118. }
  119. if (self.strictSSL === false) {
  120. self.rejectUnauthorized = false
  121. }
  122. if(!self.hasOwnProperty('proxy')) {
  123. // check for HTTP(S)_PROXY environment variables
  124. if(self.uri.protocol == "http:") {
  125. self.proxy = process.env.HTTP_PROXY || process.env.http_proxy || null;
  126. } else if(self.uri.protocol == "https:") {
  127. self.proxy = process.env.HTTPS_PROXY || process.env.https_proxy ||
  128. process.env.HTTP_PROXY || process.env.http_proxy || null;
  129. }
  130. }
  131. if (self.proxy) {
  132. if (typeof self.proxy == 'string') self.proxy = url.parse(self.proxy)
  133. // do the HTTP CONNECT dance using koichik/node-tunnel
  134. if (http.globalAgent && self.uri.protocol === "https:" && self.canTunnel) {
  135. var tunnelFn = self.proxy.protocol === "http:"
  136. ? tunnel.httpsOverHttp : tunnel.httpsOverHttps
  137. var tunnelOptions = { proxy: { host: self.proxy.hostname
  138. , port: +self.proxy.port
  139. , proxyAuth: self.proxy.auth
  140. , headers: { Host: self.uri.hostname + ':' +
  141. (self.uri.port || self.uri.protocol === 'https:' ? 443 : 80) }}
  142. , rejectUnauthorized: self.rejectUnauthorized
  143. , ca: this.ca
  144. , cert:this.cert
  145. , key: this.key}
  146. self.agent = tunnelFn(tunnelOptions)
  147. self.tunnel = true
  148. }
  149. }
  150. if (!self.uri.pathname) {self.uri.pathname = '/'}
  151. if (!self.uri.host && !self.protocol=='unix:') {
  152. // Invalid URI: it may generate lot of bad errors, like "TypeError: Cannot call method 'indexOf' of undefined" in CookieJar
  153. // Detect and reject it as soon as possible
  154. var faultyUri = url.format(self.uri)
  155. var message = 'Invalid URI "' + faultyUri + '"'
  156. if (Object.keys(options).length === 0) {
  157. // No option ? This can be the sign of a redirect
  158. // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
  159. // they should be warned that it can be caused by a redirection (can save some hair)
  160. message += '. This can be caused by a crappy redirection.'
  161. }
  162. self.emit('error', new Error(message))
  163. return // This error was fatal
  164. }
  165. self._redirectsFollowed = self._redirectsFollowed || 0
  166. self.maxRedirects = (self.maxRedirects !== undefined) ? self.maxRedirects : 10
  167. self.followRedirect = (self.followRedirect !== undefined) ? self.followRedirect : true
  168. self.followAllRedirects = (self.followAllRedirects !== undefined) ? self.followAllRedirects : false
  169. if (self.followRedirect || self.followAllRedirects)
  170. self.redirects = self.redirects || []
  171. self.headers = self.headers ? copy(self.headers) : {}
  172. self.setHost = false
  173. if (!self.hasHeader('host')) {
  174. self.setHeader('host', self.uri.hostname)
  175. if (self.uri.port) {
  176. if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') &&
  177. !(self.uri.port === 443 && self.uri.protocol === 'https:') )
  178. self.setHeader('host', self.getHeader('host') + (':'+self.uri.port) )
  179. }
  180. self.setHost = true
  181. }
  182. self.jar(self._jar || options.jar)
  183. if (!self.uri.port) {
  184. if (self.uri.protocol == 'http:') {self.uri.port = 80}
  185. else if (self.uri.protocol == 'https:') {self.uri.port = 443}
  186. }
  187. if (self.proxy && !self.tunnel) {
  188. self.port = self.proxy.port
  189. self.host = self.proxy.hostname
  190. } else {
  191. self.port = self.uri.port
  192. self.host = self.uri.hostname
  193. }
  194. self.clientErrorHandler = function (error) {
  195. if (self._aborted) return
  196. if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
  197. && self.agent.addRequestNoreuse) {
  198. self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
  199. self.start()
  200. self.req.end()
  201. return
  202. }
  203. if (self.timeout && self.timeoutTimer) {
  204. clearTimeout(self.timeoutTimer)
  205. self.timeoutTimer = null
  206. }
  207. self.emit('error', error)
  208. }
  209. self._parserErrorHandler = function (error) {
  210. if (this.res) {
  211. if (this.res.request) {
  212. this.res.request.emit('error', error)
  213. } else {
  214. this.res.emit('error', error)
  215. }
  216. } else {
  217. this._httpMessage.emit('error', error)
  218. }
  219. }
  220. self._buildRequest = function(){
  221. var self = this;
  222. if (options.form) {
  223. self.form(options.form)
  224. }
  225. if (options.qs) self.qs(options.qs)
  226. if (self.uri.path) {
  227. self.path = self.uri.path
  228. } else {
  229. self.path = self.uri.pathname + (self.uri.search || "")
  230. }
  231. if (self.path.length === 0) self.path = '/'
  232. // Auth must happen last in case signing is dependent on other headers
  233. if (options.oauth) {
  234. self.oauth(options.oauth)
  235. }
  236. if (options.aws) {
  237. self.aws(options.aws)
  238. }
  239. if (options.hawk) {
  240. self.hawk(options.hawk)
  241. }
  242. if (options.httpSignature) {
  243. self.httpSignature(options.httpSignature)
  244. }
  245. if (options.auth) {
  246. if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) options.auth.user = options.auth.username
  247. if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) options.auth.pass = options.auth.password
  248. self.auth(
  249. options.auth.user,
  250. options.auth.pass,
  251. options.auth.sendImmediately,
  252. options.auth.bearer
  253. )
  254. }
  255. if (self.gzip && !self.hasHeader('accept-encoding')) {
  256. self.setHeader('accept-encoding', 'gzip')
  257. }
  258. if (self.uri.auth && !self.hasHeader('authorization')) {
  259. var authPieces = self.uri.auth.split(':').map(function(item){ return querystring.unescape(item) })
  260. self.auth(authPieces[0], authPieces.slice(1).join(':'), true)
  261. }
  262. if (self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization') && !self.tunnel) {
  263. self.setHeader('proxy-authorization', "Basic " + toBase64(self.proxy.auth.split(':').map(function(item){ return querystring.unescape(item)}).join(':')))
  264. }
  265. if (self.proxy && !self.tunnel) self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
  266. if (options.json) {
  267. self.json(options.json)
  268. } else if (options.multipart) {
  269. self.boundary = uuid()
  270. self.multipart(options.multipart)
  271. }
  272. if (self.body) {
  273. var length = 0
  274. if (!Buffer.isBuffer(self.body)) {
  275. if (Array.isArray(self.body)) {
  276. for (var i = 0; i < self.body.length; i++) {
  277. length += self.body[i].length
  278. }
  279. } else {
  280. self.body = new Buffer(self.body)
  281. length = self.body.length
  282. }
  283. } else {
  284. length = self.body.length
  285. }
  286. if (length) {
  287. if (!self.hasHeader('content-length')) self.setHeader('content-length', length)
  288. } else {
  289. throw new Error('Argument error, options.body.')
  290. }
  291. }
  292. var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
  293. , defaultModules = {'http:':http, 'https:':https, 'unix:':http}
  294. , httpModules = self.httpModules || {}
  295. ;
  296. self.httpModule = httpModules[protocol] || defaultModules[protocol]
  297. if (!self.httpModule) return this.emit('error', new Error("Invalid protocol: " + protocol))
  298. if (options.ca) self.ca = options.ca
  299. if (!self.agent) {
  300. if (options.agentOptions) self.agentOptions = options.agentOptions
  301. if (options.agentClass) {
  302. self.agentClass = options.agentClass
  303. } else if (options.forever) {
  304. self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
  305. } else {
  306. self.agentClass = self.httpModule.Agent
  307. }
  308. }
  309. if (self.pool === false) {
  310. self.agent = false
  311. } else {
  312. self.agent = self.agent || self.getAgent()
  313. if (self.maxSockets) {
  314. // Don't use our pooling if node has the refactored client
  315. self.agent.maxSockets = self.maxSockets
  316. }
  317. if (self.pool.maxSockets) {
  318. // Don't use our pooling if node has the refactored client
  319. self.agent.maxSockets = self.pool.maxSockets
  320. }
  321. }
  322. self.on('pipe', function (src) {
  323. if (self.ntick && self._started) throw new Error("You cannot pipe to this stream after the outbound request has started.")
  324. self.src = src
  325. if (isReadStream(src)) {
  326. if (!self.hasHeader('content-type')) self.setHeader('content-type', mime.lookup(src.path))
  327. } else {
  328. if (src.headers) {
  329. for (var i in src.headers) {
  330. if (!self.hasHeader(i)) {
  331. self.setHeader(i, src.headers[i])
  332. }
  333. }
  334. }
  335. if (self._json && !self.hasHeader('content-type'))
  336. self.setHeader('content-type', 'application/json')
  337. if (src.method && !self.explicitMethod) {
  338. self.method = src.method
  339. }
  340. }
  341. // self.on('pipe', function () {
  342. // console.error("You have already piped to this stream. Pipeing twice is likely to break the request.")
  343. // })
  344. })
  345. process.nextTick(function () {
  346. if (self._aborted) return
  347. var end = function () {
  348. if (self._form) {
  349. self._form.pipe(self)
  350. }
  351. if (self.body) {
  352. if (Array.isArray(self.body)) {
  353. self.body.forEach(function (part) {
  354. self.write(part)
  355. })
  356. } else {
  357. self.write(self.body)
  358. }
  359. self.end()
  360. } else if (self.requestBodyStream) {
  361. console.warn("options.requestBodyStream is deprecated, please pass the request object to stream.pipe.")
  362. self.requestBodyStream.pipe(self)
  363. } else if (!self.src) {
  364. if (self.method !== 'GET' && typeof self.method !== 'undefined') {
  365. self.setHeader('content-length', 0)
  366. }
  367. self.end()
  368. }
  369. }
  370. if (self._form && !self.hasHeader('content-length')) {
  371. // Before ending the request, we had to compute the length of the whole form, asyncly
  372. self.setHeaders(self._form.getHeaders())
  373. self._form.getLength(function (err, length) {
  374. if (!err) {
  375. self.setHeader('content-length', length)
  376. }
  377. end()
  378. })
  379. } else {
  380. end()
  381. }
  382. self.ntick = true
  383. })
  384. } // End _buildRequest
  385. self._handleUnixSocketURI = function(self){
  386. // Parse URI and extract a socket path (tested as a valid socket using net.connect), and a http style path suffix
  387. // Thus http requests can be made to a socket using the uri unix://tmp/my.socket/urlpath
  388. // and a request for '/urlpath' will be sent to the unix socket at /tmp/my.socket
  389. self.unixsocket = true;
  390. var full_path = self.uri.href.replace(self.uri.protocol+'/', '');
  391. var lookup = full_path.split('/');
  392. var error_connecting = true;
  393. var lookup_table = {};
  394. do { lookup_table[lookup.join('/')]={} } while(lookup.pop())
  395. for (r in lookup_table){
  396. try_next(r);
  397. }
  398. function try_next(table_row){
  399. var client = net.connect( table_row );
  400. client.path = table_row
  401. client.on('error', function(){ lookup_table[this.path].error_connecting=true; this.end(); });
  402. client.on('connect', function(){ lookup_table[this.path].error_connecting=false; this.end(); });
  403. table_row.client = client;
  404. }
  405. wait_for_socket_response();
  406. response_counter = 0;
  407. function wait_for_socket_response(){
  408. var detach;
  409. if('undefined' == typeof setImmediate ) detach = process.nextTick
  410. else detach = setImmediate;
  411. detach(function(){
  412. // counter to prevent infinite blocking waiting for an open socket to be found.
  413. response_counter++;
  414. var trying = false;
  415. for (r in lookup_table){
  416. //console.log(r, lookup_table[r], lookup_table[r].error_connecting)
  417. if('undefined' == typeof lookup_table[r].error_connecting)
  418. trying = true;
  419. }
  420. if(trying && response_counter<1000)
  421. wait_for_socket_response()
  422. else
  423. set_socket_properties();
  424. })
  425. }
  426. function set_socket_properties(){
  427. var host;
  428. for (r in lookup_table){
  429. if(lookup_table[r].error_connecting === false){
  430. host = r
  431. }
  432. }
  433. if(!host){
  434. self.emit('error', new Error("Failed to connect to any socket in "+full_path))
  435. }
  436. var path = full_path.replace(host, '')
  437. self.socketPath = host
  438. self.uri.pathname = path
  439. self.uri.href = path
  440. self.uri.path = path
  441. self.host = ''
  442. self.hostname = ''
  443. delete self.host
  444. delete self.hostname
  445. self._buildRequest();
  446. }
  447. }
  448. // Intercept UNIX protocol requests to change properties to match socket
  449. if(/^unix:/.test(self.uri.protocol)){
  450. self._handleUnixSocketURI(self);
  451. } else {
  452. self._buildRequest();
  453. }
  454. }
  455. // Must call this when following a redirect from https to http or vice versa
  456. // Attempts to keep everything as identical as possible, but update the
  457. // httpModule, Tunneling agent, and/or Forever Agent in use.
  458. Request.prototype._updateProtocol = function () {
  459. var self = this
  460. var protocol = self.uri.protocol
  461. if (protocol === 'https:') {
  462. // previously was doing http, now doing https
  463. // if it's https, then we might need to tunnel now.
  464. if (self.proxy && self.canTunnel) {
  465. self.tunnel = true
  466. var tunnelFn = self.proxy.protocol === 'http:'
  467. ? tunnel.httpsOverHttp : tunnel.httpsOverHttps
  468. var tunnelOptions = { proxy: { host: self.proxy.hostname
  469. , port: +self.proxy.port
  470. , proxyAuth: self.proxy.auth }
  471. , rejectUnauthorized: self.rejectUnauthorized
  472. , ca: self.ca }
  473. self.agent = tunnelFn(tunnelOptions)
  474. return
  475. }
  476. self.httpModule = https
  477. switch (self.agentClass) {
  478. case ForeverAgent:
  479. self.agentClass = ForeverAgent.SSL
  480. break
  481. case http.Agent:
  482. self.agentClass = https.Agent
  483. break
  484. default:
  485. // nothing we can do. Just hope for the best.
  486. return
  487. }
  488. // if there's an agent, we need to get a new one.
  489. if (self.agent) self.agent = self.getAgent()
  490. } else {
  491. // previously was doing https, now doing http
  492. // stop any tunneling.
  493. if (self.tunnel) self.tunnel = false
  494. self.httpModule = http
  495. switch (self.agentClass) {
  496. case ForeverAgent.SSL:
  497. self.agentClass = ForeverAgent
  498. break
  499. case https.Agent:
  500. self.agentClass = http.Agent
  501. break
  502. default:
  503. // nothing we can do. just hope for the best
  504. return
  505. }
  506. // if there's an agent, then get a new one.
  507. if (self.agent) {
  508. self.agent = null
  509. self.agent = self.getAgent()
  510. }
  511. }
  512. }
  513. Request.prototype.getAgent = function () {
  514. var Agent = this.agentClass
  515. var options = {}
  516. if (this.agentOptions) {
  517. for (var i in this.agentOptions) {
  518. options[i] = this.agentOptions[i]
  519. }
  520. }
  521. if (this.ca) options.ca = this.ca
  522. if (this.ciphers) options.ciphers = this.ciphers
  523. if (this.secureProtocol) options.secureProtocol = this.secureProtocol
  524. if (this.secureOptions) options.secureOptions = this.secureOptions
  525. if (typeof this.rejectUnauthorized !== 'undefined') options.rejectUnauthorized = this.rejectUnauthorized
  526. if (this.cert && this.key) {
  527. options.key = this.key
  528. options.cert = this.cert
  529. }
  530. var poolKey = ''
  531. // different types of agents are in different pools
  532. if (Agent !== this.httpModule.Agent) {
  533. poolKey += Agent.name
  534. }
  535. if (!this.httpModule.globalAgent) {
  536. // node 0.4.x
  537. options.host = this.host
  538. options.port = this.port
  539. if (poolKey) poolKey += ':'
  540. poolKey += this.host + ':' + this.port
  541. }
  542. // ca option is only relevant if proxy or destination are https
  543. var proxy = this.proxy
  544. if (typeof proxy === 'string') proxy = url.parse(proxy)
  545. var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
  546. if (isHttps) {
  547. if (options.ca) {
  548. if (poolKey) poolKey += ':'
  549. poolKey += options.ca
  550. }
  551. if (typeof options.rejectUnauthorized !== 'undefined') {
  552. if (poolKey) poolKey += ':'
  553. poolKey += options.rejectUnauthorized
  554. }
  555. if (options.cert)
  556. poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
  557. if (options.ciphers) {
  558. if (poolKey) poolKey += ':'
  559. poolKey += options.ciphers
  560. }
  561. if (options.secureProtocol) {
  562. if (poolKey) poolKey += ':'
  563. poolKey += options.secureProtocol
  564. }
  565. if (options.secureOptions) {
  566. if (poolKey) poolKey += ':'
  567. poolKey += options.secureOptions
  568. }
  569. }
  570. if (this.pool === globalPool && !poolKey && Object.keys(options).length === 0 && this.httpModule.globalAgent) {
  571. // not doing anything special. Use the globalAgent
  572. return this.httpModule.globalAgent
  573. }
  574. // we're using a stored agent. Make sure it's protocol-specific
  575. poolKey = this.uri.protocol + poolKey
  576. // already generated an agent for this setting
  577. if (this.pool[poolKey]) return this.pool[poolKey]
  578. return this.pool[poolKey] = new Agent(options)
  579. }
  580. Request.prototype.start = function () {
  581. // start() is called once we are ready to send the outgoing HTTP request.
  582. // this is usually called on the first write(), end() or on nextTick()
  583. var self = this
  584. if (self._aborted) return
  585. self._started = true
  586. self.method = self.method || 'GET'
  587. self.href = self.uri.href
  588. if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
  589. self.setHeader('content-length', self.src.stat.size)
  590. }
  591. if (self._aws) {
  592. self.aws(self._aws, true)
  593. }
  594. // We have a method named auth, which is completely different from the http.request
  595. // auth option. If we don't remove it, we're gonna have a bad time.
  596. var reqOptions = copy(self)
  597. delete reqOptions.auth
  598. debug('make request', self.uri.href)
  599. self.req = self.httpModule.request(reqOptions, self.onResponse.bind(self))
  600. if (self.timeout && !self.timeoutTimer) {
  601. self.timeoutTimer = setTimeout(function () {
  602. self.req.abort()
  603. var e = new Error("ETIMEDOUT")
  604. e.code = "ETIMEDOUT"
  605. self.emit("error", e)
  606. }, self.timeout)
  607. // Set additional timeout on socket - in case if remote
  608. // server freeze after sending headers
  609. if (self.req.setTimeout) { // only works on node 0.6+
  610. self.req.setTimeout(self.timeout, function () {
  611. if (self.req) {
  612. self.req.abort()
  613. var e = new Error("ESOCKETTIMEDOUT")
  614. e.code = "ESOCKETTIMEDOUT"
  615. self.emit("error", e)
  616. }
  617. })
  618. }
  619. }
  620. self.req.on('error', self.clientErrorHandler)
  621. self.req.on('drain', function() {
  622. self.emit('drain')
  623. })
  624. self.on('end', function() {
  625. if ( self.req.connection ) self.req.connection.removeListener('error', self._parserErrorHandler)
  626. })
  627. self.emit('request', self.req)
  628. }
  629. Request.prototype.onResponse = function (response) {
  630. var self = this
  631. debug('onResponse', self.uri.href, response.statusCode, response.headers)
  632. response.on('end', function() {
  633. debug('response end', self.uri.href, response.statusCode, response.headers)
  634. });
  635. // The check on response.connection is a workaround for browserify.
  636. if (response.connection && response.connection.listeners('error').indexOf(self._parserErrorHandler) === -1) {
  637. response.connection.setMaxListeners(0)
  638. response.connection.once('error', self._parserErrorHandler)
  639. }
  640. if (self._aborted) {
  641. debug('aborted', self.uri.href)
  642. response.resume()
  643. return
  644. }
  645. if (self._paused) response.pause()
  646. // Check that response.resume is defined. Workaround for browserify.
  647. else response.resume && response.resume()
  648. self.response = response
  649. response.request = self
  650. response.toJSON = toJSON
  651. // XXX This is different on 0.10, because SSL is strict by default
  652. if (self.httpModule === https &&
  653. self.strictSSL &&
  654. !response.client.authorized) {
  655. debug('strict ssl error', self.uri.href)
  656. var sslErr = response.client.authorizationError
  657. self.emit('error', new Error('SSL Error: '+ sslErr))
  658. return
  659. }
  660. if (self.setHost && self.hasHeader('host')) delete self.headers[self.hasHeader('host')]
  661. if (self.timeout && self.timeoutTimer) {
  662. clearTimeout(self.timeoutTimer)
  663. self.timeoutTimer = null
  664. }
  665. var targetCookieJar = (self._jar && self._jar.setCookie)?self._jar:globalCookieJar;
  666. var addCookie = function (cookie) {
  667. //set the cookie if it's domain in the href's domain.
  668. try {
  669. targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true});
  670. } catch (e) {
  671. self.emit('error', e);
  672. }
  673. }
  674. if (hasHeader('set-cookie', response.headers) && (!self._disableCookies)) {
  675. var headerName = hasHeader('set-cookie', response.headers)
  676. if (Array.isArray(response.headers[headerName])) response.headers[headerName].forEach(addCookie)
  677. else addCookie(response.headers[headerName])
  678. }
  679. var redirectTo = null
  680. if (response.statusCode >= 300 && response.statusCode < 400 && hasHeader('location', response.headers)) {
  681. var location = response.headers[hasHeader('location', response.headers)]
  682. debug('redirect', location)
  683. if (self.followAllRedirects) {
  684. redirectTo = location
  685. } else if (self.followRedirect) {
  686. switch (self.method) {
  687. case 'PATCH':
  688. case 'PUT':
  689. case 'POST':
  690. case 'DELETE':
  691. // Do not follow redirects
  692. break
  693. default:
  694. redirectTo = location
  695. break
  696. }
  697. }
  698. } else if (response.statusCode == 401 && self._hasAuth && !self._sentAuth) {
  699. var authHeader = response.headers[hasHeader('www-authenticate', response.headers)]
  700. var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
  701. debug('reauth', authVerb)
  702. switch (authVerb) {
  703. case 'basic':
  704. self.auth(self._user, self._pass, true)
  705. redirectTo = self.uri
  706. break
  707. case 'bearer':
  708. self.auth(null, null, true, self._bearer)
  709. redirectTo = self.uri
  710. break
  711. case 'digest':
  712. // TODO: More complete implementation of RFC 2617.
  713. // - check challenge.algorithm
  714. // - support algorithm="MD5-sess"
  715. // - handle challenge.domain
  716. // - support qop="auth-int" only
  717. // - handle Authentication-Info (not necessarily?)
  718. // - check challenge.stale (not necessarily?)
  719. // - increase nc (not necessarily?)
  720. // For reference:
  721. // http://tools.ietf.org/html/rfc2617#section-3
  722. // https://github.com/bagder/curl/blob/master/lib/http_digest.c
  723. var challenge = {}
  724. var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
  725. for (;;) {
  726. var match = re.exec(authHeader)
  727. if (!match) break
  728. challenge[match[1]] = match[2] || match[3];
  729. }
  730. var ha1 = md5(self._user + ':' + challenge.realm + ':' + self._pass)
  731. var ha2 = md5(self.method + ':' + self.uri.path)
  732. var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
  733. var nc = qop && '00000001'
  734. var cnonce = qop && uuid().replace(/-/g, '')
  735. var digestResponse = qop ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) : md5(ha1 + ':' + challenge.nonce + ':' + ha2)
  736. var authValues = {
  737. username: self._user,
  738. realm: challenge.realm,
  739. nonce: challenge.nonce,
  740. uri: self.uri.path,
  741. qop: qop,
  742. response: digestResponse,
  743. nc: nc,
  744. cnonce: cnonce,
  745. algorithm: challenge.algorithm,
  746. opaque: challenge.opaque
  747. }
  748. authHeader = []
  749. for (var k in authValues) {
  750. if (!authValues[k]) {
  751. //ignore
  752. } else if (k === 'qop' || k === 'nc' || k === 'algorithm') {
  753. authHeader.push(k + '=' + authValues[k])
  754. } else {
  755. authHeader.push(k + '="' + authValues[k] + '"')
  756. }
  757. }
  758. authHeader = 'Digest ' + authHeader.join(', ')
  759. self.setHeader('authorization', authHeader)
  760. self._sentAuth = true
  761. redirectTo = self.uri
  762. break
  763. }
  764. }
  765. if (redirectTo) {
  766. debug('redirect to', redirectTo)
  767. // ignore any potential response body. it cannot possibly be useful
  768. // to us at this point.
  769. if (self._paused) response.resume()
  770. if (self._redirectsFollowed >= self.maxRedirects) {
  771. self.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop "+self.uri.href))
  772. return
  773. }
  774. self._redirectsFollowed += 1
  775. if (!isUrl.test(redirectTo)) {
  776. redirectTo = url.resolve(self.uri.href, redirectTo)
  777. }
  778. var uriPrev = self.uri
  779. self.uri = url.parse(redirectTo)
  780. // handle the case where we change protocol from https to http or vice versa
  781. if (self.uri.protocol !== uriPrev.protocol) {
  782. self._updateProtocol()
  783. }
  784. self.redirects.push(
  785. { statusCode : response.statusCode
  786. , redirectUri: redirectTo
  787. }
  788. )
  789. if (self.followAllRedirects && response.statusCode != 401 && response.statusCode != 307) self.method = 'GET'
  790. // self.method = 'GET' // Force all redirects to use GET || commented out fixes #215
  791. delete self.src
  792. delete self.req
  793. delete self.agent
  794. delete self._started
  795. if (response.statusCode != 401 && response.statusCode != 307) {
  796. // Remove parameters from the previous response, unless this is the second request
  797. // for a server that requires digest authentication.
  798. delete self.body
  799. delete self._form
  800. if (self.headers) {
  801. if (self.hasHeader('host')) delete self.headers[self.hasHeader('host')]
  802. if (self.hasHeader('content-type')) delete self.headers[self.hasHeader('content-type')]
  803. if (self.hasHeader('content-length')) delete self.headers[self.hasHeader('content-length')]
  804. }
  805. }
  806. self.emit('redirect');
  807. self.init()
  808. return // Ignore the rest of the response
  809. } else {
  810. self._redirectsFollowed = self._redirectsFollowed || 0
  811. // Be a good stream and emit end when the response is finished.
  812. // Hack to emit end on close because of a core bug that never fires end
  813. response.on('close', function () {
  814. if (!self._ended) self.response.emit('end')
  815. })
  816. var dataStream
  817. if (self.gzip) {
  818. var contentEncoding = response.headers["content-encoding"] || "identity"
  819. contentEncoding = contentEncoding.trim().toLowerCase()
  820. if (contentEncoding === "gzip") {
  821. dataStream = zlib.createGunzip()
  822. response.pipe(dataStream)
  823. } else {
  824. // Since previous versions didn't check for Content-Encoding header,
  825. // ignore any invalid values to preserve backwards-compatibility
  826. if (contentEncoding !== "identity") {
  827. debug("ignoring unrecognized Content-Encoding " + contentEncoding)
  828. }
  829. dataStream = response
  830. }
  831. } else {
  832. dataStream = response
  833. }
  834. if (self.encoding) {
  835. if (self.dests.length !== 0) {
  836. console.error("Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.")
  837. } else if (dataStream.setEncoding) {
  838. dataStream.setEncoding(self.encoding)
  839. } else {
  840. // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with
  841. // zlib streams.
  842. // If/When support for 0.9.4 is dropped, this should be unnecessary.
  843. dataStream = dataStream.pipe(stringstream(self.encoding))
  844. }
  845. }
  846. self.emit('response', response)
  847. self.dests.forEach(function (dest) {
  848. self.pipeDest(dest)
  849. })
  850. dataStream.on("data", function (chunk) {
  851. var emitted = self.emit("data", chunk)
  852. if (emitted) {
  853. self._destdata = true
  854. } else {
  855. // pause URL stream until we pipe it
  856. dataStream.pause()
  857. dataStream.unshift(chunk)
  858. }
  859. })
  860. dataStream.on("end", function (chunk) {
  861. self._ended = true
  862. self.emit("end", chunk)
  863. })
  864. dataStream.on("close", function () {self.emit("close")})
  865. if (self.callback) {
  866. var buffer = []
  867. var bodyLen = 0
  868. self.on("data", function (chunk) {
  869. buffer.push(chunk)
  870. bodyLen += chunk.length
  871. })
  872. self.on("end", function () {
  873. debug('end event', self.uri.href)
  874. if (self._aborted) {
  875. debug('aborted', self.uri.href)
  876. return
  877. }
  878. if (buffer.length && Buffer.isBuffer(buffer[0])) {
  879. debug('has body', self.uri.href, bodyLen)
  880. var body = new Buffer(bodyLen)
  881. var i = 0
  882. buffer.forEach(function (chunk) {
  883. chunk.copy(body, i, 0, chunk.length)
  884. i += chunk.length
  885. })
  886. if (self.encoding === null) {
  887. response.body = body
  888. } else {
  889. response.body = body.toString(self.encoding)
  890. }
  891. } else if (buffer.length) {
  892. // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
  893. // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
  894. if (self.encoding === 'utf8' && buffer[0].length > 0 && buffer[0][0] === "\uFEFF") {
  895. buffer[0] = buffer[0].substring(1)
  896. }
  897. response.body = buffer.join('')
  898. }
  899. if (self._json) {
  900. try {
  901. response.body = JSON.parse(response.body)
  902. } catch (e) {}
  903. }
  904. debug('emitting complete', self.uri.href)
  905. if(response.body == undefined && !self._json) {
  906. response.body = "";
  907. }
  908. self.emit('complete', response, response.body)
  909. })
  910. }
  911. //if no callback
  912. else{
  913. self.on("end", function () {
  914. if (self._aborted) {
  915. debug('aborted', self.uri.href)
  916. return
  917. }
  918. self.emit('complete', response);
  919. });
  920. }
  921. }
  922. debug('finish init function', self.uri.href)
  923. }
  924. Request.prototype.abort = function () {
  925. this._aborted = true
  926. if (this.req) {
  927. this.req.abort()
  928. }
  929. else if (this.response) {
  930. this.response.abort()
  931. }
  932. this.emit("abort")
  933. }
  934. Request.prototype.pipeDest = function (dest) {
  935. var response = this.response
  936. // Called after the response is received
  937. if (dest.headers && !dest.headersSent) {
  938. if (hasHeader('content-type', response.headers)) {
  939. var ctname = hasHeader('content-type', response.headers)
  940. if (dest.setHeader) dest.setHeader(ctname, response.headers[ctname])
  941. else dest.headers[ctname] = response.headers[ctname]
  942. }
  943. if (hasHeader('content-length', response.headers)) {
  944. var clname = hasHeader('content-length', response.headers)
  945. if (dest.setHeader) dest.setHeader(clname, response.headers[clname])
  946. else dest.headers[clname] = response.headers[clname]
  947. }
  948. }
  949. if (dest.setHeader && !dest.headersSent) {
  950. for (var i in response.headers) {
  951. // If the response content is being decoded, the Content-Encoding header
  952. // of the response doesn't represent the piped content, so don't pass it.
  953. if (!this.gzip || i !== 'content-encoding') {
  954. dest.setHeader(i, response.headers[i])
  955. }
  956. }
  957. dest.statusCode = response.statusCode
  958. }
  959. if (this.pipefilter) this.pipefilter(response, dest)
  960. }
  961. // Composable API
  962. Request.prototype.setHeader = function (name, value, clobber) {
  963. if (clobber === undefined) clobber = true
  964. if (clobber || !this.hasHeader(name)) this.headers[name] = value
  965. else this.headers[this.hasHeader(name)] += ',' + value
  966. return this
  967. }
  968. Request.prototype.setHeaders = function (headers) {
  969. for (var i in headers) {this.setHeader(i, headers[i])}
  970. return this
  971. }
  972. Request.prototype.hasHeader = function (header, headers) {
  973. var headers = Object.keys(headers || this.headers)
  974. , lheaders = headers.map(function (h) {return h.toLowerCase()})
  975. ;
  976. header = header.toLowerCase()
  977. for (var i=0;i<lheaders.length;i++) {
  978. if (lheaders[i] === header) return headers[i]
  979. }
  980. return false
  981. }
  982. var hasHeader = Request.prototype.hasHeader
  983. Request.prototype.qs = function (q, clobber) {
  984. var base
  985. if (!clobber && this.uri.query) base = qs.parse(this.uri.query)
  986. else base = {}
  987. for (var i in q) {
  988. base[i] = q[i]
  989. }
  990. if (qs.stringify(base) === ''){
  991. return this
  992. }
  993. this.uri = url.parse(this.uri.href.split('?')[0] + '?' + qs.stringify(base))
  994. this.url = this.uri
  995. this.path = this.uri.path
  996. return this
  997. }
  998. Request.prototype.form = function (form) {
  999. if (form) {
  1000. this.setHeader('content-type', 'application/x-www-form-urlencoded; charset=utf-8')
  1001. this.body = (typeof form === 'string') ? form.toString('utf8') : qs.stringify(form).toString('utf8')
  1002. return this
  1003. }
  1004. // create form-data object
  1005. this._form = new FormData()
  1006. return this._form
  1007. }
  1008. Request.prototype.multipart = function (multipart) {
  1009. var self = this
  1010. self.body = []
  1011. if (!self.hasHeader('content-type')) {
  1012. self.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
  1013. } else {
  1014. var headerName = self.hasHeader('content-type');
  1015. self.setHeader(headerName, self.headers[headerName].split(';')[0] + '; boundary=' + self.boundary)
  1016. }
  1017. if (!multipart.forEach) throw new Error('Argument error, options.multipart.')
  1018. if (self.preambleCRLF) {
  1019. self.body.push(new Buffer('\r\n'))
  1020. }
  1021. multipart.forEach(function (part) {
  1022. var body = part.body
  1023. if(body == null) throw Error('Body attribute missing in multipart.')
  1024. delete part.body
  1025. var preamble = '--' + self.boundary + '\r\n'
  1026. Object.keys(part).forEach(function (key) {
  1027. preamble += key + ': ' + part[key] + '\r\n'
  1028. })
  1029. preamble += '\r\n'
  1030. self.body.push(new Buffer(preamble))
  1031. self.body.push(new Buffer(body))
  1032. self.body.push(new Buffer('\r\n'))
  1033. })
  1034. self.body.push(new Buffer('--' + self.boundary + '--'))
  1035. return self
  1036. }
  1037. Request.prototype.json = function (val) {
  1038. var self = this
  1039. if (!self.hasHeader('accept')) self.setHeader('accept', 'application/json')
  1040. this._json = true
  1041. if (typeof val === 'boolean') {
  1042. if (typeof this.body === 'object') {
  1043. this.body = safeStringify(this.body)
  1044. if (!self.hasHeader('content-type'))
  1045. self.setHeader('content-type', 'application/json')
  1046. }
  1047. } else {
  1048. this.body = safeStringify(val)
  1049. if (!self.hasHeader('content-type'))
  1050. self.setHeader('content-type', 'application/json')
  1051. }
  1052. return this
  1053. }
  1054. Request.prototype.getHeader = function (name, headers) {
  1055. var result, re, match
  1056. if (!headers) headers = this.headers
  1057. Object.keys(headers).forEach(function (key) {
  1058. if (key.length !== name.length) return
  1059. re = new RegExp(name, 'i')
  1060. match = key.match(re)
  1061. if (match) result = headers[key]
  1062. })
  1063. return result
  1064. }
  1065. var getHeader = Request.prototype.getHeader
  1066. Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
  1067. if (bearer !== undefined) {
  1068. this._bearer = bearer
  1069. this._hasAuth = true
  1070. if (sendImmediately || typeof sendImmediately == 'undefined') {
  1071. if (typeof bearer === 'function') {
  1072. bearer = bearer()
  1073. }
  1074. this.setHeader('authorization', 'Bearer ' + bearer)
  1075. this._sentAuth = true
  1076. }
  1077. return this
  1078. }
  1079. if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
  1080. throw new Error('auth() received invalid user or password')
  1081. }
  1082. this._user = user
  1083. this._pass = pass
  1084. this._hasAuth = true
  1085. var header = typeof pass !== 'undefined' ? user + ':' + pass : user
  1086. if (sendImmediately || typeof sendImmediately == 'undefined') {
  1087. this.setHeader('authorization', 'Basic ' + toBase64(header))
  1088. this._sentAuth = true
  1089. }
  1090. return this
  1091. }
  1092. Request.prototype.aws = function (opts, now) {
  1093. if (!now) {
  1094. this._aws = opts
  1095. return this
  1096. }
  1097. var date = new Date()
  1098. this.setHeader('date', date.toUTCString())
  1099. var auth =
  1100. { key: opts.key
  1101. , secret: opts.secret
  1102. , verb: this.method.toUpperCase()
  1103. , date: date
  1104. , contentType: this.getHeader('content-type') || ''
  1105. , md5: this.getHeader('content-md5') || ''
  1106. , amazonHeaders: aws.canonicalizeHeaders(this.headers)
  1107. }
  1108. if (opts.bucket && this.path) {
  1109. auth.resource = '/' + opts.bucket + this.path
  1110. } else if (opts.bucket && !this.path) {
  1111. auth.resource = '/' + opts.bucket
  1112. } else if (!opts.bucket && this.path) {
  1113. auth.resource = this.path
  1114. } else if (!opts.bucket && !this.path) {
  1115. auth.resource = '/'
  1116. }
  1117. auth.resource = aws.canonicalizeResource(auth.resource)
  1118. this.setHeader('authorization', aws.authorization(auth))
  1119. return this
  1120. }
  1121. Request.prototype.httpSignature = function (opts) {
  1122. var req = this
  1123. httpSignature.signRequest({
  1124. getHeader: function(header) {
  1125. return getHeader(header, req.headers)
  1126. },
  1127. setHeader: function(header, value) {
  1128. req.setHeader(header, value)
  1129. },
  1130. method: this.method,
  1131. path: this.path
  1132. }, opts)
  1133. debug('httpSignature authorization', this.getHeader('authorization'))
  1134. return this
  1135. }
  1136. Request.prototype.hawk = function (opts) {
  1137. this.setHeader('Authorization', hawk.client.header(this.uri, this.method, opts).field)
  1138. }
  1139. Request.prototype.oauth = function (_oauth) {
  1140. var form
  1141. if (this.hasHeader('content-type') &&
  1142. this.getHeader('content-type').slice(0, 'application/x-www-form-urlencoded'.length) ===
  1143. 'application/x-www-form-urlencoded'
  1144. ) {
  1145. form = qs.parse(this.body)
  1146. }
  1147. if (this.uri.query) {
  1148. form = qs.parse(this.uri.query)
  1149. }
  1150. if (!form) form = {}
  1151. var oa = {}
  1152. for (var i in form) oa[i] = form[i]
  1153. for (var i in _oauth) oa['oauth_'+i] = _oauth[i]
  1154. if (!oa.oauth_version) oa.oauth_version = '1.0'
  1155. if (!oa.oauth_timestamp) oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
  1156. if (!oa.oauth_nonce) oa.oauth_nonce = uuid().replace(/-/g, '')
  1157. oa.oauth_signature_method = 'HMAC-SHA1'
  1158. var consumer_secret = oa.oauth_consumer_secret
  1159. delete oa.oauth_consumer_secret
  1160. var token_secret = oa.oauth_token_secret
  1161. delete oa.oauth_token_secret
  1162. var timestamp = oa.oauth_timestamp
  1163. var baseurl = this.uri.protocol + '//' + this.uri.host + this.uri.pathname
  1164. var signature = oauth.hmacsign(this.method, baseurl, oa, consumer_secret, token_secret)
  1165. // oa.oauth_signature = signature
  1166. for (var i in form) {
  1167. if ( i.slice(0, 'oauth_') in _oauth) {
  1168. // skip
  1169. } else {
  1170. delete oa['oauth_'+i]
  1171. if (i !== 'x_auth_mode') delete oa[i]
  1172. }
  1173. }
  1174. oa.oauth_timestamp = timestamp
  1175. var authHeader = 'OAuth '+Object.keys(oa).sort().map(function (i) {return i+'="'+oauth.rfc3986(oa[i])+'"'}).join(',')
  1176. authHeader += ',oauth_signature="' + oauth.rfc3986(signature) + '"'
  1177. this.setHeader('Authorization', authHeader)
  1178. return this
  1179. }
  1180. Request.prototype.jar = function (jar) {
  1181. var cookies
  1182. if (this._redirectsFollowed === 0) {
  1183. this.originalCookieHeader = this.getHeader('cookie')
  1184. }
  1185. if (!jar) {
  1186. // disable cookies
  1187. cookies = false
  1188. this._disableCookies = true
  1189. } else {
  1190. var targetCookieJar = (jar && jar.getCookieString)?jar:globalCookieJar;
  1191. var urihref = this.uri.href
  1192. //fetch cookie in the Specified host
  1193. if (targetCookieJar) {
  1194. cookies = targetCookieJar.getCookieString(urihref);
  1195. }
  1196. }
  1197. //if need cookie and cookie is not empty
  1198. if (cookies && cookies.length) {
  1199. if (this.originalCookieHeader) {
  1200. // Don't overwrite existing Cookie header
  1201. this.setHeader('cookie', this.originalCookieHeader + '; ' + cookies)
  1202. } else {
  1203. this.setHeader('cookie', cookies)
  1204. }
  1205. }
  1206. this._jar = jar
  1207. return this
  1208. }
  1209. // Stream API
  1210. Request.prototype.pipe = function (dest, opts) {
  1211. if (this.response) {
  1212. if (this._destdata) {
  1213. throw new Error("You cannot pipe after data has been emitted from the response.")
  1214. } else if (this._ended) {
  1215. throw new Error("You cannot pipe after the response has been ended.")
  1216. } else {
  1217. stream.Stream.prototype.pipe.call(this, dest, opts)
  1218. this.pipeDest(dest)
  1219. return dest
  1220. }
  1221. } else {
  1222. this.dests.push(dest)
  1223. stream.Stream.prototype.pipe.call(this, dest, opts)
  1224. return dest
  1225. }
  1226. }
  1227. Request.prototype.write = function () {
  1228. if (!this._started) this.start()
  1229. return this.req.write.apply(this.req, arguments)
  1230. }
  1231. Request.prototype.end = function (chunk) {
  1232. if (chunk) this.write(chunk)
  1233. if (!this._started) this.start()
  1234. this.req.end()
  1235. }
  1236. Request.prototype.pause = function () {
  1237. if (!this.response) this._paused = true
  1238. else this.response.pause.apply(this.response, arguments)
  1239. }
  1240. Request.prototype.resume = function () {
  1241. if (!this.response) this._paused = false
  1242. else this.response.resume.apply(this.response, arguments)
  1243. }
  1244. Request.prototype.destroy = function () {
  1245. if (!this._ended) this.end()
  1246. else if (this.response) this.response.destroy()
  1247. }
  1248. function toJSON () {
  1249. return getSafe(this, '__' + (((1+Math.random())*0x10000)|0).toString(16))
  1250. }
  1251. Request.prototype.toJSON = toJSON
  1252. /* Fix per https://github.com/mikeal/request/issues/887#issuecomment-48831952 */
  1253. var superOn = Request.prototype.on;
  1254. Request.prototype.on = function (eventName) {
  1255. if (eventName === "data") {
  1256. this.resume()
  1257. }
  1258. superOn.apply(this, arguments)
  1259. }
  1260. module.exports = Request