summaryrefslogtreecommitdiffstats
path: root/private/mvdm/vdmredir/vrnmpipe.c
blob: f1b7b07f8c012abb396487bc33c167d8c369fda7 (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
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
/*++

Copyright (c) 1991  Microsoft Corporation

Module Name:

    vrnmpipe.c

Abstract:

    Contains Named Pipe function handlers for Vdm Redir support. This module
    contains the following Vr (VdmRedir) routines:

    Contents:
        VrGetNamedPipeInfo
        VrGetNamedPipeHandleState
        VrSetNamedPipeHandleState
        VrPeekNamedPipe
        VrTransactNamedPipe
        VrCallNamedPipe
        VrWaitNamedPipe
        VrNetHandleGetInfo
        VrNetHandleSetInfo
        VrReadWriteAsyncNmPipe
        VrNmPipeInterrupt
        VrTerminateNamedPipes
        VrCancelPipeIo

    There are a couple of extra routines which must be called on open and close.
    Because these routines (in Dos Emulator) are general purpose, our open
    and close routines will be called for every file open/handle close. We
    must check that the operation is being performed on a named pipe entity.
    The routines are:

        VrAddOpenNamedPipeInfo
        VrRemoveOpenNamedPipeInfo

    Because named pipes are now opened in overlapped I/O mode, in case an app
    wishes to perform an asynchronous read or write operation, we must provide
    our own read/write routines for synchronously reading a pipe. If we just
    left this to the standard read/write routines in DEM, they would return an
    error because the handles were opened with FLAG_FILE_OVERLAPPED and the
    operations are performed with the LPOVERLAPPED parameter set to NULL

        VrReadNamedPipe
        VrWriteNamedPipe

    A couple of helper routines which are callable from outside of this module:

        VrIsNamedPipeName
        VrIsNamedPipeHandle
        VrConvertLocalNtPipeName

    Private (Vrp) routines:

        VrpAsyncNmPipeThread
        VrpSnapshotEventList
        VrpSearchForRequestByEventHandle
        VrpCompleteAsyncRequest
        VrpQueueAsyncRequest
        VrpDequeueAsyncRequest
        VrpFindCompletedRequest
        VrpAddOpenNamedPipeInfo
        VrpGetOpenNamedPipeInfo
        VrpRemoveOpenNamedPipeInfo
        RememberPipeIo
        ForgetPipeIo

Author:

    Richard L Firth (rfirth) 10-Sep-1991

Environment:

    Any 32-bit flat address space

Notes:

    This module implements client-side named pipe support for the VDM process.
    Client-side named pipes are opened using the standard DOS open call (INT 21/
    ah=3dh) from a DOS app. The actual open is performed in the 32-bit context
    where a 32-bit handle is returned. This is put in the DOS context SFT and
    DOS returns an 8-bit J(ob) F(ile) N(umber) which the app then uses in other
    named pipe calls. The redir, which handles named pipe requests apart from
    open and close, must map the 8-bit JFN to the original 32-bit handle using
    a routine exported from DOS. The handle is then stored in BP:BX and control
    passed here.

    When an open succeeds, we add an OPEN_NAMED_PIPE_INFO structure to a list
    of structures. This maps the handle and name (for DosQNmPipeInfo). We don't
    expect to have very many of these structures at any one time, so they are
    singly linked and sequentially traversed using the handle as a key

    This code assumes that only one process at a time will be updating the list
    of structures and that any non-stack data items in this module will be
    replicated to all processes which use these functions (Ie the data is NOT
    shared)

Revision History:

    10-Sep-1991 RFirth
        Created

--*/

#include <nt.h>
#include <ntrtl.h>      // ASSERT, DbgPrint
#include <nturtl.h>
#include <windows.h>
#include <softpc.h>     // x86 virtual machine definitions
#include <vrdlctab.h>
#include <vdmredir.h>   // common Vdm Redir stuff
#include <vrinit.h>     // VrQueueCompletionHandler
#include "vrdebug.h"    // IF_DEBUG
#include "vrputil.h"    // private utility prototypes
//#include <os2def.h>
//#include <bsedos.h>     // PIPEINFO structure
#include <align.h>
#include <lmcons.h>     // LM20_PATHLEN
#include <lmerr.h>      // NERR_
#include <string.h>     // Dos still dealing with ASCII
#include <dossvc.h>     // PDEMEXTERR
#include <exterr.h>     // extended error info

//
// the following 2 #undef's required because without them, insignia.h gives
// errors (BOOL previously typedef'd) when compiled for MIPS
//

#undef BOOL
#undef NT_INCLUDED
#include <insignia.h>   // Insignia defines
#include <xt.h>         // half_word
#include <ica.h>        // ica_hw_interrupt
#include <idetect.h>    // WaitIfIdle
#include <vrica.h>      // call_ica_hw_interrupt
#include <vrnmpipe.h>   // routine prototypes

#include <stdio.h>

//
// manifests
//

//#define NAMED_PIPE_TIMEOUT  300000  // 5 minutes
#define NAMED_PIPE_TIMEOUT  INFINITE

//
// private data types
//

//
// OVERLAPPED_PIPE_IO - contains handle of thread issuing named pipe I/O request.
// If the app is later killed, we need to cancel any pending named pipe I/O
//

typedef struct _OVERLAPPED_PIPE_IO {
    struct _OVERLAPPED_PIPE_IO* Next;
    DWORD Thread;
    BOOL Cancelled;
    OVERLAPPED Overlapped;
} OVERLAPPED_PIPE_IO, *POVERLAPPED_PIPE_IO;


//
// private routine prototypes
//

#undef PRIVATE
#define PRIVATE /* static */            // actually, want to see routines in FREE build

PRIVATE
DWORD
VrpAsyncNmPipeThread(
    IN LPVOID Parameters
    );

PRIVATE
DWORD
VrpSnapshotEventList(
    OUT LPHANDLE pList
    );

PRIVATE
PDOS_ASYNC_NAMED_PIPE_INFO
VrpSearchForRequestByEventHandle(
    IN HANDLE EventHandle
    );

PRIVATE
VOID
VrpCompleteAsyncRequest(
    IN PDOS_ASYNC_NAMED_PIPE_INFO pAsyncInfo
    );

PRIVATE
VOID
VrpQueueAsyncRequest(
    IN PDOS_ASYNC_NAMED_PIPE_INFO pAsyncInfo
    );

PRIVATE
PDOS_ASYNC_NAMED_PIPE_INFO
VrpDequeueAsyncRequest(
    IN PDOS_ASYNC_NAMED_PIPE_INFO pAsyncInfo
    );

PRIVATE
PDOS_ASYNC_NAMED_PIPE_INFO
VrpFindCompletedRequest(
    VOID
    );

PRIVATE
BOOL
VrpAddOpenNamedPipeInfo(
    IN HANDLE Handle,
    IN LPSTR PipeName
    );

PRIVATE
POPEN_NAMED_PIPE_INFO
VrpGetOpenNamedPipeInfo(
    IN HANDLE Handle
    );

PRIVATE
BOOL
VrpRemoveOpenNamedPipeInfo(
    IN HANDLE Handle
    );

PRIVATE
VOID
RememberPipeIo(
    IN POVERLAPPED_PIPE_IO PipeIo
    );

PRIVATE
VOID
ForgetPipeIo(
    IN POVERLAPPED_PIPE_IO PipeIo
    );

#if DBG
VOID DumpOpenPipeList(VOID);
VOID DumpRequestQueue(VOID);
#endif

//
// global data
//

DWORD VrPeekNamedPipeTickCount;

//
// private data
//

CRITICAL_SECTION VrNamedPipeCancelCritSec;
POVERLAPPED_PIPE_IO PipeIoQueue = NULL;


//
// Vdm Redir Named Pipe support routines
//

VOID
VrGetNamedPipeInfo(
    VOID
    )

/*++

Routine Description:

    Performs GetNamedPipeInfo (DosQNmPipeInfo) request on behalf of VDM redir

Arguments:

    Function = 5F32h

    ENTRY   BP:BX = 32-bit Named Pipe handle
            CX = Buffer size
            DX = Info level
            DS:SI = Buffer

    EXIT    CF = 1
                AX = Error code

            CF = 0
                no error
                AX = undefined

Return Value:

    None. Returns values in VDM Ax and Flags registers

--*/

{
    HANDLE Handle;
    DWORD Flags, OutBufferSize, InBufferSize, MaxInstances, CurInstances, bufLen;
    PIPEINFO* PipeInfo;
    BOOL Ok;
    POPEN_NAMED_PIPE_INFO OpenNamedPipeInfo;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrGetNamedPipeInfo(0x%08x, %d, %04x:%04x, %d)\n",
                 HANDLE_FROM_WORDS(getBP(), getBX()),
                 getDX(),
                 getDS(),
                 getSI(),
                 getCX()
                 );
    }
#endif

    //
    // bp:bx is 32-bit named pipe handle. Mapped from 8-bit handle in redir
    //

    Handle = HANDLE_FROM_WORDS(getBP(), getBX());

    //
    // we have to collect the info to put in the PIPEINFO structure from
    // various sources - we stored the name (& name length) in a
    // OPEN_NAMED_PIPE_INFO structure. The other stuff we get from
    // GetNamedPipeInfo and GetNamedPipeHandleState
    //

    OpenNamedPipeInfo = VrpGetOpenNamedPipeInfo(Handle);
    if (OpenNamedPipeInfo) {
        bufLen = getCX();
        if (bufLen >= sizeof(PIPEINFO)) {
            Ok =  GetNamedPipeInfo(Handle,
                                   &Flags,
                                   &OutBufferSize,
                                   &InBufferSize,
                                   &MaxInstances
                                   );
            if (Ok) {

                //
                // we are only interested in the current # instances of the
                // named pipe from this next call
                //

                Ok = GetNamedPipeHandleState(Handle,
                                             NULL,
                                             &CurInstances,
                                             NULL,
                                             NULL,
                                             NULL,
                                             0
                                             );
                if (Ok) {
                    PipeInfo = (PIPEINFO*)POINTER_FROM_WORDS(getDS(), getSI());
                    WRITE_WORD(&PipeInfo->cbOut, (OutBufferSize > 65535 ? 65535 : OutBufferSize));
                    WRITE_WORD(&PipeInfo->cbIn, (InBufferSize > 65535 ? 65535 : InBufferSize));
                    WRITE_BYTE(&PipeInfo->cbMaxInst, (MaxInstances > 255 ? 255 : MaxInstances));
                    WRITE_BYTE(&PipeInfo->cbCurInst, (CurInstances > 255 ? 255 : CurInstances));
                    WRITE_BYTE(&PipeInfo->cbName, OpenNamedPipeInfo->NameLength);

                    //
                    // copy name if enough space
                    //

                    if (bufLen - sizeof(PIPEINFO) >= OpenNamedPipeInfo->NameLength) {
                        strcpy(PipeInfo->szName, OpenNamedPipeInfo->Name);
                    }
                    setCF(0);
                } else {
                    SET_ERROR(VrpMapLastError());
                }
            } else {
                SET_ERROR(VrpMapLastError());
            }
        } else {
            SET_ERROR(ERROR_BUFFER_OVERFLOW);
        }
    } else {

#if DBG

        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrGetNamedPipeInfo: Error: can't map handle 0x%08x\n", Handle);
        }

