summaryrefslogtreecommitdiffstats
path: root/src/VBox/Runtime/r3/socket.cpp
blob: 4acfe73e97c6cfb53ef634c17b0c28003153bc5c (plain)
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
/* $Id: socket.cpp $ */
/** @file
 * IPRT - Network Sockets.
 */

/*
 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
 * in the VirtualBox distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 *
 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#ifdef RT_OS_WINDOWS
# include <iprt/win/winsock2.h>
# include <iprt/win/ws2tcpip.h>
#else /* !RT_OS_WINDOWS */
# include <errno.h>
# include <sys/select.h>
# include <sys/stat.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <arpa/inet.h>
# ifdef IPRT_WITH_TCPIP_V6
#  include <netinet6/in6.h>
# endif
# include <sys/un.h>
# include <netdb.h>
# include <unistd.h>
# include <fcntl.h>
# include <sys/uio.h>
# ifndef AF_LOCAL
#   define AF_LOCAL AF_UNIX
# endif
#endif /* !RT_OS_WINDOWS */
#include <limits.h>

#include "internal/iprt.h"
#include <iprt/socket.h>

#include <iprt/alloca.h>
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/ctype.h>
#include <iprt/err.h>
#include <iprt/mempool.h>
#include <iprt/poll.h>
#include <iprt/string.h>
#include <iprt/thread.h>
#include <iprt/time.h>
#include <iprt/mem.h>
#include <iprt/sg.h>
#include <iprt/log.h>

#include "internal/magics.h"
#include "internal/socket.h"
#include "internal/string.h"
#ifdef RT_OS_WINDOWS
# include "win/internal-r3-win.h"
#endif


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/* non-standard linux stuff (it seems). */
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL           0
#endif

/* Windows has different names for SHUT_XXX. */
#ifndef SHUT_RDWR
# ifdef SD_BOTH
#  define SHUT_RDWR             SD_BOTH
# else
#  define SHUT_RDWR             2
# endif
#endif
#ifndef SHUT_WR
# ifdef SD_SEND
#  define SHUT_WR               SD_SEND
# else
#  define SHUT_WR               1
# endif
#endif
#ifndef SHUT_RD
# ifdef SD_RECEIVE
#  define SHUT_RD               SD_RECEIVE
# else
#  define SHUT_RD               0
# endif
#endif

/* fixup backlevel OSes. */
#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
# define socklen_t              int
#endif

/** How many pending connection. */
#define RTTCP_SERVER_BACKLOG    10

/* Limit read and write sizes on Windows and OS/2. */
#ifdef RT_OS_WINDOWS
# define RTSOCKET_MAX_WRITE     (INT_MAX / 2)
# define RTSOCKET_MAX_READ      (INT_MAX / 2)
#elif defined(RT_OS_OS2)
# define RTSOCKET_MAX_WRITE     0x10000
# define RTSOCKET_MAX_READ      0x10000
#endif


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * Socket handle data.
 *
 * This is mainly required for implementing RTPollSet on Windows.
 */
typedef struct RTSOCKETINT
{
    /** Magic number (RTSOCKET_MAGIC). */
    uint32_t            u32Magic;
    /** Exclusive user count.
     * This is used to prevent two threads from accessing the handle concurrently.
     * It can be higher than 1 if this handle is reference multiple times in a
     * polling set (Windows). */
    uint32_t volatile   cUsers;
    /** The native socket handle. */
    RTSOCKETNATIVE      hNative;
    /** Indicates whether the handle has been closed or not. */
    bool volatile       fClosed;
    /** Indicates whether the socket is operating in blocking or non-blocking mode
     * currently. */
    bool                fBlocking;
    /** Whether to leave the native socket open rather than closing it (for
     * RTHandleGetStandard). */
    bool                fLeaveOpen;
#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
    /** The pollset currently polling this socket.  This is NIL if no one is
     * polling. */
    RTPOLLSET           hPollSet;
#endif
#ifdef RT_OS_WINDOWS
    /** The event semaphore we've associated with the socket handle.
     * This is WSA_INVALID_EVENT if not done. */
    WSAEVENT            hEvent;
    /** The events we're polling for. */
    uint32_t            fPollEvts;
    /** The events we're currently subscribing to with WSAEventSelect.
     * This is ZERO if we're currently not subscribing to anything. */
    uint32_t            fSubscribedEvts;
    /** Saved events which are only posted once and events harvested for
     * sockets entered multiple times into to a poll set.   Imagine a scenario where
     * you have a RTPOLL_EVT_READ entry and RTPOLL_EVT_ERROR entry.  The READ
     * condition can be triggered between checking the READ entry and the ERROR
     * entry, and we don't want to drop the READ, so we store it here and make sure
     * the event is signalled.
     *
     * The RTPOLL_EVT_ERROR is inconsistenly sticky at the momemnt... */
    uint32_t            fEventsSaved;
    /** Set if fEventsSaved contains harvested events (used to avoid multiple
     *  calls to rtSocketPollCheck on the same socket during rtSocketPollDone). */
    bool                fHarvestedEvents;
    /** Set if we're using the polling fallback. */
    bool                fPollFallback;
    /** Set if the fallback polling is active (event not set). */
    bool volatile       fPollFallbackActive;
    /** Set to shut down the fallback polling thread. */
    bool volatile       fPollFallbackShutdown;
    /** Socket use to wake up the select thread. */
    RTSOCKETNATIVE      hPollFallbackNotifyW;
    /** Socket the select thread always waits on. */
    RTSOCKETNATIVE      hPollFallbackNotifyR;
    /** The fallback polling thread. */
    RTTHREAD            hPollFallbackThread;
#endif /* RT_OS_WINDOWS */
} RTSOCKETINT;


/**
 * Address union used internally for things like getpeername and getsockname.
 */
typedef union RTSOCKADDRUNION
{
    struct sockaddr     Addr;
    struct sockaddr_in  IPv4;
#ifdef IPRT_WITH_TCPIP_V6
    struct sockaddr_in6 IPv6;
#endif
} RTSOCKADDRUNION;


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
#ifdef RT_OS_WINDOWS
/** Indicates that we've successfully initialized winsock.  */
static uint32_t volatile g_uWinSockInitedVersion = 0;
#endif


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
#ifdef RT_OS_WINDOWS
static void rtSocketPokePollFallbackThread(RTSOCKETINT *pThis);
#endif



#ifdef RT_OS_WINDOWS
/**
 * Initializes winsock for the process.
 *
 * @returns IPRT status code.
 */
static int rtSocketInitWinsock(void)
{
    if (g_uWinSockInitedVersion != 0)
        return VINF_SUCCESS;

    if (   !g_pfnWSAGetLastError
        || !g_pfnWSAStartup
        || !g_pfnsocket
        || !g_pfnclosesocket)
        return VERR_NET_INIT_FAILED;

    /*
     * Initialize winsock. Try with 2.2 and back down till we get something that works.
     */
    static const WORD s_awVersions[] =
    {
        MAKEWORD(2, 2),
        MAKEWORD(2, 1),
        MAKEWORD(2, 0),
        MAKEWORD(1, 1),
        MAKEWORD(1, 0),
    };
    for (uint32_t i = 0; i < RT_ELEMENTS(s_awVersions); i++)
    {
        WSADATA     wsaData;
        RT_ZERO(wsaData);
        int rcWsa = g_pfnWSAStartup(s_awVersions[i], &wsaData);
        if (rcWsa == 0)
        {
            /* AssertMsg(wsaData.wVersion >= s_awVersions[i]); - triggers with winsock 1.1 */
            ASMAtomicWriteU32(&g_uWinSockInitedVersion, wsaData.wVersion);
            return VINF_SUCCESS;
        }
        AssertLogRelMsg(rcWsa == WSAVERNOTSUPPORTED, ("rcWsa=%d (winsock version %#x)\n", rcWsa, s_awVersions[i]));
    }
    LogRel(("Failed to init winsock!\n"));
    return VERR_NET_INIT_FAILED;
}
#endif


/**
 * Get the last error as an iprt status code.
 *
 * @returns IPRT status code.
 */
DECLINLINE(int) rtSocketError(void)
{
#ifdef RT_OS_WINDOWS
    if (g_pfnWSAGetLastError)
        return RTErrConvertFromWin32(g_pfnWSAGetLastError());
    return VERR_NET_IO_ERROR;
#else
    return RTErrConvertFromErrno(errno);
#endif
}


/**
 * Resets the last error.
 */
DECLINLINE(void) rtSocketErrorReset(void)
{
#ifdef RT_OS_WINDOWS
    if (g_pfnWSASetLastError)
        g_pfnWSASetLastError(0);
#else
    errno = 0;
#endif
}


/**
 * Get the last resolver error as an iprt status code.
 *
 * @returns iprt status code.
 */
DECLHIDDEN(int) rtSocketResolverError(void)
{
#ifdef RT_OS_WINDOWS
    if (g_pfnWSAGetLastError)
        return RTErrConvertFromWin32(g_pfnWSAGetLastError());
    return VERR_UNRESOLVED_ERROR;
#else
    switch (h_errno)
    {
        case HOST_NOT_FOUND:
            return VERR_NET_HOST_NOT_FOUND;
        case NO_DATA:
            return VERR_NET_ADDRESS_NOT_AVAILABLE;
        case NO_RECOVERY:
            return VERR_IO_GEN_FAILURE;
        case TRY_AGAIN:
            return VERR_TRY_AGAIN;

        default:
            AssertLogRelMsgFailed(("Unhandled error %u\n", h_errno));
            return VERR_UNRESOLVED_ERROR;
    }
#endif
}


/**
 * Converts from a native socket address to a generic IPRT network address.
 *
 * @returns IPRT status code.
 * @param   pSrc                The source address.
 * @param   cbSrc               The size of the source address.
 * @param   pAddr               Where to return the generic IPRT network
 *                              address.
 */
