-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
4525 lines (4084 loc) · 151 KB
/
server.js
File metadata and controls
4525 lines (4084 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
Copyright (c) 2013, Grosan Flaviu Gheorghe
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL GROSAN FLAVIU GHEORGHE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Load various required libraries:
var _ = require('lodash') // http://lodash.com/
,fs = require('fs') // Standard file system
,util = require( 'util' ) // Standard utility
,logFacility = require( 'log4js' ); // https://github.com/nomiddlename/log4js-node
// BIG TODO: Separate authenticated/non-authenticated user commands!
/**
* Web Messaging server.
* @class Provides Web Socket server functionality.
* @constructor
* @param {Object} config Server configuration object. Supported keys are: port (listening port number), socket (socket listener configuration object),
* optional 'scope' object used for maintaining a custom scope reference,
* optional 'connectionHandler' connection handler,
* and an events object providing event handler functionality.
*/
var WEBServer = function( config ) {
// Store configuation, in a 'private' property
this._config = config;
}
/**
* Method used for attaching socket events and their handlers.
* NOTE: Event names and functions are stored in the config.events object.
* NOTE: The scope of each event handler is bound to the configured 'scope' object.
* @param {Object} socket Socket object.
* @function
*/
WEBServer.prototype.attachSocketEvents = function( socket ) {
var me = this;
Object.keys( this._config.events ).forEach( function( eventName ) {
socket.getRawSocket().on( eventName, function( data ) {
// Log debug data.
// Ignore PONG events.
if ( eventName !== "PONG" ) {
logger.debug( "Received Web data from " + socket.getRawSocket().handshake.address + ": " + util.format( "%j", data ) );
}
// Determine which scope to bind the event handler to
var scope = typeof me._config.scope !== "undefined" ? me._config.scope : me;
// Call the Application Specific Event handler, passing in the data and socket objects
me._config.events[eventName].bind( scope )( data, socket );
} );
} );
}
/**
* Method used for loading the 'http' and 'socket.io' classes, and creating the listeners.
* @function
*/
WEBServer.prototype.loadLibraries = function() {
// HTTP Server, required for serving Socket.Io JS file
// NOTE: The HTML file that makes use of it, is served by a standard HTTP server.
this._httpServer = require('http').createServer();
// Socket.Io
this._socketIo = require('socket.io')(
this._httpServer
,this._config.socket
);
}
/**
* Method used for preparing the server listeners, and attaching event handlers.
* @function
*/
WEBServer.prototype.init = function() {
// Log action.
logger.info( "Creating Web IRC server..." );
// Load required libraries.
this.loadLibraries();
// Open port for incoming connections
logger.info( "Binding on port: " + this._config.port + ", host: " + this._config.host + "." );
this._httpServer.listen( this._config.port, this._config.host );
// Attach a Socket.Io connection handler
// This handler in turn will attach application specific event handlers.
this._socketIo.sockets.on( 'connection', function ( socket ) {
// Log debug data.
logger.debug( "Incoming Web connection from: " + socket.handshake.address );
// Determine which scope to bind the event handler to
var scope = typeof this._config.scope !== "undefined" ? this._config.scope : this;
// Create IRCSocket.
socket = new IRCSocket( socket, "web", this._config, scope );
// Call a custom connection event handler, if configured
if ( typeof this._config.connection !== "undefined" ) {
this._config.connection.bind( scope )( socket );
}
// Attach the Application Specific Event handlers
this.attachSocketEvents( socket );
}.bind( this ) );
// Log action.
logger.info( "Web IRC server created." );
}
/**
* TCP Messaging server.
* TODO: Adjust documentation.
* @class Provides TCP server functionality.
* @constructor
* @param {Object} config Server configuration object. Supported keys are: port (listening port number), socket (socket listener configuration object),
* optional 'scope' object used for maintaining a custom scope reference,
* optional 'connectionHandler' connection handler,
* and an events object providing event handler functionality.
*/
var TCPServer = function( config ) {
// Store configuation, in a 'private' property
this._config = config;
}
/**
* Method used for preparing the server listeners, and attaching event handlers.
* @function
*/
TCPServer.prototype.init = function() {
// Load required libraries.
this.loadLibraries();
}
/**
* Method used for converting a text command to JSON.
* @function
* @param {String} name Command name.
* @param {String} command Raw text command as received from client.
* @return {Object} JSON object for the requested command.
*/
TCPServer.prototype.textToJson = function( name, command ) {
var responseObject = {}
,temp // Temporary variable, used for splitting a command.
,command = command.trim(); // Trim command
// Begin constructing parameters
switch ( name.toUpperCase() ) {
case "NICK":
// Split by spaces.
temp = command.split( " " );
// Construct a valid NICK JSON object.
responseObject = {
nickname: temp[1]
}
break;
case "WHO":
// Split by spaces.
temp = command.split( " " );
if ( temp.length > 1 ) {
responseObject.channels = temp[1];
}
if ( temp.length > 2 ) {
responseObject.o = temp[2];
}
break;
case "NAMES":
// Split by spaces.
temp = command.split( " " );
// Split by commas
if ( temp.length > 1 ) {
// TODO: Trim.
responseObject = {
channels: temp[1].split( "," )
}
}
break;
case "USER":
// Split by spaces.
// NOTE: The user mode is not implemented.
temp = command.split( " " );
responseObject = {
user: temp[1]
,mode: 0
};
// Split by ":" for constructing the real name.
temp = command.split( ":" );
responseObject.realname = temp.splice( 1 ).join( ":" );
break;
case "WHOIS":
// Split by spaces.
temp = command.split( " " );
if ( temp.length > 1 ) {
responseObject.target = temp[1];
}
break;
case "PONG":
responseObject = {};
break;
case "PING":
// Extract the token after the optional colon.
temp = command.split( ":" );
responseObject = {
token: temp.length > 1 ? temp[1].trim() : ""
};
break;
case "CAP":
// Split into subcommand and optional params.
temp = command.split( " " );
responseObject = {
subcommand: temp.length > 1 ? temp[1].toUpperCase() : ""
,params: temp.length > 2 ? temp.slice( 2 ).join( " " ).replace( /^:/, "" ) : ""
};
break;
case "PRIVMSG":
// Split by spaces.
temp = command.split( " " );
// Set target.
responseObject.target = temp[1];
// Set message.
temp = command.split( ":" );
responseObject.message = temp.splice( 1 ).join( ":" );
break;
case "JOIN":
// Split by spaces.
temp = command.split( " " );
var channelsPart = temp.splice( 1, 1 ).join( " " ).split( "," );
// Prepare response.
responseObject.channels = channelsPart;
// TODO: Handle keys.
break;
case "PART":
// Split by spaces.
// TODO: Handle multiple channels and part messages!
temp = command.split( " " );
// Prepare response.
if ( temp.length > 1 ) {
responseObject.channels = [ temp[1] ];
}
break;
case "TOPIC":
// TODO: Redundant with above!
// Split by spaces.
temp = command.split( " " );
// Set target.
responseObject.channel = temp[1];
// Set message.
temp = command.split( ":" );
responseObject.topic = temp.splice( 1 ).join( ":" );
break;
case "MODE":
// Split by spaces
temp = command.split( " " );
// Second array entry is the target name, and is mandatory!
responseObject = {
target: temp[1]
};
// Optionally, the third item is the mode to change.
if ( temp.length > 2 ) {
// If target is a nickname, pass in an array of modes
if ( IRCProtocol.OtherConstants.NICK_LENGTH && IRCProtocol.OtherConstants.NICK_PATTERN.test( responseObject.target ) ) {
responseObject.modes = [ temp[2] ];
} else {
// If channel, pass in a string
responseObject.modes = temp[2];
// TODO: Debu(nk)
}
}
// Optionally, all items from this point on, are added to the parameters array.
if ( temp.length > 3 ) {
responseObject.parameters = temp.slice( 3 );
}
break;
case "AWAY":
temp = command.split( ":" );
if ( temp.length > 1 ) {
// Set message, if any.
responseObject.text = temp.splice( 1 ).join( ":" );
}
break;
case "QUIT":
temp = command.split( ":" );
if ( temp.length > 1 ) {
// Set quit message, if any.
responseObject.reason = temp.splice( 1 ).join( ":" );
}
break;
case "KILL":
temp = command.split( " " );
if ( temp.length > 1 ) {
// Kill nickname.
responseObject.nickname = temp[1];
}
if ( temp.length > 2 ) {
// Kill comment.
responseObject.comment = temp[2].substring( 1 );
}
break;
case "INVITE":
temp = command.split( " " );
if ( temp.length > 1 ) {
// Nickname.
responseObject.nickname = temp[1];
}
if ( temp.length > 2 ) {
// Channel.
responseObject.channel = temp[2];
}
break;
case "WALLOPS":
temp = command.split( ":" );
if ( temp.length > 1 ) {
// Set message, if any.
responseObject.text = temp.splice( 1 ).join( ":" );
}
break;
case "OPER":
// Split by spaces.
temp = command.split( " " );
if ( temp.length > 1 ) {
responseObject.password = temp[1];
}
break;
case "ISON":
case "USERHOST":
// Split by spaces.
temp = command.split( " " );
if ( temp.length > 1 ) {
responseObject.nicknames = temp.splice( 1 );
}
break;
case "KICK":
// Split by ":".
// TODO: Allow multiple channels at a time!
temp = command.split( ":" );
var target = temp[0].split( " " );
// Get target details
if ( target.length > 1 ) {
responseObject.channel = [ target[1] ];
}
if ( target.length > 2 ) {
responseObject.user = [ target[2] ];
}
// Get comment, if any.
if ( temp.length > 1 ) {
responseObject.comment = temp.splice( 1 ).join( ":" );
}
break;
case "MOTD":
case "LUSERS":
case "VERSION":
case "TIME":
case "ADMIN":
case "INFO":
case "PONG":
case "USERS":
case "LIST":
// No parameters required.
break;
default:
// TODO: Implement.
break;
}
return responseObject;
}
/**
* Method used for attaching socket events and their handlers.
* NOTE: In this case, we need to emulate a similar behaviour to socket.io event handlers.
* NOTE: By converting from text to JSON.
* @param {Object} socket Socket object.
* @function
*/
TCPServer.prototype.attachSocketEvents = function( socket ) {
// Handle incoming text data.
socket.getRawSocket().on( 'data', function( data ) {
// NOTE: The IRC client might send a stream of multiple lines of text.
var lines = data.replace( /\r/g, "" ).split( '\n' )
,i
,temp // Temporary array
,command;
// Parse line by line
for ( i = 0; i < lines.length; i++ ) {
// Ignore empty lines.
if ( !lines[i] ) {
continue;
}
// Split line by spaces.
temp = lines[i].split( ' ' );
// Get command.
command = temp[0].toUpperCase();
// Log debug data.
// Ignore PONG event.
if ( command !== "PONG" ) {
logger.debug( "Received TCP data from " + socket.getRawSocket().remoteAddress + ": " + lines[i] );
}
// Handle each event, if there is a listener configured for it.
if ( typeof this._config.events[command] !== "undefined" ) {
// Determine which scope to bind the event handler to
// TODO: Perhaps redundant?!
var scope = typeof this._config.scope !== "undefined" ? this._config.scope : this;
// TODO: Convert data.
this._config.events[command].bind( scope )( this.textToJson( command, lines[i] ), socket );
}
// TODO: Handle an unkown command.
}
}.bind( this ) );
// Handle connection close, if an event handler is defined.
if ( typeof this._config.events["disconnect"] !== "undefined" ) {
socket.getRawSocket().on( 'close', function() {
// TODO: Perhaps redundant?!
var scope = typeof this._config.scope !== "undefined" ? this._config.scope : this;
// Handle event.
this._config.events.disconnect.bind( scope )( {}, socket );
}.bind( this ) );
}
}
/**
* Method used for loading the 'net' classe, and creating the listeners.
* @function
*/
TCPServer.prototype.loadLibraries = function() {
var socketIds = [];
// Log action.
logger.info( "Creating TCP IRC server..." );
// Load the net library and create server.
this._tcpServer = require( 'net' ).createServer(
// Socket configuration
this._config.socket
// Add listener.
,function ( socket ) {
// Log debug data.
logger.debug( "Incoming TCP connection from: " + socket.remoteAddress );
// Assign a unique id to this socket: http://stackoverflow.com/questions/6805432/how-to-uniquely-identify-a-socket-with-node-js
socket.id = Math.floor( Math.random() * 1000 );
while ( socketIds.indexOf( socket.id ) !== -1 ) {
socket.id = Math.floor( Math.random() * 1000 );
}
logger.debug( "Assigned TCP socket id: " + socket.id );
// Set encoding.
socket.setEncoding( 'utf8' );
// Determine which scope to bind the event handler to
var scope = typeof this._config.scope !== "undefined" ? this._config.scope : this;
// Create IRCSocket.
socket = new IRCSocket( socket, "tcp", this._config, scope );
// Call a custom connection event handler, if configured
if ( typeof this._config.connection !== "undefined" ) {
this._config.connection.bind( scope )( socket );
// Add "event" listeners.
this.attachSocketEvents( socket );
}
}.bind( this )
);
// Create listener.
// Log action.
logger.info( "Binding on port: " + this._config.port + ", host: " + this._config.host + "." );
this._tcpServer.listen(
this._config.port
,this._config.host
);
// Log action.
logger.info( "TCP IRC server created." );
}
/**
* IRC Socket definition.
* @param {Object} socket Connection socket object.
* @param {String} type Connection socket type. Allowed values: tcp and web.
* @param {Object} config Configuration object.
* @param {Object} scope Parent scope object.
* @construct
*/
var IRCSocket = function( socket, type, config, scope ) {
// Store configuration.
this._config = config;
// Store raw socket.
this._socket = socket;
// Store type.
this._type = type;
// Store scope.
this._scope = scope;
}
/**
* Method used for constructing the first part of a response, with the format of :server code nick.
* @function
* @param {Integer} command Command numeric id.
* @param {String} nickname Nickname.
* @return {String} First part.
*/
IRCSocket.prototype.constructFirstMessagePart = function( command, nickname ) {
return ":" + IRCProtocol.ServerName + " " + command + " " + nickname + " ";
}
/**
* Method used for converting a JSON command to text.
* @function
* @param {String} command Command name.
* @param {Object} parameters JSON object.
* @return {String} Command string.
*/
IRCSocket.prototype.jsonToText = function( command, parameters ) {
var response = "";
// Construct response.
switch ( command.toUpperCase() ) {
// "Welcome" sequence
case "RPL_WELCOME":
case "RPL_YOURHOST":
case "RPL_CREATED":
case "RPL_MYINFO":
// MOTD
case "RPL_MOTDSTART":
case "RPL_MOTD":
case "RPL_ENDOFMOTD":
// Nick command
case "ERR_NICKNAMEINUSE":
case "ERR_ERRONEUSNICKNAME":
// Away
case "RPL_UNAWAY":
case "RPL_NOWAWAY":
// Lusers
case "RPL_LUSERCLIENT":
case "RPL_LUSEROP":
case "RPL_LUSERUNKOWN":
case "RPL_LUSERCHANNELS":
case "RPL_LUSERME":
// Operator
case "RPL_YOUREOPER":
// Version
case "RPL_VERSION":
// Time
case "RPL_TIME":
// Admin
case "RPL_ADMINME":
case "RPL_ADMINLOC1":
case "RPL_ADMINLOC2":
case "RPL_ADMINEMAIL":
// Info
case "RPL_INFO":
case "RPL_ENDOFINFO":
// Users
case "ERR_USERSDISABLED":
// Generic
case "ERR_NEEDMOREPARAMS":
case "ERR_NOPRIVILEGES":
case "ERR_PASSWDMISMATCH":
case "ERR_UMODEUNKNOWNFLAG":
case "RPL_UMODEIS":
case "ERR_USERSDONTMATCH":
case "ERR_CHANOPRIVSNEEDED":
case "ERR_NOTONCHANNEL":
case "ERR_UNKNOWNMODE":
case "ERR_NOSUCHNICK":
case "ERR_USERNOTINCHANNEL":
case "RPL_INVITELIST":
case "RPL_ENDOFINVITELIST":
case "RPL_BANLIST":
case "RPL_ENDOFBANLIST":
case "RPL_EXCEPTLIST":
case "RPL_ENDOFEXCEPTLIST":
case "ERR_NOSUCHCHANNEL":
// Invite
case "ERR_USERONCHANNEL":
// Who
case "RPL_ENDOFWHO":
// List
case "RPL_LISTEND":
// TODO: RPL_CHANNELMODEIS
response = ":" + IRCProtocol.ServerName + " " + parameters.num + " " + this.Client.getNickname() + " :" + parameters.msg;
break;
case "RPL_INVITING":
response = ":" + IRCProtocol.ServerName + " " + parameters.num + " " + this.Client.getNickname() + " " + parameters.msg;
break;
case "PING":
response = "PING :" + parameters.source;
break;
case "PONG_REPLY":
response = ":" + IRCProtocol.ServerName + " PONG " + IRCProtocol.ServerName + " :" + parameters.token;
break;
case "CAP_REPLY":
response = ":" + IRCProtocol.ServerName + " CAP * " + parameters.subcommand + " :" + parameters.params;
break;
case "PRIVMSG":
response = ":" + parameters.nickname + "!" + parameters.user + "@" + parameters.host + " PRIVMSG " + parameters.target + " :" + parameters.message;
break;
case "PART":
response = ":" + parameters.nickname + "!" + parameters.user + "@" + parameters.host + " PART " + parameters.channel;
break;
case "JOIN":
response = ":" + parameters.nickname + "!" + parameters.user + "@" + parameters.host + " JOIN " + parameters.channel;
break;
case "RPL_ENDOFWHOIS":
// TODO: Store text in constants!
response = this.constructFirstMessagePart( 318, this.Client.getNickname() ) + parameters.nick + " :End of /WHOIS list.";
break;
case "RPL_TOPIC":
response = this.constructFirstMessagePart( 332, this.Client.getNickname() ) + parameters.channel + " :" + parameters.topic;
break;
case "RPL_NOTOPIC":
// TODO: Store text in constants!
response = this.constructFirstMessagePart( 331, this.Client.getNickname() ) + parameters.channel + " :No topic is set.";
break;
case "RPL_NAMREPLY":
// First part.
response = ":" + IRCProtocol.ServerName + " 353 " + this.Client.getNickname() + " ";
// Channel part.
// TODO: Handle channel types!
response += "= " + parameters.channel + " ";
// Nick part.
var nickPart = ""
,prefix;
for ( var i = 0; i < parameters.names.length; i++ ) {
prefix = parameters.names[i].operator ? "@" : "";
prefix += parameters.names[i].voice ? "+" : "";
nickPart += ( i === 0 ? "" : " " ) + prefix + parameters.names[i].nick;
}
response += ":" + nickPart;
break;
case "RPL_WHOISOPERATOR":
// TODO: Store text in constants!
response = this.constructFirstMessagePart( 313, this.Client.getNickname() ) + parameters.nick + " :is an IRC operator.";
break;
case "RPL_ENDOFNAMES":
// TODO: Store text in constants!
response = ":" + IRCProtocol.ServerName + " 366 " + this.Client.getNickname() + " :End of /NAMES list.";
break;
case "NICK":
response = ":" + parameters.initial + "!" + parameters.user + "@" + parameters.host + " NICK " + parameters.nickname;
break;
case "RPL_WHOISSERVER":
response += this.constructFirstMessagePart( 312, this.Client.getNickname() ) + parameters.nick + " " + parameters.server + " :" + parameters.serverinfo;
break;
case "RPL_WHOISUSER":
response = this.constructFirstMessagePart( 311, this.Client.getNickname() ) + parameters.nick + " " + parameters.user + " " + parameters.host + " * :" + parameters.realname;
break;
case "RPL_WHOISIDLE":
// TODO: Store text in constants!
response = ":" + IRCProtocol.ServerName + " 317 " + this.Client.getNickname() + " " + parameters.nick + " " + parameters.idle + " :seconds idle";
break;
case "RPL_AWAY":
response = ":" + IRCProtocol.ServerName + " 301 " + this.Client.getNickname() + " " + parameters.nick + " :" + parameters.text;
break;
case "RPL_WHOISCHANNELS":
response = ":" + IRCProtocol.ServerName + " 319 " + this.Client.getNickname() + " " + parameters.nick + " :" + parameters.channels;
break;
case "MODE":
// NOTE: Redundant with similar commands above!
response = ":" + parameters.nickname + "!" + parameters.user + "@" + parameters.host + " MODE " + parameters.channel + " " + parameters.mode;
// Append "parameter", e.g.: for a +ovkl command.
if ( parameters.parameter ) {
response += " " + parameters.parameter;
}
break;
case "WALLOPS":
response += ":" + parameters.server + " WALLOPS :" + parameters.text;
break;
case "QUIT":
response = ":" + parameters.nickname + "!" + parameters.user + "@" + parameters.host + " QUIT :" + parameters.reason;
break;
case "RPL_ISON":
// TODO: Test properly!
var nicknames = "";
_.each( parameters.nicknames, function( element ) {
nicknames += ( nicknames !== "" ? " " : "" ) + element;
} );
response = this.constructFirstMessagePart( 303, this.Client.getNickname() ) + ":" + nicknames;
break;
case "RPL_USERHOST":
var userhost = "";
_.each( parameters.nicknames, function( element ) {
userhost += ( userhost !== "" ? " " : "" ) + element.nickname + "=" + element.user + "@" + element.host;
} );
response = this.constructFirstMessagePart( 302, this.Client.getNickname() ) + ":" + userhost;
break;
case "KICK":
response = ":" + parameters.nickname + "!" + parameters.user + "@" + parameters.host + " KICK " + parameters.channel + " " + parameters.target + " :" + parameters.comment;
break;
case "INVITE":
response = ":" + parameters.nick + "!" + parameters.user + "@" + parameters.host + " INVITE " + this.Client.getNickname() + " " + parameters.channel;
break;
case "RPL_WHOREPLY":
response = this.constructFirstMessagePart( 352, this.Client.getNickname() ) + " " + parameters.channel + " " + parameters.user + " " + parameters.host + " " + parameters.server + " " + parameters.nick + " " + ( parameters.away ? "G" : "H" ) + " :" + parameters.hopcount + " " + parameters.realname;
break;
case "RPL_LIST":
// NOTE: RPL_LISTSTART is obsolete, according to RFC 2812, however, for backwards compatibility, include in response.
// TODO: Perhaps move somewhere else?
response = this.constructFirstMessagePart( 321, this.Client.getNickname() ) + " Channel Users :Topic";
this._socket.write( response + "\r\n" );
_.each( parameters.channels, function( element, index ) {
// Pepare response for each channel
response = this.constructFirstMessagePart( 322, this.Client.getNickname() ) + " " + parameters.channels[index] + " " + parameters.users[index] + " :" + parameters.topics[index];
// Write to socket
// TODO: Perhaps move somewhere else?
this._socket.write( response + "\r\n" );
}, this );
// Prevent standard output.
return false;
break;
default:
// TODO: Implement.
break;
}
// Return.
return response;
}
/**
* Method used for terminating a socket connection.
* @param {Object} data Empty object!
* @param {Object} socket Socket to terminate connection for.
* @function
*/
IRCSocket.prototype.disconnect = function( data, socket ) {
// Set client as quit.
socket.Client.clientQuit();
// Call protocol specific disconnect logic.
// TODO: NOTE: This logic is flawed!
try {
// Log debug data.
socket.getRawSocket().disconnect( data, socket );
} catch ( ex ) {
// TODO: Add error handling.
// End the TCP "way"
socket.getRawSocket().end();
}
}
/**
* Method used for fetching the raw socket address (ip or hostname).
* @function
* @return {String} Address.
*/
IRCSocket.prototype.getAddress = function() {
var result = "";
if ( this._type === "web" ) {
result = this._socket.handshake.address;
} else if ( this._type === "tcp" ) {
result = this._socket.remoteAddress;
}
return result;
}
/**
* Method used for fetching the raw socket.
* @function
* @return {Object} Raw socket.
*/
IRCSocket.prototype.getRawSocket = function() {
return this._socket;
}
/**
* Method used for emitting an IRC response.
* @function
* @param {String} command IRC Command string.
* @param {Object} parameters IRC Command parameters object.
*/
IRCSocket.prototype.emit = function( command, parameters ) {
if ( this._type === "web" ) {
// Write data as is.
this._socket.emit( command, parameters );
// Log debug data.
// Ignore PING event.
if ( command !== "PING" ) {
logger.debug( "Wrote Web JSON " + command + " event data to " + this._socket.handshake.address + ": " + util.format( "%j", parameters ) );
}
} else if ( this._type === "tcp" ) {
// Log debug data.
// Include both original, and wrote data, for better debugging.
// Ignore PING event.
if ( command !== "PING" ) {
logger.debug( "Writing JSON TCP event " + command + " to " + this._socket.remoteAddress + ": " + util.format( "%j", parameters ) );
}
// Convert JSON to text, and send the command over...if any.
var response = this.jsonToText.bind( this )( command, parameters );
if ( response ) {
this._socket.write( response + "\r\n" );
// Log debug data.
// Ignore PING event.
if ( command !== "PING" ) {
logger.debug( "Wrote TCP data to " + this._socket.remoteAddress + ": " + response );
}
}
}
}
// Load configuration file, in current scope
eval( fs.readFileSync('./public/config.js','utf8') );
// Configure logger
logFacility.configure( Config.Log.Configuration );
// Load logger
var logger = logFacility.getLogger( 'ircd' );
// Set log level
logger.level = Config.Log.Level;
// Begin logging.
logger.info( "Loaded log mechanism." );
/** IRC Protocol */
var IRCProtocol = {
// Daemon version
Version: "0.2"
// Server info
,ServerName: Config.Server.IRCProtocol.ServerName
,ServerInfo: Config.Server.IRCProtocol.ServerInfo
,ServerComments: Config.Server.IRCProtocol.ServerComments
,AdminInfo: Config.Server.IRCProtocol.AdminInfo
,Info: "IRC 2.0 (JSON Based Web IRC Server).\n\
Based on RFC2812. Copyright (C) The Internet Society (2000). All Rights Reserved.\n\
\n\
Copyright (c) 2013, Grosan Flaviu Gheorghe.\n\
All rights reserved.\n\
\n\
Redistribution and use in source and binary forms, with or without\n\
modification, are permitted provided that the following conditions are met:\n\
* Redistributions of source code must retain the above copyright\n\
notice, this list of conditions and the following disclaimer.\n\
* Redistributions in binary form must reproduce the above copyright\n\
notice, this list of conditions and the following disclaimer in the\n\
documentation and/or other materials provided with the distribution.\n\
* Neither the name of the author nor the\n\
names of its contributors may be used to endorse or promote products\n\
derived from this software without specific prior written permission.\n\
\n\
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\
DISCLAIMED. IN NO EVENT SHALL GROSAN FLAVIU GHEORGHE BE LIABLE FOR ANY\n\
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\
\n\
\n\
Contribute or fork:\n\
https://github.com/fgheorghe/jsIRC"
,MotdFile: Config.Server.IRCProtocol.MotdFile
,PingFrequency: Config.Server.IRCProtocol.PingFrequency // In seconds
,MaxChannelList: Config.Server.IRCProtocol.MaxChannelList // Maximum number of channels returned in a RPL_LIST event
,OperPassword: 'password' // TODO: Encrypt, and add host support
,DebugLevel: 0 // TODO: Implement debug levels
,UserModes: [
"a" // Away
,"i" // Invisible
,"w" // Wallops
,"r" // Restricted connection
,"o" // Global operator
,"O" // Local operator
,"s" // Server notices
]
,UserModeDefaults: {
a: false // Away
,i: false // Invisible
,w: false // Wallops
,r: false // Restricted connection
,o: false // Global operator
,O: false // Local operator
,s: false // Server notices
}
,ChannelModes: [
"a" // anonymous
,"i" // invite-only
,"m" // moderated
,"n" // no messages to channel from clients on the outside
,"q" // quiet
,"p" // private
,"s" // secret
,"r" // server reop
,"t" // topic settable by channel operator only
,"k" // key
,"l" // limit
,"o" // Operator
,"v" // Voice
,"b" // Ban
,"e" // Ban Exception
]
,ChannelModeDefaults: {
a: false
,i: false
,m: false
,n: false
,q: false
,p: false
,s: false
,r: false
,t: false
,k: ""
,l: 0
,o: []
}
/**
* Method used for initialising a requested protocol
* @param {String} type Type of protocol. Allowed values: 'client' or 'server' (not implemented).
* @return {Object} A new instance of the requested protocol type.
* @function
*/
,init: function( type ) {
switch ( type ) {
case "server":
// Do nothing.
break;
case "client":
// Create a new instance of the client protocol
return new this.ClientProtocol();
break;
default:
// Do nothing.
break;
}
}
// Client Protocol Numeric Replies
// Stored in array, having the numeric value as first index, and the text value as second index.
// Values that are indended to be returned within the string, are returned as a data object.
// E.g.: "<nick/channel> :Nick/channel is temporarily unavailable" would be returned as:
// { num: NICK.ERR_UNAVAILRESOURCE, msg: "Nick/channel is temporarily unavailable", value: "<nick/channel>" }
// Such response strings have their place holders removed, with a comment alongside each string.
// With few exceptions, noted below, where messages are constructed dynamically
,NumericReplyConstants: {
Client: {
NICK: {
ERR_NONICKNAMEGIVEN: [ 431, "No nickname given" ]
,ERR_ERRONEUSNICKNAME: [ 432, "Erroneous nickname" ] // <nick>