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