#endif

        SET_ERROR(ERROR_INVALID_HANDLE);
    }

#if DBG
    IF_DEBUG(NAMEPIPE) {
        if (getCF()) {
            DbgPrint("VrGetNamedPipeInfo: returning ERROR: %d\n", getAX());
        } else {
            DbgPrint("VrGetNamedPipeInfo: returning OK. PIPEINFO:\n"
                     "cbOut     %04x\n"
                     "cbIn      %04x\n"
                     "cbMaxInst %02x\n"
                     "cbCurInst %02x\n"
                     "cbName    %02x\n"
                     "szName    %s\n",
                     READ_WORD(&PipeInfo->cbOut),
                     READ_WORD(&PipeInfo->cbIn),
                     READ_BYTE(&PipeInfo->cbMaxInst),
                     READ_BYTE(&PipeInfo->cbCurInst),
                     READ_BYTE(&PipeInfo->cbName),
                     READ_BYTE(&PipeInfo->szName)
                     );
        }
    }
#endif

}


VOID
VrGetNamedPipeHandleState(
    VOID
    )

/*++

Routine Description:

    Performs GetNamedPipeHandleState request on behalf of VDM redir

Arguments:

    Function = 5F33h

    ENTRY   BP:BX = 32-bit Named Pipe handle

    EXIT    CF = 1
                AX = Error code

            CF = 0
                AX = Pipe mode:
                        BSxxxWxRIIIIIIII

                        where:
                            B = Blocking mode. If B=1 the pipe is non blocking
                            S = Server end of pipe if 1
                            W = Pipe is written in message mode if 1 (else byte mode)
                            R = Pipe is read in message mode if 1 (else byte mode)
                            I = Pipe instances. Unlimited if 0xFF

Return Value:

    None. Returns values in VDM Ax and Flags registers

--*/

{
    HANDLE  Handle;
    DWORD   State, CurInstances, Flags, MaxInstances;
    BOOL    Ok;
    WORD    PipeHandleState;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrGetNamedPipeHandleState\n");
    }
#endif

    Handle = HANDLE_FROM_WORDS(getBP(), getBX());
    Ok =  GetNamedPipeHandleState(Handle,
                                  &State,
                                  &CurInstances,
                                  NULL,
                                  NULL,
                                  NULL,
                                  0
                                  );
    if (Ok) {
        Ok = GetNamedPipeInfo(Handle, &Flags, NULL, NULL, &MaxInstances);
        if (Ok) {

            //
            // Create the Dos pipe handle state from the information gathered
            //

            PipeHandleState = (WORD)((MaxInstances > 255) ? 255 : (MaxInstances & 0xff))
                | (WORD)((State & PIPE_NOWAIT) ? NP_NBLK : 0)
                | (WORD)((State & PIPE_READMODE_MESSAGE) ? NP_RMESG : 0)

                //
                // BUGBUG - can't possibly be server end????
                //

                | (WORD)((Flags & PIPE_SERVER_END) ? NP_SERVER : 0)
                | (WORD)((Flags & PIPE_TYPE_MESSAGE) ? NP_WMESG : 0)
                ;

            setAX((WORD)PipeHandleState);
            setCF(0);
        } else {
            SET_ERROR(VrpMapLastError());
        }
    } else {
        SET_ERROR(VrpMapLastError());
    }
}


VOID
VrSetNamedPipeHandleState(
    VOID
    )

/*++

Routine Description:

    Performs SetNamedPipeHandleState request on behalf of VDM redir

Arguments:

    Function = 5F34h

    ENTRY   BP:BX = 32-bit Named Pipe handle
            CX = Pipe mode to set

    EXIT    CF = 1
                AX = Error code

            CF = 0
                AX = Pipe mode set

Return Value:

    None. Returns values in VDM Ax and Flags registers

--*/

{
    HANDLE  Handle = HANDLE_FROM_WORDS(getBP(), getBX());
    BOOL    Ok;
    WORD    DosPipeMode;
    DWORD   WinPipeMode;

#define ILLEGAL_NMP_SETMODE_BITS    ~(NP_NBLK | NP_RMESG | NP_WMESG)

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrSetNamedPipeHandleState(0x%08x, %04x)\n", Handle, getCX());
    }
#endif

    //
    // Convert the Dos pipe mode bits to Win32 pipe mode bits. We can only
    // change the wait/no-wait status and the read mode of the pipe (byte
    // or message)
    //

    DosPipeMode = getCX();

    //
    // catch disallowed flags
    //

    if (DosPipeMode & ILLEGAL_NMP_SETMODE_BITS) {
        SET_ERROR(ERROR_INVALID_PARAMETER);
        return;
    }

    WinPipeMode = ((DosPipeMode & NP_NBLK)
                    ? PIPE_NOWAIT
                    : PIPE_WAIT)
                | ((DosPipeMode & NP_RMESG)
                    ? PIPE_READMODE_MESSAGE
                    : PIPE_READMODE_BYTE);
    if (!(Ok = SetNamedPipeHandleState(Handle, &WinPipeMode, NULL, NULL))) {

#if DBG

        IF_DEBUG(NAMEPIPE) {
            DbgPrint("Error: VrSetNamedPipeHandleState: returning %d\n", GetLastError());
        }

#endif

        SET_ERROR(VrpMapLastError());
    } else {
        setCF(0);
    }
}


VOID
VrPeekNamedPipe(
    VOID
    )

/*++

Routine Description:

    Performs PeekNamedPipe request on behalf of VDM redir

Arguments:

    Function = 5F35h

    ENTRY   BP:BX = 32-bit Named Pipe handle
            CX = Size of buffer for peek
            DS:SI = Buffer address

    EXIT    CF = 1
                AX = Error code

            CF = 0
                AX = Pipe status
                BX = Number of bytes peeked into buffer
                CX = Number of bytes in pipe
                DX = Number of bytes in message
                DI = Pipe status
                DS:SI = Data peeked

Return Value:

    None. Returns values in VDM Ax and Flags registers

--*/

{
    HANDLE Handle;
    LPBYTE lpBuffer;
    DWORD nBufferSize, BytesRead, BytesAvailable, BytesLeftInMessage;
    BOOL Ok;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrPeekNamedPipe(0x%08x, %04x:%04x, %d)\n",
                 HANDLE_FROM_WORDS(getBP(), getBX()),
                 getDS(),
                 getSI(),
                 getCX()
                 );
    }
#endif

    Handle = HANDLE_FROM_WORDS(getBP(), getBX());
    lpBuffer = (LPBYTE)POINTER_FROM_WORDS(getDS(), getSI());
    nBufferSize = (DWORD)getCX();
    Ok = PeekNamedPipe(Handle,
                       lpBuffer,
                       nBufferSize,
                       &BytesRead,
                       &BytesAvailable,
                       &BytesLeftInMessage
                       );
    if (Ok) {

        //
        // Since we gave a 16-bit quantity for the buffer size, BytesRead
        // cannot be >64K
        //

        setBX((WORD)BytesRead);
        setCX((WORD)BytesAvailable);

        //
        // if message mode pipe, return total bytes in message (as opposed to
        // NT's bytes LEFT in message)
        //

        setDX(BytesLeftInMessage ? ((WORD)BytesLeftInMessage + (WORD)BytesRead) : 0);

        //
        // Not sure what this means. According to NETPIAPI.ASM, a 3 is returned
        // on success, meaning status = connected. The named pipe statuses are
        // (according to BSEDOS.H):
        //
        //      NP_DISCONNECTED 1
        //      NP_LISTENING    2
        //      NP_CONNECTED    3
        //      NP_CLOSING      4
        //
        // Presumably, a client-side pipe can only be connected or the pipe is
        // closed
        //

        setDI(NP_CONNECTED);
        setCF(0);

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrPeekNamedPipe: Ok: %d bytes peeked, %d avail, %d left in message\n",
                     BytesRead,
                     BytesAvailable,
                     BytesLeftInMessage
                     );
        }
#endif

    } else {
        SET_ERROR(VrpMapLastError());

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrPeekNamedPipe: Error %d\n", getAX());
        }
#endif

        BytesRead = 0;
    }

    //
    // idle processing - only idle if there is nothing to return (including
    // an error occurred)
    //
    // For now, allow 10(!) peeks per second - on ALL pipe handles
    //

    if (!BytesRead) {
        if (GetTickCount() - VrPeekNamedPipeTickCount < 100) {
            WaitIfIdle();
        }
    }
    VrPeekNamedPipeTickCount = GetTickCount();
}


VOID
VrTransactNamedPipe(
    VOID
    )

/*++

Routine Description:

    Performs TransactNamedPipe request on behalf of VDM redir

Arguments:

    Function = 5F36h

    ENTRY   BP:BX = 32-bit Named Pipe handle
            CX = Transmit buffer length
            DX = Receive buffer length
            DS:SI = Transmit buffer
            ES:DI = Receive buffer

    EXIT    CF = 1
                AX = Error code

            CF = 0
                CX = Number of bytes in Receive buffer


Return Value:

    None. Returns values in VDM Ax and Flags registers

--*/

{
    DWORD BytesRead;
    BOOL Ok;
    OVERLAPPED_PIPE_IO pipeio;
    DWORD Error;
    HANDLE Handle;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrTransactNamedPipe(0x%08x, TxLen=%d, TxBuf=%04x:%04x, RxLen=%d, RxBuf=%04x:%04x)\n",
                 HANDLE_FROM_WORDS(getBP(), getBX()),
                 getCX(),
                 getDS(),
                 getSI(),
                 getDX(),
                 getES(),
                 getDI()
                 );
    }
