This file is indexed.

/usr/share/pyshared/impacket/smb.py is in python-impacket 0.9.10-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
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
# Copyright (c) 2003-2012 CORE Security Technologies)
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# $Id: smb.py 738 2013-04-09 18:40:15Z bethus@gmail.com $
#
# Copyright (C) 2001 Michael Teo <michaelteo@bigfoot.com>
# smb.py - SMB/CIFS library
#
# This software is provided 'as-is', without any express or implied warranty. 
# In no event will the author be held liable for any damages arising from the 
# use of this software.
#
# Permission is granted to anyone to use this software for any purpose, 
# including commercial applications, and to alter it and redistribute it 
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not 
#    claim that you wrote the original software. If you use this software 
#    in a product, an acknowledgment in the product documentation would be
#    appreciated but is not required.
#
# 2. Altered source versions must be plainly marked as such, and must not be 
#    misrepresented as being the original software.
#
# 3. This notice cannot be removed or altered from any source distribution.
#
# Altered source done by Alberto Solino

# Todo:
# [ ] Try [SMB]transport fragmentation using Transact requests
# [ ] Try other methods of doing write (write_raw, transact2, write, write_and_unlock, write_and_close, write_mpx)
# [-] Try replacements for SMB_COM_NT_CREATE_ANDX  (CREATE, T_TRANSACT_CREATE, OPEN_ANDX works
# [x] Fix forceWriteAndx, which needs to send a RecvRequest, because recv() will not send it
# [x] Fix Recv() when using RecvAndx and the answer comes splet in several packets
# [ ] Try [SMB]transport fragmentation with overlaping segments
# [ ] Try [SMB]transport fragmentation with out of order segments
# [x] Do chained AndX requests
# [ ] Transform the rest of the calls to structure
# [ ] Implement TRANS/TRANS2 reassembly for list_path 

import os, sys, socket, string, re, select, errno
from impacket import nmb, ntlm
from impacket.dcerpc import samr
from impacket.structure import Structure
from impacket.spnego import *
import types
from binascii import a2b_hex
import random
import datetime, time
from random import randint
from struct import *
import struct
from contextlib import contextmanager

# For signing
import hashlib

unicode_support = 0
unicode_convert = 1

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

# Dialect for SMB1
SMB_DIALECT = 'NT LM 0.12'

# Shared Device Type
SHARED_DISK                      = 0x00
SHARED_DISK_HIDDEN               = 0x80000000
SHARED_PRINT_QUEUE               = 0x01
SHARED_DEVICE                    = 0x02
SHARED_IPC                       = 0x03

# Extended attributes mask
ATTR_ARCHIVE                     = 0x020
ATTR_COMPRESSED                  = 0x800
ATTR_NORMAL                      = 0x080
ATTR_HIDDEN                      = 0x002
ATTR_READONLY                    = 0x001
ATTR_TEMPORARY                   = 0x100
ATTR_DIRECTORY                   = 0x010
ATTR_SYSTEM                      = 0x004

# Service Type
SERVICE_DISK                     = 'A:'
SERVICE_PRINTER                  = 'LPT1:'
SERVICE_IPC                      = 'IPC'
SERVICE_COMM                     = 'COMM'
SERVICE_ANY                      = '?????'

# Server Type (Can be used to mask with SMBMachine.get_type() or SMBDomain.get_type())
SV_TYPE_WORKSTATION              = 0x00000001
SV_TYPE_SERVER                   = 0x00000002
SV_TYPE_SQLSERVER                = 0x00000004
SV_TYPE_DOMAIN_CTRL              = 0x00000008
SV_TYPE_DOMAIN_BAKCTRL           = 0x00000010
SV_TYPE_TIME_SOURCE              = 0x00000020
SV_TYPE_AFP                      = 0x00000040
SV_TYPE_NOVELL                   = 0x00000080
SV_TYPE_DOMAIN_MEMBER            = 0x00000100
SV_TYPE_PRINTQ_SERVER            = 0x00000200
SV_TYPE_DIALIN_SERVER            = 0x00000400
SV_TYPE_XENIX_SERVER             = 0x00000800
SV_TYPE_NT                       = 0x00001000
SV_TYPE_WFW                      = 0x00002000
SV_TYPE_SERVER_NT                = 0x00004000
SV_TYPE_POTENTIAL_BROWSER        = 0x00010000
SV_TYPE_BACKUP_BROWSER           = 0x00020000
SV_TYPE_MASTER_BROWSER           = 0x00040000
SV_TYPE_DOMAIN_MASTER            = 0x00080000
SV_TYPE_LOCAL_LIST_ONLY          = 0x40000000
SV_TYPE_DOMAIN_ENUM              = 0x80000000

# Options values for SMB.stor_file and SMB.retr_file
SMB_O_CREAT                      = 0x10   # Create the file if file does not exists. Otherwise, operation fails.
SMB_O_EXCL                       = 0x00   # When used with SMB_O_CREAT, operation fails if file exists. Cannot be used with SMB_O_OPEN.
SMB_O_OPEN                       = 0x01   # Open the file if the file exists
SMB_O_TRUNC                      = 0x02   # Truncate the file if the file exists

# Share Access Mode
SMB_SHARE_COMPAT                 = 0x00
SMB_SHARE_DENY_EXCL              = 0x10
SMB_SHARE_DENY_WRITE             = 0x20
SMB_SHARE_DENY_READEXEC          = 0x30
SMB_SHARE_DENY_NONE              = 0x40
SMB_ACCESS_READ                  = 0x00
SMB_ACCESS_WRITE                 = 0x01
SMB_ACCESS_READWRITE             = 0x02
SMB_ACCESS_EXEC                  = 0x03

TRANS_DISCONNECT_TID             = 1
TRANS_NO_RESPONSE                = 2

STATUS_SUCCESS                   = 0x00000000
STATUS_LOGON_FAILURE             = 0xC000006D
STATUS_LOGON_TYPE_NOT_GRANTED    = 0xC000015B
MAX_TFRAG_SIZE                   = 5840
EVASION_NONE                     = 0
EVASION_LOW                      = 1
EVASION_HIGH                     = 2
EVASION_MAX                      = 3
RPC_X_BAD_STUB_DATA              = 0x6F7

# SMB_FILE_ATTRIBUTES

SMB_FILE_ATTRIBUTE_NORMAL        = 0x0000
SMB_FILE_ATTRIBUTE_READONLY      = 0x0001
SMB_FILE_ATTRIBUTE_HIDDEN        = 0x0002
SMB_FILE_ATTRIBUTE_SYSTEM        = 0x0004
SMB_FILE_ATTRIBUTE_VOLUME        = 0x0008
SMB_FILE_ATTRIBUTE_DIRECORY      = 0x0010
SMB_FILE_ATTRIBUTE_ARCHIVE       = 0x0020
SMB_SEARCH_ATTRIBUTE_READONLY    = 0x0100
SMB_SEARCH_ATTRIBUTE_HIDDEN      = 0x0200
SMB_SEARCH_ATTRIBUTE_SYSTEM      = 0x0400
SMB_SEARCH_ATTRIBUTE_DIRECTORY   = 0x1000
SMB_SEARCH_ATTRIBUTE_ARCHIVE     = 0x2000

# Session SetupAndX Action flags
SMB_SETUP_GUEST                  = 0x01
SMB_SETUP_USE_LANMAN_KEY         = 0x02

# QUERY_INFORMATION levels
SMB_INFO_ALLOCATION              = 0x0001
SMB_INFO_VOLUME                  = 0x0002
SMB_QUERY_FS_VOLUME_INFO         = 0x0102
SMB_QUERY_FS_SIZE_INFO           = 0x0103
SMB_QUERY_FILE_EA_INFO           = 0x0103
SMB_QUERY_FS_DEVICE_INFO         = 0x0104
SMB_QUERY_FS_ATTRIBUTE_INFO      = 0x0105
SMB_QUERY_FILE_BASIC_INFO        = 0x0101
SMB_QUERY_FILE_STANDARD_INFO     = 0x0102
SMB_QUERY_FILE_ALL_INFO          = 0x0107

# SET_INFORMATION levels
SMB_SET_FILE_DISPOSITION_INFO    = 0x0102
SMB_SET_FILE_BASIC_INFO          = 0x0101
SMB_SET_FILE_END_OF_FILE_INFO    = 0x0104


# File System Attributes
FILE_CASE_SENSITIVE_SEARCH       = 0x00000001
FILE_CASE_PRESERVED_NAMES        = 0x00000002
FILE_UNICODE_ON_DISK             = 0x00000004
FILE_PERSISTENT_ACLS             = 0x00000008
FILE_FILE_COMPRESSION            = 0x00000010
FILE_VOLUME_IS_COMPRESSED        = 0x00008000

# FIND_FIRST2 flags and levels
SMB_FIND_CLOSE_AFTER_REQUEST     = 0x0001
SMB_FIND_CLOSE_AT_EOS            = 0x0002
SMB_FIND_RETURN_RESUME_KEYS      = 0x0004
SMB_FIND_CONTINUE_FROM_LAST      = 0x0008
SMB_FIND_WITH_BACKUP_INTENT      = 0x0010

FILE_DIRECTORY_FILE              = 0x00000001
FILE_DELETE_ON_CLOSE             = 0x00001000
FILE_NON_DIRECTORY_FILE          = 0x00000040

SMB_FIND_INFO_STANDARD           = 0x0001
SMB_FIND_FILE_DIRECTORY_INFO     = 0x0101
SMB_FIND_FILE_FULL_DIRECTORY_INFO= 0x0102
SMB_FIND_FILE_NAMES_INFO         = 0x0103
SMB_FIND_FILE_BOTH_DIRECTORY_INFO= 0x0104
SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO = 0x105
SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO = 0x106


# DesiredAccess flags
FILE_READ_DATA                   = 0x00000001
FILE_WRITE_DATA                  = 0x00000002
FILE_APPEND_DATA                 = 0x00000004
FILE_EXECUTE                     = 0x00000020
MAXIMUM_ALLOWED                  = 0200000000
GENERIC_ALL                      = 0x10000000
GENERIC_EXECUTE                  = 0x20000000
GENERIC_WRITE                    = 0x40000000
GENERIC_READ                     = 0x80000000

# ShareAccess flags
FILE_SHARE_NONE                  = 0x00000000
FILE_SHARE_READ                  = 0x00000001
FILE_SHARE_WRITE                 = 0x00000002
FILE_SHARE_DELETE                = 0x00000004

# CreateDisposition flags
FILE_SUPERSEDE                  = 0x00000000
FILE_OPEN                       = 0x00000001
FILE_CREATE                     = 0x00000002
FILE_OPEN_IF                    = 0x00000003
FILE_OVERWRITE                  = 0x00000004
FILE_OVERWRITE_IF               = 0x00000005

def strerror(errclass, errcode):
    if errclass == 0x01:
        return 'OS error', ERRDOS.get(errcode, 'Unknown error')
    elif errclass == 0x02:
        return 'Server error', ERRSRV.get(errcode, 'Unknown error')
    elif errclass == 0x03:
        return 'Hardware error', ERRHRD.get(errcode, 'Unknown error')
    # This is not a standard error class for SMB
    #elif errclass == 0x80:
    #    return 'Browse error', ERRBROWSE.get(errcode, 'Unknown error')
    elif errclass == 0xff:
        return 'Bad command', 'Bad command. Please file bug report'
    else:
        return 'Unknown error', 'Unknown error'

    

