This file is indexed.

/usr/lib/python3/dist-packages/asyncssh/sftp.py is in python3-asyncssh 1.11.1-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
# Copyright (c) 2015-2017 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
#     http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
#     Ron Frederick - initial implementation, API, and documentation
#     Jonathan Slenders - proposed changes to allow SFTP server callbacks
#                         to be coroutines

"""SFTP handlers"""

import asyncio
from collections import OrderedDict
import errno
from fnmatch import fnmatch
import os
from os import SEEK_SET, SEEK_CUR, SEEK_END
import posixpath
import stat
import sys
import time

from .constants import DEFAULT_LANG

from .constants import FXP_INIT, FXP_VERSION, FXP_OPEN, FXP_CLOSE, FXP_READ
from .constants import FXP_WRITE, FXP_LSTAT, FXP_FSTAT, FXP_SETSTAT
from .constants import FXP_FSETSTAT, FXP_OPENDIR, FXP_READDIR, FXP_REMOVE
from .constants import FXP_MKDIR, FXP_RMDIR, FXP_REALPATH, FXP_STAT, FXP_RENAME
from .constants import FXP_READLINK, FXP_SYMLINK, FXP_STATUS, FXP_HANDLE
from .constants import FXP_DATA, FXP_NAME, FXP_ATTRS, FXP_EXTENDED
from .constants import FXP_EXTENDED_REPLY

from .constants import FXF_READ, FXF_WRITE, FXF_APPEND
from .constants import FXF_CREAT, FXF_TRUNC, FXF_EXCL

from .constants import FILEXFER_ATTR_SIZE, FILEXFER_ATTR_UIDGID
from .constants import FILEXFER_ATTR_PERMISSIONS, FILEXFER_ATTR_ACMODTIME
from .constants import FILEXFER_ATTR_EXTENDED, FILEXFER_ATTR_UNDEFINED

from .constants import FX_OK, FX_EOF, FX_NO_SUCH_FILE, FX_PERMISSION_DENIED
from .constants import FX_FAILURE, FX_BAD_MESSAGE, FX_NO_CONNECTION
from .constants import FX_CONNECTION_LOST, FX_OP_UNSUPPORTED

from .misc import async_context_manager, Error, Record

from .packet import Byte, String, UInt32, UInt64, PacketDecodeError, SSHPacket

SFTP_BLOCK_SIZE = 16384

_SFTP_VERSION = 3
_MAX_SFTP_REQUESTS = 128
_MAX_READDIR_NAMES = 128

_open_modes = {
    'r':  FXF_READ,
    'w':  FXF_WRITE | FXF_CREAT | FXF_TRUNC,
    'a':  FXF_WRITE | FXF_CREAT | FXF_APPEND,
    'x':  FXF_WRITE | FXF_CREAT | FXF_EXCL,

    'r+': FXF_READ | FXF_WRITE,
    'w+': FXF_READ | FXF_WRITE | FXF_CREAT | FXF_TRUNC,
    'a+': FXF_READ | FXF_WRITE | FXF_CREAT | FXF_APPEND,
    'x+': FXF_READ | FXF_WRITE | FXF_CREAT | FXF_EXCL
}


def _mode_to_pflags(mode):
    """Convert open mode to SFTP open flags"""

    if 'b' in mode:
        mode = mode.replace('b', '')
        binary = True
    else:
        binary = False

    pflags = _open_modes.get(mode)

    if not pflags:
        raise ValueError('Invalid mode: %r' % mode)

    return pflags, binary


def _from_local_path(path):
    """Convert SFTP path to local path"""

    path = os.fsencode(path)

    if sys.platform == 'win32': # pragma: no cover
        path = path.replace(b'\\', b'/')

        if path[:1] != b'/' and path[1:2] == b':':
            path = b'/' + path

    return path


def _to_local_path(path):
    """Convert local path to SFTP path"""

    if sys.platform == 'win32': # pragma: no cover
        path = os.fsdecode(path)

        if path[:1] == '/' and path[2:3] == ':':
            path = path[1:]

        path = path.replace('/', '\\')

    return path


def _setstat(path, attrs):
    """Utility function to set file attributes"""

    if attrs.size is not None:
        os.truncate(path, attrs.size)

    if attrs.uid is not None and attrs.gid is not None:
        try:
            os.chown(path, attrs.uid, attrs.gid)
        except AttributeError: # pragma: no cover
            raise NotImplementedError

    if attrs.permissions is not None:
        os.chmod(path, stat.S_IMODE(attrs.permissions))

    if attrs.atime is not None and attrs.mtime is not None:
        os.utime(path, times=(attrs.atime, attrs.mtime))


@asyncio.coroutine
def _glob(fs, basedir, patlist, result):
    """Recursively match a glob pattern"""

    pattern, patlist = patlist[0], patlist[1:]

    names = yield from fs.listdir(basedir or b'.')

    for name in names:
        if pattern != name and name in (b'.', b'..'):
            continue

        if name[:1] == b'.' and not pattern[:1] == b'.':
            continue

        if fnmatch(name, pattern):
            if basedir:
                newbase = posixpath.join(basedir, name)
            else:
                newbase = name

            if not patlist:
                result.append(newbase)
            else:
                attrs = yield from fs.stat(newbase)

                if stat.S_ISDIR(attrs.permissions):
                    yield from _glob(fs, newbase, patlist, result)


@asyncio.coroutine
def match_glob(fs, pattern, error_handler=None):
    """Match a glob pattern"""

    names = []

    try:
        if any(c in pattern for c in b'*?'):
            patlist = pattern.split(b'/')

            if not patlist[0]:
                basedir = b'/'
                patlist = patlist[1:]
            else:
                basedir = None

            yield from _glob(fs, basedir, patlist, names)

            if not names:
                raise SFTPError(FX_NO_SUCH_FILE, 'No matches found')
        else:
            yield from fs.stat(pattern)
            names.append(pattern)
    except (OSError, SFTPError) as exc:
        # pylint: disable=attribute-defined-outside-init
        exc.srcpath = pattern

        if error_handler:
            error_handler(exc)
        else:
            raise exc

    return names


class LocalFile:
    """A coroutine wrapper around local file I/O"""

    def __init__(self, f):
        self._file = f

    @classmethod
    def encode(cls, path):
        """Encode path name using filesystem native encoding

           This method has no effect if the path is already bytes.

        """

        return os.fsencode(path)

    @classmethod
    def decode(cls, path):
        """Decode path name using filesystem native encoding

           This method has no effect if the path is already a string.

        """

        return os.fsdecode(path)

    @classmethod
    def compose_path(cls, path, parent=None):
        """Compose a path

           If parent is not specified, just encode the path.

        """

        return posixpath.join(parent, path) if parent else path

    @classmethod
    @asyncio.coroutine
    def open(cls, path, *args):
        """Open a local file"""

        return cls(open(_to_local_path(path), *args))

    @classmethod
    @asyncio.coroutine
    def stat(cls, path):
        """Get attributes of a local file or directory, following symlinks"""

        return SFTPAttrs.from_local(os.stat(_to_local_path(path)))

    @classmethod
    @asyncio.coroutine
    def lstat(cls, path):
        """Get attributes of a local file, directory, or symlink"""

        return SFTPAttrs.from_local(os.lstat(_to_local_path(path)))

    @classmethod
    @asyncio.coroutine
    def setstat(cls, path, attrs):
        """Set attributes of a local file or directory"""

        _setstat(_to_local_path(path), attrs)

    @classmethod
    @asyncio.coroutine
    def exists(cls, path):
        """Return if the local path exists and isn't a broken symbolic link"""

        return os.path.exists(_to_local_path(path))

    @classmethod
    @asyncio.coroutine
    def isdir(cls, path):
        """Return if the local path refers to a directory"""

        return os.path.isdir(_to_local_path(path))

    @classmethod
    @asyncio.coroutine
    def listdir(cls, path):
        """Read the names of the files in a local directory"""

        files = os.listdir(_to_local_path(path))

        if sys.platform == 'win32': # pragma: no cover
            files = [os.fsencode(f) for f in files]

        return files

    @classmethod
    @asyncio.coroutine
    def mkdir(cls, path):
        """Create a local directory with the specified attributes"""

        os.mkdir(_to_local_path(path))

    @classmethod
    @asyncio.coroutine
    def readlink(cls, path):
        """Return the target of a local symbolic link"""

        return _from_local_path(os.readlink(_to_local_path(path)))

    @classmethod
    @asyncio.coroutine
    def symlink(cls, oldpath, newpath):
        """Create a local symbolic link"""

        os.symlink(_to_local_path(oldpath), _to_local_path(newpath))

    @asyncio.coroutine
    def read(self, size, offset):
        """Read data from the local file"""

        self._file.seek(offset)
        return self._file.read(size)

    @asyncio.coroutine
    def write(self, data, offset):
        """Write data to the local file"""

        self._file.seek(offset)
        return self._file.write(data)

    @asyncio.coroutine
    def close(self):
        """Close the local file"""

        self._file.close()


class _SFTPFileCopier:
    """SFTP file copier

       This class parforms an SFTP file copy, initiating multiple
       read and write requests to copy chunks of the file in parallel.

    """

    def __init__(self, loop):
        self._loop = loop
        self._src = None
        self._dst = None
        self._block_size = 0
        self._bytes_left = 0
        self._offset = 0
        self._pending = set()

    @asyncio.coroutine
    def _copy_block(self, offset, size):
        """Copy the next block of the file"""

        data = yield from self._src.read(size, offset)
        yield from self._dst.write(data, offset)
        return size

    def _copy_blocks(self):
        """Create parallel requests to copy blocks from one file to another"""

        while self._bytes_left and len(self._pending) < _MAX_SFTP_REQUESTS:
            size = min(self._bytes_left, self._block_size)

            task = asyncio.Task(self._copy_block(self._offset, size),
                                loop=self._loop)
            self._pending.add(task)

            self._offset += size
            self._bytes_left -= size

    @asyncio.coroutine
    def copy(self, srcfs, dstfs, srcpath, dstpath, total_bytes,
             block_size, progress_handler):
        """Copy a file"""

        try:
            self._src = yield from srcfs.open(srcpath, 'rb')
            self._dst = yield from dstfs.open(dstpath, 'wb')
            self._block_size = block_size
            self._bytes_left = total_bytes
            self._copy_blocks()

            bytes_copied = 0

            while self._pending:
                done, self._pending = yield from asyncio.wait(
                    self._pending, return_when=asyncio.FIRST_COMPLETED)

                exceptions = []

                for task in done:
                    exc = task.exception()

                    if exc:
                        exceptions.append(exc)
                    elif progress_handler:
                        bytes_copied += task.result()
                        progress_handler(srcpath, dstpath,
                                         bytes_copied, total_bytes)

                if exceptions:
                    for task in self._pending:
                        task.cancel()

                    raise exceptions[0]

                self._copy_blocks()
        finally:
            if self._src: # pragma: no branch
                yield from self._src.close()

            if self._dst: # pragma: no branch
                yield from self._dst.close()


class SFTPError(Error):
    """SFTP error

       This exception is raised when an error occurs while processing
       an SFTP request. Exception codes should be taken from
       :ref:`SFTP error codes <SFTPErrorCodes>`.

       :param int code:
           Disconnect reason, taken from :ref:`disconnect reason
           codes <DisconnectReasons>`
       :param str reason:
           A human-readable reason for the disconnect
       :param str lang:
           The language the reason is in

    """

    def __init__(self, code, reason, lang=DEFAULT_LANG):
        super().__init__('SFTP', code, reason, lang)


class SFTPAttrs(Record):
    """SFTP file attributes

       SFTPAttrs is a simple record class with the following fields:

         ============ =========================================== ======
         Field        Description                                 Type
         ============ =========================================== ======
         size         File size in bytes                          uint64
         uid          User id of file owner                       uint32
         gid          Group id of file owner                      uint32
         permissions  Bit mask of POSIX file permissions,         uint32
         atime        Last access time, UNIX epoch seconds        uint32
         mtime        Last modification time, UNIX epoch seconds  uint32
         ============ =========================================== ======

       In addition to the above, an ``nlink`` field is provided which
       stores the number of links to this file, but it is not encoded
       in the SFTP protocol. It's included here only so that it can be
       used to create the default ``longname`` string in :class:`SFTPName`
       objects.

       Extended attributes can also be added via a field named
       ``extended`` which is a list of string name/value pairs.

       When setting attributes using an :class:`SFTPAttrs`, only fields
       which have been initialized will be changed on the selected file.

    """

    # Unfortunately, pylint can't handle attributes defined with setattr
    # pylint: disable=attribute-defined-outside-init

    __slots__ = OrderedDict((('size', None), ('uid', None), ('gid', None),
                             ('permissions', None), ('atime', None),
                             ('mtime', None), ('nlink', None),
                             ('extended', [])))

    def encode(self):
        """Encode SFTP attributes as bytes in an SSH packet"""

        flags = 0
        attrs = []

        if self.size is not None:
            flags |= FILEXFER_ATTR_SIZE
            attrs.append(UInt64(self.size))

        if self.uid is not None and self.gid is not None:
            flags |= FILEXFER_ATTR_UIDGID
            attrs.append(UInt32(self.uid) + UInt32(self.gid))

        if self.permissions is not None:
            flags |= FILEXFER_ATTR_PERMISSIONS
            attrs.append(UInt32(self.permissions))

        if self.atime is not None and self.mtime is not None:
            flags |= FILEXFER_ATTR_ACMODTIME
            attrs.append(UInt32(int(self.atime)) + UInt32(int(self.mtime)))

        if self.extended:
            flags |= FILEXFER_ATTR_EXTENDED
            attrs.append(UInt32(len(self.extended)))
            attrs.extend(String(type) + String(data)
                         for type, data in self.extended)

        return UInt32(flags) + b''.join(attrs)

    @classmethod
    def decode(cls, packet):
        """Decode bytes in an SSH packet as SFTP attributes"""

        flags = packet.get_uint32()
        attrs = cls()

        if flags & FILEXFER_ATTR_UNDEFINED:
            raise SFTPError(FX_BAD_MESSAGE, 'Unsupported attribute flags')

        if flags & FILEXFER_ATTR_SIZE:
            attrs.size = packet.get_uint64()

        if flags & FILEXFER_ATTR_UIDGID:
            attrs.uid = packet.get_uint32()
            attrs.gid = packet.get_uint32()

        if flags & FILEXFER_ATTR_PERMISSIONS:
            attrs.permissions = packet.get_uint32()

        if flags & FILEXFER_ATTR_ACMODTIME:
            attrs.atime = packet.get_uint32()
            attrs.mtime = packet.get_uint32()

        if flags & FILEXFER_ATTR_EXTENDED:
            count = packet.get_uint32()
            attrs.extended = []

            for _ in range(count):
                attr = packet.get_string()
                data = packet.get_string()
                attrs.extended.append((attr, data))

        return attrs

    @classmethod
    def from_local(cls, result):
        """Convert from local stat attributes"""

        return cls(result.st_size, result.st_uid, result.st_gid,
                   result.st_mode, result.st_atime, result.st_mtime,
                   result.st_nlink)