#endif

    //
    // now that we are opening named pipes with FLAG_FILE_OVERLAPPED, we have
    // to perform every I/O operation with an OVERLAPPED structure. We are only
    // interested in the event handle. We create a new event for synchronous
    // operation which requires an OVERLAPPED structure. Create the event to
    // be manually reset - this way, if we wait on it & the read has already
    // completed, the wait completes immediately. If we create an auto-reset
    // event, then it may go back into the not-signalled state, causing us to
    // wait forever for an event that has already occurred
    //

    RtlZeroMemory(&pipeio, sizeof(pipeio));
    pipeio.Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (pipeio.Overlapped.hEvent != NULL) {

        //
        // collect arguments from registers and perform transact named pipe call
        //

        Handle = HANDLE_FROM_WORDS(getBP(), getBX());
        RememberPipeIo(&pipeio);
        Ok = TransactNamedPipe(Handle,
                               (LPVOID)POINTER_FROM_WORDS(getDS(), getSI()),
                               (DWORD)getCX(),
                               (LPVOID)POINTER_FROM_WORDS(getES(), getDI()),
                               (DWORD)getDX(),
                               &BytesRead,
                               &pipeio.Overlapped
                               );
        Error = Ok ? NO_ERROR : GetLastError();
        if (Error == ERROR_IO_PENDING) {

#if DBG
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("VrTransactNamedPipe: Ok, Waiting on hEvent...\n");
            }
#endif

            Error = WaitForSingleObject(pipeio.Overlapped.hEvent, NAMED_PIPE_TIMEOUT);
        }
        ForgetPipeIo(&pipeio);
        if (pipeio.Cancelled) {
            Error = WAIT_TIMEOUT;
        }
        if (Error == NO_ERROR || Error == ERROR_MORE_DATA) {
            GetOverlappedResult(Handle, &pipeio.Overlapped, &BytesRead, TRUE);

#if DBG
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("WaitForSingleObject completed. BytesRead=%d\n", BytesRead);
            }
#endif

            setCX((WORD)BytesRead);
            setAX((WORD)Error);

            //
            // if we are returning NO_ERROR then carry flag is clear, else we
            // are returning ERROR_MORE_DATA: set carry flag
            //

            setCF(Error == ERROR_MORE_DATA);
        } else {

            //
            // if we timed-out then close the pipe handle
            //

            if (Error == WAIT_TIMEOUT) {

#if DBG
                IF_DEBUG(NAMEPIPE) {
                    DbgPrint("VrTransactNamedPipe: Wait timed out: closing handle %08x\n", Handle);
                }
#endif
                CloseHandle(Handle);
                VrpRemoveOpenNamedPipeInfo(Handle);
            } else {
                Error = VrpMapLastError();
            }
            SET_ERROR((WORD)Error);

#if DBG
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("VrTransactNamedPipe: Error: %d\n", getAX());
            }
#endif
        }

        //
        // kill the event handle
        //

        CloseHandle(pipeio.Overlapped.hEvent);
    } else {

        //
        // failed to create event handle
        //

        SET_ERROR(VrpMapLastError());
    }
}


VOID
VrCallNamedPipe(
    VOID
    )

/*++

Routine Description:

    Performs CallNamedPipe request on behalf of VDM redir

Arguments:

    Function = 5F37h

    ENTRY   DS:SI = Pointer to CallNmPipe structure:

                DWORD   Timeout;            +0
                LPWORD  lpBytesRead;        +4
                WORD    OutputBufferLen;    +8
                LPBYTE  OutputBuffer;       +10
                WORD    InputBufferLength;  +14
                LPBYTE  InputBuffer;        +16
                LPSTR   PipeName;           +20

    EXIT    CF = 1
                AX = Error code

            CF = 0
                CX = Bytes received

Return Value:

    None. Returns values in VDM Ax and Flags registers

--*/

{
    BOOL Ok;
    DWORD BytesRead;
    PDOS_CALL_NAMED_PIPE_STRUCT StructurePointer;


    StructurePointer = (PDOS_CALL_NAMED_PIPE_STRUCT)POINTER_FROM_WORDS(getDS(), getSI());

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrCallNamedPipe(%s)\n", (LPSTR)READ_FAR_POINTER(&StructurePointer->lpPipeName));
    }
#endif

    Ok = CallNamedPipe((LPSTR)READ_FAR_POINTER(&StructurePointer->lpPipeName),
                        READ_FAR_POINTER(&StructurePointer->lpInBuffer),
                        READ_WORD(&StructurePointer->nInBufferLen),
                        READ_FAR_POINTER(&StructurePointer->lpOutBuffer),
                        READ_WORD(&StructurePointer->nOutBufferLen),
                        &BytesRead,
                        READ_DWORD(&StructurePointer->Timeout)
                        );
    if (!Ok) {
        SET_ERROR(VrpMapLastError());

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrCallNamedPipe: Error: CallNamedPipe returns %u\n", getAX());
        }
#endif
    } else {
        WRITE_WORD(READ_FAR_POINTER(&StructurePointer->lpBytesRead), (WORD)BytesRead);
        setCX((WORD)BytesRead);
        setCF(0);

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrCallNamedPipe: Ok\n");
        }
#endif
    }
}


VOID
VrWaitNamedPipe(
    VOID
    )

/*++

Routine Description:

    Performs WaitNamedPipe request on behalf of VDM redir. We assume that the
    name we are getting is \\computer\pipe\name, anything else is invalid

Arguments:

    Function = 5F38h

    ENTRY   BX:CX = Timeout
            DS:DX = Pipe name

    EXIT    CF = 1
                AX = Error code

            CF = 0
                No error

Return Value:

    None. Returns values in VDM Ax and Flags registers

--*/

{
    BOOL Ok;

    //
    // BUGBUG - should really perform DosPathCanonicalization on input string -
    // DOS redir would convert eg //server/pipe\foo.bar into \\SERVER\PIPE\FOO.BAR
    // if it makes any difference
    //

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrWaitNamedPipe(%s, %d)\n",
                    LPSTR_FROM_WORDS(getDS(), getDX()),
                    DWORD_FROM_WORDS(getBX(), getCX())
                    );
    }
#endif

    Ok = WaitNamedPipe(LPSTR_FROM_WORDS(getDS(), getDX()),
                        DWORD_FROM_WORDS(getBX(), getCX())
                        );
    if (!Ok) {
        SET_ERROR(VrpMapLastError());
    } else {

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("WaitNamedPipe returns TRUE\n");
        }
#endif
        setAX(0);
        setCF(0);
    }
}


VOID
VrNetHandleGetInfo(
    VOID
    )

/*++

Routine Description:

    Performs local NetHandleGetInfo on behalf of the Vdm client

Arguments:

    Function = 5F3Ch

    ENTRY   BP:BX = 32-bit Named Pipe handle
            CX = Buffer length
            SI = Level (1)
            DS:DX = Buffer

    EXIT    CX = size of required buffer (whether we got it or not)
            CF = 1
                AX = Error code

            CF = 0
                indicated stuff put in buffer

Return Value:

    None. Results returned via VDM registers or in VDM memory, according to
    request

--*/

{
    HANDLE  Handle;
    DWORD   Level;
    DWORD   BufLen;
    BOOL    Ok;
    DWORD   CollectCount;
    DWORD   CollectTime;
    LPVDM_HANDLE_INFO_1 StructurePointer;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrNetHandleGetInfo\n");
    }
#endif

    Handle = HANDLE_FROM_WORDS(getBP(), getBX());
    Level = (DWORD)getSI();
    if (Level == 1) {
        BufLen = (DWORD)getCX();
        if (BufLen >= sizeof(VDM_HANDLE_INFO_1)) {

            //
            // BUGBUG - the information we are interested in cannot be returned
            // if the client and server are on the same machine, or if this is
            // the server end of the pipe???
            //

            Ok = GetNamedPipeHandleState(Handle,
                                            NULL,   // not interested in state
                                            NULL,   // ditto curInstances
                                            &CollectCount,
                                            &CollectTime,
                                            NULL,   // not interested in client app name
                                            0
                                            );
            if (!Ok) {
                SET_ERROR(VrpMapLastError());
            } else {
                StructurePointer = (LPVDM_HANDLE_INFO_1)POINTER_FROM_WORDS(getDS(), getDX());
                StructurePointer->CharTime = CollectTime;
                StructurePointer->CharCount = (WORD)CollectCount;
                setCF(0);
            }
        } else {
            SET_ERROR(NERR_BufTooSmall);
        }
    } else {
        SET_ERROR(ERROR_INVALID_LEVEL);
    }
}


VOID
VrNetHandleSetInfo(
    VOID
    )

/*++

Routine Description:

    Performs local NetHandleSetInfo on behalf of the Vdm client

Arguments:

    Function = 5F3Bh

    ENTRY   BP:BX = 32-bit Named Pipe handle
            CX = Buffer length
            SI = Level (1)
            DI = Parmnum
            DS:DX = Buffer

    EXIT    CF = 1
                AX = Error code

            CF = 0
                Stuff from buffer set

Return Value:

    None. Results returned via VDM registers or in VDM memory, according to
    request

--*/

{
    HANDLE  Handle;
    DWORD   Level;
    DWORD   BufLen;
    BOOL    Ok;
    DWORD   Data;
    DWORD   ParmNum;
    LPBYTE  Buffer;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrNetHandleGetInfo\n");
        DbgBreakPoint();
    }
#endif

    Handle = HANDLE_FROM_WORDS(getBP(), getBX());
    Level = (DWORD)getSI();
    Buffer = LPBYTE_FROM_WORDS(getDS(), getDX());
    if (Level == 1) {
        BufLen = (DWORD)getCX();

        //
        // ParmNum can be 1 (CharTime) or 2 (CharCount), Can't be 0 (set
        // everything)
        //

        ParmNum = (DWORD)getDI();
        if (!--ParmNum) {
            if (BufLen < sizeof(((LPVDM_HANDLE_INFO_1)0)->CharTime)) {
                SET_ERROR(NERR_BufTooSmall);
                return ;
            }
            Data = (DWORD)*(LPDWORD)Buffer;
        } else if (!--ParmNum) {
            if (BufLen < sizeof(((LPVDM_HANDLE_INFO_1)0)->CharCount)) {
                SET_ERROR(NERR_BufTooSmall);
                return ;
            }
            Data = (DWORD)*(LPWORD)Buffer;
        } else {
            SET_ERROR(ERROR_INVALID_PARAMETER);
            return ;
        }

        //
        // BUGBUG - the information we are interested in cannot be set
        // if the client and server are on the same machine, or if this is
        // the server end of the pipe???
        //

        Ok = SetNamedPipeHandleState(Handle,
                                        NULL,   // not interested in mode
                                        (LPDWORD)((ParmNum == 1) ? &Data : NULL),
                                        (LPDWORD)((ParmNum == 2) ? &Data : NULL)
                                        );
        if (!Ok) {
            SET_ERROR(VrpMapLastError());
        } else {
            setCF(0);
        }
    } else {
        SET_ERROR(ERROR_INVALID_LEVEL);
    }
}


//
// Request Queue. This queue holds a singly linked list of async named pipe
// read/write requests. The async thread will search this list when an async
// read or write completes (the event is signalled). It then sets up the
// information for the call back to the VDM and dequeues the request info.
// Because we can have the async thread and the request thread simultaneously
// accessing the queue, it is protected by a critical section
//

