File: SftpServer.pm

package info (click to toggle)
libnet-sftp-sftpserver-perl 1.1.0-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 492 kB
  • sloc: perl: 1,929; makefile: 10; sh: 2
file content (2758 lines) | stat: -rwxr-xr-x 85,252 bytes parent folder | download | duplicates (3)
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
#/*
# * Based on sftp-server.c
# * Copyright (c) 2000-2004 Markus Friedl.  All rights reserved.
# *
# * Ported to Perl and extended by Simon Day
# * Copyright (c) 2009 Pirum Systems Ltd.  All rights reserved.
# *
# * Permission to use, copy, modify, and distribute this software for any
# * purpose with or without fee is hereby granted, provided that the above
# * copyright notice and this permission notice appear in all copies.
# *
# * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# */
#
package Net::SFTP::SftpServer;
require Exporter;
@ISA = qw(Exporter);

@EXPORT_OK = qw(
    ALL
    NET_SFTP_SYMLINKS
    NET_SFTP_RENAME_DIR
    SSH2_FXP_INIT
    SSH2_FXP_OPEN
    SSH2_FXP_CLOSE
    SSH2_FXP_READ
    SSH2_FXP_WRITE
    SSH2_FXP_LSTAT
    SSH2_FXP_STAT_VERSION_0
    SSH2_FXP_FSTAT
    SSH2_FXP_SETSTAT
    SSH2_FXP_FSETSTAT
    SSH2_FXP_OPENDIR
    SSH2_FXP_READDIR
    SSH2_FXP_REMOVE
    SSH2_FXP_MKDIR
    SSH2_FXP_RMDIR
    SSH2_FXP_REALPATH
    SSH2_FXP_STAT
    SSH2_FXP_RENAME
    SSH2_FXP_READLINK
    SSH2_FXP_SYMLINK
    logError
    logWarning
    logGeneral
    logDetail
);


%EXPORT_TAGS = (  ACTIONS => [ qw(
                              ALL
                              NET_SFTP_SYMLINKS
                              NET_SFTP_RENAME_DIR
                              SSH2_FXP_OPEN
                              SSH2_FXP_CLOSE
                              SSH2_FXP_READ
                              SSH2_FXP_WRITE
                              SSH2_FXP_LSTAT
                              SSH2_FXP_STAT_VERSION_0
                              SSH2_FXP_FSTAT
                              SSH2_FXP_SETSTAT
                              SSH2_FXP_FSETSTAT
                              SSH2_FXP_OPENDIR
                              SSH2_FXP_READDIR
                              SSH2_FXP_REMOVE
                              SSH2_FXP_MKDIR
                              SSH2_FXP_RMDIR
                              SSH2_FXP_STAT
                              SSH2_FXP_RENAME
                              SSH2_FXP_READLINK
                              SSH2_FXP_SYMLINK
                            ) ],
                  LOG  => [qw(
                              logError
                              logWarning
                              logGeneral
                              logDetail
                           )]);

use strict;
use warnings;

use version; our $VERSION = qv('1.1.0');

use Stat::lsMode;
use Fcntl qw( O_RDWR O_CREAT O_TRUNC O_EXCL O_RDONLY O_WRONLY SEEK_SET );
use POSIX qw(strftime);
use Sys::Syslog;

$SIG{__DIE__} = sub {  ## still dies upon return
		syslog 'warning', join(" : ", @_);
};

use Errno qw(:POSIX);

use constant TIMEOUT                        => 300;
use constant MAX_PACKET_SIZE                => 1024 * 1024;
use constant MAX_OPEN_HANDLES               => 512;

#/* version */
use constant SSH2_FILEXFER_VERSION          => 3;

#/* client to server */
use constant SSH2_FXP_INIT                  => 1;
use constant SSH2_FXP_OPEN                  => 3;
use constant SSH2_FXP_CLOSE                 => 4;
use constant SSH2_FXP_READ                  => 5;
use constant SSH2_FXP_WRITE                 => 6;
use constant SSH2_FXP_LSTAT                 => 7;
use constant SSH2_FXP_STAT_VERSION_0        => 7;
use constant SSH2_FXP_FSTAT                 => 8;
use constant SSH2_FXP_SETSTAT               => 9;
use constant SSH2_FXP_FSETSTAT              => 10;
use constant SSH2_FXP_OPENDIR               => 11;
use constant SSH2_FXP_READDIR               => 12;
use constant SSH2_FXP_REMOVE                => 13;
use constant SSH2_FXP_MKDIR                 => 14;
use constant SSH2_FXP_RMDIR                 => 15;
use constant SSH2_FXP_REALPATH              => 16;
use constant SSH2_FXP_STAT                  => 17;
use constant SSH2_FXP_RENAME                => 18;
use constant SSH2_FXP_READLINK              => 19;
use constant SSH2_FXP_SYMLINK               => 20;

# SFTP allow/deny actions

use constant ALL                            => 1000;
use constant NET_SFTP_RENAME_DIR            => 1001;
use constant NET_SFTP_SYMLINKS              => 1002;

#/* server to client */
use constant SSH2_FXP_VERSION               => 2;
use constant SSH2_FXP_STATUS                => 101;
use constant SSH2_FXP_HANDLE                => 102;
use constant SSH2_FXP_DATA                  => 103;
use constant SSH2_FXP_NAME                  => 104;
use constant SSH2_FXP_ATTRS                 => 105;

use constant SSH2_FXP_EXTENDED              => 200;
use constant SSH2_FXP_EXTENDED_REPLY        => 201;

#/* attributes */
use constant SSH2_FILEXFER_ATTR_SIZE        => 0x00000001;
use constant SSH2_FILEXFER_ATTR_UIDGID      => 0x00000002;
use constant SSH2_FILEXFER_ATTR_PERMISSIONS => 0x00000004;
use constant SSH2_FILEXFER_ATTR_ACMODTIME   => 0x00000008;
use constant SSH2_FILEXFER_ATTR_EXTENDED    => 0x80000000;

#/* portable open modes */
use constant SSH2_FXF_READ                  => 0x00000001;
use constant SSH2_FXF_WRITE                 => 0x00000002;
use constant SSH2_FXF_APPEND                => 0x00000004;
use constant SSH2_FXF_CREAT                 => 0x00000008;
use constant SSH2_FXF_TRUNC                 => 0x00000010;
use constant SSH2_FXF_EXCL                  => 0x00000020;

#/* status messages */
use constant SSH2_FX_OK                     => 0;
use constant SSH2_FX_EOF                    => 1;
use constant SSH2_FX_NO_SUCH_FILE           => 2;
use constant SSH2_FX_PERMISSION_DENIED      => 3;
use constant SSH2_FX_FAILURE                => 4;
use constant SSH2_FX_BAD_MESSAGE            => 5;
use constant SSH2_FX_NO_CONNECTION          => 6;
use constant SSH2_FX_CONNECTION_LOST        => 7;
use constant SSH2_FX_OP_UNSUPPORTED         => 8;
use constant SSH2_FX_MAX                    => 8;#8 is the highest that is available

use constant MESSAGE_HANDLER => {
    SSH2_FXP_INIT()        => 'processInit',
    SSH2_FXP_OPEN()        => 'processOpen',
    SSH2_FXP_CLOSE()       => 'processClose',
    SSH2_FXP_READ()        => 'processRead',
    SSH2_FXP_WRITE()       => 'processWrite',
    SSH2_FXP_LSTAT()       => 'processLstat',
    SSH2_FXP_FSTAT()       => 'processFstat',
    SSH2_FXP_SETSTAT()     => 'processSetstat',
    SSH2_FXP_FSETSTAT()    => 'processFsetstat',
    SSH2_FXP_OPENDIR()     => 'processOpendir',
    SSH2_FXP_READDIR()     => 'processReaddir',
    SSH2_FXP_REMOVE()      => 'processRemove',
    SSH2_FXP_MKDIR()       => 'processMkdir',
    SSH2_FXP_RMDIR()       => 'processRmdir',
    SSH2_FXP_REALPATH()    => 'processRealpath',
    SSH2_FXP_STAT()        => 'processStat',
    SSH2_FXP_RENAME()      => 'processRename',
    SSH2_FXP_READLINK()    => 'processReadlink',
    SSH2_FXP_SYMLINK()     => 'processSymlink',
    SSH2_FXP_EXTENDED()    => 'processExtended',
};

use constant MESSAGE_TYPES => {
    SSH2_FXP_INIT()        => 'SSH2_FXP_INIT',
    SSH2_FXP_OPEN()        => 'SSH2_FXP_OPEN',
    SSH2_FXP_CLOSE()       => 'SSH2_FXP_CLOSE',
    SSH2_FXP_READ()        => 'SSH2_FXP_READ',
    SSH2_FXP_WRITE()       => 'SSH2_FXP_WRITE',
    SSH2_FXP_LSTAT()       => 'SSH2_FXP_LSTAT',
    SSH2_FXP_FSTAT()       => 'SSH2_FXP_FSTAT',
    SSH2_FXP_SETSTAT()     => 'SSH2_FXP_SETSTAT',
    SSH2_FXP_FSETSTAT()    => 'SSH2_FXP_FSETSTAT',
    SSH2_FXP_OPENDIR()     => 'SSH2_FXP_OPENDIR',
    SSH2_FXP_READDIR()     => 'SSH2_FXP_READDIR',
    SSH2_FXP_REMOVE()      => 'SSH2_FXP_REMOVE',
    SSH2_FXP_MKDIR()       => 'SSH2_FXP_MKDIR',
    SSH2_FXP_RMDIR()       => 'SSH2_FXP_RMDIR',
    SSH2_FXP_REALPATH()    => 'SSH2_FXP_REALPATH',
    SSH2_FXP_STAT()        => 'SSH2_FXP_STAT',
    SSH2_FXP_RENAME()      => 'SSH2_FXP_RENAME',
    SSH2_FXP_READLINK()    => 'SSH2_FXP_READLINK',
    SSH2_FXP_SYMLINK()     => 'SSH2_FXP_SYMLINK',
    SSH2_FXP_EXTENDED()    => 'SSH2_FXP_EXTENDED',
    ALL()                  => 'ALL',
    NET_SFTP_SYMLINKS()    => 'NET_SFTP_SYMLINKS',
    NET_SFTP_RENAME_DIR()  => 'NET_SFTP_RENAME_DIR',
};

