summaryrefslogtreecommitdiffstats
path: root/private/nw/svcdlls/nwwks/server/device.c
blob: a280f337420c51f48d7de3422b432651753500cf (plain) (blame)
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

/*++

Copyright (c) 1991-1993  Microsoft Corporation

Module Name:

    device.c

Abstract:

    This module contains the support routines for the APIs that call
    into the NetWare redirector

Author:

    Rita Wong       (ritaw)     20-Feb-1991
    Colin Watson    (colinw)    30-Dec-1992

Revision History:

--*/

#include <nw.h>
#include <nwcons.h>
#include <nwxchg.h>
#include <nwapi32.h>
#include <nwstatus.h>
#include <nwmisc.h>
#include <nwcons.h>
#include <nds.h>
#include <svcguid.h>
#include <tdi.h>

#define NW_LINKAGE_REGISTRY_PATH  L"NWCWorkstation\\Linkage"
#define NW_BIND_VALUENAME         L"Bind"

#define TWO_KB                  2048
#define EIGHT_KB                8192
#define EXTRA_BYTES              256

#define TREECHAR                L'*'
#define BUFFSIZE                1024

//-------------------------------------------------------------------//
//                                                                   //
// Local Function Prototypes                                         //
//                                                                   //
//-------------------------------------------------------------------//


STATIC
NTSTATUS
BindToEachTransport(
    IN PWSTR ValueName,
    IN ULONG ValueType,
    IN PVOID ValueData,
    IN ULONG ValueLength,
    IN PVOID Context,
    IN PVOID EntryContext
    );

DWORD
NwBindTransport(
    IN  LPWSTR TransportName,
    IN  DWORD QualityOfService
    );

DWORD
GetConnectedBinderyServers(
    OUT LPNW_ENUM_CONTEXT ContextHandle
    );

DWORD
GetTreeEntriesFromBindery(
    OUT LPNW_ENUM_CONTEXT ContextHandle
    );

DWORD
NwGetConnectionStatus(
    IN     LPWSTR  pszServerName,
    IN OUT PDWORD  ResumeKey,
    OUT    LPBYTE  *Buffer,
    OUT    PDWORD  EntriesRead
    );

VOID
GetNearestDirServer(
    IN  LPWSTR  TreeName,
    OUT LPDWORD lpdwReplicaAddressSize,
    OUT LPBYTE  lpReplicaAddress
    );

BOOL
NwpCompareTreeNames(
    LPWSTR lpServiceInstanceName,
    LPWSTR lpTreeName
    );

//-------------------------------------------------------------------//
//                                                                   //
// Global variables                                                  //
//                                                                   //
//-------------------------------------------------------------------//

//
// Handle to the Redirector FSD
//
STATIC HANDLE RedirDeviceHandle = NULL;

//
// Redirector name in NT string format
//
STATIC UNICODE_STRING RedirDeviceName;


DWORD
NwInitializeRedirector(
    VOID
    )
/*++

Routine Description:

    This routine initializes the NetWare redirector FSD.

Arguments:

    None.

Return Value:

    NO_ERROR or reason for failure.

--*/
{
    DWORD error;
    NWR_REQUEST_PACKET Rrp;


    //
    // Initialize global handles
    //
    RedirDeviceHandle = NULL;

    //
    // Initialize the global NT-style redirector device name string.
    //
    RtlInitUnicodeString(&RedirDeviceName, DD_NWFS_DEVICE_NAME_U);

    //
    // Load driver
    //
    error = NwLoadOrUnloadDriver(TRUE);

    if (error != NO_ERROR && error != ERROR_SERVICE_ALREADY_RUNNING) {
        return error;
    }

    if ((error = NwOpenRedirector()) != NO_ERROR) {

        //
        // Unload the redirector driver
        //
        (void) NwLoadOrUnloadDriver(FALSE);
        return error;
    }

    //
    // Send the start FSCTL to the redirector
    //
    Rrp.Version = REQUEST_PACKET_VERSION;

    return NwRedirFsControl(
                RedirDeviceHandle,
                FSCTL_NWR_START,
                &Rrp,
                sizeof(NWR_REQUEST_PACKET),
                NULL,
                0,
                NULL
                );
}



DWORD
NwOpenRedirector(
    VOID
    )
/*++

Routine Description:

    This routine opens the NT NetWare redirector FSD.

Arguments:

    None.

Return Value:

    NO_ERROR or reason for failure.

--*/
{
    return RtlNtStatusToDosError(
               NwOpenHandle(&RedirDeviceName, FALSE, &RedirDeviceHandle)
               );
}



DWORD
NwShutdownRedirector(
    VOID
    )
/*++

Routine Description:

    This routine stops the NetWare Redirector FSD and unloads it if
    possible.

Arguments:

    None.

Return Value:

    NO_ERROR or ERROR_REDIRECTOR_HAS_OPEN_HANDLES

--*/
{
    NWR_REQUEST_PACKET Rrp;
    DWORD error;


    Rrp.Version = REQUEST_PACKET_VERSION;

    error = NwRedirFsControl(
                RedirDeviceHandle,
                FSCTL_NWR_STOP,
                &Rrp,
                sizeof(NWR_REQUEST_PACKET),
                NULL,
                0,
                NULL
                );

    (void) NtClose(RedirDeviceHandle);

    RedirDeviceHandle = NULL;

    if (error != ERROR_REDIRECTOR_HAS_OPEN_HANDLES) {

        //
        // Unload the redirector only if all its open handles are closed.
        //
        (void) NwLoadOrUnloadDriver(FALSE);
    }

    return error;
}


DWORD
NwLoadOrUnloadDriver(
    BOOL Load
    )
