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