Grafting the new server to the new backbone client
[KiwiIRC.git] / server / web.js
1 var ws = require('socket.io'),
2 events = require('events'),
3 http = require('http'),
4 https = require('https'),
5 util = require('util'),
6 fs = require('fs'),
7 dns = require('dns'),
8 _ = require('underscore'),
9 Client = require('./client.js').Client;
10 HTTPHandler = require('./http-handler.js').HTTPHandler;
11
12 var WebListener = function (config, transports) {
13 var handler,
14 hs,
15 opts,
16 that = this;
17
18 events.EventEmitter.call(this);
19
20 http_handler = new HTTPHandler(config);
21
22 if (config.secure) {
23 opts = {
24 key: fs.readFileSync(__dirname + '/' + config.ssl_key),
25 cert: fs.readFileSync(__dirname + '/' + config.ssl_cert)
26 };
27 // Do we have an intermediate certificate?
28 if (typeof config.ssl_ca !== 'undefined') {
29 opts.ca = fs.readFileSync(__dirname + '/' + config.ssl_ca);
30 }
31 hs = https.createServer(opts, function (request, response) {
32 http_handler.handler(request, response);
33 });
34
35 this.ws = ws.listen(hs, {secure: true});
36 hs.listen(config.port, config.address);
37 console.log('Listening on ' + config.address + ':' + config.port.toString() + ' with SSL');
38 } else {
39 // Start some plain-text server up
40 hs = http.createServer(function (request, response) {
41 http_handler.handler(request, response);
42 });
43 this.ws = ws.listen(hs, {secure: false});
44 hs.listen(config.port, config.address);
45 console.log('Listening on ' + config.address + ':' + config.port.toString() + ' without SSL');
46 }
47
48 this.ws.set('log level', 1);
49 this.ws.enable('browser client minification');
50 this.ws.enable('browser client etag');
51 this.ws.set('transports', transports);
52
53 this.ws.of('/kiwi').authorization(authorisation).on('connection', function () {
54 connection.apply(that, arguments);
55 });
56 this.ws.of('/kiwi').on('error', console.log);
57 };
58 util.inherits(WebListener, events.EventEmitter);
59
60 module.exports.WebListener = WebListener;
61
62 var authorisation = function (handshakeData, callback) {
63 dns.reverse(handshakeData.address.address, function (err, domains) {
64 handshakeData.revdns = (err) ? handshakeData.address.address : _.first(domains);
65 callback(null, true);
66 });
67 };
68
69 var connection = function (websocket) {
70 //console.log(websocket);
71 this.emit('connection', new Client(websocket));
72 };