Batch clients into sets of 100 for reconfig command
[KiwiIRC.git] / server / irc / connection.js
1 var net = require('net'),
2 tls = require('tls'),
3 util = require('util'),
4 dns = require('dns'),
5 _ = require('lodash'),
6 EventBinder = require('./eventbinder.js'),
7 IrcServer = require('./server.js'),
8 IrcCommands = require('./commands.js'),
9 IrcChannel = require('./channel.js'),
10 IrcUser = require('./user.js'),
11 EE = require('../ee.js'),
12 iconv = require('iconv-lite'),
13 Socks;
14
15
16 // Break the Node.js version down into usable parts
17 var version_values = process.version.substr(1).split('.').map(function (item) {
18 return parseInt(item, 10);
19 });
20
21 // If we have a suitable Nodejs version, bring int he socks functionality
22 if (version_values[1] >= 10) {
23 Socks = require('socksjs');
24 }
25
26 var IrcConnection = function (hostname, port, ssl, nick, user, pass, state, con_num) {
27 var that = this;
28
29 EE.call(this,{
30 wildcard: true,
31 delimiter: ' '
32 });
33 this.setMaxListeners(0);
34
35 // Set the first configured encoding as the default encoding
36 this.encoding = global.config.default_encoding;
37
38 // Socket state
39 this.connected = false;
40
41 // IRCd write buffers (flood controll)
42 this.write_buffer = [];
43
44 // In process of writing the buffer?
45 this.writing_buffer = false;
46
47 // Max number of lines to write a second
48 this.write_buffer_lines_second = 2;
49
50 // If registeration with the IRCd has completed
51 this.registered = false;
52
53 // If we are in the CAP negotiation stage
54 this.cap_negotiation = true;
55
56 // User information
57 this.nick = nick;
58 this.user = user; // Contains users real hostname and address
59 this.username = this.nick.replace(/[^0-9a-zA-Z\-_.\/]/, '');
60 this.password = pass;
61
62 // State object
63 this.state = state;
64
65 // Connection ID in the state
66 this.con_num = con_num;
67
68 // IRC protocol handling
69 this.irc_commands = new IrcCommands(this);
70
71 // IrcServer object
72 this.server = new IrcServer(this, hostname, port);
73
74 // IrcUser objects
75 this.irc_users = Object.create(null);
76
77 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
78 this.irc_users[this.nick] = new IrcUser(this, '*');
79
80 // IrcChannel objects
81 this.irc_channels = Object.create(null);
82
83 // IRC connection information
84 this.irc_host = {hostname: hostname, port: port};
85 this.ssl = !(!ssl);
86
87 // SOCKS proxy details
88 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
89 if ((global.config.socks_proxy && global.config.socks_proxy.enabled) && ((global.config.socks_proxy.all) || (_.contains(global.config.socks_proxy.proxy_hosts, this.irc_host.hostname)))) {
90 this.socks = {
91 host: global.config.socks_proxy.address,
92 port: global.config.socks_proxy.port,
93 user: global.config.socks_proxy.user,
94 pass: global.config.socks_proxy.pass
95 };
96 } else {
97 this.socks = false;
98 }
99
100 // Options sent by the IRCd
101 this.options = Object.create(null);
102 this.cap = {requested: [], enabled: []};
103
104 // Is SASL supported on the IRCd
105 this.sasl = false;
106
107 // Buffers for data sent from the IRCd
108 this.hold_last = false;
109 this.held_data = '';
110
111 this.applyIrcEvents();
112 };
113 util.inherits(IrcConnection, EE);
114
115 module.exports.IrcConnection = IrcConnection;
116
117
118
119 IrcConnection.prototype.applyIrcEvents = function () {
120 // Listen for events on the IRC connection
121 this.irc_events = {
122 'server * connect': onServerConnect,
123 'channel * join': onChannelJoin,
124
125 // TODO: uncomment when using an IrcUser per nick
126 //'user:*:privmsg': onUserPrivmsg,
127 'user * nick': onUserNick,
128 'channel * part': onUserParts,
129 'channel * quit': onUserParts,
130 'channel * kick': onUserKick
131 };
132
133 EventBinder.bindIrcEvents('', this.irc_events, this, this);
134 };
135
136
137 /**
138 * Start the connection to the IRCd
139 */
140 IrcConnection.prototype.connect = function () {
141 var that = this;
142
143 // The socket connect event to listener for
144 var socket_connect_event_name = 'connect';
145
146 // The destination address
147 var dest_addr = this.socks ?
148 this.socks.host :
149 this.irc_host.hostname;
150
151 // Make sure we don't already have an open connection
152 this.disposeSocket();
153
154 // Get the IP family for the dest_addr (either socks or IRCd destination)
155 getConnectionFamily(dest_addr, function getConnectionFamilyCb(err, family, host) {
156 var outgoing;
157
158 // Decide which net. interface to make the connection through
159 if (global.config.outgoing_address) {
160 if ((family === 'IPv6') && (global.config.outgoing_address.IPv6)) {
161 outgoing = global.config.outgoing_address.IPv6;
162 } else {
163 outgoing = global.config.outgoing_address.IPv4 || '0.0.0.0';
164
165 // We don't have an IPv6 interface but dest_addr may still resolve to
166 // an IPv4 address. Reset `host` and try connecting anyway, letting it
167 // fail if an IPv4 resolved address is not found
168 host = dest_addr;
169 }
170
171 // If we have an array of interfaces, select a random one
172 if (typeof outgoing !== 'string' && outgoing.length) {
173 outgoing = outgoing[Math.floor(Math.random() * outgoing.length)];
174 }
175
176 // Make sure we have a valid interface address
177 if (typeof outgoing !== 'string')
178 outgoing = '0.0.0.0';
179
180 } else {
181 // No config was found so use the default
182 outgoing = '0.0.0.0';
183 }
184
185 // Are we connecting through a SOCKS proxy?
186 if (this.socks) {
187 that.socket = Socks.connect({
188 host: host,
189 port: that.irc_host.port,
190 ssl: that.ssl,
191 rejectUnauthorized: global.config.reject_unauthorised_certificates
192 }, {host: that.socks.host,
193 port: that.socks.port,
194 user: that.socks.user,
195 pass: that.socks.pass,
196 localAddress: outgoing
197 });
198
199 } else {
200 // No socks connection, connect directly to the IRCd
201
202 if (that.ssl) {
203 that.socket = tls.connect({
204 host: host,
205 port: that.irc_host.port,
206 rejectUnauthorized: global.config.reject_unauthorised_certificates,
207 localAddress: outgoing
208 });
209
210 // We need the raw socket connect event
211 that.socket.socket.on('connect', function() { rawSocketConnect.call(that, this); });
212
213 socket_connect_event_name = 'secureConnect';
214
215 } else {
216 that.socket = net.connect({
217 host: host,
218 port: that.irc_host.port,
219 localAddress: outgoing
220 });
221 }
222 }
223
224 // Apply the socket listeners
225 that.socket.on(socket_connect_event_name, function socketConnectCb() {
226
227 // TLS connections have the actual socket as a property
228 var is_tls = (typeof this.socket !== 'undefined') ?
229 true :
230 false;
231
232 // TLS sockets have already called this
233 if (!is_tls)
234 rawSocketConnect.call(that, this);
235
236 that.connected = true;
237
238 socketConnectHandler.call(that);
239 });
240
241 that.socket.on('error', function socketErrorCb(event) {
242 that.emit('error', event);
243 });
244
245 that.socket.on('data', function () {
246 parse.apply(that, arguments);
247 });
248
249 that.socket.on('close', function socketCloseCb(had_error) {
250 that.connected = false;
251
252 // Remove this socket form the identd lookup
253 if (that.identd_port_pair) {
254 delete global.clients.port_pairs[that.identd_port_pair];
255 }
256
257 that.emit('close');
258
259 // Close the whole socket down
260 that.disposeSocket();
261 });
262 });
263 };
264
265 /**
266 * Send an event to the client
267 */
268 IrcConnection.prototype.clientEvent = function (event_name, data, callback) {
269 data.server = this.con_num;
270 this.state.sendIrcCommand(event_name, data, callback);
271 };
272
273 /**
274 * Write a line of data to the IRCd
275 * @param data The line of data to be sent
276 * @param force Write the data now, ignoring any write queue
277 */
278 IrcConnection.prototype.write = function (data, force) {
279 //ENCODE string to encoding of the server
280 encoded_buffer = iconv.encode(data + '\r\n', this.encoding);
281
282 if (force) {
283 this.socket.write(encoded_buffer);
284 return;
285 }
286
287 this.write_buffer.push(encoded_buffer);
288
289 // Only flush if we're not writing already
290 if (!this.writing_buffer)
291 this.flushWriteBuffer();
292 };
293
294
295
296 /**
297 * Flush the write buffer to the server in a throttled fashion
298 */
299 IrcConnection.prototype.flushWriteBuffer = function () {
300
301 // In case the socket closed between writing our queue.. clean up
302 if (!this.connected) {
303 this.write_buffer = [];
304 this.writing_buffer = false;
305 return;
306 }
307
308 this.writing_buffer = true;
309
310 // Disabled write buffer? Send everything we have
311 if (!this.write_buffer_lines_second) {
312 this.write_buffer.forEach(function(buffer, idx) {
313 this.socket.write(buffer);
314 this.write_buffer = null;
315 });
316
317 this.write_buffer = [];
318 this.writing_buffer = false;
319
320 return;
321 }
322
323 // Nothing to write? Stop writing and leave
324 if (this.write_buffer.length === 0) {
325 this.writing_buffer = false;
326 return;
327 }
328
329 this.socket.write(this.write_buffer[0]);
330 this.write_buffer = this.write_buffer.slice(1);
331
332 // Call this function again at some point if we still have data to write
333 if (this.write_buffer.length > 0) {
334 setTimeout(this.flushWriteBuffer.bind(this), 1000 / this.write_buffer_lines_second);
335 } else {
336 // No more buffers to write.. so we've finished
337 this.writing_buffer = false;
338 }
339 };
340
341
342
343 /**
344 * Close the connection to the IRCd after forcing one last line
345 */
346 IrcConnection.prototype.end = function (data, callback) {
347 if (!this.socket)
348 return;
349
350 if (data)
351 this.write(data, true);
352
353 this.socket.end();
354 };
355
356
357
358 /**
359 * Clean up this IrcConnection instance and any sockets
360 */
361 IrcConnection.prototype.dispose = function () {
362 // If we're still connected, wait until the socket is closed before disposing
363 // so that all the events are still correctly triggered
364 if (this.socket && this.connected) {
365 this.end();
366 return;
367 }
368
369 if (this.socket) {
370 this.disposeSocket();
371 }
372
373 _.each(this.irc_users, function (user) {
374 user.dispose();
375 });
376 _.each(this.irc_channels, function (chan) {
377 chan.dispose();
378 });
379 this.irc_users = undefined;
380 this.irc_channels = undefined;
381
382 this.server.dispose();
383 this.server = undefined;
384
385 this.irc_commands = undefined;
386
387 EventBinder.unbindIrcEvents('', this.irc_events, this);
388
389 this.removeAllListeners();
390 };
391
392
393
394 /**
395 * Clean up any sockets for this IrcConnection
396 */
397 IrcConnection.prototype.disposeSocket = function () {
398 if (this.socket) {
399 this.socket.end();
400 this.socket.removeAllListeners();
401 this.socket = null;
402 }
403 };
404
405 /**
406 * Set a new encoding for this connection
407 * Return true in case of success
408 */
409
410 IrcConnection.prototype.setEncoding = function (encoding) {
411 var encoded_test;
412
413 try {
414 encoded_test = iconv.encode("TEST", encoding);
415 //This test is done to check if this encoding also supports
416 //the ASCII charset required by the IRC protocols
417 //(Avoid the use of base64 or incompatible encodings)
418 if (encoded_test == "TEST") {
419 this.encoding = encoding;
420 return true;
421 }
422 return false;
423 } catch (err) {
424 return false;
425 }
426 };
427
428 function getConnectionFamily(host, callback) {
429 if (net.isIP(host)) {
430 if (net.isIPv4(host)) {
431 callback(null, 'IPv4', host);
432 } else {
433 callback(null, 'IPv6', host);
434 }
435 } else {
436 dns.resolve6(host, function resolve6Cb(err, addresses) {
437 if (!err) {
438 callback(null, 'IPv6', addresses[0]);
439 } else {
440 dns.resolve4(host, function resolve4Cb(err, addresses) {
441 if (!err) {
442 callback(null, 'IPv4',addresses[0]);
443 } else {
444 callback(err);
445 }
446 });
447 }
448 });
449 }
450 }
451
452
453 function onChannelJoin(event) {
454 var chan;
455
456 // Only deal with ourselves joining a channel
457 if (event.nick !== this.nick)
458 return;
459
460 // We should only ever get a JOIN command for a channel
461 // we're not already a member of.. but check we don't
462 // have this channel in case something went wrong somewhere
463 // at an earlier point
464 if (!this.irc_channels[event.channel]) {
465 chan = new IrcChannel(this, event.channel);
466 this.irc_channels[event.channel] = chan;
467 chan.irc_events.join.call(chan, event);
468 }
469 }
470
471
472 function onServerConnect(event) {
473 this.nick = event.nick;
474 }
475
476
477 function onUserPrivmsg(event) {
478 var user;
479
480 // Only deal with messages targetted to us
481 if (event.channel !== this.nick)
482 return;
483
484 if (!this.irc_users[event.nick]) {
485 user = new IrcUser(this, event.nick);
486 this.irc_users[event.nick] = user;
487 user.irc_events.privmsg.call(user, event);
488 }
489 }
490
491
492 function onUserNick(event) {
493 var user;
494
495 // Only deal with messages targetted to us
496 if (event.nick !== this.nick)
497 return;
498
499 this.nick = event.newnick;
500 }
501
502
503 function onUserParts(event) {
504 // Only deal with ourselves leaving a channel
505 if (event.nick !== this.nick)
506 return;
507
508 if (this.irc_channels[event.channel]) {
509 this.irc_channels[event.channel].dispose();
510 delete this.irc_channels[event.channel];
511 }
512 }
513
514 function onUserKick(event){
515 // Only deal with ourselves being kicked from a channel
516 if (event.kicked !== this.nick)
517 return;
518
519 if (this.irc_channels[event.channel]) {
520 this.irc_channels[event.channel].dispose();
521 delete this.irc_channels[event.channel];
522 }
523
524 }
525
526
527
528 /**
529 * When a socket connects to an IRCd
530 * May be called before any socket handshake are complete (eg. TLS)
531 */
532 var rawSocketConnect = function(socket) {
533 // Make note of the port numbers for any identd lookups
534 // Nodejs < 0.9.6 has no socket.localPort so check this first
535 if (typeof socket.localPort != 'undefined') {
536 this.identd_port_pair = socket.localPort.toString() + '_' + socket.remotePort.toString();
537 global.clients.port_pairs[this.identd_port_pair] = this;
538 }
539 };
540
541
542 /**
543 * Handle the socket connect event, starting the IRCd registration
544 */
545 var socketConnectHandler = function () {
546 var that = this,
547 connect_data;
548
549 // Build up data to be used for webirc/etc detection
550 connect_data = {
551 connection: this,
552
553 // Array of lines to be sent to the IRCd before anything else
554 prepend_data: []
555 };
556
557 // Let the webirc/etc detection modify any required parameters
558 connect_data = findWebIrc.call(this, connect_data);
559
560 global.modules.emit('irc authorize', connect_data).done(function ircAuthorizeCb() {
561 // Send any initial data for webirc/etc
562 if (connect_data.prepend_data) {
563 _.each(connect_data.prepend_data, function(data) {
564 that.write(data);
565 });
566 }
567
568 that.write('CAP LS');
569
570 if (that.password)
571 that.write('PASS ' + that.password);
572
573 that.write('NICK ' + that.nick);
574 that.write('USER ' + that.username + ' 0 0 :' + '[www.kiwiirc.com] ' + that.nick);
575
576 that.emit('connected');
577 });
578 };
579
580
581
582 /**
583 * Load any WEBIRC or alternative settings for this connection
584 * Called in scope of the IrcConnection instance
585 */
586 function findWebIrc(connect_data) {
587 var webirc_pass = global.config.webirc_pass,
588 ip_as_username = global.config.ip_as_username,
589 tmp;
590
591
592 // Do we have a WEBIRC password for this?
593 if (webirc_pass && webirc_pass[this.irc_host.hostname]) {
594 // Build the WEBIRC line to be sent before IRC registration
595 tmp = 'WEBIRC ' + webirc_pass[this.irc_host.hostname] + ' KiwiIRC ';
596 tmp += this.user.hostname + ' ' + this.user.address;
597
598 connect_data.prepend_data = [tmp];
599 }
600
601
602 // Check if we need to pass the users IP as its username/ident
603 if (ip_as_username && ip_as_username.indexOf(this.irc_host.hostname) > -1) {
604 // Get a hex value of the clients IP
605 this.username = this.user.address.split('.').map(function ipSplitMapCb(i, idx){
606 var hex = parseInt(i, 10).toString(16);
607
608 // Pad out the hex value if it's a single char
609 if (hex.length === 1)
610 hex = '0' + hex;
611
612 return hex;
613 }).join('');
614
615 }
616
617 return connect_data;
618 }
619
620
621
622 /**
623 * The regex that parses a line of data from the IRCd
624 * Deviates from the RFC a little to support the '/' character now used in some
625 * IRCds
626 */
627 var parse_regex = /^(?:(?:(?:(@[^ ]+) )?):(?:([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)|([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)!([^\x00\r\n\ ]+?)@?([a-z0-9\.\-:\/_]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.+))?$/i;
628
629 var parse = function (data) {
630 var i,
631 msg,
632 msg2,
633 trm,
634 j,
635 tags = [],
636 tag;
637
638 //DECODE server encoding
639 data = iconv.decode(data, this.encoding);
640
641 if (this.hold_last && this.held_data !== '') {
642 data = this.held_data + data;
643 this.hold_last = false;
644 this.held_data = '';
645 }
646
647 // If the last line is incomplete, hold it until we have more data
648 if (data.substr(-1) !== '\n') {
649 this.hold_last = true;
650 }
651
652 // Process our data line by line
653 data = data.split("\n");
654 for (i = 0; i < data.length; i++) {
655 if (!data[i]) break;
656
657 // If flagged to hold the last line, store it and move on
658 if (this.hold_last && (i === data.length - 1)) {
659 this.held_data = data[i];
660 break;
661 }
662
663 // Parse the complete line, removing any carriage returns
664 msg = parse_regex.exec(data[i].replace(/^\r+|\r+$/, ''));
665
666 if (msg) {
667 if (msg[1]) {
668 tags = msg[1].split(';');
669 for (j = 0; j < tags.length; j++) {
670 tag = tags[j].split('=');
671 tags[j] = {tag: tag[0], value: tag[1]};
672 }
673 }
674 msg = {
675 tags: tags,
676 prefix: msg[2],
677 nick: msg[3],
678 ident: msg[4],
679 hostname: msg[5] || '',
680 command: msg[6],
681 params: msg[7] || '',
682 trailing: (msg[8]) ? msg[8].trim() : ''
683 };
684 msg.params = msg.params.split(' ');
685 this.irc_commands.dispatch(msg.command.toUpperCase(), msg);
686 } else {
687 // The line was not parsed correctly, must be malformed
688 console.log("Malformed IRC line: " + data[i].replace(/^\r+|\r+$/, ''));
689 }
690 }
691 };