aboutsummaryrefslogtreecommitdiff
path: root/nx-X11/lib/xtrans/Xtranssock.c
blob: 748340c0faeb133612d9100343213b8cff10134c (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
/**************************************************************************/
/*                                                                        */
/* Copyright (c) 2001, 2011 NoMachine (http://www.nomachine.com)          */
/* Copyright (c) 2008-2014 Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>  */
/* Copyright (c) 2011-2016 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>*/
/* Copyright (c) 2014-2016 Mihai Moldovan <ionic@ionic.de>                */
/* Copyright (c) 2014-2016 Ulrich Sibiller <uli42@gmx.de>                 */
/* Copyright (c) 2015-2016 Qindel Group (http://www.qindel.com)           */
/*                                                                        */
/* nx-X11, NX protocol compression and NX extensions to this software     */
/* are copyright of the aforementioned persons and companies.             */
/*                                                                        */
/* Redistribution and use of the present software is allowed according    */
/* to terms specified in the file LICENSE which comes in the source       */
/* distribution.                                                          */
/*                                                                        */
/* All rights reserved.                                                   */
/*                                                                        */
/* NOTE: This software has received contributions from various other      */
/* contributors, only the core maintainers and supporters are listed as   */
/* copyright holders. Please contact us, if you feel you should be listed */
/* as copyright holder, as well.                                          */
/*                                                                        */
/**************************************************************************/

/*

Copyright 1993, 1994, 1998  The Open Group
Copyright 2002 Sun Microsystems, Inc.  All rights reserved.

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of the copyright holders shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from the copyright holders.

*/

/* Copyright 1993, 1994 NCR Corporation - Dayton, Ohio, USA
 *
 * All Rights Reserved
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted, provided
 * that the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name NCR not be used in advertising
 * or publicity pertaining to distribution of the software without specific,
 * written prior permission.  NCR makes no representations about the
 * suitability of this software for any purpose.  It is provided "as is"
 * without express or implied warranty.
 *
 * NCR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
 * NO EVENT SHALL NCR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
 * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#ifdef NX_TRANS_SOCKET

#ifdef NX_TRANS_DEBUG
#define XTRANSDEBUG 5
#endif

#ifndef PF_LOCAL
#define PF_LOCAL PF_UNIX
#endif

#endif

#include <ctype.h>
#ifdef XTHREADS
#include <nx-X11/Xthreads.h>
#endif

#ifndef WIN32

#if defined(TCPCONN) || defined(UNIXCONN)
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#if defined(TCPCONN) || defined(UNIXCONN)
#define X_INCLUDE_NETDB_H
#define XOS_USE_NO_LOCKING
#include <nx-X11/Xos_r.h>
#endif

#ifdef UNIXCONN
#ifndef X_NO_SYS_UN
#ifndef Lynx
#include <sys/un.h>
#else
#include <un.h>
#endif
#endif
#include <sys/stat.h>
#endif

#if defined(MOTOROLA) && defined(SYSV)
#define NO_TCP_H
#endif 

#ifndef NO_TCP_H
#if defined(__osf__) || defined(linux) || defined(__GLIBC__) || defined(AIXV5)
#include <sys/param.h>
#endif /* osf */
#if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)
#include <sys/param.h>
#include <machine/endian.h>
#endif /* __NetBSD__ || __OpenBSD__ || __FreeBSD__ || __DragonFly__ */
#include <netinet/tcp.h>
#endif /* !NO_TCP_H */

#include <sys/ioctl.h>
#if defined(SVR4) && !defined(DGUX) && !defined(_SEQUENT_)
#include <sys/filio.h>
#endif

#if (defined(i386) && defined(SYSV)) && !defined(SCO325) && !defined(sun)
#include <net/errno.h>
#endif 

#if (defined(i386) && defined(SYSV)) && (!defined(ISC) || !defined(I_NREAD) || defined(SCO325)) || defined(_SEQUENT_)
#include <sys/stropts.h>
#endif 

#else /* !WIN32 */

#include <nx-X11/Xwinsock.h>
#include <nx-X11/Xwindows.h>
#include <nx-X11/Xw32defs.h>
#undef close
#define close closesocket
#define ECONNREFUSED WSAECONNREFUSED
#define EADDRINUSE WSAEADDRINUSE
#define EPROTOTYPE WSAEPROTOTYPE
#undef EWOULDBLOCK
#define EWOULDBLOCK WSAEWOULDBLOCK
#define EINPROGRESS WSAEINPROGRESS
#undef EINTR
#define EINTR WSAEINTR
#define X_INCLUDE_NETDB_H
#define XOS_USE_MTSAFE_NETDBAPI
#include <nx-X11/Xos_r.h>
#endif /* WIN32 */

#if defined(SO_DONTLINGER) && defined(SO_LINGER)
#undef SO_DONTLINGER
#endif

/* others don't need this */
#define SocketInitOnce() /**/

#if defined(linux)
#define HAVE_ABSTRACT_SOCKETS
#endif

#define MIN_BACKLOG 128
#ifdef SOMAXCONN
#if SOMAXCONN > MIN_BACKLOG
#define BACKLOG SOMAXCONN
#endif
#endif
#ifndef BACKLOG
#define BACKLOG MIN_BACKLOG
#endif
/*
 * This is the Socket implementation of the X Transport service layer
 *
 * This file contains the implementation for both the UNIX and INET domains,
 * and can be built for either one, or both.
 *
 */

typedef struct _Sockettrans2dev {      
    char	*transname;
    int		family;
    int		devcotsname;
    int		devcltsname;
    int		protocol;
} Sockettrans2dev;

static Sockettrans2dev Sockettrans2devtab[] = {
#ifdef TCPCONN
    {"inet",AF_INET,SOCK_STREAM,SOCK_DGRAM,0},
#if !defined(IPv6) || !defined(AF_INET6)
    {"tcp",AF_INET,SOCK_STREAM,SOCK_DGRAM,0},
#else /* IPv6 */
    {"tcp",AF_INET6,SOCK_STREAM,SOCK_DGRAM,0},
    {"tcp",AF_INET,SOCK_STREAM,SOCK_DGRAM,0}, /* fallback */
    {"inet6",AF_INET6,SOCK_STREAM,SOCK_DGRAM,0},
#endif
#endif /* TCPCONN */
#ifdef UNIXCONN
    {"unix",AF_UNIX,SOCK_STREAM,SOCK_DGRAM,0},
#if !defined(LOCALCONN)
    {"local",AF_UNIX,SOCK_STREAM,SOCK_DGRAM,0},
#endif /* !LOCALCONN */
#endif /* UNIXCONN */
};

#define NUMSOCKETFAMILIES (sizeof(Sockettrans2devtab)/sizeof(Sockettrans2dev))

#ifdef TCPCONN
static int TRANS(SocketINETClose) (XtransConnInfo ciptr);
#endif

#ifdef UNIXCONN


#if defined(X11_t)
#define UNIX_PATH "/tmp/.X11-unix/X"
#define UNIX_DIR "/tmp/.X11-unix"
#endif /* X11_t */
#if defined(XIM_t)
#define UNIX_PATH "/tmp/.XIM-unix/XIM"
#define UNIX_DIR "/tmp/.XIM-unix"
#endif /* XIM_t */
#if defined(FS_t) || defined(FONT_t)
#define UNIX_PATH "/tmp/.font-unix/fs"
#define UNIX_DIR "/tmp/.font-unix"
#endif /* FS_t || FONT_t */
#if defined(ICE_t)
#define UNIX_PATH "/tmp/.ICE-unix/"
#define UNIX_DIR "/tmp/.ICE-unix"
#endif /* ICE_t */
#if defined(TEST_t)
#define UNIX_PATH "/tmp/.Test-unix/test"
#define UNIX_DIR "/tmp/.Test-unix"
#endif
#if defined(LBXPROXY_t)
#define UNIX_PATH "/tmp/.X11-unix/X"
#define UNIX_DIR  "/tmp/.X11-unix"
#endif


#endif /* UNIXCONN */

#define PORTBUFSIZE	32

#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 255
#endif

/*
 * This provides compatibility for apps linked against system libraries
 * that don't have IPv6 support.
 */
#if defined(IPv6) && defined(AF_INET6)
static const struct in6_addr local_in6addr_any = IN6ADDR_ANY_INIT;
#pragma weak in6addr_any = local_in6addr_any
#ifndef __USLC__
#pragma weak getaddrinfo
#endif
static int haveIPv6 = 1;
#endif

#ifndef X11_t

/*
 * No NX changes if this is not
 * compiled as a X11 transport.
 */

#undef NX_TRANS_SOCKET

#endif

#ifdef NX_TRANS_SOCKET

#ifdef TRANS_CLIENT

#include <nx/NX.h>

typedef struct
{
    XtransConnInfo info;
    int            local;
    int            remote;
    int            congestion;

} _NXProxyConnInfo;

#define NX_PROXY_CONN_LIMIT     256

static _NXProxyConnInfo *_NXProxyConnInfoTab[NX_PROXY_CONN_LIMIT];

#endif /* #ifdef TRANS_CLIENT */

/*
 * Override the UNIX_DIR and UNIX_PATH settings and
 * make them configurable, based on the NX_TEMP or
 * the TEMP environment.
 *
 * We must be careful as the same defines are used
 * for different directories, based on the subsystem
 * that is compiling this, while we want to override
 * only the '/tmp/.X11-unix' and '/tmp/.X11-unix/X'
 * settings.
 */

static char _NXUnixDir[1024];
static char _NXUnixPath[1024];

static char *_NXGetUnixDir(char *dir)
{
    const char *tempDir;

    PRMSG (3, "_NXGetUnixDir(%s)\n", dir, 0, 0);

    if (strcmp(dir, UNIX_DIR) != 0)
    {
#ifdef NX_TRANS_TEST
        fprintf(stderr, "_NXGetUnixDir: Returning other Unix directory [%s].\n", dir);
#endif
        return dir;
    }

    /*
     * Check the environment only once.
     */

    if (*_NXUnixDir != '\0')
    {
        return _NXUnixDir;
    }

#ifdef NX_TRANS_TEST
    fprintf(stderr, "_NXGetUnixDir: Trying with the NX_TEMP environment.\n");
#endif

    tempDir = getenv("NX_TEMP");

    if (tempDir == NULL || *tempDir == '\0')
    {
#ifdef NX_TRANS_TEST
        fprintf(stderr, "_NXGetUnixDir: Trying with the TEMP environment.\n");
#endif

        tempDir = getenv("TEMP");
    }

    if (tempDir != NULL && *tempDir != '\0')
    {
        if (strlen(tempDir) + strlen("/.X11-unix") + 1 > 1024)
        {
#ifdef NX_TRANS_TEST
            fprintf(stderr, "_NXGetUnixDir: WARNING! Maximum length of X11 Unix directory exceeded.\n");
#endif
            goto _NXGetUnixDirError;
        }

        strcpy(_NXUnixDir, tempDir);
        strcat(_NXUnixDir, "/.X11-unix");

#ifdef NX_TRANS_TEST
        fprintf(stderr, "_NXGetUnixDir: Using X11 Unix directory [%s].\n", _NXUnixDir);
#endif

        return _NXUnixDir;
    }

_NXGetUnixDirError:

    strcpy(_NXUnixDir, dir);
 
#ifdef NX_TRANS_TEST
    fprintf(stderr, "_NXGetUnixDir: Returning default X11 Unix directory [%s].\n", _NXUnixDir);
#endif

    return _NXUnixDir;
}

static char *_NXGetUnixPath(char *path)
{
    const char *unixDir;

    PRMSG (3, "_NXGetUnixPath(%s)\n", path, 0, 0);

    if (strcmp(path, UNIX_PATH) != 0)
    {
#ifdef NX_TRANS_TEST
        fprintf(stderr, "_NXGetUnixPath: Returning other X11 Unix path [%s].\n", path);
#endif
        return path;
    }

    /*
     * Check the environment only once.
     */

    if (*_NXUnixPath != '\0')
    {
        return _NXUnixPath;
    }

    unixDir = _NXGetUnixDir(UNIX_DIR);

#ifdef NX_TRANS_TEST
    fprintf(stderr, "_NXGetUnixPath: Got X11 Unix directory [%s].\n", unixDir);
#endif

    if (strlen(unixDir) + strlen("/X") + 1 > 1024)
    {
#ifdef NX_TRANS_TEST
        fprintf(stderr, "_NXGetUnixPath: WARNING! Maximum length of X11 Unix path exceeded.\n");
#endif

        goto _NXGetUnixPathError;
    }

    strcpy(_NXUnixPath, unixDir);
    strcat(_NXUnixPath, "/X");

#ifdef NX_TRANS_TEST
    fprintf(stderr, "_NXGetUnixPath: Returning X11 Unix path [%s].\n", _NXUnixPath);
#endif

    return _NXUnixPath;

_NXGetUnixPathError:

    strcpy(_NXUnixPath, path);

#ifdef NX_TRANS_TEST
    fprintf(stderr, "_NXGetUnixPath: Returning default X11 Unix path [%s].\n", _NXUnixPath);
#endif

    return _NXUnixPath;
}


/*
 * Forcibly close any connection attempt on the
 * listening socket. Need this to avoid loopback
 * connections to the agent server.
 */

#ifdef TRANS_SERVER

void TRANS(SocketRejectConnection) (XtransConnInfo ciptr)
{
    socklen_t sa_l = sizeof(struct sockaddr);
    struct sockaddr sa;
    fd_set fs;
    struct timeval t;
    int f;

    PRMSG (3, "SocketRejectConnection(%x)\n", ciptr, 0, 0);

    FD_ZERO(&fs);
    FD_SET(ciptr -> fd, &fs);

    t.tv_sec  = 0;
    t.tv_usec = 0;

    /*
     * Check if there is an awaiting connection.
     */

    if (select(ciptr -> fd + 1, &fs, NULL, NULL, &t) == 1)
    {
#ifdef NX_TRANS_TEST
        fprintf(stderr, "SocketRejectConnection: Accepting connection attempt on fd [%d].\n",
                    ciptr -> fd);
#endif
        /*
         * If there is one, close it.
         */
 
        if ((f = accept(ciptr -> fd, &sa, &sa_l)) >= 0)
        {
#ifdef NX_TRANS_TEST
            fprintf(stderr, "SocketRejectConnection: Closing connection attempt on fd [%d].\n",
                        ciptr -> fd);
#endif
            close(f);
        }
    }
}

#endif /* #ifdef TRANS_SERVER */

#ifdef TRANS_CLIENT

void *TRANS(SocketProxyConnInfo) (XtransConnInfo ciptr)
{
    if (_NXProxyConnInfoTab[ciptr->fd] != NULL)
    {
      return ciptr->priv;
    }

    return NULL;
}

static XtransConnInfo TRANS(SocketCreateConnInfo) ()
{
    XtransConnInfo ciptr;

    int fds[2];

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketCreateConnInfo: Going to create the NX connection info.\n");
#endif

    if ((ciptr = (XtransConnInfo) calloc (1, sizeof(struct _XtransConnInfo))) == NULL)
    {
        PRMSG (1, "SocketCreateConnInfo: malloc failed\n", 0, 0, 0);
        return NULL;
    }

    /*
     * Create a pair of sockets. We'll communicate with
     * the NX proxy by reading and writing to our end.
     */

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketCreateConnInfo: Going to create the NX socketpair.\n");
#endif

    if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) < 0)
    {
        PRMSG (1, "SocketCreateConnInfo: socketpair() failed.\n", 0, 0, 0);
        free ((char *) ciptr);
        return NULL;
    }

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketCreateConnInfo: X socket end is [%d] NX proxy end is [%d].\n",
                fds[0], fds[1]);