use constant ACTIONS => [
                              ALL,
                              NET_SFTP_SYMLINKS,
                              NET_SFTP_RENAME_DIR,
                              SSH2_FXP_OPEN,
                              SSH2_FXP_CLOSE,
                              SSH2_FXP_READ,
                              SSH2_FXP_WRITE,
                              SSH2_FXP_LSTAT,
                              SSH2_FXP_STAT_VERSION_0,
                              SSH2_FXP_FSTAT,
                              SSH2_FXP_SETSTAT,
                              SSH2_FXP_FSETSTAT,
                              SSH2_FXP_OPENDIR,
                              SSH2_FXP_READDIR,
                              SSH2_FXP_REMOVE,
                              SSH2_FXP_MKDIR,
                              SSH2_FXP_RMDIR,
                              SSH2_FXP_STAT,
                              SSH2_FXP_RENAME,
                              SSH2_FXP_READLINK,
                              SSH2_FXP_SYMLINK,
                            ];

use constant STATUS_MESSAGE => [
  "Success",                #/* SSH2_FX_OK */
  "End of file",            #/* SSH2_FX_EOF */
  "No such file",           #/* SSH2_FX_NO_SUCH_FILE */
  "Permission denied",      #/* SSH2_FX_PERMISSION_DENIED */
  "Failure",                #/* SSH2_FX_FAILURE */
  "Bad message",            #/* SSH2_FX_BAD_MESSAGE */
  "No connection",          #/* SSH2_FX_NO_CONNECTION */
  "Connection lost",        #/* SSH2_FX_CONNECTION_LOST */
  "Operation unsupported",  #/* SSH2_FX_OP_UNSUPPORTED */
  "Unknown error"            #/* Others */
];

