1 var net
= require('net'),
3 util
= require('util'),
5 EventEmitter2
= require('eventemitter2').EventEmitter2
,
6 EventBinder
= require('./eventbinder.js'),
7 IrcServer
= require('./server.js'),
8 IrcChannel
= require('./channel.js'),
9 IrcUser
= require('./user.js'),
13 // Break the Node.js version down into usable parts
14 var version_values
= process
.version
.substr(1).split('.').map(function (item
) {
15 return parseInt(item
, 10);
18 // If we have a suitable Nodejs version, bring int he socks functionality
19 if (version_values
[1] >= 10) {
20 Socks
= require('../socks.js');
23 var IrcConnection = function (hostname
, port
, ssl
, nick
, user
, pass
, state
) {
26 EventEmitter2
.call(this,{
30 this.setMaxListeners(0);
33 this.connected
= false;
35 // If registeration with the IRCd has completed
36 this.registered
= false;
38 // If we are in the CAP negotiation stage
39 this.cap_negotiation
= true;
43 this.user
= user
; // Contains users real hostname and address
44 this.username
= this.nick
.replace(/[^0-9a-zA-Z\-_.\/]/, '');
51 this.server
= new IrcServer(this, hostname
, port
);
54 this.irc_users
= Object
.create(null);
57 this.irc_channels
= Object
.create(null);
59 // IRC connection information
60 this.irc_host
= {hostname
: hostname
, port
: port
};
63 // SOCKS proxy details
64 // TODO: Wildcard matching of hostnames and/or CIDR ranges of IP addresses
65 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
)))) {
67 host
: global
.config
.socks_proxy
.address
,
68 port
: global
.config
.socks_proxy
.port
,
69 user
: global
.config
.socks_proxy
.user
,
70 pass
: global
.config
.socks_proxy
.pass
76 // Options sent by the IRCd
77 this.options
= Object
.create(null);
78 this.cap
= {requested
: [], enabled
: []};
80 // Is SASL supported on the IRCd
83 // Buffers for data sent from the IRCd
84 this.hold_last
= false;
87 this.applyIrcEvents();
89 // Call any modules before making the connection
90 global
.modules
.emit('irc:connecting', {connection
: this})
95 util
.inherits(IrcConnection
, EventEmitter2
);
97 module
.exports
.IrcConnection
= IrcConnection
;
101 IrcConnection
.prototype.applyIrcEvents = function () {
102 // Listen for events on the IRC connection
104 'server:*:connect': onServerConnect
,
105 'channel:*:join': onChannelJoin
,
107 // TODO: uncomment when using an IrcUser per nick
108 //'user:*:privmsg': onUserPrivmsg,
109 'user:*:nick': onUserNick
,
110 'channel:*:part': onUserParts
,
111 'channel:*:quit': onUserParts
,
112 'channel:*:kick': onUserParts
115 EventBinder
.bindIrcEvents('', this.irc_events
, this, this);
120 * Start the connection to the IRCd
122 IrcConnection
.prototype.connect = function () {
126 // The socket connect event to listener for
127 var socket_connect_event_name
= 'connect';
130 // Make sure we don't already have an open connection
131 this.disposeSocket();
133 // Are we connecting through a SOCKS proxy?
135 this.socket
= Socks
.connect({
136 host
: this.irc_host
.hostname
,
137 port
: this.irc_host
.port
,
139 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
140 }, {host
: this.socks
.host
,
141 port
: this.socks
.port
,
142 user
: this.socks
.user
,
143 pass
: this.socks
.pass
146 } else if (this.ssl
) {
147 this.socket
= tls
.connect({
148 host
: this.irc_host
.hostname
,
149 port
: this.irc_host
.port
,
150 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
153 socket_connect_event_name
= 'secureConnect';
156 this.socket
= net
.connect({
157 host
: this.irc_host
.hostname
,
158 port
: this.irc_host
.port
162 this.socket
.on(socket_connect_event_name
, function () {
163 that
.connected
= true;
164 socketConnectHandler
.call(that
);
167 this.socket
.setEncoding('utf-8');
169 this.socket
.on('error', function (event
) {
170 that
.emit('error', event
);
174 this.socket
.on('data', function () {
175 parse
.apply(that
, arguments
);
178 this.socket
.on('close', function (had_error
) {
179 that
.connected
= false;
182 // Close the whole socket down
183 that
.disposeSocket();
188 * Send an event to the client
190 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
191 data
.server
= this.con_num
;
192 this.state
.sendIrcCommand(event_name
, data
, callback
);
196 * Write a line of data to the IRCd
198 IrcConnection
.prototype.write = function (data
, callback
) {
199 this.socket
.write(data
+ '\r\n', 'utf-8', callback
);
205 * Close the connection to the IRCd after sending one last line
207 IrcConnection
.prototype.end = function (data
, callback
) {
217 * Clean up this IrcConnection instance and any sockets
219 IrcConnection
.prototype.dispose = function () {
220 _
.each(this.irc_users
, function (user
) {
223 _
.each(this.irc_channels
, function (chan
) {
226 this.irc_users
= undefined;
227 this.irc_channels
= undefined;
229 this.server
.dispose();
230 this.server
= undefined;
232 EventBinder
.unbindIrcEvents('', this.irc_events
, this);
234 this.disposeSocket();
235 this.removeAllListeners();
241 * Clean up any sockets for this IrcConnection
243 IrcConnection
.prototype.disposeSocket = function () {
246 this.socket
.removeAllListeners();
253 function onChannelJoin(event
) {
256 // Only deal with ourselves joining a channel
257 if (event
.nick
!== this.nick
)
260 // We should only ever get a JOIN command for a channel
261 // we're not already a member of.. but check we don't
262 // have this channel in case something went wrong somewhere
263 // at an earlier point
264 if (!this.irc_channels
[event
.channel
]) {
265 chan
= new IrcChannel(this, event
.channel
);
266 this.irc_channels
[event
.channel
] = chan
;
267 chan
.irc_events
.join
.call(chan
, event
);
272 function onServerConnect(event
) {
273 this.nick
= event
.nick
;
275 // TODO: use `event.nick` instead of `'*'` when using an IrcUser per nick
276 this.irc_users
[event
.nick
] = new IrcUser(this, '*');
280 function onUserPrivmsg(event
) {
283 // Only deal with messages targetted to us
284 if (event
.channel
!== this.nick
)
287 if (!this.irc_users
[event
.nick
]) {
288 user
= new IrcUser(this, event
.nick
);
289 this.irc_users
[event
.nick
] = user
;
290 user
.irc_events
.privmsg
.call(user
, event
);
295 function onUserNick(event
) {
298 // Only deal with messages targetted to us
299 if (event
.nick
!== this.nick
)
302 this.nick
= event
.newnick
;
306 function onUserParts(event
) {
307 // Only deal with ourselves leaving a channel
308 if (event
.nick
!== this.nick
)
311 if (this.irc_channels
[event
.channel
]) {
312 this.irc_channels
[event
.channel
].dispose();
313 delete this.irc_channels
[event
.channel
];
321 * Handle the socket connect event, starting the IRCd registration
323 var socketConnectHandler = function () {
327 // Build up data to be used for webirc/etc detection
331 // Array of lines to be sent to the IRCd before anything else
335 // Let the webirc/etc detection modify any required parameters
336 connect_data
= findWebIrc
.call(this, connect_data
);
338 global
.modules
.emit('irc:authorize', connect_data
).done(function () {
339 // Send any initial data for webirc/etc
340 if (connect_data
.prepend_data
) {
341 _
.each(connect_data
.prepend_data
, function(data
) {
346 that
.write('CAP LS');
349 that
.write('PASS ' + that
.password
);
351 that
.write('NICK ' + that
.nick
);
352 that
.write('USER ' + that
.username
+ ' 0 0 :' + '[www.kiwiirc.com] ' + that
.nick
);
354 that
.emit('connected');
361 * Load any WEBIRC or alternative settings for this connection
362 * Called in scope of the IrcConnection instance
364 function findWebIrc(connect_data
) {
365 var webirc_pass
= global
.config
.webirc_pass
,
366 ip_as_username
= global
.config
.ip_as_username
,
370 // Do we have a WEBIRC password for this?
371 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
372 // Build the WEBIRC line to be sent before IRC registration
373 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
374 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
376 connect_data
.prepend_data
= [tmp
];
380 // Check if we need to pass the users IP as its username/ident
381 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
382 // Get a hex value of the clients IP
383 this.username
= this.user
.address
.split('.').map(function(i
, idx
){
384 return parseInt(i
, 10).toString(16);
395 * The regex that parses a line of data from the IRCd
396 * Deviates from the RFC a little to support the '/' character now used in some
399 var parse_regex
= /^(?:(?:(?:(@[^ ]+) )?):(?:([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)|([a-z0-9\x5B-\x60\x7B-\x7D\.\-*]+)!([a-z0-9~\.\-_|]+)@?([a-z0-9\.\-:\/_]+)?) )?(\S+)(?: (?!:)(.+?))?(?: :(.+))?$/i;
401 var parse = function (data
) {
410 if (this.hold_last
&& this.held_data
!== '') {
411 data
= this.held_data
+ data
;
412 this.hold_last
= false;
416 // If the last line is incomplete, hold it until we have more data
417 if (data
.substr(-1) !== '\n') {
418 this.hold_last
= true;
421 // Process our data line by line
422 data
= data
.split("\n");
423 for (i
= 0; i
< data
.length
; i
++) {
426 // If flagged to hold the last line, store it and move on
427 if (this.hold_last
&& (i
=== data
.length
- 1)) {
428 this.held_data
= data
[i
];
432 // Parse the complete line, removing any carriage returns
433 msg
= parse_regex
.exec(data
[i
].replace(/^\r+|\r+$/, ''));
437 tags
= msg
[1].split(';');
438 for (j
= 0; j
< tags
.length
; j
++) {
439 tag
= tags
[j
].split('=');
440 tags
[j
] = {tag
: tag
[0], value
: tag
[1]};
448 hostname
: msg
[5] || '',
450 params
: msg
[7] || '',
451 trailing
: (msg
[8]) ? msg
[8].trim() : ''
453 msg
.params
= msg
.params
.split(' ');
455 this.emit('irc_' + msg
.command
.toUpperCase(), msg
);
459 // The line was not parsed correctly, must be malformed
460 console
.log("Malformed IRC line: " + data
[i
].replace(/^\r+|\r+$/, ''));