#endif

    /*
     * Save in _NXProxyConnInfoTab the local and remote end of
     * the socketpair. The remote end will be used by the proxy.
     * When the memory-to-memory transport is activated, the
     * agent and the proxy don't read or write to the real des-
     * criptors but the communication takes place by reading
     * and writing to the proxy's buffers.
     */

    ciptr->fd = fds[0];

    if (ciptr->fd >= NX_PROXY_CONN_LIMIT)
    {
        PRMSG (1, "SocketCreateConnInfo: No space for a new _NXProxyConnInfo for [%d].\n",
                  ciptr->fd, 0, 0);
        free ((char *) ciptr);
        return NULL;
    }
    else if (_NXProxyConnInfoTab[ciptr->fd] != NULL)
    {
        PRMSG (1, "SocketCreateConnInfo: _NXProxyConnInfo for [%d] is not NULL. Exiting.\n",
                   ciptr->fd, 0, 0);
        exit(1);
    }

    _NXProxyConnInfoTab[ciptr->fd] = (_NXProxyConnInfo *) calloc(1, sizeof(_NXProxyConnInfo));

    if (_NXProxyConnInfoTab[ciptr->fd] == NULL)
    {
        PRMSG (1, "SocketCreateConnInfo: Alloc of _NXProxyConnInfo failed.\n", 0, 0, 0);
        free ((char *) ciptr);
        return NULL;
    }

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketCreateConnInfo: Allocated new _NXProxyConnInfo for [%d].\n",
                ciptr->fd);
#endif

    _NXProxyConnInfoTab[ciptr->fd]->info       = ciptr;
    _NXProxyConnInfoTab[ciptr->fd]->local      = fds[0];
    _NXProxyConnInfoTab[ciptr->fd]->remote     = fds[1];
    _NXProxyConnInfoTab[ciptr->fd]->congestion = 0;

    ciptr->priv = (char *) _NXProxyConnInfoTab[ciptr->fd];

    return ciptr;
}

static int TRANS(SocketConnectConnInfo) (XtransConnInfo ciptr, char *host, char *port)
{
    int fds[2];
    char display[1024];

    _NXProxyConnInfo *proxy_conn;

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketConnectConnInfo: Going to connect NX fd [%d] to host [%s] port [%s].\n",
                ciptr->fd, host, port);
#endif

    /*
     * We should have already created the socket pair.
     */

    proxy_conn = (_NXProxyConnInfo *) ciptr->priv;

    if (proxy_conn == NULL)
    {
        PRMSG (1, "SocketConnectConnInfo: Pointer to _NXProxyConnInfo is NULL. Exiting.\n", 0, 0, 0);

        exit(1);
    }
    else if (_NXProxyConnInfoTab[ciptr->fd] != (_NXProxyConnInfo *) ciptr->priv)
    {
        PRMSG (1, "SocketConnectConnInfo: Can't find _NXProxyConnInfo in table. Exiting.\n",
                   0, 0, 0);

        exit(1);
    }

    if (strlen(host) + strlen(port) + 1 >= 1023)
    {
        PRMSG (1, "SocketConnectConnInfo: Length of NX display string '%s:%s' would exceed %d characters.\n",
                   host, port, 1023);

        return TRANS_CONNECT_FAILED;
    }

    sprintf(display, "%s:%s", host, port);

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketConnectConnInfo: Setting close-on-exec flag on local NX descriptor [%d].\n",
                proxy_conn -> local);
#endif

#ifdef F_SETFD
#ifdef FD_CLOEXEC
    if (fcntl(proxy_conn -> local, F_SETFD, FD_CLOEXEC) != 0)
#else
    if (fcntl(proxy_conn -> local, F_SETFD, 1) != 0)
#endif
#endif
    {
        PRMSG (1, "SocketConnectConnInfo: Cannot set close-on-exec on local NX descriptor [%d].\n",
                   proxy_conn -> local, 0, 0);

        return TRANS_CONNECT_FAILED;
    }

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketConnectConnInfo: Creating the NX transport with display [%s].\n",
                display);
#endif

    if (NXTransCreate(NX_FD_ANY, NX_MODE_CLIENT, display) < 0)
    {
        PRMSG (1, "SocketConnectConnInfo: Cannot create the NX transport.\n",
                   0, 0, 0);

        return TRANS_CONNECT_FAILED;
    }

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketConnectConnInfo: Starting the NX agent with descriptor [%d].\n",
                proxy_conn -> remote);
#endif

    fds[0] = proxy_conn -> local;
    fds[1] = proxy_conn -> remote;

    NXTransAgent(fds);

    return 0;
}

static void TRANS(SocketCloseConnInfo) (XtransConnInfo ciptr)
{
    _NXProxyConnInfo *proxy_conn;

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketCloseConnInfo: Going to close the NX fd [%d].\n", ciptr->fd);
#endif

    proxy_conn = (_NXProxyConnInfo *) ciptr->priv;

    if (proxy_conn == NULL)
    {
        PRMSG (1, "SocketCloseConnInfo: Pointer to _NXProxyConnInfo is NULL. Exiting.\n", 0, 0, 0);

        exit(1);
    }
    else if (ciptr->fd >= NX_PROXY_CONN_LIMIT ||
                 _NXProxyConnInfoTab[ciptr->fd] != (_NXProxyConnInfo *) ciptr->priv)
    {
        PRMSG (1, "SocketCloseConnInfo: Can't find _NXProxyConnInfo in table. Exiting.\n",
                   0, 0, 0);
        exit(1);
    }
    else if (_NXProxyConnInfoTab[ciptr->fd] -> info != ciptr ||
                 _NXProxyConnInfoTab[ciptr->fd] -> local != ciptr->fd)
    {
        PRMSG (1, "SocketCloseConnInfo: Invalid _NXProxyConnInfo structure for [%d]. Exiting.\n",
                   ciptr->fd, 0, 0);
        exit(1);
    }
    else if (proxy_conn->local < 0 || proxy_conn->remote < 0)
    {
        PRMSG (1, "SocketCloseConnInfo: Invalid socket pair in NX connection for [%d]. Exiting.\n",
                   ciptr->fd, 0, 0);
        exit(1);
    }

    NXTransClose(ciptr->fd);

    /*
     *  Get rid of the _NXProxyConnInfo structure.
     */

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketCloseConnInfo: Freeing _NXProxyConnInfo structure for [%d].\n",
                ciptr->fd);
#endif

    free((char *) _NXProxyConnInfoTab[ciptr->fd]);

    _NXProxyConnInfoTab[ciptr->fd] = NULL;

    ciptr->priv = NULL;

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketCloseConnInfo: Should now close the local descriptor [%d].\n",
                ciptr->fd);
#endif
}

#endif /* #ifdef TRANS_CLIENT */

#if defined(TRANS_CLIENT) && defined(NX_TRANS_CHANGE)

/*
 * Check the congestion state of the NX transport
 * and return 1 if there has been a change. This
 * can be extended by adding a few counters track-
 * ing the bandwidth usage of the X11 connection.
 */

int TRANS(SocketCongestionChange) (XtransConnInfo ciptr, int *state)
{
    int congestion;

    _NXProxyConnInfo *proxy_conn;

    PRMSG (3, "SocketCongestionChange(%x)\n", ciptr, 0, 0);

    proxy_conn = (_NXProxyConnInfo *) ciptr->priv;

    if (proxy_conn == NULL)
    {
#ifdef NX_TRANS_DEBUG
        fprintf(stderr, "SocketCongestionChange: Descriptor [%d] doesn't appear to be a NX connection.\n",
                    ciptr->fd);
#endif
        return 0;
    }

#ifdef NX_TRANS_DEBUG
    fprintf(stderr, "SocketCongestionChange: Checking congestion on fd [%d] with old state [%d].\n",
                ciptr->fd, proxy_conn->congestion);
#endif

    congestion = NXTransCongestion(ciptr->fd);

    if (congestion != proxy_conn->congestion)
    {
        proxy_conn->congestion = congestion;

#ifdef NX_TRANS_TEST
        fprintf(stderr, "SocketCongestionChange: Change detected on fd [%d] with new state [%d].\n",
                    ciptr->fd, proxy_conn->congestion);
#endif
        return 1;
    }

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketCongestionChange: No change on fd [%d] with current state [%d].\n",
                ciptr->fd, congestion);
#endif
    return 0;
}

#endif /* #if defined(TRANS_CLIENT) && defined(NX_TRANS_CHANGE) */

#endif /* #ifdef NX_TRANS_SOCKET */

/*
 * These are some utility function used by the real interface function below.
 */

static int
TRANS(SocketSelectFamily) (int first, char *family)

{
    int     i;

    PRMSG (3,"SocketSelectFamily(%s)\n", family, 0, 0);

    for (i = first + 1; i < NUMSOCKETFAMILIES;i++)
    {
        if (!strcmp (family, Sockettrans2devtab[i].transname))
	    return i;
    }

    return (first == -1 ? -2 : -1);
}