CRITICAL_SECTION VrNmpRequestQueueCritSec;
PDOS_ASYNC_NAMED_PIPE_INFO RequestQueueHead = NULL;
PDOS_ASYNC_NAMED_PIPE_INFO RequestQueueTail = NULL;
HANDLE VrpNmpSomethingToDo;


VOID
VrReadWriteAsyncNmPipe(
    VOID
    )

/*++

Routine Description:

    Performs asynchronous read or write of a message mode named pipe on behalf
    of the VDM DOS application

Arguments:

    None. All arguments are extracted from DOS registers/memory.

    These calls are made through int 2fh/ax=function code, not int 21h/ah=5fh

        AX = 1186h  DosReadAsyncNmPipe
             118Fh  DosWriteAsyncNmPipe
             1190h  DosReadAsyncNmPipe2
             1191h  DosWriteAsyncNmPipe2

        BP:BX = 32-bit Named Pipe Handle

        DS:SI = DOS_ASYNC_NAMED_PIPE_STRUCT
            DD  address of returned bytes read
            DW  size of caller's buffer
            DD  address of caller's buffer
            DD  address of returned error code
            DD  address of Asynchronous Notification Routine
            DW  named pipe handle
            DD  address of caller's 'semaphore'

Return Value:

    None.

--*/

{
    HANDLE  Handle;

    //
    // Type is type of request - read or write, standard or 2 (meaning the
    // request has an associated 'semaphore' which must be cleared)
    //

    DWORD   Type;

    //
    // StructurePointer is 32-bit flat pointer to structure in DOS memory
    // containing request parameters
    //

    PDOS_ASYNC_NAMED_PIPE_STRUCT StructurePointer;

    //
    // pAsyncInfo is a pointer to the request packet we stick on the request
    // queue
    //

    PDOS_ASYNC_NAMED_PIPE_INFO pAsyncInfo;

    //
    // pipeInfo is a pointer to the information we created/stored when the
    // named pipe was opened. We just need this to check the handle's valid
    //

    POPEN_NAMED_PIPE_INFO pipeInfo;

    WORD    length;
    LPBYTE  buffer;
    DWORD   error;
    BOOL    ok;
    HANDLE  hEvent;
    DWORD   bytesTransferred;

    //
    // hThread and tid: these must be kept alive so long as the async named
    // pipe (completion) thread exists. tid can be used with ResumeThread and
    // SuspendThread as we may see fit
    //

    static HANDLE hThread = NULL;
    static DWORD tid;

    //
    // get info from registers and the async named pipe structure
    //

    Handle = HANDLE_FROM_WORDS(getBP(), getBX());
    pipeInfo = VrpGetOpenNamedPipeInfo(Handle);
    Type = (DWORD)getAX() & 0xff;   // 0x86, 0x8f, 0x90 or 0x91
    StructurePointer = (PDOS_ASYNC_NAMED_PIPE_STRUCT)POINTER_FROM_WORDS(getDS(), getSI());
    length = READ_WORD(&StructurePointer->BufferLength);
    buffer = READ_FAR_POINTER(&StructurePointer->lpBuffer);

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint(   "\n"
                    "VrReadWriteAsyncNmPipe (%04x) [%s]:\n"
                    "DOS_READ_ASYNC_NAMED_PIPE_STRUCT @ %08x:\n"
                    "32-bit named pipe handle . . . . %08x\n"
                    "Address of returned bytes read . %04x:%04x\n"
                    "Size of caller's buffer. . . . . %04x\n"
                    "Address of caller's buffer . . . %04x:%04x\n"
                    "Address of returned error code . %04x:%04x\n"
                    "Address of ANR . . . . . . . . . %04x:%04x\n"
                    "Named pipe handle. . . . . . . . %04x\n"
                    "Address of caller's semaphore. . %04x:%04x\n"
                    "\n",
                    (DWORD)getAX(), // type of read/write request
                    Type == ANP_READ
                        ? "READ"
                        : Type == ANP_WRITE
                            ? "WRITE"
                            : Type == ANP_READ2
                                ? "READ2"
                                : Type == ANP_WRITE2
                                    ? "WRITE2"
                                    : "?????",
                    StructurePointer,
                    Handle,
                    (DWORD)GET_SELECTOR(&StructurePointer->lpBytesRead),
                    (DWORD)GET_OFFSET(&StructurePointer->lpBytesRead),
                    (DWORD)StructurePointer->BufferLength,
                    (DWORD)GET_SELECTOR(&StructurePointer->lpBuffer),
                    (DWORD)GET_OFFSET(&StructurePointer->lpBuffer),
                    (DWORD)GET_SELECTOR(&StructurePointer->lpErrorCode),
                    (DWORD)GET_OFFSET(&StructurePointer->lpErrorCode),
                    (DWORD)GET_SELECTOR(&StructurePointer->lpANR),
                    (DWORD)GET_OFFSET(&StructurePointer->lpANR),
                    (DWORD)StructurePointer->PipeHandle,
                    (DWORD)GET_SELECTOR(&StructurePointer->lpSemaphore),
                    (DWORD)GET_OFFSET(&StructurePointer->lpSemaphore)
                    );
    }
#endif

    //
    // if we can't find this handle in our list of opened named pipes, return
    // an error
    //

    if (!pipeInfo) {

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrReadWriteAsyncNmPipe: Handle 0x%08x is invalid\n", Handle);
        }
#endif

        SET_ERROR(ERROR_INVALID_HANDLE);
        return;
    }

    //
    // looks like we're going to make an async read/write request. Create the
    // async thread if it doesn't already exist. Create also the "something to
    // do" event. Create this as an auto reset event which is initially in the
    // not-signalled state
    //

    if (hThread == NULL) {
        VrpNmpSomethingToDo = CreateEvent(NULL, FALSE, FALSE, NULL);
        if (VrpNmpSomethingToDo == NULL) {

#if DBG
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("VrReadWriteAsyncNmPipe: Error: Couldn't create something-to-do event: %d\n",
                            GetLastError()
                            );
            }
#endif

            //
            // return an out-of-resources error
            //

            SET_ERROR(ERROR_NOT_ENOUGH_MEMORY);
            return;
        }

        //
        // we have the "something to do" event. Now create the thread
        //

        hThread = CreateThread(NULL,
                               0,
                               VrpAsyncNmPipeThread,
                               NULL,
                               0,
                               &tid
                               );
        if (hThread == NULL) {

#if DBG
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("VrReadWriteAsyncNmPipe: Error: Couldn't create thread: %d\n",
                            GetLastError()
                            );
            }
#endif

            CloseHandle(VrpNmpSomethingToDo);
            SET_ERROR(ERROR_NOT_ENOUGH_MEMORY);
            return;
        }
    }

    //
    // allocate a structure in which to store the information required to
    // complete the request (in the VDM)
    //

    pAsyncInfo = (PDOS_ASYNC_NAMED_PIPE_INFO)LocalAlloc(LMEM_FIXED, sizeof(DOS_ASYNC_NAMED_PIPE_INFO));
    if (pAsyncInfo == NULL) {

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrReadWriteAsyncNmPipe: Error: Couldn't allocate structure\n");
        }
#endif

        SET_ERROR(ERROR_NOT_ENOUGH_MEMORY);
        return;
    }

    RtlZeroMemory(&pAsyncInfo->Overlapped, sizeof(pAsyncInfo->Overlapped));

    //
    // create a new event for this request - there can be multiple simultaneous
    // requests per named pipe. The event is manual reset so that if the request
    // completes before the WaitForMultipleObjects snaps the list, the event
    // will stay reset and hence the wait will complete. If we created the event
    // as auto-reset, it may get signalled, and go not-signalled before we wait
    // on it, potentially causing an infinite wait
    //

    hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (hEvent == NULL) {

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrReadWriteAsyncNmPipe: Error: Couldn't create event: %d\n", GetLastError());
        }
#endif

        LocalFree((HLOCAL)pAsyncInfo);

        //
        // return approximation out-of-resources error
        //

        SET_ERROR(ERROR_NOT_ENOUGH_MEMORY);
        return;
    } else {
        pAsyncInfo->Overlapped.hEvent = hEvent;
    }

    //
    // set up rest of async operation info structure
    //

    pAsyncInfo->Completed = FALSE;
    pAsyncInfo->Handle = Handle;
    pAsyncInfo->Buffer = (DWORD)StructurePointer->lpBuffer;
    pAsyncInfo->pBytesTransferred = READ_FAR_POINTER(&StructurePointer->lpBytesRead);
    pAsyncInfo->pErrorCode = READ_FAR_POINTER(&StructurePointer->lpErrorCode);
    pAsyncInfo->ANR = READ_DWORD(&StructurePointer->lpANR);

    //
    // if this is an AsyncNmPipe2 call then it has an associated semaphore
    // handle. Earlier versions don't have a semaphore
    //

    if (Type == ANP_READ2 || Type == ANP_WRITE2) {
        pAsyncInfo->Type2 = TRUE;
        pAsyncInfo->Semaphore = READ_DWORD(&StructurePointer->lpSemaphore);
    } else {
        pAsyncInfo->Type2 = FALSE;
        pAsyncInfo->Semaphore = (DWORD)NULL;
    }

#if DBG
    pAsyncInfo->RequestType = Type;
#endif

    //
    // add the completion info structure to the async thread's work queue
    //

    VrpQueueAsyncRequest(pAsyncInfo);

    //
    // Q: what happens if the request completes asynchronously before we finish
    // this routine?
    //

    if (Type == ANP_READ || Type == ANP_READ2) {
        ok = ReadFile(Handle,
                      buffer,
                      length,
                      &bytesTransferred,
                      &pAsyncInfo->Overlapped
                      );

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrReadWriteAsyncNmPipe: ReadFile(%x, %x, %d, ...): %d\n",
                     Handle,
                     buffer,
                     length,
                     ok
                     );
        }
#endif

    } else {
        ok = WriteFile(Handle,
                       buffer,
                       length,
                       &bytesTransferred,
                       &pAsyncInfo->Overlapped
                       );

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrReadWriteAsyncNmPipe: WriteFile(%x, %x, %d, ...): %d\n",
                     Handle,
                     buffer,
                     length,
                     ok
                     );
        }
#endif

    }
    error = ok ? NO_ERROR : GetLastError();

    //
    // if we get ERROR_MORE_DATA then treat it as an error. GetOverlappedResult
    // will give us the same error which we will return asynchronously
    //

    if (error != NO_ERROR && error != ERROR_IO_PENDING && error != ERROR_MORE_DATA) {

        //
        // we didn't get to start the I/O operation successfully, therefore
        // we won't get called back, so we dequeue and free the completion
        // structure and return the error
        //

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrReadWriteAsyncNmPipe: Error: IO operation returns %d\n", error);
        }