my $USER = getpwuid($>);
my $ESCALATE_DEBUG = 0;
# --------------------------------------------------------------------
# Do evilness with symbol tables to ge
sub import{
  my $self = shift;
  my $opt = {};
  if (ref $_[0] eq 'HASH'){
    $opt = shift;
  }
  $opt->{log} ||= 'daemon';
  initLog($opt->{log});

  __PACKAGE__->export_to_level(1, $self, @_ ); # Call Exporter.
}
#-------------------------------------------------------------------------------
sub logItem {
  my ($level, $prefix, @msg) = @_;
  syslog $level, "[$USER]: $prefix" . join(" : ", @msg);
}
#-------------------------------------------------------------------------------
sub logDetail {
  logItem( $ESCALATE_DEBUG ? 'info' : 'debug', '', @_);
}
#-------------------------------------------------------------------------------
sub logGeneral {
  logItem('info', '', @_);
}
#-------------------------------------------------------------------------------
sub logWarning {
  logItem('warning', 'WARNING: ', @_);
}
#-------------------------------------------------------------------------------
sub logError {
  logItem('err', 'ERROR: ', @_);
}
#-------------------------------------------------------------------------------
sub initLog {
  my $syslog = shift;
  openlog( 'sftp', 'pid', $syslog);
  my $remote_ip = 'REMOTE_IP_NOT_SET';
  my $remote_port = "0";
  my $local_ip = 'LOCAL_IP_NOT_SET';
  my $local_port = "0";
  if ( $ENV{SSH_CONNECTION} ) {
    ($remote_ip, $remote_port, $local_ip, $local_port) = split(' ', $ENV{SSH_CONNECTION});
  }
  logGeneral "Client connected from $remote_ip:$remote_port";
  logDetail "Client connected to   $local_ip:$local_port";
}
#-------------------------------------------------------------------------------
sub getLogMsg {
  my $self = shift;
  my %arg = @_;

  my $req = $self->{_payload}->getPayloadContent();

  my $process = MESSAGE_TYPES->{$req->{message_type}};

  if ($req->{handle}){
    $req->{name} =  $self->{_payload}->getFilename() ;
  }

  my $msg = '';
  if (defined $arg{response} and $arg{response}->getType() == SSH2_FXP_STATUS ){
    $msg = 'response: ' . STATUS_MESSAGE->[$arg{response}->getStatus()] . ' ';
  }

  $msg .= "process: $process";

  if ($req->{id}){
    $msg .= " id: $req->{id}";
  }

  if ($req->{name}){
    $msg .= " filename: $req->{name}";
  }

  for my $field( qw( source_name target_name off len pflags ) ){
    if (defined $req->{$field}){
      $msg .= " $field: $req->{$field}";
    }
  }

  if ($req->{attr}){
    for my $key (keys %{$req->{attr}}){
      $msg .= " attr-$key: $req->{attr}{$key}";
    }
  }

  return $msg;
}
#-------------------------------------------------------------------------------
sub logAction {
  my $self = shift;

  my $req = $self->{_payload}->getPayloadContent();

  my $msg = $self->getLogMsg();

  if ( $self->{log_action_supress}{ $req->{message_type} } ){
    logDetail $msg;
  }
  else {
    logGeneral $msg;
  }
}
#-------------------------------------------------------------------------------
sub logStatus {
  my $self = shift;
  my $response = shift;
  my $msg = $self->getLogMsg(response => $response);
  my $req = $self->{_payload}->getPayloadContent();

  if ( $response->getType() == SSH2_FXP_STATUS
      and ( $self->{log_all_status} or ( $response->getStatus() != SSH2_FX_OK and $response->getStatus() != SSH2_FX_EOF ) )){
    logGeneral $msg;
  }
  elsif ( $response->getType() == SSH2_FXP_DATA or $req->{message_type} == SSH2_FXP_WRITE ){
    # Do nothing - otherwise we spam the syslog with every read/write packet
  }
  else {
    logDetail $msg;
  }

}
#-------------------------------------------------------------------------------
sub new {
  my $class = shift;
  my $self  = {};
  bless $self, $class;
  Stat::lsMode->novice(0); #disable warnings from this module

  $self->{client_version} = 3; # Just in case we have a bad client that doesn't init the connection properly, treat it as latest version

  my %arg = @_;
  if (defined $arg{debug}     ){ $ESCALATE_DEBUG     = $arg{debug}  };

  $self->{home} = $arg{home} || '/home';
  $self->{home} =~ s!/$!!; # strip trailing /
  if (defined $arg{file_perms}){ $self->{file_perms} = $arg{file_perms} };
  if (defined $arg{dir_perms} ){ $self->{dir_perms}  = $arg{dir_perms}  };

  # if the given home already includes the user's home directory path, allow chroot'ing to a subfolder
  # of the user's home directory
  if ( $self->{home} =~ m/^$ENV{HOME}\/.*/ ) {
    $self->{home_dir} = $self->{home};
  } else {
    $self->{home_dir} = "$self->{home}/$USER";
  }
  $self->{FS} = Net::SFTP::SftpServer::FS->new();
  $self->{FS}->setChrootDir( $self->{home_dir} );
  unless ( -d $self->{home_dir} ){
    logWarning "No sftp folder $self->{home_dir} found for $USER";
    exit 1;
  }
  unless ( -o $self->{home_dir} ){
    logWarning "No $self->{home_dir} is not owned by $USER";
    exit 1;
  }

  if (defined $arg{on_file_sent}){
    $self->{on_file_sent} = $arg{on_file_sent};
  }
  if (defined $arg{on_file_received}){
    $self->{on_file_received} = $arg{on_file_received};
  }
  if (defined $arg{move_on_sent}){
    $self->{move_on_sent} = $arg{move_on_sent};
  }
  if (defined $arg{move_on_received}){
    $self->{move_on_received} = $arg{move_on_received};
  }

  $self->{use_tmp_upload} = (defined $arg{use_tmp_upload} and $arg{use_tmp_upload}) ? 1 : 0;

  $self->{max_file_size}  = (defined $arg{max_file_size}) ? $arg{max_file_size} : 0;

  $self->{valid_filename_char}  = (defined $arg{valid_filename_char} and ref $arg{valid_filename_char} eq 'ARRAY') ? quotemeta join ('', @{$arg{valid_filename_char}}) : '';


  if ( (defined $arg{deny} and $arg{deny} == ALL) or
       (defined $arg{allow} and $arg{allow} != ALL and not defined $arg{deny})
       ){
    $self->{deny} = { map { $_ => 1 } @{ACTIONS()} };
  }

  $arg{deny}  = (not defined $arg{deny})     ?  []         :
                (ref $arg{deny} eq 'ARRAY')  ? $arg{deny}  : [ $arg{deny} ];
  $arg{allow} = (not defined $arg{allow})    ?  []         :
                (ref $arg{allow} eq 'ARRAY') ? $arg{allow} : [ $arg{allow} ];

  for my $deny (@{$arg{deny}}){
    $self->{deny}{$deny} = 1;
  }
  for my $allow (@{$arg{allow}}){
    $self->{deny}{$allow} = 0;
  }

  # These have not been implemented yet
  $self->{deny}{SSH2_FXP_SETSTAT()}  = 1;
  $self->{deny}{SSH2_FXP_FSETSTAT()} = 1;
  $self->{deny}{SSH2_FXP_SYMLINK()}  = 1;
  $self->{deny}{SSH2_FXP_READLINK()} = 1;

  $self->{no_symlinks} = $self->{deny}{NET_SFTP_SYMLINKS()};
  if ($self->{no_symlinks}){
    # if denying symlinks then must deny these
    $self->{deny}{SSH2_FXP_SYMLINK()}  = 1;
    $self->{deny}{SSH2_FXP_READLINK()} = 1;
  }

  $arg{fake_ok} = (not defined $arg{fake_ok})    ?  []         :
                (ref $arg{fake_ok} eq 'ARRAY') ? $arg{fake_ok} : [ $arg{fake_ok} ];
  $self->{fake_ok} = { map {$_ => 1} @{$arg{fake_ok}} };

  $self->{handles} = {};
  $self->{handle_count} = 0;
  $self->{open_handle_count} = 0;

  # Logging levels

  $self->{log_action}  = { map { $_ => 1 } @{ $arg{log_action}  } };
  $self->{log_action_supress} = { map { $_ => 1 }
                          grep { not defined $self->{log_action}{$_} }
                          @{ $arg{log_action_supress} },
                            ( SSH2_FXP_READ,
                              SSH2_FXP_READDIR,
                              SSH2_FXP_WRITE,
                              SSH2_FXP_CLOSE,
                              SSH2_FXP_OPENDIR,
                              SSH2_FXP_STAT,
                              SSH2_FXP_FSTAT,
                              SSH2_FXP_LSTAT,
                              SSH2_FXP_REALPATH,
                               ) };

  $self->{log_all_status} = defined $arg{log_all_status} ? $arg{log_all_status} : 0;

  return $self;
}
#-------------------------------------------------------------------------------
sub run {
  my $self = shift;
  while (1) {
    #/* copy stdin to iqueue */
    # Read 4 byte length of message
    # read length = payload
    my $packet_length = unpack("N", $self->readData(4));
    if ($packet_length > MAX_PACKET_SIZE){
      logError "Packet length of $packet_length received - exiting";
      exit 1;
    }

    my $req;
    eval {
      local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
      alarm TIMEOUT;
      $req = $self->readData( $packet_length );
      alarm 0;
    };
    if ($@) {
      logError "Connection timed out trying to read $packet_length bytes";
      exit 1;
    }

    my $payload       = Net::SFTP::SftpServer::Buffer->new( data => $req );
    $self->{_payload} = $payload; # Keep a copy on self for debug output
    #/* process requests from client */
    # note - all send data will be called from the handler for this message type
    $self->process($payload);
  }
}
#-------------------------------------------------------------------------------
sub readData {
  my $self = shift;
  my $len = shift;
  my $req = '';
  #logDetail "Going to read $len bytes";
  while (length $req < $len){
    my $buf;
    my $read_len = sysread( STDIN, $buf, $len - length $req );
    if ($read_len == 0) {
      logGeneral("Client disconnected");
      $self->closeHandlesOnExit();
      exit 0;
    }
    elsif ($read_len < 0) {
      logWarning("read error");
      $self->closeHandlesOnExit();
      exit 1;
    }
    else {
      $req .= $buf;
    }
  }
  return $req;
}
#-------------------------------------------------------------------------------
sub closeHandlesOnExit {
  my $self = shift;
  for my $fd (values %{$self->{handles}}){
    $fd->close();
    logWarning "Handle for " . $fd->getFilename() . " still open on client exit";
  }
}
#-------------------------------------------------------------------------------
sub sendMessage {
  my $self = shift;
  my $msg = shift;
  #/* copy stdin to iqueue */
  # calc 4 byte length of message
  # put on front of message
  # send to STDOUT
  my $l = length $msg;
  #logDetail "Going to send $l bytes";
  my $len = pack('N', $l);
  my $write_len = syswrite( STDOUT, $len . $msg );
  if ($write_len < 0){
    logWarning "Write Error $!";
    $self->closeHandlesOnExit();
    exit 1;
  }
}
#-------------------------------------------------------------------------------
sub getHandle {
  my $self = shift;
  my $payload = shift;
  my $type = shift || '';
  my $req = $payload->getPayloadContent();
  my $handle_no = $req->{handle};
  if (defined $self->{handles}{$handle_no} and ($type eq '' or $type eq $self->{handles}{$handle_no}->getType())){
    my $handle = $self->{handles}{$handle_no};
    $payload->setFilename( $handle->getFilename() );
    $payload->setFileType( $handle->getType()     );
    return $handle;
  }
  return;
}
#-------------------------------------------------------------------------------
sub deleteHandle {
  my $self = shift;
  my $handle_no = shift;

  if (defined $self->{handles}{$handle_no}){
    $self->{open_handle_count}--;
    delete $self->{handles}{$handle_no};
  }
}
#-------------------------------------------------------------------------------
sub addHandle {
  my $self = shift;
  my $new_handle = shift;
  $self->{handle_count}++;
  $self->{open_handle_count}++;
  if ($self->{open_handle_count} > MAX_OPEN_HANDLES){
    logWarning "Exceeding max handle count";
    return;
  }
  $self->{handles}{$self->{handle_count}} = $new_handle;
  return $self->{handle_count};
}
#-------------------------------------------------------------------------------
sub process {
  my $self = shift;
  my $payload = shift;

  my $req = $payload->getPayloadContent(
    message_type  => 'char',
  );

  my $response = Net::SFTP::SftpServer::Response->new();

  if ($req->{message_type} != SSH2_FXP_INIT){
    # Init does not have an id - it has a client version - handled in processInit
    $req = $payload->getPayloadContent(
      id            => 'int',
    );
    $response->setId( $req->{id} )
  }

  logDetail "Got message_type " . MESSAGE_TYPES->{$req->{message_type}};

  if (defined MESSAGE_HANDLER->{$req->{message_type}}){
    my $method = MESSAGE_HANDLER->{$req->{message_type}};
    $self->$method($payload, $response);
  }
  else {
    logWarning("Unknown message $req->{message_type}");
    $response->setStatus( SSH2_FX_BAD_MESSAGE );
  }
  logWarning "Data left in buffer" unless $payload->done(); # check buffer is empty or warn

  $self->sendResponse( $response );
}
#-------------------------------------------------------------------------------
sub sendResponse {
  my $self = shift;
  my $response = shift;

  $self->logStatus( $response );

  my $msg;
  my $type = $response->getType();

  if ($type == SSH2_FXP_STATUS){
    my $status = $response->getStatus();
    $msg = pack('CNN', SSH2_FXP_STATUS, $response->getId() || 0, $status);
    if ($self->{client_version} >= 3){
      $msg .= pack('N', length STATUS_MESSAGE->[$status]) . STATUS_MESSAGE->[$status] . pack('N', 0);
    }
  }
  elsif ($type == SSH2_FXP_HANDLE){
    my $handle = $response->getHandle();
    $msg = pack('CNN', SSH2_FXP_HANDLE, $response->getId(), length $handle) . $handle;
  }
  elsif ($type == SSH2_FXP_DATA){
    $msg = pack('CNN', SSH2_FXP_DATA, $response->getId(), $response->getDataLength() )  . $response->getData();
  }
  elsif ($type == SSH2_FXP_VERSION){
    $msg = pack('CN', SSH2_FXP_VERSION, $response->getVersion());
  }
  elsif ($type == SSH2_FXP_ATTRS){
    $msg = pack('CN', SSH2_FXP_ATTRS, $response->getId() ) . $self->encodeAttrib( $response->getAttrs() );
  }
  elsif ($type == SSH2_FXP_NAME){
    my $files = $response->getNames();
    $msg = pack('CNN', SSH2_FXP_NAME, $response->getId(), scalar @$files );
    for my $file (@$files) {
      $msg .= pack('N', length $file->{name})      . $file->{name};
      $msg .= pack('N', length $file->{long_name}) . $file->{long_name};
      $msg .= $self->encodeAttrib($file->{attrib});
    }
  }
  else {
    logError "Unhandled response type: $type";
    # Make sure we send something back
    $msg = pack('CNN', SSH2_FXP_STATUS, $response->getId() || 0, SSH2_FX_BAD_MESSAGE );
    if ($self->{client_version} >= 3){
      $msg .= pack('N', length STATUS_MESSAGE->[SSH2_FX_BAD_MESSAGE]) . STATUS_MESSAGE->[SSH2_FX_BAD_MESSAGE] . pack('N', 0);
    }
  }
  $self->sendMessage( $msg );
}
#-------------------------------------------------------------------------------
sub processInit {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent( client_version => 'int' );
  $self->{client_version} = $req->{client_version};
  logGeneral sprintf("Connection accepted, client version: %d", $self->{client_version});

  $response->setInitVersion( SSH2_FILEXFER_VERSION );
}
#-------------------------------------------------------------------------------
sub processOpen {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    name    => 'string',
    pflags  => 'int',         #/* portable flags */
    attr    => 'attrib',
  );

  my $flags  = $self->flagsFromPortable($req->{pflags});
  my $perm = defined $self->{file_perms}                              ? $self->{file_perms}  :
             ($req->{attr}{flags} & SSH2_FILEXFER_ATTR_PERMISSIONS)  ? $req->{attr}{perm}        : 0666;

  $self->logAction();

  return if $self->denyOperation(SSH2_FXP_OPEN, $response);

  my $filename = $self->makeSafeFileName($req->{name});

  if ((not defined $filename) or ($self->{no_symlinks} and $self->{FS}->IsSymlink( $filename ))){
    $response->setStatus( SSH2_FX_NO_SUCH_FILE );
    return;
  }
  # is this an upload
  # We use a tmp file if:
  # We have specified use tmp upload
  # And we have asked to create the file
  # And we are opening for writing
  # And we have either said to truncate the file on opening, or the file does not exist or is empty
  my $use_temp = ($self->{use_tmp_upload}  and
                  $req->{pflags} & SSH2_FXF_CREAT and
                  $req->{pflags} & SSH2_FXF_WRITE and
                  ( $req->{pflags} & SSH2_FXF_TRUNC or $self->{FS}->ZeroSize( $filename ) ) )    ? 1 : 0;

  my $fd = Net::SFTP::SftpServer::File->new( $filename, $flags, $req->{perm}, $use_temp);
  if (not defined $fd) {
    $response->setStatus( $self->errnoToPortable($! + 0) );
  } else {
    my $handle = $self->addHandle($fd);
    if (defined $handle){
      $response->setHandle( $handle );
      logDetail "Opened handle $handle for file $filename";
    }
    else {
      $response->setStatus( SSH2_FX_FAILURE );
    }
  }
}
#-------------------------------------------------------------------------------
sub processClose {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    handle  => 'string',
  );

  $self->logAction();

  my $ret = -1;
  my $status;
  my $fd = $self->getHandle($payload);
  if (defined $fd){
    $ret = $fd->close();
    $response->setStatus( $ret ? SSH2_FX_OK : $self->errnoToPortable($fd->err()) );
    if( $fd->getType() eq 'file'){
      #log file transmission stats
      logGeneral $fd->getStats();
      if (defined $self->{move_on_sent} and $fd->wasSent()){
        $fd->moveToProcessed( %{$self->{move_on_sent}} );
      }
      elsif (defined $self->{move_on_received} and $fd->wasReceived()){
        $fd->moveToProcessed( %{$self->{move_on_received}} );
      }
      if (defined $self->{on_file_sent} and $fd->wasSent()){
        $fd->setCallback();
        eval { $self->{on_file_sent}($fd) };
        if ($@){
          logError "on_file_sent Handler died with $@";
        }
      }
      elsif (defined $self->{on_file_received} and $fd->wasReceived()){
        $fd->setCallback();
        eval { $self->{on_file_received}($fd) };
        if ($@){
          logError "on_file_received Handler died with $@";
        }
      }
    }
  }
  else {
    $response->setStatus( SSH2_FX_NO_SUCH_FILE );
  }

  $self->deleteHandle($req->{handle});
}
#-------------------------------------------------------------------------------
sub processRead {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    handle  => 'string',
    off     => 'int64',
    len     => 'int',
  );

  $self->logAction();

  return if $self->denyOperation(SSH2_FXP_READ, $response);

  my $fd = $self->getHandle($payload, 'file');
  if (defined $fd) {
    if ($fd->sysseek($req->{off}, SEEK_SET) < 0) {
      my $errno = $!+0;
      logWarning "processRead: seek failed $!";
      $response->setStatus( $self->errnoToPortable($errno) );
    } else {
      my $buf;
      my $ret = $fd->sysread( $buf, $req->{len} );
      if ($ret < 0) {
        $response->setStatus( $self->errnoToPortable($!+0) );
      }
      elsif ($ret == 0) {
        $response->setStatus( SSH2_FX_EOF );
      } else {
        $response->setData( $ret, $buf );
        $fd->readBytes( $ret ) if $fd->getReadBytes() eq $req->{off}; #Only log sequential reads
      }
    }
  }
  else {
    $response->setStatus( SSH2_FX_FAILURE );
  }
}
#-------------------------------------------------------------------------------
sub processWrite {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    handle  => 'string',
    off     => 'int64',
    data    => 'string',
  );

  $self->logAction();

  return if $self->denyOperation(SSH2_FXP_WRITE, $response);


  my $fd = $self->getHandle($payload, 'file');
  if (defined $fd) {
    if ($self->{max_file_size} and $req->{off} + length $req->{data} > $self->{max_file_size}){
      logError "Attempt to write greater than Max file size, offset: $req->{off}, data length:" .  length $req->{data} . " on file ". $fd->getFilename();
      $response->setStatus( SSH2_FX_PERMISSION_DENIED );
      return;
    }
    elsif ($self->{max_file_size} and $req->{off} + length $req->{data} > 0.75 * $self->{max_file_size}){
      logWarning "Writing greater than 75% of Max file size, offset: $req->{off}, data length:" .  length $req->{data} . " on file ". $fd->getFilename();
    }
    if ($fd->sysseek($req->{off}, SEEK_SET) < 0) {
      my $errno = $!+0;
      logWarning "processRead: seek failed $!";
      $response->setStatus( $self->errnoToPortable($errno) );
    } else {
      my $len = length $req->{data};
      my $ret = $fd->syswrite($req->{data}, $len);
      if ($ret < 0) {
        logWarning "process_write: write failed";
        $response->setStatus( $self->errnoToPrtable($!+0) );
      }
      elsif ($ret == $len) {
        $fd->wroteBytes( $ret ) if $fd->getWrittenBytes() eq $req->{off}; #Only log sequential writes;
        $response->setStatus( SSH2_FX_OK );
      } else {
        logGeneral("nothing at all written");
      }
    }
  }
}
#-------------------------------------------------------------------------------
sub processDoStat{
  my $self = shift;
  my $mode    = shift;
  my $payload = shift;
  my $response = shift;


  my $req = $payload->getPayloadContent(
    name    => 'string',
  );

  my $filename = $self->makeSafeFileName($req->{name});

  $self->logAction();
  return if $self->denyOperation(($mode ? SSH2_FXP_LSTAT : SSH2_FXP_STAT), $response);

  if ((not defined $filename) or ($self->{no_symlinks} and $self->{FS}->IsSymlink( $filename ))){
    $response->setStatus( SSH2_FX_NO_SUCH_FILE );
    return;
  }
  my @st = $mode ? $self->{FS}->LStat($filename) : $self->{FS}->Stat($filename);
  if (scalar @st == 0) {
    $response->setStatus( $self->errnoToPortable($!+0) );
  }
  else {
    $response->setAttrs( $self->statToAttrib(@st) );
  }
}
#-------------------------------------------------------------------------------
sub processStat {
  my $self = shift;
  my $payload = shift;
  my $response = shift;
  $self->processDoStat(0, $payload, $response);
}
#-------------------------------------------------------------------------------
sub processLstat {
  my $self = shift;
  my $payload = shift;
  my $response = shift;
  $self->processDoStat(1, $payload, $response);
}
#-------------------------------------------------------------------------------
sub processFstat {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $status = SSH2_FX_FAILURE;

  my $req = $payload->getPayloadContent(
    handle  => 'string',
  );

  $self->logAction();

  return if $self->denyOperation(SSH2_FXP_FSTAT, $response);

  my $fd = $self->getHandle($payload);
  if (defined $fd) {
    my @st = stat($fd);
    if (scalar @st == 0) {
      $response->setStatus( $self->errnoToPortable($!+0) );
    } else {
      $response->setAttrs(  $self->statToAttrib(@st) );
    }
  }
  else {
    $response->setStatus( SSH2_FX_FAILURE );
  }
}
#-------------------------------------------------------------------------------
sub processSetstat {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  #We choose not to allow any setting of stats

  my $req = $payload->getPayloadContent(
    name    => 'string',
    attr    => 'attrib',
  );

  $self->logAction();

  my $filename = $self->makeSafeFileName($req->{name});

  if ((not defined $filename) or ($self->{no_symlinks} and $self->{FS}->IsSymlink( $filename ))){
    $response->setStatus( SSH2_FX_NO_SUCH_FILE );
    return;
  }

  return if $self->denyOperation(SSH2_FXP_SETSTAT, $response);

  logError "processSetstat not implemented";
}
#-------------------------------------------------------------------------------
sub processFsetstat {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  #We choose not to allow any setting of stats

  my $req = $payload->getPayloadContent(
    handle  => 'string',
    attr    => 'attrib',
  );

  $self->logAction();

  return if $self->denyOperation(SSH2_FXP_FSETSTAT, $response);

  logError "processFsetstat not implemented";
}
#-------------------------------------------------------------------------------
sub processOpendir {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    name    => 'string',
  );

  $self->logAction();

  my $pathname = $self->makeSafeFileName($req->{name});

  return if $self->denyOperation(SSH2_FXP_OPENDIR, $response);

  if ((not defined $pathname) or ($self->{no_symlinks} and $self->{FS}->IsSymlink( $pathname ))){
    $response->setStatus( SSH2_FX_NO_SUCH_FILE );
    return;
  }

  my $dirp = Net::SFTP::SftpServer::Dir->new($pathname);
  if (!defined $dirp) {
    $response->setStatus( $self->errnoToPortable($!+0) );
  } else {
    my $handle = $self->addHandle($dirp);
    if (defined $handle){
      $response->setHandle( $handle );
    }
    else {
      $response->setStatus( SSH2_FX_FAILURE );
    }
  }
}
#-------------------------------------------------------------------------------
sub processReaddir {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    handle  => 'string',
  );

  $self->logAction();

  return if $self->denyOperation(SSH2_FXP_READDIR, $response);

  my $dirp = $self->getHandle($payload, 'dir');
  if (not defined $dirp) {
    $response->setStatus( SSH2_FX_FAILURE );
  }
  else {
    my $fullpath = $dirp->getPath();
    my $stats = [];
    my $count = 0;
    while (my $dp = $dirp->readdir()) {
      my $pathname = $fullpath . $dp;
      next if ( $self->{no_symlinks} and $self->{FS}->IsSymlink( $pathname ) ); # we only inform the user about files and directories
    my @st = $self->{FS}->LStat($pathname);
      next unless scalar @st;
      my $file = {};
      $file->{attrib} = $self->statToAttrib(@st);
      $file->{name} = $dp;
      $file->{long_name} = $self->lsFile($dp, \@st);
      $count++;
      push @{$stats}, $file;
      #/* send up to 100 entries in one message */
      #/* XXX check packet size instead */
      last if $count == 100;
    }
    if ($count > 0) {
      $response->setNames($stats);
    }
    else {
      $response->setStatus( SSH2_FX_EOF );
    }
  }
}
#-------------------------------------------------------------------------------
sub processRemove {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    name    => 'string',
  );

  $self->logAction();

  my $filename = $self->makeSafeFileName($req->{name});

  logDetail sprintf("processRemove: remove id %u name %s", $req->{id}, $req->{name});

  return if $self->denyOperation(SSH2_FXP_REMOVE, $response);

  if ((not defined $filename) or ($self->{no_symlinks} and $self->{FS}->IsSymlink( $filename ))){
    $response->setStatus( SSH2_FX_NO_SUCH_FILE );
    return;
  }

  my $ret = $self->{FS}->Unlink($filename);
  my $status = $ret ?  SSH2_FX_OK : $self->errnoToPortable($!+0);
  if ( $status == SSH2_FX_OK ){
    logGeneral "Removed $filename";
  }
  $response->setStatus( $status );
}
#-------------------------------------------------------------------------------
sub processMkdir {
  my $self = shift;
  my $payload = shift;
  my $response = shift;


  my $req = $payload->getPayloadContent(
    name    => 'string',
    attr    => 'attrib',
  );

  my $filename = $self->makeSafeFileName($req->{name});

  my $mode = defined $self->{dir_perms}                              ? $self->{dir_perms}        :
             ($req->{attr}{flags} & SSH2_FILEXFER_ATTR_PERMISSIONS)  ? $req->{attr}{perm} & 0777 : 0777;

  $self->logAction();

  return if $self->denyOperation(SSH2_FXP_MKDIR, $response);

  if (not defined $filename){
    $response->setStatus( SSH2_FX_NO_SUCH_FILE );
    return;
  }

  my $ret = $self->{FS}->Mkdir($filename, $mode);
  $response->setStatus( $ret ? SSH2_FX_OK : $self->errnoToPortable($!+0) );
}
#-------------------------------------------------------------------------------
sub processRmdir {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    name    => 'string',
  );

  my $filename = $self->makeSafeFileName($req->{name});

  $self->logAction();

  return if $self->denyOperation(SSH2_FXP_RMDIR, $response);

  if (not defined $filename){
    $response->setStatus( SSH2_FX_NO_SUCH_FILE );
    return;
  }

  my $ret = $self->{FS}->Rmdir($filename);
  $response->setStatus( $ret ? SSH2_FX_OK : $self->errnoToPortable($!+0) );
}
#-------------------------------------------------------------------------------
sub processRealpath {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    name    => 'string',
  );

  $self->logAction();

  my $path     = $self->makeSafeFileName($req->{name});

  logDetail sprintf("processRealpath: realpath id %u path %s", $req->{id}, $req->{name});

  my $file = { name => $path, long_name => $path, attrib => { flags => 0 } };

  $response->setNames( $file );
}
#-------------------------------------------------------------------------------
sub processRename {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    source_name  => 'string',
    target_name  => 'string',
  );

  my $oldpath  = $self->makeSafeFileName($req->{source_name});
  my $newpath  = $self->makeSafeFileName($req->{target_name});

  $self->logAction();

  return if $self->denyOperation(SSH2_FXP_RENAME, $response);

  if ((not defined $oldpath or not defined $newpath) or ($self->{no_symlinks} and $self->{FS}->IsSymlink( $oldpath ) )){
    $response->setStatus( SSH2_FX_NO_SUCH_FILE );
    return;
  }

  return if $self->{FS}->IsDir( $oldpath ) and $self->denyOperation(NET_SFTP_RENAME_DIR, $response);

  if ( $self->{FS}->IsFile( $oldpath )) {
    #/* Race-free rename of regular files */
    if (! $self->{FS}->Link( $oldpath,  $newpath)) {#FIXME test all codepaths
      # link method failed - try just a rename
      if (! $self->{FS}->Rename($oldpath, $newpath)){
        $response->setStatus($self->errnoToPortable($!+0));
      }
      else {
        $response->setStatus(SSH2_FX_OK);
      }
    }
    elsif (! $self->{FS}->Unlink($oldpath)) {
      $response->setStatus( $self->errnoToPortable($!+0) );
      #/* clean spare link */
      $self->{FS}->Unlink($newpath);
    }
    else {
      $response->setStatus(SSH2_FX_OK);
    }
  }
  elsif ( $self->{FS}->IsDir( $oldpath ) ) {
    if (! $self->{FS}->Rename($oldpath, $newpath)){
      $response->setStatus($self->errnoToPortable($!+0));
    }
    else {
      $response->setStatus(SSH2_FX_OK);
    }
  }
  else {
    # File does not exist or is a symlink - deny all knowlege
    $response->setStatus(SSH2_FX_NO_SUCH_FILE);
  }
}
#-------------------------------------------------------------------------------
sub processReadlink {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    name     => 'string',
  );

  $self->logAction();

  $response->setStatus(SSH2_FX_NO_SUCH_FILE); # all symlinks hidden
}
#-------------------------------------------------------------------------------
sub processSymlink {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    source_name  => 'string',
    target_name  => 'string',
  );

  my $oldpath  = $self->makeSafeFileName($req->{source_name});
  my $newpath  = $self->makeSafeFileName($req->{target_name});

  $self->logAction();

  return if $self->denyOperation(SSH2_FXP_SYMLINK, $response);

  logError "processSymlink not implemented";
}
#-------------------------------------------------------------------------------
sub processExtended {
  my $self = shift;
  my $payload = shift;
  my $response = shift;

  my $req = $payload->getPayloadContent(
    request  => 'string',
  );

  $self->logAction();

  $response->setStatus( SSH2_FX_OP_UNSUPPORTED );    #/* MUST */
}
#-------------------------------------------------------------------------------
sub denyOperation {
  my $self = shift;
  my ($op, $response) = @_;
  if (defined $self->{deny}{$op} and $self->{deny}{$op}){
    logWarning "Denying request operation: " . MESSAGE_TYPES->{$op} . ", id: " . $response->getId();
    if (defined $self->{fake_ok}{$op} and $self->{fake_ok}{$op}){
      $response->setStatus( SSH2_FX_OK );
    }
    else {
      $response->setStatus( SSH2_FX_PERMISSION_DENIED );
    }
    return 1;
  }
  return;
}
#-------------------------------------------------------------------------------
sub lsFile {
  my $self = shift;
  my $name = shift;
  my $st = shift;
  my @ltime = localtime($st->[9]);
  my $mode = format_mode($st->[2]);

  my $user  = getpwuid($st->[4]);
  my $group = getgrgid($st->[5]);
  my $sz;
  if (scalar @ltime) {
    if (time() - $st->[9] < (365*24*60*60)/2){
      $sz = strftime "%b %e %H:%M", @ltime;
    }
    else {
      $sz = strftime "%b %e  %Y",   @ltime;
    }
  }

  my $ulen = length $user  > 8 ? length $user  : 8;
  my $glen = length $group > 8 ? length $group : 8;
  return sprintf("%s %3u %-*s %-*s %8llu %s %s", $mode, $st->[3], $ulen, $user, $glen, $group, $st->[7], $sz, $name);
}
#-------------------------------------------------------------------------------
sub makeSafeFileName {
  my $self = shift;
  # We force all file names to be treated as from / which we treat as the users home directory
  my $name = shift;

  $name = "/$name";
  while ($name =~ s!/\./!/!g)   {}
  $name =~ s!//+!/!g;

  my @path = split('/', $name);
  my @newpath;
  for my $d (@path){
    if ($d eq  '..'){
      pop @newpath;
    }
    elsif ($d ne '.') {
      if ($self->{valid_filename_char}){
        if ($d !~ /^[$self->{valid_filename_char}]*$/){
          logError "Invalid characters in $name";
          return;
        }
      }
      push @newpath, $d;
    }
    if ($self->{no_symlinks}){
      if ( $self->{FS}->IsSymlink( join('/', @newpath) ) ){
        return; # no symlinks
      }
    }
  }

  $name = join('/', @newpath) || '/';
  $name =~ s!/\.$!/!;
  return $name;
}
#-------------------------------------------------------------------------------
sub encodeAttrib {
  my $self = shift;
  my $attr = shift;
  $attr->{flags} ||= 0;
  my $msg = pack('N', $attr->{flags});
  if ($attr->{flags} & SSH2_FILEXFER_ATTR_SIZE){
    my $h = int($attr->{size} / (1 << 32));
    my $l =     $attr->{size} % (1 << 32);
    $msg .= pack('NN', $h, $l );
  }
  if ($attr->{flags} & SSH2_FILEXFER_ATTR_UIDGID) {
    $msg .= pack('N', $attr->{uid});
    $msg .= pack('N', $attr->{gid});
  }
  if ($attr->{flags} & SSH2_FILEXFER_ATTR_PERMISSIONS){
    $msg .= pack('N', $attr->{perm});
  }
  if ($attr->{flags} & SSH2_FILEXFER_ATTR_ACMODTIME) {
    $msg .= pack('N', $attr->{atime});
    $msg .= pack('N', $attr->{mtime});
  }
  return $msg;
}
#-------------------------------------------------------------------------------
sub statToAttrib {
  my $self = shift;
  my @stats = @_;
  #/* Convert from struct stat to filexfer attribs */
  my $attr = {};
  $attr->{flags} = 0;
  $attr->{flags} |= SSH2_FILEXFER_ATTR_SIZE;
  $attr->{size} = $stats[7];
  $attr->{flags} |= SSH2_FILEXFER_ATTR_UIDGID;
  $attr->{uid} = $stats[4];
  $attr->{gid} = $stats[5];
  $attr->{flags} |= SSH2_FILEXFER_ATTR_PERMISSIONS;
  $attr->{perm} = $stats[2];
  $attr->{flags} |= SSH2_FILEXFER_ATTR_ACMODTIME;
  $attr->{atime} = $stats[8];
  $attr->{mtime} = $stats[9];

  return $attr;
}
#-------------------------------------------------------------------------------
sub flagsFromPortable{
  my $self = shift;
  my $pflags = shift;
  my $flags = 0;

  if (($pflags & SSH2_FXF_READ) &&
      ($pflags & SSH2_FXF_WRITE)) {
    $flags = O_RDWR;
  }
  elsif ($pflags & SSH2_FXF_READ) {
    $flags = O_RDONLY;
  }
  elsif ($pflags & SSH2_FXF_WRITE) {
    $flags = O_WRONLY;
  }
  if ($pflags & SSH2_FXF_CREAT){
    $flags |= O_CREAT;
  }
  if ($pflags & SSH2_FXF_TRUNC){
    $flags |= O_TRUNC;
  }
  if ($pflags & SSH2_FXF_EXCL){
    $flags |= O_EXCL;
  }
  return $flags;
}
#-------------------------------------------------------------------------------
sub errnoToPortable {
  my $self = shift;
  my $errno = shift;

  if ($errno == 0){
    logWarning "Good error code received by errnoToPortable";
    return SSH2_FX_OK;
  }
  elsif ( $errno ==  ENOENT or
          $errno ==  ENOTDIR or
          $errno ==  EBADF or
          $errno ==  ELOOP ){
    return SSH2_FX_NO_SUCH_FILE;
  }
  elsif ( $errno ==   EPERM or
          $errno ==   EACCES or
          $errno ==   EFAULT ){
    return SSH2_FX_PERMISSION_DENIED;
  }
  elsif ( $errno == ENAMETOOLONG or
          $errno ==   EINVAL){
    return SSH2_FX_BAD_MESSAGE;
  }
  else {
    return SSH2_FX_FAILURE;
  }
}
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
package Net::SFTP::SftpServer::Buffer;
use strict;
use warnings;

