-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFTPClient.java
More file actions
364 lines (335 loc) · 11.1 KB
/
FTPClient.java
File metadata and controls
364 lines (335 loc) · 11.1 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
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.security.*;
public class FTPClient implements Runnable
{
/**
* The place the connection between the client
* and server is made
*/
private Socket connection;
/**
* <code> Stream </code> reading from the server
*/
private DataInputStream input;
/**
* <code> Stream </code> writing to the server
*/
public DataOutputStream output;
/**
* <code> Thread </code> that continuously reads
* in from the server.
*/
private Thread inputThread;
/**
* Generates SHA-1 checksums
*/
public MessageDigest md;
/**
* Whether or not to use checksums
*/
public boolean checksum;
/**
* Instantiate various variables and start the client
*/
public static void main(String[] args) throws IOException
{
if(new File("Downloads").mkdir())
System.out.println("Downloads folder created.");
System.out.print("Connect to: ");
String stuff=new Scanner(System.in).next();
String hostname=null;
int port=5000;
try{hostname=stuff.substring(0, stuff.indexOf(":"));
port=Integer.parseInt(stuff.substring(stuff.indexOf(":")+1));}
catch(StringIndexOutOfBoundsException e){hostname=stuff;}
catch(NumberFormatException e){System.out.println(
"Invalid port number."); System.exit(0);}
(new FTPClient()).gogogo(hostname, port);
}
/**
* Make connection to server and get associated streams.
* Start separate thread to allow the client to
* continually read input from the server.
* @param host The address of the <code> FTPServer </code>
* @param port The port the server is being run on
*/
public void gogogo(String host, int port) throws IOException
{
try {
connection = new Socket(InetAddress.getByName(host), port );
input = new DataInputStream(connection.getInputStream() );
output = new DataOutputStream(connection.getOutputStream() );
}
catch(ConnectException e)
{
System.out.println("Connection refused by "+host+" at port "+port+".");
System.exit(1);
}
catch(UnknownHostException e)
{
System.out.println("Could not find "+host+".");
System.exit(1);
}
catch ( IOException e ) {
e.printStackTrace();
}
Scanner scan=new Scanner(System.in);
if(input.readBoolean())
{
System.out.println("This server requires that you authenticate yourself.");
String pass = null;
try {
pass = PasswordField.getHash(System.in, "Enter password: ");
}
catch(IOException e){e.printStackTrace();}
System.out.print("\r");
if(pass==null)
{
System.out.println("Incorrect password. Connection refused.");
System.exit(0);
}
output.writeUTF(pass);
if(input.readBoolean())
{
System.out.println("Incorrect password. Connection refused.");
System.exit(0);
}
}
checksum=input.readBoolean();
try{md=MessageDigest.getInstance("SHA-1");}
catch(NoSuchAlgorithmException e){e.printStackTrace();}
inputThread = new Thread( this );
inputThread.start();
//Writes to the server
while(true)
{
try{String request=scan.nextLine().trim();
if(request.equalsIgnoreCase("exit")||request.equalsIgnoreCase("quit")||request.equalsIgnoreCase("bye")||request.equalsIgnoreCase("close"))
System.exit(0);
output.writeUTF(request);
}
catch(NoSuchElementException e){System.exit(0);}
}
}
/**
* Control thread that allows continuous update of the
* text area display.
*/
public void run()
{
while ( true )
{
try {
String text=input.readUTF();
try
{
if(text.substring(0, 5).equals("<EOF>")) //current directory
System.out.print(text.substring(5)+"> ");
else if(text.substring(0, 6).equals("<FILE>")) //file is being transfered
recieveFile(text);
else if(text.substring(0, 8).equals("<FOLDER>"))
new File(text.substring(text.indexOf(">")+1)).mkdir();
else
System.out.println(text);
}
catch(StringIndexOutOfBoundsException e){System.out.println(text);}
catch(Exception e){e.printStackTrace();}
}
catch(SocketException e){
System.out.println("Server closed by host.");
System.exit(0);}
catch(EOFException e){
System.out.println("Server closed by host.");
System.exit(0);}
catch ( IOException e ) {
e.printStackTrace();
}
}
}
/**
* Reads in file information from the server
* and stores it locally
* @param text Filename and size of the file
*/
private void recieveFile(String text) throws IOException
{
long start=0;
FileOutputStream fos=new FileOutputStream(text.substring(6, text.lastIndexOf(":")));
BufferedOutputStream bos=new BufferedOutputStream(fos);
byte[] array=new byte[Integer.parseInt(text.substring(text.lastIndexOf(":")+1))];
int length=array.length;
if(checksum)
while(true)
{
start=System.currentTimeMillis();
input.readFully(array);
byte[] mysha=md.digest(array);
byte[] serversha=new byte[20];
input.readFully(serversha);
boolean good=true;
for(int i=0; i<20; i++)
if(mysha[i]!=serversha[i])
good=false;
if(good)
{
output.writeBoolean(true);
break;
}
else
{
output.writeBoolean(false);
System.out.println("Bad checksum; re-sending file");
}
}
else
{
start=System.currentTimeMillis();
input.readFully(array);
}
bos.write(array, 0, length);
bos.flush();
bos.close();
long time = System.currentTimeMillis()-start;
if(time==0)
time=1;
System.out.println(length+" bytes recieved in "+(time/1000.0)+" seconds ("+(length/time)+" Kbytes/s)");
}
}
/**
* 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;
buf = lineBuffer = new char[128];
int room = buf.length;
int offset = 0;
int c;
loop:
while (true)
{
switch (c = in.read())
{
case -1:
case '\n':
break loop;
case '\r':
int c2 = in.read();
if ((c2 != '\n') && (c2 != -1))
{
if (!(in instanceof PushbackInputStream))
in = new PushbackInputStream(in);
((PushbackInputStream)in).unread(c2);
}
else
break loop;
default:
if (--room < 0)
{
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
Arrays.fill(lineBuffer, ' ');
lineBuffer = buf;
}
buf[offset++] = (char) c;
break;
}
}
maskingthread.stopMasking();
if (offset == 0)
return null;
char[] ret = new char[offset];
System.arraycopy(buf, 0, ret, 0, offset);
Arrays.fill(buf, ' ');
return hash(ret);
}
/**
* Hashes a password
*/
public static String hash(char[] ___)
{
String ____="";
long _____=0, _______=___.length, __=2, ______=524287;
char[] _=___;
for(long _________=_____; _________<_______+_.length; _________=_________+__)
{
_____*=______;
_____+=_[(int)(_________/__)]+__;
}
return (_____*(_______+__))+"";
}
}