Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Session.cs « FtpServer - github.com/ClusterM/hakchi2.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 420753725ff2df824128a43897a35285317996a5 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace mooftpserv
{
    /// <summary>
    /// FTP session/connection. Does all the heavy lifting of the FTP protocol.
    /// Reads commands, sends replies, manages data connections, and so on.
    /// Each session creates its own thread.
    /// </summary>
    class Session
    {
        // transfer data type, ascii or binary
        enum DataType { ASCII, IMAGE };

        // buffer size to use for reading commands from the control connection
        private static int CMD_BUFFER_SIZE = 4096;
        // version from AssemblyInfo
        private static string LIB_VERSION = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(2);
        // monthnames for LIST command, since DateTime returns localized names
        private static string[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
        // response text for initial response. preceeded by application name and version number.
        private static string[] HELLO_TEXT = { "hakchi2 FTP server" };
        // response text for general ok messages
        private static string[] OK_TEXT = { "Sounds good.", "Success!", "Alright, I'll do it...", "Consider it done." };
        // Result for FEAT command
        private static string[] FEATURES = { "MDTM", "MLST modify*;perm*;size*;type*;unique*;UNIX.mode;", "PASV", "MFMT", "SIZE", "TVFS", "UTF8" };

        // local EOL flavor
        private static byte[] localEolBytes = Encoding.ASCII.GetBytes(Environment.NewLine);
        // FTP-mandated EOL flavor (= CRLF)
        private static byte[] remoteEolBytes = Encoding.ASCII.GetBytes("\r\n");
        // on Windows, no ASCII conversion is necessary (CRLF == CRLF)
        private static bool noAsciiConv = (localEolBytes == remoteEolBytes);

        // socket for the control connection
        private Socket controlSocket;
        // buffer size to use for sending/receiving with data connections
        private int dataBufferSize;
        // auth handler, checks user credentials
        private IAuthHandler authHandler;
        // file system handler, implements file system access for the FTP commands
        private IFileSystemHandler fsHandler;
        // log handler, used for diagnostic logging output. can be null.
        private ILogHandler logHandler;
        // Session thread, the control and data connections are processed in this thread
        private Thread thread;

        // .NET CF does not have Thread.IsAlive, so this flag replaces it
        private bool threadAlive = false;
        // Random Number Generator for OK and HELLO texts
        private Random randomTextIndex;
        // flag for whether the user has successfully logged in
        private bool loggedIn = false;
        // name of the logged in user, also used to remember the username when waiting for the PASS command
        private string loggedInUser = null;
        // argument of pending RNFR command, when waiting for an RNTO command
        private string renameFromPath = null;

        // remote data port. null when PASV is used.
        private IPEndPoint dataPort = null;
        // socket for data connections
        private Socket dataSocket = null;
        // .NET CF does not have Socket.Bound, so this flag replaces it
        private bool dataSocketBound = false;
        // buffer for reading from the control connection
        private byte[] cmdRcvBuffer;
        // number of bytes in the cmdRcvBuffer
        private int cmdRcvBytes;
        // buffer for sending/receiving with data connections
        private byte[] dataBuffer;
        // data type of the session, can be changed by the client
        private DataType transferDataType = DataType.ASCII;

        /// <summary>
        /// Creates a new session, which can afterwards be started with Start().
        /// </summary>
        public Session(Socket socket, int bufferSize, IAuthHandler authHandler, IFileSystemHandler fileSystemHandler, ILogHandler logHandler)
        {
            this.controlSocket = socket;
            this.dataBufferSize = bufferSize;
            this.authHandler = authHandler;
            this.fsHandler = fileSystemHandler;
            this.logHandler = logHandler;

            this.cmdRcvBuffer = new byte[CMD_BUFFER_SIZE];
            this.cmdRcvBytes = 0;
            this.dataBuffer = new byte[dataBufferSize + 1]; // +1 for partial EOL
            this.randomTextIndex = new Random();

            this.thread = new Thread(new ThreadStart(this.Work));
        }

        /// <summary>
        /// Indicates whether the session is still open
        /// </summary>
        public bool IsOpen
        {
            get { return threadAlive; }
        }

        /// <summary>
        /// Start the session in a new thread
        /// </summary>
        public void Start()
        {
            if (!threadAlive)
            {
                this.thread.Start();
                threadAlive = true;
            }
        }

        /// <summary>
        /// Stop the session
        /// </summary>
        public void Stop()
        {
            if (threadAlive)
            {
                threadAlive = false;
                thread.Abort();
            }

            if (controlSocket.Connected)
                controlSocket.Close();

            if (dataSocket != null && dataSocket.Connected)
                dataSocket.Close();
        }

        /// <summary>
        /// Main method of the session thread.
        /// Reads commands and executes them.
        /// </summary>
        private void Work()
        {
            if (logHandler != null)
                logHandler.NewControlConnection();

            try
            {
                if (!authHandler.AllowControlConnection())
                {
                    Respond(421, "Control connection refused.");
                    // first flush, then close
                    controlSocket.Shutdown(SocketShutdown.Both);
                    controlSocket.Close();
                    return;
                }

                Respond(220, String.Format("This is mooftpserv v{0}. {1}", LIB_VERSION, GetRandomText(HELLO_TEXT)));

                // allow anonymous login?
                if (authHandler.AllowLogin(null, null))
                {
                    loggedIn = true;
                }

                while (controlSocket.Connected)
                {
                    string verb;
                    string args;
                    if (!ReadCommand(out verb, out args))
                    {
                        if (controlSocket.Connected)
                        {
                            // assume clean disconnect if there are no buffered bytes
                            if (cmdRcvBytes != 0)
                                Respond(500, "Failed to read command, closing connection.");
                            controlSocket.Close();
                        }
                        break;
                    }
                    else if (verb.Trim() == "")
                    {
                        // ignore empty lines
                        continue;
                    }

                    try
                    {
                        if (loggedIn)
                            ProcessCommand(verb, args);
                        else if (verb == "QUIT")
                        { // QUIT should always be allowed
                            Respond(221, "Bye.");
                            // first flush, then close
                            controlSocket.Shutdown(SocketShutdown.Both);
                            controlSocket.Close();
                        }
                        else
                        {
                            HandleAuth(verb, args);
                        }
                    }
                    catch (Exception ex)
                    {
                        Respond(500, ex);
                    }
                }
            }
            catch (Exception)
            {
                // catch any uncaught stuff, the server should not throw anything
            }
            finally
            {
                if (controlSocket.Connected)
                    controlSocket.Close();

                if (logHandler != null)
                    logHandler.ClosedControlConnection();

                threadAlive = false;
            }
        }

        /// <summary>
        /// Process an FTP command.
        /// </summary>
        private void ProcessCommand(string verb, string arguments)
        {
            switch (verb)
            {
                case "SYST":
                    {
                        Respond(215, "UNIX emulated by mooftpserv");
                        break;
                    }
                case "QUIT":
                    {
                        Respond(221, "Bye.");
                        // first flush, then close
                        controlSocket.Shutdown(SocketShutdown.Both);
                        controlSocket.Close();
                        break;
                    }
                case "USER":
                    {
                        Respond(230, "You are already logged in.");
                        break;
                    }
                case "PASS":
                    {
                        Respond(230, "You are already logged in.");
                        break;
                    }
                case "FEAT":
                    {
                        Respond(211, "Features:\r\n " + String.Join("\r\n ", FEATURES), true);
                        Respond(211, "Features done.");
                        break;
                    }
                case "OPTS":
                    {
                        // Windows Explorer uses lowercase args
                        if (arguments != null && arguments.ToUpper() == "UTF8 ON")
                            Respond(200, "Always in UTF8 mode.");
                        else
                            Respond(504, "Unknown option.");
                        break;
                    }
                case "TYPE":
                    {
                        if (arguments == "A" || arguments == "A N")
                        {
                            transferDataType = DataType.ASCII;
                            Respond(200, "Switching to ASCII mode.");
                        }
                        else if (arguments == "I")
                        {
                            transferDataType = DataType.IMAGE;
                            Respond(200, "Switching to BINARY mode.");
                        }
                        else
                        {
                            Respond(500, "Unknown TYPE arguments.");
                        }
                        break;
                    }
                case "PORT":
                    {
                        IPEndPoint port = ParseAddress(arguments);
                        if (port == null)
                        {
                            Respond(500, "Invalid host-port format.");
                            break;
                        }

                        if (!authHandler.AllowActiveDataConnection(port))
                        {
                            Respond(500, "PORT arguments refused.");
                            break;
                        }

                        dataPort = port;
                        CreateDataSocket(false);
                        Respond(200, GetRandomText(OK_TEXT));
                        break;
                    }
                case "PASV":
                    {
                        dataPort = null;

                        try
                        {
                            CreateDataSocket(true);
                        }
                        catch (Exception ex)
                        {
                            Respond(500, ex);
                            break;
                        }

                        string port = FormatAddress((IPEndPoint)dataSocket.LocalEndPoint);
                        Respond(227, String.Format("Switched to passive mode ({0})", port));
                        break;
                    }
                case "XPWD":
                case "PWD":
                    {
                        ResultOrError<string> ret = fsHandler.GetCurrentDirectory();
                        if (ret.HasError)
                            Respond(500, ret.Error);
                        else
                            Respond(257, EscapePath(ret.Result));
                        break;
                    }
                case "XCWD":
                case "CWD":
                    {
                        ResultOrError<string> ret = fsHandler.ChangeDirectory(arguments);
                        if (ret.HasError)
                            Respond(550, ret.Error);
                        else
                            Respond(200, GetRandomText(OK_TEXT));
                        break;
                    }
                case "XCUP":
                case "CDUP":
                    {
                        ResultOrError<string> ret = fsHandler.ChangeDirectory("..");
                        if (ret.HasError)
                            Respond(550, ret.Error);
                        else
                            Respond(200, GetRandomText(OK_TEXT));
                        break;
                    }
                case "XMKD":
                case "MKD":
                    {
                        ResultOrError<string> ret = fsHandler.CreateDirectory(arguments);
                        if (ret.HasError)
                            Respond(550, ret.Error);
                        else
                            Respond(257, EscapePath(ret.Result));
                        break;
                    }
                case "XRMD":
                case "RMD":
                    {
                        ResultOrError<bool> ret = fsHandler.RemoveDirectory(arguments);
                        if (ret.HasError)
                            Respond(550, ret.Error);
                        else
                            Respond(250, GetRandomText(OK_TEXT));
                        break;
                    }
                case "RETR":
                    {
                        ResultOrError<Stream> ret = fsHandler.ReadFile(arguments);
                        if (ret.HasError)
                        {
                            Respond(550, ret.Error);
                            break;
                        }

                        SendData(ret.Result);
                        break;
                    }
                case "STOR":
                    {
                        ResultOrError<Stream> ret = fsHandler.WriteFile(arguments);
                        if (ret.HasError)
                        {
                            Respond(550, ret.Error);
                            break;
                        }
                        ReceiveData(ret.Result);
                        var ret2 = fsHandler.WriteFileFinalize(arguments, ret.Result);
                        if (ret2.HasError)
                        {
                            Respond(550, ret2.Error);
                            break;
                        }
                        break;
                    }
                case "DELE":
                    {
                        ResultOrError<bool> ret = fsHandler.RemoveFile(arguments);
                        if (ret.HasError)
                            Respond(550, ret.Error);
                        else
                            Respond(250, GetRandomText(OK_TEXT));
                        break;
                    }
                case "RNFR":
                    {
                        if (arguments == null || arguments.Trim() == "")
                        {
                            Respond(500, "Empty path is invalid.");
                            break;
                        }

                        renameFromPath = arguments;
                        Respond(350, "Waiting for target path.");
                        break;
                    }
                case "RNTO":
                    {
                        if (renameFromPath == null)
                        {
                            Respond(503, "Use RNFR before RNTO.");
                            break;
                        }

                        ResultOrError<bool> ret = fsHandler.RenameFile(renameFromPath, arguments);
                        renameFromPath = null;
                        if (ret.HasError)
                            Respond(550, ret.Error);
                        else
                            Respond(250, GetRandomText(OK_TEXT));
                        break;
                    }
                case "MDTM":
                    {
                        ResultOrError<DateTime> ret = fsHandler.GetLastModifiedTimeUtc(arguments);
                        if (ret.HasError)
                            Respond(550, ret.Error);
                        else
                            Respond(213, FormatTime(EnsureUnixTime(ret.Result)));
                        break;
                    }
                case "SIZE":
                    {
                        ResultOrError<long> ret = fsHandler.GetFileSize(arguments);
                        if (ret.HasError)
                            Respond(550, ret.Error);
                        else
                            Respond(213, ret.Result.ToString());
                        break;
                    }
                case "LIST":
                    {
                        // apparently browsers like to pass arguments to LIST
                        // assuming they are passed through to the UNIX ls command
                        /*
                        arguments = RemoveLsArgs(arguments);
                        
                        ResultOrError<FileSystemEntry[]> ret = fsHandler.ListEntries(arguments);
                        if (ret.HasError)
                        {
                            Respond(500, ret.Error);
                            break;
                        }

                        SendData(MakeStream(FormatDirList(ret.Result)));
                         */
                        ResultOrError<string> ret = fsHandler.ListEntriesRaw(arguments);
                        if (ret.HasError)
                        {
                            Respond(500, ret.Error);
                            break;
                        }

                        SendData(MakeStream(ret.Result));

                        break;
                    }
                case "STAT":
                    {
                        if (arguments == null || arguments.Trim() == "")
                        {
                            Respond(504, "Not implemented for these arguments.");
                            break;
                        }

                        arguments = RemoveLsArgs(arguments);

                        ResultOrError<FileSystemEntry[]> ret = fsHandler.ListEntries(arguments);
                        if (ret.HasError)
                        {
                            Respond(500, ret.Error);
                            break;
                        }

                        Respond(213, "Status:\r\n" + FormatDirList(ret.Result), true);
                        Respond(213, "Status done.");
                        break;
                    }
                case "NLST":
                    {
                        // remove common arguments, we do not support any of them
                        arguments = RemoveLsArgs(arguments);

                        ResultOrError<FileSystemEntry[]> ret = fsHandler.ListEntries(arguments);
                        if (ret.HasError)
                        {
                            Respond(500, ret.Error);
                            break;
                        }

                        SendData(MakeStream(FormatNLST(ret.Result)));
                        break;
                    }
                case "MLSD":
                case "MLST":
                    {
                        ResultOrError<FileSystemEntry[]> ret = fsHandler.ListEntries(arguments);
                        if (ret.HasError)
                        {
                            Respond(500, ret.Error);
                            break;
                        }

                        SendData(MakeStream(FormatMLST(ret.Result)));
                        break;
                    }
                case "MFMT":
                    {
                        string[] tokens = arguments.Split(' ');
                        var time = DateTime.ParseExact(tokens[0], "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
                        var file = (tokens.Length > 1 ? String.Join(" ", tokens, 1, tokens.Length - 1) : null);
                        fsHandler.SetLastModifiedTimeUtc(file, time);
                        Respond(213, string.Format("213 Modify={0}; {1}", tokens[0], file));
                        break;
                    }
                case "NOOP":
                    {
                        Respond(200, GetRandomText(OK_TEXT));
                        break;
                    }
                case "SITE":
                    {
                        string[] tokens = arguments.Split(' ');
                        var newverb = tokens[0].ToUpper(); // commands are case insensitive
                        var newargs = (tokens.Length > 1 ? String.Join(" ", tokens, 1, tokens.Length - 1) : null);
                        ProcessCommand(newverb, newargs);
                        break;
                    }
                case "CHMOD":
                    {
                        string[] tokens = arguments.Split(' ');
                        var mode = tokens[0].ToUpper(); // commands are case insensitive
                        var file = (tokens.Length > 1 ? String.Join(" ", tokens, 1, tokens.Length - 1) : "");
                        ResultOrError<bool> ret = fsHandler.ChmodFile(mode, file);
                        if (ret.HasError)
                            Respond(550, ret.Error);
                        else
                            Respond(250, GetRandomText(OK_TEXT));
                        break;
                    }
                default:
                    {
                        Respond(500, "Unknown command.");
                        break;
                    }
            }
        }

        /// <summary>
        /// Read a command from the control connection.
        /// </summary>
        /// <returns>
        /// True if a command was read.
        /// </returns>
        /// <param name='verb'>
        /// Will receive the verb of the command.
        /// </param>
        /// <param name='args'>
        /// Will receive the arguments of the command, or null.
        /// </param>
        private bool ReadCommand(out string verb, out string args)
        {
            verb = null;
            args = null;

            int endPos = -1;
            // can there already be a command in the buffer?
            if (cmdRcvBytes > 0)
                Array.IndexOf(cmdRcvBuffer, (byte)'\n', 0, cmdRcvBytes);

            try
            {
                // read data until a newline is found
                do
                {
                    int freeBytes = cmdRcvBuffer.Length - cmdRcvBytes;
                    int bytes = controlSocket.Receive(cmdRcvBuffer, cmdRcvBytes, freeBytes, SocketFlags.None);
                    if (bytes <= 0)
                        break;

                    cmdRcvBytes += bytes;

                    // search \r\n
                    endPos = Array.IndexOf(cmdRcvBuffer, (byte)'\r', 0, cmdRcvBytes);
                    if (endPos != -1 && (cmdRcvBytes <= endPos + 1 || cmdRcvBuffer[endPos + 1] != (byte)'\n'))
                        endPos = -1;
                } while (endPos == -1 && cmdRcvBytes < cmdRcvBuffer.Length);
            }
            catch (SocketException)
            {
                // in case the socket is closed or has some other error while reading
                return false;
            }

            if (endPos == -1)
                return false;

            string command = DecodeString(cmdRcvBuffer, endPos);

            // remove the command from the buffer
            cmdRcvBytes -= (endPos + 2);
            Array.Copy(cmdRcvBuffer, endPos + 2, cmdRcvBuffer, 0, cmdRcvBytes);

            // CF is missing a limited String.Split
            string[] tokens = command.Split(' ');
            verb = tokens[0].ToUpper(); // commands are case insensitive
            args = (tokens.Length > 1 ? String.Join(" ", tokens, 1, tokens.Length - 1) : null);

            if (logHandler != null)
                logHandler.ReceivedCommand(verb, args);

            return true;
        }

        /// <summary>
        /// Send a response on the control connection
        /// </summary>
        private void Respond(uint code, string desc, bool moreFollows)
        {
            string response = code.ToString();
            if (desc != null)
                response += (moreFollows ? '-' : ' ') + desc;

            if (!response.EndsWith("\r\n"))
                response += "\r\n";

            byte[] sendBuffer = EncodeString(response);
            controlSocket.Send(sendBuffer);

            if (logHandler != null)
                logHandler.SentResponse(code, desc);
        }

        /// <summary>
        /// Send a response on the control connection
        /// </summary>
        private void Respond(uint code, string desc)
        {
            Respond(code, desc, false);
        }

        /// <summary>
        /// Send a response on the control connection, with an exception as text
        /// </summary>
        private void Respond(uint code, Exception ex)
        {
            Respond(code, ex.Message.Replace(Environment.NewLine, " "));
        }

        /// <summary>
        /// Process FTP commands when the user is not yet logged in.
        /// Mostly handles the login commands USER and PASS.
        /// </summary>
        private void HandleAuth(string verb, string args)
        {
            if (verb == "USER" && args != null)
            {
                if (authHandler.AllowLogin(args, null))
                {
                    Respond(230, "Login successful.");
                    loggedIn = true;
                }
                else
                {
                    loggedInUser = args;
                    Respond(331, "Password please.");
                }
            }
            else if (verb == "PASS")
            {
                if (loggedInUser != null)
                {
                    if (authHandler.AllowLogin(loggedInUser, args))
                    {
                        Respond(230, "Login successful.");
                        loggedIn = true;
                    }
                    else
                    {
                        loggedInUser = null;
                        Respond(530, "Login failed, please try again.");
                    }
                }
                else
                {
                    Respond(530, "No USER specified.");
                }
            }
            else
            {
                Respond(530, "Please login first.");
            }
        }

        /// <summary>
        /// Read from the given stream and send the data over a data connection
        /// </summary>
        private void SendData(Stream stream)
        {
            try
            {
                bool passive = (dataPort == null);
                using (Socket socket = OpenDataConnection())
                {
                    if (socket == null)
                        return;

                    IPEndPoint remote = (IPEndPoint)socket.RemoteEndPoint;
                    IPEndPoint local = (IPEndPoint)socket.LocalEndPoint;

                    if (logHandler != null)
                        logHandler.NewDataConnection(remote, local, passive);

                    try
                    {
                        while (true)
                        {
                            int bytes = stream.Read(dataBuffer, 0, dataBufferSize);
                            if (bytes <= 0)
                            {
                                break;
                            }

                            if (transferDataType == DataType.IMAGE || noAsciiConv)
                            {
                                // TYPE I -> just pass through
                                socket.Send(dataBuffer, bytes, SocketFlags.None);
                            }
                            else
                            {
                                // TYPE A -> convert local EOL style to CRLF

                                // if the buffer ends with a potential partial EOL,
                                // try to read the rest of the EOL
                                // (i assume that the EOL has max. two bytes)
                                if (localEolBytes.Length == 2 &&
                                    dataBuffer[bytes - 1] == localEolBytes[0])
                                {
                                    if (stream.Read(dataBuffer, bytes, 1) == 1)
                                        ++bytes;
                                }

                                byte[] convBuffer = null;
                                int convBytes = ConvertAsciiBytes(dataBuffer, bytes, true, out convBuffer);
                                socket.Send(convBuffer, convBytes, SocketFlags.None);
                            }
                        }

                        // flush socket before closing (done by using-statement)
                        socket.Shutdown(SocketShutdown.Send);
                        Respond(226, "Transfer complete.");
                    }
                    catch (Exception ex)
                    {
                        Respond(500, ex);
                        return;
                    }
                    finally
                    {
                        if (logHandler != null)
                            logHandler.ClosedDataConnection(remote, local, passive);
                    }
                }
            }
            finally
            {
                stream.Close();
            }
        }

        /// <summary>
        /// Read from a data connection and write to the given stream
        /// </summary>
        private void ReceiveData(Stream stream)
        {
            try
            {
                bool passive = (dataPort == null);
                using (Socket socket = OpenDataConnection())
                {
                    if (socket == null)
                        return;

                    IPEndPoint remote = (IPEndPoint)socket.RemoteEndPoint;
                    IPEndPoint local = (IPEndPoint)socket.LocalEndPoint;

                    if (logHandler != null)
                        logHandler.NewDataConnection(remote, local, passive);

                    try
                    {
                        while (true)
                        {
                            // fill up the in-memory buffer before writing to disk
                            int totalBytes = 0;
                            while (totalBytes < dataBufferSize)
                            {
                                int freeBytes = dataBufferSize - totalBytes;
                                int newBytes = socket.Receive(dataBuffer, totalBytes, freeBytes, SocketFlags.None);

                                if (newBytes > 0)
                                {
                                    totalBytes += newBytes;
                                }
                                else if (newBytes < 0)
                                {
                                    Respond(500, String.Format("Transfer failed: Receive() returned {0}", newBytes));
                                    return;
                                }
                                else
                                {
                                    // end of data
                                    break;
                                }
                            }

                            // end of data
                            if (totalBytes == 0)
                                break;

                            if (transferDataType == DataType.IMAGE || noAsciiConv)
                            {
                                // TYPE I -> just pass through
                                stream.Write(dataBuffer, 0, totalBytes);
                            }
                            else
                            {
                                // TYPE A -> convert CRLF to local EOL style

                                // if the buffer ends with a potential partial CRLF,
                                // try to read the LF
                                if (dataBuffer[totalBytes - 1] == remoteEolBytes[0])
                                {
                                    if (socket.Receive(dataBuffer, totalBytes, 1, SocketFlags.None) == 1)
                                        ++totalBytes;
                                }

                                byte[] convBuffer = null;
                                int convBytes = ConvertAsciiBytes(dataBuffer, totalBytes, false, out convBuffer);
                                stream.Write(convBuffer, 0, convBytes);
                            }
                        }

                        socket.Shutdown(SocketShutdown.Receive);
                        Respond(226, "Transfer complete.");
                    }
                    catch (Exception ex)
                    {
                        Respond(500, ex);
                        return;
                    }
                    finally
                    {
                        if (logHandler != null)
                            logHandler.ClosedDataConnection(remote, local, passive);
                    }
                }
            }
            finally
            {
                //stream.Close();
            }
        }

        /// <summary>
        /// Create a socket for a data connection.
        /// </summary>
        /// <param name='listen'>
        /// If true, the socket will be bound to a local port for the PASV command.
        /// Otherwise the socket can be used for connecting to the address given in a PORT command.
        /// </param>
        private void CreateDataSocket(bool listen)
        {
            if (dataSocket != null)
                dataSocket.Close();

            dataSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            if (listen)
            {
                IPAddress serverIP = ((IPEndPoint)controlSocket.LocalEndPoint).Address;
                dataSocket.Bind(new IPEndPoint(serverIP, 0));
                dataSocketBound = true; // CF is missing Socket.IsBound
                dataSocket.Listen(1);
            }
        }

        /// <summary>
        /// Opens an active or passive data connection and returns the socket
        /// or null if there was no preceding PORT or PASV command or in case or error.
        /// </summary>
        private Socket OpenDataConnection()
        {
            if (dataPort == null && !dataSocketBound)
            {
                Respond(425, "No data port configured, use PORT or PASV.");
                return null;
            }

            Respond(150, "Opening data connection.");

            try
            {
                if (dataPort != null)
                {
                    // active mode
                    dataSocket.Connect(dataPort);
                    dataPort = null;
                    return dataSocket;
                }
                else
                {
                    // passive mode
                    Socket socket = dataSocket.Accept();
                    dataSocket.Close();
                    dataSocketBound = false;
                    return socket;
                }
            }
            catch (Exception ex)
            {
                Respond(500, String.Format("Failed to open data connection: {0}", ex.Message.Replace(Environment.NewLine, " ")));
                return null;
            }
        }

        /// <summary>
        /// Convert between different EOL flavors.
        /// </summary>
        /// <returns>
        /// The number of bytes in the resultBuffer.
        /// </returns>
        /// <param name='buffer'>
        /// The input buffer whose data will be converted.
        /// </param>
        /// <param name='len'>
        /// The number of bytes in the input buffer.
        /// </param>
        /// <param name='localToRemote'>
        /// If true, the conversion will be made from local to FTP flavor,
        /// otherwise from FTP to local flavor.
        /// </param>
        /// <param name='resultBuffer'>
        /// The resulting buffer with the converted text.
        /// Can be the same reference as the input buffer if there is nothing to convert.
        /// </param>
        private int ConvertAsciiBytes(byte[] buffer, int len, bool localToRemote, out byte[] resultBuffer)
        {
            byte[] fromBytes = (localToRemote ? localEolBytes : remoteEolBytes);
            byte[] toBytes = (localToRemote ? remoteEolBytes : localEolBytes);
            resultBuffer = null;

            int startIndex = 0;
            int resultLen = 0;
            int searchLen;
            while ((searchLen = len - startIndex) > 0)
            {
                // search for the first byte of the EOL sequence
                int eolIndex = Array.IndexOf(buffer, fromBytes[0], startIndex, searchLen);

                // shortcut if there is no EOL in the whole buffer
                if (eolIndex == -1 && startIndex == 0)
                {
                    resultBuffer = buffer;
                    return len;
                }

                // allocate to worst-case size
                if (resultBuffer == null)
                    resultBuffer = new byte[len * 2];

                if (eolIndex == -1)
                {
                    Array.Copy(buffer, startIndex, resultBuffer, resultLen, searchLen);
                    resultLen += searchLen;
                    break;
                }
                else
                {
                    // compare the rest of the EOL
                    int matchBytes = 1;
                    for (int i = 1; i < fromBytes.Length && eolIndex + i < len; ++i)
                    {
                        if (buffer[eolIndex + i] == fromBytes[i])
                            ++matchBytes;
                    }

                    if (matchBytes == fromBytes.Length)
                    {
                        // found an EOL to convert
                        int copyLen = eolIndex - startIndex;
                        if (copyLen > 0)
                        {
                            Array.Copy(buffer, startIndex, resultBuffer, resultLen, copyLen);
                            resultLen += copyLen;
                        }
                        Array.Copy(toBytes, 0, resultBuffer, resultLen, toBytes.Length);
                        resultLen += toBytes.Length;
                        startIndex += copyLen + fromBytes.Length;
                    }
                    else
                    {
                        int copyLen = (eolIndex - startIndex) + 1;
                        Array.Copy(buffer, startIndex, resultBuffer, resultLen, copyLen);
                        resultLen += copyLen;
                        startIndex += copyLen;
                    }
                }
            }

            return resultLen;
        }

        /// <summary>
        /// Parse the argument of a PORT command into an IPEndPoint
        /// </summary>
        private IPEndPoint ParseAddress(string address)
        {
            string[] tokens = address.Split(',');
            byte[] bytes = new byte[tokens.Length];
            for (int i = 0; i < tokens.Length; ++i)
            {
                try
                {
                    // CF is missing TryParse
                    bytes[i] = byte.Parse(tokens[i]);
                }
                catch (Exception)
                {
                    return null;
                }
            }

            long ip = bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24;
            int port = bytes[4] << 8 | bytes[5];
            return new IPEndPoint(ip, port);
        }

        /// <summary>
        /// Format an IPEndPoint so that it can be used in a response for a PASV command
        /// </summary>
        private string FormatAddress(IPEndPoint address)
        {
            byte[] ip = address.Address.GetAddressBytes();
            int port = address.Port;

            return String.Format("{0},{1},{2},{3},{4},{5}",
                                 ip[0], ip[1], ip[2], ip[3],
                                 (port & 0xFF00) >> 8, port & 0x00FF);
        }

        /// <summary>
        /// Formats a list of file system entries for a response to a LIST or STAT command
        /// </summary>
        private string FormatDirList(FileSystemEntry[] list)
        {
            int maxSizeChars = 0;
            foreach (FileSystemEntry entry in list)
            {
                maxSizeChars = Math.Max(maxSizeChars, entry.Size.ToString().Length);
            }

            DateTime sixMonthsAgo = EnsureUnixTime(DateTime.Now.ToUniversalTime().AddMonths(-6));

            StringBuilder result = new StringBuilder();
            foreach (FileSystemEntry entry in list)
            {
                char dirflag = (entry.IsDirectory ? 'd' : '-');
                string size = entry.Size.ToString().PadLeft(maxSizeChars);
                DateTime time = EnsureUnixTime(entry.LastModifiedTimeUtc);
                string timestr = MONTHS[time.Month - 1];
                if (time < sixMonthsAgo)
                    timestr += time.ToString(" dd  yyyy");
                else
                    timestr += time.ToString(" dd hh:mm");
                string mode = entry.Mode;

                if (string.IsNullOrEmpty(mode))
                    mode = dirflag + "rwxr--r--";

                result.AppendFormat("{0} 1 owner group {1} {2} {3}\r\n",
                                    mode, size, timestr, entry.Name);
            }

            return result.ToString();
        }

        /// <summary>
        /// Formats a list of file system entries for a response to an NLST command
        /// </summary>
        private string FormatNLST(FileSystemEntry[] list)
        {
            StringBuilder sb = new StringBuilder();
            foreach (FileSystemEntry entry in list)
            {
                sb.Append(entry.Name);
                sb.Append("\r\n");
            }
            return sb.ToString();
        }

        /// <summary>
        /// Formats a list of file system entries for a response to an MLST command
        /// </summary>
        private string FormatMLST(FileSystemEntry[] list)
        {
            StringBuilder sb = new StringBuilder();
            var cd = fsHandler.GetCurrentDirectory();
            foreach (FileSystemEntry entry in list)
            {
                int p = entry.Name.IndexOf(" -> ");
                string l, f;
                if (p >= 0)
                {
                    l = entry.Name.Substring(0, p);
                    f = entry.Name.Substring(p + 4);
                }
                else
                {
                    l = f = entry.Name;
                }
                sb.AppendFormat("modify={0:yyyyMMddHHmmss};perm={1};size={2};type={3};unique={4:X};unix.mode={5:D4}; {6}\r\n",
                    entry.LastModifiedTimeUtc,
                    "rw" + (entry.IsDirectory ? "l" : "") + (entry.Mode != null && entry.Mode.Contains("x") ? "x" : ""),
                    entry.Size,
                    (l != f) ? "symlink" : (entry.IsDirectory ? "dir" : "file"),
                    (cd.Result + f).GetHashCode(),
                    (string.IsNullOrEmpty(entry.Mode) || entry.Mode.Length < 10) ? 0 : (
                    ((entry.Mode[3] == 'S') ? 4000 : 0) +
                    ((entry.Mode[6] == 'S') ? 2000 : 0) +
                    ((entry.Mode[9] == 'T') ? 1000 : 0) +
                    ((entry.Mode[1] == 'r') ? 400 : 0) +
                    ((entry.Mode[2] == 'w') ? 200 : 0) +
                    ((entry.Mode[3] != '-') ? 100 : 0) +
                    ((entry.Mode[4] == 'r') ? 040 : 0) +
                    ((entry.Mode[5] == 'w') ? 020 : 0) +
                    ((entry.Mode[6] != '-') ? 010 : 0) +
                    ((entry.Mode[7] == 'r') ? 004 : 0) +
                    ((entry.Mode[8] == 'w') ? 002 : 0) +
                    ((entry.Mode[9] != '-') ? 001 : 0)
                    ),
                    l);
                sb.Append("\r\n");
            }
            return sb.ToString();
        }

        /// <summary>
        /// Format a timestamp for a reponse to a MDTM command
        /// </summary>
        private string FormatTime(DateTime time)
        {
            return time.ToString("yyyyMMddHHmmss");
        }

        /// <summary>
        /// Restrict the year in a timestamp to >= 1970
        /// </summary>
        private DateTime EnsureUnixTime(DateTime time)
        {
            // the server claims to be UNIX, so there should be
            // no timestamps before 1970.
            // e.g. FileZilla does not handle them correctly.

            int yearDiff = time.Year - 1970;
            if (yearDiff < 0)
                return time.AddYears(-yearDiff);
            else
                return time;
        }

        /// <summary>
        /// Escape a path for a response to a PWD command
        /// </summary>
        private string EscapePath(string path)
        {
            // double-quotes in paths are escaped by doubling them
            return '"' + path.Replace("\"", "\"\"") + '"';
        }

        /// <summary>
        /// Remove "-a" or "-l" from the arguments for a LIST or STAT command
        /// </summary>
        private string RemoveLsArgs(string args)
        {
            if (args != null && (args.StartsWith("-a") || args.StartsWith("-l")))
            {
                if (args.Length == 2)
                    return null;
                else if (args.Length > 3 && args[2] == ' ')
                    return args.Substring(3);
            }

            return args;
        }

        /// <summary>
        /// Convert a string to a list of UTF8 bytes
        /// </summary>
        private byte[] EncodeString(string data)
        {
            return Encoding.UTF8.GetBytes(data);
        }

        /// <summary>
        /// Convert a list of UTF8 bytes to a string
        /// </summary>
        private string DecodeString(byte[] data, int len)
        {
            return Encoding.UTF8.GetString(data, 0, len);
        }

        /// <summary>
        /// Convert a list of UTF8 bytes to a string
        /// </summary>
        private string DecodeString(byte[] data)
        {
            return DecodeString(data, data.Length);
        }

        /// <summary>
        /// Fill a stream with the given string as UTF8 bytes
        /// </summary>
        private Stream MakeStream(string data)
        {
            return new MemoryStream(EncodeString(data));
        }

        /// <summary>
        /// Return a randomly selected text from the given list
        /// </summary>
        private string GetRandomText(string[] texts)
        {
            int index = randomTextIndex.Next(0, texts.Length);
            return texts[index];
        }
    }
}