#/* attributes */
use constant SSH2_FILEXFER_ATTR_SIZE        => 0x00000001;
use constant SSH2_FILEXFER_ATTR_UIDGID      => 0x00000002;
use constant SSH2_FILEXFER_ATTR_PERMISSIONS => 0x00000004;
use constant SSH2_FILEXFER_ATTR_ACMODTIME   => 0x00000008;
use constant SSH2_FILEXFER_ATTR_EXTENDED    => 0x80000000;

1;
#-------------------------------------------------------------------------------
sub new {
  my $class = shift;
  my $self  = {};
  bless $self, $class;
  my %arg = @_;
  $self->{data} = $arg{data};
  return $self;
}
#-------------------------------------------------------------------------------
sub asString {
  my $self = shift;

  my @strings;
  push @strings, length $self->{data} . " bytes left to decode";
  push @strings, "Decoded: ";
  for my $key ( sort keys %{$self->{_decoded_data}} ){
    if ($key eq 'data' and $self->{_decoded_data}{data} !~ /^[\s\w]*$/){
      push @strings, "$key\t\t=><Binary data>";
    }
    else {
      push @strings, "$key\t\t=>$self->{_decoded_data}{$key}";
    }
  }

  return join("\n", @strings)
}
# ------------------------------------------------------------------------------
sub getPayloadContent {
  my $self = shift;

  while ( my $name = shift and my $type = shift ){
    if ($type eq 'int'){
      $self->{_decoded_data}{$name} = $self->getInt();
    }
    elsif ($type eq 'int64'){
      $self->{_decoded_data}{$name} = $self->getInt64();
    }
    elsif ($type eq 'char'){
      $self->{_decoded_data}{$name} = $self->getChar();
    }
    elsif ($type eq 'string'){
      $self->{_decoded_data}{$name} = $self->getString();
    }
    elsif ($type eq 'attrib'){
      $self->{_decoded_data}{$name} = $self->getAttrib();
    }
  }

  return $self->{_decoded_data};
}
# ------------------------------------------------------------------------------
sub getInt {
  my $self = shift;
  my $i = substr($self->{data}, 0, 4);
  $self->{data} = substr($self->{data}, 4);
  return unpack("N", $i);
}
# ------------------------------------------------------------------------------
sub getInt64 {
  my $self = shift;
  my $i = substr($self->{data}, 0, 8);
  $self->{data} = substr($self->{data}, 8);
  my ($h, $l) = unpack("NN", $i);
  return ($h << 32) + $l;
}
# ------------------------------------------------------------------------------
sub getChar {
  my $self = shift;
  my $c = substr($self->{data}, 0, 1);
  $self->{data} = substr($self->{data}, 1);
  return unpack("C", $c);
}
# ------------------------------------------------------------------------------
sub getString {
  my $self = shift;
  my $len = $self->getInt();
  my $str = substr($self->{data}, 0, $len);
  $self->{data} = substr($self->{data}, $len);
  return $str;
}
#-------------------------------------------------------------------------------
sub getAttrib {
  my $self = shift;
  #/* Decode attributes in buffer */

  my $attr = {};

  $attr->{flags} = $self->getInt();
  if ($attr->{flags} & SSH2_FILEXFER_ATTR_SIZE){
    $attr->{size} = $self->getInt64();
  }
  if ($attr->{flags} & SSH2_FILEXFER_ATTR_UIDGID) {
    $attr->{uid} = $self->getInt();
    $attr->{gid} = $self->getInt();
  }
  if ($attr->{flags} & SSH2_FILEXFER_ATTR_PERMISSIONS){
    $attr->{perm} = $self->getInt();
  }
  if ($attr->{flags} & SSH2_FILEXFER_ATTR_ACMODTIME) {
    $attr->{atime} = $self->getInt();
    $attr->{mtime} = $self->getInt();
  }

  #/* vendor-specific extensions */
  if ($attr->{flags} & SSH2_FILEXFER_ATTR_EXTENDED) {
    my $count = $self->getInt();
    for (my $i = 0; $i < $count; $i++) {
      my $type = $self->getString();
      my $req = $self->getString();
      logDetail("Got file attribute \"%s\"", $type);
    }
  }
  return $attr;
}
# ------------------------------------------------------------------------------
sub done {
  my $self = shift;
  return 1 if length $self->{data} eq 0;
  return;
}
#-------------------------------------------------------------------------------
sub setFileType {
  my $self = shift;
  $self->{file_type} = shift;
}
#-------------------------------------------------------------------------------
sub getFileType {
  my $self = shift;
  return $self->{file_type};
}
#-------------------------------------------------------------------------------
sub setFilename {
  my $self = shift;
  $self->{filename} = shift;
}
#-------------------------------------------------------------------------------
sub getFilename {
  my $self = shift;
  return $self->{filename};
}
1;
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
package Net::SFTP::SftpServer::Response;
use strict;
use warnings;

