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
  
3444
  
3445
  
3446
  
3447
  
3448
  
3449
  
3450
  
3451
  
3452
  
3453
  
3454
  
3455
  
3456
  
3457
  
3458
  
3459
  
3460
  
3461
  
3462
  
3463
  
3464
  
3465
  
3466
  
3467
  
3468
  
3469
  
3470
  
3471
  
3472
  
3473
  
3474
  
3475
  
3476
  
3477
  
3478
  
3479
  
3480
  
3481
  
3482
  
3483
  
3484
  
3485
  
3486
  
3487
  
3488
  
3489
  
3490
  
3491
  
3492
  
3493
  
3494
  
3495
  
3496
  
3497
  
3498
  
3499
  
3500
  
3501
  
3502
  
3503
  
3504
  
3505
  
3506
  
3507
  
3508
  
3509
  
3510
  
3511
  
3512
  
3513
  
3514
  
3515
  
3516
  
3517
  
3518
  
3519
  
3520
  
3521
  
3522
  
3523
  
3524
  
3525
  
3526
  
3527
  
3528
  
3529
  
3530
  
3531
  
3532
  
3533
  
3534
  
3535
  
3536
  
3537
  
3538
  
3539
  
3540
  
3541
  
3542
  
3543
  
3544
  
3545
  
3546
  
3547
  
3548
  
3549
  
3550
  
3551
  
3552
  
3553
  
3554
  
3555
  
3556
  
3557
  
3558
  
3559
  
3560
  
3561
  
3562
  
3563
  
3564
  
3565
  
3566
  
3567
  
3568
  
3569
  
3570
  
3571
  
3572
  
3573
  
3574
  
3575
  
3576
  
3577
  
3578
  
3579
  
3580
  
3581
  
3582
  
3583
  
3584
  
3585
  
3586
  
3587
  
3588
  
3589
  
3590
  
3591
  
3592
  
3593
  
3594
  
3595
  
3596
  
3597
  
3598
  
3599
  
3600
  
3601
  
3602
  
3603
  
3604
  
3605
  
3606
  
3607
  
3608
  
3609
  
3610
  
3611
  
3612
  
3613
  
3614
  
3615
  
3616
  
3617
  
3618
  
3619
  
3620
  
3621
  
3622
  
3623
  
3624
  
3625
  
3626
  
3627
  
3628
  
3629
  
3630
  
3631
  
3632
  
3633
  
3634
  
3635
  
3636
  
3637
  
3638
  
3639
  
3640
  
3641
  
3642
  
3643
  
3644
  
3645
  
3646
  
3647
  
3648
  
3649
  
3650
  
3651
  
3652
  
3653
  
3654
  
3655
  
3656
  
3657
  
3658
  
3659
  
3660
  
3661
  
3662
  
3663
  
3664
  
3665
  
3666
  
3667
  
3668
  
3669
  
3670
  
3671
  
3672
  
3673
  
3674
  
3675
  
3676
  
3677
  
3678
  
3679
  
3680
  
3681
  
3682
  
3683
  
3684
  
3685
  
3686
  
3687
  
3688
  
3689
  
3690
  
3691
  
3692
  
3693
  
3694
  
3695
  
3696
  
3697
  
3698
  
3699
  
3700
  
3701
  
3702
  
3703
  
3704
  
3705
  
3706
  
3707
  
3708
  
3709
  
3710
  
3711
  
3712
  
3713
  
3714
  
3715
  
3716
  
3717
  
3718
  
3719
  
3720
  
3721
  
3722
  
3723
  
3724
  
3725
  
3726
  
3727
  
3728
  
3729
  
3730
  
3731
  
3732
  
3733
  
3734
  
3735
  
3736
  
3737
  
3738
  
3739
  
3740
  
3741
  
3742
  
3743
  
3744
  
3745
  
3746
  
3747
  
3748
  
3749
  
3750
  
3751
  
3752
  
3753
  
3754
  
3755
  
3756
  
3757
  
3758
  
3759
  
3760
  
3761
  
3762
  
3763
  
3764
  
3765
  
3766
  
3767
  
3768
  
3769
  
3770
  
3771
  
3772
  
3773
  
3774
  
3775
  
3776
  
3777
  
3778
  
3779
  
3780
  
3781
  
3782
  
3783
  
3784
  
3785
  
3786
  
3787
  
3788
  
3789
  
3790
  
3791
  
3792
  
3793
  
3794
  
3795
  
3796
  
3797
  
3798
  
3799
  
3800
  
3801
  
3802
  
3803
  
3804
  
3805
  
3806
  
3807
  
3808
  
3809
  
3810
  
3811
  
3812
  
3813
  
3814
  
3815
  
3816
  
3817
  
3818
  
3819
  
3820
  
3821
  
3822
  
3823
  
3824
  
3825
  
3826
  
3827
  
3828
  
3829
  
3830
  
3831
  
3832
  
3833
  
3834
  
3835
  
3836
  
3837
  
3838
  
3839
  
3840
  
3841
  
3842
  
3843
  
3844
  
3845
  
3846
  
3847
  
3848
  
3849
  
3850
  
3851
  
3852
  
3853
  
3854
  
3855
  
3856
  
3857
  
3858
  
3859
  
3860
  
3861
  
3862
  
3863
  
3864
  
3865
  
3866
  
3867
  
3868
  
3869
  
3870
  
3871
  
3872
  
3873
  
3874
  
3875
  
3876
  
3877
  
3878
  
3879
  
3880
  
3881
  
3882
  
3883
  
3884
  
3885
  
3886
  
3887
  
3888
  
3889
  
3890
  
3891
  
3892
  
3893
  
3894
  
3895
  
3896
  
3897
  
3898
  
// This is a roxen protocol module. 
// Copyright © 1997 - 2001, Roxen IS. 
 
/* 
 * FTP protocol mk 2 
 * 
 * $Id: ftp.pike,v 2.92 2004/05/17 13:17:23 mani Exp $ 
 * 
 * Henrik Grubbström <grubba@roxen.com> 
 */ 
 
/* 
 * TODO: 
 * 
 * How much is supposed to be logged? 
 */ 
 
/* 
 * Relevant RFC's: 
 * 
 * RFC 764      TELNET PROTOCOL SPECIFICATION 
 * RFC 765      FILE TRANSFER PROTOCOL 
 * RFC 959      FILE TRANSFER PROTOCOL (FTP) 
 * RFC 1123     Requirements for Internet Hosts -- Application and Support 
 * RFC 1579     Firewall-Friendly FTP 
 * RFC 1635     How to Use Anonymous FTP 
 * 
 * RFC's describing extra commands: 
 * 
 * RFC 683      FTPSRV - Tenex extension for paged files 
 * RFC 737      FTP Extension: XSEN 
 * RFC 743      FTP extension: XRSQ/XRCP 
 * RFC 775      DIRECTORY ORIENTED FTP COMMANDS 
 * RFC 949      FTP unique-named store command 
 * RFC 1639     FTP Operation Over Big Address Records (FOOBAR) 
 * RFC 2228     FTP Security Extensions 
 * RFC 2428     FTP Extensions for IPv6 and NATs 
 * 
 * IETF draft 12 Extended Directory Listing, TVFS, 
 *               and Restart Mechanism for FTP 
 * 
 * RFC's with recomendations and discussions: 
 * 
 * RFC 607      Comments on the File Transfer Protocol 
 * RFC 614      Response to RFC 607, "Comments on the File Transfer Protocol" 
 * RFC 624      Comments on the File Transfer Protocol 
 * RFC 640      Revised FTP Reply Codes 
 * RFC 691      One More Try on the FTP 
 * RFC 724      Proposed Official Standard for the 
 *              Format of ARPA Network Messages 
 * 
 * RFC's describing gateways and proxies: 
 * 
 * RFC 1415     FTP-FTAM Gateway Specification 
 * 
 * More or less obsolete RFC's: 
 * 
 * RFC 412      User FTP documentation 
 * *RFC 438     FTP server-server interaction 
 * *RFC 448     Print files in FTP 
 * *RFC 458     Mail retrieval via FTP 
 * *RFC 463     FTP comments and response to RFC 430 
 * *RFC 468     FTP data compression 
 * *RFC 475     FTP and network mail system 
 * *RFC 478     FTP server-server interaction - II 
 * *RFC 479     Use of FTP by the NIC Journal 
 * *RFC 480     Host-dependent FTP parameters 
 * *RFC 505     Two solutions to a file transfer access problem 
 * *RFC 506     FTP command naming problem 
 * *RFC 520     Memo to FTP group: Proposal for File Access Protocol 
 * *RFC 532     UCSD-CC Server-FTP facility 
 * RFC 542      File Transfer Protocol for the ARPA Network 
 * RFC 561      Standardizing Network Mail Headers 
 * *RFC 571     Tenex FTP problem 
 * *RFC 630     FTP error code usage for more reliable mail service 
 * *RFC 686     Leaving well enough alone 
 * *RFC 697     CWD Command of FTP 
 * RFC 751      SURVEY OF FTP MAIL AND MLFL 
 * RFC 754      Out-of-Net Host Addresses for Mail 
 * 
 * (RFC's marked with * are not available from http://www.roxen.com/rfc/) 
 */ 
 
 
#include <config.h> 
#include <module.h> 
#include <stat.h> 
 
//#define FTP2_DEBUG 
 
#define FTP2_XTRA_HELP ({ "Report any bugs at http://community.roxen.com/crunch/" }) 
 
#define FTP2_TIMEOUT  (5*60) 
 
// #define Query(X) conf->variables[X][VAR_VALUE] 
 
#ifdef FTP2_DEBUG 
# define DWRITE(X ...)      werror(X) 
#else 
# define DWRITE(X ...) 
#endif 
 
#if constant(thread_create) 
#define BACKEND_CLOSE(FD)   do { DWRITE("close\n"); FD->set_blocking(); call_out(FD->close, 0); FD = 0; } while(0) 
#else /* !constant(thread_create) */ 
#define BACKEND_CLOSE(FD)   do { DWRITE("close\n"); FD->set_blocking(); FD->close(); FD = 0; } while(0) 
#endif /* constant(thread_create) */ 
 
class RequestID2 
{ 
  inherit RequestID; 
 
  mapping file; 
 
#ifdef FTP2_DEBUG 
  static void trace_enter(mixed a, mixed b) 
  { 
    write("FTP: TRACE_ENTER(%O, %O)\n", a, b); 
  } 
 
  static void trace_leave(mixed a) 
  { 
    write("FTP: TRACE_LEAVE(%O)\n", a); 
  } 
#endif /* FTP2_DEBUG */ 
 
  void ready_to_receive() 
  { 
    // FIXME: Should hook the STOR reply to this function. 
  } 
 
  Configuration configuration() 
  { 
    return conf; 
  } 
 
  Stdio.File connection( ) 
  { 
    return my_fd; 
  } 
 
  void send_result(mapping|void result) 
  { 
    if (mappingp(result) && my_fd && my_fd->done) { 
      my_fd->done(result); 
      return; 
    } 
 
    error("Async sending with send_result() not supported yet.\n"); 
  } 
 
  RequestID2 clone_me() 
  { 
    return this_program(this); 
  } 
 
  void end() 
  { 
  } 
 
  constant __num = ({ 0 }); 
  int _num; 
 
  void destroy() 
  { 
#ifdef FTP_REQUESTID_DEBUG 
    report_debug("REQUESTID: Destroy request id #%d.\n", _num); 
#endif 
  } 
 
  void create(object|void m_rid) 
  { 
#ifdef FTP_REQUESTID_DEBUG 
    _num = ++__num[0]; 
    report_debug("REQUESTID: New request id #%d.\n", _num); 
#else 
    DWRITE("REQUESTID: New request id.\n"); 
#endif 
 
    if (m_rid) { 
      this_program o = this; 
      foreach(indices(m_rid), string var) { 
        if (!(< "create", "connection", "configuration", 
                "__INIT", "clone_me", "end", "ready_to_receive", 
                "send", "scan_for_query", "send_result", "misc", 
                "url_base", "set_response_header", "get_xml_data", 
                "add_response_header", "set_output_charset", 
                "adjust_for_config_path", "PrefLanguages", 
                "charset_name", "charset_function", "join_charset", 
                "output_encode", 
                "destroy", "_num", "__num">)[var]) { 
#ifdef FTP2_DEBUG 
        if (catch { 
#endif /* FTP2_DEBUG */ 
          o[var] = m_rid[var]; 
#ifdef FTP2_DEBUG 
        }) { 
            report_error("FTP2: " 
                         "Failed to copy variable %s (value:%O)\n", 
                         var, m_rid[var]); 
          } 
#endif /* FTP2_DEBUG */ 
      } 
      } 
      o["misc"] = m_rid["misc"] + ([ ]); 
    } else { 
      // Defaults... 
      client = ({ "ftp" }); 
      prot = "FTP"; 
      clientprot = "FTP"; 
      real_variables = ([]); 
      variables = FakedVariables( real_variables ); 
      misc = ([ "pref_languages" : PrefLanguages() ]); 
      cookies = ([]); 
      throttle = ([]); 
      client_var = ([]); 
      request_headers = ([]); 
 
      prestate = (<>); 
      config = (<>); 
      supports = (< "ftp", "images", "tables", >); 
      pragma = (<>); 
      rest_query = ""; 
      extra_extension = ""; 
    } 
    time = predef::time(1); 
#ifdef FTP2_DEBUG 
    misc->trace_enter = trace_enter; 
    misc->trace_leave = trace_leave; 
#endif /* FTP2_DEBUG */ 
  } 
}; 
 
class FileWrapper 
{ 
  static string convert(string s); 
 
  static private function read_cb; 
  static private function close_cb; 
  static private mixed id; 
 
  static private object f; 
  static private string data; 
  static private object ftpsession; 
 
  int is_file; 
 
  static void create(object f_, string data_, object ftpsession_) 
  { 
    f = f_; 
    data = data_; 
    ftpsession = ftpsession_; 
 
    is_file = f_->is_file; 
  } 
 
  static private void read_callback(mixed i, string s) 
  { 
    read_cb(id, convert(s)); 
    ftpsession->touch_me(); 
  } 
 
  static private void close_callback(mixed i) 
  { 
    close_cb(id); 
    if (f) { 
      BACKEND_CLOSE(f); 
    } 
    ftpsession->touch_me(); 
  } 
 
  static private void delayed_nonblocking(function w_cb) 
  { 
    string d = data; 
    data = 0; 
    f->set_nonblocking(read_callback, w_cb, close_callback); 
    if (d) { 
      read_callback(0, d); 
    } 
  } 
 
  void set_nonblocking(function r_cb, function w_cb, function c_cb) 
  { 
    read_cb = r_cb; 
    close_cb = c_cb; 
    remove_call_out(delayed_nonblocking); 
    if (r_cb) { 
      if (data) { 
        // We need to call r_cb as soon as possible, but we can't do it here 
        // and we can't enable the read_callback just yet to maintain order. 
        call_out(delayed_nonblocking, 0, w_cb); 
        f->set_nonblocking(0, w_cb, 0); 
      } else { 
        f->set_nonblocking(read_callback, w_cb, close_callback); 
      } 
    } else { 
      f->set_nonblocking(0, w_cb, 0); 
    } 
  } 
 
  void set_blocking() 
  { 
    if (data) { 
      remove_call_out(delayed_nonblocking); 
    } 
    f->set_blocking(); 
  } 
 
  void set_id(mixed i) 
  { 
    id = i; 
    f->set_id(i); 
  } 
 
  int query_fd() 
  { 
    return -1; 
  } 
 