static int rtSocketNetAddrFromAddr(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
{
    /*
     * Convert the address.
     */
    if (   cbSrc == sizeof(struct sockaddr_in)
        && pSrc->Addr.sa_family == AF_INET)
    {
        RT_ZERO(*pAddr);
        pAddr->enmType      = RTNETADDRTYPE_IPV4;
        pAddr->uPort        = RT_N2H_U16(pSrc->IPv4.sin_port);
        pAddr->uAddr.IPv4.u = pSrc->IPv4.sin_addr.s_addr;
    }
#ifdef IPRT_WITH_TCPIP_V6
    else if (   cbSrc == sizeof(struct sockaddr_in6)
             && pSrc->Addr.sa_family == AF_INET6)
    {
        RT_ZERO(*pAddr);
        pAddr->enmType            = RTNETADDRTYPE_IPV6;
        pAddr->uPort              = RT_N2H_U16(pSrc->IPv6.sin6_port);
        pAddr->uAddr.IPv6.au32[0] = pSrc->IPv6.sin6_addr.s6_addr32[0];
        pAddr->uAddr.IPv6.au32[1] = pSrc->IPv6.sin6_addr.s6_addr32[1];
        pAddr->uAddr.IPv6.au32[2] = pSrc->IPv6.sin6_addr.s6_addr32[2];
        pAddr->uAddr.IPv6.au32[3] = pSrc->IPv6.sin6_addr.s6_addr32[3];
    }
#endif
    else
        return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
    return VINF_SUCCESS;
}


/**
 * Converts from a generic IPRT network address to a native socket address.
 *
 * @returns IPRT status code.
 * @param   pAddr               Pointer to the generic IPRT network address.
 * @param   pDst                The source address.
 * @param   cbDst               The size of the source address.
 * @param   pcbAddr             Where to store the size of the returned address.
 *                              Optional
 */
static int rtSocketAddrFromNetAddr(PCRTNETADDR pAddr, RTSOCKADDRUNION *pDst, size_t cbDst, int *pcbAddr)
{
    RT_BZERO(pDst, cbDst);
    if (pAddr->enmType == RTNETADDRTYPE_IPV4)
    {
        if (cbDst < sizeof(struct sockaddr_in))
            return VERR_BUFFER_OVERFLOW;

        pDst->Addr.sa_family       = AF_INET;
        pDst->IPv4.sin_port        = RT_H2N_U16(pAddr->uPort);
        pDst->IPv4.sin_addr.s_addr = pAddr->uAddr.IPv4.u;
        if (pcbAddr)
            *pcbAddr = sizeof(pDst->IPv4);
    }
#ifdef IPRT_WITH_TCPIP_V6
    else if (pAddr->enmType == RTNETADDRTYPE_IPV6)
    {
        if (cbDst < sizeof(struct sockaddr_in6))
            return VERR_BUFFER_OVERFLOW;

        pDst->Addr.sa_family              = AF_INET6;
        pDst->IPv6.sin6_port              = RT_H2N_U16(pAddr->uPort);
        pSrc->IPv6.sin6_addr.s6_addr32[0] = pAddr->uAddr.IPv6.au32[0];
        pSrc->IPv6.sin6_addr.s6_addr32[1] = pAddr->uAddr.IPv6.au32[1];
        pSrc->IPv6.sin6_addr.s6_addr32[2] = pAddr->uAddr.IPv6.au32[2];
        pSrc->IPv6.sin6_addr.s6_addr32[3] = pAddr->uAddr.IPv6.au32[3];
        if (pcbAddr)
            *pcbAddr = sizeof(pDst->IPv6);
    }
#endif
    else
        return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
    return VINF_SUCCESS;
}


/**
 * Tries to lock the socket for exclusive usage by the calling thread.
 *
 * Call rtSocketUnlock() to unlock.
 *
 * @returns @c true if locked, @c false if not.
 * @param   pThis               The socket structure.
 */
DECLINLINE(bool) rtSocketTryLock(RTSOCKETINT *pThis)
{
    return ASMAtomicCmpXchgU32(&pThis->cUsers, 1, 0);
}


/**
 * Unlocks the socket.
 *
 * @param   pThis               The socket structure.
 */
DECLINLINE(void) rtSocketUnlock(RTSOCKETINT *pThis)
{
    ASMAtomicCmpXchgU32(&pThis->cUsers, 0, 1);
}


/**
 * The slow path of rtSocketSwitchBlockingMode that does the actual switching.
 *
 * @returns IPRT status code.
 * @param   pThis               The socket structure.
 * @param   fBlocking           The desired mode of operation.
 * @remarks Do not call directly.
 */
static int rtSocketSwitchBlockingModeSlow(RTSOCKETINT *pThis, bool fBlocking)
{
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnioctlsocket, VERR_NET_NOT_UNSUPPORTED);
    u_long uBlocking = fBlocking ? 0 : 1;
    if (g_pfnioctlsocket(pThis->hNative, FIONBIO, &uBlocking))
        return rtSocketError();

#else
    int fFlags = fcntl(pThis->hNative, F_GETFL, 0);
    if (fFlags == -1)
        return rtSocketError();

    if (fBlocking)
        fFlags &= ~O_NONBLOCK;
    else
        fFlags |= O_NONBLOCK;
    if (fcntl(pThis->hNative, F_SETFL, fFlags) == -1)
       return rtSocketError();
#endif

    pThis->fBlocking = fBlocking;
    return VINF_SUCCESS;
}


/**
 * Switches the socket to the desired blocking mode if necessary.
 *
 * The socket must be locked.
 *
 * @returns IPRT status code.
 * @param   pThis               The socket structure.
 * @param   fBlocking           The desired mode of operation.
 */
DECLINLINE(int) rtSocketSwitchBlockingMode(RTSOCKETINT *pThis, bool fBlocking)
{
    if (pThis->fBlocking != fBlocking)
        return rtSocketSwitchBlockingModeSlow(pThis, fBlocking);
    return VINF_SUCCESS;
}


/**
 * Creates an IPRT socket handle for a native one.
 *
 * @returns IPRT status code.
 * @param   ppSocket        Where to return the IPRT socket handle.
 * @param   hNative         The native handle.
 * @param   fLeaveOpen      Whether to leave the native socket handle open when
 *                          closed.
 */
DECLHIDDEN(int) rtSocketCreateForNative(RTSOCKETINT **ppSocket, RTSOCKETNATIVE hNative, bool fLeaveOpen)
{
    RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pThis));
    if (!pThis)
        return VERR_NO_MEMORY;
    pThis->u32Magic         = RTSOCKET_MAGIC;
    pThis->cUsers           = 0;
    pThis->hNative          = hNative;
    pThis->fClosed          = false;
    pThis->fLeaveOpen       = fLeaveOpen;
    pThis->fBlocking        = true;
#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
    pThis->hPollSet         = NIL_RTPOLLSET;
#endif
#ifdef RT_OS_WINDOWS
    pThis->hEvent                   = WSA_INVALID_EVENT;
    pThis->fPollEvts                = 0;
    pThis->fSubscribedEvts          = 0;
    pThis->fEventsSaved             = 0;
    pThis->fHarvestedEvents         = false;
    pThis->fPollFallback            = g_uWinSockInitedVersion < MAKEWORD(2, 0)
                                   || g_pfnWSACreateEvent == NULL
                                   || g_pfnWSACloseEvent == NULL
                                   || g_pfnWSAEventSelect == NULL
                                   || g_pfnWSAEnumNetworkEvents == NULL;
    pThis->fPollFallbackActive      = false;
    pThis->fPollFallbackShutdown    = false;
    pThis->hPollFallbackNotifyR     = NIL_RTSOCKETNATIVE;
    pThis->hPollFallbackNotifyW     = NIL_RTSOCKETNATIVE;
    pThis->hPollFallbackThread      = NIL_RTTHREAD;
#endif
    *ppSocket = pThis;
    return VINF_SUCCESS;
}


RTDECL(int) RTSocketFromNative(PRTSOCKET phSocket, RTHCINTPTR uNative)
{
    AssertReturn(uNative != NIL_RTSOCKETNATIVE, VERR_INVALID_PARAMETER);
#ifndef RT_OS_WINDOWS
    AssertReturn(uNative >= 0, VERR_INVALID_PARAMETER);
#endif
    AssertPtrReturn(phSocket, VERR_INVALID_POINTER);
    return rtSocketCreateForNative(phSocket, uNative, false /*fLeaveOpen*/);
}


/**
 * Wrapper around socket().
 *
 * @returns IPRT status code.
 * @param   phSocket            Where to store the handle to the socket on
 *                              success.
 * @param   iDomain             The protocol family (PF_XXX).
 * @param   iType               The socket type (SOCK_XXX).
 * @param   iProtocol           Socket parameter, usually 0.
 * @param   fInheritable        Set to true if the socket should be inherted by
 *                              child processes, false if not inheritable.
 */
DECLHIDDEN(int) rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol, bool fInheritable)
{
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnsocket, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfnclosesocket, VERR_NET_NOT_UNSUPPORTED);

    /* Initialize WinSock. */
    int rc2 = rtSocketInitWinsock();
    if (RT_FAILURE(rc2))
        return rc2;
#endif

    /*
     * Create the socket.
     *
     * The RTSocketSetInheritance operation isn't necessarily reliable on windows,
     * so try use WSA_FLAG_NO_HANDLE_INHERIT with WSASocketW when possible.
     */
#ifdef RT_OS_WINDOWS
    bool           fCallSetInheritance = true;
    RTSOCKETNATIVE hNative;
    if (g_pfnWSASocketW)
    {
        DWORD fWsaFlags = WSA_FLAG_OVERLAPPED | (!fInheritable ? WSA_FLAG_NO_HANDLE_INHERIT : 0);
        hNative = g_pfnWSASocketW(iDomain, iType, iProtocol, NULL, 0 /*Group*/, fWsaFlags);
        if (hNative != NIL_RTSOCKETNATIVE)
            fCallSetInheritance = false;
        else
        {
            if (!fInheritable)
                hNative = g_pfnsocket(iDomain, iType, iProtocol);
            if (hNative == NIL_RTSOCKETNATIVE)
                return rtSocketError();
        }
    }
    else
    {
        hNative = g_pfnsocket(iDomain, iType, iProtocol);
        if (hNative == NIL_RTSOCKETNATIVE)
            return rtSocketError();
    }
#else
    RTSOCKETNATIVE hNative = socket(iDomain, iType, iProtocol);
    if (hNative == NIL_RTSOCKETNATIVE)
        return rtSocketError();
#endif

    /*
     * Wrap it.
     */
    int rc = rtSocketCreateForNative(phSocket, hNative, false /*fLeaveOpen*/);
    if (RT_SUCCESS(rc))
    {
#ifdef RT_OS_WINDOWS
        if (fCallSetInheritance)
#endif
            RTSocketSetInheritance(*phSocket, fInheritable);
    }
    else
    {
#ifdef RT_OS_WINDOWS
        g_pfnclosesocket(hNative);
#else
        close(hNative);
#endif
    }
    return rc;
}


/**
 * Wrapper around socketpair() for creating a local TCP connection.
 *
 * @returns IPRT status code.
 * @param   phServer            Where to return the first native socket.
 * @param   phClient            Where to return the second native socket.
 */
static int rtSocketCreateNativeTcpPair(RTSOCKETNATIVE *phServer, RTSOCKETNATIVE *phClient)
{
#ifdef RT_OS_WINDOWS
    /*
     * Initialize WinSock and make sure we got the necessary APIs.
     */
    int rc = rtSocketInitWinsock();
    if (RT_FAILURE(rc))
        return rc;
    AssertReturn(g_pfnsocket, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfnclosesocket, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfnsetsockopt, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfnbind, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfngetsockname, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfnlisten, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfnaccept, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfnconnect, VERR_NET_NOT_UNSUPPORTED);

    /*
     * Create the "server" listen socket and the "client" socket.
     */
    RTSOCKETNATIVE hListener = g_pfnsocket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (hListener == NIL_RTSOCKETNATIVE)
        return rtSocketError();
    RTSOCKETNATIVE hClient = g_pfnsocket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (hClient != NIL_RTSOCKETNATIVE)
    {

        /*
         * We let WinSock choose a port number when we bind.
         */
        union
        {
            struct sockaddr_in  Ip;
            struct sockaddr     Generic;
        } uAddr;
        RT_ZERO(uAddr);
        uAddr.Ip.sin_family      = AF_INET;
        uAddr.Ip.sin_addr.s_addr = RT_H2N_U32_C(INADDR_LOOPBACK);
        //uAddr.Ip.sin_port      = 0;
        int fReuse = 1;
        rc = g_pfnsetsockopt(hListener, SOL_SOCKET, SO_REUSEADDR, (const char *)&fReuse, sizeof(fReuse));
        if (rc == 0)
        {
            rc = g_pfnbind(hListener, &uAddr.Generic, sizeof(uAddr.Ip));
            if (rc == 0)
            {
                /*
                 * Get the address the client should connect to.  According to the docs,
                 * we cannot assume that getsockname sets the IP and family.
                 */
                RT_ZERO(uAddr);
                int cbAddr = sizeof(uAddr.Ip);
                rc = g_pfngetsockname(hListener, &uAddr.Generic, &cbAddr);
                if (rc == 0)
                {
                    uAddr.Ip.sin_family      = AF_INET;
                    uAddr.Ip.sin_addr.s_addr = RT_H2N_U32_C(INADDR_LOOPBACK);

                    /*
                     * Listen, connect and accept.
                     */
                    rc = g_pfnlisten(hListener, 1 /*cBacklog*/);
                    if (rc == 0)
                    {
                        rc = g_pfnconnect(hClient, &uAddr.Generic, sizeof(uAddr.Ip));
                        if (rc == 0)
                        {
                            RTSOCKETNATIVE hServer = g_pfnaccept(hListener, NULL, NULL);
                            if (hServer != NIL_RTSOCKETNATIVE)
                            {
                                g_pfnclosesocket(hListener);

                                /*
                                 * Done!
                                 */
                                *phServer = hServer;
                                *phClient = hClient;
                                return VINF_SUCCESS;
                            }
                        }
                    }
                }
            }
        }
        rc = rtSocketError();
        g_pfnclosesocket(hClient);
    }
    else
        rc = rtSocketError();
    g_pfnclosesocket(hListener);
    return rc;

#else
    /*
     * Got socket pair, so use it.
     * Note! This isn't TCP per se, but it should fool the users.
     */
    int aSockets[2] = { -1, -1 };
    if (socketpair(AF_LOCAL, SOCK_STREAM, 0, aSockets) == 0)
    {
        *phServer = aSockets[0];
        *phClient = aSockets[1];
        return VINF_SUCCESS;
    }
    return rtSocketError();
#endif
}


