Bug:Fix file validation issue
[vnfsdk/refrepo.git] / vnfmarket / src / main / webapp / vnfmarket / node_modules / http-proxy / lib / node-http-proxy.js
1 /*
2   node-http-proxy.js: http proxy for node.js
3
4   Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Marak Squires, Fedor Indutny
5
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:
13
14   The above copyright notice and this permission notice shall be
15   included in all copies or substantial portions of the Software.
16
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.
24
25 */
26
27 var util = require('util'),
28     http = require('http'),
29     https = require('https'),
30     events = require('events'),
31     maxSockets = 100;
32
33 //
34 // Expose version information through `pkginfo`.
35 //
36 require('pkginfo')(module, 'version');
37
38 //
39 // ### Export the relevant objects exposed by `node-http-proxy`
40 //
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;
44
45 //
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:
52 //
53 // * `httpProxy.createServer(9000, 'localhost')`
54 // * `httpProxy.createServer(9000, 'localhost', options)
55 // * `httpPRoxy.createServer(function (req, res, proxy) { ... })`
56 //
57 exports.createServer = function () {
58   var args = Array.prototype.slice.call(arguments),
59       handlers = [],
60       callback,
61       options = {},
62       message,
63       handler,
64       server,
65       proxy,
66       host,
67       port;
68
69   //
70   // Liberally parse arguments of the form:
71   //
72   //    httpProxy.createServer('localhost', 9000, callback);
73   //    httpProxy.createServer({ host: 'localhost', port: 9000 }, callback);
74   //    **NEED MORE HERE!!!**
75   //
76   args.forEach(function (arg) {
77     arg = Number(arg) || arg;
78     switch (typeof 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;
83     };
84   });
85
86   //
87   // Helper function to create intelligent error message(s)
88   // for the very liberal arguments parsing performed by
89   // `require('http-proxy').createServer()`.
90   //
91   function validArguments() {
92     var conditions = {
93       'port and host': function () {
94         return port && host;
95       },
96       'options.target or options.router': function () {
97         return options && (options.router ||
98           (options.target && options.target.host && options.target.port));
99       },
100       'or proxy handlers': function () {
101         return handlers && handlers.length;
102       }
103     }
104
105     var missing = Object.keys(conditions).filter(function (name) {
106       return !conditions[name]();
107     });
108
109     if (missing.length === 3) {
110       message = 'Cannot proxy without ' + missing.join(', ');
111       return false;
112     }
113
114     return true;
115   }
116
117   if (!validArguments()) {
118     //
119     // If `host`, `port` and `options` are all not passed (with valid
120     // options) then this server is improperly configured.
121     //
122     throw new Error(message);
123     return;
124   }
125
126   //
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.
130   //
131   options.target      = options.target      || {};
132   options.target.port = options.target.port || port;
133   options.target.host = options.target.host || host;
134
135   if (options.target && options.target.host && options.target.port) {
136     //
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.
140     //
141     proxy = new HttpProxy(options);
142     handlers.push(function (req, res) {
143       proxy.proxyRequest(req, res);
144     });
145   }
146   else {
147     //
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`).
150     //
151     proxy = new RoutingProxy(options);
152
153     if (options.router) {
154       //
155       // If a routing table has been supplied than we assume
156       // the user intends us to add the "proxy" middleware layer
157       // for them
158       //
159       handlers.push(function (req, res) {
160         proxy.proxyRequest(req, res);
161       });
162
163       proxy.on('routes', function (routes) {
164         server.emit('routes', routes);
165       });
166     }
167   }
168
169   //
170   // Create the `http[s].Server` instance which will use
171   // an instance of `httpProxy.HttpProxy`.
172   //
173   handler = handlers.length > 1
174     ? exports.stack(handlers, proxy)
175     : function (req, res) { handlers[0](req, res, proxy) };
176
177   server  = options.https
178     ? https.createServer(options.https, handler)
179     : http.createServer(handler);
180
181   server.on('close', function () {
182     proxy.close();
183   });
184
185   if (!callback) {
186     //
187     // If an explicit callback has not been supplied then
188     // automagically proxy the request using the `HttpProxy`
189     // instance we have created.
190     //
191     server.on('upgrade', function (req, socket, head) {
192       proxy.proxyWebSocketRequest(req, socket, head);
193     });
194   }
195
196   //
197   // Set the proxy on the server so it is available
198   // to the consumer of the server
199   //
200   server.proxy = proxy;
201   return server;
202 };
203
204 //
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.__
212 //
213 //      var buffer = httpProxy.buffer(req);
214 //      fs.readFile(path, function () {
215 //         httpProxy.proxyRequest(req, res, host, port, buffer);
216 //      });
217 //
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).
223 //
224 exports.buffer = function (obj) {
225   var events = [],
226       onData,
227       onEnd;
228
229   obj.on('data', onData = function (data, encoding) {
230     events.push(['data', data, encoding]);
231   });
232
233   obj.on('end', onEnd = function (data, encoding) {
234     events.push(['end', data, encoding]);
235   });
236
237   return {
238     end: function () {
239       obj.removeListener('data', onData);
240       obj.removeListener('end', onEnd);
241     },
242     destroy: function () {
243       this.end();
244         this.resume = function () {
245           console.error("Cannot resume buffer after destroying it.");
246         };
247
248         onData = onEnd = events = obj = null;
249     },
250     resume: function () {
251       this.end();
252       for (var i = 0, len = events.length; i < len; ++i) {
253         obj.emit.apply(obj, events[i]);
254       }
255     }
256   };
257 };
258
259 //
260 // ### function getMaxSockets ()
261 // Returns the maximum number of sockets
262 // allowed on __every__ outgoing request
263 // made by __all__ instances of `HttpProxy`
264 //
265 exports.getMaxSockets = function () {
266   return maxSockets;
267 };
268
269 //
270 // ### function setMaxSockets ()
271 // Sets the maximum number of sockets
272 // allowed on __every__ outgoing request
273 // made by __all__ instances of `HttpProxy`
274 //
275 exports.setMaxSockets = function (value) {
276   maxSockets = value;
277 };
278
279 //
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).
287 //
288 // adapted from https://github.com/creationix/stack
289 //
290 exports.stack = function stack (middlewares, proxy) {
291   var handle;
292   middlewares.reverse().forEach(function (layer) {
293     var child = handle;
294     handle = function (req, res) {
295       var next = function (err) {
296         if (err) {
297           if (! proxy.emit('middlewareError', err, req, res)) {
298             console.error('Error in middleware(s): %s', err.stack);
299           }
300
301           if (res._headerSent) {
302             res.destroy();
303           }
304           else {
305             res.statusCode = 500;
306             res.setHeader('Content-Type', 'text/plain');
307             res.end('Internal Server Error');
308           }
309
310           return;
311         }
312
313         if (child) {
314           child(req, res);
315         }
316       };
317
318       //
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.
322       //
323       // e.g. `function (req, res, next)` vs. `function (req, res, proxy)`
324       //
325       next.__proto__ = proxy;
326       layer(req, res, next);
327     };
328   });
329
330   return handle;
331 };
332
333 //
334 // ### function _getAgent (host, port, secure)
335 // #### @options {Object} Options to use when creating the agent.
336 //
337 //    {
338 //      host: 'localhost',
339 //      port: 9000,
340 //      https: true,
341 //      maxSockets: 100
342 //    }
343 //
344 // Createsan agent from the `http` or `https` module
345 // and sets the `maxSockets` property appropriately.
346 //
347 exports._getAgent = function _getAgent (options) {
348   if (!options || !options.host) {
349     throw new Error('`options.host` is required to create an Agent.');
350   }
351
352   if (!options.port) {
353     options.port = options.https ? 443 : 80;
354   }
355
356   var Agent = options.https ? https.Agent : http.Agent,
357       agent;
358
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);
363
364   return agent;
365 }
366
367 //
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.
372 //
373 exports._getProtocol = function _getProtocol (options) {
374   return options.https ? https : http;
375 };
376
377
378 //
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.
384 //
385 exports._getBase = function _getBase (options) {
386   var result = function () {};
387
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];
392       }
393     });
394   }
395
396   return result;
397 };