1 /*jslint sloppy: true, continue: true, forin: true, regexp: true, undef: false, node: true, nomen: true, plusplus: true, maxerr: 50, indent: 4 */
18 this.init = function (objs
) {
31 starttls
= objs
.starttls
;
32 kiwi
= require('./kiwi.js');
41 * Some process changes
43 this.setTitle = function () {
44 process
.title
= 'kiwiirc';
47 this.changeUser = function () {
48 if (typeof kiwi
.config
.group
!== 'undefined' && kiwi
.config
.group
!== '') {
50 process
.setgid(kiwi
.config
.group
);
52 console
.log('Failed to set gid: ' + err
);
57 if (typeof kiwi
.config
.user
!== 'undefined' && kiwi
.config
.user
!== '') {
59 process
.setuid(kiwi
.config
.user
);
61 console
.log('Failed to set uid: ' + e
);
80 RPL_WHOISSERVER
: '312',
81 RPL_WHOISOPERATOR
: '313',
83 RPL_ENDOFWHOIS
: '318',
84 RPL_WHOISCHANNELS
: '319',
91 RPL_ENDOFNAMES
: '366',
93 RPL_WHOISMODES
: '379',
94 ERR_NOSUCHNICK
: '401',
95 ERR_CANNOTSENDTOCHAN
: '404',
96 ERR_TOOMANYCHANNELS
: '405',
97 ERR_NICKNAMEINUSE
: '433',
98 ERR_USERNOTINCHANNEL
: '441',
99 ERR_NOTONCHANNEL
: '442',
100 ERR_NOTREGISTERED
: '451',
101 ERR_LINKCHANNEL
: '470',
102 ERR_CHANNELISFULL
: '471',
103 ERR_INVITEONLYCHAN
: '473',
104 ERR_BANNEDFROMCHAN
: '474',
105 ERR_BADCHANNELKEY
: '475',
106 ERR_CHANOPRIVSNEEDED
: '482',
112 this.parseIRCMessage = function (websocket
, ircSocket
, data
) {
113 /*global ircSocketDataHandler */
114 var msg
, regex
, opts
, options
, opt
, i
, j
, matches
, nick
, users
, chan
, channel
, params
, prefix
, prefixes
, nicklist
, caps
, rtn
, obj
, tmp
, namespace;
115 //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;
116 //regex = /^(?::(\S+) )?(\S+)(?: (?!:)(.+?))?(?: :(.+))?$/i;
117 regex
= /^(?::(?:([a-z0-9\x5B-\x60\x7B-\x7D\.\-]+)|([a-z0-9\x5B-\x60\x7B-\x7D\.\-]+)!([a-z0-9~\.\-_|]+)@?([a-z0-9\.\-:\/]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.+))?$/i;
119 msg
= regex
.exec(data
);
125 hostname
: msg
[4] || '',
127 params
: msg
[6] || '',
128 trailing
: (msg
[7]) ? msg
[7].trim() : ''
131 switch (msg
.command
.toUpperCase()) {
133 websocket
.sendServerLine('PONG ' + msg
.trailing
);
135 case ircNumerics
.RPL_WELCOME
:
136 if (ircSocket
.IRC
.CAP
.negotiating
) {
137 ircSocket
.IRC
.CAP
.negotiating
= false;
138 ircSocket
.IRC
.CAP
.enabled
= [];
139 ircSocket
.IRC
.CAP
.requested
= [];
140 ircSocket
.IRC
.registered
= true;
142 //regex = /([a-z0-9\x5B-\x60\x7B-\x7D\.\-]+)!([a-z0-9~\.\-_|]+)@?([a-z0-9\.\-:\/]+)/i;
143 //matches = regex.exec(msg.trailing);
144 nick
= msg
.params
.split(' ')[0];
145 websocket
.sendClientEvent('connect', {connected
: true, host
: null, nick
: nick
});
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]] = (typeof opt
[1] !== 'undefined') ? 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
)});
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
});
181 case ircNumerics
.RPL_LISTSTART
:
183 websocket
.sendClientEvent('list_start', {server
: ''});
184 websocket
.kiwi
.buffer
.list
= [];
187 case ircNumerics
.RPL_LISTEND
:
189 if (websocket
.kiwi
.buffer
.list
.length
> 0) {
190 websocket
.kiwi
.buffer
.list
= _
.sortBy(websocket
.kiwi
.buffer
.list
, function (channel
) {
191 return channel
.num_users
;
193 websocket
.sendClientEvent('list_channel', {chans
: websocket
.kiwi
.buffer
.list
});
194 websocket
.kiwi
.buffer
.list
= [];
196 websocket
.sendClientEvent('list_end', {server
: ''});
200 case ircNumerics
.RPL_LIST
:
202 var parts
, channel
, num_users
, modes
, topic
;
204 parts
= msg
.params
.split(' ');
206 num_users
= parts
[2];
207 modes
= msg
.trailing
.split(' ', 1);
208 topic
= msg
.trailing
.substring(msg
.trailing
.indexOf(' ') + 1);
210 //websocket.sendClientEvent('list_channel', {
211 websocket
.kiwi
.buffer
.list
.push({
216 num_users
: parseInt(num_users
, 10)
219 if (websocket
.kiwi
.buffer
.list
.length
> 200) {
220 websocket
.kiwi
.buffer
.list
= _
.sortBy(websocket
.kiwi
.buffer
.list
, function (channel
) {
221 return channel
.num_users
;
223 websocket
.sendClientEvent('list_channel', {chans
: websocket
.kiwi
.buffer
.list
});
224 websocket
.kiwi
.buffer
.list
= [];
230 case ircNumerics
.RPL_WHOISIDLE
:
231 params
= msg
.params
.split(" ", 4);
232 rtn
= {server
: '', nick
: params
[1], idle
: params
[2]};
234 rtn
.logon
= params
[3];
236 websocket
.sendClientEvent('whois', rtn
);
238 case ircNumerics
.RPL_MOTD
:
239 websocket
.sendClientEvent('motd', {server
: '', "msg": msg
.trailing
});
241 case ircNumerics
.RPL_NAMEREPLY
:
242 params
= msg
.params
.split(" ");
245 users
= msg
.trailing
.split(" ");
246 prefixes
= _
.values(ircSocket
.IRC
.options
.PREFIX
);
249 _
.each(users
, function (user
) {
250 if (_
.include(prefix
, user
.charAt(0))) {
251 prefix
= user
.charAt(0);
252 user
= user
.substring(1);
253 nicklist
[user
] = prefix
;
258 websocket
.sendClientEvent('userlist', {server
: '', 'users': nicklist
, channel
: chan
});
264 websocket
.sendClientEvent('userlist', {server
: '', "users": nicklist
, channel
: chan
});
269 case ircNumerics
.RPL_ENDOFNAMES
:
270 websocket
.sendClientEvent('userlist_end', {server
: '', channel
: msg
.params
.split(" ")[1]});
272 case ircNumerics
.ERR_LINKCHANNEL
:
273 params
= msg
.params
.split(" ");
274 websocket
.sendClientEvent('channel_redirect', {from: params
[1], to
: params
[2]});
276 case ircNumerics
.ERR_NOSUCHNICK
:
277 websocket
.sendClientEvent('irc_error', {error
: 'no_such_nick', nick
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
280 // Some BNC's send malformed JOIN causing the channel to be as a
281 // parameter instead of trailing.
282 if (typeof msg
.trailing
=== 'string' && msg
.trailing
!== '') {
283 channel
= msg
.trailing
;
284 } else if (typeof msg
.params
=== 'string' && msg
.params
!== '') {
285 channel
= msg
.params
;
288 websocket
.sendClientEvent('join', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: channel
});
289 if (msg
.nick
=== ircSocket
.IRC
.nick
) {
290 websocket
.sendServerLine('NAMES ' + msg
.trailing
);
294 websocket
.sendClientEvent('part', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: msg
.params
.trim(), message
: msg
.trailing
});
297 params
= msg
.params
.split(" ");
298 websocket
.sendClientEvent('kick', {kicked
: params
[1], nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: params
[0].trim(), message
: msg
.trailing
});
301 websocket
.sendClientEvent('quit', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, message
: msg
.trailing
});
304 if ((msg
.trailing
.charAt(0) === String
.fromCharCode(1)) && (msg
.trailing
.charAt(msg
.trailing
.length
- 1) === String
.fromCharCode(1))) {
305 // It's a CTCP response
306 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)});
308 websocket
.sendClientEvent('notice', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, target
: msg
.params
.trim(), msg
: msg
.trailing
});
312 websocket
.sendClientEvent('nick', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, newnick
: msg
.trailing
});
315 obj
= {nick
: msg
.nick
, channel
: msg
.params
, topic
: msg
.trailing
};
316 websocket
.sendClientEvent('topic', obj
);
318 case ircNumerics
.RPL_TOPIC
:
319 obj
= {nick
: '', channel
: msg
.params
.split(" ")[1], topic
: msg
.trailing
};
320 websocket
.sendClientEvent('topic', obj
);
322 case ircNumerics
.RPL_NOTOPIC
:
323 obj
= {nick
: '', channel
: msg
.params
.split(" ")[1], topic
: ''};
324 websocket
.sendClientEvent('topic', obj
);
327 opts
= msg
.params
.split(" ");
328 params
= {nick
: msg
.nick
};
329 switch (opts
.length
) {
331 params
.effected_nick
= opts
[0];
332 params
.mode
= msg
.trailing
;
335 params
.channel
= opts
[0];
336 params
.mode
= opts
[1];
339 params
.channel
= opts
[0];
340 params
.mode
= opts
[1];
341 params
.effected_nick
= opts
[2];
344 websocket
.sendClientEvent('mode', params
);
347 if ((msg
.trailing
.charAt(0) === String
.fromCharCode(1)) && (msg
.trailing
.charAt(msg
.trailing
.length
- 1) === String
.fromCharCode(1))) {
348 // It's a CTCP request
349 if (msg
.trailing
.substr(1, 6) === 'ACTION') {
350 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)});
351 } else if (msg
.trailing
.substr(1, 4) === 'KIWI') {
352 tmp
= msg
.trailing
.substr(6, msg
.trailing
.length
- 2);
353 namespace = tmp
.split(' ', 1)[0];
354 websocket
.sendClientEvent('kiwi', {namespace: namespace, data
: tmp
.substr(namespace.length
+ 1)});
356 } else if (msg
.trailing
.substr(1, 7) === 'VERSION') {
357 ircSocket
.write('NOTICE ' + msg
.nick
+ ' :' + String
.fromCharCode(1) + 'VERSION KiwiIRC' + String
.fromCharCode(1) + '\r\n');
359 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)});
362 obj
= {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: msg
.params
.trim(), msg
: msg
.trailing
};
363 websocket
.sendClientEvent('msg', obj
);
367 caps
= kiwi
.config
.cap_options
;
368 options
= msg
.trailing
.split(" ");
369 switch (_
.last(msg
.params
.split(" "))) {
372 _
.each(_
.intersect(caps
, options
), function (cap
) {
377 ircSocket
.IRC
.CAP
.requested
.push(cap
);
379 if (opts
.length
> 0) {
380 websocket
.sendServerLine('CAP REQ :' + opts
);
382 websocket
.sendServerLine('CAP END');
385 /*if (_.include(options, 'tls')) {
386 websocket.sendServerLine('STARTTLS');
387 ircSocket.IRC.CAP.requested.push('tls');
391 _
.each(options
, function (cap
) {
392 ircSocket
.IRC
.CAP
.enabled
.push(cap
);
394 if (_
.last(msg
.params
.split(" ")) !== '*') {
395 ircSocket
.IRC
.CAP
.requested
= [];
396 ircSocket
.IRC
.CAP
.negotiating
= false;
397 websocket
.sendServerLine('CAP END');
401 ircSocket
.IRC
.CAP
.requested
= [];
402 ircSocket
.IRC
.CAP
.negotiating
= false;
403 websocket
.sendServerLine('CAP END');
407 /*case ircNumerics.RPL_STARTTLS:
410 listeners = ircSocket.listeners('data');
411 ircSocket.removeAllListeners('data');
412 ssl_socket = starttls(ircSocket, {}, function () {
413 ssl_socket.on("data", function (data) {
414 ircSocketDataHandler(data, websocket, ssl_socket);
416 ircSocket = ssl_socket;
418 _.each(listeners, function (listener) {
419 ircSocket.addListener('data', listener);
422 //console.log(ircSocket);
427 case ircNumerics
.ERR_CANNOTSENDTOCHAN
:
428 websocket
.sendClientEvent('irc_error', {error
: 'cannot_send_to_chan', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
430 case ircNumerics
.ERR_TOOMANYCHANNELS
:
431 websocket
.sendClientEvent('irc_error', {error
: 'too_many_channels', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
433 case ircNumerics
.ERR_USERNOTINCHANNEL
:
434 params
= msg
.params
.split(" ");
435 websocket
.sendClientEvent('irc_error', {error
: 'user_not_in_channel', nick
: params
[0], channel
: params
[1], reason
: msg
.trainling
});
437 case ircNumerics
.ERR_NOTONCHANNEL
:
438 websocket
.sendClientEvent('irc_error', {error
: 'not_on_channel', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
440 case ircNumerics
.ERR_CHANNELISFULL
:
441 websocket
.sendClientEvent('irc_error', {error
: 'channel_is_full', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
443 case ircNumerics
.ERR_INVITEONLYCHAN
:
444 websocket
.sendClientEvent('irc_error', {error
: 'invite_only_channel', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
446 case ircNumerics
.ERR_BANNEDFROMCHAN
:
447 websocket
.sendClientEvent('irc_error', {error
: 'banned_from_channel', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
449 case ircNumerics
.ERR_BADCHANNELKEY
:
450 websocket
.sendClientEvent('irc_error', {error
: 'bad_channel_key', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
452 case ircNumerics
.ERR_CHANOPRIVSNEEDED
:
453 websocket
.sendClientEvent('irc_error', {error
: 'chanop_privs_needed', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
455 case ircNumerics
.ERR_NICKNAMEINUSE
:
456 websocket
.sendClientEvent('irc_error', {error
: 'nickname_in_use', nick
: _
.last(msg
.params
.split(" ")), reason
: msg
.trailing
});
460 websocket
.sendClientEvent('irc_error', {error
: 'error', reason
: msg
.trailing
});
461 websocket
.disconnect();
463 case ircNumerics
.ERR_NOTREGISTERED
:
464 if (ircSocket
.IRC
.registered
) {
465 console
.log('Kiwi thinks user is registered, but the IRC server thinks differently');
469 console
.log("Unknown command (" + String(msg
.command
).toUpperCase() + ")");
472 console
.log("Malformed IRC line: " + data
);
482 * NOTE: Some IRC servers or BNC's out there incorrectly use
483 * only \n as a line splitter.
485 this.ircSocketDataHandler = function (data
, websocket
, ircSocket
) {
487 if ((ircSocket
.holdLast
) && (ircSocket
.held
!== '')) {
488 data
= ircSocket
.held
+ data
;
489 ircSocket
.holdLast
= false;
492 if (data
.substr(-1) !== '\n') {
493 ircSocket
.holdLast
= true;
495 data
= data
.split("\n");
496 for (i
= 0; i
< data
.length
; i
++) {
498 if ((ircSocket
.holdLast
) && (i
=== data
.length
- 1)) {
499 ircSocket
.held
= data
[i
];
503 // We have a complete line of data, parse it!
504 kiwi
.parseIRCMessage(websocket
, ircSocket
, data
[i
].replace(/^\r+|\r+$/, ''));
513 this.httpHandler = function (request
, response
) {
514 var uri
, uri_parts
, subs
, useragent
, agent
, server_set
, server
, nick
, debug
, touchscreen
, hash
,
515 min
= {}, public_http_path
;
516 if (kiwi
.config
.handle_http
) {
517 uri
= url
.parse(request
.url
, true);
518 uri_parts
= uri
.pathname
.split('/');
520 subs
= uri
.pathname
.substr(0, 4);
521 if (uri
.pathname
=== '/js/all.js') {
522 if (kiwi
.cache
.alljs
=== '') {
523 public_http_path
= kiwi
.kiwi_root
+ '/' + kiwi
.config
.public_http
;
525 min
.underscore
= fs
.readFileSync(public_http_path
+ 'js/underscore.min.js');
526 min
.util
= fs
.readFileSync(public_http_path
+ 'js/util.js');
527 min
.gateway
= fs
.readFileSync(public_http_path
+ 'js/gateway.js');
528 min
.front
= fs
.readFileSync(public_http_path
+ 'js/front.js');
529 min
.iscroll
= fs
.readFileSync(public_http_path
+ 'js/iscroll.js');
530 min
.ast
= jsp
.parse(min
.underscore
+ min
.util
+ min
.gateway
+ min
.front
+ min
.iscroll
);
531 min
.ast
= pro
.ast_mangle(min
.ast
);
532 min
.ast
= pro
.ast_squeeze(min
.ast
);
533 min
.final_code
= pro
.gen_code(min
.ast
);
534 kiwi
.cache
.alljs
= min
.final_code
;
535 hash
= crypto
.createHash('md5').update(kiwi
.cache
.alljs
);
536 kiwi
.cache
.alljs_hash
= hash
.digest('base64');
538 if (request
.headers
['if-none-match'] === kiwi
.cache
.alljs_hash
) {
539 response
.statusCode
= 304;
541 response
.setHeader('ETag', kiwi
.cache
.alljs_hash
);
542 response
.write(kiwi
.cache
.alljs
);
545 } else if ((subs
=== '/js/') || (subs
=== '/css') || (subs
=== '/img')) {
546 request
.addListener('end', function () {
547 kiwi
.fileServer
.serve(request
, response
);
549 } else if (uri
.pathname
=== '/' || uri_parts
[1] === 'client') {
550 useragent
= (typeof request
.headers
=== 'string') ? request
.headers
['user-agent'] : '';
551 if (useragent
.match(/android/i) !== -1) {
554 } else if (useragent
.match(/iphone/) !== -1) {
557 } else if (useragent
.match(/ipad/) !== -1) {
560 } else if (useragent
.match(/ipod/) !== -1) {
570 debug
= (typeof uri
.query
.debug
!== 'undefined');
572 if (uri_parts
[1] !== 'client') {
574 server_set
= ((typeof uri
.query
.server
!== 'undefined') && (uri
.query
.server
!== ''));
575 server
= uri
.query
.server
|| 'irc.anonnet.org';
576 nick
= uri
.query
.nick
|| '';
579 server
= 'irc.anonnet.org';
583 server_set
= ((typeof uri_parts
[2] !== 'undefined') && (uri_parts
[2] !== ''));
584 server
= server_set
? uri_parts
[2] : 'irc.anonnet.org';
585 nick
= uri
.query
.nick
|| '';
588 response
.setHeader('X-Generated-By', 'KiwiIRC');
589 hash
= crypto
.createHash('md5').update(touchscreen
? 't' : 'f').update(debug
? 't' : 'f').update(server_set
? 't' : 'f').update(server
).update(nick
).update(agent
).update(JSON
.stringify(kiwi
.config
)).digest('base64');
590 if (kiwi
.cache
.html
[hash
]) {
591 if (request
.headers
['if-none-match'] === kiwi
.cache
.html
[hash
].hash
) {
592 response
.statusCode
= 304;
594 response
.setHeader('Etag', kiwi
.cache
.html
[hash
].hash
);
595 response
.write(kiwi
.cache
.html
[hash
].html
);
599 fs
.readFile(__dirname
+ '/client/index.html.jade', 'utf8', function (err
, str
) {
602 html
= kiwi
.jade
.compile(str
)({ "touchscreen": touchscreen
, "debug": debug
, "server_set": server_set
, "server": server
, "nick": nick
, "agent": agent
, "config": kiwi
.config
});
603 hash2
= crypto
.createHash('md5').update(html
).digest('base64');
604 kiwi
.cache
.html
[hash
] = {"html": html
, "hash": hash2
};
605 if (request
.headers
['if-none-match'] === hash2
) {
606 response
.statusCode
= 304;
608 response
.setHeader('Etag', hash2
);
609 response
.write(html
);
612 response
.statusCode
= 500;
617 } else if (uri
.pathname
.substr(0, 10) === '/socket.io') {
620 response
.statusCode
= 404;
629 this.websocketListen = function (port
, host
, handler
, secure
, key
, cert
) {
630 if (kiwi
.httpServer
) {
631 kiwi
.httpServer
.close();
634 kiwi
.httpServer
= https
.createServer({key
: fs
.readFileSync(__dirname
+ '/' + key
), cert
: fs
.readFileSync(__dirname
+ '/' + cert
)}, handler
);
635 kiwi
.io
= ws
.listen(kiwi
.httpServer
, {secure
: true});
636 kiwi
.httpServer
.listen(port
, host
);
638 kiwi
.httpServer
= http
.createServer(handler
);
639 kiwi
.io
= ws
.listen(kiwi
.httpServer
, {secure
: false});
640 kiwi
.httpServer
.listen(port
, host
);
643 kiwi
.io
.set('log level', 1);
644 kiwi
.io
.enable('browser client minification');
645 kiwi
.io
.enable('browser client etag');
646 kiwi
.io
.set('transports', kiwi
.config
.transports
);
648 kiwi
.io
.of('/kiwi').authorization(function (handshakeData
, callback
) {
649 var address
= handshakeData
.address
.address
;
651 if (typeof kiwi
.connections
[address
] === 'undefined') {
652 kiwi
.connections
[address
] = {count
: 0, sockets
: []};
654 callback(null, true);
655 }).on('connection', kiwi
.websocketConnection
);
663 this.websocketConnection = function (websocket
) {
665 websocket
.kiwi
= {address
: websocket
.handshake
.address
.address
, buffer
: {list
: []}};
666 con
= kiwi
.connections
[websocket
.kiwi
.address
];
668 if (con
.count
>= kiwi
.config
.max_client_conns
) {
669 websocket
.emit('too_many_connections');
670 websocket
.disconnect();
673 con
.sockets
.push(websocket
);
675 websocket
.sendClientEvent = function (event_name
, data
) {
676 var ev
= kiwi
.kiwi_mod
.run(event_name
, data
, {websocket
: this});
681 data
.event
= event_name
;
682 websocket
.emit('message', data
);
685 websocket
.sendServerLine = function (data
, eol
) {
686 eol
= (typeof eol
=== 'undefined') ? '\r\n' : eol
;
689 websocket
.ircSocket
.write(data
+ eol
);
693 websocket
.on('irc connect', kiwi
.websocketIRCConnect
);
694 websocket
.on('message', kiwi
.websocketMessage
);
695 websocket
.on('disconnect', kiwi
.websocketDisconnect
);
703 this.websocketIRCConnect = function (websocket
, nick
, host
, port
, ssl
, callback
) {
705 //setup IRC connection
707 ircSocket
= net
.createConnection(port
, host
);
709 ircSocket
= tls
.connect(port
, host
);
711 ircSocket
.setEncoding('ascii');
712 ircSocket
.IRC
= {options
: {}, CAP
: {negotiating
: true, requested
: [], enabled
: []}, registered
: false};
713 ircSocket
.on('error', function (e
) {
714 if (ircSocket
.IRC
.registered
) {
715 websocket
.emit('disconnect');
717 websocket
.emit('error', e
.message
);
720 websocket
.ircSocket
= ircSocket
;
721 ircSocket
.holdLast
= false;
724 ircSocket
.on('data', function (data
) {
725 kiwi
.ircSocketDataHandler(data
, websocket
, ircSocket
);
728 ircSocket
.IRC
.nick
= nick
;
729 // Send the login data
730 dns
.reverse(websocket
.kiwi
.address
, function (err
, domains
) {
731 //console.log(domains);
732 websocket
.kiwi
.hostname
= (err
) ? websocket
.kiwi
.address
: _
.first(domains
);
733 if ((kiwi
.config
.webirc
) && (kiwi
.config
.webirc_pass
[host
])) {
734 websocket
.sendServerLine('WEBIRC ' + kiwi
.config
.webirc_pass
[host
] + ' KiwiIRC ' + websocket
.kiwi
.hostname
+ ' ' + websocket
.kiwi
.address
);
736 websocket
.sendServerLine('CAP LS');
737 websocket
.sendServerLine('NICK ' + nick
);
738 websocket
.sendServerLine('USER kiwi_' + nick
.replace(/[^0-9a-zA-Z\-_.]/, '') + ' 0 0 :' + nick
);
740 if ((callback
) && (typeof (callback
) === 'function')) {
748 this.websocketMessage = function (websocket
, msg
, callback
) {
751 msg
.data
= JSON
.parse(msg
.data
);
752 args
= msg
.data
.args
;
753 switch (msg
.data
.method
) {
755 if ((args
.target
) && (args
.msg
)) {
756 obj
= kiwi
.kiwi_mod
.run('msgsend', args
, {websocket
: websocket
});
758 websocket
.sendServerLine('PRIVMSG ' + args
.target
+ ' :' + args
.msg
);
763 if ((args
.target
) && (args
.msg
)) {
764 websocket
.sendServerLine('PRIVMSG ' + args
.target
+ ' :' + String
.fromCharCode(1) + 'ACTION ' + args
.msg
+ String
.fromCharCode(1));
769 if ((args
.target
) && (args
.data
)) {
770 websocket
.sendServerLine('PRIVMSG ' + args
.target
+ ' :' + String
.fromCharCode(1) + 'KIWI ' + args
.data
+ String
.fromCharCode(1));
775 websocket
.sendServerLine(args
.data
);
779 _
.each(args
.channel
.split(","), function (chan
) {
780 websocket
.sendServerLine('JOIN ' + chan
);
786 websocket
.sendServerLine('TOPIC ' + args
.channel
+ ' :' + args
.topic
);
790 websocket
.ircSocket
.end('QUIT :' + args
.message
+ '\r\n');
791 websocket
.sentQUIT
= true;
792 websocket
.ircSocket
.destroySoon();
793 websocket
.disconnect();
796 if ((args
.target
) && (args
.msg
)) {
797 websocket
.sendServerLine('NOTICE ' + args
.target
+ ' :' + args
.msg
);
802 if ((callback
) && (typeof (callback
) === 'function')) {
806 console
.log("Caught error: " + e
);
812 this.websocketDisconnect = function (websocket
) {
815 if ((!websocket
.sentQUIT
) && (websocket
.ircSocket
)) {
817 websocket
.ircSocket
.end('QUIT :' + kiwi
.config
.quit_message
+ '\r\n');
818 websocket
.sentQUIT
= true;
819 websocket
.ircSocket
.destroySoon();
823 con
= kiwi
.connections
[websocket
.kiwi
.address
];
825 con
.sockets
= _
.reject(con
.sockets
, function (sock
) {
826 return sock
=== websocket
;
835 this.rehash = function () {
837 reload_config
= kiwi
.loadConfig();
839 // If loading the new config errored out, dont attempt any changes
840 if (reload_config
=== false) {
844 // We just want the settings that have been changed
845 changes
= reload_config
[1];
847 if (Object
.keys(changes
).length
!== 0) {
848 console
.log('%s config changes: \n', Object
.keys(changes
).length
, changes
);
856 kiwi
.websocketListen(kiwi
.config
.port
, kiwi
.config
.bind_address
, kiwi
.httpHandler
, kiwi
.config
.listen_ssl
, kiwi
.config
.ssl_key
, kiwi
.config
.ssl_cert
);
858 delete changes
.bind_address
;
859 delete changes
.listen_ssl
;
860 delete changes
.ssl_key
;
861 delete changes
.ssl_cert
;
867 delete changes
.group
;
871 kiwi
.kiwi_mod
.loadModules(kiwi_root
, kiwi
.config
);
872 kiwi
.kiwi_mod
.printMods();
873 delete changes
.module_dir
;
874 delete changes
.modules
;
880 // Also clear the kiwi.cached javascript and HTML
881 if (kiwi
.config
.handle_http
) {
882 kiwi
.cache
= {alljs
: '', html
: []};
893 * KiwiIRC controlling via STDIN
895 this.manageControll = function (data
) {
896 var parts
= data
.toString().trim().split(' '),
901 console
.log('Rehashing...');
902 console
.log(kiwi
.rehash() ? 'Rehash complete' : 'Rehash failed');
906 console
.log('Recoding...');
907 console
.log(kiwi
.recode() ? 'Recode complete' : 'Recode failed');
911 if (parts
[1] === 'reload') {
912 console
.log('Reloading module (' + parts
[2] + ')..');
913 kiwi
.kiwi_mod
.reloadModule(parts
[2]);
918 if (parts
[1] === 'clear') {
919 kiwi
.cache
.html
= {};
920 kiwi
.cache
.alljs
= '';
921 console
.log('HTML cache cleared');
926 for (i
in kiwi
.connections
) {
927 connections_cnt
= connections_cnt
+ parseInt(kiwi
.connections
[i
].count
, 10);
929 console
.log(connections_cnt
.toString() + ' connected clients');
933 console
.log('Unknown command \'' + parts
[0] + '\'');