# Raised when an error has occured during a session
class SessionError(Exception):
    # SMB X/Open error codes for the ERRDOS error class
    ERRsuccess                           = 0
    ERRbadfunc                           = 1
    ERRbadfile                           = 2
    ERRbadpath                           = 3
    ERRnofids                            = 4
    ERRnoaccess                          = 5
    ERRbadfid                            = 6
    ERRbadmcb                            = 7
    ERRnomem                             = 8
    ERRbadmem                            = 9
    ERRbadenv                            = 10
    ERRbadaccess                         = 12
    ERRbaddata                           = 13
    ERRres                               = 14
    ERRbaddrive                          = 15
    ERRremcd                             = 16
    ERRdiffdevice                        = 17
    ERRnofiles                           = 18
    ERRgeneral                           = 31
    ERRbadshare                          = 32
    ERRlock                              = 33
    ERRunsup                             = 50
    ERRnetnamedel                        = 64
    ERRnosuchshare                       = 67
    ERRfilexists                         = 80
    ERRinvalidparam                      = 87
    ERRcannotopen                        = 110
    ERRinsufficientbuffer                = 122
    ERRinvalidname                       = 123
    ERRunknownlevel                      = 124
    ERRnotlocked                         = 158
    ERRrename                            = 183
    ERRbadpipe                           = 230
    ERRpipebusy                          = 231
    ERRpipeclosing                       = 232
    ERRnotconnected                      = 233
    ERRmoredata                          = 234
    ERRnomoreitems                       = 259
    ERRbaddirectory                      = 267
    ERReasnotsupported                   = 282
    ERRlogonfailure                      = 1326
    ERRbuftoosmall                       = 2123
    ERRunknownipc                        = 2142
    ERRnosuchprintjob                    = 2151
    ERRinvgroup                          = 2455

    # here's a special one from observing NT
    ERRnoipc                             = 66

    # These errors seem to be only returned by the NT printer driver system
    ERRdriveralreadyinstalled            = 1795
    ERRunknownprinterport                = 1796
    ERRunknownprinterdriver              = 1797
    ERRunknownprintprocessor             = 1798
    ERRinvalidseparatorfile              = 1799
    ERRinvalidjobpriority                = 1800
    ERRinvalidprintername                = 1801
    ERRprinteralreadyexists              = 1802
    ERRinvalidprintercommand             = 1803
    ERRinvaliddatatype                   = 1804
    ERRinvalidenvironment                = 1805

    ERRunknownprintmonitor               = 3000
    ERRprinterdriverinuse                = 3001
    ERRspoolfilenotfound                 = 3002
    ERRnostartdoc                        = 3003
    ERRnoaddjob                          = 3004
    ERRprintprocessoralreadyinstalled    = 3005
    ERRprintmonitoralreadyinstalled      = 3006
    ERRinvalidprintmonitor               = 3007
    ERRprintmonitorinuse                 = 3008
    ERRprinterhasjobsqueued              = 3009

    # Error codes for the ERRSRV class

    ERRerror                             = 1
    ERRbadpw                             = 2
    ERRbadtype                           = 3
    ERRaccess                            = 4
    ERRinvnid                            = 5
    ERRinvnetname                        = 6
    ERRinvdevice                         = 7
    ERRqfull                             = 49
    ERRqtoobig                           = 50
    ERRinvpfid                           = 52
    ERRsmbcmd                            = 64
    ERRsrverror                          = 65
    ERRfilespecs                         = 67
    ERRbadlink                           = 68
    ERRbadpermits                        = 69
    ERRbadpid                            = 70
    ERRsetattrmode                       = 71
    ERRpaused                            = 81
    ERRmsgoff                            = 82
    ERRnoroom                            = 83
    ERRrmuns                             = 87
    ERRtimeout                           = 88
    ERRnoresource                        = 89
    ERRtoomanyuids                       = 90
    ERRbaduid                            = 91
    ERRuseMPX                            = 250
    ERRuseSTD                            = 251
    ERRcontMPX                           = 252
    ERRbadPW                             = None
    ERRnosupport                         = 0
    ERRunknownsmb                        = 22

    # Error codes for the ERRHRD class

    ERRnowrite                           = 19
    ERRbadunit                           = 20
    ERRnotready                          = 21
    ERRbadcmd                            = 22
    ERRdata                              = 23
    ERRbadreq                            = 24
    ERRseek                              = 25
    ERRbadmedia                          = 26
    ERRbadsector                         = 27
    ERRnopaper                           = 28
    ERRwrite                             = 29
    ERRread                              = 30
    ERRgeneral                           = 31
    ERRwrongdisk                         = 34
    ERRFCBunavail                        = 35
    ERRsharebufexc                       = 36
    ERRdiskfull                          = 39


    hard_msgs = {
      19: ("ERRnowrite", "Attempt to write on write-protected diskette."),
      20: ("ERRbadunit", "Unknown unit."),
      21: ("ERRnotready", "Drive not ready."),
      22: ("ERRbadcmd", "Unknown command."),
      23: ("ERRdata", "Data error (CRC)."),
      24: ("ERRbadreq", "Bad request structure length."),
      25: ("ERRseek", "Seek error."),
      26: ("ERRbadmedia", "Unknown media type."),
      27: ("ERRbadsector", "Sector not found."),
      28: ("ERRnopaper", "Printer out of paper."),
      29: ("ERRwrite", "Write fault."),
      30: ("ERRread", "Read fault."),
      31: ("ERRgeneral", "General failure."),
      32: ("ERRbadshare", "An open conflicts with an existing open."),
      33: ("ERRlock", "A Lock request conflicted with an existing lock or specified an invalid mode, or an Unlock requested attempted to remove a lock held by another process."),
      34: ("ERRwrongdisk", "The wrong disk was found in a drive."),
      35: ("ERRFCBUnavail", "No FCBs are available to process request."),
      36: ("ERRsharebufexc", "A sharing buffer has been exceeded.")
      }

    nt_msgs = {
        0x0000: ("STATUS_SUCCESS","The operation completed successfully."),
        0x0001: ("STATUS_UNSUCCESSFUL","A device attached to the system is not functioning."),
        0x0002: ("STATUS_NOT_IMPLEMENTED","Incorrect function."),
        0x0003: ("STATUS_INVALID_INFO_CLASS","The parameter is incorrect."),
        0x0004: ("STATUS_INFO_LENGTH_MISMATCH","The program issued a command but the command length is incorrect."),
        0x0005: ("STATUS_ACCESS_VIOLATION","Invalid access to memory location."),
        0x0006: ("STATUS_IN_PAGE_ERROR","Error performing inpage operation."),
        0x0007: ("STATUS_PAGEFILE_QUOTA","Insufficient quota to complete the requested service."),
        0x0008: ("STATUS_INVALID_HANDLE","The handle is invalid."),
        0x0009: ("STATUS_BAD_INITIAL_STACK","Recursion too deep, stack overflowed."),
        0x000a: ("STATUS_BAD_INITIAL_PC","Not a valid Windows NT application."),
        0x000b: ("STATUS_INVALID_CID","The parameter is incorrect."),
        0x000c: ("STATUS_TIMER_NOT_CANCELED","STATUS_TIMER_NOT_CANCELED"),
        0x000d: ("STATUS_INVALID_PARAMETER","The parameter is incorrect."),
        0x000e: ("STATUS_NO_SUCH_DEVICE","The system cannot find the file specified."),
        0x000f: ("STATUS_NO_SUCH_FILE","The system cannot find the file specified."),
        0x0010: ("STATUS_INVALID_DEVICE_REQUEST","Incorrect function."),
        0x0011: ("STATUS_END_OF_FILE","Reached end of file."),
        0x0012: ("STATUS_WRONG_VOLUME","The wrong diskette is in the drive. Insert %2 (Volume Serial Number: %3) into drive %1."),
        0x0013: ("STATUS_NO_MEDIA_IN_DEVICE","The device is not ready."),
        0x0014: ("STATUS_UNRECOGNIZED_MEDIA","The disk media is not recognized. It may not be formatted."),
        0x0015: ("STATUS_NONEXISTENT_SECTOR","The drive cannot find the sector requested."),
        0x0016: ("STATUS_MORE_PROCESSING_REQUIRED","More data is available."),
        0x0017: ("STATUS_NO_MEMORY","Not enough storage is available to process this command."),
        0x0018: ("STATUS_CONFLICTING_ADDRESSES","Attempt to access invalid address."),
        0x0019: ("STATUS_NOT_MAPPED_VIEW","Attempt to access invalid address."),
        0x001a: ("STATUS_UNABLE_TO_FREE_VM","The parameter is incorrect."),
        0x001b: ("STATUS_UNABLE_TO_DELETE_SECTION","The parameter is incorrect."),
        0x001c: ("STATUS_INVALID_SYSTEM_SERVICE","Incorrect function."),
        0x001d: ("STATUS_ILLEGAL_INSTRUCTION","STATUS_ILLEGAL_INSTRUCTION"),
        0x001e: ("STATUS_INVALID_LOCK_SEQUENCE","Access is denied."),
        0x001f: ("STATUS_INVALID_VIEW_SIZE","Access is denied."),
        0x0020: ("STATUS_INVALID_FILE_FOR_SECTION","Not a valid Windows NT application."),
        0x0021: ("STATUS_ALREADY_COMMITTED","Access is denied."),
        0x0022: ("STATUS_ACCESS_DENIED","Access is denied."),
        0x0023: ("STATUS_BUFFER_TOO_SMALL","The data area passed to a system call is too small."),
        0x0024: ("STATUS_OBJECT_TYPE_MISMATCH","The handle is invalid."),
        0x0025: ("STATUS_NONCONTINUABLE_EXCEPTION","STATUS_NONCONTINUABLE_EXCEPTION"),
        0x0026: ("STATUS_INVALID_DISPOSITION","STATUS_INVALID_DISPOSITION"),
        0x0027: ("STATUS_UNWIND","STATUS_UNWIND"),
        0x0028: ("STATUS_BAD_STACK","STATUS_BAD_STACK"),
        0x0029: ("STATUS_INVALID_UNWIND_TARGET","STATUS_INVALID_UNWIND_TARGET"),
        0x002a: ("STATUS_NOT_LOCKED","The segment is already unlocked."),
        0x002b: ("STATUS_PARITY_ERROR","STATUS_PARITY_ERROR"),
        0x002c: ("STATUS_UNABLE_TO_DECOMMIT_VM","Attempt to access invalid address."),
        0x002d: ("STATUS_NOT_COMMITTED","Attempt to access invalid address."),
        0x002e: ("STATUS_INVALID_PORT_ATTRIBUTES","STATUS_INVALID_PORT_ATTRIBUTES"),
        0x002f: ("STATUS_PORT_MESSAGE_TOO_LONG","STATUS_PORT_MESSAGE_TOO_LONG"),
        0x0030: ("STATUS_INVALID_PARAMETER_MIX","The parameter is incorrect."),
        0x0031: ("STATUS_INVALID_QUOTA_LOWER","STATUS_INVALID_QUOTA_LOWER"),
        0x0032: ("STATUS_DISK_CORRUPT_ERROR","The disk structure is corrupt and non-readable."),
        0x0033: ("STATUS_OBJECT_NAME_INVALID","The filename, directory name, or volume label syntax is incorrect."),
        0x0034: ("STATUS_OBJECT_NAME_NOT_FOUND","The system cannot find the file specified."),
        0x0035: ("STATUS_OBJECT_NAME_COLLISION","Cannot create a file when that file already exists."),
        0x0036: ("STATUS_HANDLE_NOT_WAITABLE","STATUS_HANDLE_NOT_WAITABLE"),
        0x0037: ("STATUS_PORT_DISCONNECTED","The handle is invalid."),
        0x0038: ("STATUS_DEVICE_ALREADY_ATTACHED","STATUS_DEVICE_ALREADY_ATTACHED"),
        0x0039: ("STATUS_OBJECT_PATH_INVALID","The specified path is invalid."),
        0x003a: ("STATUS_OBJECT_PATH_NOT_FOUND","The system cannot find the path specified."),
        0x003b: ("STATUS_OBJECT_PATH_SYNTAX_BAD","The specified path is invalid."),
        0x003c: ("STATUS_DATA_OVERRUN","The request could not be performed because of an I/O device error."),
        0x003d: ("STATUS_DATA_LATE_ERROR","The request could not be performed because of an I/O device error."),
        0x003e: ("STATUS_DATA_ERROR","Data error (cyclic redundancy check)"),
        0x003f: ("STATUS_CRC_ERROR","Data error (cyclic redundancy check)"),
        0x0040: ("STATUS_SECTION_TOO_BIG","Not enough storage is available to process this command."),
        0x0041: ("STATUS_PORT_CONNECTION_REFUSED","Access is denied."),
        0x0042: ("STATUS_INVALID_PORT_HANDLE","The handle is invalid."),
        0x0043: ("STATUS_SHARING_VIOLATION","The process cannot access the file because it is being used by another process."),
        0x0044: ("STATUS_QUOTA_EXCEEDED","Not enough quota is available to process this command."),
        0x0045: ("STATUS_INVALID_PAGE_PROTECTION","The parameter is incorrect."),
        0x0046: ("STATUS_MUTANT_NOT_OWNED","Attempt to release mutex not owned by caller."),
        0x0047: ("STATUS_SEMAPHORE_LIMIT_EXCEEDED","Too many posts were made to a semaphore."),
        0x0048: ("STATUS_PORT_ALREADY_SET","The parameter is incorrect."),
        0x0049: ("STATUS_SECTION_NOT_IMAGE","The parameter is incorrect."),
        0x004a: ("STATUS_SUSPEND_COUNT_EXCEEDED","The recipient process has refused the signal."),
        0x004b: ("STATUS_THREAD_IS_TERMINATING","Access is denied."),
        0x004c: ("STATUS_BAD_WORKING_SET_LIMIT","The parameter is incorrect."),
        0x004d: ("STATUS_INCOMPATIBLE_FILE_MAP","The parameter is incorrect."),
        0x004e: ("STATUS_SECTION_PROTECTION","The parameter is incorrect."),
        0x004f: ("STATUS_EAS_NOT_SUPPORTED","STATUS_EAS_NOT_SUPPORTED"),
        0x0050: ("STATUS_EA_TOO_LARGE","The extended attributes are inconsistent."),
        0x0051: ("STATUS_NONEXISTENT_EA_ENTRY","The file or directory is corrupt and non-readable."),
        0x0052: ("STATUS_NO_EAS_ON_FILE","The file or directory is corrupt and non-readable."),
        0x0053: ("STATUS_EA_CORRUPT_ERROR","The file or directory is corrupt and non-readable."),
        0x0054: ("STATUS_FILE_LOCK_CONFLICT","The process cannot access the file because another process has locked a portion of the file."),
        0x0055: ("STATUS_LOCK_NOT_GRANTED","The process cannot access the file because another process has locked a portion of the file."),
        0x0056: ("STATUS_DELETE_PENDING","Access is denied."),
        0x0057: ("STATUS_CTL_FILE_NOT_SUPPORTED","The network request is not supported."),
        0x0058: ("STATUS_UNKNOWN_REVISION","The revision level is unknown."),
        0x0059: ("STATUS_REVISION_MISMATCH","Indicates two revision levels are incompatible."),
        0x005a: ("STATUS_INVALID_OWNER","This security ID may not be assigned as the owner of this object."),
        0x005b: ("STATUS_INVALID_PRIMARY_GROUP","This security ID may not be assigned as the primary group of an object."),
        0x005c: ("STATUS_NO_IMPERSONATION_TOKEN","An attempt has been made to operate on an impersonation token by a thread that is not currently impersonating a client."),
        0x005d: ("STATUS_CANT_DISABLE_MANDATORY","The group may not be disabled."),
        0x005e: ("STATUS_NO_LOGON_SERVERS","There are currently no logon servers available to service the logon request."),
        0x005f: ("STATUS_NO_SUCH_LOGON_SESSION","A specified logon session does not exist. It may already have been terminated."),
        0x0060: ("STATUS_NO_SUCH_PRIVILEGE","A specified privilege does not exist."),
        0x0061: ("STATUS_PRIVILEGE_NOT_HELD","A required privilege is not held by the client."),
        0x0062: ("STATUS_INVALID_ACCOUNT_NAME","The name provided is not a properly formed account name."),
        0x0063: ("STATUS_USER_EXISTS","The specified user already exists."),
        0x0064: ("STATUS_NO_SUCH_USER","The specified user does not exist."),
        0x0065: ("STATUS_GROUP_EXISTS","The specified group already exists."),
        0x0066: ("STATUS_NO_SUCH_GROUP","The specified group does not exist."),
        0x0067: ("STATUS_MEMBER_IN_GROUP","Either the specified user account is already a member of the specified group, or the specified group cannot be deleted because it contains a member."),
        0x0068: ("STATUS_MEMBER_NOT_IN_GROUP","The specified user account is not a member of the specified group account."),
        0x0069: ("STATUS_LAST_ADMIN","The last remaining administration account cannot be disabled or deleted."),
        0x006a: ("STATUS_WRONG_PASSWORD","The specified network password is not correct."),
        0x006b: ("STATUS_ILL_FORMED_PASSWORD","Unable to update the password. The value provided for the new password contains values that are not allowed in passwords."),
        0x006c: ("STATUS_PASSWORD_RESTRICTION","Unable to update the password because a password update rule has been violated."),
        0x006d: ("STATUS_LOGON_FAILURE","Logon failure: unknown user name or bad password."),
        0x006e: ("STATUS_ACCOUNT_RESTRICTION","Logon failure: user account restriction."),
        0x006f: ("STATUS_INVALID_LOGON_HOURS","Logon failure: account logon time restriction violation."),
        0x0070: ("STATUS_INVALID_WORKSTATION","Logon failure: user not allowed to log on to this computer."),
        0x0071: ("STATUS_PASSWORD_EXPIRED","Logon failure: the specified account password has expired."),
        0x0072: ("STATUS_ACCOUNT_DISABLED","Logon failure: account currently disabled."),
        0x0073: ("STATUS_NONE_MAPPED","No mapping between account names and security IDs was done."),
        0x0074: ("STATUS_TOO_MANY_LUIDS_REQUESTED","Too many local user identifiers (LUIDs) were requested at one time."),
        0x0075: ("STATUS_LUIDS_EXHAUSTED","No more local user identifiers (LUIDs) are available."),
        0x0076: ("STATUS_INVALID_SUB_AUTHORITY","The subauthority part of a security ID is invalid for this particular use."),
        0x0077: ("STATUS_INVALID_ACL","The access control list (ACL) structure is invalid."),
        0x0078: ("STATUS_INVALID_SID","The security ID structure is invalid."),
        0x0079: ("STATUS_INVALID_SECURITY_DESCR","The security descriptor structure is invalid."),
        0x007a: ("STATUS_PROCEDURE_NOT_FOUND","The specified procedure could not be found."),
        0x007b: ("STATUS_INVALID_IMAGE_FORMAT","%1 is not a valid Windows NT application."),
        0x007c: ("STATUS_NO_TOKEN","An attempt was made to reference a token that does not exist."),
        0x007d: ("STATUS_BAD_INHERITANCE_ACL","The inherited access control list (ACL) or access control entry (ACE) could not be built."),
        0x007e: ("STATUS_RANGE_NOT_LOCKED","The segment is already unlocked."),
        0x007f: ("STATUS_DISK_FULL","There is not enough space on the disk."),
        0x0080: ("STATUS_SERVER_DISABLED","The server is currently disabled."),
        0x0081: ("STATUS_SERVER_NOT_DISABLED","The server is currently enabled."),
        0x0082: ("STATUS_TOO_MANY_GUIDS_REQUESTED","The name limit for the local computer network adapter card was exceeded."),
        0x0083: ("STATUS_GUIDS_EXHAUSTED","No more data is available."),
        0x0084: ("STATUS_INVALID_ID_AUTHORITY","The value provided was an invalid value for an identifier authority."),
        0x0085: ("STATUS_AGENTS_EXHAUSTED","No more data is available."),
        0x0086: ("STATUS_INVALID_VOLUME_LABEL","The volume label you entered exceeds the label character limit of the target file system."),
        0x0087: ("STATUS_SECTION_NOT_EXTENDED","Not enough storage is available to complete this operation."),
        0x0088: ("STATUS_NOT_MAPPED_DATA","Attempt to access invalid address."),
        0x0089: ("STATUS_RESOURCE_DATA_NOT_FOUND","The specified image file did not contain a resource section."),
        0x008a: ("STATUS_RESOURCE_TYPE_NOT_FOUND","The specified resource type can not be found in the image file."),
        0x008b: ("STATUS_RESOURCE_NAME_NOT_FOUND","The specified resource name can not be found in the image file."),
        0x008c: ("STATUS_ARRAY_BOUNDS_EXCEEDED","STATUS_ARRAY_BOUNDS_EXCEEDED"),
        0x008d: ("STATUS_FLOAT_DENORMAL_OPERAND","STATUS_FLOAT_DENORMAL_OPERAND"),
        0x008e: ("STATUS_FLOAT_DIVIDE_BY_ZERO","STATUS_FLOAT_DIVIDE_BY_ZERO"),
        0x008f: ("STATUS_FLOAT_INEXACT_RESULT","STATUS_FLOAT_INEXACT_RESULT"),
        0x0090: ("STATUS_FLOAT_INVALID_OPERATION","STATUS_FLOAT_INVALID_OPERATION"),
        0x0091: ("STATUS_FLOAT_OVERFLOW","STATUS_FLOAT_OVERFLOW"),
        0x0092: ("STATUS_FLOAT_STACK_CHECK","STATUS_FLOAT_STACK_CHECK"),
        0x0093: ("STATUS_FLOAT_UNDERFLOW","STATUS_FLOAT_UNDERFLOW"),
        0x0094: ("STATUS_INTEGER_DIVIDE_BY_ZERO","STATUS_INTEGER_DIVIDE_BY_ZERO"),
        0x0095: ("STATUS_INTEGER_OVERFLOW","Arithmetic result exceeded 32 bits."),
        0x0096: ("STATUS_PRIVILEGED_INSTRUCTION","STATUS_PRIVILEGED_INSTRUCTION"),
        0x0097: ("STATUS_TOO_MANY_PAGING_FILES","Not enough storage is available to process this command."),
        0x0098: ("STATUS_FILE_INVALID","The volume for a file has been externally altered such that the opened file is no longer valid."),
        0x0099: ("STATUS_ALLOTTED_SPACE_EXCEEDED","No more memory is available for security information updates."),
        0x009a: ("STATUS_INSUFFICIENT_RESOURCES","Insufficient system resources exist to complete the requested service."),
        0x009b: ("STATUS_DFS_EXIT_PATH_FOUND","The system cannot find the path specified."),
        0x009c: ("STATUS_DEVICE_DATA_ERROR","Data error (cyclic redundancy check)"),
        0x009d: ("STATUS_DEVICE_NOT_CONNECTED","The device is not ready."),
        0x009e: ("STATUS_DEVICE_POWER_FAILURE","The device is not ready."),
        0x009f: ("STATUS_FREE_VM_NOT_AT_BASE","Attempt to access invalid address."),
        0x00a0: ("STATUS_MEMORY_NOT_ALLOCATED","Attempt to access invalid address."),
        0x00a1: ("STATUS_WORKING_SET_QUOTA","Insufficient quota to complete the requested service."),
        0x00a2: ("STATUS_MEDIA_WRITE_PROTECTED","The media is write protected."),
        0x00a3: ("STATUS_DEVICE_NOT_READY","The device is not ready."),
        0x00a4: ("STATUS_INVALID_GROUP_ATTRIBUTES","The specified attributes are invalid, or incompatible with the attributes for the group as a whole."),
        0x00a5: ("STATUS_BAD_IMPERSONATION_LEVEL","Either a required impersonation level was not provided, or the provided impersonation level is invalid."),
        0x00a6: ("STATUS_CANT_OPEN_ANONYMOUS","Cannot open an anonymous level security token."),
        0x00a7: ("STATUS_BAD_VALIDATION_CLASS","The validation information class requested was invalid."),
        0x00a8: ("STATUS_BAD_TOKEN_TYPE","The type of the token is inappropriate for its attempted use."),
        0x00a9: ("STATUS_BAD_MASTER_BOOT_RECORD","STATUS_BAD_MASTER_BOOT_RECORD"),
        0x00aa: ("STATUS_INSTRUCTION_MISALIGNMENT","STATUS_INSTRUCTION_MISALIGNMENT"),
        0x00ab: ("STATUS_INSTANCE_NOT_AVAILABLE","All pipe instances are busy."),
        0x00ac: ("STATUS_PIPE_NOT_AVAILABLE","All pipe instances are busy."),
        0x00ad: ("STATUS_INVALID_PIPE_STATE","The pipe state is invalid."),
        0x00ae: ("STATUS_PIPE_BUSY","All pipe instances are busy."),
        0x00af: ("STATUS_ILLEGAL_FUNCTION","Incorrect function."),
        0x00b0: ("STATUS_PIPE_DISCONNECTED","No process is on the other end of the pipe."),
        0x00b1: ("STATUS_PIPE_CLOSING","The pipe is being closed."),
        0x00b2: ("STATUS_PIPE_CONNECTED","There is a process on other end of the pipe."),
        0x00b3: ("STATUS_PIPE_LISTENING","Waiting for a process to open the other end of the pipe."),
        0x00b4: ("STATUS_INVALID_READ_MODE","The pipe state is invalid."),
        0x00b5: ("STATUS_IO_TIMEOUT","The semaphore timeout period has expired."),
        0x00b6: ("STATUS_FILE_FORCED_CLOSED","Reached end of file."),
        0x00b7: ("STATUS_PROFILING_NOT_STARTED","STATUS_PROFILING_NOT_STARTED"),
        0x00b8: ("STATUS_PROFILING_NOT_STOPPED","STATUS_PROFILING_NOT_STOPPED"),
        0x00b9: ("STATUS_COULD_NOT_INTERPRET","STATUS_COULD_NOT_INTERPRET"),
        0x00ba: ("STATUS_FILE_IS_A_DIRECTORY","Access is denied."),
        0x00bb: ("STATUS_NOT_SUPPORTED","The network request is not supported."),
        0x00bc: ("STATUS_REMOTE_NOT_LISTENING","The remote computer is not available."),
        0x00bd: ("STATUS_DUPLICATE_NAME","A duplicate name exists on the network."),
        0x00be: ("STATUS_BAD_NETWORK_PATH","The network path was not found."),
        0x00bf: ("STATUS_NETWORK_BUSY","The network is busy."),
        0x00c0: ("STATUS_DEVICE_DOES_NOT_EXIST","The specified network resource or device is no longer available."),
        0x00c1: ("STATUS_TOO_MANY_COMMANDS","The network BIOS command limit has been reached."),
        0x00c2: ("STATUS_ADAPTER_HARDWARE_ERROR","A network adapter hardware error occurred."),
        0x00c3: ("STATUS_INVALID_NETWORK_RESPONSE","The specified server cannot perform the requested operation."),
        0x00c4: ("STATUS_UNEXPECTED_NETWORK_ERROR","An unexpected network error occurred."),
        0x00c5: ("STATUS_BAD_REMOTE_ADAPTER","The remote adapter is not compatible."),
        0x00c6: ("STATUS_PRINT_QUEUE_FULL","The printer queue is full."),
        0x00c7: ("STATUS_NO_SPOOL_SPACE","Space to store the file waiting to be printed is not available on the server."),
        0x00c8: ("STATUS_PRINT_CANCELLED","Your file waiting to be printed was deleted."),
        0x00c9: ("STATUS_NETWORK_NAME_DELETED","The specified network name is no longer available."),
        0x00ca: ("STATUS_NETWORK_ACCESS_DENIED","Network access is denied."),
        0x00cb: ("STATUS_BAD_DEVICE_TYPE","The network resource type is not correct."),
        0x00cc: ("STATUS_BAD_NETWORK_NAME","The network name cannot be found."),
        0x00cd: ("STATUS_TOO_MANY_NAMES","The name limit for the local computer network adapter card was exceeded."),
        0x00ce: ("STATUS_TOO_MANY_SESSIONS","The network BIOS session limit was exceeded."),
        0x00cf: ("STATUS_SHARING_PAUSED","The remote server has been paused or is in the process of being started."),
        0x00d0: ("STATUS_REQUEST_NOT_ACCEPTED","No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept."),
        0x00d1: ("STATUS_REDIRECTOR_PAUSED","The specified printer or disk device has been paused."),
        0x00d2: ("STATUS_NET_WRITE_FAULT","A write fault occurred on the network."),
        0x00d3: ("STATUS_PROFILING_AT_LIMIT","STATUS_PROFILING_AT_LIMIT"),
        0x00d4: ("STATUS_NOT_SAME_DEVICE","The system cannot move the file to a different disk drive."),
        0x00d5: ("STATUS_FILE_RENAMED","STATUS_FILE_RENAMED"),
        0x00d6: ("STATUS_VIRTUAL_CIRCUIT_CLOSED","The session was cancelled."),
        0x00d7: ("STATUS_NO_SECURITY_ON_OBJECT","Unable to perform a security operation on an object which has no associated security."),
        0x00d8: ("STATUS_CANT_WAIT","STATUS_CANT_WAIT"),
        0x00d9: ("STATUS_PIPE_EMPTY","The pipe is being closed."),
        0x00da: ("STATUS_CANT_ACCESS_DOMAIN_INFO","Indicates a Windows NT Server could not be contacted or that objects within the domain are protected such that necessary information could not be retrieved."),
        0x00db: ("STATUS_CANT_TERMINATE_SELF","STATUS_CANT_TERMINATE_SELF"),
        0x00dc: ("STATUS_INVALID_SERVER_STATE","The security account manager (SAM) or local security authority (LSA) server was in the wrong state to perform the security operation."),
        0x00dd: ("STATUS_INVALID_DOMAIN_STATE","The domain was in the wrong state to perform the security operation."),
        0x00de: ("STATUS_INVALID_DOMAIN_ROLE","This operation is only allowed for the Primary Domain Controller of the domain."),
        0x00df: ("STATUS_NO_SUCH_DOMAIN","The specified domain did not exist."),
        0x00e0: ("STATUS_DOMAIN_EXISTS","The specified domain already exists."),
        0x00e1: ("STATUS_DOMAIN_LIMIT_EXCEEDED","An attempt was made to exceed the limit on the number of domains per server."),
        0x00e2: ("STATUS_OPLOCK_NOT_GRANTED","STATUS_OPLOCK_NOT_GRANTED"),
        0x00e3: ("STATUS_INVALID_OPLOCK_PROTOCOL","STATUS_INVALID_OPLOCK_PROTOCOL"),
        0x00e4: ("STATUS_INTERNAL_DB_CORRUPTION","Unable to complete the requested operation because of either a catastrophic media failure or a data structure corruption on the disk."),
        0x00e5: ("STATUS_INTERNAL_ERROR","The security account database contains an internal inconsistency."),
        0x00e6: ("STATUS_GENERIC_NOT_MAPPED","Generic access types were contained in an access mask which should already be mapped to non-generic types."),
        0x00e7: ("STATUS_BAD_DESCRIPTOR_FORMAT","A security descriptor is not in the right format (absolute or self-relative)."),
        0x00e8: ("STATUS_INVALID_USER_BUFFER","The supplied user buffer is not valid for the requested operation."),
        0x00e9: ("STATUS_UNEXPECTED_IO_ERROR","STATUS_UNEXPECTED_IO_ERROR"),
        0x00ea: ("STATUS_UNEXPECTED_MM_CREATE_ERR","STATUS_UNEXPECTED_MM_CREATE_ERR"),
        0x00eb: ("STATUS_UNEXPECTED_MM_MAP_ERROR","STATUS_UNEXPECTED_MM_MAP_ERROR"),
        0x00ec: ("STATUS_UNEXPECTED_MM_EXTEND_ERR","STATUS_UNEXPECTED_MM_EXTEND_ERR"),
        0x00ed: ("STATUS_NOT_LOGON_PROCESS","The requested action is restricted for use by logon processes only. The calling process has not registered as a logon process."),
        0x00ee: ("STATUS_LOGON_SESSION_EXISTS","Cannot start a new logon session with an ID that is already in use."),
        0x00ef: ("STATUS_INVALID_PARAMETER_1","The parameter is incorrect."),
        0x00f0: ("STATUS_INVALID_PARAMETER_2","The parameter is incorrect."),
        0x00f1: ("STATUS_INVALID_PARAMETER_3","The parameter is incorrect."),
        0x00f2: ("STATUS_INVALID_PARAMETER_4","The parameter is incorrect."),
        0x00f3: ("STATUS_INVALID_PARAMETER_5","The parameter is incorrect."),
        0x00f4: ("STATUS_INVALID_PARAMETER_6","The parameter is incorrect."),
        0x00f5: ("STATUS_INVALID_PARAMETER_7","The parameter is incorrect."),
        0x00f6: ("STATUS_INVALID_PARAMETER_8","The parameter is incorrect."),
        0x00f7: ("STATUS_INVALID_PARAMETER_9","The parameter is incorrect."),
        0x00f8: ("STATUS_INVALID_PARAMETER_10","The parameter is incorrect."),
        0x00f9: ("STATUS_INVALID_PARAMETER_11","The parameter is incorrect."),
        0x00fa: ("STATUS_INVALID_PARAMETER_12","The parameter is incorrect."),
        0x00fb: ("STATUS_REDIRECTOR_NOT_STARTED","The system cannot find the path specified."),
        0x00fc: ("STATUS_REDIRECTOR_STARTED","STATUS_REDIRECTOR_STARTED"),
        0x00fd: ("STATUS_STACK_OVERFLOW","Recursion too deep, stack overflowed."),
        0x00fe: ("STATUS_NO_SUCH_PACKAGE","A specified authentication package is unknown."),
        0x00ff: ("STATUS_BAD_FUNCTION_TABLE","STATUS_BAD_FUNCTION_TABLE"),
        0x0101: ("STATUS_DIRECTORY_NOT_EMPTY","The directory is not empty."),
        0x0102: ("STATUS_FILE_CORRUPT_ERROR","The file or directory is corrupt and non-readable."),
        0x0103: ("STATUS_NOT_A_DIRECTORY","The directory name is invalid."),
        0x0104: ("STATUS_BAD_LOGON_SESSION_STATE","The logon session is not in a state that is consistent with the requested operation."),
        0x0105: ("STATUS_LOGON_SESSION_COLLISION","The logon session ID is already in use."),
        0x0106: ("STATUS_NAME_TOO_LONG","The filename or extension is too long."),
        0x0107: ("STATUS_FILES_OPEN","STATUS_FILES_OPEN"),
        0x0108: ("STATUS_CONNECTION_IN_USE","The device is being accessed by an active process."),
        0x0109: ("STATUS_MESSAGE_NOT_FOUND","STATUS_MESSAGE_NOT_FOUND"),
        0x010a: ("STATUS_PROCESS_IS_TERMINATING","Access is denied."),
        0x010b: ("STATUS_INVALID_LOGON_TYPE","A logon request contained an invalid logon type value."),
        0x010c: ("STATUS_NO_GUID_TRANSLATION","STATUS_NO_GUID_TRANSLATION"),
        0x010d: ("STATUS_CANNOT_IMPERSONATE","Unable to impersonate via a named pipe until data has been read from that pipe."),
        0x010e: ("STATUS_IMAGE_ALREADY_LOADED","An instance of the service is already running."),
        0x010f: ("STATUS_ABIOS_NOT_PRESENT","STATUS_ABIOS_NOT_PRESENT"),
        0x0110: ("STATUS_ABIOS_LID_NOT_EXIST","STATUS_ABIOS_LID_NOT_EXIST"),
        0x0111: ("STATUS_ABIOS_LID_ALREADY_OWNED","STATUS_ABIOS_LID_ALREADY_OWNED"),
        0x0112: ("STATUS_ABIOS_NOT_LID_OWNER","STATUS_ABIOS_NOT_LID_OWNER"),
        0x0113: ("STATUS_ABIOS_INVALID_COMMAND","STATUS_ABIOS_INVALID_COMMAND"),
        0x0114: ("STATUS_ABIOS_INVALID_LID","STATUS_ABIOS_INVALID_LID"),
        0x0115: ("STATUS_ABIOS_SELECTOR_NOT_AVAILABLE","STATUS_ABIOS_SELECTOR_NOT_AVAILABLE"),
        0x0116: ("STATUS_ABIOS_INVALID_SELECTOR","STATUS_ABIOS_INVALID_SELECTOR"),
        0x0117: ("STATUS_NO_LDT","STATUS_NO_LDT"),
        0x0118: ("STATUS_INVALID_LDT_SIZE","STATUS_INVALID_LDT_SIZE"),
        0x0119: ("STATUS_INVALID_LDT_OFFSET","STATUS_INVALID_LDT_OFFSET"),
        0x011a: ("STATUS_INVALID_LDT_DESCRIPTOR","STATUS_INVALID_LDT_DESCRIPTOR"),
        0x011b: ("STATUS_INVALID_IMAGE_NE_FORMAT","%1 is not a valid Windows NT application."),
        0x011c: ("STATUS_RXACT_INVALID_STATE","The transaction state of a Registry subtree is incompatible with the requested operation."),
        0x011d: ("STATUS_RXACT_COMMIT_FAILURE","An internal security database corruption has been encountered."),
        0x011e: ("STATUS_MAPPED_FILE_SIZE_ZERO","The volume for a file has been externally altered such that the opened file is no longer valid."),
        0x011f: ("STATUS_TOO_MANY_OPENED_FILES","The system cannot open the file."),
        0x0120: ("STATUS_CANCELLED","The I/O operation has been aborted because of either a thread exit or an application request."),
        0x0121: ("STATUS_CANNOT_DELETE","Access is denied."),
        0x0122: ("STATUS_INVALID_COMPUTER_NAME","The format of the specified computer name is invalid."),
        0x0123: ("STATUS_FILE_DELETED","Access is denied."),
        0x0124: ("STATUS_SPECIAL_ACCOUNT","Cannot perform this operation on built-in accounts."),
        0x0125: ("STATUS_SPECIAL_GROUP","Cannot perform this operation on this built-in special group."),
        0x0126: ("STATUS_SPECIAL_USER","Cannot perform this operation on this built-in special user."),
        0x0127: ("STATUS_MEMBERS_PRIMARY_GROUP","The user cannot be removed from a group because the group is currently the user's primary group."),
        0x0128: ("STATUS_FILE_CLOSED","The handle is invalid."),
        0x0129: ("STATUS_TOO_MANY_THREADS","STATUS_TOO_MANY_THREADS"),
        0x012a: ("STATUS_THREAD_NOT_IN_PROCESS","STATUS_THREAD_NOT_IN_PROCESS"),
        0x012b: ("STATUS_TOKEN_ALREADY_IN_USE","The token is already in use as a primary token."),
        0x012c: ("STATUS_PAGEFILE_QUOTA_EXCEEDED","STATUS_PAGEFILE_QUOTA_EXCEEDED"),
        0x012d: ("STATUS_COMMITMENT_LIMIT","The paging file is too small for this operation to complete."),
        0x012e: ("STATUS_INVALID_IMAGE_LE_FORMAT","%1 is not a valid Windows NT application."),
        0x012f: ("STATUS_INVALID_IMAGE_NOT_MZ","%1 is not a valid Windows NT application."),
        0x0130: ("STATUS_INVALID_IMAGE_PROTECT","%1 is not a valid Windows NT application."),
        0x0131: ("STATUS_INVALID_IMAGE_WIN_16","%1 is not a valid Windows NT application."),
        0x0132: ("STATUS_LOGON_SERVER_CONFLICT","STATUS_LOGON_SERVER_CONFLICT"),
        0x0133: ("STATUS_TIME_DIFFERENCE_AT_DC","STATUS_TIME_DIFFERENCE_AT_DC"),
        0x0134: ("STATUS_SYNCHRONIZATION_REQUIRED","STATUS_SYNCHRONIZATION_REQUIRED"),
        0x0135: ("STATUS_DLL_NOT_FOUND","The specified module could not be found."),
        0x0136: ("STATUS_OPEN_FAILED","STATUS_OPEN_FAILED"),
        0x0137: ("STATUS_IO_PRIVILEGE_FAILED","STATUS_IO_PRIVILEGE_FAILED"),
        0x0138: ("STATUS_ORDINAL_NOT_FOUND","The operating system cannot run %1."),
        0x0139: ("STATUS_ENTRYPOINT_NOT_FOUND","The specified procedure could not be found."),
        0x013a: ("STATUS_CONTROL_C_EXIT","STATUS_CONTROL_C_EXIT"),
        0x013b: ("STATUS_LOCAL_DISCONNECT","The specified network name is no longer available."),
        0x013c: ("STATUS_REMOTE_DISCONNECT","The specified network name is no longer available."),
        0x013d: ("STATUS_REMOTE_RESOURCES","The remote computer is not available."),
        0x013e: ("STATUS_LINK_FAILED","An unexpected network error occurred."),
        0x013f: ("STATUS_LINK_TIMEOUT","An unexpected network error occurred."),
        0x0140: ("STATUS_INVALID_CONNECTION","An unexpected network error occurred."),
        0x0141: ("STATUS_INVALID_ADDRESS","An unexpected network error occurred."),
        0x0142: ("STATUS_DLL_INIT_FAILED","A dynamic link library (DLL) initialization routine failed."),
        0x0143: ("STATUS_MISSING_SYSTEMFILE","STATUS_MISSING_SYSTEMFILE"),
        0x0144: ("STATUS_UNHANDLED_EXCEPTION","STATUS_UNHANDLED_EXCEPTION"),
        0x0145: ("STATUS_APP_INIT_FAILURE","STATUS_APP_INIT_FAILURE"),
        0x0146: ("STATUS_PAGEFILE_CREATE_FAILED","STATUS_PAGEFILE_CREATE_FAILED"),
        0x0147: ("STATUS_NO_PAGEFILE","STATUS_NO_PAGEFILE"),
        0x0148: ("STATUS_INVALID_LEVEL","The system call level is not correct."),
        0x0149: ("STATUS_WRONG_PASSWORD_CORE","The specified network password is not correct."),
        0x014a: ("STATUS_ILLEGAL_FLOAT_CONTEXT","STATUS_ILLEGAL_FLOAT_CONTEXT"),
        0x014b: ("STATUS_PIPE_BROKEN","The pipe has been ended."),
        0x014c: ("STATUS_REGISTRY_CORRUPT","The configuration registry database is corrupt."),
        0x014d: ("STATUS_REGISTRY_IO_FAILED","An I/O operation initiated by the Registry failed unrecoverably. The Registry could not read in, or write out, or flush, one of the files that contain the system's image of the Registry."),
        0x014e: ("STATUS_NO_EVENT_PAIR","STATUS_NO_EVENT_PAIR"),
        0x014f: ("STATUS_UNRECOGNIZED_VOLUME","The volume does not contain a recognized file system. Please make sure that all required file system drivers are loaded and that the volume is not corrupt."),
        0x0150: ("STATUS_SERIAL_NO_DEVICE_INITED","No serial device was successfully initialized. The serial driver will unload."),
        0x0151: ("STATUS_NO_SUCH_ALIAS","The specified local group does not exist."),
        0x0152: ("STATUS_MEMBER_NOT_IN_ALIAS","The specified account name is not a member of the local group."),
        0x0153: ("STATUS_MEMBER_IN_ALIAS","The specified account name is already a member of the local group."),
        0x0154: ("STATUS_ALIAS_EXISTS","The specified local group already exists."),
        0x0155: ("STATUS_LOGON_NOT_GRANTED","Logon failure: the user has not been granted the requested logon type at this computer."),
        0x0156: ("STATUS_TOO_MANY_SECRETS","The maximum number of secrets that may be stored in a single system has been exceeded."),
        0x0157: ("STATUS_SECRET_TOO_LONG","The length of a secret exceeds the maximum length allowed."),
        0x0158: ("STATUS_INTERNAL_DB_ERROR","The local security authority database contains an internal inconsistency."),
        0x0159: ("STATUS_FULLSCREEN_MODE","The requested operation cannot be performed in full-screen mode."),
        0x015a: ("STATUS_TOO_MANY_CONTEXT_IDS","During a logon attempt, the user's security context accumulated too many security IDs."),
        0x015b: ("STATUS_LOGON_TYPE_NOT_GRANTED","Logon failure: the user has not been granted the requested logon type at this computer."),
        0x015c: ("STATUS_NOT_REGISTRY_FILE","The system has attempted to load or restore a file into the Registry, but the specified file is not in a Registry file format."),
        0x015d: ("STATUS_NT_CROSS_ENCRYPTION_REQUIRED","A cross-encrypted password is necessary to change a user password."),
        0x015e: ("STATUS_DOMAIN_CTRLR_CONFIG_ERROR","STATUS_DOMAIN_CTRLR_CONFIG_ERROR"),
        0x015f: ("STATUS_FT_MISSING_MEMBER","The request could not be performed because of an I/O device error."),
        0x0160: ("STATUS_ILL_FORMED_SERVICE_ENTRY","STATUS_ILL_FORMED_SERVICE_ENTRY"),
        0x0161: ("STATUS_ILLEGAL_CHARACTER","STATUS_ILLEGAL_CHARACTER"),
        0x0162: ("STATUS_UNMAPPABLE_CHARACTER","No mapping for the Unicode character exists in the target multi-byte code page."),
        0x0163: ("STATUS_UNDEFINED_CHARACTER","STATUS_UNDEFINED_CHARACTER"),
        0x0164: ("STATUS_FLOPPY_VOLUME","STATUS_FLOPPY_VOLUME"),
        0x0165: ("STATUS_FLOPPY_ID_MARK_NOT_FOUND","No ID address mark was found on the floppy disk."),
        0x0166: ("STATUS_FLOPPY_WRONG_CYLINDER","Mismatch between the floppy disk sector ID field and the floppy disk controller track address."),
        0x0167: ("STATUS_FLOPPY_UNKNOWN_ERROR","The floppy disk controller reported an error that is not recognized by the floppy disk driver."),
        0x0168: ("STATUS_FLOPPY_BAD_REGISTERS","The floppy disk controller returned inconsistent results in its registers."),
        0x0169: ("STATUS_DISK_RECALIBRATE_FAILED","While accessing the hard disk, a recalibrate operation failed, even after retries."),
        0x016a: ("STATUS_DISK_OPERATION_FAILED","While accessing the hard disk, a disk operation failed even after retries."),
        0x016b: ("STATUS_DISK_RESET_FAILED","While accessing the hard disk, a disk controller reset was needed, but even that failed."),
        0x016c: ("STATUS_SHARED_IRQ_BUSY","Unable to open a device that was sharing an interrupt request (IRQ) with other devices. At least one other device that uses that IRQ was already opened."),
        0x016d: ("STATUS_FT_ORPHANING","The request could not be performed because of an I/O device error."),
        0x0172: ("STATUS_PARTITION_FAILURE","Tape could not be partitioned."),
        0x0173: ("STATUS_INVALID_BLOCK_LENGTH","When accessing a new tape of a multivolume partition, the current blocksize is incorrect."),
        0x0174: ("STATUS_DEVICE_NOT_PARTITIONED","Tape partition information could not be found when loading a tape."),
        0x0175: ("STATUS_UNABLE_TO_LOCK_MEDIA","Unable to lock the media eject mechanism."),
        0x0176: ("STATUS_UNABLE_TO_UNLOAD_MEDIA","Unable to unload the media."),
        0x0177: ("STATUS_EOM_OVERFLOW","Physical end of tape encountered."),
        0x0178: ("STATUS_NO_MEDIA","No media in drive."),
        0x017a: ("STATUS_NO_SUCH_MEMBER","A new member could not be added to a local group because the member does not exist."),
        0x017b: ("STATUS_INVALID_MEMBER","A new member could not be added to a local group because the member has the wrong account type."),
        0x017c: ("STATUS_KEY_DELETED","Illegal operation attempted on a Registry key which has been marked for deletion."),
        0x017d: ("STATUS_NO_LOG_SPACE","System could not allocate the required space in a Registry log."),
        0x017e: ("STATUS_TOO_MANY_SIDS","Too many security IDs have been specified."),
        0x017f: ("STATUS_LM_CROSS_ENCRYPTION_REQUIRED","A cross-encrypted password is necessary to change this user password."),
        0x0180: ("STATUS_KEY_HAS_CHILDREN","Cannot create a symbolic link in a Registry key that already has subkeys or values."),
        0x0181: ("STATUS_CHILD_MUST_BE_VOLATILE","Cannot create a stable subkey under a volatile parent key."),
        0x0182: ("STATUS_DEVICE_CONFIGURATION_ERROR","The parameter is incorrect."),
        0x0183: ("STATUS_DRIVER_INTERNAL_ERROR","The request could not be performed because of an I/O device error."),
        0x0184: ("STATUS_INVALID_DEVICE_STATE","The device does not recognize the command."),
        0x0185: ("STATUS_IO_DEVICE_ERROR","The request could not be performed because of an I/O device error."),
        0x0186: ("STATUS_DEVICE_PROTOCOL_ERROR","The request could not be performed because of an I/O device error."),
        0x0187: ("STATUS_BACKUP_CONTROLLER","STATUS_BACKUP_CONTROLLER"),
        0x0188: ("STATUS_LOG_FILE_FULL","The event log file is full."),
        0x0189: ("STATUS_TOO_LATE","The media is write protected."),
        0x018a: ("STATUS_NO_TRUST_LSA_SECRET","The workstation does not have a trust secret."),
        0x018b: ("STATUS_NO_TRUST_SAM_ACCOUNT","The SAM database on the Windows NT Server does not have a computer account for this workstation trust relationship."),
        0x018c: ("STATUS_TRUSTED_DOMAIN_FAILURE","The trust relationship between the primary domain and the trusted domain failed."),
        0x018d: ("STATUS_TRUSTED_RELATIONSHIP_FAILURE","The trust relationship between this workstation and the primary domain failed."),
        0x018e: ("STATUS_EVENTLOG_FILE_CORRUPT","The event log file is corrupt."),
        0x018f: ("STATUS_EVENTLOG_CANT_START","No event log file could be opened, so the event logging service did not start."),
        0x0190: ("STATUS_TRUST_FAILURE","The network logon failed."),
        0x0191: ("STATUS_MUTANT_LIMIT_EXCEEDED","STATUS_MUTANT_LIMIT_EXCEEDED"),
        0x0192: ("STATUS_NETLOGON_NOT_STARTED","An attempt was made to logon, but the network logon service was not started."),
        0x0193: ("STATUS_ACCOUNT_EXPIRED","The user's account has expired."),
        0x0194: ("STATUS_POSSIBLE_DEADLOCK","A potential deadlock condition has been detected."),
        0x0195: ("STATUS_NETWORK_CREDENTIAL_CONFLICT","The credentials supplied conflict with an existing set of credentials."),
        0x0196: ("STATUS_REMOTE_SESSION_LIMIT","An attempt was made to establish a session to a network server, but there are already too many sessions established to that server."),
        0x0197: ("STATUS_EVENTLOG_FILE_CHANGED","The event log file has changed between reads."),
        0x0198: ("STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT","The account used is an interdomain trust account. Use your global user account or local user account to access this server."),
        0x0199: ("STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT","The account used is a Computer Account. Use your global user account or local user account to access this server."),
        0x019a: ("STATUS_NOLOGON_SERVER_TRUST_ACCOUNT","The account used is an server trust account. Use your global user account or local user account to access this server."),
        0x019b: ("STATUS_DOMAIN_TRUST_INCONSISTENT","The name or security ID (SID) of the domain specified is inconsistent with the trust information for that domain."),
        0x019c: ("STATUS_FS_DRIVER_REQUIRED","STATUS_FS_DRIVER_REQUIRED"),
        0x0202: ("STATUS_NO_USER_SESSION_KEY","There is no user session key for the specified logon session."),
        0x0203: ("STATUS_USER_SESSION_DELETED","An unexpected network error occurred."),
        0x0204: ("STATUS_RESOURCE_LANG_NOT_FOUND","The specified resource language ID cannot be found in the image file."),
        0x0205: ("STATUS_INSUFF_SERVER_RESOURCES","Not enough server storage is available to process this command."),
        0x0206: ("STATUS_INVALID_BUFFER_SIZE","The supplied user buffer is not valid for the requested operation."),
        0x0207: ("STATUS_INVALID_ADDRESS_COMPONENT","The format of the specified network name is invalid."),
        0x0208: ("STATUS_INVALID_ADDRESS_WILDCARD","The format of the specified network name is invalid."),
        0x0209: ("STATUS_TOO_MANY_ADDRESSES","The name limit for the local computer network adapter card was exceeded."),
        0x020a: ("STATUS_ADDRESS_ALREADY_EXISTS","A duplicate name exists on the network."),
        0x020b: ("STATUS_ADDRESS_CLOSED","The specified network name is no longer available."),
        0x020c: ("STATUS_CONNECTION_DISCONNECTED","The specified network name is no longer available."),
        0x020d: ("STATUS_CONNECTION_RESET","The specified network name is no longer available."),
        0x020e: ("STATUS_TOO_MANY_NODES","The name limit for the local computer network adapter card was exceeded."),
        0x020f: ("STATUS_TRANSACTION_ABORTED","An unexpected network error occurred."),
        0x0210: ("STATUS_TRANSACTION_TIMED_OUT","An unexpected network error occurred."),
        0x0211: ("STATUS_TRANSACTION_NO_RELEASE","An unexpected network error occurred."),
        0x0212: ("STATUS_TRANSACTION_NO_MATCH","An unexpected network error occurred."),
        0x0213: ("STATUS_TRANSACTION_RESPONDED","An unexpected network error occurred."),
        0x0214: ("STATUS_TRANSACTION_INVALID_ID","An unexpected network error occurred."),
        0x0215: ("STATUS_TRANSACTION_INVALID_TYPE","An unexpected network error occurred."),
        0x0216: ("STATUS_NOT_SERVER_SESSION","The network request is not supported."),
        0x0217: ("STATUS_NOT_CLIENT_SESSION","The network request is not supported."),
        0x0218: ("STATUS_CANNOT_LOAD_REGISTRY_FILE","STATUS_CANNOT_LOAD_REGISTRY_FILE"),
        0x0219: ("STATUS_DEBUG_ATTACH_FAILED","STATUS_DEBUG_ATTACH_FAILED"),
        0x021a: ("STATUS_SYSTEM_PROCESS_TERMINATED","STATUS_SYSTEM_PROCESS_TERMINATED"),
        0x021b: ("STATUS_DATA_NOT_ACCEPTED","STATUS_DATA_NOT_ACCEPTED"),
        0x021c: ("STATUS_NO_BROWSER_SERVERS_FOUND","The list of servers for this workgroup is not currently available"),
        0x021d: ("STATUS_VDM_HARD_ERROR","STATUS_VDM_HARD_ERROR"),
        0x021e: ("STATUS_DRIVER_CANCEL_TIMEOUT","STATUS_DRIVER_CANCEL_TIMEOUT"),
        0x021f: ("STATUS_REPLY_MESSAGE_MISMATCH","STATUS_REPLY_MESSAGE_MISMATCH"),
        0x0220: ("STATUS_MAPPED_ALIGNMENT","The base address or the file offset specified does not have the proper alignment."),
        0x0221: ("STATUS_IMAGE_CHECKSUM_MISMATCH","%1 is not a valid Windows NT application."),
        0x0222: ("STATUS_LOST_WRITEBEHIND_DATA","STATUS_LOST_WRITEBEHIND_DATA"),
        0x0223: ("STATUS_CLIENT_SERVER_PARAMETERS_INVALID","STATUS_CLIENT_SERVER_PARAMETERS_INVALID"),
        0x0224: ("STATUS_PASSWORD_MUST_CHANGE","The user must change his password before he logs on the first time."),
        0x0225: ("STATUS_NOT_FOUND","STATUS_NOT_FOUND"),
        0x0226: ("STATUS_NOT_TINY_STREAM","STATUS_NOT_TINY_STREAM"),
        0x0227: ("STATUS_RECOVERY_FAILURE","STATUS_RECOVERY_FAILURE"),
        0x0228: ("STATUS_STACK_OVERFLOW_READ","STATUS_STACK_OVERFLOW_READ"),
        0x0229: ("STATUS_FAIL_CHECK","STATUS_FAIL_CHECK"),
        0x022a: ("STATUS_DUPLICATE_OBJECTID","STATUS_DUPLICATE_OBJECTID"),
        0x022b: ("STATUS_OBJECTID_EXISTS","STATUS_OBJECTID_EXISTS"),
        0x022c: ("STATUS_CONVERT_TO_LARGE","STATUS_CONVERT_TO_LARGE"),
        0x022d: ("STATUS_RETRY","STATUS_RETRY"),
        0x022e: ("STATUS_FOUND_OUT_OF_SCOPE","STATUS_FOUND_OUT_OF_SCOPE"),
        0x022f: ("STATUS_ALLOCATE_BUCKET","STATUS_ALLOCATE_BUCKET"),
        0x0230: ("STATUS_PROPSET_NOT_FOUND","STATUS_PROPSET_NOT_FOUND"),
        0x0231: ("STATUS_MARSHALL_OVERFLOW","STATUS_MARSHALL_OVERFLOW"),
        0x0232: ("STATUS_INVALID_VARIANT","STATUS_INVALID_VARIANT"),
        0x0233: ("STATUS_DOMAIN_CONTROLLER_NOT_FOUND","Could not find the domain controller for this domain."),
        0x0234: ("STATUS_ACCOUNT_LOCKED_OUT","The referenced account is currently locked out and may not be logged on to."),
        0x0235: ("STATUS_HANDLE_NOT_CLOSABLE","The handle is invalid."),
        0x0236: ("STATUS_CONNECTION_REFUSED","The remote system refused the network connection."),
        0x0237: ("STATUS_GRACEFUL_DISCONNECT","The network connection was gracefully closed."),
        0x0238: ("STATUS_ADDRESS_ALREADY_ASSOCIATED","The network transport endpoint already has an address associated with it."),
        0x0239: ("STATUS_ADDRESS_NOT_ASSOCIATED","An address has not yet been associated with the network endpoint."),
        0x023a: ("STATUS_CONNECTION_INVALID","An operation was attempted on a non-existent network connection."),
        0x023b: ("STATUS_CONNECTION_ACTIVE","An invalid operation was attempted on an active network connection."),
        0x023c: ("STATUS_NETWORK_UNREACHABLE","The remote network is not reachable by the transport."),
        0x023d: ("STATUS_HOST_UNREACHABLE","The remote system is not reachable by the transport."),
        0x023e: ("STATUS_PROTOCOL_UNREACHABLE","The remote system does not support the transport protocol."),
        0x023f: ("STATUS_PORT_UNREACHABLE","No service is operating at the destination network endpoint on the remote system."),
        0x0240: ("STATUS_REQUEST_ABORTED","The request was aborted."),
        0x0241: ("STATUS_CONNECTION_ABORTED","The network connection was aborted by the local system."),
        0x0242: ("STATUS_BAD_COMPRESSION_BUFFER","STATUS_BAD_COMPRESSION_BUFFER"),
        0x0243: ("STATUS_USER_MAPPED_FILE","The requested operation cannot be performed on a file with a user mapped section open."),
        0x0244: ("STATUS_AUDIT_FAILED","STATUS_AUDIT_FAILED"),
        0x0245: ("STATUS_TIMER_RESOLUTION_NOT_SET","STATUS_TIMER_RESOLUTION_NOT_SET"),
        0x0246: ("STATUS_CONNECTION_COUNT_LIMIT","A connection to the server could not be made because the limit on the number of concurrent connections for this account has been reached."),
        0x0247: ("STATUS_LOGIN_TIME_RESTRICTION","Attempting to login during an unauthorized time of day for this account."),
        0x0248: ("STATUS_LOGIN_WKSTA_RESTRICTION","The account is not authorized to login from this station."),
        0x0249: ("STATUS_IMAGE_MP_UP_MISMATCH","%1 is not a valid Windows NT application."),
        0x0250: ("STATUS_INSUFFICIENT_LOGON_INFO","STATUS_INSUFFICIENT_LOGON_INFO"),
        0x0251: ("STATUS_BAD_DLL_ENTRYPOINT","STATUS_BAD_DLL_ENTRYPOINT"),
        0x0252: ("STATUS_BAD_SERVICE_ENTRYPOINT","STATUS_BAD_SERVICE_ENTRYPOINT"),
        0x0253: ("STATUS_LPC_REPLY_LOST","The security account database contains an internal inconsistency."),
        0x0254: ("STATUS_IP_ADDRESS_CONFLICT1","STATUS_IP_ADDRESS_CONFLICT1"),
        0x0255: ("STATUS_IP_ADDRESS_CONFLICT2","STATUS_IP_ADDRESS_CONFLICT2"),
        0x0256: ("STATUS_REGISTRY_QUOTA_LIMIT","STATUS_REGISTRY_QUOTA_LIMIT"),
        0x0257: ("STATUS_PATH_NOT_COVERED","The remote system is not reachable by the transport."),
        0x0258: ("STATUS_NO_CALLBACK_ACTIVE","STATUS_NO_CALLBACK_ACTIVE"),
        0x0259: ("STATUS_LICENSE_QUOTA_EXCEEDED","The service being accessed is licensed for a particular number of connections. No more connections can be made to the service at this time because there are already as many connections as the service can accept."),
        0x025a: ("STATUS_PWD_TOO_SHORT","STATUS_PWD_TOO_SHORT"),
        0x025b: ("STATUS_PWD_TOO_RECENT","STATUS_PWD_TOO_RECENT"),
        0x025c: ("STATUS_PWD_HISTORY_CONFLICT","STATUS_PWD_HISTORY_CONFLICT"),
        0x025e: ("STATUS_PLUGPLAY_NO_DEVICE","The specified service is disabled and cannot be started."),
        0x025f: ("STATUS_UNSUPPORTED_COMPRESSION","STATUS_UNSUPPORTED_COMPRESSION"),
        0x0260: ("STATUS_INVALID_HW_PROFILE","STATUS_INVALID_HW_PROFILE"),
        0x0261: ("STATUS_INVALID_PLUGPLAY_DEVICE_PATH","STATUS_INVALID_PLUGPLAY_DEVICE_PATH"),
        0x0262: ("STATUS_DRIVER_ORDINAL_NOT_FOUND","The operating system cannot run %1."),
        0x0263: ("STATUS_DRIVER_ENTRYPOINT_NOT_FOUND","The specified procedure could not be found."),
        0x0264: ("STATUS_RESOURCE_NOT_OWNED","Attempt to release mutex not owned by caller."),
        0x0265: ("STATUS_TOO_MANY_LINKS","An attempt was made to create more links on a file than the file system supports."),
        0x0266: ("STATUS_QUOTA_LIST_INCONSISTENT","STATUS_QUOTA_LIST_INCONSISTENT"),
        0x0267: ("STATUS_FILE_IS_OFFLINE","STATUS_FILE_IS_OFFLINE"),
        0x0275: ("STATUS_NOT_A_REPARSE_POINT","STATUS_NOT_A_REPARSE_POINT"),
        0x0EDE: ("STATUS_NO_SUCH_JOB","STATUS_NO_SUCH_JOB"),
    }

    dos_msgs = {
      ERRbadfunc: ("ERRbadfunc", "Invalid function."),
      ERRbadfile: ("ERRbadfile", "File not found."),
      ERRbadpath: ("ERRbadpath", "Directory invalid."),
      ERRnofids: ("ERRnofids", "No file descriptors available"),
      ERRnoaccess: ("ERRnoaccess", "Access denied."),
      ERRbadfid: ("ERRbadfid", "Invalid file handle."),
      ERRbadmcb: ("ERRbadmcb", "Memory control blocks destroyed."),
      ERRnomem: ("ERRnomem", "Insufficient server memory to perform the requested function."),
      ERRbadmem: ("ERRbadmem", "Invalid memory block address."),
      ERRbadenv: ("ERRbadenv", "Invalid environment."),
      11: ("ERRbadformat", "Invalid format."),
      ERRbadaccess: ("ERRbadaccess", "Invalid open mode."),
      ERRbaddata: ("ERRbaddata", "Invalid data."),
      ERRres: ("ERRres", "reserved."),
      ERRbaddrive: ("ERRbaddrive", "Invalid drive specified."),
      ERRremcd: ("ERRremcd", "A Delete Directory request attempted  to  remove  the  server's  current directory."),
      ERRdiffdevice: ("ERRdiffdevice", "Not same device."),
      ERRnofiles: ("ERRnofiles", "A File Search command can find no more files matching the specified criteria."),
      ERRbadshare: ("ERRbadshare", "The sharing mode specified for an Open conflicts with existing  FIDs  on the file."),
      ERRlock: ("ERRlock", "A Lock request conflicted with an existing lock or specified an  invalid mode,  or an Unlock requested attempted to remove a lock held by another process."),
      ERRunsup: ("ERRunsup",  "The operation is unsupported"),
      ERRnosuchshare: ("ERRnosuchshare",  "You specified an invalid share name"),
      ERRfilexists: ("ERRfilexists", "The file named in a Create Directory, Make  New  File  or  Link  request already exists."),
      ERRinvalidname: ("ERRinvalidname",  "Invalid name"),
      ERRbadpipe: ("ERRbadpipe", "Pipe invalid."),
      ERRpipebusy: ("ERRpipebusy", "All instances of the requested pipe are busy."),
      ERRpipeclosing: ("ERRpipeclosing", "Pipe close in progress."),
      ERRnotconnected: ("ERRnotconnected", "No process on other end of pipe."),
      ERRmoredata: ("ERRmoredata", "There is more data to be returned."),
      ERRinvgroup: ("ERRinvgroup", "Invalid workgroup (try the -W option)"),
      ERRlogonfailure: ("ERRlogonfailure", "Logon failure"),
      ERRdiskfull: ("ERRdiskfull", "Disk full"),
      ERRgeneral: ("ERRgeneral",  "General failure"),
      ERRunknownlevel: ("ERRunknownlevel",  "Unknown info level")
      }

    server_msgs = { 
      1: ("ERRerror", "Non-specific error code."),
      2: ("ERRbadpw", "Bad password - name/password pair in a Tree Connect or Session Setup are invalid."),
      3: ("ERRbadtype", "reserved."),
      4: ("ERRaccess", "The requester does not have  the  necessary  access  rights  within  the specified  context for the requested function. The context is defined by the TID or the UID."),
      5: ("ERRinvnid", "The tree ID (TID) specified in a command was invalid."),
      6: ("ERRinvnetname", "Invalid network name in tree connect."),
      7: ("ERRinvdevice", "Invalid device - printer request made to non-printer connection or  non-printer request made to printer connection."),
      49: ("ERRqfull", "Print queue full (files) -- returned by open print file."),
      50: ("ERRqtoobig", "Print queue full -- no space."),
      51: ("ERRqeof", "EOF on print queue dump."),
      52: ("ERRinvpfid", "Invalid print file FID."),
      64: ("ERRsmbcmd", "The server did not recognize the command received."),
      65: ("ERRsrverror","The server encountered an internal error, e.g., system file unavailable."),
      67: ("ERRfilespecs", "The file handle (FID) and pathname parameters contained an invalid  combination of values."),
      68: ("ERRreserved", "reserved."),
      69: ("ERRbadpermits", "The access permissions specified for a file or directory are not a valid combination.  The server cannot set the requested attribute."),
      70: ("ERRreserved", "reserved."),
      71: ("ERRsetattrmode", "The attribute mode in the Set File Attribute request is invalid."),
      81: ("ERRpaused", "Server is paused."),
      82: ("ERRmsgoff", "Not receiving messages."),
      83: ("ERRnoroom", "No room to buffer message."),
      87: ("ERRrmuns", "Too many remote user names."),
      88: ("ERRtimeout", "Operation timed out."),
      89: ("ERRnoresource", "No resources currently available for request."),
      90: ("ERRtoomanyuids", "Too many UIDs active on this session."),
      91: ("ERRbaduid", "The UID is not known as a valid ID on this session."),
      250: ("ERRusempx","Temp unable to support Raw, use MPX mode."),
      251: ("ERRusestd","Temp unable to support Raw, use standard read/write."),
      252: ("ERRcontmpx", "Continue in MPX mode."),
      253: ("ERRreserved", "reserved."),
      254: ("ERRreserved", "reserved."),
  0xFFFF: ("ERRnosupport", "Function not supported.")
  }    
    # Error clases

    ERRDOS = 0x1
    error_classes = { 0: ("SUCCESS", {}),
                      ERRDOS: ("ERRDOS", dos_msgs),
                      0x02: ("ERRSRV",server_msgs),
                      0x03: ("ERRHRD",hard_msgs),
                      0x04: ("ERRXOS", {} ),
                      0xE1: ("ERRRMX1", {} ),
                      0xE2: ("ERRRMX2", {} ),
                      0xE3: ("ERRRMX3", {} ),
                      0xC000: ("ERRNT", nt_msgs),
                      0xFF: ("ERRCMD", {} ) }

    

    def __init__( self, str, error_class, error_code, nt_status = 0):
        Exception.__init__(self, str)
        self._args = str
        if nt_status:
           self.error_class = error_code
           self.error_code  = error_class
        else:
           self.error_class = error_class
           self.error_code = error_code
       
    def get_error_class( self ):
        return self.error_class

    def get_error_code( self ):
        return self.error_code

    def __str__( self ):
        error_class = SessionError.error_classes.get( self.error_class, None )
        if not error_class:
            error_code_str = self.error_code
            error_class_str = self.error_class
        else:
            error_class_str = error_class[0]
            error_code = error_class[1].get( self.error_code, None )
            if not error_code:
                error_code_str = self.error_code
            else:
                error_code_str = '%s(%s)' % (error_code)

        return 'SMB SessionError: class: %s, code: %s' % (error_class_str, error_code_str)


