aboutsummaryrefslogtreecommitdiffstats
path: root/vnfmarket/src/main/webapp/vnfmarket/node_modules/http-proxy/lib/node-http-proxy/proxy-table.js
blob: 320396fe8a6a5fda0c70c37b734f9ebddc73b161 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/*
  node-http-proxy.js: Lookup table for proxy targets in node.js

  Copyright (c) 2010 Charlie Robbins

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var util = require('util'),
    events = require('events'),
    fs = require('fs'),
    url = require('url');

//
// ### function ProxyTable (router, silent)
// #### @router {Object} Object containing the host based routes
// #### @silent {Boolean} Value indicating whether we should suppress logs
// #### @hostnameOnly {Boolean} Value indicating if we should route based on __hostname string only__
// #### @pathnameOnly {Boolean} Value indicating if we should route based on only the pathname.  __This causes hostnames to be ignored.__.  Using this along with hostnameOnly wont work at all.
// Constructor function for the ProxyTable responsible for getting
// locations of proxy targets based on ServerRequest headers; specifically
// the HTTP host header.
//
var ProxyTable = exports.ProxyTable = function (options) {
  events.EventEmitter.call(this);

  this.silent       = options.silent || options.silent !== true;
  this.target       = options.target || {};
  this.pathnameOnly = options.pathnameOnly === true;
  this.hostnameOnly = options.hostnameOnly === true;

  if (typeof options.router === 'object') {
    //
    // If we are passed an object literal setup
    // the routes with RegExps from the router
    //
    this.setRoutes(options.router);
  }
  else if (typeof options.router === 'string') {
    //
    // If we are passed a string then assume it is a
    // file path, parse that file and watch it for changes
    //
    var self = this;
    this.routeFile = options.router;
    this.setRoutes(JSON.parse(fs.readFileSync(options.router)).router);

    fs.watchFile(this.routeFile, function () {
      fs.readFile(self.routeFile, function (err, data) {
        if (err) {
          self.emit('error', err);
        }

        self.setRoutes(JSON.parse(data).router);
        self.emit('routes', self.hostnameOnly === false ? self.routes : self.router);
      });
    });
  }
  else {
    throw new Error('Cannot parse router with unknown type: ' + typeof router);
  }
};

//
// Inherit from `events.EventEmitter`
//
util.inherits(ProxyTable, events.EventEmitter);

//
// ### function addRoute (route, target)
// #### @route {String} String containing route coming in
// #### @target {String} String containing the target
// Adds a host-based route to this instance.
//
ProxyTable.prototype.addRoute = function (route, target) {
  if (!this.router) {
    throw new Error('Cannot update ProxyTable routes without router.');
  }

  this.router[route] = target;
  this.setRoutes(this.router);
};

//
// ### function removeRoute (route)
// #### @route {String} String containing route to remove
// Removes a host-based route from this instance.
//
ProxyTable.prototype.removeRoute = function (route) {
  if (!this.router) {
    throw new Error('Cannot update ProxyTable routes without router.');
  }

  delete this.router[route];
  this.setRoutes(this.router);
};

//
// ### function setRoutes (router)
// #### @router {Object} Object containing the host based routes
// Sets the host-based routes to be used by this instance.
//
ProxyTable.prototype.setRoutes = function (router) {
  if (!router) {
    throw new Error('Cannot update ProxyTable routes without router.');
  }

  var self = this;
  this.router = router;

  if (this.hostnameOnly === false) {
    this.routes = [];

    Object.keys(router).forEach(function (path) {
      if (!/http[s]?/.test(router[path])) {
        router[path] = (self.target.https ? 'https://' : 'http://')
          + router[path];
      }

      var target = url.parse(router[path]),
          defaultPort = self.target.https ? 443 : 80;

      //
      // Setup a robust lookup table for the route:
      //
      //    {
      //      source: {
      //        regexp: /^foo.com/i,
      //        sref: 'foo.com',
      //        url: {
      //          protocol: 'http:',
      //          slashes: true,
      //          host: 'foo.com',
      //          hostname: 'foo.com',
      //          href: 'http://foo.com/',
      //          pathname: '/',
      //          path: '/'
      //        }
      //    },
      //    {
      //      target: {
      //        sref: '127.0.0.1:8000/',
      //        url: {
      //          protocol: 'http:',
      //          slashes: true,
      //          host: '127.0.0.1:8000',
      //          hostname: '127.0.0.1',
      //          href: 'http://127.0.0.1:8000/',
      //          pathname: '/',
      //          path: '/'
      //        }
      //    },
      //
      self.routes.push({
        source: {
          regexp: new RegExp('^' + path, 'i'),
          sref: path,
          url: url.parse('http://' + path)
        },
        target: {
          sref: target.hostname + ':' + (target.port || defaultPort) + target.path,
          url: target
        }
      });
    });
  }
};

//
// ### function getProxyLocation (req)
// #### @req {ServerRequest} The incoming server request to get proxy information about.
// Returns the proxy location based on the HTTP Headers in the  ServerRequest `req`
// available to this instance.
//
ProxyTable.prototype.getProxyLocation = function (req) {
  if (!req || !req.headers || !req.headers.host) {
    return null;
  }

  var targetHost = req.headers.host.split(':')[0];
  if (this.hostnameOnly === true) {
    var target = targetHost;
    if (this.router.hasOwnProperty(target)) {
      var location = this.router[target].split(':'),
          host = location[0],
          port = location.length === 1 ? 80 : location[1];

      return {
        port: port,
        host: host
      };
    }
  }
  else if (this.pathnameOnly === true) {
    var target = req.url;
    for (var i in this.routes) {
      var route = this.routes[i];
      //
      // If we are matching pathname only, we remove the matched pattern.
      //
      // IE /wiki/heartbeat
      // is redirected to
      // /heartbeat
      //
      // for the route "/wiki" : "127.0.0.1:8020"
      //
      if (target.match(route.source.regexp)) {
        req.url = url.format(target.replace(route.source.regexp, ''));
        return {
          protocol: route.target.url.protocol.replace(':', ''),
          host: route.target.url.hostname,
          port: route.target.url.port
            || (this.target.https ? 443 : 80)
        };
      }
    }

  }
  else {
    var target = targetHost + req.url;
    for (var i in this.routes) {
      var route = this.routes[i];
      if (target.match(route.source.regexp)) {
        //
        // Attempt to perform any path replacement for differences
        // between the source path and the target path. This replaces the
        // path's part of the URL to the target's part of the URL.
        //
        // 1. Parse the request URL
        // 2. Replace any portions of the source path with the target path
        // 3. Set the request URL to the formatted URL with replacements.
        //
        var parsed = url.parse(req.url);

        parsed.pathname = parsed.pathname.replace(
          route.source.url.pathname,
          route.target.url.pathname
        );

        req.url = url.format(parsed);

        return {
          protocol: route.target.url.protocol.replace(':', ''),
          host: route.target.url.hostname,
          port: route.target.url.port
            || (this.target.https ? 443 : 80)
        };
      }
    }
  }

  return null;
};

//
// ### close function ()
// Cleans up the event listeneners maintained
// by this instance.
//
ProxyTable.prototype.close = function () {
  if (typeof this.routeFile === 'string') {
    fs.unwatchFile(this.routeFile);
  }
};