#/* server to client */
use constant SSH2_FXP_VERSION               => 2;
use constant SSH2_FXP_STATUS                => 101;
use constant SSH2_FXP_HANDLE                => 102;
use constant SSH2_FXP_DATA                  => 103;
use constant SSH2_FXP_NAME                  => 104;
use constant SSH2_FXP_ATTRS                 => 105;

1;
#-------------------------------------------------------------------------------
sub new {
  my $class = shift;
  my $self  = {};
  bless $self, $class;
  return $self;
}
#-------------------------------------------------------------------------------
sub asString {
  my $self = shift;

  my @strings;
  for my $key ( sort keys %$self ){
    if ($key eq 'data' and $self->{data} !~ /^[\s\w]*$/){
      push @strings, "$key\t\t=><Binary data>";
    }
    else {
      push @strings, "$key\t\t=>$self->{$key}";
    }
  }

  return join("\n", @strings)
}
#-------------------------------------------------------------------------------
sub setId {
  my $self = shift;
  $self->{id} = shift;
}
#-------------------------------------------------------------------------------
sub getId {
  my $self = shift;
  return $self->{id};
}
#-------------------------------------------------------------------------------
sub getType {
  my $self = shift;
  return $self->{type};
}
#-------------------------------------------------------------------------------
sub setStatus {
  my $self = shift;
  $self->{status} = shift;
  $self->{type} = SSH2_FXP_STATUS;
}
#-------------------------------------------------------------------------------
sub getStatus {
  my $self = shift;
  return $self->{status};
}
#-------------------------------------------------------------------------------
sub setData {
  my $self = shift;
  $self->{data_length} = shift;
  $self->{data} = shift;
  $self->{type} = SSH2_FXP_DATA;
}
#-------------------------------------------------------------------------------
sub getData {
  my $self = shift;
  return $self->{data};
}
#-------------------------------------------------------------------------------
sub getDataLength {
  my $self = shift;
  return $self->{data_length};
}
#-------------------------------------------------------------------------------
sub setHandle {
  my $self = shift;
  $self->{handle} = shift;
  $self->{type} = SSH2_FXP_HANDLE;
}
#-------------------------------------------------------------------------------
sub getHandle {
  my $self = shift;
  return $self->{handle};
}
#-------------------------------------------------------------------------------
sub setNames {
  my $self = shift;
  $self->{names} = shift;
  $self->{names} = [ $self->{names} ] unless ref $self->{names} eq 'ARRAY';
  $self->{type} = SSH2_FXP_NAME;
}
#-------------------------------------------------------------------------------
sub getNames {
  my $self = shift;
  return $self->{names};
}
#-------------------------------------------------------------------------------
sub setInitVersion {
  my $self = shift;
  $self->{version} = shift;
  $self->{type} = SSH2_FXP_VERSION;
}
#-------------------------------------------------------------------------------
sub getVersion {
  my $self = shift;
  return $self->{version};
}
#-------------------------------------------------------------------------------
sub setAttrs {
  my $self = shift;
  $self->{attr} = shift;
  $self->{type} = SSH2_FXP_ATTRS;
}
#-------------------------------------------------------------------------------
sub getAttrs {
  my $self = shift;
  return $self->{attr};
}
1;
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
package Net::SFTP::SftpServer::FS;