/**
 * Worker for RTTcpCreatePair.
 *
 * @returns IPRT status code.
 * @param   phServer            Where to return the "server" side of the pair.
 * @param   phClient            Where to return the "client" side of the pair.
 * @note    There is no server or client side, but we gotta call it something.
 */
DECLHIDDEN(int) rtSocketCreateTcpPair(RTSOCKET *phServer, RTSOCKET *phClient)
{
    RTSOCKETNATIVE hServer = NIL_RTSOCKETNATIVE;
    RTSOCKETNATIVE hClient = NIL_RTSOCKETNATIVE;
    int rc = rtSocketCreateNativeTcpPair(&hServer, &hClient);
    if (RT_SUCCESS(rc))
    {
        rc = rtSocketCreateForNative(phServer, hServer, false /*fLeaveOpen*/);
        if (RT_SUCCESS(rc))
        {
            rc = rtSocketCreateForNative(phClient, hClient, false /*fLeaveOpen*/);
            if (RT_SUCCESS(rc))
                return VINF_SUCCESS;
            RTSocketRelease(*phServer);
        }
        else
        {
#ifdef RT_OS_WINDOWS
            g_pfnclosesocket(hServer);
#else
            close(hServer);
#endif
        }
#ifdef RT_OS_WINDOWS
        g_pfnclosesocket(hClient);
#else
        close(hClient);
#endif
    }

    *phServer = NIL_RTSOCKET;
    *phClient = NIL_RTSOCKET;
    return rc;
}


RTDECL(uint32_t) RTSocketRetain(RTSOCKET hSocket)
{
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, UINT32_MAX);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
    return RTMemPoolRetain(pThis);
}


/**
 * Worker for RTSocketRelease and RTSocketClose.
 *
 * @returns IPRT status code.
 * @param   pThis               The socket handle instance data.
 * @param   fDestroy            Whether we're reaching ref count zero.
 */
static int rtSocketCloseIt(RTSOCKETINT *pThis, bool fDestroy)
{
    /*
     * Invalidate the handle structure on destroy.
     */
    if (fDestroy)
    {
        Assert(ASMAtomicReadU32(&pThis->u32Magic) == RTSOCKET_MAGIC);
        ASMAtomicWriteU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD);
    }

    int rc = VINF_SUCCESS;
    if (ASMAtomicCmpXchgBool(&pThis->fClosed, true, false))
    {
#ifdef RT_OS_WINDOWS
        /*
         * Poke the polling thread if active and give it a small chance to stop.
         */
        if (   pThis->fPollFallback
            && pThis->hPollFallbackThread != NIL_RTTHREAD)
        {
            ASMAtomicWriteBool(&pThis->fPollFallbackShutdown, true);
            rtSocketPokePollFallbackThread(pThis);
            int rc2 = RTThreadWait(pThis->hPollFallbackThread, RT_MS_1SEC, NULL);
            if (RT_SUCCESS(rc2))
                pThis->hPollFallbackThread = NIL_RTTHREAD;
        }
#endif

        /*
         * Close the native handle.
         */
        RTSOCKETNATIVE hNative = pThis->hNative;
        if (hNative != NIL_RTSOCKETNATIVE)
        {
            pThis->hNative = NIL_RTSOCKETNATIVE;

            if (!pThis->fLeaveOpen)
            {
#ifdef RT_OS_WINDOWS
                AssertReturn(g_pfnclosesocket, VERR_NET_NOT_UNSUPPORTED);
                if (g_pfnclosesocket(hNative))
#else
                if (close(hNative))
#endif
                {
                    rc = rtSocketError();
#ifdef RT_OS_WINDOWS
                    AssertMsgFailed(("closesocket(%p) -> %Rrc\n", (uintptr_t)hNative, rc));
#else
                    AssertMsgFailed(("close(%d) -> %Rrc\n", hNative, rc));
#endif
                }
            }
        }

#ifdef RT_OS_WINDOWS
        /*
         * Windows specific polling cleanup.
         */
        WSAEVENT hEvent = pThis->hEvent;
        if (hEvent != WSA_INVALID_EVENT)
        {
            pThis->hEvent = WSA_INVALID_EVENT;
            if (!pThis->fPollFallback)
            {
                Assert(g_pfnWSACloseEvent);
                if (g_pfnWSACloseEvent)
                    g_pfnWSACloseEvent(hEvent);
            }
            else
                CloseHandle(hEvent);
        }

        if (pThis->fPollFallback)
        {
            if (pThis->hPollFallbackNotifyW != NIL_RTSOCKETNATIVE)
            {
                g_pfnclosesocket(pThis->hPollFallbackNotifyW);
                pThis->hPollFallbackNotifyW = NIL_RTSOCKETNATIVE;
            }

            if (pThis->hPollFallbackThread != NIL_RTTHREAD)
            {
                int rc2 = RTThreadWait(pThis->hPollFallbackThread, RT_MS_1MIN / 2, NULL);
                AssertRC(rc2);
                pThis->hPollFallbackThread = NIL_RTTHREAD;
            }

            if (pThis->hPollFallbackNotifyR != NIL_RTSOCKETNATIVE)
            {
                g_pfnclosesocket(pThis->hPollFallbackNotifyR);
                pThis->hPollFallbackNotifyR = NIL_RTSOCKETNATIVE;
            }
        }
#endif
    }

    return rc;
}


RTDECL(uint32_t) RTSocketRelease(RTSOCKET hSocket)
{
    RTSOCKETINT *pThis = hSocket;
    if (pThis == NIL_RTSOCKET)
        return 0;
    AssertPtrReturn(pThis, UINT32_MAX);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);

    /* get the refcount without killing it... */
    uint32_t cRefs = RTMemPoolRefCount(pThis);
    AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
    if (cRefs == 1)
        rtSocketCloseIt(pThis, true);

    return RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
}


RTDECL(int) RTSocketClose(RTSOCKET hSocket)
{
    RTSOCKETINT *pThis = hSocket;
    if (pThis == NIL_RTSOCKET)
        return VINF_SUCCESS;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);

    uint32_t cRefs = RTMemPoolRefCount(pThis);
    AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);

    int rc = rtSocketCloseIt(pThis, cRefs == 1);

    RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
    return rc;
}


RTDECL(RTHCUINTPTR) RTSocketToNative(RTSOCKET hSocket)
{
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
    return (RTHCUINTPTR)pThis->hNative;
}


RTDECL(int) RTSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
{
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);

#ifndef RT_OS_WINDOWS
    if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
        return RTErrConvertFromErrno(errno);
    return VINF_SUCCESS;
