Add a limit to the number of connections made to irc servers
[KiwiIRC.git] / server / irc / state.js
1 var util = require('util'),
2 events = require('events'),
3 _ = require('lodash'),
4 IrcConnection = require('./connection.js').IrcConnection;
5
6 var State = function (client, save_state) {
7 var that = this;
8
9 events.EventEmitter.call(this);
10 this.client = client;
11 this.save_state = save_state || false;
12
13 this.irc_connections = [];
14 this.next_connection = 0;
15
16 this.client.on('dispose', function () {
17 if (!that.save_state) {
18 _.each(that.irc_connections, function (irc_connection, i, cons) {
19 if (irc_connection) {
20 irc_connection.end('QUIT :' + (global.config.quit_message || ''));
21 irc_connection.dispose();
22 global.servers.removeConnection(irc_connection);
23 cons[i] = null;
24 }
25 });
26
27 that.dispose();
28 }
29 });
30 };
31
32 util.inherits(State, events.EventEmitter);
33
34 module.exports = State;
35
36 State.prototype.connect = function (hostname, port, ssl, nick, user, pass, callback) {
37 var that = this;
38 var con, con_num;
39 if (global.config.restrict_server) {
40 con = new IrcConnection(
41 global.config.restrict_server,
42 global.config.restrict_server_port,
43 global.config.restrict_server_ssl,
44 nick,
45 user,
46 global.config.restrict_server_password,
47 this);
48
49 } else {
50 if ((global.config.max_server_conns > 0) && (!(global.config.webirc_pass && global.config.webirc_passs[hostname]))) {
51 if (global.servers.numOnHost(hostname) >= global.config.max_server_conns) {
52 return callback('Too many connections to host', {host: hostname, limit: global.config.max_server_conns});
53 }
54 }
55 con = new IrcConnection(
56 hostname,
57 port,
58 ssl,
59 nick,
60 user,
61 pass,
62 this);
63 }
64
65 con_num = this.next_connection++;
66 this.irc_connections[con_num] = con;
67 con.con_num = con_num;
68
69 new IrcCommands(con, con_num, this).bindEvents();
70
71 con.on('connected', function () {
72 global.servers.addConnection(this);
73 return callback(null, con_num);
74 });
75
76 con.on('error', function (err) {
77 console.log('irc_connection error (' + hostname + '):', err);
78 return callback(err.code, {server: con_num, error: err});
79 });
80
81 con.on('close', function () {
82 that.irc_connections[con_num] = null;
83 global.servers.removeConnection(this);
84 });
85 };
86
87 State.prototype.sendIrcCommand = function () {
88 this.client.sendIrcCommand.apply(this.client, arguments);
89 };
90
91 State.prototype.sendKiwiCommand = function () {
92 this.client.sendKiwicommand.apply(this.client, arguments);
93 };
94
95 State.prototype.dispose = function () {
96 this.emit('dispose');
97 this.removeAllListeners();
98 };