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