# Raised when an supported feature is present/required in the protocol but is not
# currently supported by pysmb
class UnsupportedFeature(Exception): pass

# Contains information about a SMB shared device/service
class SharedDevice:

    def __init__(self, name, type, comment):
        self.__name = name
        self.__type = type
        self.__comment = comment

    def get_name(self):
        return self.__name

    def get_type(self):
        return self.__type

    def get_comment(self):
        return self.__comment

    def __repr__(self):
        return '<SharedDevice instance: name=' + self.__name + ', type=' + str(self.__type) + ', comment="' + self.__comment + '">'


# Contains information about the shared file/directory
class SharedFile:
    def __init__(self, ctime, atime, mtime, filesize, allocsize, attribs, shortname, longname):
        self.__ctime = ctime
        self.__atime = atime
        self.__mtime = mtime
        self.__filesize = filesize
        self.__allocsize = allocsize
        self.__attribs = attribs
        try:
            self.__shortname = shortname[:string.index(shortname, '\0')]
        except ValueError:
            self.__shortname = shortname
        try:
            self.__longname = longname[:string.index(longname, '\0')]
        except ValueError:
            self.__longname = longname

    def get_ctime(self):
        return self.__ctime

    def get_ctime_epoch(self):
        return self.__convert_smbtime(self.__ctime)

    def get_mtime(self):
        return self.__mtime

    def get_mtime_epoch(self):
        return self.__convert_smbtime(self.__mtime)

    def get_atime(self):
        return self.__atime

    def get_atime_epoch(self):
        return self.__convert_smbtime(self.__atime)

    def get_filesize(self):
        return self.__filesize

    def get_allocsize(self):
        return self.__allocsize

    def get_attributes(self):
        return self.__attribs

    def is_archive(self):
        return self.__attribs & ATTR_ARCHIVE

    def is_compressed(self):
        return self.__attribs & ATTR_COMPRESSED

    def is_normal(self):
        return self.__attribs & ATTR_NORMAL

    def is_hidden(self):
        return self.__attribs & ATTR_HIDDEN

    def is_readonly(self):
        return self.__attribs & ATTR_READONLY

    def is_temporary(self):
        return self.__attribs & ATTR_TEMPORARY

    def is_directory(self):
        return self.__attribs & ATTR_DIRECTORY

    def is_system(self):
        return self.__attribs & ATTR_SYSTEM

    def get_shortname(self):
        return self.__shortname

    def get_longname(self):
        return self.__longname

    def __repr__(self):
        return '<SharedFile instance: shortname="' + self.__shortname + '", longname="' + self.__longname + '", filesize=' + str(self.__filesize) + '>'

    def __convert_smbtime(self, t):
        x = t >> 32
        y = t & 0xffffffffL
        geo_cal_offset = 11644473600.0  # = 369.0 * 365.25 * 24 * 60 * 60 - (3.0 * 24 * 60 * 60 + 6.0 * 60 * 60)
        return ((x * 4.0 * (1 << 30) + (y & 0xfff00000L)) * 1.0e-7 - geo_cal_offset)