/*++

Routine Description:

    This routine loads or unloads the NetWare redirector driver.

Arguments:

    Load - Supplies the flag which if TRUE load the driver; otherwise
        unloads the driver.

Return Value:

    NO_ERROR or reason for failure.

--*/
{

    LPWSTR DriverRegistryName;
    UNICODE_STRING DriverRegistryString;
    NTSTATUS ntstatus;
    BOOLEAN WasEnabled;


    DriverRegistryName = (LPWSTR) LocalAlloc(
                                      LMEM_FIXED,
                                      (UINT) (sizeof(SERVICE_REGISTRY_KEY) +
                                              (wcslen(NW_DRIVER_NAME) *
                                               sizeof(WCHAR)))
                                      );

    if (DriverRegistryName == NULL) {
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    ntstatus = RtlAdjustPrivilege(
                   SE_LOAD_DRIVER_PRIVILEGE,
                   TRUE,
                   FALSE,
                   &WasEnabled
                   );

    if (! NT_SUCCESS(ntstatus)) {
        (void) LocalFree(DriverRegistryName);
        return RtlNtStatusToDosError(ntstatus);
    }

    wcscpy(DriverRegistryName, SERVICE_REGISTRY_KEY);
    wcscat(DriverRegistryName, NW_DRIVER_NAME);

    RtlInitUnicodeString(&DriverRegistryString, DriverRegistryName);

    if (Load) {
        ntstatus = NtLoadDriver(&DriverRegistryString);
    }
    else {
        ntstatus = NtUnloadDriver(&DriverRegistryString);
    }

    (void) RtlAdjustPrivilege(
               SE_LOAD_DRIVER_PRIVILEGE,
               WasEnabled,
               FALSE,
               &WasEnabled
               );

    (void) LocalFree(DriverRegistryName);

    if (Load) {
        if (ntstatus != STATUS_SUCCESS && ntstatus != STATUS_IMAGE_ALREADY_LOADED) {
            LPWSTR SubString[1];

            KdPrint(("NWWORKSTATION: NtLoadDriver returned %08lx\n", ntstatus));

            SubString[0] = NW_DRIVER_NAME;

            NwLogEvent(
                EVENT_NWWKSTA_CANT_CREATE_REDIRECTOR,
                1,
                SubString,
                ntstatus
                );
        }
    }

    if (ntstatus == STATUS_OBJECT_NAME_NOT_FOUND) {
        return ERROR_FILE_NOT_FOUND;
    }

    return NwMapStatus(ntstatus);
}


DWORD
NwRedirFsControl(
    IN  HANDLE FileHandle,
    IN  ULONG RedirControlCode,
    IN  PNWR_REQUEST_PACKET Rrp,
    IN  ULONG RrpLength,
    IN  PVOID SecondBuffer OPTIONAL,
    IN  ULONG SecondBufferLength,
    OUT PULONG Information OPTIONAL
    )
/*++

Routine Description:

Arguments:

    FileHandle - Supplies a handle to the file or device on which the service
        is being performed.

    RedirControlCode - Supplies the NtFsControlFile function code given to
        the redirector.

    Rrp - Supplies the redirector request packet.

    RrpLength - Supplies the length of the redirector request packet.

    SecondBuffer - Supplies the second buffer in call to NtFsControlFile.

    SecondBufferLength - Supplies the length of the second buffer.

    Information - Returns the information field of the I/O status block.

Return Value:

    NO_ERROR or reason for failure.

--*/

{
    NTSTATUS ntstatus;
    IO_STATUS_BLOCK IoStatusBlock;


    //
    // Send the request to the Redirector FSD.
    //
    ntstatus = NtFsControlFile(
                   FileHandle,
                   NULL,
                   NULL,
                   NULL,
                   &IoStatusBlock,
                   RedirControlCode,
                   (PVOID) Rrp,
                   RrpLength,
                   SecondBuffer,
                   SecondBufferLength
                   );

    if (ntstatus == STATUS_SUCCESS) {
        ntstatus = IoStatusBlock.Status;
    }

    if (ARGUMENT_PRESENT(Information)) {
        *Information = IoStatusBlock.Information;
    }

#if DBG
    if (ntstatus != STATUS_SUCCESS) {
        IF_DEBUG(DEVICE) {
            KdPrint(("NWWORKSTATION: fsctl to redir returns %08lx\n", ntstatus));
        }
    }
#endif

    return NwMapStatus(ntstatus);
}


DWORD
NwBindToTransports(
    VOID
    )

/*++

Routine Description:

    This routine binds to every transport specified under the linkage
    key of the NetWare Workstation service.

Arguments:

    None.

Return Value:

    NET_API_STATUS - success/failure of the operation.

--*/

{
    NTSTATUS ntstatus;
    PRTL_QUERY_REGISTRY_TABLE QueryTable;
    ULONG NumberOfBindings = 0;


    //
    // Ask the RTL to call us back for each subvalue in the MULTI_SZ
    // value \NWCWorkstation\Linkage\Bind.
    //

    if ((QueryTable = (PVOID) LocalAlloc(
                                  LMEM_ZEROINIT,
                                  sizeof(RTL_QUERY_REGISTRY_TABLE) * 2
                                  )) == NULL) {
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    QueryTable[0].QueryRoutine = (PRTL_QUERY_REGISTRY_ROUTINE) BindToEachTransport;
    QueryTable[0].Flags = 0;
    QueryTable[0].Name = NW_BIND_VALUENAME;
    QueryTable[0].EntryContext = NULL;
    QueryTable[0].DefaultType = REG_NONE;
    QueryTable[0].DefaultData = NULL;
    QueryTable[0].DefaultLength = 0;

    QueryTable[1].QueryRoutine = NULL;
    QueryTable[1].Flags = 0;
    QueryTable[1].Name = NULL;

    ntstatus = RtlQueryRegistryValues(
                   RTL_REGISTRY_SERVICES,
                   NW_LINKAGE_REGISTRY_PATH,
                   QueryTable,
                   &NumberOfBindings,
                   NULL
                   );

    (void) LocalFree((HLOCAL) QueryTable);

    //
    // If failed to bind to any transports, the workstation will
    // not start.
    //

    if (! NT_SUCCESS(ntstatus)) {
#if DBG
        IF_DEBUG(INIT) {
            KdPrint(("NwBindToTransports: RtlQueryRegistryValues failed: "
                      "%lx\n", ntstatus));
        }
#endif
        return RtlNtStatusToDosError(ntstatus);
    }

    if (NumberOfBindings == 0) {

        NwLogEvent(
            EVENT_NWWKSTA_NO_TRANSPORTS,
            0,
            NULL,
            NO_ERROR
            );

        KdPrint(("NWWORKSTATION: NwBindToTransports: could not bind "
                 "to any transport\n"));

        return ERROR_INVALID_PARAMETER; // BUGBUG: Bad return code.
                                        // Create a NetWare specific set?
    }

    return NO_ERROR;
}


STATIC
NTSTATUS
BindToEachTransport(
    IN PWSTR ValueName,
    IN ULONG ValueType,
    IN PVOID ValueData,
    IN ULONG ValueLength,
    IN PVOID Context,
    IN PVOID EntryContext
    )
{
    DWORD error;
    LPDWORD NumberOfBindings = Context;
    LPWSTR SubStrings[2];
    static DWORD QualityOfService = 65536;


    UNREFERENCED_PARAMETER(ValueName);
    UNREFERENCED_PARAMETER(ValueLength);
    UNREFERENCED_PARAMETER(EntryContext);

    //
    // The value type must be REG_SZ (translated from REG_MULTI_SZ by
    // the RTL).
    //
    if (ValueType != REG_SZ) {

        SubStrings[0] = ValueName;
        SubStrings[1] = NW_LINKAGE_REGISTRY_PATH;

        NwLogEvent(
            EVENT_NWWKSTA_INVALID_REGISTRY_VALUE,
            2,
            SubStrings,
            NO_ERROR
            );

            KdPrint(("NWWORKSTATION: Skipping invalid value %ws\n", ValueName));

        return STATUS_SUCCESS;
    }

    //
    // The value data is the name of the transport device object.
    //

    //
    // Bind to the transport.
    //

#if DBG
    IF_DEBUG(INIT) {
        KdPrint(("NWWORKSTATION: Binding to transport %ws with QOS %lu\n",
                ValueData, QualityOfService));
    }
#endif

    error = NwBindTransport(ValueData, QualityOfService--);

    if (error != NO_ERROR) {

        //
        // If failed to bind to one transport, don't fail starting yet.
        // Try other transports.
        //
        SubStrings[0] = ValueData;

        NwLogEvent(
            EVENT_NWWKSTA_CANT_BIND_TO_TRANSPORT,
            1,
            SubStrings,
            error
            );
    }
    else {
        (*NumberOfBindings)++;
    }

    return STATUS_SUCCESS;
}


DWORD
NwBindTransport(
    IN  LPWSTR TransportName,
    IN  DWORD QualityOfService
    )
/*++

Routine Description:

    This function binds the specified transport to the redirector
    and the datagram receiver.

    NOTE: The transport name length pass to the redirector and
          datagram receiver is the number of bytes.

Arguments:

    TransportName - Supplies the name of the transport to bind to.

    QualityOfService - Supplies a value which specifies the search
        order of the transport with respect to other transports.  The
        highest value is searched first.

Return Value:

    NO_ERROR or reason for failure.

--*/
{
    DWORD status;
    DWORD RequestPacketSize;
    DWORD TransportNameSize = wcslen(TransportName) * sizeof(WCHAR);

    PNWR_REQUEST_PACKET Rrp;


    //
    // Size of request packet buffer
    //
    RequestPacketSize = TransportNameSize + sizeof(NWR_REQUEST_PACKET);

    //
    // Allocate memory for redirector/datagram receiver request packet
    //
    if ((Rrp = (PVOID) LocalAlloc(LMEM_ZEROINIT, (UINT) RequestPacketSize)) == NULL) {
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    //
    // Get redirector to bind to transport
    //
    Rrp->Version = REQUEST_PACKET_VERSION;
    Rrp->Parameters.Bind.QualityOfService = QualityOfService;

    Rrp->Parameters.Bind.TransportNameLength = TransportNameSize;
    wcscpy((LPWSTR) Rrp->Parameters.Bind.TransportName, TransportName);

    if ((status = NwRedirFsControl(
                      RedirDeviceHandle,
                      FSCTL_NWR_BIND_TO_TRANSPORT,
                      Rrp,
                      RequestPacketSize,
                      NULL,
                      0,
                      NULL
                      )) != NO_ERROR) {

        KdPrint(("NWWORKSTATION: NwBindTransport fsctl to bind to transport %ws failed\n",
                 TransportName));
    }

    (void) LocalFree((HLOCAL) Rrp);
    return status;
}


DWORD
NwCreateTreeConnectName(
    IN  LPWSTR UncName,
    IN  LPWSTR LocalName OPTIONAL,
    OUT PUNICODE_STRING TreeConnectStr
    )
/*++

Routine Description:

    This function replaces \\ with \Device\NwRdr\LocalName:\ in the
    UncName to form the NT-style tree connection name.  LocalName:\ is part
    of the tree connection name only if LocalName is specified.  A buffer
    is allocated by this function and returned as the output string.

Arguments:

    UncName - Supplies the UNC name of the shared resource.

    LocalName - Supplies the local device name for the redirection.

    TreeConnectStr - Returns a string with a newly allocated buffer that
        contains the NT-style tree connection name.

Return Value:

    NO_ERROR - the operation was successful.

    ERROR_NOT_ENOUGH_MEMORY - Could not allocate output buffer.

--*/
{
    DWORD UncNameLength = wcslen(UncName);


    //
    // Initialize tree connect string maximum length to hold
    //            \Device\NwRdr\LocalName:\Server\Volume\Path
    //
    TreeConnectStr->MaximumLength = RedirDeviceName.Length +
        sizeof(WCHAR) +                                // For '\'
        (ARGUMENT_PRESENT(LocalName) ? (wcslen(LocalName) * sizeof(WCHAR)) : 0) +
        (USHORT) (UncNameLength * sizeof(WCHAR));      // Includes '\' and
                                                       // term char


    if ((TreeConnectStr->Buffer = (PWSTR) LocalAlloc(
                                              LMEM_ZEROINIT,
                                              (UINT) TreeConnectStr->MaximumLength
                                              )) == NULL) {
        KdPrint(("NWWORKSTATION: NwCreateTreeConnectName LocalAlloc failed %lu\n",
                 GetLastError()));
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    //
    // Copy \Device\NwRdr
    //
    RtlCopyUnicodeString(TreeConnectStr, &RedirDeviceName);

    //
    // Concatenate \LocalName:
    //
    if (ARGUMENT_PRESENT(LocalName)) {

        wcscat(TreeConnectStr->Buffer, L"\\");
        TreeConnectStr->Length += sizeof(WCHAR);

        wcscat(TreeConnectStr->Buffer, LocalName);

        TreeConnectStr->Length += (USHORT) (wcslen(LocalName) * sizeof(WCHAR));
    }

    //
    // Concatenate \Server\Volume\Path
    //
    wcscat(TreeConnectStr->Buffer, &UncName[1]);
    TreeConnectStr->Length += (USHORT) ((UncNameLength - 1) * sizeof(WCHAR));

#if DBG
    IF_DEBUG(CONNECT) {
        KdPrint(("NWWORKSTATION: NwCreateTreeConnectName %ws, maxlength %u, length %u\n",
                 TreeConnectStr->Buffer, TreeConnectStr->MaximumLength,
                 TreeConnectStr->Length));
    }
#endif

    return NO_ERROR;
}



DWORD
NwOpenCreateConnection(
    IN PUNICODE_STRING TreeConnectionName,
    IN LPWSTR UserName OPTIONAL,
    IN LPWSTR Password OPTIONAL,
    IN LPWSTR UncName,
    IN ACCESS_MASK DesiredAccess,
    IN ULONG CreateDisposition,
    IN ULONG CreateOptions,
    IN ULONG ConnectionType,
    OUT PHANDLE TreeConnectionHandle,
    OUT PULONG Information OPTIONAL
    )
/*++

Routine Description:

    This function asks the redirector to either open an existing tree
    connection (CreateDisposition == FILE_OPEN), or create a new tree
    connection if one does not exist (CreateDisposition == FILE_CREATE).

    The password and user name passed to the redirector via the EA buffer
    in the NtCreateFile call.  The EA buffer is NULL if neither password
    or user name is specified.

    The redirector expects the EA descriptor strings to be in ANSI
    but the password and username themselves are in Unicode.

Arguments:

    TreeConnectionName - Supplies the name of the tree connection in NT-style
        file name format: \Device\NwRdr\Server\Volume\Directory

    UserName - Supplies the user name to create the tree connection with.

    Password - Supplies the password to create the tree connection with.

    DesiredAccess - Supplies the access need on the connection handle.

    CreateDisposition - Supplies the create disposition value to either
        open or create the tree connection.

    CreateOptions - Supplies the options used when creating or opening
        the tree connection.

    ConnectionType - Supplies the type of the connection (DISK, PRINT,
        or ANY).

    TreeConnectionHandle - Returns the handle to the tree connection
        created/opened by the redirector.

    Information - Returns the information field of the I/O status block.

Return Value:

    NO_ERROR or reason for failure.

--*/
{
    DWORD status;
    NTSTATUS ntstatus;

    OBJECT_ATTRIBUTES UncNameAttributes;
    IO_STATUS_BLOCK IoStatusBlock;

    PFILE_FULL_EA_INFORMATION EaBuffer = NULL;
    PFILE_FULL_EA_INFORMATION Ea;
    ULONG EaBufferSize = 0;

    UCHAR EaNamePasswordSize = (UCHAR) (ROUND_UP_COUNT(
                                            strlen(EA_NAME_PASSWORD) + sizeof(CHAR),
                                            ALIGN_WCHAR
                                            ) - sizeof(CHAR));
    UCHAR EaNameUserNameSize = (UCHAR) (ROUND_UP_COUNT(
                                            strlen(EA_NAME_USERNAME) + sizeof(CHAR),
                                            ALIGN_WCHAR
                                            ) - sizeof(CHAR));

    UCHAR EaNameTypeSize = (UCHAR) (ROUND_UP_COUNT(
                                        strlen(EA_NAME_TYPE) + sizeof(CHAR),
                                        ALIGN_DWORD
                                        ) - sizeof(CHAR));

    USHORT PasswordSize = 0;
    USHORT UserNameSize = 0;
    USHORT TypeSize = sizeof(ULONG);



    InitializeObjectAttributes(
        &UncNameAttributes,
        TreeConnectionName,
        OBJ_CASE_INSENSITIVE,
        NULL,
        NULL
        );

    //
    // Calculate the number of bytes needed for the EA buffer to put the
    // password or user name.
    //
    if (ARGUMENT_PRESENT(Password)) {

#if DBG
        IF_DEBUG(CONNECT) {
            KdPrint(("NWWORKSTATION: NwOpenCreateConnection password is %ws\n",
                     Password));
        }
#endif

        PasswordSize = (USHORT) (wcslen(Password) * sizeof(WCHAR));

        EaBufferSize = ROUND_UP_COUNT(
                           FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName[0]) +
                           EaNamePasswordSize + sizeof(CHAR) +
                           PasswordSize,
                           ALIGN_DWORD
                           );
    }

    if (ARGUMENT_PRESENT(UserName)) {

#if DBG
        IF_DEBUG(CONNECT) {
            KdPrint(("NWWORKSTATION: NwOpenCreateConnection username is %ws\n",
                     UserName));
        }
#endif

        UserNameSize = (USHORT) (wcslen(UserName) * sizeof(WCHAR));

        EaBufferSize += ROUND_UP_COUNT(
                            FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName[0]) +
                            EaNameUserNameSize + sizeof(CHAR) +
                            UserNameSize,
                            ALIGN_DWORD
                            );
    }

    EaBufferSize += FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName[0]) +
                    EaNameTypeSize + sizeof(CHAR) +
                    TypeSize;

    //
    // Allocate the EA buffer
    //
    if ((EaBuffer = (PFILE_FULL_EA_INFORMATION) LocalAlloc(
                                                    LMEM_ZEROINIT,
                                                    (UINT) EaBufferSize
                                                    )) == NULL) {
        status = GetLastError();
        goto FreeMemory;
    }

    Ea = EaBuffer;

    if (ARGUMENT_PRESENT(Password)) {

        //
        // Copy the EA name into EA buffer.  EA name length does not
        // include the zero terminator.
        //
        strcpy((LPSTR) Ea->EaName, EA_NAME_PASSWORD);
        Ea->EaNameLength = EaNamePasswordSize;

        //
        // Copy the EA value into EA buffer.  EA value length does not
        // include the zero terminator.
        //
        wcscpy(
            (LPWSTR) &(Ea->EaName[EaNamePasswordSize + sizeof(CHAR)]),
            Password
            );

        Ea->EaValueLength = PasswordSize;

        Ea->NextEntryOffset = ROUND_UP_COUNT(
                                  FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName[0]) +
                                  EaNamePasswordSize + sizeof(CHAR) +
                                  PasswordSize,
                                  ALIGN_DWORD
                                  );

        Ea->Flags = 0;

        (ULONG) Ea += Ea->NextEntryOffset;
    }

    if (ARGUMENT_PRESENT(UserName)) {

        //
        // Copy the EA name into EA buffer.  EA name length does not
        // include the zero terminator.
        //
        strcpy((LPSTR) Ea->EaName, EA_NAME_USERNAME);
        Ea->EaNameLength = EaNameUserNameSize;

        //
        // Copy the EA value into EA buffer.  EA value length does not
        // include the zero terminator.
        //
        wcscpy(
            (LPWSTR) &(Ea->EaName[EaNameUserNameSize + sizeof(CHAR)]),
            UserName
            );

        Ea->EaValueLength = UserNameSize;

        Ea->NextEntryOffset = ROUND_UP_COUNT(
                                  FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName[0]) +
                                  EaNameUserNameSize + sizeof(CHAR) +
                                  UserNameSize,
                                  ALIGN_DWORD
                                  );
        Ea->Flags = 0;

        (ULONG) Ea += Ea->NextEntryOffset;

    }

    //
    // Copy the connection type name into EA buffer.  EA name length
    // does not include the zero terminator.
    //
    strcpy((LPSTR) Ea->EaName, EA_NAME_TYPE);
    Ea->EaNameLength = EaNameTypeSize;

    *((PULONG) &(Ea->EaName[EaNameTypeSize + sizeof(CHAR)])) = ConnectionType;

    Ea->EaValueLength = TypeSize;

    //
    // Terminate the EA.
    //
    Ea->NextEntryOffset = 0;
    Ea->Flags = 0;

    //
    // Create or open a tree connection
    //
    ntstatus = NtCreateFile(
                   TreeConnectionHandle,
                   DesiredAccess,
                   &UncNameAttributes,
                   &IoStatusBlock,
                   NULL,
                   FILE_ATTRIBUTE_NORMAL,
                   FILE_SHARE_VALID_FLAGS,
                   CreateDisposition,
                   CreateOptions,
                   (PVOID) EaBuffer,
                   EaBufferSize
                   );

    if (ntstatus == NWRDR_PASSWORD_HAS_EXPIRED) { 
        //
        // wait till other thread is not using the popup data struct.
        // if we timeout, then we just lose the popup.
        //
        switch (WaitForSingleObject(NwPopupDoneEvent, 3000))
        {
            case WAIT_OBJECT_0:
            {
                LPWSTR lpServerStart, lpServerEnd ;
                WCHAR UserNameW[NW_MAX_USERNAME_LEN+1] ;
                DWORD dwUserNameWSize = sizeof(UserNameW)/sizeof(UserNameW[0]) ;
                DWORD dwServerLength, dwGraceLogins ;
                DWORD dwMessageId = NW_PASSWORD_HAS_EXPIRED ;

                //
                // get the current username
                //
                if (UserName)
                {
                    wcscpy(UserNameW, UserName) ;
                }
                else
                {
                    if (!GetUserNameW(UserNameW, &dwUserNameWSize))
                    {
                        SetEvent(NwPopupDoneEvent) ;
                        break ;
                    }
                }

                //
                // allocate string and fill in the username
                //
                if (!(PopupData.InsertStrings[0] =
                    (LPWSTR)LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT,
                                       sizeof(WCHAR) * (wcslen(UserNameW)+1))))
                {
                    SetEvent(NwPopupDoneEvent) ;
                    break ;
                }
                wcscpy(PopupData.InsertStrings[0], UserNameW) ;
 
                //
                // find the server name from unc name
                //
                lpServerStart = (*UncName == L'\\') ? UncName+2 : UncName ;
                lpServerEnd = wcschr(lpServerStart,L'\\') ;
                dwServerLength = lpServerEnd ? (lpServerEnd-lpServerStart) :
                                 wcslen(lpServerStart) ;

                //
                // allocate string and fill in the server insert string
                //
                if (!(PopupData.InsertStrings[1] =
                    (LPWSTR)LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT,
                                       sizeof(WCHAR) * (dwServerLength+1))))
                {
                    (void) LocalFree((HLOCAL) PopupData.InsertStrings[0]);
                    SetEvent(NwPopupDoneEvent) ;
                    break ;
                }
                wcsncpy(PopupData.InsertStrings[1],
                        lpServerStart,
                        dwServerLength) ;

                //
                // now call the NCP. if an error occurs while getting
                // the grace login count, dont use it.
                //
                if (NwGetGraceLoginCount(
                                     PopupData.InsertStrings[1],
                                     UserNameW,
                                     &dwGraceLogins) != NO_ERROR)
                {
                    dwMessageId = NW_PASSWORD_HAS_EXPIRED1 ;
                    dwGraceLogins = 0 ;
                }

                //
                // stick the number of grace logins in second insert string.
                //
                if (!(PopupData.InsertStrings[2] =
                    (LPWSTR)LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT,
                                       sizeof(WCHAR) * 16)))
                {
                    (void) LocalFree((HLOCAL) PopupData.InsertStrings[0]);
                    (void) LocalFree((HLOCAL) PopupData.InsertStrings[1]);
                    SetEvent(NwPopupDoneEvent) ;
                    break ;
                }

                wsprintfW(PopupData.InsertStrings[2], L"%d", dwGraceLogins);
                PopupData.InsertCount = 3 ;
                PopupData.MessageId = dwMessageId ;

                //
                // all done at last, trigger the other thread do the popup
                //
                SetEvent(NwPopupEvent) ;
                break ;

            }

            default:
                break ; // dont bother if we cannot
        }
    }

    if (NT_SUCCESS(ntstatus)) {
        ntstatus = IoStatusBlock.Status;
    }

    if (ntstatus == NWRDR_PASSWORD_HAS_EXPIRED) {
        ntstatus = STATUS_SUCCESS ;
    }

    if (ARGUMENT_PRESENT(Information)) {
        *Information = IoStatusBlock.Information;
    }

