Server modules location in config. Control module included
[KiwiIRC.git] / server_modules / control.js
1 /**
2 * Server control via TCP socket
3 *
4 * Listens on localhost:8888 by default
5 */
6
7 var net = require('net'),
8 kiwiModules = require('../server/modules'),
9 rehash = require('../server/rehash.js'),
10 config = require('../server/configuration.js'),
11 _ = require('lodash');
12
13 var module = new kiwiModules.Module('Control');
14
15
16 function SocketClient (socket) {
17 this.socket = socket;
18
19 this.remoteAddress = this.socket.remoteAddress;
20 console.log('Control connection from ' + this.socket.remoteAddress + ' opened');
21
22 this.bindEvents();
23
24 socket.write("\nHello, you are connected to the Kiwi server :)\n\n");
25 this.displayPrompt();
26 }
27
28 SocketClient.prototype.bindEvents = function() {
29 var that = this;
30
31 this.socket.on('data', function() { that.onData.apply(that, arguments); });
32 this.socket.on('close', function() { that.onClose.apply(that, arguments); });
33 };
34 SocketClient.prototype.unbindEvents = function() {
35 this.socket.removeAllListeners();
36 };
37
38
39
40 SocketClient.prototype.write = function(data, append) {
41 if (typeof append === 'undefined') append = '\n';
42 this.socket.write(data + append);
43 };
44 SocketClient.prototype.displayPrompt = function(prompt) {
45 prompt = prompt || 'Kiwi > ';
46 this.write(prompt, '');
47 };
48
49
50
51 SocketClient.prototype.onData = function(data) {
52 data = data.toString().trim();
53
54 try {
55 switch (data) {
56 case 'modules':
57 this.write('Loaded modules: ' + Object.keys(kiwiModules.getRegisteredModules()).join(', '));
58 break;
59
60 case 'stats':
61 this.write('Connected clients: ' + _.size(global.clients.clients).toString());
62 this.write('Num. remote hosts: ' + _.size(global.clients.addresses).toString());
63 break;
64
65 case 'rehash':
66 rehash.rehashAll();
67 this.write('Rehashed');
68 break;
69
70 case 'reconfig':
71 if (config.loadConfig()) {
72 this.write('New config file loaded');
73 } else {
74 this.write("No new config file was loaded");
75 }
76 break;
77
78 case 'exit':
79 case 'quit':
80 this.socket.destroy();
81 break;
82
83 default:
84 this.write('Unrecognised command: ' + data);
85 }
86 } catch (err) {
87 console.log('[Control error] ' + err);
88 this.write('An error occured. Check the Kiwi server log for more details');
89 }
90
91 this.displayPrompt();
92 };
93
94
95 SocketClient.prototype.onClose = function() {
96 this.unbindEvents();
97 console.log('Control connection from ' + this.remoteAddress + ' closed');
98 };
99
100
101
102
103 var server = net.createServer(function (socket) {
104 new SocketClient(socket);
105 });
106 server.listen(8888);