summaryrefslogtreecommitdiff
path: root/xc/lib/xtrans/Xtransam.c
blob: 7f798bb05d33e733c5a2a20ac8a8b590992cc8eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
/* $Xorg: Xtransam.c,v 1.3 2000/08/17 19:46:45 cpqbld Exp $ */
/*

Copyright 1994, 1998  The Open Group

All Rights Reserved.

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

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

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

*/
/* $XFree86: xc/lib/xtrans/Xtransam.c,v 3.3 2001/01/17 19:43:46 dawes Exp $ */

/* Copyright 1994 Vrije Universiteit Amsterdam, Netherlands
 *
 * All Rights Reserved
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted, provided
 * that the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name Vrije Universiteit not be used
 * in advertising or publicity pertaining to distribution of the software
 * without specific, written prior permission.  The Vrije Universiteit
 * makes no representations about the suitability of this software for
 * any purpose.  It is provided "as is" without express or implied warranty.
 *
 * THE VRIJE UNIVERSITEIT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
 * NO EVENT SHALL THE VRIJE UNIVERSITEIT 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.
 */

/*
 * This is the Amoeba implementation of the X Transport service layer
 */

#define event am_event_t
#define interval am_interval_t
#define port am_port_t
#include <amoeba.h>
#include <semaphore.h>
#include <cmdreg.h>
#include <stdcom.h>
#include <stderr.h>
#include <vc.h>
#include <circbuf.h>
#include <exception.h>
#include <module/signals.h>
#include <ampolicy.h>
#include <stdlib.h>
#include <stdio.h>
#include <exception.h>
#include <fault.h>
#include <signal.h>
#include <ctype.h>
#include <module/name.h>
#include <server/x11/Xamoeba.h>
#include <server/ip/hton.h>
#include <server/ip/types.h>
#include <server/ip/gen/in.h>
#include <server/ip/gen/tcp.h>
#include <server/ip/tcpip.h>
#include <server/ip/tcp_io.h>
#include <server/ip/gen/tcp_io.h>
#include <server/ip/gen/netdb.h>
#include <server/ip/gen/inet.h>
#undef event
#undef interval
#undef port

extern char *strdup();

/* a new family for Amoeba RPC connections */
#define AF_AMOEBA	33
#define FamilyAmoeba    33

#define	MAX_TCPIP_RETRY	4
#define	CIRCBUFSIZE	4096 /* was 1024 */

/*
 * Amoeba channel description:
 */
typedef struct _XAmChanDesc {
    int			state;		/* current state of connection */
    int			type;		/* type of connection */
    int			status;		/* status used by server */
    signum		signal;		/* signal to kill TCP/IP reader */
    semaphore		*sema;		/* select semaphore */
    struct vc		*virtcirc;	/* virtual circuit for Amoeba RPC */
    struct circbuf	*circbuf;	/* circular buffer for TCP/IP */
    capability		chancap;	/* TCP/IP channel capability */
    XtransConnInfo	conninfo;	/* back pointer to the connect info */
} XAmChanDesc;

/* Amoeba channel descriptor states */
#define	ACDS_FREE	0		/* unused */
#define	ACDS_USED	1		/* intermediate state */
#define	ACDS_CLOSED	2		/* just closed */

/* Amoeba channel types */
#define	ACDT_TCPIP	1		/* TCP/IP connection */
#define	ACDT_VIRTCIRC	2		/* Amoeba virtual circuit connection */


#ifdef XSERV_t
#include "dix.h" /* clients[] needed by AmFindReadyClients */
#define Error(list) ErrorF list
#define Fatal(list) FatalError list
#else
#define Error(list) printf list
#define Fatal(list) { printf list; exit(1); }
#endif

#define dbprintf(list) /* printf list */
#define doprintf(list) printf list /**/

/*
 * First: utility functions.
 */

#if defined(XSERV_t) || defined(FS_t)

static semaphore main_sema;

/* The X-server consists of one main thread, running the non re-entrant
 * X code, and a number of auxilary threads that take care of reading
 * the input streams, and input devices. The following set of routines
 * wake up the main thread when it has something to do.
 */
void
InitMainThread()
{
    sema_init(&main_sema, 0);
}

void
WakeUpMainThread()
{
    sema_up(&main_sema);
}

int
SleepMainThread(timeout)
am_interval_t timeout;
{
    dbprintf(("Sleeping main thread timeout %d\n", timeout));
    return (sema_trydown(&main_sema, timeout) == 0) ? 0 : -1;
}


static int init_waiters;
static semaphore init_sema;

void
AmInitWaitFor()
{
    init_waiters = 0;
    sema_init(&init_sema, 0);
}

/*
 * Force caller thread to wait until main has finished the initialization.
 */
void
WaitForInitialization()
{
    init_waiters++;
    dbprintf(("Waiting for initialization (%d)\n", init_waiters));
    sema_down(&init_sema);
}

void
WakeupInitWaiters()
{
    /* wakeup threads in initial sleep */
    if (init_waiters > 0) {
	dbprintf(("%d waiters wait for something ...\n", init_waiters));
	while (init_waiters-- > 0) {
	    sema_up(&init_sema);
	}
    }
}

#endif /* XSERV_t || FS_t */


#define	THREAD_STACK_SIZE (8*1024)

/*
 * Amoeba connection information is stored in, so called,
 * channel descriptors. Channel descriptors are identified
 * by their index in the table below.
 */
static XAmChanDesc XAmChanDescriptors[OPEN_MAX];
static void XAmCleanUpChanDesc(); /* forward */

/*
 * Cleanup connection descriptors on a signal
 */
static void
XAmSignalCleanUpChanDesc(sig)
    int sig;
{
    XAmCleanUpChanDesc();
    _exit(sig | 0x80);
}

/*
 * Cleanup connection descriptors
 */
static void
XAmCleanUpChanDesc()
{
    register int i;

    for (i = 0; i < OPEN_MAX; i++) {
	switch (XAmChanDescriptors[i].type) {
	case ACDT_TCPIP:
	    /* The Amoeba TCP/IP server is capability based, i.e.
	     * it uses capabilities to identify connections.  Since a
	     * capability is only destroyed when it has aged too much
	     * or is explicitly deleted, the connection it identifies
	     * will tend to exist for some while even if the client is
	     * already gone. To force connections to close this loop
	     * destroys all open TCP/IP connection. This loop us auto-
	     * matically executed when exit() is called.
	     */
	    std_destroy(&XAmChanDescriptors[i].chancap);
	    break;
	case ACDT_VIRTCIRC:
	    /* Close the virtual circuit asynchronously, or otherwise
	     * we may hang for a minute under some (?) conditions.
	     */
	    vc_close(XAmChanDescriptors[i].virtcirc, VC_BOTH | VC_ASYNC);
	    break;
	}
	XAmChanDescriptors[i].state = ACDS_FREE;
    }
}