#if DBG
    IF_DEBUG(CONNECT) {
        KdPrint(("NWWORKSTATION: NtCreateFile returns %lx\n", ntstatus));
    }
#endif

    status = NwMapStatus(ntstatus);

FreeMemory:
    if (EaBuffer != NULL) {
        RtlZeroMemory( EaBuffer, EaBufferSize );  // Clear the password
        (void) LocalFree((HLOCAL) EaBuffer);
    }

    return status;
}


DWORD
NwNukeConnection(
    IN HANDLE TreeConnection,
    IN DWORD UseForce
    )
/*++

Routine Description:

    This function asks the redirector to delete an existing tree
    connection.

Arguments:

    TreeConnection - Supplies the handle to an existing tree connection.

    UseForce - Supplies the force flag to delete the tree connection.

Return Value:

    NO_ERROR or reason for failure.

--*/
{
    DWORD status;
    NWR_REQUEST_PACKET Rrp;            // Redirector request packet


    //
    // Tell the redirector to delete the tree connection
    //
    Rrp.Version = REQUEST_PACKET_VERSION;
    Rrp.Parameters.DeleteConn.UseForce = (BOOLEAN) UseForce;

    status = NwRedirFsControl(
                 TreeConnection,
                 FSCTL_NWR_DELETE_CONNECTION,
                 &Rrp,
                 sizeof(NWR_REQUEST_PACKET),
                 NULL,
                 0,
                 NULL
                 );

    return status;
}


