smb2 0.11.0

Pure-Rust SMB2/3 client library with pipelined I/O
Documentation
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
//! Integration tests against Docker Samba containers.
//!
//! Requires containers running (see tests/docker/start.sh).
//! All tests are `#[ignore]` so `cargo test` doesn't fail without Docker.
//!
//! Run with:
//!   just test-docker                      # starts containers, runs, stops
//!   cargo test --test docker_integration -- --ignored   # if containers are already running

use std::collections::HashMap;
use std::ops::ControlFlow;
use std::time::Duration;

use smb2::client::{list_shares, ClientConfig, Connection, Session, SmbClient, Tree};

const GUEST_ADDR: &str = "127.0.0.1:10445";
const AUTH_ADDR: &str = "127.0.0.1:10446";
const SIGNING_ADDR: &str = "127.0.0.1:10447";
const READONLY_ADDR: &str = "127.0.0.1:10448";
const ANCIENT_ADDR: &str = "127.0.0.1:10449";
const FLAKY_ADDR: &str = "127.0.0.1:10450";
const SLOW_ADDR: &str = "127.0.0.1:10451";
const ENCRYPTION_ADDR: &str = "127.0.0.1:10452";
const SHARES50_ADDR: &str = "127.0.0.1:10453";
const MAXREAD_ADDR: &str = "127.0.0.1:10454";
const ENCRYPTION_AES128_ADDR: &str = "127.0.0.1:10455";
const DFS_ROOT_ADDR: &str = "127.0.0.1:10456";
const DFS_TARGET_ADDR: &str = "127.0.0.1:10457";
const TIMEOUT: Duration = Duration::from_secs(5);

// ── Helpers ──────────────────────────────────────────────────────────

/// Connect, negotiate, and authenticate as guest to smb-guest.
async fn connect_guest() -> (Connection, Tree) {
    let mut conn = Connection::connect(GUEST_ADDR, TIMEOUT)
        .await
        .expect("failed to connect to smb-guest");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("guest session setup failed");
    let tree = Tree::connect(&mut conn, "public")
        .await
        .expect("tree connect to 'public' failed");
    (conn, tree)
}