# Contain information about a SMB machine
class SMBMachine:

    def __init__(self, nbname, type, comment):
        self.__nbname = nbname
        self.__type = type
        self.__comment = comment

    def __repr__(self):
        return '<SMBMachine instance: nbname="' + self.__nbname + '", type=' + hex(self.__type) + ', comment="' + self.__comment + '">'



class SMBDomain:
    def __init__(self, nbgroup, type, master_browser):
        self.__nbgroup = nbgroup
        self.__type = type
        self.__master_browser = master_browser

    def __repr__(self):
        return '<SMBDomain instance: nbgroup="' + self.__nbgroup + '", type=' + hex(self.__type) + ', master browser="' + self.__master_browser + '">'
    
# Represents a SMB Packet
class NewSMBPacket(Structure):
    structure = (
        ('Signature', '"\xffSMB'),
        ('Command','B=0'),
        ('ErrorClass','B=0'),
        ('_reserved','B=0'),
        ('ErrorCode','<H=0'),
        ('Flags1','B=0'),
        ('Flags2','<H=0'),
        ('PIDHigh','<H=0'),
        ('SecurityFeatures','8s=""'),
        ('Reserved','<H=0'),
        ('Tid','<H=0xffff'),
        ('Pid','<H=0'),
        ('Uid','<H=0'),
        ('Mid','<H=0'),
        ('Data','*:'),
    )

    def __init__(self, **kargs):
        Structure.__init__(self, **kargs)

        if self.fields.has_key('Flags2') is False:
             self['Flags2'] = 0
        if self.fields.has_key('Flags1') is False:
             self['Flags1'] = 0

        if not kargs.has_key('data'):
            self['Data'] = []
    
    def addCommand(self, command):
        if len(self['Data']) == 0:
            self['Command'] = command.command
        else:
            self['Data'][-1]['Parameters']['AndXCommand'] = command.command
            self['Data'][-1]['Parameters']['AndXOffset'] = len(self)
        self['Data'].append(command)
        
    def isMoreData(self):
        return (self['Command'] in [SMB.SMB_COM_TRANSACTION, SMB.SMB_COM_READ_ANDX, SMB.SMB_COM_READ_RAW] and
                self['ErrorClass'] == 1 and self['ErrorCode'] == SessionError.ERRmoredata)

    def isMoreProcessingRequired(self):
        return self['ErrorClass'] == 0x16 and self['ErrorCode'] == 0xc000

    def isValidAnswer(self, cmd):
        # this was inside a loop reading more from the net (with recv_packet(None))
        if self['Command'] == cmd:
            if (self['ErrorClass'] == 0x00 and
                self['ErrorCode']  == 0x00):
                    return 1
            elif self.isMoreData():
                return 1
            elif self.isMoreProcessingRequired():
                return 1
            raise SessionError, ("SMB Library Error", self['ErrorClass'] + (self['_reserved'] << 8), self['ErrorCode'], self['Flags2'] & SMB.FLAGS2_NT_STATUS)
        else:
            raise UnsupportedFeature, ("Unexpected answer from server: Got %d, Expected %d" % (self['Command'], cmd))

class SMBPacket:
    def __init__(self,data = ''):
        # The uid attribute will be set when the client calls the login() method
        self._command = 0x0
        self._error_class = 0x0
        self._error_code = 0x0
        self._flags = 0x0
        self._flags2 = 0x0
        self._pad = '\0' * 12
        self._tid = 0x0
        self._pid = 0x0
        self._uid = 0x0
        self._mid = 0x0
        self._wordcount = 0x0
        self._parameter_words = ''
        self._bytecount = 0x0
        self._buffer = ''
        if data != '':
            self._command = ord(data[4])
            self._error_class = ord(data[5])
            self._reserved = ord(data[6])
            self._error_code = unpack('<H',data[7:9])[0]
            self._flags = ord(data[9])
            self._flags2 = unpack('<H',data[10:12])[0]
            self._tid = unpack('<H',data[24:26])[0]
            self._pid = unpack('<H',data[26:28])[0]
            self._uid = unpack('<H',data[28:30])[0]
            self._mid = unpack('<H',data[30:32])[0]
            self._wordcount = ord(data[32])
            self._parameter_words = data[33:33+self._wordcount*2]
            self._bytecount = ord(data[33+self._wordcount*2])
            self._buffer = data[35+self._wordcount*2:]
    def set_command(self,command):
        self._command = command
    def set_error_class(self, error_class):
        self._error_class = error_class
    def set_error_code(self,error_code):
        self._error_code = error_code
    def set_flags(self,flags):
        self._flags = flags
    def set_flags2(self, flags2):
        self._flags2 = flags2
    def set_pad(self, pad):
        self._pad = pad
    def set_tid(self,tid):
        self._tid = tid
    def set_pid(self,pid):
        self._pid = pid
    def set_uid(self,uid):
        self._uid = uid
    def set_mid(self,mid):
        self._mid = mid
    def set_parameter_words(self,param):
        self._parameter_words = param
        self._wordcount = len(param)/2
    def set_buffer(self,buffer):
        if type(buffer) is types.UnicodeType:
            raise Exception('SMBPacket: Invalid buffer. Received unicode')
        self._buffer = buffer
        self._bytecount = len(buffer)

    def get_command(self):
        return self._command
    def get_error_class(self):
        return self._error_class
    def get_error_code(self):
        return self._error_code
    def get_reserved(self):
        return self._reserved
    def get_flags(self):
        return self._flags
    def get_flags2(self):
        return self._flags2
    def get_pad(self):
        return self._pad
    def get_tid(self):
        return self._tid
    def get_pid(self):
        return self._pid
    def get_uid(self):
        return self._uid
    def get_mid(self):
        return self._mid
    def get_parameter_words(self):
        return self._parameter_words
    def get_wordcount(self):
        return self._wordcount
    def get_bytecount(self):
        return self._bytecount
    def get_buffer(self):
        return self._buffer
    def rawData(self):
        data = pack('<4sBBBHBH12sHHHHB','\xffSMB',self._command,self._error_class,0,self._error_code,self._flags,
                    self._flags2,self._pad,self._tid, self._pid, self._uid, self._mid, self._wordcount) + self._parameter_words + pack('<H',self._bytecount) + self._buffer
        return data        

class SMBCommand(Structure):
    structure = (
        ('WordCount', 'B=len(Parameters)/2'),
        ('_ParametersLength','_-Parameters','WordCount*2'),
        ('Parameters',':'),             # default set by constructor
        ('ByteCount','<H-Data'),
        ('Data',':'),                   # default set by constructor
    )

    def __init__(self, commandOrData = None, data = None, **kargs):
        if type(commandOrData) == type(0):
            self.command = commandOrData
        else:
            data = data or commandOrData

        Structure.__init__(self, data = data, **kargs)

        if data is None:
            self['Parameters'] = ''
            self['Data']       = ''

class AsciiOrUnicodeStructure(Structure):
    def __init__(self, flags = 0, **kargs):
        if flags & SMB.FLAGS2_UNICODE:
            self.structure = self.UnicodeStructure
        else:
            self.structure = self.AsciiStructure
        return Structure.__init__(self, **kargs)

class SMBCommand_Parameters(Structure):
    pass

class SMBAndXCommand_Parameters(Structure):
    commonHdr = (
        ('AndXCommand','B=0xff'),
        ('_reserved','B=0'),
        ('AndXOffset','<H=0'),
    )
    structure = (       # default structure, overriden by subclasses
        ('Data',':=""'),
    )

############# TRANSACTIONS RELATED 
# TRANS2_QUERY_FS_INFORMATION
# QUERY_FS Information Levels
# SMB_QUERY_FS_ATTRIBUTE_INFO
class SMBQueryFsAttributeInfo(Structure):
    structure = (
        ('FileSystemAttributes','<L'),
        ('MaxFilenNameLengthInBytes','<L'),
        ('LengthOfFileSystemName','<L-FileSystemName'),
        ('FileSystemName',':'),
    )

class SMBQueryFsInfoVolume(AsciiOrUnicodeStructure):
    commonHdr = (
        ('ulVolSerialNbr','<L=0xABCDEFAA'),
        ('cCharCount','<B-VolumeLabel'),
    )
    AsciiStructure = (
        ('VolumeLabel','z'),
    )
    UnicodeStructure = (
        ('VolumeLabel','u'),
    )

# SMB_QUERY_FS_SIZE_INFO
class SMBQueryFsSizeInfo(Structure):
    structure = (
        ('TotalAllocationUnits','<q=148529400'),
        ('TotalFreeAllocationUnits','<q=14851044'),
        ('SectorsPerAllocationUnit','<L=2'),
        ('BytesPerSector','<L=512'),
    )
# SMB_QUERY_FS_VOLUME_INFO
class SMBQueryFsVolumeInfo(Structure):
    structure = (
        ('VolumeCreationTime','<q'),
        ('SerialNumber','<L=0xABCDEFAA'),
        ('VolumeLabelSize','<L=len(VolumeLabel)'),
        ('Reserved','<H=0'),
        ('VolumeLabel',':')
    )
# SMB_FIND_FILE_BOTH_DIRECTORY_INFO level
class SMBFindFileBothDirectoryInfo(AsciiOrUnicodeStructure):
    commonHdr = (
        ('NextEntryOffset','<L=0'),
        ('FileIndex','<L=0'),
        ('CreationTime','<q'),
        ('LastAccessTime','<q'),
        ('LastWriteTime','<q'),
        ('LastChangeTime','<q'),
        ('EndOfFile','<q=0'),
        ('AllocationSize','<q=0'),
        ('ExtFileAttributes','<L=0'),
    )
    AsciiStructure = (
        ('FileNameLength','<L-FileName','len(FileName)'),
        ('EaSize','<L=0'),
        ('ShortNameLength','<B=0'),
        ('Reserved','<B=0'),
        ('ShortName','24s'),
        ('FileName',':'),
    )
    UnicodeStructure = (
        ('FileNameLength','<L-FileName','len(FileName)*2'),
        ('EaSize','<L=0'),
        ('ShortNameLength','<B=0'),
        ('Reserved','<B=0'),
        ('ShortName','24s'),
        ('FileName','u'),
    )


# SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO level
class SMBFindFileIdFullDirectoryInfo(AsciiOrUnicodeStructure):
    commonHdr = (
        ('NextEntryOffset','<L=0'),
        ('FileIndex','<L=0'),
        ('CreationTime','<q'),
        ('LastAccessTime','<q'),
        ('LastWriteTime','<q'),
        ('LastChangeTime','<q'),
        ('EndOfFile','<q=0'),
        ('AllocationSize','<q=0'),
        ('ExtFileAttributes','<L=0'),
    )
    AsciiStructure = (
        ('FileNameLength','<L-FileName','len(FileName)'),
        ('EaSize','<L=0'),
        ('FileID','<q=0'),
        ('FileName',':'),
    )
    UnicodeStructure = (
        ('FileNameLength','<L-FileName','len(FileName)*2'),
        ('EaSize','<L=0'),
        ('FileID','<q=0'),
        ('FileName','u'),
    )

# SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO level
class SMBFindFileIdBothDirectoryInfo(AsciiOrUnicodeStructure):
    commonHdr = (
        ('NextEntryOffset','<L=0'),
        ('FileIndex','<L=0'),
        ('CreationTime','<q'),
        ('LastAccessTime','<q'),
        ('LastWriteTime','<q'),
        ('LastChangeTime','<q'),
        ('EndOfFile','<q=0'),
        ('AllocationSize','<q=0'),
        ('ExtFileAttributes','<L=0'),
    )
    AsciiStructure = (
        ('FileNameLength','<L-FileName','len(FileName)'),
        ('EaSize','<L=0'),
        ('ShortNameLength','<B=0'),
        ('Reserved','<B=0'),
        ('ShortName','24s'),
        ('Reserved','<H=0'),
        ('FileID','<q=0'),
        ('FileName','z'),
    )
    UnicodeStructure = (
        ('FileNameLength','<L-FileName','len(FileName)*2'),
        ('EaSize','<L=0'),
        ('ShortNameLength','<B=0'),
        ('Reserved','<B=0'),
        ('ShortName','24s'),
        ('Reserved','<H=0'),
        ('FileID','<q=0'),
        ('FileName','u'),
    )

# SMB_FIND_FILE_DIRECTORY_INFO level
class SMBFindFileDirectoryInfo(AsciiOrUnicodeStructure):
    commonHdr = (
        ('NextEntryOffset','<L=0'),
        ('FileIndex','<L=0'),
        ('CreationTime','<q'),
        ('LastAccessTime','<q'),
        ('LastWriteTime','<q'),
        ('LastChangeTime','<q'),
        ('EndOfFile','<q=0'),
        ('AllocationSize','<q=1'),
        ('ExtFileAttributes','<L=0'),
    )
    AsciiStructure = (
        ('FileNameLength','<L-FileName','len(FileName)'),
        ('FileName','z'),
    )
    UnicodeStructure = (
        ('FileNameLength','<L-FileName','len(FileName)*2'),
        ('FileName','u'),
    )

# SMB_FIND_FILE_NAMES_INFO level
class SMBFindFileNamesInfo(AsciiOrUnicodeStructure):
    commonHdr = (
        ('NextEntryOffset','<L=0'),
        ('FileIndex','<L=0'),
    )
    AsciiStructure = (
        ('FileNameLength','<L-FileName','len(FileName)'),
        ('FileName','z'),
    )
    UnicodeStructure = (
        ('FileNameLength','<L-FileName','len(FileName)*2'),
        ('FileName',':'),
    )

# SMB_FIND_FILE_FULL_DIRECTORY_INFO level
class SMBFindFileFullDirectoryInfo(AsciiOrUnicodeStructure):
    commonHdr = (
        ('NextEntryOffset','<L=0'),
        ('FileIndex','<L=0'),
        ('CreationTime','<q'),
        ('LastAccessTime','<q'),
        ('LastWriteTime','<q'),
        ('LastChangeTime','<q'),
        ('EndOfFile','<q=0'),
        ('AllocationSize','<q=1'),
        ('ExtFileAttributes','<L=0'),
    )
    AsciiStructure = (
        ('FileNameLength','<L-FileName','len(FileName)'),
        ('EaSize','<L'),
        ('FileName','z'),
    )
    UnicodeStructure = (
        ('FileNameLength','<L-FileName','len(FileName)*2'),
        ('EaSize','<L'),
        ('FileName','u'),
    )

# SMB_FIND_INFO_STANDARD level
class SMBFindInfoStandard(AsciiOrUnicodeStructure):
    commonHdr = (
        ('ResumeKey','<L=0xff'),
        ('CreationDate','<H=0'),
        ('CreationTime','<H=0'),
        ('LastAccessDate','<H=0'),
        ('LastAccessTime','<H=0'),
        ('LastWriteDate','<H=0'),
        ('LastWriteTime','<H=0'),
        ('EaSize','<L'),
        ('AllocationSize','<L=1'),
        ('ExtFileAttributes','<H=0'),
    )
    AsciiStructure = (
        ('FileNameLength','<B-FileName','len(FileName)'),
        ('FileName','z'),
    )
    UnicodeStructure = (
        ('FileNameLength','<B-FileName','len(FileName)*2'),
        ('FileName','u'),
    )

# SET_FILE_INFORMATION structures
# SMB_SET_FILE_DISPOSITION_INFO
class SMBSetFileDispositionInfo(Structure):
    structure = (
        ('DeletePending','<B'),
    )

# SMB_SET_FILE_BASIC_INFO
class SMBSetFileBasicInfo(Structure):
    structure = (
        ('CreationTime','<q'),
        ('LastAccessTime','<q'),
        ('LastWriteTime','<q'),
        ('ChangeTime','<q'),
        ('ExtFileAttributes','<H'),
        ('Reserved','<L'),
    )

# SMB_SET_FILE_END_OF_FILE_INFO
class SMBSetFileEndOfFileInfo(Structure):
    structure = (
        ('EndOfFile','<q'),
    )

# TRANS2_FIND_NEXT2
class SMBFindNext2_Parameters(AsciiOrUnicodeStructure):
     commonHdr = (
         ('SID','<H'),
         ('SearchCount','<H'),
         ('InformationLevel','<H'),
         ('ResumeKey','<L'),
         ('Flags','<H'),
     )
     AsciiStructure = (
         ('FileName','z'),
     )
     UnicodeStructure = (
         ('FileName','u'),
     )

class SMBFindNext2Response_Parameters(Structure):
     structure = (
         ('SearchCount','<H'),
         ('EndOfSearch','<H=1'),
         ('EaErrorOffset','<H=0'),
         ('LastNameOffset','<H=0'),
     )

class SMBFindNext2_Data(Structure):
     structure = (
         ('GetExtendedAttributesListLength','_-GetExtendedAttributesList', 'self["GetExtendedAttributesListLength"]'),
         ('GetExtendedAttributesList',':'),
     )


# TRANS2_FIND_FIRST2 
class SMBFindFirst2Response_Parameters(Structure):
     structure = (
         ('SID','<H'),
         ('SearchCount','<H'),
         ('EndOfSearch','<H=1'),
         ('EaErrorOffset','<H=0'),
         ('LastNameOffset','<H=0'),
     )

class SMBFindFirst2_Parameters(AsciiOrUnicodeStructure):
     commonHdr = (
         ('SearchAttributes','<H'),
         ('SearchCount','<H'),
         ('Flags','<H'),
         ('InformationLevel','<H'),
         ('SearchStorageType','<L'),
     )
     AsciiStructure = (
         ('FileName','z'),
     )
     UnicodeStructure = (
         ('FileName','u'),
     )

class SMBFindFirst2_Data(Structure):
     structure = (
         ('GetExtendedAttributesListLength','_-GetExtendedAttributesList', 'self["GetExtendedAttributesListLength"]'),
         ('GetExtendedAttributesList',':'),
     )

# TRANS2_SET_PATH_INFORMATION
class SMBSetPathInformation_Parameters(AsciiOrUnicodeStructure):
    commonHdr = (
        ('InformationLevel','<H'),
        ('Reserved','<L'),
    )
    AsciiStructure = (
        ('FileName','z'),
    )
    UnicodeStructure = (
        ('FileName','u'),
    )

class SMBSetPathInformationResponse_Parameters(Structure):
    structure = (
        ('EaErrorOffset','<H=0'),
    )