DWORD
NwGetServerResource(
    IN LPWSTR LocalName,
    IN DWORD LocalNameLength,
    OUT LPWSTR RemoteName,
    IN DWORD RemoteNameLen,
    OUT LPDWORD CharsRequired
    )
/*++

Routine Description:

    This function

Arguments:


Return Value:


--*/
{
    DWORD status = NO_ERROR;

    BYTE Buffer[sizeof(NWR_REQUEST_PACKET) + 2 * sizeof(WCHAR)];
    PNWR_REQUEST_PACKET Rrp = (PNWR_REQUEST_PACKET) Buffer;


    //
    // local device name should not be longer than 4 characters e.g. LPTx, X:
    //
    if ( LocalNameLength > 4 )
        return ERROR_INVALID_PARAMETER;

    Rrp->Version = REQUEST_PACKET_VERSION;

    wcsncpy(Rrp->Parameters.GetConn.DeviceName, LocalName, LocalNameLength);
    Rrp->Parameters.GetConn.DeviceNameLength = LocalNameLength * sizeof(WCHAR);

    status = NwRedirFsControl(
                 RedirDeviceHandle,
                 FSCTL_NWR_GET_CONNECTION,
                 Rrp,
                 sizeof(NWR_REQUEST_PACKET) +
                     Rrp->Parameters.GetConn.DeviceNameLength,
                 RemoteName,
                 RemoteNameLen * sizeof(WCHAR),
                 NULL
                 );

    if (status == ERROR_INSUFFICIENT_BUFFER) {
        *CharsRequired = Rrp->Parameters.GetConn.BytesNeeded / sizeof(WCHAR);
    }
    else if (status == ERROR_FILE_NOT_FOUND) {

        //
        // Redirector could not find the specified LocalName
        //
        status = WN_NOT_CONNECTED;
    }

    return status;

}


DWORD
NwEnumerateConnections(
    IN OUT LPDWORD ResumeId,
    IN DWORD EntriesRequested,
    IN LPBYTE Buffer,
    IN DWORD BufferSize,
    OUT LPDWORD BytesNeeded,
    OUT LPDWORD EntriesRead,
    IN DWORD ConnectionType
    )
/*++

Routine Description:

    This function asks the redirector to enumerate all existing
    connections.

Arguments:

    ResumeId - On input, supplies the resume ID of the next entry
        to begin the enumeration.  This ID is an integer value that
        is either the smaller or the same value as the ID of the
        next entry to return.  On output, this ID indicates the next
        entry to start resuming from for the subsequent call.

    EntriesRequested - Supplies the number of entries to return.  If
        this value is 0xffffffff, return all available entries.

    Buffer - Receives the entries we are listing.

    BufferSize - Supplies the size of the output buffer.

    BytesNeeded - Receives the number of bytes required to get the
        first entry.  This value is returned iff ERROR_MORE_DATA is
        the return code, and Buffer is too small to even fit one
        entry.

    EntriesRead - Receives the number of entries returned in Buffer.
        This value is only returned iff NO_ERROR is the return code.
        NO_ERROR is returned as long as at least one entry was written
        into Buffer but does not necessarily mean that it's the number
        of EntriesRequested.

    ConnectionType - The type of connected resource wanted ( DISK, PRINT, ...)

Return Value:

    NO_ERROR or reason for failure.

--*/
{
    DWORD status;
    NWR_REQUEST_PACKET Rrp;            // Redirector request packet


    //
    // Tell the redirector to enumerate all connections.
    //
    Rrp.Version = REQUEST_PACKET_VERSION;

    Rrp.Parameters.EnumConn.ResumeKey = *ResumeId;
    Rrp.Parameters.EnumConn.EntriesRequested = EntriesRequested;
    Rrp.Parameters.EnumConn.ConnectionType = ConnectionType;

    status = NwRedirFsControl(
                 RedirDeviceHandle,
                 FSCTL_NWR_ENUMERATE_CONNECTIONS,
                 &Rrp,
                 sizeof(NWR_REQUEST_PACKET),
                 Buffer,                      // User output buffer
                 BufferSize,
                 NULL
                 );

    *EntriesRead = Rrp.Parameters.EnumConn.EntriesReturned;

    if (status == WN_MORE_DATA) {
        *BytesNeeded = Rrp.Parameters.EnumConn.BytesNeeded;

        //
        // NP specs expect WN_SUCCESS in this case.
        //
        if (*EntriesRead)
            status = WN_SUCCESS ;
    }

    *ResumeId = Rrp.Parameters.EnumConn.ResumeKey;

    return status;
}


DWORD
NwGetNextServerEntry(
    IN HANDLE PreferredServer,
    IN OUT LPDWORD LastObjectId,
    OUT LPSTR ServerName
    )
/*++

Routine Description:

    This function uses an opened handle to the preferred server to
    scan it bindery for all file server objects.

Arguments:

    PreferredServer - Supplies the handle to the preferred server on
        which to scan the bindery.

    LastObjectId - On input, supplies the object ID to the last file
        server object returned, which is the resume handle to get the
        next file server object.  On output, receives the object ID
        of the file server object returned.

    ServerName - Receives the name of the returned file server object.

Return Value:

    NO_ERROR - Successfully gotten a file server name.

    WN_NO_MORE_ENTRIES - No other file server object past the one
        specified by LastObjectId.

--*/
{
    NTSTATUS ntstatus;
    WORD ObjectType;


#if DBG
    IF_DEBUG(ENUM) {
        KdPrint(("NWWORKSTATION: NwGetNextServerEntry LastObjectId %lu\n",
                 *LastObjectId));
    }
#endif

    ntstatus = NwlibMakeNcp(
                   PreferredServer,
                   FSCTL_NWR_NCP_E3H,    // Bindery function
                   58,                   // Max request packet size
                   59,                   // Max response packet size
                   "bdwp|dwc",           // Format string
                   0x37,                 // Scan bindery object
                   *LastObjectId,        // Previous ID
                   0x4,                  // File server object
                   "*",                  // Wildcard to match all
                   LastObjectId,         // Current ID
                   &ObjectType,          // Ignore
                   ServerName            // Currently returned server
                   );

#if DBG
    if (ntstatus == STATUS_SUCCESS) {
        IF_DEBUG(ENUM) {
            KdPrint(("NWWORKSTATION: NwGetNextServerEntry NewObjectId %08lx, ServerName %s\n",
                     *LastObjectId, ServerName));
        }
    }
#endif

    return NwMapBinderyCompletionCode(ntstatus);
}


