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
, pass
, state
, con_num
) {
33 this.setMaxListeners(0);
35 // Set the first configured encoding as the default encoding
36 this.encoding
= global
.config
.default_encoding
;
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\-_.\/]/, '');
65 // Connection ID in the state
66 this.con_num
= con_num
;
68 // IRC protocol handling
69 this.irc_commands
= new IrcCommands(this);
72 this.server
= new IrcServer(this, hostname
, port
);
75 this.irc_users
= Object
.create(null);
77 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
78 this.irc_users
[this.nick
] = new IrcUser(this, '*');
81 this.irc_channels
= Object
.create(null);
83 // IRC connection information
84 this.irc_host
= {hostname
: hostname
, port
: port
};
87 // SOCKS proxy details
88 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
89 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
)))) {
91 host
: global
.config
.socks_proxy
.address
,
92 port
: global
.config
.socks_proxy
.port
,
93 user
: global
.config
.socks_proxy
.user
,
94 pass
: global
.config
.socks_proxy
.pass
100 // Options sent by the IRCd
101 this.options
= Object
.create(null);
102 this.cap
= {requested
: [], enabled
: []};
104 // Is SASL supported on the IRCd
107 // Buffers for data sent from the IRCd
108 this.hold_last
= false;
111 this.applyIrcEvents();
113 util
.inherits(IrcConnection
, EE
);
115 module
.exports
.IrcConnection
= IrcConnection
;
119 IrcConnection
.prototype.applyIrcEvents = function () {
120 // Listen for events on the IRC connection
122 'server * connect': onServerConnect
,
123 'channel * join': onChannelJoin
,
125 // TODO: uncomment when using an IrcUser per nick
126 //'user:*:privmsg': onUserPrivmsg,
127 'user * nick': onUserNick
,
128 'channel * part': onUserParts
,
129 'channel * quit': onUserParts
,
130 'channel * kick': onUserKick
133 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
138 * Start the connection to the IRCd
140 IrcConnection
.prototype.connect = function () {
143 // The socket connect event to listener for
144 var socket_connect_event_name
= 'connect';
146 // The destination address
147 var dest_addr
= this.socks
?
149 this.irc_host
.hostname
;
151 // Make sure we don't already have an open connection
152 this.disposeSocket();
154 // Get the IP family for the dest_addr (either socks or IRCd destination)
155 getConnectionFamily(dest_addr
, function getConnectionFamilyCb(err
, family
, host
) {
158 // Decide which net. interface to make the connection through
159 if (global
.config
.outgoing_address
) {
160 if ((family
=== 'IPv6') && (global
.config
.outgoing_address
.IPv6
)) {
161 outgoing
= global
.config
.outgoing_address
.IPv6
;
163 outgoing
= global
.config
.outgoing_address
.IPv4
|| '0.0.0.0';
165 // We don't have an IPv6 interface but dest_addr may still resolve to
166 // an IPv4 address. Reset `host` and try connecting anyway, letting it
167 // fail if an IPv4 resolved address is not found
172 // No config was found so use the default
173 outgoing
= '0.0.0.0';
176 // Are we connecting through a SOCKS proxy?
178 that
.socket
= Socks
.connect({
180 port
: that
.irc_host
.port
,
182 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
183 }, {host
: that
.socks
.host
,
184 port
: that
.socks
.port
,
185 user
: that
.socks
.user
,
186 pass
: that
.socks
.pass
,
187 localAddress
: outgoing
191 // No socks connection, connect directly to the IRCd
194 that
.socket
= tls
.connect({
196 port
: that
.irc_host
.port
,
197 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
,
198 localAddress
: outgoing
201 socket_connect_event_name
= 'secureConnect';
204 that
.socket
= net
.connect({
206 port
: that
.irc_host
.port
,
207 localAddress
: outgoing
212 // Apply the socket listeners
213 that
.socket
.on(socket_connect_event_name
, function socketConnectCb() {
215 // SSL connections have the actual socket as a property
216 var socket
= (typeof this.socket
!== 'undefined') ?
220 that
.connected
= true;
222 // Make note of the port numbers for any identd lookups
223 // Nodejs < 0.9.6 has no socket.localPort so check this first
224 if (socket
.localPort
) {
225 that
.identd_port_pair
= socket
.localPort
.toString() + '_' + socket
.remotePort
.toString();
226 global
.clients
.port_pairs
[that
.identd_port_pair
] = that
;
229 socketConnectHandler
.call(that
);
232 that
.socket
.on('error', function socketErrorCb(event
) {
233 that
.emit('error', event
);
236 that
.socket
.on('data', function () {
237 parse
.apply(that
, arguments
);
240 that
.socket
.on('close', function socketCloseCb(had_error
) {
241 that
.connected
= false;
243 // Remove this socket form the identd lookup
244 if (that
.identd_port_pair
) {
245 delete global
.clients
.port_pairs
[that
.identd_port_pair
];
250 // Close the whole socket down
251 that
.disposeSocket();
257 * Send an event to the client
259 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
260 data
.server
= this.con_num
;
261 this.state
.sendIrcCommand(event_name
, data
, callback
);
265 * Write a line of data to the IRCd
266 * @param data The line of data to be sent
267 * @param force Write the data now, ignoring any write queue
269 IrcConnection
.prototype.write = function (data
, force
) {
270 //ENCODE string to encoding of the server
271 encoded_buffer
= iconv
.encode(data
+ '\r\n', this.encoding
);
274 this.socket
.write(encoded_buffer
);
278 this.write_buffer
.push(encoded_buffer
);
280 // Only flush if we're not writing already
281 if (!this.writing_buffer
)
282 this.flushWriteBuffer();
288 * Flush the write buffer to the server in a throttled fashion
290 IrcConnection
.prototype.flushWriteBuffer = function () {
292 // In case the socket closed between writing our queue.. clean up
293 if (!this.connected
) {
294 this.write_buffer
= [];
295 this.writing_buffer
= false;
299 this.writing_buffer
= true;
301 // Disabled write buffer? Send everything we have
302 if (!this.write_buffer_lines_second
) {
303 this.write_buffer
.forEach(function(buffer
, idx
) {
304 this.socket
.write(buffer
);
305 this.write_buffer
= null;
308 this.write_buffer
= [];
309 this.writing_buffer
= false;
314 // Nothing to write? Stop writing and leave
315 if (this.write_buffer
.length
=== 0) {
316 this.writing_buffer
= false;
320 this.socket
.write(this.write_buffer
[0]);
321 this.write_buffer
= this.write_buffer
.slice(1);
323 // Call this function again at some point if we still have data to write
324 if (this.write_buffer
.length
> 0) {
325 setTimeout(this.flushWriteBuffer
.bind(this), 1000 / this.write_buffer_lines_second
);
327 // No more buffers to write.. so we've finished
328 this.writing_buffer
= false;
335 * Close the connection to the IRCd after forcing one last line
337 IrcConnection
.prototype.end = function (data
, callback
) {
342 this.write(data
, true);
350 * Clean up this IrcConnection instance and any sockets
352 IrcConnection
.prototype.dispose = function () {
353 // If we're still connected, wait until the socket is closed before disposing
354 // so that all the events are still correctly triggered
355 if (this.socket
&& this.connected
) {
361 this.disposeSocket();
364 _
.each(this.irc_users
, function (user
) {
367 _
.each(this.irc_channels
, function (chan
) {
370 this.irc_users
= undefined;
371 this.irc_channels
= undefined;
373 this.server
.dispose();
374 this.server
= undefined;
376 this.irc_commands
= undefined;
378 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
380 this.removeAllListeners();
386 * Clean up any sockets for this IrcConnection
388 IrcConnection
.prototype.disposeSocket = function () {
391 this.socket
.removeAllListeners();
397 * Set a new encoding for this connection
398 * Return true in case of success
401 IrcConnection
.prototype.setEncoding = function (encoding
) {
405 encoded_test
= iconv
.encode("TEST", encoding
);
406 //This test is done to check if this encoding also supports
407 //the ASCII charset required by the IRC protocols
408 //(Avoid the use of base64 or incompatible encodings)
409 if (encoded_test
== "TEST") {
410 this.encoding
= encoding
;
419 function getConnectionFamily(host
, callback
) {
420 if (net
.isIP(host
)) {
421 if (net
.isIPv4(host
)) {
422 callback(null, 'IPv4', host
);
424 callback(null, 'IPv6', host
);
427 dns
.resolve6(host
, function resolve6Cb(err
, addresses
) {
429 callback(null, 'IPv6', addresses
[0]);
431 dns
.resolve4(host
, function resolve4Cb(err
, addresses
) {
433 callback(null, 'IPv4',addresses
[0]);
444 function onChannelJoin(event
) {
447 // Only deal with ourselves joining a channel
448 if (event
.nick
!== this.nick
)
451 // We should only ever get a JOIN command for a channel
452 // we're not already a member of.. but check we don't
453 // have this channel in case something went wrong somewhere
454 // at an earlier point
455 if (!this.irc_channels
[event
.channel
]) {
456 chan
= new IrcChannel(this, event
.channel
);
457 this.irc_channels
[event
.channel
] = chan
;
458 chan
.irc_events
.join
.call(chan
, event
);
463 function onServerConnect(event
) {
464 this.nick
= event
.nick
;
468 function onUserPrivmsg(event
) {
471 // Only deal with messages targetted to us
472 if (event
.channel
!== this.nick
)
475 if (!this.irc_users
[event
.nick
]) {
476 user
= new IrcUser(this, event
.nick
);
477 this.irc_users
[event
.nick
] = user
;
478 user
.irc_events
.privmsg
.call(user
, event
);
483 function onUserNick(event
) {
486 // Only deal with messages targetted to us
487 if (event
.nick
!== this.nick
)
490 this.nick
= event
.newnick
;
494 function onUserParts(event
) {
495 // Only deal with ourselves leaving a channel
496 if (event
.nick
!== this.nick
)
499 if (this.irc_channels
[event
.channel
]) {
500 this.irc_channels
[event
.channel
].dispose();
501 delete this.irc_channels
[event
.channel
];
505 function onUserKick(event
){
506 // Only deal with ourselves being kicked from a channel
507 if (event
.kicked
!== this.nick
)
510 if (this.irc_channels
[event
.channel
]) {
511 this.irc_channels
[event
.channel
].dispose();
512 delete this.irc_channels
[event
.channel
];
521 * Handle the socket connect event, starting the IRCd registration
523 var socketConnectHandler = function () {
527 // Build up data to be used for webirc/etc detection
531 // Array of lines to be sent to the IRCd before anything else
535 // Let the webirc/etc detection modify any required parameters
536 connect_data
= findWebIrc
.call(this, connect_data
);
538 global
.modules
.emit('irc authorize', connect_data
).done(function ircAuthorizeCb() {
539 // Send any initial data for webirc/etc
540 if (connect_data
.prepend_data
) {
541 _
.each(connect_data
.prepend_data
, function(data
) {
546 that
.write('CAP LS');
549 that
.write('PASS ' + that
.password
);
551 that
.write('NICK ' + that
.nick
);
552 that
.write('USER ' + that
.username
+ ' 0 0 :' + '[www.kiwiirc.com] ' + that
.nick
);
554 that
.emit('connected');
561 * Load any WEBIRC or alternative settings for this connection
562 * Called in scope of the IrcConnection instance
564 function findWebIrc(connect_data
) {
565 var webirc_pass
= global
.config
.webirc_pass
,
566 ip_as_username
= global
.config
.ip_as_username
,
570 // Do we have a WEBIRC password for this?
571 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
572 // Build the WEBIRC line to be sent before IRC registration
573 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
574 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
576 connect_data
.prepend_data
= [tmp
];
580 // Check if we need to pass the users IP as its username/ident
581 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
582 // Get a hex value of the clients IP
583 this.username
= this.user
.address
.split('.').map(function ipSplitMapCb(i
, idx
){
584 var hex
= parseInt(i
, 10).toString(16);
586 // Pad out the hex value if it's a single char
587 if (hex
.length
=== 1)
601 * The regex that parses a line of data from the IRCd
602 * Deviates from the RFC a little to support the '/' character now used in some
605 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;
607 var parse = function (data
) {
616 //DECODE server encoding
617 data
= iconv
.decode(data
, this.encoding
);
619 if (this.hold_last
&& this.held_data
!== '') {
620 data
= this.held_data
+ data
;
621 this.hold_last
= false;
625 // If the last line is incomplete, hold it until we have more data
626 if (data
.substr(-1) !== '\n') {
627 this.hold_last
= true;
630 // Process our data line by line
631 data
= data
.split("\n");
632 for (i
= 0; i
< data
.length
; i
++) {
635 // If flagged to hold the last line, store it and move on
636 if (this.hold_last
&& (i
=== data
.length
- 1)) {
637 this.held_data
= data
[i
];
641 // Parse the complete line, removing any carriage returns
642 msg
= parse_regex
.exec(data
[i
].replace(/^\r+|\r+$/, ''));
646 tags
= msg
[1].split(';');
647 for (j
= 0; j
< tags
.length
; j
++) {
648 tag
= tags
[j
].split('=');
649 tags
[j
] = {tag
: tag
[0], value
: tag
[1]};
657 hostname
: msg
[5] || '',
659 params
: msg
[7] || '',
660 trailing
: (msg
[8]) ? msg
[8].trim() : ''
662 msg
.params
= msg
.params
.split(' ');
663 this.irc_commands
.dispatch(msg
.command
.toUpperCase(), msg
);
665 // The line was not parsed correctly, must be malformed
666 console
.log("Malformed IRC line: " + data
[i
].replace(/^\r+|\r+$/, ''));