/*
 * This function gets the local address of the socket and stores it in the
 * XtransConnInfo structure for the connection.
 */

static int
TRANS(SocketINETGetAddr) (XtransConnInfo ciptr)

{
#if defined(IPv6) && defined(AF_INET6)
    struct sockaddr_storage socknamev6;
#endif
    struct sockaddr_in socknamev4;
    void *socknamePtr;
#if defined(SVR4) || defined(__SCO__)
#   define SOCKLEN_T_PTR void*
    size_t namelen;
#else
#   define SOCKLEN_T_PTR socklen_t*
    socklen_t namelen;
#endif

    PRMSG (3,"SocketINETGetAddr(%p)\n", ciptr, 0, 0);

#if defined(IPv6) && defined(AF_INET6)
    if (haveIPv6)
    {
	namelen = sizeof(socknamev6);
	socknamePtr = &socknamev6;
    }
    else
#endif
    {
	namelen = sizeof(socknamev4);
	socknamePtr = &socknamev4;
    }

    if (getsockname (ciptr->fd,(struct sockaddr *) socknamePtr,
		     (SOCKLEN_T_PTR)&namelen) < 0)
    {
#ifdef WIN32
	errno = WSAGetLastError();
#endif
	PRMSG (1,"SocketINETGetAddr: getsockname() failed: %d\n",
	    EGET(),0, 0);
	return -1;
    }

    /*
     * Everything looks good: fill in the XtransConnInfo structure.
     */

    if ((ciptr->addr = (char *) malloc (namelen)) == NULL)
    {
        PRMSG (1,
	    "SocketINETGetAddr: Can't allocate space for the addr\n",
	    0, 0, 0);
        return -1;
    }

#if defined(IPv6) && defined(AF_INET6)
    if (haveIPv6)
    {
	ciptr->family = ((struct sockaddr *)socknamePtr)->sa_family;
    }
    else
#endif
    {
	ciptr->family = socknamev4.sin_family;
    }
    ciptr->addrlen = namelen;
    memcpy (ciptr->addr, socknamePtr, ciptr->addrlen);

    return 0;
}


/*
 * This function gets the remote address of the socket and stores it in the
 * XtransConnInfo structure for the connection.
 */

static int
TRANS(SocketINETGetPeerAddr) (XtransConnInfo ciptr)

{
#if defined(IPv6) && defined(AF_INET6)
    struct sockaddr_storage socknamev6;
#endif
    struct sockaddr_in 	socknamev4;
    void *socknamePtr;
#if defined(SVR4) || defined(__SCO__)
    size_t namelen;
#else
    int namelen;
#endif

#if defined(IPv6) && defined(AF_INET6)
    if (haveIPv6 && ciptr->family == AF_INET6)
    {
	namelen = sizeof(socknamev6);
	socknamePtr = &socknamev6;
    }
    else
#endif
    {
	namelen = sizeof(socknamev4);
	socknamePtr = &socknamev4;
    }

    PRMSG (3,"SocketINETGetPeerAddr(%p)\n", ciptr, 0, 0);

    if (getpeername (ciptr->fd, (struct sockaddr *) socknamePtr,
		     (void *)&namelen) < 0)
    {
#ifdef WIN32
	errno = WSAGetLastError();
#endif
	PRMSG (1,"SocketINETGetPeerAddr: getpeername() failed: %d\n",
	    EGET(), 0, 0);
	return -1;
    }

    /*
     * Everything looks good: fill in the XtransConnInfo structure.
     */

    if ((ciptr->peeraddr = (char *) malloc (namelen)) == NULL)
    {
        PRMSG (1,
	   "SocketINETGetPeerAddr: Can't allocate space for the addr\n",
	   0, 0, 0);
        return -1;
    }

    ciptr->peeraddrlen = namelen;
    memcpy (ciptr->peeraddr, socknamePtr, ciptr->peeraddrlen);

    return 0;
}


static XtransConnInfo
TRANS(SocketOpen) (int i, int type)

{
    XtransConnInfo	ciptr;

    PRMSG (3,"SocketOpen(%d,%d)\n", i, type, 0);

#if defined(IPv6) && defined(AF_INET6)
    if (getaddrinfo == NULL)
	haveIPv6 = 0;

    if (!haveIPv6 && Sockettrans2devtab[i].family == AF_INET6)
	return NULL;
#endif

    if ((ciptr = (XtransConnInfo) calloc (
	1, sizeof(struct _XtransConnInfo))) == NULL)
    {
	PRMSG (1, "SocketOpen: malloc failed\n", 0, 0, 0);
	return NULL;
    }

    if ((ciptr->fd = socket(Sockettrans2devtab[i].family, type,
	Sockettrans2devtab[i].protocol)) < 0
#ifndef WIN32
#if (defined(X11_t) && !defined(USE_POLL)) || defined(FS_t) || defined(FONT_t)
       || ciptr->fd >= TRANS_OPEN_MAX
#endif
#endif
      ) {
#ifdef WIN32
	errno = WSAGetLastError();
#endif
	PRMSG (2, "SocketOpen: socket() failed for %s\n",
	    Sockettrans2devtab[i].transname, 0, 0);

	free ((char *) ciptr);
	return NULL;
    }

#ifdef TCP_NODELAY
    if (Sockettrans2devtab[i].family == AF_INET
#if defined(IPv6) && defined(AF_INET6)
      || Sockettrans2devtab[i].family == AF_INET6
#endif
    )
    {
	/*
	 * turn off TCP coalescence for INET sockets
	 */

	int tmp = 1;
	setsockopt (ciptr->fd, IPPROTO_TCP, TCP_NODELAY,
	    (char *) &tmp, sizeof (int));
    }
#endif

    return ciptr;
}


#ifdef TRANS_REOPEN

static XtransConnInfo
TRANS(SocketReopen) (int i, int type, int fd, char *port)

{
    XtransConnInfo	ciptr;

    PRMSG (3,"SocketReopen(%d,%d,%s)\n", type, fd, port);

    if ((ciptr = (XtransConnInfo) calloc (
	1, sizeof(struct _XtransConnInfo))) == NULL)
    {
	PRMSG (1, "SocketReopen: malloc failed\n", 0, 0, 0);
	return NULL;
    }

    ciptr->fd = fd;

    return ciptr;
}

#endif /* TRANS_REOPEN */


/*
 * These functions are the interface supplied in the Xtransport structure
 */

#ifdef TRANS_CLIENT

static XtransConnInfo
TRANS(SocketOpenCOTSClientBase) (char *transname, char *protocol,
				char *host, char *port, int previndex)
{
    XtransConnInfo	ciptr;
    int			i = previndex;

    PRMSG (2, "SocketOpenCOTSClient(%s,%s,%s)\n",
	protocol, host, port);

    SocketInitOnce();

    while ((i = TRANS(SocketSelectFamily) (i, transname)) >= 0) {

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

        if ((!strcmp(protocol, "local") || !strcmp(protocol, "nx")) &&
                (!strcasecmp(host, "nx") || !strncasecmp(host, "nx,", 3)))
        {
            ciptr = TRANS(SocketCreateConnInfo) ();

            if (ciptr == NULL)
            {
                PRMSG (1, "SocketOpenCOTSClient: Unable to create the NX connection info for %s.\n",
                           transname, 0, 0);

                return NULL;
            }

            ciptr->index = i;

            return ciptr;
        }

#endif /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */

	if ((ciptr = TRANS(SocketOpen) (
		 i, Sockettrans2devtab[i].devcotsname)) != NULL)
	    break;
    }
    if (i < 0) {
	if (i == -1)
	    PRMSG (1,"SocketOpenCOTSClient: Unable to open socket for %s\n",
		   transname, 0, 0);
	else
	    PRMSG (1,"SocketOpenCOTSClient: Unable to determine socket type for %s\n",
		   transname, 0, 0);
	return NULL;
    }

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

    ciptr->priv = NULL;

#endif

    /* Save the index for later use */

    ciptr->index = i;

    return ciptr;
}

static XtransConnInfo
TRANS(SocketOpenCOTSClient) (Xtransport *thistrans, char *protocol, 
			     char *host, char *port)
{
    return TRANS(SocketOpenCOTSClientBase)(
			thistrans->TransName, protocol, host, port, -1);
}


#endif /* TRANS_CLIENT */


#ifdef TRANS_SERVER

static XtransConnInfo
TRANS(SocketOpenCOTSServer) (Xtransport *thistrans, char *protocol, 
			     char *host, char *port)

{
    XtransConnInfo	ciptr;
    int	i = -1;

    PRMSG (2,"SocketOpenCOTSServer(%s,%s,%s)\n", protocol, host, port);

    SocketInitOnce();

    while ((i = TRANS(SocketSelectFamily) (i, thistrans->TransName)) >= 0) {
	if ((ciptr = TRANS(SocketOpen) (
		 i, Sockettrans2devtab[i].devcotsname)) != NULL)
	    break;
    }
    if (i < 0) {
	if (i == -1)
	    PRMSG (1,"SocketOpenCOTSServer: Unable to open socket for %s\n",
		   thistrans->TransName, 0, 0);
	else
	    PRMSG (1,"SocketOpenCOTSServer: Unable to determine socket type for %s\n",
		   thistrans->TransName, 0, 0);
	return NULL;
    }

    /*
     * Using this prevents the bind() check for an existing server listening
     * on the same port, but it is required for other reasons.
     */
#ifdef SO_REUSEADDR

    /*
     * SO_REUSEADDR only applied to AF_INET && AF_INET6
     */

    if (Sockettrans2devtab[i].family == AF_INET
#if defined(IPv6) && defined(AF_INET6)
      || Sockettrans2devtab[i].family == AF_INET6
#endif
    )
    {
	int one = 1;
	setsockopt (ciptr->fd, SOL_SOCKET, SO_REUSEADDR,
		    (char *) &one, sizeof (int));
    }
#endif
#ifdef IPV6_V6ONLY
    if (Sockettrans2devtab[i].family == AF_INET6)
    {
	int one = 1;
	setsockopt(ciptr->fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(int));
    }
#endif
    /* Save the index for later use */

    ciptr->index = i;

    return ciptr;
}

#endif /* TRANS_SERVER */


#ifdef TRANS_CLIENT

static XtransConnInfo
TRANS(SocketOpenCLTSClient) (Xtransport *thistrans, char *protocol, 
			     char *host, char *port)

{
    XtransConnInfo	ciptr;
    int			i = -1;

    PRMSG (2,"SocketOpenCLTSClient(%s,%s,%s)\n", protocol, host, port);

    SocketInitOnce();

    while ((i = TRANS(SocketSelectFamily) (i, thistrans->TransName)) >= 0) {

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

        if ((!strcmp(protocol, "local") || !strcmp(protocol, "nx")) &&
                (!strcasecmp(host, "nx") || !strncasecmp(host, "nx,", 3)))
        {
            ciptr = TRANS(SocketCreateConnInfo) ();

            if (ciptr == NULL)
            {
                PRMSG (1, "SocketOpenCLTSClient: Unable to create the NX connection info for %s.\n",
                           thistrans->TransName, 0, 0);

                return NULL;
            }

            ciptr->index = i;

            return ciptr;
        }

#endif /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */

	if ((ciptr = TRANS(SocketOpen) (
		 i, Sockettrans2devtab[i].devcotsname)) != NULL)
	    break;
    }
    if (i < 0) {
	if (i == -1)
	    PRMSG (1,"SocketOpenCLTSClient: Unable to open socket for %s\n",
		   thistrans->TransName, 0, 0);
	else
	    PRMSG (1,"SocketOpenCLTSClient: Unable to determine socket type for %s\n",
		   thistrans->TransName, 0, 0);
	return NULL;
    }

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

    ciptr->priv = NULL;

#endif /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */

    /* Save the index for later use */

    ciptr->index = i;

    return ciptr;
}

#endif /* TRANS_CLIENT */


#ifdef TRANS_SERVER

static XtransConnInfo
TRANS(SocketOpenCLTSServer) (Xtransport *thistrans, char *protocol, 
			     char *host, char *port)

