File: FtpCommandHandler.java

package info (click to toggle)
openjdk-11 11.0.4%2B11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 757,028 kB
  • sloc: java: 5,016,041; xml: 1,191,974; cpp: 934,731; ansic: 555,697; sh: 24,299; objc: 12,703; python: 3,602; asm: 3,415; makefile: 2,772; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (719 lines) | stat: -rw-r--r-- 26,144 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

import java.net.*;
import java.io.*;
import java.util.regex.*;
import java.security.*;
import javax.net.ssl.*;

/*
 * This class handles one client connection. It will interpret and act on the
 * commands (like USER, GET, PUT etc...) sent through the socket passed to
 * the constructor.
 *
 * To function it needs to be provided 2 handlers, one for the filesystem
 * and one for authentication.
 * @see FileSystemHandler
 * @see AuthHandler
 * @see #setHandlers(FtpFileSystemHandler,FtpAuthHandler)
 */

public class FtpCommandHandler extends Thread {
    private FtpServer parent = null;
    private Socket cmd = null;
    private Socket oldCmd = null;
    private InetAddress clientAddr = null;
    private ServerSocket pasv = null;

    private BufferedReader in = null;

    private PrintStream out = null;

    private FtpFileSystemHandler fsh = null;
    private FtpAuthHandler auth = null;

    private boolean done = false;

    private String username = null;
    private String password = null;
    private String account = null;
    private boolean logged = false;
    private boolean epsvAll = false;
    private int dataPort = 0;
    private InetAddress dataAddress = null;
    private boolean pasvEnabled = true;
    private boolean portEnabled = true;
    private boolean extendedEnabled = true;
    private boolean binary = true;
    private String renameFrom = null;
    private long restart = 0;
    private boolean useCrypto = false;
    private boolean useDataCrypto = false;
    private SSLSocketFactory sslFact = null;

    private final int ERROR = -1;
    private final int QUIT = 0;
    private final int USER = 1;
    private final int PASS = 2;
    private final int CWD = 3;
    private final int CDUP = 4;
    private final int PWD = 5;
    private final int TYPE = 6;
    private final int NOOP = 7;
    private final int RETR = 8;
    private final int PORT = 9;
    private final int PASV = 10;
    private final int EPSV = 11;
    private final int EPRT = 12;
    private final int SYST = 13;
    private final int STOR = 14;
    private final int STOU = 15;
    private final int LIST = 16;
    private final int NLST = 17;
    private final int RNFR = 18;
    private final int RNTO = 19;
    private final int DELE = 20;
    private final int REST = 21;
    private final int AUTH = 22;
    private final int FEAT = 23;
    private final int CCC = 24;
    private final int PROT = 25;
    private final int PBSZ = 26;

    private String[] commands =
    { "QUIT", "USER", "PASS", "CWD", "CDUP", "PWD", "TYPE", "NOOP", "RETR",
      "PORT", "PASV", "EPSV", "EPRT", "SYST", "STOR", "STOU", "LIST", "NLST",
      "RNFR", "RNTO", "DELE", "REST", "AUTH", "FEAT", "CCC", "PROT", "PBSZ"
    };

    private boolean isPasvSet() {
        if (pasv != null && !pasvEnabled) {
            try {
                pasv.close();
            } catch ( IOException e) {

            }
            pasv = null;
        }
        if (pasvEnabled && pasv != null)
            return true;
        return false;
    }

    private OutputStream getOutDataStream() throws IOException {
        if (isPasvSet()) {
            Socket s = pasv.accept();
            if (useCrypto && useDataCrypto) {
                SSLSocket ssl = (SSLSocket) sslFact.createSocket(s, clientAddr.getHostName(), s.getPort(), true);
                ssl.setUseClientMode(false);
                s = ssl;
            }
            return s.getOutputStream();
        }
        if (dataAddress != null) {
            Socket s;
            if (useCrypto) {
                s = sslFact.createSocket(dataAddress, dataPort);
            } else
                s = new Socket(dataAddress, dataPort);
            dataAddress = null;
            dataPort = 0;
            return s.getOutputStream();
        }
        return null;
    }

