Working proxy sockets
[KiwiIRC.git] / server / irc / connection.js
1 var net = require('net'),
2 tls = require('tls'),
3 util = require('util'),
4 dns = require('dns'),
5 _ = require('lodash'),
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'),
14 Socks;
15
16
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);
20 });
21
22 // If we have a suitable Nodejs version, bring int he socks functionality
23 if (version_values[1] >= 10) {
24 Socks = require('socksjs');
25 }
26
27 var IrcConnection = function (hostname, port, ssl, nick, user, options, state, con_num) {
28 var that = this;
29
30 EE.call(this,{
31 wildcard: true,
32 delimiter: ' '
33 });
34 this.setMaxListeners(0);
35
36 options = options || {};
37
38 // Socket state
39 this.connected = false;
40
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
50 // If registeration with the IRCd has completed
51 this.registered = false;
52
53 // If we are in the CAP negotiation stage
54 this.cap_negotiation = true;
55
56 // User information
57 this.nick = nick;
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 || '';
61
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);
65 }
66
67 // State object
68 this.state = state;
69
70 // Connection ID in the state
71 this.con_num = con_num;
72
73 // IRC protocol handling
74 this.irc_commands = new IrcCommands(this);
75
76 // IrcServer object
77 this.server = new IrcServer(this, hostname, port);
78
79 // IrcUser objects
80 this.irc_users = Object.create(null);
81
82 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
83 this.irc_users[this.nick] = new IrcUser(this, '*');
84
85 // IrcChannel objects
86 this.irc_channels = Object.create(null);
87
88 // IRC connection information
89 this.irc_host = {hostname: hostname, port: port};
90 this.ssl = !(!ssl);
91
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)))) {
95 this.socks = {
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
100 };
101 } else {
102 this.socks = false;
103 }
104
105 // Net. interface this connection should be made through
106 this.outgoing_interface = false;
107
108 // Options sent by the IRCd
109 this.options = Object.create(null);
110 this.cap = {requested: [], enabled: []};
111
112 // Is SASL supported on the IRCd
113 this.sasl = false;
114
115 // Buffers for data sent from the IRCd
116 this.hold_last = false;
117 this.held_data = null;
118
119 this.applyIrcEvents();
120 };
121 util.inherits(IrcConnection, EE);
122
123 module.exports.IrcConnection = IrcConnection;
124
125
126
127 IrcConnection.prototype.applyIrcEvents = function () {
128 // Listen for events on the IRC connection
129 this.irc_events = {
130 'server * connect': onServerConnect,
131 'channel * join': onChannelJoin,
132
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
139 };
140
141 EventBinder.bindIrcEvents('', this.irc_events, this, this);
142 };
143
144
145 /**
146 * Start the connection to the IRCd
147 */
148 IrcConnection.prototype.connect = function () {
149 var that = this;
150
151 // The socket connect event to listener for
152 var socket_connect_event_name = 'connect';
153
154 // The destination address
155 var dest_addr = this.socks ?
156 this.socks.host :
157 this.irc_host.hostname;
158
159 // Make sure we don't already have an open connection
160 this.disposeSocket();
161
162 // Get the IP family for the dest_addr (either socks or IRCd destination)
163 getConnectionFamily(dest_addr, function getConnectionFamilyCb(err, family, host) {
164 var outgoing;
165
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;
170
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;
175 } else {
176 outgoing = global.config.outgoing_address.IPv4 || '0.0.0.0';
177
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
181 host = dest_addr;
182 }
183
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)];
187 }
188
189 // Make sure we have a valid interface address
190 if (typeof outgoing !== 'string')
191 outgoing = '0.0.0.0';
192
193 } else {
194 // No config was found so use the default
195 outgoing = '0.0.0.0';
196 }
197
198 // Are we connecting through a SOCKS proxy?
199 if (that.socks) {
200 that.socket = Socks.connect({
201 host: host,
202 port: that.irc_host.port,
203 ssl: that.ssl,
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
210 });
211
212 } else if (true || that.proxy) {
213 that.socket = new Proxy.ProxySocket(7779, '127.0.0.1', {
214 username: that.username,
215 });
216 that.socket.connect(that.irc_host.port, host);
217
218 } else {
219 // No socks connection, connect directly to the IRCd
220
221 if (that.ssl) {
222 that.socket = tls.connect({
223 host: host,
224 port: that.irc_host.port,
225 rejectUnauthorized: global.config.reject_unauthorised_certificates,
226 localAddress: outgoing
227 });
228
229 // We need the raw socket connect event
230 that.socket.socket.on('connect', function() { rawSocketConnect.call(that, this); });
231
232 socket_connect_event_name = 'secureConnect';
233
234 } else {
235 that.socket = net.connect({
236 host: host,
237 port: that.irc_host.port,
238 localAddress: outgoing
239 });
240 }
241 }
242
243 // Apply the socket listeners
244 that.socket.on(socket_connect_event_name, function socketConnectCb() {
245
246 // TLS connections have the actual socket as a property
247 var is_tls = (typeof this.socket !== 'undefined') ?
248 true :
249 false;
250
251 // TLS sockets have already called this
252 if (!is_tls)
253 rawSocketConnect.call(that, this);
254
255 that.connected = true;
256
257 socketConnectHandler.call(that);
258 });
259
260 that.socket.on('error', function socketErrorCb(event) {
261 that.emit('error', event);
262 });
263
264 that.socket.on('data', function () {
265 socketOnData.apply(that, arguments);
266 });
267
268 that.socket.on('close', function socketCloseCb(had_error) {
269 that.connected = false;
270
271 // Remove this socket form the identd lookup
272 if (that.identd_port_pair) {
273 delete global.clients.port_pairs[that.identd_port_pair];
274 }
275
276 that.emit('close');
277
278 // Close the whole socket down
279 that.disposeSocket();
280 });
281 });
282 };
283
284 /**
285 * Send an event to the client
286 */
287 IrcConnection.prototype.clientEvent = function (event_name, data, callback) {
288 data.server = this.con_num;
289 this.state.sendIrcCommand(event_name, data, callback);
290 };
291
292 /**
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
296 */
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);
300
301 if (force) {
302 this.socket.write(encoded_buffer);
303 return;
304 }
305
306 this.write_buffer.push(encoded_buffer);
307
308 // Only flush if we're not writing already
309 if (!this.writing_buffer)
310 this.flushWriteBuffer();
311 };
312
313
314
315 /**
316 * Flush the write buffer to the server in a throttled fashion
317 */
318 IrcConnection.prototype.flushWriteBuffer = function () {
319
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;
324 return;
325 }
326
327 this.writing_buffer = true;
328
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;
334 });
335
336 this.write_buffer = [];
337 this.writing_buffer = false;
338
339 return;
340 }
341
342 // Nothing to write? Stop writing and leave
343 if (this.write_buffer.length === 0) {
344 this.writing_buffer = false;
345 return;
346 }
347
348 this.socket.write(this.write_buffer[0]);
349 this.write_buffer = this.write_buffer.slice(1);
350
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);
354 } else {
355 // No more buffers to write.. so we've finished
356 this.writing_buffer = false;
357 }
358 };
359
360
361
362 /**
363 * Close the connection to the IRCd after forcing one last line
364 */
365 IrcConnection.prototype.end = function (data, callback) {
366 if (!this.socket)
367 return;
368
369 if (data)
370 this.write(data, true);
371
372 this.socket.end();
373 };
374
375
376
377 /**
378 * Clean up this IrcConnection instance and any sockets
379 */
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) {
384 this.end();
385 return;
386 }
387
388 if (this.socket) {
389 this.disposeSocket();
390 }
391
392 _.each(this.irc_users, function (user) {
393 user.dispose();
394 });
395 _.each(this.irc_channels, function (chan) {
396 chan.dispose();
397 });
398 this.irc_users = undefined;
399 this.irc_channels = undefined;
400
401 this.server.dispose();
402 this.server = undefined;
403
404 this.irc_commands = undefined;
405
406 EventBinder.unbindIrcEvents('', this.irc_events, this);
407
408 this.removeAllListeners();
409 };
410
411
412
413 /**
414 * Clean up any sockets for this IrcConnection
415 */
416 IrcConnection.prototype.disposeSocket = function () {
417 if (this.socket) {
418 this.socket.end();
419 this.socket.removeAllListeners();
420 this.socket = null;
421 }
422 };
423
424 /**
425 * Set a new encoding for this connection
426 * Return true in case of success
427 */
428
429 IrcConnection.prototype.setEncoding = function (encoding) {
430 var encoded_test;
431
432 try {
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;
439 return true;
440 }
441 return false;
442 } catch (err) {
443 return false;
444 }
445 };
446
447 function getConnectionFamily(host, callback) {
448 if (net.isIP(host)) {
449 if (net.isIPv4(host)) {
450 callback(null, 'IPv4', host);
451 } else {
452 callback(null, 'IPv6', host);
453 }
454 } else {
455 dns.resolve6(host, function resolve6Cb(err, addresses) {
456 if (!err) {
457 callback(null, 'IPv6', addresses[0]);
458 } else {
459 dns.resolve4(host, function resolve4Cb(err, addresses) {
460 if (!err) {
461 callback(null, 'IPv4',addresses[0]);
462 } else {
463 callback(err);
464 }
465 });
466 }
467 });
468 }
469 }
470
471
472 function onChannelJoin(event) {
473 var chan;
474
475 // Only deal with ourselves joining a channel
476 if (event.nick !== this.nick)
477 return;
478
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);
487 }
488 }
489
490
491 function onServerConnect(event) {
492 this.nick = event.nick;
493 }
494
495
496 function onUserPrivmsg(event) {
497 var user;
498
499 // Only deal with messages targetted to us
500 if (event.channel !== this.nick)
501 return;
502
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);
507 }
508 }
509
510
511 function onUserNick(event) {
512 var user;
513
514 // Only deal with messages targetted to us
515 if (event.nick !== this.nick)
516 return;
517
518 this.nick = event.newnick;
519 }
520
521
522 function onUserParts(event) {
523 // Only deal with ourselves leaving a channel
524 if (event.nick !== this.nick)
525 return;
526
527 if (this.irc_channels[event.channel]) {
528 this.irc_channels[event.channel].dispose();
529 delete this.irc_channels[event.channel];
530 }
531 }
532
533 function onUserKick(event){
534 // Only deal with ourselves being kicked from a channel
535 if (event.kicked !== this.nick)
536 return;
537
538 if (this.irc_channels[event.channel]) {
539 this.irc_channels[event.channel].dispose();
540 delete this.irc_channels[event.channel];
541 }
542
543 }
544
545
546
547 /**
548 * When a socket connects to an IRCd
549 * May be called before any socket handshake are complete (eg. TLS)
550 */
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;
557 }
558 };
559
560
561 /**
562 * Handle the socket connect event, starting the IRCd registration
563 */
564 var socketConnectHandler = function () {
565 var that = this,
566 connect_data;
567
568 // Build up data to be used for webirc/etc detection
569 connect_data = {
570 connection: this,
571
572 // Array of lines to be sent to the IRCd before anything else
573 prepend_data: []
574 };
575
576 // Let the webirc/etc detection modify any required parameters
577 connect_data = findWebIrc.call(this, connect_data);
578
579 global.modules.emit('irc authorize', connect_data).done(function ircAuthorizeCb() {
580 var gecos = '[www.kiwiirc.com] ' + that.nick;
581
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);
585 }
586
587 // Send any initial data for webirc/etc
588 if (connect_data.prepend_data) {
589 _.each(connect_data.prepend_data, function(data) {
590 that.write(data);
591 });
592 }
593
594 that.write('CAP LS');
595
596 if (that.password)
597 that.write('PASS ' + that.password);
598
599 that.write('NICK ' + that.nick);
600 that.write('USER ' + that.username + ' 0 0 :' + gecos);
601
602 that.emit('connected');
603 });
604 };
605
606
607
608 /**
609 * Load any WEBIRC or alternative settings for this connection
610 * Called in scope of the IrcConnection instance
611 */
612 function findWebIrc(connect_data) {
613 var webirc_pass = global.config.webirc_pass,
614 ip_as_username = global.config.ip_as_username,
615 tmp;
616
617
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;
623
624 connect_data.prepend_data = [tmp];
625 }
626
627
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);
633
634 // Pad out the hex value if it's a single char
635 if (hex.length === 1)
636 hex = '0' + hex;
637
638 return hex;
639 }).join('');
640
641 }
642
643 return connect_data;
644 }
645
646
647 /**
648 * Buffer any data we get from the IRCd until we have complete lines.
649 */
650 function socketOnData(data) {
651 var data_pos, // Current position within the data Buffer
652 line_start = 0,
653 lines = [],
654 line = '',
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
657
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;
663 }
664 }
665
666 // No complete lines of data? Check to see if buffering the data would exceed the max buffer size
667 if (!lines[0]) {
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();
672
673 } else {
674
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);
678 } else {
679 this.held_data = data;
680 }
681 }
682
683 // No complete lines to process..
684 return;
685 }
686
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;
693 }
694
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();
702 return;
703 }
704
705 this.hold_last = true;
706 this.held_data = new Buffer(data.length - line_start);
707 data.copy(this.held_data, 0, line_start);
708 }
709
710 // Process our data line by line
711 for (i = 0; i < lines.length; i++)
712 parseIrcLine.call(this, lines[i]);
713
714 }
715
716
717
718 /**
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
721 * IRCds
722 */
723 var parse_regex = /^(?:(?:(?:@([^ ]+) )?):(?:([^\s!]+)|([^\s!]+)!([^\s@]+)@?([^\s]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.*))?$/i;
724
725 function parseIrcLine(buffer_line) {
726 var msg,
727 i, j,
728 tags = [],
729 tag,
730 line = '';
731
732 // Decode server encoding
733 line = iconv.decode(buffer_line, this.encoding);
734 if (!line) return;
735
736 // Parse the complete line, removing any carriage returns
737 msg = parse_regex.exec(line.replace(/^\r+|\r+$/, ''));
738
739 if (!msg) {
740 // The line was not parsed correctly, must be malformed
741 console.log("Malformed IRC line: " + line.replace(/^\r+|\r+$/, ''));
742 return;
743 }
744
745 // Extract any tags (msg[1])
746 if (msg[1]) {
747 tags = msg[1].split(';');
748
749 for (j = 0; j < tags.length; j++) {
750 tag = tags[j].split('=');
751 tags[j] = {tag: tag[0], value: tag[1]};
752 }
753 }
754
755 msg = {
756 tags: tags,
757 prefix: msg[2],
758 nick: msg[3],
759 ident: msg[4],
760 hostname: msg[5] || '',
761 command: msg[6],
762 params: msg[7] || '',
763 trailing: (msg[8]) ? msg[8].trim() : ''
764 };
765
766 msg.params = msg.params.split(/ +/);
767 this.irc_commands.dispatch(msg.command.toUpperCase(), msg);
768 }