class SFTPVFSAttrs(Record):
    """SFTP file system attributes

       SFTPVFSAttrs is a simple record class with the following fields:

         ============ =========================================== ======
         Field        Description                                 Type
         ============ =========================================== ======
         bsize        File system block size (I/O size)           uint64
         frsize       Fundamental block size (allocation size)    uint64
         blocks       Total data blocks (in frsize units)         uint64
         bfree        Free data blocks                            uint64
         bavail       Available data blocks (for non-root)        uint64
         files        Total file inodes                           uint64
         ffree        Free file inodes                            uint64
         favail       Available file inodes (for non-root)        uint64
         fsid         File system id                              uint64
         flags        File system flags (read-only, no-setuid)    uint64
         namemax      Maximum filename length                     uint64
         ============ =========================================== ======

    """

    # Unfortunately, pylint can't handle attributes defined with setattr
    # pylint: disable=attribute-defined-outside-init

    __slots__ = OrderedDict((('bsize', 0), ('frsize', 0), ('blocks', 0),
                             ('bfree', 0), ('bavail', 0), ('files', 0),
                             ('ffree', 0), ('favail', 0), ('fsid', 0),
                             ('flags', 0), ('namemax', 0)))

    def encode(self):
        """Encode SFTP statvfs attributes as bytes in an SSH packet"""

        return b''.join((UInt64(self.bsize), UInt64(self.frsize),
                         UInt64(self.blocks), UInt64(self.bfree),
                         UInt64(self.bavail), UInt64(self.files),
                         UInt64(self.ffree), UInt64(self.favail),
                         UInt64(self.fsid), UInt64(self.flags),
                         UInt64(self.namemax)))

    @classmethod
    def decode(cls, packet):
        """Decode bytes in an SSH packet as SFTP statvfs attributes"""

        vfsattrs = cls()

        vfsattrs.bsize = packet.get_uint64()
        vfsattrs.frsize = packet.get_uint64()
        vfsattrs.blocks = packet.get_uint64()
        vfsattrs.bfree = packet.get_uint64()
        vfsattrs.bavail = packet.get_uint64()
        vfsattrs.files = packet.get_uint64()
        vfsattrs.ffree = packet.get_uint64()
        vfsattrs.favail = packet.get_uint64()
        vfsattrs.fsid = packet.get_uint64()
        vfsattrs.flags = packet.get_uint64()
        vfsattrs.namemax = packet.get_uint64()

        return vfsattrs

    @classmethod
    def from_local(cls, result):
        """Convert from local statvfs attributes"""

        return cls(result.f_bsize, result.f_frsize, result.f_blocks,
                   result.f_bfree, result.f_bavail, result.f_files,
                   result.f_ffree, result.f_favail, 0, result.f_flag,
                   result.f_namemax)


class SFTPName(Record):
    """SFTP file name and attributes

       SFTPName is a simple record class with the following fields:

         ========= ================================== ==================
         Field     Description                        Type
         ========= ================================== ==================
         filename  Filename                           str or bytes
         longname  Expanded form of filename & attrs  str or bytes
         attrs     File attributes                    :class:`SFTPAttrs`
         ========= ================================== ==================

       A list of these is returned by :meth:`readdir() <SFTPClient.readdir>`
       in :class:`SFTPClient` when retrieving the contents of a directory.

    """

    __slots__ = OrderedDict((('filename', ''), ('longname', ''),
                             ('attrs', SFTPAttrs())))

    def encode(self):
        """Encode an SFTP name as bytes in an SSH packet"""


        # pylint: disable=no-member
        return (String(self.filename) + String(self.longname) +
                self.attrs.encode())

    @classmethod
    def decode(cls, packet):
        """Decode bytes in an SSH packet as an SFTP name"""


        filename = packet.get_string()
        longname = packet.get_string()
        attrs = SFTPAttrs.decode(packet)

        return cls(filename, longname, attrs)


class SFTPHandler:
    """SFTP session handler"""

    # SFTP implementations with broken order for SYMLINK arguments
    _nonstandard_symlink_impls = ['OpenSSH', 'paramiko']

    # Return types by message -- unlisted entries always return FXP_STATUS,
    #                            those below return FXP_STATUS on error
    _return_types = {
        FXP_OPEN:                 FXP_HANDLE,
        FXP_READ:                 FXP_DATA,
        FXP_LSTAT:                FXP_ATTRS,
        FXP_FSTAT:                FXP_ATTRS,
        FXP_OPENDIR:              FXP_HANDLE,
        FXP_READDIR:              FXP_NAME,
        FXP_REALPATH:             FXP_NAME,
        FXP_STAT:                 FXP_ATTRS,
        FXP_READLINK:             FXP_NAME,
        b'statvfs@openssh.com':   FXP_EXTENDED_REPLY,
        b'fstatvfs@openssh.com':  FXP_EXTENDED_REPLY
    }

    def __init__(self, reader, writer):
        self._reader = reader
        self._writer = writer

    @asyncio.coroutine
    def _cleanup(self, exc):
        """Clean up this SFTP session"""

        # pylint: disable=unused-argument

        if self._writer: # pragma: no branch
            self._writer.close()
            self._reader = None
            self._writer = None

    @asyncio.coroutine
    def _process_packet(self, pkttype, pktid, packet):
        """Abstract method for processing SFTP packets"""

        raise NotImplementedError

    def send_packet(self, *args):
        """Send an SFTP packet"""

        payload = b''.join(args)

        try:
            self._writer.write(UInt32(len(payload)) + payload)
        except ConnectionError as exc:
            raise SFTPError(FX_CONNECTION_LOST, str(exc)) from None

    @asyncio.coroutine
    def recv_packet(self):
        """Receive an SFTP packet"""

        try:
            pktlen = yield from self._reader.readexactly(4)
            pktlen = int.from_bytes(pktlen, 'big')

            packet = yield from self._reader.readexactly(pktlen)
            packet = SSHPacket(packet)
        except EOFError:
            raise SFTPError(FX_CONNECTION_LOST, 'Channel closed') from None

        return packet

    @asyncio.coroutine
    def recv_packets(self):
        """Receive and process SFTP packets"""

        try:
            while self._reader: # pragma: no branch
                packet = yield from self.recv_packet()

                pkttype = packet.get_byte()
                pktid = packet.get_uint32()

                yield from self._process_packet(pkttype, pktid, packet)
        except PacketDecodeError as exc:
            yield from self._cleanup(SFTPError(FX_BAD_MESSAGE, str(exc)))
        except (OSError, SFTPError) as exc:
            yield from self._cleanup(exc)


class SFTPClientHandler(SFTPHandler):
    """An SFTP client session handler"""

    _extensions = []

    def __init__(self, loop, reader, writer):
        super().__init__(reader, writer)

        self._loop = loop
        self._version = None
        self._next_pktid = 0
        self._requests = {}
        self._nonstandard_symlink = False
        self._supports_posix_rename = False
        self._supports_statvfs = False
        self._supports_fstatvfs = False
        self._supports_hardlink = False
        self._supports_fsync = False

    @asyncio.coroutine
    def _cleanup(self, exc):
        """Clean up this SFTP client session"""

        for waiter in self._requests.values():
            if waiter and not waiter.cancelled():
                waiter.set_exception(exc)

        self._requests = {}

        yield from super()._cleanup(exc)

    @asyncio.coroutine
    def _process_packet(self, pkttype, pktid, packet):
        """Process incoming SFTP responses"""

        try:
            waiter = self._requests.pop(pktid)
        except KeyError:
            yield from self._cleanup(SFTPError(FX_BAD_MESSAGE,
                                               'Invalid response id'))
        else:
            if waiter and not waiter.cancelled():
                waiter.set_result((pkttype, packet))

    def _send_request(self, pkttype, *args, waiter=None):
        """Send an SFTP request"""

        if not self._writer:
            raise SFTPError(FX_NO_CONNECTION, 'Connection not open')

        pktid = self._next_pktid
        self._next_pktid = (self._next_pktid + 1) & 0xffffffff

        self._requests[pktid] = waiter

        if isinstance(pkttype, bytes):
            hdr = Byte(FXP_EXTENDED) + UInt32(pktid) + String(pkttype)
        else:
            hdr = Byte(pkttype) + UInt32(pktid)

        self.send_packet(hdr, *args)

    @asyncio.coroutine
    def _make_request(self, pkttype, *args):
        """Make an SFTP request and wait for a response"""

        waiter = asyncio.Future(loop=self._loop)
        self._send_request(pkttype, *args, waiter=waiter)
        resptype, resp = yield from waiter

        return_type = self._return_types.get(pkttype)

        if resptype not in (FXP_STATUS, return_type):
            raise SFTPError(FX_BAD_MESSAGE,
                            'Unexpected response type: %s' % resptype)

        result = self._packet_handlers[resptype](self, resp)

        if result is not None or return_type is None:
            return result
        else:
            raise SFTPError(FX_BAD_MESSAGE, 'Unexpected FX_OK response')

    def _process_status(self, packet):
        """Process an incoming SFTP status response"""

        # pylint: disable=no-self-use

        code = packet.get_uint32()

        try:
            reason = packet.get_string().decode('utf-8')
            lang = packet.get_string().decode('ascii')
        except UnicodeDecodeError:
            raise SFTPError(FX_BAD_MESSAGE, 'Invalid status message') from None

        packet.check_end()

        if code == FX_OK:
            return None
        else:
            raise SFTPError(code, reason, lang)

    def _process_handle(self, packet):
        """Process an incoming SFTP handle response"""

        # pylint: disable=no-self-use

        handle = packet.get_string()
        packet.check_end()
        return handle

    def _process_data(self, packet):
        """Process an incoming SFTP data response"""

        # pylint: disable=no-self-use

        data = packet.get_string()
        packet.check_end()
        return data

    def _process_name(self, packet):
        """Process an incoming SFTP name response"""

        # pylint: disable=no-self-use

        count = packet.get_uint32()
        names = [SFTPName.decode(packet) for i in range(count)]
        packet.check_end()
        return names

    def _process_attrs(self, packet):
        """Process an incoming SFTP attributes response"""

        # pylint: disable=no-self-use

        attrs = SFTPAttrs().decode(packet)
        packet.check_end()
        return attrs

    def _process_extended_reply(self, packet):
        """Process an incoming SFTP extended reply response"""

        # pylint: disable=no-self-use

        # Let the caller do the decoding for extended replies
        return packet

    _packet_handlers = {
        FXP_STATUS:         _process_status,
        FXP_HANDLE:         _process_handle,
        FXP_DATA:           _process_data,
        FXP_NAME:           _process_name,
        FXP_ATTRS:          _process_attrs,
        FXP_EXTENDED_REPLY: _process_extended_reply
    }

    @asyncio.coroutine
    def start(self):
        """Start an SFTP client"""

        extensions = (String(name) + String(data)
                      for name, data in self._extensions)

        self.send_packet(Byte(FXP_INIT), UInt32(_SFTP_VERSION), *extensions)

        resp = yield from self.recv_packet()

        resptype = resp.get_byte()

        if resptype != FXP_VERSION:
            raise SFTPError(FX_BAD_MESSAGE, 'Expected version message')

        version = resp.get_uint32()
        extensions = []

        while resp:
            name = resp.get_string()
            data = resp.get_string()
            extensions.append((name, data))

        if version != _SFTP_VERSION:
            raise SFTPError(FX_BAD_MESSAGE,
                            'Unsupported version: %d' % version)

        self._version = version

        for name, data in extensions:
            if name == b'posix-rename@openssh.com' and data == b'1':
                self._supports_posix_rename = True
            elif name == b'statvfs@openssh.com' and data == b'2':
                self._supports_statvfs = True
            elif name == b'fstatvfs@openssh.com' and data == b'2':
                self._supports_fstatvfs = True
            elif name == b'hardlink@openssh.com' and data == b'1':
                self._supports_hardlink = True
            elif name == b'fsync@openssh.com' and data == b'1':
                self._supports_fsync = True

        if version == 3:
            # Check if the server has a buggy SYMLINK implementation

            server_version = self._reader.get_extra_info('server_version', '')
            if any(name in server_version
                   for name in self._nonstandard_symlink_impls):
                self._nonstandard_symlink = True

    @asyncio.coroutine
    def open(self, filename, pflags, attrs):
        """Make an SFTP open request"""

        return (yield from self._make_request(FXP_OPEN, String(filename),
                                              UInt32(pflags), attrs.encode()))

    @asyncio.coroutine
    def close(self, handle):
        """Make an SFTP close request"""

        return (yield from self._make_request(FXP_CLOSE, String(handle)))

    def nonblocking_close(self, handle):
        """Send an SFTP close request without blocking on the response"""

        # Used by context managers, since they can't block to wait for a reply
        self._send_request(FXP_CLOSE, String(handle))

    @asyncio.coroutine
    def read(self, handle, offset, length):
        """Make an SFTP read request"""

        return (yield from self._make_request(FXP_READ, String(handle),
                                              UInt64(offset), UInt32(length)))

    @asyncio.coroutine
    def write(self, handle, offset, data):
        """Make an SFTP write request"""

        return (yield from self._make_request(FXP_WRITE, String(handle),
                                              UInt64(offset), String(data)))

    @asyncio.coroutine
    def stat(self, path):
        """Make an SFTP stat request"""

        return (yield from self._make_request(FXP_STAT, String(path)))

    @asyncio.coroutine
    def lstat(self, path):
        """Make an SFTP lstat request"""

        return (yield from self._make_request(FXP_LSTAT, String(path)))

    @asyncio.coroutine
    def fstat(self, handle):
        """Make an SFTP fstat request"""

        return (yield from self._make_request(FXP_FSTAT, String(handle)))

    @asyncio.coroutine
    def setstat(self, path, attrs):
        """Make an SFTP setstat request"""

        return (yield from self._make_request(FXP_SETSTAT, String(path),
                                              attrs.encode()))

    @asyncio.coroutine
    def fsetstat(self, handle, attrs):
        """Make an SFTP fsetstat request"""

        return (yield from self._make_request(FXP_FSETSTAT, String(handle),
                                              attrs.encode()))

    @asyncio.coroutine
    def statvfs(self, path):
        """Make an SFTP statvfs request"""

        if self._supports_statvfs:
            packet = yield from self._make_request(b'statvfs@openssh.com',
                                                   String(path))
            vfsattrs = SFTPVFSAttrs.decode(packet)
            packet.check_end()

            return vfsattrs
        else:
            raise SFTPError(FX_OP_UNSUPPORTED, 'statvfs not supported')

    @asyncio.coroutine
    def fstatvfs(self, handle):
        """Make an SFTP fstatvfs request"""

        if self._supports_fstatvfs:
            packet = yield from self._make_request(b'fstatvfs@openssh.com',
                                                   String(handle))
            vfsattrs = SFTPVFSAttrs.decode(packet)
            packet.check_end()

            return vfsattrs
        else:
            raise SFTPError(FX_OP_UNSUPPORTED, 'fstatvfs not supported')

    @asyncio.coroutine
    def remove(self, path):
        """Make an SFTP remove request"""

        return (yield from self._make_request(FXP_REMOVE, String(path)))

    @asyncio.coroutine
    def rename(self, oldpath, newpath):
        """Make an SFTP rename request"""

        return (yield from self._make_request(FXP_RENAME, String(oldpath),
                                              String(newpath)))

    @asyncio.coroutine
    def posix_rename(self, oldpath, newpath):
        """Make an SFTP POSIX rename request"""

        if self._supports_posix_rename:
            return (yield from self._make_request(b'posix-rename@openssh.com',
                                                  String(oldpath),
                                                  String(newpath)))
        else:
            raise SFTPError(FX_OP_UNSUPPORTED, 'POSIX rename not supported')

    @asyncio.coroutine
    def opendir(self, path):
        """Make an SFTP opendir request"""

        return (yield from self._make_request(FXP_OPENDIR, String(path)))

    @asyncio.coroutine
    def readdir(self, handle):
        """Make an SFTP readdir request"""

        return (yield from self._make_request(FXP_READDIR, String(handle)))

    @asyncio.coroutine
    def mkdir(self, path, attrs):
        """Make an SFTP mkdir request"""

        return (yield from self._make_request(FXP_MKDIR, String(path),
                                              attrs.encode()))

    @asyncio.coroutine
    def rmdir(self, path):
        """Make an SFTP rmdir request"""

        return (yield from self._make_request(FXP_RMDIR, String(path)))

    @asyncio.coroutine
    def realpath(self, path):
        """Make an SFTP realpath request"""

        return (yield from self._make_request(FXP_REALPATH, String(path)))

    @asyncio.coroutine
    def readlink(self, path):
        """Make an SFTP readlink request"""

        return (yield from self._make_request(FXP_READLINK, String(path)))

    @asyncio.coroutine
    def symlink(self, oldpath, newpath):
        """Make an SFTP symlink request"""

        if self._nonstandard_symlink:
            args = String(oldpath) + String(newpath)
        else:
            args = String(newpath) + String(oldpath)

        return (yield from self._make_request(FXP_SYMLINK, args))

    @asyncio.coroutine
    def link(self, oldpath, newpath):
        """Make an SFTP link request"""

        if self._supports_hardlink:
            return (yield from self._make_request(b'hardlink@openssh.com',
                                                  String(oldpath),
                                                  String(newpath)))
        else:
            raise SFTPError(FX_OP_UNSUPPORTED, 'link not supported')

    @asyncio.coroutine
    def fsync(self, handle):
        """Make an SFTP fsync request"""

        if self._supports_fsync:
            return (yield from self._make_request(b'fsync@openssh.com',
                                                  String(handle)))
        else:
            raise SFTPError(FX_OP_UNSUPPORTED, 'fsync not supported')

    def exit(self):
        """Handle a request to close the SFTP session"""

        if self._writer:
            self._writer.write_eof()

    @asyncio.coroutine
    def wait_closed(self):
        """Wait for this SFTP session to close"""

        if self._writer:
            yield from self._writer.channel.wait_closed()


