Correctly disposing IrcConnection
[KiwiIRC.git] / server / irc / connection.js
CommitLineData
cefa0900
JA
1var net = require('net'),
2 tls = require('tls'),
3 util = require('util'),
b156e01a 4 dns = require('dns'),
cefa0900 5 _ = require('lodash'),
4c25c0d7 6 EventBinder = require('./eventbinder.js'),
cefa0900 7 IrcServer = require('./server.js'),
cced0091 8 IrcCommands = require('./commands.js'),
cefa0900 9 IrcChannel = require('./channel.js'),
9650b343 10 IrcUser = require('./user.js'),
2abb4615 11 EE = require('../ee.js'),
1a452a02 12 iconv = require('iconv-lite'),
55ccaf50 13 Socks;
32a09dc1
D
14
15
55ccaf50
JA
16// Break the Node.js version down into usable parts
17var version_values = process.version.substr(1).split('.').map(function (item) {
18 return parseInt(item, 10);
19});
9de636f9 20
55ccaf50 21// If we have a suitable Nodejs version, bring int he socks functionality
9de636f9 22if (version_values[1] >= 10) {
3b259b15 23 Socks = require('socksjs');
55ccaf50 24}
db8af19d 25
cced0091 26var IrcConnection = function (hostname, port, ssl, nick, user, pass, state, con_num) {
2a8e95d1 27 var that = this;
4c25c0d7 28
2abb4615 29 EE.call(this,{
cefa0900 30 wildcard: true,
d9285da9 31 delimiter: ' '
cefa0900 32 });
4c25c0d7 33 this.setMaxListeners(0);
32a09dc1 34
d1b3e8b3 35 // Set the first configured encoding as the default encoding
3efb4f33 36 this.encoding = global.config.default_encoding;
d1b3e8b3 37
db8af19d 38 // Socket state
63008d5e 39 this.connected = false;
db8af19d 40
fc1c21b8
D
41 // IRCd write buffers (flood controll)
42 this.write_buffer = [];
43
44 // In process of writing the buffer?
45 this.writing_buffer = false;
46
47 // Max number of lines to write a second
48 this.write_buffer_lines_second = 2;
49
db8af19d 50 // If registeration with the IRCd has completed
63008d5e 51 this.registered = false;
db8af19d
D
52
53 // If we are in the CAP negotiation stage
63008d5e 54 this.cap_negotiation = true;
db8af19d
D
55
56 // User information
63008d5e
D
57 this.nick = nick;
58 this.user = user; // Contains users real hostname and address
5973d01c 59 this.username = this.nick.replace(/[^0-9a-zA-Z\-_.\/]/, '');
db8af19d 60 this.password = pass;
32a09dc1 61
b09157de
JA
62 // State object
63 this.state = state;
32a09dc1 64
cced0091
D
65 // Connection ID in the state
66 this.con_num = con_num;
67
68 // IRC protocol handling
69 this.irc_commands = new IrcCommands(this);
70
cefa0900
JA
71 // IrcServer object
72 this.server = new IrcServer(this, hostname, port);
32a09dc1 73
cefa0900
JA
74 // IrcUser objects
75 this.irc_users = Object.create(null);
efe9d487
D
76
77 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
78 this.irc_users[this.nick] = new IrcUser(this, '*');
79
cefa0900
JA
80 // IrcChannel objects
81 this.irc_channels = Object.create(null);
db8af19d
D
82
83 // IRC connection information
63008d5e
D
84 this.irc_host = {hostname: hostname, port: port};
85 this.ssl = !(!ssl);
32a09dc1 86
9650b343 87 // SOCKS proxy details
ac0b278c
JA
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)))) {
90 this.socks = {
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
95 };
96 } else {
97 this.socks = false;
98 }
db8af19d
D
99
100 // Options sent by the IRCd
63008d5e
D
101 this.options = Object.create(null);
102 this.cap = {requested: [], enabled: []};
db8af19d
D
103
104 // Is SASL supported on the IRCd
63008d5e 105 this.sasl = false;
32a09dc1 106
db8af19d 107 // Buffers for data sent from the IRCd
63008d5e
D
108 this.hold_last = false;
109 this.held_data = '';
110
4c25c0d7 111 this.applyIrcEvents();
63008d5e 112};
2abb4615 113util.inherits(IrcConnection, EE);
63008d5e
D
114
115module.exports.IrcConnection = IrcConnection;
116
f9ff7686 117
db8af19d 118
4c25c0d7
D
119IrcConnection.prototype.applyIrcEvents = function () {
120 // Listen for events on the IRC connection
121 this.irc_events = {
d9285da9
JA
122 'server * connect': onServerConnect,
123 'channel * join': onChannelJoin,
df6d68a5
D
124
125 // TODO: uncomment when using an IrcUser per nick
126 //'user:*:privmsg': onUserPrivmsg,
d9285da9
JA
127 'user * nick': onUserNick,
128 'channel * part': onUserParts,
129 'channel * quit': onUserParts,
130 'channel * kick': onUserKick
4c25c0d7
D
131 };
132
133 EventBinder.bindIrcEvents('', this.irc_events, this, this);
134};
135
db8af19d
D
136
137/**
138 * Start the connection to the IRCd
139 */
63008d5e 140IrcConnection.prototype.connect = function () {
7496de01 141 var that = this;
63008d5e 142
db8af19d
D
143 // The socket connect event to listener for
144 var socket_connect_event_name = 'connect';
145
7496de01
D
146 // The destination address
147 var dest_addr = this.socks ?
148 this.socks.host :
149 this.irc_host.hostname;
db8af19d
D
150
151 // Make sure we don't already have an open connection
152 this.disposeSocket();
153
7496de01
D
154 // Get the IP family for the dest_addr (either socks or IRCd destination)
155 getConnectionFamily(dest_addr, function (err, family, host) {
156 var outgoing;
157
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)) {
b156e01a
JA
161 outgoing = global.config.outgoing_address.IPv6;
162 } else {
7496de01 163 outgoing = global.config.outgoing_address.IPv4 || '0.0.0.0';
ddae94f5
D
164
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
168 host = dest_addr;
b156e01a 169 }
7496de01
D
170
171 } else {
172 // No config was found so use the default
173 outgoing = '0.0.0.0';
174 }
175
176 // Are we connecting through a SOCKS proxy?
177 if (this.socks) {
b156e01a 178 that.socket = Socks.connect({
ddae94f5 179 host: host,
b156e01a
JA
180 port: that.irc_host.port,
181 ssl: that.ssl,
182 rejectUnauthorized: global.config.reject_unauthorised_certificates
7496de01 183 }, {host: that.socks.host,
b156e01a
JA
184 port: that.socks.port,
185 user: that.socks.user,
186 pass: that.socks.pass,
187 localAddress: outgoing
188 });
189
7496de01
D
190 } else {
191 // No socks connection, connect directly to the IRCd
b156e01a
JA
192
193 if (that.ssl) {
194 that.socket = tls.connect({
ddae94f5 195 host: host,
b156e01a
JA
196 port: that.irc_host.port,
197 rejectUnauthorized: global.config.reject_unauthorised_certificates,
198 localAddress: outgoing
199 });
200
201 socket_connect_event_name = 'secureConnect';
202
203 } else {
204 that.socket = net.connect({
205 host: host,
206 port: that.irc_host.port,
207 localAddress: outgoing
208 });
209 }
7496de01 210 }
b156e01a 211
7496de01
D
212 // Apply the socket listeners
213 that.socket.on(socket_connect_event_name, function () {
9e225dc6
D
214
215 // SSL connections have the actual socket as a property
216 var socket = (typeof this.socket !== 'undefined') ?
217 this.socket :
218 this;
219
b156e01a 220 that.connected = true;
cc3c5d04
D
221
222 // Make note of the port numbers for any identd lookups
223 // Nodejs < 0.9.6 has no socket.localPort so check this first
9e225dc6
D
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;
cc3c5d04
D
227 }
228
b156e01a
JA
229 socketConnectHandler.call(that);
230 });
32a09dc1 231
7496de01 232 that.socket.on('error', function (event) {
b156e01a
JA
233 that.emit('error', event);
234 });
32a09dc1 235
7496de01 236 that.socket.on('data', function () {
b156e01a
JA
237 parse.apply(that, arguments);
238 });
32a09dc1 239
7496de01 240 that.socket.on('close', function (had_error) {
b156e01a 241 that.connected = false;
cc3c5d04
D
242
243 // Remove this socket form the identd lookup
9e225dc6
D
244 if (that.identd_port_pair) {
245 delete global.clients.port_pairs[that.identd_port_pair];
cc3c5d04
D
246 }
247
b156e01a 248 that.emit('close');
db8af19d 249
b156e01a
JA
250 // Close the whole socket down
251 that.disposeSocket();
252 });
7496de01 253 });
2a8e95d1 254};
2a8e95d1 255
3c91bff8
JA
256/**
257 * Send an event to the client
258 */
259IrcConnection.prototype.clientEvent = function (event_name, data, callback) {
260 data.server = this.con_num;
261 this.state.sendIrcCommand(event_name, data, callback);
262};
db8af19d
D
263
264/**
265 * Write a line of data to the IRCd
266 */
2a8e95d1 267IrcConnection.prototype.write = function (data, callback) {
1a452a02 268 //ENCODE string to encoding of the server
d1b3e8b3 269 encoded_buffer = iconv.encode(data + '\r\n', this.encoding);
fc1c21b8
D
270
271 this.write_buffer.push(encoded_buffer);
272
273 // Only flush if we're not writing already
274 if (!this.writing_buffer)
275 this.flushWriteBuffer();
276};
277
278
279
280/**
281 * Flush the write buffer to the server in a throttled fashion
282 */
283IrcConnection.prototype.flushWriteBuffer = function () {
284 this.writing_buffer = true;
285
286 // Disabled write buffer? Send everything we have
287 if (!this.write_buffer_lines_second) {
288 console.log('write buffer disabled');
289 this.write_buffer.forEach(function(buffer, idx) {
290 this.socket.write(buffer);
291 this.write_buffer = null;
292 });
293
294 this.write_buffer = [];
295 this.writing_buffer = false;
296
297 return;
298 }
299
300 // Nothing to write? Stop writing and leave
301 if (this.write_buffer.length === 0) {
302 this.writing_buffer = false;
303 return;
304 }
305
306 this.socket.write(this.write_buffer[0]);
307 this.write_buffer = this.write_buffer.slice(1);
308
309 // Call this function again at some point
310 setTimeout(this.flushWriteBuffer.bind(this), 1000 / this.write_buffer_lines_second);
2a8e95d1
D
311};
312
db8af19d
D
313
314
315/**
316 * Close the connection to the IRCd after sending one last line
317 */
2a8e95d1 318IrcConnection.prototype.end = function (data, callback) {
db8af19d
D
319 if (data)
320 this.write(data);
32a09dc1 321
db8af19d 322 this.socket.end();
2a8e95d1
D
323};
324
db8af19d
D
325
326
327/**
328 * Clean up this IrcConnection instance and any sockets
329 */
c08717da 330IrcConnection.prototype.dispose = function () {
5e211c3d
D
331 var that = this;
332
a787f79f
D
333 // If we're still connected, wait until the socket is closed before disposing
334 // so that all the events are still correctly triggered
335 if (this.socket && this.connected) {
336 this.socket.end();
337 return;
338 }
339
340 if (this.socket) {
341 this.disposeSocket();
342 this.removeAllListeners();
343 }
344
cefa0900
JA
345 _.each(this.irc_users, function (user) {
346 user.dispose();
347 });
348 _.each(this.irc_channels, function (chan) {
349 chan.dispose();
350 });
ebe178d6
D
351 this.irc_users = undefined;
352 this.irc_channels = undefined;
353
354 this.server.dispose();
355 this.server = undefined;
4c25c0d7 356
a787f79f 357 this.irc_commands = undefined;
4c25c0d7 358
a787f79f 359 EventBinder.unbindIrcEvents('', this.irc_events, this);
5e211c3d 360
c08717da
D
361};
362
363
2a8e95d1 364
db8af19d
D
365/**
366 * Clean up any sockets for this IrcConnection
367 */
368IrcConnection.prototype.disposeSocket = function () {
369 if (this.socket) {
6b8fa7a6 370 this.socket.end();
db8af19d
D
371 this.socket.removeAllListeners();
372 this.socket = null;
373 }
2a8e95d1
D
374};
375
d1b3e8b3
VDF
376/**
377 * Set a new encoding for this connection
378 * Return true in case of success
379 */
380
381IrcConnection.prototype.setEncoding = function (encoding) {
3ddc135a
D
382 var encoded_test;
383
3efb4f33
VDF
384 try {
385 encoded_test = iconv.encode("TEST", encoding);
386 //This test is done to check if this encoding also supports
387 //the ASCII charset required by the IRC protocols
388 //(Avoid the use of base64 or incompatible encodings)
389 if (encoded_test == "TEST") {
390 this.encoding = encoding;
391 return true;
392 }
393 return false;
394 } catch (err) {
395 return false;
65c5a477 396 }
d1b3e8b3 397};
2a8e95d1 398
b156e01a
JA
399function getConnectionFamily(host, callback) {
400 if (net.isIP(host)) {
401 if (net.isIPv4(host)) {
402 setImmediate(callback, null, 'IPv4', host);
403 } else {
404 setImmediate(callback, null, 'IPv6', host);
405 }
406 } else {
407 dns.resolve6(host, function (err, addresses) {
408 if (!err) {
409 callback(null, 'IPv6', addresses[0]);
410 } else {
411 dns.resolve4(host, function (err, addresses) {
412 if (!err) {
413 callback(null, 'IPv4',addresses[0]);
414 } else {
415 callback(err);
416 }
417 });
418 }
419 });
420 }
421}
422
db8af19d 423
4c25c0d7
D
424function onChannelJoin(event) {
425 var chan;
426
427 // Only deal with ourselves joining a channel
428 if (event.nick !== this.nick)
429 return;
430
431 // We should only ever get a JOIN command for a channel
432 // we're not already a member of.. but check we don't
433 // have this channel in case something went wrong somewhere
434 // at an earlier point
435 if (!this.irc_channels[event.channel]) {
436 chan = new IrcChannel(this, event.channel);
437 this.irc_channels[event.channel] = chan;
438 chan.irc_events.join.call(chan, event);
439 }
440}
441
442
443function onServerConnect(event) {
444 this.nick = event.nick;
4c25c0d7
D
445}
446
447
448function onUserPrivmsg(event) {
449 var user;
450
451 // Only deal with messages targetted to us
452 if (event.channel !== this.nick)
453 return;
454
455 if (!this.irc_users[event.nick]) {
456 user = new IrcUser(this, event.nick);
457 this.irc_users[event.nick] = user;
458 user.irc_events.privmsg.call(user, event);
459 }
460}
461
462
9be602fc
D
463function onUserNick(event) {
464 var user;
465
466 // Only deal with messages targetted to us
467 if (event.nick !== this.nick)
468 return;
469
470 this.nick = event.newnick;
471}
472
473
4c25c0d7
D
474function onUserParts(event) {
475 // Only deal with ourselves leaving a channel
476 if (event.nick !== this.nick)
477 return;
478
479 if (this.irc_channels[event.channel]) {
480 this.irc_channels[event.channel].dispose();
481 delete this.irc_channels[event.channel];
482 }
483}
484
6d2df752
MC
485function onUserKick(event){
486 // Only deal with ourselves being kicked from a channel
487 if (event.kicked !== this.nick)
488 return;
489
490 if (this.irc_channels[event.channel]) {
491 this.irc_channels[event.channel].dispose();
492 delete this.irc_channels[event.channel];
493 }
494
495}
496
4c25c0d7
D
497
498
499
db8af19d
D
500/**
501 * Handle the socket connect event, starting the IRCd registration
502 */
503var socketConnectHandler = function () {
15fefff7
D
504 var that = this,
505 connect_data;
506
507 // Build up data to be used for webirc/etc detection
508 connect_data = {
bd7196e1
D
509 connection: this,
510
511 // Array of lines to be sent to the IRCd before anything else
512 prepend_data: []
15fefff7
D
513 };
514
515 // Let the webirc/etc detection modify any required parameters
266b5087 516 connect_data = findWebIrc.call(this, connect_data);
15fefff7 517
d9285da9 518 global.modules.emit('irc authorize', connect_data).done(function () {
bd7196e1
D
519 // Send any initial data for webirc/etc
520 if (connect_data.prepend_data) {
521 _.each(connect_data.prepend_data, function(data) {
522 that.write(data);
523 });
524 }
525
526 that.write('CAP LS');
527
db8af19d 528 if (that.password)
bd7196e1 529 that.write('PASS ' + that.password);
32a09dc1 530
bd7196e1
D
531 that.write('NICK ' + that.nick);
532 that.write('USER ' + that.username + ' 0 0 :' + '[www.kiwiirc.com] ' + that.nick);
32a09dc1 533
bd7196e1
D
534 that.emit('connected');
535 });
7dfe47c6 536};
2a8e95d1 537
15fefff7 538
db8af19d
D
539
540/**
541 * Load any WEBIRC or alternative settings for this connection
542 * Called in scope of the IrcConnection instance
543 */
15fefff7 544function findWebIrc(connect_data) {
db8af19d
D
545 var webirc_pass = global.config.webirc_pass,
546 ip_as_username = global.config.ip_as_username,
547 tmp;
548
15fefff7
D
549
550 // Do we have a WEBIRC password for this?
bd7196e1 551 if (webirc_pass && webirc_pass[this.irc_host.hostname]) {
db8af19d 552 // Build the WEBIRC line to be sent before IRC registration
bd7196e1
D
553 tmp = 'WEBIRC ' + webirc_pass[this.irc_host.hostname] + ' KiwiIRC ';
554 tmp += this.user.hostname + ' ' + this.user.address;
db8af19d 555
15fefff7
D
556 connect_data.prepend_data = [tmp];
557 }
558
559
560 // Check if we need to pass the users IP as its username/ident
bd7196e1 561 if (ip_as_username && ip_as_username.indexOf(this.irc_host.hostname) > -1) {
15fefff7 562 // Get a hex value of the clients IP
bd7196e1 563 this.username = this.user.address.split('.').map(function(i, idx){
32800bf5
D
564 var hex = parseInt(i, 10).toString(16);
565
566 // Pad out the hex value if it's a single char
567 if (hex.length === 1)
568 hex = '0' + hex;
569
570 return hex;
15fefff7
D
571 }).join('');
572
573 }
574
575 return connect_data;
576}
577
578
579
db8af19d
D
580/**
581 * The regex that parses a line of data from the IRCd
582 * Deviates from the RFC a little to support the '/' character now used in some
583 * IRCds
584 */
85e1be6c 585var parse_regex = /^(?:(?:(?:(@[^ ]+) )?):(?:([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)|([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)!([^\x00\r\n\ ]+?)@?([a-z0-9\.\-:\/_]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.+))?$/i;
db8af19d 586
2a8e95d1
D
587var parse = function (data) {
588 var i,
589 msg,
16e717f5
JA
590 msg2,
591 trm,
592 j,
593 tags = [],
594 tag;
3ec786bc 595
1a452a02 596 //DECODE server encoding
d1b3e8b3 597 data = iconv.decode(data, this.encoding);
d1b3e8b3 598
db8af19d 599 if (this.hold_last && this.held_data !== '') {
2a8e95d1
D
600 data = this.held_data + data;
601 this.hold_last = false;
602 this.held_data = '';
603 }
db8af19d
D
604
605 // If the last line is incomplete, hold it until we have more data
2a8e95d1
D
606 if (data.substr(-1) !== '\n') {
607 this.hold_last = true;
608 }
db8af19d
D
609
610 // Process our data line by line
2a8e95d1
D
611 data = data.split("\n");
612 for (i = 0; i < data.length; i++) {
db8af19d
D
613 if (!data[i]) break;
614
615 // If flagged to hold the last line, store it and move on
616 if (this.hold_last && (i === data.length - 1)) {
617 this.held_data = data[i];
618 break;
619 }
1a452a02 620
db8af19d
D
621 // Parse the complete line, removing any carriage returns
622 msg = parse_regex.exec(data[i].replace(/^\r+|\r+$/, ''));
2a8e95d1 623
db8af19d
D
624 if (msg) {
625 if (msg[1]) {
626 tags = msg[1].split(';');
627 for (j = 0; j < tags.length; j++) {
628 tag = tags[j].split('=');
629 tags[j] = {tag: tag[0], value: tag[1]};
16e717f5 630 }
2a8e95d1 631 }
db8af19d
D
632 msg = {
633 tags: tags,
634 prefix: msg[2],
635 nick: msg[3],
636 ident: msg[4],
637 hostname: msg[5] || '',
638 command: msg[6],
639 params: msg[7] || '',
640 trailing: (msg[8]) ? msg[8].trim() : ''
641 };
642 msg.params = msg.params.split(' ');
3ec786bc 643 this.irc_commands.dispatch(msg.command.toUpperCase(), msg);
db8af19d 644 } else {
db8af19d
D
645 // The line was not parsed correctly, must be malformed
646 console.log("Malformed IRC line: " + data[i].replace(/^\r+|\r+$/, ''));
2a8e95d1
D
647 }
648 }
649};