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
|| '';
70 this.quit_message
= ''; // Uses default from config if empty
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
);
80 // Connection ID in the state
81 this.con_num
= con_num
;
83 // IRC protocol handling
84 this.irc_commands
= new IrcCommands
.Handler(this);
87 this.server
= new IrcServer(this, hostname
, port
);
90 this.irc_users
= Object
.create(null);
92 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
93 this.irc_users
[this.nick
] = new IrcUser(this, '*');
96 this.irc_channels
= Object
.create(null);
98 // IRC connection information
99 this.irc_host
= {hostname
: hostname
, port
: port
};
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
)))) {
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
115 // Kiwi proxy info may be set within a server module. {port: 7779, host: 'kiwi.proxy.com', ssl: false}
118 // Net. interface this connection should be made through
119 this.outgoing_interface
= false;
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'}
131 this.cap
= {requested
: [], enabled
: []};
133 // Is SASL supported on the IRCd
136 // Buffers for data sent from the IRCd
137 this.hold_last
= false;
138 this.held_data
= null;
140 this.applyIrcEvents();
142 util
.inherits(IrcConnection
, EE
);
144 module
.exports
.IrcConnection
= IrcConnection
;
148 IrcConnection
.prototype.applyIrcEvents = function () {
149 // Listen for events on the IRC connection
151 'server * connect': onServerConnect
,
152 'channel * join': onChannelJoin
,
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
162 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
167 * Start the connection to the IRCd
169 IrcConnection
.prototype.connect = function () {
172 // The socket connect event to listener for
173 var socket_connect_event_name
= 'connect';
175 // The destination address
178 dest_addr
= this.socks
.host
;
179 } else if (this.proxy
) {
180 dest_addr
= this.proxy
.host
;
182 dest_addr
= this.irc_host
.hostname
;
185 // Make sure we don't already have an open connection
186 this.disposeSocket();
188 this.requested_disconnect
= false;
190 // Get the IP family for the dest_addr (either socks or IRCd destination)
191 getConnectionFamily(dest_addr
, function getConnectionFamilyCb(err
, family
, host
) {
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
;
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
;
204 outgoing
= global
.config
.outgoing_address
.IPv4
|| '0.0.0.0';
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
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
)];
217 // Make sure we have a valid interface address
218 if (typeof outgoing
!== 'string') {
219 outgoing
= '0.0.0.0';
223 // No config was found so use the default
224 outgoing
= '0.0.0.0';
227 // Are we connecting through a SOCKS proxy?
229 that
.socket
= Socks
.connect({
230 host
: that
.irc_host
.host
,
231 port
: that
.irc_host
.port
,
233 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
235 port
: that
.socks
.port
,
236 user
: that
.socks
.user
,
237 pass
: that
.socks
.pass
,
238 localAddress
: outgoing
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
});
248 that
.socket
.connectTls(that
.irc_host
.port
, that
.irc_host
.hostname
);
250 that
.socket
.connect(that
.irc_host
.port
, that
.irc_host
.hostname
);
254 // No socks connection, connect directly to the IRCd
257 that
.socket
= tls
.connect({
259 port
: that
.irc_host
.port
,
260 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
,
261 localAddress
: outgoing
264 // We need the raw socket connect event
265 that
.socket
.socket
.on('connect', function() { rawSocketConnect
.call(that
, this); });
267 socket_connect_event_name
= 'secureConnect';
270 that
.socket
= net
.connect({
272 port
: that
.irc_host
.port
,
273 localAddress
: outgoing
278 // Apply the socket listeners
279 that
.socket
.on(socket_connect_event_name
, function socketConnectCb() {
281 // TLS connections have the actual socket as a property
282 var is_tls
= (typeof this.socket
!== 'undefined') ?
286 // TLS sockets have already called this
288 rawSocketConnect
.call(that
, this);
291 Stats
.incr('irc.connection.connected');
292 that
.connected
= true;
294 socketConnectHandler
.call(that
);
297 that
.socket
.on('error', function socketErrorCb(event
) {
298 that
.emit('error', event
);
301 that
.socket
.on('data', function () {
302 socketOnData
.apply(that
, arguments
);
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;
311 that
.connected
= false;
314 // Remove this socket form the identd lookup
315 if (that
.identd_port_pair
) {
316 delete global
.clients
.port_pairs
[that
.identd_port_pair
];
319 // Close the whole socket down
320 that
.disposeSocket();
322 if (!global
.config
.ircd_reconnect
) {
323 that
.emit('close', had_error
);
326 // If trying to reconnect, continue with it
327 if (that
.reconnect_attempts
&& that
.reconnect_attempts
< 3) {
328 should_reconnect
= true;
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;
335 should_reconnect
= false;
338 if (should_reconnect
) {
339 Stats
.incr('irc.connection.reconnect');
340 that
.reconnect_attempts
++;
341 that
.emit('reconnecting');
343 Stats
.incr('irc.connection.closed');
344 that
.emit('close', had_error
);
345 that
.reconnect_attempts
= 0;
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() {
361 * Send an event to the client
363 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
364 data
.connection_id
= this.con_num
;
365 this.state
.sendIrcCommand(event_name
, data
, callback
);
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
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
);
378 this.socket
&& this.socket
.write(encoded_buffer
, force_complete_fn
);
382 this.write_buffer
.push(encoded_buffer
);
384 // Only flush if we're not writing already
385 if (!this.writing_buffer
) {
386 this.flushWriteBuffer();
393 * Flush the write buffer to the server in a throttled fashion
395 IrcConnection
.prototype.flushWriteBuffer = function () {
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;
404 this.writing_buffer
= true;
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;
413 this.write_buffer
= [];
414 this.writing_buffer
= false;
419 // Nothing to write? Stop writing and leave
420 if (this.write_buffer
.length
=== 0) {
421 this.writing_buffer
= false;
425 this.socket
&& this.socket
.write(this.write_buffer
[0]);
426 this.write_buffer
= this.write_buffer
.slice(1);
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
);
432 // No more buffers to write.. so we've finished
433 this.writing_buffer
= false;
440 * Close the connection to the IRCd after forcing one last line
442 IrcConnection
.prototype.end = function (data
) {
449 this.requested_disconnect
= true;
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() {
460 this.socket
.destroy();
466 * Check if any server capabilities are enabled
468 IrcConnection
.prototype.capContainsAny = function (caps
) {
471 if (!caps
instanceof Array
) {
475 enabled_caps
= _
.intersection(this.cap
.enabled
, caps
);
476 return enabled_caps
.length
> 0;
482 * Clean up this IrcConnection instance and any sockets
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
) {
493 this.disposeSocket();
496 _
.each(this.irc_users
, function (user
) {
499 _
.each(this.irc_channels
, function (chan
) {
502 this.irc_users
= undefined;
503 this.irc_channels
= undefined;
505 this.server
.dispose();
506 this.server
= undefined;
508 this.irc_commands
= undefined;
510 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
512 this.removeAllListeners();
518 * Clean up any sockets for this IrcConnection
520 IrcConnection
.prototype.disposeSocket = function () {
523 this.socket
.removeAllListeners();
529 * Set a new encoding for this connection
530 * Return true in case of success
533 IrcConnection
.prototype.setEncoding = function (encoding
) {
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
;
551 function getConnectionFamily(host
, callback
) {
552 if (net
.isIP(host
)) {
553 if (net
.isIPv4(host
)) {
554 callback(null, 'IPv4', host
);
556 callback(null, 'IPv6', host
);
559 dns
.resolve6(host
, function resolve6Cb(err
, addresses
) {
561 callback(null, 'IPv6', addresses
[0]);
563 dns
.resolve4(host
, function resolve4Cb(err
, addresses
) {
565 callback(null, 'IPv4',addresses
[0]);
576 function onChannelJoin(event
) {
579 // Only deal with ourselves joining a channel
580 if (event
.nick
!== this.nick
) {
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
);
596 function onServerConnect(event
) {
597 this.nick
= event
.nick
;
601 function onUserPrivmsg(event
) {
604 // Only deal with messages targetted to us
605 if (event
.channel
!== this.nick
) {
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
);
617 function onUserNick(event
) {
618 // Only deal with messages targetted to us
619 if (event
.nick
!== this.nick
) {
623 this.nick
= event
.newnick
;
627 function onUserParts(event
) {
628 // Only deal with ourselves leaving a channel
629 if (event
.nick
!== this.nick
) {
633 if (this.irc_channels
[event
.channel
]) {
634 this.irc_channels
[event
.channel
].dispose();
635 delete this.irc_channels
[event
.channel
];
639 function onUserKick(event
){
640 // Only deal with ourselves being kicked from a channel
641 if (event
.kicked
!== this.nick
) {
645 if (this.irc_channels
[event
.channel
]) {
646 this.irc_channels
[event
.channel
].dispose();
647 delete this.irc_channels
[event
.channel
];
655 * When a socket connects to an IRCd
656 * May be called before any socket handshake are complete (eg. TLS)
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;
669 * Handle the socket connect event, starting the IRCd registration
671 var socketConnectHandler = function () {
675 // Build up data to be used for webirc/etc detection
679 // Array of lines to be sent to the IRCd before anything else
683 // Let the webirc/etc detection modify any required parameters
684 connect_data
= findWebIrc
.call(this, connect_data
);
686 global
.modules
.emit('irc authorize', connect_data
).then(function ircAuthorizeCb() {
687 var gecos
= that
.gecos
;
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
);
695 // We don't have a gecos nor a default, so lets set somthing
696 gecos
= '[www.kiwiirc.com] ' + that
.nick
;
699 // Send any initial data for webirc/etc
700 if (connect_data
.prepend_data
) {
701 _
.each(connect_data
.prepend_data
, function(data
) {
706 that
.write('CAP LS');
709 that
.write('PASS ' + that
.password
);
712 that
.write('NICK ' + that
.nick
);
713 that
.write('USER ' + that
.username
+ ' 0 0 :' + gecos
);
715 that
.emit('connected');
722 * Load any WEBIRC or alternative settings for this connection
723 * Called in scope of the IrcConnection instance
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
;
731 // Do we have a single WEBIRC password?
732 if (typeof webirc_pass
=== 'string') {
733 found_webirc_pass
= webirc_pass
;
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
];
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
;
745 connect_data
.prepend_data
= [tmp
];
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);
754 // Pad out the hex value if it's a single char
755 if (hex
.length
=== 1) {
769 * Buffer any data we get from the IRCd until we have complete lines.
771 function socketOnData(data
) {
772 var data_pos
, // Current position within the data Buffer
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
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;
787 // No complete lines of data? Check to see if buffering the data would exceed the max buffer size
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();
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
);
800 this.held_data
= data
;
804 // No complete lines to process..
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;
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();
826 this.hold_last
= true;
827 this.held_data
= new Buffer(data
.length
- line_start
);
828 data
.copy(this.held_data
, 0, line_start
);
831 // Process our data line by line
832 for (i
= 0; i
< lines
.length
; i
++) {
833 parseIrcLine
.call(this, lines
[i
]);
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
845 var parse_regex
= /^(?:(?:(?:@([^ ]+) )?):(?:([^\s!]+)|([^\s!]+)!([^\s@]+)@?([^\s]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.*))?$/i;
847 function parseIrcLine(buffer_line
) {
856 // Decode server encoding
857 line
= iconv
.decode(buffer_line
, this.encoding
);
862 // Parse the complete line, removing any carriage returns
863 msg
= parse_regex
.exec(line
.replace(/^\r+|\r+$/, ''));
866 // The line was not parsed correctly, must be malformed
867 winston
.warn('Malformed IRC line: %s', line
.replace(/^\r+|\r+$/, ''));
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+$/, ''));
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;
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
);
883 // Extract any tags (msg[1])
885 tags
= msg
[1].split(';');
887 for (i
= 0; i
< tags
.length
; i
++) {
888 tag
= tags
[i
].split('=');
889 tags
[i
] = {tag
: tag
[0], value
: tag
[1]};
896 nick
: msg
[3] || msg
[2], // Nick will be in the prefix slot if a full user mask is not used
898 hostname
: msg
[5] || '',
900 params
: msg
[7] ? msg
[7].split(/ +/) : []
904 msg_obj
.params
.push(msg
[8].trimRight());
907 this.irc_commands
.dispatch(new IrcCommands
.Command(msg_obj
.command
.toUpperCase(), msg_obj
));