/// Create an SmbClient connected as guest to smb-guest.
async fn guest_client() -> SmbClient {
    SmbClient::connect(ClientConfig {
        addr: GUEST_ADDR.to_string(),
        timeout: TIMEOUT,
        username: String::new(),
        password: String::new(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: true,
        dfs_target_overrides: HashMap::new(),
    })
    .await
    .expect("SmbClient::connect to smb-guest failed")
}

/// Create an SmbClient connected with credentials to smb-auth.
async fn auth_client() -> SmbClient {
    SmbClient::connect(ClientConfig {
        addr: AUTH_ADDR.to_string(),
        timeout: TIMEOUT,
        username: "testuser".to_string(),
        password: "testpass".to_string(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: true,
        dfs_target_overrides: HashMap::new(),
    })
    .await
    .expect("SmbClient::connect to smb-auth failed")
}

// ── Basic operations (smb-guest) ─────────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_connect_negotiate_list_directory() {
    let _ = env_logger::try_init();

    let (mut conn, tree) = connect_guest().await;

    let params = conn.params().unwrap();
    // Any SMB2+ dialect is fine — just verify we negotiated successfully.
    assert!(
        params.dialect as u16 >= 0x0202,
        "expected SMB2+ dialect, got {}",
        params.dialect
    );

    let entries = tree
        .list_directory(&mut conn, "")
        .await
        .expect("list directory failed");

    // Empty directory is fine — we just need it to not error.
    // The directory exists and is listable.
    drop(entries);

    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_write_read_delete() {
    let _ = env_logger::try_init();

    let (mut conn, tree) = connect_guest().await;

    let test_path = "docker_test_write_read.tmp";
    let test_data = b"Hello from Docker integration test!";

    // Write.
    let written = tree
        .write_file(&mut conn, test_path, test_data)
        .await
        .expect("write_file failed");
    assert_eq!(written, test_data.len() as u64);

    // Read back.
    let data = tree
        .read_file(&mut conn, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data, test_data);

    // Delete.
    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");

    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_stat_file() {
    let _ = env_logger::try_init();

    let (mut conn, tree) = connect_guest().await;

    let test_path = "docker_test_stat.tmp";
    let test_data = b"stat test content";
    tree.write_file(&mut conn, test_path, test_data)
        .await
        .expect("write_file failed");

    let info = tree.stat(&mut conn, test_path).await.expect("stat failed");
    assert_eq!(info.size, test_data.len() as u64);
    assert!(!info.is_directory);

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_create_delete_directory() {
    let _ = env_logger::try_init();

    let (mut conn, tree) = connect_guest().await;

    let dir_path = "docker_test_dir_tmp";

    tree.create_directory(&mut conn, dir_path)
        .await
        .expect("create_directory failed");

    let info = tree.stat(&mut conn, dir_path).await.expect("stat failed");
    assert!(info.is_directory);

    tree.delete_directory(&mut conn, dir_path)
        .await
        .expect("delete_directory failed");

    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

// ── Compound operations (smb-guest) ──────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_compound_read() {
    let _ = env_logger::try_init();

    let (mut conn, tree) = connect_guest().await;

    let test_path = "docker_test_compound_read.tmp";
    let test_data = b"compound read test data 1234567890";
    tree.write_file(&mut conn, test_path, test_data)
        .await
        .expect("write_file failed");

    let data = tree
        .read_file_compound(&mut conn, test_path)
        .await
        .expect("read_file_compound failed");
    assert_eq!(data, test_data);

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_compound_write() {
    let _ = env_logger::try_init();

    let (mut conn, tree) = connect_guest().await;

    let test_path = "docker_test_compound_write.tmp";
    let test_data = b"compound write test data 1234567890";

    let written = tree
        .write_file_compound(&mut conn, test_path, test_data)
        .await
        .expect("write_file_compound failed");
    assert_eq!(written, test_data.len() as u64);

    // Read back to verify.
    let data = tree
        .read_file(&mut conn, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data, test_data);

    // Empty file via compound.
    let empty_path = "docker_test_compound_empty.tmp";
    let empty_written = tree
        .write_file_compound(&mut conn, empty_path, b"")
        .await
        .expect("write_file_compound (empty) failed");
    assert_eq!(empty_written, 0);

    let empty_data = tree
        .read_file(&mut conn, empty_path)
        .await
        .expect("read empty file failed");
    assert!(empty_data.is_empty());

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.delete_file(&mut conn, empty_path)
        .await
        .expect("delete empty file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

// ── Pipelined I/O (smb-guest) ────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_pipelined_read() {
    let _ = env_logger::try_init();

    let (mut conn, tree) = connect_guest().await;

    let test_path = "docker_test_pipelined_read.tmp";
    let test_data: Vec<u8> = (0..1_048_576).map(|i| (i % 251) as u8).collect();

    tree.write_file(&mut conn, test_path, &test_data)
        .await
        .expect("write_file failed");

    let data = tree
        .read_file_pipelined(&mut conn, test_path)
        .await
        .expect("read_file_pipelined failed");

    assert_eq!(data.len(), test_data.len(), "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_pipelined_write() {
    let _ = env_logger::try_init();

    let (mut conn, tree) = connect_guest().await;

    let test_path = "docker_test_pipelined_write.tmp";
    let test_data: Vec<u8> = (0..1_048_576).map(|i| (i % 199) as u8).collect();

    let written = tree
        .write_file_pipelined(&mut conn, test_path, &test_data)
        .await
        .expect("write_file_pipelined failed");
    assert_eq!(written, test_data.len() as u64);

    let data = tree
        .read_file(&mut conn, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data.len(), test_data.len(), "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

// ── Share enumeration ────────────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_list_shares() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(GUEST_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");

    let shares = list_shares(&mut conn).await.expect("list_shares failed");

    assert!(
        shares.iter().any(|s| s.name == "public"),
        "expected 'public' share, got: {:?}",
        shares.iter().map(|s| &s.name).collect::<Vec<_>>()
    );
}

#[tokio::test]
#[ignore]
async fn auth_list_shares() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(AUTH_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "testuser", "testpass", "")
        .await
        .expect("session setup failed");

    let shares = list_shares(&mut conn).await.expect("list_shares failed");

    assert!(
        shares.iter().any(|s| s.name == "private"),
        "expected 'private' share, got: {:?}",
        shares.iter().map(|s| &s.name).collect::<Vec<_>>()
    );
}

// ── SmbClient high-level API (smb-guest) ─────────────────────────────

#[tokio::test]
#[ignore]
async fn smb_client_guest_connect_and_list() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;

    let params = client.params().unwrap();
    assert!(params.dialect as u16 >= 0x0202);

    let tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let entries = tree
        .list_directory(client.connection_mut(), "")
        .await
        .expect("list_directory failed");
    drop(entries);

    tree.disconnect(client.connection_mut())
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn smb_client_guest_list_shares() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let shares = client.list_shares().await.expect("list_shares failed");

    assert!(
        shares.iter().any(|s| s.name == "public"),
        "expected 'public' share"
    );
}

// ── Authentication (smb-auth) ────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn auth_connect_and_operate() {
    let _ = env_logger::try_init();

    let mut client = auth_client().await;
    let mut tree = client
        .connect_share("private")
        .await
        .expect("connect_share failed");

    // Write, read, delete.
    let test_path = "docker_test_auth.tmp";
    let test_data = b"authenticated write test";

    client
        .write_file(&mut tree, test_path, test_data)
        .await
        .expect("write_file failed");

    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data, test_data);

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");

    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn auth_wrong_password_fails_cleanly() {
    let _ = env_logger::try_init();

    let result = SmbClient::connect(ClientConfig {
        addr: AUTH_ADDR.to_string(),
        timeout: TIMEOUT,
        username: "testuser".to_string(),
        password: "wrongpassword".to_string(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: true,
        dfs_target_overrides: HashMap::new(),
    })
    .await;

    assert!(result.is_err(), "expected auth failure, got Ok");
}

// ── Streaming (smb-guest) ────────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_streaming_download() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "docker_test_stream_download.tmp";
    let test_data: Vec<u8> = (0..1_048_576).map(|i| (i % 251) as u8).collect();

    client
        .write_file(&mut tree, test_path, &test_data)
        .await
        .expect("write_file failed");

    let mut download = client
        .download(&tree, test_path)
        .await
        .expect("download failed");
    assert_eq!(download.size(), test_data.len() as u64);

    let mut received = Vec::new();
    while let Some(chunk) = download.next_chunk().await {
        let bytes = chunk.expect("next_chunk failed");
        assert!(!bytes.is_empty());
        received.extend_from_slice(&bytes);
    }

    assert!(
        (download.progress().fraction() - 1.0).abs() < f64::EPSILON,
        "expected progress 1.0, got {}",
        download.progress().fraction()
    );
    assert_eq!(received, test_data);

    drop(download);

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

/// `Tree::download` (borrowed `&mut Connection`) mirrors
/// `SmbClient::download` against a real Samba container. Same payload, same
/// RTT shape — the only difference is the caller holds the `Connection`
/// directly, which is what unlocks concurrent downloads on cloned
/// connections.
#[tokio::test]
#[ignore]
async fn guest_tree_download_streams_via_connection() {
    let _ = env_logger::try_init();

    let (mut conn, tree) = connect_guest().await;

    let test_path = "docker_test_tree_download.tmp";
    let test_data: Vec<u8> = (0..524_288).map(|i| (i % 251) as u8).collect();

    // Seed the file through the high-level client, then download it back
    // via the low-level Tree::download API.
    {
        let mut client = guest_client().await;
        let mut write_tree = client
            .connect_share("public")
            .await
            .expect("connect_share failed");
        client
            .write_file(&mut write_tree, test_path, &test_data)
            .await
            .expect("write_file failed");
        client
            .disconnect_share(&write_tree)
            .await
            .expect("disconnect failed");
    }

    let mut download = tree
        .download(&mut conn, test_path)
        .await
        .expect("Tree::download failed");
    assert_eq!(download.size(), test_data.len() as u64);

    let mut received = Vec::new();
    while let Some(chunk) = download.next_chunk().await {
        let bytes = chunk.expect("next_chunk failed");
        assert!(!bytes.is_empty());
        received.extend_from_slice(&bytes);
    }
    assert_eq!(received, test_data);

    drop(download);

    // Clean up via a fresh client (we already consumed `conn` for the
    // download; reuse it for the delete to exercise the same connection
    // end-to-end).
    let mut client = guest_client().await;
    let mut cleanup_tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");
    client
        .delete_file(&mut cleanup_tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&cleanup_tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_streaming_upload() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    // 2 MB to exceed MaxWriteSize and trigger chunked path.
    let test_path = "docker_test_stream_upload.tmp";
    let test_data: Vec<u8> = (0..2_097_152).map(|i| (i % 251) as u8).collect();

    let mut upload = client
        .upload(&tree, test_path, &test_data)
        .await
        .expect("upload failed");
    assert_eq!(upload.total_bytes(), test_data.len() as u64);

    while upload
        .write_next_chunk()
        .await
        .expect("write_next_chunk failed")
    {}

    assert!(
        (upload.progress().fraction() - 1.0).abs() < f64::EPSILON,
        "expected progress 1.0, got {}",
        upload.progress().fraction()
    );

    drop(upload);

    let readback = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(readback, test_data);

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

// ── Write with progress and cancellation (smb-guest) ─────────────────

#[tokio::test]
#[ignore]
async fn guest_write_with_progress() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "docker_test_write_progress.tmp";
    let test_data: Vec<u8> = (0..1_048_576).map(|i| (i % 199) as u8).collect();

    let mut progress_updates = Vec::new();
    let written = client
        .write_file_with_progress(&mut tree, test_path, &test_data, |progress| {
            progress_updates.push(progress.bytes_transferred);
            ControlFlow::Continue(())
        })
        .await
        .expect("write_file_with_progress failed");

    assert_eq!(written, test_data.len() as u64);
    assert!(!progress_updates.is_empty());

    let readback = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(readback, test_data);

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_write_cancel_midway() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let cancel_path = "docker_test_write_cancel.tmp";
    let test_data: Vec<u8> = (0..1_048_576).map(|i| (i % 199) as u8).collect();
    let half = test_data.len() as u64 / 2;

    let result = client
        .write_file_with_progress(&mut tree, cancel_path, &test_data, |progress| {
            if progress.bytes_transferred >= half {
                ControlFlow::Break(())
            } else {
                ControlFlow::Continue(())
            }
        })
        .await;

    match result {
        Err(smb2::Error::Cancelled) => {}
        other => panic!("expected Error::Cancelled, got {:?}", other),
    }

    // Best-effort cleanup.
    let _ = client.delete_file(&mut tree, cancel_path).await;
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

// ── fs_info (smb-guest) ──────────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_fs_info() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let info = client.fs_info(&mut tree).await.expect("fs_info failed");

    assert!(info.total_bytes > 0);
    assert!(info.free_bytes <= info.total_bytes);
    assert!(info.bytes_per_sector > 0);
    assert!(info.sectors_per_unit > 0);

    let _ = client.disconnect_share(&tree).await;
}

// ── Reconnect (smb-guest) ────────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_reconnect() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;

    // Verify it works.
    let tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");
    let entries = tree
        .list_directory(client.connection_mut(), "")
        .await
        .expect("list_directory failed");
    drop(entries);
    tree.disconnect(client.connection_mut())
        .await
        .expect("disconnect failed");

    // Reconnect.
    client.reconnect().await.expect("reconnect failed");

    // Verify it works again.
    let tree2 = client
        .connect_share("public")
        .await
        .expect("connect_share after reconnect failed");
    let entries2 = tree2
        .list_directory(client.connection_mut(), "")
        .await
        .expect("list_directory after reconnect failed");
    drop(entries2);
    tree2
        .disconnect(client.connection_mut())
        .await
        .expect("disconnect failed");
}

// ── File watching (smb-guest) ────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_watch_directory() {
    use smb2::FileNotifyAction;

    let _ = env_logger::try_init();

    // File watching needs two connections on the same thread (SmbClient is !Send).
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let mut watcher_client = guest_client().await;
            let mut watcher_share = watcher_client
                .connect_share("public")
                .await
                .expect("tree connect failed (watcher)");

            // Ensure a subdirectory to watch exists.
            let _ = watcher_client
                .create_directory(&mut watcher_share, "_test_watch")
                .await;

            let mut watcher = watcher_client
                .watch(&watcher_share, "_test_watch/", false)
                .await
                .expect("watch failed");

            // Spawn a writer on a second connection.
            let test_file_path = "_test_watch/docker_watch_test.tmp";
            let writer_task = tokio::task::spawn_local(async move {
                let mut writer_client = guest_client().await;
                let mut writer_share = writer_client
                    .connect_share("public")
                    .await
                    .expect("tree connect failed (writer)");

                tokio::time::sleep(Duration::from_millis(500)).await;

                writer_client
                    .write_file(&mut writer_share, test_file_path, b"watch test")
                    .await
                    .expect("write_file failed");

                (writer_client, writer_share)
            });

            let events = tokio::time::timeout(Duration::from_secs(10), watcher.next_events())
                .await
                .expect("timed out waiting for change notification")
                .expect("next_events failed");

            assert!(!events.is_empty());
            let added = events.iter().find(|e| e.action == FileNotifyAction::Added);
            assert!(added.is_some(), "expected an Added event");

            watcher.close().await.expect("watcher close failed");

            // Cleanup.
            let (mut writer_client, mut writer_share) = writer_task.await.unwrap();
            writer_client
                .delete_file(&mut writer_share, test_file_path)
                .await
                .expect("delete_file failed");
            let _ = writer_client.disconnect_share(&writer_share).await;

            let _ = watcher_client
                .delete_directory(&mut watcher_share, "_test_watch")
                .await;
        })
        .await;
}

/// Contract test for the CHANGE_NOTIFY loss window between consecutive requests.
///
/// Today's `Watcher::next_events()` issues one CHANGE_NOTIFY, awaits the
/// response, returns. Between response and the consumer's next call there
/// is no outstanding request on the wire. Servers that drop events without
/// an outstanding request (cmdr-on-naspi field repro: 9 files written, 4
/// watcher events delivered) will silently lose them; servers that queue
/// generously (Docker Samba with the parameters below) will not.
///
/// **Honest status**: this test **does not currently fail on Docker Samba**.
/// Tuned to its threshold of pain it either still buffers everything OR
/// flips to `STATUS_NOTIFY_ENUM_DIR` (server-side overflow signal,
/// different code path). The test stays in as:
///
/// 1. A pin against regressions on less-forgiving servers (older Samba,
///    Synology firmware, QNAP firmware — where naspi reproduced).
/// 2. A behavioral contract: under realistic concurrent load, the watcher
///    delivers every Added event for every file.
///
/// To get a Docker-side failing test for the loss window, see the
/// follow-up `watcher_keeps_request_outstanding_between_responses` test
/// (separate file, uses `MockTransport` to control wire timing precisely)
/// — but that needs a small lib-side hook to expose request-send and
/// response-receive instants, which we haven't added yet.
#[tokio::test]
#[ignore]
async fn watcher_does_not_lose_events_during_consumer_processing_delay() {
    use smb2::FileNotifyAction;

    let _ = env_logger::try_init();

    // Realistic concurrent load. Below the NOTIFY_ENUM_DIR overflow
    // threshold on Docker Samba; calibrated against the cmdr-on-naspi
    // field reproduction (9 files, ~1 file/sec, slow consumer-side stat).
    const N: usize = 50;
    const CONCURRENT_WRITERS: usize = 3;
    const CONSUMER_PROCESSING: Duration = Duration::from_millis(250);
    const OVERALL_DEADLINE: Duration = Duration::from_secs(30);

    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            // Watcher and writer each on their own SmbClient. Today's
            // API forces this: `Watcher` borrows `&mut Connection`.
            let mut watcher_client = guest_client().await;
            let mut watcher_share = watcher_client
                .connect_share("public")
                .await
                .expect("tree connect failed (watcher)");

            // Clean from any prior run. Deleting individual files first
            // because delete_directory only works on empty dirs.
            for i in 0..N {
                let _ = watcher_client
                    .delete_file(
                        &mut watcher_share,
                        &format!("_test_watch_loss/file_{i:03}.txt"),
                    )
                    .await;
            }
            let _ = watcher_client
                .delete_directory(&mut watcher_share, "_test_watch_loss")
                .await;
            watcher_client
                .create_directory(&mut watcher_share, "_test_watch_loss")
                .await
                .expect("create _test_watch_loss");

            let mut watcher = watcher_client
                .watch(&watcher_share, "_test_watch_loss/", true)
                .await
                .expect("watch failed");

            // Writers: CONCURRENT_WRITERS independent clients, each
            // responsible for a slice of the N files. Concurrent connections
            // hammer Samba harder than a single serial writer, increasing
            // event arrival rate during the consumer's processing window.
            let writers_done = std::rc::Rc::new(std::cell::Cell::new(0usize));
            let writer_handles: Vec<_> = (0..CONCURRENT_WRITERS)
                .map(|writer_idx| {
                    let writers_done = writers_done.clone();
                    tokio::task::spawn_local(async move {
                        let mut writer_client = guest_client().await;
                        let mut writer_share = writer_client
                            .connect_share("public")
                            .await
                            .expect("tree connect failed (writer)");

                        // Brief lead so the watcher is armed before the first write.
                        tokio::time::sleep(Duration::from_millis(200)).await;

                        let per_writer = N / CONCURRENT_WRITERS;
                        let start = writer_idx * per_writer;
                        let end = if writer_idx == CONCURRENT_WRITERS - 1 {
                            N
                        } else {
                            start + per_writer
                        };
                        for i in start..end {
                            let path = format!("_test_watch_loss/file_{i:03}.txt");
                            writer_client
                                .write_file(&mut writer_share, &path, b"x")
                                .await
                                .unwrap_or_else(|e| panic!("write_file {path}: {e}"));
                        }
                        writers_done.set(writers_done.get() + 1);
                        (writer_client, writer_share)
                    })
                })
                .collect();

            // Consumer: pull events with a deliberate processing delay
            // between iterations. This delay is the loss window today.
            let mut seen = std::collections::HashSet::new();
            let mut got_notify_enum_dir = false;
            let deadline = tokio::time::Instant::now() + OVERALL_DEADLINE;
            while tokio::time::Instant::now() < deadline && seen.len() < N {
                let res =
                    tokio::time::timeout(Duration::from_millis(500), watcher.next_events()).await;
                match res {
                    Ok(Ok(events)) => {
                        for e in events {
                            if e.action == FileNotifyAction::Added
                                && e.filename.starts_with("file_")
                            {
                                seen.insert(e.filename);
                            }
                        }
                        // Realistic consumer work (stat each new entry, update
                        // UI, etc). On servers with a real loss window, this
                        // delay is where events get dropped.
                        tokio::time::sleep(CONSUMER_PROCESSING).await;
                    }
                    Ok(Err(smb2::Error::Protocol { status, .. }))
                        if status == smb2::types::status::NtStatus::NOTIFY_ENUM_DIR =>
                    {
                        // Server's per-handle event buffer overflowed: the
                        // consumer is expected to re-scan the dir and resume
                        // watching. This test isn't trying to assert the
                        // overflow path; it's the cleaner loss window. Note
                        // it and break — overflow means the parameters are
                        // too aggressive for this server's buffer.
                        got_notify_enum_dir = true;
                        break;
                    }
                    Ok(Err(e)) => panic!("watcher error: {e}"),
                    Err(_) => continue, // 500 ms wait elapsed; loop back
                }
            }

            // Best-effort cleanup before assertion so a failed assert
            // doesn't leave the dir behind.
            watcher.close().await.expect("watcher close failed");
            let mut cleanup_client_share: Option<(SmbClient, Tree)> = None;
            for h in writer_handles {
                let (c, s) = h.await.unwrap();
                cleanup_client_share = Some((c, s));
            }
            if let Some((mut cleanup_client, mut cleanup_share)) = cleanup_client_share {
                for i in 0..N {
                    let _ = cleanup_client
                        .delete_file(
                            &mut cleanup_share,
                            &format!("_test_watch_loss/file_{i:03}.txt"),
                        )
                        .await;
                }
                let _ = cleanup_client
                    .delete_directory(&mut cleanup_share, "_test_watch_loss")
                    .await;
                let _ = cleanup_client.disconnect_share(&cleanup_share).await;
            }

            assert!(
                !got_notify_enum_dir,
                "load too aggressive for this server's CHANGE_NOTIFY buffer: \
                 got NOTIFY_ENUM_DIR. Reduce N or CONCURRENT_WRITERS — that path \
                 is server-side overflow, not the consumer-side loss window."
            );
            assert_eq!(
                seen.len(),
                N,
                "watcher lost events during consumer-side processing delay: saw {}/{N}. \
                 Missing files: {:?}",
                seen.len(),
                (0..N)
                    .map(|i| format!("file_{i:03}.txt"))
                    .filter(|name| !seen.contains(name))
                    .collect::<Vec<_>>()
            );
        })
        .await;
}

// ── Mandatory signing (smb-signing) ──────────────────────────────────

#[tokio::test]
#[ignore]
async fn signing_negotiated_as_required() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(SIGNING_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");

    let params = conn.params().unwrap();
    assert!(
        params.signing_required,
        "expected signing_required=true from smb-signing server"
    );
}

#[tokio::test]
#[ignore]
async fn signing_write_read_roundtrip() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(SIGNING_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "testuser", "testpass", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "private")
        .await
        .expect("tree connect failed");

    let test_path = "docker_test_signing.tmp";
    let test_data = b"signed write test data 1234567890";

    let written = tree
        .write_file(&mut conn, test_path, test_data)
        .await
        .expect("write_file failed (signing)");
    assert_eq!(written, test_data.len() as u64);

    let data = tree
        .read_file(&mut conn, test_path)
        .await
        .expect("read_file failed (signing)");
    assert_eq!(data, test_data);

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn signing_compound_operations() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(SIGNING_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "testuser", "testpass", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "private")
        .await
        .expect("tree connect failed");

    let test_path = "docker_test_signing_compound.tmp";
    let test_data = b"compound over signed transport";

    tree.write_file_compound(&mut conn, test_path, test_data)
        .await
        .expect("write_file_compound failed (signing)");

    let data = tree
        .read_file_compound(&mut conn, test_path)
        .await
        .expect("read_file_compound failed (signing)");
    assert_eq!(data, test_data);

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn signing_pipelined_large_file() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(SIGNING_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "testuser", "testpass", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "private")
        .await
        .expect("tree connect failed");

    let test_path = "docker_test_signing_pipelined.tmp";
    let test_data: Vec<u8> = (0..524_288).map(|i| (i % 251) as u8).collect();

    tree.write_file_pipelined(&mut conn, test_path, &test_data)
        .await
        .expect("write_file_pipelined failed (signing)");

    let data = tree
        .read_file_pipelined(&mut conn, test_path)
        .await
        .expect("read_file_pipelined failed (signing)");
    assert_eq!(data, test_data);

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

// ── Read-only share (smb-readonly) ───────────────────────────────────

#[tokio::test]
#[ignore]
async fn readonly_list_and_read_succeed() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(READONLY_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "readonly")
        .await
        .expect("tree connect failed");

    // List directory succeeds.
    let entries = tree
        .list_directory(&mut conn, "")
        .await
        .expect("list_directory failed");
    assert!(
        entries.iter().any(|e| e.name == "sample.txt"),
        "expected sample.txt in readonly share"
    );

    // Read file succeeds.
    let data = tree
        .read_file(&mut conn, "sample.txt")
        .await
        .expect("read_file failed on readonly share");
    assert!(!data.is_empty());

    // Stat file succeeds.
    let info = tree
        .stat(&mut conn, "sample.txt")
        .await
        .expect("stat failed on readonly share");
    assert!(!info.is_directory);

    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn readonly_write_returns_error() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(READONLY_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "readonly")
        .await
        .expect("tree connect failed");

    let result = tree.write_file(&mut conn, "should_fail.tmp", b"nope").await;

    assert!(result.is_err(), "expected write to fail on readonly share");

    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn readonly_delete_returns_error() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(READONLY_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "readonly")
        .await
        .expect("tree connect failed");

    let result = tree.delete_file(&mut conn, "sample.txt").await;
    assert!(result.is_err(), "expected delete to fail on readonly share");

    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn readonly_create_directory_returns_error() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(READONLY_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "readonly")
        .await
        .expect("tree connect failed");

    let result = tree.create_directory(&mut conn, "should_fail_dir").await;
    assert!(
        result.is_err(),
        "expected create_directory to fail on readonly share"
    );

    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

// ── SMB1-only server (smb-ancient) ───────────────────────────────────

#[tokio::test]
#[ignore]
async fn ancient_smb1_rejected_cleanly() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(ANCIENT_ADDR, TIMEOUT)
        .await
        .expect("TCP connect should succeed even to SMB1 server");

    // Negotiate should fail: server only speaks SMB1, we only speak SMB2+.
    let result = conn.negotiate().await;
    assert!(
        result.is_err(),
        "expected negotiate to fail against SMB1-only server"
    );
}