no strict;

use Exporter qw( import );

@EXPORT = qw(
  setChrootDir
);

use strict;
use warnings;

{
  my %callback_of;

  my $chroot_dir = '';

  #-------------------------------------------------------------------------------
  sub new {
    my $class = shift;
    my $self  = bless \do{my $anon}, $class;
    return unless $self->initialise( @_ ); # Dont keep the object unless we initialise sucessfully

    my $ident = scalar $self;

    $callback_of{$ident} = 0;

    return $self;
  }
  #-------------------------------------------------------------------------------
  sub initialise {
    return 1;
  }
  #-------------------------------------------------------------------------------
  sub setChrootDir {
    my $self = shift;
    $chroot_dir = shift;
  }
  #-------------------------------------------------------------------------------
  sub IsSymlink {
    my $self = shift;
    return -l $chroot_dir . shift;
  }
  #-------------------------------------------------------------------------------
  sub Exists {
    my $self = shift;
    return -e $chroot_dir . shift;
  }
  #-------------------------------------------------------------------------------
  sub IsFile {
    my $self = shift;
    return -f $chroot_dir . shift;
  }
  #-------------------------------------------------------------------------------
  sub IsDir {
    my $self = shift;
    return -d $chroot_dir . shift;
  }
  #-------------------------------------------------------------------------------
  sub ZeroSize {
    my $self = shift;
    return -z $chroot_dir . shift;
  }
  #-------------------------------------------------------------------------------
  sub Link {
    my $self = shift;
    return link( $chroot_dir . shift, $chroot_dir . shift);
  }
  #-------------------------------------------------------------------------------
  sub LStat {
    my $self = shift;
    return lstat $chroot_dir . shift;
  }
  #-------------------------------------------------------------------------------
  sub Stat {
    my $self = shift;
    return stat $chroot_dir . shift;
  }
  #-------------------------------------------------------------------------------
  sub Size {
    my $self = shift;
    return -s $chroot_dir . shift;
  }
  #-------------------------------------------------------------------------------
  sub Unlink {
    my $self = shift;
    return unlink $chroot_dir . shift;
  }
  #-------------------------------------------------------------------------------
  sub Mkdir {
    my $self = shift;
    return mkdir( $chroot_dir . shift, shift);
  }
  #-------------------------------------------------------------------------------
  sub Rmdir {
    my $self = shift;
    return rmdir $chroot_dir . shift;
  }
  #-------------------------------------------------------------------------------
  sub Rename {
    my $self = shift;
    my ($old, $new) = @_;
    return rename( $chroot_dir . $old, $chroot_dir . $new);
  }
  #-------------------------------------------------------------------------------
  sub chrootDir {
    my $self = shift;
    return $chroot_dir;
  }
  #-------------------------------------------------------------------------------
  sub setCallback {
    my $self = shift;
    my $ident = scalar($self);
    $callback_of{$ident} = 1;
  }
  #-------------------------------------------------------------------------------
  sub callback {
    my $self = shift;
    my $ident = scalar($self);
    return $callback_of{$ident};
  }
  #-------------------------------------------------------------------------------
  sub DESTROY {
    my $self = shift;
    my $ident = scalar($self);
    delete $callback_of{$ident};
  }
}
1;
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
package Net::SFTP::SftpServer::FileChrootBroken;

use strict;
use warnings;

our $AUTOLOAD;

sub AUTOLOAD {
  my $self = shift;

  my $method = $AUTOLOAD;
  $method =~ m/.+::(.+)(?!::)/;
  $method = $1 if $1;

  Net::SFTP::SftpServer::logError "$method is not supported after chroot is broken";

  return;
}
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
package Net::SFTP::SftpServer::File;
use strict;
use warnings;

use IO::File;
use File::Basename;
use Fcntl qw( O_RDWR O_CREAT O_TRUNC O_EXCL O_RDONLY O_WRONLY SEEK_SET );

use base qw( Net::SFTP::SftpServer::FS );