#endif

        VrpDequeueAsyncRequest(pAsyncInfo);
        CloseHandle(hEvent);
        LocalFree(pAsyncInfo);
        SET_ERROR((WORD)error);
    } else {

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrReadWriteAsyncNmPipe: IO operation started: returns %s\n",
                     error == ERROR_IO_PENDING ? "ERROR_IO_PENDING" : "NO_ERROR"
                     );
        }
#endif

        setCF(0);
    }

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrReadWriteAsyncNmPipe: returning CF=%d, AX=%d\n", getCF(), getAX());
    }
#endif
}


BOOLEAN
VrNmPipeInterrupt(
    VOID
    )

/*++

Routine Description:

    Called from hardware interrupt BOP processing to check if there are any
    async named pipe ANRs to call

Arguments:

    None.

Return Value:

    BOOLEAN
        TRUE    - there was an async named pipe operation to complete. The
                  VDM registers & data areas have been modified to indicate
                  that the named pipe ANR must be called

        FALSE   - no async named pipe processing to do. Interrupt must have
                  been generated by NetBios or DLC

--*/

{
    PDOS_ASYNC_NAMED_PIPE_INFO pAsyncInfo;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrNmPipeInterrupt\n");
    }
#endif


    //
    // locate the first async named pipe request packet that has completed and
    // is waiting for interrupt processing (ie its ANR to be called)
    //

    pAsyncInfo = VrpFindCompletedRequest();
    if (!pAsyncInfo) {

#if DBG

        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrNmPipeInterrupt - nothing to do\n");
        }

#endif

        //
        // returning FALSE indicates that the hardware interrupt callback was
        // not generated by async named pipe request completing
        //

        return FALSE;
    } else {

        //
        // set the VDM registers to indicate a named pipe callback
        //

        setDS(HIWORD(pAsyncInfo->Buffer));
        setSI(LOWORD(pAsyncInfo->Buffer));
        setES(HIWORD(pAsyncInfo->Semaphore));
        setDI(LOWORD(pAsyncInfo->Semaphore));
        setCX(HIWORD(pAsyncInfo->ANR));
        setBX(LOWORD(pAsyncInfo->ANR));
        setAL((BYTE)pAsyncInfo->Type2);
        SET_CALLBACK_NAMEPIPE();

        //
        // finished with this request packet, so dequeue and deallocate it
        //

        VrpDequeueAsyncRequest(pAsyncInfo);
        CloseHandle(pAsyncInfo->Overlapped.hEvent);
        LocalFree(pAsyncInfo);

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrNmPipeInterrupt: Setting DOS Registers:\n"
                     "DS:SI=%04x:%04x, ES:DI=%04x:%04x, CX:BX=%04x:%04x, AL=%02x\n",
                     getDS(), getSI(),
                     getES(), getDI(),
                     getCX(), getBX(),
                     getAL()
                     );
        }
#endif

        //
        // returning TRUE indicates that we have accepted a named pipe
        // completion request
        //

        //VrDismissInterrupt();
        return TRUE;
    }
}


VOID
VrTerminateNamedPipes(
    IN WORD DosPdb
    )

/*++

Routine Description:

    Cleans out all open named pipe info and pending async named pipe requests
    when the owning DOS app terminates

Arguments:

    DosPdb  - PDB (DOS 'process' identifier) of terminating DOS process

Return Value:

    None.

--*/

{
#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrTerminateNamedPipes\n");
    }
#endif
}


VOID
VrCancelPipeIo(
    IN DWORD Thread
    )

/*++

Routine Description:

    For all pending named pipe I/Os owned by Thread, mark them as cancelled
    and signal the event in the OVERLAPPED structure, causing the wait to
    terminate.

    This thread may not have any outstanding named pipe I/O

Arguments:

    Thread  - pseudo-handle of thread owning named pipe I/O

Return Value:

    None.

--*/

{
    POVERLAPPED_PIPE_IO ptr;

    EnterCriticalSection(&VrNamedPipeCancelCritSec);
    for (ptr = PipeIoQueue; ptr; ptr = ptr->Next) {
        if (ptr->Thread == Thread) {
            ptr->Cancelled = TRUE;
            SetEvent(ptr->Overlapped.hEvent);
        }
    }
    LeaveCriticalSection(&VrNamedPipeCancelCritSec);
}


PRIVATE
DWORD
VrpAsyncNmPipeThread(
    IN LPVOID Parameters
    )

/*++

Routine Description:

    Waits for an asynchronous named pipe read or write operation to complete.
    Loops forever, waiting on list of pending async (overlapped) named pipe
    operations. If there are no more outstanding named pipe read/writes then
    waits on VrpNmpSomethingToDo which is reset (put in not-signalled state)
    when there are no packets left on the request queue

Arguments:

    Parameters  - unused parameter block

Return Value:

    DWORD
        0

--*/

{
    DWORD numberOfHandles;
    DWORD index;
    HANDLE eventList[MAXIMUM_ASYNC_PIPES + 1];
    PDOS_ASYNC_NAMED_PIPE_INFO pRequest;

    UNREFERENCED_PARAMETER(Parameters);

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrAsyncNamedPipeThread: *** Started ***\n");
    }
#endif

    while (TRUE) {

        //
        // create an array of event handles. The first handle in the array is
        // the "something to do" event. This will only be reset when the queue
        // of requests changes from the empty set
        //

        numberOfHandles = VrpSnapshotEventList(eventList);
        index = WaitForMultipleObjects(numberOfHandles, eventList, FALSE, INFINITE);

        //
        // if the index is 0, then the "something to do" event has been signalled,
        // meaning that we have to snapshot a new event list and re-wait
        //

        if (index > 0 && index < numberOfHandles) {

#if DBG
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("VrpAsyncNmPipeThread: event #%d fired\n", index);
            }
#endif

            pRequest = VrpSearchForRequestByEventHandle(eventList[index]);
            if (pRequest != NULL) {
                VrpCompleteAsyncRequest(pRequest);
            }

#if DBG
            else {
                IF_DEBUG(NAMEPIPE) {
                    DbgPrint("VrpAsyncNmPipeThread: Couldn't find request for handle 0x%08x\n",
                                eventList[index]
                                );
                }
            }
#endif

        } else if (index) {

            //
            // an error occurred
            //

#if DBG
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("VrpAsyncNmPipeThread: Error: WaitForMultipleObjects returns %d (%d)\n",
                            index,
                            GetLastError()
                            );
            }
#endif

        }

#if DBG
        else {
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("VrpAsyncNmPipeThread: Something-to-do event fired\n");
            }
        }
#endif

    }

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpAsyncNmPipeThread: *** Terminated ***\n");
    }
#endif

    return 0;   // appease the compiler-god
}


PRIVATE
DWORD
VrpSnapshotEventList(
    OUT LPHANDLE pList
    )

/*++

Routine Description:

    Builds an array of event handles for those asynchronous named pipe I/O
    requests which are still not completed (the Completed flag is FALSE).
    The first event handle is always the "something to do" event

Arguments:

    pList   - pointer to callers list to build

Return Value:

    DWORD

--*/

{
    DWORD count = 1;
    PDOS_ASYNC_NAMED_PIPE_INFO ptr;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpSnapshotEventList\n");
    }
#endif

    pList[0] = VrpNmpSomethingToDo;
    EnterCriticalSection(&VrNmpRequestQueueCritSec);
    for (ptr = RequestQueueHead; ptr; ptr = ptr->Next) {
        if (ptr->Completed == FALSE) {
            pList[count++] = ptr->Overlapped.hEvent;
        }
    }
    LeaveCriticalSection(&VrNmpRequestQueueCritSec);

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpSnapshotEventList: returning %d events\n", count);
    }
#endif

    return count;
}


PRIVATE
PDOS_ASYNC_NAMED_PIPE_INFO
VrpSearchForRequestByEventHandle(
    IN HANDLE EventHandle
    )

/*++

Routine Description:

    Searches the async request queue for the structure with this event handle.
    If the structure is found, it is marked as Completed. The required structure
    may NOT be located: this might occur when an item was removed from the list
    due to an error in VrReadWriteAsyncNmPipe

Arguments:

    EventHandle - to search for

Return Value:

    PDOS_ASYNC_NAMED_PIPE_INFO
        Success - the located structure
        Failure - NULL

--*/

{
    PDOS_ASYNC_NAMED_PIPE_INFO ptr;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpSearchForRequestByEventHandle(0x%08x)\n", EventHandle);
    }
#endif

    EnterCriticalSection(&VrNmpRequestQueueCritSec);
    for (ptr = RequestQueueHead; ptr; ptr = ptr->Next) {
        if (ptr->Overlapped.hEvent == EventHandle) {
            ptr->Completed = TRUE;
            break;
        }
    }
    LeaveCriticalSection(&VrNmpRequestQueueCritSec);

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpLocateAsyncRequestByEventHandle returning 0x%08x: Request is %s\n",
                 ptr,
                 !ptr
                    ? "NO REQUEST!!"
                    : ptr->RequestType == ANP_READ
                        ? "READ"
                        : ptr->RequestType == ANP_WRITE
                            ? "WRITE"
                            : ptr->RequestType == ANP_READ2
                                ? "READ2"
                                : ptr->RequestType == ANP_WRITE2
                                    ? "WRITE2"
                                    : "UNKNOWN REQUEST!!"
                 );
    }
#endif

    return ptr;
}


PRIVATE
VOID
VrpCompleteAsyncRequest(
    IN PDOS_ASYNC_NAMED_PIPE_INFO pAsyncInfo
    )

/*++

Routine Description:

    Completes the asynchronous named pipe I/O request by getting the results
    of the transfer and filling-in the error & bytes transferred fields of
    the async named pipe info structure. If there is an ANR to be called, then
    a simulated hardware interrupt request is generated to the VDM. If there
    is no ANR to call then the async named pipe info structure is cleared out.

    If there is an ANR, the request will be completed finally when it is
    dequeued & freed by VrNmPipeInterrupt

Arguments:

    pAsyncInfo  - pointer to DOS_ASYNC_NAMED_PIPE_INFO structure to complete

Return Value:

    None.

--*/

{
    BOOL ok;
    DWORD bytesTransferred;
    DWORD error;

#if DBG

    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpCompleteAsyncRequest(0x%08x)\n", pAsyncInfo);
    }

#endif

    ok = GetOverlappedResult(pAsyncInfo->Handle,
                             &pAsyncInfo->Overlapped,
                             &bytesTransferred,
                             FALSE
                             );
    error = ok ? NO_ERROR : GetLastError();

    //
    // update the VDM variables
    //

    WRITE_WORD(pAsyncInfo->pErrorCode, error);
    WRITE_WORD(pAsyncInfo->pBytesTransferred, bytesTransferred);

#if DBG

    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpCompleteAsyncRequest: error=%d, bytesTransferred=%d\n",
                    error,
                    bytesTransferred
                    );
    }