class SFTPClientFile:
    """SFTP client remote file object

       This class represents an open file on a remote SFTP server. It
       is opened with the :meth:`open() <SFTPClient.open>` method on the
       :class:`SFTPClient` class and provides methods to read and write
       data and get and set attributes on the open file.

    """

    def __init__(self, handler, handle, appending, encoding, errors):
        self._handler = handler
        self._handle = handle
        self._appending = appending
        self._encoding = encoding
        self._errors = errors
        self._offset = None if appending else 0

    def __enter__(self):
        """Allow SFTPClientFile to be used as a context manager"""

        return self

    def __exit__(self, *exc_info):
        """Automatically close the file when used as a context manager"""

        if self._handle:
            self._handler.nonblocking_close(self._handle)
            self._handle = None

    @asyncio.coroutine
    def __aenter__(self):
        """Allow SFTPClientFile to be used as an async context manager"""

        return self

    @asyncio.coroutine
    def __aexit__(self, *exc_info):
        """Wait for file close when used as an async context manager"""

        yield from self.close()

    @asyncio.coroutine
    def _end(self):
        """Return the offset of the end of the file"""

        attrs = yield from self.stat()
        return attrs.size

    @asyncio.coroutine
    def read(self, size=-1, offset=None):
        """Read data from the remote file

           This method reads and returns up to ``size`` bytes of data
           from the remote file. If size is negative, all data up to
           the end of the file is returned.

           If offset is specified, the read will be performed starting
           at that offset rather than the current file position. This
           argument should be provided if you want to issue parallel
           reads on the same file, since the file position is not
           predictable in that case.

           Data will be returned as a string if an encoding was set when
           the file was opened. Otherwise, data is returned as bytes.

           An empty string or bytes object is returned when at EOF.

           :param int size:
               The number of bytes to read
           :param int offset: (optional)
               The offset from the beginning of the file to begin reading

           :returns: data read from the file, as a str or bytes

           :raises: | :exc:`ValueError` if the file has been closed
                    | :exc:`UnicodeDecodeError` if the data can't be
                      decoded using the requested encoding
                    | :exc:`SFTPError` if the server returns an error

        """

        if self._handle is None:
            raise ValueError('I/O operation on closed file')

        if offset is None:
            offset = self._offset

        if offset is None:
            # We're appending and haven't seeked backward in the file
            # since the last write, so there's no data to return
            data = b''
        elif size is None or size < 0:
            data = []

            try:
                while True:
                    result = yield from self._handler.read(self._handle,
                                                           offset,
                                                           SFTP_BLOCK_SIZE)
                    data.append(result)
                    offset += len(result)
                    self._offset = offset
            except SFTPError as exc:
                if exc.code != FX_EOF:
                    raise

            data = b''.join(data)
        else:
            data = b''

            try:
                data = yield from self._handler.read(self._handle,
                                                     offset, size)
                self._offset = offset + len(data)
            except SFTPError as exc:
                if exc.code != FX_EOF:
                    raise

        if self._encoding:
            data = data.decode(self._encoding, self._errors)

        return data

    @asyncio.coroutine
    def write(self, data, offset=None):
        """Write data to the remote file

           This method writes the specified data at the current
           position in the remote file.

           :param data:
               The data to write to the file
           :param int offset: (optional)
               The offset from the beginning of the file to begin writing
           :type data: str or bytes

           If offset is specified, the write will be performed starting
           at that offset rather than the current file position. This
           argument should be provided if you want to issue parallel
           writes on the same file, since the file position is not
           predictable in that case.

           :returns: number of bytes written

           :raises: | :exc:`ValueError` if the file has been closed
                    | :exc:`UnicodeEncodeError` if the data can't be
                      encoded using the requested encoding
                    | :exc:`SFTPError` if the server returns an error

        """

        if self._handle is None:
            raise ValueError('I/O operation on closed file')

        if offset is None:
            # Offset is ignored when appending, so fill in an offset of 0
            # if we don't have a current file position
            offset = self._offset or 0

        if self._encoding:
            data = data.encode(self._encoding, self._errors)

        yield from self._handler.write(self._handle, offset, data)
        self._offset = None if self._appending else offset + len(data)
        return len(data)

    @asyncio.coroutine
    def seek(self, offset, from_what=SEEK_SET):
        """Seek to a new position in the remote file

           This method changes the position in the remote file. The
           ``offset`` passed in is treated as relative to the beginning
           of the file if ``from_what`` is set to ``SEEK_SET`` (the
           default), relative to the current file position if it is
           set to ``SEEK_CUR``, or relative to the end of the file
           if it is set to ``SEEK_END``.

           :param int offset:
               The amount to seek
           :param int from_what: (optional)
               The reference point to use (SEEK_SET, SEEK_CUR, or SEEK_END)

           :returns: The new byte offset from the beginning of the file

        """

        if self._handle is None:
            raise ValueError('I/O operation on closed file')

        if from_what == SEEK_SET:
            self._offset = offset
        elif from_what == SEEK_CUR:
            self._offset += offset
        elif from_what == SEEK_END:
            self._offset = (yield from self._end()) + offset
        else:
            raise ValueError('Invalid reference point')

        return self._offset

    @asyncio.coroutine
    def tell(self):
        """Return the current position in the remote file

           This method returns the current position in the remote file.

           :returns: The current byte offset from the beginning of the file

        """

        if self._handle is None:
            raise ValueError('I/O operation on closed file')

        if self._offset is None:
            self._offset = yield from self._end()

        return self._offset

    @asyncio.coroutine
    def stat(self):
        """Return file attributes of the remote file

           This method queries file attributes of the currently open file.

           :returns: An :class:`SFTPAttrs` containing the file attributes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        if self._handle is None:
            raise ValueError('I/O operation on closed file')

        return (yield from self._handler.fstat(self._handle))

    @asyncio.coroutine
    def setstat(self, attrs):
        """Set attributes of the remote file

           This method sets file attributes of the currently open file.

           :param attrs:
               File attributes to set on the file
           :type attrs: :class:`SFTPAttrs`

           :raises: :exc:`SFTPError` if the server returns an error

        """

        if self._handle is None:
            raise ValueError('I/O operation on closed file')

        yield from self._handler.fsetstat(self._handle, attrs)

    @asyncio.coroutine
    def statvfs(self):
        """Return file system attributes of the remote file

           This method queries attributes of the file system containing
           the currently open file.

           :returns: An :class:`SFTPVFSAttrs` containing the file system
                     attributes

           :raises: :exc:`SFTPError` if the server doesn't support this
                    extension or returns an error

        """

        if self._handle is None:
            raise ValueError('I/O operation on closed file')

        return (yield from self._handler.fstatvfs(self._handle))

    @asyncio.coroutine
    def truncate(self, size=None):
        """Truncate the remote file to the specified size

           This method changes the remote file's size to the specified
           value. If a size is not provided, the current file position
           is used.

           :param int size: (optional)
               The desired size of the file, in bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        if size is None:
            size = self._offset

        yield from self.setstat(SFTPAttrs(size=size))

    @asyncio.coroutine
    def chown(self, uid, gid):
        """Change the owner user and group id of the remote file

           This method changes the user and group id of the
           currently open file.

           :param int uid:
               The new user id to assign to the file
           :param int gid:
               The new group id to assign to the file

           :raises: :exc:`SFTPError` if the server returns an error

        """

        yield from self.setstat(SFTPAttrs(uid=uid, gid=gid))

    @asyncio.coroutine
    def chmod(self, mode):
        """Change the file permissions of the remote file

           This method changes the permissions of the currently
           open file.

           :param int mode:
               The new file permissions, expressed as an int

           :raises: :exc:`SFTPError` if the server returns an error

        """

        yield from self.setstat(SFTPAttrs(permissions=mode))

    @asyncio.coroutine
    def utime(self, times=None):
        """Change the access and modify times of the remote file

           This method changes the access and modify times of the
           currently open file. If ``times`` is not provided,
           the times will be changed to the current time.

           :param times: (optional)
               The new access and modify times, as seconds relative to
               the UNIX epoch
           :type times: tuple of two int or float values

           :raises: :exc:`SFTPError` if the server returns an error

        """

        # pylint: disable=unpacking-non-sequence
        if times is None:
            atime = mtime = time.time()
        else:
            atime, mtime = times

        yield from self.setstat(SFTPAttrs(atime=atime, mtime=mtime))

    @asyncio.coroutine
    def fsync(self):
        """Force the remote file data to be written to disk"""

        if self._handle is None:
            raise ValueError('I/O operation on closed file')

        yield from self._handler.fsync(self._handle)

    @asyncio.coroutine
    def close(self):
        """Close the remote file"""

        if self._handle:
            yield from self._handler.close(self._handle)
            self._handle = None


