-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFTP.java
More file actions
549 lines (497 loc) · 13.2 KB
/
FTP.java
File metadata and controls
549 lines (497 loc) · 13.2 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
package javaforce;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.net.ssl.*;
/**
* FTP client class. Supports Passive and Active mode.
*/
public class FTP {
public static interface ProgressListener {
public void setProgress(int value);
}
private Socket s;
private Socket ds;
private InputStream is;
private OutputStream os;
private BufferedReader br;
private boolean passive = true;
private String host; //passive host
private int pasvport; //passive port
private ServerSocket ss; //active socket
private boolean log = false;
private ProgressListener progress;
private boolean aborted = false;
private boolean active = true;
private Reader reader;
public boolean debug = false;
/**
* Holds the repsonse strings from the last executed command
*/
public ArrayList<String> response = new ArrayList<String>();
public int getResponseLength() {
synchronized(response) {
return response.size();
}
}
public void addResponse(String r) {
synchronized(response) {
response.add(r);
}
}
public String getNextResponse() {
synchronized(response) {
if (response.size() == 0) return null;
return response.remove(0);
}
}
public String getLastResponse() {
while (!aborted) {
synchronized(response) {
if (response.size() == 0) return null;
String res = response.remove(0);
if (res.charAt(3) == ' ') {
return res;
}
}
}
return null;
}
public boolean connect(String host, int port) throws Exception {
active = true;
s = new Socket(host, port);
is = s.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
os = s.getOutputStream();
this.host = host;
reader = new Reader();
reader.start();
wait4Response();
if (getLastResponse().startsWith("220")) {
return true;
}
disconnect(); //not valid FTP site
return false;
}
public boolean connectSSL(String host, int port) throws Exception {
active = true;
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Let us create the factory where we can set some parameters for the connection
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
// SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); //this method will only work with trusted certs
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) sc.getSocketFactory(); //this method will work with untrusted certs
SSLSocket ssl = (SSLSocket) sslsocketfactory.createSocket(host, port);
s = (Socket) ssl;
is = s.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
os = s.getOutputStream();
this.host = host;
reader = new Reader();
reader.start();
wait4Response();
if (getLastResponse().startsWith("220")) {
return true;
}
disconnect(); //not valid FTP site
return false;
}
public void abort() {
aborted = true;
}
public void disconnect() throws Exception {
active = false;
if (s != null) {
s.close();
}
s = null;
is = null;
os = null;
reader = null;
}
public void addProgressListener(ProgressListener progress) {
this.progress = progress;
}
public void setLogging(boolean state) {
log = state;
}
public void setPassiveMode(boolean mode) {
passive = mode;
}
public boolean setBinary() throws Exception {
cmd("type i");
wait4Response();
if (!getLastResponse().startsWith("200")) {
return false;
}
return true;
}
public boolean setAscii() throws Exception {
cmd("type a");
wait4Response();
if (!getLastResponse().startsWith("200")) {
return false;
}
return true;
}
public boolean login(String user, String pass) throws Exception {
cmd("user " + user);
wait4Response();
if (!getLastResponse().startsWith("331")) {
return false;
}
cmd("pass " + pass);
wait4Response();
if (!getLastResponse().startsWith("230")) {
return false;
}
return true;
}
public void logout() throws Exception {
cmd("quit");
wait4Response(); //should be "221" but ignored
getLastResponse();
}
public void cmd(String cmd) throws Exception {
if ((s == null) || (s.isClosed())) {
throw new Exception("not connected");
}
aborted = false;
if (log) {
if (cmd.startsWith("pass ")) {
JFLog.log("pass ****");
} else {
JFLog.log(cmd);
}
}
synchronized(response) {
response.clear();
}
cmd += "\r\n";
os.write(cmd.getBytes());
}
public void get(String filename, String out) throws Exception {
getPort();
cmd("retr " + filename);
FileOutputStream fos = new FileOutputStream(out);
getData(fos);
fos.close();
wait4Response();
getLastResponse();
}
public void get(String filename, OutputStream os) throws Exception {
getPort();
cmd("retr " + filename);
getData(os);
wait4Response();
getLastResponse();
}
public InputStream getStart(String filename) throws Exception {
getPort();
cmd("retr " + filename);
return getData();
}
public void get(File remote, File local) throws Exception {
get(remote.getAbsolutePath(), local.getAbsolutePath());
}
public void getFinish() throws Exception {
wait4Response();
getLastResponse();
}
public void put(InputStream is, String filename) throws Exception {
getPort();
cmd("stor " + filename);
putData(is);
wait4Response();
getLastResponse();
}
public void put(String in, String filename) throws Exception {
getPort();
cmd("stor " + filename);
FileInputStream fis = new FileInputStream(in);
putData(fis);
fis.close();
wait4Response();
getLastResponse();
}
public void put(File local, File remote) throws Exception {
put(local.getAbsolutePath(), remote.getAbsolutePath());
}
public OutputStream putStart(String filename) throws Exception {
getPort();
cmd("stor " + filename);
return putData();
}
public void putFinish() throws Exception {
wait4Response();
getLastResponse();
}
public void cd(String path) throws Exception {
cmd("cwd " + path);
wait4Response();
getLastResponse();
}
public void chmod(int mode, String path) throws Exception {
cmd("site chmod " + Integer.toString(mode, 8) + " " + path);
wait4Response();
getLastResponse();
}
public void mkdir(String path) throws Exception {
cmd("mkd " + path);
wait4Response();
getLastResponse();
}
public void rename(String oldpath, String newpath) throws Exception {
cmd("rnfr " + oldpath);
wait4Response();
getLastResponse();
cmd("rnto " + newpath);
wait4Response();
getLastResponse();
}
public void rm(String path) throws Exception {
cmd("dele " + path);
wait4Response();
getLastResponse();
}
public void rmdir(String path) throws Exception {
cmd("rmd " + path);
wait4Response();
getLastResponse();
}
public String ls(String path) throws Exception {
getPort();
cmd("list " + path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
getData(baos);
wait4Response();
if (!getLastResponse().startsWith("226")) {
throw new Exception("bad listing");
}
return baos.toString();
}
public String pwd() throws Exception {
cmd("pwd");
wait4Response();
String str = getLastResponse();
if (!str.startsWith("257")) {
throw new Exception("pwd failed");
}
if ((str.charAt(4) == '\"') && (str.charAt(str.length() - 1) == '\"')) {
return str.substring(5, str.length() - 1);
} else {
return str.substring(4);
}
}
private final int BUFSIZ = 64 * 1024;
private void getPort() throws Exception {
if (passive) {
cmd("pasv");
wait4Response();
String str = getLastResponse();
if (!str.startsWith("227")) {
throw new Exception("pasv failed");
}
//227 Entering Passive Mode (ip,ip,ip,ip,PORTHI,PORTLO).
String strs[] = str.split(",");
if (strs.length != 6) {
throw new Exception("pasv failed - bad response");
}
int hi = Integer.valueOf(strs[4]);
int lo = Integer.valueOf(strs[5].substring(0, strs[5].indexOf(")")));
pasvport = (hi << 8) + lo;
} else {
ss = new ServerSocket();
int hi = ss.getLocalPort() >> 8;
int lo = ss.getLocalPort() & 0xff;
cmd(s.getLocalAddress().getHostAddress().replaceAll("[.]", ",") + "," + hi + "," + lo);
wait4Response();
String str = getLastResponse();
if (!str.startsWith("200")) {
throw new Exception("port failed");
}
}
}
private InputStream getData() throws Exception {
aborted = false;
if (passive) {
ds = new Socket(host, pasvport);
} else {
ds = ss.accept();
}
InputStream dis = ds.getInputStream();
wait4Response();
if (!getLastResponse().startsWith("150")) {
throw new Exception("bad get");
}
return dis;
}
private void getData(OutputStream os) throws Exception {
aborted = false;
if (passive) {
ds = new Socket(host, pasvport);
} else {
ds = ss.accept();
}
byte data[] = new byte[BUFSIZ];
InputStream dis = ds.getInputStream();
wait4Response();
if (!getLastResponse().startsWith("150")) {
throw new Exception("bad get");
}
int read, total = 0;
startTimeoutThread();
while (!ds.isClosed() && !aborted) {
timeoutCounter = 0;
read = dis.read(data);
if (read == -1) {
break;
}
if (read > 0) {
os.write(data, 0, read);
total += read;
if (progress != null) {
progress.setProgress(total);
}
}
}
//read any remaining data left in buffers
if (aborted) {
return;
}
do {
timeoutCounter = 0;
read = dis.read(data);
if (read > 0) {
os.write(data, 0, read);
total += read;
if (progress != null) {
progress.setProgress(total);
}
}
} while ((read > 0) && (!aborted));
stopTimeoutThread();
}
private OutputStream putData() throws Exception {
aborted = false;
if (passive) {
ds = new Socket(host, pasvport);
} else {
ds = ss.accept();
}
OutputStream dos = ds.getOutputStream();
wait4Response();
if (!getLastResponse().startsWith("150")) {
throw new Exception("bad put");
}
return dos;
}
private void putData(InputStream is) throws Exception {
aborted = false;
if (passive) {
ds = new Socket(host, pasvport);
} else {
ds = ss.accept();
}
byte data[] = new byte[BUFSIZ];
OutputStream dos = ds.getOutputStream();
wait4Response();
if (!getLastResponse().startsWith("150")) {
throw new Exception("bad put");
}
int total = 0;
startTimeoutThread();
while ((!ds.isClosed()) && (is.available() > 0) && (!aborted)) {
timeoutCounter = 0;
int read = is.read(data);
if (read > 0) {
dos.write(data, 0, read);
total += read;
if (progress != null) {
progress.setProgress(total);
}
}
}
stopTimeoutThread();
dos.flush();
ds.close();
ds = null;
}
private void wait4Response() throws Exception {
while (!aborted) {
synchronized(response) {
int size = response.size();
if (size > 0) {
String last = response.get(size-1);
if (last.charAt(3) == ' ') return;
}
response.wait();
}
}
}
private class Reader extends Thread {
public void run() {
while (active) {
try {
String res = br.readLine();
JFLog.log(res);
addResponse(res);
if (res.charAt(3) == ' ') {
synchronized(response) {
response.notify();
}
}
if (res.startsWith("5")) {
JFLog.log("Aborted");
aborted = true;
if (ds != null) {
ds.close();
ds = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private Timer timer;
private int timeoutCounter;
private void startTimeoutThread() {
timeoutCounter = 0;
if (timer != null) {
timer.cancel();
timer = null;
}
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
timeoutCounter++;
if (timeoutCounter == 20) {
JFLog.log("Error:Transfer Timeout");
aborted = true;
if (ds != null) {
try {ds.close();} catch (Exception e) {}
ds = null;
}
timer.cancel();
timer = null;
}
}
}, 1000, 1000);
}
private void stopTimeoutThread() {
timer.cancel();
timer = null;
}
}