Merge pull request #336 from M2Ys4U/userbox
[KiwiIRC.git] / server / weblistener.js
1 var engine = require('engine.io'),
2 WebsocketRpc = require('./websocketrpc.js');
3 events = require('events'),
4 http = require('http'),
5 https = require('https'),
6 util = require('util'),
7 fs = require('fs'),
8 dns = require('dns'),
9 url = require('url'),
10 _ = require('lodash'),
11 spdy = require('spdy'),
12 ipaddr = require('ipaddr.js'),
13 Client = require('./client.js').Client,
14 HttpHandler = require('./httphandler.js').HttpHandler,
15 rehash = require('./rehash.js');
16
17
18
19 rehash.on('rehashed', function (files) {
20 Client = require('./client.js').Client;
21 HttpHandler = require('./httphandler.js').HttpHandler;
22 });
23
24
25 // Instance of HttpHandler
26 var http_handler;
27
28
29 var WebListener = module.exports = function (web_config, transports) {
30 var hs, opts,
31 that = this;
32
33
34 events.EventEmitter.call(this);
35
36 http_handler = new HttpHandler(web_config);
37
38 if (web_config.ssl) {
39 opts = {
40 key: fs.readFileSync(web_config.ssl_key),
41 cert: fs.readFileSync(web_config.ssl_cert)
42 };
43
44 // Do we have an intermediate certificate?
45 if (typeof web_config.ssl_ca !== 'undefined') {
46 // An array of them?
47 if (typeof web_config.ssl_ca.map !== 'undefined') {
48 opts.ca = web_config.ssl_ca.map(function (f) { return fs.readFileSync(f); });
49
50 } else {
51 opts.ca = fs.readFileSync(web_config.ssl_ca);
52 }
53 }
54
55 hs = spdy.createServer(opts, handleHttpRequest);
56
57 hs.listen(web_config.port, web_config.address, function () {
58 that.emit('listening');
59 });
60 } else {
61
62 // Start some plain-text server up
63 hs = http.createServer(handleHttpRequest);
64
65 hs.listen(web_config.port, web_config.address, function () {
66 that.emit('listening');
67 });
68 }
69
70 hs.on('error', function (err) {
71 that.emit('error', err);
72 });
73
74 this.ws = engine.attach(hs, {
75 transports: ['websocket', 'polling', 'flashsocket'],
76 path: (global.config.http_base_path || '') + '/transport'
77 });
78
79 this.ws.on('connection', function(socket) {
80 initialiseSocket(socket, function(err, authorised) {
81 var client;
82
83 if (!authorised) {
84 socket.close();
85 return;
86 }
87
88 client = new Client(socket);
89 client.on('dispose', function () {
90 that.emit('client_dispose', this);
91 });
92
93 that.emit('connection', client);
94 });
95 });
96 };
97 util.inherits(WebListener, events.EventEmitter);
98
99
100
101 function handleHttpRequest(request, response) {
102 http_handler.serve(request, response);
103 }
104
105 function rangeCheck(addr, range) {
106 var i, ranges, parts;
107 ranges = (!_.isArray(range)) ? [range] : range;
108 for (i = 0; i < ranges.length; i++) {
109 parts = ranges[i].split('/');
110 if (ipaddr.process(addr).match(ipaddr.process(parts[0]), parts[1])) {
111 return true;
112 }
113 }
114 return false;
115 }
116
117
118 /**
119 * Get the reverse DNS entry for this connection.
120 * Used later on for webirc, etc functionality
121 */
122 function initialiseSocket(socket, callback) {
123 var request = socket.request,
124 address = request.connection.remoteAddress;
125
126 // Key/val data stored to the socket to be read later on
127 // May also be synced to a redis DB to lookup clients
128 socket.meta = {};
129
130 // If a forwarded-for header is found, switch the source address
131 if (request.headers[global.config.http_proxy_ip_header || 'x-forwarded-for']) {
132 // Check we're connecting from a whitelisted proxy
133 if (!global.config.http_proxies || !rangeCheck(address, global.config.http_proxies)) {
134 console.log('Unlisted proxy:', address);
135 callback(null, false);
136 return;
137 }
138
139 // We're sent from a whitelisted proxy, replace the hosts
140 address = request.headers[global.config.http_proxy_ip_header || 'x-forwarded-for'];
141 }
142
143 socket.meta.real_address = address;
144
145 // If enabled, don't go over the connection limit
146 if (global.config.max_client_conns && global.config.max_client_conns > 0) {
147 if (global.clients.numOnAddress(address) + 1 > global.config.max_client_conns) {
148 return callback(null, false);
149 }
150 }
151
152
153 try {
154 dns.reverse(address, function (err, domains) {
155 if (err || domains.length === 0) {
156 socket.meta.revdns = address;
157 } else {
158 socket.meta.revdns = _.first(domains) || address;
159 }
160
161 // All is well, authorise the connection
162 callback(null, true);
163 });
164 } catch (err) {
165 socket.meta.revdns = address;
166 callback(null, true);
167 }
168 }