File: comm.c

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

/* Floater is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */

/* This software is provided "as is" and comes with absolutely no */
/* warranties.  Geoff Pike is not liable for damages under any */
/* circumstances.  Support is not provided.  Use at your own risk. */

/* Personal, non-commercial use is allowed.  Attempting to make money */
/* from Floater or products or code derived from Floater is not allowed */
/* without prior written consent from Geoff Pike.  Anything that remotely */
/* involves commercialism, including (but not limited to) systems that */
/* show advertisements while being used and systems that collect */
/* information on users that is later sold or traded require prior */
/* written consent from Geoff Pike. */
#include <tcl.h>
#include <tk.h>
/* #include <sys/types.h> */
/* #include <sys/socket.h> */
/* #include <netinet/in.h> */
/* #include <arpa/inet.h> */
/* #include <netdb.h> */
/* #include <sys/param.h> */
#include "floater.h"
#include "comm.h"
#include "br.h"
#include "deal.h"
#include "calendar.h"


/*
   Basic idea: A tree of tables (or rooms, if you prefer that
   metaphor).  Each node in the table tree is also the root of a tree
   of people (kibitzers and players) at that table.  When someone says
   something, normally it is broadcast to everyone at the table.  To
   join either sort of tree, you send a message to anyone in the tree
   requesting to join.  You then get a message back telling you
   whether it is OK (if not, you may be "shunted"---told an alternate
   place to try to join).
   
   When someone joins a table, that fact is broadcast to the table.
   When a new table starts, that fact is broadcast to everyone at all tables.
   
   If you are hosting a table and you get unexpectedly disconnected
   from your parent, you attempt to rejoin the table tree.  Being
   connected to the table tree is considered non-critical---if you
   miss a few messages, no big deal.  Play at your table may continue
   while you (in the background) try to rejoin the table tree.  Being
   connected to the kibitzer tree is critical, so attempting to have
   an automatic rejoin mechanism is messy (it was tried, and worked at
   one time, but the new way seems cleaner).  Therefore, the kibitzer
   tree is one-level only, i.e., everyone is connected to the table
   host.

   [Old design:  If you get unexpectedly disconnected from your parent, you
   automatically attempt to reconnect to the same place.  If that
   fails, you try connecting to the root of the table tree (if you
   were a table host) or the root of the kibitzer tree (if you were a
   kibitzer at a table).]

   This code is not very specific to bridge.  Anything relating to lho
   or rho or a compass direction is bridge related, and a few things
   are bracketed by comments saying "bridge specific."  The rest is
   generic.  */

#define isspec(x) FALSE

#define BOGUS_NAME " - BOGUS - "

#ifdef LOGINSERVER
#define MAXTCHILDREN 1
#else
#define MAXTCHILDREN 4
#endif

/* if I become a table server, do I try to connect to the table tree? */
#define jointableservertree TclBool("jointableservertree")

char myname[FLOATER_MAXNAME+1] = {'\0'};
char myoutputname[FLOATER_MAXNAME+1] = {'\0'};
semistatic char *mytabledesc = NULL; /* number of players, etc., plus the note */
semistatic char *mynote = NULL; /* just the note */

char tablehostname[FLOATER_MAXNAME+1] = {'?', '\0'};
semistatic char tablehostaddr[MAXADDRLEN+1] = {'\0'};
semistatic char tablehostport[MAXPORTLEN+1] = {'\0'};
semistatic char tablerootname[FLOATER_MAXNAME+1] = {'?', '\0'};
semistatic char tablerootaddr[MAXADDRLEN+1] = {'\0'};
semistatic char tablerootport[MAXPORTLEN+1] = {'\0'};

char loginservername[FLOATER_MAXNAME+1] = {'\0'};
char loginserveraddr[MAXADDRLEN+1] = {'\0'};
char loginserverport[MAXPORTLEN+1] = {'\0'};

char resultservername[FLOATER_MAXNAME+1] = {'\0'};
char resultserveraddr[MAXADDRLEN+1] = {'\0'};
char resultserverport[MAXPORTLEN+1] = {'\0'};

#ifndef SERVER
char location[200] = {'\0'};
#endif

bool triedtologin = FALSE;
bool loggedin = FALSE;
bool canhost = FALSE;

/* whether I am root of the table tree */
semistatic bool tablerootmode = FALSE;

/* whether I am hosting a table */
bool tablehostmode = FALSE;

#define accepting_tableservers tablehostmode

#define nokibitzers TclBool("nokibitzers")
#define accepting_kibitzers (!nokibitzers && tablehostmode && \
			     (state == CONNECTED))

#define if_not_connected_reset_tablehostname() \
     if (state != CONNECTED) \
       tablehostname[0] = tablehostport[0] = tablehostaddr[0] = '\0';


int state = LIMBO;

/* hostname and IP address of machine we're on */
char *localIPaddr = NULL;

/* IP address of machine we're running on */
char *localIPaddr0 = NULL;

/* port we're listening on locally */
semistatic char *localport = NULL;

semistatic char *Floater_hostname = NULL;

semistatic char *connstr = NULL;

/* typedef int (*rejoinptr)(char *, char *, char *, int); */

static char rejoinaddr[MAXADDRLEN];
static char rejoinport[MAXPORTLEN];
static char rejoincap[2];
static int rejoinnumtries = NUMTRIES;

static stringlist *who = NULL; /* who is at the table */

/* if we get a JOIN_ELSEWHERE message, do we believe it? */
static bool expecting_join_elsewhere = FALSE;

/* When changing your password, new password stored here */
static char *newpw = NULL;

/* When changing your email, new email address stored here */
static char *newemail = NULL;

/* a few forward declarations */
static void sendstrmessage(char *to, char *s);
static char *msgtotext(message *m);
static void rebroadcast(message *m);
static void handlemessage(message *m, char *msg);
static void announce_who(void);
static void announce_tables(void);
static void rejoin(void);
static void setmyname(char *newname, bool loggedin);
static void disconnect_all(void);
static char *connect_to_resultserver(void);
static int openport(char *port);

#define defaultnote TclDo("gset defaultnote")

#define time_to_rejoin() atoi(TclDo("rejoinnow"))
#define reset_time_to_rejoin() TclDo("reset_rejoinnow")
#define time_to_find_rho() atoi(TclDo("findrhonow"))
#define reset_time_find_rho() TclDo("reset_find_rho")

#define isparentfile(x) ((parent != NULL) && streq((x), parent->connstr))
#define isparentname(x) ((parent != NULL) && streq((x), parent->name))
#define iskchildname(x) (namemember(x, kchildren))
#define iskchildfile(x) (filemember(x, kchildren))
#define istchildname(x) (namemember(x, tchildren))
#define istchildfile(x) (filemember(x, tchildren))

#ifdef LOGINSERVER
#define testConn(IPaddr, port, s) \
    tempcat((s), TclDo5("testConn {", (IPaddr), "} {", (port) , "}"))

#define nameinuse(name) atoi(TclDo3("global nameinuse; info exists {nameinuse(", \
				    upcase(name), ")}"))

void newaccount(char *name, char *email)
{
  char password[9], bits[48];
  int i;
  char *upname = upcase(name); 

  /* put 48 random bits in bits[] */
  churnsimpleseed(name);
  putbits(unifmod(1 << 24), 24, bits);
  putbits(unifmod(1 << 24), 24, bits + 24);
  
  /* Convert 48 random bits into 8 printable characters */
  put6atatime(bits, 48, password);
/*  password[8] = '\0';*/
  password[5] = '\0';
  for (i = 0; i < 5; i++)
    if (password[i] == '0' || password[i] == 'O') password[i] = '3';
    else if (password[i] == '1' || password[i] == 'l') password[i] = '4';

  TclDo3("permset {nameinuse(", upname, ")} 1");
  TclDo3("permdo {lappend names {", name, "}}");
  TclDo7("newaccount {", name, "} {", email, "} {", password, "}");
}
/* #define correctly_capitalized_name(name) TclDo3("name_fetch {", (name), "}") */
/* #define password(name) TclDo3("password_fetch {", (name), "}") */
#define password(name) TclDo3("tryget {pw(", (name), ")}")
#define email_info(name) TclDo3("tryget_nocase email {", (name), "}")
#define have_email_info(name) (strlen(email_info(name)) > 0)
#define set_location_info(name, info)				\
    TclDo7("gset {lastlocation(", upcase(name), ")} {", (info), "};"	\
	   "gset {lastlocation_timestamp(", upcase(name), ")}"	\
	   " [gset floaterclock]")
#define location_info(name) TclDo3("tryget {lastlocation(", upcase(name), ")}")
#define have_location_info(name) (strlen(location_info(name)) > 0)
#define user_exists(name) nameinuse(name)

void savenewpw(char *name, char *pw)
{
  TclDo5("permset {pw(", name, ")} {", pw, "}");
  /* TclDo5("uplevel #0 set {pwx(", upcase(name), ")} {", name, "}"); */
}

void savenewemail(char *name, char *x)
{
  TclDo5("permset {email(", name, ")} {", x, "}");
}
#endif /* LOGINSERVER */

/*****************************************************************************
Code for keeping track of all the tables out there
*****************************************************************************/

/* 
   A tablelist will be implemented as a stringlist with alternating entries:
   a name, then a description of that table, then its IP address, then port.
*/
typedef stringlist tablelist;

static tablelist *tables = NULL;

#define tabletimestamp(l) (((stringlist *) l)->s)
#define tablename(l) (((stringlist *) l)->next->s)
#define tabledescription(l) (((stringlist *) l)->next->next->s)
#define tableIPaddr(l) (((stringlist *) l)->next->next->next->s)
#define tableport(l) (((stringlist *) l)->next->next->next->next->s)
#define nexttable(l) (((stringlist *) l)->next->next->next->next->next)
#define freetablelist(l) (freestringlist(freestringlist(freestringlist(freestringlist(freestringlist((stringlist *) (l)))))))

#ifdef LOGINSERVER
static void update_activity_webpage_with_table_info()
{
  int k;
  tablelist *l;
  char *s = salloc(15000);

  fputs("update_activity_webpage_with_table_info()\n", stderr);
  s[0] = '\0';
  for (l = tables; (k = strlen(s)) < 14500 && l != NULL; l = nexttable(l))
    sprintf(s + k, "<br><b>%s</b>: %s",
	    outputname(tablename(l)), tabledescription(l));
  
  TclDo5("notetables {", STRDUP(s), "} {", floatertime(), "}");
  sfree(s);
}
#else /* not loginserver */
#define update_activity_webpage_with_table_info()
#endif


static tablelist *updatetabletimestamp(tablelist *table)
{
  reset(tabletimestamp(table));
  tabletimestamp(table) = STRDUP(TclGet("floaterclock"));
  return table;
}

static tablelist *constable(char *name, char *description, char *IPaddr,
			    char *port, tablelist *tables)
{
  return updatetabletimestamp(consstringlist(STRDUP(""),
			       consstringlist(STRDUP(name),
				consstringlist(STRDUP(description),
				 consstringlist(STRDUP(IPaddr),
				  consstringlist(STRDUP(port), tables))))));
}

static int membertablelist(char *s)
{
  tablelist *l;

  for (l = tables; l != NULL; l = nexttable(l))
    if (streq(tablename(l), s)) return TRUE;

  return FALSE;
}

static int omembertablelist(char *os)
{
  tablelist *l;

  for (l = tables; l != NULL; l = nexttable(l))
    if (streq(outputname(tablename(l)), os)) return TRUE;

  return FALSE;
}

/* add name/description to the list of tables */
/* if a table of the given name already exists, just change the description */
/* also, update the timestamp */
static void addtable(char *name, char *description, char *IPaddr, char *port)
{
  tablelist *l;
  char *oname = outputname(name);

  if (strlen(oname) > FLOATER_MAXNAME)
    oname = markgarbage(STRNDUP(oname, FLOATER_MAXNAME));
    
  /*  printf("addtable(%s, %s)\n", name, description); */

  for (l = tables; l != NULL; l = nexttable(l))
    if (streq(outputname(tablename(l)), oname)) {
      if (description != NULL && strlen(description) > 0) {
	markgarbage(tabledescription(l));
	tabledescription(l) = STRDUP(description);
	if (hasWindows) {
	    char x[FLOATER_MAXNAME + 5];

	      sprintf(x, "%12s ", oname);
	        TclDo6("join_menu_add_table {", oname, "} "
		        "{", x, description, "}");
		}
      }
      updatetabletimestamp(l);
      return;
    }

  if (!streq(name, myname)) status2(outputname(name), " is now hosting a table.");
  tables = constable(name, description, IPaddr, port, tables);
  if (hasWindows) {
    char x[FLOATER_MAXNAME + 5];
    
    sprintf(x, "%12s ", oname);
    TclDo6("join_menu_add_table {", oname, "} "
	      "{", x, description, "}");
  }
}

