aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/Twisted/py3/twisted/protocols/ftp.py
blob: 8ac115c7fab2123e0af2ee13e468ea51fba50fd7 (plain) (blame)
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
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
# -*- test-case-name: twisted.test.test_ftp -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
An FTP protocol implementation
"""

# System Imports
import errno
import fnmatch
import ipaddress
import os
import re
import stat
import time

try:
    import grp
    import pwd
except ImportError:
    pwd = grp = None  # type: ignore[assignment]

from zope.interface import Interface, implementer

# Twisted Imports
from twisted import copyright
from twisted.cred import checkers, credentials, error as cred_error, portal
from twisted.internet import defer, error, interfaces, protocol, reactor
from twisted.protocols import basic, policies
from twisted.python import failure, filepath, log

# constants
# response codes

RESTART_MARKER_REPLY = "100"
SERVICE_READY_IN_N_MINUTES = "120"
DATA_CNX_ALREADY_OPEN_START_XFR = "125"
FILE_STATUS_OK_OPEN_DATA_CNX = "150"

CMD_OK = "200.1"
TYPE_SET_OK = "200.2"
ENTERING_PORT_MODE = "200.3"
EPSV_ALL_OK = "200.4"
CMD_NOT_IMPLMNTD_SUPERFLUOUS = "202"
SYS_STATUS_OR_HELP_REPLY = "211.1"
FEAT_OK = "211.2"
DIR_STATUS = "212"
FILE_STATUS = "213"
HELP_MSG = "214"
NAME_SYS_TYPE = "215"
SVC_READY_FOR_NEW_USER = "220.1"
WELCOME_MSG = "220.2"
SVC_CLOSING_CTRL_CNX = "221.1"
GOODBYE_MSG = "221.2"
DATA_CNX_OPEN_NO_XFR_IN_PROGRESS = "225"
CLOSING_DATA_CNX = "226.1"
TXFR_COMPLETE_OK = "226.2"
ENTERING_PASV_MODE = "227"
ENTERING_EPSV_MODE = "229"
USR_LOGGED_IN_PROCEED = "230.1"  # v1 of code 230
GUEST_LOGGED_IN_PROCEED = "230.2"  # v2 of code 230
REQ_FILE_ACTN_COMPLETED_OK = "250"
PWD_REPLY = "257.1"
MKD_REPLY = "257.2"

USR_NAME_OK_NEED_PASS = "331.1"  # v1 of Code 331
GUEST_NAME_OK_NEED_EMAIL = "331.2"  # v2 of code 331
NEED_ACCT_FOR_LOGIN = "332"
REQ_FILE_ACTN_PENDING_FURTHER_INFO = "350"

SVC_NOT_AVAIL_CLOSING_CTRL_CNX = "421.1"
TOO_MANY_CONNECTIONS = "421.2"
CANT_OPEN_DATA_CNX = "425"
CNX_CLOSED_TXFR_ABORTED = "426"
REQ_ACTN_ABRTD_FILE_UNAVAIL = "450"
REQ_ACTN_ABRTD_LOCAL_ERR = "451"
REQ_ACTN_ABRTD_INSUFF_STORAGE = "452"

SYNTAX_ERR = "500"
SYNTAX_ERR_IN_ARGS = "501"
CMD_NOT_IMPLMNTD = "502.1"
OPTS_NOT_IMPLEMENTED = "502.2"
PASV_IPV6_NOT_IMPLEMENTED = "502.3"
BAD_CMD_SEQ = "503"
CMD_NOT_IMPLMNTD_FOR_PARAM = "504"
UNSUPPORTED_NETWORK_PROTOCOL = "522"
NOT_LOGGED_IN = "530.1"  # v1 of code 530 - please log in
AUTH_FAILURE = "530.2"  # v2 of code 530 - authorization failure
NEED_ACCT_FOR_STOR = "532"
FILE_NOT_FOUND = "550.1"  # no such file or directory
PERMISSION_DENIED = "550.2"  # permission denied
ANON_USER_DENIED = "550.3"  # anonymous users can't alter filesystem
IS_NOT_A_DIR = "550.4"  # rmd called on a path that is not a directory
REQ_ACTN_NOT_TAKEN = "550.5"
FILE_EXISTS = "550.6"
IS_A_DIR = "550.7"
PAGE_TYPE_UNK = "551"
EXCEEDED_STORAGE_ALLOC = "552"
FILENAME_NOT_ALLOWED = "553"


RESPONSE = {
    # -- 100's --
    # TODO: this must be fixed
    RESTART_MARKER_REPLY: "110 MARK yyyy-mmmm",
    SERVICE_READY_IN_N_MINUTES: "120 service ready in %s minutes",
    DATA_CNX_ALREADY_OPEN_START_XFR: "125 Data connection already open, "
    "starting transfer",
    FILE_STATUS_OK_OPEN_DATA_CNX: "150 File status okay; about to open "
    "data connection.",
    # -- 200's --
    CMD_OK: "200 Command OK",
    TYPE_SET_OK: "200 Type set to %s.",
    ENTERING_PORT_MODE: "200 PORT OK",
    EPSV_ALL_OK: "200 EPSV ALL OK",
    CMD_NOT_IMPLMNTD_SUPERFLUOUS: "202 Command not implemented, "
    "superfluous at this site",
    SYS_STATUS_OR_HELP_REPLY: "211 System status reply",
    FEAT_OK: ["211-Features:", "211 End"],
    DIR_STATUS: "212 %s",
    FILE_STATUS: "213 %s",
    HELP_MSG: "214 help: %s",
    NAME_SYS_TYPE: "215 UNIX Type: L8",
    WELCOME_MSG: "220 %s",
    SVC_READY_FOR_NEW_USER: "220 Service ready",
    SVC_CLOSING_CTRL_CNX: "221 Service closing control " "connection",
    GOODBYE_MSG: "221 Goodbye.",
    DATA_CNX_OPEN_NO_XFR_IN_PROGRESS: "225 data connection open, no "
    "transfer in progress",
    CLOSING_DATA_CNX: "226 Abort successful",
    TXFR_COMPLETE_OK: "226 Transfer Complete.",
    ENTERING_PASV_MODE: "227 Entering Passive Mode (%s).",
    # RFC 2428 section 3
    ENTERING_EPSV_MODE: "229 Entering Extended Passive Mode (|||%s|).",
    USR_LOGGED_IN_PROCEED: "230 User logged in, proceed",
    GUEST_LOGGED_IN_PROCEED: "230 Anonymous login ok, access " "restrictions apply.",
    # i.e. CWD completed OK
    REQ_FILE_ACTN_COMPLETED_OK: "250 Requested File Action Completed " "OK",
    PWD_REPLY: '257 "%s"',
    MKD_REPLY: '257 "%s" created',
    # -- 300's --
    USR_NAME_OK_NEED_PASS: "331 Password required for %s.",
    GUEST_NAME_OK_NEED_EMAIL: "331 Guest login ok, type your email "
    "address as password.",
    NEED_ACCT_FOR_LOGIN: "332 Need account for login.",
    REQ_FILE_ACTN_PENDING_FURTHER_INFO: "350 Requested file action pending "
    "further information.",
    # -- 400's --
    SVC_NOT_AVAIL_CLOSING_CTRL_CNX: "421 Service not available, closing "
    "control connection.",
    TOO_MANY_CONNECTIONS: "421 Too many users right now, try "
    "again in a few minutes.",
    CANT_OPEN_DATA_CNX: "425 Can't open data connection.",
    CNX_CLOSED_TXFR_ABORTED: "426 Transfer aborted.  Data " "connection closed.",
    REQ_ACTN_ABRTD_FILE_UNAVAIL: "450 Requested action aborted. " "File unavailable.",
    REQ_ACTN_ABRTD_LOCAL_ERR: "451 Requested action aborted. "
    "Local error in processing.",
    REQ_ACTN_ABRTD_INSUFF_STORAGE: "452 Requested action aborted. "
    "Insufficient storage.",
    # -- 500's --
    SYNTAX_ERR: "500 Syntax error: %s",
    SYNTAX_ERR_IN_ARGS: "501 syntax error in argument(s) %s.",
    CMD_NOT_IMPLMNTD: "502 Command '%s' not implemented",
    OPTS_NOT_IMPLEMENTED: "502 Option '%s' not implemented.",
    PASV_IPV6_NOT_IMPLEMENTED: "502 PASV available only for IPv4 (use EPSV instead)",
    BAD_CMD_SEQ: "503 Incorrect sequence of commands: " "%s",
    CMD_NOT_IMPLMNTD_FOR_PARAM: "504 Not implemented for parameter " "'%s'.",
    # RFC 2428 section 2
    UNSUPPORTED_NETWORK_PROTOCOL: "522 Network protocol not supported, use (%s)",
    NOT_LOGGED_IN: "530 Please login with USER and PASS.",
    AUTH_FAILURE: "530 Sorry, Authentication failed.",
    NEED_ACCT_FOR_STOR: "532 Need an account for storing " "files",
    FILE_NOT_FOUND: "550 %s: No such file or directory.",
    PERMISSION_DENIED: "550 %s: Permission denied.",
    ANON_USER_DENIED: "550 Anonymous users are forbidden to " "change the filesystem",
    IS_NOT_A_DIR: "550 Cannot rmd, %s is not a " "directory",
    FILE_EXISTS: "550 %s: File exists",
    IS_A_DIR: "550 %s: is a directory",
    REQ_ACTN_NOT_TAKEN: "550 Requested action not taken: %s",
    PAGE_TYPE_UNK: "551 Page type unknown",
    EXCEEDED_STORAGE_ALLOC: "552 Requested file action aborted, "
    "exceeded file storage allocation",
    FILENAME_NOT_ALLOWED: "553 Requested action not taken, file " "name not allowed",
}


# IANA address family numbers
# (https://www.iana.org/assignments/address-family-numbers).
# We only handle IP and IP6 at the moment.
#
# If these are needed by other parts of Twisted then they should be moved
# somewhere more central, filled out, and exported.
_AFNUM_IP = 1
_AFNUM_IP6 = 2


class InvalidPath(Exception):
    """
    Internal exception used to signify an error during parsing a path.
    """


def toSegments(cwd, path):
    """
    Normalize a path, as represented by a list of strings each
    representing one segment of the path.
    """
    if path.startswith("/"):
        segs = []
    else:
        segs = cwd[:]

    for s in path.split("/"):
        if s == "." or s == "":
            continue
        elif s == "..":
            if segs:
                segs.pop()
            else:
                raise InvalidPath(cwd, path)
        elif "\0" in s or "/" in s:
            raise InvalidPath(cwd, path)
        else:
            segs.append(s)
    return segs


def errnoToFailure(e, path):
    """
    Map C{OSError} and C{IOError} to standard FTP errors.
    """
    if e == errno.ENOENT:
        return defer.fail(FileNotFoundError(path))
    elif e == errno.EACCES or e == errno.EPERM:
        return defer.fail(PermissionDeniedError(path))
    elif e == errno.ENOTDIR:
        return defer.fail(IsNotADirectoryError(path))
    elif e == errno.EEXIST:
        return defer.fail(FileExistsError(path))
    elif e == errno.EISDIR:
        return defer.fail(IsADirectoryError(path))
    else:
        return defer.fail()


_testTranslation = fnmatch.translate("TEST")


def _isGlobbingExpression(segments=None):
    """
    Helper for checking if a FTPShell `segments` contains a wildcard Unix
    expression.

    Only filename globbing is supported.
    This means that wildcards can only be presents in the last element of
    `segments`.

    @type  segments: C{list}
    @param segments: List of path elements as used by the FTP server protocol.

    @rtype: Boolean
    @return: True if `segments` contains a globbing expression.
    """
    if not segments:
        return False

    # To check that something is a glob expression, we convert it to
    # Regular Expression.
    # We compare it to the translation of a known non-glob expression.
    # If the result is the same as the original expression then it contains no
    # globbing expression.
    globCandidate = segments[-1]
    globTranslations = fnmatch.translate(globCandidate)
    nonGlobTranslations = _testTranslation.replace("TEST", globCandidate, 1)

    if nonGlobTranslations == globTranslations:
        return False
    else:
        return True


class FTPCmdError(Exception):
    """
    Generic exception for FTP commands.
    """

    def __init__(self, *msg):
        Exception.__init__(self, *msg)
        self.errorMessage = msg

    def response(self):
        """
        Generate a FTP response message for this error.
        """
        return RESPONSE[self.errorCode] % self.errorMessage


class FileNotFoundError(FTPCmdError):
    """
    Raised when trying to access a non existent file or directory.
    """

    errorCode = FILE_NOT_FOUND


class AnonUserDeniedError(FTPCmdError):
    """
    Raised when an anonymous user issues a command that will alter the
    filesystem
    """

    errorCode = ANON_USER_DENIED


class PermissionDeniedError(FTPCmdError):
    """
    Raised when access is attempted to a resource to which access is
    not allowed.
    """

    errorCode = PERMISSION_DENIED


class IsNotADirectoryError(FTPCmdError):
    """
    Raised when RMD is called on a path that isn't a directory.
    """

    errorCode = IS_NOT_A_DIR


class FileExistsError(FTPCmdError):
    """
    Raised when attempted to override an existing resource.
    """

    errorCode = FILE_EXISTS


class IsADirectoryError(FTPCmdError):
    """
    Raised when DELE is called on a path that is a directory.
    """

    errorCode = IS_A_DIR


class CmdSyntaxError(FTPCmdError):
    """
    Raised when a command syntax is wrong.
    """

    errorCode = SYNTAX_ERR


class CmdArgSyntaxError(FTPCmdError):
    """
    Raised when a command is called with wrong value or a wrong number of
    arguments.
    """

    errorCode = SYNTAX_ERR_IN_ARGS


class CmdNotImplementedError(FTPCmdError):
    """
    Raised when an unimplemented command is given to the server.
    """

    errorCode = CMD_NOT_IMPLMNTD


class CmdNotImplementedForArgError(FTPCmdError):
    """
    Raised when the handling of a parameter for a command is not implemented by
    the server.
    """

    errorCode = CMD_NOT_IMPLMNTD_FOR_PARAM


class PASVIPv6NotImplementedError(FTPCmdError):
    """
    Raised when PASV is used with IPv6.
    """

    errorCode = PASV_IPV6_NOT_IMPLEMENTED


class FTPError(Exception):
    pass


class PortConnectionError(Exception):
    pass


class BadCmdSequenceError(FTPCmdError):
    """
    Raised when a client sends a series of commands in an illogical sequence.
    """

    errorCode = BAD_CMD_SEQ


class AuthorizationError(FTPCmdError):
    """
    Raised when client authentication fails.
    """

    errorCode = AUTH_FAILURE


class UnsupportedNetworkProtocolError(FTPCmdError):
    """
    Raised when the client requests an unsupported network protocol.
    """

    errorCode = UNSUPPORTED_NETWORK_PROTOCOL


def debugDeferred(self, *_):
    log.msg("debugDeferred(): %s" % str(_), debug=True)


# -- DTP Protocol --


_months = [
    None,
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
]


@implementer(interfaces.IConsumer)
class DTP(protocol.Protocol):
    isConnected = False

    _cons = None
    _onConnLost = None
    _buffer = None
    _encoding = "latin-1"

    def connectionMade(self):
        self.isConnected = True
        self.factory.deferred.callback(None)
        self._buffer = []

    def connectionLost(self, reason):
        self.isConnected = False
        if self._onConnLost is not None:
            self._onConnLost.callback(None)

    def sendLine(self, line):
        """
        Send a line to data channel.

        @param line: The line to be sent.
        @type line: L{bytes}
        """
        self.transport.write(line + b"\r\n")

    def _formatOneListResponse(
        self, name, size, directory, permissions, hardlinks, modified, owner, group
    ):
        """
        Helper method to format one entry's info into a text entry like:
        'drwxrwxrwx   0 user   group   0 Jan 01  1970 filename.txt'

        @param name: C{bytes} name of the entry (file or directory or link)
        @param size: C{int} size of the entry
        @param directory: evals to C{bool} - whether the entry is a directory
        @param permissions: L{twisted.python.filepath.Permissions} object
            representing that entry's permissions
        @param hardlinks: C{int} number of hardlinks
        @param modified: C{float} - entry's last modified time in seconds
            since the epoch
        @param owner: C{str} username of the owner
        @param group: C{str} group name of the owner

        @return: C{str} in the requisite format
        """

        def formatDate(mtime):
            now = time.gmtime()
            info = {
                "month": _months[mtime.tm_mon],
                "day": mtime.tm_mday,
                "year": mtime.tm_year,
                "hour": mtime.tm_hour,
                "minute": mtime.tm_min,
            }
            if now.tm_year != mtime.tm_year:
                return "%(month)s %(day)02d %(year)5d" % info
            else:
                return "%(month)s %(day)02d %(hour)02d:%(minute)02d" % info

        format = (
            "%(directory)s%(permissions)s%(hardlinks)4d "
            "%(owner)-9s %(group)-9s %(size)15d %(date)12s "
        )

        msg = (
            format
            % {
                "directory": directory and "d" or "-",
                "permissions": permissions.shorthand(),
                "hardlinks": hardlinks,
                "owner": owner[:8],
                "group": group[:8],
                "size": size,
                "date": formatDate(time.gmtime(modified)),
            }
        ).encode(self._encoding)
        return msg + name

    def sendListResponse(self, name, response):
        self.sendLine(self._formatOneListResponse(name, *response))

    # Proxy IConsumer to our transport
    def registerProducer(self, producer, streaming):
        return self.transport.registerProducer(producer, streaming)

    def unregisterProducer(self):
        self.transport.unregisterProducer()
        self.transport.loseConnection()

    def write(self, data):
        if self.isConnected:
            return self.transport.write(data)
        raise Exception("Crap damn crap damn crap damn")

    # Pretend to be a producer, too.
    def _conswrite(self, bytes):
        try:
            self._cons.write(bytes)
        except BaseException:
            self._onConnLost.errback()

    def dataReceived(self, bytes):
        if self._cons is not None:
            self._conswrite(bytes)
        else:
            self._buffer.append(bytes)

    def _unregConsumer(self, ignored):
        self._cons.unregisterProducer()
        self._cons = None
        del self._onConnLost
        return ignored

    def registerConsumer(self, cons):
        assert self._cons is None
        self._cons = cons
        self._cons.registerProducer(self, True)
        for chunk in self._buffer:
            self._conswrite(chunk)
        self._buffer = None
        if self.isConnected:
            self._onConnLost = d = defer.Deferred()
            d.addBoth(self._unregConsumer)
            return d
        else:
            self._cons.unregisterProducer()
            self._cons = None
            return defer.succeed(None)

    def resumeProducing(self):
        self.transport.resumeProducing()

    def pauseProducing(self):
        self.transport.pauseProducing()

    def stopProducing(self):
        self.transport.stopProducing()


class DTPFactory(protocol.ClientFactory):
    """
    Client factory for I{data transfer process} protocols.

    @ivar peerCheck: perform checks to make sure the ftp-pi's peer is the same
        as the dtp's
    @ivar pi: a reference to this factory's protocol interpreter

    @ivar _state: Indicates the current state of the DTPFactory.  Initially,
        this is L{_IN_PROGRESS}.  If the connection fails or times out, it is
        L{_FAILED}.  If the connection succeeds before the timeout, it is
        L{_FINISHED}.

    @cvar _IN_PROGRESS: Token to signal that connection is active.
    @type _IN_PROGRESS: L{object}.

    @cvar _FAILED: Token to signal that connection has failed.
    @type _FAILED: L{object}.

    @cvar _FINISHED: Token to signal that connection was successfully closed.
    @type _FINISHED: L{object}.
    """

    _IN_PROGRESS = object()
    _FAILED = object()
    _FINISHED = object()

    _state = _IN_PROGRESS

    # -- configuration variables --
    peerCheck = False

    # -- class variables --
    def __init__(self, pi, peerHost=None, reactor=None):
        """
        Constructor

        @param pi: this factory's protocol interpreter
        @param peerHost: if peerCheck is True, this is the tuple that the
            generated instance will use to perform security checks
        """
        self.pi = pi
        self.peerHost = peerHost  # from FTP.transport.peerHost()
        # deferred will fire when instance is connected
        self.deferred = defer.Deferred()
        self.delayedCall = None
        if reactor is None:
            from twisted.internet import reactor
        self._reactor = reactor

    def buildProtocol(self, addr):
        log.msg("DTPFactory.buildProtocol", debug=True)

        if self._state is not self._IN_PROGRESS:
            return None
        self._state = self._FINISHED

        self.cancelTimeout()
        p = DTP()
        p.factory = self
        p.pi = self.pi
        self.pi.dtpInstance = p
        return p

    def stopFactory(self):
        log.msg("dtpFactory.stopFactory", debug=True)
        self.cancelTimeout()

    def timeoutFactory(self):
        log.msg("timed out waiting for DTP connection")
        if self._state is not self._IN_PROGRESS:
            return
        self._state = self._FAILED

        d = self.deferred
        self.deferred = None
        d.errback(PortConnectionError(defer.TimeoutError("DTPFactory timeout")))

    def cancelTimeout(self):
        if self.delayedCall is not None and self.delayedCall.active():
            log.msg("cancelling DTP timeout", debug=True)
            self.delayedCall.cancel()

    def setTimeout(self, seconds):
        log.msg("DTPFactory.setTimeout set to %s seconds" % seconds)
        self.delayedCall = self._reactor.callLater(seconds, self.timeoutFactory)

    def clientConnectionFailed(self, connector, reason):
        if self._state is not self._IN_PROGRESS:
            return
        self._state = self._FAILED
        d = self.deferred
        self.deferred = None
        d.errback(PortConnectionError(reason))


# -- FTP-PI (Protocol Interpreter) --


class ASCIIConsumerWrapper:
    def __init__(self, cons):
        self.cons = cons
        self.registerProducer = cons.registerProducer
        self.unregisterProducer = cons.unregisterProducer

        assert (
            os.linesep == "\r\n" or len(os.linesep) == 1
        ), "Unsupported platform (yea right like this even exists)"

        if os.linesep == "\r\n":
            self.write = cons.write

    def write(self, bytes):
        return self.cons.write(bytes.replace(os.linesep, "\r\n"))


@implementer(interfaces.IConsumer)
class FileConsumer:
    """
    A consumer for FTP input that writes data to a file.

    @ivar fObj: a file object opened for writing, used to write data received.
    @type fObj: C{file}
    """

    def __init__(self, fObj):
        self.fObj = fObj

    def registerProducer(self, producer, streaming):
        self.producer = producer
        assert streaming

    def unregisterProducer(self):
        self.producer = None
        self.fObj.close()

    def write(self, bytes):
        self.fObj.write(bytes)


class FTPOverflowProtocol(basic.LineReceiver):
    """FTP mini-protocol for when there are too many connections."""

    _encoding = "latin-1"

    def connectionMade(self):
        self.sendLine(RESPONSE[TOO_MANY_CONNECTIONS].encode(self._encoding))
        self.transport.loseConnection()


class FTP(basic.LineReceiver, policies.TimeoutMixin):
    """
    Protocol Interpreter for the File Transfer Protocol

    @ivar state: The current server state.  One of L{UNAUTH},
        L{INAUTH}, L{AUTHED}, L{RENAMING}.

    @ivar shell: The connected avatar
    @ivar binary: The transfer mode.  If false, ASCII.
    @ivar dtpFactory: Generates a single DTP for this session
    @ivar dtpPort: Port returned from listenTCP
    @ivar listenFactory: A callable with the signature of
        L{twisted.internet.interfaces.IReactorTCP.listenTCP} which will be used
        to create Ports for passive connections (mainly for testing).
    @ivar _epsvAll: If true, "EPSV ALL" was received from the client,
        requiring the server to reject all data connection setup commands
        other than EPSV.  See RFC 2428.
    @ivar _supportedNetworkProtocols: A collection of network protocol
        numbers supported by the EPRT and EPSV commands.

    @ivar passivePortRange: iterator used as source of passive port numbers.
    @type passivePortRange: C{iterator}

    @cvar UNAUTH: Command channel is not yet authenticated.
    @type UNAUTH: L{int}

    @cvar INAUTH: Command channel is in the process of being authenticated.
    @type INAUTH: L{int}

    @cvar AUTHED: Command channel was successfully authenticated.
    @type AUTHED: L{int}

    @cvar RENAMING: Command channel is between the renaming command sequence.
    @type RENAMING: L{int}
    """

    disconnected = False

    # States an FTP can be in
    UNAUTH, INAUTH, AUTHED, RENAMING = range(4)

    # how long the DTP waits for a connection
    dtpTimeout = 10

    portal = None
    shell = None
    dtpFactory = None
    dtpPort = None
    dtpInstance = None
    binary = True
    _epsvAll = False
    _supportedNetworkProtocols = (_AFNUM_IP, _AFNUM_IP6)
    PUBLIC_COMMANDS = ["FEAT", "QUIT"]
    FEATURES = ["FEAT", "MDTM", "PASV", "SIZE", "TYPE A;I"]

    passivePortRange = range(0, 1)

    listenFactory = reactor.listenTCP  # type: ignore[attr-defined]
    _encoding = "latin-1"

    def reply(self, key, *args):
        msg = RESPONSE[key] % args
        self.sendLine(msg)

    def sendLine(self, line):
        """
        (Private) Encodes and sends a line

        @param line: L{bytes} or L{unicode}
        """
        if isinstance(line, str):
            line = line.encode(self._encoding)
        super().sendLine(line)

    def connectionMade(self):
        self.state = self.UNAUTH
        self.setTimeout(self.timeOut)
        self.reply(WELCOME_MSG, self.factory.welcomeMessage)

    def connectionLost(self, reason):
        # if we have a DTP protocol instance running and
        # we lose connection to the client's PI, kill the
        # DTP connection and close the port
        if self.dtpFactory:
            self.cleanupDTP()
        self.setTimeout(None)
        if hasattr(self.shell, "logout") and self.shell.logout is not None:
            self.shell.logout()
        self.shell = None
        self._epsvAll = False
        self.transport = None

    def timeoutConnection(self):
        self.transport.loseConnection()

    def lineReceived(self, line):
        self.resetTimeout()
        self.pauseProducing()
        line = line.decode(self._encoding)

        def processFailed(err):
            if err.check(FTPCmdError):
                self.sendLine(err.value.response())
            elif err.check(TypeError) and any(
                msg in err.value.args[0]
                for msg in ("takes exactly", "required positional argument")
            ):
                self.reply(SYNTAX_ERR, f"{cmd} requires an argument.")
            else:
                log.msg("Unexpected FTP error")
                log.err(err)
                self.reply(REQ_ACTN_NOT_TAKEN, "internal server error")

        def processSucceeded(result):
            if isinstance(result, tuple):
                self.reply(*result)
            elif result is not None:
                self.reply(result)

        def allDone(ignored):
            if not self.disconnected:
                self.resumeProducing()

        spaceIndex = line.find(" ")
        if spaceIndex != -1:
            cmd = line[:spaceIndex]
            args = (line[spaceIndex + 1 :],)
        else:
            cmd = line
            args = ()
        d = defer.maybeDeferred(self.processCommand, cmd, *args)
        d.addCallbacks(processSucceeded, processFailed)
        d.addErrback(log.err)

        # XXX It burnsss
        # LineReceiver doesn't let you resumeProducing inside
        # lineReceived atm
        from twisted.internet import reactor

        reactor.callLater(0, d.addBoth, allDone)

    def processCommand(self, cmd, *params):
        def call_ftp_command(command):
            method = getattr(self, "ftp_" + command, None)
            if method is not None:
                return method(*params)
            return defer.fail(CmdNotImplementedError(command))

        cmd = cmd.upper()

        if cmd in self.PUBLIC_COMMANDS:
            return call_ftp_command(cmd)

        elif self.state == self.UNAUTH:
            if cmd == "USER":
                return self.ftp_USER(*params)
            elif cmd == "PASS":
                return BAD_CMD_SEQ, "USER required before PASS"
            else:
                return NOT_LOGGED_IN

        elif self.state == self.INAUTH:
            if cmd == "PASS":
                return self.ftp_PASS(*params)
            else:
                return BAD_CMD_SEQ, "PASS required after USER"

        elif self.state == self.AUTHED:
            return call_ftp_command(cmd)

        elif self.state == self.RENAMING:
            if cmd == "RNTO":
                return self.ftp_RNTO(*params)
            else:
                return BAD_CMD_SEQ, "RNTO required after RNFR"

    def getDTPPort(self, factory, interface=""):
        """
        Return a port for passive access, using C{self.passivePortRange}
        attribute.

        @param factory: the protocol factory to connect to the port.
        @type factory: L{twisted.internet.protocol.ServerFactory}

        @param interface: the local IPv4 or IPv6 address to which to bind;
            defaults to "", i.e. all IPv4 addresses.
        @type interface: C{str}
        """
        for portn in self.passivePortRange:
            try:
                dtpPort = self.listenFactory(portn, factory, interface=interface)
            except error.CannotListenError:
                continue
            else:
                return dtpPort
        raise error.CannotListenError(
            "", portn, f"No port available in range {self.passivePortRange}"
        )

    def ftp_USER(self, username):
        """
        First part of login.  Get the username the peer wants to
        authenticate as.
        """
        if not username:
            return defer.fail(CmdSyntaxError("USER requires an argument"))

        self._user = username
        self.state = self.INAUTH
        if self.factory.allowAnonymous and self._user == self.factory.userAnonymous:
            return GUEST_NAME_OK_NEED_EMAIL
        else:
            return (USR_NAME_OK_NEED_PASS, username)

    # TODO: add max auth try before timeout from ip...
    # TODO: need to implement minimal ABOR command

    def ftp_PASS(self, password):
        """
        Second part of login.  Get the password the peer wants to
        authenticate with.
        """
        if self.factory.allowAnonymous and self._user == self.factory.userAnonymous:
            # anonymous login
            creds = credentials.Anonymous()
            reply = GUEST_LOGGED_IN_PROCEED
        else:
            # user login
            creds = credentials.UsernamePassword(self._user, password)
            reply = USR_LOGGED_IN_PROCEED
        del self._user

        def _cbLogin(result):
            (interface, avatar, logout) = result
            assert interface is IFTPShell, "The realm is busted, jerk."
            self.shell = avatar
            self.logout = logout
            self.workingDirectory = []
            self.state = self.AUTHED
            return reply

        def _ebLogin(failure):
            failure.trap(cred_error.UnauthorizedLogin, cred_error.UnhandledCredentials)
            self.state = self.UNAUTH
            raise AuthorizationError

        d = self.portal.login(creds, None, IFTPShell)
        d.addCallbacks(_cbLogin, _ebLogin)
        return d

    def ftp_PASV(self):
        """
        Request for a passive connection

        from the rfc::

            This command requests the server-DTP to \"listen\" on a data port
            (which is not its default data port) and to wait for a connection
            rather than initiate one upon receipt of a transfer command.  The
            response to this command includes the host and port address this
            server is listening on.
        """
        if self._epsvAll:
            return defer.fail(BadCmdSequenceError("may not send PASV after EPSV ALL"))

        host = self.transport.getHost().host
        try:
            address = ipaddress.IPv6Address(host)
        except ipaddress.AddressValueError:
            pass
        else:
            if address.ipv4_mapped is not None:
                # IPv4-mapped addresses are usable, but we need to make sure
                # they're encoded as IPv4 in the response.
                host = str(address.ipv4_mapped)
            else:
                # There's no standard defining the behaviour of PASV with
                # IPv6, so just claim it as unimplemented.  (Some servers
                # return something like '0,0,0,0' in the host part of the
                # response in order that at least clients that ignore the
                # host part can work, and if it becomes necessary then we
                # could do that too.)
                return defer.fail(PASVIPv6NotImplementedError())

        # if we have a DTP port set up, lose it.
        if self.dtpFactory is not None:
            # cleanupDTP sets dtpFactory to none.  Later we'll do
            # cleanup here or something.
            self.cleanupDTP()
        self.dtpFactory = DTPFactory(pi=self)
        self.dtpFactory.setTimeout(self.dtpTimeout)
        self.dtpPort = self.getDTPPort(self.dtpFactory)

        port = self.dtpPort.getHost().port
        self.reply(ENTERING_PASV_MODE, encodeHostPort(host, port))
        return self.dtpFactory.deferred.addCallback(lambda ign: None)

    def _validateNetworkProtocol(self, protocol):
        """
        Validate the network protocol requested in an EPRT or EPSV command.

        For now we just hardcode the protocols we support, since this layer
        doesn't have a good way to discover that.

        @param protocol: An address family number.  See RFC 2428 section 2.
        @type protocol: L{str}

        @raise FTPCmdError: If validation fails.
        """
        # We can't actually honour an explicit network protocol request
        # (violating a SHOULD in RFC 2428 section 3), but let's at least
        # validate it.
        try:
            protocol = int(protocol)
        except ValueError:
            raise CmdArgSyntaxError(protocol)
        if protocol not in self._supportedNetworkProtocols:
            raise UnsupportedNetworkProtocolError(
                ",".join(str(p) for p in self._supportedNetworkProtocols)
            )

    def ftp_EPSV(self, protocol=""):
        """
        Extended request for a passive connection.

        As described by U{RFC 2428 section
        3<https://tools.ietf.org/html/rfc2428#section-3>}::

            The EPSV command requests that a server listen on a data port
            and wait for a connection.  The EPSV command takes an optional
            argument.  The response to this command includes only the TCP
            port number of the listening connection.  The format of the
            response, however, is similar to the argument of the EPRT
            command.  This allows the same parsing routines to be used for
            both commands.  In addition, the format leaves a place holder
            for the network protocol and/or network address, which may be
            needed in the EPSV response in the future.
        """
        if protocol == "ALL":
            self._epsvAll = True
            return EPSV_ALL_OK
        elif protocol:
            try:
                self._validateNetworkProtocol(protocol)
            except FTPCmdError:
                return defer.fail()

        # if we have a DTP port set up, lose it.
        if self.dtpFactory is not None:
            # cleanupDTP sets dtpFactory to none.  Later we'll do
            # cleanup here or something.
            self.cleanupDTP()
        self.dtpFactory = DTPFactory(pi=self)
        self.dtpFactory.setTimeout(self.dtpTimeout)
        if not protocol or protocol == _AFNUM_IP6:
            interface = "::"
        else:
            interface = ""
        self.dtpPort = self.getDTPPort(self.dtpFactory, interface=interface)

        port = self.dtpPort.getHost().port
        self.reply(ENTERING_EPSV_MODE, port)
        return self.dtpFactory.deferred.addCallback(lambda ign: None)

    def ftp_PORT(self, address):
        if self._epsvAll:
            return defer.fail(BadCmdSequenceError("may not send PORT after EPSV ALL"))

        addr = tuple(map(int, address.split(",")))
        ip = "%d.%d.%d.%d" % tuple(addr[:4])
        port = addr[4] << 8 | addr[5]

        # if we have a DTP port set up, lose it.
        if self.dtpFactory is not None:
            self.cleanupDTP()

        self.dtpFactory = DTPFactory(pi=self, peerHost=self.transport.getPeer().host)
        self.dtpFactory.setTimeout(self.dtpTimeout)
        self.dtpPort = reactor.connectTCP(ip, port, self.dtpFactory)

        def connected(ignored):
            return ENTERING_PORT_MODE

        def connFailed(err):
            err.trap(PortConnectionError)
            return CANT_OPEN_DATA_CNX

        return self.dtpFactory.deferred.addCallbacks(connected, connFailed)

    def ftp_EPRT(self, extendedAddress):
        """
        Extended request for a data connection.

        As described by U{RFC 2428 section
        2<https://tools.ietf.org/html/rfc2428#section-2>}::

            The EPRT command allows for the specification of an extended
            address for the data connection.  The extended address MUST
            consist of the network protocol as well as the network and
            transport addresses.
        """
        if self._epsvAll:
            return defer.fail(BadCmdSequenceError("may not send EPRT after EPSV ALL"))

        try:
            protocol, ip, port = decodeExtendedAddress(extendedAddress)
        except ValueError:
            return defer.fail(CmdArgSyntaxError(extendedAddress))
        if protocol:
            try:
                self._validateNetworkProtocol(protocol)
            except FTPCmdError:
                return defer.fail()

        # if we have a DTP port set up, lose it.
        if self.dtpFactory is not None:
            self.cleanupDTP()

        self.dtpFactory = DTPFactory(pi=self, peerHost=self.transport.getPeer().host)
        self.dtpFactory.setTimeout(self.dtpTimeout)
        self.dtpPort = reactor.connectTCP(ip, port, self.dtpFactory)

        def connected(ignored):
            return ENTERING_PORT_MODE

        def connFailed(err):
            err.trap(PortConnectionError)
            return CANT_OPEN_DATA_CNX

        return self.dtpFactory.deferred.addCallbacks(connected, connFailed)

    def _encodeName(self, name):
        """
        Encode C{name} to be sent over the wire.

        This encodes L{unicode} objects as UTF-8 and leaves L{bytes} as-is.

        As described by U{RFC 3659 section
        2.2<https://tools.ietf.org/html/rfc3659#section-2.2>}::

            Various FTP commands take pathnames as arguments, or return
            pathnames in responses. When the MLST command is supported, as
            indicated in the response to the FEAT command, pathnames are to be
            transferred in one of the following two formats.

                pathname = utf-8-name / raw
                utf-8-name = <a UTF-8 encoded Unicode string>
                raw = <any string that is not a valid UTF-8 encoding>

            Which format is used is at the option of the user-PI or server-PI
            sending the pathname.

        @param name: Name to be encoded.
        @type name: L{bytes} or L{unicode}

        @return: Wire format of C{name}.
        @rtype: L{bytes}
        """
        if isinstance(name, str):
            return name.encode("utf-8")
        return name

    def ftp_LIST(self, path=""):
        """This command causes a list to be sent from the server to the
        passive DTP.  If the pathname specifies a directory or other
        group of files, the server should transfer a list of files
        in the specified directory.  If the pathname specifies a
        file then the server should send current information on the
        file.  A null argument implies the user's current working or
        default directory.
        """
        # XXX: why is this check different from ftp_RETR/ftp_STOR? See #4180
        if self.dtpInstance is None or not self.dtpInstance.isConnected:
            return defer.fail(BadCmdSequenceError("must send PORT or PASV before RETR"))

        # Various clients send flags like -L or -al etc.  We just ignore them.
        if path.lower() in ["-a", "-l", "-la", "-al"]:
            path = ""

        def gotListing(results):
            self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)
            for name, attrs in results:
                name = self._encodeName(name)
                self.dtpInstance.sendListResponse(name, attrs)
            self.dtpInstance.transport.loseConnection()
            return (TXFR_COMPLETE_OK,)

        try:
            segments = toSegments(self.workingDirectory, path)
        except InvalidPath:
            return defer.fail(FileNotFoundError(path))

        d = self.shell.list(
            segments,
            (
                "size",
                "directory",
                "permissions",
                "hardlinks",
                "modified",
                "owner",
                "group",
            ),
        )
        d.addCallback(gotListing)
        return d

    def ftp_NLST(self, path):
        """
        This command causes a directory listing to be sent from the server to
        the client. The pathname should specify a directory or other
        system-specific file group descriptor. An empty path implies the
        current working directory. If the path is non-existent, send nothing.
        If the path is to a file, send only the file name.

        @type path: C{str}
        @param path: The path for which a directory listing should be returned.

        @rtype: L{Deferred}
        @return: a L{Deferred} which will be fired when the listing request
            is finished.
        """
        # XXX: why is this check different from ftp_RETR/ftp_STOR? See #4180
        if self.dtpInstance is None or not self.dtpInstance.isConnected:
            return defer.fail(BadCmdSequenceError("must send PORT or PASV before RETR"))

        try:
            segments = toSegments(self.workingDirectory, path)
        except InvalidPath:
            return defer.fail(FileNotFoundError(path))

        def cbList(results, glob):
            """
            Send, line by line, each matching file in the directory listing,
            and then close the connection.

            @type results: A C{list} of C{tuple}. The first element of each
                C{tuple} is a C{str} and the second element is a C{list}.
            @param results: The names of the files in the directory.

            @param glob: A shell-style glob through which to filter results
                (see U{http://docs.python.org/2/library/fnmatch.html}), or
                L{None} for no filtering.
            @type glob: L{str} or L{None}

            @return: A C{tuple} containing the status code for a successful
                transfer.
            @rtype: C{tuple}
            """
            self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)
            for name, ignored in results:
                if not glob or (glob and fnmatch.fnmatch(name, glob)):
                    name = self._encodeName(name)
                    self.dtpInstance.sendLine(name)
            self.dtpInstance.transport.loseConnection()
            return (TXFR_COMPLETE_OK,)

        def listErr(results):
            """
            RFC 959 specifies that an NLST request may only return directory
            listings. Thus, send nothing and just close the connection.

            @type results: L{Failure}
            @param results: The L{Failure} wrapping a L{FileNotFoundError} that
                occurred while trying to list the contents of a nonexistent
                directory.

            @returns: A C{tuple} containing the status code for a successful
                transfer.
            @rtype: C{tuple}
            """
            self.dtpInstance.transport.loseConnection()
            return (TXFR_COMPLETE_OK,)

        if _isGlobbingExpression(segments):
            # Remove globbing expression from path
            # and keep to be used for filtering.
            glob = segments.pop()
        else:
            glob = None

        d = self.shell.list(segments)
        d.addCallback(cbList, glob)
        # self.shell.list will generate an error if the path is invalid
        d.addErrback(listErr)
        return d

    def ftp_CWD(self, path):
        try:
            segments = toSegments(self.workingDirectory, path)
        except InvalidPath:
            # XXX Eh, what to fail with here?
            return defer.fail(FileNotFoundError(path))

        def accessGranted(result):
            self.workingDirectory = segments
            return (REQ_FILE_ACTN_COMPLETED_OK,)

        return self.shell.access(segments).addCallback(accessGranted)

    def ftp_CDUP(self):
        return self.ftp_CWD("..")

    def ftp_PWD(self):
        return (PWD_REPLY, "/" + "/".join(self.workingDirectory))

    def ftp_RETR(self, path):
        """
        This command causes the content of a file to be sent over the data
        transfer channel. If the path is to a folder, an error will be raised.

        @type path: C{str}
        @param path: The path to the file which should be transferred over the
        data transfer channel.

        @rtype: L{Deferred}
        @return: a L{Deferred} which will be fired when the transfer is done.
        """
        if self.dtpInstance is None:
            raise BadCmdSequenceError("PORT, PASV, EPRT, or EPSV required before RETR")

        try:
            newsegs = toSegments(self.workingDirectory, path)
        except InvalidPath:
            return defer.fail(FileNotFoundError(path))

        # XXX For now, just disable the timeout.  Later we'll want to
        # leave it active and have the DTP connection reset it
        # periodically.
        self.setTimeout(None)

        # Put it back later
        def enableTimeout(result):
            self.setTimeout(self.factory.timeOut)
            return result

        # And away she goes
        if not self.binary:
            cons = ASCIIConsumerWrapper(self.dtpInstance)
        else:
            cons = self.dtpInstance

        def cbSent(result):
            return (TXFR_COMPLETE_OK,)

        def ebSent(err):
            log.msg("Unexpected error attempting to transmit file to client:")
            log.err(err)
            if err.check(FTPCmdError):
                return err
            return (CNX_CLOSED_TXFR_ABORTED,)

        def cbOpened(file):
            # Tell them what to doooo
            if self.dtpInstance.isConnected:
                self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)
            else:
                self.reply(FILE_STATUS_OK_OPEN_DATA_CNX)

            d = file.send(cons)
            d.addCallbacks(cbSent, ebSent)
            return d

        def ebOpened(err):
            if not err.check(
                PermissionDeniedError, FileNotFoundError, IsADirectoryError
            ):
                log.msg("Unexpected error attempting to open file for " "transmission:")
                log.err(err)
            if err.check(FTPCmdError):
                return (err.value.errorCode, "/".join(newsegs))
            return (FILE_NOT_FOUND, "/".join(newsegs))

        d = self.shell.openForReading(newsegs)
        d.addCallbacks(cbOpened, ebOpened)
        d.addBoth(enableTimeout)

        # Pass back Deferred that fires when the transfer is done
        return d

    def ftp_STOR(self, path):
        """
        STORE (STOR)

        This command causes the server-DTP to accept the data
        transferred via the data connection and to store the data as
        a file at the server site.  If the file specified in the
        pathname exists at the server site, then its contents shall
        be replaced by the data being transferred.  A new file is
        created at the server site if the file specified in the
        pathname does not already exist.
        """
        if self.dtpInstance is None:
            raise BadCmdSequenceError("PORT, PASV, EPRT, or EPSV required before STOR")

        try:
            newsegs = toSegments(self.workingDirectory, path)
        except InvalidPath:
            return defer.fail(FileNotFoundError(path))

        # XXX For now, just disable the timeout.  Later we'll want to
        # leave it active and have the DTP connection reset it
        # periodically.
        self.setTimeout(None)

        # Put it back later
        def enableTimeout(result):
            self.setTimeout(self.factory.timeOut)
            return result

        def cbOpened(file):
            """
            File was open for reading. Launch the data transfer channel via
            the file consumer.
            """
            d = file.receive()
            d.addCallback(cbConsumer)
            d.addCallback(lambda ignored: file.close())
            d.addCallbacks(cbSent, ebSent)
            return d

        def ebOpened(err):
            """
            Called when failed to open the file for reading.

            For known errors, return the FTP error code.
            For all other, return a file not found error.
            """
            if isinstance(err.value, FTPCmdError):
                return (err.value.errorCode, "/".join(newsegs))
            log.err(err, "Unexpected error received while opening file:")
            return (FILE_NOT_FOUND, "/".join(newsegs))

        def cbConsumer(cons):
            """
            Called after the file was opended for reading.

            Prepare the data transfer channel and send the response
            to the command channel.
            """
            if not self.binary:
                cons = ASCIIConsumerWrapper(cons)

            d = self.dtpInstance.registerConsumer(cons)

            # Tell them what to doooo
            if self.dtpInstance.isConnected:
                self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)
            else:
                self.reply(FILE_STATUS_OK_OPEN_DATA_CNX)

            return d

        def cbSent(result):
            """
            Called from data transport when transfer is done.
            """
            return (TXFR_COMPLETE_OK,)

        def ebSent(err):
            """
            Called from data transport when there are errors during the
            transfer.
            """
            log.err(err, "Unexpected error received during transfer:")
            if err.check(FTPCmdError):
                return err
            return (CNX_CLOSED_TXFR_ABORTED,)

        d = self.shell.openForWriting(newsegs)
        d.addCallbacks(cbOpened, ebOpened)
        d.addBoth(enableTimeout)

        # Pass back Deferred that fires when the transfer is done
        return d

    def ftp_SIZE(self, path):
        """
        File SIZE

        The FTP command, SIZE OF FILE (SIZE), is used to obtain the transfer
        size of a file from the server-FTP process.  This is the exact number
        of octets (8 bit bytes) that would be transmitted over the data
        connection should that file be transmitted.  This value will change
        depending on the current STRUcture, MODE, and TYPE of the data
        connection or of a data connection that would be created were one
        created now.  Thus, the result of the SIZE command is dependent on
        the currently established STRU, MODE, and TYPE parameters.

        The SIZE command returns how many octets would be transferred if the
        file were to be transferred using the current transfer structure,
        mode, and type.  This command is normally used in conjunction with
        the RESTART (REST) command when STORing a file to a remote server in
        STREAM mode, to determine the restart point.  The server-PI might
        need to read the partially transferred file, do any appropriate
        conversion, and count the number of octets that would be generated
        when sending the file in order to correctly respond to this command.
        Estimates of the file transfer size MUST NOT be returned; only
        precise information is acceptable.

        http://tools.ietf.org/html/rfc3659
        """
        try:
            newsegs = toSegments(self.workingDirectory, path)
        except InvalidPath:
            return defer.fail(FileNotFoundError(path))

        def cbStat(result):
            (size,) = result
            return (FILE_STATUS, str(size))

        return self.shell.stat(newsegs, ("size",)).addCallback(cbStat)

    def ftp_MDTM(self, path):
        """
        File Modification Time (MDTM)

        The FTP command, MODIFICATION TIME (MDTM), can be used to determine
        when a file in the server NVFS was last modified.  This command has
        existed in many FTP servers for many years, as an adjunct to the REST
        command for STREAM mode, thus is widely available.  However, where
        supported, the "modify" fact that can be provided in the result from
        the new MLST command is recommended as a superior alternative.

        http://tools.ietf.org/html/rfc3659
        """
        try:
            newsegs = toSegments(self.workingDirectory, path)
        except InvalidPath:
            return defer.fail(FileNotFoundError(path))

        def cbStat(result):
            (modified,) = result
            return (FILE_STATUS, time.strftime("%Y%m%d%H%M%S", time.gmtime(modified)))

        return self.shell.stat(newsegs, ("modified",)).addCallback(cbStat)

    def ftp_TYPE(self, type):
        """
        REPRESENTATION TYPE (TYPE)

        The argument specifies the representation type as described
        in the Section on Data Representation and Storage.  Several
        types take a second parameter.  The first parameter is
        denoted by a single Telnet character, as is the second
        Format parameter for ASCII and EBCDIC; the second parameter
        for local byte is a decimal integer to indicate Bytesize.
        The parameters are separated by a <SP> (Space, ASCII code
        32).
        """
        p = type.upper()
        if p:
            f = getattr(self, "type_" + p[0], None)
            if f is not None:
                return f(p[1:])
            return self.type_UNKNOWN(p)
        return (SYNTAX_ERR,)

    def type_A(self, code):
        if code == "" or code == "N":
            self.binary = False
            return (TYPE_SET_OK, "A" + code)
        else:
            return defer.fail(CmdArgSyntaxError(code))

    def type_I(self, code):
        if code == "":
            self.binary = True
            return (TYPE_SET_OK, "I")
        else:
            return defer.fail(CmdArgSyntaxError(code))

    def type_UNKNOWN(self, code):
        return defer.fail(CmdNotImplementedForArgError(code))

    def ftp_SYST(self):
        return NAME_SYS_TYPE

    def ftp_STRU(self, structure):
        p = structure.upper()
        if p == "F":
            return (CMD_OK,)
        return defer.fail(CmdNotImplementedForArgError(structure))

    def ftp_MODE(self, mode):
        p = mode.upper()
        if p == "S":
            return (CMD_OK,)
        return defer.fail(CmdNotImplementedForArgError(mode))

    def ftp_MKD(self, path):
        try:
            newsegs = toSegments(self.workingDirectory, path)
        except InvalidPath:
            return defer.fail(FileNotFoundError(path))
        return self.shell.makeDirectory(newsegs).addCallback(
            lambda ign: (MKD_REPLY, path)
        )

    def ftp_RMD(self, path):
        try:
            newsegs = toSegments(self.workingDirectory, path)
        except InvalidPath:
            return defer.fail(FileNotFoundError(path))
        return self.shell.removeDirectory(newsegs).addCallback(
            lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,)
        )

    def ftp_DELE(self, path):
        try:
            newsegs = toSegments(self.workingDirectory, path)
        except InvalidPath:
            return defer.fail(FileNotFoundError(path))
        return self.shell.removeFile(newsegs).addCallback(
            lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,)
        )

    def ftp_NOOP(self):
        return (CMD_OK,)

    def ftp_RNFR(self, fromName):
        self._fromName = fromName
        self.state = self.RENAMING
        return (REQ_FILE_ACTN_PENDING_FURTHER_INFO,)

    def ftp_RNTO(self, toName):
        fromName = self._fromName
        del self._fromName
        self.state = self.AUTHED

        try:
            fromsegs = toSegments(self.workingDirectory, fromName)
            tosegs = toSegments(self.workingDirectory, toName)
        except InvalidPath:
            return defer.fail(FileNotFoundError(fromName))
        return self.shell.rename(fromsegs, tosegs).addCallback(
            lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,)
        )

    def ftp_FEAT(self):
        """
        Advertise the features supported by the server.

        http://tools.ietf.org/html/rfc2389
        """
        self.sendLine(RESPONSE[FEAT_OK][0])
        for feature in self.FEATURES:
            self.sendLine(" " + feature)
        self.sendLine(RESPONSE[FEAT_OK][1])

    def ftp_OPTS(self, option):
        """
        Handle OPTS command.

        http://tools.ietf.org/html/draft-ietf-ftpext-utf-8-option-00
        """
        return self.reply(OPTS_NOT_IMPLEMENTED, option)

    def ftp_QUIT(self):
        self.reply(GOODBYE_MSG)
        self.transport.loseConnection()
        self.disconnected = True

    def cleanupDTP(self):
        """
        Call when DTP connection exits
        """
        log.msg("cleanupDTP", debug=True)

        log.msg(self.dtpPort)
        dtpPort, self.dtpPort = self.dtpPort, None
        if interfaces.IListeningPort.providedBy(dtpPort):
            dtpPort.stopListening()
        elif interfaces.IConnector.providedBy(dtpPort):
            dtpPort.disconnect()
        else:
            assert False, (
                "dtpPort should be an IListeningPort or IConnector, "
                "instead is %r" % (dtpPort,)
            )

        self.dtpFactory.stopFactory()
        self.dtpFactory = None

        if self.dtpInstance is not None:
            self.dtpInstance = None


class FTPFactory(policies.LimitTotalConnectionsFactory):
    """
    A factory for producing ftp protocol instances

    @ivar timeOut: the protocol interpreter's idle timeout time in seconds,
        default is 600 seconds.

    @ivar passivePortRange: value forwarded to C{protocol.passivePortRange}.
    @type passivePortRange: C{iterator}
    """

    protocol = FTP
    overflowProtocol = FTPOverflowProtocol
    allowAnonymous = True
    userAnonymous = "anonymous"
    timeOut = 600

    welcomeMessage = f"Twisted {copyright.version} FTP Server"

    passivePortRange = range(0, 1)

    def __init__(self, portal=None, userAnonymous="anonymous"):
        self.portal = portal
        self.userAnonymous = userAnonymous
        self.instances = []

    def buildProtocol(self, addr):
        p = policies.LimitTotalConnectionsFactory.buildProtocol(self, addr)
        if p is not None:
            p.wrappedProtocol.portal = self.portal
            p.wrappedProtocol.timeOut = self.timeOut
            p.wrappedProtocol.passivePortRange = self.passivePortRange
        return p

    def stopFactory(self):
        # make sure ftp instance's timeouts are set to None
        # to avoid reactor complaints
        [p.setTimeout(None) for p in self.instances if p.timeOut is not None]
        policies.LimitTotalConnectionsFactory.stopFactory(self)


# -- Cred Objects --


class IFTPShell(Interface):
    """
    An abstraction of the shell commands used by the FTP protocol for
    a given user account.

    All path names must be absolute.
    """

    def makeDirectory(path):
        """
        Create a directory.

        @param path: The path, as a list of segments, to create
        @type path: C{list} of C{unicode}

        @return: A Deferred which fires when the directory has been
        created, or which fails if the directory cannot be created.
        """

    def removeDirectory(path):
        """
        Remove a directory.

        @param path: The path, as a list of segments, to remove
        @type path: C{list} of C{unicode}

        @return: A Deferred which fires when the directory has been
        removed, or which fails if the directory cannot be removed.
        """

    def removeFile(path):
        """
        Remove a file.

        @param path: The path, as a list of segments, to remove
        @type path: C{list} of C{unicode}

        @return: A Deferred which fires when the file has been
        removed, or which fails if the file cannot be removed.
        """

    def rename(fromPath, toPath):
        """
        Rename a file or directory.

        @param fromPath: The current name of the path.
        @type fromPath: C{list} of C{unicode}

        @param toPath: The desired new name of the path.
        @type toPath: C{list} of C{unicode}

        @return: A Deferred which fires when the path has been
        renamed, or which fails if the path cannot be renamed.
        """

    def access(path):
        """
        Determine whether access to the given path is allowed.

        @param path: The path, as a list of segments

        @return: A Deferred which fires with None if access is allowed
        or which fails with a specific exception type if access is
        denied.
        """

    def stat(path, keys=()):
        """
        Retrieve information about the given path.

        This is like list, except it will never return results about
        child paths.
        """

    def list(path, keys=()):
        """
        Retrieve information about the given path.

        If the path represents a non-directory, the result list should
        have only one entry with information about that non-directory.
        Otherwise, the result list should have an element for each
        child of the directory.

        @param path: The path, as a list of segments, to list
        @type path: C{list} of C{unicode} or C{bytes}

        @param keys: A tuple of keys desired in the resulting
        dictionaries.

        @return: A Deferred which fires with a list of (name, list),
        where the name is the name of the entry as a unicode string or
        bytes and each list contains values corresponding to the requested
        keys.  The following are possible elements of keys, and the
        values which should be returned for them:

            - C{'size'}: size in bytes, as an integer (this is kinda required)

            - C{'directory'}: boolean indicating the type of this entry

            - C{'permissions'}: a bitvector (see os.stat(foo).st_mode)

            - C{'hardlinks'}: Number of hard links to this entry

            - C{'modified'}: number of seconds since the epoch since entry was
              modified

            - C{'owner'}: string indicating the user owner of this entry

            - C{'group'}: string indicating the group owner of this entry
        """

    def openForReading(path):
        """
        @param path: The path, as a list of segments, to open
        @type path: C{list} of C{unicode}

        @rtype: C{Deferred} which will fire with L{IReadFile}
        """

    def openForWriting(path):
        """
        @param path: The path, as a list of segments, to open
        @type path: C{list} of C{unicode}

        @rtype: C{Deferred} which will fire with L{IWriteFile}
        """


class IReadFile(Interface):
    """
    A file out of which bytes may be read.
    """

    def send(consumer):
        """
        Produce the contents of the given path to the given consumer.  This
        method may only be invoked once on each provider.

        @type consumer: C{IConsumer}

        @return: A Deferred which fires when the file has been
        consumed completely.
        """


class IWriteFile(Interface):
    """
    A file into which bytes may be written.
    """

    def receive():
        """
        Create a consumer which will write to this file.  This method may
        only be invoked once on each provider.

        @rtype: C{Deferred} of C{IConsumer}
        """

    def close():
        """
        Perform any post-write work that needs to be done. This method may
        only be invoked once on each provider, and will always be invoked
        after receive().

        @rtype: C{Deferred} of anything: the value is ignored. The FTP client
        will not see their upload request complete until this Deferred has
        been fired.
        """


def _getgroups(uid):
    """
    Return the primary and supplementary groups for the given UID.

    @type uid: C{int}
    """
    result = []
    pwent = pwd.getpwuid(uid)

    result.append(pwent.pw_gid)

    for grent in grp.getgrall():
        if pwent.pw_name in grent.gr_mem:
            result.append(grent.gr_gid)

    return result


def _testPermissions(uid, gid, spath, mode="r"):
    """
    checks to see if uid has proper permissions to access path with mode

    @type uid: C{int}
    @param uid: numeric user id

    @type gid: C{int}
    @param gid: numeric group id

    @type spath: C{str}
    @param spath: the path on the server to test

    @type mode: C{str}
    @param mode: 'r' or 'w' (read or write)

    @rtype: C{bool}
    @return: True if the given credentials have the specified form of
        access to the given path
    """
    if mode == "r":
        usr = stat.S_IRUSR
        grp = stat.S_IRGRP
        oth = stat.S_IROTH
        amode = os.R_OK
    elif mode == "w":
        usr = stat.S_IWUSR
        grp = stat.S_IWGRP
        oth = stat.S_IWOTH
        amode = os.W_OK
    else:
        raise ValueError(f"Invalid mode {mode!r}: must specify 'r' or 'w'")

    access = False
    if os.path.exists(spath):
        if uid == 0:
            access = True
        else:
            s = os.stat(spath)
            if usr & s.st_mode and uid == s.st_uid:
                access = True
            elif grp & s.st_mode and gid in _getgroups(uid):
                access = True
            elif oth & s.st_mode:
                access = True

    if access:
        if not os.access(spath, amode):
            access = False
            log.msg(
                "Filesystem grants permission to UID %d but it is "
                "inaccessible to me running as UID %d" % (uid, os.getuid())
            )
    return access


@implementer(IFTPShell)
class FTPAnonymousShell:
    """
    An anonymous implementation of IFTPShell

    @type filesystemRoot: L{twisted.python.filepath.FilePath}
    @ivar filesystemRoot: The path which is considered the root of
    this shell.
    """

    def __init__(self, filesystemRoot):
        self.filesystemRoot = filesystemRoot

    def _path(self, path):
        return self.filesystemRoot.descendant(path)

    def makeDirectory(self, path):
        return defer.fail(AnonUserDeniedError())

    def removeDirectory(self, path):
        return defer.fail(AnonUserDeniedError())

    def removeFile(self, path):
        return defer.fail(AnonUserDeniedError())

    def rename(self, fromPath, toPath):
        return defer.fail(AnonUserDeniedError())

    def receive(self, path):
        path = self._path(path)
        return defer.fail(AnonUserDeniedError())

    def openForReading(self, path):
        """
        Open C{path} for reading.

        @param path: The path, as a list of segments, to open.
        @type path: C{list} of C{unicode}
        @return: A L{Deferred} is returned that will fire with an object
            implementing L{IReadFile} if the file is successfully opened.  If
            C{path} is a directory, or if an exception is raised while trying
            to open the file, the L{Deferred} will fire with an error.
        """
        p = self._path(path)
        if p.isdir():
            # Normally, we would only check for EISDIR in open, but win32
            # returns EACCES in this case, so we check before
            return defer.fail(IsADirectoryError(path))
        try:
            f = p.open("r")
        except OSError as e:
            return errnoToFailure(e.errno, path)
        except BaseException:
            return defer.fail()
        else:
            return defer.succeed(_FileReader(f))

    def openForWriting(self, path):
        """
        Reject write attempts by anonymous users with
        L{PermissionDeniedError}.
        """
        return defer.fail(PermissionDeniedError("STOR not allowed"))

    def access(self, path):
        p = self._path(path)
        if not p.exists():
            # Again, win32 doesn't report a sane error after, so let's fail
            # early if we can
            return defer.fail(FileNotFoundError(path))
        # For now, just see if we can os.listdir() it
        try:
            p.listdir()
        except OSError as e:
            return errnoToFailure(e.errno, path)
        except BaseException:
            return defer.fail()
        else:
            return defer.succeed(None)

    def stat(self, path, keys=()):
        p = self._path(path)
        if p.isdir():
            try:
                statResult = self._statNode(p, keys)
            except OSError as e:
                return errnoToFailure(e.errno, path)
            except BaseException:
                return defer.fail()
            else:
                return defer.succeed(statResult)
        else:
            return self.list(path, keys).addCallback(lambda res: res[0][1])

    def list(self, path, keys=()):
        """
        Return the list of files at given C{path}, adding C{keys} stat
        informations if specified.

        @param path: the directory or file to check.
        @type path: C{str}

        @param keys: the list of desired metadata
        @type keys: C{list} of C{str}
        """
        filePath = self._path(path)
        if filePath.isdir():
            entries = filePath.listdir()
            fileEntries = [filePath.child(p) for p in entries]
        elif filePath.isfile():
            entries = [os.path.join(*filePath.segmentsFrom(self.filesystemRoot))]
            fileEntries = [filePath]
        else:
            return defer.fail(FileNotFoundError(path))

        results = []
        for fileName, filePath in zip(entries, fileEntries):
            ent = []
            results.append((fileName, ent))
            if keys:
                try:
                    ent.extend(self._statNode(filePath, keys))
                except OSError as e:
                    return errnoToFailure(e.errno, fileName)
                except BaseException:
                    return defer.fail()

        return defer.succeed(results)

    def _statNode(self, filePath, keys):
        """
        Shortcut method to get stat info on a node.

        @param filePath: the node to stat.
        @type filePath: C{filepath.FilePath}

        @param keys: the stat keys to get.
        @type keys: C{iterable}
        """
        filePath.restat()
        return [getattr(self, "_stat_" + k)(filePath) for k in keys]

    def _stat_size(self, fp):
        """
        Get the filepath's size as an int

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{int} representing the size
        """
        return fp.getsize()

    def _stat_permissions(self, fp):
        """
        Get the filepath's permissions object

        @param fp: L{twisted.python.filepath.FilePath}
        @return: L{twisted.python.filepath.Permissions} of C{fp}
        """
        return fp.getPermissions()

    def _stat_hardlinks(self, fp):
        """
        Get the number of hardlinks for the filepath - if the number of
        hardlinks is not yet implemented (say in Windows), just return 0 since
        stat-ing a file in Windows seems to return C{st_nlink=0}.

        (Reference:
        U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{int} representing the number of hardlinks
        """
        try:
            return fp.getNumberOfHardLinks()
        except NotImplementedError:
            return 0

    def _stat_modified(self, fp):
        """
        Get the filepath's last modified date

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{int} as seconds since the epoch
        """
        return fp.getModificationTime()

    def _stat_owner(self, fp):
        """
        Get the filepath's owner's username.  If this is not implemented
        (say in Windows) return the string "0" since stat-ing a file in
        Windows seems to return C{st_uid=0}.

        (Reference:
        U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{str} representing the owner's username
        """
        try:
            userID = fp.getUserID()
        except NotImplementedError:
            return "0"
        else:
            if pwd is not None:
                try:
                    return pwd.getpwuid(userID)[0]
                except KeyError:
                    pass
            return str(userID)

    def _stat_group(self, fp):
        """
        Get the filepath's owner's group.  If this is not implemented
        (say in Windows) return the string "0" since stat-ing a file in
        Windows seems to return C{st_gid=0}.

        (Reference:
        U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{str} representing the owner's group
        """
        try:
            groupID = fp.getGroupID()
        except NotImplementedError:
            return "0"
        else:
            if grp is not None:
                try:
                    return grp.getgrgid(groupID)[0]
                except KeyError:
                    pass
            return str(groupID)

    def _stat_directory(self, fp):
        """
        Get whether the filepath is a directory

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{bool}
        """
        return fp.isdir()


@implementer(IReadFile)
class _FileReader:
    def __init__(self, fObj):
        self.fObj = fObj
        self._send = False

    def _close(self, passthrough):
        self._send = True
        self.fObj.close()
        return passthrough

    def send(self, consumer):
        assert not self._send, "Can only call IReadFile.send *once* per instance"
        self._send = True
        d = basic.FileSender().beginFileTransfer(self.fObj, consumer)
        d.addBoth(self._close)
        return d


class FTPShell(FTPAnonymousShell):
    """
    An authenticated implementation of L{IFTPShell}.
    """

    def makeDirectory(self, path):
        p = self._path(path)
        try:
            p.makedirs()
        except OSError as e:
            return errnoToFailure(e.errno, path)
        except BaseException:
            return defer.fail()
        else:
            return defer.succeed(None)

    def removeDirectory(self, path):
        p = self._path(path)
        if p.isfile():
            # Win32 returns the wrong errno when rmdir is called on a file
            # instead of a directory, so as we have the info here, let's fail
            # early with a pertinent error
            return defer.fail(IsNotADirectoryError(path))
        try:
            os.rmdir(p.path)
        except OSError as e:
            return errnoToFailure(e.errno, path)
        except BaseException:
            return defer.fail()
        else:
            return defer.succeed(None)

    def removeFile(self, path):
        p = self._path(path)
        if p.isdir():
            # Win32 returns the wrong errno when remove is called on a
            # directory instead of a file, so as we have the info here,
            # let's fail early with a pertinent error
            return defer.fail(IsADirectoryError(path))
        try:
            p.remove()
        except OSError as e:
            return errnoToFailure(e.errno, path)
        except BaseException:
            return defer.fail()
        else:
            return defer.succeed(None)

    def rename(self, fromPath, toPath):
        fp = self._path(fromPath)
        tp = self._path(toPath)
        try:
            os.rename(fp.path, tp.path)
        except OSError as e:
            return errnoToFailure(e.errno, fromPath)
        except BaseException:
            return defer.fail()
        else:
            return defer.succeed(None)

    def openForWriting(self, path):
        """
        Open C{path} for writing.

        @param path: The path, as a list of segments, to open.
        @type path: C{list} of C{unicode}
        @return: A L{Deferred} is returned that will fire with an object
            implementing L{IWriteFile} if the file is successfully opened.  If
            C{path} is a directory, or if an exception is raised while trying
            to open the file, the L{Deferred} will fire with an error.
        """
        p = self._path(path)
        if p.isdir():
            # Normally, we would only check for EISDIR in open, but win32
            # returns EACCES in this case, so we check before
            return defer.fail(IsADirectoryError(path))
        try:
            fObj = p.open("w")
        except OSError as e:
            return errnoToFailure(e.errno, path)
        except BaseException:
            return defer.fail()
        return defer.succeed(_FileWriter(fObj))


@implementer(IWriteFile)
class _FileWriter:
    def __init__(self, fObj):
        self.fObj = fObj
        self._receive = False

    def receive(self):
        assert not self._receive, "Can only call IWriteFile.receive *once* per instance"
        self._receive = True
        # FileConsumer will close the file object
        return defer.succeed(FileConsumer(self.fObj))

    def close(self):
        return defer.succeed(None)


@implementer(portal.IRealm)
class BaseFTPRealm:
    """
    Base class for simple FTP realms which provides an easy hook for specifying
    the home directory for each user.
    """

    def __init__(self, anonymousRoot):
        self.anonymousRoot = filepath.FilePath(anonymousRoot)

    def getHomeDirectory(self, avatarId):
        """
        Return a L{FilePath} representing the home directory of the given
        avatar.  Override this in a subclass.

        @param avatarId: A user identifier returned from a credentials checker.
        @type avatarId: C{str}

        @rtype: L{FilePath}
        """
        raise NotImplementedError(
            f"{self.__class__!r} did not override getHomeDirectory"
        )

    def requestAvatar(self, avatarId, mind, *interfaces):
        for iface in interfaces:
            if iface is IFTPShell:
                if avatarId is checkers.ANONYMOUS:
                    avatar = FTPAnonymousShell(self.anonymousRoot)
                else:
                    avatar = FTPShell(self.getHomeDirectory(avatarId))
                return (IFTPShell, avatar, getattr(avatar, "logout", lambda: None))
        raise NotImplementedError("Only IFTPShell interface is supported by this realm")


class FTPRealm(BaseFTPRealm):
    """
    @type anonymousRoot: L{twisted.python.filepath.FilePath}
    @ivar anonymousRoot: Root of the filesystem to which anonymous
        users will be granted access.

    @type userHome: L{filepath.FilePath}
    @ivar userHome: Root of the filesystem containing user home directories.
    """

    def __init__(self, anonymousRoot, userHome="/home"):
        BaseFTPRealm.__init__(self, anonymousRoot)
        self.userHome = filepath.FilePath(userHome)

    def getHomeDirectory(self, avatarId):
        """
        Use C{avatarId} as a single path segment to construct a child of
        C{self.userHome} and return that child.
        """
        return self.userHome.child(avatarId)


class SystemFTPRealm(BaseFTPRealm):
    """
    L{SystemFTPRealm} uses system user account information to decide what the
    home directory for a particular avatarId is.

    This works on POSIX but probably is not reliable on Windows.
    """

    def getHomeDirectory(self, avatarId):
        """
        Return the system-defined home directory of the system user account
        with the name C{avatarId}.
        """
        path = os.path.expanduser("~" + avatarId)
        if path.startswith("~"):
            raise cred_error.UnauthorizedLogin()
        return filepath.FilePath(path)


# --- FTP CLIENT  -------------------------------------------------------------

####
# And now for the client...

# Notes:
#   * Reference: http://cr.yp.to/ftp.html
#   * FIXME: Does not support pipelining (which is not supported by all
#     servers anyway).  This isn't a functionality limitation, just a
#     small performance issue.
#   * Only has a rudimentary understanding of FTP response codes (although
#     the full response is passed to the caller if they so choose).
#   * Assumes that USER and PASS should always be sent
#   * Always sets TYPE I  (binary mode)
#   * Doesn't understand any of the weird, obscure TELNET stuff (\377...)
#   * FIXME: Doesn't share any code with the FTPServer


class ConnectionLost(FTPError):
    pass


class CommandFailed(FTPError):
    pass


class BadResponse(FTPError):
    pass


class UnexpectedResponse(FTPError):
    pass


class UnexpectedData(FTPError):
    pass


class FTPCommand:
    def __init__(self, text=None, public=0):
        self.text = text
        self.deferred = defer.Deferred()
        self.ready = 1
        self.public = public
        self.transferDeferred = None

    def fail(self, failure):
        if self.public:
            self.deferred.errback(failure)


class ProtocolWrapper(protocol.Protocol):
    def __init__(self, original, deferred):
        self.original = original
        self.deferred = deferred

    def makeConnection(self, transport):
        self.original.makeConnection(transport)

    def dataReceived(self, data):
        self.original.dataReceived(data)

    def connectionLost(self, reason):
        self.original.connectionLost(reason)
        # Signal that transfer has completed
        self.deferred.callback(None)


class IFinishableConsumer(interfaces.IConsumer):
    """
    A Consumer for producers that finish.

    @since: 11.0
    """

    def finish():
        """
        The producer has finished producing.
        """


@implementer(IFinishableConsumer)
class SenderProtocol(protocol.Protocol):
    def __init__(self):
        # Fired upon connection
        self.connectedDeferred = defer.Deferred()

        # Fired upon disconnection
        self.deferred = defer.Deferred()

    # Protocol stuff
    def dataReceived(self, data):
        raise UnexpectedData(
            "Received data from the server on a " "send-only data-connection"
        )

    def makeConnection(self, transport):
        protocol.Protocol.makeConnection(self, transport)
        self.connectedDeferred.callback(self)

    def connectionLost(self, reason):
        if reason.check(error.ConnectionDone):
            self.deferred.callback("connection done")
        else:
            self.deferred.errback(reason)

    # IFinishableConsumer stuff
    def write(self, data):
        self.transport.write(data)

    def registerProducer(self, producer, streaming):
        """
        Register the given producer with our transport.
        """
        self.transport.registerProducer(producer, streaming)

    def unregisterProducer(self):
        """
        Unregister the previously registered producer.
        """
        self.transport.unregisterProducer()

    def finish(self):
        self.transport.loseConnection()


def decodeHostPort(line):
    """
    Decode an FTP response specifying a host and port.

    @return: a 2-tuple of (host, port).
    """
    abcdef = re.sub("[^0-9, ]", "", line)
    parsed = [int(p.strip()) for p in abcdef.split(",")]
    for x in parsed:
        if x < 0 or x > 255:
            raise ValueError("Out of range", line, x)
    a, b, c, d, e, f = parsed
    host = f"{a}.{b}.{c}.{d}"
    port = (int(e) << 8) + int(f)
    return host, port


def encodeHostPort(host, port):
    numbers = host.split(".") + [str(port >> 8), str(port % 256)]
    return ",".join(numbers)


def decodeExtendedAddress(address):
    """
    Decode an FTP protocol/address/port combination, using the syntax
    defined in RFC 2428 section 2.

    @return: a 3-tuple of (protocol, host, port).
    """
    delim = address[0]
    protocol, host, port, _ = address[1:].split(delim)
    return protocol, host, int(port)


def _unwrapFirstError(failure):
    failure.trap(defer.FirstError)
    return failure.value.subFailure


class FTPDataPortFactory(protocol.ServerFactory):
    """
    Factory for data connections that use the PORT command

    (i.e. "active" transfers)
    """

    noisy = False

    def buildProtocol(self, addr):
        # This is a bit hackish -- we already have a Protocol instance,
        # so just return it instead of making a new one
        # FIXME: Reject connections from the wrong address/port
        #        (potential security problem)
        self.protocol.factory = self
        self.port.loseConnection()
        return self.protocol


class FTPClientBasic(basic.LineReceiver):
    """
    Foundations of an FTP client.
    """

    debug = False
    _encoding = "latin-1"

    def __init__(self):
        self.actionQueue = []
        self.greeting = None
        self.nextDeferred = defer.Deferred().addCallback(self._cb_greeting)
        self.nextDeferred.addErrback(self.fail)
        self.response = []
        self._failed = 0

    def fail(self, error):
        """
        Give an error to any queued deferreds.
        """
        self._fail(error)

    def _fail(self, error):
        """
        Errback all queued deferreds.
        """
        if self._failed:
            # We're recursing; bail out here for simplicity
            return error
        self._failed = 1
        if self.nextDeferred:
            try:
                self.nextDeferred.errback(
                    failure.Failure(ConnectionLost("FTP connection lost", error))
                )
            except defer.AlreadyCalledError:
                pass
        for ftpCommand in self.actionQueue:
            ftpCommand.fail(
                failure.Failure(ConnectionLost("FTP connection lost", error))
            )
        return error

    def _cb_greeting(self, greeting):
        self.greeting = greeting

    def sendLine(self, line):
        """
        Sends a line, unless line is None.

        @param line: Line to send
        @type line: L{bytes} or L{unicode}
        """
        if line is None:
            return
        elif isinstance(line, str):
            line = line.encode(self._encoding)
        basic.LineReceiver.sendLine(self, line)

    def sendNextCommand(self):
        """
        (Private) Processes the next command in the queue.
        """
        ftpCommand = self.popCommandQueue()
        if ftpCommand is None:
            self.nextDeferred = None
            return
        if not ftpCommand.ready:
            self.actionQueue.insert(0, ftpCommand)
            reactor.callLater(1.0, self.sendNextCommand)
            self.nextDeferred = None
            return

        # FIXME: this if block doesn't belong in FTPClientBasic, it belongs in
        #        FTPClient.
        if ftpCommand.text == "PORT":
            self.generatePortCommand(ftpCommand)

        if self.debug:
            log.msg("<-- %s" % ftpCommand.text)
        self.nextDeferred = ftpCommand.deferred
        self.sendLine(ftpCommand.text)

    def queueCommand(self, ftpCommand):
        """
        Add an FTPCommand object to the queue.

        If it's the only thing in the queue, and we are connected and we aren't
        waiting for a response of an earlier command, the command will be sent
        immediately.

        @param ftpCommand: an L{FTPCommand}
        """
        self.actionQueue.append(ftpCommand)
        if (
            len(self.actionQueue) == 1
            and self.transport is not None
            and self.nextDeferred is None
        ):
            self.sendNextCommand()

    def queueStringCommand(self, command, public=1):
        """
        Queues a string to be issued as an FTP command

        @param command: string of an FTP command to queue
        @param public: a flag intended for internal use by FTPClient.  Don't
            change it unless you know what you're doing.

        @return: a L{Deferred} that will be called when the response to the
            command has been received.
        """
        ftpCommand = FTPCommand(command, public)
        self.queueCommand(ftpCommand)
        return ftpCommand.deferred

    def popCommandQueue(self):
        """
        Return the front element of the command queue, or None if empty.
        """
        if self.actionQueue:
            return self.actionQueue.pop(0)
        else:
            return None

    def queueLogin(self, username, password):
        """
        Login: send the username, send the password.

        If the password is L{None}, the PASS command won't be sent.  Also, if
        the response to the USER command has a response code of 230 (User
        logged in), then PASS won't be sent either.
        """
        # Prepare the USER command
        deferreds = []
        userDeferred = self.queueStringCommand("USER " + username, public=0)
        deferreds.append(userDeferred)

        # Prepare the PASS command (if a password is given)
        if password is not None:
            passwordCmd = FTPCommand("PASS " + password, public=0)
            self.queueCommand(passwordCmd)
            deferreds.append(passwordCmd.deferred)

            # Avoid sending PASS if the response to USER is 230.
            # (ref: http://cr.yp.to/ftp/user.html#user)
            def cancelPasswordIfNotNeeded(response):
                if response[0].startswith("230"):
                    # No password needed!
                    self.actionQueue.remove(passwordCmd)
                return response

            userDeferred.addCallback(cancelPasswordIfNotNeeded)

        # Error handling.
        for deferred in deferreds:
            # If something goes wrong, call fail
            deferred.addErrback(self.fail)
            # But also swallow the error, so we don't cause spurious errors
            deferred.addErrback(lambda x: None)

    def lineReceived(self, line):
        """
        (Private) Parses the response messages from the FTP server.
        """
        # Add this line to the current response
        line = line.decode(self._encoding)

        if self.debug:
            log.msg("--> %s" % line)
        self.response.append(line)

        # Bail out if this isn't the last line of a response
        # The last line of response starts with 3 digits followed by a space
        codeIsValid = re.match(r"\d{3} ", line)
        if not codeIsValid:
            return

        code = line[0:3]

        # Ignore marks
        if code[0] == "1":
            return

        # Check that we were expecting a response
        if self.nextDeferred is None:
            self.fail(UnexpectedResponse(self.response))
            return

        # Reset the response
        response = self.response
        self.response = []

        # Look for a success or error code, and call the appropriate callback
        if code[0] in ("2", "3"):
            # Success
            self.nextDeferred.callback(response)
        elif code[0] in ("4", "5"):
            # Failure
            self.nextDeferred.errback(failure.Failure(CommandFailed(response)))
        else:
            # This shouldn't happen unless something screwed up.
            log.msg(f"Server sent invalid response code {code}")
            self.nextDeferred.errback(failure.Failure(BadResponse(response)))

        # Run the next command
        self.sendNextCommand()

    def connectionLost(self, reason):
        self._fail(reason)


class _PassiveConnectionFactory(protocol.ClientFactory):
    noisy = False

    def __init__(self, protoInstance):
        self.protoInstance = protoInstance

    def buildProtocol(self, ignored):
        self.protoInstance.factory = self
        return self.protoInstance

    def clientConnectionFailed(self, connector, reason):
        e = FTPError("Connection Failed", reason)
        self.protoInstance.deferred.errback(e)


class FTPClient(FTPClientBasic):
    """
    L{FTPClient} is a client implementation of the FTP protocol which
    exposes FTP commands as methods which return L{Deferred}s.

    Each command method returns a L{Deferred} which is called back when a
    successful response code (2xx or 3xx) is received from the server or
    which is error backed if an error response code (4xx or 5xx) is received
    from the server or if a protocol violation occurs.  If an error response
    code is received, the L{Deferred} fires with a L{Failure} wrapping a
    L{CommandFailed} instance.  The L{CommandFailed} instance is created
    with a list of the response lines received from the server.

    See U{RFC 959<http://www.ietf.org/rfc/rfc959.txt>} for error code
    definitions.

    Both active and passive transfers are supported.

    @ivar passive: See description in __init__.
    """

    connectFactory = reactor.connectTCP  # type: ignore[attr-defined]

    def __init__(
        self, username="anonymous", password="twisted@twistedmatrix.com", passive=1
    ):
        """
        Constructor.

        I will login as soon as I receive the welcome message from the server.

        @param username: FTP username
        @param password: FTP password
        @param passive: flag that controls if I use active or passive data
            connections.  You can also change this after construction by
            assigning to C{self.passive}.
        """
        FTPClientBasic.__init__(self)
        self.queueLogin(username, password)

        self.passive = passive

    def fail(self, error):
        """
        Disconnect, and also give an error to any queued deferreds.
        """
        self.transport.loseConnection()
        self._fail(error)

    def receiveFromConnection(self, commands, protocol):
        """
        Retrieves a file or listing generated by the given command,
        feeding it to the given protocol.

        @param commands: list of strings of FTP commands to execute then
            receive the results of (e.g. C{LIST}, C{RETR})
        @param protocol: A L{Protocol} B{instance} e.g. an
            L{FTPFileListProtocol}, or something that can be adapted to one.
            Typically this will be an L{IConsumer} implementation.

        @return: L{Deferred}.
        """
        protocol = interfaces.IProtocol(protocol)
        wrapper = ProtocolWrapper(protocol, defer.Deferred())
        return self._openDataConnection(commands, wrapper)

    def queueLogin(self, username, password):
        """
        Login: send the username, send the password, and
        set retrieval mode to binary
        """
        FTPClientBasic.queueLogin(self, username, password)
        d = self.queueStringCommand("TYPE I", public=0)
        # If something goes wrong, call fail
        d.addErrback(self.fail)
        # But also swallow the error, so we don't cause spurious errors
        d.addErrback(lambda x: None)

    def sendToConnection(self, commands):
        """
        XXX

        @return: A tuple of two L{Deferred}s:
                  - L{Deferred} L{IFinishableConsumer}. You must call
                    the C{finish} method on the IFinishableConsumer when the
                    file is completely transferred.
                  - L{Deferred} list of control-connection responses.
        """
        s = SenderProtocol()
        r = self._openDataConnection(commands, s)
        return (s.connectedDeferred, r)

    def _openDataConnection(self, commands, protocol):
        """
        This method returns a DeferredList.
        """
        cmds = [FTPCommand(command, public=1) for command in commands]
        cmdsDeferred = defer.DeferredList(
            [cmd.deferred for cmd in cmds], fireOnOneErrback=True, consumeErrors=True
        )
        cmdsDeferred.addErrback(_unwrapFirstError)

        if self.passive:
            # Hack: use a mutable object to sneak a variable out of the
            # scope of doPassive
            _mutable = [None]

            def doPassive(response):
                """Connect to the port specified in the response to PASV"""
                host, port = decodeHostPort(response[-1][4:])

                f = _PassiveConnectionFactory(protocol)
                _mutable[0] = self.connectFactory(host, port, f)

            pasvCmd = FTPCommand("PASV")
            self.queueCommand(pasvCmd)
            pasvCmd.deferred.addCallback(doPassive).addErrback(self.fail)

            results = [cmdsDeferred, pasvCmd.deferred, protocol.deferred]
            d = defer.DeferredList(results, fireOnOneErrback=True, consumeErrors=True)
            d.addErrback(_unwrapFirstError)

            # Ensure the connection is always closed
            def close(x, m=_mutable):
                m[0] and m[0].disconnect()
                return x

            d.addBoth(close)

        else:
            # We just place a marker command in the queue, and will fill in
            # the host and port numbers later (see generatePortCommand)
            portCmd = FTPCommand("PORT")

            # Ok, now we jump through a few hoops here.
            # This is the problem: a transfer is not to be trusted as complete
            # until we get both the "226 Transfer complete" message on the
            # control connection, and the data socket is closed.  Thus, we use
            # a DeferredList to make sure we only fire the callback at the
            # right time.

            portCmd.transferDeferred = protocol.deferred
            portCmd.protocol = protocol
            portCmd.deferred.addErrback(portCmd.transferDeferred.errback)
            self.queueCommand(portCmd)

            # Create dummy functions for the next callback to call.
            # These will also be replaced with real functions in
            # generatePortCommand.
            portCmd.loseConnection = lambda result: result
            portCmd.fail = lambda error: error

            # Ensure that the connection always gets closed
            cmdsDeferred.addErrback(lambda e, pc=portCmd: pc.fail(e) or e)

            results = [cmdsDeferred, portCmd.deferred, portCmd.transferDeferred]
            d = defer.DeferredList(results, fireOnOneErrback=True, consumeErrors=True)
            d.addErrback(_unwrapFirstError)

        for cmd in cmds:
            self.queueCommand(cmd)
        return d

    def generatePortCommand(self, portCmd):
        """
        (Private) Generates the text of a given PORT command.
        """

        # The problem is that we don't create the listening port until we need
        # it for various reasons, and so we have to muck about to figure out
        # what interface and port it's listening on, and then finally we can
        # create the text of the PORT command to send to the FTP server.

        # FIXME: This method is far too ugly.

        # FIXME: The best solution is probably to only create the data port
        #        once per FTPClient, and just recycle it for each new download.
        #        This should be ok, because we don't pipeline commands.

        # Start listening on a port
        factory = FTPDataPortFactory()
        factory.protocol = portCmd.protocol
        listener = reactor.listenTCP(0, factory)
        factory.port = listener

        # Ensure we close the listening port if something goes wrong
        def listenerFail(error, listener=listener):
            if listener.connected:
                listener.loseConnection()
            return error

        portCmd.fail = listenerFail

        # Construct crufty FTP magic numbers that represent host & port
        host = self.transport.getHost().host
        port = listener.getHost().port
        portCmd.text = "PORT " + encodeHostPort(host, port)

    def escapePath(self, path):
        """
        Returns a FTP escaped path (replace newlines with nulls).
        """
        # Escape newline characters
        return path.replace("\n", "\0")

    def retrieveFile(self, path, protocol, offset=0):
        """
        Retrieve a file from the given path

        This method issues the 'RETR' FTP command.

        The file is fed into the given Protocol instance.  The data connection
        will be passive if self.passive is set.

        @param path: path to file that you wish to receive.
        @param protocol: a L{Protocol} instance.
        @param offset: offset to start downloading from

        @return: L{Deferred}
        """
        cmds = ["RETR " + self.escapePath(path)]
        if offset:
            cmds.insert(0, ("REST " + str(offset)))
        return self.receiveFromConnection(cmds, protocol)

    retr = retrieveFile

    def storeFile(self, path, offset=0):
        """
        Store a file at the given path.

        This method issues the 'STOR' FTP command.

        @return: A tuple of two L{Deferred}s:
                  - L{Deferred} L{IFinishableConsumer}. You must call
                    the C{finish} method on the IFinishableConsumer when the
                    file is completely transferred.
                  - L{Deferred} list of control-connection responses.
        """
        cmds = ["STOR " + self.escapePath(path)]
        if offset:
            cmds.insert(0, ("REST " + str(offset)))
        return self.sendToConnection(cmds)

    stor = storeFile

    def rename(self, pathFrom, pathTo):
        """
        Rename a file.

        This method issues the I{RNFR}/I{RNTO} command sequence to rename
        C{pathFrom} to C{pathTo}.

        @param pathFrom: the absolute path to the file to be renamed
        @type pathFrom: C{str}

        @param pathTo: the absolute path to rename the file to.
        @type pathTo: C{str}

        @return: A L{Deferred} which fires when the rename operation has
            succeeded or failed.  If it succeeds, the L{Deferred} is called
            back with a two-tuple of lists.  The first list contains the
            responses to the I{RNFR} command.  The second list contains the
            responses to the I{RNTO} command.  If either I{RNFR} or I{RNTO}
            fails, the L{Deferred} is errbacked with L{CommandFailed} or
            L{BadResponse}.
        @rtype: L{Deferred}

        @since: 8.2
        """
        renameFrom = self.queueStringCommand("RNFR " + self.escapePath(pathFrom))
        renameTo = self.queueStringCommand("RNTO " + self.escapePath(pathTo))

        fromResponse = []

        # Use a separate Deferred for the ultimate result so that Deferred
        # chaining can't interfere with its result.
        result = defer.Deferred()
        # Bundle up all the responses
        result.addCallback(lambda toResponse: (fromResponse, toResponse))

        def ebFrom(failure):
            # Make sure the RNTO doesn't run if the RNFR failed.
            self.popCommandQueue()
            result.errback(failure)

        # Save the RNFR response to pass to the result Deferred later
        renameFrom.addCallbacks(fromResponse.extend, ebFrom)

        # Hook up the RNTO to the result Deferred as well
        renameTo.chainDeferred(result)

        return result

    def list(self, path, protocol):
        """
        Retrieve a file listing into the given protocol instance.

        This method issues the 'LIST' FTP command.

        @param path: path to get a file listing for.
        @param protocol: a L{Protocol} instance, probably a
            L{FTPFileListProtocol} instance.  It can cope with most common file
            listing formats.

        @return: L{Deferred}
        """
        if path is None:
            path = ""
        return self.receiveFromConnection(["LIST " + self.escapePath(path)], protocol)

    def nlst(self, path, protocol):
        """
        Retrieve a short file listing into the given protocol instance.

        This method issues the 'NLST' FTP command.

        NLST (should) return a list of filenames, one per line.

        @param path: path to get short file listing for.
        @param protocol: a L{Protocol} instance.
        """
        if path is None:
            path = ""
        return self.receiveFromConnection(["NLST " + self.escapePath(path)], protocol)

    def cwd(self, path):
        """
        Issues the CWD (Change Working Directory) command.

        @return: a L{Deferred} that will be called when done.
        """
        return self.queueStringCommand("CWD " + self.escapePath(path))

    def makeDirectory(self, path):
        """
        Make a directory

        This method issues the MKD command.

        @param path: The path to the directory to create.
        @type path: C{str}

        @return: A L{Deferred} which fires when the server responds.  If the
            directory is created, the L{Deferred} is called back with the
            server response.  If the server response indicates the directory
            was not created, the L{Deferred} is errbacked with a L{Failure}
            wrapping L{CommandFailed} or L{BadResponse}.
        @rtype: L{Deferred}

        @since: 8.2
        """
        return self.queueStringCommand("MKD " + self.escapePath(path))

    def removeFile(self, path):
        """
        Delete a file on the server.

        L{removeFile} issues a I{DELE} command to the server to remove the
        indicated file.  Note that this command cannot remove a directory.

        @param path: The path to the file to delete. May be relative to the
            current dir.
        @type path: C{str}

        @return: A L{Deferred} which fires when the server responds.  On error,
            it is errbacked with either L{CommandFailed} or L{BadResponse}.  On
            success, it is called back with a list of response lines.
        @rtype: L{Deferred}

        @since: 8.2
        """
        return self.queueStringCommand("DELE " + self.escapePath(path))

    def removeDirectory(self, path):
        """
        Delete a directory on the server.

        L{removeDirectory} issues a I{RMD} command to the server to remove the
        indicated directory. Described in RFC959.

        @param path: The path to the directory to delete. May be relative to
            the current working directory.
        @type path: C{str}

        @return: A L{Deferred} which fires when the server responds. On error,
            it is errbacked with either L{CommandFailed} or L{BadResponse}. On
            success, it is called back with a list of response lines.
        @rtype: L{Deferred}

        @since: 11.1
        """
        return self.queueStringCommand("RMD " + self.escapePath(path))

    def cdup(self):
        """
        Issues the CDUP (Change Directory UP) command.

        @return: a L{Deferred} that will be called when done.
        """
        return self.queueStringCommand("CDUP")

    def pwd(self):
        """
        Issues the PWD (Print Working Directory) command.

        The L{getDirectory} does the same job but automatically parses the
        result.

        @return: a L{Deferred} that will be called when done.  It is up to the
            caller to interpret the response, but the L{parsePWDResponse}
            method in this module should work.
        """
        return self.queueStringCommand("PWD")

    def getDirectory(self):
        """
        Returns the current remote directory.

        @return: a L{Deferred} that will be called back with a C{str} giving
            the remote directory or which will errback with L{CommandFailed}
            if an error response is returned.
        """

        def cbParse(result):
            try:
                # The only valid code is 257
                if int(result[0].split(" ", 1)[0]) != 257:
                    raise ValueError
            except (IndexError, ValueError):
                return failure.Failure(CommandFailed(result))
            path = parsePWDResponse(result[0])
            if path is None:
                return failure.Failure(CommandFailed(result))
            return path

        return self.pwd().addCallback(cbParse)

    def quit(self):
        """
        Issues the I{QUIT} command.

        @return: A L{Deferred} that fires when the server acknowledges the
            I{QUIT} command.  The transport should not be disconnected until
            this L{Deferred} fires.
        """
        return self.queueStringCommand("QUIT")


class FTPFileListProtocol(basic.LineReceiver):
    """
    Parser for standard FTP file listings

    This is the evil required to match::

        -rw-r--r--   1 root     other        531 Jan 29 03:26 README

    If you need different evil for a wacky FTP server, you can
    override either C{fileLinePattern} or C{parseDirectoryLine()}.

    It populates the instance attribute self.files, which is a list containing
    dicts with the following keys (examples from the above line):
        - filetype:   e.g. 'd' for directories, or '-' for an ordinary file
        - perms:      e.g. 'rw-r--r--'
        - nlinks:     e.g. 1
        - owner:      e.g. 'root'
        - group:      e.g. 'other'
        - size:       e.g. 531
        - date:       e.g. 'Jan 29 03:26'
        - filename:   e.g. 'README'
        - linktarget: e.g. 'some/file'

    Note that the 'date' value will be formatted differently depending on the
    date.  Check U{http://cr.yp.to/ftp.html} if you really want to try to parse
    it.

    It also matches the following::
        -rw-r--r--   1 root     other        531 Jan 29 03:26 I HAVE\\ SPACE
           - filename:   e.g. 'I HAVE SPACE'

        -rw-r--r--   1 root     other        531 Jan 29 03:26 LINK -> TARGET
           - filename:   e.g. 'LINK'
           - linktarget: e.g. 'TARGET'

        -rw-r--r--   1 root     other        531 Jan 29 03:26 N S -> L S
           - filename:   e.g. 'N S'
           - linktarget: e.g. 'L S'

    @ivar files: list of dicts describing the files in this listing
    """

    fileLinePattern = re.compile(
        r"^(?P<filetype>.)(?P<perms>.{9})\s+(?P<nlinks>\d*)\s*"
        r"(?P<owner>\S+)\s+(?P<group>\S+)\s+(?P<size>\d+)\s+"
        r"(?P<date>...\s+\d+\s+[\d:]+)\s+(?P<filename>.{1,}?)"
        r"( -> (?P<linktarget>[^\r]*))?\r?$"
    )
    delimiter = b"\n"
    _encoding = "latin-1"

    def __init__(self):
        self.files = []

    def lineReceived(self, line):
        line = line.decode(self._encoding)
        d = self.parseDirectoryLine(line)
        if d is None:
            self.unknownLine(line)
        else:
            self.addFile(d)

    def parseDirectoryLine(self, line):
        """
        Return a dictionary of fields, or None if line cannot be parsed.

        @param line: line of text expected to contain a directory entry
        @type line: str

        @return: dict
        """
        match = self.fileLinePattern.match(line)
        if match is None:
            return None
        else:
            d = match.groupdict()
            d["filename"] = d["filename"].replace(r"\ ", " ")
            d["nlinks"] = int(d["nlinks"])
            d["size"] = int(d["size"])
            if d["linktarget"]:
                d["linktarget"] = d["linktarget"].replace(r"\ ", " ")
            return d

    def addFile(self, info):
        """
        Append file information dictionary to the list of known files.

        Subclasses can override or extend this method to handle file
        information differently without affecting the parsing of data
        from the server.

        @param info: dictionary containing the parsed representation
                     of the file information
        @type info: dict
        """
        self.files.append(info)

    def unknownLine(self, line):
        """
        Deal with received lines which could not be parsed as file
        information.

        Subclasses can override this to perform any special processing
        needed.

        @param line: unparsable line as received
        @type line: str
        """
        pass


def parsePWDResponse(response):
    """
    Returns the path from a response to a PWD command.

    Responses typically look like::

        257 "/home/andrew" is current directory.

    For this example, I will return C{'/home/andrew'}.

    If I can't find the path, I return L{None}.
    """
    match = re.search('"(.*)"', response)
    if match:
        return match.groups()[0]
    else:
        return None