class SFTPClient:
    """SFTP client

       This class represents the client side of an SFTP session. It is
       started by calling the :meth:`start_sftp_client()
       <SSHClientConnection.start_sftp_client>` method on the
       :class:`SSHClientConnection` class.

    """

    def __init__(self, loop, handler, path_encoding, path_errors):
        self._loop = loop
        self._handler = handler
        self._path_encoding = path_encoding
        self._path_errors = path_errors
        self._cwd = None

    def __enter__(self):
        """Allow SFTPClient to be used as a context manager"""

        return self

    def __exit__(self, *exc_info):
        """Automatically close the session when used as a context manager"""

        self.exit()

    @asyncio.coroutine
    def __aenter__(self):
        """Allow SFTPClient to be used as an async context manager"""

        return self

    @asyncio.coroutine
    def __aexit__(self, *exc_info):
        """Wait for client close when used as an async context manager"""

        self.__exit__()
        yield from self.wait_closed()

    def encode(self, path):
        """Encode path name using configured path encoding

           This method has no effect if the path is already bytes.

        """

        if isinstance(path, str):
            if self._path_encoding:
                path = path.encode(self._path_encoding, self._path_errors)
            else:
                raise SFTPError(FX_BAD_MESSAGE, 'Path must be bytes when '
                                'encoding is not set')

        return path

    def decode(self, path, want_string=True):
        """Decode path name using configured path encoding

           This method has no effect if want_string is set to ``False``.

        """

        if want_string and self._path_encoding:
            try:
                path = path.decode(self._path_encoding, self._path_errors)
            except UnicodeDecodeError:
                raise SFTPError(FX_BAD_MESSAGE,
                                'Unable to decode name') from None

        return path

    def compose_path(self, path, parent=...):
        """Compose a path

           If parent is not specified, return a path relative to the
           current remote working directory.

        """

        if parent is ...:
            parent = self._cwd

        path = self.encode(path)

        return posixpath.join(parent, path) if parent else path

    @asyncio.coroutine
    def _mode(self, path, statfunc=None):
        """Return the mode of a remote path, or 0 if it can't be accessed"""

        if statfunc is None:
            statfunc = self.stat

        try:
            return (yield from statfunc(path)).permissions
        except SFTPError as exc:
            if exc.code in (FX_NO_SUCH_FILE, FX_PERMISSION_DENIED):
                return 0
            else:
                raise

    @asyncio.coroutine
    def _glob(self, fs, patterns, error_handler):
        """Begin a new glob pattern match"""

        # pylint: disable=no-self-use

        if isinstance(patterns, (str, bytes)):
            patterns = [patterns]

        result = []

        for pattern in patterns:
            if not pattern:
                continue

            names = yield from match_glob(fs, fs.encode(pattern), error_handler)

            if isinstance(pattern, str):
                names = [fs.decode(name) for name in names]

            result.extend(names)

        return result

    @asyncio.coroutine
    def _copy(self, srcfs, dstfs, srcpath, dstpath, preserve, recurse,
              follow_symlinks, block_size, progress_handler, error_handler):
        """Copy a file, directory, or symbolic link"""

        if follow_symlinks:
            srcattrs = yield from srcfs.stat(srcpath)
        else:
            srcattrs = yield from srcfs.lstat(srcpath)

        try:
            if stat.S_ISDIR(srcattrs.permissions):
                if not recurse:
                    raise SFTPError(FX_FAILURE, '%s is a directory' %
                                    srcpath.decode('utf-8', errors='replace'))

                if not (yield from dstfs.isdir(dstpath)):
                    yield from dstfs.mkdir(dstpath)

                names = yield from srcfs.listdir(srcpath)

                for name in names:
                    if name in (b'.', b'..'):
                        continue

                    srcfile = posixpath.join(srcpath, name)
                    dstfile = posixpath.join(dstpath, name)

                    yield from self._copy(srcfs, dstfs, srcfile,
                                          dstfile, preserve, recurse,
                                          follow_symlinks, block_size,
                                          progress_handler, error_handler)
            elif stat.S_ISLNK(srcattrs.permissions):
                targetpath = yield from srcfs.readlink(srcpath)
                yield from dstfs.symlink(targetpath, dstpath)
            else:
                yield from _SFTPFileCopier(self._loop).copy(
                    srcfs, dstfs, srcpath, dstpath, srcattrs.size,
                    block_size, progress_handler)

            if preserve:
                srcattrs = yield from srcfs.stat(srcpath)

                yield from dstfs.setstat(
                    dstpath, SFTPAttrs(permissions=srcattrs.permissions,
                                       atime=srcattrs.atime,
                                       mtime=srcattrs.mtime))
        except (OSError, SFTPError) as exc:
            # pylint: disable=attribute-defined-outside-init
            exc.srcpath = srcpath
            exc.dstpath = dstpath

            if error_handler:
                error_handler(exc)
            else:
                raise

    @asyncio.coroutine
    def _begin_copy(self, srcfs, dstfs, srcpaths, dstpath, preserve,
                    recurse, follow_symlinks, block_size,
                    progress_handler, error_handler):
        """Begin a new file upload, download, or copy"""

        dst_isdir = dstpath is None or (yield from dstfs.isdir(dstpath))

        if dstpath:
            dstpath = dstfs.encode(dstpath)

        if isinstance(srcpaths, (str, bytes)):
            srcpaths = [srcpaths]
        elif not dst_isdir:
            raise SFTPError(FX_FAILURE, '%s must be a directory' %
                            dstpath.decode('utf-8', errors='replace'))

        for srcfile in srcpaths:
            srcfile = srcfs.encode(srcfile)
            filename = posixpath.basename(srcfile)

            if dstpath is None:
                dstfile = filename
            elif dst_isdir:
                dstfile = dstfs.compose_path(filename, parent=dstpath)
            else:
                dstfile = dstpath

            yield from self._copy(srcfs, dstfs, srcfile, dstfile, preserve,
                                  recurse, follow_symlinks, block_size,
                                  progress_handler, error_handler)

    @asyncio.coroutine
    def get(self, remotepaths, localpath=None, *, preserve=False,
            recurse=False, follow_symlinks=False, block_size=SFTP_BLOCK_SIZE,
            progress_handler=None, error_handler=None):
        """Download remote files

           This method downloads one or more files or directories from
           the remote system. Either a single remote path or a sequence
           of remote paths to download can be provided.

           When downloading a single file or directory, the local path can
           be either the full path to download data into or the path to an
           existing directory where the data should be placed. In the
           latter case, the base file name from the remote path will be
           used as the local name.

           When downloading multiple files, the local path must refer to
           an existing directory.

           If no local path is provided, the file is downloaded
           into the current local working directory.

           If preserve is ``True``, the access and modification times
           and permissions of the original file are set on the
           downloaded file.

           If recurse is ``True`` and the remote path points at a
           directory, the entire subtree under that directory is
           downloaded.

           If follow_symlinks is set to ``True``, symbolic links found
           on the remote system will have the contents of their target
           downloaded rather than creating a local symbolic link. When
           using this option during a recursive download, one needs to
           watch out for links that result in loops.

           The block_size value controls the size of read and write
           operations issued to download the files. It defaults to 16 KB.

           If progress_handler is specified, it will be called after
           each block of a file is successfully downloaded. The arguments
           passed to this handler will be the source path, destination
           path, bytes downloaded so far, and total bytes in the file
           being downloaded. If multiple source paths are provided or
           recurse is set to ``True``, the progress_handler will be
           called consecutively on each file being downloaded.

           If error_handler is specified and an error occurs during
           the download, this handler will be called with the exception
           instead of it being raised. This is intended to primarily be
           used when multiple remote paths are provided or when recurse
           is set to ``True``, to allow error information to be collected
           without aborting the download of the remaining files. The
           error handler can raise an exception if it wants the download
           to completely stop. Otherwise, after an error, the download
           will continue starting with the next file.

           :param remotepaths:
               The paths of the remote files or directories to download
           :param str localpath: (optional)
               The path of the local file or directory to download into
           :param bool preserve: (optional)
               Whether or not to preserve the original file attributes
           :param bool recurse: (optional)
               Whether or not to recursively copy directories
           :param bool follow_symlinks: (optional)
               Whether or not to follow symbolic links
           :param int block_size: (optional)
               The block size to use for file reads and writes
           :param callable progress_handler: (optional)
               The function to call to report download progress
           :param callable error_handler: (optional)
               The function to call when an error occurs
           :type remotepaths: str or bytes, or a sequence of these

           :raises: | :exc:`OSError` if a local file I/O error occurs
                    | :exc:`SFTPError` if the server returns an error

        """

        yield from self._begin_copy(self, LocalFile, remotepaths, localpath,
                                    preserve, recurse, follow_symlinks,
                                    block_size, progress_handler,
                                    error_handler)

    @asyncio.coroutine
    def put(self, localpaths, remotepath=None, *, preserve=False,
            recurse=False, follow_symlinks=False, block_size=SFTP_BLOCK_SIZE,
            progress_handler=None, error_handler=None):
        """Upload local files

           This method uploads one or more files or directories to the
           remote system. Either a single local path or a sequence of
           local paths to upload can be provided.

           When uploading a single file or directory, the remote path can
           be either the full path to upload data into or the path to an
           existing directory where the data should be placed. In the
           latter case, the base file name from the local path will be
           used as the remote name.

           When uploading multiple files, the remote path must refer to
           an existing directory.

           If no remote path is provided, the file is uploaded into the
           current remote working directory.

           If preserve is ``True``, the access and modification times
           and permissions of the original file are set on the
           uploaded file.

           If recurse is ``True`` and the local path points at a
           directory, the entire subtree under that directory is
           uploaded.

           If follow_symlinks is set to ``True``, symbolic links found
           on the local system will have the contents of their target
           uploaded rather than creating a remote symbolic link. When
           using this option during a recursive upload, one needs to
           watch out for links that result in loops.

           The block_size value controls the size of read and write
           operations issued to upload the files. It defaults to 16 KB.

           If progress_handler is specified, it will be called after
           each block of a file is successfully uploaded. The arguments
           passed to this handler will be the source path, destination
           path, bytes uploaded so far, and total bytes in the file
           being uploaded. If multiple source paths are provided or
           recurse is set to ``True``, the progress_handler will be
           called consecutively on each file being uploaded.

           If error_handler is specified and an error occurs during
           the upload, this handler will be called with the exception
           instead of it being raised. This is intended to primarily be
           used when multiple local paths are provided or when recurse
           is set to ``True``, to allow error information to be collected
           without aborting the upload of the remaining files. The
           error handler can raise an exception if it wants the upload
           to completely stop. Otherwise, after an error, the upload
           will continue starting with the next file.

           :param localpaths:
               The paths of the local files or directories to upload
           :param remotepath: (optional)
               The path of the remote file or directory to upload into
           :param bool preserve: (optional)
               Whether or not to preserve the original file attributes
           :param bool recurse: (optional)
               Whether or not to recursively copy directories
           :param bool follow_symlinks: (optional)
               Whether or not to follow symbolic links
           :param int block_size: (optional)
               The block size to use for file reads and writes
           :param callable progress_handler: (optional)
               The function to call to report upload progress
           :param callable error_handler: (optional)
               The function to call when an error occurs
           :type localpaths: str or bytes, or a sequence of these
           :type remotepath: str or bytes

           :raises: | :exc:`OSError` if a local file I/O error occurs
                    | :exc:`SFTPError` if the server returns an error

        """

        yield from self._begin_copy(LocalFile, self, localpaths, remotepath,
                                    preserve, recurse, follow_symlinks,
                                    block_size, progress_handler,
                                    error_handler)

    @asyncio.coroutine
    def copy(self, srcpaths, dstpath=None, *, preserve=False,
             recurse=False, follow_symlinks=False, block_size=SFTP_BLOCK_SIZE,
             progress_handler=None, error_handler=None):
        """Copy remote files to a new location

           This method copies one or more files or directories on the
           remote system to a new location. Either a single source path
           or a sequence of source paths to copy can be provided.

           When copying a single file or directory, the destination path
           can be either the full path to copy data into or the path to
           an existing directory where the data should be placed. In the
           latter case, the base file name from the source path will be
           used as the destination name.

           When copying multiple files, the destination path must refer
           to an existing remote directory.

           If no destination path is provided, the file is copied into
           the current remote working directory.

           If preserve is ``True``, the access and modification times
           and permissions of the original file are set on the
           copied file.

           If recurse is ``True`` and the source path points at a
           directory, the entire subtree under that directory is
           copied.

           If follow_symlinks is set to ``True``, symbolic links found
           in the source will have the contents of their target copied
           rather than creating a copy of the symbolic link. When
           using this option during a recursive copy, one needs to
           watch out for links that result in loops.

           The block_size value controls the size of read and write
           operations issued to copy the files. It defaults to 16 KB.

           If progress_handler is specified, it will be called after
           each block of a file is successfully copied. The arguments
           passed to this handler will be the source path, destination
           path, bytes copied so far, and total bytes in the file
           being copied. If multiple source paths are provided or
           recurse is set to ``True``, the progress_handler will be
           called consecutively on each file being copied.

           If error_handler is specified and an error occurs during
           the copy, this handler will be called with the exception
           instead of it being raised. This is intended to primarily be
           used when multiple source paths are provided or when recurse
           is set to ``True``, to allow error information to be collected
           without aborting the copy of the remaining files. The error
           handler can raise an exception if it wants the copy to
           completely stop. Otherwise, after an error, the copy will
           continue starting with the next file.

           :param srcpaths:
               The paths of the remote files or directories to copy
           :param dstpath: (optional)
               The path of the remote file or directory to copy into
           :param bool preserve: (optional)
               Whether or not to preserve the original file attributes
           :param bool recurse: (optional)
               Whether or not to recursively copy directories
           :param bool follow_symlinks: (optional)
               Whether or not to follow symbolic links
           :param int block_size: (optional)
               The block size to use for file reads and writes
           :param callable progress_handler: (optional)
               The function to call to report copy progress
           :param callable error_handler: (optional)
               The function to call when an error occurs
           :type srcpaths: str or bytes, or a sequence of these
           :type dstpath: str or bytes

           :raises: | :exc:`OSError` if a local file I/O error occurs
                    | :exc:`SFTPError` if the server returns an error

        """

        yield from self._begin_copy(self, self, srcpaths, dstpath, preserve,
                                    recurse, follow_symlinks, block_size,
                                    progress_handler, error_handler)

    @asyncio.coroutine
    def mget(self, remotepaths, localpath=None, *, preserve=False,
             recurse=False, follow_symlinks=False, block_size=SFTP_BLOCK_SIZE,
             progress_handler=None, error_handler=None):
        """Download remote files with glob pattern match

           This method downloads files and directories from the remote
           system matching one or more glob patterns.

           The arguments to this method are identical to the :meth:`get`
           method, except that the remote paths specified can contain
           '*' and '?' wildcard characters.

        """

        matches = yield from self._glob(self, remotepaths, error_handler)

        yield from self._begin_copy(self, LocalFile, matches, localpath,
                                    preserve, recurse, follow_symlinks,
                                    block_size, progress_handler,
                                    error_handler)

    @asyncio.coroutine
    def mput(self, localpaths, remotepath=None, *, preserve=False,
             recurse=False, follow_symlinks=False, block_size=SFTP_BLOCK_SIZE,
             progress_handler=None, error_handler=None):
        """Upload local files with glob pattern match

           This method uploads files and directories to the remote
           system matching one or more glob patterns.

           The arguments to this method are identical to the :meth:`put`
           method, except that the local paths specified can contain
           '*' and '?' wildcard characters.

        """

        matches = yield from self._glob(LocalFile, localpaths, error_handler)

        yield from self._begin_copy(LocalFile, self, matches, remotepath,
                                    preserve, recurse, follow_symlinks,
                                    block_size, progress_handler,
                                    error_handler)

    @asyncio.coroutine
    def mcopy(self, srcpaths, dstpath=None, *, preserve=False,
              recurse=False, follow_symlinks=False, block_size=SFTP_BLOCK_SIZE,
              progress_handler=None, error_handler=None):
        """Download remote files with glob pattern match

           This method copies files and directories on the remote
           system matching one or more glob patterns.

           The arguments to this method are identical to the :meth:`copy`
           method, except that the source paths specified can contain
           '*' and '?' wildcard characters.

        """

        matches = yield from self._glob(self, srcpaths, error_handler)

        yield from self._begin_copy(self, self, matches, dstpath, preserve,
                                    recurse, follow_symlinks, block_size,
                                    progress_handler, error_handler)

    @asyncio.coroutine
    def glob(self, patterns, error_handler=None):
        """Match remote files against glob patterns

           This method matches remote files against one or more glob
           patterns. Either a single pattern or a sequence of patterns
           can be provided to match against.

           If error_handler is specified and an error occurs during
           the match, this handler will be called with the exception
           instead of it being raised. This is intended to primarily be
           used when multiple patterns are provided to allow error
           information to be collected without aborting the match
           against the remaining patterns. The error handler can raise
           an exception if it wants to completely abort the match.
           Otherwise, after an error, the match will continue starting
           with the next pattern.

           An error will be raised if any of the patterns completely
           fail to match, and this can either stop the match against
           the remaining patterns or be handled by the error_handler
           just like other errors.

           :param patterns:
               Glob patterns to try and match remote files against
           :param callable error_handler: (optional)
               The function to call when an error occurs
           :type patterns: str or bytes, or a sequence of these

           :raises: :exc:`SFTPError` if the server returns an error
                    or no match is found

        """

        return (yield from self._glob(self, patterns, error_handler))

    @async_context_manager
    def open(self, path, pflags_or_mode=FXF_READ, attrs=SFTPAttrs(),
             encoding='utf-8', errors='strict'):
        """Open a remote file

           This method opens a remote file and returns an
           :class:`SFTPClientFile` object which can be used to read and
           write data and get and set file attributes.

           The path can be either a str or bytes value. If it is a
           str, it will be encoded using the file encoding specified
           when the :class:`SFTPClient` was started.

           The following open mode flags are supported:

             ========== ======================================================
             Mode       Description
             ========== ======================================================
             FXF_READ   Open the file for reading.
             FXF_WRITE  Open the file for writing. If both this and FXF_READ
                        are set, open the file for both reading and writing.
             FXF_APPEND Force writes to append data to the end of the file
                        regardless of seek position.
             FXF_CREAT  Create the file if it doesn't exist. Without this,
                        attempts to open a non-existent file will fail.
             FXF_TRUNC  Truncate the file to zero length if it already exists.
             FXF_EXCL   Return an error when trying to open a file which
                        already exists.
             ========== ======================================================

           By default, file data is read and written as strings in UTF-8
           format with strict error checking, but this can be changed
           using the ``encoding`` and ``errors`` parameters. To read and
           write data as bytes in binary format, an ``encoding`` value of
           ``None`` can be used.

           Instead of these flags, a Python open mode string can also be
           provided. Python open modes map to the above flags as follows:

             ==== =============================================
             Mode Flags
             ==== =============================================
             r    FXF_READ
             w    FXF_WRITE | FXF_CREAT | FXF_TRUNC
             a    FXF_WRITE | FXF_CREAT | FXF_APPEND
             x    FXF_WRITE | FXF_CREAT | FXF_EXCL

             r+   FXF_READ | FXF_WRITE
             w+   FXF_READ | FXF_WRITE | FXF_CREAT | FXF_TRUNC
             a+   FXF_READ | FXF_WRITE | FXF_CREAT | FXF_APPEND
             x+   FXF_READ | FXF_WRITE | FXF_CREAT | FXF_EXCL
             ==== =============================================

           Including a 'b' in the mode causes the ``encoding`` to be set
           to ``None``, forcing all data to be read and written as bytes
           in binary format.

           The attrs argument is used to set initial attributes of the
           file if it needs to be created. Otherwise, this argument is
           ignored.

           :param path:
               The name of the remote file to open
           :param pflags_or_mode: (optional)
               The access mode to use for the remote file (see above)
           :param attrs: (optional)
               File attributes to use if the file needs to be created
           :param str encoding: (optional)
               The Unicode encoding to use for data read and written
               to the remote file
           :param str errors: (optional)
               The error-handling mode if an invalid Unicode byte
               sequence is detected, defaulting to 'strict' which
               raises an exception
           :type path: str or bytes
           :type pflags_or_mode: int or str
           :type attrs: :class:`SFTPAttrs`

           :returns: An :class:`SFTPClientFile` to use to access the file

           :raises: | :exc:`ValueError` if the mode is not valid
                    | :exc:`SFTPError` if the server returns an error

        """

        if isinstance(pflags_or_mode, str):
            pflags, binary = _mode_to_pflags(pflags_or_mode)

            if binary:
                encoding = None
        else:
            pflags = pflags_or_mode

        path = self.compose_path(path)
        handle = yield from self._handler.open(path, pflags, attrs)

        return SFTPClientFile(self._handler, handle, pflags & FXF_APPEND,
                              encoding, errors)

    @asyncio.coroutine
    def stat(self, path):
        """Get attributes of a remote file or directory, following symlinks

           This method queries the attributes of a remote file or
           directory. If the path provided is a symbolic link, the
           returned attributes will correspond to the target of the
           link.

           :param path:
               The path of the remote file or directory to get attributes for
           :type path: str or bytes

           :returns: An :class:`SFTPAttrs` containing the file attributes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        path = self.compose_path(path)
        return (yield from self._handler.stat(path))

    @asyncio.coroutine
    def lstat(self, path):
        """Get attributes of a remote file, directory, or symlink

           This method queries the attributes of a remote file,
           directory, or symlink. Unlike :meth:`stat`, this method
           returns the attributes of a symlink itself rather than
           the target of that link.

           :param path:
               The path of the remote file, directory, or link to get
               attributes for
           :type path: str or bytes

           :returns: An :class:`SFTPAttrs` containing the file attributes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        path = self.compose_path(path)
        return (yield from self._handler.lstat(path))

    @asyncio.coroutine
    def setstat(self, path, attrs):
        """Set attributes of a remote file or directory

           This method sets attributes of a remote file or directory.
           If the path provided is a symbolic link, the attributes
           will be set on the target of the link. A subset of the
           fields in ``attrs`` can be initialized and only those
           attributes will be changed.

           :param path:
               The path of the remote file or directory to set attributes for
           :param attrs:
               File attributes to set
           :type path: str or bytes
           :type attrs: :class:`SFTPAttrs`

           :raises: :exc:`SFTPError` if the server returns an error

        """

        path = self.compose_path(path)
        yield from self._handler.setstat(path, attrs)

    @asyncio.coroutine
    def statvfs(self, path):
        """Get attributes of a remote file system

           This method queries the attributes of the file system containing
           the specified path.

           :param path:
               The path of the remote file system to get attributes for
           :type path: str or bytes

           :returns: An :class:`SFTPVFSAttrs` containing the file system
                     attributes

           :raises: :exc:`SFTPError` if the server doesn't support this
                    extension or returns an error

        """

        path = self.compose_path(path)
        return (yield from self._handler.statvfs(path))

    @asyncio.coroutine
    def truncate(self, path, size):
        """Truncate a remote file to the specified size

           This method truncates a remote file to the specified size.
           If the path provided is a symbolic link, the target of
           the link will be truncated.

           :param path:
               The path of the remote file to be truncated
           :param int size:
               The desired size of the file, in bytes
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        yield from self.setstat(path, SFTPAttrs(size=size))

    @asyncio.coroutine
    def chown(self, path, uid, gid):
        """Change the owner user and group id of a remote file or directory

           This method changes the user and group id of a remote
           file or directory. If the path provided is a symbolic
           link, the target of the link will be changed.

           :param path:
               The path of the remote file to change
           :param int uid:
               The new user id to assign to the file
           :param int gid:
               The new group id to assign to the file
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        yield from self.setstat(path, SFTPAttrs(uid=uid, gid=gid))

    @asyncio.coroutine
    def chmod(self, path, mode):
        """Change the file permissions of a remote file or directory

           This method changes the permissions of a remote file or
           directory. If the path provided is a symbolic link, the
           target of the link will be changed.

           :param path:
               The path of the remote file to change
           :param int mode:
               The new file permissions, expressed as an int
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        yield from self.setstat(path, SFTPAttrs(permissions=mode))

    @asyncio.coroutine
    def utime(self, path, times=None):
        """Change the access and modify times of a remote file or directory

           This method changes the access and modify times of a
           remote file or directory. If ``times`` is not provided,
           the times will be changed to the current time. If the
           path provided is a symbolic link, the target of the link
           will be changed.

           :param path:
               The path of the remote file to change
           :param times: (optional)
               The new access and modify times, as seconds relative to
               the UNIX epoch
           :type path: str or bytes
           :type times: tuple of two int or float values

           :raises: :exc:`SFTPError` if the server returns an error

        """

        # pylint: disable=unpacking-non-sequence
        if times is None:
            atime = mtime = time.time()
        else:
            atime, mtime = times

        yield from self.setstat(path, SFTPAttrs(atime=atime, mtime=mtime))

    @asyncio.coroutine
    def exists(self, path):
        """Return if the remote path exists and isn't a broken symbolic link

           :param path:
               The remote path to check
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        return bool((yield from self._mode(path)))

    @asyncio.coroutine
    def lexists(self, path):
        """Return if the remote path exists, without following symbolic links

           :param path:
               The remote path to check
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        return bool((yield from self._mode(path, statfunc=self.lstat)))

    @asyncio.coroutine
    def getatime(self, path):
        """Return the last access time of a remote file or directory

           :param path:
               The remote path to check
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        return (yield from self.stat(path)).atime

    @asyncio.coroutine
    def getmtime(self, path):
        """Return the last modification time of a remote file or directory

           :param path:
               The remote path to check
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        return (yield from self.stat(path)).mtime

    @asyncio.coroutine
    def getsize(self, path):
        """Return the size of a remote file or directory

           :param path:
               The remote path to check
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        return (yield from self.stat(path)).size

    @asyncio.coroutine
    def isdir(self, path):
        """Return if the remote path refers to a directory

           :param path:
               The remote path to check
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        return stat.S_ISDIR((yield from self._mode(path)))

    @asyncio.coroutine
    def isfile(self, path):
        """Return if the remote path refers to a regular file

           :param path:
               The remote path to check
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        return stat.S_ISREG((yield from self._mode(path)))

    @asyncio.coroutine
    def islink(self, path):
        """Return if the remote path refers to a symbolic link

           :param path:
               The remote path to check
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        return stat.S_ISLNK((yield from self._mode(path, statfunc=self.lstat)))

    @asyncio.coroutine
    def remove(self, path):
        """Remove a remote file

           This method removes a remote file or symbolic link.

           :param path:
               The path of the remote file or link to remove
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        path = self.compose_path(path)
        yield from self._handler.remove(path)

    @asyncio.coroutine
    def unlink(self, path):
        """Remove a remote file (see :meth:`remove`)"""

        yield from self.remove(path)

    @asyncio.coroutine
    def rename(self, oldpath, newpath):
        """Rename a remote file, directory, or link

           This method renames a remote file, directory, or link.

           .. note:: This requests the standard SFTP version of rename
                     which will not overwrite the new path if it already
                     exists. To request POSIX behavior where the new
                     path is removed before the rename, use
                     :meth:`posix_rename`.

           :param oldpath:
               The path of the remote file, directory, or link to rename
           :param newpath:
               The new name for this file, directory, or link
           :type oldpath: str or bytes
           :type newpath: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        oldpath = self.compose_path(oldpath)
        newpath = self.compose_path(newpath)
        yield from self._handler.rename(oldpath, newpath)

    @asyncio.coroutine
    def posix_rename(self, oldpath, newpath):
        """Rename a remote file, directory, or link with POSIX semantics

           This method renames a remote file, directory, or link,
           removing the prior instance of new path if it previously
           existed.

           This method may not be supported by all SFTP servers.

           :param oldpath:
               The path of the remote file, directory, or link to rename
           :param newpath:
               The new name for this file, directory, or link
           :type oldpath: str or bytes
           :type newpath: str or bytes

           :raises: :exc:`SFTPError` if the server doesn't support this
                    extension or returns an error

        """

        oldpath = self.compose_path(oldpath)
        newpath = self.compose_path(newpath)
        yield from self._handler.posix_rename(oldpath, newpath)

    @asyncio.coroutine
    def readdir(self, path='.'):
        """Read the contents of a remote directory

           This method reads the contents of a directory, returning
           the names and attributes of what is contained there. If no
           path is provided, it defaults to the current remote working
           directory.

           :param path: (optional)
               The path of the remote directory to read
           :type path: str or bytes

           :returns: A list of :class:`SFTPName` entries, with path
                     names matching the type used to pass in the path

           :raises: :exc:`SFTPError` if the server returns an error

        """

        names = []

        dirpath = self.compose_path(path)
        handle = yield from self._handler.opendir(dirpath)

        try:
            while True:
                names.extend((yield from self._handler.readdir(handle)))
        except SFTPError as exc:
            if exc.code != FX_EOF:
                raise
        finally:
            yield from self._handler.close(handle)

        if isinstance(path, str):
            for name in names:
                name.filename = self.decode(name.filename)
                name.longname = self.decode(name.longname)

        return names

    @asyncio.coroutine
    def listdir(self, path='.'):
        """Read the names of the files in a remote directory

           This method reads the names of files and subdirectories
           in a remote directory. If no path is provided, it defaults
           to the current remote working directory.

           :param path: (optional)
               The path of the remote directory to read
           :type path: str or bytes

           :returns: A list of file/subdirectory names, matching the
                     type used to pass in the path

           :raises: :exc:`SFTPError` if the server returns an error

        """

        names = yield from self.readdir(path)
        return [name.filename for name in names]

    @asyncio.coroutine
    def mkdir(self, path, attrs=SFTPAttrs()):
        """Create a remote directory with the specified attributes

           This method creates a new remote directory at the
           specified path with the requested attributes.

           :param path:
               The path of where the new remote directory should be created
           :param attrs: (optional)
               The file attributes to use when creating the directory
           :type path: str or bytes
           :type attrs: :class:`SFTPAttrs`

           :raises: :exc:`SFTPError` if the server returns an error

        """

        path = self.compose_path(path)
        yield from self._handler.mkdir(path, attrs)

    @asyncio.coroutine
    def rmdir(self, path):
        """Remove a remote directory

           This method removes a remote directory. The directory
           must be empty for the removal to succeed.

           :param path:
               The path of the remote directory to remove
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        path = self.compose_path(path)
        yield from self._handler.rmdir(path)

    @asyncio.coroutine
    def realpath(self, path):
        """Return the canonical version of a remote path

           This method returns a canonical version of the requested path.

           :param path: (optional)
               The path of the remote directory to canonicalize
           :type path: str or bytes

           :returns: The canonical path as a str or bytes, matching
                     the type used to pass in the path

           :raises: :exc:`SFTPError` if the server returns an error

        """

        fullpath = self.compose_path(path)
        names = yield from self._handler.realpath(fullpath)

        if len(names) > 1:
            raise SFTPError(FX_BAD_MESSAGE, 'Too many names returned')

        return self.decode(names[0].filename, isinstance(path, str))

    @asyncio.coroutine
    def getcwd(self):
        """Return the current remote working directory

           :returns: The current remote working directory, decoded using
                     the specified path encoding

           :raises: :exc:`SFTPError` if the server returns an error

        """

        if self._cwd is None:
            self._cwd = yield from self.realpath(b'.')

        return self.decode(self._cwd)

    @asyncio.coroutine
    def chdir(self, path):
        """Change the current remote working directory

           :param path: The path to set as the new remote working directory
           :type path: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        self._cwd = yield from self.realpath(self.encode(path))

    @asyncio.coroutine
    def readlink(self, path):
        """Return the target of a remote symbolic link

           This method returns the target of a symbolic link.

           :param path:
               The path of the remote symbolic link to follow
           :type path: str or bytes

           :returns: The target path of the link as a str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        linkpath = self.compose_path(path)
        names = yield from self._handler.readlink(linkpath)

        if len(names) > 1:
            raise SFTPError(FX_BAD_MESSAGE, 'Too many names returned')

        return self.decode(names[0].filename, isinstance(path, str))

    @asyncio.coroutine
    def symlink(self, oldpath, newpath):
        """Create a remote symbolic link

           This method creates a symbolic link. The argument order here
           matches the standard Python :meth:`os.symlink` call. The
           argument order sent on the wire is automatically adapted
           depending on the version information sent by the server, as
           a number of servers (OpenSSH in particular) did not follow
           the SFTP standard when implementing this call.

           :param oldpath:
               The path the link should point to
           :param newpath:
               The path of where to create the remote symbolic link
           :type oldpath: str or bytes
           :type newpath: str or bytes

           :raises: :exc:`SFTPError` if the server returns an error

        """

        oldpath = self.compose_path(oldpath)
        newpath = self.encode(newpath)
        yield from self._handler.symlink(oldpath, newpath)

    @asyncio.coroutine
    def link(self, oldpath, newpath):
        """Create a remote hard link

           This method creates a hard link to the remote file specified
           by oldpath at the location specified by newpath.

           This method may not be supported by all SFTP servers.

           :param oldpath:
               The path of the remote file the hard link should point to
           :param newpath:
               The path of where to create the remote hard link
           :type oldpath: str or bytes
           :type newpath: str or bytes

           :raises: :exc:`SFTPError` if the server doesn't support this
                    extension or returns an error

        """

        oldpath = self.compose_path(oldpath)
        newpath = self.compose_path(newpath)
        yield from self._handler.link(oldpath, newpath)

    def exit(self):
        """Exit the SFTP client session

           This method exits the SFTP client session, closing the
           corresponding channel opened on the server.

        """

        self._handler.exit()

    @asyncio.coroutine
    def wait_closed(self):
        """Wait for this SFTP client session to close"""

        yield from self._handler.wait_closed()