static tablelist *removetable(char *name, tablelist *l)
{
/*  printf("removetable(%s)\n", name);*/
  if (l == NULL) return NULL;
  else if (streq(tablename(l), name)) {
    char *oname = outputname(name);

    status2(oname, " is no longer hosting a table.");
    TclDo3("FloaterCloseName {", name, "}");
    if (hasWindows) TclDo3("join_menu_remove_table {", oname, "}");
    return freetablelist(l);
  }
  else nexttable(l) = removetable(name, nexttable(l));
  return l;
}

void describetable(char *note)
{
  extern int scoremethod;
  char *s;

  s = markgarbage(salloc(sizeof(char) * (strlen(note) + 50)));
  sprintf(s, "%10s %3d  %s",
	  TEMPCAT((NONCOMPETITIVE() ? "nc" : "  "),
		  scoringmethods[scoremethod].scoringname),
	  length(who), note);
  if (mytabledesc != NULL && streq(mytabledesc, s)) return;
  if (mynote != note) {
    reset(mynote);
    mynote = STRDUP(note);
  }
  reset(mytabledesc);
  mytabledesc = STRDUP(s);
  addtable(myname, s, localIPaddr, localport);
  broadcast(makemsg4(ANNOUNCE_TABLE, myname, s, localIPaddr, localport));
}		     

/* used when something other than the note changes */
void redescribetable(void)
{
  assert(mynote != NULL);
  describetable(mynote);
}

/* Take t, the name of a table, and put the address and port for it into
   addr and port.  Requires exact match except case is ignored.
   Returns a boolean: whether it succeeded. */
bool tableaddr(char *t, char *addr, char *port)
{
  tablelist *l;

  for (l = tables; l != NULL; l = nexttable(l))
    if (strcaseeq(outputname(tablename(l)), t)) {
      strcpy(addr, tableIPaddr(l));
      strcpy(port, tableport(l));
      return TRUE;
    }
  return FALSE;
}

/***************************************************************************
What follows is for keeping track of connections to parents, children, 
who is at the table, etc.

Note that the connection to the loginserver, if any, is not maintained
here, except in the case of the tableroot which has the loginserver as
its parent.

These routines merely maintain our internal representation---they
usually do not issue Tcl commands to create or destroy connections.
***************************************************************************/

typedef struct conn {
  char *name, *IPaddr, *port, *connstr;
} conn;

typedef struct childlist {
  conn *c;
  struct childlist *next;
} childlist;

static conn *parent = NULL;
static conn *oldparent = NULL; /* used when we get a JOIN_ELSEWHERE request */


static conn *lho = NULL, *rho = NULL;

/* end of bridge specific things */

static childlist *kchildren = NULL;
static childlist *tchildren = NULL;

static void announce_disconn(char *s);

static int namemember(char *name, childlist *l)
{
  while (l != NULL)
    if (streq(name, l->c->name)) return TRUE;
    else l = l->next;
  return FALSE;
}

static int filemember(char *file, childlist *l)
{
  while (l != NULL)
    if (streq(file, l->c->connstr)) return TRUE;
    else l = l->next;
  return FALSE;
}

static conn *makeconn(char *name, char *IPaddr, char *port, char *connstr)
{
  conn *newc;

  newc = alloc(conn);
  newc->name = STRNDUP(name, FLOATER_MAXNAME);
  newc->IPaddr = STRNDUP(IPaddr, MAXADDRLEN);
  newc->port = STRNDUP(port, MAXPORTLEN);
  newc->connstr = STRDUP(connstr);
  return newc;
}

/* add a child to the list of children */
static void addchild(childlist **children, char *name, char *IPaddr, char *port, char *connstr)
{
  childlist *newlist;

#if DEBUGCONN
  DEBUG(talkmsg2("New child: ", name));
  DEBUG(talkmsg4("New child: ", IPaddr, ":", port));
  DEBUG(talkmsg2("New child: ", connstr));
#endif

  newlist = alloc(childlist);
  newlist->c = makeconn(name, IPaddr, port, connstr);
  newlist->next = *children;
  *children = newlist;

  /* do we have an old connection to this IPaddr:port?  If so, close it */
  /* (this should never happen) */
  for (newlist = (*children)->next; newlist != NULL; newlist = newlist->next)
    if (streq(newlist->c->IPaddr, IPaddr) && streq(newlist->c->port, port))
      TclDo3("catch {FloaterClose ", newlist->c->connstr, "}");
}

static void freeconn(conn *c)
{
  if (c == NULL) return;
#if DEBUGCONN
  DEBUG(talkmsg3(myname, "is removing connection to ", c->name));
  DEBUG(talkmsg4("Removing connection: ", c->IPaddr, ":", c->port));
  DEBUG(talkmsg2("Removing connection: ", c->connstr));
#endif
  markgarbage(c->name);
  markgarbage(c->IPaddr);
  markgarbage(c->port);
  markgarbage(c->connstr);
  markgarbage((char *) c);
}

/* frees memory used by a childlist node, and returns the contents of `next' */
static childlist *freechild(childlist *l)
{
  childlist *ret;

  if (l == NULL) return NULL; else ret = l->next;

  freeconn(l->c);
  markgarbage((char *) l);

  return ret;
}

#define removekchild(f, a) removechild(&kchildren, (f), (a))
#define removetchild(f, a) removechild(&tchildren, (f), (a))

static void removechild(childlist **children, char *connstr, bool announce)
{
  childlist *l;

#if DEBUGCONN
  if (hasWindows)
    printf("%s: removechild %s\n", myname, connstr);
#endif
  if (*children == NULL) {
#if DEBUGCONN
    DEBUG(warningmsg3("Attempting to remove child (", connstr, ") that isn't here"));
#endif
    return;
  }

  if (streq((*children)->c->connstr, connstr)) {
    char *name = TEMPCOPY((*children)->c->name);
    *children = freechild(*children);
    if (announce) announce_disconn(name);
    return;
  }
  
  for (l = *children; l->next != NULL; l = l->next)
    if (streq(l->next->c->connstr, connstr)) {
      char *name = TEMPCOPY(l->next->c->name);
      l->next = freechild(l->next);
      if (announce) announce_disconn(name);
      return;
    }
  
#if DEBUGCONN
  DEBUG(warningmsg3("Attempted to remove kchild (", connstr, ") that isn't here"));
#endif
}    

void showparent(void)
{
  if (parent == NULL) 
    status("No parent");
  else
    status7("Parent: ", parent->name, " (", parent->IPaddr, ":",
	    parent->port, ")");
}
  
void showip(void)
{
  if (openport(NULL) < 0) {
    errormsg("Unable to open a port locally; others may not connect to you.");
    return;
  }

  status4("Others may connect to you at ", localIPaddr0, ":", localport);
}

void showkchildren(void)
{
  childlist *l;
  char s[1000];

  if (kchildren == NULL) {
    status("No kchildren");
    return;
  }
  strcpy(s, "Kchildren:");
  for (l = kchildren; l != NULL && strlen(s) < 999 - FLOATER_MAXNAME; l = l->next)
    sprintf(s + strlen(s), " %s", l->c->name);
  status(s);
}

void showtchildren(void)
{
  childlist *l;
  char s[1000];

  if (tchildren == NULL) {
    status("No tchildren");
    return;
  }
  strcpy(s, "Tchildren:");
  for (l = tchildren; l != NULL && strlen(s) < 999 - FLOATER_MAXNAME; l = l->next)
    sprintf(s + strlen(s), " %s", l->c->name);
  status(s);
}

void showchildren(void) { showkchildren(); showtchildren(); }

#define sendtokchildren(s, except) sendtochildren(kchildren, (s), (except))
#define sendtotchildren(s, except) sendtochildren(tchildren, (s), (except))

/* Send s to all members of l except for those that match no_send. */
static void sendtochildren(childlist *l, char *s, char *no_send)
{
  while (l != NULL) {
    if (no_send == NULL || !streq(no_send, l->c->connstr))
      sendstrmessage(l->c->connstr, s);
     l = l->next;
  }
}

void sendtoallchildren(message *m)
{
  char *s = msgtotext(m);
  
  sendtokchildren(s, NULL);
  sendtotchildren(s, NULL);
}

/* add someone to the "who" list */
void addwho(char *s)
{
  int oldlen = length(who);

  who = addstringlist(s, who);
  if (oldlen == length(who)) return;
  if (!streq(s, myname))
    status4(outputname(s), " has joined (", itoa(length(who)), ").");
#if DEBUGCONN
  else status4(outputname(s), " has joined (", itoa(length(who)), ").");
#endif
}

/* remove someone from the "who" list */
void removewho(char *s)
{
  int oldlen = length(who);

  who = removestringlist(s, who);
  if (oldlen == length(who)) return;
  if (!streq(s, myname))
    status4(outputname(s), " has left (", itoa(length(who)), ").");
}

/****************************************************************************
Code for making messages.  Code for converting them to their string
representation and vice versa.
****************************************************************************/

message *makemsg10(char kind, char *a, char *b, char *c, char *d, char *e,
		   char *f, char *g, char *h, char *i, char *j)
{
  message *new;
  static int messageno = 0;
  char messageID[20];

  sprintf(messageID, "%x", messageno++);

  new = alloc(message);
  markgarbage((char *) new); /* mark it to be freed later */
  new->kind = kind;
  new->args = (char **) salloc(MAXMSGARGS * sizeof(char *));
  markgarbage((char *) new->args); /* mark it to be freed later */
  new->args[0] = (a == NULL) ? NULL : TEMPCOPY(a);
  new->args[1] = (b == NULL) ? NULL : TEMPCOPY(b);
  new->args[2] = (c == NULL) ? NULL : TEMPCOPY(c);
  new->args[3] = (d == NULL) ? NULL : TEMPCOPY(d);
  new->args[4] = (e == NULL) ? NULL : TEMPCOPY(e);
  new->args[5] = (f == NULL) ? NULL : TEMPCOPY(f);
  new->args[6] = (g == NULL) ? NULL : TEMPCOPY(g);
  new->args[7] = (h == NULL) ? NULL : TEMPCOPY(h);
  new->args[8] = (i == NULL) ? NULL : TEMPCOPY(i);
  new->args[9] = (j == NULL) ? NULL : TEMPCOPY(j);
  new->from = TEMPCOPY(myname);
  new->ID = TEMPCOPY(messageID);
  return new;
}

static int countargs(message *m)
{
  int numargs;
  
  for (numargs = 0; numargs < MAXMSGARGS; numargs++)
    if (m->args[numargs] == NULL) break;

  return numargs;
}

#define MAXMSGTEXT 5000
static char *msgtotext(message *m)
{
  char text[MAXMSGTEXT];
  int i, numargs, totallength;

  numargs = countargs(m);

  sprintf(text, "%c%d\\%d\\%d\\%s%s", m->kind, numargs,
	  strlen(m->from), strlen(m->ID), m->from, m->ID);
  for (i=totallength=0; i<numargs; i++) {
    sprintf(text + strlen(text), "%d\\", strlen(m->args[i]));
    totallength += strlen(m->args[i]);
  }
  assert(totallength + strlen(text) + 3 < MAXMSGTEXT);
  for (i=0; i<numargs; i++)
    sprintf(text + strlen(text), "%s", m->args[i]);

#if DBG
  if (hasWindows)
    puts(text);
#endif
  if (text[strlen(text) - 1] == '\\') sprintf(text + strlen(text), "\\");
  return TEMPCOPY(text);
}


message *mysterymessage(char *s)
{
#if SERVER
  fprintf(stderr, "Mystery message: %s\n", s);
#else
#if DBG
  DEBUG(talkmsg2("Mystery message: ", s));
#endif
#endif

  return NULL;
}

