1 var net
= require('net'),
3 util
= require('util'),
6 EventBinder
= require('./eventbinder.js'),
7 IrcServer
= require('./server.js'),
8 IrcCommands
= require('./commands.js'),
9 IrcChannel
= require('./channel.js'),
10 IrcUser
= require('./user.js'),
11 EE
= require('../ee.js'),
12 iconv
= require('iconv-lite'),
16 // Break the Node.js version down into usable parts
17 var version_values
= process
.version
.substr(1).split('.').map(function (item
) {
18 return parseInt(item
, 10);
21 // If we have a suitable Nodejs version, bring int he socks functionality
22 if (version_values
[1] >= 10) {
23 Socks
= require('socksjs');
26 var IrcConnection = function (hostname
, port
, ssl
, nick
, user
, options
, state
, con_num
) {
33 this.setMaxListeners(0);
35 options
= options
|| {};
38 this.connected
= false;
40 // IRCd write buffers (flood controll)
41 this.write_buffer
= [];
43 // In process of writing the buffer?
44 this.writing_buffer
= false;
46 // Max number of lines to write a second
47 this.write_buffer_lines_second
= 2;
49 // If registeration with the IRCd has completed
50 this.registered
= false;
52 // If we are in the CAP negotiation stage
53 this.cap_negotiation
= true;
57 this.user
= user
; // Contains users real hostname and address
58 this.username
= this.nick
.replace(/[^0-9a-zA-Z\-_.\/]/, '');
59 this.password
= options
.password
|| '';
61 // Set the passed encoding. or the default if none giving or it fails
62 if (!options
.encoding
|| !this.setEncoding(options
.encoding
)) {
63 this.setEncoding(global
.config
.default_encoding
);
69 // Connection ID in the state
70 this.con_num
= con_num
;
72 // IRC protocol handling
73 this.irc_commands
= new IrcCommands(this);
76 this.server
= new IrcServer(this, hostname
, port
);
79 this.irc_users
= Object
.create(null);
81 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
82 this.irc_users
[this.nick
] = new IrcUser(this, '*');
85 this.irc_channels
= Object
.create(null);
87 // IRC connection information
88 this.irc_host
= {hostname
: hostname
, port
: port
};
91 // SOCKS proxy details
92 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
93 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
)))) {
95 host
: global
.config
.socks_proxy
.address
,
96 port
: global
.config
.socks_proxy
.port
,
97 user
: global
.config
.socks_proxy
.user
,
98 pass
: global
.config
.socks_proxy
.pass
104 // Net. interface this connection should be made through
105 this.outgoing_interface
= false;
107 // Options sent by the IRCd
108 this.options
= Object
.create(null);
109 this.cap
= {requested
: [], enabled
: []};
111 // Is SASL supported on the IRCd
114 // Buffers for data sent from the IRCd
115 this.hold_last
= false;
116 this.held_data
= null;
118 this.applyIrcEvents();
120 util
.inherits(IrcConnection
, EE
);
122 module
.exports
.IrcConnection
= IrcConnection
;
126 IrcConnection
.prototype.applyIrcEvents = function () {
127 // Listen for events on the IRC connection
129 'server * connect': onServerConnect
,
130 'channel * join': onChannelJoin
,
132 // TODO: uncomment when using an IrcUser per nick
133 //'user:*:privmsg': onUserPrivmsg,
134 'user * nick': onUserNick
,
135 'channel * part': onUserParts
,
136 'channel * quit': onUserParts
,
137 'channel * kick': onUserKick
140 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
145 * Start the connection to the IRCd
147 IrcConnection
.prototype.connect = function () {
150 // The socket connect event to listener for
151 var socket_connect_event_name
= 'connect';
153 // The destination address
154 var dest_addr
= this.socks
?
156 this.irc_host
.hostname
;
158 // Make sure we don't already have an open connection
159 this.disposeSocket();
161 // Get the IP family for the dest_addr (either socks or IRCd destination)
162 getConnectionFamily(dest_addr
, function getConnectionFamilyCb(err
, family
, host
) {
165 // Decide which net. interface to make the connection through
166 if (that
.outgoing_interface
) {
167 // An specific interface has been given for this connection
168 outgoing
= this.outgoing_interface
;
170 } else if (global
.config
.outgoing_address
) {
171 // Pick an interface from the config
172 if ((family
=== 'IPv6') && (global
.config
.outgoing_address
.IPv6
)) {
173 outgoing
= global
.config
.outgoing_address
.IPv6
;
175 outgoing
= global
.config
.outgoing_address
.IPv4
|| '0.0.0.0';
177 // We don't have an IPv6 interface but dest_addr may still resolve to
178 // an IPv4 address. Reset `host` and try connecting anyway, letting it
179 // fail if an IPv4 resolved address is not found
183 // If we have an array of interfaces, select a random one
184 if (typeof outgoing
!== 'string' && outgoing
.length
) {
185 outgoing
= outgoing
[Math
.floor(Math
.random() * outgoing
.length
)];
188 // Make sure we have a valid interface address
189 if (typeof outgoing
!== 'string')
190 outgoing
= '0.0.0.0';
193 // No config was found so use the default
194 outgoing
= '0.0.0.0';
197 // Are we connecting through a SOCKS proxy?
199 that
.socket
= Socks
.connect({
201 port
: that
.irc_host
.port
,
203 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
204 }, {host
: that
.socks
.host
,
205 port
: that
.socks
.port
,
206 user
: that
.socks
.user
,
207 pass
: that
.socks
.pass
,
208 localAddress
: outgoing
212 // No socks connection, connect directly to the IRCd
215 that
.socket
= tls
.connect({
217 port
: that
.irc_host
.port
,
218 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
,
219 localAddress
: outgoing
222 // We need the raw socket connect event
223 that
.socket
.socket
.on('connect', function() { rawSocketConnect
.call(that
, this); });
225 socket_connect_event_name
= 'secureConnect';
228 that
.socket
= net
.connect({
230 port
: that
.irc_host
.port
,
231 localAddress
: outgoing
236 // Apply the socket listeners
237 that
.socket
.on(socket_connect_event_name
, function socketConnectCb() {
239 // TLS connections have the actual socket as a property
240 var is_tls
= (typeof this.socket
!== 'undefined') ?
244 // TLS sockets have already called this
246 rawSocketConnect
.call(that
, this);
248 that
.connected
= true;
250 socketConnectHandler
.call(that
);
253 that
.socket
.on('error', function socketErrorCb(event
) {
254 that
.emit('error', event
);
257 that
.socket
.on('data', function () {
258 socketOnData
.apply(that
, arguments
);
261 that
.socket
.on('close', function socketCloseCb(had_error
) {
262 that
.connected
= false;
264 // Remove this socket form the identd lookup
265 if (that
.identd_port_pair
) {
266 delete global
.clients
.port_pairs
[that
.identd_port_pair
];
271 // Close the whole socket down
272 that
.disposeSocket();
278 * Send an event to the client
280 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
281 data
.server
= this.con_num
;
282 this.state
.sendIrcCommand(event_name
, data
, callback
);
286 * Write a line of data to the IRCd
287 * @param data The line of data to be sent
288 * @param force Write the data now, ignoring any write queue
290 IrcConnection
.prototype.write = function (data
, force
) {
291 //ENCODE string to encoding of the server
292 encoded_buffer
= iconv
.encode(data
+ '\r\n', this.encoding
);
295 this.socket
.write(encoded_buffer
);
299 this.write_buffer
.push(encoded_buffer
);
301 // Only flush if we're not writing already
302 if (!this.writing_buffer
)
303 this.flushWriteBuffer();
309 * Flush the write buffer to the server in a throttled fashion
311 IrcConnection
.prototype.flushWriteBuffer = function () {
313 // In case the socket closed between writing our queue.. clean up
314 if (!this.connected
) {
315 this.write_buffer
= [];
316 this.writing_buffer
= false;
320 this.writing_buffer
= true;
322 // Disabled write buffer? Send everything we have
323 if (!this.write_buffer_lines_second
) {
324 this.write_buffer
.forEach(function(buffer
, idx
) {
325 this.socket
.write(buffer
);
326 this.write_buffer
= null;
329 this.write_buffer
= [];
330 this.writing_buffer
= false;
335 // Nothing to write? Stop writing and leave
336 if (this.write_buffer
.length
=== 0) {
337 this.writing_buffer
= false;
341 this.socket
.write(this.write_buffer
[0]);
342 this.write_buffer
= this.write_buffer
.slice(1);
344 // Call this function again at some point if we still have data to write
345 if (this.write_buffer
.length
> 0) {
346 setTimeout(this.flushWriteBuffer
.bind(this), 1000 / this.write_buffer_lines_second
);
348 // No more buffers to write.. so we've finished
349 this.writing_buffer
= false;
356 * Close the connection to the IRCd after forcing one last line
358 IrcConnection
.prototype.end = function (data
, callback
) {
363 this.write(data
, true);
371 * Clean up this IrcConnection instance and any sockets
373 IrcConnection
.prototype.dispose = function () {
374 // If we're still connected, wait until the socket is closed before disposing
375 // so that all the events are still correctly triggered
376 if (this.socket
&& this.connected
) {
382 this.disposeSocket();
385 _
.each(this.irc_users
, function (user
) {
388 _
.each(this.irc_channels
, function (chan
) {
391 this.irc_users
= undefined;
392 this.irc_channels
= undefined;
394 this.server
.dispose();
395 this.server
= undefined;
397 this.irc_commands
= undefined;
399 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
401 this.removeAllListeners();
407 * Clean up any sockets for this IrcConnection
409 IrcConnection
.prototype.disposeSocket = function () {
412 this.socket
.removeAllListeners();
418 * Set a new encoding for this connection
419 * Return true in case of success
422 IrcConnection
.prototype.setEncoding = function (encoding
) {
426 encoded_test
= iconv
.encode("TEST", encoding
);
427 //This test is done to check if this encoding also supports
428 //the ASCII charset required by the IRC protocols
429 //(Avoid the use of base64 or incompatible encodings)
430 if (encoded_test
== "TEST") {
431 this.encoding
= encoding
;
440 function getConnectionFamily(host
, callback
) {
441 if (net
.isIP(host
)) {
442 if (net
.isIPv4(host
)) {
443 callback(null, 'IPv4', host
);
445 callback(null, 'IPv6', host
);
448 dns
.resolve6(host
, function resolve6Cb(err
, addresses
) {
450 callback(null, 'IPv6', addresses
[0]);
452 dns
.resolve4(host
, function resolve4Cb(err
, addresses
) {
454 callback(null, 'IPv4',addresses
[0]);
465 function onChannelJoin(event
) {
468 // Only deal with ourselves joining a channel
469 if (event
.nick
!== this.nick
)
472 // We should only ever get a JOIN command for a channel
473 // we're not already a member of.. but check we don't
474 // have this channel in case something went wrong somewhere
475 // at an earlier point
476 if (!this.irc_channels
[event
.channel
]) {
477 chan
= new IrcChannel(this, event
.channel
);
478 this.irc_channels
[event
.channel
] = chan
;
479 chan
.irc_events
.join
.call(chan
, event
);
484 function onServerConnect(event
) {
485 this.nick
= event
.nick
;
489 function onUserPrivmsg(event
) {
492 // Only deal with messages targetted to us
493 if (event
.channel
!== this.nick
)
496 if (!this.irc_users
[event
.nick
]) {
497 user
= new IrcUser(this, event
.nick
);
498 this.irc_users
[event
.nick
] = user
;
499 user
.irc_events
.privmsg
.call(user
, event
);
504 function onUserNick(event
) {
507 // Only deal with messages targetted to us
508 if (event
.nick
!== this.nick
)
511 this.nick
= event
.newnick
;
515 function onUserParts(event
) {
516 // Only deal with ourselves leaving a channel
517 if (event
.nick
!== this.nick
)
520 if (this.irc_channels
[event
.channel
]) {
521 this.irc_channels
[event
.channel
].dispose();
522 delete this.irc_channels
[event
.channel
];
526 function onUserKick(event
){
527 // Only deal with ourselves being kicked from a channel
528 if (event
.kicked
!== this.nick
)
531 if (this.irc_channels
[event
.channel
]) {
532 this.irc_channels
[event
.channel
].dispose();
533 delete this.irc_channels
[event
.channel
];
541 * When a socket connects to an IRCd
542 * May be called before any socket handshake are complete (eg. TLS)
544 var rawSocketConnect = function(socket
) {
545 // Make note of the port numbers for any identd lookups
546 // Nodejs < 0.9.6 has no socket.localPort so check this first
547 if (typeof socket
.localPort
!= 'undefined') {
548 this.identd_port_pair
= socket
.localPort
.toString() + '_' + socket
.remotePort
.toString();
549 global
.clients
.port_pairs
[this.identd_port_pair
] = this;
555 * Handle the socket connect event, starting the IRCd registration
557 var socketConnectHandler = function () {
561 // Build up data to be used for webirc/etc detection
565 // Array of lines to be sent to the IRCd before anything else
569 // Let the webirc/etc detection modify any required parameters
570 connect_data
= findWebIrc
.call(this, connect_data
);
572 global
.modules
.emit('irc authorize', connect_data
).done(function ircAuthorizeCb() {
573 var gecos
= '[www.kiwiirc.com] ' + that
.nick
;
575 if (global
.config
.default_gecos
) {
576 gecos
= global
.config
.default_gecos
.toString().replace('%n', that
.nick
);
577 gecos
= gecos
.toString().replace('%h', that
.user
.hostname
);
580 // Send any initial data for webirc/etc
581 if (connect_data
.prepend_data
) {
582 _
.each(connect_data
.prepend_data
, function(data
) {
587 that
.write('CAP LS');
590 that
.write('PASS ' + that
.password
);
592 that
.write('NICK ' + that
.nick
);
593 that
.write('USER ' + that
.username
+ ' 0 0 :' + gecos
);
595 that
.emit('connected');
602 * Load any WEBIRC or alternative settings for this connection
603 * Called in scope of the IrcConnection instance
605 function findWebIrc(connect_data
) {
606 var webirc_pass
= global
.config
.webirc_pass
,
607 ip_as_username
= global
.config
.ip_as_username
,
611 // Do we have a WEBIRC password for this?
612 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
613 // Build the WEBIRC line to be sent before IRC registration
614 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
615 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
617 connect_data
.prepend_data
= [tmp
];
621 // Check if we need to pass the users IP as its username/ident
622 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
623 // Get a hex value of the clients IP
624 this.username
= this.user
.address
.split('.').map(function ipSplitMapCb(i
, idx
){
625 var hex
= parseInt(i
, 10).toString(16);
627 // Pad out the hex value if it's a single char
628 if (hex
.length
=== 1)
641 * Buffer any data we get from the IRCd until we have complete lines.
643 function socketOnData(data
) {
644 var data_pos
, // Current position within the data Buffer
648 max_buffer_size
= 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
649 // May need tweaking when IRCv3 message tags are more widespread
651 // Split data chunk into individual lines
652 for (data_pos
= 0; data_pos
< data
.length
; data_pos
++) {
653 if (data
[data_pos
] === 0x0A) { // Check if byte is a line feed
654 lines
.push(data
.slice(line_start
, data_pos
));
655 line_start
= data_pos
+ 1;
659 // No complete lines of data? Check to see if buffering the data would exceed the max buffer size
661 if ((this.held_data
? this.held_data
.length
: 0 ) + data
.length
> max_buffer_size
) {
662 // Buffering this data would exeed our max buffer size
663 this.emit('error', 'Message buffer too large');
664 this.socket
.destroy();
668 // Append the incomplete line to our held_data and wait for more
669 if (this.held_data
) {
670 this.held_data
= Buffer
.concat([this.held_data
, data
], this.held_data
.length
+ data
.length
);
672 this.held_data
= data
;
676 // No complete lines to process..
680 // If we have an incomplete line held from the previous chunk of data
681 // merge it with the first line from this chunk of data
682 if (this.hold_last
&& this.held_data
!== null) {
683 lines
[0] = Buffer
.concat([this.held_data
, lines
[0]], this.held_data
.length
+ lines
[0].length
);
684 this.hold_last
= false;
685 this.held_data
= null;
688 // If the last line of data in this chunk is not complete, hold it so
689 // it can be merged with the first line from the next chunk
690 if (line_start
< data_pos
) {
691 if ((data
.length
- line_start
) > max_buffer_size
) {
692 // Buffering this data would exeed our max buffer size
693 this.emit('error', 'Message buffer too large');
694 this.socket
.destroy();
698 this.hold_last
= true;
699 this.held_data
= new Buffer(data
.length
- line_start
);
700 data
.copy(this.held_data
, 0, line_start
);
703 // Process our data line by line
704 for (i
= 0; i
< lines
.length
; i
++)
705 parseIrcLine
.call(this, lines
[i
]);
712 * The regex that parses a line of data from the IRCd
713 * Deviates from the RFC a little to support the '/' character now used in some
716 var parse_regex
= /^(?:(?:(?:@([^ ]+) )?):(?:([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)|([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)!([^\x00\r\n\ ]+?)@?([a-z0-9\.\-:\/_]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.+))?$/i;
718 function parseIrcLine(buffer_line
) {
725 // Decode server encoding
726 line
= iconv
.decode(buffer_line
, this.encoding
);
729 // Parse the complete line, removing any carriage returns
730 msg
= parse_regex
.exec(line
.replace(/^\r+|\r+$/, ''));
733 // The line was not parsed correctly, must be malformed
734 console
.log("Malformed IRC line: " + line
.replace(/^\r+|\r+$/, ''));
738 // Extract any tags (msg[1])
740 tags
= msg
[1].split(';');
742 for (j
= 0; j
< tags
.length
; j
++) {
743 tag
= tags
[j
].split('=');
744 tags
[j
] = {tag
: tag
[0], value
: tag
[1]};
753 hostname
: msg
[5] || '',
755 params
: msg
[7] || '',
756 trailing
: (msg
[8]) ? msg
[8].trim() : ''
759 msg
.params
= msg
.params
.split(/ +/);
760 this.irc_commands
.dispatch(msg
.command
.toUpperCase(), msg
);