DWORD
GetConnectedBinderyServers(
    OUT LPNW_ENUM_CONTEXT ContextHandle
    )
/*++

Routine Description:

    This function is a helper routine for the function
    NwGetNextServerConnection. It allocates a buffer to cache
    bindery server names returned from calls to the redirector. Since the
    redirector may return duplicate bindery server names, this
    function checks to see if the server name already exist in the buffer
    before adding it.

Arguments:

    ContextHandle - Used to track cached bindery information and the 
                    current server name pointer in the cache buffer.

Return Value:

    NO_ERROR - Successfully returned a server name and cache buffer.

    WN_NO_MORE_ENTRIES - No other server object past the one
        specified by CH->ResumeId.

    ERROR_NOT_ENOUGH_MEMORY - Function was unable to allocate a buffer.

++*/
{
    DWORD  ResumeKey = 0;
    LPBYTE pBuffer = NULL;
    DWORD  EntriesRead = 0;
    BYTE   tokenIter;
    LPWSTR tokenPtr;
    BOOL   fAddToList;
    DWORD  status = NwGetConnectionStatus( NULL,
                                           &ResumeKey,
                                           &pBuffer,
                                           &EntriesRead );

    if ( status == NO_ERROR  && EntriesRead > 0 )
    {
        DWORD i;
        PCONN_STATUS pConnStatus = (PCONN_STATUS) pBuffer;

        ContextHandle->ResumeId = 0;
        ContextHandle->NdsRawDataCount = 0;
        ContextHandle->NdsRawDataSize = (NW_MAX_SERVER_LEN + 2) * EntriesRead;
        ContextHandle->NdsRawDataBuffer =
                    (DWORD) LocalAlloc( LMEM_ZEROINIT,
                                        ContextHandle->NdsRawDataSize );

        if ( ContextHandle->NdsRawDataBuffer == 0 )
        {
            KdPrint(("NWWORKSTATION: GetConnectedBinderyServers LocalAlloc failed %lu\n",
                     GetLastError()));

            ContextHandle->NdsRawDataSize = 0;

            return ERROR_NOT_ENOUGH_MEMORY;
        }

        for ( i = 0; i < EntriesRead ; i++ )
        {
            fAddToList = FALSE;

            if ( pConnStatus->fNds == 0 &&
                 ( pConnStatus->dwConnType == NW_CONN_BINDERY_LOGIN ||
                   pConnStatus->dwConnType == NW_CONN_NDS_AUTHENTICATED_NO_LICENSE ||
                   pConnStatus->dwConnType == NW_CONN_NDS_AUTHENTICATED_LICENSED ||
                   pConnStatus->dwConnType == NW_CONN_DISCONNECTED ) )
            {
                fAddToList = TRUE;
                tokenPtr = (LPWSTR) ContextHandle->NdsRawDataBuffer;
                tokenIter = 0;
    
                //
                // Walk through buffer to see if the tree name already exists.
                //
                while ( tokenIter < ContextHandle->NdsRawDataCount )
                {
                    if ( !wcscmp( tokenPtr, pConnStatus->pszServerName ) )
                    {   
                        fAddToList = FALSE;
                    }

                    tokenPtr = tokenPtr + wcslen( tokenPtr ) + 1;
                    tokenIter++;
                }
            }

            //
            //  Add the new tree name to end of buffer if needed.
            //
            if ( fAddToList )
            {
                wcscpy( tokenPtr, pConnStatus->pszServerName );
                _wcsupr( tokenPtr );
                ContextHandle->NdsRawDataCount += 1;
            }

            pConnStatus = (PCONN_STATUS) ( (DWORD) pConnStatus +
                                           pConnStatus->dwTotalLength );
        }

        if ( pBuffer != NULL )
        {
            LocalFree( pBuffer );
            pBuffer = NULL;
        }

        if ( ContextHandle->NdsRawDataCount > 0 )
        {
            //
            // Set ResumeId to point to the first entry in buffer
            // and have NdsRawDataCount set to the number
            // of tree entries left in buffer (ie. substract 1)
            //
            ContextHandle->ResumeId = ContextHandle->NdsRawDataBuffer;
            ContextHandle->NdsRawDataCount -= 1;
        }

        return NO_ERROR;
    }

    return WN_NO_MORE_ENTRIES;
}


DWORD
NwGetNextServerConnection(
    OUT LPNW_ENUM_CONTEXT ContextHandle
    )
/*++

Routine Description:

    This function queries the redirector for bindery server connections

Arguments:

    ContextHandle - Receives the name of the returned bindery server.

Return Value:

    NO_ERROR - Successfully returned a server name.

    WN_NO_MORE_ENTRIES - No other server objects past the one
        specified by CH->ResumeId exist.

--*/
{
#if DBG
    IF_DEBUG(ENUM) {
        KdPrint(("NWWORKSTATION: NwGetNextServerConnection ResumeId %lu\n",
                 ContextHandle->ResumeId));
    }
#endif

    if ( ContextHandle->ResumeId == 0xFFFFFFFF &&
         ContextHandle->NdsRawDataBuffer == 0 &&
         ContextHandle->NdsRawDataCount == 0 )
    {
        //
        // Fill the buffer and point ResumeId to the last
        // server entry name in it. NdsRawDataCount will be
        // set to one less than the number of server names in buffer.
        //
        return GetConnectedBinderyServers( ContextHandle );
    }

    if ( ContextHandle->NdsRawDataBuffer != 0 &&
         ContextHandle->NdsRawDataCount > 0 )
    {
        //
        // Move ResumeId to point to the next entry in the buffer
        // and decrement the NdsRawDataCount by one. Watch for case
        // where we backed up to 0xFFFFFFFF.
        //
        if (ContextHandle->ResumeId == 0xFFFFFFFF) {

            //
            // Reset to start of buffer.
            //
            ContextHandle->ResumeId = ContextHandle->NdsRawDataBuffer;
        }
        else {

            //
            // Treat as pointer and advance as need.
            //
            ContextHandle->ResumeId =
                       ContextHandle->ResumeId +
                       ( ( wcslen( (LPWSTR) ContextHandle->ResumeId ) + 1 ) *
                       sizeof(WCHAR) );
        }
        ContextHandle->NdsRawDataCount -= 1;

        return NO_ERROR;
    }
    
    if ( ContextHandle->NdsRawDataBuffer != 0 &&
         ContextHandle->NdsRawDataCount == 0 )
    {
        //
        // We already have a buffer and processed all server names
        // in it, and there is no more data to get.
        // So free the memory used for the buffer and return
        // WN_NO_MORE_ENTRIES to tell WinFile that we are done.
        //
        (void) LocalFree( (HLOCAL) ContextHandle->NdsRawDataBuffer );

        ContextHandle->NdsRawDataBuffer = 0;
        ContextHandle->NdsRawDataSize = 0;

        return WN_NO_MORE_ENTRIES;
    }

    //
    // Were done
    //
    return WN_NO_MORE_ENTRIES;
}


DWORD
GetTreeEntriesFromBindery(
    OUT LPNW_ENUM_CONTEXT ContextHandle
    )
