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