# TRANS2_SET_FILE_INFORMATION
class SMBSetFileInformation_Parameters(Structure):
    structure = (
        ('FID','<H'),
        ('InformationLevel','<H'),
        ('Reserved','<H'),
    )

class SMBSetFileInformationResponse_Parameters(Structure):
    structure = (
        ('EaErrorOffset','<H=0'),
    )

# TRANS2_QUERY_FILE_INFORMATION
class SMBQueryFileInformation_Parameters(Structure):
    structure = (
        ('FID','<H'),
        ('InformationLevel','<H'),
    )

class SMBQueryFileInformationResponse_Parameters(Structure):
    structure = (
        ('EaErrorOffset','<H=0')
    )

class SMBQueryFileInformation_Data(Structure):
    structure = (
        ('GetExtendedAttributeList',':'),
    )

class SMBQueryFileInformationResponse_Parameters(Structure):
    structure = (
        ('EaErrorOffset','<H=0'),
    )


# TRANS2_QUERY_PATH_INFORMATION
class SMBQueryPathInformationResponse_Parameters(Structure):
    structure = (
        ('EaErrorOffset','<H=0'),
    )

class SMBQueryPathInformation_Parameters(AsciiOrUnicodeStructure):
    commonHdr = (
        ('InformationLevel','<H'),
        ('Reserved','<L=0'),
    )
    AsciiStructure = (
        ('FileName','z'),
    )
    UnicodeStructure = (
        ('FileName','u'),
    )

class SMBQueryPathInformation_Data(Structure):
    structure = (
        ('GetExtendedAttributeList',':'),
    )


# SMB_QUERY_FILE_EA_INFO
class SMBQueryFileEaInfo(Structure):
    structure = (
        ('EaSize','<L=0'),
    )

# SMB_QUERY_FILE_BASIC_INFO 
class SMBQueryFileBasicInfo(Structure):
    structure = (
        ('CreationTime','<q'),
        ('LastAccessTime','<q'),
        ('LastWriteTime','<q'),
        ('LastChangeTime','<q'),
        ('ExtFileAttributes','<L'),
        #('Reserved','<L=0'),
    )

# SMB_QUERY_FILE_STANDARD_INFO
class SMBQueryFileStandardInfo(Structure):
    structure = (
        ('AllocationSize','<q'),
        ('EndOfFile','<q'),
        ('NumberOfLinks','<L=0'),
        ('DeletePending','<B=0'),
        ('Directory','<B'),
    )

# SMB_QUERY_FILE_ALL_INFO
class SMBQueryFileAllInfo(Structure):
    structure = (
        ('CreationTime','<q'),
        ('LastAccessTime','<q'),
        ('LastWriteTime','<q'),
        ('LastChangeTime','<q'),
        ('ExtFileAttributes','<L'),
        ('Reserved','<L=0'),
        ('AllocationSize','<q'),
        ('EndOfFile','<q'),
        ('NumberOfLinks','<L=0'),
        ('DeletePending','<B=0'),
        ('Directory','<B'),
        ('Reserved','<H=0'),
        ('EaSize','<L=0'),
        ('FileNameLength','<L-FileName','len(FileName)*2'),
        ('FileName','u'),
    )

# \PIPE\LANMAN NetShareEnum
class SMBNetShareEnum(Structure):
    structure = (
        ('RAPOpcode','<H=0'),
        ('ParamDesc','z'),
        ('DataDesc','z'),
        ('InfoLevel','<H'),
        ('ReceiveBufferSize','<H'),
    )

class SMBNetShareEnumResponse(Structure):
    structure = (
        ('Status','<H=0'),
        ('Convert','<H=0'),
        ('EntriesReturned','<H'),
        ('EntriesAvailable','<H'),
    )

class NetShareInfo1(Structure):
    structure = (
        ('NetworkName','13s'),
        ('Pad','<B=0'),
        ('Type','<H=0'),
        ('RemarkOffsetLow','<H=0'),
        ('RemarkOffsetHigh','<H=0'),
    )

# \PIPE\LANMAN NetServerGetInfo
class SMBNetServerGetInfoResponse(Structure):
    structure = (
        ('Status','<H=0'),
        ('Convert','<H=0'),
        ('TotalBytesAvailable','<H'),
    )

class SMBNetServerInfo1(Structure):
    # Level 1 Response
    structure = (
        ('ServerName','16s'),
        ('MajorVersion','B=5'),
        ('MinorVersion','B=0'),
        ('ServerType','<L=3'),
        ('ServerCommentLow','<H=0'),
        ('ServerCommentHigh','<H=0'),
    )

# \PIPE\LANMAN NetShareGetInfo
class SMBNetShareGetInfo(Structure):
    structure = (
        ('RAPOpcode','<H=0'),
        ('ParamDesc','z'),
        ('DataDesc','z'),
        ('ShareName','z'),
        ('InfoLevel','<H'),
        ('ReceiveBufferSize','<H'),
    )

class SMBNetShareGetInfoResponse(Structure):
    structure = (
        ('Status','<H=0'),
        ('Convert','<H=0'),
        ('TotalBytesAvailable','<H'),
    )

############# Security Features
class SecurityFeatures(Structure):
    structure = (
        ('Key','<L=0'),
        ('CID','<H=0'),
        ('SequenceNumber','<H=0'),
    )

############# SMB_COM_QUERY_INFORMATION2 (0x23)
class SMBQueryInformation2_Parameters(Structure):
    structure = (
        ('Fid','<H'),
    )

class SMBQueryInformation2Response_Parameters(Structure):
    structure = (
        ('CreateDate','<H'),
        ('CreationTime','<H'),
        ('LastAccessDate','<H'),
        ('LastAccessTime','<H'),
        ('LastWriteDate','<H'),
        ('LastWriteTime','<H'),
        ('FileDataSize','<L'),
        ('FileAllocationSize','<L'),
        ('FileAttributes','<L'),
    )



############# SMB_COM_SESSION_SETUP_ANDX (0x73)
class SMBSessionSetupAndX_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('MaxBuffer','<H'),
        ('MaxMpxCount','<H'),
        ('VCNumber','<H'),
        ('SessionKey','<L'),
        ('AnsiPwdLength','<H'),
        ('UnicodePwdLength','<H'),
        ('_reserved','<L=0'),
        ('Capabilities','<L'),
    )

class SMBSessionSetupAndX_Extended_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('MaxBufferSize','<H'),
        ('MaxMpxCount','<H'),
        ('VcNumber','<H'),
        ('SessionKey','<L'),
        ('SecurityBlobLength','<H'),
        ('Reserved','<L=0'),
        ('Capabilities','<L'),
    )

class SMBSessionSetupAndX_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('AnsiPwdLength','_-AnsiPwd','self["AnsiPwdLength"]'),
        ('UnicodePwdLength','_-UnicodePwd','self["UnicodePwdLength"]'),
        ('AnsiPwd',':=""'),
        ('UnicodePwd',':=""'),
        ('Account','z=""'),
        ('PrimaryDomain','z=""'),
        ('NativeOS','z=""'),
        ('NativeLanMan','z=""'),
    )
    
    UnicodeStructure = (
        ('AnsiPwdLength','_-AnsiPwd','self["AnsiPwdLength"]'),
        ('UnicodePwdLength','_-UnicodePwd','self["UnicodePwdLength"]'),
        ('AnsiPwd',':=""'),
        ('UnicodePwd',':=""'),
        ('Account','u=""'),
        ('PrimaryDomain','u=""'),
        ('NativeOS','u=""'),
        ('NativeLanMan','u=""'),
    )

class SMBSessionSetupAndX_Extended_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('SecurityBlobLength','_-SecurityBlob','self["SecurityBlobLength"]'),
        ('SecurityBlob',':'),
        ('NativeOS','z=""'),
        ('NativeLanMan','z=""'),
    )

    UnicodeStructure = (
        ('SecurityBlobLength','_-SecurityBlob','self["SecurityBlobLength"]'),
        ('SecurityBlob',':'),
        ('NativeOS','u=""'),
        ('NativeLanMan','u=""'),
    )

class SMBSessionSetupAndXResponse_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('Action','<H'),
    )

class SMBSessionSetupAndX_Extended_Response_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('Action','<H=0'),
        ('SecurityBlobLength','<H'),
    )

class SMBSessionSetupAndXResponse_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('NativeOS','z=""'),
        ('NativeLanMan','z=""'),
        ('PrimaryDomain','z=""'),
    )

    UnicodeStructure = (
        ('NativeOS','u=""'),
        ('NativeLanMan','u=""'),
        ('PrimaryDomain','u=""'),
    )

class SMBSessionSetupAndX_Extended_Response_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('SecurityBlobLength','_-SecurityBlob','self["SecurityBlobLength"]'),
        ('SecurityBlob',':'),
        ('NativeOS','z=""'),
        ('NativeLanMan','z=""'),
    )

    UnicodeStructure = (
        ('SecurityBlobLength','_-SecurityBlob','self["SecurityBlobLength"]'),
        ('SecurityBlob',':'),
        ('NativeOS','u=""'),
        ('NativeLanMan','u=""'),
    )

############# SMB_COM_TREE_CONNECT (0x70)
class SMBTreeConnect_Parameters(SMBCommand_Parameters):
    structure = (
    )

class SMBTreeConnect_Data(SMBCommand_Parameters):
    structure = (
        ('PathFormat','"\x04'),
        ('Path','z'),
        ('PasswordFormat','"\x04'),
        ('Password','z'),
        ('ServiceFormat','"\x04'),
        ('Service','z'),
    )

############# SMB_COM_TREE_CONNECT_ANDX (0x75)
class SMBTreeConnectAndX_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('Flags','<H=0'),
        ('PasswordLength','<H'),
    )

class SMBTreeConnectAndXResponse_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('OptionalSupport','<H=0'),
    )

class SMBTreeConnectAndXExtendedResponse_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('OptionalSupport','<H=1'),
        ('MaximalShareAccessRights','<L=0x1fffff'),
        ('GuestMaximalShareAccessRights','<L=0x1fffff'),
    )

class SMBTreeConnectAndX_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('_PasswordLength','_-Password','self["_PasswordLength"]'),
        ('Password',':'),
        ('Path','z'),
        ('Service','z'),
    )

    UnicodeStructure = (
        ('_PasswordLength','_-Password','self["_PasswordLength"]'),
        ('Password',':'),
        ('Path','u'),
        ('Service','z'),
    )

class SMBTreeConnectAndXResponse_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('Service','z'),
        ('PadLen','_-Pad','self["PadLen"]'),
        ('Pad',':=""'),
        ('NativeFileSystem','z'),
    )
    UnicodeStructure = (
        ('Service','z'),
        ('PadLen','_-Pad','self["PadLen"]'),
        ('Pad',':=""'),
        ('NativeFileSystem','u'),
    )

############# SMB_COM_NT_CREATE_ANDX (0xA2)
class SMBNtCreateAndX_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('_reserved', 'B=0'),
        ('FileNameLength','<H'),     # NameLength
        ('CreateFlags','<L'),        # Flags
        ('RootFid','<L=0'),          # RootDirectoryFID
        ('AccessMask','<L'),         # DesiredAccess
        ('AllocationSizeLo','<L=0'), # AllocationSize
        ('AllocationSizeHi','<L=0'),
        ('FileAttributes','<L=0'),   # ExtFileAttributes
        ('ShareAccess','<L=3'),      # 
        ('Disposition','<L=1'),      # CreateDisposition
        ('CreateOptions','<L'),      # CreateOptions
        ('Impersonation','<L=2'),
        ('SecurityFlags','B=3'),
    )

class SMBNtCreateAndXResponse_Parameters(SMBAndXCommand_Parameters):
    # XXX Is there a memory leak in the response for NTCreate (where the Data section would be) in Win 2000, Win XP, and Win 2003?
    structure = (
        ('OplockLevel', 'B=0'),
        ('Fid','<H'),
        ('CreateAction','<L'),
        ('CreateTime','<q=0'),
        ('LastAccessTime','<q=0'),
        ('LastWriteTime','<q=0'),
        ('LastChangeTime','<q=0'),
        ('FileAttributes','<L=0x80'),
        ('AllocationSize','<q=0'),
        ('EndOfFile','<q=0'),
        ('FileType','<H=0'),
        ('IPCState','<H=0'),
        ('IsDirectory','B'),
    )

class SMBNtCreateAndXExtendedResponse_Parameters(SMBAndXCommand_Parameters):
    # [MS-SMB] Extended response description
    structure = (
        ('OplockLevel', 'B=0'),
        ('Fid','<H'),
        ('CreateAction','<L'),
        ('CreateTime','<q=0'),
        ('LastAccessTime','<q=0'),
        ('LastWriteTime','<q=0'),
        ('LastChangeTime','<q=0'),
        ('FileAttributes','<L=0x80'),
        ('AllocationSize','<q=0'),
        ('EndOfFile','<q=0'),
        ('FileType','<H=0'),
        ('IPCState','<H=0'),
        ('IsDirectory','B'),
        ('VolumeGUID','16s'),
        ('FileIdLow','<L=0'),
        ('FileIdHigh','<L=0'),
        ('MaximalAccessRights','<L=0x12019b'),
        ('GuestMaximalAccessRights','<L=0x120089'),
    )

class SMBNtCreateAndX_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('FileName','z'),
    )
    UnicodeStructure = (
        ('Pad','B'),
        ('FileName','u'),
    )

############# SMB_COM_OPEN_ANDX (0xD2)
class SMBOpenAndX_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('Flags','<H=0'),
        ('DesiredAccess','<H=0'),
        ('SearchAttributes','<H=0'),
        ('FileAttributes','<H=0'),
        ('CreationTime','<L=0'),
        ('OpenMode','<H=1'),        # SMB_O_OPEN = 1
        ('AllocationSize','<L=0'),
        ('Reserved','8s=""'),
    )

class SMBOpenAndX_Data(SMBNtCreateAndX_Data):
    pass

class SMBOpenAndXResponse_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('Fid','<H=0'),
        ('FileAttributes','<H=0'),
        ('LastWriten','<L=0'),
        ('FileSize','<L=0'),
        ('GrantedAccess','<H=0'),
        ('FileType','<H=0'),
        ('IPCState','<H=0'),
        ('Action','<H=0'),
        ('ServerFid','<L=0'),
        ('_reserved','<H=0'),
    )

############# SMB_COM_WRITE (0x0B)
class SMBWrite_Parameters(SMBCommand_Parameters):
    structure = (
        ('Fid','<H'),
        ('Count','<H'),
        ('Offset','<L'),
        ('Remaining','<H'),
    )

class SMBWriteResponse_Parameters(SMBCommand_Parameters):
    structure = (
        ('Count','<H'),
    )

class SMBWrite_Data(Structure):
    structure = (
        ('BufferFormat','<B=1'),
        ('DataLength','<H-Data'),
        ('Data',':'),
    )

    
############# SMB_COM_WRITE_ANDX (0x2F)
class SMBWriteAndX_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('Fid','<H=0'),
        ('Offset','<L=0'),
        ('_reserved','<L=0xff'),
        ('WriteMode','<H=8'),
        ('Remaining','<H=0'),
        ('DataLength_Hi','<H=0'),
        ('DataLength','<H=0'),
        ('DataOffset','<H=0'),
        ('HighOffset','<L=0'),
    )

class SMBWriteAndX_Data_Short(Structure):
     structure = (
         ('_PadLen','_-Pad','self["DataOffset"] - 59'),
         ('Pad',':'),
         #('Pad','<B=0'),
         ('DataLength','_-Data','self["DataLength"]'),
         ('Data',':'),
     )

class SMBWriteAndX_Data(Structure):
     structure = (
         ('_PadLen','_-Pad','self["DataOffset"] - 63'),
         ('Pad',':'),
         #('Pad','<B=0'),
         ('DataLength','_-Data','self["DataLength"]'),
         ('Data',':'),
     )

    
class SMBWriteAndX_Parameters_Short(SMBAndXCommand_Parameters):
    structure = (
        ('Fid','<H'),
        ('Offset','<L'),
        ('_reserved','<L=0xff'),
        ('WriteMode','<H=8'),
        ('Remaining','<H'),
        ('DataLength_Hi','<H=0'),
        ('DataLength','<H'),
        ('DataOffset','<H=0'),
    )
    
class SMBWriteAndXResponse_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('Count','<H'),
        ('Available','<H'),
        ('Reserved','<L=0'),
    )

############# SMB_COM_WRITE_RAW (0x1D)
class SMBWriteRaw_Parameters(SMBCommand_Parameters):
    structure = (
        ('Fid','<H'),
        ('Count','<H'),
        ('_reserved','<H=0'),
        ('Offset','<L'),
        ('Timeout','<L=0'),
        ('WriteMode','<H=0'),
        ('_reserved2','<L=0'),
        ('DataLength','<H'),
        ('DataOffset','<H=0'),
    )
    
############# SMB_COM_READ (0x0A)
class SMBRead_Parameters(SMBCommand_Parameters):
    structure = (
        ('Fid','<H'),
        ('Count','<H'),
        ('Offset','<L'),
        ('Remaining','<H=Count'),
    )

class SMBReadResponse_Parameters(Structure):
    structure = (
        ('Count','<H=0'),
        ('_reserved','8s=""'),
    )

class SMBReadResponse_Data(Structure):
    structure = (
        ('BufferFormat','<B=0x1'),
        ('DataLength','<H-Data'),
        ('Data',':'),
    )

############# SMB_COM_READ_RAW (0x1A)
class SMBReadRaw_Parameters(SMBCommand_Parameters):
    structure = (
        ('Fid','<H'),
        ('Offset','<L'),
        ('MaxCount','<H'),
        ('MinCount','<H=MaxCount'),
        ('Timeout','<L=0'),
        ('_reserved','<H=0'),
    )

############# SMB_COM_NT_TRANSACT  (0xA0)
class SMBNTTransaction_Parameters(SMBCommand_Parameters):
    structure = (
        ('MaxSetupCount','<B=0'),
        ('Reserved1','<H=0'),
        ('TotalParameterCount','<L'),
        ('TotalDataCount','<L'),
        ('MaxParameterCount','<L=1024'),
        ('MaxDataCount','<L=65504'),
        ('ParameterCount','<L'),
        ('ParameterOffset','<L'),
        ('DataCount','<L'),
        ('DataOffset','<L'),
        ('SetupCount','<B=len(Setup)/2'),
        ('Function','<H=0'),
        ('SetupLength','_-Setup','SetupCount*2'),
        ('Setup',':'),
    )

class SMBNTTransactionResponse_Parameters(SMBCommand_Parameters):
    structure = (
        ('Reserved1','3s=""'),
        ('TotalParameterCount','<L'),
        ('TotalDataCount','<L'),
        ('ParameterCount','<L'),
        ('ParameterOffset','<L'),
        ('ParameterDisplacement','<L=0'),
        ('DataCount','<L'),
        ('DataOffset','<L'),
        ('DataDisplacement','<L=0'),
        ('SetupCount','<B=0'),
        ('SetupLength','_-Setup','SetupCount*2'),
        ('Setup',':'),
    )

class SMBNTTransaction_Data(Structure):
    structure = (
        ('Pad1Length','_-Pad1','self["Pad1Length"]'),
        ('Pad1',':'),
        ('NT_Trans_ParametersLength','_-NT_Trans_Parameters','self["NT_Trans_ParametersLength"]'),
        ('NT_Trans_Parameters',':'),
        ('Pad2Length','_-Pad2','self["Pad2Length"]'),
        ('Pad2',':'),
        ('NT_Trans_DataLength','_-NT_Trans_Data','self["NT_Trans_DataLength"]'),
        ('NT_Trans_Data',':'),
    )

class SMBNTTransactionResponse_Data(Structure):
    structure = (
        ('Pad1Length','_-Pad1','self["Pad1Length"]'),
        ('Pad1',':'),
        ('Trans_ParametersLength','_-Trans_Parameters','self["Trans_ParametersLength"]'),
        ('Trans_Parameters',':'),
        ('Pad2Length','_-Pad2','self["Pad2Length"]'),
        ('Pad2',':'),
        ('Trans_DataLength','_-Trans_Data','self["Trans_DataLength"]'),
        ('Trans_Data',':'),
    )


############# SMB_COM_TRANSACTION2_SECONDARY (0x33)
class SMBTransaction2Secondary_Parameters(SMBCommand_Parameters):
    structure = (
        ('TotalParameterCount','<H'),
        ('TotalDataCount','<H'),
        ('ParameterCount','<H'),
        ('ParameterOffset','<H'),
        ('DataCount','<H'),
        ('DataOffset','<H'),
        ('DataDisplacement','<H=0'),
        ('FID','<H'),
    )

class SMBTransaction2Secondary_Data(Structure):
    structure = (
        ('Pad1Length','_-Pad1','self["Pad1Length"]'),
        ('Pad1',':'),
        ('Trans_ParametersLength','_-Trans_Parameters','self["Trans_ParametersLength"]'),
        ('Trans_Parameters',':'),
        ('Pad2Length','_-Pad2','self["Pad2Length"]'),
        ('Pad2',':'),
        ('Trans_DataLength','_-Trans_Data','self["Trans_DataLength"]'),
        ('Trans_Data',':'),
    )


############# SMB_COM_TRANSACTION2 (0x32)

class SMBTransaction2_Parameters(SMBCommand_Parameters):
    structure = (
        ('TotalParameterCount','<H'),
        ('TotalDataCount','<H'),
        ('MaxParameterCount','<H=1024'),
        ('MaxDataCount','<H=65504'),
        ('MaxSetupCount','<B=0'),
        ('Reserved1','<B=0'),
        ('Flags','<H=0'),
        ('Timeout','<L=0'),
        ('Reserved2','<H=0'),
        ('ParameterCount','<H'),
        ('ParameterOffset','<H'),
        ('DataCount','<H'),
        ('DataOffset','<H'),
        ('SetupCount','<B=len(Setup)/2'),
        ('Reserved3','<B=0'),
        ('SetupLength','_-Setup','SetupCount*2'),
        ('Setup',':'),
    )

class SMBTransaction2Response_Parameters(SMBCommand_Parameters):
    structure = (
        ('TotalParameterCount','<H'),
        ('TotalDataCount','<H'),
        ('Reserved1','<H=0'),
        ('ParameterCount','<H'),
        ('ParameterOffset','<H'),
        ('ParameterDisplacement','<H=0'),
        ('DataCount','<H'),
        ('DataOffset','<H'),
        ('DataDisplacement','<H=0'),
        ('SetupCount','<B=0'),
        ('Reserved2','<B=0'),
        ('SetupLength','_-Setup','SetupCount*2'),
        ('Setup',':'),
    )

class SMBTransaction2_Data(Structure):
    structure = (
#        ('NameLength','_-Name','1'),
#        ('Name',':'),
        ('Pad1Length','_-Pad1','self["Pad1Length"]'),
        ('Pad1',':'),
        ('Trans_ParametersLength','_-Trans_Parameters','self["Trans_ParametersLength"]'),
        ('Trans_Parameters',':'),
        ('Pad2Length','_-Pad2','self["Pad2Length"]'),
        ('Pad2',':'),
        ('Trans_DataLength','_-Trans_Data','self["Trans_DataLength"]'),
        ('Trans_Data',':'),
    )

class SMBTransaction2Response_Data(Structure):
    structure = (
        ('Pad1Length','_-Pad1','self["Pad1Length"]'),
        ('Pad1',':'),
        ('Trans_ParametersLength','_-Trans_Parameters','self["Trans_ParametersLength"]'),
        ('Trans_Parameters',':'),
        ('Pad2Length','_-Pad2','self["Pad2Length"]'),
        ('Pad2',':'),
        ('Trans_DataLength','_-Trans_Data','self["Trans_DataLength"]'),
        ('Trans_Data',':'),
    )

############# SMB_COM_QUERY_INFORMATION (0x08)

class SMBQueryInformation_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('BufferFormat','B=4'),
        ('FileName','z'),
    )
    UnicodeStructure = (
        ('BufferFormat','B=4'),
        ('FileName','u'),
    )


class SMBQueryInformationResponse_Parameters(Structure):
    structure = (
        ('FileAttributes','<H'),
        ('LastWriteTime','<L'),
        ('FileSize','<L'),
        ('Reserved','"0123456789'),
    )

############# SMB_COM_TRANSACTION (0x25)
class SMBTransaction_Parameters(SMBCommand_Parameters):
    structure = (
        ('TotalParameterCount','<H'),
        ('TotalDataCount','<H'),
        ('MaxParameterCount','<H=1024'),
        ('MaxDataCount','<H=65504'),
        ('MaxSetupCount','<B=0'),
        ('Reserved1','<B=0'),
        ('Flags','<H=0'),
        ('Timeout','<L=0'),
        ('Reserved2','<H=0'),
        ('ParameterCount','<H'),
        ('ParameterOffset','<H'),
        ('DataCount','<H'),
        ('DataOffset','<H'),
        ('SetupCount','<B=len(Setup)/2'),
        ('Reserved3','<B=0'),
        ('SetupLength','_-Setup','SetupCount*2'),
        ('Setup',':'),
    )

class SMBTransactionResponse_Parameters(SMBCommand_Parameters):
    structure = (
        ('TotalParameterCount','<H'),
        ('TotalDataCount','<H'),
        ('Reserved1','<H=0'),
        ('ParameterCount','<H'),
        ('ParameterOffset','<H'),
        ('ParameterDisplacement','<H=0'),
        ('DataCount','<H'),
        ('DataOffset','<H'),
        ('DataDisplacement','<H=0'),
        ('SetupCount','<B'),
        ('Reserved2','<B=0'),
        ('SetupLength','_-Setup','SetupCount*2'),
        ('Setup',':'),
    )

