26d5b9c14b06d7c8c43b2636ac61f97f87a91bd6
[KiwiIRC.git] / server / kiwi.js
1 var fs = require('fs'),
2 _ = require('lodash'),
3 util = require('util'),
4 WebListener = require('./weblistener.js'),
5 config = require('./configuration.js'),
6 rehash = require('./rehash.js'),
7 modules = require('./modules.js'),
8 Identd = require('./identd.js');
9
10
11
12 process.chdir(__dirname + '/../');
13 config.loadConfig();
14
15
16 // If we're not running in the forground and we have a log file.. switch
17 // console.log to output to a file
18 if (process.argv.indexOf('-f') === -1 && global.config && global.config.log) {
19 (function () {
20 var log_file_name = global.config.log;
21
22 if (log_file_name[0] !== '/') {
23 log_file_name = __dirname + '/../' + log_file_name;
24 }
25
26
27
28 console.log = function() {
29 var logfile = fs.openSync(log_file_name, 'a'),
30 out;
31
32 out = util.format.apply(util, arguments);
33
34 // Make sure we out somthing to log and we have an open file
35 if (!out || !logfile) return;
36
37 out += '\n';
38 fs.writeSync(logfile, out, null);
39
40 fs.closeSync(logfile);
41 };
42 })();
43 }
44
45
46
47 // Make sure we have a valid config file and at least 1 server
48 if (!global.config || Object.keys(global.config).length === 0) {
49 console.log('Couldn\'t find a valid config.js file (Did you copy the config.example.js file yet?)');
50 process.exit(1);
51 }
52
53 if ((!global.config.servers) || (global.config.servers.length < 1)) {
54 console.log('No servers defined in config file');
55 process.exit(2);
56 }
57
58
59
60
61 // Create a plugin interface
62 global.modules = new modules.Publisher();
63
64 // Register as the active interface
65 modules.registerPublisher(global.modules);
66
67 // Load any modules in the config
68 if (global.config.module_dir) {
69 (global.config.modules || []).forEach(function (module_name) {
70 if (modules.load(module_name)) {
71 console.log('Module ' + module_name + ' loaded successfuly');
72 } else {
73 console.log('Module ' + module_name + ' failed to load');
74 }
75 });
76 }
77
78
79
80
81 // Holder for all the connected clients
82 global.clients = {
83 clients: Object.create(null),
84 addresses: Object.create(null),
85
86 // Local and foriegn port pairs for identd lookups
87 // {'65483_6667': client_obj, '54356_6697': client_obj}
88 port_pairs: {},
89
90 add: function (client) {
91 this.clients[client.hash] = client;
92 if (typeof this.addresses[client.real_address] === 'undefined') {
93 this.addresses[client.real_address] = Object.create(null);
94 }
95 this.addresses[client.real_address][client.hash] = client;
96 },
97
98 remove: function (client) {
99 if (typeof this.clients[client.hash] !== 'undefined') {
100 delete this.clients[client.hash];
101 delete this.addresses[client.real_address][client.hash];
102 if (Object.keys(this.addresses[client.real_address]).length < 1) {
103 delete this.addresses[client.real_address];
104 }
105 }
106 },
107
108 numOnAddress: function (addr) {
109 if (typeof this.addresses[addr] !== 'undefined') {
110 return Object.keys(this.addresses[addr]).length;
111 } else {
112 return 0;
113 }
114 }
115 };
116
117 global.servers = {
118 servers: Object.create(null),
119
120 addConnection: function (connection) {
121 var host = connection.irc_host.hostname;
122 if (!this.servers[host]) {
123 this.servers[host] = [];
124 }
125 this.servers[host].push(connection);
126 },
127
128 removeConnection: function (connection) {
129 var host = connection.irc_host.hostname
130 if (this.servers[host]) {
131 this.servers[host] = _.without(this.servers[host], connection);
132 if (this.servers[host].length === 0) {
133 delete this.servers[host];
134 }
135 }
136 },
137
138 numOnHost: function (host) {
139 if (this.servers[host]) {
140 return this.servers[host].length;
141 } else {
142 return 0;
143 }
144 }
145 };
146
147
148
149 config.on('loaded', function () {
150 for (var client in global.clients.clients) {
151 global.clients.clients[client].sendKiwiCommand('reconfig');
152 }
153 });
154
155
156
157 /*
158 * Identd server
159 */
160 if (global.config.identd && global.config.identd.enabled) {
161 var identd_resolve_user = function(port_here, port_there) {
162 var key = port_here.toString() + '_' + port_there.toString();
163
164 if (typeof global.clients.port_pairs[key] == 'undefined') {
165 return;
166 }
167
168 return global.clients.port_pairs[key].username;
169 };
170
171 var identd_server = new Identd({
172 bind_addr: global.config.identd.address,
173 bind_port: global.config.identd.port,
174 user_id: identd_resolve_user
175 });
176
177 identd_server.start();
178 }
179
180
181
182
183 /*
184 * Web listeners
185 */
186
187
188 // Start up a weblistener for each found in the config
189 _.each(global.config.servers, function (server) {
190 var wl = new WebListener(server, global.config.transports);
191
192 wl.on('connection', function (client) {
193 clients.add(client);
194 });
195
196 wl.on('client_dispose', function (client) {
197 clients.remove(client);
198 });
199
200 wl.on('listening', function () {
201 console.log('Listening on %s:%s %s SSL', server.address, server.port, (server.ssl ? 'with' : 'without'));
202 webListenerRunning();
203 });
204
205 wl.on('error', function (err) {
206 console.log('Error listening on %s:%s: %s', server.address, server.port, err.code);
207 // TODO: This should probably be refactored. ^JA
208 webListenerRunning();
209 });
210 });
211
212 // Once all the listeners are listening, set the processes UID/GID
213 var num_listening = 0;
214 function webListenerRunning() {
215 num_listening++;
216 if (num_listening === global.config.servers.length) {
217 setProcessUid();
218 }
219 }
220
221
222
223
224 /*
225 * Process settings
226 */
227
228 // Set process title
229 process.title = 'kiwiirc';
230
231 // Change UID/GID
232 function setProcessUid() {
233 if ((global.config.group) && (global.config.group !== '')) {
234 process.setgid(global.config.group);
235 }
236 if ((global.config.user) && (global.config.user !== '')) {
237 process.setuid(global.config.user);
238 }
239 }
240
241
242 // Make sure Kiwi doesn't simply quit on an exception
243 process.on('uncaughtException', function (e) {
244 console.log('[Uncaught exception] ' + e);
245 console.log(e.stack);
246 });
247
248
249 process.on('SIGUSR1', function() {
250 if (config.loadConfig()) {
251 console.log('New config file loaded');
252 } else {
253 console.log("No new config file was loaded");
254 }
255 });
256
257
258 process.on('SIGUSR2', function() {
259 console.log('Connected clients: ' + _.size(global.clients.clients).toString());
260 console.log('Num. remote hosts: ' + _.size(global.clients.addresses).toString());
261 });
262
263
264 /*
265 * Listen for runtime commands
266 */
267
268 process.stdin.resume();
269 process.stdin.on('data', function (buffered) {
270 var data = buffered.toString().trim();
271
272 switch (data) {
273 case 'stats':
274 console.log('Connected clients: ' + _.size(global.clients.clients).toString());
275 console.log('Num. remote hosts: ' + _.size(global.clients.addresses).toString());
276 break;
277
278 case 'reconfig':
279 if (config.loadConfig()) {
280 console.log('New config file loaded');
281 } else {
282 console.log("No new config file was loaded");
283 }
284
285 break;
286
287
288 case 'rehash':
289 (function () {
290 rehash.rehashAll();
291 console.log('Rehashed');
292 })();
293
294 break;
295
296 default:
297 console.log('Unrecognised command: ' + data);
298 }
299 });