summaryrefslogtreecommitdiff
path: root/open-vm-tools/lib/asyncsocket/asyncsocket.c
blob: 3afcbdea639d7ad4ae5e98d62921a3cf8bfae1ec (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
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
/*********************************************************
 * Copyright (C) 2003-2015 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation version 2.1 and no later version.
 *
 * 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 Lesser GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
 *
 *********************************************************/

/*********************************************************
 * The contents of this file are subject to the terms of the Common
 * Development and Distribution License (the "License") version 1.0
 * and no later version.  You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the License at
 *         http://www.opensource.org/licenses/cddl1.php
 *
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 *********************************************************/

/*
 * asyncsocket.c --
 *
 *      The AsyncSocket object is a fairly simple wrapper around a basic TCP
 *      socket. It's potentially asynchronous for both read and write
 *      operations. Reads are "requested" by registering a receive function
 *      that is called once the requested amount of data has been read from
 *      the socket. Similarly, writes are queued along with a send function
 *      that is called once the data has been written. Errors are reported via
 *      a separate callback.
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdarg.h>

#include "str.h"

#include "vmware.h"
#include "asyncsocket.h"
#include "asyncSocketInt.h"
#include "poll.h"
#include "log.h"
#include "err.h"
#include "hostinfo.h"
#include "util.h"
#include "msg.h"
#include "posix.h"
#include "vmci_sockets.h"
#ifndef VMX86_TOOLS
#include "vmdblib.h"
#endif

#define LOGLEVEL_MODULE asyncsocket
#include "loglevel_user.h"

#ifdef VMX86_SERVER
#include "uwvmkAPI.h"
#endif

#ifdef __linux__
/*
 * Our toolchain does not support IPV6_V6ONLY, but the host we are running on
 * may support it. Since setsockopt will return a error that we treat as
 * non-fatal, it is fine to attempt it. See define in in6.h.
 */
#ifndef IPV6_V6ONLY
#define IPV6_V6ONLY 26
#endif

/*
 * Linux versions can lack support for IPV6_V6ONLY while still supporting
 * V4MAPPED addresses. We check for a V4MAPPED address during accept to cover
 * this scenario. In case IN6_IS_ADDR_V4MAPPED is also not avaiable, define it.
 */
#ifndef IN6_IS_ADDR_V4MAPPED
#define IN6_IS_ADDR_V4MAPPED(a)                                   \
   (*(const u_int32_t *)(const void *)(&(a)->s6_addr[0]) == 0 &&  \
    *(const u_int32_t *)(const void *)(&(a)->s6_addr[4]) == 0 &&  \
    *(const u_int32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff)))
#endif
#endif

#define PORT_STRING_LEN 6 /* "12345\0" or ":12345" */

/*
 * INET6_ADDRSTRLEN allows for only 45 characters. If we somehow have a
 * non-recommended V4MAPPED address we can exceed 45 total characters in our
 * address string format. While this should not be the case it is possible.
 * Account for the possible:
 *    "[XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:AAA.BBB.CCC.DDD]:12345\0"
 *    (XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:AAA.BBB.CCC.DDD\0 + [] + :12345)
 */
#define ADDR_STRING_LEN (INET6_ADDRSTRLEN + 2 + PORT_STRING_LEN)

/*
 * The slots each have a "unique" ID, which is just an incrementing integer.
 */
static Atomic_uint32 nextid = { 1 };

/*
 * Local Functions
 */
static Bool AsyncSocketHasDataPending(AsyncSocket *asock);
static int AsyncSocketMakeNonBlocking(int fd);
static void AsyncSocketAcceptCallback(void *clientData);
static void AsyncSocketConnectCallback(void *clientData);
static int AsyncSocketBlockingWork(AsyncSocket *asock, Bool read, void *buf, int len,
                                   int *completed, int timeoutMS, Bool partial);
static VMwareStatus AsyncSocketPollAdd(AsyncSocket *asock, Bool socket,
                                       int flags, PollerFunction callback,
                                       ...);
static Bool AsyncSocketPollRemove(AsyncSocket *asock, Bool socket,
                                  int flags, PollerFunction callback);
static unsigned int AsyncSocketGetPort(struct sockaddr_storage *addr);
static AsyncSocket *AsyncSocketConnect(struct sockaddr_storage *addr,
                                       socklen_t addrLen,
                                       AsyncSocketConnectFn connectFn,
                                       void *clientData,
                                       PollerFunction internalConnectFn,
                                       AsyncSocketConnectFlags flags,
                                       AsyncSocketPollParams *pollParams,
                                       int *outError);
static int AsyncSocketConnectInternal(AsyncSocket *s);
static int AsyncSocketRecv(AsyncSocket *asock, void *buf, int len,
                           Bool fireOnPartial, void *cb, void *cbData);
static Bool AsyncSocketHasDataPendingSocket(AsyncSocket *asock);

static VMwareStatus AsyncSocketIPollAdd(AsyncSocket *asock, Bool socket,
                                        int flags, PollerFunction callback,
                                        int info);
static Bool AsyncSocketIPollRemove(AsyncSocket *asock, Bool socket, int flags,
                                   PollerFunction callback);
static void AsyncSocketIPollSendCallback(void *clientData);
static void AsyncSocketIPollRecvCallback(void *clientData);
static Bool AsyncSocketAddListenCbSocket(AsyncSocket *asock);


static const AsyncSocketVTable asyncStreamSocketVTable = {
   AsyncSocketDispatchConnect,
   AsyncSocketSendInternal,
   AsyncSocketSendSocket,
   AsyncSocketRecvSocket,
   AsyncSocketSendCallback,
   AsyncSocketRecvCallback,
   AsyncSocketHasDataPendingSocket,
   AsyncSocketCancelListenCbSocket,
   AsyncSocketCancelRecvCbSocket,
   AsyncSocketCancelCbForCloseSocket,
   AsyncSocketCancelCbForConnectingCloseSocket,
   AsyncSocketCloseSocket,
   NULL,
};


static const AsyncSocketVTable asyncStreamSocketIPollVTable = {
   AsyncSocketDispatchConnect,
   AsyncSocketSendInternal,
   AsyncSocketSendSocket,
   AsyncSocketRecvSocket,
   AsyncSocketIPollSendCallback,
   AsyncSocketIPollRecvCallback,
   AsyncSocketHasDataPendingSocket,
   AsyncSocketCancelListenCbSocket,
   AsyncSocketCancelRecvCbSocket,
   AsyncSocketCancelCbForCloseSocket,
   AsyncSocketCancelCbForConnectingCloseSocket,
   AsyncSocketCloseSocket,
   NULL,
};


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketLock --
 * AsyncSocketUnlock --
 *
 *      Acquire/Release the lock provided by the client when creating the
 *      AsyncSocket object.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

INLINE void
AsyncSocketLock(AsyncSocket *asock)   // IN:
{
   if (asock->pollParams.lock) {
      MXUser_AcquireRecLock(asock->pollParams.lock);
   }
}


