forked from splorp/npds-tracker-server
-
Notifications
You must be signed in to change notification settings - Fork 3
/
npdstracker.java
1987 lines (1785 loc) · 64.6 KB
/
npdstracker.java
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
// NPDS Tracker Server
// Developed by Victor Rehorst and Paul Guyot
// Additional contributions by Morgan Aldridge, Grant Hutchinson, Ron Parker, Manuel Probsthain, Sylvain Pilet and Peter Geremia
// Many thanks to Matt Vaughn for developing NPDS in the first place
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class npdstracker
{
//////////////////////////////////////////////////////////////////////////////
// VARIABLES AND CONSTANTS
//////////////////////////////////////////////////////////////////////////////
// ======= Constants ======= //
// Version Information
public static final String serverdesc = "NPDS Tracker Server for Java";
public static final int majorversion = 2;
public static final int minorversion = 0;
public static final int build = 1;
public static final int protocolversion = 1;
public static final String versionStr = majorversion + "." + minorversion + "." + build;
public static final String kServerStr = "Victor Rehorst's NPDS Tracker Server " + versionStr;
public static final String kUserAgentStr = "Mozilla/5.0 (compatible; " + kServerStr + "; Java)";
// 200, 400, 403, and 404 are standard HTTP codes
// 202 is a special NPDS code
public static final int HTTP_OK = 200;
public static final int NPDS_OK = 202;
public static final int HTTP_ERR = 400;
public static final int HTTP_FORBID = 403;
public static final int HTTP_NOTFOUND = 404;
public static final int kValidateTimeUnit = 60000; // 60000 = 1 minute in milliseconds
public static final int kRefreshTimeUnit = 1000; // 1000 = 1 second in milliseconds
public static final int kTimeout = 20000; // 20000 = 20 seconds in milliseconds
public static final String defaultOptionsFile = "npdstracker.ini";
public static final String defaultCmdFile = "npdscmd.txt";
public static final String defaultStatusFile = "npdsstatus.txt";
// Messages
public static final String kRTFMStr = " Please check out the protocol before telnetting to the tracker (http://npds.free.fr/)";
public static final String kAlreadyRegisteredStr = " host already exists in list";
public static final String kNotRegisteredStr = " host is unknown";
public static final String kInvalidHostStr = " host is invalid (doesn't resolve, check your client configuration)";
public static final String kPrivateHostStr = " host address is for private network (check your client configuration)";
public static final String kWeirdPortStr = " Weird port (not an integer)";
public static final String kWeirdPortValueStr = " Weird port (not within 1-65535)";
public static final String kUnsupportedVersionStr = " This version of the protocol is not supported by this tracker";
// Default port
public static final int DEFAULT_PORT = 3680;
// ======= Variables ======= //
// Server variables: time between validations, number of attempts to make before server is
// dropped, whether or not to share with other trackers, hit counter, admin password, log file
// location all of these can be set at runtime using the -o switch
public static int validateTime = 20;
public static int validateTries = 3;
public static boolean shareEnabled = true;
public static String adminPass = "qwerty";
public static Vector<Integer> kPort;
public static String logFile = "";
public static boolean logVerbose = true;
public static boolean statusFile = false;
public static boolean statusCompact = false;
public static String templateFile = "";
public static String stylesheetFile = "";
public static String imageDir = "";
public static String cmdfile = defaultCmdFile;
public static String hostName = "";
public static String hostLink = "";
// Define private host string
public static String acceptPrivateHost = "";
// Runtime variables: these are the data structures and other values used by the server while it is running
// I put all Newton info in a single Vector because I have a semaphore for accessing it and it is easier like this.
public static Vector<THostInfo> mHostInfoVector = new Vector<THostInfo>();
// Identically, I put all server info in a single Vector.
public static Vector<TServerInfo> mSharingInfoVector = new Vector<TServerInfo>();
public static int hitcounter = 0;
public static int regcounter = 0;
// Non 0 if a validation is in progress, 0 otherwise.
public static int mValidationInProgress = 0;
// Time the last validation ended (in RFC format):
public static String mLastValidation = "never";
// Validator and Server
// (Victor uses a lot of public static variables, he surely has a good reason for that)
public static TValidator mValidator;
// Vector with all the servers out there.
private Vector <TServer>mServers;
private static ExecutorService mExecutorService;
private static DateFormat mRFCGMTFormatter;
static
{
mRFCGMTFormatter = new SimpleDateFormat("EEE',' d-MMM-yyyy HH:mm:ss 'GMT'", Locale.US);
mRFCGMTFormatter.setTimeZone(TimeZone.getTimeZone("Africa/Casablanca"));
}
private static DateFormat mGMTCompactFormatter;
static
{
mGMTCompactFormatter = new SimpleDateFormat("d-MMM-yyyy HH:mm:ss 'GMT'", Locale.US);
mGMTCompactFormatter.setTimeZone(TimeZone.getTimeZone("Africa/Casablanca"));
}
//////////////////////////////////////////////////////////////////////////////
// EMBEDDED CLASSES
//////////////////////////////////////////////////////////////////////////////
// A class to handle exceptions when parsing the query
public static class TQueryException extends Exception
{
private static final long serialVersionUID = -5454365483023069659L;
public TQueryException(String s)
{
super(s);
}
}
// A class to validate the Newton servers
public static class TValidator extends Thread
{
public Date mLastCheck;
public Date mNextCheck;
public void run ()
{
// Initialization of variables to know when to check the registered Newtons.
mNextCheck = new Date();
// I'm looping forever. (I will be killed by the application as it quits).
try {
while (true)
{
try
{
Date now = new Date();
if (now.after(mNextCheck))
{
// get the current date
mLastCheck = new Date();
mNextCheck.setTime(mLastCheck.getTime() + (npdstracker.validateTime * npdstracker.kValidateTimeUnit));
npdstracker.validateServers();
}
now = new Date(); // Updates the now value.
// Let's sleep until next check if we have to
long timeout = mNextCheck.getTime() - now.getTime();
if (timeout > 0)
sleep( timeout );
} catch (InterruptedException e) {
// Ignore any interrupt.
}
} // while (true)
} catch (Exception e)
{
// Oops, some exception occured.
npdstracker.logMessage("TValidator: Exception " + e + " occurred");
e.printStackTrace();
}
}
}
// ============================================================ //
// A class to handle a connection the Newton servers.
public static class TConnection extends Thread
{
// Variables
private Socket mSocket;
// Constructor
TConnection ( Socket inSocket )
{
mSocket = inSocket;
}
// Thread entry point
public void run ()
{
try {
mSocket.setSoTimeout( npdstracker.kTimeout );
BufferedReader in = null;
PrintWriter out = null;
String result;
try
{
in = new BufferedReader( new InputStreamReader( mSocket.getInputStream() ) );
out = new PrintWriter(new OutputStreamWriter( mSocket.getOutputStream() ) );
npdstracker.logMessage("Handling connection from " + mSocket.getInetAddress().toString() );
result = in.readLine();
// pass the command to the query processor
if (result != null)
{
result.toUpperCase();
npdstracker.ProcessQuery( result, in, out, mSocket );
}
}
catch (Exception e)
{
System.err.println( "Look! Some exception!" );
System.err.println( e );
// Easier than calling System.getProperty("line.separator")
}
npdstracker.logMessage("Closing connection from " + mSocket.getInetAddress().toString());
mSocket.close();
System.gc();
} catch (Exception e)
{
// Oops, some exception occured.
npdstracker.logMessage("TConnection: Exception " + e + " occurred");
}
}
}
// ============================================================ //
// A class for servers that listen to Newtons.
public static class TServer extends Thread
{
// Variables
private ServerSocket mServer;
// Constructor
TServer( int inPort ) throws IOException
{
mServer = new ServerSocket( inPort );
}
// Thread entry point
public void run ()
{
// I'm looping waiting for connections.
while (true)
{
try
{
// Wait until a connection arrives.
Socket s = mServer.accept();
// Let a connection object handle the socket
TConnection thisConnection = new TConnection( s );
npdstracker.mExecutorService.execute(thisConnection);
} catch (Exception e)
{
// Oops, some exception occured.
npdstracker.logMessage("TServer: Exception " + e + " occurred");
}
}
}
}
// ============================================================ //
// * THostInfo *
// ============================================================ //
// A class to handle a data about Newton servers
// I need such a class because of semaphores (locks).
public static class THostInfo
{
// The Newton's hostname (including IP)
public String mName; // The string as shown in the logs and in the table.
public String mHost; // The host name only (used to check the server)
public int mPort; // The port only (default is 80)
// Unique ID of the Newton (NOT CURRENTLY USED)
public String mHash;
// Plaintext description of the Newton
public String mDesc;
// Time this Newton was last validates (string in RFC format)
public String mLastValidation;
// Current status of this Newton: 0 is up, any other number is the number
// of unsuccessful attempts made to validate, -1 is a SHARE record
public int mStatus;
// Unused yet. Because if a tracker dies, I may need to warn the Newton and
// tell it that personally, I am up. (Sounds cool, doesn't it?)
public TServerInfo mServer;
}
// ============================================================ //
// * TServerInfo *
// ============================================================ //
// A class to handle a data about other tracker servers
// I need such a class because of semaphores (locks).
public static class TServerInfo
{
// List of external trackers to get data from
public String mHost;
public String mPort;
}
//////////////////////////////////////////////////////////////////////////////
// UTILITY FUNCTIONS
//////////////////////////////////////////////////////////////////////////////
// ==================================================================== //
// * void logMessage( String ) [static]
// ==================================================================== //
// Sends a message to the System.out or the log file, if specified
public static void logMessage(String message)
{
if (logVerbose)
{
Date theDate = new Date();
if (logFile.equals(""))
System.out.println(theDate.toString() + " " + message);
else
{
try {
FileWriter outlogFile = new FileWriter(logFile, true);
outlogFile.write(theDate.toString() + " " + message + "\r\n");
outlogFile.flush();
outlogFile.close();
} catch (IOException e) {System.out.println(theDate.toString() + " FATAL - can't write to log file: " + logFile);}
}
}
}
// ==================================================================== //
// * int QueryRecord( String ) [static, private]
// ==================================================================== //
// Given a name, returns the host index or -1 if it cannot be found.
private static int QueryRecord (String host)
{
// Looks for a host with a given name.
// Searches the mHostInfoVector list and returns an index or -1
int index_i;
synchronized (mHostInfoVector)
{
for (index_i = 0; index_i < mHostInfoVector.size(); index_i++)
{
THostInfo theInfo = (THostInfo) mHostInfoVector.elementAt(index_i);
if (host.equals(theInfo.mName))
return index_i;
}
}
return -1;
}
// ==================================================================== //
// * void ReturnCode( int, String, PrintWriter ) [static, private]
// ==================================================================== //
// Given a code and a message, outputs a NPDS/TP status code line.
private static void ReturnCode(int codetype, String message, PrintWriter out)
{
out.print(codetype);
out.flush();
if ((codetype == HTTP_OK) || (codetype == NPDS_OK))
{
out.print(" OK" + message + "\r\n");
out.flush();
}
else if (codetype == HTTP_ERR)
{
out.print(" Bad Request" + message + "\r\n");
out.flush();
}
else if (codetype == HTTP_NOTFOUND)
{
out.print(" File Not Found" + message + "\r\n");
out.flush();
}
else
{
out.print(" Undefined status" + message + "\r\n");
out.flush();
}
}
// ==================================================================== //
// * String ReturnRFCTime( Date ) [static, private]
// ==================================================================== //
// Given a date, returns a RFC #1123 string.
// (cf http://www.faqs.org/rfc/rfc1123.txt)
private static String ReturnRFCTime(Date thisdate)
{
synchronized (mRFCGMTFormatter)
{
return mRFCGMTFormatter.format(thisdate);
}
}
// ==================================================================== //
// * String ReturnAbout( PrintWriter ) [static, private]
// ==================================================================== //
// Outputs to PrintWriter the about message. (the format is defined in the NPDS/TP protocol)
private static void ReturnAbout(PrintWriter out)
{
logMessage("Processing ABOUT command");
out.print("protocol: " + protocolversion + "\r\n");
out.print("period: " + validateTime + "\r\n");
out.print("tries: " + validateTries + "\r\n");
out.print("share: " + shareEnabled + "\r\n");
out.print("about: " + serverdesc + " version " + versionStr);
out.print(" running on Java " + System.getProperty("java.version") + " by " + System.getProperty("java.vendor") + " ");
out.print(System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version") + "\r\n");
out.flush();
}
// ==================================================================== //
// * void printUsage( void ) [static, private]
// ==================================================================== //
// Outputs to PrintWriter the about message. (the format is defined in the NPDS/TP protocol)
private static void printUsage()
{
System.out.println("Java NPDS Server Tracker " + versionStr);
System.out.println("Usage: java npdstracker [-h] [-c cmdfile] [-o optionsfile]");
System.out.println(" -h : Display this command usage information");
System.out.println(" -c cmdfile : Specifies the path of the npdscmd.txt file containing any commands to run at startup (defaults to none)");
System.out.println(" -o optionsfile : Specifies the path of the npdstracker.ini file containing configuration and option settings (defaults to settings at compile time)");
}
// ==================================================================== //
// * void ParseOptionsFile( String ) [static, private]
// ==================================================================== //
// Reads the server options from the INI file and parses the appropriately.
private static void ParseOptionsFile(String optionsfile) throws FileNotFoundException, IOException
{
BufferedReader optionsreader = new BufferedReader (new FileReader(optionsfile));
String tempoption = "";
int linenumber = 1;
tempoption = optionsreader.readLine();
while (tempoption != null)
{
StringTokenizer st = new StringTokenizer(tempoption, " ");
String garbage = "";
try {
garbage = st.nextToken();
} catch (NoSuchElementException e) {}
try {
if (tempoption.startsWith("kPort"))
{
garbage = st.nextToken();
if (!(garbage.equals("="))) {
logMessage("Error reading npdstracker.ini on line " + linenumber);
} else {
kPort = new Vector<Integer>();
while (true) {
try {
garbage = st.nextToken();
// Add that port to the list.
Integer thePort = Integer.valueOf(garbage);
kPort.addElement(thePort);
logMessage("Port found: " + thePort);
} catch (NoSuchElementException aNSEE) {
break;
}
}
}
}
else if (tempoption.startsWith("adminPass"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
adminPass = st.nextToken();
}
else if (tempoption.startsWith("validateTime"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Eerror reading npdstracker.ini on line " + linenumber);
else
validateTime = Integer.parseInt(st.nextToken());
}
else if (tempoption.startsWith("validateTries"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
validateTries = Integer.parseInt(st.nextToken());
}
else if (tempoption.startsWith("shareEnabled"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
shareEnabled = Boolean.valueOf(st.nextToken()).booleanValue();
}
else if (tempoption.startsWith("shareServer"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
{
TServerInfo theServerInfo = new TServerInfo();
theServerInfo.mHost = st.nextToken();
theServerInfo.mPort = st.nextToken();
mSharingInfoVector.addElement(theServerInfo);
}
}
else if (tempoption.startsWith("logFile"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
logFile = st.nextToken();
}
else if (tempoption.startsWith("logVerbose"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
logVerbose = Boolean.valueOf(st.nextToken()).booleanValue();
}
else if (tempoption.startsWith("statusFile"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
statusFile = Boolean.valueOf(st.nextToken()).booleanValue();
}
else if (tempoption.startsWith("statusCompact"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
statusCompact = Boolean.valueOf(st.nextToken()).booleanValue();
}
else if (tempoption.startsWith("pageTemplate"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
templateFile = st.nextToken();
}
else if (tempoption.startsWith("cssTemplate"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
stylesheetFile = st.nextToken();
}
else if (tempoption.startsWith("imageDir"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
{
imageDir = st.nextToken();
File imageDirFile = new File(imageDir);
if ( imageDirFile.exists() == false )
{
logMessage( "Error image directory " + imageDir + " does not exist. Defaulting to images in working directory.");
imageDir = "images";
}
}
}
else if (tempoption.startsWith("trackerName"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
hostName = st.nextToken();
}
else if (tempoption.startsWith("trackerHost"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
hostLink = st.nextToken();
}
else if (tempoption.startsWith("privateHostToAccept"))
{
garbage = st.nextToken();
if (!(garbage.equals("=")))
logMessage("Error reading npdstracker.ini on line " + linenumber);
else
acceptPrivateHost = st.nextToken();
}
else if (tempoption.startsWith("#") || garbage.equals(""))
{
// do nothing
}
} catch (NoSuchElementException e) { System.err.print("Error in options parsing " + optionsfile + " line " + linenumber + "\r\n");}
tempoption = optionsreader.readLine();
linenumber++;
}
optionsreader.close();
}
// ==================================================================== //
// String StrReplace( String, String, String ) [static, public]
// ==================================================================== //
// Replaces every occurrence of a string by another string in a string.
public static String StrReplace( String inString, String inPattern, String inReplacement )
{
String result = inString;
int fromIndex = 0;
while (true)
{
fromIndex = result.indexOf( inPattern, fromIndex );
if (fromIndex == -1)
break;
int newIndex = fromIndex + inPattern.length();
result = result.substring( 0, fromIndex ) + inReplacement + result.substring( newIndex );
fromIndex = newIndex;
}
return result;
}
//////////////////////////////////////////////////////////////////////////////
// MAIN FUNCTIONS
//////////////////////////////////////////////////////////////////////////////
// ==================================================================== //
// * void main( String[] ) [static]
// ==================================================================== //
// Main entry point.
public static void main(String[] args)
{
String tempoptionsfile = defaultOptionsFile;
// Parse command line options here
// -l [logfile] : The file to write logs to, will be created if it doesn't exist, otherwise appended to (unused?)
// -c [cmdfile] : The file to read initial commands from (REGUPs)
// -o [optionsfile] : The file to read other options from
for (int i = 0; i < args.length; i++)
{
if (args[i].equals("-c"))
{
cmdfile = args[i+1];
i++;
}
else if (args[i].equals("-o"))
{
tempoptionsfile = args[i+1];
i++;
}
else
{
System.out.println("Invalid arguments");
printUsage();
System.exit(0);
}
}
// start the tracker server
new npdstracker(cmdfile, tempoptionsfile);
}
// ==================================================================== //
// * npdstracker() [private]
// ==================================================================== //
// Constructor
private npdstracker(String tempcmdfile, String tempoptionsfile)
{
mExecutorService = Executors.newCachedThreadPool();
String tempcmd = "";
try
{
// Default values for options.
kPort = new Vector<Integer>();
kPort.addElement(Integer.valueOf(DEFAULT_PORT));
if (!(tempoptionsfile.equals("")))
ParseOptionsFile(tempoptionsfile);
if (!(tempcmdfile.equals("")))
{
BufferedReader cmdreader = new BufferedReader(new FileReader(tempcmdfile));
PrintWriter cmdwriter = new PrintWriter(new FileWriter(FileDescriptor.out));
tempcmd = cmdreader.readLine();
while (tempcmd != null)
{
ProcessQuery(tempcmd, null, cmdwriter, null);
tempcmd = cmdreader.readLine();
}
cmdreader.close();
}
// Let's create the validation thread.
mValidator = new TValidator();
mExecutorService.execute(mValidator);
mServers = new Vector<TServer>();
// For each port, create a server.
int nbServers = kPort.size();
int indexServers;
for (
indexServers = 0;
indexServers < nbServers;
indexServers++) {
int thePort = ((Integer) kPort.get(indexServers)).intValue();
TServer theServer;
try {
theServer = new TServer(thePort);
} catch (IOException theIOE) {
logMessage("npdstracker: Cannot start server on port " + thePort + " (" + theIOE + ")");
continue;
}
mExecutorService.execute(theServer);
mServers.addElement(theServer);
}
// ServerSocket timeout: I'll wait forever until a connection arrives.
// mServer.setSoTimeout( 0 ); // (this is default)
} catch(Exception e)
{
logMessage("npdstracker: Exception " + e + " occurred");
}
// Hello message
logMessage(serverdesc + " version " + versionStr + " started");
}
// ==================================================================== //
// void ProcessQuery( String, BufferedReader, PrintWriter, Socket ) [static]
// ==================================================================== //
// Function to handle the queries. (I need to have it public).
public static void ProcessQuery(String query, BufferedReader in, PrintWriter out, Socket socket) throws SocketException, IOException
{
// I get the query command.
// I now use exceptions for a cleaner way to procede (at least, I think so)
try { // Global try.
// tokenize me, baby
StringTokenizer st = new StringTokenizer( query );
// We now accept any standard delimiter, hence HT
// (the protocol says we should)
// We also accept the other delimiters, but anyway, there shouldn't be any other delimiter
// in the host name or the REGUP command, so we don't mind.
String theCommand = st.nextToken().toUpperCase();
// I do handle several commands.
if (theCommand.equals("ABOUT"))
{
ReturnCode(HTTP_OK, "", out);
ReturnAbout(out);
} else if (theCommand.equals("REGUP"))
{
logMessage("Processing REGUP command");
// Throw out the first token
String hname = st.nextToken();
String hdesc = query.substring(hname.length() + 7); // REGUP hname. Note: this isn't really protocol 1.1 compliant.
if (hname.equals("NPDS/TP"))
{
logMessage("v2 command received - not yet supported");
throw new TQueryException ( kUnsupportedVersionStr );
}
else if ((QueryRecord(hname) == -1))
{
// Host is not in our list. Let's add it.
THostInfo theInfo = new THostInfo();
theInfo.mName = hname;
// I process the host name (without the port) and the port if ever there is a colmun in the host.
StringTokenizer host_st = new StringTokenizer(hname, ":");
theInfo.mHost = host_st.nextToken();
// First, check the host. We won't accept hosts that don't resolve or that are for private networks.
byte theHostAddressAsBytes[];
try {
InetAddress theHostAddress = InetAddress.getByName( theInfo.mHost );
theHostAddressAsBytes = theHostAddress.getAddress();
} catch (UnknownHostException theException) {
throw new TQueryException ( kInvalidHostStr );
}
// Check if the explicitely allowed hostname with a private IP is registering
if (acceptPrivateHost.equals(theInfo.mHost))
{
// Accept host and write that to log
logMessage("Private IP host " + theInfo.mHost + " has now registered");
} else {
// Don't accept host and check that it's not any other private network address.
// Don't know for IPv6, so I only work with 4 bytes addies.
if (theHostAddressAsBytes.length == 4)
{
// 10.0.0.0/8
if (theHostAddressAsBytes[0] == 10)
{
throw new TQueryException ( kPrivateHostStr );
}
// 172.16.0.0/12
if ((theHostAddressAsBytes[0] == (byte) 172) && ((theHostAddressAsBytes[1] & 0xF0) == 16))
{
throw new TQueryException ( kPrivateHostStr );
}
// 192.168.0.0/16
if ((theHostAddressAsBytes[0] == (byte) 192) && (theHostAddressAsBytes[1] == (byte) 168))
{
throw new TQueryException ( kPrivateHostStr );
}
// 0.0.0.0/8 or empty host string
if (theHostAddressAsBytes[0] == 0)
{
throw new TQueryException ( kPrivateHostStr );
}
}
}
if (host_st.hasMoreTokens())
{
try {
theInfo.mPort = Integer.parseInt(host_st.nextToken());
} catch (NumberFormatException theException)
{
logMessage("Server \"" + hname + " " + hdesc + "\" wasn't inserted into the list because its port isn't correct (not an integer)");
throw new TQueryException ( kWeirdPortStr );
}
if ((theInfo.mPort < 1) || (theInfo.mPort > 65535))
{
logMessage("Server \"" + hname + " " + hdesc + "\" wasn't inserted into the list because its port isn't correct (not between 1 - 65535)");
throw new TQueryException ( kWeirdPortValueStr );
}
} else {
theInfo.mPort = 80;
}
theInfo.mDesc = hdesc;
Date tempDate = new Date();
theInfo.mLastValidation = ReturnRFCTime(tempDate);
theInfo.mStatus = 0;
//TODO We might want to check to see if this is REALLY a Newton and not add if it is not.
// Synchronized is not required here because the addElement method is synchronized.
mHostInfoVector.addElement(theInfo);
ReturnCode(HTTP_OK, "", out);
logMessage("Inserted \"" + hname + " " + hdesc + "\" into the list");
logMessage(mHostInfoVector.size() + " hosts now in the list");
regcounter++;
}
else
{
// host is already in our list,
logMessage("Did not insert \"" + hname + "\" into list - host is already registered");
throw new TQueryException ( kAlreadyRegisteredStr );
} // if ((QueryRecord(hname) == -1)) ... else
saveServers();
writeStatusFile();
}
else if (theCommand.equals("REGDN"))
{
logMessage("Processing REGDN command");
String host = null;
// throw out the first token
host = st.nextToken();
// Check there is no token left (there shouldn't be).
if (st.hasMoreTokens())
{
logMessage("Bad syntax: the tokenizer found more than two elements");
throw new TQueryException ( kRTFMStr );
}
int tempindex;
// I need the tempindex, nobody should change the list before I do remove this element
// But, because I don't want to lock the other connections, I'd better do only removal
// in the synchronized statement
synchronized (mHostInfoVector)
{
tempindex = QueryRecord(host);
if (tempindex != -1)
{
mHostInfoVector.removeElementAt(tempindex);
}
}
if (tempindex == -1)
{
logMessage("REGDN failed - host not found in list");
throw new TQueryException ( kNotRegisteredStr );
}
else
{
ReturnCode(HTTP_OK, "", out);
logMessage("Removed \"" + host + "\" from the list");
logMessage(mHostInfoVector.size() + " hosts now in the list");
} // if (tempindex == -1)
saveServers();
writeStatusFile();
}
else if (theCommand.equals("QUERY"))
{
logMessage("Processing QUERY command");
ReturnCode(NPDS_OK, "", out);
// Print out all of the Newtons registered
synchronized (mHostInfoVector)
{
for (int index_i = 0; index_i < mHostInfoVector.size(); index_i++)
{
THostInfo theInfo = (THostInfo) mHostInfoVector.elementAt(index_i);
out.print(theInfo.mName + " " + theInfo.mDesc + " " + theInfo.mLastValidation + " " + theInfo.mStatus + "\r\n");
out.flush();
}
}
}
else if (theCommand.equals("SHARE"))
{
// Return list of entries in SHARE format
logMessage("Processing SHARE command");
if (shareEnabled == true)
{
ReturnCode(HTTP_OK, "", out);
synchronized (mHostInfoVector)
{
for (int index_i = 0; index_i < mHostInfoVector.size(); index_i++)
{
THostInfo theInfo = (THostInfo) mHostInfoVector.elementAt(index_i);
if (!(theInfo.mStatus == -1 || theInfo.mStatus == -2))
{
out.print("Address: " + theInfo.mName + "\tLast Verified: "
+ theInfo.mLastValidation + "\t");
String statstring;
if (theInfo.mStatus == 0)
statstring = "UP";
else
statstring = "DOWN";
out.print("Status: " + statstring + "\tDescription: " + theInfo.mDesc + "\r\n");
out.flush();
}
}
}
}
else
{