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'),
13 Proxy
= require('../proxy.js'),
17 // Break the Node.js version down into usable parts
18 var version_values
= process
.version
.substr(1).split('.').map(function (item
) {
19 return parseInt(item
, 10);
22 // If we have a suitable Nodejs version, bring int he socks functionality
23 if (version_values
[1] >= 10) {
24 Socks
= require('socksjs');
27 var IrcConnection = function (hostname
, port
, ssl
, nick
, user
, options
, state
, con_num
) {
34 this.setMaxListeners(0);
36 options
= options
|| {};
39 this.connected
= false;
41 // IRCd write buffers (flood controll)
42 this.write_buffer
= [];
44 // In process of writing the buffer?
45 this.writing_buffer
= false;
47 // Max number of lines to write a second
48 this.write_buffer_lines_second
= 2;
50 // If registeration with the IRCd has completed
51 this.registered
= false;
53 // If we are in the CAP negotiation stage
54 this.cap_negotiation
= true;
58 this.user
= user
; // Contains users real hostname and address
59 this.username
= this.nick
.replace(/[^0-9a-zA-Z\-_.\/]/, '');
60 this.password
= options
.password
|| '';
62 // Set the passed encoding. or the default if none giving or it fails
63 if (!options
.encoding
|| !this.setEncoding(options
.encoding
)) {
64 this.setEncoding(global
.config
.default_encoding
);
70 // Connection ID in the state
71 this.con_num
= con_num
;
73 // IRC protocol handling
74 this.irc_commands
= new IrcCommands(this);
77 this.server
= new IrcServer(this, hostname
, port
);
80 this.irc_users
= Object
.create(null);
82 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
83 this.irc_users
[this.nick
] = new IrcUser(this, '*');
86 this.irc_channels
= Object
.create(null);
88 // IRC connection information
89 this.irc_host
= {hostname
: hostname
, port
: port
};
92 // SOCKS proxy details
93 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
94 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
)))) {
96 host
: global
.config
.socks_proxy
.address
,
97 port
: global
.config
.socks_proxy
.port
,
98 user
: global
.config
.socks_proxy
.user
,
99 pass
: global
.config
.socks_proxy
.pass
105 // Kiwi proxy info may be set within a server module. {port: 7779, host: 'kiwi.proxy.com', ssl: false}
108 // Net. interface this connection should be made through
109 this.outgoing_interface
= false;
111 // Options sent by the IRCd
112 this.options
= Object
.create(null);
113 this.cap
= {requested
: [], enabled
: []};
115 // Is SASL supported on the IRCd
118 // Buffers for data sent from the IRCd
119 this.hold_last
= false;
120 this.held_data
= null;
122 this.applyIrcEvents();
124 util
.inherits(IrcConnection
, EE
);
126 module
.exports
.IrcConnection
= IrcConnection
;
130 IrcConnection
.prototype.applyIrcEvents = function () {
131 // Listen for events on the IRC connection
133 'server * connect': onServerConnect
,
134 'channel * join': onChannelJoin
,
136 // TODO: uncomment when using an IrcUser per nick
137 //'user:*:privmsg': onUserPrivmsg,
138 'user * nick': onUserNick
,
139 'channel * part': onUserParts
,
140 'channel * quit': onUserParts
,
141 'channel * kick': onUserKick
144 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
149 * Start the connection to the IRCd
151 IrcConnection
.prototype.connect = function () {
154 // The socket connect event to listener for
155 var socket_connect_event_name
= 'connect';
157 // The destination address
160 dest_addr
= this.socks
.host
;
161 } else if (this.proxy
) {
162 dest_addr
= this.proxy
.host
;
164 dest_addr
= this.irc_host
.hostname
;
167 // Make sure we don't already have an open connection
168 this.disposeSocket();
170 // Get the IP family for the dest_addr (either socks or IRCd destination)
171 getConnectionFamily(dest_addr
, function getConnectionFamilyCb(err
, family
, host
) {
174 // Decide which net. interface to make the connection through
175 if (that
.outgoing_interface
) {
176 // An specific interface has been given for this connection
177 outgoing
= this.outgoing_interface
;
179 } else if (global
.config
.outgoing_address
) {
180 // Pick an interface from the config
181 if ((family
=== 'IPv6') && (global
.config
.outgoing_address
.IPv6
)) {
182 outgoing
= global
.config
.outgoing_address
.IPv6
;
184 outgoing
= global
.config
.outgoing_address
.IPv4
|| '0.0.0.0';
186 // We don't have an IPv6 interface but dest_addr may still resolve to
187 // an IPv4 address. Reset `host` and try connecting anyway, letting it
188 // fail if an IPv4 resolved address is not found
192 // If we have an array of interfaces, select a random one
193 if (typeof outgoing
!== 'string' && outgoing
.length
) {
194 outgoing
= outgoing
[Math
.floor(Math
.random() * outgoing
.length
)];
197 // Make sure we have a valid interface address
198 if (typeof outgoing
!== 'string')
199 outgoing
= '0.0.0.0';
202 // No config was found so use the default
203 outgoing
= '0.0.0.0';
206 // Are we connecting through a SOCKS proxy?
208 that
.socket
= Socks
.connect({
209 host
: that
.irc_host
.host
,
210 port
: that
.irc_host
.port
,
212 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
214 port
: that
.socks
.port
,
215 user
: that
.socks
.user
,
216 pass
: that
.socks
.pass
,
217 localAddress
: outgoing
220 } else if (that
.proxy
) {
221 that
.socket
= new Proxy
.ProxySocket(that
.proxy
.port
, host
, {
222 username
: that
.username
,
223 interface: that
.proxy
.interface
224 }, {ssl
: that
.proxy
.ssl
});
227 that
.socket
.connectTls(that
.irc_host
.port
, that
.irc_host
.hostname
);
229 that
.socket
.connect(that
.irc_host
.port
, that
.irc_host
.hostname
);
233 // No socks connection, connect directly to the IRCd
236 that
.socket
= tls
.connect({
238 port
: that
.irc_host
.port
,
239 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
,
240 localAddress
: outgoing
243 // We need the raw socket connect event
244 that
.socket
.socket
.on('connect', function() { rawSocketConnect
.call(that
, this); });
246 socket_connect_event_name
= 'secureConnect';
249 that
.socket
= net
.connect({
251 port
: that
.irc_host
.port
,
252 localAddress
: outgoing
257 // Apply the socket listeners
258 that
.socket
.on(socket_connect_event_name
, function socketConnectCb() {
260 // TLS connections have the actual socket as a property
261 var is_tls
= (typeof this.socket
!== 'undefined') ?
265 // TLS sockets have already called this
267 rawSocketConnect
.call(that
, this);
269 that
.connected
= true;
271 socketConnectHandler
.call(that
);
274 that
.socket
.on('error', function socketErrorCb(event
) {
275 that
.emit('error', event
);
278 that
.socket
.on('data', function () {
279 socketOnData
.apply(that
, arguments
);
282 that
.socket
.on('close', function socketCloseCb(had_error
) {
283 that
.connected
= false;
285 // Remove this socket form the identd lookup
286 if (that
.identd_port_pair
) {
287 delete global
.clients
.port_pairs
[that
.identd_port_pair
];
292 // Close the whole socket down
293 that
.disposeSocket();
299 * Send an event to the client
301 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
302 data
.server
= this.con_num
;
303 this.state
.sendIrcCommand(event_name
, data
, callback
);
307 * Write a line of data to the IRCd
308 * @param data The line of data to be sent
309 * @param force Write the data now, ignoring any write queue
311 IrcConnection
.prototype.write = function (data
, force
) {
312 //ENCODE string to encoding of the server
313 encoded_buffer
= iconv
.encode(data
+ '\r\n', this.encoding
);
316 this.socket
.write(encoded_buffer
);
320 this.write_buffer
.push(encoded_buffer
);
322 // Only flush if we're not writing already
323 if (!this.writing_buffer
)
324 this.flushWriteBuffer();
330 * Flush the write buffer to the server in a throttled fashion
332 IrcConnection
.prototype.flushWriteBuffer = function () {
334 // In case the socket closed between writing our queue.. clean up
335 if (!this.connected
) {
336 this.write_buffer
= [];
337 this.writing_buffer
= false;
341 this.writing_buffer
= true;
343 // Disabled write buffer? Send everything we have
344 if (!this.write_buffer_lines_second
) {
345 this.write_buffer
.forEach(function(buffer
, idx
) {
346 this.socket
.write(buffer
);
347 this.write_buffer
= null;
350 this.write_buffer
= [];
351 this.writing_buffer
= false;
356 // Nothing to write? Stop writing and leave
357 if (this.write_buffer
.length
=== 0) {
358 this.writing_buffer
= false;
362 this.socket
.write(this.write_buffer
[0]);
363 this.write_buffer
= this.write_buffer
.slice(1);
365 // Call this function again at some point if we still have data to write
366 if (this.write_buffer
.length
> 0) {
367 setTimeout(this.flushWriteBuffer
.bind(this), 1000 / this.write_buffer_lines_second
);
369 // No more buffers to write.. so we've finished
370 this.writing_buffer
= false;
377 * Close the connection to the IRCd after forcing one last line
379 IrcConnection
.prototype.end = function (data
, callback
) {
384 this.write(data
, true);
392 * Clean up this IrcConnection instance and any sockets
394 IrcConnection
.prototype.dispose = function () {
395 // If we're still connected, wait until the socket is closed before disposing
396 // so that all the events are still correctly triggered
397 if (this.socket
&& this.connected
) {
403 this.disposeSocket();
406 _
.each(this.irc_users
, function (user
) {
409 _
.each(this.irc_channels
, function (chan
) {
412 this.irc_users
= undefined;
413 this.irc_channels
= undefined;
415 this.server
.dispose();
416 this.server
= undefined;
418 this.irc_commands
= undefined;
420 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
422 this.removeAllListeners();
428 * Clean up any sockets for this IrcConnection
430 IrcConnection
.prototype.disposeSocket = function () {
433 this.socket
.removeAllListeners();
439 * Set a new encoding for this connection
440 * Return true in case of success
443 IrcConnection
.prototype.setEncoding = function (encoding
) {
447 encoded_test
= iconv
.encode("TEST", encoding
);
448 //This test is done to check if this encoding also supports
449 //the ASCII charset required by the IRC protocols
450 //(Avoid the use of base64 or incompatible encodings)
451 if (encoded_test
== "TEST") {
452 this.encoding
= encoding
;
461 function getConnectionFamily(host
, callback
) {
462 if (net
.isIP(host
)) {
463 if (net
.isIPv4(host
)) {
464 callback(null, 'IPv4', host
);
466 callback(null, 'IPv6', host
);
469 dns
.resolve6(host
, function resolve6Cb(err
, addresses
) {
471 callback(null, 'IPv6', addresses
[0]);
473 dns
.resolve4(host
, function resolve4Cb(err
, addresses
) {
475 callback(null, 'IPv4',addresses
[0]);
486 function onChannelJoin(event
) {
489 // Only deal with ourselves joining a channel
490 if (event
.nick
!== this.nick
)
493 // We should only ever get a JOIN command for a channel
494 // we're not already a member of.. but check we don't
495 // have this channel in case something went wrong somewhere
496 // at an earlier point
497 if (!this.irc_channels
[event
.channel
]) {
498 chan
= new IrcChannel(this, event
.channel
);
499 this.irc_channels
[event
.channel
] = chan
;
500 chan
.irc_events
.join
.call(chan
, event
);
505 function onServerConnect(event
) {
506 this.nick
= event
.nick
;
510 function onUserPrivmsg(event
) {
513 // Only deal with messages targetted to us
514 if (event
.channel
!== this.nick
)
517 if (!this.irc_users
[event
.nick
]) {
518 user
= new IrcUser(this, event
.nick
);
519 this.irc_users
[event
.nick
] = user
;
520 user
.irc_events
.privmsg
.call(user
, event
);
525 function onUserNick(event
) {
528 // Only deal with messages targetted to us
529 if (event
.nick
!== this.nick
)
532 this.nick
= event
.newnick
;
536 function onUserParts(event
) {
537 // Only deal with ourselves leaving a channel
538 if (event
.nick
!== this.nick
)
541 if (this.irc_channels
[event
.channel
]) {
542 this.irc_channels
[event
.channel
].dispose();
543 delete this.irc_channels
[event
.channel
];
547 function onUserKick(event
){
548 // Only deal with ourselves being kicked from a channel
549 if (event
.kicked
!== this.nick
)
552 if (this.irc_channels
[event
.channel
]) {
553 this.irc_channels
[event
.channel
].dispose();
554 delete this.irc_channels
[event
.channel
];
562 * When a socket connects to an IRCd
563 * May be called before any socket handshake are complete (eg. TLS)
565 var rawSocketConnect = function(socket
) {
566 // Make note of the port numbers for any identd lookups
567 // Nodejs < 0.9.6 has no socket.localPort so check this first
568 if (typeof socket
.localPort
!= 'undefined') {
569 this.identd_port_pair
= socket
.localPort
.toString() + '_' + socket
.remotePort
.toString();
570 global
.clients
.port_pairs
[this.identd_port_pair
] = this;
576 * Handle the socket connect event, starting the IRCd registration
578 var socketConnectHandler = function () {
582 // Build up data to be used for webirc/etc detection
586 // Array of lines to be sent to the IRCd before anything else
590 // Let the webirc/etc detection modify any required parameters
591 connect_data
= findWebIrc
.call(this, connect_data
);
593 global
.modules
.emit('irc authorize', connect_data
).done(function ircAuthorizeCb() {
594 var gecos
= '[www.kiwiirc.com] ' + that
.nick
;
596 if (global
.config
.default_gecos
) {
597 gecos
= global
.config
.default_gecos
.toString().replace('%n', that
.nick
);
598 gecos
= gecos
.toString().replace('%h', that
.user
.hostname
);
601 // Send any initial data for webirc/etc
602 if (connect_data
.prepend_data
) {
603 _
.each(connect_data
.prepend_data
, function(data
) {
608 that
.write('CAP LS');
611 that
.write('PASS ' + that
.password
);
613 that
.write('NICK ' + that
.nick
);
614 that
.write('USER ' + that
.username
+ ' 0 0 :' + gecos
);
616 that
.emit('connected');
623 * Load any WEBIRC or alternative settings for this connection
624 * Called in scope of the IrcConnection instance
626 function findWebIrc(connect_data
) {
627 var webirc_pass
= global
.config
.webirc_pass
,
628 ip_as_username
= global
.config
.ip_as_username
,
632 // Do we have a WEBIRC password for this?
633 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
634 // Build the WEBIRC line to be sent before IRC registration
635 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
636 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
638 connect_data
.prepend_data
= [tmp
];
642 // Check if we need to pass the users IP as its username/ident
643 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
644 // Get a hex value of the clients IP
645 this.username
= this.user
.address
.split('.').map(function ipSplitMapCb(i
, idx
){
646 var hex
= parseInt(i
, 10).toString(16);
648 // Pad out the hex value if it's a single char
649 if (hex
.length
=== 1)
662 * Buffer any data we get from the IRCd until we have complete lines.
664 function socketOnData(data
) {
665 var data_pos
, // Current position within the data Buffer
669 max_buffer_size
= 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
670 // May need tweaking when IRCv3 message tags are more widespread
672 // Split data chunk into individual lines
673 for (data_pos
= 0; data_pos
< data
.length
; data_pos
++) {
674 if (data
[data_pos
] === 0x0A) { // Check if byte is a line feed
675 lines
.push(data
.slice(line_start
, data_pos
));
676 line_start
= data_pos
+ 1;
680 // No complete lines of data? Check to see if buffering the data would exceed the max buffer size
682 if ((this.held_data
? this.held_data
.length
: 0 ) + data
.length
> max_buffer_size
) {
683 // Buffering this data would exeed our max buffer size
684 this.emit('error', 'Message buffer too large');
685 this.socket
.destroy();
689 // Append the incomplete line to our held_data and wait for more
690 if (this.held_data
) {
691 this.held_data
= Buffer
.concat([this.held_data
, data
], this.held_data
.length
+ data
.length
);
693 this.held_data
= data
;
697 // No complete lines to process..
701 // If we have an incomplete line held from the previous chunk of data
702 // merge it with the first line from this chunk of data
703 if (this.hold_last
&& this.held_data
!== null) {
704 lines
[0] = Buffer
.concat([this.held_data
, lines
[0]], this.held_data
.length
+ lines
[0].length
);
705 this.hold_last
= false;
706 this.held_data
= null;
709 // If the last line of data in this chunk is not complete, hold it so
710 // it can be merged with the first line from the next chunk
711 if (line_start
< data_pos
) {
712 if ((data
.length
- line_start
) > max_buffer_size
) {
713 // Buffering this data would exeed our max buffer size
714 this.emit('error', 'Message buffer too large');
715 this.socket
.destroy();
719 this.hold_last
= true;
720 this.held_data
= new Buffer(data
.length
- line_start
);
721 data
.copy(this.held_data
, 0, line_start
);
724 // Process our data line by line
725 for (i
= 0; i
< lines
.length
; i
++)
726 parseIrcLine
.call(this, lines
[i
]);
733 * The regex that parses a line of data from the IRCd
734 * Deviates from the RFC a little to support the '/' character now used in some
737 var parse_regex
= /^(?:(?:(?:@([^ ]+) )?):(?:([^\s!]+)|([^\s!]+)!([^\s@]+)@?([^\s]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.*))?$/i;
739 function parseIrcLine(buffer_line
) {
747 // Decode server encoding
748 line
= iconv
.decode(buffer_line
, this.encoding
);
753 // Parse the complete line, removing any carriage returns
754 msg
= parse_regex
.exec(line
.replace(/^\r+|\r+$/, ''));
757 // The line was not parsed correctly, must be malformed
758 console
.log("Malformed IRC line: " + line
.replace(/^\r+|\r+$/, ''));
762 // Extract any tags (msg[1])
764 tags
= msg
[1].split(';');
766 for (i
= 0; i
< tags
.length
; i
++) {
767 tag
= tags
[i
].split('=');
768 tags
[i
] = {tag
: tag
[0], value
: tag
[1]};
777 hostname
: msg
[5] || '',
779 params
: msg
[7] ? msg
[7].split(/ +/) : []
783 msg_obj
.params
.push(msg
[8].trim());
786 this.irc_commands
.dispatch(msg_obj
.command
.toUpperCase(), msg_obj
);