    private InputStream getInDataStream() throws IOException {
        if (isPasvSet()) {
            Socket s = pasv.accept();
            if (useCrypto && useDataCrypto) {
                SSLSocket ssl = (SSLSocket) sslFact.createSocket(s, clientAddr.getHostName(), s.getPort(), true);
                ssl.setUseClientMode(false);
                s = ssl;
            }
            return s.getInputStream();
        }
        if (dataAddress != null) {
            Socket s;
            if (useCrypto) {
                s = sslFact.createSocket(dataAddress, dataPort);
            } else
                s = new Socket(dataAddress, dataPort);
            dataAddress = null;
            dataPort = 0;
            return s.getInputStream();
        }
        return null;
    }

    private void parsePort(String port_arg) throws IOException {
        if (epsvAll) {
            out.println("501 PORT not allowed after EPSV ALL.");
            return;
        }
        if (!portEnabled) {
            out.println("500 PORT command is disabled, please use PASV.");
            return;
        }
        StringBuffer host;
        int i = 0, j = 4;
        while (j > 0) {
            i = port_arg.indexOf(',', i + 1);
            if (i < 0)
                break;
            j--;
        }
        if (j != 0) {
            out.println("500 '" + port_arg + "': command not understood.");
            return;
        }
        try {
            host = new StringBuffer(port_arg.substring(0, i));
            for (j = 0; j < host.length(); j++)
                if (host.charAt(j) == ',')
                    host.setCharAt(j, '.');
            String ports = port_arg.substring(i + 1);
            i = ports.indexOf(',');
            dataPort = Integer.parseInt(ports.substring(0, i)) << 8;
            dataPort += (Integer.parseInt(ports.substring(i + 1)));
            dataAddress = InetAddress.getByName(host.toString());
            out.println("200 Command okay.");
        } catch (Exception ex3) {
            dataPort = 0;
            dataAddress = null;
            out.println("500 '" + port_arg + "': command not understood.");
        }
    }

    private void parseEprt(String arg) {
        if (epsvAll) {
            out.println("501 PORT not allowed after EPSV ALL");
            return;
        }
        if (!extendedEnabled || !portEnabled) {
            out.println("500 EPRT is disabled, use PASV instead");
            return;
        }
        Pattern p = Pattern.compile("\\|(\\d)\\|(.*)\\|(\\d+)\\|");
        Matcher m = p.matcher(arg);
        if (!m.find()) {
            out.println("500 '" + arg + "': command not understood.");
            return;
        }
        try {
            dataAddress = InetAddress.getByName(m.group(2));
        } catch (UnknownHostException e) {
            out.println("500 " + arg + ": invalid address.");
            dataAddress = null;
            return;
        }
        dataPort = Integer.parseInt(m.group(3));
        out.println("200 Command okay.");
    }

    private void doPasv() {
        if (!pasvEnabled) {
            out.println("500 PASV is disabled, use PORT.");
            return;
        }
        try {
            if (pasv == null)
                pasv = new ServerSocket(0);
            int port = pasv.getLocalPort();
            InetAddress rAddress = cmd.getLocalAddress();
            if (rAddress instanceof Inet6Address) {
                out.println("500 PASV illegal over IPv6 addresses, use EPSV.");
                return;
            }
            byte[] a = rAddress.getAddress();
            out.println("227 Entering Passive Mode " + a[0] + "," + a[1] + "," + a[2] + "," + a[3] + "," +
                        (port >> 8) + "," + (port & 0xff) );
        } catch (IOException e) {
            out.println("425 can't build data connection: Connection refused.");
        }
    }

    private void doEpsv(String arg) {
        if (!extendedEnabled || !pasvEnabled) {
            out.println("500 EPSV disabled, use PORT or PASV.");
            return;
        }
        if ("all".equalsIgnoreCase(arg)) {
            out.println("200 EPSV ALL Command successful.");
            epsvAll = true;
            return;
        }
        try {
            if (pasv == null)
                pasv = new ServerSocket(0);
            int port = pasv.getLocalPort();
            out.println("229 Entering Extended Passive Mode (|||" + port + "|)");
        } catch (IOException e) {
            out.println("500 Can't create data connection.");
        }
    }

