PageRenderTime 26ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/assets/bower_components/angular-count-to/scripts/node_modules/karma/node_modules/http-proxy/lib/node-http-proxy.js

https://gitlab.com/VoroninNick/radok
JavaScript | 394 lines | 183 code | 41 blank | 170 comment | 31 complexity | bf5c1248e17d60f03e8163165ad70441 MD5 | raw file
  1. /*
  2. node-http-proxy.js: http proxy for node.js
  3. Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Marak Squires, Fedor Indutny
  4. Permission is hereby granted, free of charge, to any person obtaining
  5. a copy of this software and associated documentation files (the
  6. "Software"), to deal in the Software without restriction, including
  7. without limitation the rights to use, copy, modify, merge, publish,
  8. distribute, sublicense, and/or sell copies of the Software, and to
  9. permit persons to whom the Software is furnished to do so, subject to
  10. the following conditions:
  11. The above copyright notice and this permission notice shall be
  12. included in all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  17. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  18. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  19. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. */
  21. var util = require('util'),
  22. http = require('http'),
  23. https = require('https'),
  24. events = require('events'),
  25. maxSockets = 100;
  26. //
  27. // Expose version information through `pkginfo`.
  28. //
  29. require('pkginfo')(module, 'version');
  30. //
  31. // ### Export the relevant objects exposed by `node-http-proxy`
  32. //
  33. var HttpProxy = exports.HttpProxy = require('./node-http-proxy/http-proxy').HttpProxy,
  34. ProxyTable = exports.ProxyTable = require('./node-http-proxy/proxy-table').ProxyTable,
  35. RoutingProxy = exports.RoutingProxy = require('./node-http-proxy/routing-proxy').RoutingProxy;
  36. //
  37. // ### function createServer ([port, host, options, handler])
  38. // #### @port {number} **Optional** Port to use on the proxy target host.
  39. // #### @host {string} **Optional** Host of the proxy target.
  40. // #### @options {Object} **Optional** Options for the HttpProxy instance used
  41. // #### @handler {function} **Optional** Request handler for the server
  42. // Returns a server that manages an instance of HttpProxy. Flexible arguments allow for:
  43. //
  44. // * `httpProxy.createServer(9000, 'localhost')`
  45. // * `httpProxy.createServer(9000, 'localhost', options)
  46. // * `httpPRoxy.createServer(function (req, res, proxy) { ... })`
  47. //
  48. exports.createServer = function () {
  49. var args = Array.prototype.slice.call(arguments),
  50. handlers = [],
  51. callback,
  52. options = {},
  53. message,
  54. handler,
  55. server,
  56. proxy,
  57. host,
  58. port;
  59. //
  60. // Liberally parse arguments of the form:
  61. //
  62. // httpProxy.createServer('localhost', 9000, callback);
  63. // httpProxy.createServer({ host: 'localhost', port: 9000 }, callback);
  64. // **NEED MORE HERE!!!**
  65. //
  66. args.forEach(function (arg) {
  67. arg = Number(arg) || arg;
  68. switch (typeof arg) {
  69. case 'string': host = arg; break;
  70. case 'number': port = arg; break;
  71. case 'object': options = arg || {}; break;
  72. case 'function': callback = arg; handlers.push(callback); break;
  73. };
  74. });
  75. //
  76. // Helper function to create intelligent error message(s)
  77. // for the very liberal arguments parsing performed by
  78. // `require('http-proxy').createServer()`.
  79. //
  80. function validArguments() {
  81. var conditions = {
  82. 'port and host': function () {
  83. return port && host;
  84. },
  85. 'options.target or options.router': function () {
  86. return options && (options.router ||
  87. (options.target && options.target.host && options.target.port));
  88. },
  89. 'or proxy handlers': function () {
  90. return handlers && handlers.length;
  91. }
  92. }
  93. var missing = Object.keys(conditions).filter(function (name) {
  94. return !conditions[name]();
  95. });
  96. if (missing.length === 3) {
  97. message = 'Cannot proxy without ' + missing.join(', ');
  98. return false;
  99. }
  100. return true;
  101. }
  102. if (!validArguments()) {
  103. //
  104. // If `host`, `port` and `options` are all not passed (with valid
  105. // options) then this server is improperly configured.
  106. //
  107. throw new Error(message);
  108. return;
  109. }
  110. //
  111. // Hoist up any explicit `host` or `port` arguments
  112. // that have been passed in to the options we will
  113. // pass to the `httpProxy.HttpProxy` constructor.
  114. //
  115. options.target = options.target || {};
  116. options.target.port = options.target.port || port;
  117. options.target.host = options.target.host || host;
  118. if (options.target && options.target.host && options.target.port) {
  119. //
  120. // If an explicit `host` and `port` combination has been passed
  121. // to `.createServer()` then instantiate a hot-path optimized
  122. // `HttpProxy` object and add the "proxy" middleware layer.
  123. //
  124. proxy = new HttpProxy(options);
  125. handlers.push(function (req, res) {
  126. proxy.proxyRequest(req, res);
  127. });
  128. }
  129. else {
  130. //
  131. // If no explicit `host` or `port` combination has been passed then
  132. // we have to assume that this is a "go-anywhere" Proxy (i.e. a `RoutingProxy`).
  133. //
  134. proxy = new RoutingProxy(options);
  135. if (options.router) {
  136. //
  137. // If a routing table has been supplied than we assume
  138. // the user intends us to add the "proxy" middleware layer
  139. // for them
  140. //
  141. handlers.push(function (req, res) {
  142. proxy.proxyRequest(req, res);
  143. });
  144. proxy.on('routes', function (routes) {
  145. server.emit('routes', routes);
  146. });
  147. }
  148. }
  149. //
  150. // Create the `http[s].Server` instance which will use
  151. // an instance of `httpProxy.HttpProxy`.
  152. //
  153. handler = handlers.length > 1
  154. ? exports.stack(handlers, proxy)
  155. : function (req, res) { handlers[0](req, res, proxy) };
  156. server = options.https
  157. ? https.createServer(options.https, handler)
  158. : http.createServer(handler);
  159. server.on('close', function () {
  160. proxy.close();
  161. });
  162. if (!callback) {
  163. //
  164. // If an explicit callback has not been supplied then
  165. // automagically proxy the request using the `HttpProxy`
  166. // instance we have created.
  167. //
  168. server.on('upgrade', function (req, socket, head) {
  169. proxy.proxyWebSocketRequest(req, socket, head);
  170. });
  171. }
  172. //
  173. // Set the proxy on the server so it is available
  174. // to the consumer of the server
  175. //
  176. server.proxy = proxy;
  177. return server;
  178. };
  179. //
  180. // ### function buffer (obj)
  181. // #### @obj {Object} Object to pause events from
  182. // Buffer `data` and `end` events from the given `obj`.
  183. // Consumers of HttpProxy performing async tasks
  184. // __must__ utilize this utility, to re-emit data once
  185. // the async operation has completed, otherwise these
  186. // __events will be lost.__
  187. //
  188. // var buffer = httpProxy.buffer(req);
  189. // fs.readFile(path, function () {
  190. // httpProxy.proxyRequest(req, res, host, port, buffer);
  191. // });
  192. //
  193. // __Attribution:__ This approach is based heavily on
  194. // [Connect](https://github.com/senchalabs/connect/blob/master/lib/utils.js#L157).
  195. // However, this is not a big leap from the implementation in node-http-proxy < 0.4.0.
  196. // This simply chooses to manage the scope of the events on a new Object literal as opposed to
  197. // [on the HttpProxy instance](https://github.com/nodejitsu/node-http-proxy/blob/v0.3.1/lib/node-http-proxy.js#L154).
  198. //
  199. exports.buffer = function (obj) {
  200. var events = [],
  201. onData,
  202. onEnd;
  203. obj.on('data', onData = function (data, encoding) {
  204. events.push(['data', data, encoding]);
  205. });
  206. obj.on('end', onEnd = function (data, encoding) {
  207. events.push(['end', data, encoding]);
  208. });
  209. return {
  210. end: function () {
  211. obj.removeListener('data', onData);
  212. obj.removeListener('end', onEnd);
  213. },
  214. destroy: function () {
  215. this.end();
  216. this.resume = function () {
  217. console.error("Cannot resume buffer after destroying it.");
  218. };
  219. onData = onEnd = events = obj = null;
  220. },
  221. resume: function () {
  222. this.end();
  223. for (var i = 0, len = events.length; i < len; ++i) {
  224. obj.emit.apply(obj, events[i]);
  225. }
  226. }
  227. };
  228. };
  229. //
  230. // ### function getMaxSockets ()
  231. // Returns the maximum number of sockets
  232. // allowed on __every__ outgoing request
  233. // made by __all__ instances of `HttpProxy`
  234. //
  235. exports.getMaxSockets = function () {
  236. return maxSockets;
  237. };
  238. //
  239. // ### function setMaxSockets ()
  240. // Sets the maximum number of sockets
  241. // allowed on __every__ outgoing request
  242. // made by __all__ instances of `HttpProxy`
  243. //
  244. exports.setMaxSockets = function (value) {
  245. maxSockets = value;
  246. };
  247. //
  248. // ### function stack (middlewares, proxy)
  249. // #### @middlewares {Array} Array of functions to stack.
  250. // #### @proxy {HttpProxy|RoutingProxy} Proxy instance to
  251. // Iteratively build up a single handler to the `http.Server`
  252. // `request` event (i.e. `function (req, res)`) by wrapping
  253. // each middleware `layer` into a `child` middleware which
  254. // is in invoked by the parent (i.e. predecessor in the Array).
  255. //
  256. // adapted from https://github.com/creationix/stack
  257. //
  258. exports.stack = function stack (middlewares, proxy) {
  259. var handle;
  260. middlewares.reverse().forEach(function (layer) {
  261. var child = handle;
  262. handle = function (req, res) {
  263. var next = function (err) {
  264. if (err) {
  265. if (res._headerSent) {
  266. res.destroy();
  267. }
  268. else {
  269. res.statusCode = 500;
  270. res.setHeader('Content-Type', 'text/plain');
  271. res.end('Internal Server Error');
  272. }
  273. console.error('Error in middleware(s): %s', err.stack);
  274. return;
  275. }
  276. if (child) {
  277. child(req, res);
  278. }
  279. };
  280. //
  281. // Set the prototype of the `next` function to the instance
  282. // of the `proxy` so that in can be used interchangably from
  283. // a `connect` style callback and a true `HttpProxy` object.
  284. //
  285. // e.g. `function (req, res, next)` vs. `function (req, res, proxy)`
  286. //
  287. next.__proto__ = proxy;
  288. layer(req, res, next);
  289. };
  290. });
  291. return handle;
  292. };
  293. //
  294. // ### function _getAgent (host, port, secure)
  295. // #### @options {Object} Options to use when creating the agent.
  296. //
  297. // {
  298. // host: 'localhost',
  299. // port: 9000,
  300. // https: true,
  301. // maxSockets: 100
  302. // }
  303. //
  304. // Createsan agent from the `http` or `https` module
  305. // and sets the `maxSockets` property appropriately.
  306. //
  307. exports._getAgent = function _getAgent (options) {
  308. if (!options || !options.host) {
  309. throw new Error('`options.host` is required to create an Agent.');
  310. }
  311. if (!options.port) {
  312. options.port = options.https ? 443 : 80;
  313. }
  314. var Agent = options.https ? https.Agent : http.Agent,
  315. agent;
  316. // require('http-proxy').setMaxSockets() should override http's default
  317. // configuration value (which is pretty low).
  318. options.maxSockets = options.maxSockets || maxSockets;
  319. agent = new Agent(options);
  320. return agent;
  321. }
  322. //
  323. // ### function _getProtocol (options)
  324. // #### @options {Object} Options for the proxy target.
  325. // Returns the appropriate node.js core protocol module (i.e. `http` or `https`)
  326. // based on the `options` supplied.
  327. //
  328. exports._getProtocol = function _getProtocol (options) {
  329. return options.https ? https : http;
  330. };
  331. //
  332. // ### function _getBase (options)
  333. // #### @options {Object} Options for the proxy target.
  334. // Returns the relevate base object to create on outgoing proxy request.
  335. // If `options.https` are supplied, this function respond with an object
  336. // containing the relevant `ca`, `key`, and `cert` properties.
  337. //
  338. exports._getBase = function _getBase (options) {
  339. var result = function () {};
  340. if (options.https && typeof options.https === 'object') {
  341. ['ca', 'cert', 'key'].forEach(function (key) {
  342. if (options.https[key]) {
  343. result.prototype[key] = options.https[key];
  344. }
  345. });
  346. }
  347. return result;
  348. };