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


Copyright (c) 1993  X Consortium

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

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
X CONSORTIUM 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 X Consortium 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 X Consortium.

Author: Ralph Mor, X Consortium
******************************************************************************/

#include <X11/ICE/ICElib.h>
#include "ICElibint.h"


/*
 * Check for bad length
 */

#define CHECK_SIZE_MATCH(_iceConn, _opcode, _expected_len, _actual_len, _severity) \
    if ((((_actual_len) - SIZEOF (iceMsg)) >> 3) != _expected_len) \
    { \
       _IceErrorBadLength (_iceConn, 0, _opcode, _severity); \
       return (0); \
    }

#define CHECK_AT_LEAST_SIZE(_iceConn, _opcode, _expected_len, _actual_len, _severity) \
    if ((((_actual_len) - SIZEOF (iceMsg)) >> 3) > _expected_len) \
    { \
       _IceErrorBadLength (_iceConn, 0, _opcode, _severity); \
       return (0); \
    }

#define CHECK_COMPLETE_SIZE(_iceConn, _opcode, _expected_len, _actual_len, _pStart, _severity) \
    if (((PADDED_BYTES64((_actual_len)) - SIZEOF (iceMsg)) >> 3) \
        != _expected_len) \
    { \
       _IceErrorBadLength (_iceConn, 0, _opcode, _severity); \
       IceDisposeCompleteMessage (iceConn, _pStart); \
       return (0); \
    }



/*
 * IceProcessMessages:
 *
 * If replyWait == NULL, the client is not waiting for a reply.
 *
 * If replyWait != NULL, the client is waiting for a reply...
 *
 *    - replyWait->sequence_of_request is the sequence number of the
 *      message for which the client is waiting a reply.  This is needed
 *	to determine if an error matches a replyWait.
 *
 *    - replyWait->major_opcode_of_request is the major opcode of the
 *      message for which we are waiting a reply.
 *
 *    - replyWait->minor_opcode_of_request is the minor opcode of the
 *      message for which we are waiting a reply.
 *
 *    - replyWait->reply is a pointer to the reply message which will be
 *	filled in when the reply is ready (the protocol library should
 *      cast this IcePointer to the appropriate reply type).  In most cases,
 *      the reply will have some fixed-size part, and the sender function
 *      will have provided a pointer to a structure (e.g.) to hold this
 *      fixed-size data.  If there is variable-length data, it would be
 *      expected that the reply function will have to allocate additional
 *      memory and store pointer(s) to that memory in the fixed-size
 *      structure.  If the entire data is variable length (e.g., a single
 *      variable-length string), then the sender function would probably
 *      just pass a pointer to fixed-size space to hold a pointer, and the
 *      reply function would allocate the storage and store the pointer.
 *	It is the responsibility of the client receiving the reply to
 *	free up any memory allocated on it's behalf.
 *
 * We might be waiting for several different replies (a function can wait
 * for a reply, and while calling IceProcessMessages, a callback can be
 * invoked which will wait for another reply).  We take advantage of the
 * fact that for a given protocol, we are guaranteed that messages are
 * processed in the order we sent them.  So, everytime we have a new
 * replyWait, we add it to the END of the 'saved_reply_waits' list.  When
 * we read a message and want to see if it matches a replyWait, we use the
 * FIRST replyWait in the list with the major opcode of the message.  If the
 * reply is ready, we remove that replyWait from the list.
 *
 * If the reply/error is ready for the replyWait passed in to
 * IceProcessMessages, *replyReadyRet is set to True.
 *
 * The return value of IceProcessMessages is one of the following:
 *
 * IceProcessMessagesSuccess - the message was processed successfully.
 * IceProcessMessagesIOError - an IO error occured.  The caller should
 *			       invoked IceCloseConnection.
 * IceProcessMessagesConnectionClosed - the connection was closed as a
 *					result of shutdown negotiation.
 */

IceProcessMessagesStatus
IceProcessMessages (iceConn, replyWait, replyReadyRet)

IceConn		 iceConn;
IceReplyWaitInfo *replyWait;
Bool		 *replyReadyRet;

{
    iceMsg		*header;
    Bool		replyReady = False;
    IceReplyWaitInfo	*useThisReplyWait = NULL;
    IceProcessMessagesStatus retStatus = IceProcessMessagesSuccess;

    if (replyWait)
	*replyReadyRet = False;

    /*
     * Each time IceProcessMessages is entered, we increment the dispatch
     * level.  Each time we leave it, we decrement the dispatch level.
     */

    iceConn->dispatch_level++;


    /*
     * Read the ICE message header.
     */

    if (!_IceRead (iceConn, (unsigned long) SIZEOF (iceMsg), iceConn->inbuf))
    {
	/*
	 * If we previously sent a WantToClose and now we detected
	 * that the connection was closed, _IceRead returns status 0.
	 * Since the connection was closed, we just want to return here.
	 */

	return (IceProcessMessagesConnectionClosed);
    }

    if (!iceConn->io_ok)
    {
	/*
	 * An unexpected IO error occured.  The caller of IceProcessMessages
	 * should call IceCloseConnection which will cause the watch procedures
	 * to be invoked and the ICE connection to be freed.
	 */

	iceConn->dispatch_level--;
	iceConn->connection_status = IceConnectIOError;
	return (IceProcessMessagesIOError);
    }

    header = (iceMsg *) iceConn->inbuf;
    iceConn->inbufptr = iceConn->inbuf + SIZEOF (iceMsg);

    iceConn->receive_sequence++;

    if (iceConn->waiting_for_byteorder)
    {
	if (header->majorOpcode == 0 &&
	    header->minorOpcode == ICE_ByteOrder)
	{
	    char byteOrder = ((iceByteOrderMsg *) header)->byteOrder;
	    int endian = 1;

	    CHECK_SIZE_MATCH (iceConn, ICE_ByteOrder,
	        header->length, SIZEOF (iceByteOrderMsg),
		IceFatalToConnection);

	    if (byteOrder != IceMSBfirst && byteOrder != IceLSBfirst)
	    {
		_IceErrorBadValue (iceConn, 0,
	            ICE_ByteOrder, 2, 1, &byteOrder);

		iceConn->connection_status = IceConnectRejected;
	    }
	    else
	    {
		iceConn->swap =
	            (((*(char *) &endian) && byteOrder == IceMSBfirst) ||
	             !(*(char *) &endian) && byteOrder == IceLSBfirst);

		iceConn->waiting_for_byteorder = 0;
	    }
	}
	else
	{
	    if (header->majorOpcode != 0)
	    {
		_IceErrorBadMajor (iceConn, header->majorOpcode,
		    header->minorOpcode, IceFatalToConnection);
	    }
	    else
	    {
		_IceErrorBadState (iceConn, 0,
		    header->minorOpcode, IceFatalToConnection);
	    }

	    iceConn->connection_status = IceConnectRejected;
	}

	iceConn->dispatch_level--;
	if (!iceConn->io_ok)
	{
	    iceConn->connection_status = IceConnectIOError;
	    retStatus = IceProcessMessagesIOError;
	}

	return (retStatus);
    }

    if (iceConn->swap)
    {
	/* swap the length field */

	header->length = lswapl (header->length);
    }

    if (replyWait)
    {
	/*
	 * Add to the list of replyWaits (only if it doesn't exist
	 * in the list already.
	 */

	_IceAddReplyWait (iceConn, replyWait);


	/*
	 * Note that there are two different replyWaits.  The first is
	 * the one passed into IceProcessMessages, and is the replyWait
	 * for the message the client is blocking on.  The second is
	 * the replyWait for the message currently being processed
	 * by IceProcessMessages.  We call it "useThisReplyWait".
	 */

	useThisReplyWait = _IceSearchReplyWaits (iceConn, header->majorOpcode);
    }

    if (header->majorOpcode == 0)
    {
	/*
	 * ICE protocol
	 */

	Bool connectionClosed;

	_IceProcessCoreMsgProc processIce =
	    _IceVersions[iceConn->my_ice_version_index].process_core_msg_proc;

	(*processIce) (iceConn, header->minorOpcode,
	    header->length, iceConn->swap,
	    useThisReplyWait, &replyReady, &connectionClosed);

	if (connectionClosed)
	{
	    /*
	     * As a result of shutdown negotiation, the connection was closed.
	     */

	    return (IceProcessMessagesConnectionClosed);
	}
    }
    else
    {
	/*
	 * Sub protocol
	 */

	if ((int) header->majorOpcode < iceConn->his_min_opcode ||
	    (int) header->majorOpcode > iceConn->his_max_opcode ||
	    !(iceConn->process_msg_info[header->majorOpcode -
	    iceConn->his_min_opcode].in_use))
	{
	    /*
	     * The protocol of the message we just read is not supported.
	     */

	    _IceErrorBadMajor (iceConn, header->majorOpcode,
		header->minorOpcode, IceCanContinue);

	    _IceReadSkip (iceConn, header->length << 3);
	}
	else
	{
	    _IceProcessMsgInfo *processMsgInfo = &iceConn->process_msg_info[
		header->majorOpcode - iceConn->his_min_opcode];

	    if (processMsgInfo->accept_flag)
	    {
		IcePaProcessMsgProc processProc =
		    processMsgInfo->process_msg_proc.accept_client;

		(*processProc) (iceConn, processMsgInfo->client_data,
		    header->minorOpcode, header->length, iceConn->swap);
	    }
	    else
	    {
		IcePoProcessMsgProc processProc =
		    processMsgInfo->process_msg_proc.orig_client;

		(*processProc) (iceConn,
		    processMsgInfo->client_data, header->minorOpcode,
		    header->length, iceConn->swap,
		    useThisReplyWait, &replyReady);
	    }
	}
    }

    if (replyReady)
    {
	_IceSetReplyReady (iceConn, useThisReplyWait);
    }


    /*
     * Now we check if the reply is ready for the replyWait passed
     * into IceProcessMessages.  The replyWait is removed from the
     * replyWait list if it is ready.
     */

    if (replyWait)
	*replyReadyRet = _IceCheckReplyReady (iceConn, replyWait);


    /*
     * Decrement the dispatch level.  If we reach level 0, and the
     * free_asap bit is set, free the connection now.  Also check for
     * possible bad IO status.
     */

    iceConn->dispatch_level--;

    if (iceConn->dispatch_level == 0 && iceConn->free_asap)
    {
	_IceFreeConnection (iceConn);
	retStatus = IceProcessMessagesConnectionClosed;
    }
    else if (!iceConn->io_ok)
    {
	iceConn->connection_status = IceConnectIOError;
	retStatus = IceProcessMessagesIOError;
    }

    return (retStatus);
}



