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'),
18 // Break the Node.js version down into usable parts
19 var version_values
= process
.version
.substr(1).split('.').map(function (item
) {
20 return parseInt(item
, 10);
23 // If we have a suitable Nodejs version, bring in the SOCKS functionality
24 if (version_values
[1] >= 10) {
25 Socks
= require('socksjs');
28 var IrcConnection = function (hostname
, port
, ssl
, nick
, user
, options
, state
, con_num
) {
33 this.setMaxListeners(0);
35 options
= options
|| {};
38 this.connected
= false;
40 // If the connection closes and this is false, we reconnect
41 this.requested_disconnect
= false;
43 // Number of times we have tried to reconnect
44 this.reconnect_attempts
= 0;
46 // IRCd write buffers (flood controll)
47 this.write_buffer
= [];
49 // In process of writing the buffer?
50 this.writing_buffer
= false;
52 // Max number of lines to write a second
53 this.write_buffer_lines_second
= 2;
55 // If registeration with the IRCd has completed
56 this.registered
= false;
58 // If we are in the CAP negotiation stage
59 this.cap_negotiation
= true;
63 this.user
= user
; // Contains users real hostname and address
64 this.username
= this.nick
.replace(/[^0-9a-zA-Z\-_.\/]/, '');
65 this.gecos
= ''; // Users real-name. Uses default from config if empty
66 this.password
= options
.password
|| '';
68 // Set the passed encoding. or the default if none giving or it fails
69 if (!options
.encoding
|| !this.setEncoding(options
.encoding
)) {
70 this.setEncoding(global
.config
.default_encoding
);
76 // Connection ID in the state
77 this.con_num
= con_num
;
79 // IRC protocol handling
80 this.irc_commands
= new IrcCommands
.Handler(this);
83 this.server
= new IrcServer(this, hostname
, port
);
86 this.irc_users
= Object
.create(null);
88 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
89 this.irc_users
[this.nick
] = new IrcUser(this, '*');
92 this.irc_channels
= Object
.create(null);
94 // IRC connection information
95 this.irc_host
= {hostname
: hostname
, port
: port
};
98 // SOCKS proxy details
99 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
100 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
)))) {
102 host
: global
.config
.socks_proxy
.address
,
103 port
: global
.config
.socks_proxy
.port
,
104 user
: global
.config
.socks_proxy
.user
,
105 pass
: global
.config
.socks_proxy
.pass
111 // Kiwi proxy info may be set within a server module. {port: 7779, host: 'kiwi.proxy.com', ssl: false}
114 // Net. interface this connection should be made through
115 this.outgoing_interface
= false;
117 // Options sent by the IRCd
118 this.options
= Object
.create(null);
119 this.options
.PREFIX
= [
120 {symbol
: '~', mode
: 'q'},
121 {symbol
: '&', mode
: 'a'},
122 {symbol
: '@', mode
: 'o'},
123 {symbol
: '%', mode
: 'h'},
124 {symbol
: '+', mode
: 'v'}
127 this.cap
= {requested
: [], enabled
: []};
129 // Is SASL supported on the IRCd
132 // Buffers for data sent from the IRCd
133 this.hold_last
= false;
134 this.held_data
= null;
136 this.applyIrcEvents();
138 util
.inherits(IrcConnection
, EE
);
140 module
.exports
.IrcConnection
= IrcConnection
;
144 IrcConnection
.prototype.applyIrcEvents = function () {
145 // Listen for events on the IRC connection
147 'server * connect': onServerConnect
,
148 'channel * join': onChannelJoin
,
150 // TODO: uncomment when using an IrcUser per nick
151 //'user:*:privmsg': onUserPrivmsg,
152 'user * nick': onUserNick
,
153 'channel * part': onUserParts
,
154 'channel * quit': onUserParts
,
155 'channel * kick': onUserKick
158 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
163 * Start the connection to the IRCd
165 IrcConnection
.prototype.connect = function () {
168 // The socket connect event to listener for
169 var socket_connect_event_name
= 'connect';
171 // The destination address
174 dest_addr
= this.socks
.host
;
175 } else if (this.proxy
) {
176 dest_addr
= this.proxy
.host
;
178 dest_addr
= this.irc_host
.hostname
;
181 // Make sure we don't already have an open connection
182 this.disposeSocket();
184 this.requested_disconnect
= false;
186 // Get the IP family for the dest_addr (either socks or IRCd destination)
187 getConnectionFamily(dest_addr
, function getConnectionFamilyCb(err
, family
, host
) {
190 // Decide which net. interface to make the connection through
191 if (that
.outgoing_interface
) {
192 // An specific interface has been given for this connection
193 outgoing
= this.outgoing_interface
;
195 } else if (global
.config
.outgoing_address
) {
196 // Pick an interface from the config
197 if ((family
=== 'IPv6') && (global
.config
.outgoing_address
.IPv6
)) {
198 outgoing
= global
.config
.outgoing_address
.IPv6
;
200 outgoing
= global
.config
.outgoing_address
.IPv4
|| '0.0.0.0';
202 // We don't have an IPv6 interface but dest_addr may still resolve to
203 // an IPv4 address. Reset `host` and try connecting anyway, letting it
204 // fail if an IPv4 resolved address is not found
208 // If we have an array of interfaces, select a random one
209 if (typeof outgoing
!== 'string' && outgoing
.length
) {
210 outgoing
= outgoing
[Math
.floor(Math
.random() * outgoing
.length
)];
213 // Make sure we have a valid interface address
214 if (typeof outgoing
!== 'string') {
215 outgoing
= '0.0.0.0';
219 // No config was found so use the default
220 outgoing
= '0.0.0.0';
223 // Are we connecting through a SOCKS proxy?
225 that
.socket
= Socks
.connect({
226 host
: that
.irc_host
.host
,
227 port
: that
.irc_host
.port
,
229 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
231 port
: that
.socks
.port
,
232 user
: that
.socks
.user
,
233 pass
: that
.socks
.pass
,
234 localAddress
: outgoing
237 } else if (that
.proxy
) {
238 that
.socket
= new Proxy
.ProxySocket(that
.proxy
.port
, host
, {
239 username
: that
.username
,
240 interface: that
.proxy
.interface
241 }, {ssl
: that
.proxy
.ssl
});
244 that
.socket
.connectTls(that
.irc_host
.port
, that
.irc_host
.hostname
);
246 that
.socket
.connect(that
.irc_host
.port
, that
.irc_host
.hostname
);
250 // No socks connection, connect directly to the IRCd
253 that
.socket
= tls
.connect({
255 port
: that
.irc_host
.port
,
256 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
,
257 localAddress
: outgoing
260 // We need the raw socket connect event
261 that
.socket
.socket
.on('connect', function() { rawSocketConnect
.call(that
, this); });
263 socket_connect_event_name
= 'secureConnect';
266 that
.socket
= net
.connect({
268 port
: that
.irc_host
.port
,
269 localAddress
: outgoing
274 // Apply the socket listeners
275 that
.socket
.on(socket_connect_event_name
, function socketConnectCb() {
277 // TLS connections have the actual socket as a property
278 var is_tls
= (typeof this.socket
!== 'undefined') ?
282 // TLS sockets have already called this
284 rawSocketConnect
.call(that
, this);
287 that
.connected
= true;
289 socketConnectHandler
.call(that
);
292 that
.socket
.on('error', function socketErrorCb(event
) {
293 that
.emit('error', event
);
296 that
.socket
.on('data', function () {
297 socketOnData
.apply(that
, arguments
);
300 that
.socket
.on('close', function socketCloseCb(had_error
) {
301 // If that.connected is false, we never actually managed to connect
302 var was_connected
= that
.connected
,
303 had_registered
= that
.server
.registered
,
304 should_reconnect
= false;
306 that
.connected
= false;
309 // Remove this socket form the identd lookup
310 if (that
.identd_port_pair
) {
311 delete global
.clients
.port_pairs
[that
.identd_port_pair
];
314 // If trying to reconnect, continue with it
315 if (that
.reconnect_attempts
&& that
.reconnect_attempts
< 3) {
316 should_reconnect
= true;
318 // If this was an unplanned disconnect and we were originally connected OK, reconnect
319 } else if (!that
.requested_disconnect
&& was_connected
&& had_registered
) {
320 should_reconnect
= true;
323 should_reconnect
= false;
326 if (should_reconnect
) {
327 that
.reconnect_attempts
++;
328 that
.emit('reconnecting');
330 that
.emit('close', had_error
);
331 that
.reconnect_attempts
= 0;
334 // Close the whole socket down
335 that
.disposeSocket();
337 // If this socket closing was not expected and we did actually connect and
338 // we did previously completely register on the network, then reconnect
339 if (should_reconnect
) {
340 setTimeout(function() {
349 * Send an event to the client
351 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
352 data
.connection_id
= this.con_num
;
353 this.state
.sendIrcCommand(event_name
, data
, callback
);
357 * Write a line of data to the IRCd
358 * @param data The line of data to be sent
359 * @param force Write the data now, ignoring any write queue
361 IrcConnection
.prototype.write = function (data
, force
, force_complete_fn
) {
362 //ENCODE string to encoding of the server
363 var encoded_buffer
= iconv
.encode(data
+ '\r\n', this.encoding
);
366 this.socket
.write(encoded_buffer
, force_complete_fn
);
370 this.write_buffer
.push(encoded_buffer
);
372 // Only flush if we're not writing already
373 if (!this.writing_buffer
) {
374 this.flushWriteBuffer();
381 * Flush the write buffer to the server in a throttled fashion
383 IrcConnection
.prototype.flushWriteBuffer = function () {
385 // In case the socket closed between writing our queue.. clean up
386 if (!this.connected
) {
387 this.write_buffer
= [];
388 this.writing_buffer
= false;
392 this.writing_buffer
= true;
394 // Disabled write buffer? Send everything we have
395 if (!this.write_buffer_lines_second
) {
396 this.write_buffer
.forEach(function(buffer
) {
397 this.socket
.write(buffer
);
398 this.write_buffer
= null;
401 this.write_buffer
= [];
402 this.writing_buffer
= false;
407 // Nothing to write? Stop writing and leave
408 if (this.write_buffer
.length
=== 0) {
409 this.writing_buffer
= false;
413 this.socket
.write(this.write_buffer
[0]);
414 this.write_buffer
= this.write_buffer
.slice(1);
416 // Call this function again at some point if we still have data to write
417 if (this.write_buffer
.length
> 0) {
418 setTimeout(this.flushWriteBuffer
.bind(this), 1000 / this.write_buffer_lines_second
);
420 // No more buffers to write.. so we've finished
421 this.writing_buffer
= false;
428 * Close the connection to the IRCd after forcing one last line
430 IrcConnection
.prototype.end = function (data
) {
437 this.requested_disconnect
= true;
440 // Once the last bit of data has been sent, then re-run this function to close the socket
441 this.write(data
, true, function() {
454 * Check if any server capabilities are enabled
456 IrcConnection
.prototype.capContainsAny = function (caps
) {
459 if (!caps
instanceof Array
) {
463 enabled_caps
= _
.intersection(this.cap
.enabled
, caps
);
464 return enabled_caps
.length
> 0;
470 * Clean up this IrcConnection instance and any sockets
472 IrcConnection
.prototype.dispose = function () {
473 // If we're still connected, wait until the socket is closed before disposing
474 // so that all the events are still correctly triggered
475 if (this.socket
&& this.connected
) {
481 this.disposeSocket();
484 _
.each(this.irc_users
, function (user
) {
487 _
.each(this.irc_channels
, function (chan
) {
490 this.irc_users
= undefined;
491 this.irc_channels
= undefined;
493 this.server
.dispose();
494 this.server
= undefined;
496 this.irc_commands
= undefined;
498 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
500 this.removeAllListeners();
506 * Clean up any sockets for this IrcConnection
508 IrcConnection
.prototype.disposeSocket = function () {
511 this.socket
.removeAllListeners();
517 * Set a new encoding for this connection
518 * Return true in case of success
521 IrcConnection
.prototype.setEncoding = function (encoding
) {
525 encoded_test
= iconv
.encode("TEST", encoding
);
526 //This test is done to check if this encoding also supports
527 //the ASCII charset required by the IRC protocols
528 //(Avoid the use of base64 or incompatible encodings)
529 if (encoded_test
== "TEST") { // jshint ignore:line
530 this.encoding
= encoding
;
539 function getConnectionFamily(host
, callback
) {
540 if (net
.isIP(host
)) {
541 if (net
.isIPv4(host
)) {
542 callback(null, 'IPv4', host
);
544 callback(null, 'IPv6', host
);
547 dns
.resolve6(host
, function resolve6Cb(err
, addresses
) {
549 callback(null, 'IPv6', addresses
[0]);
551 dns
.resolve4(host
, function resolve4Cb(err
, addresses
) {
553 callback(null, 'IPv4',addresses
[0]);
564 function onChannelJoin(event
) {
567 // Only deal with ourselves joining a channel
568 if (event
.nick
!== this.nick
) {
572 // We should only ever get a JOIN command for a channel
573 // we're not already a member of.. but check we don't
574 // have this channel in case something went wrong somewhere
575 // at an earlier point
576 if (!this.irc_channels
[event
.channel
]) {
577 chan
= new IrcChannel(this, event
.channel
);
578 this.irc_channels
[event
.channel
] = chan
;
579 chan
.irc_events
.join
.call(chan
, event
);
584 function onServerConnect(event
) {
585 this.nick
= event
.nick
;
589 function onUserPrivmsg(event
) {
592 // Only deal with messages targetted to us
593 if (event
.channel
!== this.nick
) {
597 if (!this.irc_users
[event
.nick
]) {
598 user
= new IrcUser(this, event
.nick
);
599 this.irc_users
[event
.nick
] = user
;
600 user
.irc_events
.privmsg
.call(user
, event
);
605 function onUserNick(event
) {
606 // Only deal with messages targetted to us
607 if (event
.nick
!== this.nick
) {
611 this.nick
= event
.newnick
;
615 function onUserParts(event
) {
616 // Only deal with ourselves leaving a channel
617 if (event
.nick
!== this.nick
) {
621 if (this.irc_channels
[event
.channel
]) {
622 this.irc_channels
[event
.channel
].dispose();
623 delete this.irc_channels
[event
.channel
];
627 function onUserKick(event
){
628 // Only deal with ourselves being kicked from a channel
629 if (event
.kicked
!== this.nick
) {
633 if (this.irc_channels
[event
.channel
]) {
634 this.irc_channels
[event
.channel
].dispose();
635 delete this.irc_channels
[event
.channel
];
643 * When a socket connects to an IRCd
644 * May be called before any socket handshake are complete (eg. TLS)
646 var rawSocketConnect = function(socket
) {
647 // Make note of the port numbers for any identd lookups
648 // Nodejs < 0.9.6 has no socket.localPort so check this first
649 if (typeof socket
.localPort
!== 'undefined') {
650 this.identd_port_pair
= socket
.localPort
.toString() + '_' + socket
.remotePort
.toString();
651 global
.clients
.port_pairs
[this.identd_port_pair
] = this;
657 * Handle the socket connect event, starting the IRCd registration
659 var socketConnectHandler = function () {
663 // Build up data to be used for webirc/etc detection
667 // Array of lines to be sent to the IRCd before anything else
671 // Let the webirc/etc detection modify any required parameters
672 connect_data
= findWebIrc
.call(this, connect_data
);
674 global
.modules
.emit('irc authorize', connect_data
).done(function ircAuthorizeCb() {
675 var gecos
= that
.gecos
;
677 if (!gecos
&& global
.config
.default_gecos
) {
678 // We don't have a gecos yet, so use the default
679 gecos
= global
.config
.default_gecos
.toString().replace('%n', that
.nick
);
680 gecos
= gecos
.replace('%h', that
.user
.hostname
);
683 // We don't have a gecos nor a default, so lets set somthing
684 gecos
= '[www.kiwiirc.com] ' + that
.nick
;
687 // Send any initial data for webirc/etc
688 if (connect_data
.prepend_data
) {
689 _
.each(connect_data
.prepend_data
, function(data
) {
694 that
.write('CAP LS');
697 that
.write('PASS ' + that
.password
);
700 that
.write('NICK ' + that
.nick
);
701 that
.write('USER ' + that
.username
+ ' 0 0 :' + gecos
);
703 that
.emit('connected');
710 * Load any WEBIRC or alternative settings for this connection
711 * Called in scope of the IrcConnection instance
713 function findWebIrc(connect_data
) {
714 var webirc_pass
= global
.config
.webirc_pass
,
715 ip_as_username
= global
.config
.ip_as_username
,
719 // Do we have a WEBIRC password for this?
720 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
721 // Build the WEBIRC line to be sent before IRC registration
722 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
723 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
725 connect_data
.prepend_data
= [tmp
];
729 // Check if we need to pass the users IP as its username/ident
730 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
731 // Get a hex value of the clients IP
732 this.username
= this.user
.address
.split('.').map(function ipSplitMapCb(i
){
733 var hex
= parseInt(i
, 10).toString(16);
735 // Pad out the hex value if it's a single char
736 if (hex
.length
=== 1) {
750 * Buffer any data we get from the IRCd until we have complete lines.
752 function socketOnData(data
) {
753 var data_pos
, // Current position within the data Buffer
757 max_buffer_size
= 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
758 // May need tweaking when IRCv3 message tags are more widespread
760 // Split data chunk into individual lines
761 for (data_pos
= 0; data_pos
< data
.length
; data_pos
++) {
762 if (data
[data_pos
] === 0x0A) { // Check if byte is a line feed
763 lines
.push(data
.slice(line_start
, data_pos
));
764 line_start
= data_pos
+ 1;
768 // No complete lines of data? Check to see if buffering the data would exceed the max buffer size
770 if ((this.held_data
? this.held_data
.length
: 0 ) + data
.length
> max_buffer_size
) {
771 // Buffering this data would exeed our max buffer size
772 this.emit('error', 'Message buffer too large');
773 this.socket
.destroy();
777 // Append the incomplete line to our held_data and wait for more
778 if (this.held_data
) {
779 this.held_data
= Buffer
.concat([this.held_data
, data
], this.held_data
.length
+ data
.length
);
781 this.held_data
= data
;
785 // No complete lines to process..
789 // If we have an incomplete line held from the previous chunk of data
790 // merge it with the first line from this chunk of data
791 if (this.hold_last
&& this.held_data
!== null) {
792 lines
[0] = Buffer
.concat([this.held_data
, lines
[0]], this.held_data
.length
+ lines
[0].length
);
793 this.hold_last
= false;
794 this.held_data
= null;
797 // If the last line of data in this chunk is not complete, hold it so
798 // it can be merged with the first line from the next chunk
799 if (line_start
< data_pos
) {
800 if ((data
.length
- line_start
) > max_buffer_size
) {
801 // Buffering this data would exeed our max buffer size
802 this.emit('error', 'Message buffer too large');
803 this.socket
.destroy();
807 this.hold_last
= true;
808 this.held_data
= new Buffer(data
.length
- line_start
);
809 data
.copy(this.held_data
, 0, line_start
);
812 // Process our data line by line
813 for (i
= 0; i
< lines
.length
; i
++) {
814 parseIrcLine
.call(this, lines
[i
]);
822 * The regex that parses a line of data from the IRCd
823 * Deviates from the RFC a little to support the '/' character now used in some
826 var parse_regex
= /^(?:(?:(?:@([^ ]+) )?):(?:([^\s!]+)|([^\s!]+)!([^\s@]+)@?([^\s]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.*))?$/i;
828 function parseIrcLine(buffer_line
) {
836 // Decode server encoding
837 line
= iconv
.decode(buffer_line
, this.encoding
);
842 // Parse the complete line, removing any carriage returns
843 msg
= parse_regex
.exec(line
.replace(/^\r+|\r+$/, ''));
846 // The line was not parsed correctly, must be malformed
847 winston
.warn('Malformed IRC line: %s', line
.replace(/^\r+|\r+$/, ''));
851 // Extract any tags (msg[1])
853 tags
= msg
[1].split(';');
855 for (i
= 0; i
< tags
.length
; i
++) {
856 tag
= tags
[i
].split('=');
857 tags
[i
] = {tag
: tag
[0], value
: tag
[1]};
866 hostname
: msg
[5] || '',
868 params
: msg
[7] ? msg
[7].split(/ +/) : []
872 msg_obj
.params
.push(msg
[8].trim());
875 this.irc_commands
.dispatch(new IrcCommands
.Command(msg_obj
.command
.toUpperCase(), msg_obj
));