{
    XtransConnInfo	ciptr;
    int	i = -1;

    PRMSG (2,"SocketOpenCLTSServer(%s,%s,%s)\n", protocol, host, port);

    SocketInitOnce();

    while ((i = TRANS(SocketSelectFamily) (i, thistrans->TransName)) >= 0) {
	if ((ciptr = TRANS(SocketOpen) (
		 i, Sockettrans2devtab[i].devcotsname)) != NULL)
	    break;
    }
    if (i < 0) {
	if (i == -1)
	    PRMSG (1,"SocketOpenCLTSServer: Unable to open socket for %s\n",
		   thistrans->TransName, 0, 0);
	else
	    PRMSG (1,"SocketOpenCLTSServer: Unable to determine socket type for %s\n",
		   thistrans->TransName, 0, 0);
	return NULL;
    }

#ifdef IPV6_V6ONLY
    if (Sockettrans2devtab[i].family == AF_INET6)
    {
	int one = 1;
	setsockopt(ciptr->fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(int));
    }
#endif
    /* Save the index for later use */

    ciptr->index = i;

    return ciptr;
}

#endif /* TRANS_SERVER */


#ifdef TRANS_REOPEN

static XtransConnInfo
TRANS(SocketReopenCOTSServer) (Xtransport *thistrans, int fd, char *port)

{
    XtransConnInfo	ciptr;
    int			i = -1;

    PRMSG (2,
	"SocketReopenCOTSServer(%d, %s)\n", fd, port, 0);

    SocketInitOnce();

    while ((i = TRANS(SocketSelectFamily) (i, thistrans->TransName)) >= 0) {
	if ((ciptr = TRANS(SocketReopen) (
		 i, Sockettrans2devtab[i].devcotsname, fd, port)) != NULL)
	    break;
    }
    if (i < 0) {
	if (i == -1)
	    PRMSG (1,"SocketReopenCOTSServer: Unable to open socket for %s\n",
		   thistrans->TransName, 0, 0);
	else
	    PRMSG (1,"SocketReopenCOTSServer: Unable to determine socket type for %s\n",
		   thistrans->TransName, 0, 0);
	return NULL;
    }

    /* Save the index for later use */

    ciptr->index = i;

    return ciptr;
}

static XtransConnInfo
TRANS(SocketReopenCLTSServer) (Xtransport *thistrans, int fd, char *port)

{
    XtransConnInfo	ciptr;
    int			i = -1;

    PRMSG (2,
	"SocketReopenCLTSServer(%d, %s)\n", fd, port, 0);

    SocketInitOnce();

    while ((i = TRANS(SocketSelectFamily) (i, thistrans->TransName)) >= 0) {
	if ((ciptr = TRANS(SocketReopen) (
		 i, Sockettrans2devtab[i].devcotsname, fd, port)) != NULL)
	    break;
    }
    if (i < 0) {
	if (i == -1)
	    PRMSG (1,"SocketReopenCLTSServer: Unable to open socket for %s\n",
		   thistrans->TransName, 0, 0);
	else
	    PRMSG (1,"SocketReopenCLTSServer: Unable to determine socket type for %s\n",
		   thistrans->TransName, 0, 0);
	return NULL;
    }

    /* Save the index for later use */

    ciptr->index = i;

    return ciptr;
}

#endif /* TRANS_REOPEN */


static int
TRANS(SocketSetOption) (XtransConnInfo ciptr, int option, int arg)

{
    PRMSG (2,"SocketSetOption(%d,%d,%d)\n", ciptr->fd, option, arg);

#ifdef NX_TRANS_TEST
    fprintf(stderr, "SocketSetOption: WARNING! Not setting option [%d] with value [%d] on descriptor [%d].\n",
                option, arg, ciptr -> fd);
#endif

    return -1;
}

#ifdef UNIXCONN
static int
set_sun_path(const char *port, const char *upath, char *path, int abstract)
{
    struct sockaddr_un s;
    int maxlen = sizeof(s.sun_path) - 1;
    const char *at = "";

    if (!port || !*port || !path)
	return -1;

#ifdef HAVE_ABSTRACT_SOCKETS
    if (port[0] == '@')
	upath = "";
    else if (abstract)
	at = "@";
#endif

    if (*port == '/') /* a full pathname */
	upath = "";

    if (strlen(port) + strlen(upath) > maxlen)
	return -1;
    snprintf(path, sizeof(s.sun_path), "%s%s%s", at, upath, port);
    return 0;
}
#endif

#ifdef TRANS_SERVER

static int
TRANS(SocketCreateListener) (XtransConnInfo ciptr, 
			     struct sockaddr *sockname,
			     int socknamelen, unsigned int flags)

{
    int	namelen = socknamelen;
    int	fd = ciptr->fd;
    int	retry;

    PRMSG (3, "SocketCreateListener(%x,%p)\n", ciptr, fd, 0);

    if (Sockettrans2devtab[ciptr->index].family == AF_INET
#if defined(IPv6) && defined(AF_INET6)
      || Sockettrans2devtab[ciptr->index].family == AF_INET6
#endif
	)
	retry = 20;
    else
	retry = 0;

#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
    fprintf(stderr, "SocketCreateListener: Creating listener for ciptr at [%p] on path [%s].\n",
                (void *) ciptr, ((struct sockaddr_un *) sockname)->sun_family == AF_UNIX ?
                    ((struct sockaddr_un *) sockname)->sun_path : "TCP");
#endif
    while (bind (fd, (struct sockaddr *) sockname, namelen) < 0)
    {
	if (errno == EADDRINUSE) {
	    if (flags & ADDR_IN_USE_ALLOWED)
		break;
	    else
		return TRANS_ADDR_IN_USE;
	}
	
	if (retry-- == 0) {
	    PRMSG (1, "SocketCreateListener: failed to bind listener\n",
		0, 0, 0);
	    close (fd);
	    return TRANS_CREATE_LISTENER_FAILED;
	}
#ifdef SO_REUSEADDR
	sleep (1);
#else
	sleep (10);
#endif /* SO_REUSEDADDR */
    }

    if (Sockettrans2devtab[ciptr->index].family == AF_INET
#if defined(IPv6) && defined(AF_INET6)
      || Sockettrans2devtab[ciptr->index].family == AF_INET6
#endif
	) {
#ifdef SO_DONTLINGER
	setsockopt (fd, SOL_SOCKET, SO_DONTLINGER, (char *) NULL, 0);
#else
#ifdef SO_LINGER
    {
	static int linger[2] = { 0, 0 };
	setsockopt (fd, SOL_SOCKET, SO_LINGER,
		(char *) linger, sizeof (linger));
    }
#endif
#endif
}

    if (listen (fd, BACKLOG) < 0)
    {
	PRMSG (1, "SocketCreateListener: listen() failed\n", 0, 0, 0);
	close (fd);
	return TRANS_CREATE_LISTENER_FAILED;
    }
	
    /* Set a flag to indicate that this connection is a listener */

    ciptr->flags = 1 | (ciptr->flags & TRANS_KEEPFLAGS);

#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
    fprintf(stderr, "SocketCreateListener: Set flags to [%d] for ciptr [%p].\n",
                ciptr->flags, (void *) ciptr);
#endif

    return 0;
}

#ifdef TCPCONN
static int
TRANS(SocketINETCreateListener) (XtransConnInfo ciptr, char *port, unsigned int flags)

{
#if defined(IPv6) && defined(AF_INET6)
    struct sockaddr_storage sockname;
#else
    struct sockaddr_in	    sockname;
#endif
    unsigned short	    sport;
    int		namelen = sizeof(sockname);
    int		status;
    long	tmpport;
#ifdef XTHREADS_NEEDS_BYNAMEPARAMS
    _Xgetservbynameparams sparams;
#endif
    struct servent *servp;

#ifdef X11_t
    char	portbuf[PORTBUFSIZE];
#endif
    
    PRMSG (2, "SocketINETCreateListener(%s)\n", port, 0, 0);

#ifdef X11_t
    /*
     * X has a well known port, that is transport dependent. It is easier
     * to handle it here, than try and come up with a transport independent
     * representation that can be passed in and resolved the usual way.
     *
     * The port that is passed here is really a string containing the idisplay
     * from ConnectDisplay().
     */

    if (is_numeric (port))
    {
	/* fixup the server port address */
	tmpport = X_TCP_PORT + strtol (port, (char**)NULL, 10);
	sprintf (portbuf,"%lu", tmpport);
	port = portbuf;
    }
#endif

    if (port && *port)
    {
	/* Check to see if the port string is just a number (handles X11) */

	if (!is_numeric (port))
	{
	    if ((servp = _XGetservbyname (port,"tcp",sparams)) == NULL)
	    {
		PRMSG (1,
	     "SocketINETCreateListener: Unable to get service for %s\n",
		      port, 0, 0);
		return TRANS_CREATE_LISTENER_FAILED;
	    }
	    /* we trust getservbyname to return a valid number */
	    sport = servp->s_port;
	}
	else
	{
	    tmpport = strtol (port, (char**)NULL, 10);
	    /* 
	     * check that somehow the port address isn't negative or in
	     * the range of reserved port addresses. This can happen and
	     * be very bad if the server is suid-root and the user does 
	     * something (dumb) like `X :60049`. 
	     */
	    if (tmpport < 1024 || tmpport > USHRT_MAX)
		return TRANS_CREATE_LISTENER_FAILED;

	    sport = (unsigned short) tmpport;
	}
    }
    else
	sport = 0;

    bzero(&sockname, sizeof(sockname));
#if defined(IPv6) && defined(AF_INET6)
    if (Sockettrans2devtab[ciptr->index].family == AF_INET) {
	namelen = sizeof (struct sockaddr_in);
#ifdef BSD44SOCKETS
	((struct sockaddr_in *)&sockname)->sin_len = namelen;
#endif
	((struct sockaddr_in *)&sockname)->sin_family = AF_INET;
	((struct sockaddr_in *)&sockname)->sin_port = htons(sport);
	((struct sockaddr_in *)&sockname)->sin_addr.s_addr = htonl(INADDR_ANY);
    } else {
	namelen = sizeof (struct sockaddr_in6);
#ifdef SIN6_LEN
	((struct sockaddr_in6 *)&sockname)->sin6_len = sizeof(sockname);
#endif
	((struct sockaddr_in6 *)&sockname)->sin6_family = AF_INET6;
	((struct sockaddr_in6 *)&sockname)->sin6_port = htons(sport);
	((struct sockaddr_in6 *)&sockname)->sin6_addr = in6addr_any;
    }
#else
#ifdef BSD44SOCKETS
    sockname.sin_len = sizeof (sockname);
#endif
    sockname.sin_family = AF_INET;
    sockname.sin_port = htons (sport);
    sockname.sin_addr.s_addr = htonl (INADDR_ANY);
#endif

    if ((status = TRANS(SocketCreateListener) (ciptr,
	(struct sockaddr *) &sockname, namelen, flags)) < 0)
    {
	PRMSG (1,
    "SocketINETCreateListener: ...SocketCreateListener() failed\n",
	    0, 0, 0);
	return status;
    }

    if (TRANS(SocketINETGetAddr) (ciptr) < 0)
    {
	PRMSG (1,
       "SocketINETCreateListener: ...SocketINETGetAddr() failed\n",
	    0, 0, 0);
	return TRANS_CREATE_LISTENER_FAILED;
    }

    return 0;
}

#endif /* SOCKCONN */


#ifdef UNIXCONN

static int
TRANS(SocketUNIXCreateListener) (XtransConnInfo ciptr, char *port,
				 unsigned int flags)