/* the inverse of msgtotext */
/* marks its return value as garbage */
message *parsemessage(char *s)
{
  char *original = s;
  message *m;
  int numargs, i, arglen[MAXMSGARGS], fromlen, IDlen;
  
  if (s == NULL || *s == '\0') return NULL;

  m = alloc(message);
  markgarbage((char *) m);
  m->kind = *s++;
  if (!validmessagekind(m->kind)) return mysterymessage(original);
  assert(m->kind != '\0');
  m->args = (char **) salloc(sizeof(char **) * MAXMSGARGS);
  markgarbage((char *) m->args);
  if (!isdigit(*s)) return mysterymessage(original);
  numargs = parseint(&s);
  if (!isdigit(*s)) return mysterymessage(original);
  fromlen = parseint(&s);
  if (!isdigit(*s)) return mysterymessage(original);
  IDlen = parseint(&s);
  m->from = markgarbage(salloc((fromlen + 1) * sizeof(char)));
  m->ID = markgarbage(salloc((IDlen + 1) * sizeof(char)));
  strncpy(m->from, s, fromlen);
  m->from[fromlen] = m->ID[IDlen] = '\0';
  safety_check(m->from);
  s += fromlen;
  strncpy(m->ID, s, IDlen);
  s += IDlen;
  safety_check(m->ID);
  for (i=0; i<numargs; i++) {
    if (!isdigit(*s)) return mysterymessage(original);
    arglen[i] = parseint(&s);
  }
  for (i=0; i<numargs; i++) {
    m->args[i] = markgarbage(salloc((arglen[i] + 1) * sizeof(char)));
    strncpy(m->args[i], s, arglen[i]);
    m->args[i][arglen[i]] = '\0';
    if (strlen(m->args[i]) != arglen[i]) return mysterymessage(original);
    destructivebracketclean(m->args[i]);
    s += arglen[i];
  }
  if (*s != '\0') {
    char warn[100];
    sprintf(warn, "Extra cruft at end of %c message: `%s'", m->kind, s);
    warningmsg(warn);
  }
  while (i < MAXMSGARGS) m->args[i++] = NULL;
  
  return m;
}

/* take an array of n messages and output a multimessage of those messages */
/* limitation: n <= 9 */
/* should work but is currently unused */
message *multimessage(message *A[], int n)
{
  int i;
  char *B[MAXMSGARGS];

  assert(n <= 9);
  for (i = 0; i < 9; i++) B[i] = ((i < n) ? msgtotext(A[i]) : NULL);
  return makemsg10(MULTIMESSAGE, B[0], B[1], B[2], B[3], B[4],
		   B[5], B[6], B[7], B[8], NULL);
}

/*****************************************************************************/

#define BEEP_STR "_!BEEP!beep!BEEP!_"
#define saybeep_to_one(beepee) say_to_one((beepee), BEEP_STR)

static void say_to_one(char *who, char *what)
{
  extern bool spec;
  selfmessage(makemsg3(SAY_TO_ONE, itoa(spec), who, what));
}

/* A perfect match except for case? */
static char *partial_namematch1(char *x, char **l, int n)
{
  if (n <= 0) return NULL;
  if (strcaseeq(x, *l)) return *l;
  else return partial_namematch1(x, ++l, --n);
}

/* Is x a perfect prefix for exactly one element of l? */
static char *partial_namematch2(char *x, char **l, int n)
{
  if (n <= 0) return NULL;
  if (strneq(x, *l, strlen(x)))
    return (partial_namematch2(x, l + 1, --n) == NULL ? *l : NULL);
  else return partial_namematch2(x, ++l, --n);
}

/* Ignoring case, is x a perfect prefix for exactly one element of l? */
static char *partial_namematch3(char *x, char **l, int n)
{
  if (n <= 0) return NULL;
  if (strncaseeq(x, *l, strlen(x)))
    return (partial_namematch3(x, l + 1, --n) == NULL ? *l : NULL);
  else return partial_namematch3(x, ++l, --n);
}

/* l is a vector of length n of strings.  If x is a decent partial
   match for one and only one of the things in l, return that element
   of l.  Otherwise NULL. */
static char *partial_namematch(char *x, char **l, int n)
{
  char *s;
  if ((s = partial_namematch1(x, l, n)) != NULL) return s;
  if ((s = partial_namematch2(x, l, n)) != NULL) return s;
  else return partial_namematch3(x, l, n);
}

/* l is a vector of length n of strings.  Return whether x exactly
   equals anything in l. */
static bool perfect_namematch(char *x, char **l, int n)
{
  return ((n > 0) && (streq(x, *l) || perfect_namematch(x, ++l, --n)));
}

char *namematch(char *x, char **l, int n)
{
  return perfect_namematch(x, l, n) ? x : partial_namematch(x, l, n);
}

void commbeep(char *arg)
{
  int i, n;
  char **who = getwho(&n);
  char *beepee;

  if (n <= 1) { errormsg("There is no one else here to beep."); return; }

  arg = trim(arg);

  for (i = 0; i < n; i++) who[i] = outputname(who[i]);

  /* Default: beep everyone */
  if (!strexists(arg)) {
    while (--n >= 0) if (!streq(who[n], myoutputname)) commbeep(who[n]);
    return;
  }

  if ((beepee = namematch(arg, who, n)) != NULL)
    saybeep_to_one(beepee);
  else
    errormsg3("It is unclear whom to beep (`", arg, "'?)");
}

/*****************************************************************************/

#define recent_table_arrival() \
    atob(TclDo("uplevel #0 {expr $floaterclock - $table_arrival_time < 10}"))

void commresult(bool competitive, message *m, char *handname)
{
  char *s;

  s = msgtotext(m);

  if (competitive && !recent_table_arrival()) {
    /* use Tcl variable sentresult() to keep track of the hands we've
     sent out results for */
    if (atob(TclDo3("global sentresult; info exists sentresult(", handname, ")")))
      if (streq(TclDo3("gset sentresult(", handname, ")"), s)) return;
    TclDo5("gset sentresult(", handname, ") {", s, "}");

    if (atob(TclDo3("emailresult {", s, "}"))) {
      errormsg("Unable to report result to server by email!");
      errormsg(TclGet("errorstring"));
    }
    else
      status("Result successfully reported to server");
  }

  if (tablehostmode) {
    char *rs = connect_to_resultserver();

    if (rs != NULL) sendstrmessage(rs, s);
    else errormsg("Unable to connect to result server to see others' results");
  }      
}

/* delay is the number of seconds to wait before reporting (typically
   by email) what's been seen.  See mail.TCL for emailseens. */
void commseens(int delay)
{
  if (delay <= 0) {
    if (atob(TclDo("emailseens"))) {
      errormsg("Unable to report boards seen by email!");
      errormsg(TclGet("errorstring"));
    }
    else
      status("Boards seen successfully reported by email");
  } else TclDo3("after [expr 1000 * ", itoa(delay), "] emailseens");
}

/*****************************************************************************/


/* callback for when a connection times out */
int floatertimeout(ClientData clientData, Tcl_Interp *interp,
		   int argc, char *argv[])
{
  assert(argc == 2); /* argv[0] is "floatertimeout"; argv[1] is the connstr */

    
#if LOGGING
  fprintf(logfile, "closing %s (timeout)\n", argv[1]);
#endif

 if (isparentfile(argv[1]) && !tablehostmode) disconnect_all();
 else {
   /* closing the connection automatically will invoke FloaterClose(), below */
   TclDo2("FloaterClose ", argv[1]);
 }
 return TCL_OK;
}

/* Called to close a conn */
int FloaterClose(ClientData clientData, Tcl_Interp *interp,
		 int argc, char *argv[])
{
  char *sock;
  char *connstr = argv[1];

  assert(argc == 2); /* argv[0] is "FloaterClose"; argv[1] is the connstr */

  if (atoi(TclDo3("catch {uplevel #0 set conn_to_sock(", connstr, ")}")))
    /* we've already closed this one and forget all about it, so just return */
    return TCL_OK;

  sock = TclDo3("uplevel #0 set conn_to_sock(", connstr, ")");

#if DEBUGCONN
  if (hasWindows)
    printf("%s: FloaterClose %s (%s)\n", myname, connstr, sock);
#endif

  TclDo2("shouldnotsendiamalive ", connstr);
  TclDo2("shouldnotreceiveiamalive ", connstr);

#if DBG
  DEBUG(talkmsg5("Closing conn ", connstr, " (", sock, ")"));
#endif
#if LOGGING
  fprintf(logfile, "Closing conn %s (%s)\n", connstr, sock);
#endif

  TclDo3("catch {close ", sock, "}");
  TclDo3("catch {uplevel #0 unset sock_to_conn($conn_to_sock(", connstr,
	 "))}");
  TclDo3("catch {uplevel #0 unset conn_to_sock(", connstr, ")}");

#ifdef PSEUDOMAILER
  if (atob(TclDo2("remailnow ", connstr)))
    status2("remail failed: ", TclGet("errorstring"));
  else
    status("remail.");
#else
  if (iskchildfile(connstr)) removekchild(connstr, TRUE);
  else if (istchildfile(connstr)) {
    removetchild(connstr, TRUE);
#ifdef LOGINSERVER
    if (tchildren == NULL)
      tablerootname[0] = tablerootaddr[0] = tablerootport[0] = '\0';
#endif    
  } else if (isparentfile(connstr)) {
    char *parentname = TEMPCOPY(parent->name);

#if DEBUGCONN
    if (hasWindows)
      printf("%s: disconnected from parent\n", myname);
#endif
    freeconn(parent);
    parent = NULL;
    tablerootmode = FALSE;
    announce_disconn(parentname);
    if (state == DISCONNECTING) state = LIMBO;
    if (state == CONNECTED && !tablehostmode) disconnect_all();
    else if (state == CONNECTED && tablehostmode) {
      reset_time_to_rejoin();
      rejoinaddr[0] = rejoinport[0] = '\0'; /* don't ever rejoin at parent */
      rejoin();
    }
  }
  if (state == LIMBO) tablehostmode = FALSE;
  if (hasWindows) UIstate(state);
#endif
  if_not_connected_reset_tablehostname();
  return TCL_OK;
}

/* received message: argc and argv contain a message from someone */
/* argv[0] is "floaterreceive";
   argv[1] is the message;
   argv[2] is the conn of the sender */
int receivemessage(ClientData clientData, Tcl_Interp *interp,
		   int argc, char *argv[])
{
  message *m;

  assert(argv[1] != NULL);

#ifdef PSEUDOMAILER
  status4("got ", argv[1], " from ", argv[2]);
  if (streq(argv[1], "ozzie_and_harriet")) {
    TclDo3("uplevel #0 {set ozzie(", argv[2], ") 1}");
  }
  else if (atob(TclDo3("global ozzie; info exists ozzie(", argv[2], ")"))) {
    TclDo5("remail {", argv[1], "} {", argv[2], "}");
  } else {
    status4("Don't know what to do with ", argv[1], " from ", argv[2]);
  }
  return TCL_OK;
#else

  /* parse the message; if empty, ignore it and return */
  if ((m = parsemessage(argv[1])) == NULL) return TCL_OK;

  executionlog("receive: ", argv[1]); 

  reset(connstr);
  if (argc == 3) connstr = STRDUP(argv[2]);
  else assert(0);

#if LOGGING
  {
    int numargs = countargs(m);

    fprintf(logfile, "Received a %c message from %s with %d args:\n%s\n",
	    m->kind, m->from, numargs, argv[1]);
  }
#endif

  if (streq(m->from, myname)) {
    /* how droll, I'm receiving a message that I originally sent */
    return TCL_OK;
  }
  
#if DEBUGMSG0
  {
    int numargs, i;
    char s[100];

    numargs = countargs(m);

    sprintf(s, "Received a %c message from %s with %d args", m->kind,
	    m->from, numargs);
    if (hasWindows) puts(s);
    DEBUG(talkmsg(s));
    for (i=0; i<numargs; i++) {
      DEBUG(talkmsg(m->args[i]));
      if (hasWindows) puts(m->args[i]);
    }
  }
#endif

  /* take action depending on what the message is */
  handlemessage(m, argv[1]);
  return TCL_OK;
#endif
}

/* Handle a string of messages separated by tabs. */
void tabmulti(char *s)
{
  message *m;
  int i;
  bool foundtab, foundend;

  s = TEMPCOPY(s);

  while (TRUE) {
    i = 0;
    do {
      foundtab = (s[i] == '\t');
      foundend = (s[i] == '\0');
      if (foundtab) s[i] = '\0';
      i++;
    } while (!foundtab && !foundend);
    if ((m = parsemessage(s)) != NULL) handlemessage(m, s);
    if (foundtab) s = s + i; else return;
  }
}

