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 int he 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
) {
35 this.setMaxListeners(0);
37 options
= options
|| {};
40 this.connected
= false;
42 // IRCd write buffers (flood controll)
43 this.write_buffer
= [];
45 // In process of writing the buffer?
46 this.writing_buffer
= false;
48 // Max number of lines to write a second
49 this.write_buffer_lines_second
= 2;
51 // If registeration with the IRCd has completed
52 this.registered
= false;
54 // If we are in the CAP negotiation stage
55 this.cap_negotiation
= true;
59 this.user
= user
; // Contains users real hostname and address
60 this.username
= this.nick
.replace(/[^0-9a-zA-Z\-_.\/]/, '');
61 this.password
= options
.password
|| '';
63 // Set the passed encoding. or the default if none giving or it fails
64 if (!options
.encoding
|| !this.setEncoding(options
.encoding
)) {
65 this.setEncoding(global
.config
.default_encoding
);
71 // Connection ID in the state
72 this.con_num
= con_num
;
74 // IRC protocol handling
75 this.irc_commands
= new IrcCommands(this);
78 this.server
= new IrcServer(this, hostname
, port
);
81 this.irc_users
= Object
.create(null);
83 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
84 this.irc_users
[this.nick
] = new IrcUser(this, '*');
87 this.irc_channels
= Object
.create(null);
89 // IRC connection information
90 this.irc_host
= {hostname
: hostname
, port
: port
};
93 // SOCKS proxy details
94 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
95 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
)))) {
97 host
: global
.config
.socks_proxy
.address
,
98 port
: global
.config
.socks_proxy
.port
,
99 user
: global
.config
.socks_proxy
.user
,
100 pass
: global
.config
.socks_proxy
.pass
106 // Kiwi proxy info may be set within a server module. {port: 7779, host: 'kiwi.proxy.com', ssl: false}
109 // Net. interface this connection should be made through
110 this.outgoing_interface
= false;
112 // Options sent by the IRCd
113 this.options
= Object
.create(null);
114 this.cap
= {requested
: [], enabled
: []};
116 // Is SASL supported on the IRCd
119 // Buffers for data sent from the IRCd
120 this.hold_last
= false;
121 this.held_data
= null;
123 this.applyIrcEvents();
125 util
.inherits(IrcConnection
, EE
);
127 module
.exports
.IrcConnection
= IrcConnection
;
131 IrcConnection
.prototype.applyIrcEvents = function () {
132 // Listen for events on the IRC connection
134 'server * connect': onServerConnect
,
135 'channel * join': onChannelJoin
,
137 // TODO: uncomment when using an IrcUser per nick
138 //'user:*:privmsg': onUserPrivmsg,
139 'user * nick': onUserNick
,
140 'channel * part': onUserParts
,
141 'channel * quit': onUserParts
,
142 'channel * kick': onUserKick
145 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
150 * Start the connection to the IRCd
152 IrcConnection
.prototype.connect = function () {
155 // The socket connect event to listener for
156 var socket_connect_event_name
= 'connect';
158 // The destination address
161 dest_addr
= this.socks
.host
;
162 } else if (this.proxy
) {
163 dest_addr
= this.proxy
.host
;
165 dest_addr
= this.irc_host
.hostname
;
168 // Make sure we don't already have an open connection
169 this.disposeSocket();
171 // Get the IP family for the dest_addr (either socks or IRCd destination)
172 getConnectionFamily(dest_addr
, function getConnectionFamilyCb(err
, family
, host
) {
175 // Decide which net. interface to make the connection through
176 if (that
.outgoing_interface
) {
177 // An specific interface has been given for this connection
178 outgoing
= this.outgoing_interface
;
180 } else if (global
.config
.outgoing_address
) {
181 // Pick an interface from the config
182 if ((family
=== 'IPv6') && (global
.config
.outgoing_address
.IPv6
)) {
183 outgoing
= global
.config
.outgoing_address
.IPv6
;
185 outgoing
= global
.config
.outgoing_address
.IPv4
|| '0.0.0.0';
187 // We don't have an IPv6 interface but dest_addr may still resolve to
188 // an IPv4 address. Reset `host` and try connecting anyway, letting it
189 // fail if an IPv4 resolved address is not found
193 // If we have an array of interfaces, select a random one
194 if (typeof outgoing
!== 'string' && outgoing
.length
) {
195 outgoing
= outgoing
[Math
.floor(Math
.random() * outgoing
.length
)];
198 // Make sure we have a valid interface address
199 if (typeof outgoing
!== 'string')
200 outgoing
= '0.0.0.0';
203 // No config was found so use the default
204 outgoing
= '0.0.0.0';
207 // Are we connecting through a SOCKS proxy?
209 that
.socket
= Socks
.connect({
210 host
: that
.irc_host
.host
,
211 port
: that
.irc_host
.port
,
213 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
215 port
: that
.socks
.port
,
216 user
: that
.socks
.user
,
217 pass
: that
.socks
.pass
,
218 localAddress
: outgoing
221 } else if (that
.proxy
) {
222 that
.socket
= new Proxy
.ProxySocket(that
.proxy
.port
, host
, {
223 username
: that
.username
,
224 interface: that
.proxy
.interface
225 }, {ssl
: that
.proxy
.ssl
});
228 that
.socket
.connectTls(that
.irc_host
.port
, that
.irc_host
.hostname
);
230 that
.socket
.connect(that
.irc_host
.port
, that
.irc_host
.hostname
);
234 // No socks connection, connect directly to the IRCd
237 that
.socket
= tls
.connect({
239 port
: that
.irc_host
.port
,
240 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
,
241 localAddress
: outgoing
244 // We need the raw socket connect event
245 that
.socket
.socket
.on('connect', function() { rawSocketConnect
.call(that
, this); });
247 socket_connect_event_name
= 'secureConnect';
250 that
.socket
= net
.connect({
252 port
: that
.irc_host
.port
,
253 localAddress
: outgoing
258 // Apply the socket listeners
259 that
.socket
.on(socket_connect_event_name
, function socketConnectCb() {
261 // TLS connections have the actual socket as a property
262 var is_tls
= (typeof this.socket
!== 'undefined') ?
266 // TLS sockets have already called this
268 rawSocketConnect
.call(that
, this);
270 that
.connected
= true;
272 socketConnectHandler
.call(that
);
275 that
.socket
.on('error', function socketErrorCb(event
) {
276 that
.emit('error', event
);
279 that
.socket
.on('data', function () {
280 socketOnData
.apply(that
, arguments
);
283 that
.socket
.on('close', function socketCloseCb(had_error
) {
284 that
.connected
= false;
286 // Remove this socket form the identd lookup
287 if (that
.identd_port_pair
) {
288 delete global
.clients
.port_pairs
[that
.identd_port_pair
];
293 // Close the whole socket down
294 that
.disposeSocket();
300 * Send an event to the client
302 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
303 data
.server
= this.con_num
;
304 this.state
.sendIrcCommand(event_name
, data
, callback
);
308 * Write a line of data to the IRCd
309 * @param data The line of data to be sent
310 * @param force Write the data now, ignoring any write queue
312 IrcConnection
.prototype.write = function (data
, force
) {
313 //ENCODE string to encoding of the server
314 encoded_buffer
= iconv
.encode(data
+ '\r\n', this.encoding
);
317 this.socket
.write(encoded_buffer
);
321 this.write_buffer
.push(encoded_buffer
);
323 // Only flush if we're not writing already
324 if (!this.writing_buffer
)
325 this.flushWriteBuffer();
331 * Flush the write buffer to the server in a throttled fashion
333 IrcConnection
.prototype.flushWriteBuffer = function () {
335 // In case the socket closed between writing our queue.. clean up
336 if (!this.connected
) {
337 this.write_buffer
= [];
338 this.writing_buffer
= false;
342 this.writing_buffer
= true;
344 // Disabled write buffer? Send everything we have
345 if (!this.write_buffer_lines_second
) {
346 this.write_buffer
.forEach(function(buffer
, idx
) {
347 this.socket
.write(buffer
);
348 this.write_buffer
= null;
351 this.write_buffer
= [];
352 this.writing_buffer
= false;
357 // Nothing to write? Stop writing and leave
358 if (this.write_buffer
.length
=== 0) {
359 this.writing_buffer
= false;
363 this.socket
.write(this.write_buffer
[0]);
364 this.write_buffer
= this.write_buffer
.slice(1);
366 // Call this function again at some point if we still have data to write
367 if (this.write_buffer
.length
> 0) {
368 setTimeout(this.flushWriteBuffer
.bind(this), 1000 / this.write_buffer_lines_second
);
370 // No more buffers to write.. so we've finished
371 this.writing_buffer
= false;
378 * Close the connection to the IRCd after forcing one last line
380 IrcConnection
.prototype.end = function (data
, callback
) {
385 this.write(data
, true);
393 * Clean up this IrcConnection instance and any sockets
395 IrcConnection
.prototype.dispose = function () {
396 // If we're still connected, wait until the socket is closed before disposing
397 // so that all the events are still correctly triggered
398 if (this.socket
&& this.connected
) {
404 this.disposeSocket();
407 _
.each(this.irc_users
, function (user
) {
410 _
.each(this.irc_channels
, function (chan
) {
413 this.irc_users
= undefined;
414 this.irc_channels
= undefined;
416 this.server
.dispose();
417 this.server
= undefined;
419 this.irc_commands
= undefined;
421 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
423 this.removeAllListeners();
429 * Clean up any sockets for this IrcConnection
431 IrcConnection
.prototype.disposeSocket = function () {
434 this.socket
.removeAllListeners();
440 * Set a new encoding for this connection
441 * Return true in case of success
444 IrcConnection
.prototype.setEncoding = function (encoding
) {
448 encoded_test
= iconv
.encode("TEST", encoding
);
449 //This test is done to check if this encoding also supports
450 //the ASCII charset required by the IRC protocols
451 //(Avoid the use of base64 or incompatible encodings)
452 if (encoded_test
== "TEST") {
453 this.encoding
= encoding
;
462 function getConnectionFamily(host
, callback
) {
463 if (net
.isIP(host
)) {
464 if (net
.isIPv4(host
)) {
465 callback(null, 'IPv4', host
);
467 callback(null, 'IPv6', host
);
470 dns
.resolve6(host
, function resolve6Cb(err
, addresses
) {
472 callback(null, 'IPv6', addresses
[0]);
474 dns
.resolve4(host
, function resolve4Cb(err
, addresses
) {
476 callback(null, 'IPv4',addresses
[0]);
487 function onChannelJoin(event
) {
490 // Only deal with ourselves joining a channel
491 if (event
.nick
!== this.nick
)
494 // We should only ever get a JOIN command for a channel
495 // we're not already a member of.. but check we don't
496 // have this channel in case something went wrong somewhere
497 // at an earlier point
498 if (!this.irc_channels
[event
.channel
]) {
499 chan
= new IrcChannel(this, event
.channel
);
500 this.irc_channels
[event
.channel
] = chan
;
501 chan
.irc_events
.join
.call(chan
, event
);
506 function onServerConnect(event
) {
507 this.nick
= event
.nick
;
511 function onUserPrivmsg(event
) {
514 // Only deal with messages targetted to us
515 if (event
.channel
!== this.nick
)
518 if (!this.irc_users
[event
.nick
]) {
519 user
= new IrcUser(this, event
.nick
);
520 this.irc_users
[event
.nick
] = user
;
521 user
.irc_events
.privmsg
.call(user
, event
);
526 function onUserNick(event
) {
529 // Only deal with messages targetted to us
530 if (event
.nick
!== this.nick
)
533 this.nick
= event
.newnick
;
537 function onUserParts(event
) {
538 // Only deal with ourselves leaving a channel
539 if (event
.nick
!== this.nick
)
542 if (this.irc_channels
[event
.channel
]) {
543 this.irc_channels
[event
.channel
].dispose();
544 delete this.irc_channels
[event
.channel
];
548 function onUserKick(event
){
549 // Only deal with ourselves being kicked from a channel
550 if (event
.kicked
!== this.nick
)
553 if (this.irc_channels
[event
.channel
]) {
554 this.irc_channels
[event
.channel
].dispose();
555 delete this.irc_channels
[event
.channel
];
563 * When a socket connects to an IRCd
564 * May be called before any socket handshake are complete (eg. TLS)
566 var rawSocketConnect = function(socket
) {
567 // Make note of the port numbers for any identd lookups
568 // Nodejs < 0.9.6 has no socket.localPort so check this first
569 if (typeof socket
.localPort
!= 'undefined') {
570 this.identd_port_pair
= socket
.localPort
.toString() + '_' + socket
.remotePort
.toString();
571 global
.clients
.port_pairs
[this.identd_port_pair
] = this;
577 * Handle the socket connect event, starting the IRCd registration
579 var socketConnectHandler = function () {
583 // Build up data to be used for webirc/etc detection
587 // Array of lines to be sent to the IRCd before anything else
591 // Let the webirc/etc detection modify any required parameters
592 connect_data
= findWebIrc
.call(this, connect_data
);
594 global
.modules
.emit('irc authorize', connect_data
).done(function ircAuthorizeCb() {
595 var gecos
= '[www.kiwiirc.com] ' + that
.nick
;
597 if (global
.config
.default_gecos
) {
598 gecos
= global
.config
.default_gecos
.toString().replace('%n', that
.nick
);
599 gecos
= gecos
.toString().replace('%h', that
.user
.hostname
);
602 // Send any initial data for webirc/etc
603 if (connect_data
.prepend_data
) {
604 _
.each(connect_data
.prepend_data
, function(data
) {
609 that
.write('CAP LS');
612 that
.write('PASS ' + that
.password
);
614 that
.write('NICK ' + that
.nick
);
615 that
.write('USER ' + that
.username
+ ' 0 0 :' + gecos
);
617 that
.emit('connected');
624 * Load any WEBIRC or alternative settings for this connection
625 * Called in scope of the IrcConnection instance
627 function findWebIrc(connect_data
) {
628 var webirc_pass
= global
.config
.webirc_pass
,
629 ip_as_username
= global
.config
.ip_as_username
,
633 // Do we have a WEBIRC password for this?
634 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
635 // Build the WEBIRC line to be sent before IRC registration
636 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
637 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
639 connect_data
.prepend_data
= [tmp
];
643 // Check if we need to pass the users IP as its username/ident
644 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
645 // Get a hex value of the clients IP
646 this.username
= this.user
.address
.split('.').map(function ipSplitMapCb(i
, idx
){
647 var hex
= parseInt(i
, 10).toString(16);
649 // Pad out the hex value if it's a single char
650 if (hex
.length
=== 1)
663 * Buffer any data we get from the IRCd until we have complete lines.
665 function socketOnData(data
) {
666 var data_pos
, // Current position within the data Buffer
670 max_buffer_size
= 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
671 // May need tweaking when IRCv3 message tags are more widespread
673 // Split data chunk into individual lines
674 for (data_pos
= 0; data_pos
< data
.length
; data_pos
++) {
675 if (data
[data_pos
] === 0x0A) { // Check if byte is a line feed
676 lines
.push(data
.slice(line_start
, data_pos
));
677 line_start
= data_pos
+ 1;
681 // No complete lines of data? Check to see if buffering the data would exceed the max buffer size
683 if ((this.held_data
? this.held_data
.length
: 0 ) + data
.length
> max_buffer_size
) {
684 // Buffering this data would exeed our max buffer size
685 this.emit('error', 'Message buffer too large');
686 this.socket
.destroy();
690 // Append the incomplete line to our held_data and wait for more
691 if (this.held_data
) {
692 this.held_data
= Buffer
.concat([this.held_data
, data
], this.held_data
.length
+ data
.length
);
694 this.held_data
= data
;
698 // No complete lines to process..
702 // If we have an incomplete line held from the previous chunk of data
703 // merge it with the first line from this chunk of data
704 if (this.hold_last
&& this.held_data
!== null) {
705 lines
[0] = Buffer
.concat([this.held_data
, lines
[0]], this.held_data
.length
+ lines
[0].length
);
706 this.hold_last
= false;
707 this.held_data
= null;
710 // If the last line of data in this chunk is not complete, hold it so
711 // it can be merged with the first line from the next chunk
712 if (line_start
< data_pos
) {
713 if ((data
.length
- line_start
) > max_buffer_size
) {
714 // Buffering this data would exeed our max buffer size
715 this.emit('error', 'Message buffer too large');
716 this.socket
.destroy();
720 this.hold_last
= true;
721 this.held_data
= new Buffer(data
.length
- line_start
);
722 data
.copy(this.held_data
, 0, line_start
);
725 // Process our data line by line
726 for (i
= 0; i
< lines
.length
; i
++)
727 parseIrcLine
.call(this, lines
[i
]);
734 * The regex that parses a line of data from the IRCd
735 * Deviates from the RFC a little to support the '/' character now used in some
738 var parse_regex
= /^(?:(?:(?:@([^ ]+) )?):(?:([^\s!]+)|([^\s!]+)!([^\s@]+)@?([^\s]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.*))?$/i;
740 function parseIrcLine(buffer_line
) {
748 // Decode server encoding
749 line
= iconv
.decode(buffer_line
, this.encoding
);
754 // Parse the complete line, removing any carriage returns
755 msg
= parse_regex
.exec(line
.replace(/^\r+|\r+$/, ''));
758 // The line was not parsed correctly, must be malformed
759 //console.log("Malformed IRC line: " + line.replace(/^\r+|\r+$/, ''));
760 winston
.warn('Malformed IRC line: %s', line
.replace(/^\r+|\r+$/, ''));
764 // Extract any tags (msg[1])
766 tags
= msg
[1].split(';');
768 for (i
= 0; i
< tags
.length
; i
++) {
769 tag
= tags
[i
].split('=');
770 tags
[i
] = {tag
: tag
[0], value
: tag
[1]};
779 hostname
: msg
[5] || '',
781 params
: msg
[7] ? msg
[7].split(/ +/) : []
785 msg_obj
.params
.push(msg
[8].trim());
788 this.irc_commands
.dispatch(msg_obj
.command
.toUpperCase(), msg_obj
);