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 // Net. interface this connection should be made through
106 this.outgoing_interface
= false;
108 // Options sent by the IRCd
109 this.options
= Object
.create(null);
110 this.cap
= {requested
: [], enabled
: []};
112 // Is SASL supported on the IRCd
115 // Buffers for data sent from the IRCd
116 this.hold_last
= false;
117 this.held_data
= null;
119 this.applyIrcEvents();
121 util
.inherits(IrcConnection
, EE
);
123 module
.exports
.IrcConnection
= IrcConnection
;
127 IrcConnection
.prototype.applyIrcEvents = function () {
128 // Listen for events on the IRC connection
130 'server * connect': onServerConnect
,
131 'channel * join': onChannelJoin
,
133 // TODO: uncomment when using an IrcUser per nick
134 //'user:*:privmsg': onUserPrivmsg,
135 'user * nick': onUserNick
,
136 'channel * part': onUserParts
,
137 'channel * quit': onUserParts
,
138 'channel * kick': onUserKick
141 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
146 * Start the connection to the IRCd
148 IrcConnection
.prototype.connect = function () {
151 // The socket connect event to listener for
152 var socket_connect_event_name
= 'connect';
154 // The destination address
155 var dest_addr
= this.socks
?
157 this.irc_host
.hostname
;
159 // Make sure we don't already have an open connection
160 this.disposeSocket();
162 // Get the IP family for the dest_addr (either socks or IRCd destination)
163 getConnectionFamily(dest_addr
, function getConnectionFamilyCb(err
, family
, host
) {
166 // Decide which net. interface to make the connection through
167 if (that
.outgoing_interface
) {
168 // An specific interface has been given for this connection
169 outgoing
= this.outgoing_interface
;
171 } else if (global
.config
.outgoing_address
) {
172 // Pick an interface from the config
173 if ((family
=== 'IPv6') && (global
.config
.outgoing_address
.IPv6
)) {
174 outgoing
= global
.config
.outgoing_address
.IPv6
;
176 outgoing
= global
.config
.outgoing_address
.IPv4
|| '0.0.0.0';
178 // We don't have an IPv6 interface but dest_addr may still resolve to
179 // an IPv4 address. Reset `host` and try connecting anyway, letting it
180 // fail if an IPv4 resolved address is not found
184 // If we have an array of interfaces, select a random one
185 if (typeof outgoing
!== 'string' && outgoing
.length
) {
186 outgoing
= outgoing
[Math
.floor(Math
.random() * outgoing
.length
)];
189 // Make sure we have a valid interface address
190 if (typeof outgoing
!== 'string')
191 outgoing
= '0.0.0.0';
194 // No config was found so use the default
195 outgoing
= '0.0.0.0';
198 // Are we connecting through a SOCKS proxy?
200 that
.socket
= Socks
.connect({
202 port
: that
.irc_host
.port
,
204 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
205 }, {host
: that
.socks
.host
,
206 port
: that
.socks
.port
,
207 user
: that
.socks
.user
,
208 pass
: that
.socks
.pass
,
209 localAddress
: outgoing
212 } else if (true || that
.proxy
) {
213 that
.socket
= new Proxy
.ProxySocket(7779, '127.0.0.1', {
214 username
: that
.username
,
216 that
.socket
.connect(that
.irc_host
.port
, host
);
219 // No socks connection, connect directly to the IRCd
222 that
.socket
= tls
.connect({
224 port
: that
.irc_host
.port
,
225 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
,
226 localAddress
: outgoing
229 // We need the raw socket connect event
230 that
.socket
.socket
.on('connect', function() { rawSocketConnect
.call(that
, this); });
232 socket_connect_event_name
= 'secureConnect';
235 that
.socket
= net
.connect({
237 port
: that
.irc_host
.port
,
238 localAddress
: outgoing
243 // Apply the socket listeners
244 that
.socket
.on(socket_connect_event_name
, function socketConnectCb() {
246 // TLS connections have the actual socket as a property
247 var is_tls
= (typeof this.socket
!== 'undefined') ?
251 // TLS sockets have already called this
253 rawSocketConnect
.call(that
, this);
255 that
.connected
= true;
257 socketConnectHandler
.call(that
);
260 that
.socket
.on('error', function socketErrorCb(event
) {
261 that
.emit('error', event
);
264 that
.socket
.on('data', function () {
265 socketOnData
.apply(that
, arguments
);
268 that
.socket
.on('close', function socketCloseCb(had_error
) {
269 that
.connected
= false;
271 // Remove this socket form the identd lookup
272 if (that
.identd_port_pair
) {
273 delete global
.clients
.port_pairs
[that
.identd_port_pair
];
278 // Close the whole socket down
279 that
.disposeSocket();
285 * Send an event to the client
287 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
288 data
.server
= this.con_num
;
289 this.state
.sendIrcCommand(event_name
, data
, callback
);
293 * Write a line of data to the IRCd
294 * @param data The line of data to be sent
295 * @param force Write the data now, ignoring any write queue
297 IrcConnection
.prototype.write = function (data
, force
) {
298 //ENCODE string to encoding of the server
299 encoded_buffer
= iconv
.encode(data
+ '\r\n', this.encoding
);
302 this.socket
.write(encoded_buffer
);
306 this.write_buffer
.push(encoded_buffer
);
308 // Only flush if we're not writing already
309 if (!this.writing_buffer
)
310 this.flushWriteBuffer();
316 * Flush the write buffer to the server in a throttled fashion
318 IrcConnection
.prototype.flushWriteBuffer = function () {
320 // In case the socket closed between writing our queue.. clean up
321 if (!this.connected
) {
322 this.write_buffer
= [];
323 this.writing_buffer
= false;
327 this.writing_buffer
= true;
329 // Disabled write buffer? Send everything we have
330 if (!this.write_buffer_lines_second
) {
331 this.write_buffer
.forEach(function(buffer
, idx
) {
332 this.socket
.write(buffer
);
333 this.write_buffer
= null;
336 this.write_buffer
= [];
337 this.writing_buffer
= false;
342 // Nothing to write? Stop writing and leave
343 if (this.write_buffer
.length
=== 0) {
344 this.writing_buffer
= false;
348 this.socket
.write(this.write_buffer
[0]);
349 this.write_buffer
= this.write_buffer
.slice(1);
351 // Call this function again at some point if we still have data to write
352 if (this.write_buffer
.length
> 0) {
353 setTimeout(this.flushWriteBuffer
.bind(this), 1000 / this.write_buffer_lines_second
);
355 // No more buffers to write.. so we've finished
356 this.writing_buffer
= false;
363 * Close the connection to the IRCd after forcing one last line
365 IrcConnection
.prototype.end = function (data
, callback
) {
370 this.write(data
, true);
378 * Clean up this IrcConnection instance and any sockets
380 IrcConnection
.prototype.dispose = function () {
381 // If we're still connected, wait until the socket is closed before disposing
382 // so that all the events are still correctly triggered
383 if (this.socket
&& this.connected
) {
389 this.disposeSocket();
392 _
.each(this.irc_users
, function (user
) {
395 _
.each(this.irc_channels
, function (chan
) {
398 this.irc_users
= undefined;
399 this.irc_channels
= undefined;
401 this.server
.dispose();
402 this.server
= undefined;
404 this.irc_commands
= undefined;
406 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
408 this.removeAllListeners();
414 * Clean up any sockets for this IrcConnection
416 IrcConnection
.prototype.disposeSocket = function () {
419 this.socket
.removeAllListeners();
425 * Set a new encoding for this connection
426 * Return true in case of success
429 IrcConnection
.prototype.setEncoding = function (encoding
) {
433 encoded_test
= iconv
.encode("TEST", encoding
);
434 //This test is done to check if this encoding also supports
435 //the ASCII charset required by the IRC protocols
436 //(Avoid the use of base64 or incompatible encodings)
437 if (encoded_test
== "TEST") {
438 this.encoding
= encoding
;
447 function getConnectionFamily(host
, callback
) {
448 if (net
.isIP(host
)) {
449 if (net
.isIPv4(host
)) {
450 callback(null, 'IPv4', host
);
452 callback(null, 'IPv6', host
);
455 dns
.resolve6(host
, function resolve6Cb(err
, addresses
) {
457 callback(null, 'IPv6', addresses
[0]);
459 dns
.resolve4(host
, function resolve4Cb(err
, addresses
) {
461 callback(null, 'IPv4',addresses
[0]);
472 function onChannelJoin(event
) {
475 // Only deal with ourselves joining a channel
476 if (event
.nick
!== this.nick
)
479 // We should only ever get a JOIN command for a channel
480 // we're not already a member of.. but check we don't
481 // have this channel in case something went wrong somewhere
482 // at an earlier point
483 if (!this.irc_channels
[event
.channel
]) {
484 chan
= new IrcChannel(this, event
.channel
);
485 this.irc_channels
[event
.channel
] = chan
;
486 chan
.irc_events
.join
.call(chan
, event
);
491 function onServerConnect(event
) {
492 this.nick
= event
.nick
;
496 function onUserPrivmsg(event
) {
499 // Only deal with messages targetted to us
500 if (event
.channel
!== this.nick
)
503 if (!this.irc_users
[event
.nick
]) {
504 user
= new IrcUser(this, event
.nick
);
505 this.irc_users
[event
.nick
] = user
;
506 user
.irc_events
.privmsg
.call(user
, event
);
511 function onUserNick(event
) {
514 // Only deal with messages targetted to us
515 if (event
.nick
!== this.nick
)
518 this.nick
= event
.newnick
;
522 function onUserParts(event
) {
523 // Only deal with ourselves leaving a channel
524 if (event
.nick
!== this.nick
)
527 if (this.irc_channels
[event
.channel
]) {
528 this.irc_channels
[event
.channel
].dispose();
529 delete this.irc_channels
[event
.channel
];
533 function onUserKick(event
){
534 // Only deal with ourselves being kicked from a channel
535 if (event
.kicked
!== this.nick
)
538 if (this.irc_channels
[event
.channel
]) {
539 this.irc_channels
[event
.channel
].dispose();
540 delete this.irc_channels
[event
.channel
];
548 * When a socket connects to an IRCd
549 * May be called before any socket handshake are complete (eg. TLS)
551 var rawSocketConnect = function(socket
) {
552 // Make note of the port numbers for any identd lookups
553 // Nodejs < 0.9.6 has no socket.localPort so check this first
554 if (typeof socket
.localPort
!= 'undefined') {
555 this.identd_port_pair
= socket
.localPort
.toString() + '_' + socket
.remotePort
.toString();
556 global
.clients
.port_pairs
[this.identd_port_pair
] = this;
562 * Handle the socket connect event, starting the IRCd registration
564 var socketConnectHandler = function () {
568 // Build up data to be used for webirc/etc detection
572 // Array of lines to be sent to the IRCd before anything else
576 // Let the webirc/etc detection modify any required parameters
577 connect_data
= findWebIrc
.call(this, connect_data
);
579 global
.modules
.emit('irc authorize', connect_data
).done(function ircAuthorizeCb() {
580 var gecos
= '[www.kiwiirc.com] ' + that
.nick
;
582 if (global
.config
.default_gecos
) {
583 gecos
= global
.config
.default_gecos
.toString().replace('%n', that
.nick
);
584 gecos
= gecos
.toString().replace('%h', that
.user
.hostname
);
587 // Send any initial data for webirc/etc
588 if (connect_data
.prepend_data
) {
589 _
.each(connect_data
.prepend_data
, function(data
) {
594 that
.write('CAP LS');
597 that
.write('PASS ' + that
.password
);
599 that
.write('NICK ' + that
.nick
);
600 that
.write('USER ' + that
.username
+ ' 0 0 :' + gecos
);
602 that
.emit('connected');
609 * Load any WEBIRC or alternative settings for this connection
610 * Called in scope of the IrcConnection instance
612 function findWebIrc(connect_data
) {
613 var webirc_pass
= global
.config
.webirc_pass
,
614 ip_as_username
= global
.config
.ip_as_username
,
618 // Do we have a WEBIRC password for this?
619 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
620 // Build the WEBIRC line to be sent before IRC registration
621 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
622 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
624 connect_data
.prepend_data
= [tmp
];
628 // Check if we need to pass the users IP as its username/ident
629 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
630 // Get a hex value of the clients IP
631 this.username
= this.user
.address
.split('.').map(function ipSplitMapCb(i
, idx
){
632 var hex
= parseInt(i
, 10).toString(16);
634 // Pad out the hex value if it's a single char
635 if (hex
.length
=== 1)
648 * Buffer any data we get from the IRCd until we have complete lines.
650 function socketOnData(data
) {
651 var data_pos
, // Current position within the data Buffer
655 max_buffer_size
= 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
656 // May need tweaking when IRCv3 message tags are more widespread
658 // Split data chunk into individual lines
659 for (data_pos
= 0; data_pos
< data
.length
; data_pos
++) {
660 if (data
[data_pos
] === 0x0A) { // Check if byte is a line feed
661 lines
.push(data
.slice(line_start
, data_pos
));
662 line_start
= data_pos
+ 1;
666 // No complete lines of data? Check to see if buffering the data would exceed the max buffer size
668 if ((this.held_data
? this.held_data
.length
: 0 ) + data
.length
> max_buffer_size
) {
669 // Buffering this data would exeed our max buffer size
670 this.emit('error', 'Message buffer too large');
671 this.socket
.destroy();
675 // Append the incomplete line to our held_data and wait for more
676 if (this.held_data
) {
677 this.held_data
= Buffer
.concat([this.held_data
, data
], this.held_data
.length
+ data
.length
);
679 this.held_data
= data
;
683 // No complete lines to process..
687 // If we have an incomplete line held from the previous chunk of data
688 // merge it with the first line from this chunk of data
689 if (this.hold_last
&& this.held_data
!== null) {
690 lines
[0] = Buffer
.concat([this.held_data
, lines
[0]], this.held_data
.length
+ lines
[0].length
);
691 this.hold_last
= false;
692 this.held_data
= null;
695 // If the last line of data in this chunk is not complete, hold it so
696 // it can be merged with the first line from the next chunk
697 if (line_start
< data_pos
) {
698 if ((data
.length
- line_start
) > max_buffer_size
) {
699 // Buffering this data would exeed our max buffer size
700 this.emit('error', 'Message buffer too large');
701 this.socket
.destroy();
705 this.hold_last
= true;
706 this.held_data
= new Buffer(data
.length
- line_start
);
707 data
.copy(this.held_data
, 0, line_start
);
710 // Process our data line by line
711 for (i
= 0; i
< lines
.length
; i
++)
712 parseIrcLine
.call(this, lines
[i
]);
719 * The regex that parses a line of data from the IRCd
720 * Deviates from the RFC a little to support the '/' character now used in some
723 var parse_regex
= /^(?:(?:(?:@([^ ]+) )?):(?:([^\s!]+)|([^\s!]+)!([^\s@]+)@?([^\s]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.*))?$/i;
725 function parseIrcLine(buffer_line
) {
732 // Decode server encoding
733 line
= iconv
.decode(buffer_line
, this.encoding
);
736 // Parse the complete line, removing any carriage returns
737 msg
= parse_regex
.exec(line
.replace(/^\r+|\r+$/, ''));
740 // The line was not parsed correctly, must be malformed
741 console
.log("Malformed IRC line: " + line
.replace(/^\r+|\r+$/, ''));
745 // Extract any tags (msg[1])
747 tags
= msg
[1].split(';');
749 for (j
= 0; j
< tags
.length
; j
++) {
750 tag
= tags
[j
].split('=');
751 tags
[j
] = {tag
: tag
[0], value
: tag
[1]};
760 hostname
: msg
[5] || '',
762 params
: msg
[7] || '',
763 trailing
: (msg
[8]) ? msg
[8].trim() : ''
766 msg
.params
= msg
.params
.split(/ +/);
767 this.irc_commands
.dispatch(msg
.command
.toUpperCase(), msg
);