void sendmessage(char *to, message *m)
{
  char *s;

  assert(strexists(to));
  s = msgtotext(m);
  assert(strexists(s));
  TclDo5("FloaterSend ", to, " {", s, "}");
#if LOGGING  
  fprintf(logfile, "%s%s%s%s%s\n", "FloaterSend ", to, " {", s, "}");
#endif
}

static void sendstrmessage(char *to, char *s)
{
  assert(strexists(to));
  assert(strexists(s));
  TclDo5("FloaterSend ", to, " {", s, "}");
#if LOGGING
  fprintf(logfile, "%s%s%s%s%s\n", "FloaterSend ", to, " {", s, "}");
#endif
}

static void sendtoparent(char *s)
{
  if (parent != NULL) sendstrmessage(parent->connstr, s);
}

/*
   send a message to all parents and kchildren
   exception: if I'm the tablehost and its not a globally important message,
   send it only to kchildren
*/
void broadcast(message *m)
{
  char *s;

  s = msgtotext(m);

  sendtokchildren(s, NULL);
  if (!tablehostmode || globalbroadcast(m->kind)) sendtoparent(s);
  if (globalbroadcast(m->kind)) sendtotchildren(s, NULL);
}

/* send a message to myself (and automatically rebroadcast it if it is
   that kind of message) */
void selfmessage(message *m)
{
  char realconnstr;

  /* while handling a self-generated message, connstr should be empty */
  /* (having to do this hack shows why connstr should not be global) */
  if (connstr != NULL) {
    realconnstr = connstr[0];
    connstr[0] = '\0';
    handlemessage(m, NULL);
    connstr[0] = realconnstr;
  } else handlemessage(m, NULL);
}

/* broadcast, except don't send m back to whoever told us m */
static void rebroadcast(message *m)
{
  char *s;

  s = msgtotext(m);

  if (parent != NULL && strexists(connstr) && streq(connstr, parent->connstr))
    sendtokchildren(s, NULL);
  else {
    sendtokchildren(s, connstr);
    if ((tablehostmode && globalbroadcast(m->kind)) || !tablehostmode)
      sendtoparent(s);
  }
  if (globalbroadcast(m->kind)) sendtotchildren(s, connstr);
}

void commsetup()
{
  if (strlen(loginserveraddr) == 0) {
    /* be careful, as these variables may have been set to (lengthy) garbage */
    strncpy3(loginserveraddr, TclDo("gset loginserveraddr"));
    strncpy3(loginserverport, TclDo("gset loginserverport"));
    strncpy3(loginservername, TclDo("gset loginservername"));
    loginserveraddr[sizeof(loginserveraddr) - 1] = '\0';
    loginservername[sizeof(loginservername) - 1] = '\0';
    loginserverport[sizeof(loginserverport) - 1] = '\0';
  }

  if (strlen(resultserveraddr) == 0) {
    /* be careful, as these variables may have been set to (lengthy) garbage */
    strncpy3(resultserveraddr, TclDo("gset resultserveraddr"));
    strncpy3(resultserverport, TclDo("gset resultserverport"));
    strncpy3(resultservername, TclDo("gset resultservername"));
    resultserveraddr[sizeof(resultserveraddr) - 1] = '\0';
    resultservername[sizeof(resultservername) - 1] = '\0';
    resultserverport[sizeof(resultserverport) - 1] = '\0';
  }

  if (localIPaddr == NULL) {
    Floater_hostname = STRDUP(TclDo("info hostname"));
    localIPaddr = STRDUP(TclGet("localIPaddr"));
    localIPaddr0 = STRDUP(TclGet("localIPaddr0"));
#if DEBUGCONN
    if (hasWindows)
      printf("localIPaddr=%s\n", localIPaddr);
#endif
  }
#ifndef SERVER
  openport(NULL);
#endif
}

/* returns port opened on success, or -1 on failure */
/* if port is NULL, use any old port */
static int openport(char *port) 
{
  int ret;
  char *command;

  if (localport != NULL) return atoi(localport);

  command = markgarbage(salloc((((port == NULL) ? 0 : strlen(port)) + 100)
			    * sizeof(char)));

  sprintf(command,
	  "catch {FloaterListen %s} openport",
	  (port == NULL) ? "" : port);
  ret = 
    atoi(TclDo(command)) ?
      -1 : atoi(localport = STRDUP(TclDo("set openport")));

  if (localport != NULL && strlen(myname) == 0) {
    char newname[100];
    sprintf(newname, "Doe %s", localport); /* for now, use port # as name */
    setmyname(newname, FALSE);
  }

  return ret;
}

/* set up a name by concatenating the desired name and a bogus, unique tag */
/* the unique tag depends on the local IP address and port */
/* if loggedin is false, add an asterisk after the name to indicate it */
static void setmyname(char *newname, bool loggedin)
{
  /* hack because changing your name will confuse others at the table */
  if (state == CONNECTED) sever_all_communication();

  assert(strlen(newname) <= MAX_OUTPUTNAME_LENGTH);
  strcpy(myname, newname);
  if (!loggedin) sprintf(myname + strlen(myname), "*");
  strcpy(myoutputname, myname);
  openport(NULL);
  setbogusnewname(myname + strlen(myname), localIPaddr0, localport);

  /* stuff related to what hands have been seen */
  TclSet("seenname", loggedin ? myoutputname : "_everyone_");
  checknewweek();
  loadseen();
}

/* for human readable output, truncate name at the '!' */
/* do not modify input; instead, copy, and mark copy as dead */
char *outputname(char *name)
{
  int i;

  if (!strexists(name)) return "";
  i = 1;
  while ((name[i] != '\0') && (name[i] != '!')) i++;
  if (name[i] != '!') return name;
  else return markgarbage(STRNDUP(name, i));
}

static void disconnect(conn *c)
{
#if DEBUGCONN
  DEBUG(talkmsg4("Closing connection (", c->connstr, ") to ", c->name));
#endif
#if LOGGING
  fprintf(logfile, "Closing connection (%s) to %s\n", c->connstr, c->name);
#endif
  sendmessage(c->connstr, makemsg1(ANNOUNCE_DISCONNECT, myname));
  TclDo3("catch {FloaterClose ", c->connstr, "}");
}

static void disconnect_all(void)
{
  state = DISCONNECTING;

/*   UIpatientcursor();*/

#ifndef SERVER
  strcpy(location, "");
#endif
#if DEBUGCONN
    status("Severing all connections; clearing `who' list");
#endif

  while (kchildren != NULL) {
    disconnect(kchildren->c);
    kchildren = freechild(kchildren);
  }

  while (tchildren != NULL) {
    disconnect(tchildren->c);
    tchildren = freechild(tchildren);
  }

  if (parent != NULL) {
    disconnect(parent);
    freeconn(parent);
    parent = NULL;
  }

  if (lho != NULL) {
    disconnect(lho);
    freeconn(lho);
    lho = NULL;
  }

  if (rho != NULL) {
    disconnect(rho);
    freeconn(rho);
    rho = NULL;
  }

  while (who != NULL) who = freestringlist(who);

/*  UInormalcursor();*/
  tablehostmode = FALSE;
  state = LIMBO;
  nobridge();

  /* neither send nor expect iamalive messages */
  TclSet("sendiamalivelist", "");
  TclSet("receiveiamalivelist", "");
  if (hasWindows) UIstate(state);
  if_not_connected_reset_tablehostname();
}

void sever_all_communication(void)
{
  state = DISCONNECTING;
  announce_disconn(myname);
  disconnect_all();
  if (tablehostmode) {
    tablehostmode = FALSE;
    tables = removetable(myname, tables);
  }
  state = LIMBO;
}


#ifdef LOGINSERVER
void loginserver(char *p)
{
  int port;
  char s[100];
  extern char previousglobaldate[];

  /* setup(); */

  if ((port = openport(p)) <= 0) {
    errormsg("Attempt to become a login server failed (unable to open a port)");
    return;
  }
  
  disconnect_all();

  checknewweek();
  status4("Date: ", globaldate,
	  "; Previous date: ", previousglobaldate);
  TclDo4("seen_startup ", globaldate, " ", previousglobaldate);

  sprintf(s, "Listening on port %s:%d on local machine",
	  Floater_hostname, port);
  status(s);
  state = CONNECTED;
  status("You are now a login server");
}
#endif

#ifdef PSEUDOMAILER
void pseudomailer(char *p)
{
  int port;
  char s[100];

  /* setup(); */

  if ((port = openport(p)) <= 0) {
    errormsg("Attempt to become a pseudomailer failed (unable to open a port)");
    return;
  }
  
  disconnect_all();

  sprintf(s, "Listening on port %s:%d on local machine",
	  Floater_hostname, port);
  status(s);
  state = CONNECTED;
  status("You are now a pseudomailer");
}
#endif
  
#ifdef RESULTSERVER
void resultserver(char *p)
{
  int port;
  char s[100];

  /* setup(); */

  if ((port = openport(p)) <= 0) {
    errormsg("Attempt to become a result server failed (unable to open a port)");
    return;
  }
  
  disconnect_all();

  sprintf(s, "Listening on port %s:%d on local machine",
	  Floater_hostname, port);
  status(s);
  state = CONNECTED;
  checknewweek();
  tabmulti(TclDo2("loadresults ", globaldate));
  startingup = FALSE;
  status("You are now a result server");
}
#endif
  
#ifndef SERVER
/* serve a table */
void tablehost(char *addr, char *p)
{
  int port;
  char s[100];

  /* setup(); */

  if ((port = openport(NULL)) <= 0) {
    errormsg("Attempt to serve a table failed (unable to open a port)");
    return;
  }
  
  if (!tablehostmode && omembertablelist(myoutputname)) {
    if (membertablelist(myname)) tables = removetable(myname, tables);
    else {
      errormsg3("There is already a table under the name `",
		myoutputname, "', so to prevent name conflicts you will "
		"not be able to host a table right now");
      return;
    }
  }

  sever_all_communication();

  sprintf(s, "Listening on port %s:%d on local machine",
	  Floater_hostname, port);
  status(s);
  state = CONNECTED;
  status("You are now hosting a table");
#ifndef SERVER
  strcpy(location, "hosting");
#endif
  tablehostmode = TRUE;
  addwho(myname);
  describetable(defaultnote);
  STRCPY(tablehostname, myname);
  STRCPY(tablehostaddr, localIPaddr);
  STRCPY(tablehostport, localport);

  /* try to join the table tree */
  if (addr == NULL || p == NULL) {
    if (strlen(tablerootaddr) > 0) {
      addr = tablerootaddr;
      p = tablerootport;
    } else {
      addr = loginserveraddr;
      p = loginserverport;
    }
  }
  if (addr != NULL && p != NULL)
    if (!join(addr, p, TABLE_SERVERs, 1) &&
	(!streq(p, loginserverport) || !streq(addr, loginserveraddr))) {
      /* didn't work; try loginserver */
      addr = loginserveraddr;
      p = loginserverport;
      if (addr != NULL && p != NULL)
	join(addr, p, TABLE_SERVERs, 1);
    }

  tablehostmode = TRUE;
  addwho(myname);
  if (hasWindows) UIstate(state);
}
#endif /* ifndef SERVER */
  
/*****************************************************************************/

/* Go through the table list and remove any tables we haven't heard
from lately.  If we haven't heard from our parent lately, broadcast
the demise of the parent (which will kick in the rejoin mechanism). */
void checktablelisttimeouts(void)
{
  tablelist *l;
  static bool inside = FALSE; /* prevent recursive entry */
  static int lastcheck = -1;
  int time = floaterclock();
  int timeout = atoi(TclGet("tabletimeout"));

  /* checking once per second is plenty */
  if (lastcheck == time) return;
  if (inside) return; else inside = TRUE;
  lastcheck = time;

  for (l = tables; l != NULL; ) 
    if (time - atoi(tabletimestamp(l)) > timeout) {
      if (isparentname(tablename(l))) {
	status3("Haven't heard from ", outputname(tablename(l)), " for a while; assuming table is gone");
	selfmessage(makemsg1(TABLE_DEMISE, tablename(l)));
	/* don't bother processing the rest of the list right now */
	inside = FALSE;
	return;
      }
      l = tables = removetable(tablename(l), tables); /* inefficient */
    } else l = nexttable(l);

  inside = FALSE;
}

