File: connection.c

package info (click to toggle)
nas 1.9.2-4squeeze1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 7,996 kB
  • ctags: 29,014
  • sloc: ansic: 52,102; makefile: 32,002; sh: 6,972; perl: 1,104; yacc: 249; cpp: 216; lex: 68
file content (2861 lines) | stat: -rw-r--r-- 80,526 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright 1993 Network Computing Devices, Inc.
 *
 * 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, and that the name Network Computing Devices, Inc. not be
 * used in advertising or publicity pertaining to distribution of this 
 * software without specific, written prior permission.
 * 
 * THIS SOFTWARE IS PROVIDED `AS-IS'.  NETWORK COMPUTING DEVICES, INC.,
 * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT
 * LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NONINFRINGEMENT.  IN NO EVENT SHALL NETWORK
 * COMPUTING DEVICES, INC., BE LIABLE FOR ANY DAMAGES WHATSOEVER, INCLUDING
 * SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, INCLUDING LOSS OF USE, DATA,
 * OR PROFITS, EVEN IF ADVISED OF THE POSSIBILITY THEREOF, AND REGARDLESS OF
 * WHETHER IN AN ACTION IN CONTRACT, TORT OR NEGLIGENCE, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 * 
 * $NCDId: @(#)connection.c,v 1.11 1996/04/24 17:15:49 greg Exp $
 */
/***********************************************************
Some portions derived from:

Copyright 1987, 1989 by Digital Equipment Corporation, Maynard, Massachusetts,
and the Massachusetts Institute of Technology, Cambridge, Massachusetts.

                        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 names of Digital or MIT not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.  

DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL 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.

******************************************************************/
/*****************************************************************
 *  Stuff to create connections --- OS dependent
 *
 *      EstablishNewConnections, CreateWellKnownSockets, ResetWellKnownSockets,
 *      CloseDownConnection, CheckConnections, AddEnabledDevice,
 *      RemoveEnabledDevice, OnlyListToOneClient,
 *      ListenToAllClients,
 *
 *      (WaitForSomething is in its own file)
 *
 *      In this implementation, a client socket table is not kept.
 *      Instead, what would be the index into the table is just the
 *      file descriptor of the socket.  This won't work for if the
 *      socket ids aren't small nums (0 - 2^8)
 *
 *****************************************************************/

#include "nasconf.h"

#if defined(__CYGWIN__)
#define S_IFSOCK        _IFSOCK
#define S_IFMT          _IFMT

#include <limits.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif



#include <audio/audio.h>
#include <audio/Aproto.h>
#ifndef _MINIX
#include <sys/param.h>
#endif
#include <errno.h>
#include <audio/Aos.h>
#if !defined(AMOEBA) && !defined(_MINIX)
#ifdef ESIX
#include <lan/socket.h>
#else
#include <sys/socket.h>
#endif
#endif

#include <signal.h>
#include <setjmp.h>

#ifdef hpux
#include <sys/utsname.h>
#include <sys/ioctl.h>
#endif

#ifdef SVR4
#include <sys/resource.h>
#endif

#ifdef AIXV3
#include <sys/ioctl.h>
#endif

#ifdef TCPCONN
#ifndef _MINIX
# include <netinet/in.h>
# ifndef hpux
#  ifdef apollo
#   ifndef NO_TCP_H
#    include <netinet/tcp.h>
#   endif
#  else
#   include <netinet/tcp.h>
#  endif
# endif
#else /* _MINIX */
#include <sys/ioctl.h>
#include <stdlib.h>
#include <net/netlib.h>
#include <net/gen/in.h>
#include <net/gen/tcp.h>
#include <net/gen/tcp_io.h>
#endif /* _MINIX */
#endif

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

#ifdef UNIXCONN
/*
 * sites should be careful to have separate /tmp directories for diskless nodes
 */
#include <sys/un.h>
#include <sys/stat.h>
static int unixDomainConnection = -1;
#endif

#include <stdio.h>
#if !defined(AMOEBA) && !defined(_MINIX)
#include <sys/uio.h>
#endif
#include "os.h"
#include "osdep.h"
#include "opaque.h"
#include "dixstruct.h"

#if defined(SYSV) || defined(SVR4)
#ifdef hpux
#define signal  _local_signal
#define sigset  _local_signal

#ifndef NeedFunctionPrototypes
static void (*_local_signal(sig, action)) ()
int sig;
void (*action) ();
#else /* NeedFunctionPrototypes */
static void (*_local_signal(int sig, void (*action) (int))) (int)
#endif                          /* NeedFunctionPrototypes */
{
    struct sigvec vec;
    struct sigvec ovec;

    vec.sv_handler = action;
    vec.sv_flags = 0;
    sigvector(sig, &vec, &ovec);

    return (ovec.sv_handler);
}
#else
#define signal sigset
#endif
#endif

#ifdef DNETCONN
#include <netdnet/dn.h>
#endif /* DNETCONN */

#ifndef SCO
#define _OSWriteV       writev
#endif /* SCO */

#ifdef SIGNALRETURNSINT
#define SIGVAL int
#else
#define SIGVAL void
#endif

typedef long CCID;              /* mask of indices into client socket table */

#ifndef X_UNIX_PATH
# ifdef hpux
#  define X_UNIX_DIR      "/usr/spool/sockets/audio"
#  define X_UNIX_PATH     "/usr/spool/sockets/audio/"
#  define OLD_UNIX_DIR    "/tmp/.sockets"
# else
#  if defined(linux)
#   define X_UNIX_DIR      "/var/run/nasd"
#   define X_UNIX_PATH     "/var/run/nasd/audio"
#  else
#   define X_UNIX_DIR      "/tmp/.sockets"
#   define X_UNIX_PATH     "/tmp/.sockets/audio"
#  endif
# endif
#endif

#ifdef SERVER_LOCALCONN
#include <sys/stream.h>
#include <sys/stropts.h>
#include <sys/utsname.h>
#ifndef UNIXCONN
#include <sys/stat.h>
#endif
#ifdef SVR4
static int NstrFd = -1;
#endif
static int ptsFd = -1;
static int spxFd = -1;
static int xsFd = -1;
static long AllStreams[mskcnt]; /* keep up, whos on a STREAMS pipe */
/*
 * Why not use the same path as for UNIXCONN ?? 
 * Diskless workstations may have a common /tmp directory. This may cause much
 * trouble. Since every workstation MUST have it's own /dev, so lets use this
 * directory.
 */
#define AUDIO_STREAMS_DIR "/dev/Au"
#define AUDIO_STREAMS_PATH "/dev/Au/server."
#ifdef SVR4
# define AUDIO_NSTREAMS_PATH "/dev/Au/Nserver."
#endif
#define AUDIO_XSIGHT_PATH "/dev/Au"
#if defined(SVR4_ACP) && defined(UNIXCONN)
# define AUDIO_ISC_DIR "/tmp/.ISC-unix"
# define AUDIO_ISC_PATH "/tmp/.ISC-unix/Au"
#endif
#endif /* SERVER_LOCALCONN */

extern char *display;           /* The display number */
#ifndef AMOEBA
int lastfdesc;                  /* maximum file descriptor */

#ifndef _MINIX
long WellKnownConnections;      /* Listener mask */
long EnabledDevices[mskcnt];    /* mask for input devices that are on */
long AllSockets[mskcnt];        /* select on this */
long AllClients[mskcnt];        /* available clients */
long LastSelectMask[mskcnt];    /* mask returned from last select call */
long ClientsWithInput[mskcnt];  /* clients with FULL requests in buffer */
long ClientsWriteBlocked[mskcnt];       /* clients who cannot receive output */
long OutputPending[mskcnt];     /* clients with reply/event data ready to go */
long NConnBitArrays = mskcnt;
#endif
long MaxClients = MAXSOCKS;
Bool NewOutputPending;          /* not yet attempted to write some new output */
Bool AnyClientsWriteBlocked;    /* true if some client blocked on write */

Bool RunFromSmartParent;        /* send SIGUSR1 to parent process */
Bool PartialNetwork;            /* continue even if unable to bind all addrs */
static int ParentProcess;

int AudioListenPort = AU_DEFAULT_TCP_PORT;

static Bool debug_conns = FALSE;

static long IgnoredClientsWithInput[mskcnt];
static long GrabImperviousClients[mskcnt];
#ifndef _MINIX
static long SavedAllClients[mskcnt];
static long SavedAllSockets[mskcnt];
static long SavedClientsWithInput[mskcnt];
#endif /* _MINIX */
int GrabInProgress = 0;

int ConnectionTranslation[MAXSOCKS];
#endif /* !AMOEBA */

#ifdef _MINIX
asio_fd_set_t InprogressFdSet;  /* fds that have an operation in progress */
asio_fd_set_t ListenFdSet;      /* fds that accept new connections */
asio_fd_set_t CompletedFdSet;   /* fds that completed some I/O but have not
                                 * been able to process this information
                                 * synchronously (or completely) */
asio_fd_set_t ClientFdSet;      /* fds that belong to clients */
asio_fd_set_t IgnoreFdSet;      /* Ignore these clients if they have completed
                                 * I/O */
asio_fd_set_t GrabFdSet;        /* This is the client who has the grab, 
                                 * if any */

static int TcpListenFd = -1;    /* initialy there is no tcp fd. */
Bool AnyClientsWithInput = FALSE;

struct NewConnection {
    int nc_result;              /* What was the result */
    int nc_errno;               /* and the error */
} NewTcpConnection;
#endif

extern int auditTrailLevel;
extern ClientPtr NextAvailableClient();

extern SIGVAL AutoResetServer();
extern SIGVAL GiveUp();
extern AuID CheckAuthorization();
#ifndef AMOEBA
static void CloseDownFileDescriptor(), ErrorConnMax();
#endif
extern void FreeOsBuffers(), ResetOsBuffers();

#ifdef TCPCONN
#ifndef _MINIX
static int
open_tcp_socket()
{
    struct sockaddr_in insock;
    int request;
    int retry;
#ifdef SVR4
#undef SO_DONTLINGER
#endif
#ifndef SO_DONTLINGER
#ifdef SO_LINGER
    static int linger[2] = { 0, 0 };
#endif /* SO_LINGER */
#endif /* SO_DONTLINGER */

#ifdef AIXV3
#ifndef FORCE_DISPLAY_NUM
    extern int AIXTCPSocket;
    if (AIXTCPSocket >= 0) {
        request = AIXTCPSocket;
    } else
#endif /* FORCE_DISPLAY_NUM */
#endif /* AIX && etc. */
    if ((request = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        Error("Creating TCP socket");
        return -1;
    }
#ifdef SO_REUSEADDR
    /* Necesary to restart the server without a reboot */
    {
        int one = 1;
        setsockopt(request, SOL_SOCKET, SO_REUSEADDR, (char *) &one,
                   sizeof(int));
    }
#endif /* SO_REUSEADDR */
#ifdef AIXV3
#ifndef FORCE_DISPLAY_NUMBER
    if (AIXTCPSocket < 0)
#endif
#endif
    {
        bzero((char *) &insock, sizeof(insock));
#ifdef BSD44SOCKETS
        insock.sin_len = sizeof(insock);
#endif
        insock.sin_family = AF_INET;
        insock.sin_port =
                htons((unsigned short) (AudioListenPort + atoi(display)));

        if (NasConfig.LocalOnly) {
            insock.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
        } else {
            insock.sin_addr.s_addr = htonl(INADDR_ANY);
        }

        retry = 20;
        while (bind(request, (struct sockaddr *) &insock, sizeof(insock))) {
            if (--retry == 0) {
                Error("Binding TCP socket");
                close(request);
                return -1;
            }
#ifdef SO_REUSEADDR
            sleep(1);
#else
            sleep(10);
#endif /* SO_REUSEDADDR */
        }
    }
#ifdef SO_DONTLINGER
    if (setsockopt(request, SOL_SOCKET, SO_DONTLINGER, (char *) NULL, 0))
        Error("Setting TCP SO_DONTLINGER");
#else
#ifdef SO_LINGER
    if (setsockopt(request, SOL_SOCKET, SO_LINGER,
                   (char *) linger, sizeof(linger)))
        Error("Setting TCP SO_LINGER");
#endif /* SO_LINGER */
#endif /* SO_DONTLINGER */
    if (listen(request, 5)) {
        Error("TCP Listening");
        close(request);
        return -1;
    }
    return request;
}
#else /* _MINIX */

Bool EstablishNewConnections();

static int
MNX_open_tcp_socket(int *extra_fd)
{
    int fd, r, flags, retry;
    char *tcp_dev, *check;
    int display_no;
    nwio_tcpconf_t tcpconf;
    nwio_tcpcl_t tcpcl;

    /* Allow the audio server to run on a different IP device with the 
     * TCP_DEVICE environment variable, otherwise we take the default.
     * A different IP device is specified via its number concatenated
     * to the TCP device name, so check that the default TCP device is
     * a prefix of the value read from the TCP_DEVICE environment
     * variable.
     */
    tcp_dev = getenv("TCP_DEVICE");
    if (!tcp_dev || strncmp(tcp_dev, TCP_DEVICE, strlen(TCP_DEVICE))) {
        fprintf(stderr, "Ignoring invalid TCP_DEVICE environment variable.\n");
        tcp_dev = TCP_DEVICE;
    }

    fd = open(tcp_dev, O_RDWR);
    if (fd == -1) {
        Error("Creating TCP socket");
        return -1;
    }
    if (extra_fd) {
        *extra_fd = fd;

        fd = open(tcp_dev, O_RDWR);
        if (fd == -1) {
            Error("Creating TCP socket");
            close(*extra_fd);
            return -1;
        }
    }

    /* Bind the socket */
    display_no = strtol(display, &check, 0);
    if (check[0] != '\0') {
        Error("Unable to parse display number");
        return -1;
    }
    tcpconf.nwtc_flags = NWTC_SHARED | NWTC_LP_SET | NWTC_UNSET_RA |
            NWTC_UNSET_RP;
    tcpconf.nwtc_locport = htons(AUDIO_TCP_PORT + display_no);
    r = ioctl(fd, NWIOSTCPCONF, &tcpconf);
    if (r == -1) {
        Error("Binding TCP socket");
        close(fd);
        return -1;
    }

    /* Mark the filedescriptor as asynchronous */
    flags = fcntl(fd, F_GETFL);
    if (flags == -1) {
        Error("Unable to get the flags of a tcp fd");
        close(fd);
        return -1;
    }
    r = fcntl(fd, F_SETFD, flags | FD_ASYNCHIO);
    if (r == -1) {
        Error("Unable to enable asynchronous I/O on a tcp fd");
        close(fd);
        return -1;
    }

    /* Now try to listen, possible return values are:
     * EINPROGRESS: the default, we can return the fd
     * EAGAIN:      all entry in the connection table are inuse, 
     *              we wait a few seconds.
     * 0:           some client arrived, we enqueue
     *              EstablishNewConnections
     */
    for (retry = 0; retry < 10; retry++) {
        tcpcl.nwtcl_flags = 0;
        r = ioctl(fd, NWIOTCPLISTEN, &tcpcl);
        if (r == -1 && errno == EINPROGRESS)
            return fd;          /* Normal case */
        else if (r == -1 && errno == EAGAIN) {
            sleep(1);
            continue;
        } else {
            NewTcpConnection.nc_result = r;
            NewTcpConnection.nc_errno = errno;

            /* Let EstablishNewConnections deal with this
             * situation
             */
            QueueWorkProc(EstablishNewConnections, NULL,
                          (pointer) & NewTcpConnection);
            return fd;
        }
    }
    Error("Binding TCP socket");
    close(fd);
    return -1;
}
#endif /* _MINIX */
#endif /* TCPCONN */

#ifdef UNIXCONN

static struct sockaddr_un unsock;

static int
open_unix_socket(void)
{
    int oldUmask;
    int request;

    bzero((char *) &unsock, sizeof(unsock));
    unsock.sun_family = AF_UNIX;
    oldUmask = umask(0);

#ifdef X_UNIX_DIR
# ifndef S_ISVTX
#  define S_ISVTX   0           /* shouldn't use it if not available */
# endif

    /* JET - 2/23/2002 this is problematic when nasd is run as a
       normal user and root has run nasd beforehand - ie: you can't
       remove the old socket, but security is improved.  ideally nasd should
       just remove the socket on termination (SIGINT)
     */
    if (!mkdir(X_UNIX_DIR, 0777))
        chmod(X_UNIX_DIR, 0777 | S_ISVTX);
#endif

    strncpy(unsock.sun_path, X_UNIX_PATH, sizeof unsock.sun_path);
    unsock.sun_path[sizeof unsock.sun_path - 1] = '\0';
    strncat(unsock.sun_path, display,
            sizeof unsock.sun_path - strlen(unsock.sun_path) - 1);
#ifdef BSD44SOCKETS
    unsock.sun_len = strlen(unsock.sun_path);
#endif
#ifdef hpux
    {
        /*    The following is for backwards compatibility
         *    with old HP clients. This old scheme predates the use
         *    of the /usr/spool/sockets directory, and uses hostname:display
         *    in the /tmp/.sockets directory
         */
        struct utsname systemName;
        static char oldLinkName[256];

        uname(&systemName);
        strncpy(oldLinkName, OLD_UNIX_DIR, sizeof oldLinkName);
        oldLinkName[sizeof oldLinkName - 1] = '\0';
        if (!mkdir(oldLinkName, 0777))
            chown(oldLinkName, 2, 3);
        strncat(oldLinkName, "/", sizeof oldLinkName - strlen(oldLinkName) - 1);
        strncat(oldLinkName, systemName.nodename,
                sizeof oldLinkName - strlen(oldLinkName) - 1);
        strncat(oldLinkName, display,
                sizeof oldLinkName - strlen(oldLinkName) - 1);
        unlink(oldLinkName);
        symlink(unsock.sun_path, oldLinkName);
    }
#endif /* hpux */
    unlink(unsock.sun_path);
    if ((request = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
        char *buffer;
        int i;

        i = strlen(unsock.sun_path);
        buffer = (char *) malloc(i + 80);
        if (buffer) {
            snprintf(buffer, i+80, "Error creating unix socket: %s\n",
                     unsock.sun_path);
            Error(buffer);
            free(buffer);
        } else
            Error("Creating Unix socket");

        return -1;
    }
#ifdef BSD44SOCKETS
    if (bind(request, (struct sockaddr *) &unsock, SUN_LEN(&unsock)))
#else
    if (bind
        (request, (struct sockaddr *) &unsock,
         strlen(unsock.sun_path) + 2))
#endif
    {
        char *buffer;
        int i;

        i = strlen(unsock.sun_path);
        buffer = (char *) malloc(i + 80);
        if (buffer) {
            snprintf(buffer, i+80, "Error binding unix socket: %s\n",
                    unsock.sun_path);
            Error(buffer);
            free(buffer);
        } else
            Error("Creating Unix socket");

        close(request);
        return -1;
    }
    if (listen(request, 5)) {
        Error("Unix Listen");
        close(request);
        return -1;
    }
    (void) umask(oldUmask);
    return request;
}
#endif /*UNIXCONN */

#ifdef SERVER_LOCALCONN

#if !defined(SVR4) || defined(SVR4_ACP)
static int
connect_spipe(int fd1, int fd2)
{
    long temp;
    struct strfdinsert sbuf;

    sbuf.databuf.maxlen = -1;
    sbuf.databuf.len = -1;
    sbuf.databuf.buf = NULL;
    sbuf.ctlbuf.maxlen = sizeof(long);
    sbuf.ctlbuf.len = sizeof(long);
    sbuf.ctlbuf.buf = (caddr_t) & temp;
    sbuf.offset = 0;
    sbuf.fildes = fd2;
    sbuf.flags = 0;
    if (ioctl(fd1, I_FDINSERT, &sbuf) == -1)
        return (-1);

    return (0);
}

static int
named_spipe(int fd, char *path)
{
    int oldUmask, ret;
    struct stat sbuf;

    oldUmask = umask(0);

    (void) fstat(fd, &sbuf);
    ret = mknod(path, 0020666, sbuf.st_rdev);

    umask(oldUmask);

    return (ret < 0 ? -1 : fd);
}

static int
open_isc_local(void)
{
    int fd = -1, fds = -1;
    long temp;
    struct strfdinsert buf;
    char path[64];

#if defined(SVR4_ACP) && defined(UNIXCONN)
    /*
     * ISC local connections go the same place as Unix-domain sockets (brain
     * death of the highest magnitude.  To allow this to function, we put
     * the ISC streams pipe elsewhere.  This will require that a binary edit
     * be done on ISC binaries under SVR4, but life is tough some times.
     */
    mkdir(AUDIO_ISC_DIR, 0777);
    chmod(AUDIO_ISC_DIR, 0777);

    strncpy(path, AUDIO_ISC_PATH, sizeof path); path[sizeof path - 1] = '\0';
#else /* SVR4_ACP && UNIXCONN */
    mkdir(X_UNIX_DIR, 0777);
    chmod(X_UNIX_DIR, 0777);

    strncpy(path, X_UNIX_PATH, sizeof path); path[sizeof path - 1] = '\0';
#endif /* SVR4_ACP && UNIXCONN */

    strncat(path, display, sizeof path - strlen(path) - 1);

    if (unlink(path) < 0 && errno != ENOENT) {
        ErrorF("audio server: ISC listener pipe  in use (%s)\n", path);
        return (-1);
    }

    if ((fds = open("/dev/spx", O_RDWR)) >= 0 &&
        (fd = open("/dev/spx", O_RDWR)) >= 0)

        if (connect_spipe(fds, fd) != -1 && named_spipe(fds, path) != -1)

            return (fd);
        else
            Error("audio server: Can't set up ISC listener pipes");

#ifndef SVR4
    /*
     * At this point, most SVR4 versions will fail on this, so leave out the
     * warning
     */
    else
        Error("audio server: Cannot open \"/dev/spx\" for ISC listener");
#endif

    (void) close(fds);
    (void) close(fd);
    return (-1);
}


static int
accept_isc_local(void)
{
    struct strrecvfd buf;

    while (ioctl(spxFd, I_RECVFD, &buf) < 0)
        if (errno != EAGAIN) {
            Error("audio server: Can't read fildes from ISC client");
            return (-1);
        }

    BITSET(AllStreams, buf.fd);
    return (buf.fd);
}

static int
open_xsight_local(void)
{
    int fds = -1, fdr = -1;
    char pathS[64], pathR[64];

    snprintf(pathS, sizeof pathS, "%s%sS", AUDIO_XSIGHT_PATH, display);
    snprintf(pathR, sizeof pathR, "%s%sR", AUDIO_XSIGHT_PATH, display);

    if ((unlink(pathS) < 0 && errno != ENOENT) ||
        (unlink(pathR) < 0 && errno != ENOENT)) {
        ErrorF("audio server: SCO listener pipe in use (%s)\n", pathR);
        return (-1);
    }

    if ((fds = open("/dev/spx", O_RDWR)) >= 0 &&
        (fdr = open("/dev/spx", O_RDWR)) >= 0)

        if (connect_spipe(fds, fdr) != -1 &&
            named_spipe(fds, pathS) != -1 && named_spipe(fdr, pathR) != -1)

            return (fds);
        else
            Error("audio server: Can't set up SCO listener pipes");

#ifndef SVR4
    /*
     * At this point, most SVR4 versions will fail on this, so leave out the
     * warning
     */
    else
        Error("audio server: Cannot open \"/dev/spx\" for SCO listener");
#endif

    (void) close(fds);
    (void) close(fdr);
    return (-1);
}


static int
accept_xsight_local(void)
{
    char c;
    int fd;
    long temp;
    struct strfdinsert buf;

    if (read(xsFd, &c, 1) < 0) {
        Error("audio server: Can't read from SCO client");
        return (-1);
    }

    if ((fd = open("/dev/spx", O_RDWR)) < 0) {
        Error("audio server: Can't open \"/dev/spx\" for SCO client connection");
        return (-1);
    }

    if (connect_spipe(xsFd, fd) < 0) {
        Error("audio server: Can't connect pipes for SCO client connection");
        (void) close(fd);
        return (-1);
    }

    BITSET(AllStreams, fd);
    return (fd);
}
#endif /* SVR4 */

static int
open_att_local(void)
{
    char *slave;
    int fd;
    char path[64];

    mkdir(AUDIO_STREAMS_DIR, 0777);
    chmod(AUDIO_STREAMS_DIR, 0777);

    strncpy(path, AUDIO_STREAMS_PATH, sizeof path);
    path[sizeof path - 1] = '\0';
    strncat(path, display, sizeof path - strlen(path) - 1);

    if ((unlink(path) < 0 && errno != ENOENT)) {
        ErrorF("audio server: USL listener pipe in use (%s)\n", path);
        return (-1);
    }

    if ((fd = open("/dev/ptmx", O_RDWR)) < 0) {
        Error("audio server: Cannot open \"/dev/ptmx\" for USL listener");
        return (-1);
    }

    grantpt(fd);
    unlockpt(fd);
    slave = (char *) ptsname(fd);
    if (link(slave, path) < 0 || chmod(path, 0666) < 0) {
        Error("audio server: Can't set up local USL listener");
        return (-1);
    }

    if (open(path, O_RDWR) < 0) {
        ErrorF("audio server: Can't open %s for USL listener\n", path);
        close(fd);
        return (-1);
    }

    return (fd);
}

#ifdef SVR4
static int
open_att_svr4_local(void)
{
    int fd[2], tfd;
    char path[64];

    mkdir(AUDIO_STREAMS_DIR, 0777);
    chmod(AUDIO_STREAMS_DIR, 0777);

    strncpy(path, AUDIO_NSTREAMS_PATH, sizeof path);
    path[sizeof path - 1] = '\0';
    strncat(path, display, sizeof path - strlen(path) - 1);

    if ((unlink(path) < 0 && errno != ENOENT)) {
        ErrorF("audio server: SVR4 named listener pipe in use (%s)\n",
               path);
        return (-1);
    }

    if ((tfd = creat(path, (mode_t) 0666)) < 0) {
        ErrorF("audio server: Can't create named-streams path (%s)\n",
               path);
        return (-1);
    }
    close(tfd);
    if (chmod(path, (mode_t) 0666) < 0) {
        ErrorF("audio server: Can't change mode on %s\n", path);
        return (-1);
    }

    if (pipe(fd) != 0) {
        Error("audio server: SVR4 named listener pipe creation failed\n");
        return (-1);
    }

    if (ioctl(fd[0], I_PUSH, "connld") != 0) {
        Error("audio server: ioctl(I_PUSH) failed for SVR4 named listener pipe\n");
        return (-1);
    }

    if (fattach(fd[0], path) != 0) {
        ErrorF("SVR4: fattach on %s failed for SVR4 named listener pipe\n",
               path);
        return (-1);
    }

    return (fd[1]);
}
#endif /* SVR4 */

/* JET 3/17/2007 - Luigi Auriemma's nasbugs, attack #1, simple buffer
   overflow.  Now we limit to _MAX_SALVENM.
 */

#define _MAX_SLAVENM    (256)

static int
accept_att_local(void)
{
    int newconn;
    int read_in;
    unsigned char length;
    char path[_MAX_SLAVENM];

    /*
     * first get device-name
     */
    if ((read_in = read(ptsFd, &length, 1)) <= 0) {
        Error("audio server: Can't read slave name length from USL client connection");
        return (-1);
    }

    if (length >= _MAX_SLAVENM)
      length = _MAX_SLAVENM - 1;

    if ((read_in = read(ptsFd, path, length)) <= 0) {
        Error("audio server: Can't read slave name from USL client connection");
        return (-1);
    }

    path[length] = '\0';

    if ((newconn = open(path, O_RDWR)) < 0) {
        Error("audio server: Can't open slave for USL client connection");
        return (-1);
    }

    (void) write(newconn, "1", 1);      /* send an acknowledge to the client */

    BITSET(AllStreams, newconn);
    return (newconn);
}

#ifdef SVR4
static int
accept_att_svr4_local(void)
{
    struct strrecvfd str;

    if (ioctl(NstrFd, I_RECVFD, &str) < 0) {
        ErrorF("audio server: I_RECVFD failed on SVR4 named client connection\n");
        return (-1);
    }
    BITSET(AllStreams, str.fd);
    return (str.fd);
}
#endif /* SVR4 */
#endif /* SERVER_LOCALCONN */

#ifdef SYSV386
int
sysv386_getpeername(fd, from, fromlen)
int fd;
struct sockaddr *from;
int *fromlen;
{
#ifdef SERVER_LOCALCONN
    /*
     * check up whether our fd is really a streams pipe ( /dev/pts??? )
     */
    if (GETBIT(AllStreams, fd)) {
        from->sa_family = AF_UNSPEC;
        *fromlen = 0;
        return 0;
    }
#endif /* SERVER_LOCALCONN */
#if defined(TCPCONN) || defined(DNETCONN) || defined(UNIXCONN)
    return getpeername(fd, from, fromlen);
#endif
}

int
sysv386_accept(fd, from, fromlen)
int fd;
struct sockaddr *from;
int *fromlen;
{
#ifdef SERVER_LOCALCONN
    if (fd == ptsFd)
        return accept_att_local();
#ifdef SVR4
    if (fd == NstrFd)
        return accept_att_svr4_local();
#endif /* SVR4 */
#if !defined(SVR4) || defined(SVR4_ACP)
    if (fd == spxFd)
        return accept_isc_local();
    if (fd == xsFd)
        return accept_xsight_local();
#endif /* !SVR4 || SVR4_ACP) */
#endif /* SERVER_LOCALCONN */
/*
 * else we are handling the normal accept case
 */
#if defined(TCPCONN) || defined(DNETCONN) || defined(UNIXCONN)
    return accept(fd, from, fromlen);
#endif
}

#define getpeername     sysv386_getpeername
#define accept          sysv386_accept

#endif /* SYSV386 */

#ifdef hpux
/*
 * hpux returns EOPNOTSUPP when using getpeername on a unix-domain
 * socket.  In this case, smash the socket address with the address
 * used to bind the connection socket and return success.
 */
hpux_getpeername(fd, from, fromlen)
int fd;
struct sockaddr *from;
int *fromlen;
{
    int ret;
    int len;

    ret = getpeername(fd, from, fromlen);
    if (ret == -1 && errno == EOPNOTSUPP) {
        ret = 0;
        len = strlen(unsock.sun_path) + 2;
        if (len > *fromlen)
            len = *fromlen;
        bcopy((char *) &unsock, (char *) from, len);
        *fromlen = len;
    }
    return ret;
}

#define getpeername(fd, from, fromlen)  hpux_getpeername(fd, from, fromlen)

#endif

#ifdef DNETCONN
static int
open_dnet_socket(void)
{
    int request;
    struct sockaddr_dn dnsock;

    if ((request = socket(AF_DECnet, SOCK_STREAM, 0)) < 0) {
        Error("Creating DECnet socket");
        return -1;
    }
    bzero((char *) &dnsock, sizeof(dnsock));
    dnsock.sdn_family = AF_DECnet;
    snprintf(dnsock.sdn_objname, sizeof(dnsock.sdn_objname), "AUDIO$%d",
             atoi(display));
    dnsock.sdn_objnamel = strlen(dnsock.sdn_objname);
    if (bind(request, (struct sockaddr *) &dnsock, sizeof(dnsock))) {
        Error("Binding DECnet socket");
        close(request);
        return -1;
    }
    if (listen(request, 5)) {
        Error("DECnet Listening");
        close(request);
        return -1;
    }
    return request;
}
#endif /* DNETCONN */

#define NOROOM "Maximum number of clients reached"

#ifndef AMOEBA

/*****************
 * CreateWellKnownSockets
 *    At initialization, create the sockets to listen on for new clients.
 *****************/

void
CreateWellKnownSockets(void)
{
    int request, i;
#ifdef SVR4
    struct rlimit Rlimit;
#endif
#if _MINIX
    int extra_fd;
#endif

#if defined(SERVER_LOCK)
    Lock_Server();
#endif /* SERVER_LOCK */

#ifndef _MINIX
    CLEARBITS(AllSockets);
    CLEARBITS(AllClients);
    CLEARBITS(LastSelectMask);
    CLEARBITS(ClientsWithInput);

    for (i = 0; i < MAXSOCKS; i++)
        ConnectionTranslation[i] = 0;
#ifndef X_NOT_POSIX
#ifdef __FreeBSD__
    lastfdesc = getdtablesize() - 1;
#else
    lastfdesc = sysconf(_SC_OPEN_MAX) - 1;
#endif
#else
#ifdef hpux
    lastfdesc = _NFILE - 1;
#else
#ifdef SVR4
    if (getrlimit(RLIMIT_NOFILE, &Rlimit) != 0) {
        lastfdesc = _NFILE - 1;
    } else {
        /*
         * If the limit is at infinity, the server could be QUITE busy,
         * so set a reasonable limit.
         */
        if (Rlimit.rlim_cur == RLIM_INFINITY)
            lastfdesc = 1024;
        else
            lastfdesc = Rlimit.rlim_cur;
    }
#else
    lastfdesc = getdtablesize() - 1;
#endif /* SVR4 */
#endif /* hpux */
#endif /* X_NOT_POSIX */
    if (lastfdesc > MAXSOCKS) {
        lastfdesc = MAXSOCKS;
        if (debug_conns)
            ErrorF("GOT TO END OF SOCKETS %d\n", MAXSOCKS);
    }

    WellKnownConnections = 0;
#ifdef SERVER_LOCALCONN
    CLEARBITS(AllStreams);
    if ((ptsFd = open_att_local()) != -1) {
        WellKnownConnections |= (1L << ptsFd);
    }
#ifdef SVR4
    if ((NstrFd = open_att_svr4_local()) != -1) {
        WellKnownConnections |= (1L << NstrFd);
    }
#endif /* SVR4 */
#if !defined(SVR4) || defined(SVR4_ACP)
    if ((spxFd = open_isc_local()) != -1) {
        WellKnownConnections |= (1L << spxFd);
    }
    if ((xsFd = open_xsight_local()) != -1) {
        WellKnownConnections |= (1L << xsFd);
    }
#endif /* !SVR4 || SVR4_ACP */
#endif /* SERVER_LOCALCONN */
#ifdef TCPCONN
    if ((request = open_tcp_socket()) != -1) {
        WellKnownConnections |= (1L << request);
        DefineSelf(request);
    } else if (!PartialNetwork) {
        FatalError("Cannot establish tcp listening socket\n");
    } else {
        ErrorF("Cannot establish tcp listening socket\n");
    }
#endif /* TCPCONN */
#ifdef DNETCONN
    if ((request = open_dnet_socket()) != -1) {
        WellKnownConnections |= (1L << request);
        DefineSelf(request);
    } else if (!PartialNetwork) {
        FatalError("Cannot establish dnet listening socket\n");
    } else {
        ErrorF("Cannot establish dnet listening socket\n");
    }
#endif /* DNETCONN */
#ifdef UNIXCONN
    if ((request = open_unix_socket()) != -1) {
        WellKnownConnections |= (1L << request);
        unixDomainConnection = request;
    } else if (!PartialNetwork) {
        FatalError("Cannot establish unix listening socket\n");
    } else {
        ErrorF("Cannot establish unix listening socket\n");
    }
#endif /* UNIXCONN */
    if (WellKnownConnections == 0)
        FatalError("Cannot establish any listening sockets\n");
#else /* _MINIX */
    {
        int no_listeners = 0;

        for (i = 0; i < MAXSOCKS; i++)
            ConnectionTranslation[i] = 0;

        lastfdesc = ASIO_FD_SETSIZE - 1;        /* Can only fwait on these. */

        if (lastfdesc > MAXSOCKS) {
            lastfdesc = MAXSOCKS;
            if (debug_conns)
                ErrorF("GOT TO END OF SOCKETS %d\n", MAXSOCKS);
        }

        ASIO_FD_ZERO(&ListenFdSet);
        ASIO_FD_ZERO(&InprogressFdSet);
        ASIO_FD_ZERO(&CompletedFdSet);
        ASIO_FD_ZERO(&ClientFdSet);
        ASIO_FD_ZERO(&IgnoreFdSet);
        ASIO_FD_ZERO(&GrabFdSet);
#ifdef TCPCONN
        TcpListenFd = MNX_open_tcp_socket(&extra_fd);
        if (TcpListenFd != -1) {
            if (TcpListenFd < 0 || TcpListenFd > lastfdesc)
                FatalError("invaling tcp fd: %d\n", TcpListenFd);
            ASIO_FD_SET(TcpListenFd, ASIO_IOCTL, &ListenFdSet);
            ASIO_FD_SET(TcpListenFd, ASIO_IOCTL, &InprogressFdSet);
            DefineSelf(extra_fd);
            close(extra_fd);
            no_listeners++;
        } else if (!PartialNetwork) {
            FatalError("Cannot establish tcp listening socket");
        }
#endif /* TCPCONN */
        if (no_listeners == 0)
            FatalError("Cannot establish any listening sockets");
    }
#endif /* _MINIX */
    signal(SIGPIPE, SIG_IGN);
    signal(SIGHUP, AutoResetServer);
    signal(SIGINT, GiveUp);
    signal(SIGTERM, GiveUp);
#ifndef _MINIX
    AllSockets[0] = WellKnownConnections;
#endif
    ResetHosts(display);
    /*
     * Magic:  If SIGUSR1 was set to SIG_IGN when
     * the server started, assume that either
     *
     *  a- The parent process is ignoring SIGUSR1
     *
     * or
     *
     *  b- The parent process is expecting a SIGUSR1
     *     when the server is ready to accept connections
     *
     * In the first case, the signal will be harmless,
     * in the second case, the signal will be quite
     * useful
     */
    if (signal(SIGUSR1, SIG_IGN) == SIG_IGN)
        RunFromSmartParent = TRUE;
    ParentProcess = getppid();
    if (RunFromSmartParent) {
        if (ParentProcess > 0) {
            kill(ParentProcess, SIGUSR1);
        }
    }
}

void
ResetWellKnownSockets()
{
    ResetOsBuffers();
#if defined(UNIXCONN) && !defined(SVR4)
    if (unixDomainConnection != -1) {
        /*
         * see if the unix domain socket has disappeared
         */
        struct stat statb;

        if (stat(unsock.sun_path, &statb) == -1 ||
            (statb.st_mode & S_IFMT) != S_IFSOCK) {
            ErrorF("Unix domain socket %s trashed, recreating\n",
                   unsock.sun_path);
            (void) unlink(unsock.sun_path);
            (void) close(unixDomainConnection);
            WellKnownConnections &= ~(1L << unixDomainConnection);
            unixDomainConnection = open_unix_socket();
            if (unixDomainConnection != -1)
                WellKnownConnections |= (1L << unixDomainConnection);
        }
    }
#endif /* UNIXCONN */
#ifdef SERVER_LOCALCONN
    CLEARBITS(AllStreams);
#endif /* SERVER_LOCALCONN */
    ResetAuthorization();
    ResetHosts(display);
    /*
     * See above in CreateWellKnownSockets about SIGUSR1
     */
    if (RunFromSmartParent) {
        if (ParentProcess > 0) {
            kill(ParentProcess, SIGUSR1);
        }
    }
    /*
     * restart XDMCP
     */
}

static void
AuthAudit(int client, Bool letin, struct sockaddr *saddr, int len,
          unsigned short proto_n, char *auth_proto)
{
    char addr[128];

    if (!len) {
        strncpy(addr, "local host", sizeof addr);
        addr[sizeof addr - 1] = '\0';
    }
    else
        switch (saddr->sa_family) {
        case AF_UNSPEC:
#ifdef UNIXCONN
        case AF_UNIX:
#endif
            strncpy(addr, "local host", sizeof addr);
            addr[sizeof addr - 1] = '\0';
            break;
#ifdef TCPCONN
        case AF_INET:
            snprintf(addr, sizeof addr, "IP %s port %d",
                    inet_ntoa(((struct sockaddr_in *) saddr)->sin_addr),
                    (int) ntohs(((struct sockaddr_in *) saddr)->sin_port));
            break;
#endif
#ifdef DNETCONN
        case AF_DECnet:
            snprintf(addr, sizeof addr, "DN %s",
                    dnet_ntoa(&((struct sockaddr_dn *) saddr)->sdn_add));
            break;
#endif
        default:
            strncpy(addr, "unknown address", sizeof addr);
            addr[sizeof addr - 1] = '\0';
        }
    if (letin)
        AuditF("client %d connected from %s\n", client, addr);
    else
        AuditF("client %d rejected from %s\n", client, addr);
    if (proto_n)
        AuditF("  Auth name: %.*s\n", proto_n, auth_proto);
}

/*****************************************************************
 * ClientAuthorized
 *
 *    Sent by the client at connection setup:
 *                typedef struct _auConnClientPrefix {
 *                   CARD8      byteOrder;
 *                   BYTE       pad;
 *                   CARD16     majorVersion, minorVersion;
 *                   CARD16     nbytesAuthProto;    
 *                   CARD16     nbytesAuthString;   
 *                 } auConnClientPrefix;
 *
 *      It is hoped that eventually one protocol will be agreed upon.  In the
 *        mean time, a server that implements a different protocol than the
 *        client expects, or a server that only implements the host-based
 *        mechanism, will simply ignore this information.
 *
 *****************************************************************/

#ifndef _MINIX
char *
ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string)
ClientPtr client;
char *auth_proto, *auth_string;
unsigned short proto_n, string_n;
{
    OsCommPtr priv;
    union {
        struct sockaddr sa;
#ifdef UNIXCONN
        struct sockaddr_un un;
#endif                          /* UNIXCONN */
#ifdef TCPCONN
        struct sockaddr_in in;
#endif                          /* TCPCONN */
#ifdef DNETCONN
        struct sockaddr_dn dn;
#endif                          /* DNETCONN */
    } from;
    socklen_t fromlen = sizeof(from);
    AuID auth_id;

    auth_id = CheckAuthorization(proto_n, auth_proto,
                                 string_n, auth_string);

    priv = (OsCommPtr) client->osPrivate;
    if (auth_id == (AuID) ~ 0L && !NasConfig.AllowAny) {
        if (getpeername(priv->fd, &from.sa, &fromlen) != -1) {
            if (InvalidHost(&from.sa, fromlen))
                AuthAudit(client->index, FALSE, &from.sa, fromlen,
                          proto_n, auth_proto);
            else {
                auth_id = (AuID) 0;
                if (auditTrailLevel > 1)
                    AuthAudit(client->index, TRUE, &from.sa, fromlen,
                              proto_n, auth_proto);
            }
        }
        if (auth_id == (AuID) ~ 0L)
            return "Client is not authorized to connect to Server";
    } else if (auditTrailLevel > 1) {
        if (getpeername(priv->fd, &from.sa, &fromlen) != -1)
            AuthAudit(client->index, TRUE, &from.sa, fromlen,
                      proto_n, auth_proto);
    }

    priv->auth_id = auth_id;
    priv->conn_time = 0;

    /* At this point, if the client is authorized to change the access control
     * list, we should getpeername() information, and add the client to
     * the selfhosts list.  It's not really the host machine, but the
     * true purpose of the selfhosts list is to see who may change the
     * access control list.
     */
    return ((char *) NULL);
}

/*****************
 * EstablishNewConnections
 *    If anyone is waiting on listened sockets, accept them.
 *    Returns a mask with indices of new clients.  Updates AllClients
 *    and AllSockets.
 *****************/

 /*ARGSUSED*/ Bool
EstablishNewConnections(clientUnused, closure)
ClientPtr clientUnused;
pointer closure;
{
    long readyconnections;      /* mask of listeners that are ready */
    int curconn;                /* fd of listener that's ready */
    int newconn;       /* fd of new client */
    long connect_time;
    int i;
    ClientPtr client;
    OsCommPtr oc;

#ifdef TCP_NODELAY
    union {
        struct sockaddr sa;
#ifdef UNIXCONN
        struct sockaddr_un un;
#endif                          /* UNIXCONN */
#ifdef TCPCONN
        struct sockaddr_in in;
#endif                          /* TCPCONN */
#ifdef DNETCONN
        struct sockaddr_dn dn;
#endif                          /* DNETCONN */
    } from;
    socklen_t fromlen;
#endif /* TCP_NODELAY */

    readyconnections = (((long) closure) & WellKnownConnections);
    if (!readyconnections)
        return TRUE;
    connect_time = GetTimeInMillis();
    /* kill off stragglers */
    for (i = 1; i < currentMaxClients; i++) {
        if (client = clients[i]) {
            oc = (OsCommPtr) (client->osPrivate);
            if (oc && (oc->conn_time != 0) &&
                (connect_time - oc->conn_time) >= TimeOutValue)
                CloseDownClient(client);
        }
    }
    while (readyconnections) {
        curconn = ffs(readyconnections) - 1;
        readyconnections &= ~(1 << curconn);
        if ((newconn = accept(curconn,
                              (struct sockaddr *) NULL,
                              (socklen_t *) NULL)) < 0)
            continue;



        /* JET 3/17/2007 - Luigi Auriemma's nasbugs, attack #8.  
           shut down the client if the max is exceeded.  Note,
           if the client does not send any data or disconnect,
           ErrorConnMax() has been modified to return if a
           timeout occurs.  If this happens the client will simply
           be disconnected.
        */

        if (newconn >= lastfdesc - 1) {
            ErrorConnMax(newconn); 
            close(newconn);
            continue;
        }
#ifdef TCP_NODELAY
        fromlen = sizeof(from);
        if (!getpeername(newconn, &from.sa, &fromlen)) {
            if (fromlen && (from.sa.sa_family == AF_INET)) {
                int mi = 1;
                setsockopt(newconn, IPPROTO_TCP, TCP_NODELAY,
                           (char *) &mi, sizeof(int));
            }
        }
#endif /* TCP_NODELAY */
        /* ultrix reads hang on Unix sockets, hpux reads fail, AIX fails too */
#if defined(O_NONBLOCK) && (!defined(SCO) && !defined(ultrix) && !defined(hpux) && !defined(AIXV3) && !defined(uniosu))
        (void) fcntl(newconn, F_SETFL, O_NONBLOCK);
#else
#ifdef FIOSNBIO
        {
            int arg;
            arg = 1;
            ioctl(newconn, FIOSNBIO, &arg);
        }
#else
#if (defined(AIXV3) || defined(uniosu)) && defined(FIONBIO)
        {
            int arg;
            arg = 1;
            ioctl(newconn, FIONBIO, &arg);
        }
#else
        fcntl(newconn, F_SETFL, FNDELAY);
#endif
#endif
#endif
        oc = (OsCommPtr) xalloc(sizeof(OsCommRec));
        if (!oc) {
            ErrorConnMax(newconn);
            close(newconn);
            continue;
        }
        if (GrabInProgress) {
            BITSET(SavedAllClients, newconn);
            BITSET(SavedAllSockets, newconn);
        } else {
            BITSET(AllClients, newconn);
            BITSET(AllSockets, newconn);
        }
        oc->fd = newconn;
        oc->input = (ConnectionInputPtr) NULL;
        oc->output = (ConnectionOutputPtr) NULL;
        oc->conn_time = connect_time;
        if (client = NextAvailableClient((pointer) oc)) {
            ConnectionTranslation[newconn] = client->index;
        } else {
            ErrorConnMax(newconn);
            CloseDownFileDescriptor(oc);
        }
    }
    return TRUE;
}
#endif /* _MINIX */

/************
 *   ErrorConnMax
 *     Fail a connection due to lack of client or file descriptor space
 ************/

static void
ErrorConnMax(int fd)
{
    auConnSetupPrefix csp;
    char pad[3];
    struct iovec iov[3];
    char byteOrder = 0;
    int whichbyte = 1;
    struct timeval waittime;
    int rv = 0;
#ifndef _MINIX
    long mask[mskcnt];
#endif /* !_MINIX */

#ifndef _MINIX
    /* if these seems like a lot of trouble to go to, it probably is */
    waittime.tv_sec = BOTIMEOUT / MILLI_PER_SECOND;
    waittime.tv_usec = (BOTIMEOUT % MILLI_PER_SECOND) *
            (1000000 / MILLI_PER_SECOND);
    CLEARBITS(mask);
    BITSET(mask, fd);
#ifdef hpux
    rv = select(fd + 1, (int *) mask, (int *) NULL, (int *) NULL,
                &waittime);
#else
    rv =  select(fd + 1, (fd_set *) mask, (fd_set *) NULL,
                 (fd_set *) NULL, &waittime);
#endif

    /* JET 3/17/2007, if we timed out, simply return */
    if (rv == 0)
        return;

    /* try to read the byte-order of the connection */
    (void) read(fd, &byteOrder, 1);
#else
    /* Try to read the byte-order of the connection.
     * We sleep to avoid a call fwait.
     */
    sleep(1);
    if (read(fd, &byteOrder, 1) == -1) {
        /* Out of luck */
        return;
    }
#endif
    if ((byteOrder == 'l') || (byteOrder == 'B')) {
        csp.success = auFalse;
        csp.lengthReason = sizeof(NOROOM) - 1;
        csp.length = (sizeof(NOROOM) + 2) >> 2;
        csp.majorVersion = AuProtocolMajorVersion;
        csp.minorVersion = AuProtocolMinorVersion;
        if (((*(char *) &whichbyte) && (byteOrder == 'B')) ||
            (!(*(char *) &whichbyte) && (byteOrder == 'l'))) {
            swaps(&csp.majorVersion, whichbyte);
            swaps(&csp.minorVersion, whichbyte);
            swaps(&csp.length, whichbyte);
        }
#ifndef _MINIX
        iov[0].iov_len = sz_auConnSetupPrefix;
        iov[0].iov_base = (char *) &csp;
        iov[1].iov_len = csp.lengthReason;
        iov[1].iov_base = NOROOM;
        iov[2].iov_len = (4 - (csp.lengthReason & 3)) & 3;
        iov[2].iov_base = pad;
        (void) _OSWriteV(fd, iov, 3);
#else
        /* assume the underlying devices buffer a bit */
        write(fd, (char *) &csp, sz_xConnSetupPrefix);
        write(fd, NOROOM, csp.lengthReason);
        write(fd, pad, (4 - (csp.lengthReason & 3)) & 3);
#endif
    }
}

/************
 *   CloseDownFileDescriptor:
 *     Remove this file descriptor and it's I/O buffers, etc.
 ************/

#ifndef _MINIX

static void
CloseDownFileDescriptor(OsCommPtr oc)
{
    int connection = oc->fd;

    close(connection);
    FreeOsBuffers(oc);
    BITCLEAR(AllSockets, connection);
    BITCLEAR(AllClients, connection);
#ifdef SERVER_LOCALCONN
    BITCLEAR(AllStreams, connection);
#endif
    BITCLEAR(ClientsWithInput, connection);
    BITCLEAR(GrabImperviousClients, connection);
    if (GrabInProgress) {
        BITCLEAR(SavedAllSockets, connection);
        BITCLEAR(SavedAllClients, connection);
        BITCLEAR(SavedClientsWithInput, connection);
    }
    BITCLEAR(ClientsWriteBlocked, connection);
    if (!ANYSET(ClientsWriteBlocked))
        AnyClientsWriteBlocked = FALSE;
    BITCLEAR(OutputPending, connection);
    xfree(oc);
}

/*****************
 * CheckConections
 *    Some connection has died, go find which one and shut it down 
 *    The file descriptor has been closed, but is still in AllClients.
 *    If would truly be wonderful if select() would put the bogus
 *    file descriptors in the exception mask, but nooooo.  So we have
 *    to check each and every socket individually.
 *****************/

void
CheckConnections()
{
    long mask;
    long tmask[mskcnt];
    int curclient, curoff;
    int i;
    struct timeval notime;
    int r;

    notime.tv_sec = 0;
    notime.tv_usec = 0;

    for (i = 0; i < mskcnt; i++) {
        mask = AllClients[i];
        while (mask) {
            curoff = ffs(mask) - 1;
            curclient = curoff + (i << 5);
            CLEARBITS(tmask);
            BITSET(tmask, curclient);
#ifdef hpux
            r = select(curclient + 1, (int *) tmask, (int *) NULL,
                       (int *) NULL, &notime);
#else
            r = select(curclient + 1, (fd_set *) tmask, (fd_set *) NULL,
                       (fd_set *) NULL, &notime);
#endif
            if (r < 0 && errno != EINTR)
                CloseDownClient(clients[ConnectionTranslation[curclient]]);
            mask &= ~(1 << curoff);
        }
    }
}

/*****************
 * CloseDownConnection
 *    Delete client from AllClients and free resources 
 *****************/

void
CloseDownConnection(client)
ClientPtr client;
{
    OsCommPtr oc = (OsCommPtr) client->osPrivate;

    if (oc->output && oc->output->count)
        FlushClient(client, oc, (char *) NULL, 0);
    ConnectionTranslation[oc->fd] = 0;
    CloseDownFileDescriptor(oc);
    client->osPrivate = (pointer) NULL;
    if (auditTrailLevel > 1)
        AuditF("client %d disconnected\n", client->index);
}


AddEnabledDevice(fd)
int fd;
{
    BITSET(EnabledDevices, fd);
    BITSET(AllSockets, fd);
}


RemoveEnabledDevice(fd)
int fd;
{
    BITCLEAR(EnabledDevices, fd);
    BITCLEAR(AllSockets, fd);
}

/*****************
 * OnlyListenToOneClient:
 *    Only accept requests from  one client.  Continue to handle new
 *    connections, but don't take any protocol requests from the new
 *    ones.  Note that if GrabInProgress is set, EstablishNewConnections
 *    needs to put new clients into SavedAllSockets and SavedAllClients.
 *    Note also that there is no timeout for this in the protocol.
 *    This routine is "undone" by ListenToAllClients()
 *****************/

OnlyListenToOneClient(client)
ClientPtr client;
{
    OsCommPtr oc = (OsCommPtr) client->osPrivate;
    int connection = oc->fd;

    if (!GrabInProgress) {
        COPYBITS(ClientsWithInput, SavedClientsWithInput);
        MASKANDSETBITS(ClientsWithInput,
                       ClientsWithInput, GrabImperviousClients);
        if (GETBIT(SavedClientsWithInput, connection)) {
            BITCLEAR(SavedClientsWithInput, connection);
            BITSET(ClientsWithInput, connection);
        }
        UNSETBITS(SavedClientsWithInput, GrabImperviousClients);
        COPYBITS(AllSockets, SavedAllSockets);
        COPYBITS(AllClients, SavedAllClients);
        UNSETBITS(AllSockets, AllClients);
        MASKANDSETBITS(AllClients, AllClients, GrabImperviousClients);
        BITSET(AllClients, connection);
        ORBITS(AllSockets, AllSockets, AllClients);
        GrabInProgress = client->index;
    }
}

/****************
 * ListenToAllClients:
 *    Undoes OnlyListentToOneClient()
 ****************/

ListenToAllClients()
{
    if (GrabInProgress) {
        ORBITS(AllSockets, AllSockets, SavedAllSockets);
        ORBITS(AllClients, AllClients, SavedAllClients);
        ORBITS(ClientsWithInput, ClientsWithInput, SavedClientsWithInput);
        GrabInProgress = 0;
    }
}

/* make client impervious to grabs; assume only executing client calls this */

MakeClientGrabImpervious(client)
ClientPtr client;
{
    OsCommPtr oc = (OsCommPtr) client->osPrivate;
    int connection = oc->fd;

    BITSET(GrabImperviousClients, connection);
}

/* make client pervious to grabs; assume only executing client calls this */

MakeClientGrabPervious(client)
ClientPtr client;
{
    OsCommPtr oc = (OsCommPtr) client->osPrivate;
    int connection = oc->fd;

    BITCLEAR(GrabImperviousClients, connection);
    if (GrabInProgress && (GrabInProgress != client->index)) {
        if (GETBIT(ClientsWithInput, connection)) {
            BITSET(SavedClientsWithInput, connection);
            BITCLEAR(ClientsWithInput, connection);
        }
        BITCLEAR(AllSockets, connection);
        BITCLEAR(AllClients, connection);
        isItTimeToYield = TRUE;
    }
}

#else /* _MINIX */

char *
ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string)
ClientPtr client;
char *auth_proto, *auth_string;
unsigned short proto_n, string_n;
{
    OsCommPtr priv;
    AuID auth_id;
    int len;
    int r;
    struct sockaddr addr;
    nwio_tcpconf_t tcpconf;

    auth_id = CheckAuthorization(proto_n, auth_proto,
                                 string_n, auth_string);

    priv = (OsCommPtr) client->osPrivate;

    /* Assume we only have tcp connections. */
    r = ioctl(priv->fd, NWIOGTCPCONF, &tcpconf);
    if (r == -1) {
        Error("Unable to get remote address from tcp fd");
        return;
    }
    addr.sa_u.sa_in.sin_family = AF_INET;
    addr.sa_u.sa_in.sin_addr = tcpconf.nwtc_remaddr;
    addr.sa_u.sa_in.sin_port = tcpconf.nwtc_remport;
    len = sizeof(addr);

    if (auth_id == (AuID) ~ 0L && !InvalidHost(&addr, len)) {
        ErrorF("(warning) Authorization succeeded\n");
        auth_id = (AuID) 0;
    }

    if (auth_id == (AuID) ~ 0L)
        return "Client is not authorized to connect to Server";

    priv->auth_id = auth_id;
    priv->conn_time = 0;

#ifdef XDMCP
    /* indicate to Xdmcp protocol that we've opened new client */
    XdmcpOpenDisplay(priv->fd);
#endif /* XDMCP */

    return ((char *) NULL);
}

void CheckListeners();

Bool
EstablishNewConnections(clientUnused, closure)
ClientPtr clientUnused;
pointer closure;
{
    struct NewConnection *newConnP;
    int newconn;       /* fd of new client */
    long connect_time;
    ClientPtr client;
    OsCommPtr oc;
    int i;

    newConnP = (struct NewConnection *) closure;

    newconn = -1;

    /* Let's take some transport protocol specific actions */
    if (newConnP == &NewTcpConnection) {
        if (TcpListenFd < 0 || TcpListenFd > lastfdesc)
            FatalError("strange value in TcpListenFd\n");
        if (!ASIO_FD_ISSET(TcpListenFd, ASIO_IOCTL, &ListenFdSet) ||
            !ASIO_FD_ISSET(TcpListenFd, ASIO_IOCTL, &InprogressFdSet))
            FatalError("TcpListenFd not in progress\n");
        ASIO_FD_CLR(TcpListenFd, ASIO_IOCTL, &ListenFdSet);
        ASIO_FD_CLR(TcpListenFd, ASIO_IOCTL, &InprogressFdSet);
        newconn = TcpListenFd;
        TcpListenFd = -1;
    }

    if (newconn == -1)
        FatalError
                ("Unable to locate transport protocol for NewConnection\n");

    connect_time = GetTimeInMillis();
    /* kill off stragglers */
    for (i = 1; i < currentMaxClients; i++) {
        if (client = clients[i]) {
            oc = (OsCommPtr) (client->osPrivate);
            if (oc && (oc->conn_time != 0) &&
                (connect_time - oc->conn_time) >= TimeOutValue)
                CloseDownClient(client);
        }
    }

    /* Let's check if we can start some listeners that stopped */
    CheckListeners();

    oc = (OsCommPtr) xalloc(sizeof(OsCommRec));
    if (!oc) {
        ErrorConnMax(newconn);
        close(newconn);
        return TRUE;
    }
    /* Make sure that the client get called the first time */
    ASIO_FD_SET(newconn, ASIO_READ, &CompletedFdSet);
    AnyClientsWithInput = TRUE;

    oc->fd = newconn;
    oc->input = (ConnectionInputPtr) NULL;
    oc->inputFake = (ConnectionInputPtr) NULL;
    oc->output = (ConnectionOutputPtr) NULL;
    oc->outputNext = (ConnectionOutputPtr) NULL;
    oc->conn_time = connect_time;
    if ((newconn < lastfdesc) &&
        (client = NextAvailableClient((pointer) oc))) {
        ConnectionTranslation[newconn] = client->index;
    } else {
        ErrorConnMax(newconn);
        CloseDownFileDescriptor(oc);
    }
    return TRUE;
}

static void
CloseDownFileDescriptor(OsCommPtr oc)
{
    int connection = oc->fd;
    int i;

    close(connection);
    FreeOsBuffers(oc);

    for (i = 0; i < ASIO_NR; i++) {
        ASIO_FD_CLR(connection, i, &InprogressFdSet);
        ASIO_FD_CLR(connection, i, &CompletedFdSet);
        ASIO_FD_CLR(connection, i, &ClientFdSet);
        ASIO_FD_CLR(connection, i, &IgnoreFdSet);
        ASIO_FD_CLR(connection, i, &GrabFdSet);
    }
    xfree(oc);
}

CloseDownConnection(client)
ClientPtr client;
{
    OsCommPtr oc = (OsCommPtr) client->osPrivate;

    if (oc->output && oc->output->count)
        FlushClient(client, oc, (char *) NULL, 0);
    ConnectionTranslation[oc->fd] = 0;
#ifdef XDMCP
    XdmcpCloseDisplay(oc->fd);
#endif
    CloseDownFileDescriptor(oc);
    client->osPrivate = (pointer) NULL;
}

AddEnabledDevice(fd)
int fd;
{
    ASIO_FD_SET(fd, ASIO_READ, &InprogressFdSet);
}

RemoveEnabledDevice(fd)
int fd;
{
    ASIO_FD_CLR(fd, ASIO_READ, &InprogressFdSet);
}

OnlyListenToOneClient(client)
ClientPtr client;
{
    OsCommPtr oc = (OsCommPtr) client->osPrivate;
    int connection = oc->fd;

    if (!GrabInProgress) {
        ASIO_FD_ZERO(&GrabFdSet);
        ASIO_FD_SET(connection, ASIO_READ, &GrabFdSet);
        GrabInProgress = TRUE;
    }
}

ListenToAllClients()
{
    if (GrabInProgress) {
        GrabInProgress = 0;
        AnyClientsWithInput = TRUE;
    }
}

void
EnqueueNewConnection(fd, operation, result, error)
int fd;
int operation;
int result;
int error;
{
    /* Let's see which transport protocol got a new connection */
    if (!ASIO_FD_ISSET(fd, operation, &ListenFdSet))
        FatalError("result not in ListenFdSet\n");

    if (fd == TcpListenFd) {
        /* New tcp connection */
        NewTcpConnection.nc_result = result;
        NewTcpConnection.nc_errno = error;

        /* Let EstablishNewConnections deal with this
         * situation
         */
        QueueWorkProc(EstablishNewConnections, NULL,
                      (pointer) & NewTcpConnection);
        return;
    }

    FatalError("Unable to find transport protocol for new connection\n");
}

void
CheckListeners()
{
    /* Check if all devices have listeners hanging around */
#ifdef TCPCONN
    if (TcpListenFd == -1) {
        TcpListenFd = MNX_open_tcp_socket(NULL);
        if (TcpListenFd != -1) {
            if (TcpListenFd < 0 || TcpListenFd > lastfdesc)
                FatalError("invalid tcp fd: %d\n", TcpListenFd);
            ASIO_FD_SET(TcpListenFd, ASIO_IOCTL, &ListenFdSet);
            ASIO_FD_SET(TcpListenFd, ASIO_IOCTL, &InprogressFdSet);
        }
    }
#endif /* TCPCONN */
}
#endif /* _MINIX */

#else /* AMOEBA */

#include <amoeba.h>
#include <cmdreg.h>
#include <stdcom.h>
#include <stderr.h>
#include <ampolicy.h>
#include <server/ip/hton.h>
#include <server/ip/types.h>
#include <server/ip/tcpip.h>
#include <server/ip/tcp_io.h>
#include <server/ip/gen/in.h>
#include <server/ip/gen/tcp.h>
#include <server/ip/gen/tcp_io.h>

/*
 * Size of reply buffer 
 */
#define REPLY_BUFSIZE   30000

#ifdef XDEBUG
Bool amDebug;                   /* amoeba debug toggle */
#define dbprintf(list)  if (amDebug) { ErrorF list; }
#else
#define dbprintf(list)          /* nothing */
#endif /* XDEBUG */

capability Au;                  /* AudioServer capability */
char *AuServerHostName;         /* audio server host name */
char *AuTcpServerName;          /* TCP/IP server name */
long MaxClients = MAXTASKS;
ClientPtr newClient = NULL;     /* new connections */
ClientPtr Clients[MAXTASKS];    /* clients with input */
int maxClient;                  /* Highest numbered client */
int totalClients;               /* all connected applications */
ClientPtr grabClient = NULL;    /* for grabs */

mutex NewConnsLock;             /* prevent concurrent updates */
int nNewConns;                  /* # of new clients */
OsCommPtr NewConns[MAXTASKS];   /* new client connections */

static void AmoebaConnectorThread();
static void AmoebaTCPConnectorThread();

void
CreateWellKnownSockets(void)
{
    char host[100];
    char *getenv();
    void DeviceReader();
    errstat err;
    capability pubAu;
    static int threadsStarted = FALSE;

    /*
     * Each time the server is reset this routine is called to
     * setup the new well known sockets. For Amoeba we'll just
     * keep using the old threads that are already running.
     */
    if (!threadsStarted) {
        threadsStarted = TRUE;
        /*
         * Create a new capability for this audio server
         */
        if (AuServerHostName == NULL)
            AuServerHostName = getenv("AUDIOHOST");
        if (AuServerHostName == NULL)
            FatalError
                    ("AUDIOHOST not set, or server host name not given\n");
        snprintf(host, sizeof host, "%s/%s:%s", DEF_AUSVRDIR, AuServerHostName,
                0 /* port */ );

        uniqport(&Au.cap_port);
        priv2pub(&Au.cap_port, &pubAu.cap_port);
        (void) name_delete(host);
        if ((err = name_append(host, &pubAu)) != 0) {
            (void) ErrorF("Cannot create capability %s: %s\n",
                          host, err_why(err));
            exit(1);
        }

        /*
         * Initialize new connections lock
         */
        mu_init(&NewConnsLock);

        /*
         * This critical region prevents the subthread from proceeding until
         * main has finished initializing. The matching sema_down() is in
         * WaitFor.c.
         */
        sema_init(&init_sema, 0);

        /*
         * Also, initialize main thread locking
         */
        InitMainThread();

        /*
         * Initialize and start IOP reader thread
         */
        InitializeIOPServerReader();

        /*
         * Start native Amoeba service threads
         */
        if (thread_newthread(AmoebaConnectorThread, CONNECTOR_STACK, 0, 0)
            <= 0)
            FatalError("Cannot start Amoeba connector thread\n");
        if (thread_newthread(AmoebaConnectorThread, CONNECTOR_STACK, 0, 0)
            <= 0)
            FatalError("Cannot start Amoeba connector thread\n");

        /*
         * Start TCP/IP service threads
         */
        if (AuTcpServerName) {
            if (thread_newthread(AmoebaTCPConnectorThread,
                                 CONNECTOR_STACK, 0, 0) <= 0)
                FatalError("Cannot start TCP connector thread\n");
            if (thread_newthread(AmoebaTCPConnectorThread,
                                 CONNECTOR_STACK, 0, 0) <= 0)
                FatalError("Cannot start TCP connector thread\n");
        }
    }

    ResetHosts(display);

#ifdef XDMCP
    XdmcpInit();
#endif
}

void
ResetWellKnownSockets()
{
    ResetAuthorization();
    ResetHosts(display);

    /*
     * restart XDMCP
     */
#ifdef XDMCP
    XdmcpReset();
#endif
}

char *
ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string)
ClientPtr client;
char *auth_proto, *auth_string;
unsigned short proto_n, string_n;
{
    OsCommPtr priv;
    AuID auth_id;

    auth_id = CheckAuthorization(proto_n, auth_proto,
                                 string_n, auth_string);

    priv = (OsCommPtr) client->osPrivate;
    /*
     * Access control only works for audio connections over a TCP/IP stream.
     * The Amoeba philosophy is, when you have the capability you are
     * allowed to talk with the server.
     */
    if (auth_id == (AuID) ~ 0L) {
        nwio_tcpconf_t tcpconf;

        if (priv->family == FamilyInternet &&
            tcp_ioc_getconf(&priv->conn.tcp.cap, &tcpconf) == STD_OK &&
            !InvalidHost(&tcpconf.nwtc_remaddr, sizeof(ipaddr_t)))
            auth_id = (AuID) 0;
        if (priv->family == FamilyAmoeba)
            auth_id = (AuID) 0;
    }

    if (auth_id == (AuID) ~ 0L)
        return "Client is not authorized to connect to Server";

    priv->auth_id = auth_id;
    priv->conn_time = 0;

#ifdef XDMCP
    /* indicate to Xdmcp protocol that we've opened new client */
    XdmcpOpenDisplay(priv->fd);
#endif /* XDMCP */
    /* At this point, if the client is authorized to change the access control
     * list, we should getpeername() information, and add the client to
     * the selfhosts list.  It's not really the host machine, but the
     * true purpose of the selfhosts list is to see who may change the
     * access control list.
     */
    return ((char *) NULL);
}

 /*ARGSUSED*/ Bool
EstablishNewConnections(clientUnused, closure)
ClientPtr clientUnused;
pointer closure;
{
    ClientPtr newClient;
    OsCommPtr oc;
    int i;
    struct vc *vc;
    int index;

    mu_lock(&NewConnsLock);
    for (index = 0; index < nNewConns; index++) {
        oc = NewConns[index];

        /*
         * Find a new slot
         */
        if (totalClients >= MAXTASKS) {
            ErrorF("Too many audio-clients are being served already\n");
            am_close(oc, VC_BOTH | VC_ASYNC);
            xfree((char *) oc);
            continue;
        }
        totalClients++;
        for (i = 0; i < maxClient + 1; i++)
            if (Clients[i] == 0)
                break;
        if (i == maxClient)
            maxClient++;

        /*
         * Fill in client's connection number
         */
        oc->number = i;

        /*
         * Now stuff the new client in the array where
         * WaitForSomething will find it and hand it up.
         */
        newClient = NextAvailableClient((pointer) oc);
        Clients[i] = newClient;
    }
    nNewConns = 0;
    mu_unlock(&NewConnsLock);
    return TRUE;
}

#define NOROOM "Maximum number of clients reached"

OnlyListenToOneClient(client)
ClientPtr client;
{
    if (grabClient != NULL && grabClient != client) {
        ErrorF("Uncancelled OnlyListenToOneClient()?\n");
        grabClient = NULL;
    } else
        grabClient = client;
}

CloseDownConnection(client)
ClientPtr client;
{
    OsCommPtr oc;

    dbprintf(("Connection closed\n"));
    oc = (OsCommPtr) client->osPrivate;
    Clients[oc->number] = NULL;
    if (oc->number == maxClient)
        maxClient--;
    am_close(oc, VC_BOTH | VC_ASYNC);
    if (oc->buffer)
        xfree(oc->buffer);
    xfree(oc);
    client->osPrivate = (pointer) NULL;
}

ListenToAllClients()
{
    grabClient = NULL;
}

/* These two are dummies -- and are never called at run-time */
AddEnabledDevice(fd)
int fd;
{
    return;
}

RemoveEnabledDevice(fd)
int fd;
{
    return;
}

/*
 * Wakeup main thread if necessary
 */
static void
UnblockMain(reguster OsCommPtr oc)
{
    if ((oc->status & IGNORE) == 0) {
        WakeUpMainThread();
    }
}

static char *
OsCommFamily(int family)
{
    switch (family) {
    case FamilyAmoeba:
        return "AMOEBA";
    case FamilyInternet:
        return "TCP/IP";
    }
    return "UNKNOWN";
}

static char *
OsCommStatus(int status)
{
    static char buf[100];

    buf[0] = '\0';
    if (status == 0)
        snprintf(buf, sizeof buf, "NONE");
    if (status & CONN_KILLED)
        strncat(buf, " KILLED", sizeof buf - strlen(buf) - 1);
    if (status & REQ_PUSHBACK)
        strncat(buf, " PUSHBACK", sizeof buf - strlen(buf) - 1);
    if (status & IGNORE)
        strncat(buf, " IGNORE", sizeof buf - strlen(buf) - 1);
    return buf;
}

/*
 * Return status information about the open connections
 */
errstat
ConnectionStatus(hdr, buf, size)
header *hdr;
char *buf;
int size;
{
    OsCommPtr oc;
    int i;
    char *begin, *end;
    char *bprintf();

    begin = buf;
    end = buf + size;

    /* all active clients */
    if (maxClient > 0) {
        begin = bprintf(begin, end, "Active clients:\n");
        for (i = 0; i < maxClient; i++) {
            if (Clients[i] && (oc = (OsCommPtr) Clients[i]->osPrivate)) {
                begin = bprintf(begin, end, "%d: Family %s, Status %s\n",
                                i, OsCommFamily(oc->family),
                                OsCommStatus(oc->status));
            }
        }
    }

    /* all new (awaiting) clients */
    mu_lock(&NewConnsLock);
    if (nNewConns > 0) {
        begin = bprintf(begin, end, "New clients:\n");
        for (i = 0; i < nNewConns; i++) {
            oc = NewConns[i];
            begin = bprintf(begin, end, "%d: Family %s, Status %s\n",
                            i, OsCommFamily(oc->family),
                            OsCommStatus(oc->status));
        }
    }
    mu_unlock(&NewConnsLock);

    if (begin == NULL) {
        hdr->h_size = 0;
        return STD_SYSERR;
    } else {
        hdr->h_size = begin - buf;
        return STD_OK;
    }

}

/*
 * Establishing a new connection is done in two phases. This thread does the
 * first part. It filters out bad connect requests. A new rendevous port is
 * sent to the client and the main loop is informed if there is a legal
 * request. The sleep synchronizes with the main loop so that the paperwork
 * is finished for the current connect request before the thread is ready to
 * accept another connect.
 */
static void
AmoebaConnectorThread()
{
    header req, rep;
    port client_ports[2];
    port server_ports[2];
    short s;
    OsCommPtr oc;
    char *repb;
    extern CreateNewClient();

    WaitForInitialization();
    dbprintf(("AmoebaConnectorThread() running ...\n"));
    if ((repb = (char *) malloc(REPLY_BUFSIZE)) == NULL)
        FatalError("Amoeba connector thread: malloc failed");
    for (;;) {
        do {
            req.h_port = Au.cap_port;
            s = getreq(&req, NILBUF, 0);
        } while (ERR_CONVERT(s) == RPC_ABORTED);
        if (ERR_STATUS(s))
            FatalError("Amoeba connector thread: getreq failed");
        /* TODO: check privilege fields here */

        dbprintf(("AmoebaConnectorThread() accepting a request\n"));

        switch (req.h_command) {

        case STD_INFO:
            rep.h_status = STD_OK;
            snprintf(repb, REPLY_BUFSIZE, "audio server on %s",
                     AuServerHostName);
            rep.h_size = strlen(repb);
            putrep(&rep, repb, rep.h_size);
            break;

        case STD_STATUS:
            rep.h_status = ConnectionStatus(&rep, repb, REPLY_BUFSIZE);
            putrep(&rep, repb, rep.h_size);
            break;

        case AX_SHUTDOWN:
            GiveUp();
            rep.h_status = STD_OK;
            putrep(&rep, NILBUF, 0);
            break;

        case AX_REINIT:
            AutoResetServer();
            rep.h_status = STD_OK;
            putrep(&rep, NILBUF, 0);
            break;

        case AX_CONNECT:
            /*
             * All is well. Open a virtual circuit and read the prefix
             */
            if (totalClients >= MAXTASKS) {
                ErrorF("Connection refused: %s\n", NOROOM);
                goto NoSpace;
            }

            /*
             * Fill operating system's communication structure
             */
            oc = (OsCommPtr) xalloc(sizeof(OsCommRec));
            if (oc == (OsCommPtr) NULL) {
                ErrorF("Connection refused: No memory for connection data\n");
                goto NoSpace;
            }
            oc->number = -1;
            oc->buffer = NULL;
            oc->size = 0;
            oc->status = 0;
            oc->family = FamilyAmoeba;
            oc->conn_time = 0L;

            /*
             * Now some priv2pub magic vc_create must be called with a put
             * port as first parameter and a get port as 2nd parameter.
             * Since we are a server we send the opposite to the client; ie.
             * a get port and a put port respectively.
             */
            uniqport(&client_ports[0]);
            uniqport(&server_ports[1]);
            priv2pub(&client_ports[0], &server_ports[0]);
            priv2pub(&server_ports[1], &client_ports[1]);
            oc->conn.vc = vc_create(&server_ports[0], &server_ports[1],
                                    MAXBUFSIZE, MAXBUFSIZE);
            if (oc->conn.vc == (struct vc *) NULL) {
              NoSpace:
                rep.h_status = AX_FULLHOUSE;
                putrep(&rep, NILBUF, 0);
            } else {
                rep.h_status = AX_OK;
                putrep(&rep, (bufptr) client_ports, 2 * sizeof(port));
                dbprintf(("Amoeba connection accepted\n"));

                /*
                 * Store for the main loop to finish creation
                 */
                vc_warn(oc->conn.vc, VC_IN, UnblockMain, (int) oc);
                mu_lock(&NewConnsLock);
                NewConns[nNewConns++] = oc;
                mu_unlock(&NewConnsLock);
                WakeUpMainThread();
            }
            break;

        default:
            rep.h_status = STD_COMBAD;
            putrep(&rep, NILBUF, 0);
            break;
        }
    }
}

static void
TcpIpReaderSignalCatcher(signum sig, thread_ustate * us, char *extra)
{
    OsCommPtr oc = (OsCommPtr) extra;

    dbprintf(("TcpIpReaderSignalCatcher(%d), number %d\n", sig,
              oc->number));
    if (oc->conn.tcp.signal != sig) {
        ErrorF("TCP/IP Reader: Connection %s got unexpected signal %d\n",
               oc->number, sig);
    }
    oc->conn.tcp.signal = -1;
    thread_exit();
}

/*
 * TCP/IP reader thread
 */
static void
TcpIpReaderThread(void *argptr, argsize argsize)
{
    OsCommPtr oc;

    if (argsize != sizeof(OsCommPtr))
        FatalError
                ("Internal error: TcpIpReaderThread incorrectly called\n");
    oc = *((OsCommPtr *) argptr);
    (void) sig_catch(oc->conn.tcp.signal, TcpIpReaderSignalCatcher,
                     (char *) oc);
    while (TRUE) {
        char buffer[MAXBUFSIZE];
        bufsize size;

        size = tcpip_read(&oc->conn.tcp.cap, buffer, sizeof(buffer));
        dbprintf(("TcpIpReaderThread() read %d bytes\n", size));
        if (ERR_STATUS(size)) {
            ErrorF("TCP/IP read failed (%s)\n",
                   tcpip_why(ERR_CONVERT(size)));
            oc->status |= CONN_KILLED;
            oc->conn.tcp.signal = -1;
            thread_exit();
        }
        if (size == 0 || cb_puts(oc->conn.tcp.cb, buffer, size)) {
            if (size != 0)
                ErrorF("TCP/IP short write to circular buffer\n");
            oc->status |= CONN_KILLED;
            oc->conn.tcp.signal = -1;
            thread_exit();
        }
        UnblockMain(oc);
    }
}

/*
 * To prevent the audio-server from generating lots of error messages,
 * in case the server is gone or when its full.
 */
#define LOOP_OPEN       1
#define LOOP_SETCONF    2
#define LOOP_LISTEN     4

/*
 * The TCP/IP connector thread listens to a well known port (6000 +
 * display number) for connection request. When such a request arrives
 * it allocates a communication structure and a reader thread. This
 * thread prevents the main loop from blocking when there's no data.
 */
static void
AmoebaTCPConnectorThread(void)
{
    capability svrcap, chancap;
    nwio_tcpconf_t tcpconf;
    nwio_tcpcl_t tcpconnopt;
    char name[BUFSIZ];
    OsCommPtr oc, *param;
    errstat err;
    int result;
    int looping = 0;

    strncpy(name, AuTcpServerName, BUFSIZ); name[BUFSIZ-1] = '\0';
    if ((err = name_lookup(name, &svrcap)) != STD_OK) {
        snprintf(name, BUFSIZ, "%s/%s", TCP_SVR_NAME, AuTcpServerName);
        if ((err = name_lookup(name, &svrcap)) != STD_OK)
            FatalError("Lookup %s failed: %s\n", AuTcpServerName,
                       err_why(err));
    }

    WaitForInitialization();
    dbprintf(("AmoebaTCPConnectorThread() running ...\n"));

    for (;;) {
        /*
         * Listen to TCP/IP port AUDIO_TCP_PORT + offset for connections.
         * Some interesting actions have to be taken to keep this connection
         * alive and kicking :-)
         */
        if ((err = tcpip_open(&svrcap, &chancap)) != STD_OK) {
            /* the server probably disappeared, just wait for it to return */
            if (looping & LOOP_OPEN) {
                ErrorF("TCP/IP open failed: %s\n", tcpip_why(err));
                looping |= LOOP_OPEN;
            }
            sleep(60);
            (void) name_lookup(name, &svrcap);
            continue;
        }
        looping &= ~LOOP_OPEN;

        tcpconf.nwtc_locport = htons(AUDIO_TCP_PORT + atoi(offset));
        tcpconf.nwtc_flags = NWTC_EXCL | NWTC_LP_SET | NWTC_UNSET_RA |
                NWTC_UNSET_RP;
        if ((err = tcp_ioc_setconf(&chancap, &tcpconf)) != STD_OK) {
            /* couldn't configure, probably server space problem */
            if (looping & LOOP_SETCONF) {
                ErrorF("TCP/IP setconf failed: %s\n", tcpip_why(err));
                looping |= LOOP_SETCONF;
            }
            std_destroy(&chancap);
            sleep(60);
            continue;
        }
        looping &= ~LOOP_SETCONF;

        tcpconnopt.nwtcl_flags = 0;
        if ((err = tcp_ioc_listen(&chancap, &tcpconnopt)) != STD_OK) {
            /* couldn't listen, definitely a server memory problem */
            if (looping & LOOP_LISTEN) {
                ErrorF("TCP/IP listen failed: %s\n", tcpip_why(err));
                looping |= LOOP_LISTEN;
            }
            std_destroy(&chancap);
            sleep(60);
            continue;
        }
        looping &= ~LOOP_LISTEN;

        if ((err = tcpip_keepalive_cap(&chancap)) != STD_OK) {
            ErrorF("TCP/IP keep alive failed: %s\n", tcpip_why(err));
            std_destroy(&chancap);
            continue;
        }

        /*
         * Fill operating system's communication structure
         */
        oc = (OsCommPtr) xalloc(sizeof(OsCommRec));
        if (oc == (OsCommPtr) NULL) {
            ErrorF("Connection refused: No memory for connection data\n");
            goto NoSpace;
        }
        oc->number = -1;
        oc->buffer = NULL;
        oc->size = 0;
        oc->status = 0;
        oc->family = FamilyInternet;
        oc->conn_time = 0L;
        oc->conn.tcp.cap = chancap;
        if ((oc->conn.tcp.cb = cb_alloc(MAXBUFSIZE)) == NULL) {
            ErrorF("Connection refused: No memory for circular buffer\n");
            xfree((char *) oc);
            goto NoSpace;
        }

        /*
         * Start TCP/IP reader thread
         */
        oc->conn.tcp.signal = sig_uniq();
        param = (OsCommPtr *) malloc(sizeof(OsCommPtr));
        *param = oc;            /* stupid convention */
        result = thread_newthread(TcpIpReaderThread,
                                  MAXBUFSIZE + CONNECTOR_STACK,
                                  (char *) param, sizeof(OsCommPtr));
        if (result == 0) {
            ErrorF("Cannot start reader thread\n");
            cb_close(oc->conn.tcp.cb);
            cb_free(oc->conn.tcp.cb);
            xfree((char *) oc);
          NoSpace:
            std_destroy(&chancap);
            continue;
        }

        /*
         * Store for the main loop to finish creation
         */
        mu_lock(&NewConnsLock);
        NewConns[nNewConns++] = oc;
        mu_unlock(&NewConnsLock);
        WakeUpMainThread();
    }
}
#endif /* AMOEBA */

#ifdef AIXV3

static long pendingActiveClients[mskcnt];
static BOOL reallyGrabbed;

/****************
* DontListenToAnybody:
*   Don't listen to requests from any clients. Continue to handle new
*   connections, but don't take any protocol requests from anybody.
*   We have to take care if there is already a grab in progress, though.
*   Undone by PayAttentionToClientsAgain. We also have to be careful
*   not to accept any more input from the currently dispatched client.
*   we do this be telling dispatch it is time to yield.

*   We call this when the server loses access to the glass
*   (user hot-keys away).  This looks like a grab by the 
*   server itself, but gets a little tricky if there is already
*   a grab in progress.
******************/

void
DontListenToAnybody()
{
    if (!GrabInProgress) {
        COPYBITS(ClientsWithInput, SavedClientsWithInput);
        COPYBITS(AllSockets, SavedAllSockets);
        COPYBITS(AllClients, SavedAllClients);
        GrabInProgress = TRUE;
        reallyGrabbed = FALSE;
    } else {
        COPYBITS(AllClients, pendingActiveClients);
        reallyGrabbed = TRUE;
    }
    CLEARBITS(ClientsWithInput);
    UNSETBITS(AllSockets, AllClients);
    CLEARBITS(AllClients);
    isItTimeToYield = TRUE;
}

void
PayAttentionToClientsAgain()
{
    if (reallyGrabbed) {
        ORBITS(AllSockets, AllSockets, pendingActiveClients);
        ORBITS(AllClients, AllClients, pendingActiveClients);
    } else {
        ListenToAllClients();
    }
    reallyGrabbed = FALSE;
}

#endif


#if defined(SYSV) && defined(SYSV386) && !defined(STREAMSCONN)
#ifdef SCO

/*
 * SCO does not have writev so we emulate
 */

#include <sys/uio.h>

int
_OSWriteV(fd, iov, iovcnt)
int fd;
struct iovec *iov;
int iovcnt;
{
    int i, len, total;
    char *base;

    errno = 0;
    for (i = 0, total = 0; i < iovcnt; i++, iov++) {
        len = iov->iov_len;
        base = iov->iov_base;
        while (len > 0) {
            int nbytes;

            nbytes = write(fd, base, len);
            if (nbytes < 0 && total == 0)
                return (-1);
            if (nbytes <= 0)
                return (total);
            errno = 0;
            len -= nbytes;
            total += nbytes;
            base += nbytes;
        }
    }
    return (total);
}

#endif /* SCO */
#endif /* SYSV && SYSV386 && !STREAMSCONN */