#else
    /* Windows is more complicated as sockets are complicated wrt inheritance
       (see stackoverflow for details).  In general, though we cannot hope to
       make a socket really non-inheritable before vista as other layers in
       the winsock maze may have additional handles associated with the socket. */
    if (g_pfnGetHandleInformation)
    {
        /* Check if the handle is already in what seems to be the right state
           before we try doing anything. */
        DWORD fFlags;
        if (g_pfnGetHandleInformation((HANDLE)pThis->hNative, &fFlags))
        {
            if (RT_BOOL(fFlags & HANDLE_FLAG_INHERIT) == fInheritable)
                return VINF_SUCCESS;
        }
    }

    if (!g_pfnSetHandleInformation)
        return VERR_NET_NOT_UNSUPPORTED;

    if (!g_pfnSetHandleInformation((HANDLE)pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
        return RTErrConvertFromWin32(GetLastError());
    /** @todo Need we do something related to WS_SIO_ASSOCIATE_HANDLE or
     *        WS_SIO_TRANSLATE_HANDLE? Or what  other handles could be associated
     *        with the socket? that we need to modify? */

    return VINF_SUCCESS;
#endif
}


static bool rtSocketIsIPv4Numerical(const char *pszAddress, PRTNETADDRIPV4 pAddr)
{

    /* Empty address resolves to the INADDR_ANY address (good for bind). */
    if (!pszAddress || !*pszAddress)
    {
        pAddr->u = INADDR_ANY;
        return true;
    }

    /* Four quads? */
    char *psz = (char *)pszAddress;
    for (int i = 0; i < 4; i++)
    {
        uint8_t u8;
        int rc = RTStrToUInt8Ex(psz, &psz, 0, &u8);
        if (rc != VINF_SUCCESS && rc != VWRN_TRAILING_CHARS)
            return false;
        if (*psz != (i < 3 ? '.' : '\0'))
            return false;
        psz++;

        pAddr->au8[i] = u8;             /* big endian */
    }

    return true;
}

RTDECL(int) RTSocketParseInetAddress(const char *pszAddress, unsigned uPort, PRTNETADDR pAddr)
{
    int rc;

    /*
     * Validate input.
     */
    AssertReturn(uPort > 0, VERR_INVALID_PARAMETER);
    AssertPtrNullReturn(pszAddress, VERR_INVALID_POINTER);

    /*
     * Resolve the address. Pretty crude at the moment, but we have to make
     * sure to not ask the NT 4 gethostbyname about an IPv4 address as it may
     * give a wrong answer.
     */
    /** @todo this only supports IPv4, and IPv6 support needs to be added.
     * It probably needs to be converted to getaddrinfo(). */
    RTNETADDRIPV4 IPv4Quad;
    if (rtSocketIsIPv4Numerical(pszAddress, &IPv4Quad))
    {
        Log3(("rtSocketIsIPv4Numerical: %s -> %#x (%RTnaipv4)\n", pszAddress, IPv4Quad.u, IPv4Quad));
        RT_ZERO(*pAddr);
        pAddr->enmType      = RTNETADDRTYPE_IPV4;
        pAddr->uPort        = uPort;
        pAddr->uAddr.IPv4   = IPv4Quad;
        return VINF_SUCCESS;
    }

#ifdef RT_OS_WINDOWS
    /* Initialize WinSock and check version before we call gethostbyname. */
    if (!g_pfngethostbyname)
        return VERR_NET_NOT_UNSUPPORTED;

    int rc2 = rtSocketInitWinsock();
    if (RT_FAILURE(rc2))
        return rc2;

# define gethostbyname g_pfngethostbyname
#endif

    struct hostent *pHostEnt;
    pHostEnt = gethostbyname(pszAddress);
    if (!pHostEnt)
    {
        rc = rtSocketResolverError();
        AssertMsg(rc == VERR_NET_HOST_NOT_FOUND,
                  ("Could not resolve '%s', rc=%Rrc\n", pszAddress, rc));
        return rc;
    }

    if (pHostEnt->h_addrtype == AF_INET)
    {
        RT_ZERO(*pAddr);
        pAddr->enmType      = RTNETADDRTYPE_IPV4;
        pAddr->uPort        = uPort;
        pAddr->uAddr.IPv4.u = ((struct in_addr *)pHostEnt->h_addr)->s_addr;
        Log3(("gethostbyname: %s -> %#x (%RTnaipv4)\n", pszAddress, pAddr->uAddr.IPv4.u, pAddr->uAddr.IPv4));
    }
    else
        return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;

#ifdef RT_OS_WINDOWS
# undef gethostbyname
#endif
    return VINF_SUCCESS;
}


/*
 * New function to allow both ipv4 and ipv6 addresses to be resolved.
 * Breaks compatibility with windows before 2000.
 */
RTDECL(int) RTSocketQueryAddressStr(const char *pszHost, char *pszResult, size_t *pcbResult, PRTNETADDRTYPE penmAddrType)
{
    AssertPtrReturn(pszHost, VERR_INVALID_POINTER);
    AssertPtrReturn(pcbResult, VERR_INVALID_POINTER);
    AssertPtrNullReturn(penmAddrType, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pszResult, VERR_INVALID_POINTER);

#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) /** @todo dynamically resolve the APIs not present in NT4! */
    return VERR_NOT_SUPPORTED;

#else
    int rc;
    if (*pcbResult < 16)
        return VERR_NET_ADDRESS_NOT_AVAILABLE;

    /* Setup the hint. */
    struct addrinfo grHints;
    RT_ZERO(grHints);
    grHints.ai_socktype = 0;
    grHints.ai_flags    = 0;
    grHints.ai_protocol = 0;
    grHints.ai_family   = AF_UNSPEC;
    if (penmAddrType)
    {
        switch (*penmAddrType)
        {
            case RTNETADDRTYPE_INVALID:
                /*grHints.ai_family = AF_UNSPEC;*/
                break;
            case RTNETADDRTYPE_IPV4:
                grHints.ai_family = AF_INET;
                break;
            case RTNETADDRTYPE_IPV6:
                grHints.ai_family = AF_INET6;
                break;
            default:
                AssertFailedReturn(VERR_INVALID_PARAMETER);
        }
    }

# ifdef RT_OS_WINDOWS
    /*
     * Winsock2 init
     */
    if (   !g_pfngetaddrinfo
        || !g_pfnfreeaddrinfo)
        return VERR_NET_NOT_UNSUPPORTED;

    int rc2 = rtSocketInitWinsock();
    if (RT_FAILURE(rc2))
        return rc2;

#  define getaddrinfo  g_pfngetaddrinfo
#  define freeaddrinfo g_pfnfreeaddrinfo
# endif

    /** @todo r=bird: getaddrinfo and freeaddrinfo breaks the additions on NT4. */
    struct addrinfo *pgrResults = NULL;
    rc = getaddrinfo(pszHost, "", &grHints, &pgrResults);
    if (rc != 0)
        return VERR_NET_ADDRESS_NOT_AVAILABLE;

    // return data
    // on multiple matches return only the first one

    if (!pgrResults)
        return VERR_NET_ADDRESS_NOT_AVAILABLE;

    struct addrinfo const *pgrResult = pgrResults->ai_next;
    if (!pgrResult)
    {
        freeaddrinfo(pgrResults);
        return VERR_NET_ADDRESS_NOT_AVAILABLE;
    }

    RTNETADDRTYPE   enmAddrType = RTNETADDRTYPE_INVALID;
    size_t          cchIpAddress;
    char            szIpAddress[48];
    if (pgrResult->ai_family == AF_INET)
    {
        struct sockaddr_in const *pgrSa = (struct sockaddr_in const *)pgrResult->ai_addr;
        cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress),
                                   "%RTnaipv4", pgrSa->sin_addr.s_addr);
        Assert(cchIpAddress >= 7 && cchIpAddress < sizeof(szIpAddress) - 1);
        enmAddrType = RTNETADDRTYPE_IPV4;
        rc = VINF_SUCCESS;
    }
    else if (pgrResult->ai_family == AF_INET6)
    {
        struct sockaddr_in6 const *pgrSa6 = (struct sockaddr_in6 const *)pgrResult->ai_addr;
        cchIpAddress = RTStrPrintf(szIpAddress, sizeof(szIpAddress),
                                   "%RTnaipv6", (PRTNETADDRIPV6)&pgrSa6->sin6_addr);
        enmAddrType = RTNETADDRTYPE_IPV6;
        rc = VINF_SUCCESS;
    }
    else
    {
        rc = VERR_NET_ADDRESS_NOT_AVAILABLE;
        szIpAddress[0] = '\0';
        cchIpAddress = 0;
    }
    freeaddrinfo(pgrResults);

    /*
     * Copy out the result.
     */
    size_t const cbResult = *pcbResult;
    *pcbResult = cchIpAddress + 1;
    if (cchIpAddress < cbResult)
        memcpy(pszResult, szIpAddress, cchIpAddress + 1);
    else
    {
        RT_BZERO(pszResult, cbResult);
        if (RT_SUCCESS(rc))
            rc = VERR_BUFFER_OVERFLOW;
    }
    if (penmAddrType && RT_SUCCESS(rc))
        *penmAddrType = enmAddrType;
    return rc;

# ifdef RT_OS_WINDOWS
#  undef getaddrinfo
#  undef freeaddrinfo
# endif
#endif /* !RT_OS_OS2 */
}


RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
    AssertPtr(pvBuffer);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnrecv, VERR_NET_NOT_UNSUPPORTED);
# define recv g_pfnrecv
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * Read loop.
     * If pcbRead is NULL we have to fill the entire buffer!
     */
    size_t  cbRead   = 0;
    size_t  cbToRead = cbBuffer;
    for (;;)
    {
        rtSocketErrorReset();
#ifdef RTSOCKET_MAX_READ
        int    cbNow = cbToRead >= RTSOCKET_MAX_READ ? RTSOCKET_MAX_READ : (int)cbToRead;
#else
        size_t cbNow = cbToRead;
#endif
        ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
        if (cbBytesRead <= 0)
        {
            rc = rtSocketError();
            Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
            if (RT_SUCCESS_NP(rc))
            {
                if (!pcbRead)
                    rc = VERR_NET_SHUTDOWN;
                else
                {
                    *pcbRead = 0;
                    rc = VINF_SUCCESS;
                }
            }
            break;
        }
        if (pcbRead)
        {
            /* return partial data */
            *pcbRead = cbBytesRead;
            break;
        }

        /* read more? */
        cbRead += cbBytesRead;
        if (cbRead == cbBuffer)
            break;

        /* next */
        cbToRead = cbBuffer - cbRead;
    }

    rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef recv
#endif
    return rc;
}


RTDECL(int) RTSocketReadFrom(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead, PRTNETADDR pSrcAddr)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
    AssertPtr(pvBuffer);
    AssertPtr(pcbRead);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnrecvfrom, VERR_NET_NOT_UNSUPPORTED);
# define recvfrom g_pfnrecvfrom
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * Read data.
     */
    size_t  cbRead   = 0;
    size_t  cbToRead = cbBuffer;
    rtSocketErrorReset();
    RTSOCKADDRUNION u;
#ifdef RTSOCKET_MAX_READ
    int       cbNow  = cbToRead >= RTSOCKET_MAX_READ ? RTSOCKET_MAX_READ : (int)cbToRead;
    int       cbAddr = sizeof(u);
#else
    size_t    cbNow  = cbToRead;
    socklen_t cbAddr = sizeof(u);
#endif
    ssize_t cbBytesRead = recvfrom(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL, &u.Addr, &cbAddr);
    if (cbBytesRead <= 0)
    {
        rc = rtSocketError();
        Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
        if (RT_SUCCESS_NP(rc))
        {
            *pcbRead = 0;
            rc = VINF_SUCCESS;
        }
    }
    else
    {
        if (pSrcAddr)
            rc = rtSocketNetAddrFromAddr(&u, cbAddr, pSrcAddr);
        *pcbRead = cbBytesRead;
    }

    rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef recvfrom
#endif
    return rc;
}


RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnsend, VERR_NET_NOT_UNSUPPORTED);
# define send g_pfnsend
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * Try write all at once.
     */
#ifdef RTSOCKET_MAX_WRITE
    int     cbNow     = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
#else
    size_t  cbNow     = cbBuffer >= SSIZE_MAX   ? SSIZE_MAX   :      cbBuffer;
#endif
    ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
    if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
        rc = VINF_SUCCESS;
    else if (cbWritten < 0)
        rc = rtSocketError();
    else
    {
        /*
         * Unfinished business, write the remainder of the request.  Must ignore
         * VERR_INTERRUPTED here if we've managed to send something.
         */
        size_t cbSentSoFar = 0;
        for (;;)
        {
            /* advance */
            cbBuffer    -= (size_t)cbWritten;
            if (!cbBuffer)
                break;
            cbSentSoFar += (size_t)cbWritten;
            pvBuffer     = (char const *)pvBuffer + cbWritten;

            /* send */
#ifdef RTSOCKET_MAX_WRITE
            cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
#else
            cbNow = cbBuffer >= SSIZE_MAX   ? SSIZE_MAX   :      cbBuffer;
#endif
            cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
            if (cbWritten >= 0)
                AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
                                                          cbWritten, cbBuffer, rtSocketError()));
            else
            {
                rc = rtSocketError();
                if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
                    break;
                cbWritten = 0;
                rc = VINF_SUCCESS;
            }
        }
    }

    rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef send
#endif
    return rc;
}


RTDECL(int) RTSocketWriteTo(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnsendto, VERR_NET_NOT_UNSUPPORTED);
# define sendto g_pfnsendto
#endif

    /* no locking since UDP reads may be done concurrently to writes, and
     * this is the normal use case of this code. */

    int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
    if (RT_FAILURE(rc))
        return rc;

    /* Figure out destination address. */
    struct sockaddr *pSA = NULL;
#ifdef RT_OS_WINDOWS
    int cbSA = 0;
#else
    socklen_t cbSA = 0;
#endif
    RTSOCKADDRUNION u;
    if (pAddr)
    {
        rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
        if (RT_FAILURE(rc))
            return rc;
        pSA = &u.Addr;
        cbSA = sizeof(u);
    }

    /*
     * Must write all at once, otherwise it is a failure.
     */
#ifdef RT_OS_WINDOWS
    int     cbNow     = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
#else
    size_t  cbNow     = cbBuffer >= SSIZE_MAX   ? SSIZE_MAX   :      cbBuffer;
#endif
    ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
    if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
        rc = VINF_SUCCESS;
    else if (cbWritten < 0)
        rc = rtSocketError();
    else
        rc = VERR_TOO_MUCH_DATA;

    /// @todo rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef sendto
#endif
    return rc;
}


RTDECL(int) RTSocketWriteToNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, PCRTNETADDR pAddr)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnsendto, VERR_NET_NOT_UNSUPPORTED);
# define sendto g_pfnsendto
#endif

    /* no locking since UDP reads may be done concurrently to writes, and
     * this is the normal use case of this code. */

    int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
    if (RT_FAILURE(rc))
        return rc;

    /* Figure out destination address. */
    struct sockaddr *pSA = NULL;
#ifdef RT_OS_WINDOWS
    int cbSA = 0;
#else
    socklen_t cbSA = 0;
#endif
    RTSOCKADDRUNION u;
    if (pAddr)
    {
        rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), NULL);
        if (RT_FAILURE(rc))
            return rc;
        pSA = &u.Addr;
        cbSA = sizeof(u);
    }

    /*
     * Must write all at once, otherwise it is a failure.
     */
#ifdef RT_OS_WINDOWS
    int     cbNow     = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
#else
    size_t  cbNow     = cbBuffer >= SSIZE_MAX   ? SSIZE_MAX   :      cbBuffer;
#endif
    ssize_t cbWritten = sendto(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL, pSA, cbSA);
    if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
        rc = VINF_SUCCESS;
    else if (cbWritten < 0)
        rc = rtSocketError();
    else
        rc = VERR_TOO_MUCH_DATA;

    /// @todo rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef sendto
#endif
    return rc;
}


RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
    AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc = rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * Construct message descriptor (translate pSgBuf) and send it.
     */
    rc = VERR_NO_TMP_MEMORY;
#ifdef RT_OS_WINDOWS
    if (g_pfnWSASend)
    {
        AssertCompileSize(WSABUF, sizeof(RTSGSEG));
        AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));

        LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(WSABUF));
        if (paMsg)
        {
            for (unsigned i = 0; i < pSgBuf->cSegs; i++)
            {
                paMsg[i].buf = (char *)pSgBuf->paSegs[i].pvSeg;
                paMsg[i].len = (u_long)pSgBuf->paSegs[i].cbSeg;
            }

            DWORD dwSent;
            int hrc = g_pfnWSASend(pThis->hNative, paMsg, pSgBuf->cSegs, &dwSent, MSG_NOSIGNAL, NULL, NULL);
            if (!hrc)
                rc = VINF_SUCCESS;
    /** @todo check for incomplete writes */
            else
                rc = rtSocketError();

            RTMemTmpFree(paMsg);
        }
    }
    else if (g_pfnsend)
    {
        rc = VINF_SUCCESS;
        for (uint32_t iSeg = 0; iSeg < pSgBuf->cSegs; iSeg++)
        {
            uint8_t const *pbSeg = (uint8_t const *)pSgBuf->paSegs[iSeg].pvSeg;
            size_t         cbSeg = pSgBuf->paSegs[iSeg].cbSeg;
            int            cbNow;
            ssize_t        cbWritten;
            for (;;)
            {
                cbNow = cbSeg >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbSeg;
                cbWritten = g_pfnsend(pThis->hNative, (const char *)pbSeg, cbNow, MSG_NOSIGNAL);
                if ((size_t)cbWritten >= cbSeg || cbWritten < 0)
                    break;
                pbSeg += cbWritten;
                cbSeg -= cbWritten;
            }
            if (cbWritten < 0)
            {
                rc = rtSocketError();
                break;
            }
        }
    }
    else
        rc = VERR_NET_NOT_UNSUPPORTED;

#else  /* !RT_OS_WINDOWS */
    AssertCompileSize(struct iovec, sizeof(RTSGSEG));
    AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
    AssertCompileMemberSize(struct iovec, iov_len,  RT_SIZEOFMEMB(RTSGSEG, cbSeg));

    struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSegs * sizeof(struct iovec));
    if (paMsg)
    {
        for (unsigned i = 0; i < pSgBuf->cSegs; i++)
        {
            paMsg[i].iov_base = pSgBuf->paSegs[i].pvSeg;
            paMsg[i].iov_len  = pSgBuf->paSegs[i].cbSeg;
        }

        struct msghdr msgHdr;
        RT_ZERO(msgHdr);
        msgHdr.msg_iov    = paMsg;
        msgHdr.msg_iovlen = pSgBuf->cSegs;
        ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
        if (RT_LIKELY(cbWritten >= 0))
            rc = VINF_SUCCESS;
/** @todo check for incomplete writes */
        else
            rc = rtSocketError();

        RTMemTmpFree(paMsg);
    }
#endif /* !RT_OS_WINDOWS */

    rtSocketUnlock(pThis);
    return rc;
}


RTDECL(int) RTSocketSgWriteL(RTSOCKET hSocket, size_t cSegs, ...)
{
    va_list va;
    va_start(va, cSegs);
    int rc = RTSocketSgWriteLV(hSocket, cSegs, va);
    va_end(va);
    return rc;
}


RTDECL(int) RTSocketSgWriteLV(RTSOCKET hSocket, size_t cSegs, va_list va)
{
    /*
     * Set up a S/G segment array + buffer on the stack and pass it
     * on to RTSocketSgWrite.
     */
    Assert(cSegs <= 16);
    PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
    AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
    for (size_t i = 0; i < cSegs; i++)
    {
        paSegs[i].pvSeg = va_arg(va, void *);
        paSegs[i].cbSeg = va_arg(va, size_t);
    }

    RTSGBUF SgBuf;
    RTSgBufInit(&SgBuf, paSegs, cSegs);
    return RTSocketSgWrite(hSocket, &SgBuf);
}


RTDECL(int) RTSocketReadNB(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
    AssertPtr(pvBuffer);
    AssertPtrReturn(pcbRead, VERR_INVALID_PARAMETER);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnrecv, VERR_NET_NOT_UNSUPPORTED);
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
    if (RT_FAILURE(rc))
        return rc;

    rtSocketErrorReset();
#ifdef RTSOCKET_MAX_READ
    int    cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
#else
    size_t cbNow = cbBuffer;
#endif

#ifdef RT_OS_WINDOWS
    int cbRead = g_pfnrecv(pThis->hNative, (char *)pvBuffer, cbNow, MSG_NOSIGNAL);
    if (cbRead >= 0)
    {
        *pcbRead = cbRead;
        rc = VINF_SUCCESS;
    }
    else
    {
        rc = rtSocketError();
        if (rc == VERR_TRY_AGAIN)
        {
            *pcbRead = 0;
            rc = VINF_TRY_AGAIN;
        }
    }

#else
    ssize_t cbRead = recv(pThis->hNative, pvBuffer, cbNow, MSG_NOSIGNAL);
    if (cbRead >= 0)
        *pcbRead = cbRead;
    else if (   errno == EAGAIN
# ifdef EWOULDBLOCK
#  if EWOULDBLOCK != EAGAIN
             || errno == EWOULDBLOCK
#  endif
# endif
             )
    {
        *pcbRead = 0;
        rc = VINF_TRY_AGAIN;
    }
    else
        rc = rtSocketError();
#endif

    rtSocketUnlock(pThis);
    return rc;
}


RTDECL(int) RTSocketWriteNB(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnsend, VERR_NET_NOT_UNSUPPORTED);
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
    if (RT_FAILURE(rc))
        return rc;

    rtSocketErrorReset();
#ifdef RT_OS_WINDOWS
# ifdef RTSOCKET_MAX_WRITE
    int    cbNow = cbBuffer >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbBuffer;
# else
    size_t cbNow = cbBuffer;
# endif
    int cbWritten = g_pfnsend(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
    if (cbWritten >= 0)
    {
        *pcbWritten = cbWritten;
        rc = VINF_SUCCESS;
    }
    else
    {
        rc = rtSocketError();
        if (rc == VERR_TRY_AGAIN)
        {
            *pcbWritten = 0;
            rc = VINF_TRY_AGAIN;
        }
    }
#else
    ssize_t cbWritten = send(pThis->hNative, pvBuffer, cbBuffer, MSG_NOSIGNAL);
    if (cbWritten >= 0)
        *pcbWritten = cbWritten;
    else if (   errno == EAGAIN
# ifdef EWOULDBLOCK
#  if EWOULDBLOCK != EAGAIN
             || errno == EWOULDBLOCK
#  endif
# endif
            )
    {
        *pcbWritten = 0;
        rc = VINF_TRY_AGAIN;
    }
    else
        rc = rtSocketError();
#endif

    rtSocketUnlock(pThis);
    return rc;
}


RTDECL(int) RTSocketSgWriteNB(RTSOCKET hSocket, PCRTSGBUF pSgBuf, size_t *pcbWritten)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
    AssertReturn(pSgBuf->cSegs > 0, VERR_INVALID_PARAMETER);
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
    if (RT_FAILURE(rc))
        return rc;

    unsigned cSegsToSend = 0;
    rc = VERR_NO_TMP_MEMORY;
#ifdef RT_OS_WINDOWS
    if (g_pfnWSASend)
    {
        LPWSABUF paMsg = NULL;
        RTSgBufMapToNative(paMsg, pSgBuf, WSABUF, buf, char *, len, u_long, cSegsToSend);
        if (paMsg)
        {
            DWORD dwSent = 0;
            int hrc = g_pfnWSASend(pThis->hNative, paMsg, cSegsToSend, &dwSent, MSG_NOSIGNAL, NULL, NULL);
            if (!hrc)
                rc = VINF_SUCCESS;
            else
                rc = rtSocketError();

            *pcbWritten = dwSent;

            RTMemTmpFree(paMsg);
        }
    }
    else if (g_pfnsend)
    {
        size_t cbWrittenTotal = 0;
        rc = VINF_SUCCESS;
        for (uint32_t iSeg = 0; iSeg < pSgBuf->cSegs; iSeg++)
        {
            uint8_t const *pbSeg = (uint8_t const *)pSgBuf->paSegs[iSeg].pvSeg;
            size_t         cbSeg = pSgBuf->paSegs[iSeg].cbSeg;
            int            cbNow;
            ssize_t        cbWritten;
            for (;;)
            {
                cbNow = cbSeg >= RTSOCKET_MAX_WRITE ? RTSOCKET_MAX_WRITE : (int)cbSeg;
                cbWritten = g_pfnsend(pThis->hNative, (const char *)pbSeg, cbNow, MSG_NOSIGNAL);
                if ((size_t)cbWritten >= cbSeg || cbWritten < 0)
                    break;
                cbWrittenTotal += cbWrittenTotal;
                pbSeg += cbWritten;
                cbSeg -= cbWritten;
            }
            if (cbWritten < 0)
            {
                rc = rtSocketError();
                break;
            }
            if (cbWritten != cbNow)
                break;
        }
        *pcbWritten = cbWrittenTotal;
    }
    else
        rc = VERR_NET_NOT_UNSUPPORTED;

#else  /* !RT_OS_WINDOWS */
    struct iovec *paMsg = NULL;

    RTSgBufMapToNative(paMsg, pSgBuf, struct iovec, iov_base, void *, iov_len, size_t, cSegsToSend);
    if (paMsg)
    {
        struct msghdr msgHdr;
        RT_ZERO(msgHdr);
        msgHdr.msg_iov    = paMsg;
        msgHdr.msg_iovlen = cSegsToSend;
        ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
        if (RT_LIKELY(cbWritten >= 0))
        {
            rc = VINF_SUCCESS;
            *pcbWritten = cbWritten;
        }
        else
            rc = rtSocketError();

        RTMemTmpFree(paMsg);
    }
#endif /* !RT_OS_WINDOWS */

    rtSocketUnlock(pThis);
    return rc;
}


RTDECL(int) RTSocketSgWriteLNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, ...)
{
    va_list va;
    va_start(va, pcbWritten);
    int rc = RTSocketSgWriteLVNB(hSocket, cSegs, pcbWritten, va);
    va_end(va);
    return rc;
}


RTDECL(int) RTSocketSgWriteLVNB(RTSOCKET hSocket, size_t cSegs, size_t *pcbWritten, va_list va)
{
    /*
     * Set up a S/G segment array + buffer on the stack and pass it
     * on to RTSocketSgWrite.
     */
    Assert(cSegs <= 16);
    PRTSGSEG paSegs = (PRTSGSEG)alloca(cSegs * sizeof(RTSGSEG));
    AssertReturn(paSegs, VERR_NO_TMP_MEMORY);
    for (size_t i = 0; i < cSegs; i++)
    {
        paSegs[i].pvSeg = va_arg(va, void *);
        paSegs[i].cbSeg = va_arg(va, size_t);
    }

    RTSGBUF SgBuf;
    RTSgBufInit(&SgBuf, paSegs, cSegs);
    return RTSocketSgWriteNB(hSocket, &SgBuf, pcbWritten);
}


RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
    int const fdMax = (int)pThis->hNative + 1;
    AssertReturn((RTSOCKETNATIVE)(fdMax - 1) == pThis->hNative, VERR_INTERNAL_ERROR_5);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnselect, VERR_NET_NOT_UNSUPPORTED);
