1 var net
= require('net'),
3 util
= require('util'),
5 EventBinder
= require('./eventbinder.js'),
6 IrcServer
= require('./server.js'),
7 IrcChannel
= require('./channel.js'),
8 IrcUser
= require('./user.js'),
9 EE
= require('../ee.js'),
10 iconv
= require('iconv-lite'),
14 // Break the Node.js version down into usable parts
15 var version_values
= process
.version
.substr(1).split('.').map(function (item
) {
16 return parseInt(item
, 10);
19 // If we have a suitable Nodejs version, bring int he socks functionality
20 if (version_values
[1] >= 10) {
21 Socks
= require('socksjs');
24 var IrcConnection = function (hostname
, port
, ssl
, nick
, user
, pass
, state
) {
31 this.setMaxListeners(0);
33 // Set the first configured encoding as the default encoding
34 this.encoding
= global
.config
.default_encoding
;
37 this.connected
= false;
39 // If registeration with the IRCd has completed
40 this.registered
= false;
42 // If we are in the CAP negotiation stage
43 this.cap_negotiation
= true;
47 this.user
= user
; // Contains users real hostname and address
48 this.username
= this.nick
.replace(/[^0-9a-zA-Z\-_.\/]/, '');
55 this.server
= new IrcServer(this, hostname
, port
);
58 this.irc_users
= Object
.create(null);
60 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
61 this.irc_users
[this.nick
] = new IrcUser(this, '*');
64 this.irc_channels
= Object
.create(null);
66 // IRC connection information
67 this.irc_host
= {hostname
: hostname
, port
: port
};
70 // SOCKS proxy details
71 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
72 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
)))) {
74 host
: global
.config
.socks_proxy
.address
,
75 port
: global
.config
.socks_proxy
.port
,
76 user
: global
.config
.socks_proxy
.user
,
77 pass
: global
.config
.socks_proxy
.pass
83 // Options sent by the IRCd
84 this.options
= Object
.create(null);
85 this.cap
= {requested
: [], enabled
: []};
87 // Is SASL supported on the IRCd
90 // Buffers for data sent from the IRCd
91 this.hold_last
= false;
94 this.applyIrcEvents();
96 util
.inherits(IrcConnection
, EE
);
98 module
.exports
.IrcConnection
= IrcConnection
;
102 IrcConnection
.prototype.applyIrcEvents = function () {
103 // Listen for events on the IRC connection
105 'server * connect': onServerConnect
,
106 'channel * join': onChannelJoin
,
108 // TODO: uncomment when using an IrcUser per nick
109 //'user:*:privmsg': onUserPrivmsg,
110 'user * nick': onUserNick
,
111 'channel * part': onUserParts
,
112 'channel * quit': onUserParts
,
113 'channel * kick': onUserKick
116 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
121 * Start the connection to the IRCd
123 IrcConnection
.prototype.connect = function () {
127 // The socket connect event to listener for
128 var socket_connect_event_name
= 'connect';
131 // Make sure we don't already have an open connection
132 this.disposeSocket();
134 // Are we connecting through a SOCKS proxy?
136 this.socket
= Socks
.connect({
137 host
: this.irc_host
.hostname
,
138 port
: this.irc_host
.port
,
140 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
141 }, {host
: this.socks
.host
,
142 port
: this.socks
.port
,
143 user
: this.socks
.user
,
144 pass
: this.socks
.pass
147 } else if (this.ssl
) {
148 this.socket
= tls
.connect({
149 host
: this.irc_host
.hostname
,
150 port
: this.irc_host
.port
,
151 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
154 socket_connect_event_name
= 'secureConnect';
157 this.socket
= net
.connect({
158 host
: this.irc_host
.hostname
,
159 port
: this.irc_host
.port
163 this.socket
.on(socket_connect_event_name
, function () {
164 that
.connected
= true;
165 socketConnectHandler
.call(that
);
168 this.socket
.on('error', function (event
) {
169 that
.emit('error', event
);
172 this.socket
.on('data', function () {
173 parse
.apply(that
, arguments
);
176 this.socket
.on('close', function (had_error
) {
177 that
.connected
= false;
180 // Close the whole socket down
181 that
.disposeSocket();
186 * Send an event to the client
188 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
189 data
.server
= this.con_num
;
190 this.state
.sendIrcCommand(event_name
, data
, callback
);
194 * Write a line of data to the IRCd
196 IrcConnection
.prototype.write = function (data
, callback
) {
197 //ENCODE string to encoding of the server
198 encoded_buffer
= iconv
.encode(data
+ '\r\n', this.encoding
);
199 this.socket
.write(encoded_buffer
);
205 * Close the connection to the IRCd after sending one last line
207 IrcConnection
.prototype.end = function (data
, callback
) {
217 * Clean up this IrcConnection instance and any sockets
219 IrcConnection
.prototype.dispose = function () {
222 _
.each(this.irc_users
, function (user
) {
225 _
.each(this.irc_channels
, function (chan
) {
228 this.irc_users
= undefined;
229 this.irc_channels
= undefined;
231 this.server
.dispose();
232 this.server
= undefined;
234 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
236 // If we're still connected, wait until the socket is closed before disposing
237 // so that all the events are still correctly triggered
238 if (this.socket
&& this.connected
) {
239 this.socket
.once('close', function() {
240 that
.disposeSocket();
241 that
.removeAllListeners();
247 this.disposeSocket();
248 this.removeAllListeners();
255 * Clean up any sockets for this IrcConnection
257 IrcConnection
.prototype.disposeSocket = function () {
260 this.socket
.removeAllListeners();
266 * Set a new encoding for this connection
267 * Return true in case of success
270 IrcConnection
.prototype.setEncoding = function (encoding
) {
274 encoded_test
= iconv
.encode("TEST", encoding
);
275 //This test is done to check if this encoding also supports
276 //the ASCII charset required by the IRC protocols
277 //(Avoid the use of base64 or incompatible encodings)
278 if (encoded_test
== "TEST") {
279 this.encoding
= encoding
;
289 function onChannelJoin(event
) {
292 // Only deal with ourselves joining a channel
293 if (event
.nick
!== this.nick
)
296 // We should only ever get a JOIN command for a channel
297 // we're not already a member of.. but check we don't
298 // have this channel in case something went wrong somewhere
299 // at an earlier point
300 if (!this.irc_channels
[event
.channel
]) {
301 chan
= new IrcChannel(this, event
.channel
);
302 this.irc_channels
[event
.channel
] = chan
;
303 chan
.irc_events
.join
.call(chan
, event
);
308 function onServerConnect(event
) {
309 this.nick
= event
.nick
;
313 function onUserPrivmsg(event
) {
316 // Only deal with messages targetted to us
317 if (event
.channel
!== this.nick
)
320 if (!this.irc_users
[event
.nick
]) {
321 user
= new IrcUser(this, event
.nick
);
322 this.irc_users
[event
.nick
] = user
;
323 user
.irc_events
.privmsg
.call(user
, event
);
328 function onUserNick(event
) {
331 // Only deal with messages targetted to us
332 if (event
.nick
!== this.nick
)
335 this.nick
= event
.newnick
;
339 function onUserParts(event
) {
340 // Only deal with ourselves leaving a channel
341 if (event
.nick
!== this.nick
)
344 if (this.irc_channels
[event
.channel
]) {
345 this.irc_channels
[event
.channel
].dispose();
346 delete this.irc_channels
[event
.channel
];
350 function onUserKick(event
){
351 // Only deal with ourselves being kicked from a channel
352 if (event
.kicked
!== this.nick
)
355 if (this.irc_channels
[event
.channel
]) {
356 this.irc_channels
[event
.channel
].dispose();
357 delete this.irc_channels
[event
.channel
];
366 * Handle the socket connect event, starting the IRCd registration
368 var socketConnectHandler = function () {
372 // Build up data to be used for webirc/etc detection
376 // Array of lines to be sent to the IRCd before anything else
380 // Let the webirc/etc detection modify any required parameters
381 connect_data
= findWebIrc
.call(this, connect_data
);
383 global
.modules
.emit('irc authorize', connect_data
).done(function () {
384 // Send any initial data for webirc/etc
385 if (connect_data
.prepend_data
) {
386 _
.each(connect_data
.prepend_data
, function(data
) {
391 that
.write('CAP LS');
394 that
.write('PASS ' + that
.password
);
396 that
.write('NICK ' + that
.nick
);
397 that
.write('USER ' + that
.username
+ ' 0 0 :' + '[www.kiwiirc.com] ' + that
.nick
);
399 that
.emit('connected');
406 * Load any WEBIRC or alternative settings for this connection
407 * Called in scope of the IrcConnection instance
409 function findWebIrc(connect_data
) {
410 var webirc_pass
= global
.config
.webirc_pass
,
411 ip_as_username
= global
.config
.ip_as_username
,
415 // Do we have a WEBIRC password for this?
416 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
417 // Build the WEBIRC line to be sent before IRC registration
418 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
419 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
421 connect_data
.prepend_data
= [tmp
];
425 // Check if we need to pass the users IP as its username/ident
426 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
427 // Get a hex value of the clients IP
428 this.username
= this.user
.address
.split('.').map(function(i
, idx
){
429 var hex
= parseInt(i
, 10).toString(16);
431 // Pad out the hex value if it's a single char
432 if (hex
.length
=== 1)
446 * The regex that parses a line of data from the IRCd
447 * Deviates from the RFC a little to support the '/' character now used in some
450 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;
452 var parse = function (data
) {
461 //DECODE server encoding
462 data
= iconv
.decode(data
, this.encoding
);
464 if (this.hold_last
&& this.held_data
!== '') {
465 data
= this.held_data
+ data
;
466 this.hold_last
= false;
470 // If the last line is incomplete, hold it until we have more data
471 if (data
.substr(-1) !== '\n') {
472 this.hold_last
= true;
475 // Process our data line by line
476 data
= data
.split("\n");
477 for (i
= 0; i
< data
.length
; i
++) {
480 // If flagged to hold the last line, store it and move on
481 if (this.hold_last
&& (i
=== data
.length
- 1)) {
482 this.held_data
= data
[i
];
486 // Parse the complete line, removing any carriage returns
487 msg
= parse_regex
.exec(data
[i
].replace(/^\r+|\r+$/, ''));
491 tags
= msg
[1].split(';');
492 for (j
= 0; j
< tags
.length
; j
++) {
493 tag
= tags
[j
].split('=');
494 tags
[j
] = {tag
: tag
[0], value
: tag
[1]};
502 hostname
: msg
[5] || '',
504 params
: msg
[7] || '',
505 trailing
: (msg
[8]) ? msg
[8].trim() : ''
507 msg
.params
= msg
.params
.split(' ');
508 this.irc_commands
.dispatch(msg
.command
.toUpperCase(), msg
);
510 // The line was not parsed correctly, must be malformed
511 console
.log("Malformed IRC line: " + data
[i
].replace(/^\r+|\r+$/, ''));