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