#endif

    //
    // if there is no ANR then we cannot make a call-back to DOS (error? DOS
    // app polls 'semaphore'?) so close the event handle, dequeue the request
    // packet and free it
    //

    if (!pAsyncInfo->ANR) {

#if DBG

        PDOS_ASYNC_NAMED_PIPE_INFO ptr;

        ptr = VrpDequeueAsyncRequest(pAsyncInfo);
        if (ptr != pAsyncInfo) {
            DbgPrint("*** Error: incorrect request packet dequeued ***\n");
            DbgBreakPoint();
        }
#else

        VrpDequeueAsyncRequest(pAsyncInfo);

#endif

        CloseHandle(pAsyncInfo->Overlapped.hEvent);
        LocalFree(pAsyncInfo);
    } else {

        //
        // interrupt the VDM. It must call back to find out what asynchronous
        // processing there is to do
        //

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrpCompleteAsyncRequest: *** INTERRUPTING VDM ***\n");
        }
#endif

        VrQueueCompletionHandler(VrNmPipeInterrupt);
        VrRaiseInterrupt();
    }
}


PRIVATE
VOID
VrpQueueAsyncRequest(
    IN PDOS_ASYNC_NAMED_PIPE_INFO pAsyncInfo
    )

/*++

Routine Description:

    Adds a DOS_ASYNC_NAMED_PIPE_INFO structure to the end of the request queue.
    The queue is protected by a critical section

Arguments:

    pAsyncInfo  - pointer to structure to add

Return Value:

    None.

--*/

{
#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpQueueAsyncRequest\n");
    }
#endif

    EnterCriticalSection(&VrNmpRequestQueueCritSec);
    if (!RequestQueueHead) {
        RequestQueueHead = pAsyncInfo;

        //
        // the set is changing state from empty set to not empty set. Set the
        // "something to do" event. Note: it is OK to do this here (before we
        // have finished updating the queue info): because the async thread
        // must gain this critical section before it can access the request
        // queue
        //

//        PulseEvent(VrpNmpSomethingToDo);
    } else {
        RequestQueueTail->Next = pAsyncInfo;
    }
    pAsyncInfo->Next = NULL;
    RequestQueueTail = pAsyncInfo;
    SetEvent(VrpNmpSomethingToDo);
    LeaveCriticalSection(&VrNmpRequestQueueCritSec);
}


PRIVATE
PDOS_ASYNC_NAMED_PIPE_INFO
VrpDequeueAsyncRequest(
    IN PDOS_ASYNC_NAMED_PIPE_INFO pAsyncInfo
    )

/*++

Routine Description:

    Removes the DOS_ASYNC_NAMED_PIPE_INFO structure pointed at by pAsyncInfo
    from the request queue. Protected by critical section

Arguments:

    pAsyncInfo  - pointer to DOS_ASYNC_NAMED_PIPE_INFO to remove

Return Value:

    PDOS_ASYNC_NAMED_PIPE_INFO
        Success - pAsyncInfo is returned
        Failure - NULL - AsyncInfo wasn't found on the queue

--*/

{
    PDOS_ASYNC_NAMED_PIPE_INFO ptr;
    PDOS_ASYNC_NAMED_PIPE_INFO prev = (PDOS_ASYNC_NAMED_PIPE_INFO)&RequestQueueHead;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpDequeueAsyncRequest(0x%08x)\n", pAsyncInfo);
    }
#endif

    EnterCriticalSection(&VrNmpRequestQueueCritSec);
    for (ptr = RequestQueueHead; ptr; ptr = ptr->Next) {
        if (ptr == pAsyncInfo) {
            break;
        } else {
            prev = ptr;
        }
    }
    if (ptr) {
        prev->Next = ptr->Next;
        if (RequestQueueTail == ptr) {
            RequestQueueTail = prev;
        }
    }

    //
    // if this was the last item on the queue (in the set) then the set has
    // changed state from not empty to empty set. Reset the "something to do"
    // event to stop the async thread until another request arrives. Note: it
    // is safe to reset the event here
    //

//    ResetEvent(VrpNmpSomethingToDo);
    LeaveCriticalSection(&VrNmpRequestQueueCritSec);

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpDequeueAsyncRequest returning %08x\n", ptr);
    }
#endif

    return ptr;
}


PRIVATE
PDOS_ASYNC_NAMED_PIPE_INFO
VrpFindCompletedRequest(
    VOID
    )

/*++

Routine Description:

    Tries to locate the first request packet in the queue with the Completed
    field set, meaning the I/O request has completed and is waiting to generate
    a callback

Arguments:

    None.

Return Value:

    PDOS_ASYNC_NAMED_PIPE_INFO
        Success - pointer to request packet to complete
        Failure - NULL

--*/

{
    PDOS_ASYNC_NAMED_PIPE_INFO ptr;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpFindCompletedRequest\n");
    }
#endif

    EnterCriticalSection(&VrNmpRequestQueueCritSec);
    for (ptr = RequestQueueHead; ptr; ptr = ptr->Next) {
        if (ptr->Completed) {
            break;
        }
    }
    LeaveCriticalSection(&VrNmpRequestQueueCritSec);

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpFindCompletedRequest returning 0x%08x: Request is %s\n",
                 ptr,
                 !ptr
                    ? "NO REQUEST!!"
                    : ptr->RequestType == ANP_READ
                        ? "READ"
                        : ptr->RequestType == ANP_WRITE
                            ? "WRITE"
                            : ptr->RequestType == ANP_READ2
                                ? "READ2"
                                : ptr->RequestType == ANP_WRITE2
                                    ? "WRITE2"
                                    : "UNKNOWN REQUEST!!"
                 );
    }
#endif

    return ptr;
}


//
// externally callable interceptors
//

BOOL
VrAddOpenNamedPipeInfo(
    IN  HANDLE  Handle,
    IN  LPSTR   lpFileName
    )

/*++

Routine Description:

    This routine is called whenever DEM (Dos Emulator) successfully opens a
    handle to a file. We check if the file just opened was a named pipe (based
    on the name) and if so create an association between name and handle

Arguments:

    Handle      - of just opened file/pipe/device
    lpFileName  - symbolic name of what was just opened

Return Value:

    BOOL
        TRUE    - created/added open named pipe structure
        FALSE   - couldn't allocate structure memory or create event

--*/

{
    BOOL ok;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrAddOpenNamedPipeInfo\n");
    }
#endif

    if (VrIsNamedPipeName(lpFileName)) {

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("Adding %s as named pipe\n", lpFileName);
        }
#endif

        //
        // if we can't create the named pipe info structure, or the async
        // read/write event, return FALSE which results in an out-of-resources
        // error (not enough memory) since DOS doesn't understand about events
        //

        ok = VrpAddOpenNamedPipeInfo(Handle, lpFileName);
    } else {

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrAddOpenNamedPipeInfo: Error: not named pipe: %s\n", lpFileName);
        }
#endif

        ok = FALSE;

    }

    return ok;
}


BOOL
VrRemoveOpenNamedPipeInfo(
    IN HANDLE Handle
    )

/*++

Routine Description:

    This is the companion routine to VrAddOpenNamedPipeInfo. When a handle is
    successfully closed for a DOS app, we must check if it referenced a named
    pipe, and if so remove the info structure we created when the pipe was
    opened

Arguments:

    Handle  - to file/pipe/device just closed for Dos app

Return Value:

    BOOL
        TRUE
        FALSE

--*/

{
#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrRemoveOpenNamedPipeInfo\n");
    }

    if (!VrpRemoveOpenNamedPipeInfo(Handle)) {
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("Handle 0x%08x is not a named pipe\n", Handle);
        }
        return FALSE;
    } else {
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrRemoveOpenNamedPipeInfo - Handle 0x%08x has been removed\n", Handle);
        }
        return TRUE;
    }
#else
    VrpRemoveOpenNamedPipeInfo(Handle);
#endif

    return TRUE;
}


BOOL
VrReadNamedPipe(
    IN  HANDLE  Handle,
    IN  LPBYTE  Buffer,
    IN  DWORD   Buflen,
    OUT LPDWORD BytesRead,
    OUT LPDWORD Error
    )

/*++

Routine Description:

    Performs ReadFile on a named pipe handle. All named pipes are opened in
    overlapped-IO mode because async read/writes cannot be performed otherwise

Arguments:

    Handle      - of opened NamedPipe
    Buffer      - client (VDM) data buffer
    Buflen      - size of read buffer
    BytesRead   - where actual bytes read is returned
    Error       - pointer to returned error in case of failure or more data

Return Value:

    BOOL
        TRUE    - handle was successfully written
        FALSE   - an error occurred, use GetLastError

--*/

{
    OVERLAPPED_PIPE_IO pipeio;
    BOOL success;
    DWORD error;
    DWORD dwBytesRead;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrReadNamePipe(0x%08x, %x, %d)\n", Handle, Buffer, Buflen);
    }
#endif

    //
    // create an event to wait on. This goes in the overlapped structure - it
    // is the only thing in the overlapped structure we are interested in.
    // Create the event with manual reset. This is so that if the I/O operation
    // completes immediately, we don't wait on the event. If we create the
    // event as auto-reset, it can go into the signalled state, and back to the
    // not-signalled state before we prime the wait, causing us to wait forever
    // for an event that has already occurred
    //

    RtlZeroMemory(&pipeio, sizeof(pipeio));
    if ((pipeio.Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)) == NULL) {
        *Error = ERROR_NOT_ENOUGH_MEMORY;   // really want out-of-resources (71?)
        return FALSE;
    }

    //
    // event handle created ok
    //

    RememberPipeIo(&pipeio);
    success = ReadFile(Handle, Buffer, Buflen, BytesRead, &pipeio.Overlapped);
    if (!success) {
        error = GetLastError();
        if (error == ERROR_IO_PENDING) {
            error = WaitForSingleObject(pipeio.Overlapped.hEvent, NAMED_PIPE_TIMEOUT);
            if (error == 0xffffffff) {
                error = GetLastError();
            } else {
                success = (error == WAIT_OBJECT_0);
            }

        } else {

#if DBG
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("VrReadNamedPipe: ReadFile failed: %d\n", GetLastError());
            }
#endif

            //
            // if we got ERROR_MORE_DATA, then this is actually success(!). In this case
            // we don't want to SetLastError, but we do want to set the extended error
            // info in DOS data segment. This is done by demRead
            //

            if (error == ERROR_MORE_DATA) {
                success = TRUE;
            }
        }
    } else {
        error = NO_ERROR;
    }

    ForgetPipeIo(&pipeio);
    if (pipeio.Cancelled) {
        error = WAIT_TIMEOUT;
        success = FALSE;
    }

    if (success) {

        //
        // get the real bytes read. If GetOverlappedResult returns FALSE,
        // check for ERROR_MORE_DATA
        //

        success = GetOverlappedResult(Handle, &pipeio.Overlapped, &dwBytesRead, FALSE);
        error = success ? NO_ERROR : GetLastError();

        //
        // if we got ERROR_MORE_DATA, then this is actually success(!). In this case
        // we don't want to SetLastError, but we do want to set the extended error
        // info in DOS data segment. This is done by demRead
        //

        if (error == ERROR_MORE_DATA) {
            success = TRUE;
        }
    } else if (error == WAIT_TIMEOUT) {
        CloseHandle(Handle);
        VrpRemoveOpenNamedPipeInfo(Handle);
    }

    CloseHandle(pipeio.Overlapped.hEvent);

    //
    // if no bytes were read and success was returned then treat this as an
    // error - this is what the DOS Redir does
    //

    if (error == NO_ERROR && dwBytesRead == 0) {
        error = ERROR_NO_DATA;
        success = FALSE;
    }

    if (!success) {

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrReadNamePipe: Error: Returning %d\n", error);
        }