INLINE void
AsyncSocketUnlock(AsyncSocket *asock)   // IN:
{
   if (asock->pollParams.lock) {
      MXUser_ReleaseRecLock(asock->pollParams.lock);
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketIsLocked --
 *
 *      If a lock is associated with the socket, check whether the calling
 *      thread holds the lock.
 *
 * Results:
 *      TRUE if calling thread holds the lock, or if there is no assoicated
 *      lock.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

INLINE Bool
AsyncSocketIsLocked(AsyncSocket *asock)   // IN:
{
   if (asock->pollParams.lock && Poll_LockingEnabled()) {
      return MXUser_IsCurThreadHoldingRecLock(asock->pollParams.lock);
   }
   return TRUE;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_Init --
 *
 *      Initializes the host's socket library. NOP on Posix.
 *      On Windows, calls WSAStartup().
 *
 * Results:
 *      ASOCKERR_SUCCESS or ASOCKERR_GENERIC.
 *
 * Side effects:
 *      On Windows, loads winsock library.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_Init(void)
{
#ifdef _WIN32
   WSADATA wsaData;
   WORD versionRequested = MAKEWORD(2, 0);
   return WSAStartup(versionRequested, &wsaData) ?
             ASOCKERR_GENERIC : ASOCKERR_SUCCESS;
#endif
   return ASOCKERR_SUCCESS;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_Err2String --
 *
 *      Returns the error string associated with error code.
 *
 * Results:
 *      Error string.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

const char *
AsyncSocket_Err2String(int err)  // IN
{
   return Msg_StripMSGID(AsyncSocket_MsgError(err));
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_MsgError --
 *
 *      Returns the message associated with error code.
 *
 * Results:
 *      Message string.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

const char *
AsyncSocket_MsgError(int asyncSockError)   // IN
{
   const char *result = NULL;
   switch (asyncSockError) {
   case ASOCKERR_SUCCESS:
      result = MSGID(asyncsocket.success) "Success";
      break;
   case ASOCKERR_GENERIC:
      result = MSGID(asyncsocket.generic) "Asyncsocket error";
      break;
   case ASOCKERR_INVAL:
      result = MSGID(asyncsocket.invalid) "Invalid parameters";
      break;
   case ASOCKERR_TIMEOUT:
      result = MSGID(asyncsocket.timeout) "Time-out error";
      break;
   case ASOCKERR_NOTCONNECTED:
      result = MSGID(asyncsocket.notconnected) "Local socket not connected";
      break;
   case ASOCKERR_REMOTE_DISCONNECT:
      result = MSGID(asyncsocket.remotedisconnect) "Remote connection failure";
      break;
   case ASOCKERR_CLOSED:
      result = MSGID(asyncsocket.closed) "Closed socket";
      break;
   case ASOCKERR_CONNECT:
      result = MSGID(asyncsocket.connect) "Connection error";
      break;
   case ASOCKERR_POLL:
      result = MSGID(asyncsocket.poll) "Poll registration error";
      break;
   case ASOCKERR_BIND:
      result = MSGID(asyncsocket.bind) "Socket bind error";
      break;
   case ASOCKERR_BINDADDRINUSE:
      result = MSGID(asyncsocket.bindaddrinuse) "Socket bind address already in use";
      break;
   case ASOCKERR_LISTEN:
      result = MSGID(asyncsocket.listen) "Socket listen error";
      break;
   }

   if (!result) {
      Warning("%s was passed bad code %d\n", __FUNCTION__, asyncSockError);
      result = MSGID(asyncsocket.unknown) "Unknown error";
   }
   return result;
}

/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_GetFd --
 *
 *      Returns the fd for this socket.
 *
 * Results:
 *      File descriptor.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_GetFd(AsyncSocket *s)
{
   return s->fd;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketGetAddr --
 *
 *      Given an AsyncSocket object, return the sockaddr associated with the
 *      requested address family's file descriptor if available.
 *
 *      Passing AF_UNSPEC to socketFamily will provide you with the first
 *      usable sockaddr found (if multiple are available), with a preference
 *      given to IPv6.
 *
 * Results:
 *      ASOCKERR_SUCCESS. ASOCKERR_INVAL if there is no socket associated with
 *      address family requested. ASOCKERR_GENERIC for all other errors.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static int
AsyncSocketGetAddr(AsyncSocket *asock,                // IN
                   int socketFamily,                  // IN
                   struct sockaddr_storage *outAddr,  // OUT
                   socklen_t *outAddrLen)             // IN/OUT
{
   AsyncSocket *tempAsock;
   int tempFd;
   struct sockaddr_storage addr;
   socklen_t addrLen = sizeof addr;
   int ret = ASOCKERR_GENERIC;

   if (asock->fd != -1) {
      tempAsock = asock;
   } else if ((socketFamily == AF_UNSPEC || socketFamily == AF_INET6) &&
              asock->listenAsock6 && asock->listenAsock6->fd != -1) {
      tempAsock = asock->listenAsock6;
   } else if ((socketFamily == AF_UNSPEC || socketFamily == AF_INET) &&
              asock->listenAsock4 && asock->listenAsock4->fd != -1) {
      tempAsock = asock->listenAsock4;
   } else {
      return ASOCKERR_INVAL;
   }

   AsyncSocketLock(tempAsock);
   tempFd = tempAsock->fd;

   if (getsockname(tempFd, (struct sockaddr*)&addr, &addrLen) == 0) {
      if (socketFamily != AF_UNSPEC && addr.ss_family != socketFamily) {
         ret = ASOCKERR_INVAL;
         goto outWithLock;
      }

      memcpy(outAddr, &addr, Min(*outAddrLen, addrLen));
      *outAddrLen = addrLen;
      ret = ASOCKERR_SUCCESS;
   } else {
      ASOCKWARN(tempAsock, ("%s: could not locate socket.\n", __FUNCTION__));
   }

 outWithLock:
   AsyncSocketUnlock(tempAsock);
   return ret;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_GetRemoteIPStr --
 *
 *      Given an AsyncSocket object, returns the remote IP address associated
 *      with it, or an error if the request is meaningless for the underlying
 *      connection.
 *
 * Results:
 *      ASOCKERR_SUCCESS or ASOCKERR_GENERIC.
 *
 * Side effects:
 *
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_GetRemoteIPStr(AsyncSocket *asock,      // IN
                           const char **ipRetStr)   // OUT
{
   int ret = ASOCKERR_SUCCESS;

   ASSERT(asock);
   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(ipRetStr != NULL);

   if (ipRetStr == NULL || asock == NULL ||
       asock->state != AsyncSocketConnected ||
       (asock->remoteAddrLen != sizeof (struct sockaddr_in) &&
        asock->remoteAddrLen != sizeof (struct sockaddr_in6))) {
      ret = ASOCKERR_GENERIC;
   } else {
      char addrBuf[NI_MAXHOST];

      if (Posix_GetNameInfo((struct sockaddr *)&asock->remoteAddr,
                            asock->remoteAddrLen, addrBuf,
                            sizeof addrBuf, NULL, 0, NI_NUMERICHOST) != 0) {
         ret = ASOCKERR_GENERIC;
      } else {
         *ipRetStr = Util_SafeStrdup(addrBuf);
      }
   }

   return ret;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_GetINETIPStr --
 *
 *      Given an AsyncSocket object, returns the IP addresses associated with
 *      the requested address family's file descriptor if available.
 *
 *      Passing AF_UNSPEC to socketFamily will provide you with the first
 *      usable IP address found (if multiple are available), with a preference
 *      given to IPv6.
 *
 *      It is the caller's responsibility to free ipRetStr.
 *
 * Results:
 *      ASOCKERR_SUCCESS. ASOCKERR_INVAL if there is no socket associated with
 *      address family requested. ASOCKERR_GENERIC for all other errors.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_GetINETIPStr(AsyncSocket *asock,  // IN
                         int socketFamily,    // IN
                         char **ipRetStr)     // OUT
{
   struct sockaddr_storage addr;
   socklen_t addrLen = sizeof addr;
   int ret;

   AsyncSocketLock(asock);

   ret = AsyncSocketGetAddr(asock, socketFamily, &addr, &addrLen);
   if (ret == ASOCKERR_SUCCESS) {
      char addrBuf[NI_MAXHOST];

      if (ipRetStr == NULL) {
         ret = ASOCKERR_INVAL;
      } else if (Posix_GetNameInfo((struct sockaddr *)&addr, addrLen, addrBuf,
                                   sizeof addrBuf, NULL, 0,
                                   NI_NUMERICHOST) == 0) {
         *ipRetStr = Util_SafeStrdup(addrBuf);
      } else {
         ASOCKWARN(asock, ("%s: could not find IP address.\n", __FUNCTION__));
         ret = ASOCKERR_GENERIC;
      }
   }

   AsyncSocketUnlock(asock);

   return ret;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_GetLocalVMCIAddress --
 *
 *      Given an AsyncSocket object, returns the local VMCI context ID and
 *      port number associated with it, or an error if the request is
 *      meaningless for the underlying connection.
 *
 * Results:
 *      ASOCKERR_SUCCESS or ASOCKERR_GENERIC.
 *
 * Side effects:
 *
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_GetLocalVMCIAddress(AsyncSocket *asock,  // IN
                                uint32 *cid,         // OUT: optional
                                uint32 *port)        // OUT: optional
{
   ASSERT(asock);

   if (asock->localAddrLen != sizeof(struct sockaddr_vm)) {
      return ASOCKERR_GENERIC;
   }

   if (cid != NULL) {
      *cid = ((struct sockaddr_vm *)&asock->localAddr)->svm_cid;
   }

   if (port != NULL) {
      *port = ((struct sockaddr_vm *)&asock->localAddr)->svm_port;
   }

   return ASOCKERR_SUCCESS;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_GetRemoteVMCIAddress --
 *
 *      Given an AsyncSocket object, returns the remote VMCI context ID and
 *      port number associated with it, or an error if the request is
 *      meaningless for the underlying connection.
 *
 * Results:
 *      ASOCKERR_SUCCESS or ASOCKERR_GENERIC.
 *
 * Side effects:
 *
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_GetRemoteVMCIAddress(AsyncSocket *asock,  // IN
                                 uint32 *cid,         // OUT: optional
                                 uint32 *port)        // OUT: optional
{
   ASSERT(asock);

   if (asock->remoteAddrLen != sizeof(struct sockaddr_vm)) {
      return ASOCKERR_GENERIC;
   }

   if (cid != NULL) {
      *cid = ((struct sockaddr_vm *)&asock->remoteAddr)->svm_cid;
   }

   if (port != NULL) {
      *port = ((struct sockaddr_vm *)&asock->remoteAddr)->svm_port;
   }

   return ASOCKERR_SUCCESS;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketListenImpl --
 *
 *      Initializes, binds, and listens on pre-populated address structure.
 *
 * Results:
 *      New AsyncSocket in listening state or NULL on error.
 *
 * Side effects:
 *      Creates new socket, binds and listens.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocketListenImpl(struct sockaddr_storage *addr,      // IN
                      socklen_t addrLen,                  // IN
                      AsyncSocketConnectFn connectFn,     // IN
                      void *clientData,                   // IN
                      AsyncSocketPollParams *pollParams,  // IN: optional
                      Bool isWebSock,                     // IN
                      Bool webSockUseSSL,                 // IN:
                      int *outError)                      // OUT: optional
{
   AsyncSocket *asock = AsyncSocketInit(addr->ss_family, pollParams, outError);

   if (asock != NULL) {
#ifndef VMX86_TOOLS
      if (isWebSock) {
         AsyncSocketInitWebSocket(asock, clientData, webSockUseSSL);
      }
#endif

      if (AsyncSocketBind(asock, addr, addrLen, outError) &&
          AsyncSocketListen(asock, connectFn, clientData, outError)) {
         return asock;
      }
   }

   return NULL;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketListenerCreateImpl --
 *
 *      Listens on specified address and/or port for resolved/requested socket
 *      family and accepts new connections. Fires the connect callback with
 *      new AsyncSocket object for each connection.
 *
 * Results:
 *      New AsyncSocket in listening state or NULL on error.
 *
 * Side effects:
 *      Creates new socket, binds and listens.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocketListenerCreateImpl(const char *addrStr,                // IN: optional
                              unsigned int port,                  // IN: optional
                              int socketFamily,                   // IN
                              AsyncSocketConnectFn connectFn,     // IN
                              void *clientData,                   // IN
                              AsyncSocketPollParams *pollParams,  // IN
                              Bool isWebSock,                     // IN
                              Bool webSockUseSSL,                 // IN
                              int *outError)                      // OUT: optional
{
   AsyncSocket *asock = NULL;
   struct sockaddr_storage addr;
   socklen_t addrLen;
   char *ipString = NULL;
   int getaddrinfoError = AsyncSocketResolveAddr(addrStr, port, socketFamily,
                                                 TRUE, &addr, &addrLen,
                                                 &ipString);

   if (getaddrinfoError == 0) {
      asock = AsyncSocketListenImpl(&addr, addrLen, connectFn, clientData,
                                    pollParams, isWebSock, webSockUseSSL,
                                    outError);

      if (asock) {
         ASOCKLG0(asock,
                  ("Created new %s %s listener for (%s)\n",
                   addr.ss_family == AF_INET ? "IPv4" : "IPv6",
                   isWebSock ? "web socket" : "socket", ipString));
      } else {
         Log(ASOCKPREFIX "Could not create %s listener socket, error %d: %s\n",
             addr.ss_family == AF_INET ? "IPv4" : "IPv6", *outError,
             AsyncSocket_Err2String(*outError));
      }
      free(ipString);
   } else {
      Log(ASOCKPREFIX "Could not resolve listener socket address.\n");
      if (outError) {
         *outError = ASOCKERR_LISTEN;
      }
   }

   return asock;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketListenerCreate --
 *
 *      Listens on specified address and/or port for all resolved socket
 *      families and accepts new connections. Fires the connect callback with
 *      new AsyncSocket object for each connection.
 *
 *      If address string is present and that string is not the "localhost"
 *      loopback, then we will listen on resolved address only.
 *
 *      If address string is NULL or is "localhost" we will listen on all
 *      address families that will resolve on the host.
 *
 *      If port requested is 0, we will let the system assign the first
 *      available port.
 *
 *      If address string is NULL and port requested is not 0, we will listen
 *      on any address for all resolved protocols for the port requested.
 *
 *      If address string is "localhost" and port is 0, we will use the first
 *      port we are given if the host supports multiple address families.
 *      If by chance we try to bind on a port that is available for one
 *      protocol and not the other, we will attempt a second time with the
 *      order of address families reversed.
 *
 *      If address string is NULL, port cannot be 0.
 *
 * Results:
 *      New AsyncSocket in listening state or NULL on error.
 *
 * Side effects:
 *      Creates new socket/s, binds and listens.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocketListenerCreate(const char *addrStr,                // IN: optional
                          unsigned int port,                  // IN: optional
                          AsyncSocketConnectFn connectFn,     // IN
                          void *clientData,                   // IN
                          AsyncSocketPollParams *pollParams,  // IN
                          Bool isWebSock,                     // IN
                          Bool webSockUseSSL,                 // IN
                          int *outError)                      // OUT: optional
{
   if (addrStr != NULL && *addrStr != '\0' &&
       Str_Strcmp(addrStr, "localhost")) {
      return AsyncSocketListenerCreateImpl(addrStr, port, AF_UNSPEC, connectFn,
                                           clientData, pollParams, FALSE,
                                           FALSE, outError);
   } else {
      Bool localhost = addrStr != NULL && !Str_Strcmp(addrStr, "localhost");
      unsigned int tempPort = port;
      AsyncSocket *asock6 = NULL;
      AsyncSocket *asock4 = NULL;
      int tempError4;
      int tempError6;

      asock6 = AsyncSocketListenerCreateImpl(addrStr, port, AF_INET6,
                                             connectFn, clientData, pollParams,
                                             isWebSock, webSockUseSSL,
                                             &tempError6);

      if (localhost && port == 0) {
         tempPort = AsyncSocket_GetPort(asock6);
         if (tempPort == MAX_UINT32) {
            Log(ASOCKPREFIX
                "Could not resolve IPv6 listener socket port number.\n");
            tempPort = port;
         }
      }

      asock4 = AsyncSocketListenerCreateImpl(addrStr, tempPort, AF_INET,
                                             connectFn, clientData, pollParams,
                                             isWebSock, webSockUseSSL,
                                             &tempError4);

      if (localhost && port == 0 && tempError4 == ASOCKERR_BINDADDRINUSE) {
         Log(ASOCKPREFIX "Failed to reuse IPv6 localhost port number for IPv4 "
             "listener socket.\n");
         AsyncSocket_Close(asock6);

         tempError4 = ASOCKERR_SUCCESS;
         asock4 = AsyncSocketListenerCreateImpl(addrStr, port, AF_INET,
                                                connectFn, clientData,
                                                pollParams, isWebSock,
                                                webSockUseSSL, &tempError4);

         tempPort = AsyncSocket_GetPort(asock4);
         if (tempPort == MAX_UINT32) {
            Log(ASOCKPREFIX
                "Could not resolve IPv4 listener socket port number.\n");
            tempPort = port;
         }

         tempError6 = ASOCKERR_SUCCESS;
         asock6 = AsyncSocketListenerCreateImpl(addrStr, tempPort, AF_INET6,
                                                connectFn, clientData,
                                                pollParams, isWebSock,
                                                webSockUseSSL, &tempError6);

         if (!asock6 && tempError6 == ASOCKERR_BINDADDRINUSE) {
            Log(ASOCKPREFIX "Failed to reuse IPv4 localhost port number for "
                "IPv6 listener socket.\n");
            AsyncSocket_Close(asock4);
         }
      }

      if (asock6 && asock4) {
         AsyncSocket *asock;

         asock = AsyncSocketCreate(NULL);
         asock->state = AsyncSocketListening;
         asock->asockType = ASYNCSOCKET_TYPE_SOCKET;
         asock->listenAsock6 = asock6;
         asock->listenAsock4 = asock4;

         return asock;
      } else if (asock6) {
         return asock6;
      } else if (asock4) {
         return asock4;
      }

      if (outError) {
         /* Client only gets one error and the one for IPv6 is favored. */
         if (!asock6) {
            *outError = tempError6;
         } else if (!asock4) {
            *outError = tempError4;
         } else {
            *outError = ASOCKERR_LISTEN;
         }
      }

      return NULL;
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketListenerCreateLoopback --
 *
 *      Listens on loopback interface and port for all resolved socket
 *      families and accepts new connections. Fires the connect callback with
 *      new AsyncSocket object for each connection.
 *
 * Results:
 *      New AsyncSocket in listening state or NULL on error.
 *
 * Side effects:
 *      Creates new socket/s, binds and listens.
 *
 *----------------------------------------------------------------------------
 */

static AsyncSocket *
AsyncSocketListenerCreateLoopback(unsigned int port,                  // IN
                                  AsyncSocketConnectFn connectFn,     // IN
                                  void *clientData,                   // IN
                                  AsyncSocketPollParams *pollParams,  // IN
                                  Bool isWebSock,                     // IN
                                  Bool webSockUseSSL,                 // IN
                                  int *outError)                      // OUT: optional
{
   AsyncSocket *asock6 = NULL;
   AsyncSocket *asock4 = NULL;
   int tempError4;
   int tempError6;

   /*
    * "localhost6" does not work on Windows. "localhost" does
    * not work for IPv6 on old Linux versions like 2.6.18. So,
    * using IP address for both the cases to be consistent.
    */
   asock6 = AsyncSocketListenerCreateImpl("::1", port, AF_INET6,
                                          connectFn, clientData, pollParams,
                                          isWebSock, webSockUseSSL,
                                          &tempError6);

   asock4 = AsyncSocketListenerCreateImpl("127.0.0.1", port, AF_INET,
                                          connectFn, clientData, pollParams,
                                          isWebSock, webSockUseSSL,
                                          &tempError4);

   if (asock6 && asock4) {
      AsyncSocket *asock;

      asock = AsyncSocketCreate(NULL);
      asock->state = AsyncSocketListening;
      asock->asockType = ASYNCSOCKET_TYPE_SOCKET;
      asock->listenAsock6 = asock6;
      asock->listenAsock4 = asock4;

      return asock;
   } else if (asock6) {
      return asock6;
   } else if (asock4) {
      return asock4;
   }

   if (outError) {
      /* Client only gets one error and the one for IPv6 is favored. */
      if (!asock6) {
         *outError = tempError6;
      } else if (!asock4) {
         *outError = tempError4;
      } else {
         *outError = ASOCKERR_LISTEN;
      }
   }

   return NULL;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_Listen --
 *
 *      Listens on specified address and/or port for all resolved socket
 *      families and accepts new connections. Fires the connect callback with
 *      new AsyncSocket object for each connection.
 *
 *      If address string is present and that string is not the "localhost"
 *      loopback, then we will listen on resolved address only.
 *
 *      If address string is NULL or is "localhost" we will listen on all
 *      address families that will resolve on the host.
 *
 *      If port requested is 0, we will let the system assign the first
 *      available port.
 *
 *      If address string is NULL and port requested is not 0, we will listen
 *      on any address for all resolved protocols for the port requested.
 *
 *      If address string is "localhost" and port is 0, we will use the first
 *      port we are given if the host supports multiple address families.
 *      If by chance we try to bind on a port that is available for one
 *      protocol and not the other, we will attempt a second time with the
 *      order of address families reversed.
 *
 *      If address string is NULL, port cannot be 0.
 *
 * Results:
 *      New AsyncSocket in listening state or NULL on error.
 *
 * Side effects:
 *      Creates new socket/s, binds and listens.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocket_Listen(const char *addrStr,                // IN: optional
                   unsigned int port,                  // IN: optional
                   AsyncSocketConnectFn connectFn,     // IN
                   void *clientData,                   // IN
                   AsyncSocketPollParams *pollParams,  // IN
                   int *outError)                      // OUT: optional
{
   return AsyncSocketListenerCreate(addrStr, port, connectFn, clientData,
                                    pollParams, FALSE, FALSE, outError);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_ListenLoopback --
 *
 *      Listens on loopback interface and port for all resolved socket
 *      families and accepts new connections. Fires the connect callback with
 *      new AsyncSocket object for each connection.
 *
 *      If port requested is 0, we will let the system assign the first
 *      available port.
 *
 * Results:
 *      New AsyncSocket in listening state or NULL on error.
 *
 * Side effects:
 *      Creates new socket/s, binds and listens.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocket_ListenLoopback(unsigned int port,                  // IN
                           AsyncSocketConnectFn connectFn,     // IN
                           void *clientData,                   // IN
                           AsyncSocketPollParams *pollParams,  // IN
                           int *outError)                      // OUT: optional
{
   return AsyncSocketListenerCreateLoopback(port, connectFn, clientData,
                                            pollParams, FALSE, FALSE, outError);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_ListenVMCI --
 *
 *      Listens on the specified port and accepts new connections. Fires the
 *      connect callback with new AsyncSocket object for each connection.
 *
 * Results:
 *      New AsyncSocket in listening state or NULL on error.
 *
 * Side effects:
 *      Creates new socket, binds and listens.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocket_ListenVMCI(unsigned int cid,                  // IN
                       unsigned int port,                 // IN
                       AsyncSocketConnectFn connectFn,    // IN
                       void *clientData,                  // IN
                       AsyncSocketPollParams *pollParams, // IN
                       int *outError)                     // OUT
{
   struct sockaddr_vm addr;
   AsyncSocket *asock;
   int vsockDev = -1;

   memset(&addr, 0, sizeof addr);
   addr.svm_family = VMCISock_GetAFValueFd(&vsockDev);
   addr.svm_cid = cid;
   addr.svm_port = port;

   asock = AsyncSocketListenImpl((struct sockaddr_storage *)&addr, sizeof addr,
                                 connectFn, clientData, pollParams, FALSE,
                                 FALSE, outError);

   VMCISock_ReleaseAFValueFd(vsockDev);
   return asock;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketInit --
 *
 *      This is an internal routine that sets up a SOCK_STREAM (TCP) socket.
 *
 * Results:
 *      New AsyncSocket or NULL on error.
 *
 * Side effects:
 *      Creates new socket.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocketInit(int socketFamily,                  // IN
                AsyncSocketPollParams *pollParams, // IN
                int *outError)                     // OUT
{
   AsyncSocket *asock = NULL;
   int error = ASOCKERR_GENERIC;
   int sysErr;
   int fd;

   /*
    * Create a new socket
    */

   if ((fd = socket(socketFamily, SOCK_STREAM, 0)) == -1) {
      sysErr = ASOCK_LASTERROR();
      Warning(ASOCKPREFIX "could not create new socket, error %d: %s\n",
              sysErr, Err_Errno2String(sysErr));
      goto errorNoFd;
   }

   /*
    * Wrap it with an asock object
    */

   if ((asock = AsyncSocket_AttachToFd(fd, pollParams, &error)) == NULL) {
      goto error;
   }

   return asock;

error:
   SSLGeneric_close(fd);

errorNoFd:
   if (outError) {
      *outError = error;
   }

   return NULL;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketGetPort --
 *
 *      This is an internal routine that gets a port given an address.  The
 *      address must be in either AF_INET, AF_INET6 or AF_VMCI format.
 *
 * Results:
 *      Port number (in host byte order for INET).
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static unsigned int
AsyncSocketGetPort(struct sockaddr_storage *addr)
{
   ASSERT(NULL != addr);

   if (AF_INET == addr->ss_family) {
      return ntohs(((struct sockaddr_in *)addr)->sin_port);
   } else if (AF_INET6 == addr->ss_family) {
      return ntohs(((struct sockaddr_in6 *)addr)->sin6_port);
#ifndef _WIN32
   } else if (AF_UNIX == addr->ss_family) {
      return MAX_UINT32; // Not applicable
#endif
   } else {
#ifdef VMX86_DEBUG
      int vsockDev = -1;

      ASSERT(VMCISock_GetAFValueFd(&vsockDev) == addr->ss_family);
      VMCISock_ReleaseAFValueFd(vsockDev);

#endif
      return ((struct sockaddr_vm *)addr)->svm_port;
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_GetPort --
 *
 *      Given an AsyncSocket object, returns the port number associated with
 *      the requested address family's file descriptor if available.
 *
 * Results:
 *      Port number in host byte order. MAX_UINT32 on error.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

unsigned int
AsyncSocket_GetPort(AsyncSocket *asock)  // IN
{
   AsyncSocket *tempAsock;
   struct sockaddr_storage addr;
   socklen_t addrLen = sizeof addr;
   unsigned int ret = MAX_UINT32;

   if (asock->fd != -1) {
      tempAsock = asock;
   } else if (asock->listenAsock6 && asock->listenAsock6->fd != -1) {
      tempAsock = asock->listenAsock6;
   } else if (asock->listenAsock4 && asock->listenAsock4->fd != -1) {
      tempAsock = asock->listenAsock4;
   } else {
      return ret;
   }

   AsyncSocketLock(tempAsock);

   if (AsyncSocketGetAddr(tempAsock, AF_UNSPEC, &addr, &addrLen) ==
       ASOCKERR_SUCCESS) {
      ret = AsyncSocketGetPort(&addr);
   }

   AsyncSocketUnlock(tempAsock);

   return ret;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketOSVersionSupportsV4Mapped --
 *
 *      Determine if runtime environment supports IPv4-mapped IPv6 addressed
 *      and all the functionality needed to deal with this scenario.
 *
 * Results:
 *      Returns TRUE if supported.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static Bool
AsyncSocketOSVersionSupportsV4Mapped()
{
#ifdef _WIN32
   OSVERSIONINFOW osvi = {sizeof(OSVERSIONINFOW)};
   GetVersionExW(&osvi);
   /* Windows version is at least Vista or higher */
   return osvi.dwMajorVersion >= 6;
#else
   return TRUE;
#endif
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketBind --
 *
 *      This is an internal routine that binds a socket to a port.
 *
 * Results:
 *      Returns TRUE upon success, FALSE upon failure.
 *
 * Side effects:
 *      Socket is bound to a particular port.
 *
 *----------------------------------------------------------------------------
 */

Bool
AsyncSocketBind(AsyncSocket *asock,             // IN
                struct sockaddr_storage *addr,  // IN
                socklen_t addrLen,              // IN
                int *outError)                  // OUT
{
   int error = ASOCKERR_BIND;
   int sysErr;
   unsigned int port;

   ASSERT(NULL != asock);
   ASSERT(NULL != asock->sslSock);
   ASSERT(NULL != addr);

   port = AsyncSocketGetPort(addr);
   ASOCKLG0(asock, ("creating new listening socket on port %d\n", port));

#ifndef _WIN32
   /*
    * Don't ever use SO_REUSEADDR on Windows; it doesn't mean what you think
    * it means.
    */

   if (addr->ss_family == AF_INET || addr->ss_family == AF_INET6) {
      int reuse = port != 0;

      if (setsockopt(asock->fd, SOL_SOCKET, SO_REUSEADDR,
                     (const void *) &reuse, sizeof(reuse)) != 0) {
         sysErr = ASOCK_LASTERROR();
         Warning(ASOCKPREFIX "could not set SO_REUSEADDR, error %d: %s\n",
                 sysErr, Err_Errno2String(sysErr));
      }
   }
#else
   /*
    * Always set SO_EXCLUSIVEADDRUSE on Windows, to prevent other applications
    * from stealing this socket. (Yes, Windows is that stupid).
    */

   {
      int exclusive = 1;

      if (setsockopt(asock->fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
                     (const void *) &exclusive, sizeof(exclusive)) != 0) {
         sysErr = ASOCK_LASTERROR();
         Warning(ASOCKPREFIX "could not set SO_EXCLUSIVEADDRUSE, error %d: "
                 "%s\n", sysErr, Err_Errno2String(sysErr));
      }
   }
#endif

#if defined(IPV6_V6ONLY)
   /*
    * WINDOWS: By default V4MAPPED was not supported until Windows Vista.
    * IPV6_V6ONLY was disabled by default until Windows 7. So if we are binding
    * to a AF_INET6 socket and IPV6_V6ONLY existed, we need to turn it on no
    * matter what the setting is to disable V4 mapping.
    *
    * MAC OSX: Support for IPV6_V6ONLY can be found in 10.5+.
    *
    * LINUX: IPV6_V6ONLY was released after V4MAPPED was implemented. There is
    * no way to turn V4MAPPED off on those systems. The default behavior
    * differs from distro-to-distro so attempt to turn V4MAPPED off on all
    * systems that have IPV6_V6ONLY define. There is no good solution for the
    * case where we cannot enable IPV6_V6ONLY, if we error in this case and do
    * not have a IPv4 option then we render the application useless.
    * See AsyncSocketAcceptInternal for the IN6_IS_ADDR_V4MAPPED validation
    * for incomming addresses to close this loophole.
    */

   if (addr->ss_family == AF_INET6 && AsyncSocketOSVersionSupportsV4Mapped()) {
      int on = 1;

      if (setsockopt(asock->fd, IPPROTO_IPV6, IPV6_V6ONLY,
                     (const void *) &on, sizeof(on)) != 0) {
         Warning(ASOCKPREFIX "Cannot set IPV6_V6ONLY socket option.\n");
      }
   }
#else
#error No compiler definition for IPV6_V6ONLY
#endif

   /*
    * Bind to a port
    */

   if (bind(asock->fd, (struct sockaddr *)addr, addrLen) != 0) {
      sysErr = ASOCK_LASTERROR();
      if (sysErr == ASOCK_EADDRINUSE) {
         error = ASOCKERR_BINDADDRINUSE;
      }
      Warning(ASOCKPREFIX "Could not bind socket, error %d: %s\n", sysErr,
              Err_Errno2String(sysErr));
      goto error;
   }

   return TRUE;

error:
   SSL_Shutdown(asock->sslSock);
   free(asock);

   if (outError) {
      *outError = error;
   }

   return FALSE;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketListen --
 *
 *      This is an internal routine that calls listen() on a socket.
 *
 * Results:
 *      Returns TRUE upon success, FALSE upon failure.
 *
 * Side effects:
 *      Socket is in listening state.
 *
 *----------------------------------------------------------------------------
 */

Bool
AsyncSocketListen(AsyncSocket *asock,                // IN
                  AsyncSocketConnectFn connectFn,    // IN
                  void *clientData,                  // IN
                  int *outError)                     // OUT
{
   VMwareStatus pollStatus;
   int error;

   ASSERT(NULL != asock);
   ASSERT(NULL != asock->sslSock);

   if (!connectFn) {
      Warning(ASOCKPREFIX "invalid arguments to listen!\n");
      error = ASOCKERR_INVAL;
      goto error;
   }

   /*
    * Listen on the socket
    */

   if (listen(asock->fd, 5) != 0) {
      int sysErr = ASOCK_LASTERROR();
      Warning(ASOCKPREFIX "could not listen on socket, error %d: %s\n",
              sysErr, Err_Errno2String(sysErr));
      error = ASOCKERR_LISTEN;
      goto error;
   }

   /*
    * Register a read callback to fire each time the socket
    * is ready for accept.
    */

   AsyncSocketLock(asock);
   pollStatus = AsyncSocketPollAdd(asock, TRUE,
                                   POLL_FLAG_READ | POLL_FLAG_PERIODIC,
                                   AsyncSocketAcceptCallback);

   if (pollStatus != VMWARE_STATUS_SUCCESS) {
      ASOCKWARN(asock, ("could not register accept callback!\n"));
      error = ASOCKERR_POLL;
      AsyncSocketUnlock(asock);
      goto error;
   }
   asock->state = AsyncSocketListening;

   asock->connectFn = connectFn;
   asock->clientData = clientData;
   AsyncSocketUnlock(asock);

   return TRUE;

error:
   SSL_Shutdown(asock->sslSock);
   free(asock);

   if (outError) {
      *outError = error;
   }

   return FALSE;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketConnectImpl --
 *
 *      AsyncSocket AF_INET/AF_INET6 connect.
 *
 *      NOTE: This function can block.
 *
 * Results:
 *      AsyncSocket * on success and NULL on failure.
 *      On failure, error is returned in *outError.
 *
 * Side effects:
 *      Allocates an AsyncSocket, registers a poll callback.
 *
 *----------------------------------------------------------------------------
 */

static AsyncSocket *
AsyncSocketConnectImpl(int socketFamily,
                       const char *hostname,
                       unsigned int port,
                       AsyncSocketConnectFn connectFn,
                       void *clientData,
                       AsyncSocketConnectFlags flags,
                       AsyncSocketPollParams *pollParams,
                       int *outError)
{
   struct sockaddr_storage addr;
   int getaddrinfoError;
   int error;
   AsyncSocket *asock;
   char *ipString = NULL;
   socklen_t addrLen;

   /*
    * Resolve the hostname.  Handles dotted decimal strings, too.
    */

   getaddrinfoError = AsyncSocketResolveAddr(hostname, port, socketFamily,
                                             FALSE, &addr, &addrLen, &ipString);
   if (0 != getaddrinfoError) {
      Log(ASOCKPREFIX "Failed to resolve %s address '%s' and port %u\n",
          socketFamily == AF_INET ? "IPv4" : "IPv6", hostname, port);
      error = ASOCKERR_CONNECT;
      goto error;
   }

   Log(ASOCKPREFIX "creating new %s socket, connecting to %s (%s)\n",
       socketFamily == AF_INET ? "IPv4" : "IPv6", ipString, hostname);
   free(ipString);

   asock = AsyncSocketConnect(&addr, addrLen, connectFn, clientData,
                              AsyncSocketConnectCallback, flags, pollParams,
                              &error);
   if (!asock) {
      Warning(ASOCKPREFIX "%s connection attempt failed\n",
              socketFamily == AF_INET ? "IPv4" : "IPv6");
      error = ASOCKERR_CONNECT;
      goto error;
   }

   return asock;

error:
   if (outError) {
      *outError = error;
   }

   return NULL;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_Connect --
 *
 *      AsyncSocket connect. Connection is attempted with AF_INET socket
 *      family, when that fails AF_INET6 is attempted.
 *
 *      NOTE: This function can block.
 *
 * Results:
 *      AsyncSocket * on success and NULL on failure.
 *      On failure, error is returned in *outError.
 *
 * Side effects:
 *      Allocates an AsyncSocket, registers a poll callback.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocket_Connect(const char *hostname,
                    unsigned int port,
                    AsyncSocketConnectFn connectFn,
                    void *clientData,
                    AsyncSocketConnectFlags flags,
                    AsyncSocketPollParams *pollParams,
                    int *outError)
{
   int error = ASOCKERR_CONNECT;
   AsyncSocket *asock = NULL;

   if (!connectFn || !hostname) {
      error = ASOCKERR_INVAL;
      Warning(ASOCKPREFIX "invalid arguments to connect!\n");
      goto error;
   }

   asock = AsyncSocketConnectImpl(AF_INET, hostname, port, connectFn,
                                  clientData, flags, pollParams, &error);
   if (!asock) {
      asock = AsyncSocketConnectImpl(AF_INET6, hostname, port, connectFn,
                                     clientData, flags, pollParams, &error);
   }

error:
   if (!asock && outError) {
      *outError = error;
   }

   return asock;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_ConnectVMCI --
 *
 *      AsyncSocket AF_VMCI constructor. Connects to the specified cid:port,
 *      and passes the caller a valid asock via the callback once the
 *      connection has been established.
 *
 * Results:
 *      ASOCKERR_SUCCESS or ASOCKERR_GENERIC.
 *
 * Side effects:
 *      Allocates an AsyncSocket, registers a poll callback.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocket_ConnectVMCI(unsigned int cid,                  // IN
                        unsigned int port,                 // IN
                        AsyncSocketConnectFn connectFn,    // IN
                        void *clientData,                  // IN
                        AsyncSocketConnectFlags flags,     // IN
                        AsyncSocketPollParams *pollParams, // IN
                        int *outError)                     // OUT
{
   int vsockDev = -1;
   struct sockaddr_vm addr;
   AsyncSocket *asock;

   memset(&addr, 0, sizeof addr);
   addr.svm_family = VMCISock_GetAFValueFd(&vsockDev);
   addr.svm_cid = cid;
   addr.svm_port = port;

   Log(ASOCKPREFIX "creating new socket, connecting to %u:%u\n", cid, port);

   asock = AsyncSocketConnect((struct sockaddr_storage *)&addr,
                              sizeof addr, connectFn, clientData,
                              AsyncSocketConnectCallback, flags, pollParams,
                              outError);

   VMCISock_ReleaseAFValueFd(vsockDev);
   return asock;
}


#ifndef _WIN32
/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_ConnectUnixDomain --
 *
 *      AsyncSocket AF_UNIX constructor. Connects to the specified unix socket,
 *      and passes the caller a valid asock via the callback once the
 *      connection has been established.
 *
 * Results:
 *      ASOCKERR_SUCCESS or ASOCKERR_GENERIC.
 *
 * Side effects:
 *      Allocates an AsyncSocket, registers a poll callback.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocket_ConnectUnixDomain(const char *path,                  // IN
                              AsyncSocketConnectFn connectFn,    // IN
                              void *clientData,                  // IN
                              AsyncSocketConnectFlags flags,     // IN
                              AsyncSocketPollParams *pollParams, // IN
                              int *outError)                     // OUT
{
   struct sockaddr_un addr;
   AsyncSocket *asock;

   memset(&addr, 0, sizeof addr);
   addr.sun_family = AF_UNIX;

   if (strlen(path) + 1 > sizeof addr.sun_path) {
      Warning(ASOCKPREFIX "Path '%s' is too long for a unix domain socket!\n", path);
      return NULL;
   }
   Str_Strcpy(addr.sun_path, path, sizeof addr.sun_path);

   Log(ASOCKPREFIX "creating new socket, connecting to %s\n", path);

   asock = AsyncSocketConnect((struct sockaddr_storage *)&addr,
                              sizeof addr, connectFn, clientData,
                              AsyncSocketConnectCallback, flags, pollParams,
                              outError);

   return asock;
}
#endif


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketConnect --
 * AsyncSocketConnectWithAsock --
 *
 *      Internal AsyncSocket constructor.
 *
 * Results:
 *      ASOCKERR_SUCCESS or ASOCKERR_GENERIC.
 *
 * Side effects:
 *      Allocates an AsyncSocket, registers a poll callback.
 *
 *----------------------------------------------------------------------------
 */

static AsyncSocket *
AsyncSocketConnect(struct sockaddr_storage *addr,
                   socklen_t addrLen,
                   AsyncSocketConnectFn connectFn,
                   void *clientData,
                   PollerFunction internalConnectFn,
                   AsyncSocketConnectFlags flags,
                   AsyncSocketPollParams *pollParams,
                   int *outError)
{
   int fd;
   AsyncSocket *asock = NULL;
   int error = ASOCKERR_GENERIC;
   int sysErr;

   ASSERT(addr);

   if (!connectFn) {
      error = ASOCKERR_INVAL;
      Warning(ASOCKPREFIX "invalid arguments to connect!\n");
      goto error;
   }

   if (!internalConnectFn) {
      error = ASOCKERR_INVAL;
      Warning(ASOCKPREFIX "invalid arguments to connect!\n");
      goto error;
   }

   /*
    * Create a new IP socket
    */
   if ((fd = socket(addr->ss_family, SOCK_STREAM, 0)) == -1) {
      sysErr = ASOCK_LASTERROR();
      Warning(ASOCKPREFIX "failed to create socket, error %d: %s\n",
              sysErr, Err_Errno2String(sysErr));
      error = ASOCKERR_CONNECT;
      goto error;
   }

   /*
    * Wrap it with an asock
    */

   if ((asock = AsyncSocket_AttachToFd(fd, pollParams, &error)) == NULL) {
      SSLGeneric_close(fd);
      goto error;
   }

   return AsyncSocketConnectWithAsock(asock, addr, addrLen, connectFn,
                                      clientData, internalConnectFn,
                                      pollParams, outError);

error:
   if (outError) {
      *outError = error;
   }

   return NULL;
}

AsyncSocket *
AsyncSocketConnectWithAsock(AsyncSocket *asock,
                            struct sockaddr_storage *addr,
                            socklen_t addrLen,
                            AsyncSocketConnectFn connectFn,
                            void *clientData,
                            PollerFunction internalConnectFn,
                            AsyncSocketPollParams *pollParams,
                            int *outError)
{
   VMwareStatus pollStatus;
   int sysErr;
   int error = ASOCKERR_GENERIC;

   /*
    * Call connect(), which can either succeed immediately or return an error
    * indicating that the connection is in progress. In the latter case, we
    * can poll the fd for write to find out when the connection attempt
    * has succeeded (or failed). In either case, we want to invoke the
    * caller's connect callback from Poll rather than directly, so if the
    * connection succeeds immediately, we just schedule the connect callback
    * as a one-time (RTime) callback instead.
    */

   AsyncSocketLock(asock);
   if (connect(asock->fd, (struct sockaddr *)addr, addrLen) != 0) {
      if (ASOCK_LASTERROR() == ASOCK_ECONNECTING) {
         ASSERT(!(vmx86_server && addr->ss_family == AF_UNIX));
         ASOCKLOG(1, asock, ("registering write callback for socket connect\n"));
         pollStatus = AsyncSocketPollAdd(asock, TRUE, POLL_FLAG_WRITE,
                                         internalConnectFn);
      } else {
         sysErr = ASOCK_LASTERROR();
         Log(ASOCKPREFIX "connect failed, error %d: %s\n",
             sysErr, Err_Errno2String(sysErr));
         error = ASOCKERR_CONNECT;
         goto errorHaveAsock;
      }
   } else {
      ASOCKLOG(2, asock,
               ("socket connected, registering RTime callback for connect\n"));
      pollStatus = AsyncSocketPollAdd(asock, FALSE, 0,
                                      internalConnectFn, 0);
   }

   if (pollStatus != VMWARE_STATUS_SUCCESS) {
      ASOCKWARN(asock, ("failed to register callback in connect!\n"));
      error = ASOCKERR_POLL;
      goto errorHaveAsock;
   }

   asock->state = AsyncSocketConnecting;
   asock->connectFn = connectFn;
   asock->clientData = clientData;

   /* Store a copy of the sockaddr_storage so we can look it up later. */
   asock->remoteAddr = *addr;
   asock->remoteAddrLen = addrLen;

   AsyncSocketUnlock(asock);

   return asock;

errorHaveAsock:
   SSL_Shutdown(asock->sslSock);
   AsyncSocketUnlock(asock);
   free(asock);

   if (outError) {
      *outError = error;
   }

   return NULL;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketCreate --
 *
 *      AsyncSocket constructor for fields common to all AsyncSocket types.
 *
 * Results:
 *      New AsyncSocket object.
 *
 * Side effects:
 *      Allocates memory.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocketCreate(AsyncSocketPollParams *pollParams) // IN
{
   AsyncSocket *s;

   s = Util_SafeCalloc(1, sizeof *s);
   s->id = Atomic_ReadInc32(&nextid);
   s->state = AsyncSocketConnected;
   s->fd = -1;
   s->refCount = 1;
   s->inRecvLoop = FALSE;
   s->sendBufFull = FALSE;
   s->sendBufTail = &(s->sendBufList);
   s->passFd.fd = -1;

   if (pollParams) {
      s->pollParams = *pollParams;
   } else {
      s->pollParams.pollClass = POLL_CS_MAIN;
      s->pollParams.flags = 0;
      s->pollParams.lock = NULL;
      s->pollParams.iPoll = NULL;
   }

   return s;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_AttachToSSLSock --
 *
 *      AsyncSocket constructor. Wraps an existing SSLSock object with an
 *      AsyncSocket and returns the latter.
 *
 * Results:
 *      New AsyncSocket object or NULL on error.
 *
 * Side effects:
 *      Allocates memory, makes the underlying fd for the socket non-blocking.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocket_AttachToSSLSock(SSLSock sslSock,
                            AsyncSocketPollParams *pollParams,
                            int *outError)
{
   AsyncSocket *s;
   int fd;
   int error;

   ASSERT(sslSock);

   fd = SSL_GetFd(sslSock);

   if ((AsyncSocketMakeNonBlocking(fd)) != ASOCKERR_SUCCESS) {
      int sysErr = ASOCK_LASTERROR();
      Warning(ASOCKPREFIX "failed to make fd %d non-blocking!: %d, %s\n",
              fd, sysErr, Err_Errno2String(sysErr));
      error = ASOCKERR_GENERIC;
      goto error;
   }

   s = AsyncSocketCreate(pollParams);
   s->sslSock = sslSock;
   s->fd = fd;
   s->asockType = ASYNCSOCKET_TYPE_SOCKET;
   if (s->pollParams.iPoll == NULL) {
      s->vt = &asyncStreamSocketVTable;
   } else {
      s->vt = &asyncStreamSocketIPollVTable;
   }

   /* From now on socket is ours. */
   SSL_SetCloseOnShutdownFlag(sslSock);
   ASOCKLOG(1, s, ("new asock id %u attached to fd %d\n", s->id, s->fd));

   return s;

error:
   if (outError) {
      *outError = error;
   }

   return NULL;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_AttachToFd --
 *
 *      AsyncSocket constructor. Wraps a valid socket fd with an AsyncSocket
 *      object.
 *
 * Results:
 *      New AsyncSocket or NULL on error.
 *
 * Side effects:
 *      If function succeeds, fd is owned by AsyncSocket and should not be
 *      used (f.e. closed) anymore.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocket *
AsyncSocket_AttachToFd(int fd,
                       AsyncSocketPollParams *pollParams,
                       int *outError)
{
   SSLSock sslSock;
   AsyncSocket *asock;

   /*
    * Create a new SSL socket object with the current socket
    */

   if (!(sslSock = SSL_New(fd, FALSE))) {
      if (outError) {
         *outError = ENOMEM;
      }
      LOG(0, (ASOCKPREFIX "failed to create SSL socket object\n"));

      return NULL;
   }
   asock = AsyncSocket_AttachToSSLSock(sslSock, pollParams, outError);
   if (asock) {
      return asock;
   }
   SSL_Shutdown(sslSock);

   return NULL;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_UseNodelay --
 *
 *      Sets or unset TCP_NODELAY on the socket, which disables or
 *      enables Nagle's algorithm, respectively.
 *
 * Results:
 *      ASOCKERR_SUCCESS on success, ASOCKERR_GENERIC otherwise.
 *
 * Side Effects:
 *      Increased bandwidth usage for short messages on this socket
 *      due to TCP overhead, in exchange for lower latency.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_UseNodelay(AsyncSocket *asock,  // IN/OUT:
                       Bool nodelay)        // IN:
{
   int flag = nodelay ? 1 : 0;

   AsyncSocketLock(asock);
   if (setsockopt(asock->fd, IPPROTO_TCP, TCP_NODELAY,
                  (const void *) &flag, sizeof(flag)) != 0) {
      asock->genericErrno = Err_Errno();
      LOG(0, (ASOCKPREFIX "could not set TCP_NODELAY, error %d: %s\n",
              Err_Errno(), Err_ErrString()));
      AsyncSocketUnlock(asock);
      return ASOCKERR_GENERIC;
   } else {
      AsyncSocketUnlock(asock);
      return ASOCKERR_SUCCESS;
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_SetTCPTimeouts --
 *
 *      Allow caller to set a number of TCP-specific timeout
 *      parameters on the socket for the active connection.
 *
 *      Parameters:
 *      keepIdle --  The number of seconds a TCP connection must be idle before
 *                   keep-alive probes are sent.
 *      keepIntvl -- The number of seconds between TCP keep-alive probes once
 *                   they are being sent.
 *      keepCnt   -- The number of keep-alive probes to send before killing
 *                   the connection if no response is received from the peer.
 *
 * Results:
 *      ASOCKERR_SUCCESS on success, ASOCKERR_GENERIC otherwise.
 *
 * Side Effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

#ifdef VMX86_SERVER
int
AsyncSocket_SetTCPTimeouts(AsyncSocket *asock,  // IN/OUT:
                           int keepIdle,        // IN
                           int keepIntvl,       // IN
                           int keepCnt)         // IN
{
   int val;
   int opt;

   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   AsyncSocketLock(asock);

   val = keepIdle;
   opt = TCP_KEEPIDLE;
   if (setsockopt(asock->fd, IPPROTO_TCP, opt,
                  &val, sizeof val) != 0) {
      goto error;
   }

   val = keepIntvl;
   opt = TCP_KEEPINTVL;
   if (setsockopt(asock->fd, IPPROTO_TCP, opt,
                  &val, sizeof val) != 0) {
      goto error;
   }

   val = keepCnt;
   opt = TCP_KEEPCNT;
   if (setsockopt(asock->fd, IPPROTO_TCP, opt,
                  &val, sizeof val) != 0) {
      goto error;
   }

   AsyncSocketUnlock(asock);
   return ASOCKERR_SUCCESS;

error:
   asock->genericErrno = Err_Errno();
   LOG(0, (ASOCKPREFIX "could not set TCP Timeout %d, error %d: %s\n",
           opt, Err_Errno(), Err_ErrString()));
   AsyncSocketUnlock(asock);
   return ASOCKERR_GENERIC;
}
#endif


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketRecvSocket --
 *
 *      Does the socket specific portion of a AsyncSocket_Recv call.
 *
 * Results:
 *      ASOCKERR_*.
 *
 * Side effects:
 *      Could register poll callback.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocketRecvSocket(AsyncSocket *asock, // IN:
                      void *buf,          // IN: unused
                      int len)            // IN: unused
{
   int retVal = ASOCKERR_SUCCESS;

   if (!asock->recvBuf && !asock->recvCb) {
      VMwareStatus pollStatus;

      /*
       * Register the Poll callback
       */

      ASOCKLOG(3, asock, ("installing recv poll callback\n"));

      pollStatus = AsyncSocketPollAdd(asock, TRUE,
                                      POLL_FLAG_READ | POLL_FLAG_PERIODIC,
                                      asock->vt->recvCallback);

      if (pollStatus != VMWARE_STATUS_SUCCESS) {
         ASOCKWARN(asock, ("failed to install recv callback!\n"));
         retVal = ASOCKERR_POLL;
         goto out;
      }
      asock->recvCb = TRUE;
   }

   if (AsyncSocketHasDataPending(asock) && !asock->inRecvLoop) {
      ASOCKLOG(0, asock, ("installing recv RTime poll callback\n"));
      if (Poll_CB_RTime(asock->vt->recvCallback,
                        asock, 0, FALSE, NULL) !=
          VMWARE_STATUS_SUCCESS) {
         retVal = ASOCKERR_POLL;
         goto out;
      }
   }

out:
   return retVal;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_Recv --
 * AsyncSocket_RecvPartial --
 *
 *      Registers a callback that will fire once the specified amount of data
 *      has been received on the socket.
 *
 *      In the case of AsyncSocket_RecvPartial, the callback is fired
 *      once all or part of the data has been received on the socket.
 *
 *      Data that was not retrieved at the last call of SSL_read() could still
 *      be buffered inside the SSL layer and will be retrieved on the next
 *      call to SSL_read(). However poll/select might not mark the socket as
 *      for reading since there might not be any data in the underlying network
 *      socket layer. Hence in the read callback, we keep spinning until all
 *      all the data buffered inside the SSL layer is retrieved before
 *      returning to the poll loop (See AsyncSocketFillRecvBuffer()).
 *
 *      However, we might not have come out of Poll in the first place, e.g.
 *      if this is the first call to AsyncSocket_Recv() after creating a new
 *      connection. In this situation, if there is buffered SSL data pending,
 *      we have to schedule an RTTime callback to force retrieval of the data.
 *      This could also happen if the client calls AsyncSocket_RecvBlocking,
 *      some data is left in the SSL layer, and the client then calls
 *      AsyncSocket_Recv. We use the inRecvLoop variable to detect and handle
 *      this condition, i.e., if inRecvLoop is FALSE, we need to schedule the
 *      RTime callback.
 *
 *      TCP usage:
 *      AsyncSocket_Recv(AsyncSocket *asock,
 *                       void *buf,
 *                       int len,
 *                       AsyncSocketRecvFn recvFn,
 *                       void *clientData)
 *
 * Results:
 *      ASOCKERR_*.
 *
 * Side effects:
 *      Could register poll callback.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_Recv(AsyncSocket *asock,
                        void *buf,
                        int len,
                        void *cb,
                        void *cbData)
{
   return AsyncSocketRecv(asock, buf, len, FALSE, cb, cbData);
}

int
AsyncSocket_RecvPartial(AsyncSocket *asock,
                        void *buf,
                        int len,
                        void *cb,
                        void *cbData)
{
   /*
    * Not yet implemented/tested on windows named pipe (though support
    * there should be easy).
    */
   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   return AsyncSocketRecv(asock, buf, len, TRUE, cb, cbData);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketRecv --
 *
 *      Internal function to implement AsyncSocket_Recv and
 *      AsyncSocket_RecvPartial.
 *
 * Results:
 *      ASOCKERR_*.
 *
 * Side effects:
 *      Could register poll callback.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocketRecv(AsyncSocket *asock,  // IN:
                void *buf,           // IN: unused
                int len,             // IN: unused
                Bool fireOnPartial,  // IN:
                void *cb,            // IN:
                void *cbData)        // IN:
{
   AsyncSocketRecvFn recvFn = NULL;
   void *clientData = NULL;
   int retVal;

   if (!asock) {
      Warning(ASOCKPREFIX "Recv called with invalid arguments!\n");

      return ASOCKERR_INVAL;
   }

   if (!asock->errorFn) {
      ASOCKWARN(asock, ("%s: no registered error handler!\n", __FUNCTION__));

      return ASOCKERR_INVAL;
   }

   recvFn = cb;
   clientData = cbData;

   /*
    * XXX We might want to allow passing NULL for the recvFn, to indicate that
    *     the client is no longer interested in reading from the socket. This
    *     would be useful e.g. for HTTP, where the client sends a request and
    *     then the client->server half of the connection is closed.
    */

   if (!buf || !recvFn || len <= 0) {
      Warning(ASOCKPREFIX "Recv called with invalid arguments!\n");

      return ASOCKERR_INVAL;
   }

   AsyncSocketLock(asock);

   if (asock->state != AsyncSocketConnected) {
      ASOCKWARN(asock, ("recv called but state is not connected!\n"));
      retVal = ASOCKERR_NOTCONNECTED;
      goto outHaveLock;
   }

   if (asock->inBlockingRecv) {
      ASOCKWARN(asock, ("Recv called while a blocking recv is pending.\n"));
      retVal = ASOCKERR_INVAL;
      goto outHaveLock;
   }

   if (asock->recvBuf && asock->recvPos != 0) {
      ASOCKWARN(asock, ("Recv called -- partially read buffer discarded.\n"));
   }

   ASSERT(asock->vt);
   ASSERT(asock->vt->recv);
   retVal = asock->vt->recv(asock, buf, len);
   if (retVal != ASOCKERR_SUCCESS) {
      goto outHaveLock;
   }

   asock->recvBuf = buf;
   asock->recvFn = recvFn;
   asock->recvLen = len;
   asock->recvFireOnPartial = fireOnPartial;
   asock->recvPos = 0;
   asock->clientData = clientData;
   retVal = ASOCKERR_SUCCESS;

outHaveLock:
   AsyncSocketUnlock(asock);
   return retVal;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_RecvPassedFd --
 *
 *      See AsyncSocket_Recv.  Besides that it allows for receiving one
 *      file descriptor...
 *
 * Results:
 *      ASOCKERR_*.
 *
 * Side effects:
 *      Could register poll callback.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_RecvPassedFd(AsyncSocket *asock,  // IN/OUT: socket
                         void *buf,           // OUT: buffer with data
                         int len,             // IN: length
                         void *cb,            // IN: completion calback
                         void *cbData)        // IN: callback's data
{
   int err;

   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   if (!asock) {
      Warning(ASOCKPREFIX "Recv called with invalid arguments!\n");

      return ASOCKERR_INVAL;
   }

   if (!asock->errorFn) {
      ASOCKWARN(asock, ("%s: no registered error handler!\n", __FUNCTION__));

      return ASOCKERR_INVAL;
   }

   AsyncSocketLock(asock);
   if (asock->passFd.fd != -1) {
      SSLGeneric_close(asock->passFd.fd);
      asock->passFd.fd = -1;
   }
   asock->passFd.expected = TRUE;

   err = AsyncSocket_Recv(asock, buf, len, cb, cbData);
   if (err != ASOCKERR_SUCCESS) {
      asock->passFd.expected = FALSE;
   }
   AsyncSocketUnlock(asock);

   return err;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketPoll --
 *
 *      Blocks on the specified socket until there's data pending or a
 *      timeout occurs.
 *
 *      If the specified socket is a dual stack listener, we will poll on all
 *      listening sockets and will return when one is ready with data for a
 *      connection. If both socket families happen to race with connect data,
 *      we will favor IPv6 for the return.
 *
 * Results:
 *      ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on system call
 *        failures
 *      ASOCKERR_TIMEOUT if we just didn't receive enough data.
 *
 * Side effects:
 *      None.
 *----------------------------------------------------------------------------
 */

static int
AsyncSocketPoll(AsyncSocket *s,          // IN:
                Bool read,               // IN:
                int timeoutMS,           // IN:
                AsyncSocket **outAsock)  // OUT:
{
#ifndef _WIN32
   struct pollfd p[2];
   int retval;
#else
   /*
    * We use select() to do this on Windows, since there ain't no poll().
    * Fortunately, select() doesn't have the 1024 fd value limit.
    */

   int retval;
   struct timeval tv;
   struct fd_set rwfds;
   struct fd_set exceptfds;
#endif
   AsyncSocket *asock[2];
   int numSock = 0;
   int i;

   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(*outAsock == NULL);

   if (read && s->fd == -1) {
      if (!s->listenAsock4 && !s->listenAsock6) {
         ASSERT(FALSE);
         return ASOCKERR_GENERIC;
      }

      if (s->listenAsock6 && s->listenAsock6->fd != -1) {
         asock[numSock++] = s->listenAsock6;
      }
      if (s->listenAsock4 && s->listenAsock4->fd != -1) {
         asock[numSock++] = s->listenAsock4;
      }
   } else {
      asock[numSock++] = s;
   }

   for (i = 0; i < numSock; i++) {
      if (read && SSL_Pending(asock[i]->sslSock)) {
         *outAsock = asock[i];
         return ASOCKERR_SUCCESS;
      }
   }

   while (1) {
#ifndef _WIN32
      for (i = 0; i < numSock; i++) {
         p[i].fd = asock[i]->fd;
         p[i].events = read ? POLLIN : POLLOUT;
      }

      retval = poll(p, numSock, timeoutMS);
#else
      tv.tv_sec = timeoutMS / 1000;
      tv.tv_usec = (timeoutMS % 1000) * 1000;

      FD_ZERO(&rwfds);
      FD_ZERO(&exceptfds);

      for (i = 0; i < numSock; i++) {
         FD_SET(asock[i]->fd, &rwfds);
         FD_SET(asock[i]->fd, &exceptfds);
      }

      retval = select(1, read ? &rwfds : NULL, read ? NULL : &rwfds,
                      &exceptfds, timeoutMS >= 0 ? &tv : NULL);
#endif

      switch (retval) {
      case 1:
      case 2: {
         Bool failed = FALSE;

#ifndef _WIN32
         for (i = 0; i < numSock; i++) {
            if (p[i].revents & (POLLERR | POLLNVAL)) {
               failed = TRUE;
            }
         }
#else
         for (i = 0; i < numSock; i++) {
            if (FD_ISSET(asock[i]->fd, &exceptfds)) {
               failed = TRUE;
            }
         }
#endif

         if (failed) {
            int sockErr = 0;
            int sysErr;
            int sockErrLen = sizeof sockErr;

            for (i = 0; i < numSock; i++) {
               if (getsockopt(asock[i]->fd, SOL_SOCKET, SO_ERROR,
                              (void *) &sockErr, (void *) &sockErrLen) == 0) {
                  if (sockErr) {
                     asock[i]->genericErrno = sockErr;
                     ASOCKLG0(asock[i],
                              ("%s: Socket error lookup returned %d: %s\n",
                               __FUNCTION__, sockErr,
                               Err_Errno2String(sockErr)));
                  }
               } else {
                  sysErr = ASOCK_LASTERROR();
                  asock[i]->genericErrno = sysErr;
                  ASOCKLG0(asock[i],
                           ("%s: Last socket error %d: %s\n",
                            __FUNCTION__, sysErr, Err_Errno2String(sysErr)));
               }
            }

            return ASOCKERR_GENERIC;
         }

         /*
          * If one socket is ready, and it wasn't in an exception state,
          * everything is ok. The socket is ready for reading/writing.
          */

#ifndef _WIN32
         for (i = 0; i < numSock; i++) {
            if (p[i].revents & (read ? POLLIN : POLLOUT)) {
               *outAsock = asock[i];
               return ASOCKERR_SUCCESS;
            }
         }
#else
         for (i = 0; i < numSock; i++) {
            if (FD_ISSET(asock[i]->fd, &rwfds)) {
               *outAsock = asock[i];
               return ASOCKERR_SUCCESS;
            }
         }
#endif

         ASOCKWARN(s, ("Failed to return a ready socket.\n"));
         return ASOCKERR_GENERIC;
      }
      case 0:
         /*
          * No sockets were ready within the specified time.
          */
         return ASOCKERR_TIMEOUT;

      case -1:
         if (ASOCK_LASTERROR() == EINTR) {
            /*
             * We were somehow interrupted by signal. Let's loop and retry.
             */

            continue;
         }
         s->genericErrno = ASOCK_LASTERROR();

         return ASOCKERR_GENERIC;
      default:
         NOT_REACHED();
      }
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_RecvBlocking --
 * AsyncSocket_RecvPartialBlocking --
 * AsyncSocket_SendBlocking --
 *
 *      Implement "blocking + timeout" operations on the socket. These are
 *      simple wrappers around the AsyncSocketBlockingWork function, which
 *      operates on the actual non-blocking socket, using poll to determine
 *      when it's ok to keep reading/writing. If we can't finish within the
 *      specified time, we give up and return the ASOCKERR_TIMEOUT error.
 *
 *      Note that if these are called from a callback and a lock is being
 *      used (pollParams.lock), the whole blocking operation takes place
 *      with that lock held.  Regardless, it is the caller's responsibility
 *      to make sure the synchronous and asynchronous operations do not mix.
 *
 * Results:
 *      ASOCKERR_SUCCESS if we finished the operation, ASOCKERR_* error codes
 *      otherwise.
 *
 * Side effects:
 *      Reads/writes the socket.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_RecvBlocking(AsyncSocket *s,
                         void *buf,
                         int len,
                         int *received,
                         int timeoutMS)
{
   return AsyncSocketBlockingWork(s, TRUE, buf, len, received, timeoutMS, FALSE);
}

int
AsyncSocket_RecvPartialBlocking(AsyncSocket *s,
                                void *buf,
                                int len,
                                int *received,
                                int timeoutMS)
{
   return AsyncSocketBlockingWork(s, TRUE, buf, len, received, timeoutMS, TRUE);
}

int
AsyncSocket_SendBlocking(AsyncSocket *s,
                         void *buf,
                         int len,
                         int *sent,
                         int timeoutMS)
{
   return AsyncSocketBlockingWork(s, FALSE, buf, len, sent, timeoutMS, FALSE);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketBlockingWork --
 *
 *      Try to complete the specified read/write operation within the
 *      specified time.
 *
 * Results:
 *      ASOCKERR_*.
 *
 * Side effects:
 *      None.
 *----------------------------------------------------------------------------
 */

int
AsyncSocketBlockingWork(AsyncSocket *s,  // IN:
                        Bool read,       // IN:
                        void *buf,       // IN/OUT:
                        int len,         // IN:
                        int *completed,  // OUT:
                        int timeoutMS,   // IN:
                        Bool partial)    // IN:
{
   VmTimeType now, done;
   int sysErr;

   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   if (s == NULL || buf == NULL || len <= 0) {
      Warning(ASOCKPREFIX "Recv called with invalid arguments!\n");

      return ASOCKERR_INVAL;
   }

   if (s->state != AsyncSocketConnected) {
      ASOCKWARN(s, ("recv called but state is not connected!\n"));

      return ASOCKERR_NOTCONNECTED;
   }

   if (completed) {
      *completed = 0;
   }
   now = Hostinfo_SystemTimerUS() / 1000;
   done = now + timeoutMS;
   do {
      int numBytes, error;
      AsyncSocket *asock = NULL;

      if ((error = AsyncSocketPoll(s, read, done - now, &asock)) !=
          ASOCKERR_SUCCESS) {
         return error;
      }

      ASSERT(asock == s);
      if ((numBytes = read ? SSL_Read(s->sslSock, buf, len)
                           : SSL_Write(s->sslSock, buf, len)) > 0) {
         if (completed) {
            *completed += numBytes;
         }
         len -= numBytes;
         if (len == 0 || partial) {
            return ASOCKERR_SUCCESS;
         }
         buf = (uint8*)buf + numBytes;
      } else if (numBytes == 0) {
         ASOCKLG0(s, ("blocking %s detected peer closed connection\n",
                      read ? "recv" : "send"));
         return ASOCKERR_REMOTE_DISCONNECT;
      } else if ((sysErr = ASOCK_LASTERROR()) != ASOCK_EWOULDBLOCK) {
         s->genericErrno = sysErr;
         ASOCKWARN(s, ("blocking %s error %d: %s\n", read ? "recv" : "send",
                       sysErr, Err_Errno2String(sysErr)));

         return ASOCKERR_GENERIC;
      }

      now = Hostinfo_SystemTimerUS() / 1000;
   } while ((now < done && timeoutMS > 0) || (timeoutMS < 0));

   return ASOCKERR_TIMEOUT;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketSendSocket --
 *
 *      Does the socket specific portion of a AsyncSocket_Send call.
 *
 * Results:
 *      ASOCKERR_*.
 *
 * Side effects:
 *      May register poll callback or perform I/O.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocketSendSocket(AsyncSocket *asock,      // IN:
                      Bool bufferListWasEmpty, // IN:
                      void *buf,               // IN: unused
                      int len)                 // IN: unused
{
   int retVal = ASOCKERR_SUCCESS;

   if (bufferListWasEmpty && !asock->sendCb) {
#ifdef _WIN32
      /*
       * If the send buffer list was empty, we schedule a one-time callback
       * to "prime" the output. This is necessary to support the FD_WRITE
       * network event semantic for sockets on Windows (see WSAEventSelect
       * documentation). The event won't signal unless a previous write() on
       * the socket failed with WSAEWOULDBLOCK, so we have to perform at
       * least one partial write before we can start polling for write.
       *
       * XXX: This can be a device callback once all poll implementations
       * know to get around this Windows quirk.  Both PollVMX and PollDefault
       * already make 0-byte send() to force WSAEWOULDBLOCK.
       */

      if (AsyncSocketPollAdd(asock, FALSE, 0, asock->vt->sendCallback, 0)
          != VMWARE_STATUS_SUCCESS) {
         retVal = ASOCKERR_POLL;
         return retVal;
      }
      asock->sendCbTimer = TRUE;
      asock->sendCb = TRUE;
#else
      if (asock->sendLowLatency) {
         /*
          * For low-latency sockets, call the callback directly from
          * this thread.  It is non-blocking and will schedule device
          * callbacks if necessary to complete the operation.
          *
          * Unfortunately we can't make this the default as current
          * consumers of asyncsocket are not expecting the completion
          * callback to be invoked prior to the call to
          * AsyncSocket_Send() returning.
          */
         asock->vt->sendCallback((void *)asock);
      } else {
         if (AsyncSocketPollAdd(asock, TRUE, POLL_FLAG_WRITE,
                                asock->vt->sendCallback)
             != VMWARE_STATUS_SUCCESS) {
            retVal = ASOCKERR_POLL;
            return retVal;
         }
         asock->sendCb = TRUE;
      }
#endif
   }

   return retVal;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_Send --
 *
 *      Queues the provided data for sending on the socket. If a send callback
 *      is provided, the callback is fired after the data has been written to
 *      the socket. Note that this only guarantees that the data has been
 *      copied to the transmit buffer, we make no promises about whether it
 *      has actually been transmitted, or received by the client, when the
 *      callback is fired.
 *
 *      Send callbacks should also be able to deal with being called if none
 *      or only some of the queued buffer has been transmitted, since the send
 *      callbacks for any remaining buffers are fired by AsyncSocket_Close().
 *      This condition can be detected by checking the len parameter passed to
 *      the send callback.
 *
 * Results:
 *      ASOCKERR_*.
 *
 * Side effects:
 *      May register poll callback or perform I/O.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_Send(AsyncSocket *asock,
                 void *buf,
                 int len,
                 AsyncSocketSendFn sendFn,
                 void *clientData)
{
   int retVal;
   SendBufList *listBeforeAppend = asock->sendBufList;
   Bool bufferListWasEmpty = FALSE;

   /*
    * Note: I think it should be fine to send with a length of zero and a
    * buffer of NULL or any other garbage value.  However the code
    * downstream of here is unprepared for it (silently misbehaves).  Hence
    * the <= zero check instead of just a < zero check.  --Jeremy.
    */

   if (!asock || !buf || len <= 0) {
      Warning(ASOCKPREFIX "Send called with invalid arguments! asynchSock: %p "
              "buffer: %p length: %d\n", asock, buf, len);

      return ASOCKERR_INVAL;
   }

   LOG(2, ("%s: sending %d bytes\n", __FUNCTION__, len));

   AsyncSocketLock(asock);

   if (asock->state != AsyncSocketConnected) {
      ASOCKWARN(asock, ("send called but state is not connected!\n"));
      retVal = ASOCKERR_NOTCONNECTED;
      goto outHaveLock;
   }

   ASSERT(asock->vt);
   ASSERT(asock->vt->prepareSend);
   retVal = asock->vt->prepareSend(asock, buf, len,
                                   sendFn, clientData, &bufferListWasEmpty);
   if (retVal != ASOCKERR_SUCCESS) {
      goto outUndoAppend;
   }

   ASSERT(asock->vt->send);
   retVal = asock->vt->send(asock, bufferListWasEmpty, buf, len);
   if (retVal != ASOCKERR_SUCCESS) {
      goto outUndoAppend;
   }

   retVal = ASOCKERR_SUCCESS;
   goto outHaveLock;

outUndoAppend:
   if (asock->sendBufList != listBeforeAppend) {
      SendBufList *appendedBuffer = asock->sendBufList;
      asock->sendBufList = listBeforeAppend;
      if (asock->sendBufList == NULL) {
         asock->sendBufTail = &(asock->sendBufList);
      }
      free(appendedBuffer);
   }

outHaveLock:
   AsyncSocketUnlock(asock);
   return retVal;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketResolveAddr --
 *
 *      Resolves a hostname and port.
 *
 * Results:
 *      Zero upon success.  This returns whatever getaddrinfo() returns.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */
int
AsyncSocketResolveAddr(const char *hostname,
                       unsigned int port,
                       int family,
                       Bool passive,
                       struct sockaddr_storage *addr,
                       socklen_t *addrLen,
                       char **addrString)
{
   struct addrinfo hints;
   struct addrinfo *aiTop = NULL;
   struct addrinfo *aiIterator = NULL;
   int getaddrinfoError = 0;
   char portString[PORT_STRING_LEN];

   ASSERT(NULL != addr);

   if (port > MAX_UINT16) {
      Log(ASOCKPREFIX "port number requested (%d) is out of range.\n", port);
      return EAI_SERVICE;
   }

   Str_Sprintf(portString, sizeof(portString), "%d", port);
   memset(&hints, 0, sizeof(hints));
   hints.ai_family = family;
   hints.ai_socktype = SOCK_STREAM;
   if (passive) {
      hints.ai_flags = AI_PASSIVE;
   }

   getaddrinfoError = Posix_GetAddrInfo(hostname, portString, &hints, &aiTop);
   if (0 != getaddrinfoError) {
      Log(ASOCKPREFIX "getaddrinfo failed for host %s: %s\n", hostname,
                      gai_strerror(getaddrinfoError));
      goto bye;
   }

   for (aiIterator = aiTop; NULL != aiIterator ; aiIterator =
                                                       aiIterator->ai_next) {
      if ((family == AF_UNSPEC && (aiIterator->ai_family == AF_INET ||
                                   aiIterator->ai_family == AF_INET6)) ||
          family == aiIterator->ai_family) {
         if (addrString != NULL) {
            char tempAddrString[ADDR_STRING_LEN];
            static char unknownAddr[] = "(Unknown)";
#if defined(_WIN32)
            DWORD len = ARRAYSIZE(tempAddrString);

            if (WSAAddressToString(aiIterator->ai_addr, aiIterator->ai_addrlen,
                                   NULL, tempAddrString, &len)) {
               *addrString = Util_SafeStrdup(unknownAddr);
            } else {
               *addrString = Util_SafeStrdup(tempAddrString);
            }
#else

            if (aiIterator->ai_family == AF_INET &&
                !inet_ntop(aiIterator->ai_family,
                     &(((struct sockaddr_in *)aiIterator->ai_addr)->sin_addr),
                     tempAddrString, INET6_ADDRSTRLEN)) {
               *addrString = Util_SafeStrdup(unknownAddr);
            } else if (aiIterator->ai_family == AF_INET6 &&
                       !inet_ntop(aiIterator->ai_family,
                  &(((struct sockaddr_in6 *)aiIterator->ai_addr)->sin6_addr),
                  tempAddrString, INET6_ADDRSTRLEN)) {
               *addrString = Util_SafeStrdup(unknownAddr);
            } else {
               *addrString = Str_SafeAsprintf(NULL, aiIterator->ai_family ==
                                                    AF_INET6 ? "[%s]:%u" :
                                                               "%s:%u",
                                              tempAddrString, port);
            }
#endif
         }

         memcpy(addr, aiIterator->ai_addr, aiIterator->ai_addrlen);
         *addrLen = aiIterator->ai_addrlen;

         break;
      }
   }

bye:
   if (NULL != aiTop) {
      Posix_FreeAddrInfo(aiTop);
   }

   return getaddrinfoError;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketCheckAndDispatchRecv --
 *
 *      Check if the recv buffer is full and dispatch the client callback.
 *
 *      Handles the possibility that the client registers a new receive buffer
 *      or closes the socket in their callback.
 *
 * Results:
 *      TRUE if the socket was closed or the receive was cancelled,
 *      FALSE if the caller should continue to try to receive data.
 *
 * Side effects:
 *      Could fire recv completion or trigger socket destruction.
 *
 *----------------------------------------------------------------------------
 */

Bool
AsyncSocketCheckAndDispatchRecv(AsyncSocket *s,  // IN
                                int *result)     // OUT
{
   ASSERT(s);
   ASSERT(result);
   ASSERT(s->recvFn);
   ASSERT(s->recvBuf);
   ASSERT(s->recvLen > 0);
   ASSERT(s->recvPos <= s->recvLen);

   if (s->recvPos == s->recvLen || s->recvFireOnPartial) {
      void *recvBuf = s->recvBuf;
      ASOCKLOG(3, s, ("recv buffer full, calling recvFn\n"));

      /*
       * We do this dance in case the handler frees the buffer (so
       * that there's no possible window where there are dangling
       * references here.  Obviously if the handler frees the buffer,
       * but them fails to register a new one, we'll put back the
       * dangling reference in the automatic reset case below, but
       * there's currently a limit to how far we go to shield clients
       * who use our API in a broken way.
       */

      s->recvBuf = NULL;
      s->recvFn(recvBuf, s->recvPos, s, s->clientData);
      if (s->state == AsyncSocketClosed) {
         ASOCKLG0(s, ("owner closed connection in recv callback\n"));
         *result = ASOCKERR_CLOSED;
         return TRUE;
      } else if (s->recvFn == NULL && s->recvLen == 0) {
         /*
          * Further recv is cancelled from within the last recvFn, see
          * AsyncSocket_CancelRecv(). So exit from the loop.
          */
         *result = ASOCKERR_SUCCESS;
         return TRUE;
      } else if (s->recvLen - s->recvPos == 0) {
         /* Automatically reset keeping the current handler */
         s->recvPos = 0;
         s->recvBuf = recvBuf;
      }
   }

   return FALSE;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketFillRecvBuffer --
 *
 *      Called when an asock has data ready to be read via the poll callback.
 *
 * Results:
 *      ASOCKERR_SUCCESS if everything worked,
 *      ASOCKERR_REMOTE_DISCONNECT if peer closed connection gracefully,
 *      ASOCKERR_CLOSED if trying to read from a closed socket.
 *      ASOCKERR_GENERIC for other errors.
 *
 * Side effects:
 *      Reads data, could fire recv completion or trigger socket destruction.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocketFillRecvBuffer(AsyncSocket *s)
{
   int recvd;
   int needed;
   int sysErr = 0;
   int result;
   int pending = 0;

   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(AsyncSocketIsLocked(s));
   ASSERT(s->state == AsyncSocketConnected);

   /*
    * When a socket has received all its desired content and FillRecvBuffer is
    * called again for the same socket, just return ASOCKERR_SUCCESS. The
    * reason we need this hack is that if a client which registered a receive
    * callback asynchronously later changes its mind to do it synchronously,
    * (e.g. aioMgr wait function), then FillRecvBuffer can be potentially be
    * called twice for the same receive event.
    */

   needed = s->recvLen - s->recvPos;
   if (!s->recvBuf && needed == 0) {
      return ASOCKERR_SUCCESS;
   }

   ASSERT(needed > 0);

   AsyncSocketAddRef(s);

   /*
    * See comment in AsyncSocket_Recv
    */

   s->inRecvLoop = TRUE;

   do {

      /*
       * Try to read the remaining bytes to complete the current recv request.
       */

      if (s->passFd.expected) {
         int fd;

         recvd = SSL_RecvDataAndFd(s->sslSock,
                                   (uint8 *) s->recvBuf + s->recvPos,
                                   needed, &fd);
         if (fd != -1) {
            s->passFd.fd = fd;
            s->passFd.expected = FALSE;
         }
      } else {
         recvd = SSL_Read(s->sslSock, (uint8 *) s->recvBuf + s->recvPos,
                          needed);
      }
      ASOCKLOG(3, s, ("need\t%d\trecv\t%d\tremain\t%d\n", needed, recvd,
                      needed - recvd));

      if (recvd > 0) {
         s->sslConnected = TRUE;
         s->recvPos += recvd;
         if (AsyncSocketCheckAndDispatchRecv(s, &result)) {
            goto exit;
         }
      } else if (recvd == 0) {
         ASOCKLG0(s, ("recv detected client closed connection\n"));
         /*
          * We treat this as an error so that the owner can detect closing
          * of connection by peer (via the error handler callback).
          */
         result = ASOCKERR_REMOTE_DISCONNECT;
         goto exit;
      } else if ((sysErr = ASOCK_LASTERROR()) == ASOCK_EWOULDBLOCK) {
         ASOCKLOG(4, s, ("recv would block\n"));
         break;
      } else {
         ASOCKLG0(s, ("recv error %d: %s\n", sysErr,
                      Err_Errno2String(sysErr)));
         s->genericErrno = sysErr;
         result = ASOCKERR_GENERIC;
         goto exit;
      }

      /*
       * At this point, s->recvFoo have been updated to point to the
       * next chained Recv buffer. By default we're done at this
       * point, but we may want to continue if the SSL socket has data
       * buffered in userspace already (SSL_Pending).
       */

      needed = s->recvLen - s->recvPos;
      ASSERT(needed > 0);

      pending = SSL_Pending(s->sslSock);
      needed = MIN(needed, pending);

   } while (needed);

   /*
    * Reach this point only when previous SSL_Pending returns 0 or
    * error is ASOCK_EWOULDBLOCK
    */

   ASSERT(pending == 0 || sysErr == ASOCK_EWOULDBLOCK);

   /*
    * Both a spurious wakeup and receiving any data even if it wasn't enough
    * to fire the callback are both success.  We were ready and now
    * presumably we aren't ready anymore.
    */

   result = ASOCKERR_SUCCESS;

exit:
   s->inRecvLoop = FALSE;
   AsyncSocketRelease(s, FALSE);

   return result;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketDispatchSentBuffer --
 *
 *      Pop off the head of the send buffer list and call its callback.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

void
AsyncSocketDispatchSentBuffer(AsyncSocket *s)
{
   /*
    * We're done with the current buffer, so pop it off and nuke it.
    * We do the list management *first*, so that the list is in a
    * consistent state.
    */

   SendBufList *head = s->sendBufList;
   SendBufList tmp = *head;

   s->sendBufList = head->next;
   if (s->sendBufList == NULL) {
      s->sendBufTail = &(s->sendBufList);
   }
   s->sendPos = 0;
   free(tmp.base64Buf);
   free(head);

   if (tmp.sendFn) {
      /*
       * XXX
       * Firing the send completion could trigger the socket's
       * destruction (since the callback could turn around and call
       * AsyncSocket_Close()). Since we're in the middle of a loop on
       * the asock's queue, we avoid a use-after-free by deferring
       * the actual freeing of the asock structure. This is shady but
       * it works. --rrdharan
       */

      tmp.sendFn(tmp.buf, tmp.len, s, tmp.clientData);
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketWriteBuffers --
 *
 *      The meat of AsyncSocket's sending functionality.  This function
 *      actually writes to the wire assuming there's space in the buffers
 *      for the socket.
 *
 * Results:
 *      ASOCKERR_SUCESS if everything worked, else ASOCKERR_GENERIC.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static int
AsyncSocketWriteBuffers(AsyncSocket *s)
{
   int result;

   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(AsyncSocketIsLocked(s));

   if (s->sendBufList == NULL) {
      return ASOCKERR_SUCCESS;     /* Vacuously true */
   }

   if (s->state != AsyncSocketConnected) {
      ASOCKWARN(s, ("write buffers on a disconnected socket (%d)!\n",
                    s->state));
      return ASOCKERR_GENERIC;
   }

   AsyncSocketAddRef(s);

   while (s->sendBufList && s->state == AsyncSocketConnected) {
      SendBufList *head = s->sendBufList;
      int error = 0;
      int sent = 0;
      int left = head->len - s->sendPos;
      int sizeToSend = head->len;

      if (head->base64Buf) {
         sent = SSL_Write(s->sslSock,
                          (uint8 *) head->base64Buf + s->sendPos, left);
      } else {
         sent = SSL_Write(s->sslSock,
                          (uint8 *) head->buf + s->sendPos, left);
      }
      ASOCKLOG(3, s, ("left\t%d\tsent\t%d\tremain\t%d\n",
                      left, sent, left - sent));
      if (sent > 0) {
         s->sendBufFull = FALSE;
         s->sslConnected = TRUE;
         if ((s->sendPos += sent) == sizeToSend) {
            AsyncSocketDispatchSentBuffer(s);
         }
      } else if (sent == 0) {
         ASOCKLG0(s, ("socket write() should never return 0.\n"));
         NOT_REACHED();
      } else if ((error = ASOCK_LASTERROR()) != ASOCK_EWOULDBLOCK) {
         ASOCKLG0(s, ("send error %d: %s\n", error, Err_Errno2String(error)));
         s->genericErrno = error;
         result = ASOCKERR_GENERIC;
         goto exit;
      } else {
         /*
          * Ran out of space to send. This is actually successful completion
          * (our contract obligates us to send as much data as space allows
          * and we fulfilled that).
          *
          * Indicate send buffer is full.
          */

         s->sendBufFull = TRUE;
         break;
      }
   }

   result = ASOCKERR_SUCCESS;

exit:
   AsyncSocketRelease(s, FALSE);

   return result;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketAcceptInternal --
 *
 *      The meat of 'accept'.  This function can be invoked either via a
 *      poll callback or blocking. We call accept to get the new socket fd,
 *      create a new asock, and call the newFn callback previously supplied
 *      by the call to AsyncSocket_Listen.
 *
 * Results:
 *      ASOCKERR_SUCCESS if everything works, else an error code.
 *      ASOCKERR_GENERIC is returned to hide accept() system call's
 *        nitty-gritty, it implies that we should try accept() again and not
 *        report error to client.
 *      ASOCKERR_ACCEPT to report accept operation's error to client.
 *
 * Side effects:
 *      Accepts on listening fd, creates new asock.
 *
 *----------------------------------------------------------------------------
 */

static int
AsyncSocketAcceptInternal(AsyncSocket *s)
{
   AsyncSocket *newsock;
   int sysErr;
   int fd;
   struct sockaddr_storage remoteAddr;
   socklen_t remoteAddrLen = sizeof remoteAddr;

   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(AsyncSocketIsLocked(s));
   ASSERT(s->state == AsyncSocketListening);

   if ((fd = accept(s->fd, (struct sockaddr *)&remoteAddr,
                    &remoteAddrLen)) == -1) {
      sysErr = ASOCK_LASTERROR();
      s->genericErrno = sysErr;
      if (sysErr == ASOCK_EWOULDBLOCK) {
         ASOCKWARN(s, ("spurious accept notification\n"));

         return ASOCKERR_GENERIC;
#ifndef _WIN32
         /*
          * This sucks. Linux accept() can return ECONNABORTED for connections
          * that closed before we got to actually call accept(), but Windows
          * just ignores this case. So we have to special case for Linux here.
          * We return ASOCKERR_GENERIC here because we still want to continue
          * accepting new connections.
          */

      } else if (sysErr == ECONNABORTED) {
         ASOCKLG0(s, ("accept: new connection was aborted\n"));

         return ASOCKERR_GENERIC;
#endif
      } else {
         ASOCKWARN(s, ("accept failed on fd %d, error %d: %s\n",
                       s->fd, sysErr, Err_Errno2String(sysErr)));

         return ASOCKERR_ACCEPT;
      }
   }

   if (remoteAddr.ss_family == AF_INET6 &&
       AsyncSocketOSVersionSupportsV4Mapped()) {
      struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&remoteAddr;

      /*
       * Remote address should not be a V4MAPPED address. Validate for the rare
       * case that IPV6_V6ONLY is not defined and V4MAPPED is enabled by
       * default when setting up socket listener.
       */

      if (IN6_IS_ADDR_V4MAPPED(&(addr6->sin6_addr))) {
         ASOCKWARN(s, ("accept rejected on fd %d due to a IPv4-mapped IPv6 "
                       "remote connection address.\n", s->fd));
         SSLGeneric_close(fd);

         return ASOCKERR_ACCEPT;
      }
   }

   newsock = AsyncSocket_AttachToFd(fd, &s->pollParams, NULL);
   if (!newsock) {
      SSLGeneric_close(fd);

      return ASOCKERR_ACCEPT;
   }

   newsock->remoteAddr = remoteAddr;
   newsock->remoteAddrLen = remoteAddrLen;
   newsock->state = AsyncSocketConnected;
   newsock->vt = s->vt;

   ASSERT(s->vt);
   ASSERT(s->vt->dispatchConnect);
   s->vt->dispatchConnect(s, newsock);

   return ASOCKERR_SUCCESS;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketConnectInternal --
 *
 *      The meat of connect.  This function is invoked either via a poll
 *      callback or the blocking API and verifies that connect() succeeded
 *      or reports is failure.  On success we call the registered 'new
 *      connection' function.
 *
 * Results:
 *      ASOCKERR_SUCCESS if it all worked out or ASOCKERR_GENERIC.
 *
 * Side effects:
 *      Creates new asock, fires newFn callback.
 *
 *----------------------------------------------------------------------------
 */

static int
AsyncSocketConnectInternal(AsyncSocket *s)
{
   int optval = 0, optlen = sizeof optval, sysErr;

   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(AsyncSocketIsLocked(s));
   ASSERT(s->state == AsyncSocketConnecting);

   /* Remove when bug 859728 is fixed */
   if (vmx86_server && s->remoteAddr.ss_family == AF_UNIX) {
      goto done;
   }

   if (getsockopt(s->fd, SOL_SOCKET, SO_ERROR,
                  (void *) &optval, (void *)&optlen) != 0) {
      sysErr = ASOCK_LASTERROR();
      s->genericErrno = sysErr;
      Warning(ASOCKPREFIX "getsockopt for connect on fd %d failed with "
              "error %d : %s\n", s->fd, sysErr, Err_Errno2String(sysErr));

      return ASOCKERR_GENERIC;
   }

   if (optval != 0) {
      s->genericErrno = optval;
      ASOCKLOG(1, s, ("connection SO_ERROR: %s\n", Err_Errno2String(optval)));

      return ASOCKERR_GENERIC;
   }

   s->localAddrLen = sizeof s->localAddr;
   if (getsockname(s->fd, (struct sockaddr *)&s->localAddr,
                   &s->localAddrLen) != 0) {
      sysErr = ASOCK_LASTERROR();
      s->genericErrno = sysErr;
      Warning(ASOCKPREFIX "getsockname for connect on fd %d failed with "
              "error %d: %s\n", s->fd, sysErr, Err_Errno2String(sysErr));

      return ASOCKERR_GENERIC;
   }

done:
   s->state = AsyncSocketConnected;
   s->connectFn(s, s->clientData);

   return ASOCKERR_SUCCESS;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_GetGenericErrno --
 *
 *      Used when an ASOCKERR_GENERIC is returned due to a system error.
 *      The errno that was returned by the system is stored in the asock
 *      struct and returned to the user in this function.
 *
 *      XXX: This function is not thread-safe.  The errno should be returned
 *      in a parameter to any function that can return ASOCKERR_GENERIC.
 *
 * Results:
 *      int error code
 *
 * Side effects:
 *      None
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_GetGenericErrno(AsyncSocket *s)  // IN:
{
   ASSERT(s);

   return s->genericErrno;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_WaitForConnection --
 *
 *      Spins a socket currently listening or connecting until the
 *      connection completes or the allowed time elapses.
 *
 * Results:
 *      ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on failures, and
 *      ASOCKERR_TIMEOUT if nothing happened in the allotted time.
 *
 * Side effects:
 *      None.
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_WaitForConnection(AsyncSocket *s,  // IN:
                              int timeoutMS)   // IN:
{
   Bool read = FALSE;
   int error;
   VmTimeType now, done;
   Bool removed = FALSE;

   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   AsyncSocketLock(s);

   if (s->state == AsyncSocketConnected) {
      error = ASOCKERR_SUCCESS;
      AsyncSocketUnlock(s);
      goto out;
   }

   if (s->state != AsyncSocketListening &&
       s->state != AsyncSocketConnecting) {
      error = ASOCKERR_GENERIC;
      AsyncSocketUnlock(s);
      goto out;
   }

   read = s->state == AsyncSocketListening;

   /*
    * For listening sockets, unregister AsyncSocketAcceptCallback before
    * starting polling and re-register before returning.
    *
    * ConnectCallback() is either registered as a device or rtime callback
    * depending on the prior return value of connect(). So we try to remove it
    * from both.
    */
   if (read) {
      if (s->fd == -1) {
         if (s->listenAsock4) {
            AsyncSocketLock(s->listenAsock4);
            AsyncSocketCancelListenCbSocket(s->listenAsock4);
            AsyncSocketUnlock(s->listenAsock4);
         }
         if (s->listenAsock6) {
            AsyncSocketLock(s->listenAsock6);
            AsyncSocketCancelListenCbSocket(s->listenAsock6);
            AsyncSocketUnlock(s->listenAsock6);
         }
      } else {
         AsyncSocketCancelListenCbSocket(s);
      }

      removed = TRUE;
   } else {
      removed = AsyncSocketPollRemove(s, TRUE, POLL_FLAG_WRITE,
                                      AsyncSocketConnectCallback)
         || AsyncSocketPollRemove(s, FALSE, 0, AsyncSocketConnectCallback);
      ASSERT(removed);
   }

   AsyncSocketUnlock(s);

   now = Hostinfo_SystemTimerUS() / 1000;
   done = now + timeoutMS;

   do {
      AsyncSocket *asock = NULL;

      if ((error = AsyncSocketPoll(s, read,
                                   done - now, &asock)) != ASOCKERR_SUCCESS) {
         goto out;
      }

      AsyncSocketLock(asock);

      now = Hostinfo_SystemTimerUS() / 1000;

      if (read) {
         if (AsyncSocketAcceptInternal(asock) != ASOCKERR_SUCCESS) {
            ASOCKLG0(s, ("wait for connection: accept failed\n"));

            /*
             * Just fall through, we'll loop and try again as long as we still
             * have time remaining.
             */

         } else {
            error = ASOCKERR_SUCCESS;
            AsyncSocketUnlock(asock);
            goto out;
         }
      } else {
         error = AsyncSocketConnectInternal(asock);
         AsyncSocketUnlock(asock);
         goto out;
      }

      AsyncSocketUnlock(asock);
   } while ((now < done && timeoutMS > 0) || (timeoutMS < 0));

   error = ASOCKERR_TIMEOUT;

out:
   if (read && removed) {
      if (s->fd == -1) {
         if (s->listenAsock4 && s->listenAsock4->state != AsyncSocketClosed) {
            AsyncSocketLock(s->listenAsock4);
            if (!AsyncSocketAddListenCbSocket(s->listenAsock4)) {
               error = ASOCKERR_POLL;
            }
            AsyncSocketUnlock(s->listenAsock4);
         }

         if (s->listenAsock6 && s->listenAsock6->state != AsyncSocketClosed) {
            AsyncSocketLock(s->listenAsock6);
            if (!AsyncSocketAddListenCbSocket(s->listenAsock6)) {
               error = ASOCKERR_POLL;
            }
            AsyncSocketUnlock(s->listenAsock6);
         }
      } else if (s->state != AsyncSocketClosed) {
         AsyncSocketLock(s);
         if (!AsyncSocketAddListenCbSocket(s)) {
            error = ASOCKERR_POLL;
         }
         AsyncSocketUnlock(s);
      }
   }

   return error;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_DoOneMsg --
 *
 *      Spins a socket until the specified amount of time has elapsed or
 *      data has arrived / been sent.
 *
 * Results:
 *      ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on system call
 *         failures
 *      ASOCKERR_TIMEOUT if nothing happened in the allotted time.
 *
 * Side effects:
 *      None.
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_DoOneMsg(AsyncSocket *s, Bool read, int timeoutMS)
{
   int retVal;
   AsyncSocket *asock = NULL;

   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   if (!s) {
      Warning(ASOCKPREFIX "DoOneMsg called with invalid paramters.\n");
      return ASOCKERR_INVAL;
   }

   if (read) {
      /*
       * Bug 158571: There could other threads polling on the same asyncsocket.
       * If two threads land up polling  on the same socket at the same time,
       * the first thread to be scheduled reads the data from the socket,
       * while the second one blocks infinitely. This hangs the VM. To prevent
       * this, we temporarily remove the poll callback and then reinstate it
       * after reading the data.
       */

      Bool removed;

      AsyncSocketLock(s);
      ASSERT(s->state == AsyncSocketConnected);
      ASSERT(s->recvCb); /* We are supposed to call someone... */
      AsyncSocketAddRef(s);
      removed = AsyncSocketPollRemove(s, TRUE,
                                      POLL_FLAG_READ | POLL_FLAG_PERIODIC,
                                      s->vt->recvCallback);
      ASSERT(removed || s->pollParams.iPoll);

      s->inBlockingRecv++;
      AsyncSocketUnlock(s); /* We may sleep in poll. */
      retVal = AsyncSocketPoll(s, read, timeoutMS, &asock);
      AsyncSocketLock(s);
      s->inBlockingRecv--;
      if (retVal != ASOCKERR_SUCCESS) {
         if (retVal == ASOCKERR_GENERIC) {
            ASOCKWARN(s, ("%s: failed to poll on the socket during read.\n",
                          __FUNCTION__));
         }
      } else {
         ASSERT(asock == s);
         retVal = AsyncSocketFillRecvBuffer(s);
      }

      /*
       * If socket got closed in AsyncSocketFillRecvBuffer, we cannot add poll
       * callback - AsyncSocket_Close() would remove it if we would not remove
       * it above.
       */

      if (s->state != AsyncSocketClosed) {
         VMwareStatus pollStatus;

         ASSERT(s->refCount > 1); /* We should not be last user of socket */
         ASSERT(s->state == AsyncSocketConnected);
         ASSERT(s->recvCb); /* Still interested in callback. */
         pollStatus = AsyncSocketPollAdd(s, TRUE,
                                         POLL_FLAG_READ | POLL_FLAG_PERIODIC,
                                         s->vt->recvCallback);

         if (pollStatus != VMWARE_STATUS_SUCCESS) {
            ASOCKWARN(s, ("failed to install recv callback!\n"));
            AsyncSocketRelease(s, TRUE);

            retVal = ASOCKERR_POLL;
            goto out;
         }
      }
      /* This may destroy socket s if it is in AsyncSocketClosed state now. */
      AsyncSocketRelease(s, TRUE);
   } else {
      if ((retVal = AsyncSocketPoll(s, read, timeoutMS, &asock)) !=
          ASOCKERR_SUCCESS) {
         if (retVal == ASOCKERR_GENERIC) {
            ASOCKWARN(s, ("%s: failed to poll on the socket during write.\n",
                          __FUNCTION__));
         }
      } else {
         ASSERT(asock == s);
         AsyncSocketLock(s);
         retVal = AsyncSocketWriteBuffers(s);
         AsyncSocketUnlock(s);
      }
   }

out:
   return retVal;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_Flush --
 *
 *      Try to send any pending out buffers until we run out of buffers, or
 *      the timeout expires.
 *
 * Results:
 *      ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on system call
 *      failures, and ASOCKERR_TIMEOUT if we couldn't send enough data
 *      before the timeout expired.
 *
 * Side effects:
 *      None.
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_Flush(AsyncSocket *s, int timeoutMS)
{
   VmTimeType now, done;
   int retVal;

   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   if (s == NULL) {
      Warning(ASOCKPREFIX "Flush called with invalid arguments!\n");

      return ASOCKERR_INVAL;
   }

   AsyncSocketLock(s);
   AsyncSocketAddRef(s);

   if (s->state != AsyncSocketConnected) {
      ASOCKWARN(s, ("flush called but state is not connected!\n"));
      retVal = ASOCKERR_INVAL;
      goto outHaveLock;
   }

   now = Hostinfo_SystemTimerUS() / 1000;
   done = now + timeoutMS;

   while (s->sendBufList) {
      AsyncSocket *asock = NULL;

      AsyncSocketUnlock(s); /* We may sleep in poll. */
      retVal = AsyncSocketPoll(s, FALSE, done - now, &asock);
      AsyncSocketLock(s);

      if (retVal != ASOCKERR_SUCCESS) {
         ASOCKWARN(s, ("flush failed\n"));
         goto outHaveLock;
      }

      ASSERT(asock == s);
      if ((retVal = AsyncSocketWriteBuffers(s)) != ASOCKERR_SUCCESS) {
         goto outHaveLock;
      }
      ASSERT(s->state == AsyncSocketConnected);

      /* Setting timeoutMS to -1 means never timeout. */
      if (timeoutMS >= 0) {
         now = Hostinfo_SystemTimerUS() / 1000;

         /* Don't timeout if you've sent everything */
         if (now > done && s->sendBufList) {
            ASOCKWARN(s, ("flush timed out\n"));
            retVal = ASOCKERR_TIMEOUT;
            goto outHaveLock;
         }
      }
   }

   retVal = ASOCKERR_SUCCESS;

outHaveLock:
   AsyncSocketRelease(s, TRUE);

   return retVal;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_SetErrorFn --
 *
 *      Sets the error handling function for the asock. The error function
 *      is invoked automatically on I/O errors. Passing NULL as the error
 *      function restores the default behavior, which is to just destroy the
 *      AsyncSocket on any errors.
 *
 * Results:
 *      ASOCKERR_SUCCESS or ASOCKERR_INVAL.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_SetErrorFn(AsyncSocket *asock,           // IN/OUT
                       AsyncSocketErrorFn errorFn,   // IN
                       void *clientData)             // IN
{
   if (!asock) {
      Warning(ASOCKPREFIX "%s called with invalid arguments!\n",
              __FUNCTION__);

      return ASOCKERR_INVAL;
   }
   AsyncSocketLock(asock);
   asock->errorFn = errorFn;
   asock->errorClientData = clientData;
   AsyncSocketUnlock(asock);

   return ASOCKERR_SUCCESS;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketCancelListenCbSocket --
 *
 *      Socket specific code for canceling callbacks for a listening socket.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

void
AsyncSocketCancelListenCbSocket(AsyncSocket *asock)  // IN:
{
   Bool removed;

   ASSERT(AsyncSocketIsLocked(asock));

   removed = AsyncSocketPollRemove(asock, TRUE,
                                   POLL_FLAG_READ | POLL_FLAG_PERIODIC,
                                   AsyncSocketAcceptCallback);
   ASSERT(removed);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketAddListenCbSocket --
 *
 *      Socket specific code for adding callbacks for a listening socket.
 *
 * Results:
 *      TRUE if Poll callback successfully added.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static Bool
AsyncSocketAddListenCbSocket(AsyncSocket *asock)  // IN:
{
   VMwareStatus pollStatus;

   ASSERT(AsyncSocketIsLocked(asock));

   pollStatus = AsyncSocketPollAdd(asock, TRUE, POLL_FLAG_READ |
                                                POLL_FLAG_PERIODIC,
                                   AsyncSocketAcceptCallback);

   if (pollStatus != VMWARE_STATUS_SUCCESS) {
      ASOCKWARN(asock, ("failed to install listen accept callback!\n"));
   }

   return pollStatus == VMWARE_STATUS_SUCCESS;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketCancelRecvCbSocket --
 *
 *      Socket specific code for canceling callbacks when a receive
 *      request is being canceled.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

void
AsyncSocketCancelRecvCbSocket(AsyncSocket *asock)  // IN:
{
   ASSERT(AsyncSocketIsLocked(asock));

   if (asock->recvCb) {
      Bool removed;
      ASOCKLOG(1, asock, ("Removing poll recv callback while cancelling recv.\n"));
      removed = AsyncSocketPollRemove(asock, TRUE,
                                      POLL_FLAG_READ | POLL_FLAG_PERIODIC,
                                      asock->vt->recvCallback);
      VERIFY(removed || asock->pollParams.iPoll);
      asock->recvCb = FALSE;
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketCancelCbForCloseSocket --
 *
 *      Socket specific code for canceling callbacks when a socket is
 *      being closed.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Unregisters send/recv Poll callbacks, and fires the send
 *      triggers for any remaining output buffers. May also change
 *      the socket state.
 *
 *----------------------------------------------------------------------------
 */

void
AsyncSocketCancelCbForCloseSocket(AsyncSocket *asock)  // IN:
{
   Bool removed;

   /*
    * Remove the read and write poll callbacks.
    *
    * We could fire the current recv completion callback here, but in
    * practice clients won't want to know about partial reads since it just
    * complicates the common case (i.e. every read callback would need to
    * check the len parameter).
    *
    * For writes, however, we *do* fire all of the callbacks. The argument
    * here is that the common case for writes is "fire and forget", e.g.
    * send this buffer and free it. Firing the triggers at close time
    * simplifies client code, since the clients aren't forced to keep track
    * of send buffers themselves. Clients can figure out how much data was
    * actually transmitted (if they care) by checking the len parameter
    * passed to the send callback.
    *
    * A modification suggested by Jeremy is to pass a list of unsent
    * buffers and their completion callbacks to the error handler if one is
    * registered, and only fire the callbacks here if there was no error
    * handler invoked.
    */

   ASSERT(!asock->recvBuf || asock->recvCb);

   if (asock->recvCb) {
      ASOCKLOG(1, asock, ("recvCb is non-NULL, removing recv callback\n"));
      removed = AsyncSocketPollRemove(asock, TRUE,
                                      POLL_FLAG_READ | POLL_FLAG_PERIODIC,
                                      asock->vt->recvCallback);

      /*
       * Callback might be temporarily removed in AsyncSocket_DoOneMsg.
       */

      ASSERT_NOT_TESTED(removed || asock->pollParams.iPoll);

      /*
       * We may still have the RTime callback, try to remove if it exists
       */

      removed = Poll_CB_RTimeRemove(asock->vt->recvCallback,
                                    asock, FALSE);
      asock->recvCb = FALSE;
      asock->recvBuf = NULL;
   }

   if (asock->sendCb) {
      ASOCKLOG(1, asock, ("sendBufList is non-NULL, removing send callback\n"));

      /*
       * The send callback could be either a device or RTime callback, so
       * we check the latter if it wasn't the former.
       */

      if (asock->sendCbTimer) {
         removed = AsyncSocketPollRemove(asock, FALSE, 0,
                                         asock->vt->sendCallback);
      } else {
         removed = AsyncSocketPollRemove(asock, TRUE, POLL_FLAG_WRITE,
                                         asock->vt->sendCallback);
      }
      ASSERT(removed || asock->pollParams.iPoll);
      asock->sendCb = FALSE;
      asock->sendCbTimer = FALSE;
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketCancelCbForCloseInt --
 *
 *      Cancel future asynchronous send and recv by unregistering
 *      their Poll callbacks, and change the socket state to
 *      AsyncSocketCBCancelled if the socket state is AsyncSocketConnected.
 *
 *      The function can be called in a send/recv error handler before
 *      actually closing the socket in a separate thread, to prevent other
 *      code calling AsyncSocket_Send/Recv from re-registering the
 *      callbacks again. The next operation should be just AsyncSocket_Close().
 *      This helps to avoid unnecessary send/recv callbacks before the
 *      socket is closed.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Unregisters send/recv Poll callbacks, and fires the send
 *      triggers for any remaining output buffers. May also change
 *      the socket state.
 *
 *----------------------------------------------------------------------------
 */

static void
AsyncSocketCancelCbForCloseInt(AsyncSocket *asock)  // IN:
{
   ASSERT(AsyncSocketIsLocked(asock));

   if (asock->state == AsyncSocketConnected) {
      asock->state = AsyncSocketCBCancelled;
   }

   ASSERT(asock->vt);
   ASSERT(asock->vt->cancelCbForClose);
   asock->vt->cancelCbForClose(asock);

   AsyncSocketAddRef(asock);
   while (asock->sendBufList) {
      /*
       * Pop each remaining buffer and fire its completion callback.
       */

      SendBufList *cur = asock->sendBufList;
      int pos = asock->sendPos;

      /*
       * Free the Base64 encoded data if it exists.
       */
      free(cur->base64Buf);
      asock->sendBufList = asock->sendBufList->next;
      asock->sendPos = 0;

      if (cur->sendFn) {
         cur->sendFn(cur->buf, pos, asock, cur->clientData);
      }
      free(cur);
   }
   AsyncSocketRelease(asock, FALSE);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_CancelCbForClose --
 *
 *      This is the external version of AsyncSocketCancelCbForCloseInt().  It
 *      takes care of acquiring any necessary lock before calling the internal
 *      function.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

void
AsyncSocket_CancelCbForClose(AsyncSocket *asock)  // IN:
{
   AsyncSocketLock(asock);
   AsyncSocketCancelCbForCloseInt(asock);
   AsyncSocketUnlock(asock);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketCloseSocket --
 *
 *      AsyncSocket destructor for SSL sockets.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Closes the socket fd.
 *
 *----------------------------------------------------------------------------
 */

void
AsyncSocketCloseSocket(AsyncSocket *asock) // IN
{
   SSL_Shutdown(asock->sslSock);

   if (asock->passFd.fd != -1) {
      SSLGeneric_close(asock->passFd.fd);
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketCancelCbForConnectingCloseSocket --
 *
 *      Cancels outstanding connect requests for a socket that is going
 *      away.
 *
 * Results:
 *      TRUE on callback removed. FALSE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

Bool
AsyncSocketCancelCbForConnectingCloseSocket(AsyncSocket *asock) // IN
{
   return AsyncSocketPollRemove(asock, TRUE, POLL_FLAG_WRITE,
                                AsyncSocketConnectCallback)
      || AsyncSocketPollRemove(asock, FALSE, 0, AsyncSocketConnectCallback);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_Close --
 *
 *      AsyncSocket destructor. The destructor should be safe to call at any
 *      time.  It's invoked automatically for I/O errors on slots that have no
 *      error handler set, and should be called manually by the error handler
 *      as necessary. It could also be called as part of the normal program
 *      flow.
 *
 * Results:
 *      ASOCKERR_*.
 *
 * Side effects:
 *      Closes the socket fd, unregisters all Poll callbacks, and fires the
 *      send triggers for any remaining output buffers.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_Close(AsyncSocket *asock)
{
   Bool isListener = TRUE;

   if (!asock) {
      return ASOCKERR_INVAL;
   }

   AsyncSocketLock(asock);

   if (asock->state == AsyncSocketClosed) {
      Warning("%s() called on already closed asock!\n", __FUNCTION__);
      AsyncSocketUnlock(asock);

      return ASOCKERR_CLOSED;
   }

   if (asock->listenAsock4 || asock->listenAsock6) {
      ASSERT(asock->refCount == 1);

      if (asock->listenAsock4) {
         AsyncSocket_Close(asock->listenAsock4);
      }
      if (asock->listenAsock6) {
         AsyncSocket_Close(asock->listenAsock6);
      }
   } else {
      Bool removed;
      AsyncSocketState oldState;

      isListener = FALSE;

      /*
       * Set the new state to closed, and then check the old state and do the
       * right thing accordingly
       */

      ASOCKLOG(1, asock, ("closing socket\n"));
      oldState = asock->state;
      asock->state = AsyncSocketClosed;

      ASSERT(asock->vt);

      switch(oldState) {
      case AsyncSocketListening:
         ASOCKLOG(1, asock, ("old state was listening, removing accept "
                             "callback\n"));
         ASSERT(asock->vt->cancelListenCb);
         asock->vt->cancelListenCb(asock);
         break;

      case AsyncSocketConnecting:
         ASOCKLOG(1, asock, ("old state was connecting, removing connect "
                             "callback\n"));
         ASSERT(asock->vt->cancelCbForConnectingClose);
         removed = asock->vt->cancelCbForConnectingClose(asock);
         if (!removed) {
            ASOCKLOG(1, asock, ("connect callback is not present in the poll "
                                "list.\n"));
         }
         break;

      case AsyncSocketConnected:
         ASOCKLOG(1, asock, ("old state was connected\n"));
         AsyncSocketCancelCbForCloseInt(asock);
         break;

      case AsyncSocketCBCancelled:
         ASOCKLOG(1, asock, ("old state was CB-cancelled\n"));
         break;

      default:
         NOT_REACHED();
      }

      ASSERT(asock->vt->close);
      asock->vt->close(asock);
   }

   AsyncSocketRelease(asock, TRUE);

   return ASOCKERR_SUCCESS;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_GetState --
 *
 *      Returns the state of the provided asock or ASOCKERR_INVAL.  Note that
 *      unless this is called from a callback function, the state should be
 *      treated as transient (except the state AsyncSocketClosed).
 *
 * Results:
 *      AsyncSocketState enum.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

AsyncSocketState
AsyncSocket_GetState(AsyncSocket *asock)
{
   return (asock ? asock->state : ASOCKERR_INVAL);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_IsSendBufferFull --
 *
 *      Indicate if socket send buffer is full.  Note that unless this is
 *      called from a callback function, the return value should be treated
 *      as transient.
 *
 * Results:
 *      0: send space probably available,
 *      1: send has reached maximum,
 *      ASOCKERR_GENERIC: null socket.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_IsSendBufferFull(AsyncSocket *asock)
{
   return (asock ? asock->sendBufFull : ASOCKERR_GENERIC);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocket_GetID --
 *
 *      Returns a unique identifier for the asock.
 *
 * Results:
 *      Integer id or ASOCKERR_INVAL.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocket_GetID(AsyncSocket *asock)
{
   return (asock ? asock->id : ASOCKERR_INVAL);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketSendInternal --
 *
 *      Internal send method for 'regular' socket connections, allocates & prepares
 *      a buffer and enqueues it.
 *
 * Results:
 *      ASOCKERR_SUCCESS if there are no errors.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

int
AsyncSocketSendInternal(AsyncSocket *asock,         // IN
                        void *buf,                  // IN
                        int len,                    // IN
                        AsyncSocketSendFn sendFn,   // IN
                        void *clientData,           // IN
                        Bool *bufferListWasEmpty)   // IN
{
   SendBufList *newBuf;
   ASSERT(bufferListWasEmpty);

   /*
    * Allocate and initialize new send buffer entry
    */

   newBuf = Util_SafeCalloc(1, sizeof(SendBufList));
   newBuf->buf = buf;
   newBuf->len = len;
   newBuf->sendFn = sendFn;
   newBuf->clientData = clientData;

   /*
    * Append new send buffer to the tail of list.
    */

   *asock->sendBufTail = newBuf;
   asock->sendBufTail = &(newBuf->next);
   if (asock->sendBufList == newBuf) {
      *bufferListWasEmpty = TRUE;
   }

   return ASOCKERR_SUCCESS;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketDispatchConnect --
 *
 *      Simple dispatch to call the connect callback for the socket pair.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

void
AsyncSocketDispatchConnect(AsyncSocket *asock,
                           AsyncSocket *newsock)
{
   asock->connectFn(newsock, asock->clientData);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketHasDataPendingSocket --
 *
 *      Determine if the SSL socket has any pending/unread data.
 *
 * Results:
 *      TRUE if this socket has pending data.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static Bool
AsyncSocketHasDataPendingSocket(AsyncSocket *asock) // IN
{
   return SSL_Pending(asock->sslSock);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketHasDataPending --
 *
 *      Determine if the SSL or WebSocket has any pending/unread data.
 *
 * Results:
 *      TRUE if this socket has pending data.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static Bool
AsyncSocketHasDataPending(AsyncSocket *asock)   // IN:
{
   ASSERT(asock->vt);
   ASSERT(asock->vt->hasDataPending);

   return asock->vt->hasDataPending(asock);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketMakeNonBlocking --
 *
 *      Make the specified socket non-blocking if it isn't already.
 *
 * Results:
 *      ASOCKERR_SUCCESS if the operation succeeded, ASOCKERR_GENERIC otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static int
AsyncSocketMakeNonBlocking(int fd)
{
#ifdef _WIN32
   int retval;
   u_long argp = 1; /* non-zero => enable non-blocking mode */

   retval = ioctlsocket(fd, FIONBIO, &argp);

   if (retval != 0) {
      ASSERT(retval == SOCKET_ERROR);

      return ASOCKERR_GENERIC;
   }
#elif defined(__APPLE__)
   int argp = 1;
   if (ioctl(fd, FIONBIO, &argp) < 0) {
      return ASOCKERR_GENERIC;
   }
#else
   int flags;

   if ((flags = fcntl(fd, F_GETFL)) < 0) {
      return ASOCKERR_GENERIC;
   }

   if (!(flags & O_NONBLOCK) && (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0))
   {
      return ASOCKERR_GENERIC;
   }
#endif

   return ASOCKERR_SUCCESS;
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketHandleError --
 *
 *      Internal error handling helper. Changes the socket's state to error,
 *      and calls the registered error handler or closes the socket.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Lots.
 *
 *----------------------------------------------------------------------------
 */

void
AsyncSocketHandleError(AsyncSocket *asock, int asockErr)
{
   ASSERT(asock);
   if (asock->errorFn) {
      ASOCKLOG(3, asock, ("firing error callback\n"));
      asock->errorFn(asockErr, asock, asock->errorClientData);
   } else {
      ASOCKLOG(3, asock, ("no error callback, closing socket\n"));
      AsyncSocket_Close(asock);
   }
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketAcceptCallback --
 *
 *      Poll callback for listening fd waiting to complete an accept
 *      operation. We call accept to get the new socket fd, create a new
 *      asock, and call the newFn callback previously supplied by the call to
 *      AsyncSocket_Listen.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Accepts on listening fd, creates new asock.
 *
 *----------------------------------------------------------------------------
 */

static void
AsyncSocketAcceptCallback(void *clientData)
{
   AsyncSocket *asock = (AsyncSocket *) clientData;
   int retval;

   ASSERT(asock);
   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(asock->pollParams.iPoll == NULL);
   ASSERT(AsyncSocketIsLocked(asock));

   AsyncSocketAddRef(asock);
   retval = AsyncSocketAcceptInternal(asock);

   /*
    * See comment for return value of AsyncSocketAcceptInternal().
    */

   if (retval == ASOCKERR_ACCEPT) {
      AsyncSocketHandleError(asock, retval);
   }
   AsyncSocketRelease(asock, FALSE);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketConnectCallback --
 *
 *      Poll callback for connecting fd. Calls through to
 *      AsyncSocketConnectInternal to do the real work.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Creates new asock, fires newFn callback.
 *
 *----------------------------------------------------------------------------
 */

static void
AsyncSocketConnectCallback(void *clientData)
{
   AsyncSocket *asock = (AsyncSocket *) clientData;
   int retval;

   ASSERT(asock);
   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(asock->pollParams.iPoll == NULL);
   ASSERT(AsyncSocketIsLocked(asock));

   AsyncSocketAddRef(asock);
   retval = AsyncSocketConnectInternal(asock);
   if (retval != ASOCKERR_SUCCESS) {
      ASSERT(retval == ASOCKERR_GENERIC); /* Only one we're expecting */
      AsyncSocketHandleError(asock, retval);
   }
   AsyncSocketRelease(asock, FALSE);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketRecvCallback --
 *
 *      Poll callback for input waiting on the socket. We try to pull off the
 *      remaining data requested by the current receive function.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Reads data, could fire recv completion or trigger socket destruction.
 *
 *----------------------------------------------------------------------------
 */

void
AsyncSocketRecvCallback(void *clientData)
{
   AsyncSocket *asock = (AsyncSocket *) clientData;
   int error;

   ASSERT(asock);
   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(AsyncSocketIsLocked(asock));

   AsyncSocketAddRef(asock);

   error = AsyncSocketFillRecvBuffer(asock);
   if (error == ASOCKERR_GENERIC || error == ASOCKERR_REMOTE_DISCONNECT) {
      AsyncSocketHandleError(asock, error);
   }

   AsyncSocketRelease(asock, FALSE);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketIPollRecvCallback --
 *
 *      Poll callback for input waiting on the socket.  IVmdbPoll does not
 *      handle callback locks, so this function first locks the asyncsocket
 *      and verify that the recv callback has not been cancelled before
 *      calling AsyncSocketFillRecvBuffer to do the real work.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Reads data, could fire recv completion or trigger socket destruction.
 *
 *----------------------------------------------------------------------------
 */

static void
AsyncSocketIPollRecvCallback(void *clientData)  // IN:
{
#ifdef VMX86_TOOLS
   NOT_IMPLEMENTED();
#else
   AsyncSocket *asock = (AsyncSocket *) clientData;
   MXUserRecLock *lock;

   ASSERT(asock);
   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(asock->pollParams.lock == NULL ||
          !MXUser_IsCurThreadHoldingRecLock(asock->pollParams.lock));

   AsyncSocketLock(asock);
   lock = asock->pollParams.lock;
   if (asock->recvCb) {
      /*
       * There is no need to take a reference here -- the fact that this
       * callback is running means AsyncsocketIPollRemove would not release a
       * reference if it is called.
       */
      int error = AsyncSocketFillRecvBuffer(asock);

      if (error == ASOCKERR_GENERIC || error == ASOCKERR_REMOTE_DISCONNECT) {
         AsyncSocketHandleError(asock, error);
      }
   }

   if (asock->recvCb) {
      AsyncSocketUnlock(asock);
   } else {
      /*
       * Callback has been unregistered.  Per above, we need to release the
       * reference explicitly.
       */
      AsyncSocketRelease(asock, TRUE);
      if (lock != NULL) {
         MXUser_DecRefRecLock(lock);
      }
   }
#endif
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketSendCallback --
 *
 *      Poll callback for output socket buffer space available (socket is
 *      writable). We iterate over all the remaining buffers in our queue,
 *      writing as much as we can until we fill the socket buffer again. If we
 *      don't finish, we register ourselves as a device write callback.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Writes data, could trigger write completion or socket destruction.
 *
 *----------------------------------------------------------------------------
 */

void
AsyncSocketSendCallback(void *clientData)
{
   AsyncSocket *s = (AsyncSocket *) clientData;
   int retval;

   ASSERT(s);
   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(AsyncSocketIsLocked(s));

   AsyncSocketAddRef(s);
   s->sendCb = FALSE; /* AsyncSocketSendCallback is never periodic */
   s->sendCbTimer = FALSE;
   retval = AsyncSocketWriteBuffers(s);
   if (retval != ASOCKERR_SUCCESS) {
      AsyncSocketHandleError(s, retval);
   } else if (s->sendBufList && !s->sendCb) {
      VMwareStatus pollStatus;

      /*
       * We didn't finish, so we need to reschedule the Poll callback (the
       * write callback is *not* periodic).
       */

#ifdef _WIN32
      /*
       * If any data has been sent out or read in from the sslSock,
       * SSL has finished the handshaking. Otherwise,
       * we have to schedule a realtime callback for write. See bug 37147
       */

      if (!s->sslConnected) {
         pollStatus = AsyncSocketPollAdd(s, FALSE, 0,
                                         s->vt->sendCallback, 100000);
         VERIFY(pollStatus == VMWARE_STATUS_SUCCESS);
         s->sendCbTimer = TRUE;
      } else
#endif
      {
         pollStatus = AsyncSocketPollAdd(s, TRUE, POLL_FLAG_WRITE,
                                         s->vt->sendCallback);
         VERIFY(pollStatus == VMWARE_STATUS_SUCCESS);
      }
      s->sendCb = TRUE;
   }
   AsyncSocketRelease(s, FALSE);
}


/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketIPollSendCallback --
 *
 *      IVmdbPoll callback for output socket buffer space available.  IVmdbPoll
 *      does not handle callback locks, so this function first locks the
 *      asyncsocket and verify that the send callback has not been cancelled.
 *      IVmdbPoll only has periodic callbacks, so this function unregisters
 *      itself before calling AsyncSocketSendCallback to do the real work.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Writes data, could trigger write completion or socket destruction.
 *
 *----------------------------------------------------------------------------
 */

static void
AsyncSocketIPollSendCallback(void *clientData)  // IN:
{
#ifdef VMX86_TOOLS
   NOT_IMPLEMENTED();
#else
   AsyncSocket *s = (AsyncSocket *) clientData;
   MXUserRecLock *lock;

   ASSERT(s);
   ASSERT(s->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   AsyncSocketLock(s);
   lock = s->pollParams.lock;
   if (s->sendCb) {
      /*
       * Unregister this callback as we want the non-periodic behavior.  There
       * is no need to take a reference here -- the fact that this callback is
       * running means AsyncsocketIPollRemove would not release a reference.
       * We would release that reference at the end.
       */
      if (s->sendCbTimer) {
         AsyncSocketIPollRemove(s, FALSE, 0, AsyncSocketIPollSendCallback);
      } else {
         AsyncSocketIPollRemove(s, TRUE, POLL_FLAG_WRITE,
                                AsyncSocketIPollSendCallback);
      }

      AsyncSocketSendCallback(s);
   }

   AsyncSocketRelease(s, TRUE);
   if (lock != NULL) {
      MXUser_DecRefRecLock(lock);
   }
#endif
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocketAddRef --
 *
 *    Increments reference count on AsyncSocket struct.
 *
 * Results:
 *    New reference count.
 *
 * Side effects:
 *    None.
 *
 *-----------------------------------------------------------------------------
 */

int
AsyncSocketAddRef(AsyncSocket *s)
{
   ASSERT(s && s->refCount > 0);
   ASOCKLOG(1, s, ("%s (count now %d)\n", __FUNCTION__, s->refCount + 1));

   return ++s->refCount;
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocketRelease --
 *
 *    Decrements reference count on AsyncSocket struct, freeing it when it
 *    reaches 0.  If "unlock" is TRUE, releases the lock after decrementing
 *    the count.
 *
 * Results:
 *    New reference count; 0 if freed.
 *
 * Side effects:
 *    May free struct.
 *
 *-----------------------------------------------------------------------------
 */

int
AsyncSocketRelease(AsyncSocket *s,  // IN:
                   Bool unlock)     // IN: release lock
{
   int count = --s->refCount;

   if (unlock) {
      AsyncSocketUnlock(s);
   }
   if (0 == count) {
      ASOCKLOG(1, s, ("Final release; freeing asock struct\n"));
      if (s->vt && s->vt->release) {
         s->vt->release(s);
      }
      free(s);

      return 0;
   }
   ASOCKLOG(1, s, ("Release (count now %d)\n", count));

   return count;
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocketPollAdd --
 *
 *    Add a poll callback.  Wrapper for Poll_Callback since we always call
 *    it in one of two basic forms.
 *
 *    If socket is FALSE, user has to pass in the timeout value
 *
 * Results:
 *    VMwareStatus result code from Poll_Callback
 *
 * Side effects:
 *    Only the obvious.
 *
 *-----------------------------------------------------------------------------
 */

VMwareStatus
AsyncSocketPollAdd(AsyncSocket *asock,
                   Bool socket,
                   int flags,
                   PollerFunction callback,
                   ...)
{
   int type, info;

   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   if (socket) {
      ASSERT(asock->fd != -1);
      type = POLL_DEVICE;
      flags |= POLL_FLAG_SOCKET;
      info = asock->fd;
   } else {
      va_list marker;
      va_start(marker, callback);

      type = POLL_REALTIME;
      info = va_arg(marker, int);

      va_end(marker);
   }

   if (asock->pollParams.iPoll != NULL) {
      return AsyncSocketIPollAdd(asock, socket, flags, callback, info);
   }

   return Poll_Callback(asock->pollParams.pollClass,
                        flags | asock->pollParams.flags,
                        callback, asock, type, info,
                        asock->pollParams.lock);
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocketPollRemove --
 *
 *    Remove a poll callback.  Wrapper for Poll_CallbackRemove since we
 *    always call it in one of two basic forms.
 *
 * Results:
 *    TRUE if removed, FALSE if not found.
 *
 * Side effects:
 *    Only the obvious.
 *
 *-----------------------------------------------------------------------------
 */

Bool
AsyncSocketPollRemove(AsyncSocket *asock,
                      Bool socket,
                      int flags,
                      PollerFunction callback)
{
   int type;

   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   if (asock->pollParams.iPoll != NULL) {
      return AsyncSocketIPollRemove(asock, socket, flags, callback);
   }

   if (socket) {
      ASSERT(asock->fd != -1);
      type = POLL_DEVICE;
      flags |= POLL_FLAG_SOCKET;
   } else {
      type = POLL_REALTIME;
   }

   return Poll_CallbackRemove(asock->pollParams.pollClass,
                              flags | asock->pollParams.flags,
                              callback, asock, type);
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocketIPollAdd --
 *
 *    Add a poll callback.  Wrapper for IVmdbPoll.Register[Timer].
 *
 *    If socket is FALSE, user has to pass in the timeout value
 *
 * Results:
 *    VMwareStatus result code.
 *
 * Side effects:
 *    None.
 *
 *-----------------------------------------------------------------------------
 */

static VMwareStatus
AsyncSocketIPollAdd(AsyncSocket *asock,
                    Bool socket,
                    int flags,
                    PollerFunction callback,
                    int info)
{
#ifdef VMX86_TOOLS
   return VMWARE_STATUS_ERROR;
#else
   VMwareStatus status = VMWARE_STATUS_SUCCESS;
   VmdbRet ret;
   IVmdbPoll *poll;

   ASSERT(asock->pollParams.iPoll);
   ASSERT(AsyncSocketIsLocked(asock));

   /* Protect asyncsocket and lock from disappearing */
   AsyncSocketAddRef(asock);
   if (asock->pollParams.lock != NULL) {
      MXUser_IncRefRecLock(asock->pollParams.lock);
   }

   poll = asock->pollParams.iPoll;

   if (socket) {
      int pollFlags = (flags & POLL_FLAG_READ) != 0 ? VMDB_PRF_READ
                                                    : VMDB_PRF_WRITE;

      ret = poll->Register(poll, pollFlags, callback, asock, info);
   } else {
      ret = poll->RegisterTimer(poll, callback, asock, info);
   }

   if (ret != VMDB_S_OK) {
      Log(ASOCKPREFIX "failed to register callback (%s %d): error %d\n",
          socket ? "socket" : "delay", info, ret);
      if (asock->pollParams.lock != NULL) {
         MXUser_DecRefRecLock(asock->pollParams.lock);
      }
      AsyncSocketRelease(asock, FALSE);
      status = VMWARE_STATUS_ERROR;
   }

   return status;
#endif
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocketIPollRemove --
 *
 *    Remove a poll callback.  Wrapper for IVmdbPoll.Unregister[Timer].
 *
 * Results:
 *    TRUE  if the callback was registered and has been cancelled successfully.
 *    FALSE if the callback was not registered, or the callback is already
 *          scheduled to fire (and is guaranteed to fire).
 *
 * Side effects:
 *    None.
 *
 *-----------------------------------------------------------------------------
 */

static Bool
AsyncSocketIPollRemove(AsyncSocket *asock,
                       Bool socket,
                       int flags,
                       PollerFunction callback)
{
#ifdef VMX86_TOOLS
   return FALSE;
#else
   IVmdbPoll *poll;
   Bool ret;

   ASSERT(asock->pollParams.iPoll);
   ASSERT(AsyncSocketIsLocked(asock));

   poll = asock->pollParams.iPoll;

   if (socket) {
      int pollFlags = (flags & POLL_FLAG_READ) != 0 ? VMDB_PRF_READ
                                                    : VMDB_PRF_WRITE;

      ret = poll->Unregister(poll, pollFlags, callback, asock);
   } else {
      ret = poll->UnregisterTimer(poll, callback, asock);
   }

   if (ret) {
      MXUserRecLock *lock = asock->pollParams.lock;

      /* Release the reference taken when registering the callback. */
      AsyncSocketRelease(asock, FALSE);
      if (lock != NULL) {
         MXUser_DecRefRecLock(lock);
      }
   }

   return ret;
#endif
}




/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocket_CancelRecv --
 * AsyncSocket_CancelRecvEx --
 *
 *    Call this function if you know what you are doing. This should be
 *    called if you want to synchronously receive the outstanding data on
 *    the socket. It removes the recv poll callback. It also returns number of
 *    partially read bytes (if any). A partially read response may exist as
 *    AsyncSocketRecvCallback calls the recv callback only when all the data
 *    has been received.
 *
 * Results:
 *    ASOCKERR_SUCCESS or ASOCKERR_INVAL.
 *
 * Side effects:
 *    Subsequent client call to AsyncSocket_Recv can reinstate async behaviour.
 *
 *-----------------------------------------------------------------------------
 */

int
AsyncSocket_CancelRecv(AsyncSocket *asock,         // IN
                       int *partialRecvd,          // OUT
                       void **recvBuf,             // OUT
                       void **recvFn)              // OUT
{
   return AsyncSocket_CancelRecvEx(asock, partialRecvd, recvBuf, recvFn, FALSE);
}

int
AsyncSocket_CancelRecvEx(AsyncSocket *asock,         // IN
                         int *partialRecvd,          // OUT
                         void **recvBuf,             // OUT
                         void **recvFn,              // OUT
                         Bool cancelOnSend)          // IN
{
   int retVal;

   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   if (!asock) {
      Warning(ASOCKPREFIX "Invalid socket while cancelling recv request!\n");

      return ASOCKERR_INVAL;
   }

   AsyncSocketLock(asock);

   if (asock->state != AsyncSocketConnected) {
      Warning(ASOCKPREFIX "Failed to cancel request on disconnected socket!\n");
      retVal = ASOCKERR_INVAL;
      goto outHaveLock;
   }

   if (asock->inBlockingRecv) {
      Warning(ASOCKPREFIX "Cannot cancel request while a blocking recv is "
                          "pending.\n");
      retVal = ASOCKERR_INVAL;
      goto outHaveLock;
   }

   if (!cancelOnSend && (asock->sendBufList || asock->sendCb)) {
      Warning(ASOCKPREFIX "Can't cancel request as socket has send operation "
              "pending.\n");
      retVal = ASOCKERR_INVAL;
      goto outHaveLock;
   }

   ASSERT(asock->vt);
   ASSERT(asock->vt->cancelRecvCb);
   asock->vt->cancelRecvCb(asock);

   if (partialRecvd && asock->recvLen > 0) {
      ASOCKLOG(1, asock, ("Partially read %d bytes out of %d bytes while "
                          "cancelling recv request.\n", asock->recvPos, asock->recvLen));
      *partialRecvd = asock->recvPos;
   }
   if (recvFn) {
      *recvFn = asock->recvFn;
   }
   if (recvBuf) {
      *recvBuf = asock->recvBuf;
   }
   asock->recvBuf = NULL;
   asock->recvFn = NULL;
   asock->recvPos = 0;
   asock->recvLen = 0;

   if (asock->passFd.fd != -1) {
      SSLGeneric_close(asock->passFd.fd);
      asock->passFd.fd = -1;
   }
   asock->passFd.expected = FALSE;

   retVal = ASOCKERR_SUCCESS;

outHaveLock:
   AsyncSocketUnlock(asock);
   return retVal;
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocket_GetReceivedFd --
 *
 *    Retrieve received file descriptor from socket.
 *
 * Results:
 *    File descriptor.  Or -1 if none was received.
 *
 * Side effects:
 *    None.
 *
 *-----------------------------------------------------------------------------
 */

int
AsyncSocket_GetReceivedFd(AsyncSocket *asock)      // IN
{
   int fd;

   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   if (!asock) {
      Warning(ASOCKPREFIX "Invalid socket while receiving fd!\n");

      return -1;
   }

   AsyncSocketLock(asock);

   if (asock->state != AsyncSocketConnected) {
      Warning(ASOCKPREFIX "Failed to receive fd on disconnected socket!\n");
      AsyncSocketUnlock(asock);

      return -1;
   }
   fd = asock->passFd.fd;
   asock->passFd.fd = -1;
   asock->passFd.expected = FALSE;

   AsyncSocketUnlock(asock);

   return fd;
}

#ifndef USE_SSL_DIRECT

/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocket_ConnectSSL --
 *
 *    Initialize the socket's SSL object, by calling SSL_ConnectAndVerify.
 *    NOTE: This call is blocking.
 *
 * Results:
 *    TRUE if SSL_ConnectAndVerify succeeded, FALSE otherwise.
 *
 * Side effects:
 *    None.
 *
 *-----------------------------------------------------------------------------
 */

Bool
AsyncSocket_ConnectSSL(AsyncSocket *asock,          // IN
                       SSLVerifyParam *verifyParam) // IN/OPT
{
   ASSERT(asock);
   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   return SSL_ConnectAndVerify(asock->sslSock, verifyParam);
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocket_AcceptSSL --
 *
 *    Initialize the socket's SSL object, by calling SSL_Accept.
 *
 * Results:
 *    TRUE if SSL_Accept succeeded, FALSE otherwise.
 *
 * Side effects:
 *    None.
 *
 *-----------------------------------------------------------------------------
 */

Bool
AsyncSocket_AcceptSSL(AsyncSocket *asock)  // IN
{
   ASSERT(asock);
   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);

   return SSL_Accept(asock->sslSock);
}

#endif /* ! USE_SSL_DIRECT */

/*
 *----------------------------------------------------------------------------
 *
 * AsyncSocketSslAcceptCallback --
 *
 *      Poll callback for redrive an outstanding ssl accept operation
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

static void
AsyncSocketSslAcceptCallback(void *clientData)
{
   int sslOpCode;
   AsyncSocket *asock = (AsyncSocket *) clientData;
   VMwareStatus pollStatus;

   ASSERT(asock);
   ASSERT(asock->pollParams.iPoll == NULL);
   ASSERT(AsyncSocketIsLocked(asock));

   AsyncSocketAddRef(asock);

   sslOpCode = SSL_TryCompleteAccept(asock->sslSock);
   if (sslOpCode > 0) {
      (*asock->sslAcceptFn)(TRUE, asock, clientData);
   } else if (sslOpCode < 0) {
      (*asock->sslAcceptFn)(FALSE, asock, clientData);
   } else {
      /* register the poll callback to redrive the SSL accept */
      pollStatus = AsyncSocketPollAdd(asock, TRUE,
                                      SSL_WantRead(asock->sslSock) ?
                                      POLL_FLAG_READ : POLL_FLAG_WRITE,
                                      AsyncSocketSslAcceptCallback);

      if (pollStatus != VMWARE_STATUS_SUCCESS) {
         ASOCKWARN(asock, ("failed to reinstall ssl accept callback!\n"));
         (*asock->sslAcceptFn)(FALSE, asock, clientData);
      }
   }

   AsyncSocketRelease(asock, FALSE);
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocket_StartSslAccept --
 *
 *    Start an asynchronous SSL accept operation.
 *
 *    The supplied callback function is called when the operation is complete
 *    or an error occurs.
 *
 *    Note: The client callback could be invoked from this function or
 *          from a poll callback. If there is any requirement to always
 *          invoke the client callback from outside this function, consider
 *          changing this code to use a poll timer callback with timeout
 *          set to zero.
 *
 *    Note: sslCtx is typed as void *, so that the async socket code does
 *          not have to include the openssl header. This is in sync with
 *          SSL_AcceptWithContext(), where the sslCtx param is typed as void *
 * Results:
 *    None.
 *    Error is always reported using the callback supplied.
 *
 * Side effects:
 *    None.
 *
 *-----------------------------------------------------------------------------
 */

void
AsyncSocket_StartSslAccept(AsyncSocket *asock,                 // IN
                           void *sslCtx,                       // IN
                           AsyncSocketSslAcceptFn sslAcceptFn, // IN
                           void *clientData)                   // IN
{
   Bool ok;

   ASSERT(asock);
   ASSERT(asock->asockType != ASYNCSOCKET_TYPE_NAMEDPIPE);
   ASSERT(sslAcceptFn);

   AsyncSocketLock(asock);

   if (asock->sslAcceptFn) {
      ASOCKWARN(asock, ("A SSL accept operation has already been initiated.\n"));
      goto done;
   }

   ok = SSL_SetupAcceptWithContext(asock->sslSock, sslCtx);
   if (!ok) {
      /* Something went wrong already */
      (*sslAcceptFn)(FALSE, asock, clientData);
      goto done;
   }

   asock->sslAcceptFn = sslAcceptFn;
   asock->clientData = clientData;

   AsyncSocketSslAcceptCallback(asock);

done:
   AsyncSocketUnlock(asock);
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocket_SetBufferSizes --
 *
 *    Set socket level recv/send buffer sizes if they are less than given sizes.
 *
 * Result
 *    TRUE: on success
 *    FALSE: on failure
 *
 * Side-effects
 *    None
 *
 *-----------------------------------------------------------------------------
 */

Bool
AsyncSocket_SetBufferSizes(AsyncSocket *asock,  // IN
                           int sendSz,          // IN
                           int recvSz)          // IN
{
   int err;
   int buffSz;
   int len = sizeof buffSz;
   int sysErr;
   int fd;

   if (!asock) {
      return FALSE;
   }

   fd = asock->fd;

   err = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&buffSz, &len);
   if (err) {
      sysErr = ASOCK_LASTERROR();
      Warning(ASOCKPREFIX "Could not get recv buffer size for socket %d, "
              "error %d: %s\n", fd, sysErr, Err_Errno2String(sysErr));
      return FALSE;
   }

   if (buffSz < recvSz) {
      buffSz = recvSz;
      err = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&buffSz, len);
      if (err) {
         sysErr = ASOCK_LASTERROR();
         Warning(ASOCKPREFIX "Could not set recv buffer size for socket %d "
                 "to %d, error %d: %s\n", fd, buffSz,
                 sysErr, Err_Errno2String(sysErr));
         return FALSE;
      }
   }

   err =  getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *)&buffSz, &len);
   if (err) {
      sysErr = ASOCK_LASTERROR();
      Warning(ASOCKPREFIX "Could not get send buffer size for socket %d, "
              "error %d: %s\n", fd, sysErr, Err_Errno2String(sysErr));
      return FALSE;
   }

   if (buffSz < sendSz) {
      buffSz = sendSz;
      err = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *)&buffSz, len);
      if (err) {
         sysErr = ASOCK_LASTERROR();
         Warning(ASOCKPREFIX "Could not set send buffer size for socket %d "
                 "to %d, error %d: %s\n", fd, buffSz,
                 sysErr, Err_Errno2String(sysErr));
         return FALSE;
      }
   }

   return TRUE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * AsyncSocket_SetSendLowLatencyMode --
 *
 *    Put the socket into a mode where we attempt to issue sends
 *    directly from within AsyncSocket_Send().  Ordinarily, we would
 *    set up a Poll callback from within AsyncSocket_Send(), which
 *    introduces some non-zero latency to the send path.  In
 *    low-latency-send mode, that delay is potentially avoided.  This
 *    does introduce a behavioural change; the send completion
 *    callback may be triggered before the call to Send() returns.  As
 *    not all clients may be expecting this, we don't enable this mode
 *    unless requested by the client.
 *
 * Result
 *    None
 *
 * Side-effects
 *    See description above.
 *
 *-----------------------------------------------------------------------------
 */

void
AsyncSocket_SetSendLowLatencyMode(AsyncSocket *asock,  // IN
                                  Bool enable)         // IN
{
   asock->sendLowLatency = enable;
}