  string read(int|void n) 
  { 
    ftpsession->touch_me(); 
    if (data) { 
      if (n) { 
        if (n < sizeof(data)) { 
          string d = data[..n-1]; 
          data = data[n..]; 
          return convert(d); 
        } else { 
          string d = data; 
          data = 0; 
          return convert(d + f->read(n - sizeof(d))); 
        } 
      } else { 
        string d = data; 
        data = 0; 
        return convert(d + f->read()); 
      } 
    } 
    return(convert(f->read(n))); 
  } 
 
  void close() 
  { 
    ftpsession->touch_me(); 
    if (f) { 
      f->set_blocking(); 
      BACKEND_CLOSE(f); 
    } 
  } 
} 
 
class ToAsciiWrapper 
{ 
  inherit FileWrapper; 
 
  int converted; 
 
  static string convert(string s) 
  { 
    converted += sizeof(s); 
    return(replace(s, ({ "\r\n", "\n", "\r" }), ({ "\r\n", "\r\n", "\r\n" }))); 
  } 
} 
 
class FromAsciiWrapper 
{ 
  inherit FileWrapper; 
 
  int converted; 
 
  static string convert(string s) 
  { 
    converted += sizeof(s); 
#ifdef __NT__ 
    // This replace shouldn't be needed, but we're paranoid. 
    return(replace(s, ({ "\r\n", "\n", "\r" }), ({ "\r\n", "\r\n", "\r\n" }))); 
#else /* !__NT__ */ 
#ifdef __MACOS__ 
    return(replace(s, ({ "\r\n", "\n", "\r" }), ({ "\r", "\r", "\r" }))); 
#else /* !__MACOS__ */ 
    return(replace(s, ({ "\r\n", "\n", "\r" }), ({ "\n", "\n", "\n" }))); 
#endif /* __MACOS__ */ 
#endif /* __NT__ */ 
  } 
} 
 
// This one is needed for touch_me() to be called as needed. 
class BinaryWrapper 
{ 
  inherit FileWrapper; 
 
  static string convert(string s) 
  { 
    return(s); 
  } 
} 
 
// EBCDIC Wrappers here. 
 
class ToEBCDICWrapper 
{ 
  inherit FileWrapper; 
 
  int converted; 
 
  static object converter = Locale.Charset.encoder("EBCDIC-US", ""); 
 
  static string convert(string s) 
  { 
    converted += sizeof(s); 
    return(converter->feed(s)->drain()); 
  } 
} 
 
class FromEBCDICWrapper 
{ 
  inherit FileWrapper; 
 
  int converted; 
 
  static object converter = Locale.Charset.decoder("EBCDIC-US"); 
 
  static string convert(string s) 
  { 
    converted += sizeof(s); 
    return(converter->feed(s)->drain()); 
  } 
} 
 
 
class PutFileWrapper 
{ 
  static int response_code = 226; 
  static string response = "Stored."; 
  static string gotdata = ""; 
  static int closed, recvd; 
  static function other_read_callback; 
 
  static object from_fd; 
  static object session; 
  static object ftpsession; 
 
  int is_file; 
 
  static void create(object from_fd_, object session_, object ftpsession_) 
  { 
    from_fd = from_fd_; 
    session = session_; 
    ftpsession = ftpsession_; 
 
    is_file = from_fd->is_file; 
  } 
 
#include <variables.h> 
 
  int bytes_received() 
  { 
    return recvd; 
  } 
 
  int close(string|void how) 
  { 
    DWRITE("FTP: PUT: close()\n"); 
    ftpsession->touch_me(); 
    if(how != "w" && !closed) { 
      ftpsession->send(response_code, ({ response })); 
      closed = 1; 
      session->conf->received += recvd; 
      session->file->len = recvd; 
      session->conf->log(session->file, session); 
      session->file = 0; 
      session->my_fd = from_fd; 
    } 
    if (how) { 
      return from_fd->close(how); 
    } else { 
      BACKEND_CLOSE(from_fd); 
      return 0; 
    } 
  } 
 
  string read(mixed ... args) 
  { 
    DWRITE("FTP: PUT: read()\n"); 
    ftpsession->touch_me(); 
    string r = from_fd->read(@args); 
    if(stringp(r)) 
      recvd += sizeof(r); 
    return r; 
  } 
 
  static mixed my_read_callback(mixed id, string data) 
  { 
    DWRITE("FTP: PUT: my_read_callback(X, \"%s\")\n", data||""); 
    ftpsession->touch_me(); 
    if(stringp(data)) 
      recvd += sizeof(data); 
    return other_read_callback(id, data); 
  } 
 
  void set_read_callback(function read_callback) 
  { 
    DWRITE("FTP: PUT: set_read_callback()\n"); 
    ftpsession->touch_me(); 
    if(read_callback) { 
      other_read_callback = read_callback; 
      from_fd->set_read_callback(my_read_callback); 
    } else 
      from_fd->set_read_callback(read_callback); 
  } 
 
  void set_nonblocking(function ... args) 
  { 
    DWRITE("FTP: PUT: set_nonblocking()\n"); 
    if(sizeof(args) && args[0]) { 
      other_read_callback = args[0]; 
      from_fd->set_nonblocking(my_read_callback, @args[1..]); 
    } else 
      from_fd->set_nonblocking(@args); 
  } 
 
  void set_blocking() 
  { 
    from_fd->set_blocking(); 
  } 
 
  void set_id(mixed id) 
  { 
    from_fd->set_id(id); 
  } 
 
  int write(string data) 
  { 
    DWRITE("FTP: PUT: write(\"%s\")\n", data||""); 
 
    ftpsession->touch_me(); 
 
    int n, code; 
    string msg; 
    gotdata += data; 
    while((n=search(gotdata, "\n"))>=0) { 
      if(3==sscanf(gotdata[..n], "HTTP/%*s %d %[^\r\n]", code, msg) 
         && code>199) { 
        if(code < 300) 
          code = 226; 
        else 
          code = 550; 
        response_code = code; 
        response = msg; 
      } 
      gotdata = gotdata[n+1..]; 
    } 
    return strlen(data); 
  } 
 
  void done(mapping result) 
  { 
    if (result->error < 300) { 
      response_code = 226; 
    } else { 
      response_code = 550; 
    } 
 
    // Cut away the code. 
    response = ((result->rettext || errors[result->error])/" ")[1..] * " "; 
    gotdata = result->data || ""; 
 
    close(); 
  } 
 
  string query_address(int|void loc) 
  { 
    return from_fd->query_address(loc); 
  } 
} 
 
 
// Simulated /usr/bin/ls pipe 
 
#define LS_FLAG_A       0x00001 
#define LS_FLAG_a       0x00002 
#define LS_FLAG_b   0x00004 
#define LS_FLAG_C       0x00008 
#define LS_FLAG_d       0x00010 
#define LS_FLAG_F       0x00020 
#define LS_FLAG_f       0x00040 
#define LS_FLAG_G       0x00080 
#define LS_FLAG_h   0x00100 
#define LS_FLAG_l       0x00200 
#define LS_FLAG_m   0x00400 
#define LS_FLAG_n       0x00800 
#define LS_FLAG_r       0x01000 
#define LS_FLAG_Q   0x02000 
#define LS_FLAG_R       0x04000 
#define LS_FLAG_S   0x08000 
#define LS_FLAG_s   0x10000 
#define LS_FLAG_t       0x20000 
#define LS_FLAG_U       0x40000 
#define LS_FLAG_v   0x80000 
 