# define select g_pfnselect
#endif

    /*
     * Set up the file descriptor sets and do the select.
     */
    fd_set fdsetR;
    FD_ZERO(&fdsetR);
    FD_SET(pThis->hNative, &fdsetR);

    fd_set fdsetE = fdsetR;

    int rc;
    if (cMillies == RT_INDEFINITE_WAIT)
        rc = select(fdMax, &fdsetR, NULL, &fdsetE, NULL);
    else
    {
        struct timeval timeout;
        timeout.tv_sec = cMillies / 1000;
        timeout.tv_usec = (cMillies % 1000) * 1000;
        rc = select(fdMax, &fdsetR, NULL, &fdsetE, &timeout);
    }
    if (rc > 0)
        rc = VINF_SUCCESS;
    else if (rc == 0)
        rc = VERR_TIMEOUT;
    else
        rc = rtSocketError();

#ifdef RT_OS_WINDOWS
# undef select
#endif
    return rc;
}


/**
 * Internal worker for RTSocketSelectOneEx and rtSocketPollCheck (fallback)
 *
 * @returns IPRT status code
 * @param   pThis               The socket (valid).
 * @param   fEvents             The events to select for.
 * @param   pfEvents            Where to return the events.
 * @param   cMillies            How long to select for, in milliseconds.
 */
static int rtSocketSelectOneEx(RTSOCKET pThis, uint32_t fEvents, uint32_t *pfEvents, RTMSINTERVAL cMillies)
{
    RTSOCKETNATIVE hNative = pThis->hNative;
    if (hNative == NIL_RTSOCKETNATIVE)
    {
        /* Socket is already closed? Possible we raced someone calling rtSocketCloseIt.
           Should we return a different status code? */
        *pfEvents = RTSOCKET_EVT_ERROR;
        return VINF_SUCCESS;
    }

    int const fdMax = (int)hNative + 1;
    AssertReturn((RTSOCKETNATIVE)(fdMax - 1) == hNative, VERR_INTERNAL_ERROR_5);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnselect, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfn__WSAFDIsSet, VERR_NET_NOT_UNSUPPORTED);
# define select         g_pfnselect
# define __WSAFDIsSet   g_pfn__WSAFDIsSet
#endif

    *pfEvents = 0;

    /*
     * Set up the file descriptor sets and do the select.
     */
    fd_set fdsetR;
    fd_set fdsetW;
    fd_set fdsetE;
    FD_ZERO(&fdsetR);
    FD_ZERO(&fdsetW);
    FD_ZERO(&fdsetE);

    if (fEvents & RTSOCKET_EVT_READ)
        FD_SET(hNative, &fdsetR);
    if (fEvents & RTSOCKET_EVT_WRITE)
        FD_SET(hNative, &fdsetW);
    if (fEvents & RTSOCKET_EVT_ERROR)
        FD_SET(hNative, &fdsetE);

    int rc;
    if (cMillies == RT_INDEFINITE_WAIT)
        rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, NULL);
    else
    {
        struct timeval timeout;
        timeout.tv_sec = cMillies / 1000;
        timeout.tv_usec = (cMillies % 1000) * 1000;
        rc = select(fdMax, &fdsetR, &fdsetW, &fdsetE, &timeout);
    }
    if (rc > 0)
    {
        if (pThis->hNative == hNative)
        {
            if (FD_ISSET(hNative, &fdsetR))
                *pfEvents |= RTSOCKET_EVT_READ;
            if (FD_ISSET(hNative, &fdsetW))
                *pfEvents |= RTSOCKET_EVT_WRITE;
            if (FD_ISSET(hNative, &fdsetE))
                *pfEvents |= RTSOCKET_EVT_ERROR;
            rc = VINF_SUCCESS;
        }
        else
        {
            /* Socket was closed while we waited (rtSocketCloseIt).  Different status code? */
            *pfEvents = RTSOCKET_EVT_ERROR;
            rc = VINF_SUCCESS;
        }
    }
    else if (rc == 0)
        rc = VERR_TIMEOUT;
    else
        rc = rtSocketError();

#ifdef RT_OS_WINDOWS
# undef select
# undef __WSAFDIsSet
#endif
    return rc;
}


RTDECL(int) RTSocketSelectOneEx(RTSOCKET hSocket, uint32_t fEvents, uint32_t *pfEvents, RTMSINTERVAL cMillies)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertPtrReturn(pfEvents, VERR_INVALID_PARAMETER);
    AssertReturn(!(fEvents & ~RTSOCKET_EVT_VALID_MASK), VERR_INVALID_PARAMETER);
    AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);

    return rtSocketSelectOneEx(pThis, fEvents, pfEvents, cMillies);
}


RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
{
    /*
     * Validate input, don't lock it because we might want to interrupt a call
     * active on a different thread.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
    AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnshutdown, VERR_NET_NOT_UNSUPPORTED);
# define shutdown g_pfnshutdown
#endif

    /*
     * Do the job.
     */
    int rc = VINF_SUCCESS;
    int fHow;
    if (fRead && fWrite)
        fHow = SHUT_RDWR;
    else if (fRead)
        fHow = SHUT_RD;
    else
        fHow = SHUT_WR;
    if (shutdown(pThis->hNative, fHow) == -1)
        rc = rtSocketError();

#ifdef RT_OS_WINDOWS
# undef shutdown
#endif
    return rc;
}


RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfngetsockname, VERR_NET_NOT_UNSUPPORTED);
# define getsockname g_pfngetsockname
#endif

    /*
     * Get the address and convert it.
     */
    int             rc;
    RTSOCKADDRUNION u;
#ifdef RT_OS_WINDOWS
    int             cbAddr = sizeof(u);
#else
    socklen_t       cbAddr = sizeof(u);
#endif
    RT_ZERO(u);
    if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
        rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
    else
        rc = rtSocketError();

#ifdef RT_OS_WINDOWS
# undef getsockname
#endif
    return rc;
}


RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfngetpeername, VERR_NET_NOT_UNSUPPORTED);
# define getpeername g_pfngetpeername
#endif

    /*
     * Get the address and convert it.
     */
    int             rc;
    RTSOCKADDRUNION u;
#ifdef RT_OS_WINDOWS
    int             cbAddr = sizeof(u);
#else
    socklen_t       cbAddr = sizeof(u);
#endif
    RT_ZERO(u);
    if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
        rc = rtSocketNetAddrFromAddr(&u, cbAddr, pAddr);
    else
        rc = rtSocketError();

#ifdef RT_OS_WINDOWS
# undef getpeername
#endif
    return rc;
}



/**
 * Wrapper around bind.
 *
 * @returns IPRT status code.
 * @param   hSocket             The socket handle.
 * @param   pAddr               The address to bind to.
 */
DECLHIDDEN(int) rtSocketBind(RTSOCKET hSocket, PCRTNETADDR pAddr)
{
    RTSOCKADDRUNION u;
    int             cbAddr;
    int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
    if (RT_SUCCESS(rc))
        rc = rtSocketBindRawAddr(hSocket, &u.Addr, cbAddr);
    return rc;
}


/**
 * Very thin wrapper around bind.
 *
 * @returns IPRT status code.
 * @param   hSocket             The socket handle.
 * @param   pvAddr              The address to bind to (struct sockaddr and
 *                              friends).
 * @param   cbAddr              The size of the address.
 */
DECLHIDDEN(int) rtSocketBindRawAddr(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
    AssertPtrReturn(pvAddr, VERR_INVALID_POINTER);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnbind, VERR_NET_NOT_UNSUPPORTED);
# define bind g_pfnbind
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc;
    if (bind(pThis->hNative, (struct sockaddr const *)pvAddr, (int)cbAddr) == 0)
        rc = VINF_SUCCESS;
    else
        rc = rtSocketError();

    rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef bind
#endif
    return rc;
}



/**
 * Wrapper around listen.
 *
 * @returns IPRT status code.
 * @param   hSocket             The socket handle.
 * @param   cMaxPending         The max number of pending connections.
 */
DECLHIDDEN(int) rtSocketListen(RTSOCKET hSocket, int cMaxPending)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnlisten, VERR_NET_NOT_UNSUPPORTED);
# define listen g_pfnlisten
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc = VINF_SUCCESS;
    if (listen(pThis->hNative, cMaxPending) != 0)
        rc = rtSocketError();

    rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef listen
#endif
    return rc;
}


/**
 * Wrapper around accept.
 *
 * @returns IPRT status code.
 * @param   hSocket             The socket handle.
 * @param   phClient            Where to return the client socket handle on
 *                              success.
 * @param   pAddr               Where to return the client address.
 * @param   pcbAddr             On input this gives the size buffer size of what
 *                              @a pAddr point to.  On return this contains the
 *                              size of what's stored at @a pAddr.
 */
DECLHIDDEN(int) rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
{
    /*
     * Validate input.
     * Only lock the socket temporarily while we get the native handle, so that
     * we can safely shutdown and destroy the socket from a different thread.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnaccept, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfnclosesocket, VERR_NET_NOT_UNSUPPORTED);
# define accept g_pfnaccept
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    /*
     * Call accept().
     */
    rtSocketErrorReset();
    int         rc      = VINF_SUCCESS;
#ifdef RT_OS_WINDOWS
    int         cbAddr  = (int)*pcbAddr;
#else
    socklen_t   cbAddr  = *pcbAddr;
#endif
    RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
    if (hNativeClient != NIL_RTSOCKETNATIVE)
    {
        *pcbAddr = cbAddr;

        /*
         * Wrap the client socket.
         */
        rc = rtSocketCreateForNative(phClient, hNativeClient, false /*fLeaveOpen*/);
        if (RT_FAILURE(rc))
        {
#ifdef RT_OS_WINDOWS
            g_pfnclosesocket(hNativeClient);
#else
            close(hNativeClient);
#endif
        }
    }
    else
        rc = rtSocketError();

    rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef accept
#endif
    return rc;
}


/**
 * Wrapper around connect.
 *
 * @returns IPRT status code.
 * @param   hSocket             The socket handle.
 * @param   pAddr               The socket address to connect to.
 * @param   cMillies            Number of milliseconds to wait for the connect attempt to complete.
 *                              Use RT_INDEFINITE_WAIT to wait for ever.
 *                              Use RT_TCPCLIENTCONNECT_DEFAULT_WAIT to wait for the default time
 *                              configured on the running system.
 */
DECLHIDDEN(int) rtSocketConnect(RTSOCKET hSocket, PCRTNETADDR pAddr, RTMSINTERVAL cMillies)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnconnect, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfnselect, VERR_NET_NOT_UNSUPPORTED);
    AssertReturn(g_pfngetsockopt, VERR_NET_NOT_UNSUPPORTED);
# define connect        g_pfnconnect
# define select         g_pfnselect
# define getsockopt     g_pfngetsockopt
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    RTSOCKADDRUNION u;
    int             cbAddr;
    int rc = rtSocketAddrFromNetAddr(pAddr, &u, sizeof(u), &cbAddr);
    if (RT_SUCCESS(rc))
    {
        if (cMillies == RT_SOCKETCONNECT_DEFAULT_WAIT)
        {
            if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
                rc = rtSocketError();
        }
        else
        {
            /*
             * Switch the socket to nonblocking mode, initiate the connect
             * and wait for the socket to become writable or until the timeout
             * expires.
             */
            rc = rtSocketSwitchBlockingMode(pThis, false /* fBlocking */);
            if (RT_SUCCESS(rc))
            {
                if (connect(pThis->hNative, &u.Addr, cbAddr) != 0)
                {
                    rc = rtSocketError();
                    if (rc == VERR_TRY_AGAIN || rc == VERR_NET_IN_PROGRESS)
                    {
                        int rcSock = 0;
                        fd_set FdSetWriteable;
                        struct timeval TvTimeout;

                        TvTimeout.tv_sec = cMillies / RT_MS_1SEC;
                        TvTimeout.tv_usec = (cMillies % RT_MS_1SEC) * RT_US_1MS;

                        FD_ZERO(&FdSetWriteable);
                        FD_SET(pThis->hNative, &FdSetWriteable);
                        do
                        {
                            rcSock = select(pThis->hNative + 1, NULL, &FdSetWriteable, NULL,
                                              cMillies == RT_INDEFINITE_WAIT || cMillies >= INT_MAX
                                            ? NULL
                                            : &TvTimeout);
                            if (rcSock > 0)
                            {
                                int iSockError = 0;
                                socklen_t cbSockOpt = sizeof(iSockError);
                                rcSock = getsockopt(pThis->hNative, SOL_SOCKET, SO_ERROR, (char *)&iSockError, &cbSockOpt);
                                if (rcSock == 0)
                                {
                                    if (iSockError == 0)
                                        rc = VINF_SUCCESS;
                                    else
                                    {
#ifdef RT_OS_WINDOWS
                                        rc = RTErrConvertFromWin32(iSockError);
#else
                                        rc = RTErrConvertFromErrno(iSockError);
#endif
                                    }
                                }
                                else
                                    rc = rtSocketError();
                            }
                            else if (rcSock == 0)
                                rc = VERR_TIMEOUT;
                            else
                                rc = rtSocketError();
                        } while (rc == VERR_INTERRUPTED);
                    }
                }

                rtSocketSwitchBlockingMode(pThis, true /* fBlocking */);
            }
        }
    }

    rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef connect