    private void doRetr(String arg) {
        try {
            OutputStream dOut = getOutDataStream();
            if (dOut != null) {
                InputStream dIn = fsh.getFile(arg);
                if (dIn == null) {
                    out.println("550 File not found.");
                    dOut.close();
                    return;
                }
                out.println("150 Opening " + (binary ? "BINARY " : "ASCII ") + " data connection for file " + arg +
                            "(" + fsh.getFileSize(arg) + " bytes).");
                if (binary) {
                    byte[] buf = new byte[2048];
                    dOut = new BufferedOutputStream(dOut);
                    int count;
                    if (restart > 0) {
                        dIn.skip(restart);
                        restart = 0;
                    }
                    do {
                        count = dIn.read(buf);
                        if (count > 0)
                            dOut.write(buf, 0, count);
                    } while (count >= 0);
                    dOut.close();
                    dIn.close();
                    out.println("226 Transfer complete.");
                }
            }
        } catch (IOException e) {

        }
    }

    private void doStor(String arg, boolean unique) {
        try {
            InputStream dIn = getInDataStream();
            if (dIn != null) {
                OutputStream dOut = fsh.putFile(arg);
                if (dOut == null) {
                    out.println("500 Can't create file " + arg);
                    dIn.close();
                    return;
                }
                out.println("150 Opening " + (binary ? "BINARY " : "ASCII ") + " data connection for file " + arg);
                if (binary) {
                    byte[] buf = new byte[2048];
                    dOut = new BufferedOutputStream(dOut);
                    int count;
                    do {
                        count = dIn.read(buf);
                        if (count > 0)
                            dOut.write(buf, 0, count);
                    } while (count >= 0);
                    dOut.close();
                    dIn.close();
                    out.println("226 Transfer complete.");
                }
            }
        } catch (IOException e) {

        }
    }

    private void doList() {
        try {
            OutputStream dOut = getOutDataStream();
            if (dOut != null) {
                InputStream dIn = fsh.listCurrentDir();
                if (dIn == null) {
                    out.println("550 File not found.");
                    dOut.close();
                    return;
                }
                out.println("150 Opening ASCII data connection for file list");
                byte[] buf = new byte[2048];
                dOut = new BufferedOutputStream(dOut);
                int count;
                do {
                    count = dIn.read(buf);
                    if (count > 0)
                        dOut.write(buf, 0, count);
                } while (count >= 0);
                dOut.close();
                dIn.close();
                out.println("226 Transfer complete.");
            }
        } catch (IOException e) {

        }
    }

    private boolean useTLS() {
        if (sslFact == null) {
            sslFact = (SSLSocketFactory) SSLSocketFactory.getDefault();
        }
        if (sslFact == null)
            return false;
        return true;
    }

    private void stopTLS() {
        if (useCrypto) {
            SSLSocket ssl = (SSLSocket) cmd;
            try {
                ssl.close();
            } catch (IOException e) {
                // nada
            }
            cmd = oldCmd;
            oldCmd = null;
            try {
                in = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
                out = new PrintStream(cmd.getOutputStream(), true, "ISO8859_1");
            } catch (Exception ex) {

            }
        }
    }

    public void setHandlers(FtpFileSystemHandler f, FtpAuthHandler a) {
        fsh = f;
        auth = a;
    }

    public FtpCommandHandler(Socket cl, FtpServer p) {
        parent = p;
        cmd = cl;
        clientAddr = cl.getInetAddress();
    }

    public void terminate() {
        done = true;
    }

    private int parseCmd(StringBuffer cmd) {

        if (cmd == null || cmd.length() < 3) // Shortest command is 3 char long
            return ERROR;
        int blank = cmd.indexOf(" ");
        if (blank < 0)
            blank = cmd.length();
        if (blank < 3)
            return ERROR;
        String s = cmd.substring(0,blank);
        cmd.delete(0, blank + 1);
        System.out.println("parse: cmd = " + s + " arg = " +cmd.toString());
        for (int i = 0; i < commands.length; i++)
            if (s.equalsIgnoreCase(commands[i]))
                return i;
        // Unknown command
        return ERROR;
    }