class SFTPServerHandler(SFTPHandler):
    """An SFTP server session handler"""

    _extensions = [(b'posix-rename@openssh.com', b'1'),
                   (b'hardlink@openssh.com', b'1'),
                   (b'fsync@openssh.com', b'1')]

    if hasattr(os, 'statvfs'): # pragma: no branch
        _extensions += [(b'statvfs@openssh.com', b'2'),
                        (b'fstatvfs@openssh.com', b'2')]

    def __init__(self, server, reader, writer):
        super().__init__(reader, writer)

        self._server = server
        self._version = None
        self._nonstandard_symlink = False
        self._next_handle = 0
        self._file_handles = {}
        self._dir_handles = {}

    @asyncio.coroutine
    def _cleanup(self, exc):
        """Clean up this SFTP server session"""

        if self._server: # pragma: no branch
            for file_obj in self._file_handles.values():
                result = self._server.close(file_obj)

                if asyncio.iscoroutine(result):
                    result = yield from result

            result = self._server.exit()

            if asyncio.iscoroutine(result):
                result = yield from result

            self._server = None
            self._file_handles = []
            self._dir_handles = []

        yield from super()._cleanup(exc)

    def _get_next_handle(self):
        """Get the next available unique file handle number"""

        while True:
            handle = self._next_handle.to_bytes(4, 'big')
            self._next_handle = (self._next_handle + 1) & 0xffffffff

            if (handle not in self._file_handles and
                    handle not in self._dir_handles):
                return handle

    @asyncio.coroutine
    def _process_packet(self, pkttype, pktid, packet):
        """Process incoming SFTP requests"""

        # pylint: disable=broad-except
        try:
            if pkttype == FXP_EXTENDED:
                pkttype = packet.get_string()

            handler = self._packet_handlers.get(pkttype)
            if not handler:
                raise SFTPError(FX_OP_UNSUPPORTED,
                                'Unsupported request type: %s' % pkttype)

            return_type = self._return_types.get(pkttype, FXP_STATUS)
            result = yield from handler(self, packet)

            if return_type == FXP_STATUS:
                result = UInt32(FX_OK) + String('') + String('')
            elif return_type in (FXP_HANDLE, FXP_DATA):
                result = String(result)
            elif return_type == FXP_NAME:
                result = (UInt32(len(result)) +
                          b''.join(name.encode() for name in result))
            else:
                if isinstance(result, os.stat_result):
                    result = SFTPAttrs.from_local(result)
                elif isinstance(result, os.statvfs_result):
                    result = SFTPVFSAttrs.from_local(result)

                result = result.encode()
        except PacketDecodeError as exc:
            return_type = FXP_STATUS
            result = (UInt32(FX_BAD_MESSAGE) + String(str(exc)) +
                      String(DEFAULT_LANG))
        except SFTPError as exc:
            return_type = FXP_STATUS
            result = UInt32(exc.code) + String(exc.reason) + String(exc.lang)
        except NotImplementedError as exc:
            name = handler.__name__[9:]
            return_type = FXP_STATUS
            result = (UInt32(FX_OP_UNSUPPORTED) +
                      String('Operation not supported: %s' % name) +
                      String(DEFAULT_LANG))
        except OSError as exc:
            return_type = FXP_STATUS

            if exc.errno in (errno.ENOENT, errno.ENOTDIR):
                code = FX_NO_SUCH_FILE
            elif exc.errno == errno.EACCES:
                code = FX_PERMISSION_DENIED
            else:
                code = FX_FAILURE

            result = (UInt32(code) + String(exc.strerror or str(exc)) +
                      String(DEFAULT_LANG))
        except Exception as exc: # pragma: no cover
            return_type = FXP_STATUS
            result = (UInt32(FX_FAILURE) +
                      String('Uncaught exception: %s' % str(exc)) +
                      String(DEFAULT_LANG))

        self.send_packet(Byte(return_type), UInt32(pktid), result)

    @asyncio.coroutine
    def _process_open(self, packet):
        """Process an incoming SFTP open request"""

        path = packet.get_string()
        pflags = packet.get_uint32()
        attrs = SFTPAttrs.decode(packet)
        packet.check_end()

        result = self._server.open(path, pflags, attrs)

        if asyncio.iscoroutine(result):
            result = yield from result

        handle = self._get_next_handle()
        self._file_handles[handle] = result
        return handle

    @asyncio.coroutine
    def _process_close(self, packet):
        """Process an incoming SFTP close request"""

        handle = packet.get_string()
        packet.check_end()

        file_obj = self._file_handles.pop(handle, None)
        if file_obj:
            result = self._server.close(file_obj)

            if asyncio.iscoroutine(result):
                yield from result

            return

        if self._dir_handles.pop(handle, None) is not None:
            return

        raise SFTPError(FX_FAILURE, 'Invalid file handle')

    @asyncio.coroutine
    def _process_read(self, packet):
        """Process an incoming SFTP read request"""

        handle = packet.get_string()
        offset = packet.get_uint64()
        length = packet.get_uint32()
        packet.check_end()

        file_obj = self._file_handles.get(handle)

        if file_obj:
            result = self._server.read(file_obj, offset, length)

            if asyncio.iscoroutine(result):
                result = yield from result

            if result:
                return result
            else:
                raise SFTPError(FX_EOF, '')
        else:
            raise SFTPError(FX_FAILURE, 'Invalid file handle')

    @asyncio.coroutine
    def _process_write(self, packet):
        """Process an incoming SFTP write request"""

        handle = packet.get_string()
        offset = packet.get_uint64()
        data = packet.get_string()
        packet.check_end()

        file_obj = self._file_handles.get(handle)

        if file_obj:
            result = self._server.write(file_obj, offset, data)

            if asyncio.iscoroutine(result):
                result = yield from result

            return result
        else:
            raise SFTPError(FX_FAILURE, 'Invalid file handle')

    @asyncio.coroutine
    def _process_lstat(self, packet):
        """Process an incoming SFTP lstat request"""

        path = packet.get_string()
        packet.check_end()

        result = self._server.lstat(path)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_fstat(self, packet):
        """Process an incoming SFTP fstat request"""

        handle = packet.get_string()
        packet.check_end()

        file_obj = self._file_handles.get(handle)

        if file_obj:
            result = self._server.fstat(file_obj)

            if asyncio.iscoroutine(result):
                result = yield from result

            return result
        else:
            raise SFTPError(FX_FAILURE, 'Invalid file handle')

    @asyncio.coroutine
    def _process_setstat(self, packet):
        """Process an incoming SFTP setstat request"""

        path = packet.get_string()
        attrs = SFTPAttrs.decode(packet)
        packet.check_end()

        result = self._server.setstat(path, attrs)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_fsetstat(self, packet):
        """Process an incoming SFTP fsetstat request"""

        handle = packet.get_string()
        attrs = SFTPAttrs.decode(packet)
        packet.check_end()

        file_obj = self._file_handles.get(handle)

        if file_obj:
            result = self._server.fsetstat(file_obj, attrs)

            if asyncio.iscoroutine(result):
                result = yield from result

            return result
        else:
            raise SFTPError(FX_FAILURE, 'Invalid file handle')

    @asyncio.coroutine
    def _process_opendir(self, packet):
        """Process an incoming SFTP opendir request"""

        path = packet.get_string()
        packet.check_end()

        listdir_result = self._server.listdir(path)

        if asyncio.iscoroutine(listdir_result):
            listdir_result = yield from listdir_result

        for i, name in enumerate(listdir_result):
            # pylint: disable=no-member

            if isinstance(name, bytes):
                name = SFTPName(name)
                listdir_result[i] = name

                # pylint: disable=attribute-defined-outside-init

                filename = os.path.join(path, name.filename)
                attr_result = self._server.lstat(filename)

                if asyncio.iscoroutine(attr_result):
                    attr_result = yield from attr_result

                if isinstance(attr_result, os.stat_result):
                    attr_result = SFTPAttrs.from_local(attr_result)

                name.attrs = attr_result

            if not name.longname:
                longname_result = self._server.format_longname(name)

                if asyncio.iscoroutine(longname_result):
                    yield from longname_result

        handle = self._get_next_handle()
        self._dir_handles[handle] = listdir_result
        return handle

    @asyncio.coroutine
    def _process_readdir(self, packet):
        """Process an incoming SFTP readdir request"""

        handle = packet.get_string()
        packet.check_end()

        names = self._dir_handles.get(handle)
        if names:
            result = names[:_MAX_READDIR_NAMES]
            del names[:_MAX_READDIR_NAMES]
            return result
        else:
            raise SFTPError(FX_EOF, '')

    @asyncio.coroutine
    def _process_remove(self, packet):
        """Process an incoming SFTP remove request"""

        path = packet.get_string()
        packet.check_end()

        result = self._server.remove(path)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_mkdir(self, packet):
        """Process an incoming SFTP mkdir request"""

        path = packet.get_string()
        attrs = SFTPAttrs.decode(packet)
        packet.check_end()

        result = self._server.mkdir(path, attrs)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_rmdir(self, packet):
        """Process an incoming SFTP rmdir request"""

        path = packet.get_string()
        packet.check_end()

        result = self._server.rmdir(path)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_realpath(self, packet):
        """Process an incoming SFTP realpath request"""

        path = packet.get_string()
        packet.check_end()

        result = self._server.realpath(path)

        if asyncio.iscoroutine(result):
            result = yield from result

        return [SFTPName(result)]

    @asyncio.coroutine
    def _process_stat(self, packet):
        """Process an incoming SFTP stat request"""

        path = packet.get_string()
        packet.check_end()

        result = self._server.stat(path)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_rename(self, packet):
        """Process an incoming SFTP rename request"""

        oldpath = packet.get_string()
        newpath = packet.get_string()
        packet.check_end()

        result = self._server.rename(oldpath, newpath)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_readlink(self, packet):
        """Process an incoming SFTP readlink request"""

        path = packet.get_string()
        packet.check_end()

        result = self._server.readlink(path)

        if asyncio.iscoroutine(result):
            result = yield from result

        return [SFTPName(result)]

    @asyncio.coroutine
    def _process_symlink(self, packet):
        """Process an incoming SFTP symlink request"""

        if self._nonstandard_symlink:
            oldpath = packet.get_string()
            newpath = packet.get_string()
        else:
            newpath = packet.get_string()
            oldpath = packet.get_string()

        packet.check_end()

        result = self._server.symlink(oldpath, newpath)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_posix_rename(self, packet):
        """Process an incoming SFTP POSIX rename request"""

        oldpath = packet.get_string()
        newpath = packet.get_string()
        packet.check_end()

        result = self._server.posix_rename(oldpath, newpath)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_statvfs(self, packet):
        """Process an incoming SFTP statvfs request"""

        path = packet.get_string()
        packet.check_end()

        result = self._server.statvfs(path)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_fstatvfs(self, packet):
        """Process an incoming SFTP fstatvfs request"""

        handle = packet.get_string()
        packet.check_end()

        file_obj = self._file_handles.get(handle)

        if file_obj:
            result = self._server.fstatvfs(file_obj)

            if asyncio.iscoroutine(result):
                result = yield from result

            return result
        else:
            raise SFTPError(FX_FAILURE, 'Invalid file handle')

    @asyncio.coroutine
    def _process_link(self, packet):
        """Process an incoming SFTP hard link request"""

        oldpath = packet.get_string()
        newpath = packet.get_string()
        packet.check_end()

        result = self._server.link(oldpath, newpath)

        if asyncio.iscoroutine(result):
            result = yield from result

        return result

    @asyncio.coroutine
    def _process_fsync(self, packet):
        """Process an incoming SFTP fsync request"""

        handle = packet.get_string()
        packet.check_end()

        file_obj = self._file_handles.get(handle)

        if file_obj:
            result = self._server.fsync(file_obj)

            if asyncio.iscoroutine(result):
                result = yield from result

            return result
        else:
            raise SFTPError(FX_FAILURE, 'Invalid file handle')

    _packet_handlers = {
        FXP_OPEN:                     _process_open,
        FXP_CLOSE:                    _process_close,
        FXP_READ:                     _process_read,
        FXP_WRITE:                    _process_write,
        FXP_LSTAT:                    _process_lstat,
        FXP_FSTAT:                    _process_fstat,
        FXP_SETSTAT:                  _process_setstat,
        FXP_FSETSTAT:                 _process_fsetstat,
        FXP_OPENDIR:                  _process_opendir,
        FXP_READDIR:                  _process_readdir,
        FXP_REMOVE:                   _process_remove,
        FXP_MKDIR:                    _process_mkdir,
        FXP_RMDIR:                    _process_rmdir,
        FXP_REALPATH:                 _process_realpath,
        FXP_STAT:                     _process_stat,
        FXP_RENAME:                   _process_rename,
        FXP_READLINK:                 _process_readlink,
        FXP_SYMLINK:                  _process_symlink,
        b'posix-rename@openssh.com':  _process_posix_rename,
        b'statvfs@openssh.com':       _process_statvfs,
        b'fstatvfs@openssh.com':      _process_fstatvfs,
        b'hardlink@openssh.com':      _process_link,
        b'fsync@openssh.com':         _process_fsync
    }

    @asyncio.coroutine
    def run(self):
        """Run an SFTP server"""

        try:
            packet = yield from self.recv_packet()

            pkttype = packet.get_byte()
            version = packet.get_uint32()
        except PacketDecodeError as exc:
            yield from self._cleanup(SFTPError(FX_BAD_MESSAGE, str(exc)))
            return
        except SFTPError as exc:
            yield from self._cleanup(exc)
            return

        if pkttype != FXP_INIT:
            yield from self._cleanup(SFTPError(FX_BAD_MESSAGE,
                                               'Expected init message'))
            return

        version = min(version, _SFTP_VERSION)
        extensions = (String(name) + String(data)
                      for name, data in self._extensions)

        try:
            self.send_packet(Byte(FXP_VERSION), UInt32(version), *extensions)
        except SFTPError as exc:
            yield from self._cleanup(exc)
            return

        if version == 3:
            # Check if the server has a buggy SYMLINK implementation

            client_version = self._reader.get_extra_info('client_version', '')
            if any(name in client_version
                   for name in self._nonstandard_symlink_impls):
                self._nonstandard_symlink = True

        yield from self.recv_packets()