static void
AuthRequired (iceConn, authIndex, authDataLen, authData)

IceConn		iceConn;
int  		authIndex;
int  		authDataLen;
IcePointer	authData;

{
    iceAuthRequiredMsg *pMsg;

    IceGetHeader (iceConn, 0, ICE_AuthRequired,
	SIZEOF (iceAuthRequiredMsg), iceAuthRequiredMsg, pMsg);

    pMsg->authIndex = authIndex;
    pMsg->authDataLength = authDataLen;
    pMsg->length += WORD64COUNT (authDataLen);

    IceWriteData (iceConn, authDataLen, (char *) authData);

    if (PAD64 (authDataLen))
	IceWritePad (iceConn, PAD64 (authDataLen));

    IceFlush (iceConn);
}



static void
AuthReply (iceConn, authDataLen, authData)

IceConn		iceConn;
int 		authDataLen;
IcePointer	authData;

{
    iceAuthReplyMsg *pMsg;

    IceGetHeader (iceConn, 0, ICE_AuthReply,
	SIZEOF (iceAuthReplyMsg), iceAuthReplyMsg, pMsg);

    pMsg->authDataLength = authDataLen;
    pMsg->length +=  WORD64COUNT (authDataLen);

    IceWriteData (iceConn, authDataLen, (char *) authData);

    if (PAD64 (authDataLen))
	IceWritePad (iceConn, PAD64 (authDataLen));

    IceFlush (iceConn);
}



static void
AuthNextPhase (iceConn, authDataLen, authData)

IceConn		iceConn;
int  		authDataLen;
IcePointer	authData;

{
    iceAuthNextPhaseMsg *pMsg;

    IceGetHeader (iceConn, 0, ICE_AuthNextPhase,
	SIZEOF (iceAuthNextPhaseMsg), iceAuthNextPhaseMsg, pMsg);

    pMsg->authDataLength = authDataLen;
    pMsg->length += WORD64COUNT (authDataLen);

    IceWriteData (iceConn, authDataLen, (char *) authData);

    if (PAD64 (authDataLen))
	IceWritePad (iceConn, PAD64 (authDataLen));

    IceFlush (iceConn);
}



static void
AcceptConnection (iceConn, versionIndex)

IceConn iceConn;
int 	versionIndex;

{
    iceConnectionReplyMsg	*pMsg;
    char			*pData;
    int				extra;

    extra = STRING_BYTES (IceVendorString) + STRING_BYTES (IceReleaseString);

    IceGetHeaderExtra (iceConn, 0, ICE_ConnectionReply,
	SIZEOF (iceConnectionReplyMsg), WORD64COUNT (extra),
	iceConnectionReplyMsg, pMsg, pData);

    pMsg->versionIndex = versionIndex;

    STORE_STRING (pData, IceVendorString);
    STORE_STRING (pData, IceReleaseString);

    IceFlush (iceConn);

    iceConn->connection_status = IceConnectAccepted;
}



static void
AcceptProtocol (iceConn, hisOpcode, myOpcode, versionIndex, vendor, release)

IceConn iceConn;
int  	hisOpcode;
int  	myOpcode;
int  	versionIndex;
char 	*vendor;
char 	*release;

{
    iceProtocolReplyMsg	*pMsg;
    char		*pData;
    int			extra;

    extra = STRING_BYTES (vendor) + STRING_BYTES (release);

    IceGetHeaderExtra (iceConn, 0, ICE_ProtocolReply,
	SIZEOF (iceProtocolReplyMsg), WORD64COUNT (extra),
	iceProtocolReplyMsg, pMsg, pData);

    pMsg->protocolOpcode = myOpcode;
    pMsg->versionIndex = versionIndex;

    STORE_STRING (pData, vendor);
    STORE_STRING (pData, release);

    IceFlush (iceConn);


    /*
     * We may be using a different major opcode for this protocol
     * than the other client.  Whenever we get a message, we must
     * map to our own major opcode.
     */

    _IceAddOpcodeMapping (iceConn, hisOpcode, myOpcode);
}



static void
PingReply (iceConn)

IceConn iceConn;

{
    IceSimpleMessage (iceConn, 0, ICE_PingReply);
    IceFlush (iceConn);
}



static Bool
ProcessError (iceConn, length, swap, replyWait)

IceConn		 iceConn;
unsigned long	 length;
Bool		 swap;
IceReplyWaitInfo *replyWait;