/*
 * Allocate a channel descriptor
 */
static XAmChanDesc *
XAmAllocChanDesc()
{
    register int i;

#ifndef XSERV_t

    static int initialized = 0;

    /*
     * Since the TCP/IP server is capability based its connections exists
     * even if the owner process is long gone. To overcome this nuisance,
     * a sweep is made over the connection descriptors when exit() is
     * called or when an un-catched (by application program) signal is 
     * received.
     */
    if (!initialized) {
	initialized = 1;
	atexit(XAmCleanUpChanDesc);
	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
	    signal(SIGHUP, XAmSignalCleanUpChanDesc);
	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
	    signal(SIGQUIT, XAmSignalCleanUpChanDesc);
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
	    signal(SIGINT, XAmSignalCleanUpChanDesc);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
	    signal(SIGTERM, XAmSignalCleanUpChanDesc);
    }
#endif

    for (i = 0; i < OPEN_MAX; i++) {
	if (XAmChanDescriptors[i].state == ACDS_FREE) {
	    XAmChanDescriptors[i].state = ACDS_USED;
	    XAmChanDescriptors[i].conninfo = NULL;
	    return &XAmChanDescriptors[i];
	}
    }
    return NULL;
}

/*
 * Convert ``file descriptor'' to channel descriptor
 */
static XAmChanDesc *
XAmFdToChanDesc(fd)
    int fd;
{
    if (fd >= 0 && fd < OPEN_MAX) {
	return &XAmChanDescriptors[fd];
    } else {
	return NULL;
    }
}

/*
 * Convert channel descriptor to ``file descriptor''
 */
static int
XAmChanDescToFd(chandesc)
    XAmChanDesc *chandesc;
{
    return chandesc - XAmChanDescriptors;
}

/*
 * Free channel descriptor
 */
static void
XAmFreeChanDesc(chandesc)
    XAmChanDesc *chandesc;
{
    if (chandesc->sema) {
	xfree(chandesc->sema);
	chandesc->sema = NULL;
    }
    chandesc->state = ACDS_FREE;
}

static void XAmReaderThread();

static int
MakeAmConnection(phostname, idisplay, familyp, saddrlenp, saddrp)
    char *phostname;
    int idisplay;
    int *familyp;			/* RETURN */
    int *saddrlenp;			/* RETURN */
    char **saddrp;			/* RETURN */
{
    capability xservercap;
    char xserverpath[256];
    XAmChanDesc *chandesc;
    errstat err;

    /* Amoeba requires a server hostname */
    if (phostname == NULL || *phostname == '\0') {
	fprintf(stderr, "MakeAmConnection: Display name expected\n");
	return -1;
    }

    /* allocate channel descriptor */
    chandesc = XAmAllocChanDesc();
    if (chandesc == NULL) {
	fprintf(stderr, "MakeAmConnection: Out of channel capabilities\n");
	return -1;
    }

    /*
     * There are two possible way to make a connection on Amoeba. Either
     * through an Amoeba RPC or a TCP/IP connection. Depending on whether
     * the X server resides on Amoeba, Amoeba RPC's are used. Otherwise
     * it uses a TCP/IP connection.
     */
    (void)sprintf(xserverpath, "%s/%s:%d", DEF_XSVRDIR, phostname, idisplay);
    if ((err = name_lookup(xserverpath, &xservercap)) == STD_OK) {
	am_port_t vccaps[2];
	bufsize size;
	errstat err;
	header hdr;

	/* Amoeba virtual circuit connection */
	chandesc->type = ACDT_VIRTCIRC;

	/* get the two connection ports from the X-server */
	hdr.h_command = AX_CONNECT;
	hdr.h_port = xservercap.cap_port;
	hdr.h_priv = xservercap.cap_priv;
	size = trans(&hdr, NILBUF, 0, &hdr, (char *)vccaps, sizeof(vccaps));
	if (ERR_STATUS(size)) {
	    err = ERR_CONVERT(size);
	} else {
	    err = ERR_CONVERT(hdr.h_status);
	}
	if (err != STD_OK || size != sizeof(vccaps)) {
	    fprintf(stderr, "Xlib: connect to Amoeba X-server failed (%s)\n",
		    err_why(err));
	    XAmFreeChanDesc(chandesc);
	    return -1;
	}

	/* setup an Amoeba virtual circuit */
	chandesc->virtcirc =
	    vc_create(&vccaps[1], &vccaps[0], MAXBUFSIZE, MAXBUFSIZE);
	if (chandesc->virtcirc == (struct vc *)NULL) {
	    fprintf(stderr, "Xlib: Amoeba virtual circuit create failed\n");
	    XAmFreeChanDesc(chandesc);
	    return -1;
	}

	/* Special Amoeba family type. For Amoeba no additional access control
	 * mechanism exists;  when you have the server capability, you have
	 * the access.  Just use a fake address.
	 */
	*familyp = AF_AMOEBA;
	*saddrp = strdup("Amoeba");
	*saddrlenp = strlen(*saddrp);
    } else {
	char tcpname[256];
	capability tcpcap;
	ipaddr_t ipaddr;
	char *tcpsvr;
	nwio_tcpcl_t tcpcl;
	nwio_tcpconf_t tcpconf;
	XAmChanDesc **param;
	int result;

	/* Amoeba TCP/IP connection */
	chandesc->type = ACDT_TCPIP;

	/* lookup up TCP/IP server */
	if ((tcpsvr = getenv("TCP_SERVER")) == NULL) {
	    tcpsvr = TCP_SVR_NAME;
	}
	if ((err = name_lookup(tcpsvr, &tcpcap)) != STD_OK) {
	    fprintf(stderr, "Xlib: Cannot lookup %s (%s)\n",
		    tcpsvr, err_why(err));
	    std_destroy(&chandesc->chancap);
	    XAmFreeChanDesc(chandesc);
	    return -1;
	}

	/* establish TCP/IP connection */
	if ((err = tcpip_open(&tcpcap, &chandesc->chancap)) != STD_OK) {
	    fprintf(stderr, "Xlib: Cannot open TCP/IP server on %s (%s)\n",
		    tcpsvr, tcpip_why(err));
	    std_destroy(&chandesc->chancap);
	    XAmFreeChanDesc(chandesc);
	    return -1;
	}

	/* lookup TCP/IP hostname */
	if (isdigit(phostname[0])) {
	    ipaddr = inet_addr(phostname);
	} else {
	    struct hostent *hp = gethostbyname(phostname);
	    if (hp == NULL) {
		fprintf(stderr, "Xlib: %s unknown host\n", phostname);
		return -1;
	    }
	    memcpy(&ipaddr, hp->h_addr, hp->h_length);
	}

	/* set remote address/port on the TCP/IP connection */
	tcpconf.nwtc_flags = NWTC_SET_RA|NWTC_SET_RP|NWTC_LP_SEL;
	tcpconf.nwtc_remaddr = ipaddr;
	tcpconf.nwtc_remport = htons(6000+idisplay);
	if ((err = tcp_ioc_setconf(&chandesc->chancap, &tcpconf)) != STD_OK) {
	    fprintf(stderr, "Xlib: Cannot configure TCP/IP server (%s)\n",
		    tcpip_why(err));
	    std_destroy(&chandesc->chancap);
	    XAmFreeChanDesc(chandesc);
	    return -1;
	}

	/* make the actual TCP/IP connection */
	tcpcl.nwtcl_flags = 0;
	if ((err = tcp_ioc_connect(&chandesc->chancap, &tcpcl)) != STD_OK) {
	    fprintf(stderr, "Xlib: Cannot make TCP/IP connection (%s)\n",
		    tcpip_why(err));
	    std_destroy(&chandesc->chancap);
	    XAmFreeChanDesc(chandesc);
	    return -1;
	}

	/* start TCP/IP reader thread */
	chandesc->signal = sig_uniq();
	chandesc->circbuf = cb_alloc(CIRCBUFSIZE);
	param = (XAmChanDesc **) xalloc(sizeof(XAmChanDesc *)); /* error checking? */
	*param = chandesc;
	result = thread_newthread(XAmReaderThread, THREAD_STACK_SIZE,
				  (char *)param, sizeof(XAmChanDesc *));
	if (result == 0) {
	    fprintf(stderr, "Xlib: Cannot start reader thread\n");
	    std_destroy(&chandesc->chancap);
	    XAmFreeChanDesc(chandesc);
	    return -1;
	}
	threadswitch(); /* give reader a try */

	/*
	 * Family type is set to Internet so that the .Xauthority
	 * files from Unix will work under Amoeba (for Unix displays).
	 */
	*familyp = AF_INET;
	*saddrlenp = sizeof(ipaddr_t);
	*saddrp = xalloc(sizeof(ipaddr_t));
	memcpy(*saddrp, (char *)&ipaddr, sizeof(ipaddr_t)); /* error checking? */
    }

    return XAmChanDescToFd(chandesc);
}

