df9b5b9b1ddec91919554a6659293cea8c21f70f
[KiwiIRC.git] / server / irc / connection.js
1 var net = require('net'),
2 tls = require('tls'),
3 util = require('util'),
4 _ = require('lodash'),
5 EventBinder = require('./eventbinder.js'),
6 IrcServer = require('./server.js'),
7 IrcChannel = require('./channel.js'),
8 IrcUser = require('./user.js'),
9 EE = require('../ee.js'),
10 iconv = require('iconv-lite'),
11 Socks;
12
13
14 // Break the Node.js version down into usable parts
15 var version_values = process.version.substr(1).split('.').map(function (item) {
16 return parseInt(item, 10);
17 });
18
19 // If we have a suitable Nodejs version, bring int he socks functionality
20 if (version_values[1] >= 10) {
21 Socks = require('socksjs');
22 }
23
24 var IrcConnection = function (hostname, port, ssl, nick, user, pass, state) {
25 var that = this;
26
27 EE.call(this,{
28 wildcard: true,
29 delimiter: ' '
30 });
31 this.setMaxListeners(0);
32
33 // Set the first configured encoding as the default encoding
34 this.encoding = global.config.default_encoding;
35
36 // Socket state
37 this.connected = false;
38
39 // If registeration with the IRCd has completed
40 this.registered = false;
41
42 // If we are in the CAP negotiation stage
43 this.cap_negotiation = true;
44
45 // User information
46 this.nick = nick;
47 this.user = user; // Contains users real hostname and address
48 this.username = this.nick.replace(/[^0-9a-zA-Z\-_.\/]/, '');
49 this.password = pass;
50
51 // State object
52 this.state = state;
53
54 // IrcServer object
55 this.server = new IrcServer(this, hostname, port);
56
57 // IrcUser objects
58 this.irc_users = Object.create(null);
59
60 // TODO: use `this.nick` instead of `'*'` when using an IrcUser per nick
61 this.irc_users[this.nick] = new IrcUser(this, '*');
62
63 // IrcChannel objects
64 this.irc_channels = Object.create(null);
65
66 // IRC connection information
67 this.irc_host = {hostname: hostname, port: port};
68 this.ssl = !(!ssl);
69
70 // SOCKS proxy details
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 }
82
83 // Options sent by the IRCd
84 this.options = Object.create(null);
85 this.cap = {requested: [], enabled: []};
86
87 // Is SASL supported on the IRCd
88 this.sasl = false;
89
90 // Buffers for data sent from the IRCd
91 this.hold_last = false;
92 this.held_data = '';
93
94 this.applyIrcEvents();
95 };
96 util.inherits(IrcConnection, EE);
97
98 module.exports.IrcConnection = IrcConnection;
99
100
101
102 IrcConnection.prototype.applyIrcEvents = function () {
103 // Listen for events on the IRC connection
104 this.irc_events = {
105 'server * connect': onServerConnect,
106 'channel * join': onChannelJoin,
107
108 // TODO: uncomment when using an IrcUser per nick
109 //'user:*:privmsg': onUserPrivmsg,
110 'user * nick': onUserNick,
111 'channel * part': onUserParts,
112 'channel * quit': onUserParts,
113 'channel * kick': onUserKick
114 };
115
116 EventBinder.bindIrcEvents('', this.irc_events, this, this);
117 };
118
119
120 /**
121 * Start the connection to the IRCd
122 */
123 IrcConnection.prototype.connect = function () {
124 var that = this;
125 var socks;
126
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
134 // Are we connecting through a SOCKS proxy?
135 if (this.socks) {
136 this.socket = Socks.connect({
137 host: this.irc_host.hostname,
138 port: this.irc_host.port,
139 ssl: this.ssl,
140 rejectUnauthorized: global.config.reject_unauthorised_certificates
141 }, {host: this.socks.host,
142 port: this.socks.port,
143 user: this.socks.user,
144 pass: this.socks.pass
145 });
146
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
152 });
153
154 socket_connect_event_name = 'secureConnect';
155
156 } else {
157 this.socket = net.connect({
158 host: this.irc_host.hostname,
159 port: this.irc_host.port
160 });
161 }
162
163 this.socket.on(socket_connect_event_name, function () {
164 that.connected = true;
165 socketConnectHandler.call(that);
166 });
167
168 this.socket.on('error', function (event) {
169 that.emit('error', event);
170 });
171
172 this.socket.on('data', function () {
173 parse.apply(that, arguments);
174 });
175
176 this.socket.on('close', function (had_error) {
177 that.connected = false;
178 that.emit('close');
179
180 // Close the whole socket down
181 that.disposeSocket();
182 });
183 };
184
185 /**
186 * Send an event to the client
187 */
188 IrcConnection.prototype.clientEvent = function (event_name, data, callback) {
189 data.server = this.con_num;
190 this.state.sendIrcCommand(event_name, data, callback);
191 };
192
193 /**
194 * Write a line of data to the IRCd
195 */
196 IrcConnection.prototype.write = function (data, callback) {
197 //ENCODE string to encoding of the server
198 encoded_buffer = iconv.encode(data + '\r\n', this.encoding);
199 this.socket.write(encoded_buffer);
200 };
201
202
203
204 /**
205 * Close the connection to the IRCd after sending one last line
206 */
207 IrcConnection.prototype.end = function (data, callback) {
208 if (data)
209 this.write(data);
210
211 this.socket.end();
212 };
213
214
215
216 /**
217 * Clean up this IrcConnection instance and any sockets
218 */
219 IrcConnection.prototype.dispose = function () {
220 var that = this;
221
222 _.each(this.irc_users, function (user) {
223 user.dispose();
224 });
225 _.each(this.irc_channels, function (chan) {
226 chan.dispose();
227 });
228 this.irc_users = undefined;
229 this.irc_channels = undefined;
230
231 this.server.dispose();
232 this.server = undefined;
233
234 EventBinder.unbindIrcEvents('', this.irc_events, this);
235
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 }
250 };
251
252
253
254 /**
255 * Clean up any sockets for this IrcConnection
256 */
257 IrcConnection.prototype.disposeSocket = function () {
258 if (this.socket) {
259 this.socket.end();
260 this.socket.removeAllListeners();
261 this.socket = null;
262 }
263 };
264
265 /**
266 * Set a new encoding for this connection
267 * Return true in case of success
268 */
269
270 IrcConnection.prototype.setEncoding = function (encoding) {
271 var encoded_test;
272
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;
285 }
286 };
287
288
289 function 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
308 function onServerConnect(event) {
309 this.nick = event.nick;
310 }
311
312
313 function 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
328 function 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
339 function 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
350 function 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
362
363
364
365 /**
366 * Handle the socket connect event, starting the IRCd registration
367 */
368 var socketConnectHandler = function () {
369 var that = this,
370 connect_data;
371
372 // Build up data to be used for webirc/etc detection
373 connect_data = {
374 connection: this,
375
376 // Array of lines to be sent to the IRCd before anything else
377 prepend_data: []
378 };
379
380 // Let the webirc/etc detection modify any required parameters
381 connect_data = findWebIrc.call(this, connect_data);
382
383 global.modules.emit('irc authorize', connect_data).done(function () {
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
393 if (that.password)
394 that.write('PASS ' + that.password);
395
396 that.write('NICK ' + that.nick);
397 that.write('USER ' + that.username + ' 0 0 :' + '[www.kiwiirc.com] ' + that.nick);
398
399 that.emit('connected');
400 });
401 };
402
403
404
405 /**
406 * Load any WEBIRC or alternative settings for this connection
407 * Called in scope of the IrcConnection instance
408 */
409 function findWebIrc(connect_data) {
410 var webirc_pass = global.config.webirc_pass,
411 ip_as_username = global.config.ip_as_username,
412 tmp;
413
414
415 // Do we have a WEBIRC password for this?
416 if (webirc_pass && webirc_pass[this.irc_host.hostname]) {
417 // Build the WEBIRC line to be sent before IRC registration
418 tmp = 'WEBIRC ' + webirc_pass[this.irc_host.hostname] + ' KiwiIRC ';
419 tmp += this.user.hostname + ' ' + this.user.address;
420
421 connect_data.prepend_data = [tmp];
422 }
423
424
425 // Check if we need to pass the users IP as its username/ident
426 if (ip_as_username && ip_as_username.indexOf(this.irc_host.hostname) > -1) {
427 // Get a hex value of the clients IP
428 this.username = this.user.address.split('.').map(function(i, idx){
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;
436 }).join('');
437
438 }
439
440 return connect_data;
441 }
442
443
444
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 */
450 var parse_regex = /^(?:(?:(?:(@[^ ]+) )?):(?:([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)|([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)!([^\x00\r\n\ ]+?)@?([a-z0-9\.\-:\/_]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.+))?$/i;
451
452 var parse = function (data) {
453 var i,
454 msg,
455 msg2,
456 trm,
457 j,
458 tags = [],
459 tag;
460
461 //DECODE server encoding
462 data = iconv.decode(data, this.encoding);
463
464 if (this.hold_last && this.held_data !== '') {
465 data = this.held_data + data;
466 this.hold_last = false;
467 this.held_data = '';
468 }
469
470 // If the last line is incomplete, hold it until we have more data
471 if (data.substr(-1) !== '\n') {
472 this.hold_last = true;
473 }
474
475 // Process our data line by line
476 data = data.split("\n");
477 for (i = 0; i < data.length; i++) {
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 }
485
486 // Parse the complete line, removing any carriage returns
487 msg = parse_regex.exec(data[i].replace(/^\r+|\r+$/, ''));
488
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]};
495 }
496 }
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(' ');
508 this.irc_commands.dispatch(msg.command.toUpperCase(), msg);
509 } else {
510 // The line was not parsed correctly, must be malformed
511 console.log("Malformed IRC line: " + data[i].replace(/^\r+|\r+$/, ''));
512 }
513 }
514 };