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'),
13 // Break the Node.js version down into usable parts
14 var version_values
= process
.version
.substr(1).split('.').map(function (item
) {
15 return parseInt(item
, 10);
18 // If we have a suitable Nodejs version, bring int he socks functionality
19 if (version_values
[1] >= 10) {
20 Socks
= require('socksjs');
23 var IrcConnection = function (hostname
, port
, ssl
, nick
, user
, pass
, state
) {
30 this.setMaxListeners(0);
33 this.connected
= false;
35 // If registeration with the IRCd has completed
36 this.registered
= false;
38 // If we are in the CAP negotiation stage
39 this.cap_negotiation
= true;
43 this.user
= user
; // Contains users real hostname and address
44 this.username
= this.nick
.replace(/[^0-9a-zA-Z\-_.\/]/, '');
51 this.server
= new IrcServer(this, hostname
, port
);
54 this.irc_users
= Object
.create(null);
56 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
57 this.irc_users
[this.nick
] = new IrcUser(this, '*');
60 this.irc_channels
= Object
.create(null);
62 // IRC connection information
63 this.irc_host
= {hostname
: hostname
, port
: port
};
66 // SOCKS proxy details
67 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
68 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
)))) {
70 host
: global
.config
.socks_proxy
.address
,
71 port
: global
.config
.socks_proxy
.port
,
72 user
: global
.config
.socks_proxy
.user
,
73 pass
: global
.config
.socks_proxy
.pass
79 // Options sent by the IRCd
80 this.options
= Object
.create(null);
81 this.cap
= {requested
: [], enabled
: []};
83 // Is SASL supported on the IRCd
86 // Buffers for data sent from the IRCd
87 this.hold_last
= false;
90 this.applyIrcEvents();
92 // Call any modules before making the connection
93 global
.modules
.emit('irc connecting', {connection
: this})
98 util
.inherits(IrcConnection
, EE
);
100 module
.exports
.IrcConnection
= IrcConnection
;
104 IrcConnection
.prototype.applyIrcEvents = function () {
105 // Listen for events on the IRC connection
107 'server * connect': onServerConnect
,
108 'channel * join': onChannelJoin
,
110 // TODO: uncomment when using an IrcUser per nick
111 //'user:*:privmsg': onUserPrivmsg,
112 'user * nick': onUserNick
,
113 'channel * part': onUserParts
,
114 'channel * quit': onUserParts
,
115 'channel * kick': onUserKick
118 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
123 * Start the connection to the IRCd
125 IrcConnection
.prototype.connect = function () {
129 // The socket connect event to listener for
130 var socket_connect_event_name
= 'connect';
133 // Make sure we don't already have an open connection
134 this.disposeSocket();
136 // Are we connecting through a SOCKS proxy?
138 this.socket
= Socks
.connect({
139 host
: this.irc_host
.hostname
,
140 port
: this.irc_host
.port
,
142 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
143 }, {host
: this.socks
.host
,
144 port
: this.socks
.port
,
145 user
: this.socks
.user
,
146 pass
: this.socks
.pass
149 } else if (this.ssl
) {
150 this.socket
= tls
.connect({
151 host
: this.irc_host
.hostname
,
152 port
: this.irc_host
.port
,
153 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
156 socket_connect_event_name
= 'secureConnect';
159 this.socket
= net
.connect({
160 host
: this.irc_host
.hostname
,
161 port
: this.irc_host
.port
165 this.socket
.on(socket_connect_event_name
, function () {
166 that
.connected
= true;
167 socketConnectHandler
.call(that
);
170 this.socket
.setEncoding('utf-8');
172 this.socket
.on('error', function (event
) {
173 that
.emit('error', event
);
176 this.socket
.on('data', function () {
177 parse
.apply(that
, arguments
);
180 this.socket
.on('close', function (had_error
) {
181 that
.connected
= false;
184 // Close the whole socket down
185 that
.disposeSocket();
190 * Send an event to the client
192 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
193 data
.server
= this.con_num
;
194 this.state
.sendIrcCommand(event_name
, data
, callback
);
198 * Write a line of data to the IRCd
200 IrcConnection
.prototype.write = function (data
, callback
) {
201 this.socket
.write(data
+ '\r\n', 'utf-8', callback
);
207 * Close the connection to the IRCd after sending one last line
209 IrcConnection
.prototype.end = function (data
, callback
) {
219 * Clean up this IrcConnection instance and any sockets
221 IrcConnection
.prototype.dispose = function () {
224 _
.each(this.irc_users
, function (user
) {
227 _
.each(this.irc_channels
, function (chan
) {
230 this.irc_users
= undefined;
231 this.irc_channels
= undefined;
233 this.server
.dispose();
234 this.server
= undefined;
236 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
238 // If we're still connected, wait until the socket is closed before disposing
239 // so that all the events are still correctly triggered
240 if (this.socket
&& this.connected
) {
241 this.socket
.once('close', function() {
242 that
.disposeSocket();
243 that
.removeAllListeners();
249 this.disposeSocket();
250 this.removeAllListeners();
257 * Clean up any sockets for this IrcConnection
259 IrcConnection
.prototype.disposeSocket = function () {
262 this.socket
.removeAllListeners();
269 function onChannelJoin(event
) {
272 // Only deal with ourselves joining a channel
273 if (event
.nick
!== this.nick
)
276 // We should only ever get a JOIN command for a channel
277 // we're not already a member of.. but check we don't
278 // have this channel in case something went wrong somewhere
279 // at an earlier point
280 if (!this.irc_channels
[event
.channel
]) {
281 chan
= new IrcChannel(this, event
.channel
);
282 this.irc_channels
[event
.channel
] = chan
;
283 chan
.irc_events
.join
.call(chan
, event
);
288 function onServerConnect(event
) {
289 this.nick
= event
.nick
;
293 function onUserPrivmsg(event
) {
296 // Only deal with messages targetted to us
297 if (event
.channel
!== this.nick
)
300 if (!this.irc_users
[event
.nick
]) {
301 user
= new IrcUser(this, event
.nick
);
302 this.irc_users
[event
.nick
] = user
;
303 user
.irc_events
.privmsg
.call(user
, event
);
308 function onUserNick(event
) {
311 // Only deal with messages targetted to us
312 if (event
.nick
!== this.nick
)
315 this.nick
= event
.newnick
;
319 function onUserParts(event
) {
320 // Only deal with ourselves leaving a channel
321 if (event
.nick
!== this.nick
)
324 if (this.irc_channels
[event
.channel
]) {
325 this.irc_channels
[event
.channel
].dispose();
326 delete this.irc_channels
[event
.channel
];
330 function onUserKick(event
){
331 // Only deal with ourselves being kicked from a channel
332 if (event
.kicked
!== this.nick
)
335 if (this.irc_channels
[event
.channel
]) {
336 this.irc_channels
[event
.channel
].dispose();
337 delete this.irc_channels
[event
.channel
];
346 * Handle the socket connect event, starting the IRCd registration
348 var socketConnectHandler = function () {
352 // Build up data to be used for webirc/etc detection
356 // Array of lines to be sent to the IRCd before anything else
360 // Let the webirc/etc detection modify any required parameters
361 connect_data
= findWebIrc
.call(this, connect_data
);
363 global
.modules
.emit('irc authorize', connect_data
).done(function () {
364 // Send any initial data for webirc/etc
365 if (connect_data
.prepend_data
) {
366 _
.each(connect_data
.prepend_data
, function(data
) {
371 that
.write('CAP LS');
374 that
.write('PASS ' + that
.password
);
376 that
.write('NICK ' + that
.nick
);
377 that
.write('USER ' + that
.username
+ ' 0 0 :' + '[www.kiwiirc.com] ' + that
.nick
);
379 that
.emit('connected');
386 * Load any WEBIRC or alternative settings for this connection
387 * Called in scope of the IrcConnection instance
389 function findWebIrc(connect_data
) {
390 var webirc_pass
= global
.config
.webirc_pass
,
391 ip_as_username
= global
.config
.ip_as_username
,
395 // Do we have a WEBIRC password for this?
396 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
397 // Build the WEBIRC line to be sent before IRC registration
398 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
399 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
401 connect_data
.prepend_data
= [tmp
];
405 // Check if we need to pass the users IP as its username/ident
406 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
407 // Get a hex value of the clients IP
408 this.username
= this.user
.address
.split('.').map(function(i
, idx
){
409 var hex
= parseInt(i
, 10).toString(16);
411 // Pad out the hex value if it's a single char
412 if (hex
.length
=== 1)
426 * The regex that parses a line of data from the IRCd
427 * Deviates from the RFC a little to support the '/' character now used in some
430 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;
432 var parse = function (data
) {
441 if (this.hold_last
&& this.held_data
!== '') {
442 data
= this.held_data
+ data
;
443 this.hold_last
= false;
447 // If the last line is incomplete, hold it until we have more data
448 if (data
.substr(-1) !== '\n') {
449 this.hold_last
= true;
452 // Process our data line by line
453 data
= data
.split("\n");
454 for (i
= 0; i
< data
.length
; i
++) {
457 // If flagged to hold the last line, store it and move on
458 if (this.hold_last
&& (i
=== data
.length
- 1)) {
459 this.held_data
= data
[i
];
463 // Parse the complete line, removing any carriage returns
464 msg
= parse_regex
.exec(data
[i
].replace(/^\r+|\r+$/, ''));
468 tags
= msg
[1].split(';');
469 for (j
= 0; j
< tags
.length
; j
++) {
470 tag
= tags
[j
].split('=');
471 tags
[j
] = {tag
: tag
[0], value
: tag
[1]};
479 hostname
: msg
[5] || '',
481 params
: msg
[7] || '',
482 trailing
: (msg
[8]) ? msg
[8].trim() : ''
484 msg
.params
= msg
.params
.split(' ');
485 this.irc_commands
.dispatch(msg
.command
.toUpperCase(), msg
);
487 // The line was not parsed correctly, must be malformed
488 console
.log("Malformed IRC line: " + data
[i
].replace(/^\r+|\r+$/, ''));