{
    struct sockaddr_un	sockname;
    int			namelen;
    int			oldUmask;
    int			status;
    unsigned int	mode;
    char		tmpport[108];

    int			abstract = 0;
#ifdef HAVE_ABSTRACT_SOCKETS
    abstract = ciptr->transptr->flags & TRANS_ABSTRACT;
#endif

    PRMSG (2, "SocketUNIXCreateListener(%s)\n",
	port ? port : "NULL", 0, 0);

    /* Make sure the directory is created */

    oldUmask = umask (0);

#ifdef UNIX_DIR
#ifdef HAS_STICKY_DIR_BIT
    mode = 01777;
#else
    mode = 0777;
#endif
#ifdef NX_TRANS_SOCKET
    if (!abstract && trans_mkdir(_NXGetUnixDir(UNIX_DIR), mode) == -1) {
        PRMSG (1, "SocketUNIXCreateListener: mkdir(%s) failed, errno = %d\n",
               _NXGetUnixDir(UNIX_DIR), errno, 0);
#else
    if (!abstract && trans_mkdir(UNIX_DIR, mode) == -1) {
	PRMSG (1, "SocketUNIXCreateListener: mkdir(%s) failed, errno = %d\n",
	       UNIX_DIR, errno, 0);
#endif
	(void) umask (oldUmask);
	return TRANS_CREATE_LISTENER_FAILED;
    }
#endif

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

    if (!(port && *port)) {
	snprintf (tmpport, sizeof(tmpport), "%s%ld", UNIX_PATH, (long)getpid());
	port = tmpport;
    }
    if (port && *port) {
#ifdef NX_TRANS_SOCKET
        if (set_sun_path(port, _NXGetUnixPath(UNIX_PATH), sockname.sun_path, abstract) != 0) {
#else
	if (set_sun_path(port, UNIX_PATH, sockname.sun_path, abstract) != 0) {
#endif
	    PRMSG (1, "SocketUNIXCreateListener: path too long\n", 0, 0, 0);
	    return TRANS_CREATE_LISTENER_FAILED;
	}
    } else {
#ifdef NX_TRANS_SOCKET
	sprintf (sockname.sun_path, "%s%ld", _NXGetUnixPath(UNIX_PATH), (long)getpid());
#else
	sprintf (sockname.sun_path, "%s%ld", UNIX_PATH, (long)getpid());
#endif
    }

#if (defined(BSD44SOCKETS) || defined(__UNIXWARE__)) && !defined(Lynx)
    sockname.sun_len = strlen(sockname.sun_path);
    namelen = SUN_LEN(&sockname);
#else
    namelen = strlen(sockname.sun_path) + sizeof(sockname.sun_family);
#endif

#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
    fprintf(stderr, "SocketUNIXCreateListener: Unlinking path [%s] for ciptr at [%p].\n",
                sockname.sun_path, (void *) ciptr);
#endif
    if (abstract) {
	sockname.sun_path[0] = '\0';
	namelen = offsetof(struct sockaddr_un, sun_path) + 1 + strlen(&sockname.sun_path[1]);
    }
    else
	unlink (sockname.sun_path);

    if ((status = TRANS(SocketCreateListener) (ciptr,
	(struct sockaddr *) &sockname, namelen, flags)) < 0)
    {
	PRMSG (1,
    "SocketUNIXCreateListener: ...SocketCreateListener() failed\n",
	    0, 0, 0);
	(void) umask (oldUmask);
	return status;
    }

    /*
     * Now that the listener is esablished, create the addr info for
     * this connection. getpeername() doesn't work for UNIX Domain Sockets
     * on some systems (hpux at least), so we will just do it manually, instead
     * of calling something like TRANS(SocketUNIXGetAddr).
     */

    namelen = sizeof (sockname); /* this will always make it the same size */

    if ((ciptr->addr = (char *) malloc (namelen)) == NULL)
    {
        PRMSG (1,
        "SocketUNIXCreateListener: Can't allocate space for the addr\n",
	    0, 0, 0);
	(void) umask (oldUmask);
        return TRANS_CREATE_LISTENER_FAILED;
    }

    if (abstract)
	sockname.sun_path[0] = '@';

    ciptr->family = sockname.sun_family;
    ciptr->addrlen = namelen;
    memcpy (ciptr->addr, &sockname, ciptr->addrlen);

    (void) umask (oldUmask);

    return 0;
}

static int
TRANS(SocketUNIXResetListener) (XtransConnInfo ciptr)

{
    /*
     * See if the unix domain socket has disappeared.  If it has, recreate it.
     */

    struct sockaddr_un 	*unsock = (struct sockaddr_un *) ciptr->addr;
    struct stat		statb;
    int 		status = TRANS_RESET_NOOP;
    unsigned int	mode;
    int abstract = 0;
#ifdef HAVE_ABSTRACT_SOCKETS
    abstract = ciptr->transptr->flags & TRANS_ABSTRACT;
#endif

    PRMSG (3, "SocketUNIXResetListener(%p,%d)\n", ciptr, ciptr->fd, 0);

    if (!abstract && (
	stat (unsock->sun_path, &statb) == -1 ||
        ((statb.st_mode & S_IFMT) !=
#if (defined (sun) && defined(SVR4)) || defined(NCR) || defined(SCO325) || !defined(S_IFSOCK)
	  		S_IFIFO))
#else
			S_IFSOCK)))
#endif
    {
	int oldUmask = umask (0);

#ifdef UNIX_DIR
#ifdef HAS_STICKY_DIR_BIT
	mode = 01777;
#else
	mode = 0777;
#endif
#ifdef NX_TRANS_SOCKET
        if (trans_mkdir(_NXGetUnixDir(UNIX_DIR), mode) == -1) {
            PRMSG (1, "SocketUNIXResetListener: mkdir(%s) failed, errno = %d\n",
            _NXGetUnixDir(UNIX_DIR), errno, 0);
#else
        if (trans_mkdir(UNIX_DIR, mode) == -1) {
            PRMSG (1, "SocketUNIXResetListener: mkdir(%s) failed, errno = %d\n",
	    UNIX_DIR, errno, 0);
#endif
	    (void) umask (oldUmask);
	    return TRANS_RESET_FAILURE;
        }
#endif

	close (ciptr->fd);
	unlink (unsock->sun_path);

	if ((ciptr->fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
	{
	    TRANS(FreeConnInfo) (ciptr);
	    (void) umask (oldUmask);
	    return TRANS_RESET_FAILURE;
	}

	if (bind (ciptr->fd, (struct sockaddr *) unsock, ciptr->addrlen) < 0)
	{
	    close (ciptr->fd);
	    TRANS(FreeConnInfo) (ciptr);
	    return TRANS_RESET_FAILURE;
	}

	if (listen (ciptr->fd, BACKLOG) < 0)
	{
	    close (ciptr->fd);
	    TRANS(FreeConnInfo) (ciptr);
	    (void) umask (oldUmask);
	    return TRANS_RESET_FAILURE;
	}

	umask (oldUmask);

	status = TRANS_RESET_NEW_FD;
    }

    return status;
}

#endif /* UNIXCONN */


#ifdef TCPCONN

static XtransConnInfo
TRANS(SocketINETAccept) (XtransConnInfo ciptr, int *status)

{
    XtransConnInfo	newciptr;
    struct sockaddr_in	sockname;
    int			namelen = sizeof(sockname);

    PRMSG (2, "SocketINETAccept(%p,%d)\n", ciptr, ciptr->fd, 0);

    if ((newciptr = (XtransConnInfo) calloc (
	1, sizeof(struct _XtransConnInfo))) == NULL)
    {
	PRMSG (1, "SocketINETAccept: malloc failed\n", 0, 0, 0);
	*status = TRANS_ACCEPT_BAD_MALLOC;
	return NULL;
    }

    if ((newciptr->fd = accept (ciptr->fd,
	(struct sockaddr *) &sockname, (void *)&namelen)) < 0)
    {
#ifdef WIN32
	errno = WSAGetLastError();
#endif
	PRMSG (1, "SocketINETAccept: accept() failed\n", 0, 0, 0);
	free (newciptr);
	*status = TRANS_ACCEPT_FAILED;
	return NULL;
    }

#ifdef TCP_NODELAY
    {
	/*
	 * turn off TCP coalescence for INET sockets
	 */

	int tmp = 1;
	setsockopt (newciptr->fd, IPPROTO_TCP, TCP_NODELAY,
	    (char *) &tmp, sizeof (int));
    }
#endif

    /*
     * Get this address again because the transport may give a more 
     * specific address now that a connection is established.
     */

    if (TRANS(SocketINETGetAddr) (newciptr) < 0)
    {
	PRMSG (1,
	    "SocketINETAccept: ...SocketINETGetAddr() failed:\n",
	    0, 0, 0);
	close (newciptr->fd);
	free (newciptr);
	*status = TRANS_ACCEPT_MISC_ERROR;
        return NULL;
    }

    if (TRANS(SocketINETGetPeerAddr) (newciptr) < 0)
    {
	PRMSG (1,
	  "SocketINETAccept: ...SocketINETGetPeerAddr() failed:\n",
		0, 0, 0);
	close (newciptr->fd);
	if (newciptr->addr) free (newciptr->addr);
	free (newciptr);
	*status = TRANS_ACCEPT_MISC_ERROR;
        return NULL;
    }

    *status = 0;

    return newciptr;
}

#endif /* TCPCONN */


#ifdef UNIXCONN
static XtransConnInfo
TRANS(SocketUNIXAccept) (XtransConnInfo ciptr, int *status)

{
    XtransConnInfo	newciptr;
    struct sockaddr_un	sockname;
#if defined(SVR4) || defined(__SCO__)
    size_t namelen = sizeof sockname;
#else
    int namelen = sizeof sockname;
#endif

    PRMSG (2, "SocketUNIXAccept(%p,%d)\n", ciptr, ciptr->fd, 0);

    if ((newciptr = (XtransConnInfo) calloc (
	1, sizeof(struct _XtransConnInfo))) == NULL)
    {
	PRMSG (1, "SocketUNIXAccept: malloc() failed\n", 0, 0, 0);
	*status = TRANS_ACCEPT_BAD_MALLOC;
	return NULL;
    }

    if ((newciptr->fd = accept (ciptr->fd,
	(struct sockaddr *) &sockname, (void *)&namelen)) < 0)
    {
	PRMSG (1, "SocketUNIXAccept: accept() failed\n", 0, 0, 0);
	free (newciptr);
	*status = TRANS_ACCEPT_FAILED;
	return NULL;
    }

    /*
     * Get the socket name and the peer name from the listener socket,
     * since this is unix domain.
     */

    if ((newciptr->addr = (char *) malloc (ciptr->addrlen)) == NULL)
    {
        PRMSG (1,
        "SocketUNIXAccept: Can't allocate space for the addr\n",
	      0, 0, 0);
	close (newciptr->fd);
	free (newciptr);
	*status = TRANS_ACCEPT_BAD_MALLOC;
        return NULL;
    }


    /*
     * if the socket is abstract, we already modified the address to have a
     * @ instead of the initial NUL, so no need to do that again here.
     */

    newciptr->addrlen = ciptr->addrlen;
    memcpy (newciptr->addr, ciptr->addr, newciptr->addrlen);

    if ((newciptr->peeraddr = (char *) malloc (ciptr->addrlen)) == NULL)
    {
        PRMSG (1,
	      "SocketUNIXAccept: Can't allocate space for the addr\n",
	      0, 0, 0);
	close (newciptr->fd);
	if (newciptr->addr) free (newciptr->addr);
	free (newciptr);
	*status = TRANS_ACCEPT_BAD_MALLOC;
        return NULL;
    }
    
    newciptr->peeraddrlen = ciptr->addrlen;
    memcpy (newciptr->peeraddr, ciptr->addr, newciptr->addrlen);

    newciptr->family = AF_UNIX;

    *status = 0;

    return newciptr;
}

#endif /* UNIXCONN */

#endif /* TRANS_SERVER */


#ifdef TRANS_CLIENT

#ifdef TCPCONN

#if defined(IPv6) && defined(AF_INET6)
struct addrlist {
    struct addrinfo *	addr;
    struct addrinfo *	firstaddr; 
    char 		port[PORTBUFSIZE];
    char 		host[MAXHOSTNAMELEN];
};
static struct addrlist  *addrlist = NULL;
#endif


static int
TRANS(SocketINETConnect) (XtransConnInfo ciptr, char *host, char *port)

{
    struct sockaddr *	socketaddr = NULL;
    int			socketaddrlen = 0;
    int			res;
#if defined(IPv6) && defined(AF_INET6)
    struct addrinfo 	hints;
    char		ntopbuf[INET6_ADDRSTRLEN];
    int			resetonce = 0;
#endif
    struct sockaddr_in	sockname;
#ifdef XTHREADS_NEEDS_BYNAMEPARAMS
    _Xgethostbynameparams hparams;
    _Xgetservbynameparams sparams;
#endif
    struct hostent	*hostp;
    struct servent	*servp;
    unsigned long 	tmpaddr;
#ifdef X11_t
    char	portbuf[PORTBUFSIZE];
#endif

    long		tmpport;
    char 		hostnamebuf[256];		/* tmp space */

    PRMSG (2,"SocketINETConnect(%d,%s,%s)\n", ciptr->fd, host, port);

    if (!host)
    {
	hostnamebuf[0] = '\0';
	(void) TRANS(GetHostname) (hostnamebuf, sizeof hostnamebuf);
	host = hostnamebuf;
    }

#ifdef X11_t
    /*
     * X has a well known port, that is transport dependent. It is easier
     * to handle it here, than try and come up with a transport independent
     * representation that can be passed in and resolved the usual way.
     *
     * The port that is passed here is really a string containing the idisplay
     * from ConnectDisplay().
     */

    if (is_numeric (port))
    {
	tmpport = X_TCP_PORT + strtol (port, (char**)NULL, 10);
	sprintf (portbuf, "%lu", tmpport);
	port = portbuf;
    }
#endif

#if defined(IPv6) && defined(AF_INET6)
    if (haveIPv6) {
	if (addrlist != NULL) {
	    if (strcmp(host,addrlist->host) || strcmp(port,addrlist->port)) {
		if (addrlist->firstaddr)
		    freeaddrinfo(addrlist->firstaddr);
		addrlist->firstaddr = NULL;
	    }
	} else {
	    addrlist = malloc(sizeof(struct addrlist));
	    addrlist->firstaddr = NULL;
	}

	if (addrlist->firstaddr == NULL) {
	    strncpy(addrlist->port, port, sizeof(addrlist->port));
	    addrlist->port[sizeof(addrlist->port) - 1] = '\0';
	    strncpy(addrlist->host, host, sizeof(addrlist->host));
	    addrlist->host[sizeof(addrlist->host) - 1] = '\0';

	    bzero(&hints,sizeof(hints));
	    hints.ai_socktype = Sockettrans2devtab[ciptr->index].devcotsname;

	    res = getaddrinfo(host,port,&hints,&addrlist->firstaddr);
	    if (res != 0) {
		PRMSG (1, "SocketINETConnect() can't get address "
			"for %s:%s: %s\n", host, port, gai_strerror(res));
		ESET(EINVAL);
		return TRANS_CONNECT_FAILED;
	    }
	    for (res = 0, addrlist->addr = addrlist->firstaddr;
		 addrlist->addr ; res++) {
		addrlist->addr = addrlist->addr->ai_next;
	    }
	    PRMSG(4,"Got New Address list with %d addresses\n", res, 0, 0);
	    res = 0;
	    addrlist->addr = NULL;
	}

	while (socketaddr == NULL) {
	    if (addrlist->addr == NULL) {
		if (resetonce) { 
		    /* Already checked entire list - no usable addresses */
		    PRMSG (1, "SocketINETConnect() no usable address "
			   "for %s:%s\n", host, port, 0);
		    return TRANS_CONNECT_FAILED;
		} else {
		    /* Go back to beginning of list */
		    resetonce = 1;
		    addrlist->addr = addrlist->firstaddr;
		}
	    } 

	    socketaddr = addrlist->addr->ai_addr;
	    socketaddrlen = addrlist->addr->ai_addrlen;

	    if (addrlist->addr->ai_family == AF_INET) {
		struct sockaddr_in *sin = (struct sockaddr_in *) socketaddr;

		PRMSG (4,"SocketINETConnect() sockname.sin_addr = %s\n",
			inet_ntop(addrlist->addr->ai_family,&sin->sin_addr,
			ntopbuf,sizeof(ntopbuf)), 0, 0); 

		PRMSG (4,"SocketINETConnect() sockname.sin_port = %d\n",
			ntohs(sin->sin_port), 0, 0); 

		if (Sockettrans2devtab[ciptr->index].family == AF_INET6) {
		    if (strcmp(Sockettrans2devtab[ciptr->index].transname,
				"tcp") == 0) {
			XtransConnInfo newciptr;

			/*
			 * Our socket is an IPv6 socket, but the address is
			 * IPv4.  Close it and get an IPv4 socket.  This is
			 * needed for IPv4 connections to work on platforms
			 * that don't allow IPv4 over IPv6 sockets.
			 */
			TRANS(SocketINETClose)(ciptr);
			newciptr = TRANS(SocketOpenCOTSClientBase)(
					"tcp", "tcp", host, port, ciptr->index);
			if (newciptr)
			    ciptr->fd = newciptr->fd;
			if (!newciptr ||
			    Sockettrans2devtab[newciptr->index].family !=
				AF_INET) {
			    socketaddr = NULL;
			    PRMSG (4,"SocketINETConnect() Cannot get IPv4 "
					" socketfor IPv4 address\n", 0,0,0);
			}
			if (newciptr)
			    free(newciptr);
		    } else {
			socketaddr = NULL;
			PRMSG (4,"SocketINETConnect Skipping IPv4 address\n",
				0,0,0);
		    }
		}
	    } else if (addrlist->addr->ai_family == AF_INET6) {
		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) socketaddr;
	
		PRMSG (4,"SocketINETConnect() sockname.sin6_addr = %s\n",
			inet_ntop(addrlist->addr->ai_family,
				  &sin6->sin6_addr,ntopbuf,sizeof(ntopbuf)),
			0, 0); 
		PRMSG (4,"SocketINETConnect() sockname.sin6_port = %d\n",
			ntohs(sin6->sin6_port), 0, 0); 

		if (Sockettrans2devtab[ciptr->index].family == AF_INET) {
		    if (strcmp(Sockettrans2devtab[ciptr->index].transname,
				"tcp") == 0) {
			XtransConnInfo newciptr;

			/*
			 * Close the IPv4 socket and try to open an IPv6 socket.
			 */
			TRANS(SocketINETClose)(ciptr);
			newciptr = TRANS(SocketOpenCOTSClientBase)(
					"tcp", "tcp", host, port, -1);
			if (newciptr)
			    ciptr->fd = newciptr->fd;
			if (!newciptr ||
			    Sockettrans2devtab[newciptr->index].family !=
					AF_INET6) {
			    socketaddr = NULL;
			    PRMSG (4,"SocketINETConnect() Cannot get IPv6 "
				   "socket for IPv6 address\n", 0,0,0);
			}
			if (newciptr)
			    free(newciptr);
		    }
		    else
		    {
			socketaddr = NULL;
			PRMSG (4,"SocketINETConnect() Skipping IPv6 address\n",
				0,0,0);
		    }
		}
	    } else {
		socketaddr = NULL; /* Unsupported address type */
	    }
	    if (socketaddr == NULL) {
		addrlist->addr = addrlist->addr->ai_next;
	    }
	} 
    } else
#endif
    {
	/*
	 * Build the socket name.
	 */

#ifdef BSD44SOCKETS
	sockname.sin_len = sizeof (struct sockaddr_in);
#endif
	sockname.sin_family = AF_INET;

	/*
	 * fill in sin_addr
	 */

#ifndef INADDR_NONE
#define INADDR_NONE ((in_addr_t) 0xffffffff)
#endif

	/* check for ww.xx.yy.zz host string */

	if (isascii (host[0]) && isdigit (host[0])) {
	    tmpaddr = inet_addr (host); /* returns network byte order */
	} else {
	    tmpaddr = INADDR_NONE;
	}

	PRMSG (4,"SocketINETConnect() inet_addr(%s) = %x\n", host, tmpaddr, 0);

	if (tmpaddr == INADDR_NONE) {
	    if ((hostp = _XGethostbyname(host,hparams)) == NULL) {
		PRMSG (1,"SocketINETConnect: Can't get address for %s\n",
			host, 0, 0);
		ESET(EINVAL);
		return TRANS_CONNECT_FAILED;
	    }
	    if (hostp->h_addrtype != AF_INET) {  /* is IP host? */
		PRMSG (1,"SocketINETConnect: not INET host%s\n", host, 0, 0);
		ESET(EPROTOTYPE);
		return TRANS_CONNECT_FAILED;
	    }
	    memcpy ((char *) &sockname.sin_addr, (char *) hostp->h_addr,
		    sizeof (sockname.sin_addr));
	} else {
	    sockname.sin_addr.s_addr = tmpaddr;
        }

	/*
	 * fill in sin_port
	 */

	/* Check for number in the port string */

	if (!is_numeric (port)) {
	    if ((servp = _XGetservbyname (port,"tcp",sparams)) == NULL) {
		PRMSG (1,"SocketINETConnect: can't get service for %s\n",
			port, 0, 0);
		return TRANS_CONNECT_FAILED;
	    }
	    sockname.sin_port = htons (servp->s_port);
	} else {
	    tmpport = strtol (port, (char**)NULL, 10);
	    if (tmpport < 1024 || tmpport > USHRT_MAX)
		return TRANS_CONNECT_FAILED;
	    sockname.sin_port = htons (((unsigned short) tmpport));
	}

	PRMSG (4,"SocketINETConnect: sockname.sin_port = %d\n",
		ntohs(sockname.sin_port), 0, 0);
	socketaddr = (struct sockaddr *) &sockname;
	socketaddrlen = sizeof(sockname);
    }

    /*
     * Turn on socket keepalive so the client process will eventually
     * be notified with a SIGPIPE signal if the display server fails
     * to respond to a periodic transmission of messages
     * on the connected socket.
     * This is useful to avoid hung application processes when the
     * processes are not spawned from the xdm session and
     * the display server terminates abnormally.
     * (Someone turned off the power switch.)
     */

    {
	int tmp = 1;
	setsockopt (ciptr->fd, SOL_SOCKET, SO_KEEPALIVE,
		(char *) &tmp, sizeof (int));
    }

    /*
     * Do the connect()
     */

    if (connect (ciptr->fd, socketaddr, socketaddrlen ) < 0)
    {
#ifdef WIN32
	int olderrno = WSAGetLastError();
#else
	int olderrno = errno;
#endif

	/*
	 * If the error was ECONNREFUSED, the server may be overloaded
	 * and we should try again.
	 *
	 * If the error was EWOULDBLOCK or EINPROGRESS then the socket
	 * was non-blocking and we should poll using select
	 *
	 * If the error was EINTR, the connect was interrupted and we
	 * should try again.
	 *
	 * If multiple addresses are found for a host then we should
	 * try to connect again with a different address for a larger
	 * number of errors that made us quit before, since those
	 * could be caused by trying to use an IPv6 address to contact
	 * a machine with an IPv4-only server or other reasons that
	 * only affect one of a set of addresses.  
	 */

	if (olderrno == ECONNREFUSED || olderrno == EINTR
#if defined(IPv6) && defined(AF_INET6)
	  || (haveIPv6 && ((addrlist->addr->ai_next != NULL) || 
	        (addrlist->addr != addrlist->firstaddr)) &&
               (olderrno == ENETUNREACH || olderrno == EAFNOSUPPORT ||
		 olderrno == EADDRNOTAVAIL || olderrno == ETIMEDOUT
#if defined(EHOSTDOWN)
		   || olderrno == EHOSTDOWN
#endif
	       ))
#endif
	    )
	    res = TRANS_TRY_CONNECT_AGAIN;
	else if (olderrno == EWOULDBLOCK || olderrno == EINPROGRESS)
	    res = TRANS_IN_PROGRESS;
	else
	{
	    PRMSG (2,"SocketINETConnect: Can't connect: errno = %d\n",
		   olderrno,0, 0);

	    res = TRANS_CONNECT_FAILED;	
	}
    } else {
	res = 0;
    

	/*
	 * Sync up the address fields of ciptr.
	 */
    
	if (TRANS(SocketINETGetAddr) (ciptr) < 0)
	{
	    PRMSG (1,
	     "SocketINETConnect: ...SocketINETGetAddr() failed:\n",
	      0, 0, 0);
	    res = TRANS_CONNECT_FAILED;
	}

	else if (TRANS(SocketINETGetPeerAddr) (ciptr) < 0)
	{
	    PRMSG (1,
	      "SocketINETConnect: ...SocketINETGetPeerAddr() failed:\n",
	      0, 0, 0);
	    res = TRANS_CONNECT_FAILED;
	}
    }

#if defined(IPv6) && defined(AF_INET6)
   if (haveIPv6 && res != 0) { 
	addrlist->addr = addrlist->addr->ai_next;
   }
#endif

    return res;
}

#endif /* TCPCONN */



#ifdef UNIXCONN

/*
 * Make sure 'host' is really local.
 */

static int
UnixHostReallyLocal (char *host)

{
    char hostnamebuf[256];

#if defined(IPv6) && defined(AF_INET6)
    if (getaddrinfo == NULL)
	haveIPv6 = 0;
#endif

    TRANS(GetHostname) (hostnamebuf, sizeof (hostnamebuf));

    if (strcmp (hostnamebuf, host) == 0)
    {
	return (1);
    }
#if defined(IPv6) && defined(AF_INET6)
    else if (haveIPv6)
    {
	struct addrinfo *localhostaddr;
	struct addrinfo *otherhostaddr;
	struct addrinfo *i, *j;
	int equiv = 0;

	if (getaddrinfo(hostnamebuf, NULL, NULL, &localhostaddr) != 0)
	    return 0;
	if (getaddrinfo(host, NULL, NULL, &otherhostaddr) != 0) {
	    freeaddrinfo(localhostaddr);
	    return 0;
	}

	for (i = localhostaddr; i != NULL && equiv == 0; i = i->ai_next) {
	    for (j = otherhostaddr; j != NULL && equiv == 0; j = j->ai_next) {
		if (i->ai_family == j->ai_family) {
		    if (i->ai_family == AF_INET) {
			struct sockaddr_in *sinA 
			  = (struct sockaddr_in *) i->ai_addr;
			struct sockaddr_in *sinB
			  = (struct sockaddr_in *) j->ai_addr;
			struct in_addr *A = &sinA->sin_addr;
			struct in_addr *B = &sinB->sin_addr;

			if (memcmp(A,B,sizeof(struct in_addr)) == 0) {
			    equiv = 1;
			}
		    } else if (i->ai_family == AF_INET6) {
			struct sockaddr_in6 *sinA 
			  = (struct sockaddr_in6 *) i->ai_addr;
			struct sockaddr_in6 *sinB 
			  = (struct sockaddr_in6 *) j->ai_addr;
			struct in6_addr *A = &sinA->sin6_addr;
			struct in6_addr *B = &sinB->sin6_addr;

			if (memcmp(A,B,sizeof(struct in6_addr)) == 0) {
			    equiv = 1;
			}
		    }
		}
	    }
	}
	
	freeaddrinfo(localhostaddr);
	freeaddrinfo(otherhostaddr);
	return equiv;
    }
#endif
    else
    {
	/*
	 * A host may have more than one network address.  If any of the
	 * network addresses of 'host' (specified to the connect call)
	 * match any of the network addresses of 'hostname' (determined
	 * by TRANS(GetHostname)), then the two hostnames are equivalent,
	 * and we know that 'host' is really a local host.
	 */
	char specified_local_addr_list[10][4];
	int scount, equiv, i, j;
#ifdef XTHREADS_NEEDS_BYNAMEPARAMS
	_Xgethostbynameparams hparams;
#endif
	struct hostent *hostp;

	if ((hostp = _XGethostbyname (host,hparams)) == NULL)
	    return (0);

	scount = 0;
	while (hostp->h_addr_list[scount] && scount <= 8)
	{
	    /*
	     * The 2nd call to gethostname() overrides the data
	     * from the 1st call, so we must save the address list.
	     */

	    specified_local_addr_list[scount][0] = 
				hostp->h_addr_list[scount][0];
	    specified_local_addr_list[scount][1] = 
				hostp->h_addr_list[scount][1];
	    specified_local_addr_list[scount][2] = 
				hostp->h_addr_list[scount][2];
	    specified_local_addr_list[scount][3] = 
				hostp->h_addr_list[scount][3];
	    scount++;
	}
	if ((hostp = _XGethostbyname (hostnamebuf,hparams)) == NULL)
	    return (0);

	equiv = 0;
	i = 0;

	while (i < scount && !equiv)
	{
	    j = 0;

	    while (hostp->h_addr_list[j])
	    {
		if ((specified_local_addr_list[i][0] == 
					hostp->h_addr_list[j][0]) &&
		    (specified_local_addr_list[i][1] == 
					hostp->h_addr_list[j][1]) &&
		    (specified_local_addr_list[i][2] == 
					hostp->h_addr_list[j][2]) &&
		    (specified_local_addr_list[i][3] == 
					hostp->h_addr_list[j][3]))
		{
		    /* They're equal, so we're done */
		    
		    equiv = 1;
		    break;
		}

		j++;
	    }

	    i++;
	}
	return (equiv);
    }
}

static int
TRANS(SocketUNIXConnect) (XtransConnInfo ciptr, char *host, char *port)

{
    struct sockaddr_un	sockname;
    int			namelen;


    int abstract = 0;
#ifdef HAVE_ABSTRACT_SOCKETS
    abstract = ciptr->transptr->flags & TRANS_ABSTRACT;
#endif



    PRMSG (2,"SocketUNIXConnect(%d,%s,%s)\n", ciptr->fd, host, port);
    
    /*
     * Make sure 'host' is really local.  If not, we return failure.
     * The reason we make this check is because a process may advertise
     * a "local" network ID for which it can accept connections, but if
     * a process on a remote machine tries to connect to this network ID,
     * we know for sure it will fail.
     */

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)
    if (strcmp(host, "unix") != 0 && strcasecmp(host, "nx") != 0 &&
            strncasecmp(host, "nx,", 3) != 0 && !UnixHostReallyLocal (host))
#else
    if (strcmp (host, "unix") != 0 && !UnixHostReallyLocal (host))
#endif
    {
	PRMSG (1,
	   "SocketUNIXConnect: Cannot connect to non-local host %s\n",
	       host, 0, 0);
	return TRANS_CONNECT_FAILED;
    }


    /*
     * Check the port.
     */

    if (!port || !*port)
    {
	PRMSG (1,"SocketUNIXConnect: Missing port specification\n",
	      0, 0, 0);
	return TRANS_CONNECT_FAILED;
    }

    /*
     * Build the socket name.
     */
    
    sockname.sun_family = AF_UNIX;

#ifdef NX_TRANS_SOCKET
    if (set_sun_path(port, _NXGetUnixPath(UNIX_PATH), sockname.sun_path, abstract) != 0) {
#else
    if (set_sun_path(port, UNIX_PATH, sockname.sun_path, abstract) != 0) {
#endif
	PRMSG (1, "SocketUNIXConnect: path too long\n", 0, 0, 0);
	return TRANS_CONNECT_FAILED;
    }

#if (defined(BSD44SOCKETS) || defined(__UNIXWARE__)) && !defined(Lynx)
    sockname.sun_len = strlen (sockname.sun_path);
    namelen = SUN_LEN (&sockname);
#else
    namelen = strlen (sockname.sun_path) + sizeof (sockname.sun_family);
#endif



#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

    if (ciptr->priv != NULL)
    {
        if (TRANS(SocketConnectConnInfo) (ciptr, host, port) != 0)
        {
            return TRANS_CONNECT_FAILED;
        }

        goto SocketUNIXConnectPost;
    }

#endif

    /*
     * Adjust the socket path if using abstract sockets.
     * Done here because otherwise all the strlen() calls above would fail.
     */

    if (abstract)
	sockname.sun_path[0] = '\0';

    /*
     * Do the connect()
     */

    if (connect (ciptr->fd, (struct sockaddr *) &sockname, namelen) < 0)
    {
	int olderrno = errno;
	int connected = 0;
	
	if (!connected)
	{
	    errno = olderrno;
	    
	    /*
	     * If the error was ENOENT, the server may be starting up
	     * and we should try again.
	     *
	     * If the error was EWOULDBLOCK or EINPROGRESS then the socket
	     * was non-blocking and we should poll using select
	     *
	     * If the error was EINTR, the connect was interrupted and we
	     * should try again.
	     */

	    if (olderrno == EWOULDBLOCK || olderrno == EINPROGRESS)
		return TRANS_IN_PROGRESS;
	    else if (olderrno == EINTR)
		return TRANS_TRY_CONNECT_AGAIN;
	    else if (olderrno == ENOENT || olderrno == ECONNREFUSED)
		/* If opening as abstract failed, try again normally */
		if (abstract) {
		    ciptr->transptr->flags &= ~(TRANS_ABSTRACT);
		    return TRANS_TRY_CONNECT_AGAIN;
		} else {
		    return TRANS_CONNECT_FAILED;
	    } else {
		PRMSG (2,"SocketUNIXConnect: Can't connect: errno = %d\n",
		       EGET(),0, 0);

		return TRANS_CONNECT_FAILED;
	    }
	}
    }

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

SocketUNIXConnectPost:

#endif

    /*
     * Get the socket name and the peer name from the connect socket,
     * since this is unix domain.
     */

    if ((ciptr->addr = (char *) malloc(namelen)) == NULL ||
       (ciptr->peeraddr = (char *) malloc(namelen)) == NULL)
    {
        PRMSG (1,
	"SocketUNIXCreateListener: Can't allocate space for the addr\n",
	      0, 0, 0);
        return TRANS_CONNECT_FAILED;
    }

    if (abstract)
	sockname.sun_path[0] = '@';

    ciptr->family = AF_UNIX;
    ciptr->addrlen = namelen;
    ciptr->peeraddrlen = namelen;
    memcpy (ciptr->addr, &sockname, ciptr->addrlen);
    memcpy (ciptr->peeraddr, &sockname, ciptr->peeraddrlen);
    
    return 0;
}

#endif /* UNIXCONN */

#endif /* TRANS_CLIENT */


static int
TRANS(SocketBytesReadable) (XtransConnInfo ciptr, BytesReadable_t *pend)

{
    PRMSG (2,"SocketBytesReadable(%p,%d,%p)\n",
	ciptr, ciptr->fd, pend);

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

    if (ciptr->priv)
    {
        if (NXTransRunning(ciptr->fd) == 0)
        {
            /*
             * Force the application to shut down the
             * socket if the NX transport is gone. We
             * may probably save this additional call.
             */

#ifdef NX_TRANS_DEBUG
            fprintf(stderr, "SocketBytesReadable: NX transport not running for descriptor [%d].\n",
                        ciptr->fd);
#endif
            ESET(EPIPE);

            return -1;
        }
        else
        {
            /*
             * Emulate BytesReadable. Some X applications may use the system
             * select() in their main loop, instead of the _XSelect() that is
             * replaced by NX. Still these applications use _XEventsQueued to
             * poll events from the X connection, and _XEventsQueued uses the
             * NX _XSelect(), so it is generally possible to let the client
             * yield the control to NX and let it handle the I/O on the proxy
             * descriptors even if the application is not explicitly designed
             * to work as a NX agent.         
             */

#ifdef NX_TRANS_DEBUG

            int result;

            result = NXTransReadable(ciptr->fd, (int *) pend);

            fprintf(stderr, "SocketBytesReadable: Descriptor [%d] result [%d] readable [%ld].\n",
                        ciptr->fd, result, *pend);

            return result;
#else
            return NXTransReadable(ciptr->fd, (int *) pend);
#endif
        }
    }

#endif /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */

#if defined(QNX4)
    *pend = 0L; /* FIONREAD only returns a short. Zero out upper bits */
#endif
#ifdef WIN32
    {
	int ret = ioctlsocket ((SOCKET) ciptr->fd, FIONREAD, (u_long *) pend);
	errno = WSAGetLastError();
	return ret;
    }
#else
#if (defined(i386) && defined(SYSV) && !defined(SCO325)) || (defined(_SEQUENT_) && _SOCKET_VERSION == 1)
    return ioctl (ciptr->fd, I_NREAD, (char *) pend);
#else
    return ioctl (ciptr->fd, FIONREAD, (char *) pend);
#endif /* i386 && SYSV || _SEQUENT_ && _SOCKET_VERSION == 1 */
#endif /* WIN32 */
}


static int
TRANS(SocketRead) (XtransConnInfo ciptr, char *buf, int size)

{
    PRMSG (2,"SocketRead(%d,%p,%d)\n", ciptr->fd, buf, size);

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

    /*
     * If we have a valid priv pointer then this
     * is an internal connection to the proxy.
     * In this case we should emulate the read.
     */

    if (ciptr->priv)
    {
        int result;

        result = NXTransRead(ciptr->fd, buf, size);

#ifdef NX_TRANS_DEBUG
        if (result < 0 && EGET() == EAGAIN)
        {
            fprintf(stderr, "SocketRead: Read from descriptor [%d] would block.\n",
                     ciptr->fd);
        }
        else
        {
            fprintf(stderr, "SocketRead: Read [%d] bytes from descriptor [%d].\n",
                     result, ciptr->fd);
        }
#endif
        return result;
    }
    else
    {
        return read (ciptr->fd, buf, size);
    }

#else /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */

#if defined(WIN32) || defined(__UNIXOS2__)
    {
	int ret = recv ((SOCKET)ciptr->fd, buf, size, 0);
#ifdef WIN32
	errno = WSAGetLastError();
#endif
	return ret;
    }
#else
    return read (ciptr->fd, buf, size);
#endif /* WIN32 */

#endif /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */
}


static int
TRANS(SocketWrite) (XtransConnInfo ciptr, char *buf, int size)

{
    PRMSG (2,"SocketWrite(%d,%p,%d)\n", ciptr->fd, buf, size);

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

    /*
     * If we have a valid priv pointer then this
     * is an internal connection to the proxy.
     * In this case we should emulate the write.
     */

    if (ciptr->priv)
    {
        int result;

        result = NXTransWrite(ciptr->fd, buf, size);

#ifdef NX_TRANS_DEBUG
        if (result < 0 && EGET() == EAGAIN)
        {
            fprintf(stderr, "SocketWrite: Write on descriptor [%d] would block.\n",
                     ciptr->fd);
        }
        else
        {
            fprintf(stderr, "SocketWrite: Written [%d] bytes on descriptor [%d].\n",
                     result, ciptr->fd);
        }
#endif
        return result;
    }
    else
    {
        return write (ciptr->fd, buf, size);
    }

#else /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */

#if defined(WIN32) || defined(__UNIXOS2__)
    {
	int ret = send ((SOCKET)ciptr->fd, buf, size, 0);
#ifdef WIN32
	errno = WSAGetLastError();
#endif
	return ret;
    }
#else
    return write (ciptr->fd, buf, size);
#endif /* WIN32 */

#endif /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */
}


static int
TRANS(SocketReadv) (XtransConnInfo ciptr, struct iovec *buf, int size)

{
    PRMSG (2,"SocketReadv(%d,%p,%d)\n", ciptr->fd, buf, size);

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

    /*
     * If we have a valid priv pointer then this
     * is an internal connection to the proxy.
     * In this case we should emulate the readv.
     */

    if (ciptr->priv)
    {
        return NXTransReadVector(ciptr->fd, buf, size);
    }
    else
    {
        return READV (ciptr, buf, size);
    }

#else /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */

    return READV (ciptr, buf, size);

#endif /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */
}


static int
TRANS(SocketWritev) (XtransConnInfo ciptr, struct iovec *buf, int size)

{
    PRMSG (2,"SocketWritev(%d,%p,%d)\n", ciptr->fd, buf, size);

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

    /*
     * If we have a valid priv pointer then this
     * is an internal connection to the proxy.
     * In this case we should emulate the writev.
     */

    if (ciptr->priv)
    {
        return NXTransWriteVector(ciptr->fd, buf, size);
    }
    else
    {
        return WRITEV (ciptr, buf, size);
    }

#else /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */

    return WRITEV (ciptr, buf, size);

#endif /* #if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT) */
}


static int
TRANS(SocketDisconnect) (XtransConnInfo ciptr)

{
    PRMSG (2,"SocketDisconnect(%p,%d)\n", ciptr, ciptr->fd, 0);

#ifdef WIN32
    { 
	int ret = shutdown (ciptr->fd, 2);
	errno = WSAGetLastError();
	return ret;
    }
#else
    return shutdown (ciptr->fd, 2); /* disallow further sends and receives */
#endif
}


#ifdef TCPCONN
static int
TRANS(SocketINETClose) (XtransConnInfo ciptr)

{
    PRMSG (2,"SocketINETClose(%p,%d)\n", ciptr, ciptr->fd, 0);

#ifdef WIN32
    {
	int ret = close (ciptr->fd);
	errno = WSAGetLastError();
	return ret;
    }
#else
    return close (ciptr->fd);
#endif
}

#endif /* TCPCONN */


#ifdef UNIXCONN
static int
TRANS(SocketUNIXClose) (XtransConnInfo ciptr)

{
    /*
     * If this is the server side, then once the socket is closed,
     * it must be unlinked to completely close it
     */

    struct sockaddr_un	*sockname = (struct sockaddr_un *) ciptr->addr;
    int ret;

    PRMSG (2,"SocketUNIXClose(%x,%d)\n", ciptr, ciptr->fd, 0);

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

    if (ciptr->priv)
    {
        TRANS(SocketCloseConnInfo) (ciptr);
    }

#endif

    ret = close(ciptr->fd);

#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
    fprintf(stderr, "SocketUNIXClose: Flags are [%d] for ciptr at [%p] check is [%d].\n",
                ciptr->flags, (void *) ciptr, (ciptr->flags && sockname
                    && sockname->sun_family == AF_UNIX && sockname->sun_path[0]));
#endif

    if (ciptr->flags
       && sockname
       && sockname->sun_family == AF_UNIX
       && sockname->sun_path[0])
    {
#if defined(NX_TRANS_SOCKET) && defined(NX_TRANS_TEST)
        if (!(ciptr->flags & TRANS_NOUNLINK))
        {
                fprintf(stderr, "SocketUNIXClose: Unlinking path [%s] for ciptr at [%p].\n",
                            sockname->sun_path, (void *) ciptr);
                unlink (sockname->sun_path);
        }
#else
	if (!(ciptr->flags & TRANS_NOUNLINK))
		unlink (sockname->sun_path);
#endif
    }

    return ret;
}

static int
TRANS(SocketUNIXCloseForCloning) (XtransConnInfo ciptr)

{
    /*
     * Don't unlink path.
     */

    int ret;

    PRMSG (2,"SocketUNIXCloseForCloning(%p,%d)\n",
	ciptr, ciptr->fd, 0);

#if defined(NX_TRANS_SOCKET) && defined(TRANS_CLIENT)

    if (ciptr->priv)
    {
        TRANS(SocketCloseConnInfo) (ciptr);
    }

#endif

    ret = close(ciptr->fd);

    return ret;
}

#endif /* UNIXCONN */


#ifdef TCPCONN
# ifdef TRANS_SERVER
static char* tcp_nolisten[] = {
	"inet",
#if defined(IPv6) && defined(AF_INET6)
	"inet6",
#endif
	NULL
};
# endif

Xtransport	TRANS(SocketTCPFuncs) = {
	/* Socket Interface */
	"tcp",
        TRANS_ALIAS,
#ifdef TRANS_CLIENT
	TRANS(SocketOpenCOTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	tcp_nolisten,
	TRANS(SocketOpenCOTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(SocketOpenCLTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	TRANS(SocketOpenCLTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_REOPEN
	TRANS(SocketReopenCOTSServer),
	TRANS(SocketReopenCLTSServer),
#endif
	TRANS(SocketSetOption),
#ifdef TRANS_SERVER
	TRANS(SocketINETCreateListener),
	NULL,		       			/* ResetListener */
	TRANS(SocketINETAccept),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(SocketINETConnect),
#endif /* TRANS_CLIENT */
	TRANS(SocketBytesReadable),
	TRANS(SocketRead),
	TRANS(SocketWrite),
	TRANS(SocketReadv),
	TRANS(SocketWritev),
	TRANS(SocketDisconnect),
	TRANS(SocketINETClose),
	TRANS(SocketINETClose),
	};

Xtransport	TRANS(SocketINETFuncs) = {
	/* Socket Interface */
	"inet",
	0,
#ifdef TRANS_CLIENT
	TRANS(SocketOpenCOTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	NULL,
	TRANS(SocketOpenCOTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(SocketOpenCLTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	TRANS(SocketOpenCLTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_REOPEN
	TRANS(SocketReopenCOTSServer),
	TRANS(SocketReopenCLTSServer),
#endif
	TRANS(SocketSetOption),
#ifdef TRANS_SERVER
	TRANS(SocketINETCreateListener),
	NULL,		       			/* ResetListener */
	TRANS(SocketINETAccept),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(SocketINETConnect),
#endif /* TRANS_CLIENT */
	TRANS(SocketBytesReadable),
	TRANS(SocketRead),
	TRANS(SocketWrite),
	TRANS(SocketReadv),
	TRANS(SocketWritev),
	TRANS(SocketDisconnect),
	TRANS(SocketINETClose),
	TRANS(SocketINETClose),
	};

#if defined(IPv6) && defined(AF_INET6)
Xtransport     TRANS(SocketINET6Funcs) = {
	/* Socket Interface */
	"inet6",
	0,
#ifdef TRANS_CLIENT
	TRANS(SocketOpenCOTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	NULL,
	TRANS(SocketOpenCOTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(SocketOpenCLTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	TRANS(SocketOpenCLTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_REOPEN
	TRANS(SocketReopenCOTSServer),
	TRANS(SocketReopenCLTSServer),
#endif
	TRANS(SocketSetOption),
#ifdef TRANS_SERVER
	TRANS(SocketINETCreateListener),
	NULL,					/* ResetListener */
	TRANS(SocketINETAccept),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(SocketINETConnect),
#endif /* TRANS_CLIENT */
	TRANS(SocketBytesReadable),
	TRANS(SocketRead),
	TRANS(SocketWrite),
	TRANS(SocketReadv),
	TRANS(SocketWritev),
	TRANS(SocketDisconnect),
	TRANS(SocketINETClose),
	TRANS(SocketINETClose),
	};
#endif /* IPv6 */
#endif /* TCPCONN */

#ifdef UNIXCONN
#if !defined(LOCALCONN)
Xtransport	TRANS(SocketLocalFuncs) = {
	/* Socket Interface */
	"local",
#ifdef HAVE_ABSTRACT_SOCKETS
	TRANS_ABSTRACT,
#else
	0,
#endif
#ifdef TRANS_CLIENT
	TRANS(SocketOpenCOTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	NULL,
	TRANS(SocketOpenCOTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(SocketOpenCLTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	TRANS(SocketOpenCLTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_REOPEN
	TRANS(SocketReopenCOTSServer),
	TRANS(SocketReopenCLTSServer),
#endif
	TRANS(SocketSetOption),
#ifdef TRANS_SERVER
	TRANS(SocketUNIXCreateListener),
	TRANS(SocketUNIXResetListener),
	TRANS(SocketUNIXAccept),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(SocketUNIXConnect),
#endif /* TRANS_CLIENT */
	TRANS(SocketBytesReadable),
	TRANS(SocketRead),
	TRANS(SocketWrite),
	TRANS(SocketReadv),
	TRANS(SocketWritev),
	TRANS(SocketDisconnect),
	TRANS(SocketUNIXClose),
	TRANS(SocketUNIXCloseForCloning),
	};
#endif /* !LOCALCONN */
# ifdef TRANS_SERVER
#  if !defined(LOCALCONN)
static char* unix_nolisten[] = { "local" , NULL };
#  endif
# endif
	    
Xtransport	TRANS(SocketUNIXFuncs) = {
	/* Socket Interface */
	"unix",
#if !defined(LOCALCONN) && !defined(HAVE_ABSTRACT_SOCKETS)
        TRANS_ALIAS,
#else
	0,
#endif
#ifdef TRANS_CLIENT
	TRANS(SocketOpenCOTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
#if !defined(LOCALCONN)
	unix_nolisten,
#else
	NULL,
#endif
	TRANS(SocketOpenCOTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(SocketOpenCLTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	TRANS(SocketOpenCLTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_REOPEN
	TRANS(SocketReopenCOTSServer),
	TRANS(SocketReopenCLTSServer),
#endif
	TRANS(SocketSetOption),
#ifdef TRANS_SERVER
	TRANS(SocketUNIXCreateListener),
	TRANS(SocketUNIXResetListener),
	TRANS(SocketUNIXAccept),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(SocketUNIXConnect),
#endif /* TRANS_CLIENT */
	TRANS(SocketBytesReadable),
	TRANS(SocketRead),
	TRANS(SocketWrite),
	TRANS(SocketReadv),
	TRANS(SocketWritev),
	TRANS(SocketDisconnect),
	TRANS(SocketUNIXClose),
	TRANS(SocketUNIXCloseForCloning),
	};

#endif /* UNIXCONN */