1 var net
= require('net'),
3 util
= require('util'),
5 EventEmitter2
= require('eventemitter2').EventEmitter2
,
6 IrcServer
= require('./server.js'),
7 IrcChannel
= require('./channel.js'),
8 IrcUser
= require('./user.js');
11 var IrcConnection = function (hostname
, port
, ssl
, nick
, user
, pass
, state
) {
13 EventEmitter2
.call(this,{
19 this.connected
= false;
21 // If registeration with the IRCd has completed
22 this.registered
= false;
24 // If we are in the CAP negotiation stage
25 this.cap_negotiation
= true;
29 this.user
= user
; // Contains users real hostname and address
30 this.username
= this.nick
.replace(/[^0-9a-zA-Z\-_.]/, '');
37 this.server
= new IrcServer(this, hostname
, port
);
40 this.irc_users
= Object
.create(null);
43 this.irc_channels
= Object
.create(null);
45 // Create IrcUser and IrcChannel objects when needed
46 // TODO: Remove IrcUser objects when they are no longer needed
47 this.on('server:*:connect', function (event
) {
48 that
.nick
= event
.nick
;
49 that
.irc_users
[event
.nick
] = new IrcUser(that
, event
.nick
);
51 this.on('channel:*:join', function (event
) {
53 if (event
.nick
=== that
.nick
) {
54 chan
= new IrcChannel(that
, event
.channel
);
55 that
.irc_channels
[event
.channel
] = chan
;
56 chan
.irc_events
.join
.call(chan
, event
);
60 this.on('user:*:privmsg', function (event
) {
62 if (event
.channel
=== that
.nick
) {
63 if (!that
.irc_users
[event
.nick
]) {
64 user
= new IrcUser(that
, event
.nick
);
65 that
.irc_users
[event
.nick
] = user
;
66 user
.irc_events
.privmsg
.call(user
, event
);
71 // IRC connection information
72 this.irc_host
= {hostname
: hostname
, port
: port
};
75 // Options sent by the IRCd
76 this.options
= Object
.create(null);
77 this.cap
= {requested
: [], enabled
: []};
79 // Is SASL supported on the IRCd
82 // Buffers for data sent from the IRCd
83 this.hold_last
= false;
87 // Call any modules before making the connection
88 global
.modules
.emit('irc:connecting', {connection
: this})
93 util
.inherits(IrcConnection
, EventEmitter2
);
95 module
.exports
.IrcConnection
= IrcConnection
;
101 * Start the connection to the IRCd
103 IrcConnection
.prototype.connect = function () {
106 // The socket connect event to listener for
107 var socket_connect_event_name
= 'connect';
110 // Make sure we don't already have an open connection
111 this.disposeSocket();
113 // Open either a secure or plain text socket
115 this.socket
= tls
.connect({
116 host
: this.irc_host
.hostname
,
117 port
: this.irc_host
.port
,
118 rejectUnauthorized
: global
.config
.reject_unauthorised_certificates
121 socket_connect_event_name
= 'secureConnect';
124 this.socket
= net
.connect({
125 host
: this.irc_host
.hostname
,
126 port
: this.irc_host
.port
130 this.socket
.setEncoding('utf-8');
132 this.socket
.on(socket_connect_event_name
, function () {
133 that
.connected
= true;
134 socketConnectHandler
.apply(that
, arguments
);
137 this.socket
.on('error', function (event
) {
138 that
.emit('error', event
);
142 this.socket
.on('data', function () {
143 parse
.apply(that
, arguments
);
146 this.socket
.on('close', function (had_error
) {
147 that
.connected
= false;
150 // Close the whole socket down
151 that
.disposeSocket();
156 * Send an event to the client
158 IrcConnection
.prototype.clientEvent = function (event_name
, data
, callback
) {
159 data
.server
= this.con_num
;
160 this.state
.sendIrcCommand(event_name
, data
, callback
);
164 * Write a line of data to the IRCd
166 IrcConnection
.prototype.write = function (data
, callback
) {
167 this.socket
.write(data
+ '\r\n', 'utf-8', callback
);
173 * Close the connection to the IRCd after sending one last line
175 IrcConnection
.prototype.end = function (data
, callback
) {
185 * Clean up this IrcConnection instance and any sockets
187 IrcConnection
.prototype.dispose = function () {
188 _
.each(this.irc_users
, function (user
) {
191 _
.each(this.irc_channels
, function (chan
) {
194 this.irc_users
= null;
195 this.irc_channels
= null;
196 this.disposeSocket();
197 this.removeAllListeners();
203 * Clean up any sockets for this IrcConnection
205 IrcConnection
.prototype.disposeSocket = function () {
207 this.socket
.removeAllListeners();
215 * Handle the socket connect event, starting the IRCd registration
217 var socketConnectHandler = function () {
221 // Build up data to be used for webirc/etc detection
225 // Array of lines to be sent to the IRCd before anything else
229 // Let the webirc/etc detection modify any required parameters
230 connect_data
= findWebIrc
.call(this, connect_data
);
232 global
.modules
.emit('irc:authorize', connect_data
).done(function () {
233 // Send any initial data for webirc/etc
234 if (connect_data
.prepend_data
) {
235 _
.each(connect_data
.prepend_data
, function(data
) {
240 that
.write('CAP LS');
243 that
.write('PASS ' + that
.password
);
245 that
.write('NICK ' + that
.nick
);
246 that
.write('USER ' + that
.username
+ ' 0 0 :' + '[www.kiwiirc.com] ' + that
.nick
);
248 that
.emit('connected');
255 * Load any WEBIRC or alternative settings for this connection
256 * Called in scope of the IrcConnection instance
258 function findWebIrc(connect_data
) {
259 var webirc_pass
= global
.config
.webirc_pass
,
260 ip_as_username
= global
.config
.ip_as_username
,
264 // Do we have a WEBIRC password for this?
265 if (webirc_pass
&& webirc_pass
[this.irc_host
.hostname
]) {
266 // Build the WEBIRC line to be sent before IRC registration
267 tmp
= 'WEBIRC ' + webirc_pass
[this.irc_host
.hostname
] + ' KiwiIRC ';
268 tmp
+= this.user
.hostname
+ ' ' + this.user
.address
;
270 connect_data
.prepend_data
= [tmp
];
274 // Check if we need to pass the users IP as its username/ident
275 if (ip_as_username
&& ip_as_username
.indexOf(this.irc_host
.hostname
) > -1) {
276 // Get a hex value of the clients IP
277 this.username
= this.user
.address
.split('.').map(function(i
, idx
){
278 return parseInt(i
, 10).toString(16);
289 * The regex that parses a line of data from the IRCd
290 * Deviates from the RFC a little to support the '/' character now used in some
293 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;
295 var parse = function (data
) {
304 if (this.hold_last
&& this.held_data
!== '') {
305 data
= this.held_data
+ data
;
306 this.hold_last
= false;
310 // If the last line is incomplete, hold it until we have more data
311 if (data
.substr(-1) !== '\n') {
312 this.hold_last
= true;
315 // Process our data line by line
316 data
= data
.split("\n");
317 for (i
= 0; i
< data
.length
; i
++) {
320 // If flagged to hold the last line, store it and move on
321 if (this.hold_last
&& (i
=== data
.length
- 1)) {
322 this.held_data
= data
[i
];
326 // Parse the complete line, removing any carriage returns
327 msg
= parse_regex
.exec(data
[i
].replace(/^\r+|\r+$/, ''));
331 tags
= msg
[1].split(';');
332 for (j
= 0; j
< tags
.length
; j
++) {
333 tag
= tags
[j
].split('=');
334 tags
[j
] = {tag
: tag
[0], value
: tag
[1]};
342 hostname
: msg
[5] || '',
344 params
: msg
[7] || '',
345 trailing
: (msg
[8]) ? msg
[8].trim() : ''
347 msg
.params
= msg
.params
.split(' ');
349 this.emit('irc_' + msg
.command
.toUpperCase(), msg
);
353 // The line was not parsed correctly, must be malformed
354 console
.log("Malformed IRC line: " + data
[i
].replace(/^\r+|\r+$/, ''));