# TODO: We should merge these both. But this will require fixing 
# the instances where this structure is used on the client side
class SMBTransaction_SData(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('Name','z'),
        ('Trans_ParametersLength','_-Trans_Parameters'),
        ('Trans_Parameters',':'),
        ('Trans_DataLength','_-Trans_Data'),
        ('Trans_Data',':'),
    )
    UnicodeStructure = (
        ('Pad','B'),
        ('Name','u'),
        ('Trans_ParametersLength','_-Trans_Parameters'),
        ('Trans_Parameters',':'),
        ('Trans_DataLength','_-Trans_Data'),
        ('Trans_Data',':'),
    )

class SMBTransaction_Data(Structure):
    structure = (
        ('NameLength','_-Name'),
        ('Name',':'),
        ('Trans_ParametersLength','_-Trans_Parameters'),
        ('Trans_Parameters',':'),
        ('Trans_DataLength','_-Trans_Data'),
        ('Trans_Data',':'),
    )

class SMBTransactionResponse_Data(Structure):
    structure = (
        ('Trans_ParametersLength','_-Trans_Parameters'),
        ('Trans_Parameters',':'),
        ('Trans_DataLength','_-Trans_Data'),
        ('Trans_Data',':'),
    )

############# SMB_COM_READ_ANDX (0x2E)
class SMBReadAndX_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('Fid','<H'),
        ('Offset','<L'),
        ('MaxCount','<H'),
        ('MinCount','<H=MaxCount'),
        ('_reserved','<L=0xffffffff'),
        ('Remaining','<H=MaxCount'),
        ('HighOffset','<L=0'),
    )

class SMBReadAndX_Parameters2(SMBAndXCommand_Parameters):
    structure = (
        ('Fid','<H'),
        ('Offset','<L'),
        ('MaxCount','<H'),
        ('MinCount','<H=MaxCount'),
        ('_reserved','<L=0xffffffff'),
        ('Remaining','<H=MaxCount'),
    )

class SMBReadAndXResponse_Parameters(SMBAndXCommand_Parameters):
    structure = (
        ('Remaining','<H=0'),
        ('DataMode','<H=0'),
        ('_reserved','<H=0'),
        ('DataCount','<H'),
        ('DataOffset','<H'),
        ('DataCount_Hi','<L'),
        ('_reserved2','6s=""'),
    )

############# SMB_COM_ECHO (0x2B)
class SMBEcho_Data(Structure):
    structure = (
        ('Data',':'),
    )

class SMBEcho_Parameters(Structure):
    structure = (
        ('EchoCount','<H'),
    )

class SMBEchoResponse_Data(Structure):
    structure = (
        ('Data',':'),
    )

class SMBEchoResponse_Parameters(Structure):
    structure = (
        ('SequenceNumber','<H=1'),
    )

############# SMB_COM_QUERY_INFORMATION_DISK (0x80)
class SMBQueryInformationDiskResponse_Parameters(Structure):
    structure = (
        ('TotalUnits','<H'),
        ('BlocksPerUnit','<H'),
        ('BlockSize','<H'),
        ('FreeUnits','<H'),
        ('Reserved','<H=0'),
    )


############# SMB_COM_LOGOFF_ANDX (0x74)
class SMBLogOffAndX(SMBAndXCommand_Parameters):
    strucure = ()

############# SMB_COM_CLOSE (0x04)
class SMBClose_Parameters(SMBCommand_Parameters):
   structure = (
        ('FID','<H'),
        ('Time','<L=0'),
   )

############# SMB_COM_CREATE_DIRECTORY (0x00)
class SMBCreateDirectory_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('BufferFormat','<B=4'),
        ('DirectoryName','z'),
    )
    UnicodeStructure = (
        ('BufferFormat','<B=4'),
        ('DirectoryName','u'),
    )

############# SMB_COM_DELETE (0x06)
class SMBDelete_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('BufferFormat','<B=4'),
        ('FileName','z'),
    )
    UnicodeStructure = (
        ('BufferFormat','<B=4'),
        ('FileName','u'),
    )

class SMBDelete_Parameters(Structure):
    structure = (
        ('SearchAttributes','<H'),
    )

############# SMB_COM_DELETE_DIRECTORY (0x01)
class SMBDeleteDirectory_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('BufferFormat','<B=4'),
        ('DirectoryName','z'),
    )
    UnicodeStructure = (
        ('BufferFormat','<B=4'),
        ('DirectoryName','u'),
    )

############# SMB_COM_RENAME (0x07)
class SMBRename_Parameters(SMBCommand_Parameters):
    structure = (
        ('SearchAttributes','<H'),
    )

class SMBRename_Data(AsciiOrUnicodeStructure):
    AsciiStructure = (
        ('BufferFormat1','<B=4'),
        ('OldFileName','z'),
        ('BufferFormat2','<B=4'),
        ('NewFileName','z'),
    )
    UnicodeStructure = (
        ('BufferFormat1','<B=4'),
        ('OldFileName','u'),
        ('BufferFormat2','<B=4'),
        ('Pad','B'),
        ('NewFileName','u'),
    )


############# SMB_COM_OPEN (0x02)
class SMBOpen_Parameters(SMBCommand_Parameters):
    structure = (
        ('DesiredAccess','<H=0'),
        ('SearchAttributes','<H=0'),
    )

class SMBOpen_Data(Structure):
    structure = (
        ('FileNameFormat','"\x04'),
        ('FileName','z'),
    )

class SMBOpenResponse_Parameters(SMBCommand_Parameters):
    structure = (
        ('Fid','<H=0'),
        ('FileAttributes','<H=0'),
        ('LastWriten','<L=0'),
        ('FileSize','<L=0'),
        ('GrantedAccess','<H=0'),
    )

############# EXTENDED SECURITY CLASSES
class SMBExtended_Security_Parameters(Structure):
    structure = (
        ('DialectIndex','<H'),
        ('SecurityMode','<B'),
        ('MaxMpxCount','<H'),
        ('MaxNumberVcs','<H'),
        ('MaxBufferSize','<L'),
        ('MaxRawSize','<L'),
        ('SessionKey','<L'),
        ('Capabilities','<L'),
        ('LowDateTime','<L'),
        ('HighDateTime','<L'),
        ('ServerTimeZone','<H'),
        ('ChallengeLength','<B'),
    )

class SMBExtended_Security_Data(Structure):
    structure = (
        ('ServerGUID','16s'),
        ('SecurityBlob',':'),
    )

class SMBNTLMDialect_Parameters(Structure):
    structure = (
        ('DialectIndex','<H'),
        ('SecurityMode','<B'),
        ('MaxMpxCount','<H'),
        ('MaxNumberVcs','<H'),
        ('MaxBufferSize','<L'),
        ('MaxRawSize','<L'),
        ('SessionKey','<L'),
        ('Capabilities','<L'),
        ('LowDateTime','<L'),
        ('HighDateTime','<L'),
        ('ServerTimeZone','<H'),
        ('ChallengeLength','<B'),
    )

class SMBNTLMDialect_Data(Structure):
    structure = (
        ('ChallengeLength','_-Challenge','self["ChallengeLength"]'),
        ('Challenge',':'),
        ('Payload',':'),
# For some reason on an old Linux this field is not present, we have to check this out. There must be a flag stating this.
        ('DomainName','_'),
        ('ServerName','_'),
    )
    def __init__(self,data = None, alignment = 0):
         Structure.__init__(self,data,alignment)
         #self['ChallengeLength']=8
         
    def fromString(self,data):
        Structure.fromString(self,data)
        self['DomainName'] = '' 
        self['ServerName'] = ''
           