{
    int		invokeHandler;
    Bool	errorReturned = False;
    iceErrorMsg *message;
    char 	*pData, *pStart;
    char	severity;

    CHECK_AT_LEAST_SIZE (iceConn, ICE_Error,
	length, SIZEOF (iceErrorMsg),
	(iceConn->connect_to_you || iceConn->connect_to_me) ?
	IceFatalToConnection : IceFatalToProtocol);

    IceReadCompleteMessage (iceConn, SIZEOF (iceErrorMsg),
	iceErrorMsg, message, pStart);

    if (!IceValidIO (iceConn))
    {
	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    severity = message->severity;

    if (severity != IceCanContinue && severity != IceFatalToProtocol &&
	severity != IceFatalToConnection)
    {
	_IceErrorBadValue (iceConn, 0,
	    ICE_Error, 9, 1, &severity);
	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    pData = pStart;

    if (swap)
    {
	message->errorClass = lswaps (message->errorClass);
	message->offendingSequenceNum = lswapl (message->offendingSequenceNum);
    }

    if (!replyWait ||
	message->offendingSequenceNum != replyWait->sequence_of_request)
    {
	invokeHandler = 1;
    }
    else
    {
	if (iceConn->connect_to_you &&
	    ((!iceConn->connect_to_you->auth_active &&
            message->offendingMinorOpcode == ICE_ConnectionSetup) ||
            (iceConn->connect_to_you->auth_active &&
	    message->offendingMinorOpcode == ICE_AuthReply)))
	{
	    _IceConnectionError *errorReply =
	        &(((_IceReply *) (replyWait->reply))->connection_error);
	    char *errorStr = NULL;
	    char *tempstr;
	    char *prefix, *temp;

	    invokeHandler = 0;
	    errorReturned = True;

	    switch (message->errorClass)
	    {
	    case IceNoVersion:

		tempstr =
		    "None of the ICE versions specified are supported";
		errorStr = (char *) malloc (strlen (tempstr) + 1);
		strcpy (errorStr, tempstr);
		break;

	    case IceNoAuth:

		tempstr =
		    "None of the authentication protocols specified are supported";
		errorStr = (char *) malloc (strlen (tempstr) + 1);
		strcpy (errorStr, tempstr);
		break;

	    case IceSetupFailed:

		prefix = "Connection Setup Failed, reason : ";

		EXTRACT_STRING (pData, swap, temp);
		errorStr = (char *) malloc (
		    strlen (prefix) + strlen (temp) + 1);
		sprintf (errorStr, "%s%s", prefix, temp);
		free (temp);
		break;

	    case IceAuthRejected:

		prefix = "Authentication Rejected, reason : ";
		EXTRACT_STRING (pData, swap, temp);
		errorStr = (char *) malloc (
		    strlen (prefix) + strlen (temp) + 1);
		sprintf (errorStr, "%s%s", prefix, temp);
		free (temp);
		break;

	    case IceAuthFailed:

		prefix = "Authentication Failed, reason : ";
		EXTRACT_STRING (pData, swap, temp);
		errorStr = (char *) malloc (
		    strlen (prefix) + strlen (temp) + 1);
		sprintf (errorStr, "%s%s", prefix, temp);
		free (temp);
		break;

	    default:
		invokeHandler = 1;
	    }

	    errorReply->type = ICE_CONNECTION_ERROR;
	    errorReply->error_message = errorStr;
	}
	else if (iceConn->protosetup_to_you &&
	    ((!iceConn->protosetup_to_you->auth_active &&
            message->offendingMinorOpcode == ICE_ProtocolSetup) ||
            (iceConn->protosetup_to_you->auth_active &&
	    message->offendingMinorOpcode == ICE_AuthReply)))
	{
	    _IceProtocolError *errorReply =
	        &(((_IceReply *) (replyWait->reply))->protocol_error);
	    char *errorStr = "";
	    char *prefix, *temp;

	    invokeHandler = 0;
	    errorReturned = True;

	    switch (message->errorClass)
	    {
	    case IceNoVersion:

	        temp =
		    "None of the protocol versions specified are supported";
		errorStr = (char *) malloc (strlen (temp) + 1);
		strcpy (errorStr, temp);
		break;

	    case IceNoAuth:

		temp =
		    "None of the authentication protocols specified are supported";
		errorStr = (char *) malloc (strlen (temp) + 1);
		strcpy (errorStr, temp);
		break;

	    case IceSetupFailed:

		prefix = "Protocol Setup Failed, reason : ";

		EXTRACT_STRING (pData, swap, temp);
		errorStr = (char *) malloc (
		    strlen (prefix) + strlen (temp) + 1);
		sprintf (errorStr, "%s%s", prefix, temp);
		free (temp);
		break;

	    case IceAuthRejected:

		prefix = "Authentication Rejected, reason : ";
		EXTRACT_STRING (pData, swap, temp);
		errorStr = (char *) malloc (
		    strlen (prefix) + strlen (temp) + 1);
		sprintf (errorStr, "%s%s", prefix, temp);
		free (temp);
		break;

	    case IceAuthFailed:

		prefix = "Authentication Failed, reason : ";
		EXTRACT_STRING (pData, swap, temp);
		errorStr = (char *) malloc (
		    strlen (prefix) + strlen (temp) + 1);
		sprintf (errorStr, "%s%s", prefix, temp);
		free (temp);
		break;

	    case IceProtocolDuplicate:

		prefix = "Protocol was already registered : ";
		EXTRACT_STRING (pData, swap, temp);
		errorStr = (char *) malloc (
		    strlen (prefix) + strlen (temp) + 1);
		sprintf (errorStr, "%s%s", prefix, temp);
		free (temp);
		break;

	    case IceMajorOpcodeDuplicate:

		prefix = "The major opcode was already used : ";
		errorStr = (char *) malloc (strlen (prefix) + 2);
		sprintf (errorStr, "%s%d", prefix, (int) *pData);
		break;

	    case IceUnknownProtocol:

		prefix = "Unknown Protocol : ";
		EXTRACT_STRING (pData, swap, temp);
		errorStr = (char *) malloc (
		    strlen (prefix) + strlen (temp) + 1);
		sprintf (errorStr, "%s%s", prefix, temp);
		free (temp);
		break;

	    default:
		invokeHandler = 1;
	    }

	    errorReply->type = ICE_PROTOCOL_ERROR;
	    errorReply->error_message = errorStr;
	}

	if (errorReturned == True)
	{
	    /*
	     * If we tried to authenticate, tell the authentication
	     * procedure to clean up.
	     */

	    IcePoAuthProc authProc;

	    if (iceConn->connect_to_you &&
		iceConn->connect_to_you->auth_active)
	    {
		authProc = _IcePoAuthProcs[
		    iceConn->connect_to_you->my_auth_index];

		(*authProc) (iceConn, &iceConn->connect_to_you->my_auth_state,
		    True /* clean up */, False /* swap */,
		    0, NULL, NULL, NULL, NULL);
	    }
	    else if (iceConn->protosetup_to_you &&
		iceConn->protosetup_to_you->auth_active)
	    {
		_IcePoProtocol *protocol = _IceProtocols[
		    iceConn->protosetup_to_you->my_opcode - 1].orig_client;

		authProc = protocol->auth_procs[iceConn->
		    protosetup_to_you->my_auth_index];

		(*authProc) (iceConn,
		    &iceConn->protosetup_to_you->my_auth_state,
		    True /* clean up */, False /* swap */,
		    0, NULL, NULL, NULL, NULL);
	    }
	}
    }

    if (invokeHandler)
    {
	(*_IceErrorHandler) (iceConn, swap, message->offendingMinorOpcode,
	    message->offendingSequenceNum, message->errorClass,
	    message->severity, (IcePointer) pData);
    }

    IceDisposeCompleteMessage (iceConn, pStart);

    return (errorReturned);
}



static
ProcessConnectionSetup (iceConn, length, swap)

IceConn		iceConn;
unsigned long	length;
Bool		swap;

{
    iceConnectionSetupMsg *message;
    int  myVersionCount, hisVersionCount;
    int	 myVersionIndex, hisVersionIndex;
    int  hisMajorVersion, hisMinorVersion;
    int	 myAuthCount, hisAuthCount;
    int	 found, i, j;
    char *myAuthName, **hisAuthNames;
    char *pData, *pStart;
    char *vendor = NULL;
    char *release = NULL;
    int myAuthIndex = 0;
    int hisAuthIndex = 0;
    int accept_setup_now = 0;
    char mustAuthenticate;
    int	authUsableCount;
    int	authUsableFlags[MAX_ICE_AUTH_NAMES];
    int	authIndices[MAX_ICE_AUTH_NAMES];

    CHECK_AT_LEAST_SIZE (iceConn, ICE_ConnectionSetup,
	length, SIZEOF (iceConnectionSetupMsg), IceFatalToConnection);

    IceReadCompleteMessage (iceConn, SIZEOF (iceConnectionSetupMsg),
	iceConnectionSetupMsg, message, pStart);

    if (!IceValidIO (iceConn))
    {
	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    pData = pStart;

    SKIP_STRING (pData, swap);				       /* vendor */
    SKIP_STRING (pData, swap);				       /* release */
    SKIP_LISTOF_STRING (pData, swap, (int) message->authCount);/* auth names */
    pData += (message->versionCount * 4);		       /* versions */

    CHECK_COMPLETE_SIZE (iceConn, ICE_ConnectionSetup,
	length, pData - pStart + SIZEOF (iceConnectionSetupMsg),
	pStart, IceFatalToConnection);

    mustAuthenticate = message->mustAuthenticate;
    if (mustAuthenticate != 0 && mustAuthenticate != 1)
    {
	_IceErrorBadValue (iceConn, 0,
	    ICE_ConnectionSetup, 8, 1, &mustAuthenticate);
	iceConn->connection_status = IceConnectRejected;
	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    pData = pStart;

    EXTRACT_STRING (pData, swap, vendor);
    EXTRACT_STRING (pData, swap, release);

    if ((hisAuthCount = message->authCount) > 0)
    {
	hisAuthNames = (char **) malloc (hisAuthCount * sizeof (char *));
	EXTRACT_LISTOF_STRING (pData, swap, hisAuthCount, hisAuthNames);
    }

    hisVersionCount = message->versionCount;
    myVersionCount = _IceVersionCount;

    hisVersionIndex = myVersionIndex = found = 0;

    for (i = 0; i < hisVersionCount && !found; i++)
    {
	EXTRACT_CARD16 (pData, swap, hisMajorVersion);
	EXTRACT_CARD16 (pData, swap, hisMinorVersion);

	for (j = 0; j < myVersionCount && !found; j++)
	{
	    if (_IceVersions[j].major_version == hisMajorVersion &&
		_IceVersions[j].minor_version == hisMinorVersion)
	    {
		hisVersionIndex = i;
		myVersionIndex = j;
		found = 1;
	    }
	}
    }

    if (!found)
    {
	_IceErrorNoVersion (iceConn, ICE_ConnectionSetup);
	iceConn->connection_status = IceConnectRejected;

	free (vendor);
	free (release);

	if (hisAuthCount > 0)
	{
	    for (i = 0; i < hisAuthCount; i++)
		free (hisAuthNames[i]);
	
	    free ((char *) hisAuthNames);
	}

	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    _IceGetPaValidAuthIndices ("ICE", iceConn->connection_string,
	_IceAuthCount, _IceAuthNames, &authUsableCount, authIndices);

    for (i = 0; i < _IceAuthCount; i++)
    {
	authUsableFlags[i] = 0;
	for (j = 0; j < authUsableCount && !authUsableFlags[i]; j++)
	    authUsableFlags[i] = (authIndices[j] == i);
    }

    myAuthCount = _IceAuthCount;

    for (i = found = 0; i < myAuthCount && !found; i++)
    {
	if (authUsableFlags[i])
	{
	    myAuthName = _IceAuthNames[i];

	    for (j = 0; j < hisAuthCount && !found; j++)
		if (strcmp (myAuthName, hisAuthNames[j]) == 0)
		{
		    myAuthIndex = i;
		    hisAuthIndex = j;
		    found = 1;
		}
	}
    }

    if (!found)
    {
	/*
	 * None of the authentication methods specified by the
	 * other client is supported.  If the other client requires
	 * authentication, we must reject the connection now.
	 * Otherwise, we can invoke the host-based authentication callback
	 * to see if we can accept this connection.
	 */

	if (mustAuthenticate || !iceConn->listen_obj->host_based_auth_proc)
	{
	    _IceErrorNoAuthentication (iceConn, ICE_ConnectionSetup);
	    iceConn->connection_status = IceConnectRejected;
	}
	else
	{
	    char *hostname = _IceGetPeerName (iceConn);

	    if ((*iceConn->listen_obj->host_based_auth_proc) (hostname))
	    {
		accept_setup_now = 1;
	    }
	    else 
	    {
		_IceErrorAuthenticationRejected (iceConn,
	            ICE_ConnectionSetup, "None of the authentication protocols specified are supported and host-based authentication failed");

		iceConn->connection_status = IceConnectRejected;
	    }

	    if (hostname)
		free (hostname);
	}

	if (iceConn->connection_status == IceConnectRejected)
	{
	    free (vendor);
	    free (release);
	}
    }
    else
    {
	IcePaAuthStatus	status;
	int		authDataLen;
	IcePointer	authData = NULL;
	IcePointer	authState;
	char		*errorString = NULL;
	IcePaAuthProc	authProc = _IcePaAuthProcs[myAuthIndex];

	authState = NULL;

	status = (*authProc) (iceConn, &authState,
	    swap, 0, NULL, &authDataLen, &authData, &errorString);

	if (status == IcePaAuthContinue)
	{
	    _IceConnectToMeInfo *setupInfo;

	    AuthRequired (iceConn, hisAuthIndex, authDataLen, authData);

	    iceConn->connect_to_me = setupInfo = (_IceConnectToMeInfo *)
		malloc (sizeof (_IceConnectToMeInfo));

	    setupInfo->my_version_index = myVersionIndex;
	    setupInfo->his_version_index = hisVersionIndex;
	    setupInfo->his_vendor = vendor;
	    setupInfo->his_release = release;
	    setupInfo->my_auth_index = myAuthIndex;
	    setupInfo->my_auth_state = authState;
	    setupInfo->must_authenticate = mustAuthenticate;
	}
	else if (status == IcePaAuthAccepted)
	{
	    accept_setup_now = 1;
	}

	if (authData && authDataLen > 0)
	    free ((char *) authData);

	if (errorString)
	    free (errorString);
    }
    
    if (accept_setup_now)
    {
	AcceptConnection (iceConn, hisVersionIndex);

	iceConn->vendor = vendor;
	iceConn->release = release;
	iceConn->my_ice_version_index = myVersionIndex;
    }

    if (hisAuthCount > 0)
    {
	for (i = 0; i < hisAuthCount; i++)
	    free (hisAuthNames[i]);
	
	free ((char *) hisAuthNames);
    }

    IceDisposeCompleteMessage (iceConn, pStart);
    return (0);
}



static Bool
ProcessAuthRequired (iceConn, length, swap, replyWait)

IceConn			iceConn;
unsigned long	 	length;
Bool			swap;
IceReplyWaitInfo	*replyWait;

{
    iceAuthRequiredMsg  *message;
    int			authDataLen;
    IcePointer 		authData;
    int 		replyDataLen;
    IcePointer 		replyData = NULL;
    char		*errorString = NULL;
    IcePoAuthProc	authProc;
    IcePoAuthStatus	status;
    IcePointer 		authState;
    int			realAuthIndex;

    CHECK_AT_LEAST_SIZE (iceConn, ICE_AuthRequired,
	length, SIZEOF (iceAuthRequiredMsg),
	iceConn->connect_to_you ? IceFatalToConnection : IceFatalToProtocol);

    IceReadCompleteMessage (iceConn, SIZEOF (iceAuthRequiredMsg),
	iceAuthRequiredMsg, message, authData);

    if (!IceValidIO (iceConn))
    {
	IceDisposeCompleteMessage (iceConn, authData);
	return (0);
    }

    if (swap)
    {
	message->authDataLength = lswaps (message->authDataLength);
    }

    CHECK_COMPLETE_SIZE (iceConn, ICE_AuthRequired, length,
	message->authDataLength + SIZEOF (iceAuthRequiredMsg), authData,
	iceConn->connect_to_you ? IceFatalToConnection : IceFatalToProtocol);

    if (iceConn->connect_to_you)
    {
	if ((int) message->authIndex >= _IceAuthCount)
	{
	    _IceConnectionError *errorReply =
	        &(((_IceReply *) (replyWait->reply))->connection_error);

	    char *tempstr = "Received bad authIndex in the AuthRequired message";
	    char errIndex = (int) message->authIndex;

	    errorString = (char *) malloc (strlen (tempstr) + 1);
	    strcpy (errorString, tempstr);

	    errorReply->type = ICE_CONNECTION_ERROR;
	    errorReply->error_message = errorString;

	    _IceErrorBadValue (iceConn, 0,
		ICE_AuthRequired, 2, 1, &errIndex);

	    IceDisposeCompleteMessage (iceConn, authData);
	    return (1);
	}
	else
	{
	    authProc = _IcePoAuthProcs[message->authIndex];

	    iceConn->connect_to_you->auth_active = 1;
	}
    }
    else if (iceConn->protosetup_to_you)
    {
	if ((int) message->authIndex >=
	    iceConn->protosetup_to_you->my_auth_count)
	{
	    _IceProtocolError *errorReply =
	        &(((_IceReply *) (replyWait->reply))->protocol_error);

	    char *tempstr = "Received bad authIndex in the AuthRequired message";
	    char errIndex = (int) message->authIndex;

	    errorString = (char *) malloc (strlen (tempstr) + 1);
	    strcpy (errorString, tempstr);

	    errorReply->type = ICE_PROTOCOL_ERROR;
	    errorReply->error_message = errorString;

	    _IceErrorBadValue (iceConn, 0,
		ICE_AuthRequired, 2, 1, &errIndex);

	    IceDisposeCompleteMessage (iceConn, authData);
	    return (1);
	}
	else
	{
	    _IcePoProtocol *myProtocol = _IceProtocols[
	        iceConn->protosetup_to_you->my_opcode - 1].orig_client;

	    realAuthIndex = iceConn->protosetup_to_you->
		my_auth_indices[message->authIndex];

	    authProc = myProtocol->auth_procs[realAuthIndex];

	    iceConn->protosetup_to_you->auth_active = 1;
	}
    }
    else
    {
	/*
	 * Unexpected message
	 */

	_IceErrorBadState (iceConn, 0, ICE_AuthRequired, IceCanContinue);

	IceDisposeCompleteMessage (iceConn, authData);
	return (0);
    }

    authState = NULL;
    authDataLen = message->authDataLength;

    status = (*authProc) (iceConn, &authState, False /* don't clean up */,
	swap, authDataLen, authData, &replyDataLen, &replyData, &errorString);

    if (status == IcePoAuthHaveReply)
    {
	AuthReply (iceConn, replyDataLen, replyData);

	replyWait->sequence_of_request = iceConn->send_sequence;
	replyWait->minor_opcode_of_request = ICE_AuthReply;

	if (iceConn->connect_to_you)
	{
	    iceConn->connect_to_you->my_auth_state = authState;
	    iceConn->connect_to_you->my_auth_index = message->authIndex;
	}
	else if (iceConn->protosetup_to_you)
	{
	    iceConn->protosetup_to_you->my_auth_state = authState;
	    iceConn->protosetup_to_you->my_auth_index = realAuthIndex;
	}
    }
    else if (status == IcePoAuthRejected || status == IcePoAuthFailed)
    {
	char *prefix, *returnErrorString;

	if (status == IcePoAuthRejected)
	{
	    _IceErrorAuthenticationRejected (iceConn,
	        ICE_AuthRequired, errorString);

	    prefix = "Authentication Rejected, reason : ";
	}
	else
	{
	    _IceErrorAuthenticationFailed (iceConn,
	       ICE_AuthRequired, errorString);

	    prefix = "Authentication Failed, reason : ";
	}

	returnErrorString = (char *) malloc (strlen (prefix) +
	    strlen (errorString) + 1);
	sprintf (returnErrorString, "%s%s", prefix, errorString);
	free (errorString);
	
	if (iceConn->connect_to_you)
	{
	    _IceConnectionError *errorReply =
	        &(((_IceReply *) (replyWait->reply))->connection_error);

	    errorReply->type = ICE_CONNECTION_ERROR;
	    errorReply->error_message = returnErrorString;
	}
	else
	{
	    _IceProtocolError *errorReply =
	        &(((_IceReply *) (replyWait->reply))->protocol_error);

	    errorReply->type = ICE_PROTOCOL_ERROR;
	    errorReply->error_message = returnErrorString;
	}
    }

    if (replyData && replyDataLen > 0)
	free ((char *) replyData);

    IceDisposeCompleteMessage (iceConn, authData);

    return (status != IcePoAuthHaveReply);
}



static
ProcessAuthReply (iceConn, length, swap)

IceConn		iceConn;
unsigned long	length;
Bool		swap;

{
    iceAuthReplyMsg 	*message;
    int			replyDataLen;
    IcePointer		replyData;
    int 		authDataLen;
    IcePointer 		authData = NULL;
    char		*errorString = NULL;

    CHECK_AT_LEAST_SIZE (iceConn, ICE_AuthReply,
	length, SIZEOF (iceAuthReplyMsg),
	iceConn->connect_to_me ? IceFatalToConnection : IceFatalToProtocol);

    IceReadCompleteMessage (iceConn, SIZEOF (iceAuthReplyMsg),
	iceAuthReplyMsg, message, replyData);

    if (!IceValidIO (iceConn))
    {
	IceDisposeCompleteMessage (iceConn, replyData);
	return (0);
    }

    if (swap)
    {
	message->authDataLength = lswaps (message->authDataLength);
    }

    CHECK_COMPLETE_SIZE (iceConn, ICE_AuthReply, length,
	message->authDataLength + SIZEOF (iceAuthReplyMsg), replyData,
	iceConn->connect_to_me ? IceFatalToConnection : IceFatalToProtocol);

    replyDataLen = message->authDataLength;

    if (iceConn->connect_to_me)
    {
	IcePaAuthProc authProc = _IcePaAuthProcs[
	    iceConn->connect_to_me->my_auth_index];
	IcePaAuthStatus status =
	    (*authProc) (iceConn, &iceConn->connect_to_me->my_auth_state, swap,
	    replyDataLen, replyData, &authDataLen, &authData, &errorString);

	if (status == IcePaAuthContinue)
	{
	    AuthNextPhase (iceConn, authDataLen, authData);
	}
	else if (status == IcePaAuthRejected || status == IcePaAuthFailed)
	{
	    /*
	     * Before we reject, invoke host-based authentication callback
	     * and give it a chance to accept the connection (only if the
	     * other client doesn't require authentication).
	     */

	    if (!iceConn->connect_to_me->must_authenticate &&
		iceConn->listen_obj->host_based_auth_proc)
	    {
		char *hostname = _IceGetPeerName (iceConn);

		if ((*iceConn->listen_obj->host_based_auth_proc) (hostname))
		{
		    status = IcePaAuthAccepted;
		}

		if (hostname)
		    free (hostname);
	    }

	    if (status != IcePaAuthAccepted)
	    {
		free (iceConn->connect_to_me->his_vendor);
		free (iceConn->connect_to_me->his_release);
		free ((char *) iceConn->connect_to_me);
		iceConn->connect_to_me = NULL;

		iceConn->connection_status = IceConnectRejected;

		if (status == IcePaAuthRejected)
		{
		    _IceErrorAuthenticationRejected (iceConn,
	                ICE_AuthReply, errorString);
		}
		else
		{
		    _IceErrorAuthenticationFailed (iceConn,
	                ICE_AuthReply, errorString);
		}
	    }
	}

	if (status == IcePaAuthAccepted)
	{
	    AcceptConnection (iceConn,
		iceConn->connect_to_me->his_version_index);

	    iceConn->vendor = iceConn->connect_to_me->his_vendor;
	    iceConn->release = iceConn->connect_to_me->his_release;
	    iceConn->my_ice_version_index =
		iceConn->connect_to_me->my_version_index;

	    free ((char *) iceConn->connect_to_me);
	    iceConn->connect_to_me = NULL;
	}
    }
    else if (iceConn->protosetup_to_me)
    {
	_IcePaProtocol *myProtocol = _IceProtocols[iceConn->protosetup_to_me->
	    my_opcode - 1].accept_client;
	IcePaAuthProc authProc = myProtocol->auth_procs[
	    iceConn->protosetup_to_me->my_auth_index];
	IcePaAuthStatus status =
	    (*authProc) (iceConn, &iceConn->protosetup_to_me->my_auth_state,
	    swap, replyDataLen, replyData,
	    &authDataLen, &authData, &errorString);
	int free_setup_info = 1;

	if (status == IcePaAuthContinue)
	{
	    AuthNextPhase (iceConn, authDataLen, authData);
	    free_setup_info = 0;
	}
	else if (status == IcePaAuthRejected || status == IcePaAuthFailed)
	{
	    /*
	     * Before we reject, invoke host-based authentication callback
	     * and give it a chance to accept the Protocol Setup (only if the
	     * other client doesn't require authentication).
	     */

	    if (!iceConn->protosetup_to_me->must_authenticate &&
		myProtocol->host_based_auth_proc)
	    {
		char *hostname = _IceGetPeerName (iceConn);

		if ((*myProtocol->host_based_auth_proc) (hostname))
		{
		    status = IcePaAuthAccepted;
		}

		if (hostname)
		    free (hostname);
	    }

	    if (status == IcePaAuthRejected)
	    {
		_IceErrorAuthenticationRejected (iceConn,
	            ICE_AuthReply, errorString);
	    }
	    else
	    {
	        _IceErrorAuthenticationFailed (iceConn,
	            ICE_AuthReply, errorString);
	    }
	}

	if (status == IcePaAuthAccepted)
	{
	    IcePaProcessMsgProc	processMsgProc;
	    IceProtocolSetupProc protocolSetupProc;
	    IceProtocolActivateProc protocolActivateProc;
	    _IceProcessMsgInfo *process_msg_info;
	    IcePointer clientData = NULL;
	    char *failureReason = NULL;
	    Status status = 1;

	    protocolSetupProc = myProtocol->protocol_setup_proc;
	    protocolActivateProc = myProtocol->protocol_activate_proc;

	    if (protocolSetupProc)
	    {
		/*
		 * Notify the client of the Protocol Setup.
		 */

		status = (*protocolSetupProc) (iceConn,
		    myProtocol->version_recs[iceConn->protosetup_to_me->
		        my_version_index].major_version,
		    myProtocol->version_recs[iceConn->protosetup_to_me->
		        my_version_index].minor_version,
		    iceConn->protosetup_to_me->his_vendor,
		    iceConn->protosetup_to_me->his_release,
		    &clientData, &failureReason);

		/*
		 * Set vendor and release pointers to NULL, so it won't
		 * get freed below.  The ProtocolSetupProc should
		 * free it.
		 */

		iceConn->protosetup_to_me->his_vendor = NULL;
		iceConn->protosetup_to_me->his_release = NULL;
	    }

	    if (status != 0)
	    {
		/*
		 * Send the Protocol Reply
		 */

		AcceptProtocol (iceConn,
	            iceConn->protosetup_to_me->his_opcode,
	            iceConn->protosetup_to_me->my_opcode,
	            iceConn->protosetup_to_me->his_version_index,
		    myProtocol->vendor, myProtocol->release);


		/*
		 * Set info for this protocol.
		 */

		processMsgProc = myProtocol->version_recs[
	            iceConn->protosetup_to_me->
	            my_version_index].process_msg_proc;

		process_msg_info = &iceConn->process_msg_info[
	            iceConn->protosetup_to_me->
		    his_opcode -iceConn->his_min_opcode];

		process_msg_info->client_data = clientData;
		process_msg_info->accept_flag = 1;
		process_msg_info->process_msg_proc.
		    accept_client = processMsgProc;


		/*
		 * Increase the reference count for the number
		 * of active protocols.
		 */

		iceConn->proto_ref_count++;


		/*
		 * Notify the client that the protocol is active.  The reason
		 * we have this 2nd callback invoked is because the client
		 * may wish to immediately generate a message for this
		 * protocol, but it must wait until we send the Protocol Reply.
		 */

		if (protocolActivateProc)
		{
		    (*protocolActivateProc) (iceConn,
		        process_msg_info->client_data);
		}
	    }
	    else
	    {
		/*
		 * An error was encountered.
		 */

		_IceErrorSetupFailed (iceConn, ICE_ProtocolSetup,
		    failureReason);

		if (failureReason)
		    free (failureReason);
	    }
	}


	if (free_setup_info)
	{
	    if (iceConn->protosetup_to_me->his_vendor)
		free (iceConn->protosetup_to_me->his_vendor);
	    if (iceConn->protosetup_to_me->his_release)
		free (iceConn->protosetup_to_me->his_release);
	    free ((char *) iceConn->protosetup_to_me);
	    iceConn->protosetup_to_me = NULL;
	}
    }
    else
    {
	/*
	 * Unexpected message
	 */

	_IceErrorBadState (iceConn, 0, ICE_AuthReply, IceCanContinue);
    }

    if (authData && authDataLen > 0)
	free ((char *) authData);

    if (errorString)
	free (errorString);

    IceDisposeCompleteMessage (iceConn, replyData);
    return (0);
}



static Bool
ProcessAuthNextPhase (iceConn, length, swap, replyWait)

IceConn		  	iceConn;
unsigned long	 	length;
Bool			swap;
IceReplyWaitInfo	*replyWait;

{
    iceAuthNextPhaseMsg *message;
    int 		authDataLen;
    IcePointer		authData;
    int 		replyDataLen;
    IcePointer		replyData = NULL;
    char		*errorString = NULL;
    IcePoAuthProc 	authProc;
    IcePoAuthStatus	status;
    IcePointer 		*authState;

    CHECK_AT_LEAST_SIZE (iceConn, ICE_AuthNextPhase,
	length, SIZEOF (iceAuthNextPhaseMsg),
	iceConn->connect_to_you ? IceFatalToConnection : IceFatalToProtocol);

    IceReadCompleteMessage (iceConn, SIZEOF (iceAuthNextPhaseMsg),
	iceAuthNextPhaseMsg, message, authData);

    if (!IceValidIO (iceConn))
    {
	IceDisposeCompleteMessage (iceConn, authData);
	return (0);
    }

    if (swap)
    {
	message->authDataLength = lswaps (message->authDataLength);
    }

    CHECK_COMPLETE_SIZE (iceConn, ICE_AuthNextPhase, length,
	message->authDataLength + SIZEOF (iceAuthNextPhaseMsg), authData,
	iceConn->connect_to_you ? IceFatalToConnection : IceFatalToProtocol);

    if (iceConn->connect_to_you)
    {
	authProc = _IcePoAuthProcs[
	    iceConn->connect_to_you->my_auth_index];

	authState = &iceConn->connect_to_you->my_auth_state;
    }
    else if (iceConn->protosetup_to_you)
    {
	_IcePoProtocol *myProtocol =
	  _IceProtocols[iceConn->protosetup_to_you->my_opcode - 1].orig_client;

	authProc = myProtocol->auth_procs[
	    iceConn->protosetup_to_you->my_auth_index];

	authState = &iceConn->protosetup_to_you->my_auth_state;
    }
    else
    {
	/*
	 * Unexpected message
	 */

	_IceErrorBadState (iceConn, 0, ICE_AuthNextPhase, IceCanContinue);

	IceDisposeCompleteMessage (iceConn, authData);
	return (0);
    }

    authDataLen = message->authDataLength;

    status = (*authProc) (iceConn, authState, False /* don't clean up */,
	swap, authDataLen, authData, &replyDataLen, &replyData, &errorString);

    if (status == IcePoAuthHaveReply)
    {
	AuthReply (iceConn, replyDataLen, replyData);

	replyWait->sequence_of_request = iceConn->send_sequence;
    }
    else if (status == IcePoAuthRejected || status == IcePoAuthFailed)
    {
	char *prefix, *returnErrorString;

	if (status == IcePoAuthRejected)
	{
	    _IceErrorAuthenticationRejected (iceConn,
	       ICE_AuthNextPhase, errorString);

	    prefix = "Authentication Rejected, reason : ";
	}
	else if (status == IcePoAuthFailed)
	{
	    _IceErrorAuthenticationFailed (iceConn,
	       ICE_AuthNextPhase, errorString);

	    prefix = "Authentication Failed, reason : ";
	}

	returnErrorString = (char *) malloc (strlen (prefix) +
	    strlen (errorString) + 1);
	sprintf (returnErrorString, "%s%s", prefix, errorString);
	free (errorString);

	if (iceConn->connect_to_you)
	{
	    _IceConnectionError *errorReply =
	        &(((_IceReply *) (replyWait->reply))->connection_error);

	    errorReply->type = ICE_CONNECTION_ERROR;
	    errorReply->error_message = returnErrorString;
	}
	else
	{
	    _IceProtocolError *errorReply =
	        &(((_IceReply *) (replyWait->reply))->protocol_error);

	    errorReply->type = ICE_PROTOCOL_ERROR;
	    errorReply->error_message = returnErrorString;
	}
    }

    if (replyData && replyDataLen > 0)
	free ((char *) replyData);

    IceDisposeCompleteMessage (iceConn, authData);

    return (status != IcePoAuthHaveReply);
}



static Bool
ProcessConnectionReply (iceConn, length, swap, replyWait)

IceConn			iceConn;
unsigned long	 	length;
Bool			swap;
IceReplyWaitInfo 	*replyWait;

{
    iceConnectionReplyMsg 	*message;
    char 			*pData, *pStart;
    Bool			replyReady;

    CHECK_AT_LEAST_SIZE (iceConn, ICE_ConnectionReply,
	length, SIZEOF (iceConnectionReplyMsg), IceFatalToConnection);

    IceReadCompleteMessage (iceConn, SIZEOF (iceConnectionReplyMsg),
	iceConnectionReplyMsg, message, pStart);

    if (!IceValidIO (iceConn))
    {
	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    pData = pStart;

    SKIP_STRING (pData, swap);				     /* vendor */
    SKIP_STRING (pData, swap);				     /* release */

    CHECK_COMPLETE_SIZE (iceConn, ICE_ConnectionReply,
	length, pData - pStart + SIZEOF (iceConnectionReplyMsg),
	pStart, IceFatalToConnection);

    pData = pStart;

    if (iceConn->connect_to_you)
    {
	if (iceConn->connect_to_you->auth_active)
	{
	    /*
	     * Tell the authentication procedure to clean up.
	     */

	    IcePoAuthProc authProc = _IcePoAuthProcs[
		iceConn->connect_to_you->my_auth_index];

	    (*authProc) (iceConn, &iceConn->connect_to_you->my_auth_state,
		True /* clean up */, False /* swap */,
	        0, NULL, NULL, NULL, NULL);
	}

	if ((int) message->versionIndex >= _IceVersionCount)
	{
	    _IceConnectionError *errorReply =
	        &(((_IceReply *) (replyWait->reply))->connection_error);
	    char errIndex = message->versionIndex;

	    _IceErrorBadValue (iceConn, 0,
		ICE_ConnectionReply, 2, 1, &errIndex);
	    
	    errorReply->type = ICE_CONNECTION_ERROR;
	    errorReply->error_message =
		"Received bad version index in Connection Reply";
	}
	else
	{
	    _IceReply *reply = (_IceReply *) (replyWait->reply);

	    reply->type = ICE_CONNECTION_REPLY;
	    reply->connection_reply.version_index = message->versionIndex;

	    EXTRACT_STRING (pData, swap, reply->connection_reply.vendor);
	    EXTRACT_STRING (pData, swap, reply->connection_reply.release);
	}

	replyReady = True;
    }
    else
    {
	/*
	 * Unexpected message
	 */

	_IceErrorBadState (iceConn, 0, ICE_ConnectionReply, IceCanContinue);

	replyReady = False;
    }

    IceDisposeCompleteMessage (iceConn, pStart);

    return (replyReady);
}



static
ProcessProtocolSetup (iceConn, length, swap)

IceConn		iceConn;
unsigned long	length;
Bool		swap;

{
    iceProtocolSetupMsg	*message;
    _IcePaProtocol 	*myProtocol;
    int  	      	myVersionCount, hisVersionCount;
    int	 	      	myVersionIndex, hisVersionIndex;
    int  	      	hisMajorVersion, hisMinorVersion;
    int	 	      	myAuthCount, hisAuthCount;
    int  	      	myOpcode, hisOpcode;
    int	 	      	found, i, j;
    char	      	*myAuthName, **hisAuthNames;
    char 	      	*protocolName;
    char 		*pData, *pStart;
    char 	      	*vendor = NULL;
    char 	      	*release = NULL;
    int  	      	accept_setup_now = 0;
    int			myAuthIndex = 0;
    int			hisAuthIndex = 0;
    char		mustAuthenticate;
    int			authUsableCount;
    int			authUsableFlags[MAX_ICE_AUTH_NAMES];
    int			authIndices[MAX_ICE_AUTH_NAMES];

    CHECK_AT_LEAST_SIZE (iceConn, ICE_ProtocolSetup,
	length, SIZEOF (iceProtocolSetupMsg), IceFatalToProtocol);

    if (iceConn->want_to_close)
    {
	/*
	 * If we sent a WantToClose message, but just got a ProtocolSetup,
	 * we must cancel our WantToClose.  It is the responsiblity of the
	 * other client to send a WantToClose later on.
	 */

	iceConn->want_to_close = 0;
    }

    IceReadCompleteMessage (iceConn, SIZEOF (iceProtocolSetupMsg),
	iceProtocolSetupMsg, message, pStart);

    if (!IceValidIO (iceConn))
    {
	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    pData = pStart;

    SKIP_STRING (pData, swap);				       /* proto name */
    SKIP_STRING (pData, swap);				       /* vendor */
    SKIP_STRING (pData, swap);				       /* release */
    SKIP_LISTOF_STRING (pData, swap, (int) message->authCount);/* auth names */
    pData += (message->versionCount * 4);		       /* versions */

    CHECK_COMPLETE_SIZE (iceConn, ICE_ProtocolSetup,
	length, pData - pStart + SIZEOF (iceProtocolSetupMsg),
	pStart, IceFatalToProtocol);

    mustAuthenticate = message->mustAuthenticate;

    if (mustAuthenticate != 0 && mustAuthenticate != 1)
    {
	_IceErrorBadValue (iceConn, 0,
	    ICE_ProtocolSetup, 4, 1, &mustAuthenticate);
	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    pData = pStart;

    if (iceConn->process_msg_info &&
	(int) message->protocolOpcode >= iceConn->his_min_opcode &&
        (int) message->protocolOpcode <= iceConn->his_max_opcode &&
	iceConn->process_msg_info[
	message->protocolOpcode - iceConn->his_min_opcode].in_use)
    {
	_IceErrorMajorOpcodeDuplicate (iceConn, message->protocolOpcode);
	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    EXTRACT_STRING (pData, swap, protocolName);

    if (iceConn->process_msg_info)
    {
	for (i = 0;
	    i <= (iceConn->his_max_opcode - iceConn->his_min_opcode); i++)
	{
	    if (iceConn->process_msg_info[i].in_use && strcmp (protocolName,
	        iceConn->process_msg_info[i].protocol->protocol_name) == 0)
	    {
		_IceErrorProtocolDuplicate (iceConn, protocolName);
		free (protocolName);
		IceDisposeCompleteMessage (iceConn, pStart);
		return (0);
	    }
	}
    }

    for (i = 0; i < _IceLastMajorOpcode; i++)
	if (strcmp (protocolName, _IceProtocols[i].protocol_name) == 0)
	    break;

    if (i < _IceLastMajorOpcode &&
        (myProtocol = _IceProtocols[i].accept_client) != NULL)
    {
	hisOpcode = message->protocolOpcode;
	myOpcode = i + 1;
	free (protocolName);
    }
    else
    {
	_IceErrorUnknownProtocol (iceConn, protocolName);
	free (protocolName);
	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    EXTRACT_STRING (pData, swap, vendor);
    EXTRACT_STRING (pData, swap, release);

    if ((hisAuthCount = message->authCount) > 0)
    {
	hisAuthNames = (char **) malloc (hisAuthCount * sizeof (char *));
	EXTRACT_LISTOF_STRING (pData, swap, hisAuthCount, hisAuthNames);
    }

    hisVersionCount = message->versionCount;
    myVersionCount = myProtocol->version_count;

    hisVersionIndex = myVersionIndex = found = 0;

    for (i = 0; i < hisVersionCount && !found; i++)
    {
	EXTRACT_CARD16 (pData, swap, hisMajorVersion);
	EXTRACT_CARD16 (pData, swap, hisMinorVersion);

	for (j = 0; j < myVersionCount && !found; j++)
	{
	    if (myProtocol->version_recs[j].major_version == hisMajorVersion &&
		myProtocol->version_recs[j].minor_version == hisMinorVersion)
	    {
		hisVersionIndex = i;
		myVersionIndex = j;
		found = 1;
	    }
	}
    }

    if (!found)
    {
	_IceErrorNoVersion (iceConn, ICE_ProtocolSetup);

	free (vendor);
	free (release);

	if (hisAuthCount > 0)
	{
	    for (i = 0; i < hisAuthCount; i++)
		free (hisAuthNames[i]);
	
	    free ((char *) hisAuthNames);
	}

	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    myAuthCount = myProtocol->auth_count;

    _IceGetPaValidAuthIndices (
	_IceProtocols[myOpcode - 1].protocol_name,
	iceConn->connection_string, myAuthCount, myProtocol->auth_names,
        &authUsableCount, authIndices);

    for (i = 0; i < myAuthCount; i++)
    {
	authUsableFlags[i] = 0;
	for (j = 0; j < authUsableCount && !authUsableFlags[i]; j++)
	    authUsableFlags[i] = (authIndices[j] == i);
    }

    for (i = found = 0; i < myAuthCount && !found; i++)
    {
	if (authUsableFlags[i])
	{
	    myAuthName = myProtocol->auth_names[i];

	    for (j = 0; j < hisAuthCount && !found; j++)
		if (strcmp (myAuthName, hisAuthNames[j]) == 0)
		{
		    myAuthIndex = i;
		    hisAuthIndex = j;
		    found = 1;
		}
	}
    }

    if (!found)
    {
	/*
	 * None of the authentication methods specified by the
	 * other client is supported.  If the other client requires
	 * authentication, we must reject the Protocol Setup now.
	 * Otherwise, we can invoke the host-based authentication callback
	 * to see if we can accept this Protocol Setup.
	 */

	if (mustAuthenticate || !myProtocol->host_based_auth_proc)
	{
	    _IceErrorNoAuthentication (iceConn, ICE_ProtocolSetup);
	}
	else
	{
	    char *hostname = _IceGetPeerName (iceConn);

	    if ((*myProtocol->host_based_auth_proc) (hostname))
	    {
		accept_setup_now = 1;
	    }
	    else 
	    {
		_IceErrorAuthenticationRejected (iceConn,
	            ICE_ProtocolSetup, "None of the authentication protocols specified are supported and host-based authentication failed");
	    }

	    if (hostname)
		free (hostname);
	}
    }
    else
    {
	IcePaAuthStatus	status;
	int 		authDataLen;
	IcePointer 	authData = NULL;
	IcePointer 	authState;
	char		*errorString = NULL;
	IcePaAuthProc	authProc =
		myProtocol->auth_procs[myAuthIndex];

	authState = NULL;

	status = (*authProc) (iceConn, &authState, swap, 0, NULL,
	    &authDataLen, &authData, &errorString);

	if (status == IcePaAuthContinue)
	{
	    _IceProtoSetupToMeInfo *setupInfo;

	    AuthRequired (iceConn, hisAuthIndex, authDataLen, authData);
	 
	    iceConn->protosetup_to_me = setupInfo =
		(_IceProtoSetupToMeInfo *) malloc (
		sizeof (_IceProtoSetupToMeInfo));

	    setupInfo->his_opcode = hisOpcode;
	    setupInfo->my_opcode = myOpcode;
	    setupInfo->my_version_index = myVersionIndex;
	    setupInfo->his_version_index = hisVersionIndex;
	    setupInfo->his_vendor = vendor;
	    setupInfo->his_release = release;
	    vendor = release = NULL;   /* so we don't free it */
	    setupInfo->my_auth_index = myAuthIndex;
	    setupInfo->my_auth_state = authState;
	    setupInfo->must_authenticate = mustAuthenticate;
	}
	else if (status == IcePaAuthAccepted)
	{
	    accept_setup_now = 1;
	}

	if (authData && authDataLen > 0)
	    free ((char *) authData);

	if (errorString)
	    free (errorString);
    }

    if (accept_setup_now)
    {
	IcePaProcessMsgProc		processMsgProc;
	IceProtocolSetupProc		protocolSetupProc;
	IceProtocolActivateProc		protocolActivateProc;
	_IceProcessMsgInfo		*process_msg_info;
	IcePointer			clientData = NULL;
	char 				*failureReason = NULL;
	Status				status = 1;

	protocolSetupProc = myProtocol->protocol_setup_proc;
	protocolActivateProc = myProtocol->protocol_activate_proc;

	if (protocolSetupProc)
	{
	    /*
	     * Notify the client of the Protocol Setup.
	     */

	    status = (*protocolSetupProc) (iceConn,
		myProtocol->version_recs[myVersionIndex].major_version,
		myProtocol->version_recs[myVersionIndex].minor_version,
	        vendor, release, &clientData, &failureReason);

	    vendor = release = NULL;   /* so we don't free it */
	}

	if (status != 0)
	{
	    /*
	     * Send the Protocol Reply
	     */

	    AcceptProtocol (iceConn, hisOpcode, myOpcode, hisVersionIndex,
	        myProtocol->vendor, myProtocol->release);


	    /*
	     * Set info for this protocol.
	     */

	    processMsgProc = myProtocol->version_recs[
	        myVersionIndex].process_msg_proc;

	    process_msg_info = &iceConn->process_msg_info[hisOpcode -
	        iceConn->his_min_opcode];

	    process_msg_info->client_data = clientData;
	    process_msg_info->accept_flag = 1;
	    process_msg_info->process_msg_proc.accept_client = processMsgProc;


	    /*
	     * Increase the reference count for the number of active protocols.
	     */

	    iceConn->proto_ref_count++;


	    /*
	     * Notify the client that the protocol is active.  The reason
	     * we have this 2nd callback invoked is because the client
	     * may wish to immediately generate a message for this
	     * protocol, but it must wait until we send the Protocol Reply.
	     */

	    if (protocolActivateProc)
	    {
		(*protocolActivateProc) (iceConn,
		    process_msg_info->client_data);
	    }
	}
	else
	{
	    /*
	     * An error was encountered.
	     */

	    _IceErrorSetupFailed (iceConn, ICE_ProtocolSetup, failureReason);

	    if (failureReason)
		free (failureReason);
	}
    }

    if (vendor)
	free (vendor);

    if (release)
	free (release);

    if (hisAuthCount > 0)
    {
	for (i = 0; i < hisAuthCount; i++)
	    free (hisAuthNames[i]);

	free ((char *) hisAuthNames);
    }

    IceDisposeCompleteMessage (iceConn, pStart);
    return (0);
}



static Bool
ProcessProtocolReply (iceConn, length, swap, replyWait)

IceConn		  	iceConn;
unsigned long	 	length;
Bool			swap;
IceReplyWaitInfo 	*replyWait;

{
    iceProtocolReplyMsg *message;
    char		*pData, *pStart;
    Bool		replyReady;

    CHECK_AT_LEAST_SIZE (iceConn, ICE_ProtocolReply,
	length, SIZEOF (iceProtocolReplyMsg), IceFatalToProtocol);

    IceReadCompleteMessage (iceConn, SIZEOF (iceProtocolReplyMsg),
	iceProtocolReplyMsg, message, pStart);

    if (!IceValidIO (iceConn))
    {
	IceDisposeCompleteMessage (iceConn, pStart);
	return (0);
    }

    pData = pStart;

    SKIP_STRING (pData, swap);				     /* vendor */
    SKIP_STRING (pData, swap);				     /* release */

    CHECK_COMPLETE_SIZE (iceConn, ICE_ProtocolReply,
	length, pData - pStart + SIZEOF (iceProtocolReplyMsg),
	pStart, IceFatalToProtocol);

    pData = pStart;

    if (iceConn->protosetup_to_you)
    {
	if (iceConn->protosetup_to_you->auth_active)
	{
	    /*
	     * Tell the authentication procedure to clean up.
	     */

	    _IcePoProtocol *myProtocol = _IceProtocols[
		iceConn->protosetup_to_you->my_opcode - 1].orig_client;

	    IcePoAuthProc authProc = myProtocol->auth_procs[
		iceConn->protosetup_to_you->my_auth_index];

#ifdef SVR4

/*
 * authProc is never NULL, but the cc compiler on UNIX System V/386
 * Release 4.2 Version 1 screws up an optimization.  Unless there is
 * some sort of reference to authProc before the function call, the
 * function call will seg fault.
 */
	    if (authProc)
#endif
		(*authProc) (iceConn,
		&iceConn->protosetup_to_you->my_auth_state,
		True /* clean up */, False /* swap */,
	        0, NULL, NULL, NULL, NULL);
	}

	if ((int) message->versionIndex >= _IceVersionCount)
	{
	    _IceProtocolError *errorReply =
	        &(((_IceReply *) (replyWait->reply))->protocol_error);
	    char errIndex = message->versionIndex;

	    _IceErrorBadValue (iceConn, 0,
		ICE_ProtocolReply, 2, 1, &errIndex);
	    
	    errorReply->type = ICE_PROTOCOL_ERROR;
	    errorReply->error_message =
		"Received bad version index in Protocol Reply";
	}
	else
	{
	    _IceProtocolReply *reply = 
	        &(((_IceReply *) (replyWait->reply))->protocol_reply);

	    reply->type = ICE_PROTOCOL_REPLY;
	    reply->major_opcode = message->protocolOpcode;
	    reply->version_index = message->versionIndex;

	    EXTRACT_STRING (pData, swap, reply->vendor);
	    EXTRACT_STRING (pData, swap, reply->release);
	}

	replyReady = True;
    }
    else
    {
	_IceErrorBadState (iceConn, 0, ICE_ProtocolReply, IceCanContinue);

	replyReady = False;
    }

    IceDisposeCompleteMessage (iceConn, pStart);

    return (replyReady);
}



static
ProcessPing (iceConn, length)

IceConn 	iceConn;
unsigned long	length;

{
    CHECK_SIZE_MATCH (iceConn, ICE_Ping,
	length, SIZEOF (icePingMsg), IceFatalToConnection);

    PingReply (iceConn);

    return (0);
}



static
ProcessPingReply (iceConn, length)

IceConn 	iceConn;
unsigned long	length;

{
    CHECK_SIZE_MATCH (iceConn, ICE_PingReply,
	length, SIZEOF (icePingReplyMsg), IceFatalToConnection);

    if (iceConn->ping_waits)
    {
	_IcePingWait *next = iceConn->ping_waits->next;
	
	(*iceConn->ping_waits->ping_reply_proc) (iceConn,
	    iceConn->ping_waits->client_data);

	free ((char *) iceConn->ping_waits);
	iceConn->ping_waits = next;
    }
    else
    {
	_IceErrorBadState (iceConn, 0, ICE_PingReply, IceCanContinue);
    }

    return (0);
}



static
ProcessWantToClose (iceConn, length, connectionClosedRet)

IceConn 	iceConn;
unsigned long	length;
Bool		*connectionClosedRet;

{
    *connectionClosedRet = False;

    CHECK_SIZE_MATCH (iceConn, ICE_WantToClose,
	length, SIZEOF (iceWantToCloseMsg), IceFatalToConnection);

    if (iceConn->want_to_close || iceConn->open_ref_count == 0)
    {
	/*
	 * We just received a WantToClose.  Either we also sent a
	 * WantToClose, so we close the connection, or the iceConn
	 * is not being used, so we close the connection.  This
	 * second case is possible if we sent a WantToClose because
	 * the iceConn->open_ref_count reached zero, but then we
	 * received a NoClose.
	 */

	_IceConnectionClosed (iceConn);		/* invoke watch procs */
	_IceFreeConnection (iceConn);
	*connectionClosedRet = True;
    }
    else if (iceConn->proto_ref_count > 0)
    {
	/*
	 * We haven't shut down all of our protocols yet.  We send a NoClose,
	 * and it's up to us to generate a WantToClose later on.
	 */

	IceSimpleMessage (iceConn, 0, ICE_NoClose);
	IceFlush (iceConn);
    }
    else
    {
	/*
	 * The reference count on this iceConn is zero.  This means that
	 * there are no active protocols, but the client didn't explicitly
	 * close the connection yet.  If we didn't just send a Protocol Setup,
	 * we send a NoClose, and it's up to us to generate a WantToClose
	 * later on.
	 */

	if (!iceConn->protosetup_to_you)
	{
	    IceSimpleMessage (iceConn, 0, ICE_NoClose);
	    IceFlush (iceConn);
	}
    }

    return (0);
}



static
ProcessNoClose (iceConn, length)

IceConn 	iceConn;
unsigned long	length;

{
    CHECK_SIZE_MATCH (iceConn, ICE_NoClose,
	length, SIZEOF (iceNoCloseMsg), IceFatalToConnection);

    if (iceConn->want_to_close)
    {
	/*
	 * The other side can't close now.  We cancel our WantToClose,
	 * and we can expect a WantToClose from the other side.
	 */

	iceConn->want_to_close = 0;
    }
    else
    {
	_IceErrorBadState (iceConn, 0, ICE_NoClose, IceCanContinue);
    }

    return (0);
}



void
_IceProcessCoreMessage (iceConn, opcode, length, swap,
    replyWait, replyReadyRet, connectionClosedRet)

IceConn 	 iceConn;
int     	 opcode;
unsigned long	 length;
Bool    	 swap;
IceReplyWaitInfo *replyWait;
Bool		 *replyReadyRet;
Bool		 *connectionClosedRet;

{
    Bool replyReady = False;

    *connectionClosedRet = False;

    switch (opcode)
    {
    case ICE_Error:

	replyReady = ProcessError (iceConn, length, swap, replyWait);
	break;

    case ICE_ConnectionSetup:

	ProcessConnectionSetup (iceConn, length, swap);
	break;

    case ICE_AuthRequired:

	replyReady = ProcessAuthRequired (iceConn, length, swap, replyWait);
        break;

    case ICE_AuthReply:

	ProcessAuthReply (iceConn, length, swap);
	break;

    case ICE_AuthNextPhase:

	replyReady = ProcessAuthNextPhase (iceConn, length, swap, replyWait);
	break;

    case ICE_ConnectionReply:

	replyReady = ProcessConnectionReply (iceConn, length, swap, replyWait);
	break;

    case ICE_ProtocolSetup:

	ProcessProtocolSetup (iceConn, length, swap);
	break;

    case ICE_ProtocolReply:

	replyReady = ProcessProtocolReply (iceConn, length, swap, replyWait);
	break;

    case ICE_Ping:

	ProcessPing (iceConn, length);
	break;

    case ICE_PingReply:

	ProcessPingReply (iceConn, length);
	break;

    case ICE_WantToClose:

	ProcessWantToClose (iceConn, length, connectionClosedRet);
	break;

    case ICE_NoClose:

	ProcessNoClose (iceConn, length);
	break;

    default:

	_IceErrorBadMinor (iceConn, 0, opcode, IceCanContinue);
	_IceReadSkip (iceConn, length << 3);
	break;
    }

    if (replyWait)
	*replyReadyRet = replyReady;
}