Better IRC server reconnection logic
[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'),
94b00b2d 6 winston = require('winston'),
4c25c0d7 7 EventBinder = require('./eventbinder.js'),
cefa0900 8 IrcServer = require('./server.js'),
cced0091 9 IrcCommands = require('./commands.js'),
cefa0900 10 IrcChannel = require('./channel.js'),
9650b343 11 IrcUser = require('./user.js'),
2abb4615 12 EE = require('../ee.js'),
1a452a02 13 iconv = require('iconv-lite'),
b5574d3b 14 Proxy = require('../proxy.js'),
55ccaf50 15 Socks;
32a09dc1
D
16
17
55ccaf50
JA
18// Break the Node.js version down into usable parts
19var version_values = process.version.substr(1).split('.').map(function (item) {
20 return parseInt(item, 10);
21});
9de636f9 22
0c0dfa95 23// If we have a suitable Nodejs version, bring in the SOCKS functionality
9de636f9 24if (version_values[1] >= 10) {
3b259b15 25 Socks = require('socksjs');
55ccaf50 26}
db8af19d 27
cc54c0a1 28var IrcConnection = function (hostname, port, ssl, nick, user, options, state, con_num) {
2abb4615 29 EE.call(this,{
cefa0900 30 wildcard: true,
d9285da9 31 delimiter: ' '
cefa0900 32 });
4c25c0d7 33 this.setMaxListeners(0);
32a09dc1 34
cc54c0a1
D
35 options = options || {};
36
db8af19d 37 // Socket state
63008d5e 38 this.connected = false;
db8af19d 39
7746ca17
D
40 // If the connection closes and this is false, we reconnect
41 this.requested_disconnect = false;
42
8401673d
D
43 // Number of times we have tried to reconnect
44 this.reconnect_attempts = 0;
45
fc1c21b8
D
46 // IRCd write buffers (flood controll)
47 this.write_buffer = [];
48
49 // In process of writing the buffer?
50 this.writing_buffer = false;
51
52 // Max number of lines to write a second
53 this.write_buffer_lines_second = 2;
54
db8af19d 55 // If registeration with the IRCd has completed
63008d5e 56 this.registered = false;
db8af19d
D
57
58 // If we are in the CAP negotiation stage
63008d5e 59 this.cap_negotiation = true;
db8af19d
D
60
61 // User information
63008d5e
D
62 this.nick = nick;
63 this.user = user; // Contains users real hostname and address
5973d01c 64 this.username = this.nick.replace(/[^0-9a-zA-Z\-_.\/]/, '');
63811c17 65 this.gecos = ''; // Users real-name. Uses default from config if empty
cc54c0a1
D
66 this.password = options.password || '';
67
68 // Set the passed encoding. or the default if none giving or it fails
69 if (!options.encoding || !this.setEncoding(options.encoding)) {
70 this.setEncoding(global.config.default_encoding);
71 }
32a09dc1 72
b09157de
JA
73 // State object
74 this.state = state;
32a09dc1 75
cced0091
D
76 // Connection ID in the state
77 this.con_num = con_num;
78
79 // IRC protocol handling
138d8d17 80 this.irc_commands = new IrcCommands.Handler(this);
cced0091 81
cefa0900
JA
82 // IrcServer object
83 this.server = new IrcServer(this, hostname, port);
32a09dc1 84
cefa0900
JA
85 // IrcUser objects
86 this.irc_users = Object.create(null);
efe9d487
D
87
88 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
89 this.irc_users[this.nick] = new IrcUser(this, '*');
90
cefa0900
JA
91 // IrcChannel objects
92 this.irc_channels = Object.create(null);
db8af19d
D
93
94 // IRC connection information
63008d5e
D
95 this.irc_host = {hostname: hostname, port: port};
96 this.ssl = !(!ssl);
32a09dc1 97
9650b343 98 // SOCKS proxy details
ac0b278c
JA
99 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
100 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)))) {
101 this.socks = {
102 host: global.config.socks_proxy.address,
103 port: global.config.socks_proxy.port,
104 user: global.config.socks_proxy.user,
105 pass: global.config.socks_proxy.pass
106 };
107 } else {
108 this.socks = false;
109 }
db8af19d 110
29bc2066 111 // Kiwi proxy info may be set within a server module. {port: 7779, host: 'kiwi.proxy.com', ssl: false}
4b329880
D
112 this.proxy = false;
113
7cf75020
D
114 // Net. interface this connection should be made through
115 this.outgoing_interface = false;
116
db8af19d 117 // Options sent by the IRCd
63008d5e 118 this.options = Object.create(null);
d772b95d
D
119 this.options.PREFIX = [
120 {symbol: '~', mode: 'q'},
121 {symbol: '&', mode: 'a'},
122 {symbol: '@', mode: 'o'},
123 {symbol: '%', mode: 'h'},
124 {symbol: '+', mode: 'v'}
125 ];
126
63008d5e 127 this.cap = {requested: [], enabled: []};
db8af19d
D
128
129 // Is SASL supported on the IRCd
63008d5e 130 this.sasl = false;
32a09dc1 131
db8af19d 132 // Buffers for data sent from the IRCd
63008d5e 133 this.hold_last = false;
a8d8af60 134 this.held_data = null;
63008d5e 135
4c25c0d7 136 this.applyIrcEvents();
63008d5e 137};
2abb4615 138util.inherits(IrcConnection, EE);
63008d5e
D
139
140module.exports.IrcConnection = IrcConnection;
141
f9ff7686 142
db8af19d 143
4c25c0d7
D
144IrcConnection.prototype.applyIrcEvents = function () {
145 // Listen for events on the IRC connection
146 this.irc_events = {
d9285da9
JA
147 'server * connect': onServerConnect,
148 'channel * join': onChannelJoin,
df6d68a5
D
149
150 // TODO: uncomment when using an IrcUser per nick
151 //'user:*:privmsg': onUserPrivmsg,
d9285da9
JA
152 'user * nick': onUserNick,
153 'channel * part': onUserParts,
154 'channel * quit': onUserParts,
155 'channel * kick': onUserKick
4c25c0d7
D
156 };
157
158 EventBinder.bindIrcEvents('', this.irc_events, this, this);
159};
160
db8af19d
D
161
162/**
163 * Start the connection to the IRCd
164 */
63008d5e 165IrcConnection.prototype.connect = function () {
7496de01 166 var that = this;
63008d5e 167
db8af19d
D
168 // The socket connect event to listener for
169 var socket_connect_event_name = 'connect';
170
7496de01 171 // The destination address
4b329880
D
172 var dest_addr;
173 if (this.socks) {
174 dest_addr = this.socks.host;
175 } else if (this.proxy) {
176 dest_addr = this.proxy.host;
177 } else {
178 dest_addr = this.irc_host.hostname;
179 }
db8af19d
D
180
181 // Make sure we don't already have an open connection
182 this.disposeSocket();
183
7746ca17
D
184 this.requested_disconnect = false;
185
7496de01 186 // Get the IP family for the dest_addr (either socks or IRCd destination)
e991ec2f 187 getConnectionFamily(dest_addr, function getConnectionFamilyCb(err, family, host) {
7496de01
D
188 var outgoing;
189
190 // Decide which net. interface to make the connection through
7cf75020
D
191 if (that.outgoing_interface) {
192 // An specific interface has been given for this connection
193 outgoing = this.outgoing_interface;
194
195 } else if (global.config.outgoing_address) {
196 // Pick an interface from the config
7496de01 197 if ((family === 'IPv6') && (global.config.outgoing_address.IPv6)) {
b156e01a
JA
198 outgoing = global.config.outgoing_address.IPv6;
199 } else {
7496de01 200 outgoing = global.config.outgoing_address.IPv4 || '0.0.0.0';
ddae94f5
D
201
202 // We don't have an IPv6 interface but dest_addr may still resolve to
203 // an IPv4 address. Reset `host` and try connecting anyway, letting it
204 // fail if an IPv4 resolved address is not found
205 host = dest_addr;
b156e01a 206 }
7496de01 207
72280d53
D
208 // If we have an array of interfaces, select a random one
209 if (typeof outgoing !== 'string' && outgoing.length) {
210 outgoing = outgoing[Math.floor(Math.random() * outgoing.length)];
211 }
212
213 // Make sure we have a valid interface address
e8c4bb74 214 if (typeof outgoing !== 'string') {
72280d53 215 outgoing = '0.0.0.0';
e8c4bb74 216 }
72280d53 217
7496de01
D
218 } else {
219 // No config was found so use the default
220 outgoing = '0.0.0.0';
221 }
222
223 // Are we connecting through a SOCKS proxy?
6cd5ba87 224 if (that.socks) {
b156e01a 225 that.socket = Socks.connect({
4b329880 226 host: that.irc_host.host,
b156e01a
JA
227 port: that.irc_host.port,
228 ssl: that.ssl,
229 rejectUnauthorized: global.config.reject_unauthorised_certificates
4b329880 230 }, {host: host,
b156e01a
JA
231 port: that.socks.port,
232 user: that.socks.user,
233 pass: that.socks.pass,
234 localAddress: outgoing
235 });
236
4b329880
D
237 } else if (that.proxy) {
238 that.socket = new Proxy.ProxySocket(that.proxy.port, host, {
b5574d3b 239 username: that.username,
5bba0980 240 interface: that.proxy.interface
e0bdbc31 241 }, {ssl: that.proxy.ssl});
96ecb5e7
D
242
243 if (that.ssl) {
244 that.socket.connectTls(that.irc_host.port, that.irc_host.hostname);
245 } else {
246 that.socket.connect(that.irc_host.port, that.irc_host.hostname);
247 }
b5574d3b 248
7496de01
D
249 } else {
250 // No socks connection, connect directly to the IRCd
b156e01a
JA
251
252 if (that.ssl) {
253 that.socket = tls.connect({
ddae94f5 254 host: host,
b156e01a
JA
255 port: that.irc_host.port,
256 rejectUnauthorized: global.config.reject_unauthorised_certificates,
257 localAddress: outgoing
258 });
259
4de89532
D
260 // We need the raw socket connect event
261 that.socket.socket.on('connect', function() { rawSocketConnect.call(that, this); });
262
b156e01a
JA
263 socket_connect_event_name = 'secureConnect';
264
265 } else {
266 that.socket = net.connect({
267 host: host,
268 port: that.irc_host.port,
269 localAddress: outgoing
270 });
271 }
7496de01 272 }
b156e01a 273
7496de01 274 // Apply the socket listeners
e991ec2f 275 that.socket.on(socket_connect_event_name, function socketConnectCb() {
9e225dc6 276
4de89532
D
277 // TLS connections have the actual socket as a property
278 var is_tls = (typeof this.socket !== 'undefined') ?
279 true :
280 false;
9e225dc6 281
4de89532 282 // TLS sockets have already called this
e8c4bb74 283 if (!is_tls) {
4de89532 284 rawSocketConnect.call(that, this);
e8c4bb74 285 }
cc3c5d04 286
4de89532 287 that.connected = true;
cc3c5d04 288
b156e01a
JA
289 socketConnectHandler.call(that);
290 });
32a09dc1 291
e991ec2f 292 that.socket.on('error', function socketErrorCb(event) {
b156e01a
JA
293 that.emit('error', event);
294 });
32a09dc1 295
7496de01 296 that.socket.on('data', function () {
8b967a99 297 socketOnData.apply(that, arguments);
b156e01a 298 });
32a09dc1 299
e991ec2f 300 that.socket.on('close', function socketCloseCb(had_error) {
7746ca17
D
301 // If that.connected is false, we never actually managed to connect
302 var was_connected = that.connected,
303 had_registered = that.server.registered,
304 should_reconnect = false;
305
b156e01a 306 that.connected = false;
7746ca17 307 that.server.reset();
cc3c5d04
D
308
309 // Remove this socket form the identd lookup
9e225dc6
D
310 if (that.identd_port_pair) {
311 delete global.clients.port_pairs[that.identd_port_pair];
cc3c5d04
D
312 }
313
8401673d
D
314 // If trying to reconnect, continue with it
315 if (that.reconnect_attempts && that.reconnect_attempts < 3) {
316 should_reconnect = true;
317
318 // If this was an unplanned disconnect and we were originally connected OK, reconnect
319 } else if (!that.requested_disconnect && was_connected && had_registered) {
320 should_reconnect = true;
321
322 } else {
323 should_reconnect = false;
324 }
7746ca17
D
325
326 if (should_reconnect) {
8401673d 327 that.reconnect_attempts++;
7746ca17
D
328 that.emit('reconnecting');
329 } else {
330 that.emit('close', had_error);
8401673d 331 that.reconnect_attempts = 0;
7746ca17 332 }
db8af19d 333
b156e01a
JA
334 // Close the whole socket down
335 that.disposeSocket();
7746ca17
D
336
337 // If this socket closing was not expected and we did actually connect and
338 // we did previously completely register on the network, then reconnect
339 if (should_reconnect) {
340 setTimeout(function() {
341 that.connect();
8401673d 342 }, 4000);
7746ca17 343 }
b156e01a 344 });
7496de01 345 });
2a8e95d1 346};
2a8e95d1 347
3c91bff8
JA
348/**
349 * Send an event to the client
350 */
351IrcConnection.prototype.clientEvent = function (event_name, data, callback) {
cbdab563 352 data.connection_id = this.con_num;
3c91bff8
JA
353 this.state.sendIrcCommand(event_name, data, callback);
354};
db8af19d
D
355
356/**
357 * Write a line of data to the IRCd
56f0f1b9
D
358 * @param data The line of data to be sent
359 * @param force Write the data now, ignoring any write queue
db8af19d 360 */
9c6e1a86 361IrcConnection.prototype.write = function (data, force, force_complete_fn) {
1a452a02 362 //ENCODE string to encoding of the server
ae3506f9 363 var encoded_buffer = iconv.encode(data + '\r\n', this.encoding);
fc1c21b8 364
56f0f1b9 365 if (force) {
9c6e1a86 366 this.socket.write(encoded_buffer, force_complete_fn);
56f0f1b9
D
367 return;
368 }
369
fc1c21b8
D
370 this.write_buffer.push(encoded_buffer);
371
372 // Only flush if we're not writing already
e8c4bb74 373 if (!this.writing_buffer) {
fc1c21b8 374 this.flushWriteBuffer();
e8c4bb74 375 }
fc1c21b8
D
376};
377
378
379
380/**
381 * Flush the write buffer to the server in a throttled fashion
382 */
383IrcConnection.prototype.flushWriteBuffer = function () {
14a18c21
D
384
385 // In case the socket closed between writing our queue.. clean up
386 if (!this.connected) {
387 this.write_buffer = [];
388 this.writing_buffer = false;
389 return;
390 }
391
fc1c21b8
D
392 this.writing_buffer = true;
393
394 // Disabled write buffer? Send everything we have
395 if (!this.write_buffer_lines_second) {
9478baca 396 this.write_buffer.forEach(function(buffer) {
fc1c21b8
D
397 this.socket.write(buffer);
398 this.write_buffer = null;
399 });
400
401 this.write_buffer = [];
402 this.writing_buffer = false;
403
404 return;
405 }
406
407 // Nothing to write? Stop writing and leave
408 if (this.write_buffer.length === 0) {
409 this.writing_buffer = false;
410 return;
411 }
412
413 this.socket.write(this.write_buffer[0]);
414 this.write_buffer = this.write_buffer.slice(1);
415
14a18c21
D
416 // Call this function again at some point if we still have data to write
417 if (this.write_buffer.length > 0) {
418 setTimeout(this.flushWriteBuffer.bind(this), 1000 / this.write_buffer_lines_second);
419 } else {
420 // No more buffers to write.. so we've finished
421 this.writing_buffer = false;
422 }
2a8e95d1
D
423};
424
db8af19d
D
425
426
427/**
56f0f1b9 428 * Close the connection to the IRCd after forcing one last line
db8af19d 429 */
9478baca 430IrcConnection.prototype.end = function (data) {
9c6e1a86
D
431 var that = this;
432
e8c4bb74 433 if (!this.socket) {
56f0f1b9 434 return;
e8c4bb74 435 }
56f0f1b9 436
7746ca17
D
437 this.requested_disconnect = true;
438
e8c4bb74 439 if (data) {
9c6e1a86
D
440 // Once the last bit of data has been sent, then re-run this function to close the socket
441 this.write(data, true, function() {
442 that.end();
443 });
444
445 return;
e8c4bb74 446 }
32a09dc1 447
db8af19d 448 this.socket.end();
2a8e95d1
D
449};
450
db8af19d
D
451
452
b0587b80
D
453/**
454 * Check if any server capabilities are enabled
455 */
456IrcConnection.prototype.capContainsAny = function (caps) {
457 var enabled_caps;
458
459 if (!caps instanceof Array) {
460 caps = [caps];
461 }
462
463 enabled_caps = _.intersection(this.cap.enabled, caps);
464 return enabled_caps.length > 0;
465};
466
467
468
db8af19d
D
469/**
470 * Clean up this IrcConnection instance and any sockets
471 */
c08717da 472IrcConnection.prototype.dispose = function () {
a787f79f
D
473 // If we're still connected, wait until the socket is closed before disposing
474 // so that all the events are still correctly triggered
475 if (this.socket && this.connected) {
14a18c21 476 this.end();
a787f79f
D
477 return;
478 }
479
480 if (this.socket) {
481 this.disposeSocket();
a787f79f
D
482 }
483
cefa0900
JA
484 _.each(this.irc_users, function (user) {
485 user.dispose();
486 });
487 _.each(this.irc_channels, function (chan) {
488 chan.dispose();
489 });
ebe178d6
D
490 this.irc_users = undefined;
491 this.irc_channels = undefined;
492
493 this.server.dispose();
494 this.server = undefined;
4c25c0d7 495
a787f79f 496 this.irc_commands = undefined;
4c25c0d7 497
a787f79f 498 EventBinder.unbindIrcEvents('', this.irc_events, this);
5e211c3d 499
14a18c21 500 this.removeAllListeners();
c08717da
D
501};
502
503
2a8e95d1 504
db8af19d
D
505/**
506 * Clean up any sockets for this IrcConnection
507 */
508IrcConnection.prototype.disposeSocket = function () {
509 if (this.socket) {
6b8fa7a6 510 this.socket.end();
db8af19d
D
511 this.socket.removeAllListeners();
512 this.socket = null;
513 }
2a8e95d1
D
514};
515
d1b3e8b3
VDF
516/**
517 * Set a new encoding for this connection
518 * Return true in case of success
519 */
520
521IrcConnection.prototype.setEncoding = function (encoding) {
3ddc135a
D
522 var encoded_test;
523
3efb4f33
VDF
524 try {
525 encoded_test = iconv.encode("TEST", encoding);
526 //This test is done to check if this encoding also supports
527 //the ASCII charset required by the IRC protocols
528 //(Avoid the use of base64 or incompatible encodings)
27bca914 529 if (encoded_test == "TEST") { // jshint ignore:line
3efb4f33
VDF
530 this.encoding = encoding;
531 return true;
532 }
533 return false;
534 } catch (err) {
535 return false;
65c5a477 536 }
d1b3e8b3 537};
2a8e95d1 538
b156e01a
JA
539function getConnectionFamily(host, callback) {
540 if (net.isIP(host)) {
541 if (net.isIPv4(host)) {
3e01340e 542 callback(null, 'IPv4', host);
b156e01a 543 } else {
3e01340e 544 callback(null, 'IPv6', host);
b156e01a
JA
545 }
546 } else {
e991ec2f 547 dns.resolve6(host, function resolve6Cb(err, addresses) {
b156e01a
JA
548 if (!err) {
549 callback(null, 'IPv6', addresses[0]);
550 } else {
e991ec2f 551 dns.resolve4(host, function resolve4Cb(err, addresses) {
b156e01a
JA
552 if (!err) {
553 callback(null, 'IPv4',addresses[0]);
554 } else {
555 callback(err);
556 }
557 });
558 }
559 });
560 }
561}
562
db8af19d 563
4c25c0d7
D
564function onChannelJoin(event) {
565 var chan;
566
567 // Only deal with ourselves joining a channel
e8c4bb74 568 if (event.nick !== this.nick) {
4c25c0d7 569 return;
e8c4bb74 570 }
4c25c0d7
D
571
572 // We should only ever get a JOIN command for a channel
573 // we're not already a member of.. but check we don't
574 // have this channel in case something went wrong somewhere
575 // at an earlier point
576 if (!this.irc_channels[event.channel]) {
577 chan = new IrcChannel(this, event.channel);
578 this.irc_channels[event.channel] = chan;
579 chan.irc_events.join.call(chan, event);
580 }
581}
582
583
584function onServerConnect(event) {
585 this.nick = event.nick;
4c25c0d7
D
586}
587
588
589function onUserPrivmsg(event) {
590 var user;
591
592 // Only deal with messages targetted to us
e8c4bb74 593 if (event.channel !== this.nick) {
4c25c0d7 594 return;
e8c4bb74 595 }
4c25c0d7
D
596
597 if (!this.irc_users[event.nick]) {
598 user = new IrcUser(this, event.nick);
599 this.irc_users[event.nick] = user;
600 user.irc_events.privmsg.call(user, event);
601 }
602}
603
604
9be602fc 605function onUserNick(event) {
9be602fc 606 // Only deal with messages targetted to us
e8c4bb74 607 if (event.nick !== this.nick) {
9be602fc 608 return;
e8c4bb74 609 }
9be602fc
D
610
611 this.nick = event.newnick;
612}
613
614
4c25c0d7
D
615function onUserParts(event) {
616 // Only deal with ourselves leaving a channel
e8c4bb74 617 if (event.nick !== this.nick) {
4c25c0d7 618 return;
e8c4bb74 619 }
4c25c0d7
D
620
621 if (this.irc_channels[event.channel]) {
622 this.irc_channels[event.channel].dispose();
623 delete this.irc_channels[event.channel];
624 }
625}
626
6d2df752
MC
627function onUserKick(event){
628 // Only deal with ourselves being kicked from a channel
e8c4bb74 629 if (event.kicked !== this.nick) {
6d2df752 630 return;
e8c4bb74 631 }
6d2df752
MC
632
633 if (this.irc_channels[event.channel]) {
634 this.irc_channels[event.channel].dispose();
635 delete this.irc_channels[event.channel];
636 }
637
638}
639
4c25c0d7
D
640
641
4de89532
D
642/**
643 * When a socket connects to an IRCd
644 * May be called before any socket handshake are complete (eg. TLS)
645 */
646var rawSocketConnect = function(socket) {
647 // Make note of the port numbers for any identd lookups
648 // Nodejs < 0.9.6 has no socket.localPort so check this first
353d261a 649 if (typeof socket.localPort !== 'undefined') {
4de89532
D
650 this.identd_port_pair = socket.localPort.toString() + '_' + socket.remotePort.toString();
651 global.clients.port_pairs[this.identd_port_pair] = this;
652 }
653};
654
4c25c0d7 655
db8af19d
D
656/**
657 * Handle the socket connect event, starting the IRCd registration
658 */
659var socketConnectHandler = function () {
15fefff7
D
660 var that = this,
661 connect_data;
662
663 // Build up data to be used for webirc/etc detection
664 connect_data = {
bd7196e1
D
665 connection: this,
666
667 // Array of lines to be sent to the IRCd before anything else
668 prepend_data: []
15fefff7
D
669 };
670
671 // Let the webirc/etc detection modify any required parameters
266b5087 672 connect_data = findWebIrc.call(this, connect_data);
15fefff7 673
e991ec2f 674 global.modules.emit('irc authorize', connect_data).done(function ircAuthorizeCb() {
63811c17 675 var gecos = that.gecos;
c14b67ae 676
63811c17
D
677 if (!gecos && global.config.default_gecos) {
678 // We don't have a gecos yet, so use the default
cb234b7e 679 gecos = global.config.default_gecos.toString().replace('%n', that.nick);
63811c17
D
680 gecos = gecos.replace('%h', that.user.hostname);
681
682 } else if (!gecos) {
683 // We don't have a gecos nor a default, so lets set somthing
684 gecos = '[www.kiwiirc.com] ' + that.nick;
cb234b7e
D
685 }
686
bd7196e1
D
687 // Send any initial data for webirc/etc
688 if (connect_data.prepend_data) {
689 _.each(connect_data.prepend_data, function(data) {
690 that.write(data);
691 });
692 }
693
694 that.write('CAP LS');
695
e8c4bb74 696 if (that.password) {
bd7196e1 697 that.write('PASS ' + that.password);
e8c4bb74 698 }
32a09dc1 699
bd7196e1 700 that.write('NICK ' + that.nick);
cb234b7e 701 that.write('USER ' + that.username + ' 0 0 :' + gecos);
32a09dc1 702
bd7196e1
D
703 that.emit('connected');
704 });
7dfe47c6 705};
2a8e95d1 706
15fefff7 707
db8af19d
D
708
709/**
710 * Load any WEBIRC or alternative settings for this connection
711 * Called in scope of the IrcConnection instance
712 */
15fefff7 713function findWebIrc(connect_data) {
db8af19d
D
714 var webirc_pass = global.config.webirc_pass,
715 ip_as_username = global.config.ip_as_username,
716 tmp;
717
15fefff7
D
718
719 // Do we have a WEBIRC password for this?
bd7196e1 720 if (webirc_pass && webirc_pass[this.irc_host.hostname]) {
db8af19d 721 // Build the WEBIRC line to be sent before IRC registration
bd7196e1
D
722 tmp = 'WEBIRC ' + webirc_pass[this.irc_host.hostname] + ' KiwiIRC ';
723 tmp += this.user.hostname + ' ' + this.user.address;
db8af19d 724
15fefff7
D
725 connect_data.prepend_data = [tmp];
726 }
727
728
729 // Check if we need to pass the users IP as its username/ident
bd7196e1 730 if (ip_as_username && ip_as_username.indexOf(this.irc_host.hostname) > -1) {
15fefff7 731 // Get a hex value of the clients IP
9478baca 732 this.username = this.user.address.split('.').map(function ipSplitMapCb(i){
32800bf5
D
733 var hex = parseInt(i, 10).toString(16);
734
735 // Pad out the hex value if it's a single char
e8c4bb74 736 if (hex.length === 1) {
32800bf5 737 hex = '0' + hex;
e8c4bb74 738 }
32800bf5
D
739
740 return hex;
15fefff7
D
741 }).join('');
742
743 }
744
745 return connect_data;
746}
747
748
db8af19d 749/**
8b967a99 750 * Buffer any data we get from the IRCd until we have complete lines.
db8af19d 751 */
8b967a99
D
752function socketOnData(data) {
753 var data_pos, // Current position within the data Buffer
75083de9
D
754 line_start = 0,
755 lines = [],
ae3506f9 756 i,
f429dec1
JA
757 max_buffer_size = 1024; // 1024 bytes is the maximum length of two RFC1459 IRC messages.
758 // May need tweaking when IRCv3 message tags are more widespread
3ec786bc 759
a8d8af60 760 // Split data chunk into individual lines
75083de9
D
761 for (data_pos = 0; data_pos < data.length; data_pos++) {
762 if (data[data_pos] === 0x0A) { // Check if byte is a line feed
763 lines.push(data.slice(line_start, data_pos));
764 line_start = data_pos + 1;
a8d8af60
JA
765 }
766 }
d1b3e8b3 767
75083de9
D
768 // No complete lines of data? Check to see if buffering the data would exceed the max buffer size
769 if (!lines[0]) {
770 if ((this.held_data ? this.held_data.length : 0 ) + data.length > max_buffer_size) {
f429dec1
JA
771 // Buffering this data would exeed our max buffer size
772 this.emit('error', 'Message buffer too large');
773 this.socket.destroy();
75083de9 774
f429dec1 775 } else {
75083de9
D
776
777 // Append the incomplete line to our held_data and wait for more
f429dec1
JA
778 if (this.held_data) {
779 this.held_data = Buffer.concat([this.held_data, data], this.held_data.length + data.length);
780 } else {
781 this.held_data = data;
782 }
f429dec1 783 }
75083de9
D
784
785 // No complete lines to process..
786 return;
f429dec1
JA
787 }
788
a8d8af60
JA
789 // If we have an incomplete line held from the previous chunk of data
790 // merge it with the first line from this chunk of data
791 if (this.hold_last && this.held_data !== null) {
75083de9 792 lines[0] = Buffer.concat([this.held_data, lines[0]], this.held_data.length + lines[0].length);
2a8e95d1 793 this.hold_last = false;
a8d8af60 794 this.held_data = null;
2a8e95d1 795 }
db8af19d 796
a8d8af60
JA
797 // If the last line of data in this chunk is not complete, hold it so
798 // it can be merged with the first line from the next chunk
75083de9
D
799 if (line_start < data_pos) {
800 if ((data.length - line_start) > max_buffer_size) {
f429dec1
JA
801 // Buffering this data would exeed our max buffer size
802 this.emit('error', 'Message buffer too large');
803 this.socket.destroy();
804 return;
805 }
75083de9 806
2a8e95d1 807 this.hold_last = true;
75083de9
D
808 this.held_data = new Buffer(data.length - line_start);
809 data.copy(this.held_data, 0, line_start);
2a8e95d1 810 }
db8af19d 811
a8d8af60 812 // Process our data line by line
e8c4bb74 813 for (i = 0; i < lines.length; i++) {
8b967a99 814 parseIrcLine.call(this, lines[i]);
e8c4bb74 815 }
8b967a99
D
816
817}
818
819
820
821/**
822 * The regex that parses a line of data from the IRCd
823 * Deviates from the RFC a little to support the '/' character now used in some
824 * IRCds
825 */
b38c590f 826var parse_regex = /^(?:(?:(?:@([^ ]+) )?):(?:([^\s!]+)|([^\s!]+)!([^\s@]+)@?([^\s]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.*))?$/i;
8b967a99
D
827
828function parseIrcLine(buffer_line) {
829 var msg,
17dfa698 830 i,
8b967a99
D
831 tags = [],
832 tag,
17dfa698 833 line = '',
c61b3f74 834 msg_obj;
8b967a99
D
835
836 // Decode server encoding
837 line = iconv.decode(buffer_line, this.encoding);
17dfa698
JA
838 if (!line) {
839 return;
840 }
8b967a99
D
841
842 // Parse the complete line, removing any carriage returns
843 msg = parse_regex.exec(line.replace(/^\r+|\r+$/, ''));
844
845 if (!msg) {
846 // The line was not parsed correctly, must be malformed
94b00b2d 847 winston.warn('Malformed IRC line: %s', line.replace(/^\r+|\r+$/, ''));
8b967a99
D
848 return;
849 }
850
851 // Extract any tags (msg[1])
852 if (msg[1]) {
853 tags = msg[1].split(';');
854
17dfa698
JA
855 for (i = 0; i < tags.length; i++) {
856 tag = tags[i].split('=');
857 tags[i] = {tag: tag[0], value: tag[1]};
2a8e95d1
D
858 }
859 }
8b967a99 860
c61b3f74 861 msg_obj = {
8b967a99
D
862 tags: tags,
863 prefix: msg[2],
864 nick: msg[3],
865 ident: msg[4],
866 hostname: msg[5] || '',
867 command: msg[6],
17dfa698 868 params: msg[7] ? msg[7].split(/ +/) : []
8b967a99
D
869 };
870
17dfa698 871 if (msg[8]) {
c61b3f74 872 msg_obj.params.push(msg[8].trim());
17dfa698
JA
873 }
874
138d8d17 875 this.irc_commands.dispatch(new IrcCommands.Command(msg_obj.command.toUpperCase(), msg_obj));
8b967a99 876}