2 node-http-proxy.js: http proxy for node.js
4 Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Marak Squires, Fedor Indutny
6 Permission is hereby granted, free of charge, to any person obtaining
7 a copy of this software and associated documentation files (the
8 "Software"), to deal in the Software without restriction, including
9 without limitation the rights to use, copy, modify, merge, publish,
10 distribute, sublicense, and/or sell copies of the Software, and to
11 permit persons to whom the Software is furnished to do so, subject to
12 the following conditions:
14 The above copyright notice and this permission notice shall be
15 included in all copies or substantial portions of the Software.
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 var util = require('util'),
28 http = require('http'),
29 https = require('https'),
30 events = require('events'),
34 // Expose version information through `pkginfo`.
36 require('pkginfo')(module, 'version');
39 // ### Export the relevant objects exposed by `node-http-proxy`
41 var HttpProxy = exports.HttpProxy = require('./node-http-proxy/http-proxy').HttpProxy,
42 ProxyTable = exports.ProxyTable = require('./node-http-proxy/proxy-table').ProxyTable,
43 RoutingProxy = exports.RoutingProxy = require('./node-http-proxy/routing-proxy').RoutingProxy;
46 // ### function createServer ([port, host, options, handler])
47 // #### @port {number} **Optional** Port to use on the proxy target host.
48 // #### @host {string} **Optional** Host of the proxy target.
49 // #### @options {Object} **Optional** Options for the HttpProxy instance used
50 // #### @handler {function} **Optional** Request handler for the server
51 // Returns a server that manages an instance of HttpProxy. Flexible arguments allow for:
53 // * `httpProxy.createServer(9000, 'localhost')`
54 // * `httpProxy.createServer(9000, 'localhost', options)
55 // * `httpPRoxy.createServer(function (req, res, proxy) { ... })`
57 exports.createServer = function () {
58 var args = Array.prototype.slice.call(arguments),
70 // Liberally parse arguments of the form:
72 // httpProxy.createServer('localhost', 9000, callback);
73 // httpProxy.createServer({ host: 'localhost', port: 9000 }, callback);
74 // **NEED MORE HERE!!!**
76 args.forEach(function (arg) {
77 arg = Number(arg) || arg;
79 case 'string': host = arg; break;
80 case 'number': port = arg; break;
81 case 'object': options = arg || {}; break;
82 case 'function': callback = arg; handlers.push(callback); break;
87 // Helper function to create intelligent error message(s)
88 // for the very liberal arguments parsing performed by
89 // `require('http-proxy').createServer()`.
91 function validArguments() {
93 'port and host': function () {
96 'options.target or options.router': function () {
97 return options && (options.router ||
98 (options.target && options.target.host && options.target.port));
100 'or proxy handlers': function () {
101 return handlers && handlers.length;
105 var missing = Object.keys(conditions).filter(function (name) {
106 return !conditions[name]();
109 if (missing.length === 3) {
110 message = 'Cannot proxy without ' + missing.join(', ');
117 if (!validArguments()) {
119 // If `host`, `port` and `options` are all not passed (with valid
120 // options) then this server is improperly configured.
122 throw new Error(message);
127 // Hoist up any explicit `host` or `port` arguments
128 // that have been passed in to the options we will
129 // pass to the `httpProxy.HttpProxy` constructor.
131 options.target = options.target || {};
132 options.target.port = options.target.port || port;
133 options.target.host = options.target.host || host;
135 if (options.target && options.target.host && options.target.port) {
137 // If an explicit `host` and `port` combination has been passed
138 // to `.createServer()` then instantiate a hot-path optimized
139 // `HttpProxy` object and add the "proxy" middleware layer.
141 proxy = new HttpProxy(options);
142 handlers.push(function (req, res) {
143 proxy.proxyRequest(req, res);
148 // If no explicit `host` or `port` combination has been passed then
149 // we have to assume that this is a "go-anywhere" Proxy (i.e. a `RoutingProxy`).
151 proxy = new RoutingProxy(options);
153 if (options.router) {
155 // If a routing table has been supplied than we assume
156 // the user intends us to add the "proxy" middleware layer
159 handlers.push(function (req, res) {
160 proxy.proxyRequest(req, res);
163 proxy.on('routes', function (routes) {
164 server.emit('routes', routes);
170 // Create the `http[s].Server` instance which will use
171 // an instance of `httpProxy.HttpProxy`.
173 handler = handlers.length > 1
174 ? exports.stack(handlers, proxy)
175 : function (req, res) { handlers[0](req, res, proxy) };
177 server = options.https
178 ? https.createServer(options.https, handler)
179 : http.createServer(handler);
181 server.on('close', function () {
187 // If an explicit callback has not been supplied then
188 // automagically proxy the request using the `HttpProxy`
189 // instance we have created.
191 server.on('upgrade', function (req, socket, head) {
192 proxy.proxyWebSocketRequest(req, socket, head);
197 // Set the proxy on the server so it is available
198 // to the consumer of the server
200 server.proxy = proxy;
205 // ### function buffer (obj)
206 // #### @obj {Object} Object to pause events from
207 // Buffer `data` and `end` events from the given `obj`.
208 // Consumers of HttpProxy performing async tasks
209 // __must__ utilize this utility, to re-emit data once
210 // the async operation has completed, otherwise these
211 // __events will be lost.__
213 // var buffer = httpProxy.buffer(req);
214 // fs.readFile(path, function () {
215 // httpProxy.proxyRequest(req, res, host, port, buffer);
218 // __Attribution:__ This approach is based heavily on
219 // [Connect](https://github.com/senchalabs/connect/blob/master/lib/utils.js#L157).
220 // However, this is not a big leap from the implementation in node-http-proxy < 0.4.0.
221 // This simply chooses to manage the scope of the events on a new Object literal as opposed to
222 // [on the HttpProxy instance](https://github.com/nodejitsu/node-http-proxy/blob/v0.3.1/lib/node-http-proxy.js#L154).
224 exports.buffer = function (obj) {
229 obj.on('data', onData = function (data, encoding) {
230 events.push(['data', data, encoding]);
233 obj.on('end', onEnd = function (data, encoding) {
234 events.push(['end', data, encoding]);
239 obj.removeListener('data', onData);
240 obj.removeListener('end', onEnd);
242 destroy: function () {
244 this.resume = function () {
245 console.error("Cannot resume buffer after destroying it.");
248 onData = onEnd = events = obj = null;
250 resume: function () {
252 for (var i = 0, len = events.length; i < len; ++i) {
253 obj.emit.apply(obj, events[i]);
260 // ### function getMaxSockets ()
261 // Returns the maximum number of sockets
262 // allowed on __every__ outgoing request
263 // made by __all__ instances of `HttpProxy`
265 exports.getMaxSockets = function () {
270 // ### function setMaxSockets ()
271 // Sets the maximum number of sockets
272 // allowed on __every__ outgoing request
273 // made by __all__ instances of `HttpProxy`
275 exports.setMaxSockets = function (value) {
280 // ### function stack (middlewares, proxy)
281 // #### @middlewares {Array} Array of functions to stack.
282 // #### @proxy {HttpProxy|RoutingProxy} Proxy instance to
283 // Iteratively build up a single handler to the `http.Server`
284 // `request` event (i.e. `function (req, res)`) by wrapping
285 // each middleware `layer` into a `child` middleware which
286 // is in invoked by the parent (i.e. predecessor in the Array).
288 // adapted from https://github.com/creationix/stack
290 exports.stack = function stack (middlewares, proxy) {
292 middlewares.reverse().forEach(function (layer) {
294 handle = function (req, res) {
295 var next = function (err) {
297 if (! proxy.emit('middlewareError', err, req, res)) {
298 console.error('Error in middleware(s): %s', err.stack);
301 if (res._headerSent) {
305 res.statusCode = 500;
306 res.setHeader('Content-Type', 'text/plain');
307 res.end('Internal Server Error');
319 // Set the prototype of the `next` function to the instance
320 // of the `proxy` so that in can be used interchangably from
321 // a `connect` style callback and a true `HttpProxy` object.
323 // e.g. `function (req, res, next)` vs. `function (req, res, proxy)`
325 next.__proto__ = proxy;
326 layer(req, res, next);
334 // ### function _getAgent (host, port, secure)
335 // #### @options {Object} Options to use when creating the agent.
338 // host: 'localhost',
344 // Createsan agent from the `http` or `https` module
345 // and sets the `maxSockets` property appropriately.
347 exports._getAgent = function _getAgent (options) {
348 if (!options || !options.host) {
349 throw new Error('`options.host` is required to create an Agent.');
353 options.port = options.https ? 443 : 80;
356 var Agent = options.https ? https.Agent : http.Agent,
359 // require('http-proxy').setMaxSockets() should override http's default
360 // configuration value (which is pretty low).
361 options.maxSockets = options.maxSockets || maxSockets;
362 agent = new Agent(options);
368 // ### function _getProtocol (options)
369 // #### @options {Object} Options for the proxy target.
370 // Returns the appropriate node.js core protocol module (i.e. `http` or `https`)
371 // based on the `options` supplied.
373 exports._getProtocol = function _getProtocol (options) {
374 return options.https ? https : http;
379 // ### function _getBase (options)
380 // #### @options {Object} Options for the proxy target.
381 // Returns the relevate base object to create on outgoing proxy request.
382 // If `options.https` are supplied, this function respond with an object
383 // containing the relevant `ca`, `key`, and `cert` properties.
385 exports._getBase = function _getBase (options) {
386 var result = function () {};
388 if (options.https && typeof options.https === 'object') {
389 ['ca', 'cert', 'key'].forEach(function (key) {
390 if (options.https[key]) {
391 result.prototype[key] = options.https[key];