class LS_L(static RequestID master_session, 
           static int|void flags) 
{ 
  static constant decode_mode = ({ 
    ({ S_IRUSR, S_IRUSR, 1, "r" }), 
    ({ S_IWUSR, S_IWUSR, 2, "w" }), 
    ({ S_IXUSR|S_ISUID, S_IXUSR, 3, "x" }), 
    ({ S_IXUSR|S_ISUID, S_ISUID, 3, "S" }), 
    ({ S_IXUSR|S_ISUID, S_IXUSR|S_ISUID, 3, "s" }), 
    ({ S_IRGRP, S_IRGRP, 4, "r" }), 
    ({ S_IWGRP, S_IWGRP, 5, "w" }), 
    ({ S_IXGRP|S_ISGID, S_IXGRP, 6, "x" }), 
    ({ S_IXGRP|S_ISGID, S_ISGID, 6, "S" }), 
    ({ S_IXGRP|S_ISGID, S_IXGRP|S_ISGID, 6, "s" }), 
    ({ S_IROTH, S_IROTH, 7, "r" }), 
    ({ S_IWOTH, S_IWOTH, 8, "w" }), 
    ({ S_IXOTH|S_ISVTX, S_IXOTH, 9, "x" }), 
    ({ S_IXOTH|S_ISVTX, S_ISVTX, 9, "T" }), 
    ({ S_IXOTH|S_ISVTX, S_IXOTH|S_ISVTX, 9, "t" }) 
  }); 
 
  static constant months = ({ "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
                              "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }); 
 
  static string name_from_uid(int uid) 
  { 
    User user; 
    foreach(master_session->conf->user_databases(), UserDB user_db) { 
      if (user = user_db->find_user_from_uid(uid)) { 
        return user->name(); 
      } 
    } 
    return (uid?((string)uid):"root"); 
  } 
 
  string ls_l(string file, array st) 
  { 
    DWRITE("ls_l(\"%s\")\n", file); 
 
    int mode = st[0] & 007777; 
    array(string) perm = "----------"/""; 
 
    if (st[1] < 0) { 
      perm[0] = "d"; 
    } 
 
    foreach(decode_mode, array(string|int) info) { 
      if ((mode & info[0]) == info[1]) { 
        perm[info[2]] = info[3]; 
      } 
    } 
 
    mapping lt = localtime(st[3]); 
 
    // NOTE: SiteBuilder may set st[5] and st[6] to strings. 
    string user = (string)st[5]; 
    string group = (string)st[6]; 
    if (!(flags & LS_FLAG_n)) { 
      // Use symbolic names for uid and gid. 
      if (!stringp(st[5])) { 
        user = name_from_uid(st[5]); 
      } 
 
      // FIXME: Convert st[6] to symbolic group name. 
    } 
 
    string ts; 
    int now = time(1); 
    // Half a year: 
    //   365.25*24*60*60/2 = 15778800 
    if ((st[3] <= now - 15778800) || (st[3] > now)) { 
      // Month Day  Year 
      ts = sprintf("%s %02d  %04d", 
                   months[lt->mon], lt->mday, 1900+lt->year); 
    } else { 
      // Month Day Hour:minute 
      ts = sprintf("%s %02d %02d:%02d", 
                   months[lt->mon], lt->mday, lt->hour, lt->min); 
    } 
 
    if (flags & LS_FLAG_G) { 
      // No group. 
      return sprintf("%s   1 %-10s %12d %s %s\n", perm*"", 
                     user, (st[1]<0? 512:st[1]), 
                     ts, file); 
    } else { 
      return sprintf("%s   1 %-10s %-6s %12d %s %s\n", perm*"", 
                     user, group, (st[1]<0? 512:st[1]), 
                     ts, file); 
    } 
  } 
} 
 
class LSFile 
{ 
  static inherit LS_L; 
 
  static string cwd; 
  static array(string) argv; 
  static object ftpsession; 
 
  static array(string) output_queue = ({}); 
  static int output_pos; 
  static string output_mode = "A"; 
 
  static mapping(string:array|object) stat_cache = ([]); 
 
  static object conv; 
 
  static array|object stat_file(string long, RequestID|void session) 
  { 
    array|object st = stat_cache[long]; 
    if (zero_type(st)) { 
      if (!session) { 
        session = RequestID2(master_session); 
        session->method = "DIR"; 
      } 
      long = replace(long, "//", "/"); 
      st = session->conf->stat_file(long, session); 
      stat_cache[long] = st; 
    } 
    return st; 
  } 
 
  // FIXME: Should convert output somewhere below. 
  static void output(string s) 
  { 
    if(stringp(s)) { 
      // ls is always ASCII-mode... 
      s = replace(s, "\n", "\r\n"); 
      if (conv) { 
        // EBCDIC or potentially other charsets. 
        s = conv->feed(s)->drain(); 
      } 
    } 
    output_queue += ({ s }); 
  } 
 
  static string quote_non_print(string s) 
  { 
    return(replace(s, ({ 
      "\000", "\001", "\002", "\003", "\004", "\005", "\006", "\007", 
      "\010", "\011", "\012", "\013", "\014", "\015", "\016", "\017", 
      "\200", "\201", "\202", "\203", "\204", "\205", "\206", "\207", 
      "\210", "\211", "\212", "\213", "\214", "\215", "\216", "\217", 
      "\177", 
    }), ({ 
      "\\000", "\\001", "\\002", "\\003", "\\004", "\\005", "\\006", "\\007", 
      "\\010", "\\011", "\\012", "\\013", "\\014", "\\015", "\\016", "\\017", 
      "\\200", "\\201", "\\202", "\\203", "\\204", "\\205", "\\206", "\\207", 
      "\\210", "\\211", "\\212", "\\213", "\\214", "\\215", "\\216", "\\217", 
      "\\177", 
    }))); 
  } 
 
  static string list_files(array(string) files, string|void dir) 
  { 
    dir = dir || cwd; 
 
    DWRITE("FTP: LSFile->list_files(%O, \"%s\"\n", files, dir); 
 
    if (!(flags & LS_FLAG_U)) { 
      if (flags & LS_FLAG_S) { 
        array(int) sizes = allocate(sizeof(files)); 
        int i; 
        for (i=0; i < sizeof(files); i++) { 
          array|object st = stat_file(combine_path(dir, files[i])); 
          if (st) { 
            sizes[i] = st[1]; 
          } else { 
            // Should not happen, but... 
            files -= ({ files[i] }); 
          } 
        } 
        sort(sizes, files); 
      } else if (flags & LS_FLAG_t) { 
        array(int) times = allocate(sizeof(files)); 
        int i; 
        for (i=0; i < sizeof(files); i++) { 
          array|object st = stat_file(combine_path(dir, files[i])); 
          if (st) { 
            times[i] = -st[-4]; // Note: Negative time. 
          } else { 
            // Should not happen, but... 
            files -= ({ files[i] }); 
          } 
        } 
        sort(times, files); 
      } else { 
        sort(files); 
      } 
      if (flags & LS_FLAG_r) { 
        files = reverse(files); 
      } 
    } 
 
    string res = ""; 
    int total; 
    foreach(files, string short) { 
      string long = combine_path(dir, short); 
      array|object st = stat_file(long); 
      if (st) { 
        if (flags & LS_FLAG_Q) { 
          // Enclose in quotes. 
          // Space needs to be quoted to be compatible with -m 
          short = "\"" + 
            replace(short, 
                    ({ "\n", "\r", "\\", "\"", "\'", " " }), 
                    ({ "\\n", "\\r", "\\\\", "\\\"", "\\\'", "\\020" })) + 
            "\""; 
        } 
        if (flags & LS_FLAG_F) { 
          if (st[1] < 0) { 
            // Directory 
            short += "/"; 
          } else if (st[0] & 0111) { 
            // Executable 
            short += "*"; 
          } 
        } 
        int blocks = 1; 
        if (st[1] >= 0) { 
          blocks = (st[1] + 1023)/1024; // Blocks are 1KB. 
        } 
        total += blocks; 
        if (flags & LS_FLAG_s) { 
          res += sprintf("%7d ", blocks); 
        } 
        if (flags & LS_FLAG_b) { 
          short = quote_non_print(short); 
        } 
        if (flags & LS_FLAG_l) { 
          res += ls_l(short, st); 
        } else { 
          res += short + "\n"; 
        } 
      } 
    } 
    switch (flags & (LS_FLAG_l|LS_FLAG_C|LS_FLAG_m)) { 
    case LS_FLAG_C: 
      res = sprintf("%#-79s\n", res); 
      break; 
    case LS_FLAG_m: 
      res = sprintf("%=-79s\n", (res/"\n")*", "); 
      break; 
    case LS_FLAG_l: 
      res = "total " + total + "\n" + res; 
      break; 
    default: 
      break; 
    } 
    return(res); 
  } 
 
  static ADT.Stack dir_stack = ADT.Stack(); 
  static int name_directories; 
 
  static string fix_path(string s) 
  { 
    return(combine_path(cwd, s)); 
  } 
 
  static void list_next_directory() 
  { 
    if (dir_stack->ptr) { 
      string short = dir_stack->pop(); 
      string long = fix_path(short); 
 
      if ((!sizeof(long)) || (long[-1] != '/')) { 
        long += "/"; 
      } 
      RequestID session = RequestID2(master_session); 
      session->method = "DIR"; 
 
      mixed err; 
      mapping(string:array) dir; 
      err = catch { 
        dir = session->conf->find_dir_stat(long, session); 
      }; 
 
      if (err) { 
        report_error("FTP: LSFile->list_next_directory(): " 
                     "find_dir_stat(\"%s\") failed:\n" 
                     "%s\n", long, describe_backtrace(err)); 
      } 
 
      DWRITE("FTP: LSFile->list_next_directory(): " 
             "find_dir_stat(\"%s\") => %O\n", long, dir); 
 
      // Put them in the stat cache. 
      foreach(indices(dir||({})), string f) { 
        stat_cache[combine_path(long, f)] = dir[f]; 
      } 
 
      if ((flags & LS_FLAG_a) && 
          (long != "/")) { 
        if (dir) { 
          dir[".."] = stat_file(combine_path(long,"../")); 
        } else { 
          dir = ([ "..":stat_file(combine_path(long,"../")) ]); 
        } 
      } 
      string listing = ""; 
      if (dir && sizeof(dir)) { 
        if (!(flags & LS_FLAG_A)) { 
          foreach(indices(dir), string f) { 
            if (sizeof(f) && (f[0] == '.')) { 
              m_delete(dir, f); 
            } 
          } 
        } else if (!(flags & LS_FLAG_a)) { 
          foreach(indices(dir), string f) { 
            if ((< ".", ".." >)[f]) { 
              m_delete(dir, f); 
            } 
          } 
        } 
        if (flags & LS_FLAG_R) { 
          foreach(indices(dir), string f) { 
            if (!((<".","..">)[f])) { 
              array(mixed) st = dir[f]; 
              if (st && (st[1] < 0)) { 
                if (short[-1] == '/') { 
                  dir_stack->push(short + f); 
                } else { 
                  dir_stack->push(short + "/" + f); 
                } 
              } 
            } 
          } 
        } 
        if (sizeof(dir)) { 
          listing = list_files(indices(dir), long); 
        } else if (flags & LS_FLAG_l) { 
          listing = "total 0\n"; 
        } 
      } else { 
        DWRITE("FTP: LSFile->list_next_directory(): NO FILES!\n"); 
 
        if (flags & LS_FLAG_l) { 
          listing = "total 0\n"; 
        } 
      } 
      if (name_directories) { 
        listing = "\n" + short + ":\n" + listing; 
      } 
      if (listing != "") { 
        output(listing); 
      } 
      session = RequestID2(master_session); 
      session->method = "LIST"; 
      session->not_query = long; 
      session->conf->sent = sizeof(listing); 
      session->conf->log(([ "error":200, "len":sizeof(listing) ]), session); 
    } 
    if (!dir_stack->ptr) { 
      output(0);                // End marker. 
    } else { 
      name_directories = 1; 
    } 
  } 
 
  void set_blocking() 
  { 
  } 
 
  int query_fd() 
  { 
    return -1; 
  } 
 
  static mixed id; 
 
  void set_id(mixed i) 
  { 
    id = i; 
  } 
 
  string read(int|void n, int|void not_all) 
  { 
    DWRITE("FTP: LSFile->read(%d, %d)\n", n, not_all); 
 
    ftpsession->touch_me(); 
 
    while(sizeof(output_queue) <= output_pos) { 
      // Clean anything pending in the queue. 
      output_queue = ({}); 
      output_pos = 0; 
 
      // Generate some more output... 
      list_next_directory(); 
    } 
    string s = output_queue[output_pos]; 
 
    if (s) { 
      if (n && (n < sizeof(s))) { 
        output_queue[output_pos] = s[n..]; 
        s = s[..n-1]; 
      } else { 
        output_queue[output_pos++] = 0; 
      } 
      return s; 
    } else { 
      // EOF 
      master_session->file = 0; // Avoid extra log-entry. 
      return ""; 
    } 
  } 
 
  void create(string cwd_, array(string) argv_, int flags_, 
              object session_, string output_mode_, object ftpsession_) 
  { 
    DWRITE("FTP: LSFile(\"%s\", %O, %08x, X, \"%s\")\n", 
           cwd_, argv_, flags_, output_mode_); 
 
    ::create(session_, flags_); 
 
    cwd = cwd_; 
    argv = argv_; 
    output_mode = output_mode_; 
    ftpsession = ftpsession_; 
 
    if (output_mode == "E") { 
      // EBCDIC 
      conv = Locale.Charset.encoder("EBCDIC-US", ""); 
    } 
 
    array(string) files = allocate(sizeof(argv)); 
    int n_files; 
 
    foreach(argv, string short) { 
      RequestID session = RequestID2(master_session); 
      session->method = "LIST"; 
      string long = fix_path(short); 
      array|object st = stat_file(long, session); 
      if (st) { 
        if ((< -2, -3 >)[st[1]] && 
            (!(flags & LS_FLAG_d))) { 
          // Directory 
          dir_stack->push(short); 
        } else { 
          files[n_files++] = short; 
        } 
      } else { 
        output(short + ": not found\n"); 
        session->conf->log(([ "error":404 ]), session); 
      } 
    } 
 
    DWRITE("FTP: LSFile: %d files, %d directories\n", 
           n_files, dir_stack->ptr); 
 
    if (n_files) { 
      if (n_files < sizeof(files)) { 
        files -= ({ 0 }); 
      } 
      string s = list_files(files, cwd);    // May modify dir_stack (-R) 
      output(s); 
      RequestID session = RequestID2(master_session); 
      session->not_query = Array.map(files, fix_path) * " "; 
      session->method = "LIST"; 
      session->conf->sent = sizeof(s); 
      session->conf->log(([ "error":200, "len":sizeof(s) ]), session); 
    } 
    if (dir_stack->ptr) { 
      name_directories = dir_stack->ptr && 
        ((dir_stack->ptr > 1) || n_files); 
 
      list_next_directory(); 
    } else { 
      output(0); 
    } 
  } 
} 
 
class TelnetSession { 
  static object fd; 
  static object conf; 
 
  static private mapping cb; 
  static private mixed id; 
  static private function(mixed|void:string) write_cb; 
  static private function(mixed, string:void) read_cb; 
  static private function(mixed|void:void) close_cb; 
 
  static private constant TelnetCodes = ([ 
    236:"EOF",              // End Of File 
    237:"SUSP",             // Suspend Process 
    238:"ABORT",    // Abort Process 
    239:"EOR",              // End Of Record 
 
    // The following ones are specified in RFC 959: 
    240:"SE",               // Subnegotiation End 
    241:"NOP",              // No Operation 
    242:"DM",               // Data Mark 
    243:"BRK",              // Break 
    244:"IP",               // Interrupt Process 
    245:"AO",               // Abort Output 
    246:"AYT",              // Are You There 
    247:"EC",               // Erase Character 
    248:"EL",               // Erase Line 
    249:"GA",               // Go Ahead 
    250:"SB",               // Subnegotiation 
    251:"WILL",             // Desire to begin/confirmation of option 
    252:"WON'T",    // Refusal to begin/continue option 
    253:"DO",               // Request to begin/confirmation of option 
    254:"DON'T",    // Demand/confirmation of stop of option 
    255:"IAC",              // Interpret As Command 
  ]); 
 
  // Some prototypes needed by Pike 0.5 
  static private void got_data(mixed ignored, string s); 
  static private void send_data(); 
  static private void got_oob(mixed ignored, string s); 
 
  void set_write_callback(function(mixed|void:string) w_cb) 
  { 
    if (fd) { 
      write_cb = w_cb; 
      fd->set_nonblocking(got_data, w_cb && send_data, close_cb, got_oob); 
    } 
  } 
 
  static private string to_send = ""; 
  static private void send(string s) 
  { 
    to_send += s; 
  } 
 
  static private void send_data() 
  { 
    if (!sizeof(to_send)) { 
      to_send = write_cb(id); 
    } 
    if (fd) { 
      if (!to_send) { 
        // Support for delayed close. 
        BACKEND_CLOSE(fd); 
      } else if (sizeof(to_send)) { 
        int n = fd->write(to_send); 
 
        if (n >= 0) { 
          conf->hsent += n; 
 
          to_send = to_send[n..]; 
 
          if (sizeof(to_send)) { 
            fd->set_write_callback(send_data); 
          } 
        } else { 
          // Error. 
          DWRITE("TELNET: write failed: errno:%d\n", fd->errno()); 
          BACKEND_CLOSE(fd); 
        } 
      } else { 
        // Nothing to send for the moment. 
 
        // FIXME: Is this the correct use? 
        fd->set_write_callback(0); 
 
        report_warning("FTP2: Write callback with nothing to send.\n"); 
      } 
    } else { 
      report_error("FTP2: Write callback with no fd.\n"); 
      destruct(); 
    } 
  } 
 
  static private mapping(string:function) default_cb = ([ 
    "BRK":lambda() { 
            if(fd) { 
              fd->close(); 
              fd = 0; 
            } 
            destruct(); 
            throw(0); 
          }, 
    "AYT":lambda() { 
            send("\377\361");       // NOP 
          }, 
    "WILL":lambda(int code) { 
              send(sprintf("\377\376%c", code));    // DON'T xxx 
           }, 
    "DO":lambda(int code) { 
           send(sprintf("\377\374%c", code));       // WON'T xxx 
         }, 
  ]); 
 
  static private int sync = 0; 
 
  static private void got_oob(mixed ignored, string s) 
  { 
    DWRITE("TELNET: got_oob(\"%s\")\n", s); 
 
    sync = sync || (s == "\377"); 
    if (cb["URG"]) { 
      cb["URG"](id, s); 
    } 
  } 
 
  static private string rest = ""; 
  static private void got_data(mixed ignored, string s) 
  { 
    DWRITE("TELNET: got_data(\"%s\")\n", s); 
 
    if (sizeof(s) && (s[0] == 242)) { 
      DWRITE("TELNET: Data Mark\n"); 
      // Data Mark handing. 
      s = s[1..]; 
      sync = 0; 
    } 
 
    // A single read() can contain multiple or partial commands 
    // RFC 1123 4.1.2.10 
 
    array lines = s/"\r\n"; 
 
    // Censor the raw string. 
    s = sprintf("string(%d bytes)", sizeof(s)); 
 
    int lineno; 
    for(lineno = 0; lineno < sizeof(lines); lineno++) { 
      string line = lines[lineno]; 
      if (has_value(line, "\377")) { 
        array a = line / "\377"; 
 
        string parsed_line = a[0]; 
        int i; 
        for (i=1; i < sizeof(a); i++) { 
          string part = a[i]; 
          if (sizeof(part)) { 
            string name = TelnetCodes[part[0]]; 
 
            DWRITE("TELNET: Code %s\n", name || "Unknown"); 
 
            int j; 
            function fun; 
            switch (name) { 
            case 0: 
              // FIXME: Should probably have a warning here. 
              break; 
            default: 
              if (fun = (cb[name] || default_cb[name])) { 
                mixed err = catch { 
                  fun(); 
                }; 
                if (err) { 
                  throw(err); 
                } else if (!zero_type(err)) { 
                  // We were just destructed. 
                  return; 
                } 
              } 
              a[i] = a[i][1..]; 
              break; 
            case "EC":  // Erase Character 
              for (j=i; j--;) { 
                if (sizeof(a[j])) { 
                  a[j] = a[j][..sizeof(a[j])-2]; 
                  break; 
                } 
              } 
              a[i] = a[i][1..]; 
              break; 
            case "EL":  // Erase Line 
              for (j=0; j < i; j++) { 
                a[j] = ""; 
              } 
              a[i] = a[i][1..]; 
              break; 
            case "WILL": 
            case "WON'T": 
            case "DO": 
            case "DON'T": 
              if (fun = (cb[name] || default_cb[name])) { 
                fun(a[i][1]); 
              } 
              a[i] = a[i][2..]; 
              break; 
            case "DM":  // Data Mark 
              if (sync) { 
                for (j=0; j < i; j++) { 
                  a[j] = ""; 
                } 
              } 
              a[i] = a[i][1..]; 
              sync = 0; 
              break; 
            } 
          } else { 
            a[i] = "\377"; 
            i++; 
          } 
        } 
        line = a * ""; 
      } 
      if (!lineno) { 
        line = rest + line; 
      } 
      if (lineno < (sizeof(lines)-1)) { 
        if ((!sync) && read_cb) { 
          DWRITE("TELNET: Calling read_callback(X, \"%s\")\n", line); 
          read_cb(id, line); 
        } 
      } else { 
        DWRITE("TELNET: Partial line is \"%s\"\n", line); 
        rest = line; 
      } 
    } 
  } 
 
  void create(object f, 
              function(mixed,string:void) r_cb, 
              function(mixed|void:string) w_cb, 
              function(mixed|void:void) c_cb, 
              mapping callbacks, mixed|void new_id) 
  { 
    fd = f; 
    cb = callbacks; 
 
    read_cb = r_cb; 
    write_cb = w_cb; 
    close_cb = c_cb; 
    id = new_id; 
 
    fd->set_nonblocking(got_data, w_cb && send_data, close_cb, got_oob); 
  } 
}; 
 
class FTPSession 
{ 
  // However, a server-FTP MUST be capable of 
  // accepting and refusing Telnet negotiations (i.e., sending 
  // DON'T/WON'T). RFC 1123 4.1.2.12 
 
  inherit TelnetSession; 
 
  inherit "roxenlib"; 
 
  static private constant cmd_help = ([ 
    // FTP commands in reverse RFC order. 
 
    // The following is a command suggested by the author of ncftp. 
    "CLNT":"<sp> <client-name> <sp> <client-version> " 
    "[<sp> <optional platform info>] (Set client name)", 
 
    // The following are in 
    // "Extended Directory Listing, TVFS, and Restart Mechanism for FTP" 
    // IETF draft 4. 
    "FEAT":"(Feature list)", 
    "MDTM":"<sp> path-name (Modification time)", 
    "SIZE":"<sp> path-name (Size)", 
    "MLST":"<sp> path-name (Machine Processing List File)", 
    "MLSD":"<sp> path-name (Machine Processing List Directory)", 
    "OPTS":"<sp> command <sp> options (Set Command-specific Options)", 
 
    // These are from RFC 2428 
    "EPRT":"<sp> <d>net-prt<d>net-addr<d>tcp-port<d> (Extended Address Port)", 
    "EPSV":"[<sp> net-prt|ALL] (Extended Address Passive Mode)", 
 
    // These are from RFC 2228 (FTP Security Extensions) 
    "AUTH":"security-mechanism (Authentication/Security Mechanism)", 
    "ADAT":"security-data (Authentication/Security Data)", 
    "PBSZ":"<sp> size (Protection Buffer SiZe)", 
    "PROT":"<sp> [ C | S | E | P ] (Data Channel Protection Level)", 
    "CCC":"(Clear Command Channel)", 
    "MIC":"command (Integrity Protected Command)", 
    "CONF":"command (Confidentiality Protected Command)", 
    "ENC":"command (Privacy Protected Command)", 
 
    // These are in RFC 1639 
    "LPRT":"<sp> <long-host-port> (Long Port)", 
    "LPSV":"(Long Passive)", 
 
    // Commands in the order from RFC 959 
 
    // Login 
    "USER":"<sp> username (Change user)", 
    "PASS":"<sp> password (Change password)", 
    "ACCT":"<sp> <account-information> (Account)", 
    "CWD":"[ <sp> directory-name ] (Change working directory)", 
    "CDUP":"(Change to parent directory)", 
    "SMNT":"<sp> <pathname> (Structure mount)", 
    // Logout 
    "REIN":"(Reinitialize)", 
    "QUIT":"(Terminate service)", 
    // Transfer parameters 
    "PORT":"<sp> b0, b1, b2, b3, b4 (Set port IP and number)", 
    "PASV":"(Set server in passive mode)", 
    "TYPE":"<sp> [ A | E | I | L ] (Ascii, Ebcdic, Image, Local)", 
    "STRU":"<sp> <structure-code> (File structure)", 
    "MODE":"<sp> <mode-code> (Transfer mode)", 
    // File action commands 
    "ALLO":"<sp> <decimal-integer> [<sp> R <sp> <decimal-integer>]" 
    " (Allocate space for file)", 
    "REST":"<sp> marker (Set restart marker)", 
    "STOR":"<sp> file-name (Store file)", 
    "STOU":"(Store file with unique name)", 
    "RETR":"<sp> file-name (Retreive file)", 
    "LIST":"[ <sp> <pathname> ] (List directory)", 
    "NLST":"[ <sp> <pathname> ] (List directory)", 
    "APPE":"<sp> <pathname> (Append file)", 
    "RNFR":"<sp> <pathname> (Rename from)", 
    "RNTO":"<sp> <pathname> (Rename to)", 
    "DELE":"<sp> file-name (Delete file)", 
    "RMD":"<sp> <pathname> (Remove directory)", 
    "MKD":"<sp> <pathname> (Make directory)", 
    "PWD":"(Return current directory)", 
    "ABOR":"(Abort current transmission)", 
    // Informational commands 
    "SYST":"(Get type of operating system)", 
    "STAT":"[ <sp> <pathname> ] (Status for server/file)", 
    "HELP":"[ <sp> <string> ] (Give help)", 
    // Miscellaneous commands 
    "SITE":"<sp> <string> (Site parameters)",   // Has separate help 
    "NOOP":"(No operation)", 
 
    // Old "Experimental commands" 
    // These are in RFC 775 
    // Required by RFC 1123 4.1.3.1 
    "XMKD":"<sp> path-name (Make directory)", 
    "XRMD":"<sp> path-name (Remove directory)", 
    "XPWD":"(Return current directory)", 
    "XCWD":"[ <sp> directory-name ] (Change working directory)", 
    "XCUP":"(Change to parent directory)", 
 
    // These are in RFC 765 but not in RFC 959 
    "MAIL":"[<sp> <recipient name>] (Mail to user)", 
    "MSND":"[<sp> <recipient name>] (Mail send to terminal)", 
    "MSOM":"[<sp> <recipient name>] (Mail send to terminal or mailbox)", 
    "MSAM":"[<sp> <recipient name>] (Mail send to terminal and mailbox)", 
    "MRSQ":"[<sp> <scheme>] (Mail recipient scheme question)", 
    "MRCP":"<sp> <recipient name> (Mail recipient)", 
 
    // These are in RFC 743 
    "XRSQ":"[<sp> <scheme>] (Scheme selection)", 
    "XRCP":"<sp> <recipient name> (Recipient specification)", 
 
    // These are in RFC 737 
    "XSEN":"[<sp> <recipient name>] (Send to terminal)", 
    "XSEM":"[<sp> <recipient name>] (Send, mail if can\'t)", 
    "XMAS":"[<sp> <recipient name>] (Mail and send)", 
 
    // These are in RFC 542 
    "BYE":"(Logout)", 
    "BYTE":"<sp> <bits> (Byte size)", 
    "SOCK":"<sp> host-socket (Data socket)", 
 
    // This one is referenced in a lot of old RFCs 
    "MLFL":"(Mail file)", 
  ]); 
 
  static private constant site_help = ([ 
    "CHMOD":"<sp> mode <sp> file", 
    "UMASK":"<sp> mode", 
    "PRESTATE":"<sp> prestate", 
  ]); 
 
  static private constant modes = ([ 
    "A":"ASCII", 
    "E":"EBCDIC", 
    "I":"BINARY", 
    "L":"LOCAL", 
  ]); 
 
  static private int time_touch = time(); 
 
  static private ADT.Queue to_send = ADT.Queue(); 
 
  static private int end_marker = 0; 
 
  void touch_me() 
  { 
    time_touch = time(); 
  } 
 
  static private string write_cb() 
  { 
    touch_me(); 
 
    if (to_send->is_empty()) { 
 
      DWRITE("FTP2: write_cb(): Empty send queue.\n"); 
 
      ::set_write_callback(0); 
      if (end_marker) { 
        DWRITE("FTP2: write_cb(): Sending EOF.\n"); 
        return(0);  // Mark EOF 
      } 
      DWRITE("FTP2: write_cb(): Sending \"\"\n"); 
      return("");       // Shouldn't happen, but... 
    } else { 
      string s = to_send->get(); 
 
      DWRITE("FTP2: write_cb(): Sending \"%s\"\n", s); 
 
      if ((to_send->is_empty()) && (!end_marker)) { 
        ::set_write_callback(0); 
      } else { 
        ::set_write_callback(write_cb); 
      } 
      return(s); 
    } 
  } 
 
  void send(int code, array(string) data, int|void enumerate_all) 
  { 
    DWRITE("FTP2: send(%d, %O)\n", code, data); 
 
    if (!data || end_marker) { 
      end_marker = 1; 
      ::set_write_callback(write_cb); 
      return; 
    } 
 
    string s; 
    int i; 
    if (sizeof(data) > 1) { 
      data[0] = sprintf("%03d-%s\r\n", code, data[i]); 
      for (i = sizeof(data)-1; --i; ) { 
        if (enumerate_all) { 
          data[i] = sprintf("%03d-%s\r\n", code, data[i]); 
        } else { 
          data[i] = " " + data[i] + "\r\n"; 
        } 
      } 
    } 
    data[sizeof(data)-1] = sprintf("%03d %s\r\n", code, data[sizeof(data)-1]); 
    s = data * ""; 
 
    if (sizeof(s)) { 
      if (to_send->is_empty()) { 
        to_send->put(s); 
        ::set_write_callback(write_cb); 
      } else { 
        to_send->put(s); 
      } 
    } else { 
      DWRITE("FTP2: send(): Nothing to send!\n"); 
    } 
  } 
 
  static private RequestID master_session; 
 
  static private string dataport_addr; 
  static private int dataport_port; 
 
  static private string mode = "A"; 
 
  static private string cwd = "/"; 
 
  static private User auth_user; 
  // Authenticated user. 
 
  static private string user; 
  static private string password; 
  static private int logged_in; 
 
  static private object curr_pipe; 
  static private int restart_point; 
 
  static private multiset|int allowed_shells = 0; 
 
  // On a multihomed server host, the default data transfer port 
  // (L-1) MUST be associated with the same local IP address as 
  // the corresponding control connection to port L. 
  // RFC 1123 4.1.2.12 
  string local_addr; 
  int local_port; 
 
  // The listen port object 
  core.Protocol port_obj; 
 
  /* 
   * Misc 
   */ 
 
  static private int check_shell(string shell) 
  { 
    // FIXME: Should the shell database be protocol specific or 
    // virtual-server specific? 
    if (port_obj->query_option("shells") != "") { 
      // FIXME: Hmm, the cache will probably be empty almost always 
      // since it's part of the FTPsession object. 
      // Oh, well, shouldn't matter much unless you have *lots* of 
      // shells. 
      //      /grubba 1998-05-21 
      if (!allowed_shells) { 
        object(Stdio.File) file = Stdio.File(); 
 
        if (file->open(port_obj->query_option("shells"), "r")) { 
          allowed_shells = 
            aggregate_multiset(@(Array.map(file->read(0x7fffffff)/"\n", 
                                           lambda(string line) { 
                                             return(((((line/"#")[0])/"") - 
                                                     ({" ", "\t"}))*""); 
                                           } )-({""}))); 
          DWRITE("ftp.pike: allowed_shells: %O\n", allowed_shells); 
        } else { 
          report_debug("ftp.pike: Failed to open shell database (%O)\n", 
                       port_obj->query_option("shells")); 
          return 0; 
        } 
      } 
      return(allowed_shells[shell]); 
    } 
    return 1; 
  } 
 
  static private string fix_path(string s) 
  { 
    if (!sizeof(s)) { 
      if (cwd[-1] == '/') { 
        return(cwd); 
      } else { 
        return(cwd + "/"); 
      } 
    } else if (s[0] == '~') { 
      return(combine_path("/", s)); 
    } else if (s[0] == '/') { 
      return(simplify_path(s)); 
    } else { 
      return(combine_path(cwd, s)); 
    } 
  } 
 
  /* 
   * PASV handling 
   */ 
  static private object pasv_port; 
  static private function(object, mixed:void) pasv_callback; 
  static private mixed pasv_args; 
  static private array(object) pasv_accepted = ({}); 
 
  void pasv_accept_callback(mixed id) 
  { 
    DWRITE("FTP: pasv_accept_callback(%O)...\n", id); 
    touch_me(); 
 
    if(pasv_port) { 
      object fd = pasv_port->accept(); 
      if(fd) { 
        // On a multihomed server host, the default data transfer port 
        // (L-1) MUST be associated with the same local IP address as 
        // the corresponding control connection to port L. 
        // RFC 1123 4.1.2.12 
 
        array(string) remote = (fd->query_address()||"? ?")/" "; 
#ifdef FD_DEBUG 
      mark_fd(fd->query_fd(), 
                "ftp communication: -> "+remote[0]+":"+remote[1]); 
#endif 
      if (use_ssl) { 
          fd = SSL.sslfile(fd, port_obj->ctx); 
          DWRITE("FTP: Created an sslfile: %O\n", fd); 
        } 
        if(pasv_callback) { 
          pasv_callback(fd, "", @pasv_args); 
          pasv_callback = 0; 
        } else { 
          pasv_accepted += ({ fd }); 
        } 
      } 
    } 
  } 
 
  static private void ftp_async_accept(function(object,mixed ...:void) fun, 
                                       mixed ... args) 
  { 
    DWRITE("FTP: async_accept(%O, %@O)...\n", fun, args); 
    touch_me(); 
 
    if (sizeof(pasv_accepted)) { 
      fun(pasv_accepted[0], "", @args); 
      pasv_accepted = pasv_accepted[1..]; 
    } else { 
      pasv_callback = fun; 
      pasv_args = args; 
    } 
  } 
 
  /* 
   * PORT handling 
   */ 
 
  static private void ftp_async_connect(function(object,string,mixed ...:void) fun, 
                                        mixed ... args) 
  { 
    DWRITE("FTP: async_connect(%O, %@O)...\n", fun, args); 
 
    // More or less copied from socket.pike 
 
    if (!dataport_addr) { 
      DWRITE("FTP: No dataport specified.\n"); 
      fun(0, "", @args); 
      return; 
    } 
 
    object(Stdio.File) f = Stdio.File(); 
 
    // FIXME: Race-condition: open_socket() for other connections will fail 
    //        until the socket has been connected. 
 
    object privs; 
    if(local_port-1 < 1024 && geteuid()) 
      privs = Privs("FTP: Opening the data connection on " + local_addr + 
                    ":" + (local_port-1) + "."); 
 
    if(!f->open_socket(local_port-1, local_addr)) 
    { 
      privs = 0; 
      DWRITE("FTP: socket(%d, %O) failed. Trying with any port.\n", 
             local_port-1, local_addr); 
 
      if(!f->open_socket(0, local_addr)) 
      { 
        DWRITE("FTP: socket(0, %O) failed. " 
               "Trying with any port, any ip.\n", local_addr); 
        if (!f->open_socket()) { 
          DWRITE("FTP: socket() failed. Out of sockets?\n"); 
          fun(0, 0, @args); 
          destruct(f); 
          return; 
        } 
      } 
    } 
    privs = 0; 
 
    Stdio.File raw_connection = f; 
 
    if (use_ssl) { 
      f = (object)SSL.sslfile(f, port_obj->ctx, 1, 0); 
    } 
 
    f->set_nonblocking(lambda(mixed ignored, string data) { 
                         DWRITE("FTP: async_connect ok. Got data.\n"); 
                         f->set_nonblocking(0,0,0,0,0); 
                         fun(f, data, @args); 
                       }, 
                       lambda(mixed ignored) { 
                         DWRITE("FTP: async_connect ok.\n"); 
                         f->set_nonblocking(0,0,0,0,0); 
                         fun(f, "", @args); 
                       }, 
                       lambda(mixed ignored) { 
                         DWRITE("FTP: connect_and_send failed\n"); 
                         destruct(f); 
                         fun(0, 0, @args); 
                       }, 
                       lambda(mixed ignored) { 
                         DWRITE("FTP: connect_and_send failed\n"); 
                         destruct(f); 
                         fun(0, 0, @args); 
                       }); 
 
#ifdef FD_DEBUG 
    mark_fd(raw_connection->query_fd(), 
            sprintf("ftp communication: %s:%d -> %s:%d", 
                    local_addr, local_port - 1, 
                    dataport_addr, dataport_port)); 
#endif 
 
    if(catch(raw_connection->connect(dataport_addr, dataport_port))) { 
      DWRITE("FTP: Illegal internet address in connect in async comm.\n"); 
      destruct(f); 
      fun(0, 0, @args); 
      return; 
    } 
  } 
 
  /* 
   * Data connection handling 
   */ 
  static private void send_done_callback( object fd, object session, 
                                          int amount ) 
  { 
    DWRITE("FTP: send_done_callback()\n"); 
 
    if(fd) 
    { 
      //DWRITE("FTP: fd: %O: %O\n", fd, mkmapping(indices(fd), values(fd))); 
      if (fd->set_blocking) { 
        fd->set_blocking();       // Force close() to flush any buffers. 
      } 
      call_out(fd->close, 0); 
      fd = 0; 
      //BACKEND_CLOSE(fd); 
    } 
    curr_pipe = 0; 
 
    if (session && session->file) { 
      session->file->len = amount; 
      session->conf->log(session->file, session); 
      session->file = 0; 
    } 
 
    send(226, ({ "Transfer complete." })); 
  } 
 
  static private mapping|array|object stat_file(string fname, 
                                                object|void session) 
  { 
    mapping file; 
 
    if (!session) { 
      session = RequestID2(master_session); 
      session->method = "STAT"; 
    } 
 
    session->not_query = fname; 
 
    foreach(conf->first_modules(), function funp) { 
      if ((file = funp(session))) { 
        break; 
      } 
    } 
 
    if (!file) { 
      fname = replace(fname, "//", "/"); 
      return(conf->stat_file(fname, session)); 
    } 
    return(file); 
  } 
 
  static private int expect_argument(string cmd, string args) 
  { 
    if ((< "", 0 >)[args]) { 
      send(504, ({ sprintf("Syntax: %s %s", cmd, cmd_help[cmd]) })); 
      return 0; 
    } 
    return 1; 
  } 
 
  static private void send_error(string cmd, string f, mapping file, 
                                 object session) 
  { 
    switch(file && file->error) { 
    case 301: 
    case 302: 
      if (file->extra_heads && file->extra_heads->Location) { 
        send(504, ({ sprintf("'%s': %s: Redirect to %O.", 
                             cmd, f, file->extra_heads->Location) })); 
      } else { 
        send(504, ({ sprintf("'%s': %s: Redirect.", cmd, f) })); 
      } 
      break; 
    case 401: 
      send(530, ({ sprintf("'%s': %s: Access denied.", 
                           cmd, f) })); 
      break; 
    case 403: 
      send(451, ({ sprintf("'%s': %s: Forbidden.", 
                           cmd, f) })); 
      break; 
    case 405: 
      send(550, ({ sprintf("'%s': %s: Method not allowed.", 
                           cmd, f) })); 
      break; 
    case 500: 
      send(451, ({ sprintf("'%s': Requested action aborted: " 
                           "local error in processing.", cmd) })); 
      break; 
    default: 
      if (!file) { 
        file = ([ "error":404 ]); 
      } 
      send(550, ({ sprintf("'%s': %s: No such file or directory.", 
                           cmd, f) })); 
      break; 
    } 
    session->conf->sent = file->len; 
    session->conf->log(file, session); 
  } 
 
  static private int open_file(string fname, object session, string cmd) 
  { 
    object|array|mapping file; 
 
    file = stat_file(fname, session); 
 
    if (objectp(file) || arrayp(file)) { 
      array|object st = file; 
      file = 0; 
      if (st && (st[1] < 0) && !((<"RMD", "XRMD", "CHMOD">)[cmd])) { 
        send(550, ({ sprintf("%s: not a plain file.", fname) })); 
        return 0; 
      } 
      mixed err; 
      if ((err = catch(file = conf->get_file(session)))) { 
        report_error("FTP: Error opening file \"%s\"\n" 
                     "%s\n", fname, describe_backtrace(err)); 
        send(550, ({ sprintf("%s: Error, can't open file.", fname) })); 
        return 0; 
      } 
    } else if ((< "STOR", "APPE", "MKD", "XMKD", "MOVE" >)[cmd]) { 
      mixed err; 
      if ((err = catch(file = conf->get_file(session)))) { 
        report_error("FTP: Error opening file \"%s\"\n" 
                     "%s\n", fname, describe_backtrace(err)); 
        send(550, ({ sprintf("%s: Error, can't open file.", fname) })); 
        return 0; 
      } 
    } 
 
    session->file = file; 
 
    if (!file || (file->error && (file->error >= 300))) { 
      DWRITE("FTP: open_file(\"%s\") failed: %O\n", fname, file); 
      send_error(cmd, fname, file, session); 
      return 0; 
    } 
 
    //  If data is a wide string we flatten it according to the charset 
    //  preferences in the current ID object. 
    if (file->data && String.width(file->data) > 8) 
      file->data = session->output_encode(file->data, 0)[1]; 
 
    file->full_path = fname; 
    file->request_start = time(1); 
 
    if (!file->len) { 
      if (file->data) { 
        file->len = sizeof(file->data); 
      } 
      if (objectp(file->file)) { 
        file->len += file->file->stat()[1]; 
      } 
    } 
 
    return 1; 
  } 
 
  static private void connected_to_send(object fd, string ignored, 
                                        mapping file, object session) 
  { 
    DWRITE("FTP: connected_to_send(X, %O, %O, X)\n", ignored, file); 
 
    touch_me(); 
 
    if(!file->len) 
      file->len = file->data?(stringp(file->data)?strlen(file->data):0):0; 
 
    if (!file->mode) { 
      file->mode = mode; 
    } 
 
    if(fd) 
    { 
      if (file->len) { 
        send(150, ({ sprintf("Opening %s data connection for %s (%d bytes).", 
                             modes[file->mode], file->full_path, file->len) })); 
      } else { 
        send(150, ({ sprintf("Opening %s mode data connection for %s", 
                             modes[file->mode], file->full_path) })); 
      } 
    } 
    else 
    { 
      send(425, ({ "Can't build data connect: Connection refused." })); 
      return; 
    } 
    switch(file->mode) { 
    case "A": 
      if (file->data) { 
        file->data = replace(file->data, 
                             ({ "\r\n", "\n",   "\r" }), 
                             ({ "\r\n", "\r\n", "\r\n" })); 
      } 
      if(objectp(file->file) && file->file->set_nonblocking) 
      { 
        // The list_stream object doesn't support nonblocking I/O, 
        // but converts to ASCII anyway, so we don't have to do 
        // anything about it. 
        file->file = ToAsciiWrapper(file->file, 0, this); 
      } 
      break; 
    case "E": 
      // EBCDIC handling here. 
      if (file->data) { 
        object conv = Locale.Charset.encoder("EBCDIC-US", ""); 
        file->data = conv->feed(file->data)->drain(); 
      } 
      if(objectp(file->file) && file->file->set_nonblocking) 
      { 
        // The list_stream object doesn't support nonblocking I/O, 
        // but converts to ASCII anyway, so we don't have to do 
        // anything about it. 
        // But EBCDIC doen't work... 
        file->file = ToEBCDICWrapper(file->file, 0, this); 
      } 
      break; 
    default: 
      // "I" and "L" 
      // Binary -- no conversion needed. 
      if (objectp(file->file) && file->file->set_nonblocking) { 
        file->file = BinaryWrapper(file->file, 0, this); 
      } 
      break; 
    } 
 
    object throttler=session->throttler; 
    object pipe; 
    pipe = core.get_shuffler( fd ); 
    if( conf ) 
      conf->connection_add( this, pipe ); 
 
    if( throttler || conf->throttler ) 
      pipe->set_throttler( throttler || conf->throttler ); 
 
    pipe->set_done_callback( 
      lambda( Shuffler.Shuffle r, int reason ) { 
        send_done_callback( fd, session, r->sent_data() ); 
      } ); 
    master_session->file = session->file = file; 
    if(stringp(file->data)) { 
      pipe->add_source(file->data,0,strlen(file->data)); 
    } 
    if(file->file) { 
      int off; 
      file->file->set_blocking(); 
      catch( off = file->tell() ); 
      pipe->add_source( file->file, max(off,0),     (file->len||-1) ); 
    } 
    pipe->start(); 
    curr_pipe = pipe; 
  } 
 
  static private void connected_to_receive(object fd, string data, string args) 
  { 
    DWRITE("FTP: connected_to_receive(X, %O, %O)\n", data, args); 
 
    touch_me(); 
 
    if (fd) { 
      send(150, ({ sprintf("Opening %s mode data connection for %s.", 
                           modes[mode], args) })); 
    } else { 
      send(425, ({ "Can't build data connect: Connection refused." })); 
      return; 
    } 
 
    data = data && sizeof(data) && data; 
 
    switch(mode) { 
    case "A": 
      fd = FromAsciiWrapper(fd, data, this); 
      break; 
    case "E": 
      fd = FromEBCDICWrapper(fd, data, this); 
      return; 
    default:        // "I" and "L" 
      // Binary, no need to do anything. 
      fd = BinaryWrapper(fd, data, this); 
      break; 
    } 
 
    object session = RequestID2(master_session); 
    session->method = "PUT"; 
    session->my_fd = PutFileWrapper(fd, session, this); 
    session->misc->len = 0x7fffffff; 
 
    if (open_file(args, session, "STOR")) { 
      if (!(session->file->pipe)) { 
        if (fd) { 
          BACKEND_CLOSE(fd); 
        } 
        switch(session->file->error) { 
        case 401: 
          send(530, ({ sprintf("%s: Need account for storing files.", args)})); 
          break; 
        case 413: 
          send(550, ({ sprintf("%s: Quota exceeded.", args) })); 
          break; 
        case 501: 
          send(502, ({ sprintf("%s: Command not implemented.", args) })); 
          break; 
        default: 
          send(550, ({ sprintf("%s: Error opening file.", args) })); 
          break; 
        } 
        session->conf->sent = session->file->len; 
        session->conf->log(session->file, session); 
        return; 
      } 
      master_session->file = session->file; 
    } else { 
      // Error message has already been sent. 
      if (fd) { 
        BACKEND_CLOSE(fd); 
      } 
    } 
  } 
 
  static private void discard_data_connection() { 
    if(pasv_port && sizeof(pasv_accepted)) 
      pasv_accepted = pasv_accepted[1..]; 
  } 
 
  static private void connect_and_send(mapping file, object session) 
  { 
    DWRITE("FTP: connect_and_send(%O)\n", file); 
 
    if (pasv_port) { 
      ftp_async_accept(connected_to_send, file, session); 
    } else { 
      ftp_async_connect(connected_to_send, file, session); 
    } 
  } 
 
  static private void connect_and_receive(string arg) 
  { 
    DWRITE("FTP: connect_and_receive(\"%s\")\n", arg); 
 
    if (pasv_port) { 
      ftp_async_accept(connected_to_receive, arg); 
    } else { 
      ftp_async_connect(connected_to_receive, arg); 
    } 
  } 
 
  /* 
   * Command-line simulation 
   */ 
 
  // NOTE: base is modified destructably! 
  array(string) my_combine_path_array(array(string) base, string part) 
  { 
    if ((part == ".") || (part == "")) { 
      if ((part == "") && (!sizeof(base))) { 
        return(({""})); 
      } else { 
        return(base); 
      } 
    } else if ((part == "..") && sizeof(base) && 
               (base[-1] != "..") && (base[-1] != "")) { 
      base[-1] = part; 
      return(base); 
    } else { 
      return(base + ({ part })); 
    } 
  } 
 
  static private string my_combine_path(string base, string part) 
  { 
    if ((sizeof(part) && (part[0] == '/')) || 
        (sizeof(base) && (base[0] == '/'))) { 
      return(combine_path(base, part)); 
    } 
    // Combine two relative paths. 
    int i; 
    array(string) arr = ((base/"/") + (part/"/")) - ({ ".", "" }); 
    foreach(arr, string part) { 
      if ((part == "..") && i && (arr[i-1] != "..")) { 
        i--; 
      } else { 
        arr[i++] = part; 
      } 
    } 
    if (i) { 
      return(arr[..i-1]*"/"); 
    } else { 
      return(""); 
    } 
  } 
 
  static private constant IFS = (<" ", "\t">); 
  static private constant Quote = (< "\'", "\"", "\`", "\\" >); 
  static private constant Specials = IFS|Quote; 
 
  static private array(string) split_command_line(string cmdline) 
  { 
    // Check if we need to handle quoting at all... 
    int need_quoting; 
    foreach(indices(Quote), string c) { 
      if (need_quoting = (search(cmdline, c) >= 0)) { 
        break; 
      } 
    } 
    if (!need_quoting) { 
      // The easy case... 
      return ((replace(cmdline, "\t", " ")/" ") - ({ "" })); 
    } 
 
    array(string) res = ({}); 
    string arg = 0; 
    int argstart = 0; 
    int i; 
    for(i=0; i < sizeof(cmdline); i++) { 
      string c; 
      if (Specials[c = cmdline[i..i]]) { 
        if (argstart < i) { 
          arg = (arg || "") + cmdline[argstart..i-1]; 
        } 
        switch(c) { 
        case "\"": 
        case "\'": 
        case "\`": 
          // NOTE: We handle all of the above as \'. 
          int j = search(cmdline, c, i+1); 
          if (j == -1) { 
            // No endquote! 
            // Simulate one at EOL. 
            j = sizeof(cmdline); 
          } 
          arg = (arg || "") + cmdline[i+1..j-1]; 
          i = j; 
          break; 
        case "\\": 
          i++; 
          arg += cmdline[i..i]; 
          break; 
        case " ": 
        case "\t": 
          // IFS 
          if (arg) { 
            res += ({ arg }); 
            arg = 0; 
          } 
          break; 
        } 
        argstart = i+1; 
      } 
    } 
    if (argstart < i) { 
      arg = (arg || "") + cmdline[argstart..]; 
    } 
    if (arg) { 
      res += ({ arg }); 
    } 
    return res; 
  } 
 
  static private array(string) glob_expand_command_line(string cmdline) 
  { 
    DWRITE("glob_expand_command_line(\"%s\")\n", cmdline); 
 
    array(string|array(string)) args = split_command_line(cmdline); 
 
    int index; 
 
    for(index = 0; index < sizeof(args); index++) { 
 
      // Glob-expand args[index] 
 
      array (int) st; 
 
      // FIXME: Does not check if "*" or "?" was quoted! 
      if (replace(args[index], ({"*", "?"}), ({ "", "" })) != args[index]) { 
 
        // Globs in the file-name. 
 
        array(string|array(string)) matches = ({ ({ }) }); 
        multiset(string) paths; // Used to filter out duplicates. 
        int i; 
        foreach(my_combine_path("", args[index])/"/", string part) { 
          paths = (<>); 
          if (replace(part, ({"*", "?"}), ({ "", "" })) != part) { 
            // Got a glob. 
            array(array(string)) new_matches = ({}); 
            foreach(matches, array(string) path) { 
              array(string) dir; 
              RequestID id = RequestID2(master_session); 
              id->method = "LIST"; 
              dir = id->conf->find_dir(combine_path(cwd, path*"/")+"/", id); 
              if (dir && sizeof(dir)) { 
                dir = glob(part, dir); 
                if ((< '*', '?' >)[part[0]]) { 
                  // Glob-expanding does not expand to files starting with '.' 
                  dir = Array.filter(dir, lambda(string f) { 
                    return (sizeof(f) && (f[0] != '.')); 
                  }); 
                } 
                foreach(sort(dir), string f) { 
                  array(string) arr = my_combine_path_array(path, f); 
                  string p = arr*"/"; 
                  if (!paths[p]) { 
                    paths[p] = 1; 
                    new_matches += ({ arr }); 
                  } 
                } 
              } 
            } 
            matches = new_matches; 
          } else { 
            // No glob 
            // Just add the part. Modify matches in-place. 
            for(i=0; i<sizeof(matches); i++) { 
              matches[i] = my_combine_path_array(matches[i], part); 
              string path = matches[i]*"/"; 
              if (paths[path]) { 
                matches[i] = 0; 
              } else { 
                paths[path] = 1; 
              } 
            } 
            matches -= ({ 0 }); 
          } 
          if (!sizeof(matches)) { 
            break; 
          } 
        } 
        if (sizeof(matches)) { 
          // Array => string 
          for (i=0; i < sizeof(matches); i++) { 
            matches[i] *= "/"; 
          } 
          // Filter out non-existing or forbiden files/directories 
          matches = Array.filter(matches, 
                                 lambda(string short, string cwd, 
                                        object m_id) { 
                                   object id = RequestID2(m_id); 
                                   id->method = "LIST"; 
                                   id->not_query = combine_path(cwd, short); 
                                   return(id->conf->stat_file(id->not_query, 
                                                              id)); 
                                 }, cwd, master_session); 
          if (sizeof(matches)) { 
            args[index] = matches; 
          } 
        } 
      } 
      if (stringp(args[index])) { 
        // No glob 
        args[index] = ({ my_combine_path("", args[index]) }); 
      } 
    } 
    return(args * ({})); 
  } 
 
  /* 
   * LS handling 
   */ 
 
  static private constant ls_options = ({ 
    ({ ({ "-A", "--almost-all" }),      LS_FLAG_A, 
       "do not list implied . and .." }), 
    ({ ({ "-a", "--all" }),             LS_FLAG_a|LS_FLAG_A, 
       "do not hide entries starting with ." }), 
    ({ ({ "-b", "--escape" }),          LS_FLAG_b, 
       "print octal escapes for nongraphic characters" }), 
    ({ ({ "-C" }),                  LS_FLAG_C, 
       "list entries by columns" }), 
    ({ ({ "-d", "--directory" }),       LS_FLAG_d, 
       "list directory entries instead of contents" }), 
    ({ ({ "-F", "--classify" }),        LS_FLAG_F, 
       "append a character for typing each entry"}), 
    ({ ({ "-f" }),                  LS_FLAG_a|LS_FLAG_A|LS_FLAG_U, 
       "do not sort, enable -aU, disable -lst" }), 
    ({ ({ "-G", "--no-group" }),        LS_FLAG_G, 
       "inhibit display of group information" }), 
    ({ ({ "-g" }),                  0, 
       "(ignored)" }), 
    ({ ({ "-h", "--help" }),            LS_FLAG_h, 
       "display this help and exit" }), 
    ({ ({ "-k", "--kilobytes" }),       0, 
       "use 1024 blocks (ignored, always done anyway)" }), 
    ({ ({ "-L", "--dereference" }),     0, 
       "(ignored)" }), 
    ({ ({ "-l" }),                  LS_FLAG_l, 
       "use a long listing format" }), 
    ({ ({ "-m" }),                  LS_FLAG_m, 
       "fill width with a comma separated list of entries" }), 
    ({ ({ "-n", "--numeric-uid-gid" }), LS_FLAG_n, 
       "list numeric UIDs and GIDs instead of names" }), 
    ({ ({ "-o" }),                  LS_FLAG_l|LS_FLAG_G, 
       "use long listing format without group info" }), 
    ({ ({ "-Q", "--quote-name" }),      LS_FLAG_Q, 
       "enclose entry names in double quotes" }), 
    ({ ({ "-R", "--recursive" }),       LS_FLAG_R, 
       "list subdirectories recursively" }), 
    ({ ({ "-r", "--reverse" }),         LS_FLAG_r, 
       "reverse order while sorting" }), 
    ({ ({ "-S" }),                  LS_FLAG_S, 
       "sort by file size" }), 
    ({ ({ "-s", "--size" }),            LS_FLAG_s, 
       "print block size of each file" }), 
    ({ ({ "-t" }),                  LS_FLAG_t, 
       "sort by modification time; with -l: show mtime" }), 
    ({ ({ "-U" }),                  LS_FLAG_U, 
       "do not sort; list entries in directory order" }), 
    ({ ({ "-v", "--version" }),         LS_FLAG_v, 
       "output version information and exit" }), 
  }); 
 
  static private array(array(string)|string|int) 
    ls_getopt_args = Array.map(ls_options, 
                               lambda(array(array(string)|int|string) entry) { 
                                 return({ entry[1], Getopt.NO_ARG, entry[0] }); 
                               }); 
 
  static private string ls_help(string ls) 
  { 
    return sprintf("Usage: %s [OPTION]... [FILE]...\n" 
                   "List information about the FILEs " 
                   "(the current directory by default).\n" 
                   "Sort entries alphabetically if none " 
                   "of -cftuSUX nor --sort.\n" 
                   "\n" 
                   "%@s\n", 
                   ls, 
                   Array.map(ls_options, 
                             lambda(array entry) { 
                               if (sizeof(entry[0]) > 1) { 
                                 return(sprintf("  %s, %-22s %s\n", 
                                                @(entry[0]), entry[2])); 
                               } 
                               return(sprintf("  %s  " 
                                              "                       %s\n", 
                                              entry[0][0], entry[2])); 
                             })); 
  } 
 
  void call_ls(array(string) argv) 
  { 
    /* Parse options */ 
    array options; 
    mixed err; 
 
    if (err = catch { 
      options = Getopt.find_all_options(argv, ls_getopt_args, 1, 1); 
    }) { 
      send(550, (argv[0]+": "+err[0])/"\n"); 
      discard_data_connection(); 
      return; 
    } 
 
    int flags; 
 
    foreach(options, array(int) option) { 
      flags |= option[0]; 
    } 
 
    if (err = catch { 
      argv = Getopt.get_args(argv, 1, 1); 
    }) { 
      send(550, (argv[0] + ": " + err[0])/"\n"); 
      discard_data_connection(); 
      return; 
    } 
 
    if (sizeof(argv) == 1) { 
      argv += ({ "./" }); 
    } 
 
    RequestID session = RequestID2(master_session); 
    session->method = "LIST"; 
    // For logging purposes... 
    session->not_query = Array.map(argv[1..], fix_path)*" "; 
 
    mapping file = ([]); 
 
    // The listings returned by a LIST or NLST command SHOULD use an 
    // implied TYPE AN, unless the current type is EBCDIC, in which 
    // case an implied TYPE EN SHOULD be used. 
    // RFC 1123 4.1.2.7 
    if (mode != "E") { 
      file->mode = "A"; 
    } else { 
      file->mode = "E"; 
    } 
 
    if (flags & LS_FLAG_v) { 
      file->data = "ls - builtin_ls 1.1\n"; 
    } else if (flags & LS_FLAG_h) { 
      file->data = ls_help(argv[0]); 
    } else { 
      if (flags & LS_FLAG_d) { 
        flags &= ~LS_FLAG_R; 
      } 
      if (flags & (LS_FLAG_f|LS_FLAG_C|LS_FLAG_m)) { 
        flags &= ~LS_FLAG_l; 
      } 
      if (flags & LS_FLAG_C) { 
        flags &= ~LS_FLAG_m; 
      } 
 
      file->file = LSFile(cwd, argv[1..], flags, session, 
                          file->mode, this); 
    } 
 
    if (!file->full_path) { 
      file->full_path = argv[0]; 
    } 
    session->file = file; 
    connect_and_send(file, session); 
  } 
 
  /* 
   * Listings for Machine Processing 
   */ 
 
  string make_MDTM(int t) 
  { 
    mapping lt = gmtime(t); 
    return sprintf("%04d%02d%02d%02d%02d%02d", 
                   lt->year + 1900, lt->mon + 1, lt->mday, 
                   lt->hour, lt->min, lt->sec); 
  } 
 
  string make_MLSD_fact(string f, mapping(string:array) dir, object session) 
  { 
    array st = dir[f]; 
 
    mapping(string:string) facts = ([]); 
 
    // Construct the facts here. 
 
    facts["UNIX.mode"] = st[0]; 
 
    if (st[1] >= 0) { 
      facts->size = (string)st[1]; 
      facts->type = "File"; 
      facts["media-type"] = session->conf->type_from_filename(f) || 
        "application/octet-stream"; 
    } else { 
      facts->type = ([ "..":"pdir", ".":"cdir" ])[f] || "dir"; 
    } 
 
    facts->modify = make_MDTM(st[3]); 
 
    facts->charset = "8bit"; 
 
    // Construct and return the answer. 
 
    return(Array.map(indices(facts), lambda(string s, mapping f) { 
                                       return s + "=" + f[s]; 
                                     }, facts) * ";" + " " + f); 
  } 
 
  void send_MLSD_response(mapping(string:array) dir, object session) 
  { 
    dir = dir || ([]); 
 
    array f = indices(dir); 
 
    session->file->data = sizeof(f) ? 
      (Array.map(f, make_MLSD_fact, dir, session) * "\r\n") + "\r\n" : 
      "" ; 
 
    session->file->mode = "I"; 
    connect_and_send(session->file, session); 
  } 
 
  void send_MLST_response(mapping(string:array) dir, object session) 
  { 
    dir = dir || ([]); 
    send(250,({ "OK" }) +  
         Array.map(indices(dir), make_MLSD_fact, dir, session) + 
         ({ "OK" }) ); 
  } 
 
  /* 
   * Session handling 
   */ 
 
  int login() 
  { 
    int session_limit = port_obj->query_option("ftp_user_session_limit"); 
 
    if (session_limit > 0) { 
 
      if (session_limit <= (port_obj->ftp_sessions[user])) { 
        return 0;           // Session limit reached. 
      } 
 
      if (logged_in) { 
        report_error("Internal error in session-handler."); 
        return 1; 
      } 
 
      DWRITE("FTP2: Increasing # of sessions for user %O\n", user); 
      port_obj->ftp_sessions[user]++; 
    } 
    logged_in = (user != 0) || -1; 
 
    return 1; 
  } 
 
  void logout() 
  { 
    if (!logged_in) return; 
 
    int session_limit = port_obj->query_option("ftp_user_session_limit"); 
 
    if (session_limit > 0) { 
 
      DWRITE("FTP2: Decreasing # of sessions for user %O\n", user); 
      if ((--port_obj->ftp_sessions[user]) < 0) { 
        port_obj->ftp_sessions[user] = 0; 
      } 
    } 
    logged_in = 0; 
  } 
 
  int check_login() 
  { 
    int session_limit = port_obj->query_option("ftp_user_session_limit"); 
 
    if (session_limit <= 0) return 1; 
 
    if (session_limit <= (port_obj->ftp_sessions[user])) { 
      return 0;             // Session limit reached. 
    } 
 
    return 1; 
  } 
 
  /* 
   * FTP commands begin here 
   */ 
 
  // Set to 1 by EPSV ALL. 
  int epsv_only; 
  // Set to 1 by PROT S,E and P, cleared by PROT C. 
  int use_ssl; 
 
  void ftp_REIN(string|int args) 
  { 
    logout(); 
 
    // FIXME: What about EPSV ALL mode? RFC 2428 doesn't say. 
    // I guess that it shouldn't be reset. 
 
    // Compatibility... 
    m_delete(master_session->misc, "home"); 
 
    dataport_addr = 0; 
    dataport_port = 0; 
    mode = "A"; 
    cwd = "/"; 
    auth_user = 0; 
    user = password = 0; 
    curr_pipe = 0; 
    restart_point = 0; 
    logged_in = 0; 
    if (pasv_port) { 
      destruct(pasv_port); 
      pasv_port = 0; 
    } 
    if (args != 1) { 
      // Not called by QUIT. 
      send(220, ({ "Server ready for new user." })); 
    } 
  } 
 
  void ftp_USER(string args) 
  { 
    logout(); 
 
    auth_user = 0; 
    user = args; 
    password = 0; 
    logged_in = 0; 
    cwd = "/"; 
    master_session->method = "LOGIN"; 
    if ((< 0, "ftp", "anonymous" >)[user]) { 
      master_session->not_query = "Anonymous"; 
      user = 0; 
      if (port_obj->query_option("anonymous_ftp")) { 
        if (check_login()) { 
#if 0 
        send(200, ({ "Anonymous ftp, at your service" })); 
#else /* !0 */ 
        // ncftp doesn't like the above answer -- stupid program! 
          send(331, ({ "Anonymous ftp accepted, send " 
                       "your complete e-mail address as password." })); 
#endif /* 0 */ 
        conf->log(([ "error":200 ]), master_session); 
        } else { 
          send(530, ({ 
            sprintf("Too many anonymous users (%d).", 
                    port_obj->query_option("ftp_user_session_limit")) 
          })); 
          conf->log(([ "error":403 ]), master_session); 
        } 
      } else { 
        send(530, ({ "Anonymous ftp disabled" })); 
        conf->log(([ "error":403 ]), master_session); 
      } 
    } else { 
      if (check_login()) { 
        send(331, ({ sprintf("Password required for %s.", user) })); 
        master_session->not_query = user; 
        conf->log(([ "error":407 ]), master_session); 
      } else { 
        // Session limit exceeded. 
        send(530, ({ 
          sprintf("Concurrent session limit (%d) exceeded for user \"%s\".", 
                  port_obj->query_option("ftp_user_session_limit"), user) 
        })); 
        conf->log(([ "error":403 ]), master_session); 
        user = 0; 
        return; 
      } 
    } 
  } 
 
  void ftp_PASS(string args) 
  { 
    if (!user) { 
      if (port_obj->query_option("anonymous_ftp")) { 
        if (login()) { 
          send(230, ({ "Guest login ok, access restrictions apply." })); 
          master_session->method = "LOGIN"; 
          master_session->not_query = "Anonymous User:"+args; 
          conf->log(([ "error":200 ]), master_session); 
          logged_in = -1; 
        } else { 
          send(530, ({ 
            sprintf("Too many anonymous users (%d).", 
                    port_obj->query_option("ftp_user_session_limit")) 
          })); 
          conf->log(([ "error":403 ]), master_session); 
        } 
      } else { 
        send(503, ({ "Login with USER first." })); 
      } 
      return; 
    } 
 
    logout(); 
 
    password = args||""; 
    args = "CENSORED_PASSWORD";     // Censored in case of backtrace. 
    master_session->method = "LOGIN"; 
    master_session->realauth = user + ":" + password; 
    master_session->not_query = user; 
 
    master_session->misc->user = user;           // Loophole for new API 
    master_session->misc->password = password;  // Otherwise we have to emulate 
                                               // the Authentication header 
    // Compatibility... 
    m_delete(master_session->misc, "home"); 
 
    auth_user = master_session->conf->authenticate(master_session); 
 
    if (!auth_user) { 
      if (!port_obj->query_option("guest_ftp")) { 
        send(530, ({ sprintf("User %s access denied.", user) })); 
        conf->log(([ "error":401 ]), master_session); 
      } else { 
        // Guest user. 
        string u = user; 
        user = 0; 
        if (login()) { 
          send(230, ({ sprintf("Guest user %s logged in.", u) })); 
          logged_in = -1; 
          conf->log(([ "error":200 ]), master_session); 
          DWRITE("FTP: Guest-user: %O\n", master_session->realauth); 
        } else { 
          send(530, ({ 
            sprintf("Too many anonymous/guest users (%d).", 
                    port_obj->query_option("ftp_user_session_limit")) 
          })); 
          conf->log(([ "error":403 ]), master_session); 
        } 
      } 
      return; 
    } 
 
    // Authentication successful 
 
    if (!port_obj->query_option("named_ftp") || 
        !check_shell(auth_user->shell())) { 
      send(530, ({ "You are not allowed to use named-ftp.", 
                   "Try using anonymous, or check /etc/shells" })); 
      conf->log(([ "error":402 ]), master_session); 
      auth_user = 0; 
      return; 
    } 
 
    if (!login()) { 
      send(530, ({ 
        sprintf("Too many concurrent sessions (limit is %d).", 
                port_obj->query_option("ftp_user_session_limit")) 
      })); 
      conf->log(([ "error":403 ]), master_session); 
      return; 
    } 
 
    if (stringp(auth_user->homedir())) { 
      // Check if it is possible to cd to the users home-directory. 
      string home = auth_user->homedir(); 
      if ((home == "") || (home[-1] != '/')) { 
        home += "/"; 
      } 
 
      // Compatibility... 
      master_session->misc->home = home; 
 
      object session = RequestID2(master_session); 
      session->method = "STAT"; 
      array(int)|object st = conf->stat_file(home, session); 
 
      if (st && (st[1] < 0)) { 
        cwd = home; 
      } 
    } 
    logged_in = 1; 
    send(230, ({ sprintf("User %s logged in.", user) })); 
    conf->log(([ "error":202 ]), master_session); 
  } 
 
  void ftp_CWD(string args) 
  { 
    if (!expect_argument("CWD", args)) { 
      return; 
    } 
 
    string ncwd = fix_path(args); 
 
    if ((ncwd == "") || (ncwd[-1] != '/')) { 
      ncwd += "/"; 
    } 
 
    object session = RequestID2(master_session); 
    session->method = "CWD"; 
    session->not_query = ncwd; 
 
    array|object st = conf->stat_file(ncwd, session); 
    ncwd = session->not_query; // Makes internal redirects to work. 
    if (!st) { 
      send(550, ({ sprintf("%s: No such file or directory, or access denied.", 
                           ncwd) })); 
      session->conf->sent = session->file && session->file->len; 
      session->conf->log(session->file || ([ "error":404 ]), session); 
      return; 
    } 
 
    if (!(< -2, -3 >)[st[1]]) { 
      send(504, ({ sprintf("%s: Not a directory.", ncwd) })); 
      session->conf->log(([ "error":400 ]), session); 
      return; 
    } 
 
    // CWD Successfull 
    cwd = ncwd; 
 
    array(string) reply = ({ sprintf("Current directory is now %s.", cwd) }); 
 
    // Check for .messages etc 
    session->method = "GET";        // Important 
    array(string) files = conf->find_dir(cwd, session); 
 
    if (files) { 
      files = reverse(sort(Array.filter(files, lambda(string s) { 
                                                 return(s[..5] == "README"); 
                                               }))); 
      foreach(files, string f) { 
        array|object st = conf->stat_file(replace(cwd + f, "//", "/"), 
                                          session); 
 
        if (st && (st[1] >= 0)) { 
          reply = ({ sprintf("Please read the file %s.", f), 
                     sprintf("It was last modified %s - %d days ago.", 
                             ctime(st[3]) - "\n", 
                             (time(1) - st[3])/86400), 
                     "" }) + reply; 
        } 
      } 
    } 
    string message; 
    catch { 
      message = conf->try_get_file(cwd + ".message", session); 
    }; 
    if (message) { 
      reply = (message/"\n")+({ "" })+reply; 
    } 
 
    session->method = "CWD";        // Restore it again. 
    send(250, reply); 
    session->conf->sent = sizeof(reply * "\n"); 
    session->conf->log(([ "error":200, "len":session->conf->sent ]), session); 
  } 
 
  void ftp_XCWD(string args) 
  { 
    ftp_CWD(args); 
  } 
 
  void ftp_CDUP(string args) 
  { 
    ftp_CWD("../"); 
  } 
 
  void ftp_XCUP(string args) 
  { 
    ftp_CWD("../"); 
  } 
 
  void ftp_QUIT(string args) 
  { 
    send(221, ({ "Bye! It was nice talking to you!" })); 
    send(0, 0);         // EOF marker. 
 
    master_session->method = "QUIT"; 
    master_session->not_query = user || "Anonymous"; 
    conf->log(([ "error":200 ]), master_session); 
 
    // Reinitialize the connection. 
    ftp_REIN(1); 
  } 
 
  void ftp_BYE(string args) 
  { 
    ftp_QUIT(args); 
  } 
 
  void ftp_PBSZ(string args) 
  { 
    if (!expect_argument("PROT", args)) return; 
 
    send(200, ({ "PBSZ=0" })); 
  } 
 
  void ftp_PROT(string args) 
  { 
    if (!expect_argument("PROT", args)) return; 
 
    args = upper_case(replace(args, ({ " ", "\t" }), ({ "", "" }))); 
    switch(args) { 
    case "C": // Clear. 
      use_ssl = 0; 
      break; 
    case "S": // Safe. 
    case "E": // Confidential. 
    case "P": // Private. 
      if (!port_obj->ctx) { 
        send(536, ({ sprintf("Only supported over FTPS") })); 
        return; 
      } 
      use_ssl = 1; 
      break; 
    default: 
      send(504, ({ sprintf("Unknown protection level: %s", args) })); 
      return; 
    } 
    send(200, ({ "OK" })); 
  } 
 
  void ftp_PORT(string args) 
  { 
    if (epsv_only) { 
      send(530, ({ "'PORT': Method not allowed in EPSV ALL mode." })); 
      return; 
    } 
 
    int a, b, c, d, e, f; 
 
    if (sscanf(args||"", "%d,%d,%d,%d,%d,%d", a, b, c, d, e, f)<6) 
      send(501, ({ "I don't understand your parameters." })); 
    else { 
      dataport_addr = sprintf("%d.%d.%d.%d", a, b, c, d); 
      dataport_port = e*256 + f; 
 
      if (pasv_port) { 
        destruct(pasv_port); 
      } 
      send(200, ({ "PORT command ok ("+dataport_addr+ 
                   " port "+dataport_port+")" })); 
    } 
  } 
 
  void ftp_EPRT(string args) 
  { 
    if (epsv_only) { 
      send(530, ({ "'EPRT': Method not allowed in EPSV ALL mode." })); 
      return; 
    } 
 
    if (sizeof(args) < 3) { 
      send(501, ({ "I don't understand your parameters." })); 
      return; 
    } 
 
    string delimiter = args[0..0]; 
    if ((delimiter[0] <= 32) || (delimiter[0] >= 127)) { 
      send(501, ({ "Invalid delimiter." })); 
    } 
    array(string) segments = args/delimiter; 
 
    if (sizeof(args) != 5) { 
      send(501, ({ "I don't understand your parameters." })); 
      return; 
    } 
    if (segments[1] != "1") { 
      // FIXME: No support for IPv6 yet. 
      send(522, ({ "Network protocol not supported, use (1)" })); 
      return; 
    } 
    if ((sizeof(segments[2]/".") != 4) || 
        sizeof(replace(segments[2], ".0123456789"/"", allocate(11, "")))) { 
      send(501, ({ sprintf("Bad IPv4 address: '%s'", segments[2]) })); 
      return; 
    } 
    if (!((int)segments[3])) { 
      send(501, ({ sprintf("Bad port number: '%s'", segments[3]) })); 
      return; 
    } 
    dataport_addr = segments[2]; 
    dataport_port = (int)segments[3]; 
 
    if (pasv_port) { 
      destruct(pasv_port); 
    } 
    send(200, ({ "EPRT command ok ("+dataport_addr+ 
                 " port "+dataport_port+")" })); 
  } 
 
  void ftp_PASV(string args) 
  { 
    // Required by RFC 1123 4.1.2.6 
    int min; 
    int max; 
 
    if (epsv_only) { 
      send(530, ({ "'PASV': Method not allowed in EPSV ALL mode." })); 
      return; 
    } 
 
    if(pasv_port) 
      destruct(pasv_port); 
 
    pasv_port = Stdio.Port(0, pasv_accept_callback, local_addr); 
    /* FIXME: Hmm, getting the address from an anonymous port seems not 
     * to work on NT... 
     */ 
    int port=(int)((pasv_port->query_address()/" ")[1]); 
 
    min = port_obj->query_option("passive_port_min"); 
    max = port_obj->query_option("passive_port_max"); 
    if ((port < min) || (port > max)) { 
      if (max > 65535) max = 65535; 
      if (min < 0) min = 0; 
      for (port = min; port <= max; port++) { 
        if (pasv_port->bind(port, pasv_accept_callback, local_addr)) { 
          break; 
        } 
      } 
      if (port > max) { 
        destruct(pasv_port); 
        pasv_port = 0; 
        send(452, ({ "Requested action aborted: Out of ports." })); 
        return; 
      } 
    } 
    send(227, ({ sprintf("Entering Passive Mode. (%s,%d,%d)", 
                         replace(local_addr, ".", ","), 
                         (port>>8), (port&0xff)) })); 
  } 
 
  void ftp_EPSV(string args) 
  { 
    // Specified by RFC 2428: 
    // Extensions for IPv6 and NATs. 
    int min; 
    int max; 
 
    if (args && args != "1") { 
      if (lower_case(args) == "all") { 
        epsv_only = 1; 
        send(200, ({ "Entering EPSV ALL mode." })); 
      } else { 
        // FIXME: No support for IPv6 yet. 
        send(522, ({ "Network protocol not supported, use (1)" })); 
      } 
      return; 
    } 
    if (pasv_port) 
      destruct(pasv_port); 
 
    pasv_port = Stdio.Port(0, pasv_accept_callback, local_addr); 
    /* FIXME: Hmm, getting the address from an anonymous port seems not 
     * to work on NT... 
     */ 
    int port=(int)((pasv_port->query_address()/" ")[1]); 
 
    min = port_obj->query_option("passive_port_min"); 
    max = port_obj->query_option("passive_port_max"); 
    if ((port < min) || (port > max)) { 
      if (max > 65535) max = 65535; 
      if (min < 0) min = 0; 
      for (port = min; port <= max; port++) { 
        if (pasv_port->bind(port, pasv_accept_callback, local_addr)) { 
          break; 
        } 
      } 
      if (port > max) { 
        destruct(pasv_port); 
        pasv_port = 0; 
        send(452, ({ "Requested action aborted: Out of ports." })); 
        return; 
      } 
    } 
    send(229, ({ sprintf("Entering Extended Passive Mode (|||%d|)", 
                         /* "1", local_addr,*/ port) })); 
  } 
 
  void ftp_TYPE(string args) 
  { 
    if (!expect_argument("TYPE", args)) { 
      return; 
    } 
 
    args = upper_case(replace(args, ({ " ", "\t" }), ({ "", "" }))); 
 
    // I and L8 are required by RFC 1123 4.1.2.1 
    switch(args) { 
    case "L8": 
    case "L": 
    case "I": 
      mode = "I"; 
      break; 
    case "A": 
      mode = "A"; 
      break; 
    case "E": 
      mode = "E"; 
      break; 
    default: 
      send(504, ({ "'TYPE': Unknown type:"+args })); 
      return; 
    } 
 
    send(200, ({ sprintf("Using %s mode for transferring files.", 
                         modes[mode]) })); 
  } 
 
  void ftp_RETR(string args) 
  { 
    if (!expect_argument("RETR", args)) { 
      return; 
    } 
 
    args = fix_path(args); 
 
    RequestID session = RequestID2(master_session); 
 
    session->method = "GET"; 
    session->not_query = args; 
 
    if (open_file(args, session, "RETR")) { 
      if (restart_point) { 
        if (session->file->data) { 
          if (sizeof(session->file->data) >= restart_point) { 
            session->file->data = session->file->data[restart_point..]; 
            restart_point = 0; 
          } else { 
            restart_point -= sizeof(session->file->data); 
            m_delete(session->file, "data"); 
          } 
        } 
        if (restart_point) { 
          if (!(session->file->file && session->file->file->seek && 
                (session->file->file->seek(restart_point) != -1))) { 
            restart_point = 0; 
            send(550, ({ "'RETR': Error restoring restart point." })); 
            discard_data_connection(); 
            return; 
          } 
          restart_point = 0; 
        } 
      } 
 
      connect_and_send(session->file, session); 
    } 
    else 
      discard_data_connection(); 
  } 
 
  void ftp_STOR(string args) 
  { 
    if (!expect_argument("STOR", args)) { 
      return; 
    } 
 
    args = fix_path(args); 
 
    connect_and_receive(args); 
  } 
 
  void ftp_REST(string args) 
  { 
    if (!expect_argument("REST", args)) { 
      return; 
    } 
    restart_point = (int)args; 
    send(350, ({ "'REST' ok" })); 
  } 
 
  void ftp_ABOR(string args) 
  { 
    if (curr_pipe) { 
      catch { 
        curr_pipe->stop(); 
      }; 
      curr_pipe = 0; 
      send(426, ({ "Data transmission terminated." })); 
    } 
    send(226, ({ "'ABOR' Completed." })); 
  } 
 
  void ftp_PWD(string args) 
  { 
    send(257, ({ sprintf("\"%s\" is current directory.", cwd) })); 
  } 
 
  void ftp_XPWD(string args) 
  { 
    ftp_PWD(args); 
  } 
 
  /* 
   * Handling of file moving 
   */ 
 
  static private string rename_from; // rename from 
 
  void ftp_RNFR(string args) 
  { 
    if (!expect_argument("RNFR", args)) { 
      return; 
    } 
    args = fix_path(args); 
 
    RequestID session = RequestID2(master_session); 
 
    session->method = "STAT"; 
 
    if (stat_file(args, session)) { 
      send(350, ({ sprintf("%s ok, waiting for destination name.", args) }) ); 
      rename_from = args; 
    } else { 
      send(550, ({ sprintf("%s: no such file or permission denied.",args) }) ); 
    } 
  } 
 
  void ftp_RNTO(string args) 
  { 
    if(!rename_from) { 
      send(503, ({ "RNFR needed before RNTO." })); 
      return; 
    } 
    if (!expect_argument("RNTO", args)) { 
      return; 
    } 
    args = fix_path(args); 
 
    RequestID session = RequestID2(master_session); 
 
    session->method = "MV"; 
    session->misc->move_from = rename_from; 
    session->not_query = args; 
    if (open_file(args, session, "MOVE")) { 
      send(250, ({ sprintf("%s moved to %s.", rename_from, args) })); 
      session->conf->log(([ "error":200 ]), session); 
    } 
    rename_from = 0; 
  } 
 
 
  void ftp_NLST(string args) 
  { 
    // ftp_MLST(args); return; 
 
    array(string) argv = glob_expand_command_line("/usr/bin/ls " + (args||"")); 
 
    call_ls(argv); 
  } 
 
  void ftp_LIST(string args) 
  { 
    // ftp_MLSD(args); return; 
 
    ftp_NLST("-l " + (args||"")); 
  } 
 
  void ftp_MLST(string args) 
  { 
    args = fix_path(args || "."); 
 
    RequestID session = RequestID2(master_session); 
 
    session->method = "DIR"; 
 
    array|object st = stat_file(args, session); 
 
    if (st) { 
      session->file = ([]); 
      session->file->full_path = args; 
      send_MLST_response(([ args:st ]), session); 
    } else { 
      send_error("MLST", args, session->file, session); 
    } 
  } 
 
  void ftp_MLSD(string args) 
  { 
    args = fix_path(args || "."); 
 
    RequestID session = RequestID2(master_session); 
 
    session->method = "DIR"; 
 
    array|object st = stat_file(args, session); 
 
    if (st && (st[1] < 0)) { 
      if (args[-1] != '/') { 
        args += "/"; 
      } 
 
      session->file = ([]); 
      session->file->full_path = args; 
      send_MLSD_response(session->conf->find_dir_stat(args, session), session); 
    } else { 
      if (st) { 
        session->file->error = 405; 
      } 
      send_error("MLSD", args, session->file, session); 
      discard_data_connection(); 
    } 
  } 
 
  void ftp_DELE(string args) 
  { 
    if (!expect_argument("DELE", args)) { 
      return; 
    } 
 
    args = fix_path(args); 
 
    RequestID session = RequestID2(master_session); 
 
    session->data = 0; 
    session->misc->len = 0; 
    session->method = "DELETE"; 
 
    if (open_file(args, session, "DELE")) { 
      send(250, ({ sprintf("%s deleted.", args) })); 
      session->conf->log(([ "error":200 ]), session); 
      return; 
    } 
  } 
 
  void ftp_RMD(string args) 
  { 
    if (!expect_argument("RMD", args)) { 
      return; 
    } 
 
    args = fix_path(args); 
 
    RequestID session = RequestID2(master_session); 
 
    session->data = 0; 
    session->misc->len = 0; 
    session->method = "DELETE"; 
 
    array|object st = stat_file(args, session); 
 
    if (!st) { 
      send_error("RMD", args, session->file, session); 
      return; 
    } else if (st[1] != -2) { 
      if (st[1] == -3) { 
        send(504, ({ sprintf("%s is a module mountpoint.", args) })); 
        session->conf->log(([ "error":405 ]), session); 
      } else { 
        send(504, ({ sprintf("%s is not a directory.", args) })); 
        session->conf->log(([ "error":405 ]), session); 
      } 
      return; 
    } 
 
    if (open_file(args, session, "RMD")) { 
      send(250, ({ sprintf("%s deleted.", args) })); 
      session->conf->log(([ "error":200 ]), session); 
      return; 
    } 
  } 
 
  void ftp_XRMD(string args) 
  { 
    ftp_RMD(args); 
  } 
 
  void ftp_MKD(string args) 
  { 
    if (!expect_argument("MKD", args)) { 
      return; 
    } 
 
    args = fix_path(args); 
 
    RequestID session = RequestID2(master_session); 
 
    session->method = "MKDIR"; 
    session->data = 0; 
    session->misc->len = 0; 
 
    if (open_file(args, session, "MKD")) { 
      send(257, ({ sprintf("\"%s\" created.", args) })); 
      session->conf->log(([ "error":200 ]), session); 
      return; 
    } 
  } 
 
  void ftp_XMKD(string args) 
  { 
    ftp_MKD(args); 
  } 
 
  void ftp_SYST(string args) 
  { 
    send(215, ({ "UNIX Type: L8: ChiliMoon Internet Server"})); 
  } 
 
  void ftp_CLNT(string args) 
  { 
    if (!expect_argument("CLNT", args)) { 
      return; 
    } 
 
    send(200, ({ "Ok, gottcha!"})); 
    master_session->client = args/" " - ({ "" }); 
  } 
 
  void ftp_FEAT(string args) 
  { 
    array a = sort(Array.filter(indices(cmd_help), 
                                lambda(string s) { 
                                  return(this["ftp_"+s]); 
                                })); 
    a = Array.map(a, 
                  lambda(string s) { 
                    return(([ "REST":"REST STREAM", 
                              "MLST":"MLST UNIX.mode;size;type;modify;charset;media-type", 
                              "MLSD":"", 
                    ])[s] || s); 
                  }) - ({ "" }); 
 
    send(211, ({ "The following features are supported:" }) + a + 
         ({ "END" })); 
  } 
 
  void ftp_MDTM(string args) 
  { 
    if (!expect_argument("MDTM", args)) { 
      return; 
    } 
    args = fix_path(args); 
    RequestID session = RequestID2(master_session); 
    session->method = "STAT"; 
    mapping|array|object st = stat_file(args, session); 
 
    if (!arrayp(st) && !objectp(st)) { 
      send_error("MDTM", args, st, session); 
      return; 
    } 
    send(213, ({ make_MDTM(st[3]) })); 
  } 
 
  void ftp_SIZE(string args) 
  { 
    if (!expect_argument("SIZE", args)) { 
      return; 
    } 
    args = fix_path(args); 
 
    RequestID session = RequestID2(master_session); 
    session->method = "STAT"; 
    mapping|array|object st = stat_file(args, session); 
 
    if (!arrayp(st) && !objectp(st)) { 
      send_error("SIZE", args, st, session); 
      return; 
    } 
    int size = st[1]; 
    if (size < 0) { 
      send_error("SIZE", args, ([ "error":405, ]), session); 
      return; 
      // size = 512; 
    } 
    send(213, ({ (string)size })); 
  } 
 
  void ftp_STAT(string args) 
  { 
    // According to RFC 1123 4.1.3.3, this command can be sent during 
    // a file-transfer. 
    // RFC 959 4.1.3: 
    // The command may be sent during a file transfer (along with the 
    // Telnet IP and Synch signals--see the Section on FTP Commands) 
    // in which case the server will respond with the status of the 
    // operation in progress, [...] 
    // FIXME: This is not supported yet. 
 
    if ((< "", 0 >)[args]) { 
      /* RFC 959 4.1.3: 
       * If no argument is given, the server should return general 
       * status information about the server FTP process.  This 
       * should include current values of all transfer parameters and 
       * the status of connections. 
       */ 
      send(211, 
           sprintf("%s FTP server status:\n" 
                   "Version %s\n" 
                   "Listening on %s\n" 
                   "Connected to %s\n" 
                   "Logged in %s\n" 
                   "TYPE: %s, FORM: %s; STRUcture: %s; transfer MODE: %s\n" 
                   "End of status", 
                   replace(fd->query_address(1), " ", ":"), 
                   core.version(), 
                   port_obj->sorted_urls * "\nListening on ", 
                   replace(fd->query_address(), " ", ":"), 
                   user?sprintf("as %s", user):"anonymously", 
                   (["A":"ASCII", "E":"EBCDIC", "I":"IMAGE", "L":"LOCAL"]) 
                   [mode], 
                   "Non-Print", 
                   "File", 
                   "Stream" 
                   )/"\n"); 
      return; 
    } 
    string long = fix_path(args); 
    RequestID session = RequestID2(master_session); 
    session->method = "STAT"; 
    mapping|array|object st = stat_file(long); 
 
    if (!arrayp(st) && !objectp(st)) { 
      send_error("STAT", long, st, session); 
      return; 
    } 
 
    string s = LS_L(master_session)->ls_l(args, st); 
 
    send(213, sprintf("status of \"%s\":\n" 
                      "%s" 
                      "End of Status", args, s)/"\n"); 
  } 
 
  void ftp_NOOP(string args) 
  { 
    send(200, ({ "Nothing done ok" })); 
  } 
 
  void ftp_HELP(string args) 
  { 
    if ((< "", 0 >)[args]) { 
      send(214, ({ 
        "The following commands are recognized (* =>'s unimplemented):", 
        @(sprintf(" %#70s", sort(Array.map(indices(cmd_help), 
                                           lambda(string s) { 
                                             return(upper_case(s)+ 
                                                    (this["ftp_"+s]? 
                                                     "   ":"*  ")); 
                                           }))*"\n")/"\n"), 
        @(FTP2_XTRA_HELP), 
      })); 
    } else if ((args/" ")[0] == "SITE") { 
      array(string) a = (upper_case(args)/" ")-({""}); 
      if (sizeof(a) == 1) { 
        send(214, ({ "The following SITE commands are recognized:", 
                     @(sprintf(" %#70s", sort(indices(site_help))*"\n")/"\n") 
        })); 
      } else if (site_help[a[1]]) { 
        send(214, ({ sprintf("Syntax: SITE %s %s", a[1], site_help[a[1]]) })); 
      } else { 
        send(504, ({ sprintf("Unknown SITE command %s.", a[1]) })); 
      } 
    } else { 
      args = upper_case(args); 
      if (cmd_help[args]) { 
        send(214, ({ sprintf("Syntax: %s %s%s", args, 
                             cmd_help[args], 
                             (this["ftp_"+args]? 
                              "":"; unimplemented")) })); 
      } else { 
        send(504, ({ sprintf("Unknown command %s.", args) })); 
      } 
    } 
  } 
 
  void ftp_SITE(string args) 
  { 
    // Extended commands. 
    // Site specific commands are required to be part of the site command 
    // by RFC 1123 4.1.2.8 
 
    if ((< 0, "" >)[args]) { 
      ftp_HELP("SITE"); 
      return; 
    } 
 
    array a = (args/" ") - ({ "" }); 
 
    if (!sizeof(a)) { 
      ftp_HELP("SITE"); 
      return; 
    } 
    a[0] = upper_case(a[0]); 
    if (!site_help[a[0]]) { 
      send(502, ({ sprintf("Bad SITE command: '%s'", a[0]) })); 
    } else if (this["ftp_SITE_"+a[0]]) { 
      this["ftp_SITE_"+a[0]](a[1..]); 
    } else { 
      send(502, ({ sprintf("SITE command '%s' is not currently supported.", 
                           a[0]) })); 
    } 
  } 
 
  void ftp_SITE_CHMOD(array(string) args) 
  { 
    if (sizeof(args) < 2) { 
      send(501, ({ sprintf("'SITE CHMOD %s': incorrect arguments", 
                           args*" ") })); 
      return; 
    } 
 
    int mode; 
    foreach(args[0] / "", string m) 
      // We do this loop, instead of using a sscanf or cast to be able 
      // to catch arguments which aren't an octal number like 0891. 
    { 
      mode *= 010; 
      if(m[0] < '0' || m[0] > '7') 
      { 
        // This is not an octal number... 
        mode = -1; 
        break; 
      } 
      mode += (int)("0"+m); 
    } 
    if(mode == -1 || mode > 0777) 
    { 
      send(501, ({ "SITE CHMOD: mode should be between 0 and 0777" })); 
      return; 
    } 
 
    string fname = fix_path(args[1..]*" "); 
    RequestID session = RequestID2(master_session); 
 
    session->method = "CHMOD"; 
    session->misc->mode = mode; 
    session->not_query = fname; 
    if (open_file(fname, session, "CHMOD")) { 
      send(250, ({ sprintf("Changed permissions of %s to 0%o.", 
                           fname, mode) })); 
      session->conf->log(([ "error":200 ]), session); 
    } 
  } 
 
  void ftp_SITE_UMASK(array(string) args) 
  { 
    if (sizeof(args) < 1) { 
      send(501, ({ sprintf("'SITE UMASK %s': incorrect arguments", 
                           args*" ") })); 
      return; 
    } 
 
    int mode; 
    foreach(args[0] / "", string m) 
      // We do this loop, instead of using a sscanf or cast to be able 
      // to catch arguments which aren't an octal number like 0891. 
    { 
      mode *= 010; 
      if(m[0] < '0' || m[0] > '7') 
      { 
        // This is not an octal number... 
        mode = -1; 
        break; 
      } 
      mode += (int)("0"+m); 
    } 
    if(mode == -1 || mode > 0777) 
    { 
      send(501, ({ "SITE UMASK: mode should be between 0 and 0777" })); 
      return; 
    } 
 
    master_session->misc->umask = mode; 
    send(250, ({ sprintf("Umask set to 0%o.", mode) })); 
  } 
 
  void ftp_SITE_PRESTATE(array(string) args) 
  { 
    if (!sizeof(args)) { 
      master_session->prestate = (<>); 
      send(200, ({ "Prestate cleared" })); 
    } else { 
      master_session->prestate = aggregate_multiset(@((args*" ")/","-({""}))); 
      send(200, ({ "Prestate set" })); 
    } 
  } 
 
  static private void timeout() 
  { 
    if (fd) { 
      int t = (time() - time_touch); 
      if (t > FTP2_TIMEOUT) { 
        // Recomended by RFC 1123 4.1.3.2 
        send(421, ({ "Connection timed out." })); 
        send(0,0); 
        if (master_session->file) { 
          if (objectp(master_session->file->file)) { 
            destruct(master_session->file->file); 
          } 
          if (objectp(master_session->file->pipe)) { 
            destruct(master_session->file->pipe); 
          } 
        } 
        if (objectp(pasv_port)) { 
          destruct(pasv_port); 
        } 
        master_session->method = "QUIT"; 
        master_session->not_query = user || "Anonymous"; 
        master_session->conf->log(([ "error":408 ]), master_session); 
      } else { 
        // Not time yet to sever the connection. 
        call_out(timeout, FTP2_TIMEOUT + 30 - t); 
      } 
    } else { 
      // We ought to be dead already... 
      DWRITE("FTP2: Timeout on dead connection.\n"); 
      destruct(); 
    } 
  } 
 
  static private void got_command(mixed ignored, string line) 
  { 
    DWRITE("FTP2: got_command(X, \"%s\")\n", line); 
 
    touch_me(); 
 
    string cmd = line; 
    string args; 
    int i; 
 
    if (line == "") { 
      // The empty command. 
      // Some stupid ftp-proxies send this. 
      return;       // Even less than a NOOP. 
    } 
 
    if ((i = search(line, " ")) != -1) { 
      cmd = line[..i-1]; 
      args = line[i+1..] - "\0"; 
    } 
    cmd = upper_case(cmd); 
 
    if ((< "PASS" >)[cmd]) { 
      // Censor line, so that the password doesn't show 
      // in backtraces. 
      line = cmd + " CENSORED_PASSWORD"; 
    } 
 
#if 0 
    if (!conf->extra_statistics) { 
      conf->extra_statistics = ([ "ftp": (["commands":([ cmd:1 ])])]); 
    } else if (!conf->extra_statistics->ftp) { 
      conf->extra_statistics->ftp = (["commands":([ cmd:1 ])]); 
    } else if (!conf->extra_statistics->ftp->commands) { 
      conf->extra_statistics->ftp->commands = ([ cmd:1 ]); 
    } else { 
      conf->extra_statistics->ftp->commands[cmd]++; 
    } 
#endif /* 0 */ 
 
    if (cmd_help[cmd]) { 
      if (!logged_in) { 
        if (!(< "REIN", "USER", "PASS", "SYST", 
                "ACCT", "QUIT", "ABOR", "HELP" >)[cmd]) { 
          send(530, ({ "You need to login first." })); 
 
          return; 
        } 
      } 
      if (this["ftp_"+cmd]) { 
        conf->requests++; 
#if 1 
      mixed err; 
        if (err = catch { 
          this["ftp_"+cmd](args); 
        }) { 
          report_error("Internal server error in FTP2\n" 
                       "Handling command %O\n%s\n", 
                       line, describe_backtrace(err)); 
        } 
#else 
      core->handle(lambda(function f, string args, string line) { 
                       mixed err; 
                       if (err = catch { 
                         f(args); 
                       }) { 
                         report_error("Internal server error in FTP2\n" 
                                      "Handling command %O\n%s\n", 
                                      line, describe_backtrace(err)); 
                       } 
                     }, this["ftp_"+cmd], args, line); 
#endif 
      } else { 
        send(502, ({ sprintf("'%s' is not currently supported.", cmd) })); 
      } 
    } else { 
      send(502, ({ sprintf("Unknown command '%s'.", cmd) })); 
    } 
 
    touch_me(); 
  } 
 
  void con_closed() 
  { 
    DWRITE("FTP2: con_closed()\n"); 
 
    logout(); 
 
    master_session->method = "QUIT"; 
    master_session->not_query = user || "Anonymous"; 
    conf->log(([ "error":204, "request_time":(time(1)-master_session->time) ]), 
              master_session); 
 
    if (fd) { 
      fd->close(); 
    } 
    if (pasv_port) { 
      destruct(pasv_port); 
      pasv_port = 0; 
    } 
    // Make sure we disappear... 
    destruct(); 
  } 
 
  void destroy() 
  { 
    DWRITE("FTP2: destroy()\n"); 
 
    logout(); 
 
    port_obj->sessions--; 
  } 
 
  void create(object fd, object c) 
  { 
    port_obj = c; 
 
    // FIXME: Only supports one configuration! 
    conf = port_obj->urls[port_obj->sorted_urls[0]]->conf; 
 
    // Support delayed loading. 
    if (!conf->inited) { 
      conf->enable_all_modules(); 
    } 
 
#if 0 
    werror("FTP: conf:%O\n" 
           "FTP:urls:%O\n", 
           mkmapping(indices(conf), values(conf)), port_obj->urls); 
#endif /* 0 */ 
 
    master_session = RequestID2(); 
    master_session->remoteaddr = (fd->query_address()/" ")[0]; 
    master_session->conf = conf; 
    master_session->port_obj = c; 
    master_session->my_fd = fd; 
    master_session->misc->defaulted = 1; 
    ::create(fd, got_command, 0, con_closed, ([])); 
 
    array a = fd->query_address(1)/" "; 
    local_addr = a[0]; 
    local_port = (int)a[1]; 
 
    call_out(timeout, FTP2_TIMEOUT); 
 
    string s = c->query_option("FTPWelcome"); 
 
    s = replace(s, 
                ({ "$roxen_version", "$roxen_build", "$full_version", 
                   "$pike_version", "$ident", }), 
                ({ core.__roxen_version__, core.__roxen_build__, 
                   core.real_version, version(), core.version() })); 
 
    send(220, s/"\n", 1); 
  } 
}; 
 
void create(object f, object c) 
{ 
  if (f) 
  { 
    c->sessions++; 
    c->ftp_users++; 
    FTPSession(f, c); 
  } 
}