{
  my $TMP_EXT = ".SftpXFR.$$";

  my %fh_of;
  my %filename_of;
  my %mode_of;
  my %perm_of;
  my %write_of;
  my %read_of;
  my %opentime_of;
  my %use_temp_of;
  my %err_of;
  my %state_of;

  #-------------------------------------------------------------------------------
  sub initialise {
    my $self = shift;

    my ($filename, $mode, $perm, $use_tmp) = @_;

    $use_tmp ||= 0;
    my $realfile = $filename;
    if ($use_tmp){
      $filename .= $TMP_EXT;
    }

    my $fd = IO::File->new($self->chrootDir . $filename, $mode, $perm);

    return unless defined $fd;

    my $ident = scalar($self);
    $filename_of{$ident} = $realfile;
    $fh_of{$ident}       = $fd;
    $mode_of{$ident}     = $mode;
    $perm_of{$ident}     = $perm;
    $write_of{$ident}    = 0;
    $read_of{$ident}     = 0;
    $opentime_of{$ident} = time();
    $use_temp_of{$ident} = $use_tmp;
    $state_of{$ident}    = 'open';

    return 1;
  }
  #-------------------------------------------------------------------------------
  sub err {
    my $self = shift;
    my $ident = scalar($self);

    return $err_of{$ident};
  }
  #-------------------------------------------------------------------------------
  sub close {
    my $self = shift;
    my $ident = scalar($self);
    my $ret = $fh_of{$ident}->close();
    unless ($ret){
      $err_of{$ident} = $!+0;
    }

    if ($use_temp_of{$ident}){
      $self->Rename( $filename_of{$ident} . $TMP_EXT, $filename_of{$ident} );
      $use_temp_of{$ident} = 0;
    }

    $state_of{$ident}    = 'closed';
    return $ret;
  }
  #-------------------------------------------------------------------------------
  sub getFilename {
    my $self = shift;
    my $ident = scalar($self);
    return $filename_of{$ident};
  }
  #-------------------------------------------------------------------------------
  sub getMode {
    my $self = shift;
    my $ident = scalar($self);
    return $mode_of{$ident};
  }
  #-------------------------------------------------------------------------------
  sub getPerm {
    my $self = shift;
    my $ident = scalar($self);
    return $perm_of{$ident};
  }
  #-------------------------------------------------------------------------------
  sub wroteBytes {
    my $self = shift;
    my $ident = scalar($self);
    my $size = shift;
    $write_of{$ident} += $size;
  }
  #-------------------------------------------------------------------------------
  sub readBytes {
    my $self = shift;
    my $ident = scalar($self);
    my $size = shift;
    $read_of{$ident} += $size;
  }
  #-------------------------------------------------------------------------------
  sub getWrittenBytes {
    my $self = shift;
    my $ident = scalar($self);
    return $write_of{$ident};
  }
  #-------------------------------------------------------------------------------
  sub getReadBytes {
    my $self = shift;
    my $ident = scalar($self);
    $read_of{$ident};
  }
  #-------------------------------------------------------------------------------
  sub getStats {
    my $self = shift;
    my $ident = scalar($self);
    my $stats = "Filename: $filename_of{$ident} ";
    my $dtime = (time() - $opentime_of{$ident}) || 1;
    if ($write_of{$ident} and $read_of{$ident}){
      ## reads and writes
      my $speed = int(($write_of{$ident} + $read_of{$ident}) / (1024 * $dtime));
      $stats .= "Received: $write_of{$ident} bytes Sent: $read_of{$ident} in $dtime seconds Speed: $speed K/s";
    }
    elsif ($write_of{$ident}){
      # File received
      my $speed = int($write_of{$ident} / (1024 * $dtime));
      $stats .= "Received: $write_of{$ident} bytes in $dtime seconds Speed: $speed K/s";
    }
    elsif ($read_of{$ident}){
      # File Sent
      my $speed = int($read_of{$ident} / (1024 * $dtime));
      $stats .= "Sent: $read_of{$ident} bytes in $dtime seconds Speed: $speed K/s";
    }
    else {
      $stats .= "No data sent or received";
    }
    return $stats;
  }
  #-------------------------------------------------------------------------------
  sub wasReceived {
    my $self = shift;
    my $ident = scalar($self);
    if ($write_of{$ident} and ! $read_of{$ident} and $self->Size( $filename_of{$ident} ) eq $write_of{$ident}){
      return 1;
    }
    return;
  }
  #-------------------------------------------------------------------------------
  sub wasSent {
    my $self = shift;
    my $ident = scalar($self);
    if ($read_of{$ident} and ! $write_of{$ident} and $self->Size( $filename_of{$ident} ) eq $read_of{$ident}){
      return 1;
    }
    return;
  }
  #-------------------------------------------------------------------------------
  sub getType {
    my $self = shift;
    return 'file';
  }
  #-------------------------------------------------------------------------------
  sub sysread {
    my $self = shift;
    my $ident = scalar($self);
    return $fh_of{$ident}->sysread( @_ );
  }
  #-------------------------------------------------------------------------------
  sub syswrite {
    my $self = shift;
    my $ident = scalar($self);
    return $fh_of{$ident}->syswrite( @_ );
  }
  #-------------------------------------------------------------------------------
  sub sysseek {
    my $self = shift;
    my $ident = scalar($self);
    return $fh_of{$ident}->sysseek( @_ );
  }
  #-------------------------------------------------------------------------------
  sub read {
    my $self = shift;
    my $ident = scalar($self);
    unless ( $self->callback ){
      Net::SFTP::SftpServer::logError "read method called outside from callback";
      return;
    }

    if ($state_of{$ident} ne 'open'){
      $fh_of{$ident}->open( $self->chrootDir . $filename_of{$ident}, '<' );
      $state_of{$ident} = 'open';
    }
    return $fh_of{$ident}->read( @_ );
  }
  #-------------------------------------------------------------------------------
  sub open {
    my $self = shift;
    my $ident = scalar($self);
    unless ( $self->callback ){
      Net::SFTP::SftpServer::logError "open method called outside from callback";
      return;
    }

    if ($state_of{$ident} ne 'open'){
      my $ret = $fh_of{$ident}->open( $self->chrootDir . $filename_of{$ident}, @_ );
      $state_of{$ident} = 'open';
      return $ret;
    }
  }
  #-------------------------------------------------------------------------------
  sub moveToProcessed {
    my $self = shift;
    my %arg = @_;

    my $ident = scalar $self;

    if ($arg{BREAKCHROOT}){
      return $self->moveToProcessedBREAKCHROOT( @_ );
    }

    $arg{dst}         ||= 'processed';
    $arg{dir_perms}   ||= 0770;

    unless ($self->Exists($filename_of{$ident})){
      Net::SFTP::SftpServer::logWarning "moveToProcessed: File $filename_of{$ident} does not exist";
      return;
    }


    if ($filename_of{$ident} =~ m!/$arg{dst}/!){
      # file is already in a processed directory
      return;
    }

    if ($arg{filename_condition}){
      return unless ($filename_of{$ident} =~ m/$arg{filename_condition}/ );
    }

    my $dir = dirname($filename_of{$ident});
    if (! $self->Exists( "$dir/processed" )){
      unless ($self->Mkdir( "$dir/processed", $arg{dir_perms} )){
        Net::SFTP::SftpServer::logWarning "moveToProcessed: failed to mkdir $dir/processed";
        return;
      }
    }
    elsif (! $self->IsDir( "$dir/processed") ){
      Net::SFTP::SftpServer::logWarning "moveToProcessed: $dir/processed exists but is not a directory";
      return;
    }

    my $name = fileparse($filename_of{$ident});
    if ( $self->Exists( "$dir/processed/$name" ) ){
      Net::SFTP::SftpServer::logWarning "moveToProcessed: cannot move $filename_of{$ident} - $dir/processed/$name already exists";
      return;
    }

    unless ($self->Rename( $filename_of{$ident}, "$dir/processed/$name" )){
      Net::SFTP::SftpServer::logWarning "moveToProcessed: failed to rename $filename_of{$ident} to $dir/processed/$name";
      return;
    }

    $filename_of{$ident} = "$dir/processed/$name";

    Net::SFTP::SftpServer::logGeneral "moveToProcessed: moved $filename_of{$ident} to $dir/processed/$name";
  }
  #-------------------------------------------------------------------------------
  sub moveToProcessedBREAKCHROOT {
    my $self = shift;
    my %arg = @_;

    my $ident = scalar $self;

    unless ( -d $arg{dst} and -w $arg{dst} ){
      Net::SFTP::SftpServer::logWarning "Cannot write to target directory $arg{dst}";
      return;
    }

    unless ($self->Exists($filename_of{$ident})){
      Net::SFTP::SftpServer::logWarning "moveToProcessed: File $filename_of{$ident} does not exist";
      return;
    }

    if ($arg{filename_condition}){
      return unless ($filename_of{$ident} =~ m/$arg{filename_condition}/ );
    }

    my $name = fileparse($filename_of{$ident});

    bless $self, 'Net::SFTP::SftpServer::FileChrootBroken';

    $self->renameBREADCHROOT( $arg{dst} . "/$name" );

    Net::SFTP::SftpServer::logGeneral "moveToProcessed: moved $filename_of{$ident} to $arg{dst}/$name";
  }
  #-------------------------------------------------------------------------------
  sub getFullFilenameBREAKCHROOT {
    my $self = shift;
    my $ident = scalar $self;

    my $chroot_dir = $self->chrootDir;

    bless $self, 'Net::SFTP::SftpServer::FileChrootBroken';

    return $chroot_dir . $filename_of{$ident}
  }
  #-------------------------------------------------------------------------------
  sub renameBREAKCHROOT {
    my $self = shift;
    my $ident = scalar $self;

    my $newname = shift;

    my $chroot_dir = $self->chrootDir;

    bless $self, 'Net::SFTP::SftpServer::FileChrootBroken';

    return rename $chroot_dir . $filename_of{$ident}, $newname;
  }
  #-------------------------------------------------------------------------------
  sub DESTROY {
    my $self = shift;
    my $ident = scalar($self);

    $fh_of{$ident}->close() if defined $fh_of{$ident} and $fh_of{$ident}->opened;
    delete $fh_of{$ident};
    delete $filename_of{$ident};
    delete $mode_of{$ident};
    delete $perm_of{$ident};
    delete $write_of{$ident};
    delete $read_of{$ident};
    delete $opentime_of{$ident};
    delete $use_temp_of{$ident};
    delete $err_of{$ident};
    delete $state_of{$ident};

    $self->SUPER::DESTROY()
  }
}
1;
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
package Net::SFTP::SftpServer::Dir;
use strict;
use warnings;

use IO::Dir;

use base qw( Net::SFTP::SftpServer::FS  );

{
  my %fd_of;
  my %path_of;
  my %dir_err_of;
  #-------------------------------------------------------------------------------
  sub initialise {
    my $self = shift;

    my ($path) = @_;

    my $fd = IO::Dir->new($self->chrootDir() . $path);

    return unless defined $fd;

    $path .= '/';
    $path =~ s!//$!/!; # make sure we have a trailing /
    my $ident = scalar($self);
    $path_of{$ident} = $path;
    $fd_of{$ident}   = $fd;

    return 1;
  }
  #-------------------------------------------------------------------------------
  sub err {
    my $self = shift;
    my $ident = scalar($self);

    return $dir_err_of{$ident};
  }
  #-------------------------------------------------------------------------------
  sub close {
    my $self = shift;
    my $ident = scalar($self);

    my $ret = $fd_of{$ident}->close();
    unless ($ret){
      $dir_err_of{$ident} = $!+0;
    }

    return $ret;
  }
  #-------------------------------------------------------------------------------
  sub getFilename {
    my $self = shift;
    my $ident = scalar($self);
    return "$path_of{$ident}";
  }
  #-------------------------------------------------------------------------------
  sub getPath {
    my $self = shift;
    my $ident = scalar($self);
    return $path_of{$ident};
  }
  #-------------------------------------------------------------------------------
  sub getType {
    my $self = shift;
    return 'dir';
  }
  #-------------------------------------------------------------------------------
  sub readdir {
    my $self = shift;
    my $ident = scalar $self;
    return $fd_of{$ident}->read();
  }
  #-------------------------------------------------------------------------------
  sub DESTROY {
    my $self = shift;
    my $ident = scalar($self);

    delete $fd_of{$ident};
    delete $path_of{$ident};
    delete $dir_err_of{$ident};

    $self->SUPER::DESTROY()
  }
}
1;
#-------------------------------------------------------------------------------
__END__
#-------------------------------------------------------------------------------
=head1 NAME

