1 /*jslint sloppy: true, continue: true, forin: true, regexp: true, undef: false, node: true, nomen: true, plusplus: true, maxerr: 50, indent: 4 */
19 this.init = function (objs
) {
32 starttls
= objs
.starttls
;
33 kiwi
= require('./kiwi.js');
42 * Some process changes
44 this.setTitle = function () {
45 process
.title
= 'kiwiirc';
48 this.changeUser = function () {
49 if (typeof kiwi
.config
.group
!== 'undefined' && kiwi
.config
.group
!== '') {
51 process
.setgid(kiwi
.config
.group
);
53 console
.log('Failed to set gid: ' + err
);
58 if (typeof kiwi
.config
.user
!== 'undefined' && kiwi
.config
.user
!== '') {
60 process
.setuid(kiwi
.config
.user
);
62 console
.log('Failed to set uid: ' + e
);
81 RPL_WHOISSERVER
: '312',
82 RPL_WHOISOPERATOR
: '313',
84 RPL_ENDOFWHOIS
: '318',
85 RPL_WHOISCHANNELS
: '319',
92 RPL_ENDOFNAMES
: '366',
94 RPL_WHOISMODES
: '379',
95 ERR_NOSUCHNICK
: '401',
96 ERR_CANNOTSENDTOCHAN
: '404',
97 ERR_TOOMANYCHANNELS
: '405',
98 ERR_NICKNAMEINUSE
: '433',
99 ERR_USERNOTINCHANNEL
: '441',
100 ERR_NOTONCHANNEL
: '442',
101 ERR_NOTREGISTERED
: '451',
102 ERR_LINKCHANNEL
: '470',
103 ERR_CHANNELISFULL
: '471',
104 ERR_INVITEONLYCHAN
: '473',
105 ERR_BANNEDFROMCHAN
: '474',
106 ERR_BADCHANNELKEY
: '475',
107 ERR_CHANOPRIVSNEEDED
: '482',
113 this.parseIRCMessage = function (websocket
, ircSocket
, data
) {
114 /*global ircSocketDataHandler */
115 var msg
, regex
, opts
, options
, opt
, i
, j
, matches
, nick
, users
, chan
, channel
, params
, nicklist
, caps
, rtn
, obj
, tmp
, namespace;
116 //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;
117 //regex = /^(?::(\S+) )?(\S+)(?: (?!:)(.+?))?(?: :(.+))?$/i;
118 regex
= /^(?::(?:([a-z0-9\x5B-\x60\x7B-\x7D\.\-]+)|([a-z0-9\x5B-\x60\x7B-\x7D\.\-]+)!([a-z0-9~\.\-_|]+)@?([a-z0-9\.\-:\/]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.+))?$/i;
120 msg
= regex
.exec(data
);
126 hostname
: msg
[4] || '',
128 params
: msg
[6] || '',
129 trailing
: (msg
[7]) ? msg
[7].trim() : ''
132 switch (msg
.command
.toUpperCase()) {
134 websocket
.sendServerLine('PONG ' + msg
.trailing
);
136 case ircNumerics
.RPL_WELCOME
:
137 if (ircSocket
.IRC
.CAP
.negotiating
) {
138 ircSocket
.IRC
.CAP
.negotiating
= false;
139 ircSocket
.IRC
.CAP
.enabled
= [];
140 ircSocket
.IRC
.CAP
.requested
= [];
141 ircSocket
.IRC
.registered
= true;
143 //regex = /([a-z0-9\x5B-\x60\x7B-\x7D\.\-]+)!([a-z0-9~\.\-_|]+)@?([a-z0-9\.\-:\/]+)/i;
144 //matches = regex.exec(msg.trailing);
145 nick
= msg
.params
.split(' ')[0];
146 websocket
.sendClientEvent('connect', {connected
: true, host
: null, nick
: nick
});
148 case ircNumerics
.RPL_ISUPPORT
:
149 opts
= msg
.params
.split(" ");
151 for (i
= 0; i
< opts
.length
; i
++) {
152 opt
= opts
[i
].split("=", 2);
153 opt
[0] = opt
[0].toUpperCase();
154 ircSocket
.IRC
.options
[opt
[0]] = (typeof opt
[1] !== 'undefined') ? opt
[1] : true;
155 if (_
.include(['NETWORK', 'PREFIX', 'CHANTYPES', 'NAMESX'], opt
[0])) {
156 if (opt
[0] === 'PREFIX') {
157 regex
= /\(([^)]*)\)(.*)/;
158 matches
= regex
.exec(opt
[1]);
159 if ((matches
) && (matches
.length
=== 3)) {
160 ircSocket
.IRC
.options
[opt
[0]] = [];
161 for (j
= 0; j
< matches
[2].length
; j
++) {
162 //ircSocket.IRC.options[opt[0]][matches[2].charAt(j)] = matches[1].charAt(j);
163 ircSocket
.IRC
.options
[opt
[0]].push({symbol
: matches
[2].charAt(j
), mode
: matches
[1].charAt(j
)});
168 if (opt
[0] === 'NAMESX') {
169 websocket
.sendServerLine('PROTOCTL NAMESX');
174 websocket
.sendClientEvent('options', {server
: '', "options": ircSocket
.IRC
.options
});
176 case ircNumerics
.RPL_WHOISUSER
:
177 case ircNumerics
.RPL_WHOISSERVER
:
178 case ircNumerics
.RPL_WHOISOPERATOR
:
179 case ircNumerics
.RPL_ENDOFWHOIS
:
180 case ircNumerics
.RPL_WHOISCHANNELS
:
181 case ircNumerics
.RPL_WHOISMODES
:
182 websocket
.sendClientEvent('whois', {server
: '', nick
: msg
.params
.split(" ", 3)[1], "msg": msg
.trailing
});
185 case ircNumerics
.RPL_LISTSTART
:
187 websocket
.sendClientEvent('list_start', {server
: ''});
188 websocket
.kiwi
.buffer
.list
= [];
191 case ircNumerics
.RPL_LISTEND
:
193 if (websocket
.kiwi
.buffer
.list
.length
> 0) {
194 websocket
.kiwi
.buffer
.list
= _
.sortBy(websocket
.kiwi
.buffer
.list
, function (channel
) {
195 return channel
.num_users
;
197 websocket
.sendClientEvent('list_channel', {chans
: websocket
.kiwi
.buffer
.list
});
198 websocket
.kiwi
.buffer
.list
= [];
200 websocket
.sendClientEvent('list_end', {server
: ''});
204 case ircNumerics
.RPL_LIST
:
206 var parts
, channel
, num_users
, modes
, topic
;
208 parts
= msg
.params
.split(' ');
210 num_users
= parts
[2];
211 modes
= msg
.trailing
.split(' ', 1);
212 topic
= msg
.trailing
.substring(msg
.trailing
.indexOf(' ') + 1);
214 //websocket.sendClientEvent('list_channel', {
215 websocket
.kiwi
.buffer
.list
.push({
220 num_users
: parseInt(num_users
, 10)
223 if (websocket
.kiwi
.buffer
.list
.length
> 200) {
224 websocket
.kiwi
.buffer
.list
= _
.sortBy(websocket
.kiwi
.buffer
.list
, function (channel
) {
225 return channel
.num_users
;
227 websocket
.sendClientEvent('list_channel', {chans
: websocket
.kiwi
.buffer
.list
});
228 websocket
.kiwi
.buffer
.list
= [];
234 case ircNumerics
.RPL_WHOISIDLE
:
235 params
= msg
.params
.split(" ", 4);
236 rtn
= {server
: '', nick
: params
[1], idle
: params
[2]};
238 rtn
.logon
= params
[3];
240 websocket
.sendClientEvent('whois', rtn
);
242 case ircNumerics
.RPL_MOTD
:
243 websocket
.sendClientEvent('motd', {server
: '', "msg": msg
.trailing
});
245 case ircNumerics
.RPL_NAMEREPLY
:
246 params
= msg
.params
.split(" ");
249 users
= msg
.trailing
.split(" ");
252 _
.each(users
, function (user
) {
253 var j
, k
, modes
= [];
254 for (j
= 0; j
< user
.length
; j
++) {
255 for (k
= 0; k
< ircSocket
.IRC
.options
.PREFIX
.length
; k
++) {
256 if (user
.charAt(j
) === ircSocket
.IRC
.options
.PREFIX
[k
].symbol
) {
257 modes
.push(ircSocket
.IRC
.options
.PREFIX
[k
].mode
);
261 nicklist
.push({nick
: user
, modes
: modes
});
263 websocket
.sendClientEvent('userlist', {server
: '', 'users': nicklist
, channel
: chan
});
269 websocket
.sendClientEvent('userlist', {server
: '', "users": nicklist
, channel
: chan
});
274 case ircNumerics
.RPL_ENDOFNAMES
:
275 websocket
.sendClientEvent('userlist_end', {server
: '', channel
: msg
.params
.split(" ")[1]});
277 case ircNumerics
.ERR_LINKCHANNEL
:
278 params
= msg
.params
.split(" ");
279 websocket
.sendClientEvent('channel_redirect', {from: params
[1], to
: params
[2]});
281 case ircNumerics
.ERR_NOSUCHNICK
:
282 websocket
.sendClientEvent('irc_error', {error
: 'no_such_nick', nick
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
285 // Some BNC's send malformed JOIN causing the channel to be as a
286 // parameter instead of trailing.
287 if (typeof msg
.trailing
=== 'string' && msg
.trailing
!== '') {
288 channel
= msg
.trailing
;
289 } else if (typeof msg
.params
=== 'string' && msg
.params
!== '') {
290 channel
= msg
.params
;
293 websocket
.sendClientEvent('join', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: channel
});
294 if (msg
.nick
=== ircSocket
.IRC
.nick
) {
295 websocket
.sendServerLine('NAMES ' + msg
.trailing
);
299 websocket
.sendClientEvent('part', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: msg
.params
.trim(), message
: msg
.trailing
});
302 params
= msg
.params
.split(" ");
303 websocket
.sendClientEvent('kick', {kicked
: params
[1], nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: params
[0].trim(), message
: msg
.trailing
});
306 websocket
.sendClientEvent('quit', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, message
: msg
.trailing
});
309 if ((msg
.trailing
.charAt(0) === String
.fromCharCode(1)) && (msg
.trailing
.charAt(msg
.trailing
.length
- 1) === String
.fromCharCode(1))) {
310 // It's a CTCP response
311 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)});
313 websocket
.sendClientEvent('notice', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, target
: msg
.params
.trim(), msg
: msg
.trailing
});
317 websocket
.sendClientEvent('nick', {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, newnick
: msg
.trailing
});
320 obj
= {nick
: msg
.nick
, channel
: msg
.params
, topic
: msg
.trailing
};
321 websocket
.sendClientEvent('topic', obj
);
323 case ircNumerics
.RPL_TOPIC
:
324 obj
= {nick
: '', channel
: msg
.params
.split(" ")[1], topic
: msg
.trailing
};
325 websocket
.sendClientEvent('topic', obj
);
327 case ircNumerics
.RPL_NOTOPIC
:
328 obj
= {nick
: '', channel
: msg
.params
.split(" ")[1], topic
: ''};
329 websocket
.sendClientEvent('topic', obj
);
332 opts
= msg
.params
.split(" ");
333 params
= {nick
: msg
.nick
};
334 switch (opts
.length
) {
336 params
.effected_nick
= opts
[0];
337 params
.mode
= msg
.trailing
;
340 params
.channel
= opts
[0];
341 params
.mode
= opts
[1];
344 params
.channel
= opts
[0];
345 params
.mode
= opts
[1];
346 params
.effected_nick
= opts
[2];
349 websocket
.sendClientEvent('mode', params
);
352 if ((msg
.trailing
.charAt(0) === String
.fromCharCode(1)) && (msg
.trailing
.charAt(msg
.trailing
.length
- 1) === String
.fromCharCode(1))) {
353 // It's a CTCP request
354 if (msg
.trailing
.substr(1, 6) === 'ACTION') {
355 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)});
356 } else if (msg
.trailing
.substr(1, 4) === 'KIWI') {
357 tmp
= msg
.trailing
.substr(6, msg
.trailing
.length
- 2);
358 namespace = tmp
.split(' ', 1)[0];
359 websocket
.sendClientEvent('kiwi', {namespace: namespace, data
: tmp
.substr(namespace.length
+ 1)});
361 } else if (msg
.trailing
.substr(1, 7) === 'VERSION') {
362 ircSocket
.write('NOTICE ' + msg
.nick
+ ' :' + String
.fromCharCode(1) + 'VERSION KiwiIRC' + String
.fromCharCode(1) + '\r\n');
364 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)});
367 obj
= {nick
: msg
.nick
, ident
: msg
.ident
, hostname
: msg
.hostname
, channel
: msg
.params
.trim(), msg
: msg
.trailing
};
368 websocket
.sendClientEvent('msg', obj
);
372 caps
= kiwi
.config
.cap_options
;
373 options
= msg
.trailing
.split(" ");
374 switch (_
.last(msg
.params
.split(" "))) {
377 _
.each(_
.intersect(caps
, options
), function (cap
) {
382 ircSocket
.IRC
.CAP
.requested
.push(cap
);
384 if (opts
.length
> 0) {
385 websocket
.sendServerLine('CAP REQ :' + opts
);
387 websocket
.sendServerLine('CAP END');
390 /*if (_.include(options, 'tls')) {
391 websocket.sendServerLine('STARTTLS');
392 ircSocket.IRC.CAP.requested.push('tls');
396 _
.each(options
, function (cap
) {
397 ircSocket
.IRC
.CAP
.enabled
.push(cap
);
399 if (_
.last(msg
.params
.split(" ")) !== '*') {
400 ircSocket
.IRC
.CAP
.requested
= [];
401 ircSocket
.IRC
.CAP
.negotiating
= false;
402 websocket
.sendServerLine('CAP END');
406 ircSocket
.IRC
.CAP
.requested
= [];
407 ircSocket
.IRC
.CAP
.negotiating
= false;
408 websocket
.sendServerLine('CAP END');
412 /*case ircNumerics.RPL_STARTTLS:
415 listeners = ircSocket.listeners('data');
416 ircSocket.removeAllListeners('data');
417 ssl_socket = starttls(ircSocket, {}, function () {
418 ssl_socket.on("data", function (data) {
419 ircSocketDataHandler(data, websocket, ssl_socket);
421 ircSocket = ssl_socket;
423 _.each(listeners, function (listener) {
424 ircSocket.addListener('data', listener);
427 //console.log(ircSocket);
432 case ircNumerics
.ERR_CANNOTSENDTOCHAN
:
433 websocket
.sendClientEvent('irc_error', {error
: 'cannot_send_to_chan', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
435 case ircNumerics
.ERR_TOOMANYCHANNELS
:
436 websocket
.sendClientEvent('irc_error', {error
: 'too_many_channels', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
438 case ircNumerics
.ERR_USERNOTINCHANNEL
:
439 params
= msg
.params
.split(" ");
440 websocket
.sendClientEvent('irc_error', {error
: 'user_not_in_channel', nick
: params
[0], channel
: params
[1], reason
: msg
.trainling
});
442 case ircNumerics
.ERR_NOTONCHANNEL
:
443 websocket
.sendClientEvent('irc_error', {error
: 'not_on_channel', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
445 case ircNumerics
.ERR_CHANNELISFULL
:
446 websocket
.sendClientEvent('irc_error', {error
: 'channel_is_full', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
448 case ircNumerics
.ERR_INVITEONLYCHAN
:
449 websocket
.sendClientEvent('irc_error', {error
: 'invite_only_channel', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
451 case ircNumerics
.ERR_BANNEDFROMCHAN
:
452 websocket
.sendClientEvent('irc_error', {error
: 'banned_from_channel', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
454 case ircNumerics
.ERR_BADCHANNELKEY
:
455 websocket
.sendClientEvent('irc_error', {error
: 'bad_channel_key', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
457 case ircNumerics
.ERR_CHANOPRIVSNEEDED
:
458 websocket
.sendClientEvent('irc_error', {error
: 'chanop_privs_needed', channel
: msg
.params
.split(" ")[1], reason
: msg
.trailing
});
460 case ircNumerics
.ERR_NICKNAMEINUSE
:
461 websocket
.sendClientEvent('irc_error', {error
: 'nickname_in_use', nick
: _
.last(msg
.params
.split(" ")), reason
: msg
.trailing
});
465 websocket
.sendClientEvent('irc_error', {error
: 'error', reason
: msg
.trailing
});
466 websocket
.disconnect();
468 case ircNumerics
.ERR_NOTREGISTERED
:
469 if (ircSocket
.IRC
.registered
) {
470 console
.log('Kiwi thinks user is registered, but the IRC server thinks differently');
474 console
.log("Unknown command (" + String(msg
.command
).toUpperCase() + ")");
477 console
.log("Malformed IRC line: " + data
);
487 * NOTE: Some IRC servers or BNC's out there incorrectly use
488 * only \n as a line splitter.
490 this.ircSocketDataHandler = function (data
, websocket
, ircSocket
) {
492 if ((ircSocket
.holdLast
) && (ircSocket
.held
!== '')) {
493 data
= ircSocket
.held
+ data
;
494 ircSocket
.holdLast
= false;
497 if (data
.substr(-1) !== '\n') {
498 ircSocket
.holdLast
= true;
500 data
= data
.split("\n");
501 for (i
= 0; i
< data
.length
; i
++) {
503 if ((ircSocket
.holdLast
) && (i
=== data
.length
- 1)) {
504 ircSocket
.held
= data
[i
];
508 // We have a complete line of data, parse it!
509 kiwi
.parseIRCMessage(websocket
, ircSocket
, data
[i
].replace(/^\r+|\r+$/, ''));
518 this.httpHandler = function (request
, response
) {
519 var uri
, uri_parts
, subs
, useragent
, agent
, server_set
, server
, nick
, debug
, touchscreen
, hash
,
520 min
= {}, public_http_path
,
521 secure
= (typeof request
.client
.encrypted
=== 'object');
524 if (kiwi
.config
.handle_http
) {
525 uri
= url
.parse(request
.url
, true);
526 uri_parts
= uri
.pathname
.split('/');
528 subs
= uri
.pathname
.substr(0, 4);
529 if (uri
.pathname
=== '/js/all.js') {
530 if (kiwi
.cache
.alljs
=== '') {
531 public_http_path
= kiwi
.kiwi_root
+ '/' + kiwi
.config
.public_http
;
533 min
.underscore
= fs
.readFileSync(public_http_path
+ 'js/underscore.min.js');
534 min
.util
= fs
.readFileSync(public_http_path
+ 'js/util.js');
535 min
.gateway
= fs
.readFileSync(public_http_path
+ 'js/gateway.js');
536 min
.front
= fs
.readFileSync(public_http_path
+ 'js/front.js');
537 min
.front_events
= fs
.readFileSync(public_http_path
+ 'js/front.events.js');
538 min
.front_ui
= fs
.readFileSync(public_http_path
+ 'js/front.ui.js');
539 min
.iscroll
= fs
.readFileSync(public_http_path
+ 'js/iscroll.js');
540 min
.ast
= jsp
.parse(min
.underscore
+ min
.util
+ min
.gateway
+ min
.front
+ min
.front_events
+ min
.front_ui
+ min
.iscroll
);
541 min
.ast
= pro
.ast_mangle(min
.ast
);
542 min
.ast
= pro
.ast_squeeze(min
.ast
);
543 min
.final_code
= pro
.gen_code(min
.ast
);
544 kiwi
.cache
.alljs
= min
.final_code
;
545 hash
= crypto
.createHash('md5').update(kiwi
.cache
.alljs
);
546 kiwi
.cache
.alljs_hash
= hash
.digest('base64');
548 if (request
.headers
['if-none-match'] === kiwi
.cache
.alljs_hash
) {
549 response
.statusCode
= 304;
551 response
.setHeader('Content-type', 'application/javascript');
552 response
.setHeader('ETag', kiwi
.cache
.alljs_hash
);
553 response
.write(kiwi
.cache
.alljs
);
556 } else if ((subs
=== '/js/') || (subs
=== '/css') || (subs
=== '/img')) {
557 request
.addListener('end', function () {
558 kiwi
.fileServer
.serve(request
, response
);
560 } else if (uri
.pathname
=== '/' || uri_parts
[1] === 'client') {
561 useragent
= (typeof request
.headers
=== 'string') ? request
.headers
['user-agent'] : '';
562 if (useragent
.match(/android/i) !== -1) {
565 } else if (useragent
.match(/iphone/) !== -1) {
568 } else if (useragent
.match(/ipad/) !== -1) {
571 } else if (useragent
.match(/ipod/) !== -1) {
581 debug
= (typeof uri
.query
.debug
!== 'undefined');
583 if (uri_parts
[1] !== 'client') {
585 server_set
= ((typeof uri
.query
.server
!== 'undefined') && (uri
.query
.server
!== ''));
586 server
= uri
.query
.server
|| 'irc.anonnet.org';
587 nick
= uri
.query
.nick
|| '';
590 server
= 'irc.anonnet.org';
594 server_set
= ((typeof uri_parts
[2] !== 'undefined') && (uri_parts
[2] !== ''));
595 server
= server_set
? uri_parts
[2] : 'irc.anonnet.org';
596 nick
= uri
.query
.nick
|| '';
599 response
.setHeader('X-Generated-By', 'KiwiIRC');
600 hash
= crypto
.createHash('md5').update(touchscreen
? 't' : 'f')
601 .update(debug
? 't' : 'f')
602 .update(server_set
? 't' : 'f')
603 .update(secure
? 't' : 'f')
607 .update(JSON
.stringify(kiwi
.config
))
609 if (kiwi
.cache
.html
[hash
]) {
610 if (request
.headers
['if-none-match'] === kiwi
.cache
.html
[hash
].hash
) {
611 response
.statusCode
= 304;
613 response
.setHeader('Etag', kiwi
.cache
.html
[hash
].hash
);
614 response
.setHeader('Content-type', 'text/html');
615 response
.write(kiwi
.cache
.html
[hash
].html
);
619 fs
.readFile(__dirname
+ '/client/index.html.jade', 'utf8', function (err
, str
) {
622 html
= kiwi
.jade
.compile(str
)({ "touchscreen": touchscreen
, "debug": debug
, "secure": secure
, "server_set": server_set
, "server": server
, "nick": nick
, "agent": agent
, "config": kiwi
.config
});
623 hash2
= crypto
.createHash('md5').update(html
).digest('base64');
624 kiwi
.cache
.html
[hash
] = {"html": html
, "hash": hash2
};
625 if (request
.headers
['if-none-match'] === hash2
) {
626 response
.statusCode
= 304;
628 response
.setHeader('Etag', hash2
);
629 response
.setHeader('Content-type', 'text/html');
630 response
.write(html
);
633 response
.statusCode
= 500;
638 } else if (uri
.pathname
.substr(0, 10) === '/socket.io') {
641 response
.statusCode
= 404;
647 console
.log('ERROR app.httpHandler()');
655 this.websocketListen = function (ports
, host
, handler
, key
, cert
) {
656 if (kiwi
.httpServers
.length
> 0) {
657 _
.each(kiwi
.httpServers
, function (hs
) {
660 kiwi
.httpsServers
= [];
663 _
.each(ports
, function (port
) {
665 if (port
.secure
=== true) {
666 hs
= https
.createServer({key
: fs
.readFileSync(__dirname
+ '/' + key
), cert
: fs
.readFileSync(__dirname
+ '/' + cert
)}, handler
);
667 kiwi
.io
.push(ws
.listen(hs
, {secure
: true}));
668 hs
.listen(port
.number
);
669 console
.log("Listening on %s:%d with SSL", host
, port
.number
);
671 hs
= http
.createServer(handler
);
672 kiwi
.io
.push(ws
.listen(hs
, {secure
: false}));
673 hs
.listen(port
.number
);
674 console
.log("Listening on %s:%d without SSL", host
, port
.number
);
678 _
.each(kiwi
.io
, function (io
) {
679 io
.set('log level', 1);
680 io
.enable('browser client minification');
681 io
.enable('browser client etag');
682 io
.set('transports', kiwi
.config
.transports
);
684 io
.of('/kiwi').authorization(function (handshakeData
, callback
) {
685 var address
= handshakeData
.address
.address
;
686 if (typeof kiwi
.connections
[address
] === 'undefined') {
687 kiwi
.connections
[address
] = {count
: 0, sockets
: []};
689 callback(null, true);
690 }).on('connection', kiwi
.websocketConnection
);
699 this.websocketConnection = function (websocket
) {
701 console
.log("New connection!");
702 websocket
.kiwi
= {address
: websocket
.handshake
.address
.address
, buffer
: {list
: []}};
703 con
= kiwi
.connections
[websocket
.kiwi
.address
];
705 if (con
.count
>= kiwi
.config
.max_client_conns
) {
706 websocket
.emit('too_many_connections');
707 websocket
.disconnect();
710 con
.sockets
.push(websocket
);
712 websocket
.sendClientEvent = function (event_name
, data
) {
713 var ev
= kiwi
.kiwi_mod
.run(event_name
, data
, {websocket
: this});
718 data
.event
= event_name
;
719 websocket
.emit('message', data
);
722 websocket
.sendServerLine = function (data
, eol
) {
723 eol
= (typeof eol
=== 'undefined') ? '\r\n' : eol
;
726 websocket
.ircSocket
.write(data
+ eol
);
730 websocket
.on('irc connect', kiwi
.websocketIRCConnect
);
731 websocket
.on('message', kiwi
.websocketMessage
);
732 websocket
.on('disconnect', kiwi
.websocketDisconnect
);
740 this.websocketIRCConnect = function (websocket
, nick
, host
, port
, ssl
, callback
) {
742 //setup IRC connection
744 ircSocket
= net
.createConnection(port
, host
);
746 ircSocket
= tls
.connect(port
, host
);
748 ircSocket
.setEncoding('ascii');
749 ircSocket
.IRC
= {options
: {}, CAP
: {negotiating
: true, requested
: [], enabled
: []}, registered
: false};
750 ircSocket
.on('error', function (e
) {
751 if (ircSocket
.IRC
.registered
) {
752 websocket
.emit('disconnect');
754 websocket
.emit('error', e
.message
);
757 websocket
.ircSocket
= ircSocket
;
758 ircSocket
.holdLast
= false;
761 ircSocket
.on('data', function (data
) {
762 kiwi
.ircSocketDataHandler(data
, websocket
, ircSocket
);
765 ircSocket
.IRC
.nick
= nick
;
766 // Send the login data
767 dns
.reverse(websocket
.kiwi
.address
, function (err
, domains
) {
768 //console.log(domains);
769 websocket
.kiwi
.hostname
= (err
) ? websocket
.kiwi
.address
: _
.first(domains
);
770 if ((kiwi
.config
.webirc
) && (kiwi
.config
.webirc_pass
[host
])) {
771 websocket
.sendServerLine('WEBIRC ' + kiwi
.config
.webirc_pass
[host
] + ' KiwiIRC ' + websocket
.kiwi
.hostname
+ ' ' + websocket
.kiwi
.address
);
773 websocket
.sendServerLine('CAP LS');
774 websocket
.sendServerLine('NICK ' + nick
);
775 websocket
.sendServerLine('USER kiwi_' + nick
.replace(/[^0-9a-zA-Z\-_.]/, '') + ' 0 0 :' + nick
);
777 if ((callback
) && (typeof (callback
) === 'function')) {
785 this.websocketMessage = function (websocket
, msg
, callback
) {
788 msg
.data
= JSON
.parse(msg
.data
);
789 args
= msg
.data
.args
;
790 switch (msg
.data
.method
) {
792 if ((args
.target
) && (args
.msg
)) {
793 obj
= kiwi
.kiwi_mod
.run('msgsend', args
, {websocket
: websocket
});
795 websocket
.sendServerLine('PRIVMSG ' + args
.target
+ ' :' + args
.msg
);
800 if ((args
.target
) && (args
.msg
)) {
801 websocket
.sendServerLine('PRIVMSG ' + args
.target
+ ' :' + String
.fromCharCode(1) + 'ACTION ' + args
.msg
+ String
.fromCharCode(1));
806 if ((args
.target
) && (args
.data
)) {
807 websocket
.sendServerLine('PRIVMSG ' + args
.target
+ ' :' + String
.fromCharCode(1) + 'KIWI ' + args
.data
+ String
.fromCharCode(1));
812 websocket
.sendServerLine(args
.data
);
816 _
.each(args
.channel
.split(","), function (chan
) {
817 websocket
.sendServerLine('JOIN ' + chan
);
823 websocket
.sendServerLine('TOPIC ' + args
.channel
+ ' :' + args
.topic
);
827 websocket
.ircSocket
.end('QUIT :' + args
.message
+ '\r\n');
828 websocket
.sentQUIT
= true;
829 websocket
.ircSocket
.destroySoon();
830 websocket
.disconnect();
833 if ((args
.target
) && (args
.msg
)) {
834 websocket
.sendServerLine('NOTICE ' + args
.target
+ ' :' + args
.msg
);
839 if ((callback
) && (typeof (callback
) === 'function')) {
843 console
.log("Caught error: " + e
);
849 this.websocketDisconnect = function (websocket
) {
852 if ((!websocket
.sentQUIT
) && (websocket
.ircSocket
)) {
854 websocket
.ircSocket
.end('QUIT :' + kiwi
.config
.quit_message
+ '\r\n');
855 websocket
.sentQUIT
= true;
856 websocket
.ircSocket
.destroySoon();
860 con
= kiwi
.connections
[websocket
.kiwi
.address
];
862 con
.sockets
= _
.reject(con
.sockets
, function (sock
) {
863 return sock
=== websocket
;
872 this.rehash = function () {
874 reload_config
= kiwi
.loadConfig();
876 // If loading the new config errored out, dont attempt any changes
877 if (reload_config
=== false) {
881 // We just want the settings that have been changed
882 changes
= reload_config
[1];
884 if (Object
.keys(changes
).length
!== 0) {
885 console
.log('%s config changes: \n', Object
.keys(changes
).length
, changes
);
892 kiwi
.websocketListen(kiwi
.config
.ports
, kiwi
.config
.bind_address
, kiwi
.httpHandler
, kiwi
.config
.ssl_key
, kiwi
.config
.ssl_cert
);
893 delete changes
.ports
;
894 delete changes
.bind_address
;
895 delete changes
.ssl_key
;
896 delete changes
.ssl_cert
;
902 delete changes
.group
;
906 kiwi
.kiwi_mod
.loadModules(kiwi_root
, kiwi
.config
);
907 kiwi
.kiwi_mod
.printMods();
908 delete changes
.module_dir
;
909 delete changes
.modules
;
915 // Also clear the kiwi.cached javascript and HTML
916 if (kiwi
.config
.handle_http
) {
917 kiwi
.cache
= {alljs
: '', html
: []};
928 * KiwiIRC controlling via STDIN
930 this.manageControll = function (data
) {
931 var parts
= data
.toString().trim().split(' '),
936 console
.log('Rehashing...');
937 console
.log(kiwi
.rehash() ? 'Rehash complete' : 'Rehash failed');
941 console
.log('Recoding...');
942 console
.log(kiwi
.recode() ? 'Recode complete' : 'Recode failed');
946 if (parts
[1] === 'reload') {
947 console
.log('Reloading module (' + parts
[2] + ')..');
948 kiwi
.kiwi_mod
.reloadModule(parts
[2]);
953 if (parts
[1] === 'clear') {
954 kiwi
.cache
.html
= {};
955 kiwi
.cache
.alljs
= '';
956 console
.log('HTML cache cleared');
961 for (i
in kiwi
.connections
) {
962 connections_cnt
= connections_cnt
+ parseInt(kiwi
.connections
[i
].count
, 10);
964 console
.log(connections_cnt
.toString() + ' connected clients');
968 console
.log('Unknown command \'' + parts
[0] + '\'');