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