/*++

Routine Description:

    This function is a helper routine for the function NwGetNextNdsTreeEntry.
    It allocates a buffer (if needed) to cache NDS tree names returned from
    calls to the bindery. Since the bindery often returns duplicates of a
    NDS tree name, this function checks to see if the tree name already
    exist in the buffer before adding it to it if not present.

Arguments:

    ContextHandle - Used to track cached bindery information and the 
                    current tree name pointer in the cache buffer.

Return Value:

    NO_ERROR - Successfully returned a NDS tree name and cache buffer.

    WN_NO_MORE_ENTRIES - No other NDS tree object past the one
        specified by CH->ResumeId.

    ERROR_NOT_ENOUGH_MEMORY - Function was unable to allocate a buffer.

++*/
{
    NTSTATUS ntstatus = STATUS_SUCCESS;
    SERVERNAME TreeName;
    LPWSTR UTreeName = NULL; //Unicode tree name
    DWORD tempDataId;
    WORD ObjectType;
    BYTE iter;
    BYTE tokenIter;
    LPWSTR tokenPtr;
    BOOL fAddToList;

    //
    // Check to see if we need to allocate a buffer for use
    //
    if ( ContextHandle->NdsRawDataBuffer == 0x00000000 )
    {
        ContextHandle->NdsRawDataId = ContextHandle->ResumeId;
        ContextHandle->NdsRawDataSize = EIGHT_KB;
        ContextHandle->NdsRawDataBuffer =
                    (DWORD) LocalAlloc( LMEM_FIXED | LMEM_ZEROINIT,
                                ContextHandle->NdsRawDataSize );

        if ( ContextHandle->NdsRawDataBuffer == 0 )
        {
            KdPrint(("NWWORKSTATION: GetTreeEntriesFromBindery LocalAlloc failed %lu\n",
                     GetLastError()));

            ContextHandle->NdsRawDataSize = 0;
            ContextHandle->NdsRawDataId = 0xFFFFFFFF;

            return ERROR_NOT_ENOUGH_MEMORY;
        }
    }

    //
    // Repeatedly call bindery to fill buffer with NDS tree names until
    // buffer is full.
    //
    while ( ntstatus == STATUS_SUCCESS )
    {
        RtlZeroMemory( TreeName, sizeof( TreeName ) );

        tempDataId = ContextHandle->NdsRawDataId;

        ntstatus = NwlibMakeNcp(
                   ContextHandle->TreeConnectionHandle,
                   FSCTL_NWR_NCP_E3H,            // Bindery function
                   58,                           // Max request packet size
                   59,                           // Max response packet size
                   "bdwp|dwc",                   // Format string
                   0x37,                         // Scan bindery object
                   ContextHandle->NdsRawDataId,  // Previous ID
                   0x278,                        // Directory server object
                   "*",                          // Wildcard to match all
                   &ContextHandle->NdsRawDataId, // Current ID
                   &ObjectType,                  // Ignore
                   TreeName                      // Currently returned NDS tree
                   );

        //
        // We got a tree name, clean it up (i.e. get rid of underscores ),
        // and add it to buffer if unique.
        //
        if ( ntstatus == STATUS_SUCCESS )
        {
            iter = 31;

            while ( TreeName[iter] == '_' && iter > 0 )
            {
                iter--;
            }

            TreeName[iter + 1] = '\0';

            //
            // Convert tree name to a UNICODE string and proccess it,
            // else just skip it and move on to the next tree name.
            //
            if ( NwConvertToUnicode( &UTreeName, TreeName ) )
            {
               tokenPtr = (LPWSTR) ContextHandle->NdsRawDataBuffer;
               tokenIter = 0;
               fAddToList = TRUE;
    
               //
               // Walk through buffer to see if the tree name already exists.
               //
               while ( tokenIter < ContextHandle->NdsRawDataCount )
               {
                   if ( !wcscmp( tokenPtr, UTreeName ) )
                   {   
                       fAddToList = FALSE;
                   }

                   tokenPtr = tokenPtr + wcslen( tokenPtr ) + 1;
                   tokenIter++;
               }

               //
               //  Add the new tree name to end of buffer if needed.
               //
               if ( fAddToList )
               {
                   DWORD BytesNeededToAddTreeName = (wcslen(UTreeName)+1) * sizeof(WCHAR);
                   DWORD NumberOfBytesAvailable = ContextHandle->NdsRawDataBuffer +
                                            ContextHandle->NdsRawDataSize -
                                            (DWORD) tokenPtr;

                   if ( BytesNeededToAddTreeName < NumberOfBytesAvailable )
                   {
                       wcscpy( tokenPtr, UTreeName );
                       ContextHandle->NdsRawDataCount += 1;
                   }
                   else
                   {
                       ContextHandle->NdsRawDataId = tempDataId;
                       ntstatus = ERROR_NOT_ENOUGH_MEMORY;
                   }
               }

               (void) LocalFree((HLOCAL) UTreeName);
            }
        }
    }

    //
    // We are done filling buffer, and there are no more tree names 
    // to request. Set id to indicate last value.
    //
    if ( ntstatus == STATUS_NO_MORE_ENTRIES )
    {
        ContextHandle->NdsRawDataId = 0xFFFFFFFF;
        ntstatus = STATUS_SUCCESS;
    }

    //
    // We are done because the buffer is full. So we return NO_ERROR to
    // indicate completion, and leave ContextHandle->NdsRawDataId as is
    // to indicate where we left off.
    //
    if ( ntstatus == ERROR_NOT_ENOUGH_MEMORY )
    {
        ntstatus = STATUS_SUCCESS;
    }

    if ( ContextHandle->NdsRawDataCount == 0 )
    {
        if ( ContextHandle->NdsRawDataBuffer )
            (void) LocalFree( (HLOCAL) ContextHandle->NdsRawDataBuffer );

        ContextHandle->NdsRawDataBuffer = 0;
        ContextHandle->NdsRawDataSize = 0;
        ContextHandle->NdsRawDataId = 0xFFFFFFFF;

        return WN_NO_MORE_ENTRIES;
    }

    if ( ContextHandle->NdsRawDataCount > 0 )
    {
        //
        // Set ResumeId to point to the first entry in buffer
        // and have NdsRawDataCount set to the number
        // of tree entries left in buffer (ie. substract 1)
        //
        ContextHandle->ResumeId = ContextHandle->NdsRawDataBuffer;
        ContextHandle->NdsRawDataCount -= 1;

        return NO_ERROR;
    }

    if ( ContextHandle->NdsRawDataBuffer )
        (void) LocalFree( (HLOCAL) ContextHandle->NdsRawDataBuffer );

    ContextHandle->NdsRawDataBuffer = 0;
    ContextHandle->NdsRawDataSize = 0;
    ContextHandle->NdsRawDataId = 0xFFFFFFFF;

    return NwMapStatus( ntstatus );
}


DWORD
NwGetNextNdsTreeEntry(
    OUT LPNW_ENUM_CONTEXT ContextHandle
    )
/*++

Routine Description:

    This function uses an opened handle to the preferred server to
    scan it bindery for all NDS tree objects.

Arguments:

    ContextHandle - Receives the name of the returned NDS tree object
    given the current preferred server connection and CH->ResumeId.

Return Value:

    NO_ERROR - Successfully returned a NDS tree name.

    WN_NO_MORE_ENTRIES - No other NDS tree objects past the one
        specified by CH->ResumeId exist.

--*/
{
#if DBG
    IF_DEBUG(ENUM) {
        KdPrint(("NWWORKSTATION: NwGetNextNdsTreeEntry ResumeId %lu\n",
                 ContextHandle->ResumeId));
    }
#endif

    if ( ContextHandle->ResumeId == 0xFFFFFFFF &&
         ContextHandle->NdsRawDataBuffer == 0 &&
         ContextHandle->NdsRawDataCount == 0 )
    {
        //
        // Fill the buffer and point ResumeId to the last
        // tree entry name in it. NdsRawDataCount will be
        // set to one less than the number of tree names in buffer.
        //
        return GetTreeEntriesFromBindery( ContextHandle );
    }

    if ( ContextHandle->NdsRawDataBuffer != 0 &&
         ContextHandle->NdsRawDataCount > 0 )
    {
        //
        // Move ResumeId to point to the next entry in the buffer
        // and decrement the NdsRawDataCount by one. Watch for case
        // where we backed up to 0xFFFFFFFF.
        //
        if (ContextHandle->ResumeId == 0xFFFFFFFF) {

            //
            // Reset to start of buffer.
            //
            ContextHandle->ResumeId = ContextHandle->NdsRawDataBuffer;
        }
        else {

            //
            // Move ResumeId to point to the next entry in the buffer
            // and decrement the NdsRawDataCount by one
            //
            ContextHandle->ResumeId =
                       ContextHandle->ResumeId +
                       ( ( wcslen( (LPWSTR) ContextHandle->ResumeId ) + 1 ) *
                       sizeof(WCHAR) );
        }

        ContextHandle->NdsRawDataCount -= 1;

        return NO_ERROR;
    }
    
    if ( ContextHandle->NdsRawDataBuffer != 0 &&
         ContextHandle->NdsRawDataCount == 0 &&
         ContextHandle->NdsRawDataId != 0xFFFFFFFF )
    {
        //
        // We already have a buffer and processed all tree names
        // in it, and there is more data in the bindery to get.
        // So go get it and point ResumeId to the last tree
        // entry name in the buffer and set NdsRawDataCount to
        // one less than the number of tree names in buffer.
        //
        return GetTreeEntriesFromBindery( ContextHandle );
    }
    
    if ( ContextHandle->NdsRawDataBuffer != 0 &&
         ContextHandle->NdsRawDataCount == 0 &&
         ContextHandle->NdsRawDataId == 0xFFFFFFFF )
    {
        //
        // We already have a buffer and processed all tree names
        // in it, and there is no more data in the bindery to get.
        // So free the memory used for the buffer and return
        // WN_NO_MORE_ENTRIES to tell WinFile that we are done.
        //
        (void) LocalFree( (HLOCAL) ContextHandle->NdsRawDataBuffer );

        ContextHandle->NdsRawDataBuffer = 0;
        ContextHandle->NdsRawDataSize = 0;

        return WN_NO_MORE_ENTRIES;
    }

    //
    // We should never hit this area!
    //
    return WN_NO_MORE_ENTRIES;
}


DWORD
NwGetNextVolumeEntry(
    IN HANDLE ServerConnection,
    IN DWORD NextVolumeNumber,
    OUT LPSTR VolumeName
    )
/*++

Routine Description:

    This function lists the volumes on the server specified by
    an opened tree connection handle to the server.

Arguments:

    ServerConnection - Supplies the tree connection handle to the
        server to enumerate volumes from.

    NextVolumeNumber - Supplies the volume number which to look
        up the name.

    VolumeName - Receives the name of the volume associated with
        NextVolumeNumber.

Return Value:

    NO_ERROR - Successfully gotten the volume name.

    WN_NO_MORE_ENTRIES - No other volume name associated with the
         specified volume number.

--*/
{
    NTSTATUS ntstatus;

#if DBG
    IF_DEBUG(ENUM) {
        KdPrint(("NWWORKSTATION: NwGetNextVolumeEntry volume number %lu\n",
                 NextVolumeNumber));
    }
#endif

    ntstatus = NwlibMakeNcp(
                   ServerConnection,
                   FSCTL_NWR_NCP_E2H,       // Directory function
                   4,                       // Max request packet size
                   19,                      // Max response packet size
                   "bb|p",                  // Format string
                   0x6,                     // Get volume name
                   (BYTE) NextVolumeNumber, // Previous ID
                   VolumeName               // Currently returned server
                   );

    return NwMapStatus(ntstatus);
}


DWORD
NwRdrLogonUser(
    IN PLUID LogonId,
    IN LPWSTR UserName,
    IN DWORD UserNameSize,
    IN LPWSTR Password OPTIONAL,
    IN DWORD PasswordSize,
    IN LPWSTR PreferredServer OPTIONAL,
    IN DWORD PreferredServerSize
    )