/* tablehosts should reannounce their existence so others know they're
   still alive */
void periodictablereannounce(void)
{
  static int lastreannounce = -1;
  int time = floaterclock();
  int timeout = atoi(TclGet("tablereannounce"));

  if (!tablehostmode || !strexists(mytabledesc)) return;
  if (lastreannounce != -1 && ((time - lastreannounce) < timeout)) return;

  DEBUG(talkmsg("Reannouncing my table"));
  selfmessage(makemsg4(ANNOUNCE_TABLE, myname, mytabledesc,
		       localIPaddr, localport));
  lastreannounce = time;
}

/*****************************************************************************/

void try_rejoin(void)
{
#if DEBUBCONN
  DEBUG(talkmsg("call to try_rejoin()"));
#endif

  if (tablehostmode && parent == NULL && time_to_rejoin()) rejoin();
}

/* Set *q to a copy of the part of addr before its first '!'; set *p to a
   copy of the rest.  Assumes '!' appears at least once in addr. */
static void addrsplit(char *addr, char **p, char **q)
{
  *p = TEMPCOPY(addr);
  for (*q = *p; **q != '!'; ++*q);
  **q = '\0';
  ++*q;
}

/* Open a socket.  join() is one of the two functions that calls
   FloaterConnect (the other is connect_to_loginserver()).  Return 1
   on success, 0 on failure. */
int join(char *addr, char *port, char *capacity, int numtries)
{
  int t, retry, lport;
  char s[100];

  if (numtries == 0) return 0;

  assert(numtries > 0);

  UIpatientcursor();

  if ((lport = openport(NULL)) <= 0) {
    errormsg("Attempt to join failed (unable to open a port locally)");
    UInormalcursor();
    return 0;
  }

  if (streq(addr, localIPaddr) && streq(port, localport)) {
    UInormalcursor();
    return 0;
  }

  if (isin('!', addr)) {
    int ret;
    char *p, *q;
    addrsplit(addr, &p, &q);
#if DBG||DEBUGCONN
    TclDo5("catch {talkmsg {recursive join on ", p, " and ", q, "}}");
#endif
    ret = (join(p, port, capacity, numtries) ? 1 :
	   join(q, port, capacity, numtries));
    UInormalcursor();
    return ret;
  }

  if (tablehostmode && capacity[0] == KIBITZER)
    sever_all_communication();
  else if (!tablehostmode && state != DISCONNECTING && state != LIMBO)
    disconnect_all();

  assert(parent == NULL);

  if (localport != NULL && strlen(myname) == 0) {
    char newname[100];
    sprintf(newname, "Doe %s", localport); /* for now, use port # as name */
    setmyname(newname, FALSE);
  }

  for (retry = 0; retry < numtries; retry++) {
    if (retry == 1) UIpatientcursor();
    if (retry > 0) {
      sprintf(s, "for {set i 0} {$i < %d} {incr i} {update; after 125}",
	      retry * retry * 8);
      TclDo(s);
    }
    if (retry > 0)
      status4("Failed to connect to ", addr, ":", port);
    status4("Attempting to connect to ", addr, ":", port);
    t = atoi(TclDo5("uplevel #0 {catch {FloaterConnect ",
		    addr, " ", port, "} joinfile}"));
    if (t == 0) break; /* it worked */
  }
  if (retry >= 1 && numtries > 1) UInormalcursor();

#if LOGGING
  fprintf(logfile, "joined %s:%s with %s\n", addr, port, TclGet("joinfile"));
#endif
#if DBG
  DEBUG(talkmsg6("joined ", addr, ":", port, " with ", TclGet("joinfile")));
#endif

  if (t != 0) {
    /* connection didn't work */

    if (tablehostmode && parent == NULL)
      if (capacity[0] == KIBITZER) 
	{ assert(0); }
      else {
	/* The following line is commented out to avoid alarming the user. */
	/* status("You've been disconnected from the table tree."); */
	/* Note that attempts to rejoin the table tree will continue... */
	UInormalcursor();
	return 0;
      }
    else status4("Giving up attempt to connect to ", addr, ":", port);

    if (!tablehostmode) {
      state = LIMBO;
      disconnect_all();
    }
    UInormalcursor();
    return 0;
  }

  status("Communication established");
  
  /* set the parent or rho variable even though we may end up being rejected */
  if (capacity[0] == KIBITZER || capacity[0] == TABLE_SERVER) {
    parent = makeconn(BOGUS_NAME, addr, port,
		      TclDo("uplevel #0 {set parentfile $joinfile}"));
    expecting_join_elsewhere = TRUE;
  }
  else if (capacity[0] == LHO) {
    /* I'm trying to join as his LHO, i.e., he is my RHO */
    if (rho != NULL) {
      disconnect(rho);
      freeconn(rho);
    }
    rho = makeconn(BOGUS_NAME, addr, port,
		   TclDo("uplevel #0 {set rhofile $joinfile}"));
  }
  sendmessage(TclDo("uplevel #0 set joinfile"),
	      makemsg5(REQUEST_JOIN, FLOATER_VERSION,
		       myname, localIPaddr, itoa(lport), capacity));
  state = CONNECTED;
  if (hasWindows) UIstate(state);
  UInormalcursor();
  return 1;
}

static void reject_join(char *reason, char *caps)
{
  sendmessage(connstr, makemsg2(REJECTED_JOIN, reason, caps));
  TclDo3("catch {FloaterClose ", connstr, "}");
}

/* tell the guy connected on file to please connect to addr:port instead */
static void shunt2(char *connstr,
		   char *name, char *addr, char *port, char *cap)
{
#if DEBUGCONN
  char s[200];
  sprintf(s, "Asking %s to connect to %s at %s:%s", connstr, name, addr, port);
  DEBUG(talkmsg(s));
#endif

  sendmessage(connstr, makemsg4(JOIN_ELSEWHERE, name, addr, port, cap));
}

/* Called when some new guy wants to join.  If it decides to shunt, it randomly
   selects one of my children to tell the new guy to try, and returns TRUE.
   If it decides not to shunt, it returns FALSE and does nothing. */
/* Currently only used for the table tree. */
static bool shunt(char *connstr, char *cap)
{
  int numtchildren;
  childlist *c;

  for (numtchildren = 0, c = tchildren; c != NULL; numtchildren++) c = c->next;
  if (numtchildren >= MAXTCHILDREN) {
    int skip =  unifmod(numtchildren);
    for (c = tchildren; skip > 0; skip--) c = c->next;
    shunt2(connstr, c->c->name, c->c->IPaddr, c->c->port, cap);
    return TRUE;
  }
  return FALSE;
}

static void accept_join(char *name, char *IPaddr, char *port, char capacity)
{
  char caps[2];

  caps[0] = capacity;
  caps[1] = '\0';
  sendmessage(connstr, makemsg3(ACCEPTED_JOIN, caps, localIPaddr, localport));
  TclDo3("if ![info exists connstr] {set connstr ", connstr, "}");
  TclDo("shouldsendiamalive $connstr");
  TclDo("shouldreceiveiamalive $connstr");
  TclDo4("uplevel #0 set \\{name_to_conn(", name, ")\\} ", connstr);

  switch (capacity) {
  case KIBITZER:
    addchild(&kchildren, name, IPaddr, port, connstr);
    addwho(name);
    tellhandstatus(outputname(name), connstr); /* bring newcomer up to date */
    announce_who(); /* tell the newcomer who is here */
    tellseatstatus(connstr); /* bring the newcomer up to date */
    tellcc(connstr); /* transmit convention cards to newcomer */
    announce_tables();
    break;
  case TABLE_SERVER:
    addchild(&tchildren, name, IPaddr, port, connstr);
    addtable(name, "", IPaddr, port);
    announce_tables();
    break;
  case LHO:
    if (lho != NULL) { 
     disconnect(lho);
      freeconn(lho);
    }
#if DBG
    DEBUG(status5(name, " is connected as LHO (to ", myname,
		  ") via ", connstr));
#endif
    lho = makeconn(name, IPaddr, port, connstr);
    break;
  }
}

/* try to connect to login server; return connstr on success, otherwise NULL */
static char *connect_to_loginserver(void)
{
  int t, retry;
  char *addr, *port;

  addr = loginserveraddr;
  port = loginserverport;

  if (isin('!', addr)) {
    char *p, *q;
    addrsplit(addr, &p, &q);
    addr = p;
  }

  if (openport(NULL) < 0) {
    errormsg("Unable to open a port locally; unable to log in");
    return NULL;
  }

  for (retry = 0; retry < NUMTRIES; retry++) {
    if (retry == 1) UIpatientcursor();
    if (retry > 0) {
      char s[100];

      if (!hasWindows) textrefresh();
      /* wait for retry * retry seconds */
      sprintf(s, "for {set i 0} {$i < %d} {incr i} {update; after 125}",
	      retry * retry * 8);
      TclDo(s);
    }
    if (retry > 0)
      status4("Failed to connect to ", addr, ":", port);
    status4("Attempting to connect to login server at ", addr, ":", port);
    t = atoi(TclDo5("catch {FloaterConnect ",
		    addr, " ", port, "} serverfile"));
    if (t == 0) break; /* it worked */
  }

  if (retry >= 1 && NUMTRIES > 1) UInormalcursor();
  return ((t == 0) ? TclDo("set serverfile") : NULL);
}

/* try to connect to result server; return connstr on success, otherwise NULL */
static char *connect_to_resultserver(void)
{
  int t, retry;
  char *addr, *port;

  addr = resultserveraddr;
  port = resultserverport;

  if (isin('!', addr)) {
    char *p, *q;
    addrsplit(addr, &p, &q);
    addr = p;
  }

  for (retry = 0; retry < NUMRSTRIES; retry++) {
    if (retry == 1) UIpatientcursor();
    if (retry > 0) {
      char s[100];

      if (!hasWindows) textrefresh();
      /* wait for retry * retry seconds */
      sprintf(s, "for {set i 0} {$i < %d} {incr i} {update; after 125}",
	      retry * retry * 8);
      TclDo(s);
    }
    if (retry > 0)
      status4("Failed to connect to ", addr, ":", port);
    status4("Attempting to connect to result server at ", addr, ":", port);
    t = atoi(TclDo5("catch {FloaterConnect ",
		    addr, " ", port, "} serverfile"));
    if (t == 0) break; /* it worked */
  }

  if (retry >= 1 && NUMRSTRIES > 1) UInormalcursor();
  return ((t == 0) ? TclDo("set serverfile") : NULL);
}

static bool validname(char *name)
{
  int len = (name == NULL ? -1 : strlen(name));
  int i;

  if (len < 1) return FALSE;
  if (len > MAX_OUTPUTNAME_LENGTH) {
    errormsg3("A valid name is at most ",
	      itoa(MAX_OUTPUTNAME_LENGTH), " characters long");
    return FALSE;
  }

  for (i = 0; i < len; i++)
    if (!(isalpha(name[i]) || isdigit(name[i]) || isin(name[i], ":'`^~./?-_#")
	  || (i > 0 && name[i] == ' '))) {
      errormsg("A valid name consists of letters, spaces, digits, and :'`^~./?-_#");
      return FALSE;
    }

  return TRUE;
}

/* new is a boolean---whether this is a new user */
/* if new is true then password is actually an email address */
void login(char *name, char *password, bool new)
{
  char *serverfile;

  loggedin = FALSE;

  /* neither name nor password may be the empty string */
  if (!strexists(name) || !strexists(password)) return;

  name = trim(name);

  if (!validname(name)) return;

  if ((serverfile = connect_to_loginserver()) == NULL) {
    status("Giving up attempt to connect to login server");
    if (new || !prioruse(name)) {
/*      setbogusnewname(myname, localIPaddr0, localport);*/
      status3("For now, you will be allowed to play under the name ",
	      myoutputname, ".");
      status("Results you get under this name will not be recorded.");
    } else {
      setmyname(name, FALSE);
      status3("You may still play as ", myoutputname,
	      ", but you won't be logged in.");
      /*status("You may use the command `help login' for details on what this means");*/
      status("Check the manual for details on what this means.");
    }
    triedtologin = TRUE;
    return;
  }

  /* hack because changing your name will confuse others at the table */
  if (state == CONNECTED) sever_all_communication();

  sendmessage(serverfile,
	      makemsg7(LOGIN, FLOATER_VERSION, name, password,
		       localIPaddr, localport, new ? "new" : "", platform));
  status("Server contacted: logging in...");
  triedtologin = TRUE;
}