Net::SFTP::SftpServer - A Perl implementation of the SFTP subsystem with user access controls

=head1 SYNOPSIS

  use Net::SFTP::SftpServer;

  my $sftp = Net::SFTP::SftpServer->new();

  $sftp->run();

=head1 DESCRIPTION


A Perl port of sftp-server from openssh providing access control on a per user per command basis and improved logging via syslog

The limitations compared with the openssh implementation are as follows:

=over

=item *

Only files and directories are dealt with - other types are not returned on readdir

=item *

a virtual chroot is performed - / is treated as the users home directory from the
client perspective and all file access to / will be in /<home_path>/<username>
home_path is defined on object initialisation not accessed from /etc/passwd
The script DOES NOT run under chroot - this prevents it needing SUID to start.
The virtual chroot is enforced by the objects and prevent opperations outside the
home area

=item *

all sym linked files or directories are hidden and not accessible on request

=item *

symlink returns permission denied. Please contact me if you need this functionaility implementing

=item *

readlink returns file does not exist. Please contact me if you need this functionaility implementing

=item *

setting of stats (set_stat or set_fstat) is disabled - client will receive permission denied.
Please contact me if you need this functionaility implementing

=item *

permissions for file or dir is defaulted - default set on object initialisation

=back

=head1 USAGE

Basic usage:

  use Net::SFTP::SftpServer;

Import options:

  :LOG    - Import logging functions for use in callbacks
  :ACTION - Import constants for Allow/Deny of actions

Configuring syslog:

Syslog output mode must be configured in the use statement of the module as follows:

  use Net::SFTP::SftpServer ( { log => 'local5' }, qw ( :LOG :ACTIONS ) );

Net::SFTP::SftpServer will default to using C<daemon> see your system's syslog documentation for more details


Options for object initialisation:

=over

=item

debug

Log debug level information. Deault=0 (note this will create very large log files - use with caution)

=item

home

Filesystem location of user home directories. default=/home

=item

file_perms

Octal file permissions to force on creation of files. Default=0666 or permissions specified by file open command from client

=item

dir_perms

Octal dir permissions to force on creation of directories. Default=0777 or permissions specified by mkdir command from client

=item

on_file_sent, on_file_received

References to callback functions to be called on complete file sent or received. Function will be passed the full path and filename on the filesystem as a single argument

=item

use_tmp_upload

Use temporary upload filenames while a file is being uploaded - this allows a monitoring script to know which files are in transit without having to watch file size.
Will be done transparently to the user, the file will be renamed to the original file name when close. The temportary extension is ".SftpXFR.$$". Default=0

=item

max_file_size

Maximum file size (in bytes) which can be uploaded. Default=0 (no limit)

=item

valid_filename_char

Array of valid characters for filenames

=item

allow, deny

Actions allowed or denied - see L</PERMISSIONS> for details, Default is to allow ALL.

=item

fake_ok

Array of actions (see action contants in L</PERMISSIONS>) which will be given response SSH2_FX_OK instead of SSH2_FX_PERMISSION_DENIED when denied by above deny options. Default=[]

=item

log_action_supress

Array of actions to log quietly (logDetail - syslog debug level), logs messages whenever this action is performed. Default is quiet for SSH2_FXP_READ, SSH2_FXP_WRITE, SSH2_FX_OPENDIR, SSH2_FXP_READDIR, SSH2_FXP_CLOSE, SSH2_FXP_STAT SSH2_FXP_FSTAT and SSH2_FXP_LSTAT override with log_action, see below.

=item

log_action

Array of actions to log loudly (logGeneral - syslog info level), logs messages whenever this action is performed.

=item

log_all_status

Log all status messages at info level. By default SSH2_FX_OK and SSH2_FX_EOF will be logged at debug level.

=back

=head1 PERMISSIONS

  ALL                      - All actions
  NET_SFTP_SYMLINKS        - Symlinks in paths to files (recommended deny to enforce chroot)
  NET_SFTP_RENAME_DIR      - Rename directories (recommended deny if also denying SSH2_FXP_MKDIR)
  SSH2_FXP_OPEN
  SSH2_FXP_CLOSE
  SSH2_FXP_READ
  SSH2_FXP_WRITE
  SSH2_FXP_LSTAT
  SSH2_FXP_STAT_VERSION_0
  SSH2_FXP_FSTAT
  SSH2_FXP_SETSTAT         - Automatically denied, not implemented in module
  SSH2_FXP_FSETSTAT        - Automatically denied, not implemented in module
  SSH2_FXP_OPENDIR
  SSH2_FXP_READDIR
  SSH2_FXP_REMOVE
  SSH2_FXP_MKDIR
  SSH2_FXP_RMDIR
  SSH2_FXP_STAT
  SSH2_FXP_RENAME
  SSH2_FXP_READLINK        - Automatically denied, not implemented in module
  SSH2_FXP_SYMLINK         - Automatically denied, not implemented in module

=head1 CALLBACKS

Callback functions can be used to perform actions when files are sent or received, for example move a fully downloaded file to a processed directory or move a received file into an input directory.
The callback is proided with a Net::SFTP::SftpServer::File object. This object allows access to the file within the virtual chroot environment. It will also return the full filename, or move the file to an explicit location on the full filesystem. Either of these actions will break the chroot and the methods on the object will no longer be available.

The following methods are provided

=over

=item

read

Read the data from the file - as the IO::File->read. Will open the file for reading if it is not already open and read back the data.

=item

open

Will open the file - as IO::File->open but the filename is not supplied.

=item

getFilename

Will return the filename as within the virtual chroot

=item

getFullFilenameBREAKCHROOT

Will return the full filename on the real file system and break the virtual chroot

=item

renameBREAKCHROOT

Takes a single argument of the new filename, will rename the file to that location and break the virtual chroot

=back

=head1 LOGGING

If :LOG is used when including Net::SFTP::SftpServer the following logging functions will be available:

  logError    - syslog with a log level of error
  logWarning  - syslog with a log level of warning
  logGeneral  - syslog with a log level of info
  logDetail   - syslog with a log level of debug, unless object was created with debug=>1 then syslog with a level of info

=head1 HARDENED EXAMPLE SCRIPT

The following example script shows how this module can be used to give far greater control over what is allowed on your SFTP server.

This setup is aimed at admins which want to user SFTP uploads but do not wish to grant users a system account.
You will also need to set both the SFTP subsystem and the user's shell to the sftp script, eg /usr/local/bin/sftp-server.pl

This configuration:

=over

=item * Enforces that users can only access the sftp script, not an ssh shell.

=item * Chroots them into their home directory in /var/upload/sftp

=item * Sets all file permissions to 0660 and does not permit users to change them.

=item * Does not allow symlinks, making directories or renaming directories, but allows all other normal actions.

=item * Has a max upload filesize of 200Mb

=item * Has a script memory limit of 100Mb for safety

=item * Will log actions by user sftptest in debug mode

=item * Will only allow alphanumeric plus _ . and - in filenames

=item * Will call ActionOnSent and ActionOnReceived respectively when files have been sent or received.

=back

  #!/usr/local/bin/perl

  use strict;
  use warnings;
  use Net::SFTP::SftpServer ( { log => 'local5' }, qw ( :LOG :ACTIONS ) );
  use BSD::Resource;        # for setrlimit

  use constant DEBUG_USER => {
    SFTPTEST => 1,
  };


  # Security - make sure we have started this as sftp not ssh
  unless ( scalar @ARGV == 2 and
           $ARGV[0] eq '-c'  and
           ($ARGV[1] eq '/usr/local/bin/sftp-server.pl') ){

         logError "SFTP connection attempted for application $ARGV[0] - exiting";
         print "\n\rYou do not have permission to login interactively to this host.\n\r\n\rPlease contact the system administrator if you believe this to be a configuration error.\n\r";
         exit 1;
  }

  my $MEMLIMIT = 100 * 1024 * 1024; # 100 Mb

  # hard limits on process memory usage;
  setrlimit( RLIMIT_RSS,  $MEMLIMIT, $MEMLIMIT );
  setrlimit( RLIMIT_VMEM, $MEMLIMIT, $MEMLIMIT );

  my $debug = (defined DEBUG_USER->{uc(getpwuid($>))} and DEBUG_USER->{uc(getpwuid($>))}) ? 1 : 0;

  my $sftp = Net::SFTP::SftpServer->new(
    debug               => $debug,
    home                => '/var/upload/sftp',
    file_perms          => 0660,
    on_file_sent        => \&ActionOnSent,
    on_file_received    => \&ActionOnReceived,
    use_tmp_upload      => 1,
    max_file_size       => 200 * 1024 * 1024,
    valid_filename_char => [ 'a' .. 'z', 'A' .. 'Z', '0' .. '9', '_', '.', '-' ],
    deny                => ALL,
    allow               => [ (
                                SSH2_FXP_OPEN,
                                SSH2_FXP_CLOSE,
                                SSH2_FXP_READ,
                                SSH2_FXP_WRITE,
                                SSH2_FXP_LSTAT,
                                SSH2_FXP_STAT_VERSION_0,
                                SSH2_FXP_FSTAT,
                                SSH2_FXP_OPENDIR,
                                SSH2_FXP_READDIR,
                                SSH2_FXP_REMOVE,
                                SSH2_FXP_STAT,
                                SSH2_FXP_RENAME,
                             )],
    fake_ok             => [ (
                                SSH2_FXP_SETSTAT,
                                SSH2_FXP_FSETSTAT,
                             )],
  );

  $sftp->run();

  sub ActionOnSent {
    my $fileObject = shift;
     ## Do Stuff
  }

  sub ActionOnReceived {
    my $fileObject = shift;
     ## Do Stuff
  }

=head1 DEPENDENCIES

  Stat::lsMode
  Fcntl
  POSIX
  Sys::Syslog
  Errno

=head1 SEE ALSO

Sftp protocol L<http://www.openssh.org/txt/draft-ietf-secsh-filexfer-02.txt>

=head1 AUTHOR

  Simon Day, Pirum Systems Ltd
  cpan <at> simonday.info

=head1 COPYRIGHT AND LICENSE

Based on sftp-server.c
Copyright (c) 2000-2004 Markus Friedl.  All rights reserved.

Ported to Perl and extended by Simon Day
Copyright (c) 2009 Pirum Systems Ltd.  All rights reserved.

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


=cut