/*++

Routine Description:

    This function tells the redirector the user logon credential.

Arguments:

    UserName - Supplies the user name.

    UserNameSize - Supplies the size in bytes of the user name string without
        the NULL terminator.

    Password - Supplies the password.

    PasswordSize - Supplies the size in bytes of the password string without
        the NULL terminator.

    PreferredServer - Supplies the preferred server name.

    PreferredServerSize - Supplies the size in bytes of the preferred server
        string without the NULL terminator.

Return Value:

    NO_ERROR or reason for failure.

--*/
{
    DWORD status;

    PNWR_REQUEST_PACKET Rrp;            // Redirector request packet

    DWORD RrpSize = sizeof(NWR_REQUEST_PACKET) +
                        UserNameSize +
                        PasswordSize +
                        PreferredServerSize;
    LPBYTE Dest;
    BYTE   lpReplicaAddress[sizeof(TDI_ADDRESS_IPX)];
    DWORD  ReplicaAddressSize = 0;


#if DBG
    IF_DEBUG(LOGON) {
        BYTE PW[128];


        RtlZeroMemory(PW, sizeof(PW));

        if (PasswordSize > (sizeof(PW) - 1)) {
            memcpy(PW, Password, sizeof(PW) - 1);
        }
        else {
            memcpy(PW, Password, PasswordSize);
        }

        KdPrint(("NWWORKSTATION: NwRdrLogonUser: UserName %ws\n", UserName));
        KdPrint(("                               Password %ws\n", PW));
        if ( PreferredServer )
            KdPrint(("                               Server   %ws\n", PreferredServer ));
    }
#endif

    if ( PreferredServer && PreferredServer[0] == TREECHAR )
    {
        WCHAR  TreeName[MAX_NDS_NAME_CHARS + 1];
        LPWSTR lpTemp;

        //
        // Find the nearest dir server for the tree that the user wants to
        // connect to.
        //

        wcscpy( TreeName, PreferredServer + 1 );
        lpTemp = wcschr( TreeName, L'\\' );
        lpTemp[0] = L'\0';

        GetNearestDirServer( TreeName,
                             &ReplicaAddressSize,
                             lpReplicaAddress );

        RrpSize += ReplicaAddressSize;
    }

    //
    // Allocate the request packet
    //
    if ((Rrp = (PVOID) LocalAlloc(
                           LMEM_ZEROINIT,
                           RrpSize
                           )) == NULL) {

        KdPrint(("NWWORKSTATION: NwRdrLogonUser LocalAlloc failed %lu\n",
                 GetLastError()));
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    //
    // Tell the redirector the user logon credential.
    //
    Rrp->Version = REQUEST_PACKET_VERSION;

    RtlCopyLuid(&(Rrp->Parameters.Logon.LogonId), LogonId);

#if DBG
    IF_DEBUG(LOGON) {
        KdPrint(("NWWORKSTATION: NwRdrLogonUser passing to Rdr logon ID %lu %lu\n",
                 *LogonId, *((PULONG) ((DWORD) LogonId + sizeof(ULONG)))));
    }
#endif

    Rrp->Parameters.Logon.UserNameLength = UserNameSize;
    Rrp->Parameters.Logon.PasswordLength = PasswordSize;
    Rrp->Parameters.Logon.ServerNameLength = PreferredServerSize;
    Rrp->Parameters.Logon.ReplicaAddrLength = ReplicaAddressSize;

    memcpy(Rrp->Parameters.Logon.UserName, UserName, UserNameSize);
    Dest = (LPBYTE) ((DWORD) Rrp->Parameters.Logon.UserName + UserNameSize);

    if (PasswordSize > 0)
    {
        memcpy(Dest, Password, PasswordSize);
        Dest = (LPBYTE) ((DWORD) Dest + PasswordSize);
    }

    if (PreferredServerSize > 0)
    {
        memcpy(Dest, PreferredServer, PreferredServerSize);

        if (ReplicaAddressSize > 0)
        {
            Dest = (LPBYTE) ((DWORD) Dest + PreferredServerSize);
            memcpy(Dest, lpReplicaAddress, ReplicaAddressSize);
        }
    }

    status = NwRedirFsControl(
                 RedirDeviceHandle,
                 FSCTL_NWR_LOGON,
                 Rrp,
                 RrpSize,
                 NULL,              // No logon script in this release
                 0,
                 NULL
                 );

    RtlZeroMemory(Rrp, RrpSize);   // Clear the password
    (void) LocalFree((HLOCAL) Rrp);

    return status;
}


VOID
NwRdrChangePassword(
    IN PNWR_REQUEST_PACKET Rrp
    )
/*++

Routine Description:

    This function tells the redirector the new password for a user on
    a particular server.

Arguments:

    Rrp - Supplies the username, new password and servername.

    RrpSize - Supplies the size of the request packet.

Return Value:

    None.

--*/
{

    //
    // Tell the redirector the user new password.
    //
    Rrp->Version = REQUEST_PACKET_VERSION;

    (void) NwRedirFsControl(
               RedirDeviceHandle,
               FSCTL_NWR_CHANGE_PASS,
               Rrp,
               sizeof(NWR_REQUEST_PACKET) +
                   Rrp->Parameters.ChangePass.UserNameLength +
                   Rrp->Parameters.ChangePass.PasswordLength +
                   Rrp->Parameters.ChangePass.ServerNameLength,
               NULL,
               0,
               NULL
               );

}


DWORD
NwRdrSetInfo(
    IN DWORD PrintOption,
    IN DWORD PacketBurstSize,
    IN LPWSTR PreferredServer OPTIONAL,
    IN DWORD PreferredServerSize,
    IN LPWSTR ProviderName OPTIONAL,
    IN DWORD ProviderNameSize
    )
/*++

Routine Description:

    This function passes some workstation configuration and current user's
    preference to the redirector. This includes the network provider name, the
    packet burst size, the user's selected preferred server and print option.

Arguments:

    PrintOption  - The current user's print option

    PacketBurstSize - The packet burst size stored in the registry

    PreferredServer - The preferred server the current user selected
    PreferredServerSize - Supplies the size in bytes of the preferred server
                   string without the NULL terminator.

    ProviderName - Supplies the provider name.
    ProviderNameSize - Supplies the size in bytes of the provider name
                   string without the NULL terminator.


Return Value:

    NO_ERROR or reason for failure.

--*/
{
    DWORD status;

    PNWR_REQUEST_PACKET Rrp;            // Redirector request packet

    DWORD RrpSize = sizeof(NWR_REQUEST_PACKET) +
                        PreferredServerSize +
                        ProviderNameSize;

    LPBYTE Dest;

    //
    // Allocate the request packet
    //
    if ((Rrp = (PVOID) LocalAlloc(
                           LMEM_ZEROINIT,
                           RrpSize
                           )) == NULL) {

        KdPrint(("NWWORKSTATION: NwRdrSetInfo LocalAlloc failed %lu\n",
                 GetLastError()));
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    Rrp->Version = REQUEST_PACKET_VERSION;

    Rrp->Parameters.SetInfo.PrintOption = PrintOption;
    Rrp->Parameters.SetInfo.MaximumBurstSize = PacketBurstSize;

    Rrp->Parameters.SetInfo.PreferredServerLength = PreferredServerSize;
    Rrp->Parameters.SetInfo.ProviderNameLength  = ProviderNameSize;

    if (ProviderNameSize > 0) {
        memcpy( Rrp->Parameters.SetInfo.PreferredServer,
                PreferredServer, PreferredServerSize);
    }

    Dest = (LPBYTE) ((DWORD) Rrp->Parameters.SetInfo.PreferredServer
                     + PreferredServerSize);

    if (ProviderNameSize > 0) {
        memcpy(Dest, ProviderName, ProviderNameSize);
    }

    status = NwRedirFsControl(
                 RedirDeviceHandle,
                 FSCTL_NWR_SET_INFO,
                 Rrp,
                 RrpSize,
                 NULL,
                 0,
                 NULL
                 );

    (void) LocalFree((HLOCAL) Rrp);


    if ( status != NO_ERROR )
    {
        KdPrint(("NwRedirFsControl: FSCTL_NWR_SET_INFO failed with %d\n",
                status ));
    }

    return status;
}


DWORD
NwRdrLogoffUser(
    IN PLUID LogonId
    )
/*++

Routine Description:

    This function asks the redirector to log off the interactive user.

Arguments:

    None.

Return Value:

    NO_ERROR or reason for failure.

--*/
{
    DWORD status;
    NWR_REQUEST_PACKET Rrp;            // Redirector request packet


    //
    // Tell the redirector to logoff user.
    //
    Rrp.Version = REQUEST_PACKET_VERSION;

    RtlCopyLuid(&Rrp.Parameters.Logoff.LogonId, LogonId);

    status = NwRedirFsControl(
                 RedirDeviceHandle,
                 FSCTL_NWR_LOGOFF,
                 &Rrp,
                 sizeof(NWR_REQUEST_PACKET),
                 NULL,
                 0,
                 NULL
                 );

    return status;
}


DWORD
NwConnectToServer(
    IN LPWSTR ServerName
    )
/*++

Routine Description:

    This function opens a handle to \Device\Nwrdr\ServerName, given
    ServerName, and then closes the handle if the open was successful.
    It is to validate that the current user credential can access
    the server.

Arguments:

    ServerName - Supplies the name of the server to validate the
        user credential.

Return Value:

    NO_ERROR or reason for failure.

--*/
{
    DWORD status;
    UNICODE_STRING ServerStr;
    HANDLE ServerHandle;



    ServerStr.MaximumLength = (wcslen(ServerName) + 2) *
                                  sizeof(WCHAR) +          // \ServerName0
                                  RedirDeviceName.Length;  // \Device\Nwrdr

    if ((ServerStr.Buffer = (PWSTR) LocalAlloc(
                                        LMEM_ZEROINIT,
                                        (UINT) ServerStr.MaximumLength
                                        )) == NULL) {
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    //
    // Copy \Device\NwRdr
    //
    RtlCopyUnicodeString(&ServerStr, &RedirDeviceName);

    //
    // Concatenate \ServerName
    //
    wcscat(ServerStr.Buffer, L"\\");
    ServerStr.Length += sizeof(WCHAR);

    wcscat(ServerStr.Buffer, ServerName);
    ServerStr.Length += (USHORT) (wcslen(ServerName) * sizeof(WCHAR));


    status = NwOpenCreateConnection(
                 &ServerStr,
                 NULL,
                 NULL,
                 ServerName,
                 SYNCHRONIZE | FILE_WRITE_DATA,
                 FILE_OPEN,
                 FILE_SYNCHRONOUS_IO_NONALERT,
                 RESOURCETYPE_DISK,
                 &ServerHandle,
                 NULL
                 );

    if (status == ERROR_FILE_NOT_FOUND) {
        status = ERROR_BAD_NETPATH;
    }

    (void) LocalFree((HLOCAL) ServerStr.Buffer);

    if (status == NO_ERROR || status == NW_PASSWORD_HAS_EXPIRED) {
        (void) NtClose(ServerHandle);
    }

    return status;
}

DWORD
NWPGetConnectionStatus(
    IN     LPWSTR  pszRemoteName,
    IN OUT PDWORD  ResumeKey,
    OUT    LPBYTE  Buffer,
    IN     DWORD   BufferSize,
    OUT    PDWORD  BytesNeeded,
    OUT    PDWORD  EntriesRead
)
{
    NTSTATUS ntstatus = STATUS_SUCCESS;
    HANDLE            handleRdr = NULL;
    OBJECT_ATTRIBUTES ObjectAttributes;
    IO_STATUS_BLOCK   IoStatusBlock;
    UNICODE_STRING    uRdrName;
    WCHAR             RdrPrefix[] = L"\\Device\\NwRdr\\*";

    PNWR_REQUEST_PACKET RequestPacket = NULL;
    DWORD             RequestPacketSize = 0;
    DWORD             dwRemoteNameLen = 0;

    //
    // Set up the object attributes.
    //

    RtlInitUnicodeString( &uRdrName, RdrPrefix );

    InitializeObjectAttributes( &ObjectAttributes,
                                &uRdrName,
                                OBJ_CASE_INSENSITIVE,
                                NULL,
                                NULL );

    ntstatus = NtOpenFile( &handleRdr,
                           SYNCHRONIZE | FILE_LIST_DIRECTORY,
                           &ObjectAttributes,
                           &IoStatusBlock,
                           FILE_SHARE_VALID_FLAGS,
                           FILE_SYNCHRONOUS_IO_NONALERT );

    if ( !NT_SUCCESS(ntstatus) )
        goto CleanExit;

    dwRemoteNameLen = pszRemoteName? wcslen(pszRemoteName)*sizeof(WCHAR) : 0;

    RequestPacketSize = sizeof( NWR_REQUEST_PACKET ) + dwRemoteNameLen;

    RequestPacket = (PNWR_REQUEST_PACKET) LocalAlloc( LMEM_ZEROINIT,
                                                      RequestPacketSize );

    if ( RequestPacket == NULL )
    {
        ntstatus = STATUS_NO_MEMORY;
        goto CleanExit;
    }

    //
    // Fill out the request packet for FSCTL_NWR_GET_CONN_STATUS.
    //

    RequestPacket->Parameters.GetConnStatus.ResumeKey = *ResumeKey;

    RequestPacket->Version = REQUEST_PACKET_VERSION;
    RequestPacket->Parameters.GetConnStatus.ConnectionNameLength = dwRemoteNameLen;

    RtlCopyMemory( &(RequestPacket->Parameters.GetConnStatus.ConnectionName[0]),
                   pszRemoteName,
                   dwRemoteNameLen );

    ntstatus = NtFsControlFile( handleRdr,
                                NULL,
                                NULL,
                                NULL,
                                &IoStatusBlock,
                                FSCTL_NWR_GET_CONN_STATUS,
                                (PVOID) RequestPacket,
                                RequestPacketSize,
                                (PVOID) Buffer,
                                BufferSize );

    if ( NT_SUCCESS( ntstatus ))
        ntstatus = IoStatusBlock.Status;

    *EntriesRead = RequestPacket->Parameters.GetConnStatus.EntriesReturned;
    *ResumeKey   = RequestPacket->Parameters.GetConnStatus.ResumeKey;
    *BytesNeeded = RequestPacket->Parameters.GetConnStatus.BytesNeeded;

CleanExit:

    if ( handleRdr != NULL )
        NtClose( handleRdr );

    if ( RequestPacket != NULL )
        LocalFree( RequestPacket );

    return RtlNtStatusToDosError( ntstatus );
}

DWORD
NwGetConnectionStatus(
    IN  LPWSTR  pszRemoteName,
    OUT PDWORD  ResumeKey,
    OUT LPBYTE  *Buffer,
    OUT PDWORD  EntriesRead
)
{
    DWORD err = NO_ERROR;
    DWORD dwBytesNeeded = 0;
    DWORD dwBufferSize  = TWO_KB;

    *Buffer = NULL;
    *EntriesRead = 0;

    do {

        *Buffer = (LPBYTE) LocalAlloc( LMEM_ZEROINIT, dwBufferSize );

        if ( *Buffer == NULL )
            return ERROR_NOT_ENOUGH_MEMORY;

        err = NWPGetConnectionStatus( pszRemoteName,
                                      ResumeKey,
                                      *Buffer,
                                      dwBufferSize,
                                      &dwBytesNeeded,
                                      EntriesRead );

        if ( err == ERROR_INSUFFICIENT_BUFFER )
        {
            dwBufferSize = dwBytesNeeded + EXTRA_BYTES;
            LocalFree( *Buffer );
            *Buffer = NULL;
        }

    } while ( err == ERROR_INSUFFICIENT_BUFFER );

    if ( err == ERROR_INVALID_PARAMETER )  // not attached
    {
        err = NO_ERROR;
        *EntriesRead = 0;
    }

    return err;
}

VOID
GetNearestDirServer(
    IN  LPWSTR  TreeName,
    OUT LPDWORD lpdwReplicaAddressSize,
    OUT LPBYTE  lpReplicaAddress
    )
{
    WCHAR Buffer[BUFFSIZE];
    PWSAQUERYSETW Query = (PWSAQUERYSETW)Buffer;
    HANDLE hRnr;
    DWORD dwQuerySize = BUFFSIZE;
    GUID gdService = SVCID_NETWARE(0x278);
    WSADATA wsaData;
    WCHAR  ServiceInstanceName[] = L"*";

    WSAStartup(MAKEWORD(1, 1), &wsaData);

    memset(Query, 0, sizeof(*Query));

    //
    // putting a "*" in the lpszServiceInstanceName causes
    // the query to look for all server instances. Putting a
    // specific name in here will search only for instance of
    // that name. If you have a specific name to look for,
    // put a pointer to the name here.
    //
    Query->lpszServiceInstanceName = ServiceInstanceName;
    Query->dwNameSpace = NS_SAP;
    Query->dwSize = sizeof(*Query);
    Query->lpServiceClassId = &gdService;

    //
    // Find the servers. The flags indicate:
    // LUP_NEAREST: look for nearest servers
    // LUP_DEEP : if none are found on the local segement look
    //            for server using a general query
    // LUP_RETURN_NAME: return the name
    // LUP_RETURN_ADDR: return the server address
    //
    // if only servers on the local segment are acceptable, omit
    // setting LUP_DEEP
    //
    if( WSALookupServiceBegin( Query,
                               LUP_NEAREST |
                               LUP_DEEP |
                               LUP_RETURN_NAME |
                               LUP_RETURN_ADDR,
                               &hRnr ) == SOCKET_ERROR )
    {
        //
        // Something went wrong, return no address. The redirector will
        // have to come up with a dir server on its own.
        //
        *lpdwReplicaAddressSize = 0;
        return ;
    }
    else
    {
        //
        // Ready to actually look for one of the suckers ...
        //
        Query->dwSize = BUFFSIZE;

        while( WSALookupServiceNext( hRnr,
                                     0,
                                     &dwQuerySize,
                                     Query ) == NO_ERROR )
        {
            //
            // Found a dir server, now see if it is a server for the NDS tree
            // TreeName.
            //
            if ( NwpCompareTreeNames( Query->lpszServiceInstanceName,
                                      TreeName ) )
            {
                *lpdwReplicaAddressSize = sizeof(TDI_ADDRESS_IPX);
                memcpy( lpReplicaAddress,
                        Query->lpcsaBuffer->RemoteAddr.lpSockaddr->sa_data,
                        sizeof(TDI_ADDRESS_IPX) );

                WSALookupServiceEnd(hRnr);
                return ;
            }
        }

        //
        // Could not find a dir server, return no address. The redirector will
        // have to come up with a dir server on its own.
        //
        *lpdwReplicaAddressSize = 0;
        WSALookupServiceEnd(hRnr);
    }
}

BOOL
NwpCompareTreeNames(
    LPWSTR lpServiceInstanceName,
    LPWSTR lpTreeName
    )
{
    DWORD  iter = 31;

    while ( lpServiceInstanceName[iter] == '_' && iter > 0 )
    {
        iter--;
    }

    lpServiceInstanceName[iter + 1] = '\0';

    if ( !_wcsicmp( lpServiceInstanceName, lpTreeName ) )
    {
        return TRUE;
    }

    return FALSE;
}