/*
 * The TCP/IP server silently assumes a maximum buffer size of 30000 bytes.
 */
#define	TCPIP_BUFSIZE	16384

static void
XAMCloseChannel(chandesc)
XAmChanDesc *chandesc;
{
    if (chandesc->state == ACDS_USED && chandesc->type == ACDT_TCPIP) {
	cb_close(chandesc->circbuf);
	chandesc->state = ACDS_CLOSED;
    }
}


/*
 * Shutdown TCP/IP reader thread
 */
static void
XAmReaderSignalCatcher(sig, us, extra)
    signum sig;
    thread_ustate *us;
    _VOIDSTAR extra;
{
    register XAmChanDesc *chandesc = (XAmChanDesc *)extra;

    XAMCloseChannel(chandesc);
    thread_exit();
}

/*
 * TCP/IP reader thread
 */
static void
XAmReaderThread(argptr, argsize)
    void *argptr;
    int argsize;
{
    register XAmChanDesc *chandesc;

    chandesc = *((XAmChanDesc **)argptr);
    (void) sig_catch(chandesc->signal, XAmReaderSignalCatcher,
		     (_VOIDSTAR) chandesc);

    while (chandesc->state == ACDS_USED) {
	char buffer[CIRCBUFSIZE];
	bufsize size;

	size = tcpip_read(&chandesc->chancap, buffer, sizeof(buffer));
	if (ERR_STATUS(size) || size == 0) {
	    if (size == 0) {
		static char msg[] = "Xlib: TCP/IP channel closed\n";

		write(2, msg, sizeof(msg));
	    } else {
		fprintf(stderr, "Xlib: TCP/IP read failed (%s)\n",
			err_why(ERR_CONVERT(size)));
	    }
	    XAMCloseChannel(chandesc);
	    break;
	}

	if (cb_puts(chandesc->circbuf, buffer, size) != 0) {
	    fprintf(stderr, "Xlib: short write to circular buffer\n");
	    XAMCloseChannel(chandesc);
	}
    }

    thread_exit();
}

/*
 * Wait until input is available or until the timer expires.
 */
int
TRANS(AmSelect)(ifd, timout)
    int ifd;
    int timout;
{
    XAmChanDesc *chandesc;
    int n;

    errno = 0;

    chandesc = XAmFdToChanDesc(ifd);
    if (chandesc == NULL || chandesc->state != ACDS_USED) {
	errno = EBADF;
	return -1;
    }

    if (chandesc->sema == NULL) {
	/* Allocate semaphore to sleep on when no data is
	 * available. The underlying circular buffer and
	 * virtual circuit packages manage this semaphore.
	 */
	chandesc->sema = (semaphore *) xalloc(sizeof(semaphore));
	if (chandesc->sema == NULL) {
	    errno = ENOMEM;
	    return -1;
	}

	sema_init(chandesc->sema, 0);
	switch (chandesc->type) {
	case ACDT_TCPIP:
	    cb_setsema(chandesc->circbuf, chandesc->sema);
	    break;
	case ACDT_VIRTCIRC:
	    vc_setsema(chandesc->virtcirc, chandesc->sema);
	    break;
	}
    }

    switch (chandesc->type) {
    case ACDT_TCPIP:
	if ((n = cb_full(chandesc->circbuf)) != 0) {
	    if (n < 0) errno = EPIPE;
	    return n; /* includes error as well */
	}
	if (sema_trydown(chandesc->sema, timout) < 0) {
	    errno = EINTR;
	    return -1;
	} else {
	    /* we down for all the bytes in AMRead, so undo the down */
	    sema_up(chandesc->sema);
	}
	if ((n = cb_full(chandesc->circbuf)) < 0) {
	    errno = EPIPE;
	    return -1;
	}
	return n;

    case ACDT_VIRTCIRC:
	if ((n = vc_avail(chandesc->virtcirc, VC_IN)) != 0) {
	    if (n < 0) errno = EPIPE;
	    return n; /* includes error as well */
	}
	if (sema_trydown(chandesc->sema, timout) < 0) {
	    errno = EINTR;
	    return -1;
	} else {
	    /* we down for all the bytes in AMRead, so undo the down */
	    sema_up(chandesc->sema);
	}
	if ((n = vc_avail(chandesc->virtcirc, VC_IN)) < 0) {
	    errno = EPIPE;
	    return -1;
	}
	return n;
    }

    errno = EINVAL;
    return -1;
}

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

static int
TRANS(AMGetAddr)(ciptr)
XtransConnInfo	ciptr;
{
    PRMSG(1,"AMGetAddr(%x)\n", ciptr, 0,0 );
    PRMSG(1,"AMGetAddr: TODO\n", 0, 0, 0);

    return -1;
}


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