#endif

        SetLastError(error);
    } else {
        *BytesRead = dwBytesRead;

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrReadNamePipe: Ok: %d bytes read from pipe\n", *BytesRead);
        }
#endif

    }

    //
    // set the error code so that we can set the extended error code info
    // from demRead and return the success/failure indication
    //

    *Error = error;
    return success;
}


BOOL
VrWriteNamedPipe(
    IN  HANDLE  Handle,
    IN  LPBYTE  Buffer,
    IN  DWORD   Buflen,
    OUT LPDWORD BytesWritten
    )

/*++

Routine Description:

    Performs WriteFile on a named pipe handle. All named pipes are opened in
    overlapped-IO mode because async read/writes cannot be performed otherwise

Arguments:

    Handle          - of opened NamedPipe
    Buffer          - client (VDM) data buffer
    Buflen          - size of write
    BytesWritten    - where actual bytes written is returned

Return Value:

    BOOL
        TRUE    - handle was successfully written
        FALSE   - an error occurred, use GetLastError

--*/

{
    OVERLAPPED_PIPE_IO pipeio;
    BOOL success;
    DWORD error;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrWriteNamePipe(0x%08x, %x, %d)\n", Handle, Buffer, Buflen);
    }
#endif

    //
    // create an event to wait on. This goes in the overlapped structure - it
    // is the only thing in the overlapped structure we are interested in.
    // Create the event with manual reset. This is so that if the I/O operation
    // completes immediately, we don't wait on the event. If we create the
    // event as auto-reset, it can go into the signalled state, and back to the
    // not-signalled state before we prime the wait, causing us to wait forever
    // for an event that has already occurred
    //

    RtlZeroMemory(&pipeio, sizeof(pipeio));
    if ((pipeio.Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)) == NULL) {
        error = ERROR_NOT_ENOUGH_MEMORY;
        success = FALSE;
    } else {
        RememberPipeIo(&pipeio);
        success = WriteFile(Handle, Buffer, Buflen, BytesWritten, &pipeio.Overlapped);
        error = success ? NO_ERROR : GetLastError();
        if (error == ERROR_IO_PENDING) {
            error = WaitForSingleObject(pipeio.Overlapped.hEvent, NAMED_PIPE_TIMEOUT);
            if (error == 0xffffffff) {
                error = GetLastError();
            } else {
                success = (error == WAIT_OBJECT_0);
            }
        }
        ForgetPipeIo(&pipeio);
        if (pipeio.Cancelled) {
            error = WAIT_TIMEOUT;
            success = FALSE;
        }
    }
    if (success) {

        //
        // get the real bytes written
        //

        GetOverlappedResult(Handle, &pipeio.Overlapped, BytesWritten, FALSE);
    }
    CloseHandle(pipeio.Overlapped.hEvent);
    if (!success) {

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrWriteNamePipe: Error: Returning %d\n", error);
        }
#endif

        SetLastError(error);
        if (error == WAIT_TIMEOUT) {
            CloseHandle(Handle);
            VrpRemoveOpenNamedPipeInfo(Handle);
        }
    }

#if DBG

    else {
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrWriteNamePipe: Ok: %d bytes written to pipe\n", *BytesWritten);
        }
    }

#endif

    return success;
}


//
// externally callable helpers
//

BOOL
VrIsNamedPipeName(
    IN LPSTR Name
    )

/*++

Routine Description:

    Checks if a string designates a named pipe. As criteria for the decision
    we use:

        \\computername\PIPE\...

    DOS (client-side) can only open a named pipe which is created at a server
    and must therefore be prefixed by a computername

    We *know* that Name has just been used to successfully open a handle to
    a named <something>, so it should at least be semi-sensible. We can
    assume the following:

        * ASCIZ string
        * an LPSTR points at a single byte (& therefore ++ will add 1)

    But we can't assume the following:

        * Canonicalized name

Arguments:

    Name    - to check for (Dos) named pipe syntax

Return Value:

    BOOL
        TRUE    - Name refers to (local or remote) named pipe
        FALSE   - Name doesn't look like name of pipe

--*/

{
    int     CharCount;

#if DBG
    LPSTR   OriginalName = Name;
#endif

    if (IS_ASCII_PATH_SEPARATOR(*Name)) {
        ++Name;
        if (IS_ASCII_PATH_SEPARATOR(*Name)) {
            ++Name;
            CharCount = 0;
            while (*Name && !IS_ASCII_PATH_SEPARATOR(*Name)) {
                ++Name;
                ++CharCount;
            }
            if (!CharCount || !*Name) {

                //
                // Name is \\ or \\\ or just \\name which I don't understand,
                // so its not a named pipe - fail it
                //

#if DBG
                IF_DEBUG(NAMEPIPE) {
                    DbgPrint("VrIsNamedPipeName - returning FALSE for %s\n", OriginalName);
                }
#endif
                return FALSE;
            }

            //
            // bump name past next path separator. Note that we don't have to
            // check CharCount for max. length of a computername, because this
            // function is called only after the (presumed) named pipe has been
            // successfully opened, therefore we know that the name has been
            // validated
            //

            ++Name;
        } else {

#if DBG
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("VrIsNamedPipeName - returning FALSE for %s\n", OriginalName);
            }
#endif

            return FALSE;

        }

        //
        // We are at <something> (after \ or \\<name>\). Check if <something>
        // is [Pp][Ii][Pp][Ee][\\/]
        //

        if (!_strnicmp(Name, "PIPE", 4)) {
            Name += 4;
            if (IS_ASCII_PATH_SEPARATOR(*Name)) {

#if DBG
                IF_DEBUG(NAMEPIPE) {
                    DbgPrint("VrIsNamedPipeName - returning TRUE for %s\n", OriginalName);
                }
#endif

                return TRUE;
            }
        }
    }

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrIsNamedPipeName - returning FALSE for %s\n", OriginalName);
    }
#endif

    return FALSE;
}


BOOL
VrIsNamedPipeHandle(
    IN HANDLE Handle
    )

/*++

Routine Description:

    Checks if Handle appears in the list of known named pipe handles. Callable
    from outside this module

Arguments:

    Handle  - of suspected name pipe

Return Value:

    BOOL
        TRUE    Handle refers to an open named pipe
        FALSE   Don't know what Handle refers to

--*/

{
    return VrpGetOpenNamedPipeInfo(Handle) != NULL;
}


LPSTR
VrConvertLocalNtPipeName(
    OUT LPSTR Buffer OPTIONAL,
    IN LPSTR Name
    )

/*++

Routine Description:

    Converts a pipe name of the form \\<local-machine-name>\pipe\name to
    \\.\pipe\name

    If non-NULL pointer is returned, the buffer contains a canonicalized
    name - any forward-slash characters (/) are converted to backward-slash
    characters (\). In the interest of future-proofing, the name is not
    upper-cased

    Assumes: Name points to a named pipe specification (\\Server\PIPE\name)

    Note: it is possible to supply the same input and output buffers and have
          the conversion take place in situ. However, this is a side-effect
          of the fact the input computername is replaced by effectively a
          computername of length 1. Nevertheless, it is safe

Arguments:

    Buffer  - pointer to CHAR array where name is placed. If this parameter
              is not present then this routine will allocate a buffer (using
              LocalAlloc and return that
    Name    - pointer to ASCIZ pipe name

Return Value:

    LPSTR   - pointer to buffer containing name or NULL if failed

--*/

{
    DWORD prefixLength; // length of \\computername
    DWORD pipeLength;   // length of pipe name without computername/device prefix
    LPSTR pipeName;     // \PIPE\name...
    static char ThisComputerName[MAX_COMPUTERNAME_LENGTH+1] = {0};
    static DWORD ThisComputerNameLength = 0xffffffff;
    BOOLEAN mapped = FALSE;

    ASSERT(Name);
    ASSERT(IS_ASCII_PATH_SEPARATOR(Name[0]) && IS_ASCII_PATH_SEPARATOR(Name[1]));

    //
    // first time round, get the computername. If this fails assume there is no
    // computername (i.e. no network)
    //

    if (ThisComputerNameLength == 0xffffffff) {
        ThisComputerNameLength = sizeof(ThisComputerName);
        if (!GetComputerName((LPTSTR)&ThisComputerName, &ThisComputerNameLength)) {
            ThisComputerNameLength = 0;
        }
    }

    if (!ARGUMENT_PRESENT(Buffer)) {
        Buffer = (LPSTR)LocalAlloc(LMEM_FIXED, strlen(Name)+1);
    }

    if (Buffer) {
        pipeName = strchr(Name+2, '\\');    // starts \pipe\...
        if (!pipeName) {
            pipeName = strchr(Name+2, '/');
        }
        ASSERT(pipeName);
        pipeLength = strlen(pipeName);
        prefixLength = (DWORD)pipeName - (DWORD)Name;
        if (ThisComputerNameLength && (prefixLength - 2 == ThisComputerNameLength)) {
            if (!_strnicmp(ThisComputerName, &Name[2], ThisComputerNameLength)) {
                strcpy(Buffer, LOCAL_DEVICE_PREFIX);
                mapped = TRUE;
            }
        }
        if (!mapped) {
            strncpy(Buffer, Name, prefixLength);
            Buffer[prefixLength] = 0;

        }
        strcat(Buffer, pipeName);

        //
        // convert any forward-slashes to backward-slashes
        //


        do {
            if (pipeName = strchr(Buffer, '/')) {
                *pipeName++ = '\\';
            }
        } while (pipeName);

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrConvertLocalNtPipeName - returning %s\n", Buffer);
        }
#endif

    }

    return Buffer;
}


//
// Private utilities
//

//
// Private list of open named pipe info structures for this VDM process, and
// associated manipulation routines
//

PRIVATE
POPEN_NAMED_PIPE_INFO   OpenNamedPipeInfoList = NULL;