    private boolean checkLogged() {
        if (!logged) {
            out.println("530 Not logged in.");
            return false;
        }
        return true;
    }

    public void run() {
        try {
            // cmd.setSoTimeout(2000);
            in = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
            out = new PrintStream(cmd.getOutputStream(), true, "ISO8859_1");
            out.println("---------------------------------\n220 Java FTP test server"
                    + " (j2se 6.0) ready.\n \n                Please send commands\n"
                    + "-----------------------------\n\n\n");
            out.flush();
            if (auth.authType() == 0) // No auth needed
                logged = true;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        String str;
        StringBuffer buf;
        int res;
        while (!done) {
            try {
                str = in.readLine();
                System.out.println("line: " + str);
                buf = new StringBuffer(str);
                res = parseCmd(buf);
                switch (res) {
                case ERROR:
                    out.println("500 '" + str +"': command not understood.");
                    break;
                case QUIT:
                    out.println("221 Goodbye.");
                    done = true;
                    break;
                case USER:
                    logged = false;
                    username = buf.toString();
                    if (auth.authType() > 1)
                        out.println("331 User name okay, need password.");
                    else {
                        if (auth.authenticate(username, null)) {
                            out.println("230 User logged in, proceed.");
                            logged = true;
                        } else {
                            out.println("331 User name okay, need password.");
                        }
                    }
                    break;
                case PASS:
                    if (logged || (username == null)) {
                        out.println("503 Login with USER first.");
                        break;
                    }
                    password = buf.toString();
                    if (auth.authType() == 3) {
                        out.println("332 Need account for login.");
                        break;
                    }
                    if (auth.authenticate(username, password)) {
                        logged = true;
                        out.println("230 User " + username + " logged in.");
                        break;
                    }
                    out.println("530 Login incorrect.");
                    username = null;
                    break;
                case CWD:
                    if (checkLogged()) {
                        String path = buf.toString();
                        if (fsh.cd(path)) {
                            out.println("250 CWD command successful.");
                        } else {
                            out.println("550 " + path + ": no such file or directory.");
                        }
                    }
                    break;
                case CDUP:
                    if (checkLogged()) {
                        if (fsh.cdUp())
                            out.println("250 CWD command successful.");
                        else
                            out.println("550 invalid path.");
                    }
                    break;
                case PWD:
                    if (checkLogged()) {
                        String s = fsh.pwd();
                        out.println("257 \"" + s + "\" is current directory");
                    }
                    break;
                case NOOP:
                    if (checkLogged()) {
                        out.println("200 NOOP command successful.");
                    }
                    break;
                case PORT:
                    if (checkLogged()) {
                        parsePort(buf.toString());
                    }
                    break;
                case EPRT:
                    if (checkLogged()) {
                        parseEprt(buf.toString());
                    }
                    break;
                case PASV:
                    if (checkLogged())
                        doPasv();
                    break;
                case EPSV:
                    if (checkLogged())
                        doEpsv(buf.toString());
                    break;
                case RETR:
                    if (checkLogged()) {
                        doRetr(buf.toString());
                    }
                    break;
                case SYST:
                    if (checkLogged()) {
                        out.println("215 UNIX Type: L8 Version: Java 6.0");
                    }
                    break;
                case TYPE:
                    if (checkLogged()) {
                        String arg = buf.toString();
                        if (arg.length() != 1 || "AIE".indexOf(arg.charAt(0)) < 0) {
                            out.println("500 'TYPE " + arg + "' command not understood.");
                            continue;
                        }
                        out.println("200 Type set to " + buf.toString() + ".");
                        if (arg.charAt(0) == 'I')
                            binary = true;
                        else
                            binary = false;
                    }
                    break;
                case STOR:
                case STOU:
                    // TODO: separate STOR and STOU (Store Unique)
                    if (checkLogged()) {
                        doStor(buf.toString(), false);
                    }
                    break;
                case LIST:
                    if (checkLogged()) {
                        doList();
                    }
                    break;
                case NLST:
                    // TODO: implememt
                    break;
                case DELE:
                    if (checkLogged()) {
                        String arg = buf.toString();
                        if (fsh.removeFile(arg)) {
                            out.println("250 file " + arg + " deleted.");
                            break;
                        }
                        out.println("550 " + arg + ": no such file or directory.");
                    }
                    break;
                case RNFR:
                    if (checkLogged()) {
                        if (renameFrom != null) {
                            out.println("503 Bad sequence of commands.");
                            break;
                        }
                        renameFrom = buf.toString();
                        if (fsh.fileExists(renameFrom)) {
                            out.println("350 File or directory exists, ready for destination name.");
                        } else {
                            out.println("550 " + renameFrom + ": no such file or directory");
                            renameFrom = null;
                        }
                    }
                    break;
                case RNTO:
                    if (checkLogged()) {
                        if (renameFrom == null) {
                            out.println("503 Bad sequence of commands.");
                            break;
                        }
                        if (fsh.rename(renameFrom, buf.toString())) {
                            out.println("250 Rename successful");
                        } else {
                            out.println("550 Rename ");
                        }
                        renameFrom = null;
                    }
                    break;
                case REST:
                    if (checkLogged()) {
                        String arg = buf.toString();
                        restart = Long.parseLong(arg);
                        if (restart > 0)
                            out.println("350 Restarting at " + restart + ". Send STORE or RETRIEVE to initiate transfer");
                        else
                            out.println("501 Syntax error in command of arguments.");
                    }
                    break;
                case FEAT:
                    out.println("211-Features:");
                    out.println(" REST STREAM");
                    out.println(" PBSZ");
                    out.println(" AUTH TLS");
                    out.println(" PROT P");
                    out.println(" CCC");
                    out.println("211 End");
                    break;
                case AUTH:
                    if ("TLS".equalsIgnoreCase(buf.toString()) && useTLS()) {
                        out.println("234 TLS Authentication OK.");
                        out.flush();
                        SSLSocket ssl;
                        String[] suites = sslFact.getSupportedCipherSuites();
                        try {
                            ssl = (SSLSocket) sslFact.createSocket(cmd, cmd.getInetAddress().getHostName(), cmd.getPort(), false);
                            ssl.setUseClientMode(false);
                            ssl.setEnabledCipherSuites(suites);
                            ssl.startHandshake();
                        } catch (IOException ioe) {
                            ioe.printStackTrace();
                            out.println("550 Unable to create secure channel.");
                            break;
                        }
                        oldCmd = cmd;
                        cmd = ssl;
                        out = new PrintStream(cmd.getOutputStream(), true, "ISO8859_1");
                        in = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
                        System.out.println("Secure socket created!");
                        useCrypto = true;
                        break;
                    }
                    out.println("501 Unknown or unsupported AUTH type");
                    break;
                case CCC:
                    out.println("200 Command OK.");
                    stopTLS();
                    break;
                case PROT:
                    String arg = buf.toString();
                    if ("C".equalsIgnoreCase(arg)) {
                        // PROT C : Clear protection level
                        // No protection on data channel;
                        useDataCrypto = false;
                        out.println("200 Command OK.");
                        break;
                    }
                    if ("P".equalsIgnoreCase(arg)) {
                        // PROT P : Private protection level
                        // Data channel is integrity and confidentiality protected
                        useDataCrypto = true;
                        out.println("200 Command OK.");
                        break;
                    }
                    out.println("537 Requested PROT level not supported by security mechanism.");
                    break;
                case PBSZ:
                    // TODO: finish
                    out.println("200 Command OK.");
                    break;

                }

            } catch (InterruptedIOException ie) {
                // loop
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
        try {
            in.close();
            out.close();
            cmd.close();
        } catch (IOException e) {
        }
        parent.removeClient(this);
    }
}