# undef select
# undef getsockopt
#endif
    return rc;
}


/**
 * Wrapper around connect, raw address, no timeout.
 *
 * @returns IPRT status code.
 * @param   hSocket             The socket handle.
 * @param   pvAddr              The raw socket address to connect to.
 * @param   cbAddr              The size of the raw address.
 */
DECLHIDDEN(int) rtSocketConnectRaw(RTSOCKET hSocket, void const *pvAddr, size_t cbAddr)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnconnect, VERR_NET_NOT_UNSUPPORTED);
# define connect        g_pfnconnect
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc;
    if (connect(pThis->hNative, (const struct sockaddr *)pvAddr, (int)cbAddr) == 0)
        rc = VINF_SUCCESS;
    else
        rc = rtSocketError();

    rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef connect
#endif
    return rc;
}


/**
 * Wrapper around setsockopt.
 *
 * @returns IPRT status code.
 * @param   hSocket             The socket handle.
 * @param   iLevel              The protocol level, e.g. IPPORTO_TCP.
 * @param   iOption             The option, e.g. TCP_NODELAY.
 * @param   pvValue             The value buffer.
 * @param   cbValue             The size of the value pointed to by pvValue.
 */
DECLHIDDEN(int) rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
{
    /*
     * Validate input.
     */
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
#ifdef RT_OS_WINDOWS
    AssertReturn(g_pfnsetsockopt, VERR_NET_NOT_UNSUPPORTED);
# define setsockopt g_pfnsetsockopt
#endif
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc = VINF_SUCCESS;
    if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
        rc = rtSocketError();

    rtSocketUnlock(pThis);
#ifdef RT_OS_WINDOWS
# undef setsockopt
#endif
    return rc;
}


/**
 * Internal RTPollSetAdd helper that returns the handle that should be added to
 * the pollset.
 *
 * @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
 * @param   hSocket             The socket handle.
 * @param   fEvents             The events we're polling for.
 * @param   phNative            Where to put the primary handle.
 */
DECLHIDDEN(int) rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PRTHCINTPTR phNative)
{
    RTSOCKETINT *pThis = hSocket;
    RT_NOREF_PV(fEvents);
    AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
#ifdef RT_OS_WINDOWS
    AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);

    int rc = VINF_SUCCESS;
    if (pThis->hEvent != WSA_INVALID_EVENT)
        *phNative = (RTHCINTPTR)pThis->hEvent;
    else if (g_pfnWSACreateEvent)
    {
        pThis->hEvent = g_pfnWSACreateEvent();
        *phNative = (RTHCINTPTR)pThis->hEvent;
        if (pThis->hEvent == WSA_INVALID_EVENT)
            rc = rtSocketError();
    }
    else
    {
        AssertCompile(WSA_INVALID_EVENT == (WSAEVENT)NULL);
        pThis->hEvent = CreateEventW(NULL, TRUE /*fManualReset*/, FALSE /*fInitialState*/,  NULL /*pwszName*/);
        *phNative = (RTHCINTPTR)pThis->hEvent;
        if (pThis->hEvent == WSA_INVALID_EVENT)
            rc = RTErrConvertFromWin32(GetLastError());
    }

    rtSocketUnlock(pThis);
    return rc;

#else  /* !RT_OS_WINDOWS */
    *phNative = (RTHCUINTPTR)pThis->hNative;
    return VINF_SUCCESS;
#endif /* !RT_OS_WINDOWS */
}

#ifdef RT_OS_WINDOWS

/**
 * Fallback poller thread.
 *
 * @returns VINF_SUCCESS.
 * @param   hSelf               The thread handle.
 * @param   pvUser              Socket instance data.
 */
static DECLCALLBACK(int) rtSocketPollFallbackThreadProc(RTTHREAD hSelf, void *pvUser)
{
    RTSOCKETINT *pThis = (RTSOCKETINT *)pvUser;
    RT_NOREF(hSelf);
# define __WSAFDIsSet g_pfn__WSAFDIsSet

    /*
     * The execution loop.
     */
    while (!ASMAtomicReadBool(&pThis->fPollFallbackShutdown))
    {
        /*
         * Do the selecting (with a 15 second timeout because that seems like a good idea).
         */
        struct fd_set SetRead;
        struct fd_set SetWrite;
        struct fd_set SetXcpt;

        FD_ZERO(&SetRead);
        FD_ZERO(&SetWrite);
        FD_ZERO(&SetXcpt);

        FD_SET(pThis->hPollFallbackNotifyR, &SetRead);
        FD_SET(pThis->hPollFallbackNotifyR, &SetXcpt);

        bool     fActive = ASMAtomicReadBool(&pThis->fPollFallbackActive);
        uint32_t fEvents;
        if (!fActive)
            fEvents = 0;
        else
        {
            fEvents = ASMAtomicReadU32(&pThis->fSubscribedEvts);
            if (fEvents & RTPOLL_EVT_READ)
                FD_SET(pThis->hNative, &SetRead);
            if (fEvents & RTPOLL_EVT_WRITE)
                FD_SET(pThis->hNative, &SetWrite);
            if (fEvents & RTPOLL_EVT_ERROR)
                FD_SET(pThis->hNative, &SetXcpt);
        }

        struct timeval Timeout;
        Timeout.tv_sec  = 15;
        Timeout.tv_usec = 0;
        int rc = g_pfnselect(INT_MAX /*ignored*/, &SetRead, &SetWrite, &SetXcpt, &Timeout);

        /* Stop immediately if told to shut down. */
        if (ASMAtomicReadBool(&pThis->fPollFallbackShutdown))
            break;

        /*
         * Process the result.
         */
        if (rc > 0)
        {
            /* First the socket we're listening on. */
            if (   fEvents
                && (   FD_ISSET(pThis->hNative, &SetRead)
                    || FD_ISSET(pThis->hNative, &SetWrite)
                    || FD_ISSET(pThis->hNative, &SetXcpt)) )
            {
                ASMAtomicWriteBool(&pThis->fPollFallbackActive, false);
                SetEvent(pThis->hEvent);
            }

            /* Then maintain the notification pipe.  (We only read one byte here
               because we're overly paranoid wrt socket switching to blocking mode.) */
            if (FD_ISSET(pThis->hPollFallbackNotifyR, &SetRead))
            {
                char chIgnored;
                g_pfnrecv(pThis->hPollFallbackNotifyR, &chIgnored, sizeof(chIgnored), MSG_NOSIGNAL);
            }
        }
        else
            AssertMsg(rc == 0, ("%Rrc\n", rtSocketError()));
    }

# undef __WSAFDIsSet
    return VINF_SUCCESS;
}


/**
 * Pokes the fallback thread, making sure it gets out of whatever it's stuck in.
 *
 * @param   pThis               The socket handle.
 */
static void rtSocketPokePollFallbackThread(RTSOCKETINT *pThis)
{
    Assert(pThis->fPollFallback);
    if (pThis->hPollFallbackThread != NIL_RTTHREAD)
    {
        int cbWritten = g_pfnsend(pThis->hPollFallbackNotifyW, "!", 1, MSG_NOSIGNAL);
        AssertMsg(cbWritten == 1, ("cbWritten=%d err=%Rrc\n",  rtSocketError()));
        RT_NOREF_PV(cbWritten);
    }
}


/**
 * Called by rtSocketPollStart to make the thread start selecting on the socket.
 *
 * @returns 0 on success, RTPOLL_EVT_ERROR on failure.
 * @param   pThis               The socket handle.
 */
static uint32_t rtSocketPollFallbackStart(RTSOCKETINT *pThis)
{
    /*
     * Reset the event and tell the thread to start selecting on the socket.
     */
    ResetEvent(pThis->hEvent);
    ASMAtomicWriteBool(&pThis->fPollFallbackActive, true);

    /*
     * Wake up the thread the thread.
     */
    if (pThis->hPollFallbackThread != NIL_RTTHREAD)
        rtSocketPokePollFallbackThread(pThis);
    else
    {
        /*
         * Not running, need to set it up and start it.
         */
        AssertLogRelReturn(pThis->hEvent != NULL && pThis->hEvent != INVALID_HANDLE_VALUE, RTPOLL_EVT_ERROR);

        /* Create the notification socket pair. */
        int rc;
        if (pThis->hPollFallbackNotifyR == NIL_RTSOCKETNATIVE)
        {
            rc = rtSocketCreateNativeTcpPair(&pThis->hPollFallbackNotifyW, &pThis->hPollFallbackNotifyR);
            AssertLogRelRCReturn(rc, RTPOLL_EVT_ERROR);

            /* Make the read end non-blocking (not fatal). */
            u_long fNonBlocking = 1;
            rc = g_pfnioctlsocket(pThis->hPollFallbackNotifyR, FIONBIO, &fNonBlocking);
            AssertLogRelMsg(rc == 0,  ("rc=%#x %Rrc\n", rc, rtSocketError()));
        }

        /* Finally, start the thread.  ASSUME we don't need too much stack. */
        rc = RTThreadCreate(&pThis->hPollFallbackThread, rtSocketPollFallbackThreadProc, pThis,
                            _128K, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "sockpoll");
        AssertLogRelRCReturn(rc, RTPOLL_EVT_ERROR);
    }
    return 0;
}


/**
 * Undos the harm done by WSAEventSelect.
 *
 * @returns IPRT status code.
 * @param   pThis               The socket handle.
 */