PRIVATE
POPEN_NAMED_PIPE_INFO   LastOpenNamedPipeInfo = NULL;

PRIVATE
BOOL
VrpAddOpenNamedPipeInfo(
    IN HANDLE Handle,
    IN LPSTR PipeName
    )

/*++

Routine Description:

    When a named pipe is successfully opened, we call this routine to
    associate an open handle and a pipe name. This is required by
    DosQNmPipeInfo (VrGetNamedPipeInfo)

Arguments:

    Handle      - The handle returned from CreateFile (in demOpen)
    PipeName    - Name of pipe being opened

Return Value:

    BOOL
        TRUE    - created a OPEN_NAMED_PIPE_INFO structure and added to list
        FALSE   - couldn't get memory, or couldn't create event. Use GetLastError
                  if you really want to know why this failed

--*/

{
    POPEN_NAMED_PIPE_INFO PipeInfo;
    DWORD NameLength;

    //
    // grab a OPEN_NAMED_PIPE_INFO structure
    //

    NameLength = strlen(PipeName) + 1;
    PipeInfo = (POPEN_NAMED_PIPE_INFO)
                LocalAlloc(LMEM_FIXED,
                    ROUND_UP_COUNT((sizeof(OPEN_NAMED_PIPE_INFO) + NameLength),
                        sizeof(DWORD)
                        )
                    );

    //
    // if we cannot claim memory here, we should *really* close the pipe and
    // return an insufficient memory error to the VDM. However, I don't expect
    // us to run out of memory
    //

    if (PipeInfo == NULL) {

#if DBG
        IF_DEBUG(NAMEPIPE) {
            DbgPrint("VrpAddOpenNamedPipeInfo: couldn't allocate structure - returning FALSE\n");
        }
#endif

        return FALSE;
    }

    //
    // fill it in
    //

    PipeInfo->Next = NULL;
    PipeInfo->Handle = Handle;
    PipeInfo->NameLength = NameLength;
    strcpy(PipeInfo->Name, PipeName);   // from DOS, so its old-fashioned ASCII

    //
    // put it at the end of the list
    //

    if (LastOpenNamedPipeInfo == NULL) {
        OpenNamedPipeInfoList = PipeInfo;
    } else {
        LastOpenNamedPipeInfo->Next = PipeInfo;
    }
    LastOpenNamedPipeInfo = PipeInfo;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpAddOpenNamedPipeInfo - adding structure @ %08x, Handle=0x%08x, Name=%s\n",
            PipeInfo,
            PipeInfo->Handle,
            PipeInfo->Name
            );
    }
#endif

    return TRUE;
}


PRIVATE
POPEN_NAMED_PIPE_INFO
VrpGetOpenNamedPipeInfo(
    IN HANDLE Handle
    )

/*++

Routine Description:

    Linear search for an OPEN_NAMED_PIPE_INFO structure in OpenNamedPipeInfoList
    using the handle as search criteria

Arguments:

    Handle  - to search for

Return Value:

    POPEN_NAMED_PIPE_INFO
        Success - Pointer to located structure
        Failure - NULL

--*/

{
    POPEN_NAMED_PIPE_INFO ptr;

    for (ptr = OpenNamedPipeInfoList; ptr; ptr = ptr->Next) {
        if (ptr->Handle == Handle) {
            break;
        }
    }
    return ptr;
}


PRIVATE
BOOL
VrpRemoveOpenNamedPipeInfo(
    IN HANDLE Handle
    )

/*++

Routine Description:

    Unlinks and frees an OPEN_NAMED_PIPE_INFO structure from
    OpenNamedPipeInfoList

    Note: Assumes that the Handle is in the list (no action taken if not
    found)

Arguments:

    Handle  - defining OPEN_NAMED_PIPE_INFO structure to remove from list

Return Value:

    BOOL
        TRUE    - OPEN_NAMED_PIPE_INFO structure corresponding to Handle was
                  removed from list and freed
        FALSE   - OPEN_NAMED_PIPE_INFO structure corresponding to Handle was
                  not found

--*/

{
    POPEN_NAMED_PIPE_INFO ptr, prev = NULL;

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpRemoveOpenNamedPipeInfo(0x%08x)\n", Handle);
        DumpOpenPipeList();
        DumpRequestQueue();
    }
#endif

    for (ptr = OpenNamedPipeInfoList; ptr; ) {
        if (ptr->Handle == Handle) {
            if (!prev) {
                OpenNamedPipeInfoList = ptr->Next;
            } else {
                prev->Next = ptr->Next;
            }
            if (LastOpenNamedPipeInfo == ptr) {
                LastOpenNamedPipeInfo = prev;
            }

#if DBG
            IF_DEBUG(NAMEPIPE) {
                DbgPrint("VrpRemoveOpenNamedPipeInfo - freeing structure @ %08x, Handle=0x%08x, Name=%s\n",
                    ptr,
                    ptr->Handle,
                    ptr->Name
                    );
            }
#endif

            LocalFree(ptr);
            return TRUE;
        } else {
            prev = ptr;
            ptr = ptr->Next;
        }
    }

#if DBG
    IF_DEBUG(NAMEPIPE) {
        DbgPrint("VrpRemoveOpenNamedPipeInfo: Can't find 0x%08x in list\n", Handle);
    }
#endif

    return FALSE;
}


PRIVATE
VOID
RememberPipeIo(
    IN POVERLAPPED_PIPE_IO PipeIo
    )

/*++

Routine Description:

    Adds an OVERLAPPED_PIPE_IO structure to the list of in-progress named pipe
    I/Os

Arguments:

    PipeIo  - pointer to OVERLAPPED_PIPE_IO structure to add to list

Return Value:

    None.

--*/

{
    //
    // just stick this at front of list; order is not important - this is just
    // a stack of in-progress requests
    //

    PipeIo->Thread = GetCurrentThreadId();
    EnterCriticalSection(&VrNamedPipeCancelCritSec);
    PipeIo->Next = PipeIoQueue;
    PipeIoQueue = PipeIo;
    LeaveCriticalSection(&VrNamedPipeCancelCritSec);
}


PRIVATE
VOID
ForgetPipeIo(
    IN POVERLAPPED_PIPE_IO PipeIo
    )

/*++

Routine Description:

    Removes an OVERLAPPED_PIPE_IO structure from the list of in-progress named
    pipe I/Os

Arguments:

    PipeIo  - pointer to OVERLAPPED_PIPE_IO structure to remove

Return Value:

    None.

--*/

{
    POVERLAPPED_PIPE_IO prev, ptr;

    EnterCriticalSection(&VrNamedPipeCancelCritSec);
    for (ptr = PipeIoQueue, prev = (POVERLAPPED_PIPE_IO)&PipeIoQueue; ptr && ptr != PipeIo; ) {
        prev = ptr;
        ptr = ptr->Next;
    }
    if (ptr == PipeIo) {
        prev->Next = ptr->Next;
    }
    LeaveCriticalSection(&VrNamedPipeCancelCritSec);
}


#if DBG
VOID DumpOpenPipeList()
{
    POPEN_NAMED_PIPE_INFO ptr = OpenNamedPipeInfoList;

    DbgPrint("DumpOpenPipeList\n");

    if (!ptr) {
        DbgPrint("DumpOpenPipeList: no open named pipe structures\n");
    } else {
        while (ptr) {
            DbgPrint("\n"
                     "OPEN_NAMED_PIPE_INFO structure @%08x:\n"
                     "Next. . . . . . . . . . %08x\n"
                     "Handle. . . . . . . . . %08x\n"
                     "NameLength. . . . . . . %d\n"
                     "DosPdb. . . . . . . . . %04x\n"
                     "Name. . . . . . . . . . %s\n",
                     ptr,
                     ptr->Next,
                     ptr->Handle,
                     ptr->NameLength,
                     ptr->DosPdb,
                     ptr->Name
                     );
            ptr = ptr->Next;
        }
        DbgPrint("\n");
    }
}

VOID DumpRequestQueue()
{
    PDOS_ASYNC_NAMED_PIPE_INFO ptr;

    DbgPrint("DumpRequestQueue\n");

    EnterCriticalSection(&VrNmpRequestQueueCritSec);
    ptr = RequestQueueHead;
    if (!ptr) {
        DbgPrint("DumpRequestQueue: no request packets queued\n");
    } else {
        for (; ptr; ptr = ptr->Next) {

            //
            // NT (308c) can't handle all this being put on the stack - gets
            // fault in KdpCopyDataToStack
            //

            DbgPrint("\n"
                     "DOS_ASYNC_NAMED_PIPE_INFO structure @%08x:\n"
                     "Next. . . . . . . . . . %08x\n"
                     "Overlapped.Internal . . %08x\n"
                     "Overlapped.InternalHigh %08x\n"
                     "Overlapped.Offset . . . %08x\n"
                     "Overlapped.OffsetHigh . %08x\n"
                     "Overlapped.hEvent . . . %08x\n",
                     ptr,
                     ptr->Next,
                     ptr->Overlapped.Internal,
                     ptr->Overlapped.InternalHigh,
                     ptr->Overlapped.Offset,
                     ptr->Overlapped.OffsetHigh,
                     ptr->Overlapped.hEvent
                     );
            DbgPrint("Type2 . . . . . . . . . %d\n"
                     "Completed . . . . . . . %d\n"
                     "Handle. . . . . . . . . %08x\n"
                     "Buffer. . . . . . . . . %04x:%04x\n"
                     "BytesTransferred. . . . %d\n"
                     "pBytesTransferred . . . %08x\n"
                     "pErrorCode. . . . . . . %08x\n"
                     "ANR . . . . . . . . . . %04x:%04x\n"
                     "Semaphore . . . . . . . %04x:%04x\n"
                     "RequestType . . . . . . %04x [%s]\n",
                     ptr->Type2,
                     ptr->Completed,
                     ptr->Handle,
                     HIWORD(ptr->Buffer),
                     LOWORD(ptr->Buffer),
                     ptr->BytesTransferred,
                     ptr->pBytesTransferred,
                     ptr->pErrorCode,
                     HIWORD(ptr->ANR),
                     LOWORD(ptr->ANR),
                     HIWORD(ptr->Semaphore),
                     LOWORD(ptr->Semaphore),
                     ptr->RequestType,
                     ptr->RequestType == ANP_READ
                        ? "READ"
                        : ptr->RequestType == ANP_READ2
                            ? "READ2"
                            : ptr->RequestType == ANP_WRITE
                                ? "WRITE"
                                : ptr->RequestType == ANP_WRITE2
                                    ? "WRITE2"
                                    : "*** UNKNOWN REQUEST ***"
                    );
        }
        DbgPrint("\n");
    }
    LeaveCriticalSection(&VrNmpRequestQueueCritSec);
}
#endif