// ── Mandatory encryption (smb-encryption, share-level, SMB 3.1.1) ────

/// Helper: SmbClient connected to the encryption server.
async fn encryption_client() -> SmbClient {
    SmbClient::connect(ClientConfig {
        addr: ENCRYPTION_ADDR.to_string(),
        timeout: TIMEOUT,
        username: "testuser".to_string(),
        password: "testpass".to_string(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: true,
        dfs_target_overrides: HashMap::new(),
    })
    .await
    .expect("SmbClient::connect to smb-encryption failed")
}

#[tokio::test]
#[ignore]
async fn encryption_required_connect_and_operate() {
    let _ = env_logger::try_init();

    let mut client = encryption_client().await;
    let mut tree = client
        .connect_share("private")
        .await
        .expect("connect_share failed");

    let test_path = "docker_test_encrypted.tmp";
    let test_data = b"encrypted write test data 1234567890";

    client
        .write_file(&mut tree, test_path, test_data)
        .await
        .expect("write_file failed (encrypted)");

    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed (encrypted)");
    assert_eq!(data, test_data);

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn encryption_required_pipelined_large_file() {
    let _ = env_logger::try_init();

    let mut client = encryption_client().await;
    let mut tree = client
        .connect_share("private")
        .await
        .expect("connect_share failed");

    let test_path = "docker_test_encrypted_pipelined.tmp";
    let test_data: Vec<u8> = (0..524_288).map(|i| (i % 199) as u8).collect();

    client
        .write_file_pipelined(&mut tree, test_path, &test_data)
        .await
        .expect("write_file_pipelined failed (encrypted)");

    let data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed (encrypted)");
    assert_eq!(data, test_data);

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn encryption_required_list_shares() {
    let _ = env_logger::try_init();

    let mut client = encryption_client().await;
    let shares = client.list_shares().await.expect("list_shares failed");
    assert!(
        shares.iter().any(|s| s.name == "private"),
        "expected 'private' share, got: {:?}",
        shares.iter().map(|s| &s.name).collect::<Vec<_>>()
    );
}

// ── AES-128-CCM encryption (smb-encryption-aes128, SMB 3.0.2) ───────

#[tokio::test]
#[ignore]
async fn encryption_aes128_ccm_connect_and_operate() {
    let _ = env_logger::try_init();

    let mut client = SmbClient::connect(ClientConfig {
        addr: ENCRYPTION_AES128_ADDR.to_string(),
        timeout: TIMEOUT,
        username: "testuser".to_string(),
        password: "testpass".to_string(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: true,
        dfs_target_overrides: HashMap::new(),
    })
    .await
    .expect("connect failed");

    let params = client.params().unwrap();
    assert!(
        params.dialect as u16 >= 0x0300 && params.dialect as u16 <= 0x0302,
        "expected SMB 3.0-3.0.2, got {}",
        params.dialect
    );

    let mut tree = client
        .connect_share("private")
        .await
        .expect("connect_share failed");

    let test_path = "docker_test_aes128.tmp";
    let test_data = b"AES-128-CCM encrypted write test";

    client
        .write_file(&mut tree, test_path, test_data)
        .await
        .expect("write_file failed (AES-128-CCM)");

    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed (AES-128-CCM)");
    assert_eq!(data, test_data);

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

// ── Flaky server (smb-flaky, 5s up / 5s down) ───────────────────────

#[tokio::test]
#[ignore]
async fn flaky_connect_during_up_phase() {
    let _ = env_logger::try_init();

    // The flaky server cycles 5s up / 5s down. We retry the full
    // connect+negotiate sequence for up to 15 seconds to catch an "up" window.
    let deadline = std::time::Instant::now() + Duration::from_secs(15);
    let (mut conn, tree) = loop {
        let connect_result = async {
            let mut c = Connection::connect(FLAKY_ADDR, Duration::from_secs(2)).await?;
            c.negotiate().await?;
            let _session = Session::setup(&mut c, "", "", "").await?;
            let t = Tree::connect(&mut c, "public").await?;
            Ok::<_, smb2::Error>((c, t))
        }
        .await;

        match connect_result {
            Ok(result) => break result,
            Err(_) if std::time::Instant::now() < deadline => {
                tokio::time::sleep(Duration::from_millis(500)).await;
            }
            Err(e) => panic!("could not connect to flaky server within 15s: {}", e),
        }
    };

    // Verify basic operation works during the up phase.
    let entries = tree
        .list_directory(&mut conn, "")
        .await
        .expect("list_directory failed");
    drop(entries);

    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn flaky_error_is_clean_not_hang() {
    let _ = env_logger::try_init();

    // Connect during an up phase.
    let deadline = std::time::Instant::now() + Duration::from_secs(12);
    let mut client = loop {
        match SmbClient::connect(ClientConfig {
            addr: FLAKY_ADDR.to_string(),
            timeout: Duration::from_secs(1),
            username: String::new(),
            password: String::new(),
            domain: String::new(),
            auto_reconnect: false,
            compression: false,
            dfs_enabled: true,
            dfs_target_overrides: HashMap::new(),
        })
        .await
        {
            Ok(c) => break c,
            Err(_) if std::time::Instant::now() < deadline => {
                tokio::time::sleep(Duration::from_millis(500)).await;
            }
            Err(e) => panic!("could not connect to flaky server within 12s: {}", e),
        }
    };

    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    // Wait for the server to cycle down (up to 10s).
    // Keep trying operations — eventually one should fail with a clean error.
    let mut got_error = false;
    for _ in 0..20 {
        tokio::time::sleep(Duration::from_millis(500)).await;
        match client.list_directory(&mut tree, "").await {
            Ok(_) => continue,
            Err(smb2::Error::Io(_) | smb2::Error::Disconnected) => {
                got_error = true;
                break;
            }
            Err(e) => {
                // Any error is acceptable — the point is it didn't hang.
                got_error = true;
                eprintln!("flaky server error (acceptable): {}", e);
                break;
            }
        }
    }

    assert!(got_error, "expected an error after server went down");
}

// ── Slow server (smb-slow, 200ms latency) ────────────────────────────

#[tokio::test]
#[ignore]
async fn slow_operations_still_work() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(SLOW_ADDR, Duration::from_secs(10))
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "public")
        .await
        .expect("tree connect failed");

    let test_path = "docker_test_slow.tmp";
    let test_data = b"slow server test data";

    tree.write_file(&mut conn, test_path, test_data)
        .await
        .expect("write_file failed (slow)");

    let data = tree
        .read_file(&mut conn, test_path)
        .await
        .expect("read_file failed (slow)");
    assert_eq!(data, test_data);

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn slow_pipelined_large_file() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(SLOW_ADDR, Duration::from_secs(10))
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "public")
        .await
        .expect("tree connect failed");

    // 256 KB over a 200ms-latency link — pipelining matters here.
    let test_path = "docker_test_slow_pipelined.tmp";
    let test_data: Vec<u8> = (0..262_144).map(|i| (i % 199) as u8).collect();

    tree.write_file_pipelined(&mut conn, test_path, &test_data)
        .await
        .expect("write_file_pipelined failed (slow)");

    let data = tree
        .read_file_pipelined(&mut conn, test_path)
        .await
        .expect("read_file_pipelined failed (slow)");
    assert_eq!(data, test_data);

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

// ── 50-share server (smb-50shares) ───────────────────────────────────

#[tokio::test]
#[ignore]
async fn shares50_list_all() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(SHARES50_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");

    let shares = list_shares(&mut conn).await.expect("list_shares failed");

    // Filter out IPC$ and other admin shares.
    let user_shares: Vec<_> = shares.iter().filter(|s| !s.name.ends_with('$')).collect();

    assert_eq!(
        user_shares.len(),
        50,
        "expected 50 user shares, got {} (total including admin: {})",
        user_shares.len(),
        shares.len()
    );

    // Verify naming pattern.
    assert!(user_shares.iter().any(|s| s.name == "share_01"));
    assert!(user_shares.iter().any(|s| s.name == "share_50"));
}

#[tokio::test]
#[ignore]
async fn shares50_connect_to_first_and_last() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(SHARES50_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");

    // Connect to first share.
    let tree1 = Tree::connect(&mut conn, "share_01")
        .await
        .expect("tree connect to share_01 failed");
    tree1
        .disconnect(&mut conn)
        .await
        .expect("disconnect failed");

    // Connect to last share.
    let tree50 = Tree::connect(&mut conn, "share_50")
        .await
        .expect("tree connect to share_50 failed");
    tree50
        .disconnect(&mut conn)
        .await
        .expect("disconnect failed");
}

// ── Tiny MaxReadSize (smb-maxreadsize) ───────────────────────────────

#[tokio::test]
#[ignore]
async fn maxread_negotiated_small() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(MAXREAD_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");

    let params = conn.params().unwrap();
    assert!(
        params.max_read_size <= 65536,
        "expected max_read_size <= 64KB, got {}",
        params.max_read_size
    );
    assert!(
        params.max_write_size <= 65536,
        "expected max_write_size <= 64KB, got {}",
        params.max_write_size
    );
}

#[tokio::test]
#[ignore]
async fn maxread_large_file_still_works() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(MAXREAD_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "public")
        .await
        .expect("tree connect failed");

    // 512 KB file with 64 KB max read/write -> many chunks.
    let test_path = "docker_test_maxread.tmp";
    let test_data: Vec<u8> = (0..524_288).map(|i| (i % 199) as u8).collect();

    tree.write_file_pipelined(&mut conn, test_path, &test_data)
        .await
        .expect("write_file_pipelined failed (maxreadsize)");

    let data = tree
        .read_file_pipelined(&mut conn, test_path)
        .await
        .expect("read_file_pipelined failed (maxreadsize)");
    assert_eq!(data.len(), test_data.len(), "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn maxread_streaming_download() {
    let _ = env_logger::try_init();

    let mut client = SmbClient::connect(ClientConfig {
        addr: MAXREAD_ADDR.to_string(),
        timeout: TIMEOUT,
        username: String::new(),
        password: String::new(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: true,
        dfs_target_overrides: HashMap::new(),
    })
    .await
    .expect("connect failed");

    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "docker_test_maxread_stream.tmp";
    let test_data: Vec<u8> = (0..262_144).map(|i| (i % 251) as u8).collect();

    client
        .write_file(&mut tree, test_path, &test_data)
        .await
        .expect("write_file failed");

    let mut download = client
        .download(&tree, test_path)
        .await
        .expect("download failed");

    let mut received = Vec::new();
    let mut chunk_count = 0u32;
    while let Some(chunk) = download.next_chunk().await {
        let bytes = chunk.expect("next_chunk failed");
        received.extend_from_slice(&bytes);
        chunk_count += 1;
    }

    assert_eq!(received, test_data);
    // With 64KB max read and 256KB file, we should get at least 4 chunks.
    assert!(
        chunk_count >= 4,
        "expected at least 4 chunks, got {}",
        chunk_count
    );

    drop(download);
    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

// ── DFS tests (smb-dfs-root:10456 -> smb-dfs-target:10457) ─────────

/// Helper: SmbClient connected to the DFS root server.
///
/// The DFS link in the root share points to `smb-dfs-target\files` (Docker
/// internal hostname). Since the test runs on the host, we override
/// `smb-dfs-target` to `127.0.0.1:10457` (the port-mapped address).
async fn dfs_client() -> SmbClient {
    let mut overrides = HashMap::new();
    overrides.insert("smb-dfs-target".to_string(), DFS_TARGET_ADDR.to_string());
    SmbClient::connect(ClientConfig {
        addr: DFS_ROOT_ADDR.to_string(),
        timeout: TIMEOUT,
        username: String::new(),
        password: String::new(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: true,
        dfs_target_overrides: overrides,
    })
    .await
    .expect("SmbClient::connect to smb-dfs-root failed")
}

#[tokio::test]
#[ignore]
async fn dfs_tree_connect_reports_dfs_capability() {
    let _ = env_logger::try_init();

    let mut client = dfs_client().await;
    let tree = client
        .connect_share("dfs")
        .await
        .expect("connect_share('dfs') failed");

    assert!(tree.is_dfs, "expected DFS root share to report is_dfs=true");

    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn dfs_read_file_through_link() {
    let _ = env_logger::try_init();

    let mut client = dfs_client().await;
    let mut tree = client
        .connect_share("dfs")
        .await
        .expect("connect_share('dfs') failed");

    // "data/hello.txt" goes through the DFS link to smb-dfs-target's "files" share.
    let data = client
        .read_file(&mut tree, "data/hello.txt")
        .await
        .expect("read_file through DFS link failed");

    let text = String::from_utf8(data).expect("not UTF-8");
    assert_eq!(text.trim(), "Hello from DFS target!");

    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn dfs_list_directory_through_link() {
    let _ = env_logger::try_init();

    let mut client = dfs_client().await;
    let mut tree = client
        .connect_share("dfs")
        .await
        .expect("connect_share('dfs') failed");

    // List the "data/" directory, which is a DFS link to smb-dfs-target's "files" share.
    let entries = client
        .list_directory(&mut tree, "data")
        .await
        .expect("list_directory through DFS link failed");

    let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
    assert!(
        names.contains(&"hello.txt"),
        "expected hello.txt in DFS-linked directory, got: {:?}",
        names
    );
    assert!(
        names.contains(&"subdir"),
        "expected subdir in DFS-linked directory, got: {:?}",
        names
    );

    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn dfs_write_and_read_roundtrip() {
    let _ = env_logger::try_init();

    let test_path = "data/docker_dfs_roundtrip.tmp";
    let test_data = b"DFS roundtrip test data 1234567890";

    // Write through DFS link using a fresh client.
    {
        let mut client = dfs_client().await;
        let mut tree = client
            .connect_share("dfs")
            .await
            .expect("connect_share('dfs') failed");

        client
            .write_file(&mut tree, test_path, test_data)
            .await
            .expect("write_file through DFS link failed");

        client
            .disconnect_share(&tree)
            .await
            .expect("disconnect failed");
    }

    // Read back through DFS link using a fresh client (separate DFS resolution).
    {
        let mut client = dfs_client().await;
        let mut tree = client
            .connect_share("dfs")
            .await
            .expect("connect_share('dfs') failed");

        let data = client
            .read_file(&mut tree, test_path)
            .await
            .expect("read_file through DFS link failed");
        assert_eq!(data, test_data);

        // Clean up: after the DFS redirect, the tree now points to the
        // target share directly. Use the target-relative path (without
        // the "data/" DFS link prefix) for cleanup.
        client
            .delete_file(&mut tree, "docker_dfs_roundtrip.tmp")
            .await
            .expect("delete_file on target failed");

        client
            .disconnect_share(&tree)
            .await
            .expect("disconnect failed");
    }
}

// ── Streamed write (smb-guest) ──────────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_streamed_write() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_streamed_1mb.tmp";
    let total_size = 1_048_576usize; // 1 MB
    let chunk_size = 256 * 1024; // 256 KB
    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 199) as u8).collect();

    let mut offset = 0usize;
    let data_ref = &test_data;
    let mut next_chunk = move || -> Option<Result<Vec<u8>, std::io::Error>> {
        if offset >= data_ref.len() {
            return None;
        }
        let end = (offset + chunk_size).min(data_ref.len());
        let chunk = data_ref[offset..end].to_vec();
        offset = end;
        Some(Ok(chunk))
    };

    let written = client
        .write_file_streamed(&mut tree, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed");
    assert_eq!(written, total_size as u64);

    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data.len(), test_data.len(), "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_streamed_write_small_file() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_streamed_small.tmp";
    let test_data: Vec<u8> = (0..100).map(|i| (i % 199) as u8).collect();

    let mut called = false;
    let data_clone = test_data.clone();
    let mut next_chunk = move || -> Option<Result<Vec<u8>, std::io::Error>> {
        if called {
            return None;
        }
        called = true;
        Some(Ok(data_clone.clone()))
    };

    let written = client
        .write_file_streamed(&mut tree, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed");
    assert_eq!(written, 100);

    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data, test_data);

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_streamed_write_large() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_streamed_10mb.tmp";
    let total_size = 10 * 1024 * 1024usize; // 10 MB
    let chunk_size = 256 * 1024;
    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 199) as u8).collect();

    let mut offset = 0usize;
    let data_ref = &test_data;
    let mut next_chunk = move || -> Option<Result<Vec<u8>, std::io::Error>> {
        if offset >= data_ref.len() {
            return None;
        }
        let end = (offset + chunk_size).min(data_ref.len());
        let chunk = data_ref[offset..end].to_vec();
        offset = end;
        Some(Ok(chunk))
    };

    let start = std::time::Instant::now();
    let written = client
        .write_file_streamed(&mut tree, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed");
    let elapsed = start.elapsed();
    assert_eq!(written, total_size as u64);

    println!(
        "Streamed write: {} bytes in {:.2?} ({:.1} MB/s)",
        written,
        elapsed,
        written as f64 / (1024.0 * 1024.0) / elapsed.as_secs_f64()
    );

    let data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed");
    assert_eq!(data.len(), test_data.len(), "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_streamed_write_empty() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_streamed_empty.tmp";

    let mut next_chunk = || -> Option<Result<Vec<u8>, std::io::Error>> { None };

    let written = client
        .write_file_streamed(&mut tree, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed");
    assert_eq!(written, 0);

    // Verify empty file was created.
    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert!(data.is_empty(), "expected empty file");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn maxread_streamed_write() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(MAXREAD_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "public")
        .await
        .expect("tree connect failed");

    let test_path = "smb2_test_streamed_maxread.tmp";
    let total_size = 512 * 1024usize; // 512 KB
    let chunk_size = 64 * 1024; // 64 KB (matches server max)
    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 199) as u8).collect();

    let mut offset = 0usize;
    let data_ref = &test_data;
    let mut next_chunk = move || -> Option<Result<Vec<u8>, std::io::Error>> {
        if offset >= data_ref.len() {
            return None;
        }
        let end = (offset + chunk_size).min(data_ref.len());
        let chunk = data_ref[offset..end].to_vec();
        offset = end;
        Some(Ok(chunk))
    };

    let written = tree
        .write_file_streamed(&mut conn, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed (maxreadsize)");
    assert_eq!(written, total_size as u64);

    let data = tree
        .read_file_pipelined(&mut conn, test_path)
        .await
        .expect("read_file_pipelined failed (maxreadsize)");
    assert_eq!(data.len(), test_data.len(), "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn signing_streamed_write() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(SIGNING_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "testuser", "testpass", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "private")
        .await
        .expect("tree connect failed");

    let test_path = "smb2_test_streamed_signing.tmp";
    let total_size = 512 * 1024usize;
    let chunk_size = 64 * 1024;
    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 199) as u8).collect();

    let mut offset = 0usize;
    let data_ref = &test_data;
    let mut next_chunk = move || -> Option<Result<Vec<u8>, std::io::Error>> {
        if offset >= data_ref.len() {
            return None;
        }
        let end = (offset + chunk_size).min(data_ref.len());
        let chunk = data_ref[offset..end].to_vec();
        offset = end;
        Some(Ok(chunk))
    };

    let written = tree
        .write_file_streamed(&mut conn, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed (signing)");
    assert_eq!(written, total_size as u64);

    let data = tree
        .read_file_pipelined(&mut conn, test_path)
        .await
        .expect("read_file_pipelined failed (signing)");
    assert_eq!(data.len(), test_data.len(), "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    tree.delete_file(&mut conn, test_path)
        .await
        .expect("delete_file failed");
    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn encryption_streamed_write() {
    let _ = env_logger::try_init();

    let mut client = encryption_client().await;
    let mut tree = client
        .connect_share("private")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_streamed_encryption.tmp";
    let total_size = 512 * 1024usize;
    let chunk_size = 64 * 1024;
    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 199) as u8).collect();

    let mut offset = 0usize;
    let data_ref = &test_data;
    let mut next_chunk = move || -> Option<Result<Vec<u8>, std::io::Error>> {
        if offset >= data_ref.len() {
            return None;
        }
        let end = (offset + chunk_size).min(data_ref.len());
        let chunk = data_ref[offset..end].to_vec();
        offset = end;
        Some(Ok(chunk))
    };

    let written = client
        .write_file_streamed(&mut tree, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed (encryption)");
    assert_eq!(written, total_size as u64);

    let data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed (encryption)");
    assert_eq!(data.len(), test_data.len(), "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn readonly_streamed_write_fails() {
    let _ = env_logger::try_init();

    let mut conn = Connection::connect(READONLY_ADDR, TIMEOUT)
        .await
        .expect("connect failed");
    conn.negotiate().await.expect("negotiate failed");
    let _session = Session::setup(&mut conn, "", "", "")
        .await
        .expect("session setup failed");
    let tree = Tree::connect(&mut conn, "readonly")
        .await
        .expect("tree connect failed");

    let mut next_chunk =
        || -> Option<Result<Vec<u8>, std::io::Error>> { Some(Ok(vec![0x42; 100])) };

    let result = tree
        .write_file_streamed(
            &mut conn,
            "smb2_test_streamed_readonly.tmp",
            &mut next_chunk,
        )
        .await;

    assert!(
        result.is_err(),
        "expected streamed write to fail on readonly share"
    );

    tree.disconnect(&mut conn).await.expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_streamed_write_early_stop() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_streamed_early_stop.tmp";
    let chunk_size = 1024usize;
    let chunks_to_send = 2;

    // Build deterministic data for 2 chunks.
    let expected_data: Vec<u8> = (0..(chunk_size * chunks_to_send))
        .map(|i| (i % 199) as u8)
        .collect();

    let mut call_count = 0usize;
    let data_ref = &expected_data;
    let mut next_chunk = move || -> Option<Result<Vec<u8>, std::io::Error>> {
        if call_count >= chunks_to_send {
            return None; // Stop early (a 10-chunk file would need 10 calls).
        }
        let start = call_count * chunk_size;
        let end = start + chunk_size;
        let chunk = data_ref[start..end].to_vec();
        call_count += 1;
        Some(Ok(chunk))
    };

    let written = client
        .write_file_streamed(&mut tree, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed");
    assert_eq!(written, (chunk_size * chunks_to_send) as u64);

    // Verify partial file exists with correct content.
    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data.len(), expected_data.len(), "size mismatch");
    assert_eq!(data, expected_data, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

// ── Streamed write stress tests ──────────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_streamed_write_stress_100mb() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_streamed_stress_100mb.tmp";
    let total_size = 100 * 1024 * 1024usize; // 100 MB
    let chunk_size = 1024 * 1024; // 1 MB chunks

    // Build deterministic data.
    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 251) as u8).collect();

    let mut offset = 0usize;
    let data_ref = &test_data;
    let mut next_chunk = move || -> Option<Result<Vec<u8>, std::io::Error>> {
        if offset >= data_ref.len() {
            return None;
        }
        let end = (offset + chunk_size).min(data_ref.len());
        let chunk = data_ref[offset..end].to_vec();
        offset = end;
        Some(Ok(chunk))
    };

    let start = std::time::Instant::now();
    let written = client
        .write_file_streamed(&mut tree, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed");
    let write_elapsed = start.elapsed();
    assert_eq!(written, total_size as u64);

    println!(
        "Stress write: {} MB in {:.2?} ({:.1} MB/s)",
        total_size / (1024 * 1024),
        write_elapsed,
        written as f64 / (1024.0 * 1024.0) / write_elapsed.as_secs_f64()
    );

    // Read back and verify integrity.
    let read_data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed");
    assert_eq!(read_data.len(), test_data.len(), "size mismatch");
    assert_eq!(
        read_data, test_data,
        "content mismatch in 100 MB stress test"
    );

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_streamed_write_rapid_sequential_50_files() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let file_count = 50;
    let file_size = 1024usize; // 1 KB each

    for i in 0..file_count {
        let test_path = format!("smb2_test_rapid_seq_{:03}.tmp", i);
        let test_data: Vec<u8> = (0..file_size).map(|j| ((j + i * 7) % 251) as u8).collect();

        let mut called = false;
        let data_clone = test_data.clone();
        let mut next_chunk = move || -> Option<Result<Vec<u8>, std::io::Error>> {
            if called {
                return None;
            }
            called = true;
            Some(Ok(data_clone.clone()))
        };

        let written = client
            .write_file_streamed(&mut tree, &test_path, &mut next_chunk)
            .await
            .unwrap_or_else(|e| panic!("write_file_streamed failed on file {}: {}", i, e));
        assert_eq!(written, file_size as u64, "wrong byte count for file {}", i);
    }

    // Read back all 50 files and verify.
    for i in 0..file_count {
        let test_path = format!("smb2_test_rapid_seq_{:03}.tmp", i);
        let expected: Vec<u8> = (0..file_size).map(|j| ((j + i * 7) % 251) as u8).collect();

        let data = client
            .read_file(&mut tree, &test_path)
            .await
            .unwrap_or_else(|e| panic!("read_file failed on file {}: {}", i, e));
        assert_eq!(data, expected, "content mismatch on file {}", i);
    }

    // Cleanup.
    for i in 0..file_count {
        let test_path = format!("smb2_test_rapid_seq_{:03}.tmp", i);
        client
            .delete_file(&mut tree, &test_path)
            .await
            .unwrap_or_else(|e| panic!("delete_file failed on file {}: {}", i, e));
    }

    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_streamed_write_large_single_chunk() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_streamed_large_chunk.tmp";
    let total_size = 5 * 1024 * 1024usize; // 5 MB as a single chunk
    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 251) as u8).collect();

    // Deliver the entire 5 MB in one callback call. This forces the
    // chunk-splitting logic to split against max_write_size.
    let mut called = false;
    let data_clone = test_data.clone();
    let mut next_chunk = move || -> Option<Result<Vec<u8>, std::io::Error>> {
        if called {
            return None;
        }
        called = true;
        Some(Ok(data_clone.clone()))
    };

    let written = client
        .write_file_streamed(&mut tree, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed");
    assert_eq!(written, total_size as u64);

    let read_data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed");
    assert_eq!(read_data.len(), test_data.len(), "size mismatch");
    assert_eq!(
        read_data, test_data,
        "content mismatch in large single-chunk test"
    );

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_streamed_write_alternating_sizes() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_streamed_alternating.tmp";

    // Build chunks alternating between 1 byte and 1 MB.
    let small_size = 1usize;
    let large_size = 1024 * 1024usize;
    let num_pairs = 5; // 5 pairs of (1 byte, 1 MB)

    let mut expected_data = Vec::new();
    let mut chunks: Vec<Vec<u8>> = Vec::new();
    for pair in 0..num_pairs {
        // Small chunk: 1 byte.
        let small = vec![(pair * 2) as u8; small_size];
        expected_data.extend_from_slice(&small);
        chunks.push(small);

        // Large chunk: 1 MB with deterministic pattern.
        let large: Vec<u8> = (0..large_size)
            .map(|j| ((j + pair * 13) % 251) as u8)
            .collect();
        expected_data.extend_from_slice(&large);
        chunks.push(large);
    }

    let mut chunk_iter = chunks.into_iter();
    let mut next_chunk =
        move || -> Option<Result<Vec<u8>, std::io::Error>> { chunk_iter.next().map(Ok) };

    let written = client
        .write_file_streamed(&mut tree, test_path, &mut next_chunk)
        .await
        .expect("write_file_streamed failed");
    assert_eq!(written, expected_data.len() as u64);

    let read_data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed");
    assert_eq!(read_data.len(), expected_data.len(), "size mismatch");
    assert_eq!(
        read_data, expected_data,
        "content mismatch in alternating sizes test"
    );

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

// ── FileWriter (push-based streaming writes) ──────────────────────────

#[tokio::test]
#[ignore]
async fn guest_file_writer_basic() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_basic.bin";
    let chunk1 = b"Hello, ";
    let chunk2 = b"FileWriter ";
    let chunk3 = b"world!";
    let expected: Vec<u8> = [&chunk1[..], &chunk2[..], &chunk3[..]].concat();

    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed");

    writer
        .write_chunk(chunk1)
        .await
        .expect("write_chunk 1 failed");
    writer
        .write_chunk(chunk2)
        .await
        .expect("write_chunk 2 failed");
    writer
        .write_chunk(chunk3)
        .await
        .expect("write_chunk 3 failed");

    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, expected.len() as u64);

    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data, expected, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_file_writer_large() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_large.bin";
    let chunk_size = 1024 * 1024; // 1 MB
    let num_chunks = 5;
    let total_size = chunk_size * num_chunks;
    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 199) as u8).collect();

    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed");

    for chunk_idx in 0..num_chunks {
        let start = chunk_idx * chunk_size;
        let end = start + chunk_size;
        writer
            .write_chunk(&test_data[start..end])
            .await
            .expect("write_chunk failed");
    }

    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, total_size as u64);

    let data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed");
    assert_eq!(data.len(), test_data.len(), "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_file_writer_empty_file() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_empty.bin";

    let writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed");

    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, 0);

    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert!(data.is_empty(), "expected empty file");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_file_writer_single_byte() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_single_byte.bin";

    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed");

    writer
        .write_chunk(&[0x42])
        .await
        .expect("write_chunk failed");

    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, 1);

    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data, vec![0x42]);

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_file_writer_overwrite() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_overwrite.bin";

    // Write a 10 KB file first.
    let big_data: Vec<u8> = (0..10240).map(|i| (i % 251) as u8).collect();
    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed (first write)");
    writer
        .write_chunk(&big_data)
        .await
        .expect("write_chunk failed (first write)");
    let written1 = writer.finish().await.expect("finish failed (first write)");
    assert_eq!(written1, 10240);

    // Overwrite with a 1 KB file.
    let small_data: Vec<u8> = (0..1024).map(|i| (i % 173) as u8).collect();
    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed (overwrite)");
    writer
        .write_chunk(&small_data)
        .await
        .expect("write_chunk failed (overwrite)");
    let written2 = writer.finish().await.expect("finish failed (overwrite)");
    assert_eq!(written2, 1024);

    // Read back -- must be exactly 1 KB, no leftover from old file.
    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data.len(), 1024, "expected 1 KB, got {} bytes", data.len());
    assert_eq!(data, small_data, "content mismatch after overwrite");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_file_writer_equivalence_with_pipelined() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_data: Vec<u8> = (0..512 * 1024).map(|i| (i % 199) as u8).collect();

    // Write via write_file_pipelined.
    let pipelined_path = "smb2_test_fw_equiv_pipelined.bin";
    client
        .write_file_pipelined(&mut tree, pipelined_path, &test_data)
        .await
        .expect("write_file_pipelined failed");

    // Write via FileWriter.
    let writer_path = "smb2_test_fw_equiv_writer.bin";
    let chunk_size = 64 * 1024;
    let mut writer = client
        .create_file_writer(&tree, writer_path)
        .await
        .expect("create_file_writer failed");
    for chunk in test_data.chunks(chunk_size) {
        writer.write_chunk(chunk).await.expect("write_chunk failed");
    }
    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, test_data.len() as u64);

    // Read both back and compare.
    let pipelined_data = client
        .read_file_pipelined(&mut tree, pipelined_path)
        .await
        .expect("read pipelined file failed");
    let writer_data = client
        .read_file_pipelined(&mut tree, writer_path)
        .await
        .expect("read writer file failed");

    assert_eq!(pipelined_data.len(), writer_data.len(), "size mismatch");
    assert_eq!(
        pipelined_data, writer_data,
        "FileWriter output differs from write_file_pipelined"
    );

    client
        .delete_file(&mut tree, pipelined_path)
        .await
        .expect("delete pipelined file failed");
    client
        .delete_file(&mut tree, writer_path)
        .await
        .expect("delete writer file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn guest_file_writer_binary_data() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_binary.bin";

    // Build data containing all 256 byte values, repeated for good measure.
    let mut test_data = Vec::with_capacity(256 * 4);
    for round in 0..4u8 {
        for byte in 0..=255u8 {
            test_data.push(byte.wrapping_add(round.wrapping_mul(37)));
        }
    }

    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed");

    // Write in two chunks to exercise boundary handling.
    let mid = test_data.len() / 2;
    writer
        .write_chunk(&test_data[..mid])
        .await
        .expect("write_chunk 1 failed");
    writer
        .write_chunk(&test_data[mid..])
        .await
        .expect("write_chunk 2 failed");

    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, test_data.len() as u64);

    let data = client
        .read_file(&mut tree, test_path)
        .await
        .expect("read_file failed");
    assert_eq!(data, test_data, "binary data mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn maxread_file_writer() {
    let _ = env_logger::try_init();

    let mut client = SmbClient::connect(ClientConfig {
        addr: MAXREAD_ADDR.to_string(),
        timeout: TIMEOUT,
        username: String::new(),
        password: String::new(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: false,
        dfs_target_overrides: HashMap::new(),
    })
    .await
    .expect("connect failed");
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_maxread.bin";
    let total_size = 200 * 1024usize; // 200 KB
    let chunk_size = 50 * 1024; // 50 KB chunks
    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 199) as u8).collect();

    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed");

    for chunk in test_data.chunks(chunk_size) {
        writer.write_chunk(chunk).await.expect("write_chunk failed");
    }

    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, total_size as u64);

    let data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed");
    assert_eq!(data.len(), test_data.len(), "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn signing_file_writer() {
    let _ = env_logger::try_init();

    let mut client = SmbClient::connect(ClientConfig {
        addr: SIGNING_ADDR.to_string(),
        timeout: TIMEOUT,
        username: "testuser".to_string(),
        password: "testpass".to_string(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: false,
        dfs_target_overrides: HashMap::new(),
    })
    .await
    .expect("connect failed");
    let mut tree = client
        .connect_share("private")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_signing.bin";
    let test_data: Vec<u8> = (0..128 * 1024).map(|i| (i % 199) as u8).collect();

    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed");

    for chunk in test_data.chunks(32 * 1024) {
        writer.write_chunk(chunk).await.expect("write_chunk failed");
    }

    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, test_data.len() as u64);

    let data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed");
    assert_eq!(data, test_data, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn encryption_file_writer() {
    let _ = env_logger::try_init();

    let mut client = encryption_client().await;
    let mut tree = client
        .connect_share("private")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_encryption.bin";
    let test_data: Vec<u8> = (0..128 * 1024).map(|i| (i % 199) as u8).collect();

    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed");

    for chunk in test_data.chunks(32 * 1024) {
        writer.write_chunk(chunk).await.expect("write_chunk failed");
    }

    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, test_data.len() as u64);

    let data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed");
    assert_eq!(data, test_data, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn readonly_file_writer_error() {
    let _ = env_logger::try_init();

    let mut client = SmbClient::connect(ClientConfig {
        addr: READONLY_ADDR.to_string(),
        timeout: TIMEOUT,
        username: String::new(),
        password: String::new(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: false,
        dfs_target_overrides: HashMap::new(),
    })
    .await
    .expect("connect failed");
    let tree = client
        .connect_share("readonly")
        .await
        .expect("connect_share failed");

    let is_err = client
        .create_file_writer(&tree, "smb2_test_file_writer_readonly.bin")
        .await
        .is_err();

    assert!(
        is_err,
        "expected create_file_writer to fail on readonly share"
    );

    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

// ── FileWriter stress tests ──────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn guest_file_writer_stress_100mb() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_stress_100mb.bin";
    let chunk_size = 1024 * 1024; // 1 MB
    let num_chunks = 100;
    let total_size = chunk_size * num_chunks;

    // Build deterministic data
    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 251) as u8).collect();

    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed");

    for chunk_idx in 0..num_chunks {
        let start = chunk_idx * chunk_size;
        let end = start + chunk_size;
        writer
            .write_chunk(&test_data[start..end])
            .await
            .expect("write_chunk failed");
    }

    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, total_size as u64);

    let data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed");
    assert_eq!(data.len(), total_size, "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn slow_file_writer_stress_100mb() {
    let _ = env_logger::try_init();

    let mut client = SmbClient::connect(ClientConfig {
        addr: SLOW_ADDR.to_string(),
        timeout: Duration::from_secs(30),
        username: String::new(),
        password: String::new(),
        domain: String::new(),
        auto_reconnect: false,
        compression: false,
        dfs_enabled: false,
        dfs_target_overrides: HashMap::new(),
    })
    .await
    .expect("connect failed");
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");

    let test_path = "smb2_test_file_writer_slow_stress.bin";
    let chunk_size = 512 * 1024; // 512 KB chunks to test more pipelining cycles
    let num_chunks = 200; // 100 MB total
    let total_size = chunk_size * num_chunks;

    let test_data: Vec<u8> = (0..total_size).map(|i| (i % 173) as u8).collect();

    let mut writer = client
        .create_file_writer(&tree, test_path)
        .await
        .expect("create_file_writer failed");

    for chunk_idx in 0..num_chunks {
        let start = chunk_idx * chunk_size;
        let end = start + chunk_size;
        writer
            .write_chunk(&test_data[start..end])
            .await
            .expect("write_chunk failed");
    }

    let bytes_written = writer.finish().await.expect("finish failed");
    assert_eq!(bytes_written, total_size as u64);

    let data = client
        .read_file_pipelined(&mut tree, test_path)
        .await
        .expect("read_file_pipelined failed");
    assert_eq!(data.len(), total_size, "size mismatch");
    assert_eq!(data, test_data, "content mismatch");

    client
        .delete_file(&mut tree, test_path)
        .await
        .expect("delete_file failed");
    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

// ── Diagnostics (M3) ──────────────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn diagnostics_basic_counters_against_smb_guest() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");
    let _entries = client
        .list_directory(&mut tree, "")
        .await
        .expect("list_directory failed");

    let d = client.diagnostics();

    // Negotiated parameters look real.
    let n = d.primary.negotiated.expect("negotiated after connect");
    assert!(
        n.dialect as u16 >= 0x0210,
        "expected SMB 2.1+, got {:?}",
        n.dialect
    );
    assert!(n.max_read_size > 0);

    // Counters reflect at least negotiate + session setup + tree connect + list.
    assert!(d.primary.metrics.requests_sent >= 4);
    assert!(d.primary.metrics.responses_routed_ok >= 4);
    assert!(d.primary.metrics.wire_bytes_sent > 0);
    assert!(d.primary.metrics.wire_bytes_received > 0);
    assert_eq!(d.primary.metrics.requests_returned_err, 0);
    assert_eq!(d.primary.metrics.responses_stray, 0);
    assert_eq!(d.primary.metrics.responses_late_after_drop, 0);

    // Session is populated.
    let s = d.primary.session.expect("session after setup");
    assert_ne!(s.session_id, smb2::types::SessionId::NONE);

    // Server name matches the address.
    assert!(
        d.primary.server.starts_with("127.0.0.1"),
        "server: {:?}",
        d.primary.server
    );

    client
        .disconnect_share(&tree)
        .await
        .expect("disconnect failed");
}

#[tokio::test]
#[ignore]
async fn diagnostics_reconnects_counter_survives_reconnect() {
    let _ = env_logger::try_init();

    let mut client = guest_client().await;
    let mut tree = client
        .connect_share("public")
        .await
        .expect("connect_share failed");
    let _ = client.list_directory(&mut tree, "").await;
    let before = client.diagnostics();
    assert_eq!(before.client.metrics.reconnects, 0);

    client.reconnect().await.expect("reconnect failed");
    // Per-conn counters reset to a fresh `Inner` and only reflect the
    // post-reconnect negotiate + session setup; client-level survives.
    let after = client.diagnostics();
    assert_eq!(after.client.metrics.reconnects, 1);
    assert!(
        after.primary.metrics.responses_routed_ok < before.primary.metrics.responses_routed_ok,
        "per-conn counters reset across reconnect: before {} → after {}",
        before.primary.metrics.responses_routed_ok,
        after.primary.metrics.responses_routed_ok,
    );
}