static int rtSocketPollClearEventAndRestoreBlocking(RTSOCKETINT *pThis)
{
    int rc = VINF_SUCCESS;
    if (pThis->fSubscribedEvts)
    {
        if (!pThis->fPollFallback)
        {
            Assert(g_pfnWSAEventSelect && g_pfnioctlsocket);
            if (g_pfnWSAEventSelect && g_pfnioctlsocket)
            {
                if (g_pfnWSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
                {
                    pThis->fSubscribedEvts = 0;

                    /*
                     * Switch back to blocking mode if that was the state before the
                     * operation.
                     */
                    if (pThis->fBlocking)
                    {
                        u_long fNonBlocking = 0;
                        int rc2 = g_pfnioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
                        if (rc2 != 0)
                        {
                            rc = rtSocketError();
                            AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
                        }
                    }
                }
                else
                {
                    rc = rtSocketError();
                    AssertMsgFailed(("%Rrc\n", rc));
                }
            }
            else
            {
                Assert(pThis->fPollFallback);
                rc = VINF_SUCCESS;
            }
        }
        /*
         * Just clear the event mask as we never started waiting if we get here.
         */
        else
            ASMAtomicWriteU32(&pThis->fSubscribedEvts, 0);
    }
    return rc;
}


/**
 * Updates the mask of events we're subscribing to.
 *
 * @returns IPRT status code.
 * @param   pThis               The socket handle.
 * @param   fEvents             The events we want to subscribe to.
 */
static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
{
    if (!pThis->fPollFallback)
    {
        LONG fNetworkEvents = 0;
        if (fEvents & RTPOLL_EVT_READ)
            fNetworkEvents |= FD_READ;
        if (fEvents & RTPOLL_EVT_WRITE)
            fNetworkEvents |= FD_WRITE;
        if (fEvents & RTPOLL_EVT_ERROR)
            fNetworkEvents |= FD_CLOSE;
        LogFlowFunc(("fNetworkEvents=%#x\n", fNetworkEvents));

        if (g_pfnWSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
        {
            pThis->fSubscribedEvts = fEvents;
            return VINF_SUCCESS;
        }

        int rc = rtSocketError();
        AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
        return rc;
    }

    /*
     * Update the events we're waiting for.  Caller will poke/start the thread. later
     */
    ASMAtomicWriteU32(&pThis->fSubscribedEvts, fEvents);
    return VINF_SUCCESS;
}

#endif  /* RT_OS_WINDOWS */


#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)

/**
 * Checks for pending events.
 *
 * @returns Event mask or 0.
 * @param   pThis               The socket handle.
 * @param   fEvents             The desired events.
 */
static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
{
    uint32_t fRetEvents = 0;

    LogFlowFunc(("pThis=%#p fEvents=%#x\n", pThis, fEvents));

# ifdef RT_OS_WINDOWS
    /* Make sure WSAEnumNetworkEvents returns what we want. */
    int rc = VINF_SUCCESS;
    if ((pThis->fSubscribedEvts & fEvents) != fEvents)
        rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);

    if (!pThis->fPollFallback)
    {
        /* Atomically get pending events and reset the event semaphore. */
        Assert(g_pfnWSAEnumNetworkEvents);
        WSANETWORKEVENTS NetEvts;
        RT_ZERO(NetEvts);
        if (g_pfnWSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
        {
            if (   (NetEvts.lNetworkEvents & FD_READ)
                && NetEvts.iErrorCode[FD_READ_BIT] == 0)
                fRetEvents |= RTPOLL_EVT_READ;

            if (   (NetEvts.lNetworkEvents & FD_WRITE)
                && NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
                fRetEvents |= RTPOLL_EVT_WRITE;

            if (NetEvts.lNetworkEvents & FD_CLOSE)
                fRetEvents |= RTPOLL_EVT_ERROR;
            else
                for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
                    if (   (NetEvts.lNetworkEvents & (1L << i))
                        && NetEvts.iErrorCode[i] != 0)
                        fRetEvents |= RTPOLL_EVT_ERROR;

            pThis->fEventsSaved = fRetEvents |= pThis->fEventsSaved;
            fRetEvents &= fEvents | RTPOLL_EVT_ERROR;
        }
        else
            rc = rtSocketError();
    }

    /* Fall back on select if we hit an error above or is using fallback polling. */
    if (pThis->fPollFallback || RT_FAILURE(rc))
    {
        rc = rtSocketSelectOneEx(pThis, fEvents & RTPOLL_EVT_ERROR ? fEvents | RTPOLL_EVT_READ : fEvents, &fRetEvents, 0);
        if (RT_SUCCESS(rc))
        {
            /* rtSocketSelectOneEx may return RTPOLL_EVT_READ on disconnect.  Use
               getpeername to fix this. */
            if ((fRetEvents & (RTPOLL_EVT_READ | RTPOLL_EVT_ERROR)) == RTPOLL_EVT_READ)
            {
# if 0 /* doens't work */
                rtSocketErrorReset();
                char chIgn;
                rc = g_pfnrecv(pThis->hNative, &chIgn, 0, MSG_NOSIGNAL);
                rc = rtSocketError();
                if (RT_FAILURE(rc))
                    fRetEvents |= RTPOLL_EVT_ERROR;

                rc = g_pfnsend(pThis->hNative, &chIgn, 0, MSG_NOSIGNAL);
                rc = rtSocketError();
                if (RT_FAILURE(rc))
                    fRetEvents |= RTPOLL_EVT_ERROR;

                RTSOCKADDRUNION u;
                int cbAddr = sizeof(u);
                if (g_pfngetpeername(pThis->hNative, &u.Addr, &cbAddr) == SOCKET_ERROR)
                    fRetEvents |= RTPOLL_EVT_ERROR;
# endif
                /* If no bytes are available, assume error condition. */
                u_long cbAvail = 0;
                rc = g_pfnioctlsocket(pThis->hNative, FIONREAD, &cbAvail);
                if (rc == 0 && cbAvail == 0)
                    fRetEvents |= RTPOLL_EVT_ERROR;
            }
            fRetEvents &= fEvents | RTPOLL_EVT_ERROR;
        }
        else if (rc == VERR_TIMEOUT)
            fRetEvents = 0;
        else
            fRetEvents |= RTPOLL_EVT_ERROR;
    }

# else  /* RT_OS_OS2 */
    int aFds[4] = { pThis->hNative, pThis->hNative, pThis->hNative, -1 };
    int rc = os2_select(aFds, 1, 1, 1, 0);
    if (rc > 0)
    {
        if (aFds[0] == pThis->hNative)
            fRetEvents |= RTPOLL_EVT_READ;
        if (aFds[1] == pThis->hNative)
            fRetEvents |= RTPOLL_EVT_WRITE;
        if (aFds[2] == pThis->hNative)
            fRetEvents |= RTPOLL_EVT_ERROR;
        fRetEvents &= fEvents;
    }
# endif /* RT_OS_OS2 */

    LogFlowFunc(("fRetEvents=%#x\n", fRetEvents));
    return fRetEvents;
}


/**
 * Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
 * clear, starts whatever actions we've got running during the poll call.
 *
 * @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
 *          Event mask (in @a fEvents) and no actions if the handle is ready
 *          already.
 *          UINT32_MAX (asserted) if the socket handle is busy in I/O or a
 *          different poll set.
 *
 * @param   hSocket             The socket handle.
 * @param   hPollSet            The poll set handle (for access checks).
 * @param   fEvents             The events we're polling for.
 * @param   fFinalEntry         Set if this is the final entry for this handle
 *                              in this poll set.  This can be used for dealing
 *                              with duplicate entries.
 * @param   fNoWait             Set if it's a zero-wait poll call.  Clear if
 *                              we'll wait for an event to occur.
 *
 * @remarks There is a potential race wrt duplicate handles when @a fNoWait is
 *          @c true, we don't currently care about that oddity...
 */
DECLHIDDEN(uint32_t) rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
{
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, UINT32_MAX);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
    /** @todo This isn't quite sane. Replace by critsect and open up concurrent
     *        reads and writes! */
    if (rtSocketTryLock(pThis))
        pThis->hPollSet = hPollSet;
    else
    {
        AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
        ASMAtomicIncU32(&pThis->cUsers);
    }

    /* (rtSocketPollCheck will reset the event object). */
# ifdef RT_OS_WINDOWS
    uint32_t fRetEvents = pThis->fEventsSaved;
    pThis->fEventsSaved = 0; /* Reset */
    fRetEvents |= rtSocketPollCheck(pThis, fEvents);

    if (   !fRetEvents
        && !fNoWait)
    {
        pThis->fPollEvts |= fEvents;
        if (fFinalEntry)
        {
            if (pThis->fSubscribedEvts != pThis->fPollEvts)
            {
                /** @todo seems like there might be a call to many here and that fPollEvts is
                 *        totally unnecessary... (bird) */
                int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
                if (RT_FAILURE(rc))
                {
                    pThis->fPollEvts = 0;
                    fRetEvents       = UINT32_MAX;
                }
            }

            /* Make sure we don't block when there are events pending relevant to an earlier poll set entry. */
            if (pThis->fEventsSaved && !pThis->fPollFallback && g_pfnWSASetEvent && fRetEvents == 0)
                g_pfnWSASetEvent(pThis->hEvent);
        }
    }
# else
    uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
# endif

    if (fRetEvents || fNoWait)
    {
        if (pThis->cUsers == 1)
        {
# ifdef RT_OS_WINDOWS
            pThis->fEventsSaved    &= RTPOLL_EVT_ERROR;
            pThis->fHarvestedEvents = false;
            rtSocketPollClearEventAndRestoreBlocking(pThis);
# endif
            pThis->hPollSet = NIL_RTPOLLSET;
        }
# ifdef RT_OS_WINDOWS
        else
            pThis->fHarvestedEvents = true;
# endif
        ASMAtomicDecU32(&pThis->cUsers);
    }
# ifdef RT_OS_WINDOWS
    /*
     * Kick the poller thread on if this is the final entry and we're in
     * winsock 1.x fallback mode.
     */
    else if (pThis->fPollFallback && fFinalEntry)
        fRetEvents = rtSocketPollFallbackStart(pThis);
# endif

    return fRetEvents;
}


/**
 * Called after a WaitForMultipleObjects returned in order to check for pending
 * events and stop whatever actions that rtSocketPollStart() initiated.
 *
 * @returns Event mask or 0.
 *
 * @param   hSocket             The socket handle.
 * @param   fEvents             The events we're polling for.
 * @param   fFinalEntry         Set if this is the final entry for this handle
 *                              in this poll set.  This can be used for dealing
 *                              with duplicate entries.  Only keep in mind that
 *                              this method is called in reverse order, so the
 *                              first call will have this set (when the entire
 *                              set was processed).
 * @param   fHarvestEvents      Set if we should check for pending events.
 */
DECLHIDDEN(uint32_t) rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry, bool fHarvestEvents)
{
    RTSOCKETINT *pThis = hSocket;
    AssertPtrReturn(pThis, 0);
    AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
    Assert(pThis->cUsers > 0);
    Assert(pThis->hPollSet != NIL_RTPOLLSET);
    RT_NOREF_PV(fFinalEntry);

# ifdef RT_OS_WINDOWS
    /*
     * Deactivate the poll thread if we're in winsock 1.x fallback poll mode.
     */
    if (   pThis->fPollFallback
        && pThis->hPollFallbackThread != NIL_RTTHREAD)
    {
        ASMAtomicWriteU32(&pThis->fSubscribedEvts, 0);
        if (ASMAtomicXchgBool(&pThis->fPollFallbackActive, false))
            rtSocketPokePollFallbackThread(pThis);
    }
# endif

    /*
     * Harvest events and clear the event mask for the next round of polling.
     */
    uint32_t fRetEvents;
# ifdef RT_OS_WINDOWS
    if (!pThis->fPollFallback)
    {
        if (!pThis->fHarvestedEvents)
        {
            fRetEvents = rtSocketPollCheck(pThis, fEvents);
            pThis->fHarvestedEvents = true;
        }
        else
            fRetEvents = pThis->fEventsSaved;
        if (fHarvestEvents)
            fRetEvents &= fEvents;
        else
            fRetEvents = 0;
        pThis->fPollEvts = 0;
    }
    else
# endif
    {
        if (fHarvestEvents)
            fRetEvents = rtSocketPollCheck(pThis, fEvents);
        else
            fRetEvents = 0;
    }

    /*
     * Make the socket blocking again and unlock the handle.
     */
    if (pThis->cUsers == 1)
    {
# ifdef RT_OS_WINDOWS
        pThis->fEventsSaved    &= RTPOLL_EVT_ERROR;
        pThis->fHarvestedEvents = false;
        rtSocketPollClearEventAndRestoreBlocking(pThis);
# endif
        pThis->hPollSet = NIL_RTPOLLSET;
    }
    ASMAtomicDecU32(&pThis->cUsers);
    return fRetEvents;
}

#endif /* RT_OS_WINDOWS || RT_OS_OS2 */