class SFTPServer:
    """SFTP server

       Applications should subclass this when implementing an SFTP
       server. The methods listed below should be implemented to
       provide the desired application behavior.

           .. note:: Any method can optionally be defined as a
                     coroutine if that method needs to perform
                     blocking opertions to determine its result.

       The ``conn`` object provided here refers to the
       :class:`SSHServerConnection` instance this SFTP server is
       associated with. It can be queried to determine which user
       the client authenticated as or to request key and certificate
       options or permissions which should be applied to this session.

       If the ``chroot`` argument is specified when this object is
       created, the default :meth:`map_path` and :meth:`reverse_map_path`
       methods will enforce a virtual root directory starting in that
       location, limiting access to only files within that directory
       tree. This will also affect path names returned by the
       :meth:`realpath` and :meth:`readlink` methods.

    """

    # The default implementation of a number of these methods don't need self
    # pylint: disable=no-self-use

    def __init__(self, conn, chroot=None):
        # pylint: disable=unused-argument

        if chroot:
            self._chroot = _from_local_path(os.path.realpath(chroot))
        else:
            self._chroot = None

    def format_user(self, uid):
        """Return the user name associated with a uid

           This method returns a user name string to insert into
           the ``longname`` field of an :class:`SFTPName` object.

           By default, it calls the Python :func:`pwd.getpwuid`
           function if it is available, or returns the numeric
           uid as a string if not. If there is no uid, it returns
           an empty string.

           :param uid:
               The uid value to look up
           :type uid: int or ``None``

           :returns: The formatted user name string

        """

        if uid is not None:
            try:
                import pwd
                user = pwd.getpwuid(uid).pw_name
            except (ImportError, KeyError):
                user = str(uid)
        else:
            user = ''

        return user


    def format_group(self, gid):
        """Return the group name associated with a gid

           This method returns a group name string to insert into
           the ``longname`` field of an :class:`SFTPName` object.

           By default, it calls the Python :func:`grp.getgrgid`
           function if it is available, or returns the numeric
           gid as a string if not. If there is no gid, it returns
           an empty string.

           :param gid:
               The gid value to look up
           :type gid: int or ``None``

           :returns: The formatted group name string

        """

        if gid is not None:
            try:
                import grp
                group = grp.getgrgid(gid).gr_name
            except (ImportError, KeyError):
                group = str(gid)
        else:
            group = ''

        return group


    def format_longname(self, name):
        """Format the long name associated with an SFTP name

           This method fills in the ``longname`` field of a
           :class:`SFTPName` object. By default, it generates
           something similar to UNIX "ls -l" output. The ``filename``
           and ``attrs`` fields of the :class:`SFTPName` should
           already be filled in before this method is called.

           :param name:
               The :class:`SFTPName` instance to format the long name for
           :type name: :class:`SFTPName`

        """

        if name.attrs.permissions is not None:
            mode = stat.filemode(name.attrs.permissions)
        else:
            mode = ''

        nlink = str(name.attrs.nlink) if name.attrs.nlink else ''

        user = self.format_user(name.attrs.uid)
        group = self.format_group(name.attrs.gid)

        size = str(name.attrs.size) if name.attrs.size is not None else ''

        if name.attrs.mtime is not None:
            now = time.time()
            mtime = time.localtime(name.attrs.mtime)
            modtime = time.strftime('%b ', mtime)

            try:
                modtime += time.strftime('%e', mtime)
            except ValueError:
                modtime += time.strftime('%d', mtime)

            if now - 365*24*60*60/2 < name.attrs.mtime <= now:
                modtime += time.strftime(' %H:%M', mtime)
            else:
                modtime += time.strftime('  %Y', mtime)
        else:
            modtime = ''

        detail = '{:10s} {:>4s} {:8s} {:8s} {:>8s} {:12s} '.format(
            mode, nlink, user, group, size, modtime)

        name.longname = detail.encode('utf-8') + name.filename

    def map_path(self, path):
        """Map the path requested by the client to a local path

           This method can be overridden to provide a custom mapping
           from path names requested by the client to paths in the local
           filesystem. By default, it will enforce a virtual "chroot"
           if one was specified when this server was created. Otherwise,
           path names are left unchanged, with relative paths being
           interpreted based on the working directory of the currently
           running process.

           :param bytes path:
               The path name to map

           :returns: bytes containing the local path name to operate on

        """

        if self._chroot:
            normpath = posixpath.normpath(os.path.join(b'/', path))
            return posixpath.join(self._chroot, normpath[1:])
        else:
            return path

    def reverse_map_path(self, path):
        """Reverse map a local path into the path reported to the client

           This method can be overridden to provide a custom reverse
           mapping for the mapping provided by :meth:`map_path`. By
           default, it hides the portion of the local path associated
           with the virtual "chroot" if one was specified.

           :param bytes path:
               The local path name to reverse map

           :returns: bytes containing the path name to report to the client

        """

        if self._chroot:
            if path == self._chroot:
                return b'/'
            elif path.startswith(self._chroot + b'/'):
                return path[len(self._chroot):]
            else:
                raise SFTPError(FX_NO_SUCH_FILE, 'File not found')
        else:
            return path

    def open(self, path, pflags, attrs):
        """Open a file to serve to a remote client

           This method returns a file object which can be used to read
           and write data and get and set file attributes.

           The possible open mode flags and their meanings are:

             ========== ======================================================
             Mode       Description
             ========== ======================================================
             FXF_READ   Open the file for reading. If neither FXF_READ nor
                        FXF_WRITE are set, this is the default.
             FXF_WRITE  Open the file for writing. If both this and FXF_READ
                        are set, open the file for both reading and writing.
             FXF_APPEND Force writes to append data to the end of the file
                        regardless of seek position.
             FXF_CREAT  Create the file if it doesn't exist. Without this,
                        attempts to open a non-existent file will fail.
             FXF_TRUNC  Truncate the file to zero length if it already exists.
             FXF_EXCL   Return an error when trying to open a file which
                        already exists.
             ========== ======================================================

           The attrs argument is used to set initial attributes of the
           file if it needs to be created. Otherwise, this argument is
           ignored.

           :param bytes path:
               The name of the file to open
           :param int pflags:
               The access mode to use for the file (see above)
           :param attrs:
               File attributes to use if the file needs to be created
           :type attrs: :class:`SFTPAttrs`

           :returns: A file object to use to access the file

           :raises: :exc:`SFTPError` to return an error to the client

        """

        if pflags & FXF_EXCL:
            mode = 'xb'
        elif pflags & FXF_APPEND:
            mode = 'ab'
        elif pflags & FXF_WRITE and not pflags & FXF_READ:
            mode = 'wb'
        else:
            mode = 'rb'

        if pflags & FXF_READ and pflags & FXF_WRITE:
            mode += '+'
            flags = os.O_RDWR
        elif pflags & FXF_WRITE:
            flags = os.O_WRONLY
        else:
            flags = os.O_RDONLY

        if pflags & FXF_APPEND:
            flags |= os.O_APPEND

        if pflags & FXF_CREAT:
            flags |= os.O_CREAT

        if pflags & FXF_TRUNC:
            flags |= os.O_TRUNC

        if pflags & FXF_EXCL:
            flags |= os.O_EXCL

        flags |= getattr(os, 'O_BINARY', 0)

        perms = 0o666 if attrs.permissions is None else attrs.permissions
        return open(_to_local_path(self.map_path(path)), mode, buffering=0,
                    opener=lambda path, _: os.open(path, flags, perms))

    def close(self, file_obj):
        """Close an open file or directory

           :param file file_obj:
               The file or directory object to close

           :raises: :exc:`SFTPError` to return an error to the client

        """

        file_obj.close()

    def read(self, file_obj, offset, size):
        """Read data from an open file

           :param file file_obj:
               The file to read from
           :param int offset:
               The offset from the beginning of the file to begin reading
           :param int size:
               The number of bytes to read

           :returns: bytes read from the file

           :raises: :exc:`SFTPError` to return an error to the client

        """

        file_obj.seek(offset)
        return file_obj.read(size)

    def write(self, file_obj, offset, data):
        """Write data to an open file

           :param file file_obj:
               The file to write to
           :param int offset:
               The offset from the beginning of the file to begin writing
           :param bytes data:
               The data to write to the file

           :returns: number of bytes written

           :raises: :exc:`SFTPError` to return an error to the client

        """

        file_obj.seek(offset)
        return file_obj.write(data)

    def lstat(self, path):
        """Get attributes of a file, directory, or symlink

           This method queries the attributes of a file, directory,
           or symlink. Unlike :meth:`stat`, this method should
           return the attributes of a symlink itself rather than
           the target of that link.

           :param bytes path:
               The path of the file, directory, or link to get attributes for

           :returns: An :class:`SFTPAttrs` or an os.stat_result containing
                     the file attributes

           :raises: :exc:`SFTPError` to return an error to the client

        """

        return os.lstat(_to_local_path(self.map_path(path)))

    def fstat(self, file_obj):
        """Get attributes of an open file

           :param file file_obj:
               The file to get attributes for

           :returns: An :class:`SFTPAttrs` or an os.stat_result containing
                     the file attributes

           :raises: :exc:`SFTPError` to return an error to the client

        """

        file_obj.flush()
        return os.fstat(file_obj.fileno())

    def setstat(self, path, attrs):
        """Set attributes of a file or directory

           This method sets attributes of a file or directory. If
           the path provided is a symbolic link, the attributes
           should be set on the target of the link. A subset of the
           fields in ``attrs`` can be initialized and only those
           attributes should be changed.

           :param bytes path:
               The path of the remote file or directory to set attributes for
           :param attrs:
               File attributes to set
           :type attrs: :class:`SFTPAttrs`

           :raises: :exc:`SFTPError` to return an error to the client

        """

        _setstat(_to_local_path(self.map_path(path)), attrs)

    def fsetstat(self, file_obj, attrs):
        """Set attributes of an open file

           :param attrs:
               File attributes to set on the file
           :type attrs: :class:`SFTPAttrs`

           :raises: :exc:`SFTPError` to return an error to the client

        """

        file_obj.flush()

        if sys.platform == 'win32': # pragma: no cover
            _setstat(file_obj.name, attrs)
        else:
            _setstat(file_obj.fileno(), attrs)

    def listdir(self, path):
        """List the contents of a directory

           :param bytes path:
               The path of the directory to open

           :returns: A list of names of files in the directory

           :raises: :exc:`SFTPError` to return an error to the client

        """

        files = os.listdir(_to_local_path(self.map_path(path)))

        if sys.platform == 'win32': # pragma: no cover
            files = [os.fsencode(f) for f in files]

        return [b'.', b'..'] + files

    def remove(self, path):
        """Remove a file or symbolic link

           :param bytes path:
               The path of the file or link to remove

           :raises: :exc:`SFTPError` to return an error to the client

        """

        os.remove(_to_local_path(self.map_path(path)))

    def mkdir(self, path, attrs):
        """Create a directory with the specified attributes

           :param bytes path:
               The path of where the new directory should be created
           :param attrs:
               The file attributes to use when creating the directory
           :type attrs: :class:`SFTPAttrs`

           :raises: :exc:`SFTPError` to return an error to the client

        """

        mode = 0o777 if attrs.permissions is None else attrs.permissions
        os.mkdir(_to_local_path(self.map_path(path)), mode)

    def rmdir(self, path):
        """Remove a directory

           :param bytes path:
               The path of the directory to remove

           :raises: :exc:`SFTPError` to return an error to the client

        """

        os.rmdir(_to_local_path(self.map_path(path)))

    def realpath(self, path):
        """Return the canonical version of a path

           :param bytes path:
               The path of the directory to canonicalize

           :returns: bytes containing the canonical path

           :raises: :exc:`SFTPError` to return an error to the client

        """

        path = os.path.realpath(_to_local_path(self.map_path(path)))
        return self.reverse_map_path(_from_local_path(path))

    def stat(self, path):
        """Get attributes of a file or directory, following symlinks

           This method queries the attributes of a file or directory.
           If the path provided is a symbolic link, the returned
           attributes should correspond to the target of the link.

           :param bytes path:
               The path of the remote file or directory to get attributes for

           :returns: An :class:`SFTPAttrs` or an os.stat_result containing
                     the file attributes

           :raises: :exc:`SFTPError` to return an error to the client

        """

        return os.stat(_to_local_path(self.map_path(path)))

    def rename(self, oldpath, newpath):
        """Rename a file, directory, or link

           This method renames a file, directory, or link.

           .. note:: This is a request for the standard SFTP version
                     of rename which will not overwrite the new path
                     if it already exists. The :meth:`posix_rename`
                     method will be called if the client requests the
                     POSIX behavior where an existing instance of the
                     new path is removed before the rename.

           :param bytes oldpath:
               The path of the file, directory, or link to rename
           :param bytes newpath:
               The new name for this file, directory, or link

           :raises: :exc:`SFTPError` to return an error to the client

        """

        oldpath = _to_local_path(self.map_path(oldpath))
        newpath = _to_local_path(self.map_path(newpath))

        if os.path.exists(newpath):
            raise SFTPError(FX_FAILURE, 'File already exists')

        os.rename(oldpath, newpath)

    def readlink(self, path):
        """Return the target of a symbolic link

           :param bytes path:
               The path of the symbolic link to follow

           :returns: bytes containing the target path of the link

           :raises: :exc:`SFTPError` to return an error to the client

        """

        path = os.readlink(_to_local_path(self.map_path(path)))
        return self.reverse_map_path(_from_local_path(path))

    def symlink(self, oldpath, newpath):
        """Create a symbolic link

           :param bytes oldpath:
               The path the link should point to
           :param bytes newpath:
               The path of where to create the symbolic link

           :raises: :exc:`SFTPError` to return an error to the client

        """

        if posixpath.isabs(oldpath):
            oldpath = self.map_path(oldpath)
        else:
            newdir = posixpath.dirname(newpath)
            abspath1 = self.map_path(posixpath.join(newdir, oldpath))

            mapped_newdir = self.map_path(newdir)
            abspath2 = os.path.join(mapped_newdir, oldpath)

            # Make sure the symlink doesn't point outside the chroot
            if os.path.realpath(abspath1) != os.path.realpath(abspath2):
                oldpath = os.path.relpath(abspath1, start=mapped_newdir)

        newpath = self.map_path(newpath)

        os.symlink(_to_local_path(oldpath), _to_local_path(newpath))

    def posix_rename(self, oldpath, newpath):
        """Rename a file, directory, or link with POSIX semantics

           This method renames a file, directory, or link, removing
           the prior instance of new path if it previously existed.

           :param bytes oldpath:
               The path of the file, directory, or link to rename
           :param bytes newpath:
               The new name for this file, directory, or link

           :raises: :exc:`SFTPError` to return an error to the client

        """

        oldpath = _to_local_path(self.map_path(oldpath))
        newpath = _to_local_path(self.map_path(newpath))

        os.replace(oldpath, newpath)

    def statvfs(self, path):
        """Get attributes of the file system containing a file

           :param bytes path:
               The path of the file system to get attributes for

           :returns: An :class:`SFTPVFSAttrs` or an os.statvfs_result
                     containing the file system attributes

           :raises: :exc:`SFTPError` to return an error to the client

        """

        try:
            return os.statvfs(_to_local_path(self.map_path(path)))
        except AttributeError: # pragma: no cover
            raise SFTPError(FX_OP_UNSUPPORTED, 'statvfs not supported')

    def fstatvfs(self, file_obj):
        """Return attributes of the file system containing an open file

           :param file file_obj:
               The open file to get file system attributes for

           :returns: An :class:`SFTPVFSAttrs` or an os.statvfs_result
                     containing the file system attributes

           :raises: :exc:`SFTPError` to return an error to the client

        """

        try:
            return os.statvfs(file_obj.fileno())
        except AttributeError: # pragma: no cover
            raise SFTPError(FX_OP_UNSUPPORTED, 'fstatvfs not supported')

    def link(self, oldpath, newpath):
        """Create a hard link

           :param bytes oldpath:
               The path of the file the hard link should point to
           :param bytes newpath:
               The path of where to create the hard link

           :raises: :exc:`SFTPError` to return an error to the client

        """

        oldpath = _to_local_path(self.map_path(oldpath))
        newpath = _to_local_path(self.map_path(newpath))

        os.link(oldpath, newpath)

    def fsync(self, file_obj):
        """Force file data to be written to disk

           :param file file_obj:
               The open file containing the data to flush to disk

           :raises: :exc:`SFTPError` to return an error to the client

        """

        os.fsync(file_obj.fileno())

    def exit(self):
        """Shut down this SFTP server"""

        pass


