1 /*jslint continue: true, forin: true, regexp: true, confusion: true, undef: false, node: true, sloppy: true, nomen: true, plusplus: true, maxerr: 50, indent: 4 */
3 var tls
= require('tls'),
5 http
= require('http'),
6 https
= require('https'),
9 ws
= require('socket.io'),
10 _
= require('./lib/underscore.min.js'),
11 starttls
= require('./lib/starttls.js');
13 // Libraries may need to know kiwi.js path as __dirname
14 // only gives that librarys path. Set it here for usage later.
15 var kiwi_root
= __dirname
;
19 * Find a config file in the following order:
20 * - /etc/kiwi/config.json
24 config_filename
= 'config.json',
25 config_dirs
= ['/etc/kiwiirc/', __dirname
+ '/'];
29 for (i
in config_dirs
) {
31 if (fs
.lstatSync(config_dirs
[i
] + config_filename
).isDirectory() === false) {
32 config
= JSON
.parse(fs
.readFileSync(config_dirs
[i
] + config_filename
, 'ascii'));
33 console
.log('Using config file ' + config_dirs
[i
] + config_filename
);
41 if (config
=== null) {
42 console
.log('Couldn\'t find a config file!');
49 * Load the modules as set in the config and print them out
51 var kiwi_mod
= require('./lib/kiwi_mod.js');
52 kiwi_mod
.loadModules(kiwi_root
, config
);
59 * Some process changes
61 process
.title
= 'kiwiirc';
62 var changeUser = function () {
63 if (typeof config
.group
!== 'undefined' && config
.group
!== '') {
65 process
.setgid(config
.group
);
67 console
.log('Failed to set gid: ' + err
);
72 if (typeof config
.user
!== 'undefined' && config
.user
!== '') {
74 process
.setuid(config
.user
);
76 console
.log('Failed to set uid: ' + e
);
84 * And now KiwiIRC, the server :)
92 RPL_WHOISSERVER
: '312',
93 RPL_WHOISOPERATOR
: '313',
95 RPL_ENDOFWHOIS
: '318',
96 RPL_WHOISCHANNELS
: '319',
100 RPL_ENDOFNAMES
: '366',
102 RPL_WHOISMODES
: '379',
103 ERR_NOSUCHNICK
: '401',
104 ERR_CANNOTSENDTOCHAN
: '404',
105 ERR_TOOMANYCHANNELS
: '405',
106 ERR_USERNOTINCHANNEL
: '441',
107 ERR_NOTONCHANNEL
: '442',
108 ERR_LINKCHANNEL
: '470',
109 ERR_CHANNELISFULL
: '471',
110 ERR_INVITEONLYCHAN
: '473',
111 ERR_BANNEDFROMCHAN
: '474',
112 ERR_BADCHANNELKEY
: '475',
113 ERR_CHANOPRIVSNEEDED
: '482',
120 var parseIRCMessage = function (websocket
, ircSocket
, data
) {
121 /*global ircSocketDataHandler */
122 var msg
, regex
, opts
, options
, opt
, i
, j
, matches
, nick
, users
, chan
, params
, prefix
, prefixes
, nicklist
, caps
, rtn
, obj
;
123 regex
= /^(?::(?:([a-z0-9\x5B-\x60\x7B-\x7D\.\-]+)|([a-z0-9\x5B-\x60\x7B-\x7D\.\-]+)!([a-z0-9~\.\-_|]+)@?([a-z0-9\.\-:]+)?) )?([a-z0-9]+)(?:(?: ([^:]+))?(?: :(.+))?)$/i;
124 msg
= regex
.exec(data
);
130 hostname
: (msg
[4]) ? msg
[4] : '',
132 params
: msg
[6] || '',
133 trailing
: (msg
[7]) ? msg
[7].trim() : ''
135 switch (msg
.command
.toUpperCase()) {
137 websocket
.sendServerLine('PONG ' + msg
.trailing
);
139 case ircNumerics
.RPL_WELCOME
:
140 if (ircSocket
.IRC
.CAP
.negotiating
) {
141 ircSocket
.IRC
.CAP
.negotiating
= false;
142 ircSocket
.IRC
.CAP
.enabled
= [];
143 ircSocket
.IRC
.CAP
.requested
= [];
145 websocket
.sendClientEvent('connect', {connected
: true, host
: null});
147 case ircNumerics
.RPL_ISUPPORT
:
148 opts
= msg
.params
.split(" ");
150 for (i
= 0; i
< opts
.length
; i
++) {
151 opt
= opts
[i
].split("=", 2);
152 opt
[0] = opt
[0].toUpperCase();
153 ircSocket
.IRC
.options
[opt
[0]] = opt
[1] || true;
154 if (_
.include(['NETWORK', 'PREFIX', 'CHANTYPES'], opt
[0])) {
155 if (opt
[0] === 'PREFIX') {
156 regex
= /\(([^)]*)\)(.*)/;
157 matches
= regex
.exec(opt
[1]);
158 if ((matches
) && (matches
.length
=== 3)) {
159 ircSocket
.IRC
.options
[opt
[0]] = [];
160 for (j
= 0; j
< matches
[2].length
; j
++) {
161 //ircSocket.IRC.options[opt[0]][matches[2].charAt(j)] = matches[1].charAt(j);
162 ircSocket
.IRC
.options
[opt
[0]].push({symbol
: matches
[2].charAt(j
), mode
: matches
[1].charAt(j
)});
163 //console.log({symbol: matches[2].charAt(j), mode: matches[1].charAt(j)});
165 console
.log(ircSocket
.IRC
.options
);
170 websocket
.sendClientEvent('options', {server
: '', "options": ircSocket
.IRC
.options
});
172 case ircNumerics
.RPL_WHOISUSER
:
173 case ircNumerics
.RPL_WHOISSERVER
:
174 case ircNumerics
.RPL_WHOISOPERATOR
:
175 case ircNumerics
.RPL_ENDOFWHOIS
:
176 case ircNumerics
.RPL_WHOISCHANNELS
:
177 case ircNumerics
.RPL_WHOISMODES
:
178 websocket
.sendClientEvent('whois', {server
: '', nick
: msg
.params
.split(" ", 3)[1], "msg": msg
.trailing
});
180 case ircNumerics
.RPL_WHOISIDLE
:
181 params
= msg
.params
.split(" ", 4);
182 rtn
= {server
: '', nick
: params
[1], idle
: params
[2]};
184 rtn
.logon
= params
[3];
186 websocket
.sendClientEvent('whois', rtn
);
188 case ircNumerics
.RPL_MOTD
:
189 websocket
.sendClientEvent('motd', {server
: '', "msg": msg
.trailing
});
191 case ircNumerics
.RPL_NAMEREPLY
:
192 params
= msg
.params
.split(" ");
195 users
= msg
.trailing
.split(" ");
196 prefixes
= _
.values(ircSocket
.IRC
.options
.PREFIX
);
199 _
.each(users
, function (user
) {
200 if (_
.include(prefix
, user
.charAt(0))) {
201 prefix
= user
.charAt(0);
202 user
= user
.substring(1);
203 nicklist
[user
] = prefix
;
208 websocket
.sendClientEvent('userlist', {server
: '', 'users': nicklist
, channel
: chan
});
214 websocket
.sendClientEvent('userlist', {server
: '', "users": nicklist
, channel
: chan
});
219 case ircNumerics
.RPL_ENDOFNAMES
:
220 websocket
.sendClientEvent('userlist_end', {server
: '', channel
: msg
.params
.split(" ")[1]});
222 case ircNumerics
.ERR_LINKCHANNEL
:
223 params
= msg
.params
.split(" ");
224 websocket
.sendClientEvent('channel_redirect', {from: params
[1], to
: params
[2]});
226 case ircNumerics
.ERR_NOSUCHNICK
:
227 websocket
.sendClientEvent('irc_error', {error
: 'no_such_nick', nick
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
230 // Some BNC's send malformed JOIN causing the channel to be as a
231 // parameter instead of trailing.
232 if(typeof msg
.trailing
=== 'string' && msg
.trailing
!== ''){
233 channel
= msg
.trailing
;
234 } else if(typeof msg
.params
=== 'string' && msg
.params
!== ''){
235 channel
= msg
.params
;
238 websocket
.sendClientEvent('join', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: channel
});
239 if (msg
.nick
=== ircSocket
.IRC
.nick
) {
240 websocket
.sendServerLine('NAMES ' + msg
.trailing
);
244 websocket
.sendClientEvent('part', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: msg
.params
.trim(), message
: msg
.trailing
});
247 params
= msg
.params
.split(" ");
248 websocket
.sendClientEvent('kick', {kicked
: params
[1], nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: params
[0].trim(), message
: msg
.trailing
});
251 websocket
.sendClientEvent('quit', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, message
: msg
.trailing
});
254 if ((msg
.trailing
.charAt(0) === String
.fromCharCode(1)) && (msg
.trailing
.charAt(msg
.trailing
.length
- 1) === String
.fromCharCode(1))) {
255 // It's a CTCP response
256 websocket
.sendClientEvent('ctcp_response', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: msg
.params
.trim(), msg
: msg
.trailing
.substr(1, msg
.trailing
.length
- 2)});
258 websocket
.sendClientEvent('notice', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: msg
.params
.trim(), msg
: msg
.trailing
});
262 websocket
.sendClientEvent('nick', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, newnick
: msg
.trailing
});
265 obj
= {nick
: msg
.nick
, channel
: msg
.params
, topic
: msg
.trailing
};
266 websocket
.sendClientEvent('topic', obj
);
268 case ircNumerics
.RPL_TOPIC
:
269 obj
= {nick
: '', channel
: msg
.params
.split(" ")[1], topic
: msg
.trailing
};
270 websocket
.sendClientEvent('topic', obj
);
272 case ircNumerics
.RPL_NOTOPIC
:
273 obj
= {nick
: '', channel
: msg
.params
.split(" ")[1], topic
: ''};
274 websocket
.sendClientEvent('topic', obj
);
277 opts
= msg
.params
.split(" ");
278 params
= {nick
: msg
.nick
};
279 switch (opts
.length
) {
281 params
.effected_nick
= opts
[0];
282 params
.mode
= msg
.trailing
;
285 params
.channel
= opts
[0];
286 params
.mode
= opts
[1];
289 params
.channel
= opts
[0];
290 params
.mode
= opts
[1];
291 params
.effected_nick
= opts
[2];
294 websocket
.sendClientEvent('mode', params
);
297 if ((msg
.trailing
.charAt(0) === String
.fromCharCode(1)) && (msg
.trailing
.charAt(msg
.trailing
.length
- 1) === String
.fromCharCode(1))) {
298 // It's a CTCP request
299 if (msg
.trailing
.substr(1, 6) === 'ACTION') {
300 websocket
.sendClientEvent('action', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: msg
.params
.trim(), msg
: msg
.trailing
.substr(7, msg
.trailing
.length
- 2)});
301 } else if (msg
.trailing
.substr(1, 7) === 'VERSION') {
302 ircSocket
.write('NOTICE ' + msg
.nick
+ ' :' + String
.fromCharCode(1) + 'VERSION KiwiIRC' + String
.fromCharCode(1) + '\r\n');
304 websocket
.sendClientEvent('ctcp_request', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: msg
.params
.trim(), msg
: msg
.trailing
.substr(1, msg
.trailing
.length
- 2)});
307 obj
= {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: msg
.params
.trim(), msg
: msg
.trailing
};
308 websocket
.sendClientEvent('msg', obj
);
312 caps
= config
.cap_options
;
313 options
= msg
.trailing
.split(" ");
314 switch (_
.first(msg
.params
.split(" "))) {
317 _
.each(_
.intersect(caps
, options
), function (cap
) {
322 ircSocket
.IRC
.CAP
.requested
.push(cap
);
324 if (opts
.length
> 0) {
325 websocket
.sendServerLine('CAP REQ :' + opts
);
327 websocket
.sendServerLine('CAP END');
330 /*if (_.include(options, 'tls')) {
331 websocket.sendServerLine('STARTTLS');
332 ircSocket.IRC.CAP.requested.push('tls');
336 _
.each(options
, function (cap
) {
337 ircSocket
.IRC
.CAP
.enabled
.push(cap
);
339 if (_
.last(msg
.params
.split(" ")) !== '*') {
340 ircSocket
.IRC
.CAP
.requested
= [];
341 ircSocket
.IRC
.CAP
.negotiating
= false;
342 websocket
.sendServerLine('CAP END');
346 ircSocket
.IRC
.CAP
.requested
= [];
347 ircSocket
.IRC
.CAP
.negotiating
= false;
348 websocket
.sendServerLine('CAP END');
352 /*case ircNumerics.RPL_STARTTLS:
355 listeners = ircSocket.listeners('data');
356 ircSocket.removeAllListeners('data');
357 ssl_socket = starttls(ircSocket, {}, function () {
358 ssl_socket.on("data", function (data) {
359 ircSocketDataHandler(data, websocket, ssl_socket);
361 ircSocket = ssl_socket;
363 _.each(listeners, function (listener) {
364 ircSocket.addListener('data', listener);
367 //console.log(ircSocket);
372 case ircNumerics
.ERR_CANNOTSENDTOCHAN
:
373 websocket
.sendClientEvent('irc_error', {error
: 'cannot_send_to_chan', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
375 case ircNumerics
.ERR_TOOMANYCHANNELS
:
376 websocket
.sendClientEvent('irc_error', {error
: 'too_many_channels', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
378 case ircNumerics
.ERR_USERNOTINCHANNEL
:
379 params
= msg
.params
.split(" ");
380 websocket
.sendClientEvent('irc_error', {error
: 'user_not_in_channel', nick
: params
[0], channel
: params
[1], reason
: msg
.trainling
});
382 case ircNumerics
.ERR_NOTONCHANNEL
:
383 websocket
.sendClientEvent('irc_error', {error
: 'not_on_channel', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
385 case ircNumerics
.ERR_CHANNELISFULL
:
386 websocket
.sendClientEvent('irc_error', {error
: 'channel_is_full', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
388 case ircNumerics
.ERR_INVITEONLYCHAN
:
389 websocket
.sendClientEvent('irc_error', {error
: 'invite_only_channel', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
391 case ircNumerics
.ERR_BANNEDFROMCHAN
:
392 websocket
.sendClientEvent('irc_error', {error
: 'banned_from_channel', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
394 case ircNumerics
.ERR_BADCHANNELKEY
:
395 websocket
.sendClientEvent('irc_error', {error
: 'bad_channel_key', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
397 case ircNumerics
.ERR_CHANOPRIVSNEEDED
:
398 websocket
.sendClientEvent('irc_error', {error
: 'chanop_privs_needed', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
402 console
.log("Unknown command (" + String(msg
.command
).toUpperCase() + ")");
405 console
.log("Malformed IRC line");
411 * NOTE: Some IRC servers or BNC's out there incorrectly use
412 * only \n as a line splitter.
414 var ircSocketDataHandler = function (data
, websocket
, ircSocket
) {
416 if ((ircSocket
.holdLast
) && (ircSocket
.held
!== '')) {
417 data
= ircSocket
.held
+ data
;
418 ircSocket
.holdLast
= false;
421 if (data
.substr(-2) === '\n') {
422 ircSocket
.holdLast
= true;
424 data
= data
.split("\n");
425 for (i
= 0; i
< data
.length
; i
++) {
427 if ((ircSocket
.holdLast
) && (i
=== data
.length
- 1)) {
428 ircSocket
.held
= data
[i
];
431 console
.log("->" + data
[i
]);
432 parseIRCMessage(websocket
, ircSocket
, data
[i
].replace(/^\r+|\r+$/, '') );
437 if (config
.handle_http
) {
438 var fileServer
= new (require('node-static').Server
)(__dirname
+ config
.public_http
);
439 var jade
= require('jade');
442 var httpHandler = function (request
, response
) {
443 var uri
, subs
, useragent
, agent
, server_set
, server
, nick
, debug
, touchscreen
;
444 if (config
.handle_http
) {
445 uri
= url
.parse(request
.url
);
446 subs
= uri
.pathname
.substr(0, 4);
447 if ((subs
=== '/js/') || (subs
=== '/css') || (subs
=== '/img')) {
448 request
.addListener('end', function () {
449 fileServer
.serve(request
, response
);
451 } else if (uri
.pathname
=== '/') {
452 useragent
= (response
.headers
) ? response
.headers
['user-agent'] : '';
453 if (useragent
.indexOf('android') !== -1) {
456 } else if (useragent
.indexOf('iphone') !== -1) {
459 } else if (useragent
.indexOf('ipad') !== -1) {
462 } else if (useragent
.indexOf('ipod') !== -1) {
470 server_set
= (uri
.query
.server
!== '');
471 server
= uri
.query
.server
|| 'irc.anonnet.org';
472 nick
= uri
.query
.nick
|| '';
473 debug
= (uri
.query
.debug
!== '');
475 server
= 'irc.anonnet.org';
478 response
.setHeader('Connection', 'close');
479 response
.setHeader('X-Generated-By', 'KiwiIRC');
480 jade
.renderFile(__dirname
+ '/client/index.html.jade', { locals
: { "touchscreen": touchscreen
, "debug": debug
, "server_set": server_set
, "server": server
, "nick": nick
, "agent": agent
, "config": config
}}, function (err
, html
) {
482 response
.write(html
);
484 response
.statusCode
= 500;
488 } else if (uri
.pathname
.substr(0, 10) === '/socket.io') {
491 response
.statusCode
= 404;
497 //setup websocket listener
498 if (config
.listen_ssl
) {
499 var httpServer
= https
.createServer({key
: fs
.readFileSync(__dirname
+ '/' + config
.ssl_key
), cert
: fs
.readFileSync(__dirname
+ '/' + config
.ssl_cert
)}, httpHandler
);
500 var io
= ws
.listen(httpServer
, {secure
: true});
501 httpServer
.listen(config
.port
, config
.bind_address
);
503 var httpServer
= http
.createServer(httpHandler
);
504 var io
= ws
.listen(httpServer
, {secure
: false});
505 httpServer
.listen(config
.port
, config
.bind_address
);
507 io
.set('log level', 1);
509 // Now we're listening on the network, set our UID/GIDs if required
512 var connections
= {};
514 // The main socket listening/handling routines
515 io
.of('/kiwi').authorization(function (handshakeData
, callback
) {
516 var connection
, address
= handshakeData
.address
.address
;
517 if (typeof connections
[address
] === 'undefined') {
518 connections
[address
] = {count
: 0, sockets
: []};
520 callback(null, true);
521 }).on('connection', function (websocket
) {
523 websocket
.kiwi
= {address
: websocket
.handshake
.address
.address
};
524 con
= connections
[websocket
.kiwi
.address
];
525 if (con
.count
>= config
.max_client_conns
) {
526 websocket
.emit('too_many_connections');
527 websocket
.disconnect();
530 con
.sockets
.push(websocket
);
532 websocket
.sendClientEvent = function (event_name
, data
) {
533 kiwi_mod
.run(event_name
, data
, {websocket
: this});
534 data
.event
= event_name
;
535 websocket
.emit('message', data
);
538 websocket
.sendServerLine = function (data
, eol
) {
539 eol
= (typeof eol
=== 'undefined') ? '\r\n' : eol
;
540 //console.log('Out: -----\n' + data + '\n-----');
541 websocket
.ircSocket
.write(data
+ eol
);
544 websocket
.on('irc connect', function (nick
, host
, port
, ssl
, callback
) {
546 //setup IRC connection
548 ircSocket
= net
.createConnection(port
, host
);
550 ircSocket
= tls
.connect(port
, host
);
552 ircSocket
.setEncoding('ascii');
553 ircSocket
.IRC
= {options
: {}, CAP
: {negotiating
: true, requested
: [], enabled
: []}};
554 websocket
.ircSocket
= ircSocket
;
555 ircSocket
.holdLast
= false;
558 ircSocket
.on('data', function (data
) {
559 //console.log('In: -----\n' + data + '\n-----');
560 ircSocketDataHandler(data
, websocket
, ircSocket
);
563 ircSocket
.IRC
.nick
= nick
;
564 // Send the login data
565 websocket
.sendServerLine('CAP LS');
566 websocket
.sendServerLine('NICK ' + nick
);
567 websocket
.sendServerLine('USER ' + nick
+ '_kiwi 0 0 :' + nick
);
569 if ((callback
) && (typeof (callback
) === 'function')) {
573 websocket
.on('message', function (msg
, callback
) {
576 msg
.data
= JSON
.parse(msg
.data
);
577 args
= msg
.data
.args
;
578 switch (msg
.data
.method
) {
580 if ((args
.target
) && (args
.msg
)) {
581 obj
= kiwi_mod
.run('msgsend', args
, {websocket
: websocket
});
583 websocket
.sendServerLine('PRIVMSG ' + args
.target
+ ' :' + args
.msg
);
588 if ((args
.target
) && (args
.msg
)) {
589 websocket
.sendServerLine('PRIVMSG ' + args
.target
+ ' :\ 1ACTION ' + args
.msg
);
593 websocket
.sendServerLine(args
.data
);
597 _
.each(args
.channel
.split(","), function (chan
) {
598 websocket
.sendServerLine('JOIN ' + chan
);
604 websocket
.sendServerLine('TOPIC ' + args
.channel
+ ' :' + args
.topic
);
608 websocket
.ircSocket
.end('QUIT :' + args
.message
+ '\r\n');
609 websocket
.sentQUIT
= true;
610 websocket
.ircSocket
.destroySoon();
611 websocket
.disconnect();
614 if ((args
.target
) && (args
.msg
)) {
615 websocket
.sendServerLine('NOTICE ' + args
.target
+ ' :' + args
.msg
);
620 if ((callback
) && (typeof (callback
) === 'function')) {
624 console
.log("Caught error: " + e
);
629 websocket
.on('disconnect', function () {
630 if ((!websocket
.sentQUIT
) && (websocket
.ircSocket
)) {
631 websocket
.ircSocket
.end('QUIT :' + config
.quit_message
+ '\r\n');
632 websocket
.sentQUIT
= true;
633 websocket
.ircSocket
.destroySoon();
635 con
= connections
[websocket
.kiwi
.address
];
637 con
.sockets
= _
.reject(con
.sockets
, function (sock
) {
638 return sock
=== websocket
;