static int
TRANS(AMGetPeerAddr)(ciptr)
XtransConnInfo	ciptr;
{
    struct nwio_tcpconf tcpconf;
    errstat err;
    XAmChanDesc *chandesc;

    PRMSG(2,"AMGetPeerAddr(%x)\n", ciptr, 0,0 );

    chandesc = XAmFdToChanDesc(ciptr->fd);
    if (chandesc == NULL || chandesc->state != ACDS_USED) {
	errno = EBADF;
	return -1;
    }

    switch (chandesc->type) {
    case ACDT_TCPIP:
	/* get the remote adress from the TCP/IP server */
	if ((err = tcp_ioc_getconf(&chandesc->chancap, &tcpconf)) != STD_OK) {
	    PRMSG (1, "AMGetPeerAddr: Cannot get remote address (%d)\n",
		   (int) err, 0, 0);
	    return -1;
	}

#if 0 /* debug */
        {
	    struct hostent *remote;
	    char *hostname;

	    remote = gethostbyaddr((char *) &tcpconf.nwtc_remaddr,
				   sizeof(tcpconf.nwtc_remaddr), AF_INET);
	    if ((remote == NULL) || (remote->h_name == NULL)) {
		hostname = inet_ntoa(tcpconf.nwtc_remaddr);
	    } else {
		hostname = remote->h_name;
	    }
	    PRMSG (1, "AMGetPeerAddr: remote addr `%s'\n",
		   hostname, 0, 0);
	}
#endif

	ciptr->peeraddrlen = sizeof(tcpconf.nwtc_remaddr);
	ciptr->peeraddr = (char *) xalloc (ciptr->peeraddrlen);
	if (ciptr->peeraddr == NULL) {
	    PRMSG (1, "AMGetPeerAddr: Can't allocate peeraddr\n",
		   0, 0, 0);
	    return -1;
	}

	memcpy (ciptr->peeraddr, &tcpconf.nwtc_remaddr, ciptr->peeraddrlen);
	break;

    case ACDT_VIRTCIRC:
	/* for Amoeba virtual circuits just copy the client address */
	if ((ciptr->peeraddr = (char *) xalloc (ciptr->addrlen)) == NULL) {
	    PRMSG (1, "AMGetPeerAddr: Can't allocate peeraddr\n",
		   0, 0, 0);
	    return -1;
	}

	ciptr->peeraddrlen = ciptr->addrlen;
	memcpy (ciptr->peeraddr, ciptr->addr, ciptr->peeraddrlen);
	break;
    }

    return 0;
}


static XtransConnInfo
TRANS(AMOpen)(device)
char	*device;
{
    PRMSG(1,"AMOpen(%s)\n", device, 0,0 );
    PRMSG(1,"AMOpen: TODO\n", 0, 0, 0);

    return NULL;
}


static	int
TRANS(AMAddrToNetbuf)(tlifamily, host, port, netbufp)
int		tlifamily;
char		*host;
char		*port;
struct netbuf	*netbufp;
{
    PRMSG(1,"AMAddrToNetbuf(%d,%s,%s)\n", tlifamily, host, port );
    PRMSG(1,"AMAddrToNetbuf: TODO\n", 0, 0, 0);

    return -1;
}

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

#ifdef TRANS_CLIENT

static XtransConnInfo
TRANS(AMOpenCOTSClient)(thistrans, protocol, host, port)
Xtransport	*thistrans;
char		*protocol;
char		*host;
char		*port;
{
    XtransConnInfo  ciptr;
    XAmChanDesc    *chandesc;

    PRMSG(2,"AMOpenCOTSClient(%s,%s,%s)\n", protocol, host, port );
    
    ciptr = (XtransConnInfo) xcalloc (1, sizeof(struct _XtransConnInfo));
    if (ciptr == NULL) {
        PRMSG (1, "AMOpenCotsClient: malloc failed\n", 0, 0, 0);
        return NULL;
    }

    ciptr->fd = MakeAmConnection (host, 0 /* TODO */, &ciptr->family,
				  &ciptr->addrlen, &ciptr->addr);
    if (ciptr->fd < 0) {
	PRMSG(1,"AMOpenCOTSClient: Unable to make connection to %s\n",
	      host, 0,0 );
	xfree(ciptr);
	return NULL;
    }

    /* set the back pointer */
    chandesc = XAmFdToChanDesc(ciptr->fd);
    chandesc->conninfo = ciptr;

    TRANS(AMGetPeerAddr)(ciptr);

    PRMSG(2,"AMOpenCOTSClient: made connection to %s; fd = %d, family = %d\n",
	  host, ciptr->fd, ciptr->family);

    return ciptr;
}

#endif /* TRANS_CLIENT */

#if defined(XSERV_t) || defined(FS_t)

/* The following defines come from osdep.h;
 * they should removed from there eventually.
 */

/*
 * Some fundamental constants
 */
#define CONNECTOR_STACK 4000    /* stack for connector task */
#define DEVREADER_STACK 4000    /* stack for device reader */
#define CREATOR_STACK   4000    /* stack for connection creator */
#define MAXTASKS        100     /* Maximum # clients */

/*
 * OsComm status bits
 */
#define CONN_KILLED     0x1     /* Connection being closed */
#define REQ_PUSHBACK    0x2     /* Request pushed back */
#define IGNORE          0x4     /* True if client ignored */
#define CONN_INIT       0x8     /* True if still initializing */
#define CONN_ALIVE      0x10    /* True if living */


#define REPLY_BUFSIZE   30000

capability	X;			/* X capability */
char		*XServerHostName;	/* X server host name */
char		*XTcpServerName;	/* TCP/IP server name */

static XtransConnInfo NewConns[MAXTASKS]; /* new client connections */
int	              nNewConns;	  /* # of new clients */

int		maxClient;		/* Highest allocated client fd + 1*/
static int	minClient = 1;		/* Lowest allocated client fd */

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

    buf[0] = '\0';
    if (status == 0)
	sprintf(buf, "NONE");
    if (status & CONN_INIT)
	sprintf(buf, "%s INIT", buf);
    if (status & CONN_ALIVE)
	sprintf(buf, "%s ALIVE", buf);
    if (status & CONN_KILLED)
	sprintf(buf, "%s KILLED", buf);
    if (status & REQ_PUSHBACK)
	sprintf(buf, "%s PUSHBACK", buf);
    if (status & IGNORE)
	sprintf(buf, "%s IGNORE", buf);
    return buf;
}

static char *
OsCommFamily(family)
    int family;
{
    if (family == FamilyAmoeba) {
	return "AMOEBA";
    } else {
	return "TCP/IP";
    }
}


/*
 * Return status information about the open connections
 */
