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 // Options sent by the IRCd
105 this.options
= Object
.create(null);
106 this.cap
= {requested
: [], enabled
: []};
108 // Is SASL supported on the IRCd
111 // Buffers for data sent from the IRCd
112 this.hold_last
= false;
113 this.held_data
= null;
115 this.applyIrcEvents();
117 util
.inherits(IrcConnection
, EE
);
119 module
.exports
.IrcConnection
= IrcConnection
;
123 IrcConnection
.prototype.applyIrcEvents = function () {
124 // Listen for events on the IRC connection
126 'server * connect': onServerConnect
,
127 'channel * join': onChannelJoin
,
129 // TODO: uncomment when using an IrcUser per nick
130 //'user:*:privmsg': onUserPrivmsg,
131 'user * nick': onUserNick
,
132 'channel * part': onUserParts
,
133 'channel * quit': onUserParts
,
134 'channel * kick': onUserKick
137 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
142 * Start the connection to the IRCd
144 IrcConnection
.prototype.connect = function () {
147 // The socket connect event to listener for
148 var socket_connect_event_name
= 'connect';
150 // The destination address
151 var dest_addr
= this.socks
?
153 this.irc_host
.hostname
;
155 // Make sure we don't already have an open connection
156 this.disposeSocket();
158 // Get the IP family for the dest_addr (either socks or IRCd destination)
159 getConnectionFamily(dest_addr
, function getConnectionFamilyCb(err
, family
, host
) {
162 // Decide which net. interface to make the connection through
163 if (global
.config
.outgoing_address
) {
164 if ((family
=== 'IPv6') && (global
.config
.outgoing_address
.IPv6
)) {
165 outgoing
= global
.config
.outgoing_address
.IPv6
;
167 outgoing
= global
.config
.outgoing_address
.IPv4
|| '0.0.0.0';
169 // We don't have an IPv6 interface but dest_addr may still resolve to
170 // an IPv4 address. Reset `host` and try connecting anyway, letting it
171 // fail if an IPv4 resolved address is not found
175 // If we have an array of interfaces, select a random one
176 if (typeof outgoing
!== 'string' && outgoing
.length
) {
177 outgoing
= outgoing
[Math
.floor(Math
.random() * outgoing
.length
)];
180 // Make sure we have a valid interface address
181 if (typeof outgoing
!== 'string')
182 outgoing
= '0.0.0.0';
185 // No config was found so use the default
186 outgoing
= '0.0.0.0';
189 // Are we connecting through a SOCKS proxy?
191 that
.socket
= Socks
.connect({
193 port
: that
.irc_host
.port
,
195 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
196 }, {host
: that
.socks
.host
,
197 port
: that
.socks
.port
,
198 user
: that
.socks
.user
,
199 pass
: that
.socks
.pass
,
200 localAddress
: outgoing
204 // No socks connection, connect directly to the IRCd
207 that
.socket
= tls
.connect({
209 port
: that
.irc_host
.port
,
210 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
,
211 localAddress
: outgoing
214 // We need the raw socket connect event
215 that
.socket
.socket
.on('connect', function() { rawSocketConnect
.call(that
, this); });
217 socket_connect_event_name
= 'secureConnect';
220 that
.socket
= net
.connect({
222 port
: that
.irc_host
.port
,
223 localAddress
: outgoing
228 // Apply the socket listeners
229 that
.socket
.on(socket_connect_event_name
, function socketConnectCb() {
231 // TLS connections have the actual socket as a property
232 var is_tls
= (typeof this.socket
!== 'undefined') ?
236 // TLS sockets have already called this
238 rawSocketConnect
.call(that
, this);
240 that
.connected
= true;
242 socketConnectHandler
.call(that
);
245 that
.socket
.on('error', function socketErrorCb(event
) {
246 that
.emit('error', event
);
249 that
.socket
.on('data', function () {
250 socketOnData
.apply(that
, arguments
);
253 that
.socket
.on('close', function socketCloseCb(had_error
) {
254 that
.connected
= false;
256 // Remove this socket form the identd lookup
257 if (that
.identd_port_pair
) {
258 delete global
.clients
.port_pairs
[that
.identd_port_pair
];
263 // Close the whole socket down
264 that
.disposeSocket();
270 * Send an event to the client
272 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
273 data
.server
= this.con_num
;
274 this.state
.sendIrcCommand(event_name
, data
, callback
);
278 * Write a line of data to the IRCd
279 * @param data The line of data to be sent
280 * @param force Write the data now, ignoring any write queue
282 IrcConnection
.prototype.write = function (data
, force
) {
283 //ENCODE string to encoding of the server
284 encoded_buffer
= iconv
.encode(data
+ '\r\n', this.encoding
);
287 this.socket
.write(encoded_buffer
);
291 this.write_buffer
.push(encoded_buffer
);
293 // Only flush if we're not writing already
294 if (!this.writing_buffer
)
295 this.flushWriteBuffer();
301 * Flush the write buffer to the server in a throttled fashion
303 IrcConnection
.prototype.flushWriteBuffer = function () {
305 // In case the socket closed between writing our queue.. clean up
306 if (!this.connected
) {
307 this.write_buffer
= [];
308 this.writing_buffer
= false;
312 this.writing_buffer
= true;
314 // Disabled write buffer? Send everything we have
315 if (!this.write_buffer_lines_second
) {
316 this.write_buffer
.forEach(function(buffer
, idx
) {
317 this.socket
.write(buffer
);
318 this.write_buffer
= null;
321 this.write_buffer
= [];
322 this.writing_buffer
= false;
327 // Nothing to write? Stop writing and leave
328 if (this.write_buffer
.length
=== 0) {
329 this.writing_buffer
= false;
333 this.socket
.write(this.write_buffer
[0]);
334 this.write_buffer
= this.write_buffer
.slice(1);
336 // Call this function again at some point if we still have data to write
337 if (this.write_buffer
.length
> 0) {
338 setTimeout(this.flushWriteBuffer
.bind(this), 1000 / this.write_buffer_lines_second
);
340 // No more buffers to write.. so we've finished
341 this.writing_buffer
= false;
348 * Close the connection to the IRCd after forcing one last line
350 IrcConnection
.prototype.end = function (data
, callback
) {
355 this.write(data
, true);
363 * Clean up this IrcConnection instance and any sockets
365 IrcConnection
.prototype.dispose = function () {
366 // If we're still connected, wait until the socket is closed before disposing
367 // so that all the events are still correctly triggered
368 if (this.socket
&& this.connected
) {
374 this.disposeSocket();
377 _
.each(this.irc_users
, function (user
) {
380 _
.each(this.irc_channels
, function (chan
) {
383 this.irc_users
= undefined;
384 this.irc_channels
= undefined;
386 this.server
.dispose();
387 this.server
= undefined;
389 this.irc_commands
= undefined;
391 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
393 this.removeAllListeners();
399 * Clean up any sockets for this IrcConnection
401 IrcConnection
.prototype.disposeSocket = function () {
404 this.socket
.removeAllListeners();
410 * Set a new encoding for this connection
411 * Return true in case of success
414 IrcConnection
.prototype.setEncoding = function (encoding
) {
418 encoded_test
= iconv
.encode("TEST", encoding
);
419 //This test is done to check if this encoding also supports
420 //the ASCII charset required by the IRC protocols
421 //(Avoid the use of base64 or incompatible encodings)
422 if (encoded_test
== "TEST") {
423 this.encoding
= encoding
;
432 function getConnectionFamily(host
, callback
) {
433 if (net
.isIP(host
)) {
434 if (net
.isIPv4(host
)) {
435 callback(null, 'IPv4', host
);
437 callback(null, 'IPv6', host
);
440 dns
.resolve6(host
, function resolve6Cb(err
, addresses
) {
442 callback(null, 'IPv6', addresses
[0]);
444 dns
.resolve4(host
, function resolve4Cb(err
, addresses
) {
446 callback(null, 'IPv4',addresses
[0]);
457 function onChannelJoin(event
) {
460 // Only deal with ourselves joining a channel
461 if (event
.nick
!== this.nick
)
464 // We should only ever get a JOIN command for a channel
465 // we're not already a member of.. but check we don't
466 // have this channel in case something went wrong somewhere
467 // at an earlier point
468 if (!this.irc_channels
[event
.channel
]) {
469 chan
= new IrcChannel(this, event
.channel
);
470 this.irc_channels
[event
.channel
] = chan
;
471 chan
.irc_events
.join
.call(chan
, event
);
476 function onServerConnect(event
) {
477 this.nick
= event
.nick
;
481 function onUserPrivmsg(event
) {
484 // Only deal with messages targetted to us
485 if (event
.channel
!== this.nick
)
488 if (!this.irc_users
[event
.nick
]) {
489 user
= new IrcUser(this, event
.nick
);
490 this.irc_users
[event
.nick
] = user
;
491 user
.irc_events
.privmsg
.call(user
, event
);
496 function onUserNick(event
) {
499 // Only deal with messages targetted to us
500 if (event
.nick
!== this.nick
)
503 this.nick
= event
.newnick
;
507 function onUserParts(event
) {
508 // Only deal with ourselves leaving a channel
509 if (event
.nick
!== this.nick
)
512 if (this.irc_channels
[event
.channel
]) {
513 this.irc_channels
[event
.channel
].dispose();
514 delete this.irc_channels
[event
.channel
];
518 function onUserKick(event
){
519 // Only deal with ourselves being kicked from a channel
520 if (event
.kicked
!== this.nick
)
523 if (this.irc_channels
[event
.channel
]) {
524 this.irc_channels
[event
.channel
].dispose();
525 delete this.irc_channels
[event
.channel
];
533 * When a socket connects to an IRCd
534 * May be called before any socket handshake are complete (eg. TLS)
536 var rawSocketConnect = function(socket
) {
537 // Make note of the port numbers for any identd lookups
538 // Nodejs < 0.9.6 has no socket.localPort so check this first
539 if (typeof socket
.localPort
!= 'undefined') {
540 this.identd_port_pair
= socket
.localPort
.toString() + '_' + socket
.remotePort
.toString();
541 global
.clients
.port_pairs
[this.identd_port_pair
] = this;
547 * Handle the socket connect event, starting the IRCd registration
549 var socketConnectHandler = function () {
553 // Build up data to be used for webirc/etc detection
557 // Array of lines to be sent to the IRCd before anything else
561 // Let the webirc/etc detection modify any required parameters
562 connect_data
= findWebIrc
.call(this, connect_data
);
564 global
.modules
.emit('irc authorize', connect_data
).done(function ircAuthorizeCb() {
565 // Send any initial data for webirc/etc
566 if (connect_data
.prepend_data
) {
567 _
.each(connect_data
.prepend_data
, function(data
) {
572 that
.write('CAP LS');
575 that
.write('PASS ' + that
.password
);
577 that
.write('NICK ' + that
.nick
);
578 that
.write('USER ' + that
.username
+ ' 0 0 :' + '[www.kiwiirc.com] ' + that
.nick
);
580 that
.emit('connected');
587 * Load any WEBIRC or alternative settings for this connection
588 * Called in scope of the IrcConnection instance
590 function findWebIrc(connect_data
) {
591 var webirc_pass
= global
.config
.webirc_pass
,
592 ip_as_username
= global
.config
.ip_as_username
,
596 // Do we have a WEBIRC password for this?
597 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
598 // Build the WEBIRC line to be sent before IRC registration
599 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
600 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
602 connect_data
.prepend_data
= [tmp
];
606 // Check if we need to pass the users IP as its username/ident
607 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
608 // Get a hex value of the clients IP
609 this.username
= this.user
.address
.split('.').map(function ipSplitMapCb(i
, idx
){
610 var hex
= parseInt(i
, 10).toString(16);
612 // Pad out the hex value if it's a single char
613 if (hex
.length
=== 1)
626 * Buffer any data we get from the IRCd until we have complete lines.
628 function socketOnData(data
) {
629 var data_pos
, // Current position within the data Buffer
633 max_buffer_size
= 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
634 // May need tweaking when IRCv3 message tags are more widespread
636 // Split data chunk into individual lines
637 for (data_pos
= 0; data_pos
< data
.length
; data_pos
++) {
638 if (data
[data_pos
] === 0x0A) { // Check if byte is a line feed
639 lines
.push(data
.slice(line_start
, data_pos
));
640 line_start
= data_pos
+ 1;
644 // No complete lines of data? Check to see if buffering the data would exceed the max buffer size
646 if ((this.held_data
? this.held_data
.length
: 0 ) + data
.length
> max_buffer_size
) {
647 // Buffering this data would exeed our max buffer size
648 this.emit('error', 'Message buffer too large');
649 this.socket
.destroy();
653 // Append the incomplete line to our held_data and wait for more
654 if (this.held_data
) {
655 this.held_data
= Buffer
.concat([this.held_data
, data
], this.held_data
.length
+ data
.length
);
657 this.held_data
= data
;
661 // No complete lines to process..
665 // If we have an incomplete line held from the previous chunk of data
666 // merge it with the first line from this chunk of data
667 if (this.hold_last
&& this.held_data
!== null) {
668 lines
[0] = Buffer
.concat([this.held_data
, lines
[0]], this.held_data
.length
+ lines
[0].length
);
669 this.hold_last
= false;
670 this.held_data
= null;
673 // If the last line of data in this chunk is not complete, hold it so
674 // it can be merged with the first line from the next chunk
675 if (line_start
< data_pos
) {
676 if ((data
.length
- line_start
) > max_buffer_size
) {
677 // Buffering this data would exeed our max buffer size
678 this.emit('error', 'Message buffer too large');
679 this.socket
.destroy();
683 this.hold_last
= true;
684 this.held_data
= new Buffer(data
.length
- line_start
);
685 data
.copy(this.held_data
, 0, line_start
);
688 // Process our data line by line
689 for (i
= 0; i
< lines
.length
; i
++)
690 parseIrcLine
.call(this, lines
[i
]);
697 * The regex that parses a line of data from the IRCd
698 * Deviates from the RFC a little to support the '/' character now used in some
701 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;
703 function parseIrcLine(buffer_line
) {
710 // Decode server encoding
711 line
= iconv
.decode(buffer_line
, this.encoding
);
714 // Parse the complete line, removing any carriage returns
715 msg
= parse_regex
.exec(line
.replace(/^\r+|\r+$/, ''));
718 // The line was not parsed correctly, must be malformed
719 console
.log("Malformed IRC line: " + line
.replace(/^\r+|\r+$/, ''));
723 // Extract any tags (msg[1])
725 tags
= msg
[1].split(';');
727 for (j
= 0; j
< tags
.length
; j
++) {
728 tag
= tags
[j
].split('=');
729 tags
[j
] = {tag
: tag
[0], value
: tag
[1]};
738 hostname
: msg
[5] || '',
740 params
: msg
[7] || '',
741 trailing
: (msg
[8]) ? msg
[8].trim() : ''
744 msg
.params
= msg
.params
.split(' ');
745 this.irc_commands
.dispatch(msg
.command
.toUpperCase(), msg
);