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