static errstat
ConnectionStatus(hdr, buf, size)
    header *hdr;
    char *buf;
    int size;
{
    char	*begin, *end;
    char	*bprintf();
    int fd;
    XAmChanDesc *chandesc;

    begin = buf;
    end = buf + size;


    /* all active clients */
    begin = bprintf(begin, end, "Active clients:\n");
    for (fd = minClient; fd < maxClient; fd++) {
	static XAmChanDesc *chandesc;

	chandesc = XAmFdToChanDesc(fd);
	if (chandesc != NULL && chandesc->conninfo != NULL) {
	    begin = bprintf(begin, end, "%d: Family %s, State %d, Status %s\n",
			    fd, OsCommFamily(chandesc->conninfo->family),
			    chandesc->state, OsCommStatus(chandesc->status));
	}
    }

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

/*
 * Wakeup main thread if necessary
 */
static void
UnblockMain(fd)
int fd;
{
    XAmChanDesc *chandesc;

    chandesc = XAmFdToChanDesc(fd);
    if (chandesc != NULL) {
	if ((chandesc->status & IGNORE) == 0) {
	    WakeUpMainThread();
	}
    } else {
	Error(("UnblockMain: invalid fd %d\n", fd));
    }
}

static void
TcpIpReaderSignalCatcher(sig, us, extra)
    signum sig;
    thread_ustate *us;
    _VOIDSTAR extra;
{
    XAmChanDesc *chandesc = (XAmChanDesc *) extra;

    if (chandesc->conninfo != NULL) {
	dbprintf(("TcpIpReaderSignalCatcher(%d), number %d\n",
		  sig, chandesc->conninfo->fd));
	if (chandesc->signal != sig) {
	    Error(("TCP/IP Reader: Connection %s got unexpected signal %d\n",
		   chandesc->conninfo->fd, sig));
	}
    }

    chandesc->signal = -1;
    thread_exit();
}

void
TcpIpReaderThread(argptr, argsize)
    void *argptr;
    int argsize;
{
    XAmChanDesc *chandesc;

    if (argsize != sizeof(XAmChanDesc *)) {
	Fatal(("Internal error: TcpIpReaderThread incorrectly called\n"));
    }

    chandesc = * ((XAmChanDesc **) argptr);
    (void) sig_catch(chandesc->signal, TcpIpReaderSignalCatcher,
		     (_VOIDSTAR) chandesc);

    for (;;) {
	char buffer[MAXBUFSIZE];
	bufsize size;

	size = tcpip_read(&chandesc->chancap, buffer, sizeof(buffer));

	dbprintf(("TcpIpReaderThread() read %d bytes\n", size));
	if (ERR_STATUS(size)) {
	    Error(("TCP/IP read failed (%s)\n", tcpip_why(ERR_CONVERT(size))));
	    chandesc->status |= CONN_KILLED;
	    chandesc->status &= ~CONN_ALIVE;
	    chandesc->signal = -1;
	    thread_exit();
	}

	if (size == 0 || cb_puts(chandesc->circbuf, buffer, size)) {
	    if (size != 0) {
		Error(("TCP/IP short write to circular buffer for %d\n",
		       XAmChanDescToFd(chandesc)));
	    } else {
		Error(("TCP/IP read failed for client %d\n",
		       XAmChanDescToFd(chandesc)));
	    }

	    chandesc->status |= CONN_KILLED;
	    chandesc->status &= ~CONN_ALIVE;
	    chandesc->signal = -1;
	    thread_exit();
	}
	UnblockMain(XAmChanDescToFd(chandesc));
    }
}

static XAmChanDesc *
AllocClientChannel()
{
    XAmChanDesc *chandesc;
    int fd;

    chandesc = XAmAllocChanDesc();
    if (chandesc == NULL) {
	return NULL;
    }

    fd = XAmChanDescToFd(chandesc);
    if (fd >= maxClient) {
	maxClient = fd + 1;
	dbprintf(("new max Client: %d\n", fd));
    }
    if (fd < minClient) {
	minClient = fd;
    }

    return chandesc;
}

static errstat
AmRegisterRPCconn(client_ports, server_ports)
am_port_t client_ports[2];
am_port_t server_ports[2];
{
    XAmChanDesc *chandesc;

    if ((chandesc = AllocClientChannel()) == NULL) {
	return STD_NOSPACE;
    }

    chandesc->type = ACDT_VIRTCIRC;
    chandesc->virtcirc = vc_create(&server_ports[0], &server_ports[1],
				   MAXBUFSIZE, MAXBUFSIZE);
    if (chandesc->virtcirc == NULL) {
	Error(("Connection refused: No memory for virtual circuit\n"));
	XAmFreeChanDesc(chandesc);
	return STD_NOSPACE;
    }

    dbprintf(("Amoeba connection registered\n"));

    vc_warn(chandesc->virtcirc, VC_IN, UnblockMain, XAmChanDescToFd(chandesc));
    
    chandesc->status = CONN_INIT;

    /* cause WaitFor to call EstablishNewConnections: */
    nNewConns++;
    WakeUpMainThread();

    return STD_OK;
}

static XAmChanDesc *
XAmFetchConnectingClient()
{
    XAmChanDesc *chandesc;
    int fd;

    for (fd = minClient; fd < maxClient; fd++) {
	chandesc = XAmFdToChanDesc(fd);

	if (chandesc->status & CONN_INIT) {
	    Error(("Client %d is connecting\n", fd));
	    chandesc->status &= ~CONN_INIT;
	    return chandesc;
	}
    }

    return NULL;
}

static errstat
AmRegisterTCPconn(chancap)
capability *chancap;
{
    XAmChanDesc *chandesc, **param;

    if ((chandesc = AllocClientChannel()) == NULL) {
	return STD_NOSPACE;
    }
    
    chandesc->type = ACDT_TCPIP;
    chandesc->chancap = *chancap;

    if ((chandesc->circbuf = cb_alloc(MAXBUFSIZE)) == NULL) {
	Error(("TCPconn refused: No memory for circular buffer\n"));
	XAmFreeChanDesc(chandesc);
	return STD_NOSPACE;
    }

    chandesc->signal = sig_uniq();
    param = (XAmChanDesc **) xalloc(sizeof(XAmChanDesc *)); /* error checking? */
    *param = chandesc;
    if (thread_newthread(TcpIpReaderThread, MAXBUFSIZE + CONNECTOR_STACK,
			 (char *)param, sizeof(XAmChanDesc *)) == 0)
    {
	Error(("TCPconn refused: Cannot start reader thread\n"));
	cb_close(chandesc->circbuf);
	cb_free(chandesc->circbuf);
	XAmFreeChanDesc(chandesc);
	return STD_NOSPACE;
    }

    dbprintf(("TCP connection registered\n"));

    chandesc->status = CONN_INIT;

    /* cause WaitFor to call EstablishNewConnections: */
    nNewConns++;
    WakeUpMainThread();

    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
AmConnectorThread()
{
    header	req, rep;
    am_port_t	client_ports[2];
    am_port_t	server_ports[2];
    short	s;
    char	*repb;
    extern	CreateNewClient();

    WaitForInitialization();
    dbprintf(("AmConnectorThread() running ...\n"));
    if ((repb = (char *)xalloc(REPLY_BUFSIZE)) == NULL) {
	Fatal(("Amoeba connector thread: malloc failed"));
    }
    for (;;) {
	do {
	    req.h_port = X.cap_port;
	    s = getreq(&req, NILBUF, 0);
	} while (ERR_CONVERT(s) == RPC_ABORTED);
	if (ERR_STATUS(s))
	    Fatal(("Amoeba connector thread: getreq failed"));

	/* TODO: check privilege fields here */

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

	switch (req.h_command) {

	case STD_INFO:
	    rep.h_status = STD_OK;
	    sprintf(repb, "X11R6 server on %s", XServerHostName);
	    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;

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

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

	case AX_CONNECT:
	    uniqport(&client_ports[0]);
	    uniqport(&server_ports[1]);
	    priv2pub(&client_ports[0], &server_ports[0]);
	    priv2pub(&server_ports[1], &client_ports[1]);

	    rep.h_status = AmRegisterRPCconn(client_ports, server_ports);
	    if (rep.h_status == STD_OK) {
		putrep(&rep, (bufptr)client_ports, 2*sizeof(am_port_t));
	    } else {
		putrep(&rep, NILBUF, 0);
	    }
	    break;

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

#ifdef XSERV_t

/*
 * To prevent the X-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

extern char *display;		/* The display number */

/*
 * 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
AmTCPConnectorThread()
{
    capability		svrcap, chancap;
    nwio_tcpconf_t	tcpconf;
    nwio_tcpcl_t	tcpconnopt;
    char 		name[BUFSIZ];
    errstat 		err;
    int			result;
    int			looping = 0;

    strncpy(name, XTcpServerName, BUFSIZ);
    if ((err = name_lookup(name, &svrcap)) != STD_OK) {
	sprintf(name, "%s/%s", TCP_SVR_NAME, XTcpServerName);
	if ((err = name_lookup(name, &svrcap)) != STD_OK)
	    Fatal(("Lookup %s failed: %s\n", XTcpServerName, err_why(err)));
    }

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

    for (;;) {
	/*
	 * Listen to TCP/IP port X_TCP_PORT + display 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) {
		Error(("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(X_TCP_PORT + atoi(display));
	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) {
		Error(("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) {
		Error(("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) {
	    Error(("TCP/IP keep alive failed: %s\n", tcpip_why(err)));
	    std_destroy(&chancap);
	    continue;
	}

	err = AmRegisterTCPconn(&chancap);
	if (err != STD_OK) {
	    Error(("AmRegisterTCPconn failed (%s)\n", err_why(err)));
	    std_destroy(&chancap);
	}
    }
}

static void
AmStartXserverThreads(chandesc)
XAmChanDesc *chandesc;
{
    char		host[100];
    errstat		err;
    capability		pubX;
    static int		threadsStarted = 0;

    /*
     * 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 = 1;

	/*
	 * Create a new capability for this X server
	 */
	if (XServerHostName == NULL)
	    XServerHostName = getenv("XHOST");
	if (XServerHostName == NULL) {
	    Fatal(("XHOST not set, or server host name not given\n"));
	}
	sprintf(host, "%s/%s:%s", DEF_XSVRDIR, XServerHostName, display);

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

	/* Allow WaitFor module to initialize */
	AmInitWaitFor();

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

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

	/* Start native Amoeba service threads */
	if (thread_newthread(AmConnectorThread, CONNECTOR_STACK, 0, 0) <= 0) {
	    Fatal(("Cannot start Amoeba connector thread\n"));
	}
	if (thread_newthread(AmConnectorThread, CONNECTOR_STACK, 0, 0) <= 0) {
	    Fatal(("Cannot start Amoeba connector thread\n"));
	}
	chandesc->type = ACDT_VIRTCIRC;
	chandesc->status = CONN_ALIVE;

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

int
AmFindReadyClients(pClientsReady, mask)
int *pClientsReady;
long *mask;
{
    /* Check for clients needing attention.  They may have input,
     * or they might be dying.  Ignore the clients not present in
     * the file descriptor bit vector `mask'.  This is used for
     * implementing server grabs.
     * Returns the number of clients having data for us.
     */
    extern int ConnectionTranslation[];
    XAmChanDesc *chandesc;
    int fd;
    int nready;

    /* Since we're scheduled non-preemptively by default, allow the
     * listener threads to run first, if needed:
     */
    threadswitch();

    nready = 0;
    for (fd = minClient; fd < maxClient; fd++) {
	int which;
	int n;

	if (fd > 0 && (fd % 32) == 0) {
	    /* switch to next fd mask */
	    mask++;
	}

	if ((*mask & (1L << fd)) == 0) {
	    dbprintf(("skip %d\n", fd));
	    continue;
	}

	chandesc = XAmFdToChanDesc(fd);
	if (chandesc->state != ACDS_USED) {
	    dbprintf(("AmFindReady: fd %d not in use\n", fd));
	    continue;
	}

	which = ConnectionTranslation[fd];
	dbprintf(("checking client %d (fd %d) of %d\n",
		  fd, which, maxClient));

	if (chandesc->status & CONN_KILLED) {
	    dbprintf(("conn killed; close client with fd %d\n", fd));
	    CloseDownClient(clients[which]);
	    chandesc->status &= ~(CONN_KILLED | CONN_ALIVE);
	    continue;
	}

	if ((chandesc->status & CONN_ALIVE) == 0) {
	    dbprintf(("conn with %d is not alive\n", fd));
	    continue;
	}

	/* see if there is data available */
	switch (chandesc->type) {
	case ACDT_TCPIP:
	    n = cb_full(chandesc->circbuf);
	    break;
	case ACDT_VIRTCIRC:
	    n = vc_avail(chandesc->virtcirc, VC_IN);
	    break;
	default:
	    n = -1;
	}

	if (n < 0) {
	    dbprintf(("avail %d; close client %d\n", n, which));
	    CloseDownClient(clients[which]);
	    continue;
	} else {
	    if (n > 0) {
		*pClientsReady++ = which;
		nready++;
		dbprintf(("client %d has %d bytes available\n", which, n));
	    } else {
		dbprintf(("client %d has no data available\n", which, n));
	    }
	}

	/* Clients that already have (possibly inserted) data are found
	 * with help from io.c (the ClientsWithData bit array).
	 */
    }

    return nready;
}

#endif /* XSERV_t */

#endif /* XSERV_t || FS_t */

static
TRANS(AmSetAddr)(ciptr, chandesc)
    XtransConnInfo  ciptr;
    XAmChanDesc    *chandesc;
{
    switch (chandesc->type) {
    case ACDT_TCPIP:
	/* should really ask the TCP/IP server */
	ciptr->family = AF_INET;
	ciptr->addr = strdup("XXXXTODO");
	ciptr->addrlen = strlen("XXXXTODO");
	break;
    case ACDT_VIRTCIRC:
	/* For Amoeba connections the adress is not really used,
	 * so just fake something
	 */
	ciptr->family = AF_AMOEBA;
	ciptr->addr = strdup("Amoeba");
	ciptr->addrlen = strlen(ciptr->addr);
	break;
    }
}

#ifdef TRANS_SERVER

static XtransConnInfo
TRANS(AMOpenCOTSServer)(thistrans, protocol, given_host, port)
Xtransport	*thistrans;
char		*protocol;
char		*given_host;
char		*port;
{
    XAmChanDesc    *chandesc;
    XtransConnInfo  ciptr;

    PRMSG(2,"AMOpenCOTSServer(%s,%s,%s)\n", protocol, given_host, port);

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

    chandesc = XAmAllocChanDesc();
    if (chandesc == NULL) {
	return NULL;
    }

#ifdef XSERV_t
    AmStartXserverThreads(chandesc);
#endif

    chandesc->conninfo = ciptr;
    ciptr->fd = XAmChanDescToFd(chandesc);

    TRANS(AmSetAddr)(ciptr, chandesc);
    TRANS(AMGetPeerAddr)(ciptr);

    return ciptr;
}

#endif /* TRANS_SERVER */


#ifdef TRANS_CLIENT

static XtransConnInfo
TRANS(AMOpenCLTSClient)(thistrans, protocol, host, port)
Xtransport	*thistrans;
char		*protocol;
char		*host;
char		*port;
{
    XtransConnInfo	ciptr;
    int 		i;
    
    PRMSG(1,"AMOpenCLTSClient(%d,%s,%s)\n", protocol, host, port );
    /* TODO */
    return NULL;
}			

#endif /* TRANS_CLIENT */


#ifdef TRANS_SERVER

static XtransConnInfo
TRANS(AMOpenCLTSServer)(thistrans, protocol, host, port)
Xtransport	*thistrans;
char		*protocol;
char		*host;
char		*port;
{
    XtransConnInfo	ciptr;
    int 		i;
    
    PRMSG(1,"AMOpenCLTSServer(%d,%s,%s)\n", protocol, host, port );
    /* TODO */
    return NULL;
}			

static int
TRANS(AMResetListener)(ciptr)
XtransConnInfo	ciptr;
{
    PRMSG(2,"AMResetListener()\n", 0, 0, 0 );

    /* nothing to do? */
    return 0;
}

#endif /* TRANS_SERVER */

static
TRANS(AMSetOption)(ciptr, option, arg)
XtransConnInfo	ciptr;
int		option;
int		arg;
{
    PRMSG(1,"AMSetOption(%d,%d,%d)\n", ciptr->fd, option, arg );
    /* TODO */
    return -1;
}


#ifdef TRANS_SERVER

static
TRANS(AMCreateListener)(ciptr, req)
XtransConnInfo	ciptr;
char	       *req;
{
    PRMSG(2,"AMCreateListener(%x->%d,%x)\n", ciptr, ciptr->fd, req );

    /* Listener threads are already created at this point */
    return 0;
}


static XtransConnInfo
TRANS(AMAccept)(ciptr)
XtransConnInfo	ciptr;
{
    XAmChanDesc    *chandesc;
    XtransConnInfo  newciptr;

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

#if defined(XSERV_t) || defined(FS_t)
    chandesc = XAmFetchConnectingClient();
    if (chandesc == NULL) {
        PRMSG (1, "AMAccept: no client waiting?\n", 0, 0, 0);
        return NULL;
    }
    nNewConns--;

    newciptr = (XtransConnInfo) xcalloc (1, sizeof(struct _XtransConnInfo));
    if (newciptr == NULL)
    {
        PRMSG (1, "AMAccept: malloc failed\n", 0, 0, 0);
        return NULL;
    }

    newciptr->fd = XAmChanDescToFd(chandesc);
    chandesc->conninfo = newciptr;
    chandesc->status |= CONN_ALIVE;

    PRMSG(2,"AMAccept: OK: (%x->%d)\n", newciptr, newciptr->fd, 0 );

    TRANS(AmSetAddr)(newciptr, chandesc);
    TRANS(AMGetPeerAddr)(newciptr);
    
    return newciptr;
#else
    return NULL;
#endif
}

#endif /* TRANS_SERVER */


#ifdef TRANS_CLIENT

static
TRANS(AMConnect)(ciptr, host, port)
XtransConnInfo	ciptr;
char		*host;
char		*port;
{
    /* If this function is called, we are already connected */
    PRMSG(2, "AMConnect(%d,%s)\n", ciptr->fd, host, 0);
    return 0;
}

#endif /* TRANS_CLIENT */


int
TRANS(AmFdBytesReadable)(fd, count)
int fd;
BytesReadable_t	*count;
{
    register XAmChanDesc *chandesc;

    PRMSG(2, "AmFdBytesReadable(%d,%x): ", fd, count, 0 );

#ifndef XSERV_t
    /* give reader threads a chance: */
    threadswitch();
#endif

    errno = 0;
    chandesc = XAmFdToChanDesc(fd);
    if (chandesc == NULL || chandesc->state != ACDS_USED) {
	errno = EBADF;
	*count = 0;
	return -1;
    }

    switch (chandesc->type) {
    case ACDT_TCPIP:
	*count = cb_full(chandesc->circbuf);
	break;
    case ACDT_VIRTCIRC:
	*count = vc_avail(chandesc->virtcirc, VC_IN);
	break;
    }

    if (*count < 0) {
	errno = (chandesc->state == ACDS_CLOSED) ? EINTR : EPIPE;
	*count = 0;
	return -1;
    }

    PRMSG(2, "AMFdBytesReadable: %d\n", *count, 0, 0 );

    return 0;
}

static
TRANS(AMBytesReadable)(ciptr, count)
XtransConnInfo	ciptr;
BytesReadable_t	*count;
{
    return TRANS(AmFdBytesReadable)(ciptr->fd, count);
}


static
TRANS(AMRead)(ciptr, buf, count)
XtransConnInfo	ciptr;
char		*buf;
int		count;
{
    int fdi;
    register XAmChanDesc *chandesc;
    register int rv;
    BytesReadable_t avail;

    fdi = ciptr->fd;
    PRMSG(2, "AMRead(%d,%x,%d)\n", ciptr->fd, buf, count );

    errno = 0;
    chandesc = XAmFdToChanDesc(fdi);
    if (chandesc == NULL || chandesc->state != ACDS_USED) {
	errno = EBADF;
	return -1;
    }

    /* do a non-blocking read (maybe only conditionally?) */
    if ((TRANS(AMBytesReadable)(ciptr, &avail)) == 0) {
	if (avail <= 0) {
	    PRMSG(2, "AMRead: nothing available yet\n", 0, 0, 0);
	    errno = EAGAIN;
	    return 0;
	} else if (count > avail) {
	    PRMSG(2, "AMRead(%d): only %d of %d available\n",
		  ciptr->fd, avail, count);
	    count = avail; /* just read amount available */
	}
    } else {
	PRMSG(1, "AMRead: ...BytesReadable failed\n", 0, 0, 0);
	return -1;
    }

    switch (chandesc->type) {
    case ACDT_TCPIP:
	rv = cb_gets(chandesc->circbuf, buf, count, count);
	if (rv != count) {
	    if (rv == 0) {
		fprintf(stderr, "Xlib: Cannot read circbuf\n");
		errno = EPIPE;
		rv = -1;
	    } else {
		fprintf(stderr, "Xlib: Cannot read circbuf (%d)\n", rv);
	    }
	}
	break;

    case ACDT_VIRTCIRC:
	rv = vc_readall(chandesc->virtcirc, buf, count);
	if (rv < 0) {
	    fprintf(stderr, "Xlib: Cannot read virtual circuit\n");
	    errno = EPIPE;
	    rv = -1;
	}
	break;
    }

    /* The circular buffer writer will only UP the semaphore when
     * characters are available; we have to down it ourselfs.
     */
    if (chandesc->sema && rv > 0)
	sema_mdown(chandesc->sema, rv);

    PRMSG(2, "AMRead: %d bytes\n", rv, 0, 0);

    return rv;
}


static
TRANS(AMWrite)(ciptr, buf, count)
XtransConnInfo	ciptr;
char		*buf;
int		count;
{
    register XAmChanDesc *chandesc;
    register int written;
    
    PRMSG(2, "AMWrite(%d,%x,%d)\n", ciptr->fd, buf, count );

    errno = 0;
    written = 0;

    chandesc = XAmFdToChanDesc(ciptr->fd);
    if (chandesc == NULL || chandesc->state != ACDS_USED) {
	errno = EBADF;
	return -1;
    }

    switch (chandesc->type) {
    case ACDT_TCPIP:
	while (count > 0) {
	    bufsize bsize;
	    int wrcnt;

	    wrcnt = count > TCPIP_BUFSIZE ? TCPIP_BUFSIZE : count;
	    bsize = tcpip_write(&chandesc->chancap, buf, wrcnt);
	    if (ERR_STATUS(bsize)) {
		fprintf(stderr, "Xlib: TCP/IP write failed (%s)\n",
			tcpip_why(ERR_CONVERT(bsize)));
		errno = EPIPE;
		return -1;
	    }
	    if (bsize != wrcnt) {
		fprintf(stderr,
			"Xlib: TCP/IP write failed (expected %d, wrote %d)\n",
			(int)bsize, wrcnt);
		errno = EPIPE;
		return -1;
	    }
	    buf += bsize;
	    count -= (int) bsize;
	    written += (int) bsize;
	}
	break;

    case ACDT_VIRTCIRC:
	if ((written = vc_write(chandesc->virtcirc, buf, count)) < 0) {
	    fprintf(stderr, "Xlib: virtual circuit write failed\n");
	    errno = EPIPE;
	    return -1;
	}
	break;
    }

    return written;
}


static
TRANS(AMReadv)(ciptr, iov, n)
XtransConnInfo	ciptr;
struct iovec   *iov;
int		n;
{
    int i;
    int count = 0, thiscount;

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

    for (i = 0; i < n; i++, iov++) {
	if (iov->iov_len) {
	    thiscount = TRANS(AMRead)(ciptr, iov->iov_base, iov->iov_len);
	    if (thiscount < 0) return thiscount;
	    count += thiscount;
	    if (thiscount < iov->iov_len) break;
	}
    }

    return count;
}


static
TRANS(AMWritev)(ciptr, iov, n)
XtransConnInfo	ciptr;
struct iovec	*iov;
int		n;
{
    int i;
    int count = 0, thiscount;

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

    for (i = 0; i < n; i++, iov++) {
	if (iov->iov_len) {
	    thiscount = TRANS(AMWrite)(ciptr, iov->iov_base, iov->iov_len);
	    if (thiscount < 0)
		return thiscount;
	    count += thiscount;
	    if (thiscount < iov->iov_len) break;
	}
    }

    return count;
}


static
TRANS(AMDisconnect)(ciptr)
XtransConnInfo	ciptr;
{
    register XAmChanDesc *chandesc;

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

    chandesc = XAmFdToChanDesc(ciptr->fd);
    if (chandesc != NULL) {
	switch (chandesc->type) {
	case ACDT_TCPIP:
	    if (chandesc->signal != -1) {
		sig_raise(chandesc->signal);
		chandesc->signal = -1;
	    }
	    std_destroy(&chandesc->chancap);
	    break;

	case ACDT_VIRTCIRC:
	    vc_close(chandesc->virtcirc, VC_BOTH | VC_ASYNC);
	    break;
	}
#ifdef XSERV_t
	if (ciptr->fd == maxClient - 1) {
	    maxClient--;
	    /* we could look if maxClient can be reduced even more */
	}
#endif
	XAmFreeChanDesc(chandesc);
    }

    return 0;
}


static
TRANS(AMClose)(ciptr)
XtransConnInfo	ciptr;
{
    PRMSG(2, "AMClose(%x->%d)\n", ciptr, ciptr->fd, 0 );

    return TRANS(AMDisconnect)(ciptr);
}


Xtransport	TRANS(AmConnFuncs) = {
	/* Combined AMOEBA RPC/TCP Interface; maybe we should split this  */
	"amcon",
	0,
#ifdef TRANS_CLIENT
	TRANS(AMOpenCOTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	TRANS(AMOpenCOTSServer),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(AMOpenCLTSClient),
#endif /* TRANS_CLIENT */
#ifdef TRANS_SERVER
	TRANS(AMOpenCLTSServer),
#endif /* TRANS_SERVER */
	TRANS(AMSetOption),
#ifdef TRANS_SERVER
	TRANS(AMCreateListener),
	TRANS(AMResetListener),
	TRANS(AMAccept),
#endif /* TRANS_SERVER */
#ifdef TRANS_CLIENT
	TRANS(AMConnect),
#endif /* TRANS_CLIENT */
	TRANS(AMBytesReadable),
	TRANS(AMRead),
	TRANS(AMWrite),
	TRANS(AMReadv),
	TRANS(AMWritev),
	TRANS(AMDisconnect),
	TRANS(AMClose),
};