class SMB:
    # SMB Command Codes
    SMB_COM_CREATE_DIRECTORY                = 0x00
    SMB_COM_DELETE_DIRECTORY                = 0x01
    SMB_COM_OPEN                            = 0x02
    SMB_COM_CREATE                          = 0x03
    SMB_COM_CLOSE                           = 0x04
    SMB_COM_FLUSH                           = 0x05
    SMB_COM_DELETE                          = 0x06
    SMB_COM_RENAME                          = 0x07
    SMB_COM_QUERY_INFORMATION               = 0x08
    SMB_COM_SET_INFORMATION                 = 0x09
    SMB_COM_READ                            = 0x0A
    SMB_COM_WRITE                           = 0x0B
    SMB_COM_LOCK_BYTE_RANGE                 = 0x0C
    SMB_COM_UNLOCK_BYTE_RANGE               = 0x0D
    SMB_COM_CREATE_TEMPORARY                = 0x0E
    SMB_COM_CREATE_NEW                      = 0x0F
    SMB_COM_CHECK_DIRECTORY                 = 0x10
    SMB_COM_PROCESS_EXIT                    = 0x11
    SMB_COM_SEEK                            = 0x12
    SMB_COM_LOCK_AND_READ                   = 0x13
    SMB_COM_WRITE_AND_UNLOCK                = 0x14
    SMB_COM_READ_RAW                        = 0x1A
    SMB_COM_READ_MPX                        = 0x1B
    SMB_COM_READ_MPX_SECONDARY              = 0x1C
    SMB_COM_WRITE_RAW                       = 0x1D
    SMB_COM_WRITE_MPX                       = 0x1E
    SMB_COM_WRITE_MPX_SECONDARY             = 0x1F
    SMB_COM_WRITE_COMPLETE                  = 0x20
    SMB_COM_QUERY_SERVER                    = 0x21
    SMB_COM_SET_INFORMATION2                = 0x22
    SMB_COM_QUERY_INFORMATION2              = 0x23
    SMB_COM_LOCKING_ANDX                    = 0x24
    SMB_COM_TRANSACTION                     = 0x25
    SMB_COM_TRANSACTION_SECONDARY           = 0x26
    SMB_COM_IOCTL                           = 0x27
    SMB_COM_IOCTL_SECONDARY                 = 0x28
    SMB_COM_COPY                            = 0x29
    SMB_COM_MOVE                            = 0x2A
    SMB_COM_ECHO                            = 0x2B
    SMB_COM_WRITE_AND_CLOSE                 = 0x2C
    SMB_COM_OPEN_ANDX                       = 0x2D
    SMB_COM_READ_ANDX                       = 0x2E
    SMB_COM_WRITE_ANDX                      = 0x2F
    SMB_COM_NEW_FILE_SIZE                   = 0x30
    SMB_COM_CLOSE_AND_TREE_DISC             = 0x31
    SMB_COM_TRANSACTION2                    = 0x32
    SMB_COM_TRANSACTION2_SECONDARY          = 0x33
    SMB_COM_FIND_CLOSE2                     = 0x34
    SMB_COM_FIND_NOTIFY_CLOSE               = 0x35
    # Used by Xenix/Unix 0x60 - 0x6E 
    SMB_COM_TREE_CONNECT                    = 0x70
    SMB_COM_TREE_DISCONNECT                 = 0x71
    SMB_COM_NEGOTIATE                       = 0x72
    SMB_COM_SESSION_SETUP_ANDX              = 0x73
    SMB_COM_LOGOFF_ANDX                     = 0x74
    SMB_COM_TREE_CONNECT_ANDX               = 0x75
    SMB_COM_QUERY_INFORMATION_DISK          = 0x80
    SMB_COM_SEARCH                          = 0x81
    SMB_COM_FIND                            = 0x82
    SMB_COM_FIND_UNIQUE                     = 0x83
    SMB_COM_FIND_CLOSE                      = 0x84
    SMB_COM_NT_TRANSACT                     = 0xA0
    SMB_COM_NT_TRANSACT_SECONDARY           = 0xA1
    SMB_COM_NT_CREATE_ANDX                  = 0xA2
    SMB_COM_NT_CANCEL                       = 0xA4
    SMB_COM_NT_RENAME                       = 0xA5
    SMB_COM_OPEN_PRINT_FILE                 = 0xC0
    SMB_COM_WRITE_PRINT_FILE                = 0xC1
    SMB_COM_CLOSE_PRINT_FILE                = 0xC2
    SMB_COM_GET_PRINT_QUEUE                 = 0xC3
    SMB_COM_READ_BULK                       = 0xD8
    SMB_COM_WRITE_BULK                      = 0xD9
    SMB_COM_WRITE_BULK_DATA                 = 0xDA

    # TRANSACT codes
    TRANS_TRANSACT_NMPIPE                   = 0x26

    # TRANSACT2 codes
    TRANS2_FIND_FIRST2                      = 0x0001
    TRANS2_FIND_NEXT2                       = 0x0002
    TRANS2_QUERY_FS_INFORMATION             = 0x0003
    TRANS2_QUERY_PATH_INFORMATION           = 0x0005
    TRANS2_QUERY_FILE_INFORMATION           = 0x0007
    TRANS2_SET_FILE_INFORMATION             = 0x0008
    TRANS2_SET_PATH_INFORMATION             = 0x0006

    # Security Share Mode (Used internally by SMB class)
    SECURITY_SHARE_MASK                     = 0x01
    SECURITY_SHARE_SHARE                    = 0x00
    SECURITY_SHARE_USER                     = 0x01
    SECURITY_SIGNATURES_ENABLED             = 0X04
    SECURITY_SIGNATURES_REQUIRED            = 0X08
    
    # Security Auth Mode (Used internally by SMB class)
    SECURITY_AUTH_MASK                      = 0x02
    SECURITY_AUTH_ENCRYPTED                 = 0x02
    SECURITY_AUTH_PLAINTEXT                 = 0x00

    # Raw Mode Mask (Used internally by SMB class. Good for dialect up to and including LANMAN2.1)
    RAW_READ_MASK                           = 0x01
    RAW_WRITE_MASK                          = 0x02

    # Capabilities Mask (Used internally by SMB class. Good for dialect NT LM 0.12)
    CAP_RAW_MODE                            = 0x00000001
    CAP_MPX_MODE                            = 0x0002
    CAP_UNICODE                             = 0x0004
    CAP_LARGE_FILES                         = 0x0008
    CAP_EXTENDED_SECURITY                   = 0x80000000
    CAP_USE_NT_ERRORS                       = 0x40
    CAP_NT_SMBS                             = 0x10
    CAP_LARGE_READX                         = 0x00004000
    CAP_LARGE_WRITEX                        = 0x00008000

    # Flags1 Mask
    FLAGS1_LOCK_AND_READ_OK                 = 0x01
    FLAGS1_PATHCASELESS                     = 0x08
    FLAGS1_CANONICALIZED_PATHS              = 0x10
    FLAGS1_REPLY                            = 0x80

    # Flags2 Mask
    FLAGS2_LONG_NAMES                       = 0x0001
    FLAGS2_EAS                              = 0x0002
    FLAGS2_SMB_SECURITY_SIGNATURE           = 0x0004
    FLAGS2_IS_LONG_NAME                     = 0x0040
    FLAGS2_DFS                              = 0x1000
    FLAGS2_PAGING_IO                        = 0x2000
    FLAGS2_NT_STATUS                        = 0x4000
    FLAGS2_UNICODE                          = 0x8000
    FLAGS2_COMPRESSED                       = 0x0008
    FLAGS2_SMB_SECURITY_SIGNATURE_REQUIRED  = 0x0010
    FLAGS2_EXTENDED_SECURITY                = 0x0800
    
    # Dialect's Security Mode flags
    NEGOTIATE_USER_SECURITY                 = 0x01
    NEGOTIATE_ENCRYPT_PASSWORDS             = 0x02
    NEGOTIATE_SECURITY_SIGNATURE_ENABLE     = 0x04
    NEGOTIATE_SECURITY_SIGNATURE_REQUIRED   = 0x08

    # Tree Connect AndX Response optionalSuppor flags
    SMB_SUPPORT_SEARCH_BITS                 = 0x01
    SMB_SHARE_IS_IN_DFS                     = 0x02 



    def __init__(self, remote_name, remote_host, my_name = None, host_type = nmb.TYPE_SERVER, sess_port = 445, timeout=None, UDP = 0, session = None, negPacket = None):
        # The uid attribute will be set when the client calls the login() method
        self._uid = 0
        self.__server_name = ''
        self.__server_os = ''
        self.__server_lanman = ''
        self.__server_domain = ''
        self.__remote_name = string.upper(remote_name)
        self.__remote_host = remote_host
        self.__is_pathcaseless = 0
        self.__isNTLMv2 = True
        # Negotiate Protocol Result, used everywhere
        # Could be extended or not, flags should be checked before 
        self._dialect_data = 0
        self._dialect_parameters = 0
        self._action = 0
        self._sess = None
        self.encrypt_passwords = True
        self.tid = 0
        self.fid = 0
        
        # Signing stuff
        self._SignSequenceNumber = 0
        self._SigningSessionKey = ''
        self._SigningChallengeResponse = ''
        self._SignatureEnabled = False
        self._SignatureVerificationEnabled = False
        self._SignatureRequired = False

        # Base flags
        self.__flags1 = 0
        self.__flags2 = 0

        if timeout==None:
            self.__timeout = 10
        else:
            self.__timeout = timeout

        if session is None:
            if not my_name:
                my_name = socket.gethostname()
                i = string.find(my_name, '.')
                if i > -1:
                    my_name = my_name[:i]

            # If port 445 and the name sent is *SMBSERVER we're setting the name to the IP. This is to help some old applications still believing 
            # *SMSBSERVER will work against modern OSes. If port is NETBIOS_SESSION_PORT the user better know about *SMBSERVER's limitations
            if sess_port == 445 and remote_name == '*SMBSERVER':
               self.__remote_name = remote_host

            if UDP:
                self._sess = nmb.NetBIOSUDPSession(my_name, remote_name, remote_host, host_type, sess_port, self.__timeout)
            else:
                self._sess = nmb.NetBIOSTCPSession(my_name, remote_name, remote_host, host_type, sess_port, self.__timeout)

                # Initialize session values (_dialect_data and _dialect_parameters)
                self.neg_session()

                # Call login() without any authentication information to 
                # setup a session if the remote server
                # is in share mode.
                if (self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SHARE_MASK) == SMB.SECURITY_SHARE_SHARE:
                    self.login('', '')
        else:
            self._sess = session
            self.neg_session(negPacket = negPacket)
            # Call login() without any authentication information to 
            # setup a session if the remote server
            # is in share mode.
            if (self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SHARE_MASK) == SMB.SECURITY_SHARE_SHARE:
                self.login('', '')


    def ntlm_supported(self):
        return False

    def get_remote_name(self):
        return self.__remote_name

    def get_remote_host(self):
        return self.__remote_host

    def get_flags(self):
        return self.__flags1, self.__flags2

    def set_flags(self, flags1=None, flags2=None):
        if flags1 is not None:
           self.__flags1 = flags1
        if flags2 is not None:
           self.__flags2 = flags2

    def set_timeout(self, timeout):
        self.__timeout = timeout

    def get_timeout(self):
        return self.__timeout

    @contextmanager
    def use_timeout(self, timeout):
        prev_timeout = self.set_timeout(timeout)
        try:
            yield
        finally:
            self.set_timeout(prev_timeout)

    def get_session(self):        
        return self._sess
    
    def get_tid(self):
        return self.tid

    def get_fid(self):
        return self.fid
   
    def isGuestSession(self):
        return self._action & SMB_SETUP_GUEST 
 
    def doesSupportNTLMv2(self):
        return self.__isNTLMv2

    def __del__(self):
        if self._sess:
            self._sess.close()

    def recvSMB(self):
        r = self._sess.recv_packet(self.__timeout)
        return NewSMBPacket(data = r.get_trailer())
    
    def recv_packet(self):
        r = self._sess.recv_packet(self.__timeout)
        return SMBPacket(r.get_trailer())
    
    def __decode_trans(self, params, data):
        totparamcnt, totdatacnt, _, paramcnt, paramoffset, paramds, datacnt, dataoffset, datads, setupcnt = unpack('<HHHHHHHHHB', params[:19])
        if paramcnt + paramds < totparamcnt or datacnt + datads < totdatacnt:
            has_more = 1
        else:
            has_more = 0
        paramoffset = paramoffset - 55 - setupcnt * 2
        dataoffset = dataoffset - 55 - setupcnt * 2
        return has_more, params[20:20 + setupcnt * 2], data[paramoffset:paramoffset + paramcnt], data[dataoffset:dataoffset + datacnt]

    # TODO: Move this to NewSMBPacket, it belongs there
    def signSMB(self, packet, signingSessionKey, signingChallengeResponse):
        # This logic MUST be applied for messages sent in response to any of the higher-layer actions and in
        # compliance with the message sequencing rules.
        #  * The client or server that sends the message MUST provide the 32-bit sequence number for this
        #    message, as specified in sections 3.2.4.1 and 3.3.4.1.
        #  * The SMB_FLAGS2_SMB_SECURITY_SIGNATURE flag in the header MUST be set.
        #  * To generate the signature, a 32-bit sequence number is copied into the 
        #    least significant 32 bits of the SecuritySignature field and the remaining 
        #    4 bytes are set to 0x00.
        #  * The MD5 algorithm, as specified in [RFC1321], MUST be used to generate a hash of the SMB
        #    message from the start of the SMB Header, which is defined as follows.
        #    CALL MD5Init( md5context )
        #    CALL MD5Update( md5context, Connection.SigningSessionKey )
        #    CALL MD5Update( md5context, Connection.SigningChallengeResponse )
        #    CALL MD5Update( md5context, SMB message )
        #    CALL MD5Final( digest, md5context )
        #    SET signature TO the first 8 bytes of the digest
        # The resulting 8-byte signature MUST be copied into the SecuritySignature field of the SMB Header,
        # after which the message can be transmitted.

        #print "seq(%d) signingSessionKey %r, signingChallengeResponse %r" % (self._SignSequenceNumber, signingSessionKey, signingChallengeResponse)
        packet['SecurityFeatures'] = struct.pack('<q',self._SignSequenceNumber)
        # Sign with the sequence
        m = hashlib.md5()
        m.update( signingSessionKey )
        m.update( signingChallengeResponse )
        m.update( str(packet) )
        # Replace sequence with acual hash
        packet['SecurityFeatures'] = m.digest()[:8]
        if self._SignatureVerificationEnabled:
           self._SignSequenceNumber +=1
        else:
           self._SignSequenceNumber +=2


    def checkSignSMB(self, packet, signingSessionKey, signingChallengeResponse):
        # Let's check
        signature = packet['SecurityFeatures']
        #print "Signature received: %r " % signature
        self.signSMB(packet, signingSessionKey, signingChallengeResponse) 
        #print "Signature calculated: %r" % packet['SecurityFeatures']
        if self._SignatureVerificationEnabled is not True:
           self._SignSequenceNumber -= 1
        return packet['SecurityFeatures'] == signature
         
    def sendSMB(self,smb):
        smb['Uid'] = self._uid
        smb['Pid'] = os.getpid()
        smb['Flags1'] |= self.__flags1
        smb['Flags2'] |= self.__flags2
        if self._SignatureEnabled:
            smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE
            self.signSMB(smb, self._SigningSessionKey, self._SigningChallengeResponse)
        self._sess.send_packet(str(smb))

    # Should be gone soon. Not used anymore within the library. DON'T use it!
    # Use sendSMB instead (and build the packet with NewSMBPacket)
    def send_smb(self,s):
        s.set_uid(self._uid)
        s.set_pid(os.getpid())
        self._sess.send_packet(s.rawData())

    def __send_smb_packet(self, cmd, flags, flags2, tid, mid, params = '', data = ''):
        smb = NewSMBPacket()
        smb['Flags1'] = flags
        smb['Flags2'] = flags2
        smb['Tid'] = tid
        smb['Mid'] = mid
        cmd = SMBCommand(cmd)
        smb.addCommand(cmd)

        cmd['Parameters'] = params
        cmd['Data'] = data
        self.sendSMB(smb)

    def isValidAnswer(self, s, cmd):
        while 1:
            if s.rawData():
                if s.get_command() == cmd:
                    if s.get_error_class() == 0x00 and s.get_error_code() == 0x00:
                        return 1
                    else:
                        raise SessionError, ( "SMB Library Error", s.get_error_class()+ (s.get_reserved() << 8), s.get_error_code() , s.get_flags2() & SMB.FLAGS2_NT_STATUS )
                else:
                    break
        return 0

    def neg_session(self, extended_security = True, negPacket = None):
        def parsePacket(smb):
            if smb.isValidAnswer(SMB.SMB_COM_NEGOTIATE):
                sessionResponse = SMBCommand(smb['Data'][0])
                self._dialects_parameters = SMBNTLMDialect_Parameters(sessionResponse['Parameters'])
                self._dialects_data = SMBNTLMDialect_Data()
                self._dialects_data['ChallengeLength'] = self._dialects_parameters['ChallengeLength']
                self._dialects_data.fromString(sessionResponse['Data'])
                if self._dialects_parameters['Capabilities'] & SMB.CAP_EXTENDED_SECURITY:
                    # Whether we choose it or it is enforced by the server, we go for extended security
                    self._dialects_parameters = SMBExtended_Security_Parameters(sessionResponse['Parameters'])
                    self._dialects_data = SMBExtended_Security_Data(sessionResponse['Data'])
                    # Let's setup some variable for later use
                    if self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SIGNATURES_REQUIRED:
                         self._SignatureRequired = True

                    # Interestingly, the security Blob might be missing sometimes.
                    #spnego = SPNEGO_NegTokenInit(self._dialects_data['SecurityBlob'])
                    #for i in spnego['MechTypes']:
                    #      print "Mech Found: %s" % MechTypes[i]
                    return 1

                # If not, let's try the old way
                else:
                    if self._dialects_data['ServerName'] is not None:
                        self.__server_name = self._dialects_data['ServerName']

                    if self._dialects_parameters['DialectIndex'] == 0xffff:
                        raise UnsupportedFeature,"Remote server does not know NT LM 0.12"
                    self.__is_pathcaseless = smb['Flags1'] & SMB.FLAGS1_PATHCASELESS
                    return 1
            else:
                return 0

        if negPacket is None:
            smb = NewSMBPacket()
            negSession = SMBCommand(SMB.SMB_COM_NEGOTIATE)
            if extended_security == True:
                smb['Flags2']=SMB.FLAGS2_EXTENDED_SECURITY 
            negSession['Data'] = '\x02NT LM 0.12\x00'
            smb.addCommand(negSession)
            self.sendSMB(smb)

            while 1:
                smb = self.recvSMB()
                return parsePacket(smb)
        else:
            
            return parsePacket( NewSMBPacket( data = negPacket))


    def tree_connect(self, path, password = '', service = SERVICE_ANY):
        print "[MS-CIFS] This is an original Core Protocol command.\nThis command has been deprecated.\nClient Implementations SHOULD use SMB_COM_TREE_CONNECT_ANDX"

        # return 0x800
        if password:
            # Password is only encrypted if the server passed us an "encryption" during protocol dialect
            if self._dialects_parameters['ChallengeLength'] > 0:
                # this code is untested
                password = self.get_ntlmv1_response(ntlm.compute_lmhash(password))

        if not unicode_support:
            if unicode_convert:
                path = str(path)
            else:
                raise Exception('SMB: Can\t conver path from unicode!')

        smb = NewSMBPacket()
        smb['Flags1']  = SMB.FLAGS1_PATHCASELESS
        
        treeConnect = SMBCommand(SMB.SMB_COM_TREE_CONNECT)
        treeConnect['Parameters'] = SMBTreeConnect_Parameters()
        treeConnect['Data']       = SMBTreeConnect_Data()
        treeConnect['Data']['Path'] = path.upper()
        treeConnect['Data']['Password'] = password
        treeConnect['Data']['Service'] = service

        smb.addCommand(treeConnect)

        self.sendSMB(smb)

        while 1:
            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_TREE_CONNECT):
                # XXX Here we are ignoring the rest of the response
                return smb['Tid']
            return smb['Tid']

    def get_uid(self):
        return self._uid

    def set_uid(self, uid):
        self._uid = uid

    def tree_connect_andx(self, path, password = None, service = SERVICE_ANY, smb_packet=None):
        if password:
            # Password is only encrypted if the server passed us an "encryption" during protocol dialect
            if self._dialects_parameters['ChallengeLength'] > 0:
                # this code is untested
                password = self.get_ntlmv1_response(ntlm.compute_lmhash(password))
        else:
            password = '\x00'

        if not unicode_support:
            if unicode_convert:
                path = str(path)
            else:
                raise Exception('SMB: Can\t convert path from unicode!')

        if smb_packet == None:
            smb = NewSMBPacket()
            smb['Flags1']  = SMB.FLAGS1_PATHCASELESS
        else:
            smb = smb_packet
        
        treeConnect = SMBCommand(SMB.SMB_COM_TREE_CONNECT_ANDX)
        treeConnect['Parameters'] = SMBTreeConnectAndX_Parameters()
        treeConnect['Data']       = SMBTreeConnectAndX_Data()
        treeConnect['Parameters']['PasswordLength'] = len(password)
        treeConnect['Data']['Password'] = password
        treeConnect['Data']['Path'] = path.upper()
        treeConnect['Data']['Service'] = service

        smb.addCommand(treeConnect)

        # filename = "\PIPE\epmapper"

        # ntCreate = SMBCommand(SMB.SMB_COM_NT_CREATE_ANDX)
        # ntCreate['Parameters'] = SMBNtCreateAndX_Parameters()
        # ntCreate['Data']       = SMBNtCreateAndX_Data()
        # ntCreate['Parameters']['FileNameLength'] = len(filename)
        # ntCreate['Parameters']['CreateFlags'] = 0
        # ntCreate['Parameters']['AccessMask'] = 0x3
        # ntCreate['Parameters']['CreateOptions'] = 0x0
        # ntCreate['Data']['FileName'] = filename

        # smb.addCommand(ntCreate)
        self.sendSMB(smb)

        while 1:
            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_TREE_CONNECT_ANDX):
                # XXX Here we are ignoring the rest of the response
                self.tid = smb['Tid']
                return self.tid
            self.tid = smb['Tid']
            return self.tid

    # backwars compatibility
    connect_tree = tree_connect_andx

    def getDialect(self):
        return SMB_DIALECT

    def get_server_name(self):
        #return self._dialects_data['ServerName']
        return self.__server_name

    def get_session_key(self):
        return self._dialects_parameters['SessionKey']

    def get_encryption_key(self):
        if self._dialects_data.fields.has_key('Challenge'):
            return self._dialects_data['Challenge']
        else:
            return None

    def get_server_time(self):
        timestamp = self._dialects_parameters['HighDateTime']
        timestamp <<= 32
        timestamp |= self._dialects_parameters['LowDateTime']
        timestamp -= 116444736000000000
        timestamp /= 10000000
        d = datetime.datetime.utcfromtimestamp(timestamp)
        return d.strftime("%a, %d %b %Y %H:%M:%S GMT")

    def disconnect_tree(self, tid):
        smb = NewSMBPacket()
        smb['Tid']  = tid
        smb.addCommand(SMBCommand(SMB.SMB_COM_TREE_DISCONNECT))
        self.sendSMB(smb)

        smb = self.recvSMB()

    def open(self, tid, filename, open_mode, desired_access):
        filename = string.replace(filename,'/', '\\')
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_LONG_NAMES
        smb['Tid']    = tid

        openFile = SMBCommand(SMB.SMB_COM_OPEN)
        openFile['Parameters'] = SMBOpen_Parameters()
        openFile['Parameters']['DesiredAccess']    = desired_access
        openFile['Parameters']['OpenMode']         = open_mode
        openFile['Parameters']['SearchAttributes'] = ATTR_READONLY | ATTR_HIDDEN | ATTR_ARCHIVE
        openFile['Data']       = SMBOpen_Data()
        openFile['Data']['FileName'] = filename
        
        smb.addCommand(openFile)

        self.sendSMB(smb)
        
        smb = self.recvSMB()
        if smb.isValidAnswer(SMB.SMB_COM_OPEN):
            # XXX Here we are ignoring the rest of the response
            openFileResponse   = SMBCommand(smb['Data'][0])
            openFileParameters = SMBOpenResponse_Parameters(openFileResponse['Parameters'])

            return (
                openFileParameters['Fid'],
                openFileParameters['FileAttributes'],
                openFileParameters['LastWriten'],
                openFileParameters['FileSize'],
                openFileParameters['GrantedAccess'],
            )
        
    def open_andx(self, tid, filename, open_mode, desired_access):
        filename = string.replace(filename,'/', '\\')
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_LONG_NAMES
        smb['Tid']    = tid

        openFile = SMBCommand(SMB.SMB_COM_OPEN_ANDX)
        openFile['Parameters'] = SMBOpenAndX_Parameters()
        openFile['Parameters']['DesiredAccess']    = desired_access
        openFile['Parameters']['OpenMode']         = open_mode
        openFile['Parameters']['SearchAttributes'] = ATTR_READONLY | ATTR_HIDDEN | ATTR_ARCHIVE
        openFile['Data']       = SMBOpenAndX_Data()
        openFile['Data']['FileName'] = filename
        
        smb.addCommand(openFile)

        self.sendSMB(smb)
        
        smb = self.recvSMB()
        if smb.isValidAnswer(SMB.SMB_COM_OPEN_ANDX):
            # XXX Here we are ignoring the rest of the response
            openFileResponse   = SMBCommand(smb['Data'][0])
            openFileParameters = SMBOpenAndXResponse_Parameters(openFileResponse['Parameters'])

            return (
                openFileParameters['Fid'],
                openFileParameters['FileAttributes'],
                openFileParameters['LastWriten'],
                openFileParameters['FileSize'],
                openFileParameters['GrantedAccess'],
                openFileParameters['FileType'],
                openFileParameters['IPCState'],
                openFileParameters['Action'],
                openFileParameters['ServerFid'],
            )
        
    def close(self, tid, fid):
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_LONG_NAMES
        smb['Tid']    = tid

        closeFile = SMBCommand(SMB.SMB_COM_CLOSE)
        closeFile['Parameters'] = SMBClose_Parameters()
        closeFile['Parameters']['FID']    = fid
        smb.addCommand(closeFile)

        self.sendSMB(smb)
        smb = self.recvSMB()
        if smb.isValidAnswer(SMB.SMB_COM_CLOSE):
           return 1
        return 0

    def send_trans(self, tid, setup, name, param, data, noAnswer = 0):
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_LONG_NAMES
        smb['Tid']    = tid

        transCommand = SMBCommand(SMB.SMB_COM_TRANSACTION)
        transCommand['Parameters'] = SMBTransaction_Parameters()
        transCommand['Data'] = SMBTransaction_Data()

        transCommand['Parameters']['Setup'] = setup
        transCommand['Parameters']['TotalParameterCount'] = len(param) 
        transCommand['Parameters']['TotalDataCount'] = len(data)

        transCommand['Parameters']['ParameterCount'] = len(param)
        transCommand['Parameters']['ParameterOffset'] = 32+3+28+len(setup)+len(name)

        transCommand['Parameters']['DataCount'] = len(data)
        transCommand['Parameters']['DataOffset'] = transCommand['Parameters']['ParameterOffset'] + len(param)

        transCommand['Data']['Name'] = name
        transCommand['Data']['Trans_Parameters'] = param
        transCommand['Data']['Trans_Data'] = data

        if noAnswer:
           transCommand['Parameters']['Flags'] = TRANS_NO_RESPONSE
      
        smb.addCommand(transCommand)
        self.sendSMB(smb)

    def trans2(self, tid, setup, name, param, data):
        data_len = len(data)
        name_len = len(name)
        param_len = len(param)
        setup_len = len(setup)

        assert setup_len & 0x01 == 0

        param_offset = name_len + setup_len + 63
        data_offset = param_offset + param_len
            
        self.__send_smb_packet(SMB.SMB_COM_TRANSACTION2, self.__is_pathcaseless, SMB.FLAGS2_LONG_NAMES, tid, 0, pack('<HHHHBBHLHHHHHBB', param_len, data_len, 1024, self._dialects_parameters['MaxBufferSize'], 0, 0, 0, 0, 0, param_len, param_offset, data_len, data_offset, setup_len / 2, 0) + setup, name  + param + data)

    def query_file_info(self, tid, fid):
        self.trans2(tid, '\x07\x00', '\x00', pack('<HH', fid, 0x107), '')

        while 1:
            s = self.recv_packet()
            if self.isValidAnswer(s,SMB.SMB_COM_TRANSACTION2):
                f1, f2 = unpack('<LL', s.get_buffer()[53:53+8])
                return (f2 & 0xffffffffL) << 32 | f1

    def __nonraw_retr_file(self, tid, fid, offset, datasize, callback):
        if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_READX) and self._SignatureEnabled is False:
            max_buf_size = 65000
        else:
            max_buf_size = self._dialects_parameters['MaxBufferSize'] & ~0x3ff  # Read in multiple KB blocks

        read_offset = offset
        while read_offset < datasize:
            data = self.read_andx(tid, fid, read_offset, max_buf_size)

            callback(data)
            read_offset += len(data)

    def __raw_retr_file(self, tid, fid, offset, datasize, callback):
        print "[MS-CIFS] This command was introduced in the CorePlus dialect, but is often listed as part of the LAN Manager 1.0 dialect.\nThis command has been deprecated.\nClients SHOULD use SMB_COM_READ_ANDX"

        max_buf_size = self._dialects_parameters['MaxBufferSize'] & ~0x3ff  # Write in multiple KB blocks
        read_offset = offset
        while read_offset < datasize:
            data = self.read_raw(tid, fid, read_offset, 0xffff)
            if not data:
                # No data returned. Need to send SMB_COM_READ_ANDX to find out what is the error.
                data = self.read_andx(tid, fid, read_offset, max_buf_size)

            callback(data)
            read_offset += len(data)

    def __nonraw_stor_file(self, tid, fid, offset, datasize, callback):
        if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_WRITEX) and self._SignatureEnabled is False:
            max_buf_size = 65000
        else:
            max_buf_size = self._dialects_parameters['MaxBufferSize'] & ~0x3ff  # Write in multiple KB blocks

        write_offset = offset
        while 1:
            data = callback(max_buf_size)
            if not data:
                break

            smb = self.write_andx(tid,fid,data, write_offset)
            writeResponse   = SMBCommand(smb['Data'][0])
            writeResponseParameters = SMBWriteAndXResponse_Parameters(writeResponse['Parameters'])
            write_offset += writeResponseParameters['Count']

    def __raw_stor_file(self, tid, fid, offset, datasize, callback):
        print "[MS-CIFS] This command was introduced in the CorePlus dialect, but is often listed as part of the LAN Manager 1.0 dialect.\nThis command has been deprecated.\nClients SHOULD use SMB_COM_WRITE_ANDX"
        write_offset = offset
        while 1:
            max_raw_size = self._dialects_parameters['MaxRawSize']
            # Due to different dialects interpretation of MaxRawSize, we're limiting it to 0xffff
            if max_raw_size > 65535:
               max_raw_size = 65535
            read_data = callback(max_raw_size)

            if not read_data:
                break
            read_len = len(read_data)
            self.__send_smb_packet(SMB.SMB_COM_WRITE_RAW, 0, 0, tid, 0, pack('<HHHLLHLHH', fid, read_len, 0, write_offset, 0, 0, 0, 0, 59), '')
            while 1:
                s = self.recv_packet()
                if self.isValidAnswer(s,SMB.SMB_COM_WRITE_RAW):
                    self._sess.send_packet(read_data)
                    write_offset = write_offset + read_len
                    break

    def get_server_domain(self):
        return self.__server_domain

    def get_server_os(self):
        return self.__server_os

    def set_server_os(self, os):
        self.__server_os = os

    def get_server_lanman(self):
        return self.__server_lanman

    def is_login_required(self):
        # Login is required if share mode is user. 
        # Otherwise only public services or services in share mode
        # are allowed.
        return (self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SHARE_MASK) == SMB.SECURITY_SHARE_USER

    def get_ntlmv1_response(self, key):
        challenge = self._dialects_data['Challenge']
        return ntlm.get_ntlmv1_response(key, challenge)

    def login_extended(self, user, password, domain = '', lmhash = '', nthash = '', use_ntlmv2 = True ):
        # Once everything's working we should join login methods into a single one
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY 
        # Are we required to sign SMB? If so we do it, if not we skip it
        if self._SignatureRequired: 
           smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE
          

        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)
        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()
        sessionSetup['Data']       = SMBSessionSetupAndX_Extended_Data()

        sessionSetup['Parameters']['MaxBufferSize']        = 61440
        sessionSetup['Parameters']['MaxMpxCount']          = 2
        sessionSetup['Parameters']['VcNumber']             = 1
        sessionSetup['Parameters']['SessionKey']           = 0
        sessionSetup['Parameters']['Capabilities']         = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE | SMB.CAP_LARGE_READX | SMB.CAP_LARGE_WRITEX


        # Let's build a NegTokenInit with the NTLMSSP
        # TODO: In the future we should be able to choose different providers

        blob = SPNEGO_NegTokenInit() 

        # NTLMSSP
        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]
        auth = ntlm.getNTLMSSPType1('',domain,self._SignatureRequired, use_ntlmv2 = use_ntlmv2)
        blob['MechToken'] = str(auth)
        
        sessionSetup['Parameters']['SecurityBlobLength']  = len(blob)
        sessionSetup['Parameters'].getData()
        sessionSetup['Data']['SecurityBlob']       = blob.getData()

        # Fake Data here, don't want to get us fingerprinted
        sessionSetup['Data']['NativeOS']      = 'Unix'
        sessionSetup['Data']['NativeLanMan']  = 'Samba'

        smb.addCommand(sessionSetup)
        self.sendSMB(smb)

        smb = self.recvSMB()
        if smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX):
            # We will need to use this uid field for all future requests/responses
            self._uid = smb['Uid']

            # Now we have to extract the blob to continue the auth process
            sessionResponse   = SMBCommand(smb['Data'][0])
            sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters'])
            sessionData       = SMBSessionSetupAndX_Extended_Response_Data(flags = smb['Flags2'])
            sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength']
            sessionData.fromString(sessionResponse['Data'])
            respToken = SPNEGO_NegTokenResp(sessionData['SecurityBlob'])

            # Let's parse some data and keep it to ourselves in case it is asked
            ntlmChallenge = ntlm.NTLMAuthChallenge(respToken['ResponseToken'])
            if ntlmChallenge['TargetInfoFields_len'] > 0:
                infoFields = ntlmChallenge['TargetInfoFields']
                av_pairs = ntlm.AV_PAIRS(ntlmChallenge['TargetInfoFields'][:ntlmChallenge['TargetInfoFields_len']]) 
                if av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] is not None:
                   try:
                       self.__server_name = av_pairs[ntlm.NTLMSSP_AV_HOSTNAME][1].decode('utf-16le')
                   except:
                       # For some reason, we couldn't decode Unicode here.. silently discard the operation
                       pass 
                if av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] is not None:
                   try:
                       if self.__server_name != av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le'): 
                           self.__server_domain = av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le')
                   except:
                       # For some reason, we couldn't decode Unicode here.. silently discard the operation
                       pass 

            type3, exportedSessionKey = ntlm.getNTLMSSPType3(auth, respToken['ResponseToken'], user, password, domain, lmhash, nthash, use_ntlmv2 = use_ntlmv2)

            if exportedSessionKey is not None: 
                self._SigningSessionKey = exportedSessionKey

            smb = NewSMBPacket()
            smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
            smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY #| SMB.FLAGS2_NT_STATUS

            # Are we required to sign SMB? If so we do it, if not we skip it
            if self._SignatureRequired: 
               smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE

            respToken2 = SPNEGO_NegTokenResp()
            respToken2['ResponseToken'] = str(type3)

            # Reusing the previous structure
            sessionSetup['Parameters']['SecurityBlobLength'] = len(respToken2)
            sessionSetup['Data']['SecurityBlob'] = respToken2.getData()

            # Storing some info for later use
            self.__server_os     = sessionData['NativeOS']
            self.__server_lanman = sessionData['NativeLanMan']

            smb.addCommand(sessionSetup)
            self.sendSMB(smb)
            
            smb = self.recvSMB()
            self._uid = 0
            if smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX):
                self._uid = smb['Uid']
                sessionResponse   = SMBCommand(smb['Data'][0])
                sessionParameters = SMBSessionSetupAndXResponse_Parameters(sessionResponse['Parameters'])
                sessionData       = SMBSessionSetupAndXResponse_Data(flags = smb['Flags2'], data = sessionResponse['Data'])

                self._action = sessionParameters['Action']
                # If smb sign required, let's enable it for the rest of the connection
                if self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SIGNATURES_REQUIRED:
                   self._SignSequenceNumber = 2
                   self._SignatureEnabled = True
                # Set up the flags to be used from now on
                self.__flags1 = SMB.FLAGS1_PATHCASELESS
                self.__flags2 = SMB.FLAGS2_EXTENDED_SECURITY
                return 1
        else:
            raise Exception('Error: Could not login successfully')

    def login(self, user, password, domain = '', lmhash = '', nthash = ''):

        # If we have hashes, normalize them
        if ( lmhash != '' or nthash != ''):
            if len(lmhash) % 2:     lmhash = '0%s' % lmhash
            if len(nthash) % 2:     nthash = '0%s' % nthash
            try: # just in case they were converted already
                lmhash = a2b_hex(lmhash)
                nthash = a2b_hex(nthash)
            except:
                pass

        if self._dialects_parameters['Capabilities'] & SMB.CAP_EXTENDED_SECURITY:
            try:
                self.login_extended(user, password, domain, lmhash, nthash, use_ntlmv2 = True)
            except:
                # If the target OS is Windows 5.0 or Samba, let's try using NTLMv1
                if (self.get_server_lanman().find('Windows 2000') != -1) or (self.get_server_lanman().find('Samba') != -1):
                    self.login_extended(user, password, domain, lmhash, nthash, use_ntlmv2 = False)
                    self.__isNTLMv2 = False
                else:
                    raise
        else:
            self.login_standard(user, password, domain, lmhash, nthash)
            self.__isNTLMv2 = False

    def login_standard(self, user, password, domain = '', lmhash = '', nthash = ''):
        # Only supports NTLMv1
        # Password is only encrypted if the server passed us an "encryption key" during protocol dialect negotiation
        if self._dialects_parameters['ChallengeLength'] > 0:
            if lmhash != '' or nthash != '':
               pwd_ansi = self.get_ntlmv1_response(lmhash)
               pwd_unicode = self.get_ntlmv1_response(nthash)
            elif password: 
               lmhash = ntlm.compute_lmhash(password)
               nthash = ntlm.compute_nthash(password)
               pwd_ansi = self.get_ntlmv1_response(lmhash)
               pwd_unicode = self.get_ntlmv1_response(nthash)
            else: # NULL SESSION
               pwd_ansi = ''
               pwd_unicode = ''
        else:
            pwd_ansi = password
            pwd_unicode = ''

        smb = NewSMBPacket()
        smb['Flags1']  = SMB.FLAGS1_PATHCASELESS
        
        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)
        sessionSetup['Parameters'] = SMBSessionSetupAndX_Parameters()
        sessionSetup['Data']       = SMBSessionSetupAndX_Data()

        sessionSetup['Parameters']['MaxBuffer']        = 61440
        sessionSetup['Parameters']['MaxMpxCount']      = 2
        sessionSetup['Parameters']['VCNumber']         = os.getpid()
        sessionSetup['Parameters']['SessionKey']       = self._dialects_parameters['SessionKey']
        sessionSetup['Parameters']['AnsiPwdLength']    = len(pwd_ansi)
        sessionSetup['Parameters']['UnicodePwdLength'] = len(pwd_unicode)
        sessionSetup['Parameters']['Capabilities']     = SMB.CAP_RAW_MODE | SMB.CAP_USE_NT_ERRORS | SMB.CAP_LARGE_READX | SMB.CAP_LARGE_WRITEX

        sessionSetup['Data']['AnsiPwd']       = pwd_ansi
        sessionSetup['Data']['UnicodePwd']    = pwd_unicode
        sessionSetup['Data']['Account']       = str(user)
        sessionSetup['Data']['PrimaryDomain'] = str(domain)
        sessionSetup['Data']['NativeOS']      = str(os.name)
        sessionSetup['Data']['NativeLanMan']  = 'pysmb'

        smb.addCommand(sessionSetup)

        self.sendSMB(smb)

        smb = self.recvSMB()
        if smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX):
            # We will need to use this uid field for all future requests/responses
            self._uid = smb['Uid']
            sessionResponse   = SMBCommand(smb['Data'][0])
            sessionParameters = SMBSessionSetupAndXResponse_Parameters(sessionResponse['Parameters'])
            sessionData       = SMBSessionSetupAndXResponse_Data(flags = smb['Flags2'], data = sessionResponse['Data'])

            self._action = sessionParameters['Action']

            # Still gotta figure out how to do this with no EXTENDED_SECURITY
            if sessionParameters['Action'] & SMB_SETUP_USE_LANMAN_KEY == 0:
                 self._SigningChallengeResponse = sessionSetup['Data']['UnicodePwd'] 
                 self._SigningSessionKey = nthash
            else:
                 self._SigningChallengeResponse = sessionSetup['Data']['AnsiPwd'] 
                 self._SigningSessionKey = lmhash

            #self._SignSequenceNumber = 1
            #self.checkSignSMB(smb, self._SigningSessionKey ,self._SigningChallengeResponse)
            #self._SignatureEnabled = True
            self.__server_os     = sessionData['NativeOS']
            self.__server_lanman = sessionData['NativeLanMan']
            self.__server_domain = sessionData['PrimaryDomain']

            # Set up the flags to be used from now on
            self.__flags1 = SMB.FLAGS1_PATHCASELESS
            self.__flags2 = 0
            return 1
        else: raise Exception('Error: Could not login successfully')

    def waitNamedPipe(self, tid, pipe, timeout = 5, noAnswer = 0):
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_LONG_NAMES
        smb['Tid']    = tid

        transCommand = SMBCommand(SMB.SMB_COM_TRANSACTION)
        transCommand['Parameters'] = SMBTransaction_Parameters()
        transCommand['Data'] = SMBTransaction_Data()

        setup = '\x53\x00\x00\x00'
        name = '\\PIPE%s\x00' % pipe
        transCommand['Parameters']['Setup'] = setup
        transCommand['Parameters']['TotalParameterCount'] = 0
        transCommand['Parameters']['TotalDataCount'] = 0
        transCommand['Parameters']['MaxParameterCount'] = 0
        transCommand['Parameters']['MaxDataCount'] = 0
        transCommand['Parameters']['Timeout'] = timeout * 1000

        transCommand['Parameters']['ParameterCount'] = 0
        transCommand['Parameters']['ParameterOffset'] = 32+3+28+len(setup)+len(name)

        transCommand['Parameters']['DataCount'] = 0
        transCommand['Parameters']['DataOffset'] = 0

        transCommand['Data']['Name'] = name
        transCommand['Data']['Trans_Parameters'] = ''
        transCommand['Data']['Trans_Data'] = ''

        if noAnswer:
           transCommand['Parameters']['Flags'] = TRANS_NO_RESPONSE
      
        smb.addCommand(transCommand)
        self.sendSMB(smb)

        smb = self.recvSMB()
        if smb.isValidAnswer(SMB.SMB_COM_TRANSACTION):
           return 1
        return 0

    def read(self, tid, fid, offset=0, max_size = None, wait_answer=1):
        if not max_size:
            max_size = self._dialects_parameters['MaxBufferSize'] # Read in multiple KB blocks
        
        # max_size is not working, because although it would, the server returns an error (More data avail)

        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_CANONICALIZED_PATHS | SMB.FLAGS1_PATHCASELESS 
        smb['Flags2'] = 0
        smb['Tid']    = tid

        read = SMBCommand(SMB.SMB_COM_READ)
        
        read['Parameters'] = SMBRead_Parameters()
        read['Parameters']['Fid'] = fid
        read['Parameters']['Offset'] = offset
        read['Parameters']['Count'] = max_size

        smb.addCommand(read)

        if wait_answer:
            answer = ''
            while 1:
                self.sendSMB(smb)
                ans = self.recvSMB()

                if ans.isValidAnswer(SMB.SMB_COM_READ):
                    readResponse   = SMBCommand(ans['Data'][0])
                    readParameters = SMBReadResponse_Parameters(readResponse['Parameters'])
                    readData       = SMBReadResponse_Data(readResponse['Data'])

                    return readData['Data']

        return None

    def read_andx(self, tid, fid, offset=0, max_size = None, wait_answer=1, smb_packet=None):
        if not max_size:
            if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_READX) and self._SignatureEnabled is False:
                max_size = 65000
            else:
                max_size = self._dialects_parameters['MaxBufferSize'] # Read in multiple KB blocks
        
        # max_size is not working, because although it would, the server returns an error (More data avail)

        if smb_packet == None:
            smb = NewSMBPacket()
            smb['Flags1'] = SMB.FLAGS1_CANONICALIZED_PATHS | SMB.FLAGS1_PATHCASELESS 
            smb['Flags2'] = 0
            smb['Tid']    = tid

            readAndX = SMBCommand(SMB.SMB_COM_READ_ANDX)
            readAndX['Parameters'] = SMBReadAndX_Parameters()
            readAndX['Parameters']['Fid'] = fid
            readAndX['Parameters']['Offset'] = offset
            readAndX['Parameters']['MaxCount'] = max_size

            smb.addCommand(readAndX)
        else:
            smb = smb_packet


        if wait_answer:
            answer = ''
            while 1:
                self.sendSMB(smb)
                ans = self.recvSMB()

                if ans.isValidAnswer(SMB.SMB_COM_READ_ANDX):
                    # XXX Here we are only using a few fields from the response
                    readAndXResponse   = SMBCommand(ans['Data'][0])
                    readAndXParameters = SMBReadAndXResponse_Parameters(readAndXResponse['Parameters'])

                    offset = readAndXParameters['DataOffset']
                    count = readAndXParameters['DataCount']+0x10000*readAndXParameters['DataCount_Hi']
                    answer += str(ans)[offset:offset+count]
                    if not ans.isMoreData():
                        return answer
                    max_size = min(max_size, readAndXParameters['Remaining'])
                    readAndX['Parameters']['Offset'] += count                      # XXX Offset is not important (apparently)
        else:
            self.sendSMB(smb)
            ans = self.recvSMB()

            try:
                if ans.isValidAnswer(SMB.SMB_COM_READ_ANDX):
                    return ans
                else:
                    return None
            except:
                return ans

        return None

    def read_raw(self, tid, fid, offset=0, max_size = None, wait_answer=1):
        if not max_size:
            max_size = self._dialects_parameters['MaxBufferSize'] # Read in multiple KB blocks
        
        # max_size is not working, because although it would, the server returns an error (More data avail)
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_CANONICALIZED_PATHS | SMB.FLAGS1_PATHCASELESS 
        smb['Flags2'] = 0
        smb['Tid']    = tid

        readRaw = SMBCommand(SMB.SMB_COM_READ_RAW)
        
        readRaw['Parameters'] = SMBReadRaw_Parameters()
        readRaw['Parameters']['Fid'] = fid
        readRaw['Parameters']['Offset'] = offset
        readRaw['Parameters']['MaxCount'] = max_size

        smb.addCommand(readRaw)

        self.sendSMB(smb)
        if wait_answer:
            data = self._sess.recv_packet(self.__timeout).get_trailer()
            if not data:
                # If there is no data it means there was an error
                data = self.read_andx(tid, fid, offset, max_size)
            return data

        return None

    def write(self,tid,fid,data, offset = 0, wait_answer=1):
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_CANONICALIZED_PATHS | SMB.FLAGS1_PATHCASELESS 
        smb['Flags2'] = 0
        smb['Tid']    = tid

        write = SMBCommand(SMB.SMB_COM_WRITE)
        smb.addCommand(write)
        
        write['Parameters'] = SMBWrite_Parameters()
        write['Data'] = SMBWrite_Data()
        write['Parameters']['Fid'] = fid
        write['Parameters']['Count'] = len(data)
        write['Parameters']['Offset'] = offset
        write['Parameters']['Remaining'] = len(data)
        write['Data']['Data'] = data

        self.sendSMB(smb)
                
        if wait_answer:
            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_WRITE):
                return smb
        return None

    def write_andx(self,tid,fid,data, offset = 0, wait_answer=1, write_pipe_mode = False, smb_packet=None):
        if smb_packet == None:
            smb = NewSMBPacket()
            smb['Flags1'] = SMB.FLAGS1_CANONICALIZED_PATHS | SMB.FLAGS1_PATHCASELESS 
            smb['Flags2'] = 0
            smb['Tid']    = tid

            writeAndX = SMBCommand(SMB.SMB_COM_WRITE_ANDX)
            smb.addCommand(writeAndX)
       
            writeAndX['Parameters'] = SMBWriteAndX_Parameters()
            writeAndX['Parameters']['Fid'] = fid
            writeAndX['Parameters']['Offset'] = offset
            writeAndX['Parameters']['WriteMode'] = 8
            writeAndX['Parameters']['Remaining'] = len(data)
            writeAndX['Parameters']['DataLength'] = len(data)
            writeAndX['Parameters']['DataOffset'] = len(smb)    # this length already includes the parameter
            writeAndX['Data'] = data
            
            if write_pipe_mode is True:
                # First of all we gotta know what the MaxBuffSize is
                maxBuffSize = self._dialects_parameters['MaxBufferSize'] 
                if len(data) > maxBuffSize:
                    chunks_size = maxBuffSize - 60
                    writeAndX['Parameters']['WriteMode'] = 0x0c
                    sendData = '\xff\xff' + data
                    totalLen = len(sendData)
                    writeAndX['Parameters']['DataLength'] = chunks_size
                    writeAndX['Parameters']['Remaining'] = totalLen-2
                    writeAndX['Data'] = sendData[:chunks_size]

                    self.sendSMB(smb)
                    if wait_answer:
                        smbResp = self.recvSMB()
                        smbResp.isValidAnswer(SMB.SMB_COM_WRITE_ANDX)

                    alreadySent = chunks_size
                    sendData = sendData[chunks_size:]

                    while alreadySent < totalLen:
                        writeAndX['Parameters']['WriteMode'] = 0x04
                        writeAndX['Parameters']['DataLength'] = len(sendData[:chunks_size])
                        writeAndX['Data'] = sendData[:chunks_size]
                        self.sendSMB(smb)
                        if wait_answer:
                            smbResp = self.recvSMB()
                            smbResp.isValidAnswer(SMB.SMB_COM_WRITE_ANDX)
                        alreadySent += writeAndX['Parameters']['DataLength'] 
                        sendData = sendData[chunks_size:]

                    return smbResp

        else:
            smb = smb_packet

        self.sendSMB(smb)
                
        if wait_answer:
            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_WRITE_ANDX):
                return smb
        return None

    def write_raw(self,tid,fid,data, offset = 0, wait_answer=1):
        print "[MS-CIFS] This command was introduced in the CorePlus dialect, but is often listed as part of the LAN Manager 1.0 dialect.\nThis command has been deprecated.\nClients SHOULD use SMB_COM_WRITE_ANDX"
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_CANONICALIZED_PATHS | SMB.FLAGS1_PATHCASELESS 
        smb['Flags2'] = 0
        smb['Tid']    = tid

        writeRaw = SMBCommand(SMB.SMB_COM_WRITE_RAW)
        smb.addCommand(writeRaw)
        
        writeRaw['Parameters'] = SMBWriteRaw_Parameters()
        writeRaw['Parameters']['Fid'] = fid
        writeRaw['Parameters']['Offset'] = offset
        writeRaw['Parameters']['Count'] = len(data)
        writeRaw['Parameters']['DataLength'] = 0
        writeRaw['Parameters']['DataOffset'] = 0

        self.sendSMB(smb)
        self._sess.send_packet(data)
                
        if wait_answer:
            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_WRITE_RAW):
                return smb
        return None

    def TransactNamedPipe(self, tid, fid, data = '', noAnswer = 0, waitAnswer = 1, offset = 0):
        self.send_trans(tid,pack('<HH', 0x26, fid),'\\PIPE\\\x00','',data, noAnswer = noAnswer)

        if noAnswer or not waitAnswer:
            return
        smb = self.recvSMB()
        if smb.isValidAnswer(SMB.SMB_COM_TRANSACTION):
           transResponse = SMBCommand(smb['Data'][0])
           transParameters = SMBTransactionResponse_Parameters(transResponse['Parameters'])
           return transResponse['Data'][-transParameters['TotalDataCount']:] # Remove Potential Prefix Padding
        return None

    def TransactNamedPipeRecv(self):
        s = self.recvSMB()
        if s.isValidAnswer(SMB.SMB_COM_TRANSACTION):
           transResponse = SMBCommand(s['Data'][0])
           transParameters = SMBTransactionResponse_Parameters(transResponse['Parameters'])
           return transResponse['Data'][-transParameters['TotalDataCount']:] # Remove Potential Prefix Padding
        return None


    def nt_create_andx(self,tid,filename, smb_packet=None, cmd = None):
        filename = string.replace(filename,'/', '\\')
        if smb_packet == None:
            smb = NewSMBPacket()
            smb['Flags1'] = SMB.FLAGS1_CANONICALIZED_PATHS | SMB.FLAGS1_PATHCASELESS 
            smb['Flags2'] = SMB.FLAGS2_LONG_NAMES
            smb['Tid']    = tid
        else:
            smb = smb_packet
        
        if cmd == None:
            ntCreate = SMBCommand(SMB.SMB_COM_NT_CREATE_ANDX)
            ntCreate['Parameters'] = SMBNtCreateAndX_Parameters()
            ntCreate['Data']       = SMBNtCreateAndX_Data()
            ntCreate['Parameters']['FileNameLength'] = len(filename)
            ntCreate['Parameters']['CreateFlags'] = 0x16
            ntCreate['Parameters']['AccessMask'] = 0x2019f
            ntCreate['Parameters']['CreateOptions'] = 0x40
            ntCreate['Data']['FileName'] = filename
        else:
            ntCreate = cmd

        smb.addCommand(ntCreate)

        self.sendSMB(smb)

        while 1:
            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_NT_CREATE_ANDX):
                # XXX Here we are ignoring the rest of the response
                ntCreateResponse   = SMBCommand(smb['Data'][0])
                ntCreateParameters = SMBNtCreateAndXResponse_Parameters(ntCreateResponse['Parameters'])

                self.fid = ntCreateParameters['Fid']
                return ntCreateParameters['Fid']

    def logoff(self):
        smb = NewSMBPacket()
        logOff = SMBCommand(SMB.SMB_COM_LOGOFF_ANDX)
        logOff['Parameters'] = SMBLogOffAndX()
        smb.addCommand(logOff)
        self.sendSMB(smb)
        smb = self.recvSMB()
        # Let's clear some fields so you can login again under the same session
        self._uid = 0 


    def list_shared(self):
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\IPC$')

        buf = StringIO()
        try:
            self.send_trans(tid, '', '\\PIPE\\LANMAN\0', '\x00\x00WrLeh\0B13BWz\0\x01\x00\xe0\xff', '')
            numentries = 0
            share_list = [ ]
            while 1:
                s = self.recv_packet()
                if self.isValidAnswer(s,SMB.SMB_COM_TRANSACTION):
                    has_more, _, transparam, transdata = self.__decode_trans(s.get_parameter_words(), s.get_buffer())
                    if not numentries:
                        status, data_offset, numentries = unpack('<HHH', transparam[:6])
                    buf.write(transdata)

                    if not has_more:
                        share_data = buf.getvalue()
                        offset = 0
                        for i in range(0, numentries):
                            name = share_data[offset:string.find(share_data, '\0', offset)]
                            type, commentoffset = unpack('<HH', share_data[offset + 14:offset + 18])
                            comment = share_data[commentoffset-data_offset:share_data.find('\0', commentoffset-data_offset)]
                            offset = offset + 20
                            share_list.append(SharedDevice(name, type, comment))
                        return share_list
        finally:
            buf.close()
            self.disconnect_tree(tid)

    def list_path(self, service, path = '*', password = None):
        path = string.replace(path, '/', '\\')

        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            self.trans2(tid, '\x01\x00', '\x00', '\x16\x00\x00\x02\x06\x00\x04\x01\x00\x00\x00\x00' + path + '\x00', '')
            resume = False
            files = [ ]

            while 1:
                s = self.recv_packet()
                if self.isValidAnswer(s,SMB.SMB_COM_TRANSACTION2):
                    has_more, _, transparam, transdata = self.__decode_trans(s.get_parameter_words(), s.get_buffer())
                    # A fairly quick trans reassembly. 
                    while has_more:
                       s2 = self.recv_packet()
                       if self.isValidAnswer(s2,SMB.SMB_COM_TRANSACTION2):
                          has_more, _, transparam2, transdata2 = self.__decode_trans(s2.get_parameter_words(), s2.get_buffer())
                          transdata += transdata2
                          transparam += transparam2

                    if not resume:
                        sid, searchcnt, eos, erroffset, lastnameoffset = unpack('<HHHHH', transparam)
                    else:
                        searchcnt, eos, erroffset, lastnameoffset = unpack('<HHHH', transparam)

                    offset = 0
                    data_len = len(transdata)
                    while offset < data_len:
                        nextentry, fileindex, lowct, highct, lowat, highat, lowmt, highmt, lowcht, hightcht, loweof, higheof, lowsz, highsz, attrib, longnamelen, easz, shortnamelen = unpack('<lL12LLlLB', transdata[offset:offset + 69])
                        files.append(SharedFile(highct << 32 | lowct, highat << 32 | lowat, highmt << 32 | lowmt, higheof << 32 | loweof, highsz << 32 | lowsz, attrib, transdata[offset + 70:offset + 70 + shortnamelen], transdata[offset + 94:offset + 94 + longnamelen]))
                        resume_filename = transdata[offset + 94:offset + 94 + longnamelen]
                        offset = offset + nextentry
                        if not nextentry:
                            break
                    if eos:
                       return files
                    else:
                       self.trans2(tid, '\x02\x00', '\x00', pack('<H', sid) + '\x56\x05\x04\x01\x00\x00\x00\x00\x06\x00' + resume_filename + '\x00', '')
                       resume = True
                       resume_filename = ''
        finally:
            self.disconnect_tree(tid)

    def retr_file(self, service, filename, callback, mode = SMB_O_OPEN, offset = 0, password = None):
        filename = string.replace(filename, '/', '\\')

        fid = -1
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            fid, attrib, lastwritetime, datasize, grantedaccess, filetype, devicestate, action, serverfid = self.open_andx(tid, filename, mode, SMB_ACCESS_READ | SMB_SHARE_DENY_WRITE)

            if not datasize:
                datasize = self.query_file_info(tid, fid)

            self.__nonraw_retr_file(tid, fid, offset, datasize, callback)
        finally:
            if fid >= 0:
                self.close(tid, fid)
            self.disconnect_tree(tid)

    def stor_file(self, service, filename, callback, mode = SMB_O_CREAT | SMB_O_TRUNC, offset = 0, password = None):
        filename = string.replace(filename, '/', '\\')

        fid = -1
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            fid, attrib, lastwritetime, datasize, grantedaccess, filetype, devicestate, action, serverfid = self.open_andx(tid, filename, mode, SMB_ACCESS_WRITE | SMB_SHARE_DENY_WRITE)
            
            self.__nonraw_stor_file(tid, fid, offset, datasize, callback)
        finally:
            if fid >= 0:
                self.close(tid, fid)
            self.disconnect_tree(tid)

    def stor_file_nonraw(self, service, filename, callback, mode = SMB_O_CREAT | SMB_O_TRUNC, offset = 0, password = None):
        filename = string.replace(filename, '/', '\\')

        fid = -1
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            fid, attrib, lastwritetime, datasize, grantedaccess, filetype, devicestate, action, serverfid = self.open_andx(tid, filename, mode, SMB_ACCESS_WRITE | SMB_SHARE_DENY_WRITE)
            self.__nonraw_stor_file(tid, fid, offset, datasize, callback)
        finally:
            if fid >= 0:
                self.close(tid, fid)
            self.disconnect_tree(tid)

    def copy(self, src_service, src_path, dest_service, dest_path, callback = None, write_mode = SMB_O_CREAT | SMB_O_TRUNC, src_password = None, dest_password = None):
        dest_path = string.replace(dest_path, '/', '\\')
        src_path = string.replace(src_path, '/', '\\')
        src_tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + src_service, src_password)

        dest_tid = -1
        try:
            if src_service == dest_service:
                dest_tid = src_tid
            else:
                dest_tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + dest_service, dest_password)
            
            dest_fid = self.open_andx(dest_tid, dest_path, write_mode, SMB_ACCESS_WRITE | SMB_SHARE_DENY_WRITE)[0]
            src_fid, _, _, src_datasize, _, _, _, _, _ = self.open_andx(src_tid, src_path, SMB_O_OPEN, SMB_ACCESS_READ | SMB_SHARE_DENY_WRITE)
            if not src_datasize:
                src_datasize = self.query_file_info(src_tid, src_fid)

            if callback:
                callback(0, src_datasize)

            max_buf_size = (self._dialects_parameters['MaxBufferSize'] >> 10) << 10
            read_offset = 0
            write_offset = 0
            while read_offset < src_datasize:
                self.__send_smb_packet(SMB.SMB_COM_READ_ANDX, 0, 0, src_tid, 0, pack('<BBHHLHHLH', 0xff, 0, 0, src_fid, read_offset, max_buf_size, max_buf_size, 0, 0), '')
                while 1:
                    s = self.recv_packet()
                    if self.isValidAnswer(s,SMB.SMB_COM_READ_ANDX):
                        offset = unpack('<H', s.get_parameter_words()[2:4])[0]
                        data_len, dataoffset = unpack('<HH', s.get_parameter_words()[10+offset:14+offset])
                        d = s.get_buffer()
                        if data_len == len(d):
                            self.__send_smb_packet(SMB.SMB_COM_WRITE_ANDX, 0, 0, dest_tid, 0, pack('<BBHHLLHHHHH', 0xff, 0, 0, dest_fid, write_offset, 0, 0, 0, 0, data_len, 59), d)
                        else:
                            self.__send_smb_packet(SMB.SMB_COM_WRITE_ANDX, 0, 0, dest_tid, 0, pack('<BBHHLLHHHHH', 0xff, 0, 0, dest_fid, write_offset, 0, 0, 0, 0, data_len, 59), d[dataoffset - 59:dataoffset - 59 + data_len])
                        while 1:
                            s = self.recv_packet()
                            if self.isValidAnswer(s,SMB.SMB_COM_WRITE_ANDX):
                                data_len, dataoffset = unpack('<HH', s.get_parameter_words()[4:8])
                                break
                        read_offset = read_offset + data_len
                        if callback:
                            callback(read_offset, src_datasize)
                        break
                
        finally:
            self.disconnect_tree(src_tid)
            if dest_tid > -1 and src_service != dest_service:
                self.disconnect_tree(dest_tid)

    def check_dir(self, service, path, password = None):
        path = string.replace(path,'/', '\\')
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            self.__send_smb_packet(SMB.SMB_COM_CHECK_DIRECTORY, 0x08, 0, tid, 0, '', '\x04' + path + '\x00')

            while 1:
                s = self.recv_packet()
                if self.isValidAnswer(s,SMB.SMB_COM_CHECK_DIRECTORY):
                    return
        finally:
            self.disconnect_tree(tid)

    def remove(self, service, path, password = None):
        path = string.replace(path,'/', '\\')
        # Perform a list to ensure the path exists
        self.list_path(service, path, password)

        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            self.__send_smb_packet(SMB.SMB_COM_DELETE, 0x08, 0, tid, 0, pack('<H', ATTR_HIDDEN | ATTR_SYSTEM | ATTR_ARCHIVE), '\x04' + path + '\x00')

            while 1:
                s = self.recv_packet()
                if self.isValidAnswer(s,SMB.SMB_COM_DELETE):
                    return
        finally:
            self.disconnect_tree(tid)

    def rmdir(self, service, path, password = None):
        path = string.replace(path,'/', '\\')
        # Check that the directory exists
        self.check_dir(service, path, password)

        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            self.__send_smb_packet(SMB.SMB_COM_DELETE_DIRECTORY, 0x08, 0, tid, 0, '', '\x04' + path + '\x00')

            while 1:
                s = self.recv_packet()
                if self.isValidAnswer(s,SMB.SMB_COM_DELETE_DIRECTORY):
                    return
        finally:
            self.disconnect_tree(tid)

    def mkdir(self, service, path, password = None):
        path = string.replace(path,'/', '\\')
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            smb = NewSMBPacket()
            smb['Tid'] = tid
            createDir = SMBCommand(SMB.SMB_COM_CREATE_DIRECTORY)
            createDir['Data'] = SMBCreateDirectory_Data()
            createDir['Data']['DirectoryName'] = path
            smb.addCommand(createDir)
            self.sendSMB(smb)
        
            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_CREATE_DIRECTORY):
                return 1
            return 0
        finally:
            self.disconnect_tree(tid)

    def rename(self, service, old_path, new_path, password = None):
        old_path = string.replace(old_path,'/', '\\')
        new_path = string.replace(new_path,'/', '\\')
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            smb = NewSMBPacket()
            smb['Tid'] = tid
            smb['Flags'] = SMB.FLAGS1_PATHCASELESS
            renameCmd = SMBCommand(SMB.SMB_COM_RENAME)
            renameCmd['Parameters'] = SMBRename_Parameters()
            renameCmd['Parameters']['SearchAttributes'] = ATTR_SYSTEM | ATTR_HIDDEN | ATTR_DIRECTORY 
            renameCmd['Data'] = SMBRename_Data()
            renameCmd['Data']['OldFileName'] = old_path
            renameCmd['Data']['NewFileName'] = new_path 

            smb.addCommand(renameCmd)
            self.sendSMB(smb)
            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_RENAME):
               return 1
            return 0 
        finally:
            self.disconnect_tree(tid)

    def writeFile(self, treeId, fileId, data, offset = 0):
        if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_WRITEX) and self._SignatureEnabled is False:
            max_buf_size = 65000
        else:
            max_buf_size = self._dialects_parameters['MaxBufferSize'] & ~0x3ff  # Write in multiple KB blocks

        write_offset = offset
        while 1:
            if len(data) == 0:
                break
            writeData = data[:max_buf_size]
            data = data[max_buf_size:]

            smb = self.write_andx(treeId,fileId,writeData, write_offset)
            writeResponse   = SMBCommand(smb['Data'][0])
            writeResponseParameters = SMBWriteAndXResponse_Parameters(writeResponse['Parameters'])
            write_offset += writeResponseParameters['Count']

    def get_socket(self):
        return self._sess.get_socket()

