Server module refactor; Control module refactor;
[KiwiIRC.git] / server / irc / connection.js
CommitLineData
cefa0900
JA
1var net = require('net'),
2 tls = require('tls'),
3 util = require('util'),
4 _ = require('lodash'),
4c25c0d7 5 EventBinder = require('./eventbinder.js'),
cefa0900
JA
6 IrcServer = require('./server.js'),
7 IrcChannel = require('./channel.js'),
9650b343 8 IrcUser = require('./user.js'),
2abb4615 9 EE = require('../ee.js'),
1a452a02 10 iconv = require('iconv-lite'),
55ccaf50 11 Socks;
32a09dc1
D
12
13
55ccaf50
JA
14// Break the Node.js version down into usable parts
15var version_values = process.version.substr(1).split('.').map(function (item) {
16 return parseInt(item, 10);
17});
9de636f9 18
55ccaf50 19// If we have a suitable Nodejs version, bring int he socks functionality
9de636f9 20if (version_values[1] >= 10) {
3b259b15 21 Socks = require('socksjs');
55ccaf50 22}
db8af19d 23
b09157de 24var IrcConnection = function (hostname, port, ssl, nick, user, pass, state) {
2a8e95d1 25 var that = this;
4c25c0d7 26
2abb4615 27 EE.call(this,{
cefa0900 28 wildcard: true,
d9285da9 29 delimiter: ' '
cefa0900 30 });
4c25c0d7 31 this.setMaxListeners(0);
32a09dc1 32
d1b3e8b3 33 // Set the first configured encoding as the default encoding
3efb4f33 34 this.encoding = global.config.default_encoding;
d1b3e8b3 35
db8af19d 36 // Socket state
63008d5e 37 this.connected = false;
db8af19d
D
38
39 // If registeration with the IRCd has completed
63008d5e 40 this.registered = false;
db8af19d
D
41
42 // If we are in the CAP negotiation stage
63008d5e 43 this.cap_negotiation = true;
db8af19d
D
44
45 // User information
63008d5e
D
46 this.nick = nick;
47 this.user = user; // Contains users real hostname and address
5973d01c 48 this.username = this.nick.replace(/[^0-9a-zA-Z\-_.\/]/, '');
db8af19d 49 this.password = pass;
32a09dc1 50
b09157de
JA
51 // State object
52 this.state = state;
32a09dc1 53
cefa0900
JA
54 // IrcServer object
55 this.server = new IrcServer(this, hostname, port);
32a09dc1 56
cefa0900
JA
57 // IrcUser objects
58 this.irc_users = Object.create(null);
efe9d487
D
59
60 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
61 this.irc_users[this.nick] = new IrcUser(this, '*');
62
cefa0900
JA
63 // IrcChannel objects
64 this.irc_channels = Object.create(null);
db8af19d
D
65
66 // IRC connection information
63008d5e
D
67 this.irc_host = {hostname: hostname, port: port};
68 this.ssl = !(!ssl);
32a09dc1 69
9650b343 70 // SOCKS proxy details
ac0b278c
JA
71 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
72 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)))) {
73 this.socks = {
74 host: global.config.socks_proxy.address,
75 port: global.config.socks_proxy.port,
76 user: global.config.socks_proxy.user,
77 pass: global.config.socks_proxy.pass
78 };
79 } else {
80 this.socks = false;
81 }
db8af19d
D
82
83 // Options sent by the IRCd
63008d5e
D
84 this.options = Object.create(null);
85 this.cap = {requested: [], enabled: []};
db8af19d
D
86
87 // Is SASL supported on the IRCd
63008d5e 88 this.sasl = false;
32a09dc1 89
db8af19d 90 // Buffers for data sent from the IRCd
63008d5e
D
91 this.hold_last = false;
92 this.held_data = '';
93
4c25c0d7 94 this.applyIrcEvents();
63008d5e 95};
2abb4615 96util.inherits(IrcConnection, EE);
63008d5e
D
97
98module.exports.IrcConnection = IrcConnection;
99
f9ff7686 100
db8af19d 101
4c25c0d7
D
102IrcConnection.prototype.applyIrcEvents = function () {
103 // Listen for events on the IRC connection
104 this.irc_events = {
d9285da9
JA
105 'server * connect': onServerConnect,
106 'channel * join': onChannelJoin,
df6d68a5
D
107
108 // TODO: uncomment when using an IrcUser per nick
109 //'user:*:privmsg': onUserPrivmsg,
d9285da9
JA
110 'user * nick': onUserNick,
111 'channel * part': onUserParts,
112 'channel * quit': onUserParts,
113 'channel * kick': onUserKick
4c25c0d7
D
114 };
115
116 EventBinder.bindIrcEvents('', this.irc_events, this, this);
117};
118
db8af19d
D
119
120/**
121 * Start the connection to the IRCd
122 */
63008d5e
D
123IrcConnection.prototype.connect = function () {
124 var that = this;
9650b343 125 var socks;
63008d5e 126
db8af19d
D
127 // The socket connect event to listener for
128 var socket_connect_event_name = 'connect';
129
130
131 // Make sure we don't already have an open connection
132 this.disposeSocket();
133
9650b343
JA
134 // Are we connecting through a SOCKS proxy?
135 if (this.socks) {
57c22370 136 this.socket = Socks.connect({
32a09dc1 137 host: this.irc_host.hostname,
63008d5e 138 port: this.irc_host.port,
57c22370
JA
139 ssl: this.ssl,
140 rejectUnauthorized: global.config.reject_unauthorised_certificates
9650b343
JA
141 }, {host: this.socks.host,
142 port: this.socks.port,
143 user: this.socks.user,
144 pass: this.socks.pass
145 });
32a09dc1 146
57c22370
JA
147 } else if (this.ssl) {
148 this.socket = tls.connect({
149 host: this.irc_host.hostname,
150 port: this.irc_host.port,
151 rejectUnauthorized: global.config.reject_unauthorised_certificates
36108ca9 152 });
57c22370
JA
153
154 socket_connect_event_name = 'secureConnect';
155
2a8e95d1 156 } else {
57c22370
JA
157 this.socket = net.connect({
158 host: this.irc_host.hostname,
159 port: this.irc_host.port
2a8e95d1
D
160 });
161 }
32a09dc1 162
57c22370
JA
163 this.socket.on(socket_connect_event_name, function () {
164 that.connected = true;
165 socketConnectHandler.call(that);
166 });
32a09dc1 167
d2d91c10
D
168 this.socket.on('error', function (event) {
169 that.emit('error', event);
2a8e95d1 170 });
32a09dc1 171
2a8e95d1
D
172 this.socket.on('data', function () {
173 parse.apply(that, arguments);
174 });
32a09dc1 175
db8af19d
D
176 this.socket.on('close', function (had_error) {
177 that.connected = false;
2a8e95d1 178 that.emit('close');
db8af19d
D
179
180 // Close the whole socket down
181 that.disposeSocket();
2a8e95d1 182 });
2a8e95d1 183};
2a8e95d1 184
3c91bff8
JA
185/**
186 * Send an event to the client
187 */
188IrcConnection.prototype.clientEvent = function (event_name, data, callback) {
189 data.server = this.con_num;
190 this.state.sendIrcCommand(event_name, data, callback);
191};
db8af19d
D
192
193/**
194 * Write a line of data to the IRCd
195 */
2a8e95d1 196IrcConnection.prototype.write = function (data, callback) {
1a452a02 197 //ENCODE string to encoding of the server
d1b3e8b3 198 encoded_buffer = iconv.encode(data + '\r\n', this.encoding);
1a452a02 199 this.socket.write(encoded_buffer);
2a8e95d1
D
200};
201
db8af19d
D
202
203
204/**
205 * Close the connection to the IRCd after sending one last line
206 */
2a8e95d1 207IrcConnection.prototype.end = function (data, callback) {
db8af19d
D
208 if (data)
209 this.write(data);
32a09dc1 210
db8af19d 211 this.socket.end();
2a8e95d1
D
212};
213
db8af19d
D
214
215
216/**
217 * Clean up this IrcConnection instance and any sockets
218 */
c08717da 219IrcConnection.prototype.dispose = function () {
5e211c3d
D
220 var that = this;
221
cefa0900
JA
222 _.each(this.irc_users, function (user) {
223 user.dispose();
224 });
225 _.each(this.irc_channels, function (chan) {
226 chan.dispose();
227 });
ebe178d6
D
228 this.irc_users = undefined;
229 this.irc_channels = undefined;
230
231 this.server.dispose();
232 this.server = undefined;
4c25c0d7
D
233
234 EventBinder.unbindIrcEvents('', this.irc_events, this);
235
5e211c3d
D
236 // If we're still connected, wait until the socket is closed before disposing
237 // so that all the events are still correctly triggered
238 if (this.socket && this.connected) {
239 this.socket.once('close', function() {
240 that.disposeSocket();
241 that.removeAllListeners();
242 });
243
244 this.socket.end();
245
246 } else {
247 this.disposeSocket();
248 this.removeAllListeners();
249 }
c08717da
D
250};
251
252
2a8e95d1 253
db8af19d
D
254/**
255 * Clean up any sockets for this IrcConnection
256 */
257IrcConnection.prototype.disposeSocket = function () {
258 if (this.socket) {
6b8fa7a6 259 this.socket.end();
db8af19d
D
260 this.socket.removeAllListeners();
261 this.socket = null;
262 }
2a8e95d1
D
263};
264
d1b3e8b3
VDF
265/**
266 * Set a new encoding for this connection
267 * Return true in case of success
268 */
269
270IrcConnection.prototype.setEncoding = function (encoding) {
3ddc135a
D
271 var encoded_test;
272
3efb4f33
VDF
273 try {
274 encoded_test = iconv.encode("TEST", encoding);
275 //This test is done to check if this encoding also supports
276 //the ASCII charset required by the IRC protocols
277 //(Avoid the use of base64 or incompatible encodings)
278 if (encoded_test == "TEST") {
279 this.encoding = encoding;
280 return true;
281 }
282 return false;
283 } catch (err) {
284 return false;
65c5a477 285 }
d1b3e8b3 286};
2a8e95d1 287
db8af19d 288
4c25c0d7
D
289function onChannelJoin(event) {
290 var chan;
291
292 // Only deal with ourselves joining a channel
293 if (event.nick !== this.nick)
294 return;
295
296 // We should only ever get a JOIN command for a channel
297 // we're not already a member of.. but check we don't
298 // have this channel in case something went wrong somewhere
299 // at an earlier point
300 if (!this.irc_channels[event.channel]) {
301 chan = new IrcChannel(this, event.channel);
302 this.irc_channels[event.channel] = chan;
303 chan.irc_events.join.call(chan, event);
304 }
305}
306
307
308function onServerConnect(event) {
309 this.nick = event.nick;
4c25c0d7
D
310}
311
312
313function onUserPrivmsg(event) {
314 var user;
315
316 // Only deal with messages targetted to us
317 if (event.channel !== this.nick)
318 return;
319
320 if (!this.irc_users[event.nick]) {
321 user = new IrcUser(this, event.nick);
322 this.irc_users[event.nick] = user;
323 user.irc_events.privmsg.call(user, event);
324 }
325}
326
327
9be602fc
D
328function onUserNick(event) {
329 var user;
330
331 // Only deal with messages targetted to us
332 if (event.nick !== this.nick)
333 return;
334
335 this.nick = event.newnick;
336}
337
338
4c25c0d7
D
339function onUserParts(event) {
340 // Only deal with ourselves leaving a channel
341 if (event.nick !== this.nick)
342 return;
343
344 if (this.irc_channels[event.channel]) {
345 this.irc_channels[event.channel].dispose();
346 delete this.irc_channels[event.channel];
347 }
348}
349
6d2df752
MC
350function onUserKick(event){
351 // Only deal with ourselves being kicked from a channel
352 if (event.kicked !== this.nick)
353 return;
354
355 if (this.irc_channels[event.channel]) {
356 this.irc_channels[event.channel].dispose();
357 delete this.irc_channels[event.channel];
358 }
359
360}
361
4c25c0d7
D
362
363
364
db8af19d
D
365/**
366 * Handle the socket connect event, starting the IRCd registration
367 */
368var socketConnectHandler = function () {
15fefff7
D
369 var that = this,
370 connect_data;
371
372 // Build up data to be used for webirc/etc detection
373 connect_data = {
bd7196e1
D
374 connection: this,
375
376 // Array of lines to be sent to the IRCd before anything else
377 prepend_data: []
15fefff7
D
378 };
379
380 // Let the webirc/etc detection modify any required parameters
266b5087 381 connect_data = findWebIrc.call(this, connect_data);
15fefff7 382
d9285da9 383 global.modules.emit('irc authorize', connect_data).done(function () {
bd7196e1
D
384 // Send any initial data for webirc/etc
385 if (connect_data.prepend_data) {
386 _.each(connect_data.prepend_data, function(data) {
387 that.write(data);
388 });
389 }
390
391 that.write('CAP LS');
392
db8af19d 393 if (that.password)
bd7196e1 394 that.write('PASS ' + that.password);
32a09dc1 395
bd7196e1
D
396 that.write('NICK ' + that.nick);
397 that.write('USER ' + that.username + ' 0 0 :' + '[www.kiwiirc.com] ' + that.nick);
32a09dc1 398
bd7196e1
D
399 that.emit('connected');
400 });
7dfe47c6 401};
2a8e95d1 402
15fefff7 403
db8af19d
D
404
405/**
406 * Load any WEBIRC or alternative settings for this connection
407 * Called in scope of the IrcConnection instance
408 */
15fefff7 409function findWebIrc(connect_data) {
db8af19d
D
410 var webirc_pass = global.config.webirc_pass,
411 ip_as_username = global.config.ip_as_username,
412 tmp;
413
15fefff7
D
414
415 // Do we have a WEBIRC password for this?
bd7196e1 416 if (webirc_pass && webirc_pass[this.irc_host.hostname]) {
db8af19d 417 // Build the WEBIRC line to be sent before IRC registration
bd7196e1
D
418 tmp = 'WEBIRC ' + webirc_pass[this.irc_host.hostname] + ' KiwiIRC ';
419 tmp += this.user.hostname + ' ' + this.user.address;
db8af19d 420
15fefff7
D
421 connect_data.prepend_data = [tmp];
422 }
423
424
425 // Check if we need to pass the users IP as its username/ident
bd7196e1 426 if (ip_as_username && ip_as_username.indexOf(this.irc_host.hostname) > -1) {
15fefff7 427 // Get a hex value of the clients IP
bd7196e1 428 this.username = this.user.address.split('.').map(function(i, idx){
32800bf5
D
429 var hex = parseInt(i, 10).toString(16);
430
431 // Pad out the hex value if it's a single char
432 if (hex.length === 1)
433 hex = '0' + hex;
434
435 return hex;
15fefff7
D
436 }).join('');
437
438 }
439
440 return connect_data;
441}
442
443
444
db8af19d
D
445/**
446 * The regex that parses a line of data from the IRCd
447 * Deviates from the RFC a little to support the '/' character now used in some
448 * IRCds
449 */
85e1be6c 450var parse_regex = /^(?:(?:(?:(@[^ ]+) )?):(?:([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)|([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)!([^\x00\r\n\ ]+?)@?([a-z0-9\.\-:\/_]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.+))?$/i;
db8af19d 451
2a8e95d1
D
452var parse = function (data) {
453 var i,
454 msg,
16e717f5
JA
455 msg2,
456 trm,
457 j,
458 tags = [],
459 tag;
3ec786bc 460
1a452a02 461 //DECODE server encoding
d1b3e8b3 462 data = iconv.decode(data, this.encoding);
d1b3e8b3 463
db8af19d 464 if (this.hold_last && this.held_data !== '') {
2a8e95d1
D
465 data = this.held_data + data;
466 this.hold_last = false;
467 this.held_data = '';
468 }
db8af19d
D
469
470 // If the last line is incomplete, hold it until we have more data
2a8e95d1
D
471 if (data.substr(-1) !== '\n') {
472 this.hold_last = true;
473 }
db8af19d
D
474
475 // Process our data line by line
2a8e95d1
D
476 data = data.split("\n");
477 for (i = 0; i < data.length; i++) {
db8af19d
D
478 if (!data[i]) break;
479
480 // If flagged to hold the last line, store it and move on
481 if (this.hold_last && (i === data.length - 1)) {
482 this.held_data = data[i];
483 break;
484 }
1a452a02 485
db8af19d
D
486 // Parse the complete line, removing any carriage returns
487 msg = parse_regex.exec(data[i].replace(/^\r+|\r+$/, ''));
2a8e95d1 488
db8af19d
D
489 if (msg) {
490 if (msg[1]) {
491 tags = msg[1].split(';');
492 for (j = 0; j < tags.length; j++) {
493 tag = tags[j].split('=');
494 tags[j] = {tag: tag[0], value: tag[1]};
16e717f5 495 }
2a8e95d1 496 }
db8af19d
D
497 msg = {
498 tags: tags,
499 prefix: msg[2],
500 nick: msg[3],
501 ident: msg[4],
502 hostname: msg[5] || '',
503 command: msg[6],
504 params: msg[7] || '',
505 trailing: (msg[8]) ? msg[8].trim() : ''
506 };
507 msg.params = msg.params.split(' ');
3ec786bc 508 this.irc_commands.dispatch(msg.command.toUpperCase(), msg);
db8af19d 509 } else {
db8af19d
D
510 // The line was not parsed correctly, must be malformed
511 console.log("Malformed IRC line: " + data[i].replace(/^\r+|\r+$/, ''));
2a8e95d1
D
512 }
513 }
514};