1 var net
= require('net'),
3 util
= require('util'),
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'),
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);
24 // If we have a suitable Nodejs version, bring in the SOCKS functionality
25 if (version_values
[1] >= 10) {
26 Socks
= require('socksjs');
29 var IrcConnection = function (hostname
, port
, ssl
, nick
, user
, options
, state
, con_num
) {
34 this.setMaxListeners(0);
36 Stats
.incr('irc.connection.created');
38 options
= options
|| {};
41 this.connected
= false;
43 // If the connection closes and this is false, we reconnect
44 this.requested_disconnect
= false;
46 // Number of times we have tried to reconnect
47 this.reconnect_attempts
= 0;
49 // Last few lines from the IRCd for context when disconnected (server errors, etc)
50 this.last_few_lines
= [];
52 // IRCd write buffers (flood controll)
53 this.write_buffer
= [];
55 // In process of writing the buffer?
56 this.writing_buffer
= false;
58 // Max number of lines to write a second
59 this.write_buffer_lines_second
= 2;
61 // If we are in the CAP negotiation stage
62 this.cap_negotiation
= true;
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
|| '';
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
);
79 // Connection ID in the state
80 this.con_num
= con_num
;
82 // IRC protocol handling
83 this.irc_commands
= new IrcCommands
.Handler(this);
86 this.server
= new IrcServer(this, hostname
, port
);
89 this.irc_users
= Object
.create(null);
91 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
92 this.irc_users
[this.nick
] = new IrcUser(this, '*');
95 this.irc_channels
= Object
.create(null);
97 // IRC connection information
98 this.irc_host
= {hostname
: hostname
, port
: port
};
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
)))) {
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
114 // Kiwi proxy info may be set within a server module. {port: 7779, host: 'kiwi.proxy.com', ssl: false}
117 // Net. interface this connection should be made through
118 this.outgoing_interface
= false;
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'}
130 this.cap
= {requested
: [], enabled
: []};
132 // Is SASL supported on the IRCd
135 // Buffers for data sent from the IRCd
136 this.hold_last
= false;
137 this.held_data
= null;
139 this.applyIrcEvents();
141 util
.inherits(IrcConnection
, EE
);
143 module
.exports
.IrcConnection
= IrcConnection
;
147 IrcConnection
.prototype.applyIrcEvents = function () {
148 // Listen for events on the IRC connection
150 'server * connect': onServerConnect
,
151 'channel * join': onChannelJoin
,
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
161 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
166 * Start the connection to the IRCd
168 IrcConnection
.prototype.connect = function () {
171 // The socket connect event to listener for
172 var socket_connect_event_name
= 'connect';
174 // The destination address
177 dest_addr
= this.socks
.host
;
178 } else if (this.proxy
) {
179 dest_addr
= this.proxy
.host
;
181 dest_addr
= this.irc_host
.hostname
;
184 // Make sure we don't already have an open connection
185 this.disposeSocket();
187 this.requested_disconnect
= false;
189 // Get the IP family for the dest_addr (either socks or IRCd destination)
190 getConnectionFamily(dest_addr
, function getConnectionFamilyCb(err
, family
, host
) {
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
;
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
;
203 outgoing
= global
.config
.outgoing_address
.IPv4
|| '0.0.0.0';
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
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
)];
216 // Make sure we have a valid interface address
217 if (typeof outgoing
!== 'string') {
218 outgoing
= '0.0.0.0';
222 // No config was found so use the default
223 outgoing
= '0.0.0.0';
226 // Are we connecting through a SOCKS proxy?
228 that
.socket
= Socks
.connect({
229 host
: that
.irc_host
.host
,
230 port
: that
.irc_host
.port
,
232 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
234 port
: that
.socks
.port
,
235 user
: that
.socks
.user
,
236 pass
: that
.socks
.pass
,
237 localAddress
: outgoing
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
});
247 that
.socket
.connectTls(that
.irc_host
.port
, that
.irc_host
.hostname
);
249 that
.socket
.connect(that
.irc_host
.port
, that
.irc_host
.hostname
);
253 // No socks connection, connect directly to the IRCd
256 that
.socket
= tls
.connect({
258 port
: that
.irc_host
.port
,
259 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
,
260 localAddress
: outgoing
263 // We need the raw socket connect event
264 that
.socket
.socket
.on('connect', function() { rawSocketConnect
.call(that
, this); });
266 socket_connect_event_name
= 'secureConnect';
269 that
.socket
= net
.connect({
271 port
: that
.irc_host
.port
,
272 localAddress
: outgoing
277 // Apply the socket listeners
278 that
.socket
.on(socket_connect_event_name
, function socketConnectCb() {
280 // TLS connections have the actual socket as a property
281 var is_tls
= (typeof this.socket
!== 'undefined') ?
285 // TLS sockets have already called this
287 rawSocketConnect
.call(that
, this);
290 Stats
.incr('irc.connection.connected');
291 that
.connected
= true;
293 socketConnectHandler
.call(that
);
296 that
.socket
.on('error', function socketErrorCb(event
) {
297 that
.emit('error', event
);
300 that
.socket
.on('data', function () {
301 socketOnData
.apply(that
, arguments
);
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;
310 that
.connected
= false;
313 // Remove this socket form the identd lookup
314 if (that
.identd_port_pair
) {
315 delete global
.clients
.port_pairs
[that
.identd_port_pair
];
318 // Close the whole socket down
319 that
.disposeSocket();
321 if (!global
.config
.ircd_reconnect
) {
322 that
.emit('close', had_error
);
325 // If trying to reconnect, continue with it
326 if (that
.reconnect_attempts
&& that
.reconnect_attempts
< 3) {
327 should_reconnect
= true;
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;
334 should_reconnect
= false;
337 if (should_reconnect
) {
338 Stats
.incr('irc.connection.reconnect');
339 that
.reconnect_attempts
++;
340 that
.emit('reconnecting');
342 Stats
.incr('irc.connection.closed');
343 that
.emit('close', had_error
);
344 that
.reconnect_attempts
= 0;
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() {
360 * Send an event to the client
362 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
363 data
.connection_id
= this.con_num
;
364 this.state
.sendIrcCommand(event_name
, data
, callback
);
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
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
);
377 this.socket
.write(encoded_buffer
, force_complete_fn
);
381 this.write_buffer
.push(encoded_buffer
);
383 // Only flush if we're not writing already
384 if (!this.writing_buffer
) {
385 this.flushWriteBuffer();
392 * Flush the write buffer to the server in a throttled fashion
394 IrcConnection
.prototype.flushWriteBuffer = function () {
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;
403 this.writing_buffer
= true;
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;
412 this.write_buffer
= [];
413 this.writing_buffer
= false;
418 // Nothing to write? Stop writing and leave
419 if (this.write_buffer
.length
=== 0) {
420 this.writing_buffer
= false;
424 this.socket
.write(this.write_buffer
[0]);
425 this.write_buffer
= this.write_buffer
.slice(1);
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
);
431 // No more buffers to write.. so we've finished
432 this.writing_buffer
= false;
439 * Close the connection to the IRCd after forcing one last line
441 IrcConnection
.prototype.end = function (data
) {
448 this.requested_disconnect
= true;
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() {
465 * Check if any server capabilities are enabled
467 IrcConnection
.prototype.capContainsAny = function (caps
) {
470 if (!caps
instanceof Array
) {
474 enabled_caps
= _
.intersection(this.cap
.enabled
, caps
);
475 return enabled_caps
.length
> 0;
481 * Clean up this IrcConnection instance and any sockets
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
) {
492 this.disposeSocket();
495 _
.each(this.irc_users
, function (user
) {
498 _
.each(this.irc_channels
, function (chan
) {
501 this.irc_users
= undefined;
502 this.irc_channels
= undefined;
504 this.server
.dispose();
505 this.server
= undefined;
507 this.irc_commands
= undefined;
509 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
511 this.removeAllListeners();
517 * Clean up any sockets for this IrcConnection
519 IrcConnection
.prototype.disposeSocket = function () {
522 this.socket
.removeAllListeners();
528 * Set a new encoding for this connection
529 * Return true in case of success
532 IrcConnection
.prototype.setEncoding = function (encoding
) {
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
;
550 function getConnectionFamily(host
, callback
) {
551 if (net
.isIP(host
)) {
552 if (net
.isIPv4(host
)) {
553 callback(null, 'IPv4', host
);
555 callback(null, 'IPv6', host
);
558 dns
.resolve6(host
, function resolve6Cb(err
, addresses
) {
560 callback(null, 'IPv6', addresses
[0]);
562 dns
.resolve4(host
, function resolve4Cb(err
, addresses
) {
564 callback(null, 'IPv4',addresses
[0]);
575 function onChannelJoin(event
) {
578 // Only deal with ourselves joining a channel
579 if (event
.nick
!== this.nick
) {
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
);
595 function onServerConnect(event
) {
596 this.nick
= event
.nick
;
600 function onUserPrivmsg(event
) {
603 // Only deal with messages targetted to us
604 if (event
.channel
!== this.nick
) {
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
);
616 function onUserNick(event
) {
617 // Only deal with messages targetted to us
618 if (event
.nick
!== this.nick
) {
622 this.nick
= event
.newnick
;
626 function onUserParts(event
) {
627 // Only deal with ourselves leaving a channel
628 if (event
.nick
!== this.nick
) {
632 if (this.irc_channels
[event
.channel
]) {
633 this.irc_channels
[event
.channel
].dispose();
634 delete this.irc_channels
[event
.channel
];
638 function onUserKick(event
){
639 // Only deal with ourselves being kicked from a channel
640 if (event
.kicked
!== this.nick
) {
644 if (this.irc_channels
[event
.channel
]) {
645 this.irc_channels
[event
.channel
].dispose();
646 delete this.irc_channels
[event
.channel
];
654 * When a socket connects to an IRCd
655 * May be called before any socket handshake are complete (eg. TLS)
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;
668 * Handle the socket connect event, starting the IRCd registration
670 var socketConnectHandler = function () {
674 // Build up data to be used for webirc/etc detection
678 // Array of lines to be sent to the IRCd before anything else
682 // Let the webirc/etc detection modify any required parameters
683 connect_data
= findWebIrc
.call(this, connect_data
);
685 global
.modules
.emit('irc authorize', connect_data
).done(function ircAuthorizeCb() {
686 var gecos
= that
.gecos
;
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
);
694 // We don't have a gecos nor a default, so lets set somthing
695 gecos
= '[www.kiwiirc.com] ' + that
.nick
;
698 // Send any initial data for webirc/etc
699 if (connect_data
.prepend_data
) {
700 _
.each(connect_data
.prepend_data
, function(data
) {
705 that
.write('CAP LS');
708 that
.write('PASS ' + that
.password
);
711 that
.write('NICK ' + that
.nick
);
712 that
.write('USER ' + that
.username
+ ' 0 0 :' + gecos
);
714 that
.emit('connected');
721 * Load any WEBIRC or alternative settings for this connection
722 * Called in scope of the IrcConnection instance
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
;
730 // Do we have a single WEBIRC password?
731 if (typeof webirc_pass
=== 'string') {
732 found_webirc_pass
= webirc_pass
;
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
];
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
;
744 connect_data
.prepend_data
= [tmp
];
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);
753 // Pad out the hex value if it's a single char
754 if (hex
.length
=== 1) {
768 * Buffer any data we get from the IRCd until we have complete lines.
770 function socketOnData(data
) {
771 var data_pos
, // Current position within the data Buffer
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
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;
786 // No complete lines of data? Check to see if buffering the data would exceed the max buffer size
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();
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
);
799 this.held_data
= data
;
803 // No complete lines to process..
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;
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();
825 this.hold_last
= true;
826 this.held_data
= new Buffer(data
.length
- line_start
);
827 data
.copy(this.held_data
, 0, line_start
);
830 // Process our data line by line
831 for (i
= 0; i
< lines
.length
; i
++) {
832 parseIrcLine
.call(this, lines
[i
]);
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
844 var parse_regex
= /^(?:(?:(?:@([^ ]+) )?):(?:([^\s!]+)|([^\s!]+)!([^\s@]+)@?([^\s]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.*))?$/i;
846 function parseIrcLine(buffer_line
) {
855 // Decode server encoding
856 line
= iconv
.decode(buffer_line
, this.encoding
);
861 // Parse the complete line, removing any carriage returns
862 msg
= parse_regex
.exec(line
.replace(/^\r+|\r+$/, ''));
865 // The line was not parsed correctly, must be malformed
866 winston
.warn('Malformed IRC line: %s', line
.replace(/^\r+|\r+$/, ''));
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+$/, ''));
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;
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
);
882 // Extract any tags (msg[1])
884 tags
= msg
[1].split(';');
886 for (i
= 0; i
< tags
.length
; i
++) {
887 tag
= tags
[i
].split('=');
888 tags
[i
] = {tag
: tag
[0], value
: tag
[1]};
897 hostname
: msg
[5] || '',
899 params
: msg
[7] ? msg
[7].split(/ +/) : []
903 msg_obj
.params
.push(msg
[8].trim());
906 this.irc_commands
.dispatch(new IrcCommands
.Command(msg_obj
.command
.toUpperCase(), msg_obj
));