-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFTPServer.java
More file actions
1063 lines (1014 loc) · 32.8 KB
/
FTPServer.java
File metadata and controls
1063 lines (1014 loc) · 32.8 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
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
import java.security.*;
public class FTPServer extends Thread
{
/**
* @author Collin Berman
* @version 5.2.2011
*/
/**
* Array of all the connected clients. An array is
* used instead of an <code> ArrayList </code> so that
* an effective maximum on connections can be maintained.
*/
private User[] users;
/**
* Maintains information about this server used when
* accepting new connections.
*/
private ServerSocket server;
/**
* Maximum number of connections to this server allowed
*/
private int maxConnections=-1;
/**
* Port that this server is run on
*/
public int port=-1;
/**
* Message sent to the client after a <code> NOOP </code> command
*/
public String noop;
/**
* Path that new connections start at
*/
public String defaultPath;
/**
* Highest path that clients are allowed to navigate to
*/
public String root;
/**
* Message sent to clients on successful connection
*/
public String welcome;
/**
* Used to navigate between directories. Either
* a \ or a /, depending on the operating system.
*/
public String fd;
/**
* The hashed password to the server
*/
private String pass;
/**
* Whether or not this server is secured with a password.
*/
public boolean hasPass=false;
/**
* Generates SHA-1 checksums
*/
public MessageDigest md;
/**
* Whether or not to use checksums
*/
public boolean checksum;
/**
* Whether or not to allow file deletion
*/
public boolean dRight;
/**
* Create a new server and instantiate various variables
*/
public FTPServer() throws IOException
{
boolean hasCheck=false, hasD=false;
String os=System.getProperty("os.name");
System.out.println("OS detected as "+os);
System.out.println("IP detected as "+InetAddress.getLocalHost().getHostAddress());
if(os.contains("Linux"))
fd="/";
else if(os.contains("Windows"))
fd="\\";
else if(os.contains("Apple")||os.contains("Mac"))
fd="/";
PrintStream out=null;
if(!new File("server.cfg").exists())
{
System.out.println("server.cfg not found");
try{out=new PrintStream(new FileOutputStream("server.cfg", true));}
catch(Exception e){e.printStackTrace(); System.exit(1);}
System.out.println("server.cfg created successfully");
}
else
{
try{out=new PrintStream(new FileOutputStream("server.cfg", true));}
catch(Exception e){e.printStackTrace(); System.exit(1);}
System.out.println("server.cfg successfully loaded");
}
BufferedReader f=null;
try{f=new BufferedReader(new FileReader("server.cfg"));}
catch(Exception e){
e.printStackTrace();
System.exit(1);}
StringTokenizer st;
for(String line=f.readLine(); line!=null; line=f.readLine())
{
st=new StringTokenizer(line);
String header=st.nextToken();
if(header.equalsIgnoreCase("CONNECTIONS:"))
try{maxConnections=Integer.parseInt(st.nextToken());}
catch(Exception e){System.out.println("Invalid CONNECTIONS header; will be reset.");}
else if(header.equalsIgnoreCase("DIRECTORY:"))
{
defaultPath=st.nextToken();
while(st.hasMoreTokens())
defaultPath+=" "+st.nextToken();
}
else if(header.equalsIgnoreCase("ROOT:"))
{
root=st.nextToken();
while(st.hasMoreTokens())
root+=" "+st.nextToken();
}
else if(header.equalsIgnoreCase("CONNECT:"))
{
welcome=st.nextToken();
while(st.hasMoreTokens())
welcome+=" "+st.nextToken();
}
else if(header.equalsIgnoreCase("PORT:"))
try{port=Integer.parseInt(st.nextToken());}
catch(Exception e){System.out.println("Invalid PORT header; will be reset.");}
else if(header.equalsIgnoreCase("CHECKSUM:"))
{
hasCheck=true;
if(st.nextToken().equalsIgnoreCase("NO"))
checksum=false;
else
checksum=true;
}
else if(header.equalsIgnoreCase("DELETION:"))
{
hasD=true;
if(st.nextToken().equalsIgnoreCase("YES"))
dRight=true;
else
dRight=false;
}
}
if(maxConnections==-1)
{
System.out.println("Header CONNECTIONS not found; Max connections set as 5");
maxConnections=5;
out.println("CONNECTIONS: 5");
}
noop="200 <OK>";
if(welcome==null)
{
System.out.println("Header CONNECT not found; New connection response set as \"Connection successful\"");
welcome="Connection successful";
out.println("CONNECT: Connection successful");
}
if(os.contains("Linux"))
{
if(defaultPath==null)
{
System.out.println("Header DIRECTORY not found; Start directory set as /");
defaultPath="/";
out.println("DIRECTORY: /");
}
if(root==null)
{
System.out.println("Header ROOT not found; Root directory set as /");
root="/";
out.println("ROOT: /");
}
}
else if (os.contains("Windows"))
{
if(defaultPath==null)
{
System.out.println("Header DIRECTORY not found; Start directory set as C:\\");
defaultPath="C:\\";
out.println("DIRECTORY: C:\\");
}
if(root==null)
{
System.out.println("Header ROOT not found; Root directory set as C:\\");
root="C:\\";
out.println("ROOT: C:\\");
}
}
if(os.contains("Apple")||os.contains("Mac"))
{
if(defaultPath==null)
{
System.out.println("Header DIRECTORY not found; Start directory set as /");
defaultPath="/";
out.println("DIRECTORY: /");
}
if(root==null)
{
System.out.println("Header ROOT not found; Root directory set as /");
root="/";
out.println("ROOT: /");
}
}
if(port==-1)
{
System.out.println("Header PORT not found; Port set as 5000");
port=5000;
out.println("PORT: 5000");
}
if(!hasCheck)
{
System.out.println("Header CHECKSUM not found; Checkum use set to YES");
checksum=true;
out.println("CHECKSUM: YES");
}
if(!hasD)
{
System.out.println("Header DELETION not found; Deletion rights set to NO");
dRight=false;
out.println("DELETION: NO");
}
users = new User[ maxConnections ];
try {
server = new ServerSocket( port, 2 );
}
catch(BindException e)
{
System.out.println("Something is already being run on this port.");
System.exit(1);
}
catch( IOException e ) {
e.printStackTrace();
System.exit( 1 );
}
server.setSoTimeout(500);
//password input
pass = null;
try {
pass = PasswordField.getHash(System.in,
"Enter a password for the server (hit ENTER for no password): ");
}
catch(IOException e){e.printStackTrace();}
System.out.print("\n\r"); //carriage return
if(pass!=null)
hasPass=true;
if(checksum)
try{md=MessageDigest.getInstance("SHA-1");}
catch(NoSuchAlgorithmException e){e.printStackTrace();}
}
/**
* Constantly checks for new connections and accepts them.
*/
public void run()
{
while(true)
{
for ( int i = 0; i < users.length; i++ )
{
try{this.sleep(5000);}
catch(InterruptedException e){e.printStackTrace();}
if(users[i]==null)
{
try {
users[ i ] = new User( server.accept(), this);
users[ i ].start();
}
catch(SocketTimeoutException e){}
catch( IOException e ) {
e.printStackTrace();
System.exit( 1 );
}
}
else if(users[i].disconnected){
try{
display(users[i].IP+" has disconnected.");
users[i]=null;
}
catch(Exception e){
e.printStackTrace();
System.exit(1);}}
}
}
}
/**
* Writes a message to standard out
* @param s The message to be displayed
*/
public void display( String s ) throws IOException
{
System.out.println(s);
}
/**
* Interprets a message from the client and
* delegates the task to a new method
* @param p The client that sent the command
* @param text The message sent by the client
*/
public void interpret(User p, String text) throws IOException
{
String[] word=text.split("[ \t\n\f\r]");
if(word[0].equalsIgnoreCase("noop"))
p.output.writeUTF(noop);
else if(word[0].equalsIgnoreCase("ls")||word[0].equalsIgnoreCase("list")||word[0].equalsIgnoreCase("dir"))
list(p, word);
else if(word[0].equalsIgnoreCase("flist"))
flist(p, word);
else if(word[0].equalsIgnoreCase("dlist"))
dlist(p, word);
else if(word[0].equalsIgnoreCase("cdup"))
cdup(p);
else if(word[0].equalsIgnoreCase("cd")||word[0].equalsIgnoreCase("cwd"))
cwd(p, word);
else if(word[0].equalsIgnoreCase("size"))
{
String size=size(p, word);
if(size!="")
p.output.writeUTF(size);
}
else if(word[0].equalsIgnoreCase("get")||word[0].equalsIgnoreCase("retr"))
retr(p, word);
else if(word[0].equalsIgnoreCase("pwd"))
p.output.writeUTF(p.path.getPath());
else if(word[0].equalsIgnoreCase("rm")||word[0].equalsIgnoreCase("dele"))
rm(p, word);
else if(word[0].equalsIgnoreCase("mdtm"))
mdtm(p, word);
else if(word[0].equalsIgnoreCase("mget"))
mget(p, word);
else if(word[0].equalsIgnoreCase("fget"))
fget(p, word);
// else if(word[0].equalsIgnoreCase("shutdown")) //temp
// System.exit(0);
else
p.output.writeUTF(word[0]+" is not recognized as a command.");
p.output.writeUTF("<EOF>"+p.path.getPath());
}
/**
* Sends the client a list of files and directories
* of the specified directory. If no directory is
* specified, the current one is used.
* @param p The client that requested the list
* @param word The exact message sent by the client
*/
public void list(User p, String[] word) throws IOException
{
String[] files=null;
File dir=null;
if(word.length==0)
dir=p.path;
else
{
String newPath="";
for(int i=1; i<word.length; i++)
newPath+=(i>1)?" "+word[i]:word[i];
dir=new File(p.path.getPath()+fd+newPath);
if(!dir.exists())
{
p.output.writeUTF(newPath+": No such file or directory");
return;
}
else if(!dir.isDirectory())
{
p.output.writeUTF(newPath+": Not a directory");
return;
}
}
files=dir.list();
if(files==null)
{
p.output.writeUTF("Access to "+dir.getName()+" denied");
return;
}
p.output.writeUTF(".\n..");
for(String i:files)
p.output.writeUTF(i);
}
/**
* Sends the client a list of files
* of the specified directory. If no directory is
* specified, the current one is used.
* @param p The client that requested the list
* @param word The exact message sent by the client
*/
public void flist(User p, String[] word) throws IOException
{
File[] files=null;
File dir=null;
if(word.length==0)
dir=p.path;
else
{
String newPath="";
for(int i=1; i<word.length; i++)
newPath+=(i>1)?" "+word[i]:word[i];
dir=new File(p.path.getPath()+fd+newPath);
if(!dir.exists())
{
p.output.writeUTF(newPath+": No such file or directory");
return;
}
else if(!dir.isDirectory())
{
p.output.writeUTF(newPath+": Not a directory");
return;
}
}
files=dir.listFiles();
if(files==null)
{
p.output.writeUTF("Access to "+dir.getName()+" denied");
return;
}
for(File i:files)
if(!i.isDirectory())
p.output.writeUTF(i.getName());
}
/**
* Sends the client a list of directories
* in the specified directory. If no directory is
* specified, the current one is used.
* @param p The client that requested the list
* @param word The exact message sent by the client
*/
public void dlist(User p, String[] word) throws IOException
{
File[] files=null;
File dir=null;
if(word.length==0)
dir=p.path;
else
{
String newPath="";
for(int i=1; i<word.length; i++)
newPath+=(i>1)?" "+word[i]:word[i];
dir=new File(p.path.getPath()+fd+newPath);
if(!dir.exists())
{
p.output.writeUTF(newPath+": No such file or directory");
return;
}
else if(!dir.isDirectory())
{
p.output.writeUTF(newPath+": Not a directory");
return;
}
}
files=dir.listFiles();
if(files==null)
{
p.output.writeUTF("Access to "+dir.getName()+" denied");
return;
}
p.output.writeUTF(".\n..");
for(File i:files)
if(i.isDirectory())
p.output.writeUTF(i.getName());
}
/**
* Changes the directory to the parent directory
* of the current directory.
* @param p The client that requested the directory change
*/
public void cdup(User p) throws IOException
{
String[] word=new String[2];
word[0]="cwd";
word[1]="..";
cwd(p, word);
}
/**
* Changes the directory to the specified directory
* @param p The client that requested the directory change
* @param word The exact message sent by the client
*/
public void cwd(User p, String[] word) throws IOException
{
if(word.length==1)
p.path=new File(defaultPath);
else if(word[1].equals(".")&&word.length==2);
else if(word[1].equals("..")&&word.length==2)
{
if(p.path.getPath().equals(root))
p.output.writeUTF("You are not allowed to go any higher");
else
p.path=new File(p.path.getPath().substring(0, p.path.getPath().lastIndexOf(fd)+1));
}
else
{
String newPath="";
for(int i=1; i<word.length; i++)
newPath+=(i>1)?" "+word[i]:word[i];
File dir=new File(p.path.getPath()+fd+newPath);
if(!dir.exists())
p.output.writeUTF(newPath+": No such file or directory");
else if(!dir.isDirectory())
p.output.writeUTF(newPath+": Not a directory");
else
p.path=dir;
}
}
/**
* Sends the client the size of a file or folder.
* Uses a <code> Queue </code>
* @param p The client that requested the file size
* @param word The exact message sent by the client
*/
public String size(User p, String[] word) throws IOException
{
if(word.length==1)
{
p.output.writeUTF(word[0]+" requires a filename argument");
return "";
}
long divisor=1;
String unit="b";
String newPath="";
boolean coolGuy=true;
for(int i=1; i<word.length; i++)
if(word[i].charAt(0)=='-')
switch(word[i].charAt(1))
{
case 'b':
divisor=1;
unit="b";
break;
case 'k':
divisor=1024;
unit="kb";
break;
case 'm':
divisor=1048576;
unit="mb";
break;
case 'g':
divisor=1073741824;
unit="gb";
break;
default:
p.output.writeUTF(word[i].charAt(1)+" is not a valid identifier");
}
else
{
if(!coolGuy)
newPath+=" ";
else
coolGuy=false;
newPath+=word[i];
}
File file=new File(p.path.getPath()+fd+newPath);
if(!file.exists())
{
p.output.writeUTF(newPath+": No such file or directory");
return "";
}
Queue<File> q=new LinkedList<File>();
q.offer(file);
long sum=0;
while(!q.isEmpty())
{
file=q.remove();
if(file.isDirectory())
try
{
for(File i:file.listFiles())
q.offer(i);
}
catch(NullPointerException e){
try{p.output.writeUTF("Access to "+file.getName()+" denied");}
catch(SocketException ex){p.disconnected=true;}}
else
sum+=file.length();
}
return (sum/divisor)+unit;
}
/**
* Sends the client a file
* @param p The client that requested the file
* @param word The exact message sent by the client
*/
public void retr(User p, String[] word) throws IOException
{
if(word.length==1)
p.output.writeUTF(word[0]+" requires a filename argument");
else
{
String newPath="";
for(int i=1; i<word.length; i++)
newPath+=(i>1)?" "+word[i]:word[i];
File file=new File(p.path.getPath()+fd+newPath);
if(!file.exists())
p.output.writeUTF(file.getName()+": No such file or directory");
else if(file.isDirectory())
p.output.writeUTF(file.getName()+": Is a directory");
else
sendFile(p, file, file.getName());
}
}
/**
* Sends the client a file
* @param p The client that requested the file
* @param path The path of the file requested by the client
*/
public void sendFile(User p, File file, String name) throws IOException
{
byte[] array=new byte[0];
boolean tooBig=false;
try{array=new byte[(int)file.length()];}
catch(OutOfMemoryError e){tooBig=true;}
if(tooBig||(long)array.length!=file.length())
p.output.writeUTF("File too big to transfer");
else
{
do
{
new BufferedInputStream(new FileInputStream(file)).read(array, 0, array.length);
p.output.writeUTF("<FILE>"+"Downloads"+fd+name+":"+array.length);
p.output.write(array, 0, array.length);
p.output.flush();
byte[] sha1hash = md.digest(array);
p.output.write(sha1hash, 0, sha1hash.length);
p.output.flush();
} while(!p.input.readBoolean());
}
}
/**
* Removes a file from the server
* @param p The client that requested the file removal
* @param word The exact message sent by the client
*/
public void rm(User p, String[] word) throws IOException
{
if(!dRight)
p.output.writeUTF("You do not have permissions to delete files");
else if(word.length==1)
p.output.writeUTF(word[0]+" requires a filename argument");
else
{
String newPath="";
for(int i=1; i<word.length; i++)
newPath+=(i>1)?" "+word[i]:word[i];
File file=new File(p.path.getPath()+fd+newPath);
if(!file.exists())
p.output.writeUTF(newPath+": No such file or directory");
else if(file.isDirectory())
p.output.writeUTF("Cannot remove "+newPath+": Is a directory");
else
file.delete();
}
}
/**
* Sends the client the date a file was last modified
* in milliseconds since the epoch.
* @param p The client that requested the date
* @param word The exact message sent by the client
*/
public void mdtm(User p, String[] word) throws IOException
{
if(word.length==1)
p.output.writeUTF(word[0]+" requires a filename argument");
else
{
String newPath="";
for(int i=1; i<word.length; i++)
newPath+=(i>1)?" "+word[i]:word[i];
File file=new File(p.path.getPath()+fd+newPath);
if(!file.exists())
p.output.writeUTF(newPath+": No such file or directory");
else
p.output.writeUTF(file.lastModified()+"");
}
}
/**
* Sends the client all the files in a folder
* that match the given regular expression.
* @param p The client that requested the date
* @param word The exact message sent by the client
*/
public void mget(User p, String[] word) throws IOException
{
if(word.length==1)
p.output.writeUTF(word[0]+" requires an argument");
else
{
String regex="";
for(int i=1; i<word.length; i++)
regex+=(i>1)?" "+word[i]:word[i];
for(File i:p.path.listFiles())
if(i.exists()&&!i.isDirectory()&&matches(regex, i.getName()))
sendFile(p, i, i.getName());
}
}
/**
* Used by <code> mget </code> to determine if
* a specific file should be sent.
* @param regex The regular expression.
* @param name The name of the file
*/
public boolean matches(String regex, String name)
{
for(int i=0; i<regex.length(); i++)
{
char c=regex.charAt(i);
switch(c)
{
case '?':
break;
case '*':
for(int s=i; s<name.length(); s++)
if(matches(regex.substring(i+1), name.substring(s)))
return true;
break;
default:
if(c!=name.charAt(i))
return false;
}
}
return true;
}
/**
* Sends the client a folder, and all it's subdirectories
* @param p The client that requested the date
* @param word The exact message sent by the client
*/
public void fget(User p, String[] word) throws IOException
{
if(word.length==1)
p.output.writeUTF(word[0]+" requires a filename argument");
else
{
String newPath="";
for(int i=1; i<word.length; i++)
newPath+=(i>1)?" "+word[i]:word[i];
File file=new File(p.path.getPath()+fd+newPath);
if(!file.exists())
p.output.writeUTF(newPath+": No such file or directory");
else if(!file.isDirectory())
p.output.writeUTF(newPath+": Not a directory");
else
{
int start=file.getPath().length()-file.getName().length();
Stack<File> stack=new Stack<File>();
stack.push(file);
while(!stack.isEmpty())
{
file=stack.pop();
if(file.isDirectory())
{
p.output.writeUTF("<FOLDER>"+"Downloads"+fd+file.getPath().substring(start));
for(File i:file.listFiles())
stack.push(i);
}
else if(file.exists())
sendFile(p, file, file.getPath().substring(start));
}
}
}
}
/**
* Checks to see if the password sent by the client
* mathces the server's password.
* @param hash The hashed password from the client
*/
public boolean isPass(String hash)
{
return hash.equals(pass);
}
/**
* Creates a new server and starts the required <code> Thread</code>s
*/
public static void main( String args[] ) throws IOException
{
FTPServer server = new FTPServer();
System.out.println("Server up and running");
server.start();
}
}
/**
* <code> Class </code> maintaining information on each client
*/
class User extends Thread
{
/**
* The place the connection between the client
* and server is made
*/
private Socket connection;
/**
* <code> Stream </code> reading from the client
*/
public DataInputStream input;
/**
* <code> Stream </code> writing to the client
*/
public DataOutputStream output;
/**
* <code> FTPServer </code> associated with this client
*/
private FTPServer control;
/**
* The directory the user is currently in
*/
public File path;
/**
* The IP address of the client machine
*/
public String IP;
/**
* Tells the server if it's safe to remove this user
*/
public boolean disconnected = false;
/**
* Creates a new connection
* @param socket The place the connection is made
* @param server The host server
*/
public User( Socket socket, FTPServer server)
{
connection = socket;
try {
input = new DataInputStream(connection.getInputStream());
output = new DataOutputStream(connection.getOutputStream());
}
catch( IOException e ) {
e.printStackTrace();
System.exit( 1 );
}
control = server;
path=new File(control.defaultPath);
}
/**
* Reads in requests from the client and
* sends them to the server for interpretation.
*/
public void run()
{
try {
IP=connection.getInetAddress().getHostAddress();
control.display( "New connection from "+IP );
output.writeBoolean(control.hasPass);
if(control.hasPass)
{
String hash=input.readUTF();
if(!control.isPass(hash))
{
output.writeBoolean(true);
disconnected=true;
}
else
output.writeBoolean(false);
}
output.writeBoolean(control.checksum);
output.writeUTF(control.welcome);
output.writeUTF("<EOF>"+path.getPath());
while ( true )
{
String text="";
try{
text = input.readUTF();}
catch(EOFException e){
disconnected=true;
break;}
catch(SocketException e){
disconnected=true;
break;}
control.interpret(this, text);
}
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
/**
* This <code> Class </code> attempts to erase characters echoed to the console.
*/
class MaskingThread extends Thread
{
/**
* Whether or not the console is being masked.
*/
private volatile boolean stop;
/**
* Which <code> Character </code> the
* console is being masked with.
*/
private char echochar = ' ';
/**
* Starts a new <code> Thread </code> that masks passwords
*@param prompt The prompt displayed to the user
*/
public MaskingThread(String prompt)
{
System.out.print(prompt);
}
/**
* Begin masking until asked to stop.
*/
public void run()
{
int priority = Thread.currentThread().getPriority();
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
try {
stop = true;
while(stop)
{
System.out.print("\010" + echochar);
try {
// attempt masking at this rate
Thread.currentThread().sleep(1);
}
catch (InterruptedException iex) {
Thread.currentThread().interrupt();
return;
}
}
}
finally { // restore the original priority
Thread.currentThread().setPriority(priority);
}
}
/**
* Instruct the <code> Thread </code> to stop masking.
*/
public void stopMasking()
{
this.stop = false;
}
}
/**
* This <code> Class </code> prompts the user for a password
* and attempts to mask input with blank spaces
*/
class PasswordField
{
/**
* Has the user enter a password
*@param in Input stream to be used (e.g. System.in)
*@param prompt The prompt to display to the user.
*@return The hash of the password as entered by the user.
*/
public static final String getHash(InputStream in, String prompt) throws IOException {
MaskingThread maskingthread = new MaskingThread(prompt);
Thread thread = new Thread(maskingthread);
thread.start();
char[] lineBuffer;
char[] buf;
int i;