void changepw(char *name, char *old, char *new)
{
  char *serverfile;

  if (!strexists(new)) {
    errormsg("New password must be at least one character long");
    return;
  }
  if ((serverfile = connect_to_loginserver()) != NULL) {
    sendmessage(serverfile, makemsg3(CHANGEPW, name, old, new));
    reset(newpw);
    newpw = STRDUP(new);
    status("Changing password...");
  }
}

void changeemail(char *name, char *new)
{
  char *serverfile;

  if (!strexists(new)) {
    errormsg("New email must be at least one character long");
    return;
  }
  if ((serverfile = connect_to_loginserver()) != NULL) {
    sendmessage(serverfile, makemsg2(CHANGEEMAIL, name, new));
    reset(newemail);
    newemail = STRDUP(new);
    status("Changing email...");
  }
}

#ifndef SERVER
void updatelocation(void)
{
  if (!isin('*', myoutputname))
    selfmessage(makemsg2(UPDATE_LOCATION, myoutputname, location));
}
#endif

static void announce_disconn(char *s)
{
#if DEBUGCONN
  if (hasWindows) printf("%s: announce_disconn(%s)\n", myname, s);
#endif
#if LOGGING
  fprintf(logfile, "%s: announce_disconn(%s)\n", myname, s);  
#endif

  if (member(s, who)) {
#if DEBUGCONN
    DEBUG(talkmsg3("broadcasting ANNOUNCE_DISCONNECT ( ", s, " )"));
#endif
    selfmessage(makemsg1(ANNOUNCE_DISCONNECT, s));
  }
  if (membertablelist(s)) {
#if DEBUGCONN
    DEBUG(talkmsg3("broadcasting TABLE_DEMISE ( ", s, " )"));
#endif
    selfmessage(makemsg1(TABLE_DEMISE, s));
  }    
}


void listwho(void)
{
  stringlist *l;
  char s[10000], t[10000];
  extern char *northname, *southname, *eastname, *westname, *curhandID;

  if (who == NULL) {
    talkmsg("Who: nobody's here at all");
    return;
  }

  s[0] = t[0] = '\0';
  for (l = who; l != NULL && strlen(s) < 9999 - FLOATER_MAXNAME; l = l->next)
    if (curhandID == NULL || !is_spec(l->s, curhandID)) {
      sprintf(s + strlen(s), ", %s", outputname(l->s));
      if (northname != NULL && streq(northname, l->s)) strcat(s, " (N)");
      else if (southname != NULL && streq(southname, l->s)) strcat(s, " (S)");
      else if (eastname != NULL && streq(eastname, l->s)) strcat(s, " (E)");
      else if (westname != NULL && streq(westname, l->s)) strcat(s, " (W)");
    }

  if (curhandID != NULL)
    for (l = who; l != NULL && strlen(t) < 9999 - FLOATER_MAXNAME; l = l->next)
      if (is_spec(l->s, curhandID)) {
	sprintf(t + strlen(t), ", %s", outputname(l->s));
	if (northname != NULL && streq(northname, l->s)) strcat(t, " (N)");
	else if (southname != NULL && streq(southname, l->s)) strcat(t, " (S)");
	else if (eastname != NULL && streq(eastname, l->s)) strcat(t, " (E)");
	else if (westname != NULL && streq(westname, l->s)) strcat(t, " (W)");
    }

  talkmsg2("Who:", s + 1); /* s + 1 to skip first comma */
  if (t[0] != '\0')
    talkmsg2("Who (spectators):", t + 1); /* t + 1 to skip first comma */
}

/* Set *n to the number elements in the who list, and return a vector
   containing the names on the who list.  Return value is marked as garbage. */
char **getwho(int *n)
{
  int i;
  char **r;
  stringlist *l;

  if (who == NULL) {
    *n = 0;
    return NULL;
  }
  *n = length(who);
  r = (char **) markgarbage(salloc(sizeof(char *) * (*n)));
  for (i = 0, l = who; i < *n; i++, l = l->next) r[i] = l->s;
  return r;
}

static void listtables(void)
{
  tablelist *l;
  int c;
  char s[80];

  if (tables == NULL) {
    talkmsg("Tables: none");
    return;
  }

  for (c = 0, l = tables; l != NULL; (l = nexttable(l)), c++) {
    strcpy(s, "               ");
    talkmsg3("Tables: ",
	     strncpy3(s, outputname(tablename(l))),
	     tabledescription(l));
  }
  sprintf(s, "Tables: a total of %s\n", maybe_plural(itoa(c), "table"));
  talkmsg(s);
}

#define expecting_goodbye(f) TclDo5("uplevel #0 {if [info exists {expecting_goodbye(", f, ")}] {set {expecting_goodbye(", f, ")}}}")
#define set_expecting_goodbye(f, s) \
	TclDo4("uplevel #0 set {expecting_goodbye(", f, ")} ", s)
#define unset_expecting_goodbye(f) \
	TclDo3("uplevel #0 unset {expecting_goodbye(", f, ")}")

#ifdef LOGINSERVER
void gettables(void) { listtables(); }
#else
void gettables(void)
{
  char *serverfile;

  if (state == CONNECTED) {
    listtables();
    return;
  }

  if ((serverfile = connect_to_loginserver()) == NULL) {
    status("Unable to connect to login server to get fresh list of tables");
    listtables();
  } else {
    sendmessage(serverfile, makemsg0(TABLES_REQUEST));
    set_expecting_goodbye(serverfile, "listtables");
  }
}
#endif

void getfind(char *s)
{
  char *serverfile;

  if ((serverfile = connect_to_loginserver()) == NULL) {
    status("Unable to connect to login server to do `find'");
  } else {
    sendmessage(serverfile, makemsg1(FIND, s));
    /* set_expecting_goodbye(serverfile, "find"); */
  }
}

#ifdef LOGINSERVER

static void handlefindname(char *name)
{
  char s[1000];
  bool hli, hei = FALSE;

  fprintf(stderr, "handlefindname(%s)\n", name);
  if (hli = have_location_info(name)) {
    sprintf(s, "%s last seen %s", name, location_info(name));
    sendmessage(connstr, makemsg1(FOUND, s));
  }
#if 0
  if (hei = have_email_info(name)) {
    sprintf(s, "email for %s is %s", name, email_info(name));
    sendmessage(connstr, makemsg1(FOUND, s));
  }
#endif
  if (!(hei || hli)) {
    if (user_exists(name)) 
      sprintf(s, "Sorry, no recent information on %s", name);
    else
      sprintf(s, "There is no user named `%s'", name);
    sendmessage(connstr, makemsg1(FOUND, s));
  }    
}

/* Go through comma separated list of names and call handlefindname()
   on each. */
static void handlefind(char *s)
{
  char *curname = TEMPCOPY(s);
  bool done;
  int i;

  do {
    /* stop at next comma or end of string */
    for (i = 0; curname[i] != '\0' && curname[i] != ','; i++);
    done = (curname[i] == '\0');
    curname[i] = '\0'; /* truncate at comma */
    handlefindname(trim(curname));
    if (done) break;
    /* advance past name we just handled */
    while (*curname != '\0') curname++;
    curname++;
  } while (TRUE);
}

#endif /* LOGINSERVER */


/* announce who's here, who is N, who is S, who is tablehost, ... to new guy */
static void announce_who(void)
{
  extern char *curhandID;
  stringlist *l;

  sendmessage(connstr, makemsg0(FORGET_WHO));
  sendmessage(connstr, makemsg4(ANNOUNCE_TABLEHOST, myname, tablehostname,
				tablehostaddr, tablehostport));
  for (l = who; l != NULL; l = l->next)
    sendmessage(connstr, makemsg3(ANNOUNCE_PRESENCE, l->s,
				  (curhandID == NULL) ? "baloney" : curhandID,
				  (is_spec(l->s, curhandID) ? "1" : "0")));
}

/* announce all the tables that we know of to the new guy */
static void announce_tables(void)
{
  tablelist *l;

  /* update globaldate and globalseed if it is a new week */
  checknewweek();

/*  sendmessage(connstr, makemsg0(FORGET_TABLES));*/
  if (strlen(loginserveraddr) > 1)
    sendmessage(connstr,
		makemsg4(ANNOUNCE_LOGINSERVER, myname, loginservername,
			 loginserveraddr, loginserverport));
  if (strlen(tablerootaddr) > 1)
    sendmessage(connstr, makemsg4(ANNOUNCE_TABLEROOT, myname, tablerootname,
				  tablerootaddr, tablerootport));
#ifndef LOGINSERVER
  if (strlen(globaldate) > 1)
    sendmessage(connstr,
		makemsg2(ANNOUNCE_GLOBALDATE, globaldate, globalseed
			 /*, seconds_to_next_week()*/
			 ));
#endif
  for (l = tables; l != NULL; l = nexttable(l))
    sendmessage(connstr, makemsg4(ANNOUNCE_TABLE,
				  tablename(l), tabledescription(l),
				  tableIPaddr(l), tableport(l)));
}

static void rejoin(void)
{
  assert(tablehostmode);
  if (!strexists(rejoinaddr)) {
#if DEBUGCONN    
    DEBUG(talkmsg("Rejoining at tableroot"));
#endif
    /* try the tableroot, but only once---reset tablerootaddr after this */
    strcpy(rejoinaddr, tablerootaddr);
    strcpy(rejoinport, tablerootport);
    strcpy(rejoincap, TABLE_SERVERs);
    rejoinnumtries = NUMTRIES;
    tablerootaddr[0] = tablerootport[0] = '\0';
  }
  if (!strexists(rejoinaddr)) {
#if DEBUGCONN
    DEBUG(talkmsg("Rejoining at loginserver"));
#endif
    strcpy(rejoinaddr, loginserveraddr);
    strcpy(rejoinport, loginserverport);
    strcpy(rejoincap, TABLE_SERVERs);
    rejoinnumtries = NUMTRIES;
  }

#if DEBUGCONN
  {
    char s[2000];
    sprintf(s, "Rejoining at %s:%s as %s", rejoinaddr, rejoinport, rejoincap);
    DEBUG(talkmsg(s));
  }
#endif

  status("Attempting to rejoin the table tree (do not be alarmed).");
  if (!join(rejoinaddr, rejoinport, rejoincap, rejoinnumtries)) {
#if DEBUGCONN
    DEBUG(talkmsg("Will probably next try rejoining at loginserver"));
#endif
    strcpy(rejoinaddr, loginserveraddr);
    strcpy(rejoinport, loginserverport);
    strcpy(rejoincap, TABLE_SERVERs);
    rejoinnumtries = NUMTRIES;
  }

#if DEBUGCONN
  DEBUG(talkmsg("Done with rejoin attempt"));
#endif
}

void requestseat(int which)
{
  extern bool spec;

  if (parent == NULL && !tablehostmode) {
    errormsg("You can't sit down when you aren't at a table");
    return;
  }
  if (which != Noseat && !unoccupied(seattochar[which])) {
    if (myseat == which) {
      char s[100];
      sprintf(s, "You are already sitting %c", seattochar[which]);
      status(s);
    } else errormsg("That seat is taken");
  } else if (seated && spec && which != Noseat) {
    errormsg("You are a spectator and you are seated at the table; therefore you aren't allowed to change seats");
  } else if (!seated && spec && which != Noseat) {
    errormsg("Spectators are not allowed to take a seat in the middle of hand");
  } else {
    if (which != Noseat) {
      status("Requesting seat...");
      selfmessage(makemsg4(REQUEST_SEAT, myname, seattostring[which],
			   localIPaddr, localport));
    } else
      if (myseat != Noseat) selfmessage(makemsg4(REQUEST_SEAT, myname, "0",
						 localIPaddr, localport));
      else status("You already are a kibitzer");
  }
}

/* Close the connstr that sent us this message.  Used by the
   loginserver to disconnect you after it has answered you, for example. */
static void connclose(void)
{
  TclDo3("catch {FloaterClose ", connstr, "}");
}