class SFTPServerFile:
    """A wrapper around SFTPServer used to access files it manages"""

    def __init__(self, server):
        self._server = server
        self._file_obj = None

    @asyncio.coroutine
    def stat(self, path):
        """Get attributes of a file"""

        attrs = self._server.stat(path)

        if asyncio.iscoroutine(attrs):
            attrs = yield from attrs

        if isinstance(attrs, os.stat_result):
            attrs = SFTPAttrs.from_local(attrs)

        return attrs

    @asyncio.coroutine
    def setstat(self, path, attrs):
        """Set attributes of a file or directory"""

        result = self._server.setstat(path, attrs)

        if asyncio.iscoroutine(result):
            attrs = yield from result

    @asyncio.coroutine
    def _mode(self, path):
        """Return the file mode of a path, or 0 if it can't be accessed"""

        try:
            return (yield from self.stat(path)).permissions
        except OSError as exc:
            if exc.errno in (errno.ENOENT, errno.EACCES):
                return 0
            else:
                raise
        except SFTPError as exc:
            if exc.code in (FX_NO_SUCH_FILE, FX_PERMISSION_DENIED):
                return 0
            else:
                raise

    @asyncio.coroutine
    def exists(self, path):
        """Return if a path exists"""

        return (yield from self._mode(path)) != 0

    @asyncio.coroutine
    def isdir(self, path):
        """Return if the path refers to a directory"""

        return stat.S_ISDIR((yield from self._mode(path)))

    @asyncio.coroutine
    def mkdir(self, path):
        """Create a directory"""

        result = self._server.mkdir(path, SFTPAttrs())

        if asyncio.iscoroutine(result):
            yield from result

    @asyncio.coroutine
    def listdir(self, path):
        """List the contents of a directory"""

        files = self._server.listdir(path)

        if asyncio.iscoroutine(files):
            files = yield from files

        return files

    @asyncio.coroutine
    def open(self, path, mode='rb'):
        """Open a file"""

        pflags, _ = _mode_to_pflags(mode)
        file_obj = self._server.open(path, pflags, SFTPAttrs())

        if asyncio.iscoroutine(file_obj):
            file_obj = yield from file_obj

        self._file_obj = file_obj
        return self

    @asyncio.coroutine
    def read(self, size, offset):
        """Read bytes from the file"""

        data = self._server.read(self._file_obj, offset, size)

        if asyncio.iscoroutine(data):
            data = yield from data

        return data

    @asyncio.coroutine
    def write(self, data, offset):
        """Write bytes to the file"""

        size = self._server.write(self._file_obj, offset, data)

        if asyncio.iscoroutine(size):
            size = yield from size

        return size

    @asyncio.coroutine
    def close(self):
        """Close a file managed by the associated SFTPServer"""

        result = self._server.close(self._file_obj)

        if asyncio.iscoroutine(result):
            yield from result


@asyncio.coroutine
def start_sftp_client(conn, loop, reader, writer, path_encoding, path_errors):
    """Start an SFTP client"""

    handler = SFTPClientHandler(loop, reader, writer)

    yield from handler.start()

    conn.create_task(handler.recv_packets())

    return SFTPClient(loop, handler, path_encoding, path_errors)


@asyncio.coroutine
def run_sftp_server(sftp_server, reader, writer):
    """Return a handler for an SFTP server session"""

    handler = SFTPServerHandler(sftp_server, reader, writer)

    yield from handler.run()