ERRDOS = { 1: 'Invalid function',
           2: 'File not found',
           3: 'Invalid directory',
           4: 'Too many open files',
           5: 'Access denied',
           6: 'Invalid file handle. Please file a bug report.',
           7: 'Memory control blocks destroyed',
           8: 'Out of memory',
           9: 'Invalid memory block address',
           10: 'Invalid environment',
           11: 'Invalid format',
           12: 'Invalid open mode',
           13: 'Invalid data',
           15: 'Invalid drive',
           16: 'Attempt to remove server\'s current directory',
           17: 'Not the same device',
           18: 'No files found',
           32: 'Sharing mode conflicts detected',
           33: 'Lock request conflicts detected',
           80: 'File already exists'
           }

ERRSRV = { 1: 'Non-specific error',
           2: 'Bad password',
           4: 'Access denied',
           5: 'Invalid tid. Please file a bug report.',
           6: 'Invalid network name',
           7: 'Invalid device',
           49: 'Print queue full',
           50: 'Print queue full',
           51: 'EOF on print queue dump',
           52: 'Invalid print file handle',
           64: 'Command not recognized. Please file a bug report.',
           65: 'Internal server error',
           67: 'Invalid path',
           69: 'Invalid access permissions',
           71: 'Invalid attribute mode',
           81: 'Server is paused',
           82: 'Not receiving messages',
           83: 'No room to buffer messages',
           87: 'Too many remote user names',
           88: 'Operation timeout',
           89: 'Out of resources',
           91: 'Invalid user handle. Please file a bug report.',
           250: 'Temporarily unable to support raw mode for transfer',
           251: 'Temporarily unable to support raw mode for transfer',
           252: 'Continue in MPX mode',
           65535: 'Unsupported function'
           }

ERRHRD = { 19: 'Media is write-protected',
           20: 'Unknown unit',
           21: 'Drive not ready',
           22: 'Unknown command',
           23: 'CRC error',
           24: 'Bad request',
           25: 'Seek error',
           26: 'Unknown media type',
           27: 'Sector not found',
           28: 'Printer out of paper',
           29: 'Write fault',
           30: 'Read fault',
           31: 'General failure',
           32: 'Open conflicts with an existing open',
           33: 'Invalid lock request',
           34: 'Wrong disk in drive',
           35: 'FCBs not available',
           36: 'Sharing buffer exceeded'
           }