static void handlemessage(message *m, char *msg)
{
  int numargs = countargs(m);
  char **argv = m->args;
#if DBG
  static int msgcount = 0;
#endif
  if (m->kind == '\0') executionlog("handlemessage: ", "null kind");
  else {
    char s[2] = {m->kind, '\0'};
    executionlog("handlemessage: ", s);
  }

  if (tablebroadcast(m->kind) || globalbroadcast(m->kind)) rebroadcast(m);

#if DBG
  if (hasWindows)
    printf("%s(%d): start with %c msg\n", myoutputname, msgcount, m->kind);
#endif
  assert(m->kind != '\0');

  if (!hasWindows) needrefresh = TRUE;
  switch (m->kind) {

    /* Note: bridge specific stuff follows */

#ifdef RESULTSERVER
  case REQUEST_RESULT:
    if (numargs != 2) goto wrongargs;
    resultrequest(argv[1], connstr);
    if (argv[0][0] == 'Y') connclose();
    break;
  case RESULT:
    if (numargs != 9) goto wrongargs;
    if (isCompetitiveHandname(argv[0]))
      result(argv[0], atoi(argv[1]), argv[2], argv[3], argv[4], argv[5],
	     argv[6], argv[7], argv[8], msg);
    if (!startingup) {
      resultrequest(argv[0], connstr);
      connclose();
    }
    break;
#else
  case RESULT:
    if (numargs != 9) goto wrongargs;
    result(argv[0], atoi(argv[1]), argv[2], argv[3], argv[4], argv[5],
	   argv[6], argv[7], argv[8], msg);
    break;
#endif
  case RESULT_DUMP:
    if (numargs != 4) goto wrongargs;
    if (streq(argv[1], "done")) {
      if (atoi(argv[2]) > 1 || haveseen(atoi(argv[2]), atoi(argv[3])))
	dumpresult(argv[0]);
    } else tabmulti(argv[1]);
    break;

  case PASS_STATUS:
    if (numargs != 2) goto wrongargs;
    if (filehandinfo(m)) broadcast_curpassstate();
    break;

  case NEW_HAND:
    if (numargs != 8) goto wrongargs; else goto fileinfo;
  case AUCTION_STATUS:
    if (numargs != 2) goto wrongargs; else goto fileinfo;
  case PLAY_STATUS:
    if (numargs != 2) goto wrongargs;
    /* Only tablehost can end the hand */
    if (numcards_(argv[1]) == 52 && !streq(m->from, tablehostname)) {
      if (streq(myname, tablehostname))
	selfmessage(makemsg2(PLAY_STATUS, argv[0], argv[1]));
      else
	sendtoparent(msgtotext(m));
      break;
    }
    /* fall through */
  fileinfo:
    if (filehandinfo(m)) {
      if (seated) UIupdate();
      rebroadcast(m);
    }
    break;

  case ANNOUNCE_GLOBALDATE:
    /* this message is used both to announce the date and seed, and to
       request a SEEN message from everyone who is seated */
    if (numargs != 2) goto wrongargs;
    if (!streq(argv[0], globaldate)) {
      setglobaldate(argv[0]);
      setglobalseed(argv[1]);
      /*    set_seconds_to_next_week(argv[2]);*/
      resetseen();
    }
    if (seated) {
      selfmessage(makemsg3(SEEN, seattostring[myseat], "0",
			   TclDo3("seen ", globaldate, "IMP")));
      selfmessage(makemsg3(SEEN, seattostring[myseat], "1",
			   TclDo3("seen ", globaldate, "MP")));
    }
    break;

  case YOU_HAVE_SEEN:
    /* This message type is sent by the loginserver to a player who logs in.
       First arg is set name; second arg is compressed bit vector indicating
       which boards have been seen. */
    if (numargs != 2) goto wrongargs;
    parse_you_have_seen(argv[0], argv[1]);
    break;

  case SEEN:
    if (numargs != 3) goto wrongargs;
    if (tablehostmode) {
      parseseen(argv[0][0], atoi(argv[1]), argv[2]);
    } else if (parent != NULL) sendmessage(parent->connstr, m);
    break;
    
    /* CC_TO_HOST message type just goes up to the table host, who then
       broadcasts a CC message.  This keeps everyone's view coherent. */
  case CC_TO_HOST:
    if (tablehostmode) {
      if (numargs != 2) goto wrongargs;
      if (!streq(argv[0], "EW") && !streq(argv[0], "NS")) goto undecipherable;
      selfmessage(makemsg2(CC, argv[0], argv[1]));
    } else if (parent != NULL) sendmessage(parent->connstr, m);
    break;
    
  case CC:
    if (numargs != 2) goto wrongargs;
    if (!streq(argv[0], "EW") && !streq(argv[0], "NS")) goto undecipherable;
    ccupdate(argv[0], argv[1]);
    break;

  case REQUEST_SEAT:
    if (tablehostmode) {
      if (numargs != 4) goto wrongargs;
      if (!isin(argv[1][0], "NSEW0")) goto undecipherable;
      if (argv[1][0] == '0') {
	/* someone getting up from a seat */
	extern char *northname, *southname, *eastname, *westname;
	char ch;

	if (safestreq(m->from, northname)) ch = 'N';
	else if (safestreq(m->from, southname)) ch = 'S';
	else if (safestreq(m->from, eastname)) ch = 'E';
	else if (safestreq(m->from, westname)) ch = 'W';
	else goto undecipherable;
	parseseen(ch, -1, "?");
	selfmessage(makemsg4(SEATED, argv[0], argv[1], argv[2], argv[3]));
      } else if (unoccupied(argv[1][0])) {
	/* we don't know what new guy has seen */
	parseseen(argv[1][0], -1, "?");
	selfmessage(makemsg4(SEATED, argv[0], argv[1], argv[2], argv[3]));
      }
    } else if (parent != NULL) sendmessage(parent->connstr, m);
    break;
    
  case SEATED:
    if (numargs != 4) goto wrongargs;
    if (streq(myname, argv[0])) {
      if (isin(argv[1][0], "NSEW")) {
	extern bool duplicate; /* from br.c */
	if (tablehostmode) checknewweek();
	selfmessage(makemsg3(SEEN, argv[1], "0",
			     TclDo3("seen ", globaldate, "IMP")));
	selfmessage(makemsg3(SEEN, argv[1], "1",
			     TclDo3("seen ", globaldate, "MP")));
      }
    }
    sit(argv[0], argv[1][0], argv[2], argv[3]);
    break;
    
    /* Note: end of bridge specific section */
    
  case SAY:
    if (numargs != 2) goto wrongargs;
    talkmsg3(argv[0], ": ", argv[1]);
    break;
    
  case SAY_TO_ONE:
    if (numargs != 3) goto wrongargs;
    {
      bool senderspec = atob(argv[0]);
      char *who = argv[1], *what = argv[2], *owho = outputname(who);

      extern bool spec;
      
      if (streq(who, myoutputname)) {
	if (streq(what, BEEP_STR)) {
	  UIbeep();
	  status3("BEEP! (from ", outputname(m->from), ")");
	} else if (spec == senderspec || !senderspec)
	  talkmsg3(owho, "- ", what);
	else
	  warningmsg2(owho,
		     ", a spectator, is trying to send you a private message");
      } else if (streq(what, BEEP_STR))
	status4("Beep sent from ", outputname(m->from), " to ", owho);
    }
    break;
    
  case SAY_TO_SPEC:
    if (numargs != 2) goto wrongargs;
    {
      extern bool spec; /* from UI.c */
      if (spec) talkmsg3(argv[0], "% ", argv[1]);
    }
    break;
    
  case SAY_EXCEPT_PARD:
    if (numargs != 3) goto wrongargs;
    if (!(seated && myseat == (atoi(argv[2]) ^ 2)))
      talkmsg3(argv[0], "! ", argv[1]);
    break;
    
  case SAY_TO_OPP:
    if (numargs != 4 && numargs != 3) goto wrongargs;
    if (seated && (myseat == atoi(argv[2]) ||
		   (numargs == 4 && myseat == atoi(argv[3]))))
      talkmsg3(argv[0], numargs == 3 ? "- " : "= ", argv[1]);
    break;
    
  case JOIN_ELSEWHERE:
    /* request that we join somewhere else */
    if (numargs != 4) goto wrongargs;
    if (parent == NULL) goto spoof;  /* spoofing?? */
    if (!streq(m->from, parent->name))
      if (!isparentname(BOGUS_NAME) ||
	  !expecting_join_elsewhere)
	goto spoof;    /* spoofing?? */
    oldparent = parent;
    parent = NULL;
/*    puts("setting parent to NULL at 1418"); */
    status("Shunted...");
    if (join(argv[1], argv[2], argv[3], NUMTRIES)) {
      /* communication established with new parent */
      TclDo2("FloaterClose ", oldparent->connstr);
      freeconn(oldparent);
    } else {
      parent = oldparent;
      oldparent = NULL;
    }
    break;
    
  case REJECTED_JOIN:
    /* rejected outright --- compare with JOIN_ELSEWHERE */
    if (numargs != 2) goto wrongargs;
    if (isupper(argv[0][0])) status(argv[0]);
    else status3(outputname(m->from), " ", argv[0]);
    if (argv[1][0] == KIBITZER || argv[1][0] == TABLE_SERVER) {
      freeconn(parent);
      parent = NULL;
/*      puts("setting parent to NULL at 1438");*/
      if (!tablehostmode) {
	state = LIMBO;
	if_not_connected_reset_tablehostname();
	if (hasWindows) UIstate(state);
      }
    }
    else if (rho != NULL && streq(m->from, rho->name)) {
      freeconn(rho);
      rho = NULL;
    }
    expecting_join_elsewhere = FALSE;
    rejoinaddr[0] = rejoinport[0] = '\0';
    break;
    
  case ACCEPTED_JOIN:
    TclDo2("shouldsendiamalive ", connstr);
    TclDo2("shouldreceiveiamalive ", connstr);
    switch (argv[0][0]) {
    case KIBITZER:
#ifndef SERVER
      sprintf(location, "kibitzing at %s's table", outputname(m->from));
      TclDo("uplevel #0 {set table_arrival_time $floaterclock}");
#endif
      broadcast(makemsg1(ANNOUNCE_CONNECT, myname));
      /* fall through */
    case TABLE_SERVER:
      addwho(myname);
      state = CONNECTED;
      if (hasWindows) UIstate(state);

      /* Copy info for possible later use if we are unexpectly disconnected;
	 currently, however, this information is never used---we always try
	 to rejoin the table tree at the top, not at our parent who left us. */
      STRCPY(rejoinaddr, argv[1] /* parent->IPaddr */);
      STRCPY(rejoinport, argv[2] /* parent->port */);
      STRCPY(rejoincap, argv[0]);

      if (argv[0][0] == TABLE_SERVER) 
	selfmessage(makemsg4(ANNOUNCE_TABLE, myname, mytabledesc,
			     localIPaddr, localport));
      expecting_join_elsewhere = FALSE;
      break;
    case LHO:
      assert(LHO_RHO_CONNECTIONS);
      if (rho != NULL) freeconn(rho);
      rho = makeconn(m->from, argv[1], argv[2], connstr);
    }
    break;
    
  case REQUEST_JOIN:
    if (numargs != 5) goto wrongargs;
    {
      char capacity = argv[4][0], *version = argv[0], *name = argv[1];
      char *IPaddr = argv[2], *port = argv[3], *caps = argv[4];

      /* would check version number for compatibility here */

      switch (capacity) {
#ifndef SERVER
      case KIBITZER:
	if (accepting_kibitzers) accept_join(name, IPaddr, port, capacity);
	else reject_join(tablehostmode ?
			 (nokibitzers ?
			  "The table is not accepting new connections" :
			  "is too busy") :
			 "is not hosting a table", caps);
	break;
      case TABLE_SERVER:
	if (accepting_tableservers) {
	  if (!shunt(connstr, caps))
	    accept_join(name, IPaddr, port, capacity);
	} else reject_join(tablehostmode ? "is too busy" :
			   "is not a table server", caps);
	break;
	/* bridge specific */
      case LHO:
	if (lho == NULL || streq(name, lho->name))
	  accept_join(name, IPaddr, port, capacity);
	else reject_join("You aren't the LHO!", caps);
	break;
	/* end of bridge specific */
#endif
#ifdef LOGINSERVER
      case TABLE_SERVER:
	STRCPY(loginservername, myname);
	STRCPY(loginserveraddr, localIPaddr);
	STRCPY(loginserverport, localport);
	/* status4(localIPaddr, ":", localport, " is loginserver location"); */

	if (version[0] != '8') {
	  sendmessage(connstr,
		      makemsg1(INFO,
			       "Please upgrade to version 1.2 or higher!"));
	  reject_join("You must upgrade to host a table", caps);
	  break;
	}

	if (strlen(tablerootaddr) == 0) {
	  status2(name, " is tableroot");
	  STRCPY(tablerootname, name);
	  STRCPY(tablerootaddr, IPaddr);
	  STRCPY(tablerootport, port);
	  accept_join(name, IPaddr, port, capacity);
	} else assert((tchildren != NULL) && shunt(connstr, caps));
	break;
      case KIBITZER:
      case LHO:
#endif
      default:
	reject_join("doesn't understand in what capacity you're trying to join", caps);
      }
    }
    break;
    
  case TABLE_DEMISE:
    if (numargs != 1) goto wrongargs;
    tables = removetable(argv[0], tables);
    update_activity_webpage_with_table_info();
    if (streq(argv[0], tablerootname))
      tablerootname[0] = tablerootaddr[0] = tablerootport[0] = '\0';
    if (streq(tablehostname, argv[0])) {
      /* the table I'm at is closing, so don't try to rejoin */
      status3("The table (hosted by ", outputname(argv[0]), ") has closed.");
      sever_all_communication();
      state = LIMBO;
      if_not_connected_reset_tablehostname();
      if (hasWindows) UIstate(state);
    }
    break;
    
  case ANNOUNCE_DISCONNECT:
    if (numargs != 1) goto wrongargs;
    TclDo3("FloaterCloseName {", argv[0], "}");
    persongone(argv[0]); /* handles bookkeeping if it was a player who left */
    if (streq(argv[0], tablerootname)) /* shouldn't happen, I don't think */
      tablerootname[0] = tablerootaddr[0] = tablerootport[0] = '\0';
    removewho(argv[0]);
    if (tablehostmode) redescribetable();
    break;
    
  case ANNOUNCE_CONNECT:
    if (numargs != 1) goto wrongargs;
    addwho(argv[0]);
    if (tablehostmode) redescribetable();
    break;
    
  case FORGET_WHO:
    if (numargs != 0) goto wrongargs;
#if DEBUGCONN
    DEBUG(status("Clearing `who' list"));
#endif
    while (who != NULL) who = freestringlist(who);
    addwho(myname);
    break;
    
/*
  case FORGET_TABLES:
    if (numargs != 0) goto wrongargs;
    while (tables != NULL) tables = freetablelist(tables);
    if (tablehostmode) addtable(myname, mytabledesc, localIPaddr, localport);
    break;
*/    
  case ANNOUNCE_PRESENCE:
    if (numargs != 3) goto wrongargs;
    addwho(argv[0]);
    if (argv[2][0] == '1') goto makespec;
    break;
    
    /* SPEC is somewhat bridge specific (might apply in similar games too) */
  case SPEC:
    /* args are name of person going spec, and handID */
    if (numargs != 2) goto wrongargs;
  makespec:
    {
      extern char *curhandID;
      make_spec(argv[0], argv[1]);
      if (curhandID == NULL || !streq(curhandID, argv[1]))
	status4(outputname(argv[0]), " is a spectator (for ",
		TclDo3("global handname; if [catch {set handname(",
		       argv[1], ")} n] "
		       "{return {next hand}} {return \"hand $n\"}"),
		")");
      else
	status2(outputname(argv[0]), " is a spectator");
    }
    break;

  case ANNOUNCE_TABLE:
    if (numargs != 4) goto wrongargs;
    addtable(argv[0], argv[1], argv[2], argv[3]);
    break;
    
  case ANNOUNCE_LOGINSERVER:
    if (numargs != 4) goto wrongargs;
    if (tablerootmode && streq(m->from, argv[0])) {
      if (parent == NULL)
	parent = makeconn(argv[0], argv[1], argv[2], connstr);
      parent->name = STRDUP(argv[0]);
    }
    
    argv[0] = TEMPCOPY(myname); /* use my name for broadcast to my children */
    STRCPY(loginservername, argv[1]);
    STRCPY(loginserveraddr, argv[2]);
    STRCPY(loginserverport, argv[3]);
    rebroadcast(m);
    break;
    
  case ANNOUNCE_TABLEHOST:
    if (numargs != 4) goto wrongargs;
    if (isparentname(BOGUS_NAME)) strncpy2(parent->name, argv[0],
					   FLOATER_MAXNAME - 1);
    argv[0] = TEMPCOPY(myname); /* use my name for broadcast to my children */
    STRCPY(tablehostname, argv[1]);
    STRCPY(tablehostaddr, argv[2]);
    STRCPY(tablehostport, argv[3]);
    rebroadcast(m);
    break;
    
  case ANNOUNCE_TABLEROOT:
    if (numargs != 4) goto wrongargs;
    if (isparentname(BOGUS_NAME)) strncpy2(parent->name, argv[0],
					   FLOATER_MAXNAME - 1);
    argv[0] = TEMPCOPY(myname);
    STRCPY(tablerootname, argv[1]);
    STRCPY(tablerootaddr, argv[2]);
    STRCPY(tablerootport, argv[3]);
    tablerootmode = tablehostmode && streq(myname, tablerootname) &&
      streq(localport, tablerootport) && streq(localIPaddr, tablerootaddr);
    rebroadcast(m);
    break;
    
  case UPDATE_LOCATION:
    if (numargs != 2) goto wrongargs;
#ifdef LOGINSERVER
    set_location_info(argv[0], argv[1]);
#else
    if (parent != NULL) sendmessage(parent->connstr, m);
#endif
    break;

#ifdef LOGINSERVER
  case CHANGEPW:
    if (numargs != 3) goto wrongargs;
    if (strexists(argv[1]) && streq(argv[1], password(argv[0]))) {
      savenewpw(argv[0], argv[2]);
      sendmessage(connstr, makemsg3(CHANGEDPW, argv[0], argv[1], argv[2]));
    } else
      sendmessage(connstr, makemsg0(WRONG_PASSWORD));
    break;

  case CHANGEEMAIL:
    if (numargs != 2) goto wrongargs;
    if (!streq(outputname(m->from), argv[0])) goto spoof;
    savenewemail(argv[0], argv[1]);
    sendmessage(connstr, makemsg2(CHANGEDEMAIL, argv[0], argv[1]));
    break;

  case LOGIN:
    if (numargs != 7) goto wrongargs;
    {
      char *IPaddr = argv[3], *port = argv[4];
      if (!streq(argv[0], FLOATER_VERSION)) {
	sendmessage(connstr, makemsg1(INFO, TEMPCAT("You are using an outdated version!  Please upgrade to ", TclGet("floater_version"))));
	sendmessage(connstr, makemsg1(INFO, "The latest news is always at http://www.floater.org/"));
	if (argv[0][0] != FLOATER_VERSION[0]) {
	  sendmessage(connstr,
		      makemsg1(INFO, "Log in request rejected!  Sorry."));
	  connclose();
	  goto done;
	}
      }

      fprintf(stderr, "login: %s on %s\n", argv[1], argv[6]);

      if (streq(argv[5], "new")) {
	if (nameinuse(argv[1])) sendmessage(connstr, makemsg0(NAME_IN_USE));
	else {
	  sendmessage(connstr, makemsg2(LOGGED_IN, argv[1],
					testConn(IPaddr, port, argv[5])));
	  TclDo5("notelogin {", argv[1], "} {", floatertime(), "}");
	  announce_tables();
	  newaccount(argv[1], argv[2]);
	}
      } else {
	if (strexists(argv[2]) && streq(argv[2], password(argv[1]))) {
	  /* won't work---need to kill the existing table!gCai... not argv[1]
	     if (omembertablelist(argv[1]))
	     selfmessage(makemsg1(TABLE_DEMISE, argv[1]));
	   */
	  sendmessage(connstr, makemsg1(INFO, "Welcome to Floater.  Initializing..."));
	  announce_seen(connstr, argv[1]);
	  announce_tables();
	  sendmessage(connstr, makemsg2(LOGGED_IN, argv[1],
					testConn(IPaddr, port, argv[5])));
	  TclDo5("notelogin {", argv[1], "} {", floatertime(), "}");
	  update_activity_webpage_with_table_info();
	} else
	  sendmessage(connstr, makemsg0(WRONG_PASSWORD));
      }
    }
    break;
#else
  case CHANGEDPW:
    if (numargs != 3) goto wrongargs;
    if (newpw != NULL && streq(newpw, argv[2])) {
      status2("Password changed for ", argv[0]);
      reset(newpw);
    }
    connclose();
    break;

  case CHANGEDEMAIL:
    if (numargs != 2) goto wrongargs;
    if (newemail != NULL && streq(newemail, argv[1])) {
      status2("Email address changed for ", argv[0]);
      reset(newemail);
    }
    connclose();
    break;

  case LOGGED_IN:
    /* First arg is my name; Second is two things concatenated:
       "new" or "" followed by "y" or "n".  The first is whether I'm
       new and should expect my password to arrive by email.
       The second is whether I am allowed to host a table. */
    if (numargs != 2) goto wrongargs;
    if (loggedin) goto spoof;
    triedtologin = loggedin = TRUE;
    setmyname(argv[0], TRUE);
    status2("You are now logged in as ", myoutputname);
    TclDo3("catch {wm title . {Floater: ", myoutputname, "}}");
    TclDo3("catch {wm iconname . {Floater: ", myoutputname, "}}");
    if (strneq(argv[1], "new", 3))
      status("You will receive your password by email");
    canhost = streq(argv[1], "newy") || streq(argv[1], "y");
    setprioruse(myname);
    connclose();
    sever_all_communication();
    break;
    
  case WRONG_PASSWORD:
    triedtologin = TRUE;
    if (numargs != 0) goto wrongargs;
    UIwrongpassword();
    connclose();
    break;
    
  case NAME_IN_USE:
    if (numargs != 0) goto wrongargs;
    if (!triedtologin || loggedin) goto spoof;
    UInameinuse();
    connclose();
    break;
    
  case GOODBYE:
    if (numargs != 0) goto wrongargs;
    {
      char *s = expecting_goodbye(connstr);

      if (!strexists(s)) goto spoof;
      if (streq(s, "listtables")) listtables();
      connclose();
      unset_expecting_goodbye(connstr);
    }
    break;

    /* claiming is bridge specific */
  case CLAIM:
  case REJECT_CLAIM:
  case ACCEPT_CLAIM:
  case RETRACT_CLAIM:
    if (numargs != 2) goto wrongargs;
    handleclaimmessage(m->kind, argv[0], atoi(argv[1]), m->from);
    break;
#endif
    
#ifdef LOGINSERVER
  case FIND:
    if (numargs != 1) goto wrongargs;
    handlefind(argv[0]);
    connclose();
    break;
#endif

  case FOUND:
    if (numargs != 1) goto wrongargs;
    foundmsg(argv[0]);
    break;

  case TABLES_REQUEST:
    if (numargs != 0) goto wrongargs;
    announce_tables();
    sendmessage(connstr, makemsg0(GOODBYE));
    break;

  case INFO:
    if (numargs != 1) goto wrongargs;
    talkmsg2("Info: ", argv[0]);
    break;

  case MULTIMESSAGE:
    {
      int i;
      for (i = 0; i < numargs; i++)
	handlemessage(parsemessage(argv[i]), argv[i]);
    }
    break;

  case '\0':
    /* Shouldn't happen, but ignore it unless we're debugging. */
#if !DBG
    return;
#endif
    /* fall through */

  undecipherable:
  spoof:
  wrongargs:
  default:
    {
      int i;
      char s[100];

      sprintf(s, "Received a bogus %c message from %s with %d args",
	      m->kind, connstr, numargs);
#if DBG
      DEBUG(talkmsg(s));
      for (i=0; i<numargs; i++) DEBUG(talkmsg(argv[i]));
#else
      warningmsg(s);
#endif
    }

#ifdef LOGINSERVER
    connclose();
#endif    
  }
done:
#if DBG
  if (hasWindows)
    printf("%s(%d): done with %c msg\n", myoutputname, msgcount++, m->kind);
#endif
  ;
}