File: host.c

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

#if ! defined (lint)
static const char *rcsid = "$Id: host.c,v 1.21 1997/08/25 05:32:33 scrappy Exp $" ;
static void use_rcsid (const char *rid) {   /* Never called */
  use_rcsid (rcsid) ; use_rcsid (rid) ;
}
#endif


#include "config.h"

#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <sys/param.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>
#include <math.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <limits.h> /* LONG_MAX */
#include <float.h>

#include "host.h"
#include "tape.h"
#include "connection.h"
#include "article.h"
#include "buffer.h"
#include "endpoint.h"
#include "innlistener.h"
#include "msgs.h"
#include "configfile.h"

#define REQ 1
#define NOTREQ 0
#define NOTREQNOADD 2

#define VALUE_OK 0
#define VALUE_TOO_HIGH 1
#define VALUE_TOO_LOW 2
#define VALUE_MISSING 3
#define VALUE_WRONG_TYPE 4

#define METHOD_STATIC 0
#define METHOD_APS 1
#define METHOD_QUEUE 2
#define METHOD_COMBINED 3

/* the limit of number of connections open when a host is
   set to 0 to mean "infinite" */
#define MAXCON 500
#define MAXCONLIMIT(xx) ((xx==0)?MAXCON:xx)

#define BACKLOGFILTER 0.7
#define BACKLOGLWM 20.0
#define BACKLOGHWM 50.0

/* time between retrying blocked hosts in seconds */
#define TRYBLOCKEDHOSTPERIOD 120

extern char *configFile ;
extern mainLogStatus (FILE *fp) ;

/* the host keeps a couple lists of these */
typedef struct proc_q_elem 
{
    Article article ;
    struct proc_q_elem *next ;
    struct proc_q_elem *prev ;
} *ProcQElem ;

typedef struct host_param_s
{
  char *peerName;
  char *ipName;
  u_int articleTimeout;
  u_int responseTimeout;
  u_int initialConnections;
  u_int absMaxConnections;
  u_int maxChecks;
  u_short portNum;
  u_int closePeriod;
  u_int dynamicMethod;
  bool wantStreaming;
  double lowPassLow; /* as percentages */
  double lowPassHigh;
  double lowPassFilter;
  u_int backlogLimit ;
  u_int backlogLimitHigh ;
  double backlogFactor ;
  double dynBacklogFilter ;
  double dynBacklogLowWaterMark ;
  double dynBacklogHighWaterMark ;
} *HostParams ;

struct host_s 
{
    InnListener listener ;      /* who created me. */
    char **ipAddrs ;		/* the ip addresses of the remote */
    char **nextIpAddr ;		/* the next ip address to hand out */

    Connection *connections ;   /* NULL-terminated list of all connections */
    bool *cxnActive ;           /* true if the corresponding cxn is active */
    bool *cxnSleeping ;         /* true if the connection is sleeping */
    u_int maxConnections;       /* maximum no of cxns controlled by method */
    u_int activeCxns ;          /* number of connections currently active */
    u_int sleepingCxns ;        /* number of connections currently sleeping */
    Connection blockedCxn ;     /* the first connection to get the 400 banner*/
    Connection notThisCxn ;	/* don't offer articles to this connection */

    HostParams params;          /* Parameters from config file */

    bool remoteStreams ;        /* true if remote supports streaming */
    
    ProcQElem queued ;          /* articles done nothing with yet. */
    ProcQElem queuedTail ;

    ProcQElem processed ;       /* articles given to a Connection */
    ProcQElem processedTail ;
    
    TimeoutId statsId ;         /* timeout id for stats logging. */
    TimeoutId ChkCxnsId ;     /* timeout id for dynamic connections */

    Tape myTape ;
    
    bool backedUp ;             /* set to true when all cxns are full */
    u_int backlog ;             /* number of arts in `queued' queue */

    bool loggedModeOn ;         /* true if we logged going into no-CHECK mode */
    bool loggedModeOff ;        /* true if we logged going out of no-CHECK mode */

    bool loggedBacklog ;        /* true if we already logged the fact */
    bool notifiedChangedRemBlckd ; /* true if we logged a new response 400 */
    bool removeOnReload ;	/* true if host should be removed at end of
				 * config reload
				 */
    bool isDynamic;             /* true if host created dynamically */

    /* these numbers get reset periodically (after a 'final' logging). */
    u_int artsOffered ;         /* # of articles we offered to remote. */
    u_int artsAccepted ;        /* # of articles succesfully transferred */
    u_int artsNotWanted ;       /* # of articles remote already had */
    u_int artsRejected ;        /* # of articles remote rejected */
    u_int artsDeferred ;        /* # of articles remote asked us to retry */
    u_int artsMissing ;         /* # of articles whose file was missing. */
    u_int artsToTape ;          /* # of articles given to tape */
    u_int artsQueueOverflow ;   /* # of articles that overflowed `queued' */
    u_int artsCxnDrop ;         /* # of articles caught in dead cxn */
    u_int artsHostSleep ;       /* # of articles spooled by sleeping host */
    u_int artsHostClose ;       /* # of articles caught by closing host */
    u_int artsFromTape ;        /* # of articles we pulled off tape */

    /* Dynamic Peerage - MGF */
    u_int artsProcLastPeriod ;  /* # of articles processed in last period */
    u_int secsInLastPeriod ;    /* Number of seconds in last period */
    u_int lastCheckPoint ;      /* total articles at end of last period */
    u_int lastSentCheckPoint ;  /* total articles sent end of last period */
    u_int lastTotalCheckPoint ; /* total articles total end of last period */
    bool maxCxnChk ;            /* check for maxConnections */
    time_t lastMaxCxnTime ;     /* last time a maxConnections increased */
    time_t lastChkTime;         /* last time a check was made for maxConnect */
    u_int nextCxnTimeChk ;      /* next check for maxConnect */

    double backlogFilter;        /* IIR filter for size of backlog */

    /* These numbers are as above, but for the life of the process. */
    u_int gArtsOffered ;        
    u_int gArtsAccepted ;
    u_int gArtsNotWanted ;
    u_int gArtsRejected ;
    u_int gArtsDeferred ;
    u_int gArtsMissing ;
    u_int gArtsToTape ;
    u_int gArtsQueueOverflow ;
    u_int gArtsCxnDrop ;
    u_int gArtsHostSleep ;
    u_int gArtsHostClose ;
    u_int gArtsFromTape ;

    time_t firstConnectTime ;   /* time of first connect. */
    time_t connectTime ;        /* the time the first connection was fully
                                   set up (MODE STREAM and everything
                                   else). */
    time_t spoolTime ;          /* the time the Host had to revert to
                                   spooling articles to tape. */
    time_t lastSpoolTime ;      /* the time the last time the Host had to
                                   revert to spooling articles to tape. */
    time_t nextIpLookup ;	/* time of last IP name resolution */

    char *blockedReason ;       /* what the 400 from the remote says. */
    
    Host next ;                 /* for global list of hosts. */

    u_int blNone ;              /* number of times the backlog was 0 */
    u_int blFull ;              /* number of times the backlog was full */
    u_int blQuartile[4] ;       /* number of times in each quartile */
    u_long blAccum ;            /* cumulative backlog for computing mean */
    u_int blCount ;             /* the sample count */
};

/* A holder for the info we got out of the config file, but couldn't create
   the Host object for (normally due to lock-file problems).*/

typedef struct host_holder_s
{
  HostParams params;
  struct host_holder_s *next ;
} *HostHolder ;


/* These numbers are as above, but for all hosts over
   the life of the process. */
long procArtsOffered ;        
long procArtsAccepted ;
long procArtsNotWanted ;
long procArtsRejected ;
long procArtsDeferred ;
long procArtsMissing ;

static HostParams defaultParams=NULL;

static HostHolder blockedHosts ; /* lists of hosts we can't lock */
static TimeoutId tryBlockedHostsId = 0 ;
static time_t lastStatusLog ;

  /*
   * Host object private methods.
   */
static void articleGone (Host host, Connection cxn, Article article) ;
static void hostStopSpooling (Host host) ;
static void hostStartSpooling (Host host) ;
static void hostLogStats (Host host, bool final) ;
static void hostStatsTimeoutCbk (TimeoutId tid, void *data) ;
static void backlogToTape (Host host) ;
static void queuesToTape (Host host) ;
static bool amClosing (Host host) ;
static void hostLogStatus (void) ;
static void hostPrintStatus (Host host, FILE *fp) ;
static int validateBool (FILE *fp, const char *name,
                         int required, bool setval,
			 scope * sc, u_int inh);
static int validateReal (FILE *fp, const char *name, double low,
			 double high, int required, double setval,
			 scope * sc, u_int inh);
static int validateInteger (FILE *fp, const char *name,
			    long low, long high, int required, long setval,
			    scope * sc, u_int inh);

static HostParams newHostParams(HostParams p);
static void freeHostParams(HostParams params);

static HostHolder FindBlockedHost(const char *name);
static void addBlockedHost(HostParams params);
static void tryBlockedHosts(TimeoutId tid, void *data);
static Host newHost (InnListener listener, HostParams p);

static HostParams getHostInfo (void);
static HostParams hostDetails (scope *s,
			       char *name,
			       bool isDefault,
			       FILE *fp);

static Host findHostByName (char *name) ;
static void hostCleanup (void) ;
static void hostAlterMaxConnections(Host host,
				    u_int absMaxCxns, u_int maxCxns,
				    bool makeConnect);

/* article queue management functions */
static Article remHead (ProcQElem *head, ProcQElem *tail) ;
static void queueArticle (Article article, ProcQElem *head, ProcQElem *tail) ;
static bool remArticle (Article article, ProcQElem *head, ProcQElem *tail) ;





/*
 * Host class data
 */

/* if true then when a Host logs its stats, it has all its connections
   log theirs too. */
static bool logConnectionStats = (bool) LOG_CONNECTION_STATS ;

/* The frequency in seconds with which a Host will log its stats. */
static time_t statsPeriod = STATS_PERIOD ;
static time_t statsResetPeriod = STATS_RESET_PERIOD ;

static Host gHostList = NULL ;

static u_int gHostCount = 0 ;

static u_int maxIpNameLen = 0 ;
static u_int maxPeerNameLen = 0 ;

static u_int hostHighwater = HOST_HIGHWATER ;
static time_t start ;
static char startTime [30] ;    /* for ctime(3) */
static pid_t myPid ;

static char *statusFile = NULL ;
static u_int dnsRetPeriod ;
static u_int dnsExpPeriod ;

static bool genHtml = false ;

/*******************************************************************/
/*                  PUBLIC FUNCTIONS                               */
/*******************************************************************/


/* function called when the config file is loaded */
int hostConfigLoadCbk (void *data)
{
  int rval = 1, bval ;
  long iv ;
  FILE *fp = (FILE *) data ;
  char *p ;


  dprintf(1,"hostConfigLoadCbk\n");

  if (defaultParams)
    {
      freeHostParams(defaultParams);
      defaultParams=NULL;
    }
   
  /* get optional global defaults */
  if (getInteger (topScope,"dns-retry",&iv,NO_INHERIT))
    {
      if (iv < 1)
        {
          rval = 0 ;
          logOrPrint (LOG_ERR,fp,LESS_THAN_ONE,"dns-retry",
                      iv,"global scope",(long)DNS_RETRY_PERIOD) ;
          iv = DNS_RETRY_PERIOD ;
        }
    }
  else
    iv = DNS_RETRY_PERIOD ;
  dnsRetPeriod = (u_int) iv ;
  
  
  if (getInteger (topScope,"dns-expire",&iv,NO_INHERIT))
    {
      if (iv < 1)
        {
          rval = 0 ;
          logOrPrint (LOG_ERR,fp,LESS_THAN_ONE,"dns-expire",iv,
                      "global scope",(long)DNS_EXPIRE_PERIOD) ;
          iv = DNS_EXPIRE_PERIOD ;
        }
    }
  else
    iv = DNS_EXPIRE_PERIOD ;
  dnsExpPeriod = (u_int) iv ;

  if (getBool (topScope,"gen-html",&bval,NO_INHERIT))
    genHtml = (bval ? true : false) ;
  else
    genHtml = GEN_HTML ;
  
  
  if (getString (topScope,"status-file",&p,NO_INHERIT))
    {
      hostSetStatusFile (p) ;
      FREE (p) ;
    }
  else
    hostSetStatusFile (INNFEED_STATUS) ;
  
  
  if (getBool (topScope,"connection-stats",&bval,NO_INHERIT))
    logConnectionStats = (bval ? true : false) ;
  else
    logConnectionStats = (LOG_CONNECTION_STATS ? true : false) ;


  if (getInteger (topScope,"host-queue-highwater", &iv,NO_INHERIT))
    {
      if (iv < 0)
        {
          rval = 0 ;
          logOrPrint (LOG_ERR,fp,LESS_THAN_ZERO,"host-queue-highwater",
                      iv,"global scope",(long) HOST_HIGHWATER) ;
          iv = HOST_HIGHWATER ;
        }
    }
  else
    iv = HOST_HIGHWATER ;
  hostHighwater = (u_int) iv ;

  if (getInteger (topScope,"stats-period",&iv,NO_INHERIT))
    {
      if (iv < 0)
        {
          rval = 0 ;
          logOrPrint (LOG_ERR,fp,LESS_THAN_ZERO,"stats-period",
                      iv,"global scope",(long)STATS_PERIOD) ;
          iv = STATS_PERIOD ;
        }
    }
  else
    iv = STATS_PERIOD ;
  statsPeriod = (u_int) iv ;


  if (getInteger (topScope,"stats-reset",&iv,NO_INHERIT))
    {
      if (iv < 0)
        {
          rval = 0 ;
          logOrPrint (LOG_ERR,fp,LESS_THAN_ZERO,"stats-reset",iv,
                      "global scope",(long)STATS_RESET_PERIOD) ;
          iv = STATS_RESET_PERIOD ;
        }
    }
  else
    iv = STATS_RESET_PERIOD ;
  statsResetPeriod = (u_int) iv ;
  
  defaultParams=hostDetails(topScope, NULL, true, fp);
  ASSERT(defaultParams!=NULL);

  return rval ;
}

/*
 * make a new HostParams structure copying an existing one
 * or from compiled defaults
 */

HostParams newHostParams(HostParams p)
{
  HostParams params;

  params = ALLOC (struct host_param_s,1) ;
  ASSERT (params != NULL);

  if (p != NULL)
    {
      /* Copy old stuff in */
      memcpy ((char *) params, (char *) p, sizeof(struct host_param_s));
      if (params->peerName)
	params->peerName = strdup(params->peerName);
      if (params->ipName)
	params->ipName = strdup(params->ipName);
    }
  else
    {
      /* Fill in defaults */
      params->peerName=NULL;
      params->ipName=NULL;
      params->articleTimeout=ARTTOUT;
      params->responseTimeout=RESPTOUT;
      params->initialConnections=INIT_CXNS;
      params->absMaxConnections=MAX_CXNS;
      params->maxChecks=MAX_Q_SIZE;
      params->portNum=PORTNUM;
      params->closePeriod=CLOSE_PERIOD;
      params->dynamicMethod=METHOD_STATIC;
      params->wantStreaming=STREAM;
      params->lowPassLow=NOCHECKLOW;
      params->lowPassHigh=NOCHECKHIGH;
      params->lowPassFilter=FILTERVALUE;
      params->backlogLimit=BLOGLIMIT;
      params->backlogLimitHigh=BLOGLIMIT_HIGH ;
      params->backlogFactor=LIMIT_FUDGE ;
      params->dynBacklogFilter = BACKLOGFILTER ;
      params->dynBacklogLowWaterMark = BACKLOGLWM;
      params->dynBacklogHighWaterMark = BACKLOGHWM;
    }
  return (params);
}
            
/*
 * Free up a param structure
 */

void freeHostParams(HostParams params)
{
  ASSERT(params != NULL);
  if (params->peerName)
    FREE (params->peerName) ;
  if (params->ipName)
    FREE (params->ipName) ;
  FREE (params) ;
}  

void hostReconfigure(Host h, HostParams params)
{
  u_int i, absMaxCxns ;
  double oldBacklogFilter ;
  
  if (strcmp(h->params->ipName, params->ipName) != 0)
    {
      FREE (h->params->ipName) ;
      h->params->ipName = strdup (params->ipName) ;
      h->nextIpLookup = theTime () ;
    }
  
  /* Put in new parameters
     Unfortunately we can't blat on top of absMaxConnections
     as we need to do some resizing here
     */
  
  ASSERT (h->params != NULL);
  
  oldBacklogFilter = h->params->dynBacklogFilter;
  i = h->params->absMaxConnections; /* keep old value */
  absMaxCxns = params->absMaxConnections;
  /* Use this set of params and allocate, and free
   * up the old
   */
  freeHostParams(h->params);
  h->params = params;
  h->params->absMaxConnections = i; /* restore old value */
  
  /* If the backlog filter value has changed, reset the
   * filter as the value therein will be screwy
   */
  if (h->params->dynBacklogFilter != oldBacklogFilter)
    h->backlogFilter = ((h->params->dynBacklogLowWaterMark
			 + h->params->dynBacklogHighWaterMark)
			/200.0 /(1.0-h->params->dynBacklogFilter));
  
  /* We call this anyway - it does nothing if the values
   * haven't changed. This is because doing things like
   * just changing "dynamic-method" requires this call
   * to be made
   */
  hostAlterMaxConnections(h, absMaxCxns, h->maxConnections, false);
  
  for ( i = 0 ; i < MAXCONLIMIT(h->params->absMaxConnections) ; i++ )
    if (h->connections[i] != NULL)
      cxnSetCheckThresholds (h->connections[i],
			     h->params->lowPassLow,
			     h->params->lowPassHigh,
			     h->params->lowPassFilter) ;
  
  /* XXX how to handle initCxns change? */
}


void configHosts (bool talkSelf)
{
  Host nHost, h, q ;
  HostHolder hh, hi ;
  HostParams params;

  /* Remove the current blocked host list */
  for (hh = blockedHosts, hi = NULL ; hh != NULL ; hh = hi)
    {
      freeHostParams(hh->params);
      hi = hh->next ;
      FREE (hh) ;
    }
  blockedHosts = NULL ;

  closeDroppedArticleFile () ;
  openDroppedArticleFile () ;
  
  while ((params = getHostInfo ()) !=NULL )
    {
      h = findHostByName (params->peerName) ;
      /* We know the host isn't blocked as we cleared the blocked list */
      /* Have we already got this host up and running ?*/
      if ( h != NULL )
	{
	  hostReconfigure(h, params);
	  h->removeOnReload = false ; /* Don't remove at the end */
	}
      else
        {
	    
	  /* It's a host we haven't seen from the config file before */
	  nHost = newHost (mainListener, params);

	  if (nHost == NULL)
	    {
	      addBlockedHost(params);
               
	      syslog (LOG_ERR,NO_HOST,params->peerName) ;
	    }
	  else 
	    {
	      if (params->initialConnections == 0 && talkSelf)
		syslog (LOG_NOTICE,BATCH_AND_NO_CXNS,params->peerName) ;

	      if ( !listenerAddPeer (mainListener,nHost) )
		die ("failed to add a new peer\n") ;
	    }
	}

    }
  

  for (h = gHostList; h != NULL; h = q) 
    {
      q = h->next ;
      if (h->removeOnReload)
	{
	  if (h->isDynamic)
	    {
	      /* change to the new default parameters */
	      params = newHostParams(defaultParams);
	      ASSERT(params->peerName == NULL);
	      ASSERT(params->ipName == NULL);
	      ASSERT(h->params->peerName != NULL);
	      ASSERT(h->params->ipName != NULL);
	      params->peerName = strdup(h->params->peerName);
	      params->ipName = strdup(h->params->ipName);
	      hostReconfigure(h, params);
	      h->removeOnReload = true;
	    }
	  else
	    hostClose (h) ;         /* h may be deleted in here. */
	}
      else
        /* prime it for the next config file read */
        h->removeOnReload = true ;
    }

  hostLogStatus () ;
}


void hostAlterMaxConnections(Host host,
			     u_int absMaxCxns, u_int maxCxns,
			     bool makeConnect)
{
  u_int lAbsMaxCxns;
  u_int i;
  
  /* Fix 0 unlimited case */
  lAbsMaxCxns = MAXCONLIMIT(absMaxCxns);
  
  /* Don't accept 0 for maxCxns */
  maxCxns=MAXCONLIMIT(maxCxns);
  
  if ( host->params->dynamicMethod == METHOD_STATIC)
    {
      /* If running static, ignore the maxCxns passed in, we'll
	 just use absMaxCxns
	 */
      maxCxns = lAbsMaxCxns;
    }
  
  if ( maxCxns > lAbsMaxCxns)
    {
      /* ensure maxCxns is of the correct form */
      maxCxns = lAbsMaxCxns;
    }

  if ((maxCxns < host->maxConnections) && (host->connections != NULL))
    {
      /* We are going to have to nuke some connections, as the current
         max is now greater than the new max
	 */
      for ( i = host->maxConnections ; i > maxCxns ; i-- )
	{
	  /* XXX this is harsh, and arguably there could be a
	     cleaner way of doing it.  the problem being addressed
	     by doing it this way is that eventually a connection
	     closed cleanly via cxnClose can end up ultimately
	     calling hostCxnDead after h->maxConnections has
	     been lowered and the relevant arrays downsized.
	     If trashing the old, unallocated space in
	     hostCxnDead doesn't kill the process, the
	     ASSERT against h->maxConnections surely will.
	     */
	  if (host->connections[i - 1] != NULL)
	    {
	      cxnNuke (host->connections[i-1]) ;
	      host->connections[i-1] = NULL;
	    }
	}
      host->maxConnections = maxCxns ;
    }
  
  if (host->connections)
    for (i = host->maxConnections ; i <= MAXCONLIMIT(host->params->absMaxConnections) ; i++)
      {
	/* Ensure we've got an empty values only beyond the maxConnection
	   water mark.
	   */
	ASSERT (host->connections[i] == NULL);
      }
  
  if ((lAbsMaxCxns != MAXCONLIMIT(host->params->absMaxConnections)) ||
      (host->connections == NULL))
    {
      /* we need to change the size of the connection array */
      if (host->connections == NULL)
	{
	  /* not yet allocated */
	  
	  host->connections = CALLOC (Connection, lAbsMaxCxns + 1) ;
	  ASSERT (host->connections != NULL) ;
	  
	  ASSERT (host->cxnActive == NULL);
	  host->cxnActive = CALLOC (bool, lAbsMaxCxns) ;
	  ASSERT (host->cxnActive != NULL) ;
	  
	  ASSERT (host->cxnSleeping == NULL) ;
	  host->cxnSleeping = CALLOC (bool, lAbsMaxCxns) ;
	  ASSERT (host->cxnSleeping != NULL) ;
	  
	  for (i = 0 ; i < lAbsMaxCxns ; i++)
	    {
	      host->connections [i] = NULL ;
	      host->cxnActive[i] = false ;
	      host->cxnSleeping[i] = false ;
	    }
	  host->connections[lAbsMaxCxns] = NULL;
	}
      else
	{
	  host->connections =
	    REALLOC (host->connections, Connection, lAbsMaxCxns + 1);
	  ASSERT (host->connections != NULL) ;
	  host->cxnActive = REALLOC (host->cxnActive, bool, lAbsMaxCxns) ;
	  ASSERT (host->cxnActive != NULL) ;
	  host->cxnSleeping = REALLOC (host->cxnSleeping, bool, lAbsMaxCxns) ;
	  ASSERT (host->cxnSleeping != NULL) ;

	  if (lAbsMaxCxns > MAXCONLIMIT(host->params->absMaxConnections))
	    {
	      for (i = MAXCONLIMIT(host->params->absMaxConnections) ;
		   i < lAbsMaxCxns ; i++)
		{
		  host->connections[i+1] = NULL; /* array always 1 larger */
		  host->cxnActive[i] = false ;
		  host->cxnSleeping[i] = false ;
		}
	    }
	}
      host->params->absMaxConnections = absMaxCxns;
    }    
  /* if maximum was raised, establish the new connexions
     (but don't start using them).
     */
  if ( maxCxns > host->maxConnections)
    {
      i = host->maxConnections ;
      /* need to set host->maxConnections before cxnWait() */
      host->maxConnections = maxCxns;

      while ( i < maxCxns )
	{
	  host->cxnActive [i] = false ;
	  host->cxnSleeping [i] = false ;
	  /* create a new connection */
	  host->connections [i] =
	    newConnection (host, i,
			   host->params->ipName,
			   host->params->articleTimeout,
			   host->params->portNum,
			   host->params->responseTimeout,
			   host->params->closePeriod,
			   host->params->lowPassLow,
			   host->params->lowPassHigh,
			   host->params->lowPassFilter) ;

	  /* connect if low enough numbered, or we were forced to */
	  if ((i < host->params->initialConnections) || makeConnect)
	    cxnConnect (host->connections [i]) ;
	  else
	    cxnWait (host->connections [i]) ;
	  i++ ;
	}
    }

}

/*
 * Find a host on the blocked host list
 */

static HostHolder FindBlockedHost(const char *name)
{
  HostHolder hh = blockedHosts;
  while (hh != NULL)
    if ((hh->params) && (hh->params->peerName) &&
	(strcmp(name,hh->params->peerName) == 0))
      return hh;
    else
      hh=hh->next;
  return NULL;
}

static void addBlockedHost(HostParams params)
{
  HostHolder hh;

  hh = ALLOC (struct host_holder_s,1) ;
  /* Use this set of params */
	  
  hh->params = params;
  
  hh->next = blockedHosts ;
  blockedHosts = hh ;
}

/*
 * We iterate through the blocked host list and try and reconnect ones
 * where we couldn't get a lock
 */
static void tryBlockedHosts(TimeoutId tid /*unused*/ , void *data /*unused*/ )
{
  HostHolder hh,hi;
  HostParams params;
  
  hh = blockedHosts; /* Get start of our queue */
  blockedHosts = NULL ; /* remove them all from the queue of hosts */

  while (hh != NULL)
    {
      params = hh->params;
      hi= hh->next;
      FREE(hh);
      hh = hi;

      if (params && params->peerName)
	{
	  if (findHostByName(params->peerName)!=NULL)
	    {
	      /* Wierd, someone's managed to start it when it's on
	       * the blocked list. Just silently discard.
	       */
	      freeHostParams(params);
	    }
	  else
	    {
	      Host nHost;
	      nHost = newHost (mainListener, params);

	      if (nHost == NULL)
		{
		  addBlockedHost(params);
               
		  syslog (LOG_ERR,NO_HOST,params->peerName) ;
		}
	      else 
		{
		  dprintf(1,"Unblocked host %s\n",params->peerName);

		  if (params->initialConnections == 0 &&
		      listenerIsDummy(mainListener) /*talk to self*/)
		    syslog (LOG_NOTICE,BATCH_AND_NO_CXNS,params->peerName) ;

		  if ( !listenerAddPeer (mainListener,nHost) )
		    die ("failed to add a new peer\n") ;
		}
	    }
	}
    }
  tryBlockedHostsId = prepareSleep(tryBlockedHosts,
				   TRYBLOCKEDHOSTPERIOD, NULL);
}


/*
 * Create a new Host object with default parameters. Called by the
 * InnListener.
 */

Host newDefaultHost (InnListener listener,
		     const char *name) 
{
  HostParams p;
  Host h = NULL;

  if (FindBlockedHost(name)==NULL)
    {

      p=newHostParams(defaultParams);
      ASSERT(p!=NULL);

      /* relies on fact listener and names are null in default*/
      p->peerName=strdup(name);
      p->ipName=strdup(name);
      
      h=newHost (listener,p);
      h->isDynamic = true;
      h->removeOnReload = true;

      if (h==NULL)
	{
	  /* Couldn't get a lock - add to list of blocked peers */
	  addBlockedHost(p);
	  
	  syslog (LOG_ERR,NO_HOST,p->peerName) ;

	  return NULL;
	}

      syslog (LOG_NOTICE,DYNAMIC_PEER,p->peerName) ;

    }
  return h;
}

/*
 * Create a new host and attach the supplied param structure
 */

static bool inited = false ;
Host newHost (InnListener listener, HostParams p)
{
  Host nh ; 

  ASSERT (p->maxChecks > 0) ;

  if (!inited)
    {
      inited = true ;
      atexit (hostCleanup) ;
    }

  /*
   * Once only, init the first blocked host check
   */
  if (tryBlockedHostsId==0)
    tryBlockedHostsId = prepareSleep(tryBlockedHosts,
				     TRYBLOCKEDHOSTPERIOD, NULL);

  nh =  CALLOC (struct host_s, 1) ;
  ASSERT (nh != NULL) ;

  nh->params = p;
  nh->listener = listener;

  nh->connections = NULL; /* We'll get these allocated later */
  nh->cxnActive = NULL;
  nh->cxnSleeping = NULL;

  nh->activeCxns = 0 ;
  nh->sleepingCxns = 0 ;

  nh->blockedCxn = NULL ;
  nh->notThisCxn = NULL ;

  nh->queued = NULL ;
  nh->queuedTail = NULL ;

  nh->processed = NULL ;
  nh->processedTail = NULL ;
  
  nh->statsId = 0 ;
  nh->ChkCxnsId = 0 ;

  nh->myTape = newTape (nh->params->peerName,
			listenerIsDummy (nh->listener)) ;
  if (nh->myTape == NULL)
    {                           /* tape couldn't be locked, probably */
      FREE (nh->connections) ;
      FREE (nh->cxnActive) ;
      FREE (nh->cxnSleeping) ;
      
      FREE (nh) ;
      return NULL ; /* note we don't free up p */
    }

  nh->backedUp = false ;
  nh->backlog = 0 ;

  nh->loggedBacklog = false ;
  nh->loggedModeOn = false ;
  nh->loggedModeOff = false ;
  nh->notifiedChangedRemBlckd = false ;
  nh->removeOnReload = false ; /* ready for config file reload */
  nh->isDynamic = false ;

  nh->artsOffered = 0 ;
  nh->artsAccepted = 0 ;
  nh->artsNotWanted = 0 ;
  nh->artsRejected = 0 ;
  nh->artsDeferred = 0 ;
  nh->artsMissing = 0 ;
  nh->artsToTape = 0 ;
  nh->artsQueueOverflow = 0 ;
  nh->artsCxnDrop = 0 ;
  nh->artsHostSleep = 0 ;
  nh->artsHostClose = 0 ;
  nh->artsFromTape = 0 ;

  nh->artsProcLastPeriod = 0;
  nh->secsInLastPeriod = 0;
  nh->lastCheckPoint = 0;
  nh->lastSentCheckPoint = 0;
  nh->lastTotalCheckPoint = 0;
  nh->maxCxnChk = true;
  nh->lastMaxCxnTime = time(0);
  nh->lastChkTime = time(0);
  nh->nextCxnTimeChk = 30;
  nh->backlogFilter = ((nh->params->dynBacklogLowWaterMark
			+ nh->params->dynBacklogHighWaterMark)
		       /200.0 /(1.0-nh->params->dynBacklogFilter));

  nh->gArtsOffered = 0 ;
  nh->gArtsAccepted = 0 ;
  nh->gArtsNotWanted = 0 ;
  nh->gArtsRejected = 0 ;
  nh->gArtsDeferred = 0 ;
  nh->gArtsMissing = 0 ;
  nh->gArtsToTape = 0 ;
  nh->gArtsQueueOverflow = 0 ;
  nh->gArtsCxnDrop = 0 ;
  nh->gArtsHostSleep = 0 ;
  nh->gArtsHostClose = 0 ;
  nh->gArtsFromTape = 0 ;
  
  nh->firstConnectTime = 0 ;
  nh->connectTime = 0 ;
  
  nh->spoolTime = 0 ;

  nh->blNone = 0 ;
  nh->blFull = 0 ;
  nh->blQuartile[0] = nh->blQuartile[1] = nh->blQuartile[2] =
		      nh->blQuartile[3] = 0 ;
  nh->blAccum = 0;
  nh->blCount = 0;


  nh->maxConnections = 0; /* we currently have no connections allocated */

  /* Note that the following will override the initialCxns specified as
     maxCxns if we are on non-dyamic feed
   */
  hostAlterMaxConnections(nh, nh->params->absMaxConnections,
			  nh->params->initialConnections, false);

  nh->next = gHostList ;
  gHostList = nh ;
  gHostCount++ ;

  if (maxIpNameLen == 0)
    {
      start = theTime() ;
      strcpy (startTime,ctime (&start)) ;
      myPid = getpid() ;
    }
  
  if (strlen (nh->params->ipName) > maxIpNameLen)
    maxIpNameLen = strlen (nh->params->ipName) ;
  if (strlen (nh->params->peerName) > maxPeerNameLen)
    maxPeerNameLen = strlen (nh->params->peerName) ;
  
  return nh ;
}

struct in_addr *hostIpAddr (Host host)
{
  int i ;
  char *p ;
  char **newIpAddrs = NULL;
  struct in_addr ipAddr, *returnAddr ;
  struct hostent *hostEnt ;

  ASSERT(host->params != NULL);

  /* check to see if need to look up the host name */
  if (host->nextIpLookup <= theTime())
    {
      /* see if the ipName we're given is a dotted quad */
      if ( !inet_aton (host->params->ipName,&ipAddr) )
	{
	  if ((hostEnt = gethostbyname (host->params->ipName)) == NULL)
	    syslog (LOG_ERR, HOST_RESOLV_ERROR, host->params->peerName,
		    host->params->ipName, host_err_str ()) ;
	  else
	    {
	      /* figure number of pointers that need space */
	      for (i = 0 ; hostEnt->h_addr_list[i] ; i++)
		;
	      i++;		

	      newIpAddrs =
		(char **) MALLOC ( (i * sizeof(char *)) +
				  ( (i - 1) * hostEnt->h_length) ) ;
	      ASSERT (newIpAddrs != NULL) ;

	      /* copy the addresses from gethostbyname() static space */
	      p = (char *)&newIpAddrs [ i ] ;
	      i = 0;
	      for (i = 0 ; hostEnt->h_addr_list[i] ; i++)
		{
		  newIpAddrs[i] = p;
		  memcpy (p, hostEnt->h_addr_list[i], hostEnt->h_length) ;
		  p += hostEnt->h_length ;
		}
	      newIpAddrs[i] = NULL ;
	    }
	}
      else
	{
	  newIpAddrs = (char **) MALLOC (2 * sizeof(char *) + sizeof(ipAddr)) ;
	  ASSERT (newIpAddrs != NULL) ;
	  p = (char *)&newIpAddrs [ 2 ];
	  newIpAddrs[0] = p;
	  memcpy (p, (char *)&ipAddr, sizeof(ipAddr)) ;
	  newIpAddrs[1] = NULL;
	}

      if (newIpAddrs)
	{
	  if (host->ipAddrs)
	    FREE (host->ipAddrs) ;
	  host->ipAddrs = newIpAddrs ;
	  host->nextIpAddr = host->ipAddrs ;
	  host->nextIpLookup = theTime () + dnsExpPeriod ;
	}
      else
	{
	  /* failed to setup new addresses */
	  host->nextIpLookup = theTime () + dnsRetPeriod ;
	}
    }

  if (host->ipAddrs)
    {
      returnAddr = (struct in_addr *)(host->nextIpAddr[0]) ;
      if (*(++host->nextIpAddr) == NULL)
	host->nextIpAddr = host->ipAddrs ;
    }
  else
    returnAddr = NULL ;

  return returnAddr ;
}


void gPrintHostInfo (FILE *fp, u_int indentAmt)
{
  Host h ;
  char indent [INDENT_BUFFER_SIZE] ;
  u_int i ;
  
  for (i = 0 ; i < MIN(INDENT_BUFFER_SIZE - 1,indentAmt) ; i++)
    indent [i] = ' ' ;
  indent [i] = '\0' ;
  
  fprintf (fp,"%sGlobal Host list : (count %d) {\n",indent,gHostCount) ;
  
  for (h = gHostList ; h != NULL ; h = h->next)
    printHostInfo (h,fp,indentAmt + INDENT_INCR) ;
  
  fprintf (fp,"%s}\n",indent) ;
}


void printHostInfo (Host host, FILE *fp, u_int indentAmt)
{
  char indent [INDENT_BUFFER_SIZE] ;
  u_int i ;
  ProcQElem qe ;
  double cnt = (host->blCount) ? (host->blCount) : 1.0;
  
  for (i = 0 ; i < MIN(INDENT_BUFFER_SIZE - 1,indentAmt) ; i++)
    indent [i] = ' ' ;
  indent [i] = '\0' ;

  fprintf (fp,"%sHost : %p {\n",indent,host) ;

  if (host == NULL)
    {
      fprintf (fp,"%s}\n",indent) ;
      return ;
    }
  
  fprintf (fp,"%s    peer-name : %s\n",indent,host->params->peerName) ;
  fprintf (fp,"%s    ip-name : %s\n",indent,host->params->ipName) ;
  fprintf (fp,"%s    abs-max-connections : %d\n",indent,
	   host->params->absMaxConnections) ;
  fprintf (fp,"%s    active-connections : %d\n",indent,host->activeCxns) ;
  fprintf (fp,"%s    sleeping-connections : %d\n",indent,host->sleepingCxns) ;
  fprintf (fp,"%s    initial-connections : %d\n",indent,
	   host->params->initialConnections) ;
  fprintf (fp,"%s    want-streaming : %s\n",indent,
           boolToString (host->params->wantStreaming)) ;
  fprintf (fp,"%s    remote-streams : %s\n",indent,
           boolToString (host->remoteStreams)) ;
  fprintf (fp,"%s    max-checks : %d\n",indent,host->params->maxChecks) ;
  fprintf (fp,"%s    article-timeout : %d\n",indent,
	   host->params->articleTimeout) ;
  fprintf (fp,"%s    response-timeout : %d\n",indent,
	   host->params->responseTimeout) ;
  fprintf (fp,"%s    close-period : %d\n",indent,
	   host->params->closePeriod) ;
  fprintf (fp,"%s    port : %d\n",indent,host->params->portNum) ;
  fprintf (fp,"%s    dynamic-method : %d\n",indent,
	   host->params->dynamicMethod) ;
  fprintf (fp,"%s    dynamic-backlog-filter : %2.1f\n",indent,
	   host->params->dynBacklogFilter) ;
  fprintf (fp,"%s    dynamic-backlog-lwm : %2.1f\n",indent,
	   host->params->dynBacklogLowWaterMark) ;
  fprintf (fp,"%s    dynamic-backlog-hwm : %2.1f\n",indent,
	   host->params->dynBacklogHighWaterMark) ;
  fprintf (fp,"%s    no-check on : %2.1f\n",indent,
	   host->params->lowPassHigh) ;
  fprintf (fp,"%s    no-check off : %2.1f\n",indent,
	   host->params->lowPassLow) ;
  fprintf (fp,"%s    no-check filter : %2.1f\n",indent,
	   host->params->lowPassFilter) ;
  fprintf (fp,"%s    backlog-limit : %d\n",indent,
	   host->params->backlogLimit) ;
  fprintf (fp,"%s    backlog-limit-high : %d\n",indent,
	   host->params->backlogLimitHigh) ;
  fprintf (fp,"%s    backlog-factor : %2.1f\n",indent,
	   host->params->backlogFactor) ;
  fprintf (fp,"%s    max-connections : %d\n",indent,
	   host->maxConnections) ;


  fprintf (fp,"%s    statistics-id : %d\n",indent,host->statsId) ;
  fprintf (fp,"%s    ChkCxns-id : %d\n",indent,host->ChkCxnsId) ;
  fprintf (fp,"%s    backed-up : %s\n",indent,boolToString (host->backedUp));
  fprintf (fp,"%s    backlog : %d\n",indent,host->backlog) ;
  fprintf (fp,"%s    loggedModeOn : %s\n",indent,
           boolToString (host->loggedModeOn)) ;
  fprintf (fp,"%s    loggedModeOff : %s\n",indent,
           boolToString (host->loggedModeOff)) ;
  fprintf (fp,"%s    logged-backlog : %s\n",indent,
           boolToString (host->loggedBacklog)) ;
  fprintf (fp,"%s    streaming-type changed : %s\n",indent,
           boolToString (host->notifiedChangedRemBlckd)) ;
  fprintf (fp,"%s    articles offered : %d\n",indent,host->artsOffered) ;
  fprintf (fp,"%s    articles accepted : %d\n",indent,host->artsAccepted) ;
  fprintf (fp,"%s    articles not wanted : %d\n",indent,
           host->artsNotWanted) ;
  fprintf (fp,"%s    articles rejected : %d\n",indent,host->artsRejected);
  fprintf (fp,"%s    articles deferred : %d\n",indent,host->artsDeferred) ;
  fprintf (fp,"%s    articles missing : %d\n",indent,host->artsMissing) ;
  fprintf (fp,"%s    articles spooled : %d\n",indent,host->artsToTape) ;
  fprintf (fp,"%s      because of queue overflow : %d\n",indent,
           host->artsQueueOverflow) ;
  fprintf (fp,"%s      when the we closed the host : %d\n",indent,
           host->artsHostClose) ;
  fprintf (fp,"%s      because the host was asleep : %d\n",indent,
           host->artsHostSleep) ;
  fprintf (fp,"%s    articles unspooled : %d\n",indent,host->artsFromTape) ;
  fprintf (fp,"%s    articles requeued from dropped connections : %d\n",indent,
           host->artsCxnDrop) ;

  fprintf (fp,"%s    process articles offered : %d\n",indent,
           host->gArtsOffered) ;
  fprintf (fp,"%s    process articles accepted : %d\n",indent,
           host->gArtsAccepted) ;
  fprintf (fp,"%s    process articles not wanted : %d\n",indent,
           host->gArtsNotWanted) ;
  fprintf (fp,"%s    process articles rejected : %d\n",indent,
           host->gArtsRejected);
  fprintf (fp,"%s    process articles deferred : %d\n",indent,
           host->gArtsDeferred) ;
  fprintf (fp,"%s    process articles missing : %d\n",indent,
           host->gArtsMissing) ;
  fprintf (fp,"%s    process articles spooled : %d\n",indent,
           host->gArtsToTape) ;
  fprintf (fp,"%s      because of queue overflow : %d\n",indent,
           host->gArtsQueueOverflow) ;
  fprintf (fp,"%s      when the we closed the host : %d\n",indent,
           host->gArtsHostClose) ;
  fprintf (fp,"%s      because the host was asleep : %d\n",indent,
           host->gArtsHostSleep) ;
  fprintf (fp,"%s    process articles unspooled : %d\n",indent,
           host->gArtsFromTape) ;
  fprintf (fp,"%s    process articles requeued from dropped connections : %d\n",
           indent, host->gArtsCxnDrop) ;

  fprintf (fp,"%s    average (mean) queue length : %.1f\n", indent,
           (double) host->blAccum / cnt) ;
  fprintf (fp,"%s      percentage of the time empty : %.1f\n", indent,
           100.0 * host->blNone / cnt) ;
  fprintf (fp,"%s      percentage of the time >0%%-25%% : %.1f\n", indent,
           100.0 * host->blQuartile[0] / cnt) ;
  fprintf (fp,"%s      percentage of the time 25%%-50%% : %.1f\n", indent,
           100.0 * host->blQuartile[1] / cnt) ;
  fprintf (fp,"%s      percentage of the time 50%%-75%% : %.1f\n", indent,
           100.0 * host->blQuartile[2] / cnt) ;
  fprintf (fp,"%s      percentage of the time 75%%-<100%% : %.1f\n", indent,
           100.0 * host->blQuartile[3] / cnt) ;
  fprintf (fp,"%s      percentage of the time full : %.1f\n", indent,
           100.0 * host->blFull / cnt) ;
  fprintf (fp,"%s      number of samples : %u\n", indent, host->blCount) ;

  fprintf (fp,"%s    firstConnectTime : %s",indent,
           ctime (&host->firstConnectTime));
  fprintf (fp,"%s    connectTime : %s",indent,ctime (&host->connectTime));
  fprintf (fp,"%s    spoolTime : %s",indent,ctime (&host->spoolTime)) ;
  fprintf (fp,"%s    last-spool-time : %s",indent,
           ctime (&host->lastSpoolTime)) ;
  
#if 0
  fprintf (fp,"%s    tape {\n",indent) ;
  printTapeInfo (host->myTape,fp,indentAmt + INDENT_INCR) ;
  fprintf (fp,"%s    }\n",indent) ;
#else
  fprintf (fp,"%s    tape : %p\n",indent,host->myTape) ;
#endif
  
  fprintf (fp,"%s    QUEUED articles {\n",indent) ;
  for (qe = host->queued ; qe != NULL ; qe = qe->next)
    {
#if 0
      printArticleInfo (qe->article,fp,indentAmt + INDENT_INCR) ;
#else
      fprintf (fp,"%s    %p\n",indent,qe->article) ;
#endif
    }
  
  fprintf (fp,"%s    }\n",indent) ;
  
  fprintf (fp,"%s    IN PROCESS articles {\n",indent) ;
  for (qe = host->processed ; qe != NULL ; qe = qe->next)
    {
#if 0
      printArticleInfo (qe->article,fp,indentAmt + INDENT_INCR) ;
#else
      fprintf (fp,"%s    %p\n",indent,qe->article) ;
#endif
    }
  
  fprintf (fp,"%s    }\n",indent) ;

  
  
  fprintf (fp,"%s    Connections {\n",indent) ;
  for (i = 0 ; i < host->maxConnections ; i++)
    {
#if 0
      if (host->connections[i] != NULL)
        printCxnInfo (*cxn,fp,indentAmt + INDENT_INCR) ;
#else
      fprintf (fp,"%s        %p\n",indent,host->connections[i]) ;
#endif
    }
  fprintf (fp,"%s    }\n",indent) ;

  fprintf (fp,"%s    Active Connections {\n%s        ",indent,indent) ;
  for (i = 0 ; i < host->maxConnections ; i++)
    if (host->cxnActive[i])
      fprintf (fp," [%d:%p]",i,host->connections[i]) ;
  fprintf (fp,"\n%s    }\n",indent) ;

  fprintf (fp,"%s    Sleeping Connections {\n%s        ",indent,indent) ;
  for (i = 0 ; i < host->maxConnections ; i++)
    if (host->cxnSleeping[i])
      fprintf (fp," [%d:%p]",i,host->connections[i]) ;
  fprintf (fp,"\n%s    }\n",indent) ;

  fprintf (fp,"%s}\n",indent) ;
}







/* close down all the connections of the Host. All articles that are in
 * processes are still pushed out and then a QUIT is issued. The Host will
 * also spool all inprocess articles to tape incase the process is about to
 * be killed (they'll be refused next time around). When all Connections
 * report that they're gone, then the Host will delete itself.
 */
void hostClose (Host host)
{
  u_int i ;
  u_int cxnCount ;

  dprintf (1,"Closing host %s\n",host->params->peerName) ;
  
  queuesToTape (host) ;
  delTape (host->myTape) ;
  host->myTape = NULL ;
  
  hostLogStats (host,true) ;

  clearTimer (host->statsId) ;
  clearTimer (host->ChkCxnsId) ;
  
  host->connectTime = 0 ;

  /* when we call cxnTerminate() on the last Connection, the Host objects
     will end up getting deleted out from under us (via hostCxnGone()). If
     we are running with a malloc that scribbles over memory after freeing
     it, then we'd fail in the second for loop test. Trying to access
     host->maxConnections. */
  for (i = 0, cxnCount = 0 ; i < host->maxConnections ; i++) 
    cxnCount += (host->connections [i] != NULL ? 1 : 0) ;
  for (i = 0 ; i < cxnCount ; i++)
    if (host->connections[i] != NULL)
      cxnTerminate (host->connections [i]) ;
}


/*
 * check if host should get more connections opened, or some closed...
 */
void hostChkCxns(TimeoutId tid /*unused*/, void *data) {
  Host host = (Host) data;
  u_int currArticles, currSentArticles, currTotalArticles, newMaxCxns ;
  double lastAPS, currAPS, percentTaken, ratio ;
  double backlogRatio, backlogMult;

  if(!host->maxCxnChk)
    return;

  ASSERT(host->params != NULL);

  if(host->secsInLastPeriod > 0) 
    lastAPS = host->artsProcLastPeriod / (host->secsInLastPeriod * 1.0);
  else
    lastAPS = host->artsProcLastPeriod * 1.0;

  newMaxCxns = host->maxConnections;

  currArticles =        (host->gArtsAccepted + host->gArtsRejected +
                        (host->gArtsNotWanted / 4)) - host->lastCheckPoint ;

  host->lastCheckPoint = (host->gArtsAccepted + host->gArtsRejected +
			 (host->gArtsNotWanted / 4));

  currSentArticles = host->gArtsAccepted + host->gArtsRejected
                      - host->lastSentCheckPoint ;

  host->lastSentCheckPoint = host->gArtsAccepted + host->gArtsRejected;

  currTotalArticles = host->gArtsAccepted + host->gArtsRejected
                      + host->gArtsRejected + host->gArtsQueueOverflow
		      - host->lastTotalCheckPoint ;

  host->lastTotalCheckPoint = host->gArtsAccepted + host->gArtsRejected
                      + host->gArtsRejected + host->gArtsQueueOverflow ;

  currAPS = currArticles / (host->nextCxnTimeChk * 1.0) ;

  percentTaken = currSentArticles * 1.0 /
    ((currTotalArticles==0)?1:currTotalArticles);

  /* Get how full the queue is currently */
  backlogRatio = (host->backlog * 1.0 / hostHighwater);
  backlogMult = 1.0/(1.0-host->params->dynBacklogFilter);

  dprintf(1,"%s hostChkCxns - entry filter=%3.3f blmult=%3.3f blratio=%3.3f",host->params->peerName,host->backlogFilter, backlogMult, backlogRatio);

  ratio = 0.0; /* ignore APS by default */

  switch (host->params->dynamicMethod)
    {
      case METHOD_COMBINED:
        /* When a high % of articles is being taken, take notice of the
	 * APS values. However for smaller %s, quickly start to ignore this
	 * and concentrate on queue sizes
	 */
        ratio = percentTaken * percentTaken;
	/* nobreak; */
      case METHOD_QUEUE:
        /* backlogFilter is an IIR filtered version of the backlogRatio.
	 */
        host->backlogFilter *= host->params->dynBacklogFilter;
	/* Penalise anything over the backlog HWM twice as severely
	 * (otherwise we end up feeding some sites constantly
	 * just below the HWM. This way random noise makes
	 * such sites jump to one more connection
	 *
	 * Use factor (1-ratio) so if ratio is near 1 we ignore this
	 */
	if (backlogRatio>host->params->dynBacklogLowWaterMark/100.0)
	  host->backlogFilter += (backlogRatio+1.0)/2.0 * (1.0-ratio);
	else
	  host->backlogFilter += backlogRatio * (1.0-ratio);

	/*
	 * Now bump it around for APS too
	 */
	if ((currAPS - lastAPS) >= 0.1)
	  host->backlogFilter += ratio*((currAPS - lastAPS) + 1.0);
	else if ((currAPS - lastAPS) < -.2)
	  host->backlogFilter -= ratio;
	
	dprintf(1,"%s hostChkCxns - entry hwm=%3.3f lwm=%3.3f new=%3.3f [%3.3f,%3.3f]",
	       host->params->peerName,host->params->dynBacklogHighWaterMark,
	       host->params->dynBacklogLowWaterMark,host->backlogFilter, 
	       (host->params->dynBacklogLowWaterMark * backlogMult / 100.0),
	       (host->params->dynBacklogHighWaterMark * backlogMult / 100.0));

        if (host->backlogFilter <
	    (host->params->dynBacklogLowWaterMark * backlogMult / 100.0))
	  newMaxCxns--;
	else if (host->backlogFilter >
		 (host->params->dynBacklogHighWaterMark * backlogMult / 100.0))
	  newMaxCxns++;
	break;
      case METHOD_STATIC:
	/* well not much to do, just check maxConnection = absMaxConnections */
	ASSERT (host->maxConnections == MAXCONLIMIT(host->params->absMaxConnections));
	break;
      case METHOD_APS:
	if ((currAPS - lastAPS) >= 0.1)
	  newMaxCxns += (int)(currAPS - lastAPS) + 1 ;
	else if ((currAPS - lastAPS) < -.2)
	  newMaxCxns--;
	break;
    }

  dprintf(1, "hostChkCxns: Chngs %f\n", currAPS - lastAPS);

  if (newMaxCxns < 1) newMaxCxns=1;
  if (newMaxCxns > MAXCONLIMIT(host->params->absMaxConnections))
    newMaxCxns = MAXCONLIMIT(host->params->absMaxConnections);

  if (newMaxCxns != host->maxConnections)
    {
      syslog(LOG_NOTICE, HOST_MAX_CONNECTIONS,
	     host->params->peerName, host->maxConnections,newMaxCxns);
 
      host->backlogFilter= ((host->params->dynBacklogLowWaterMark
			     + host->params->dynBacklogHighWaterMark)
			    /200.0 * backlogMult);
      host->artsProcLastPeriod = currArticles ;
      host->secsInLastPeriod = host->nextCxnTimeChk ;

      /* Alter MaxConnections and in doing so ensure we connect new
	 cxns immediately if we are adding stuff
       */
      hostAlterMaxConnections(host, host->params->absMaxConnections,
			      newMaxCxns, true);
  }

  if(host->nextCxnTimeChk <= 240) host->nextCxnTimeChk *= 2;
  else host->nextCxnTimeChk = 300;
  dprintf(1, "prepareSleep hostChkCxns, %d\n", host->nextCxnTimeChk);
  host->ChkCxnsId = prepareSleep(hostChkCxns, host->nextCxnTimeChk, host);
}


/*
 * have the Host transmit the Article if possible.
 */
void hostSendArticle (Host host, Article article)
{
  ASSERT(host->params != NULL);
  if (host->spoolTime > 0)
    {                           /* all connections are asleep */
      host->artsHostSleep++ ;
      host->gArtsHostSleep++ ;
      host->artsToTape++ ;
      host->gArtsToTape++ ;
      tapeTakeArticle (host->myTape, article) ;
      return ;
    }

  /* at least one connection is feeding or waiting and there's no backlog */
  if (host->queued == NULL)
    {
      u_int idx ;
      Article extraRef ;
      Connection cxn ;
      
      extraRef = artTakeRef (article) ; /* the referrence we give away */
      
      /* stick on the queue of articles we've handed off--we're hopeful. */
      queueArticle (article,&host->processed,&host->processedTail) ;

      /* first we try to give it to one of our active connections. We
         simply start at the bottom and work our way up. This way
         connections near the end of the list will get closed sooner from
         idleness. */
      for (idx = 0 ; idx < host->maxConnections ; idx++)
        {
          if (host->cxnActive [idx] &&
              (cxn = host->connections[idx]) != host->notThisCxn &&
              cxnTakeArticle (cxn, extraRef))
	    return ;
        }

      /* Wasn't taken so try to give it to one of the waiting connections. */
      for (idx = 0 ; idx < host->maxConnections ; idx++)
        if (!host->cxnActive [idx] && !host->cxnSleeping [idx] &&
            (cxn = host->connections[idx]) != host->notThisCxn)
          {
            if (cxnTakeArticle (cxn, extraRef))
              return ;
            else
              dprintf (1,"%s Inactive connection %d refused an article\n",
                       host->params->peerName,idx) ;
          }

      /* this'll happen if all connections are feeding and all
         their queues are full, or if those not feeding are asleep. */
      dprintf (1, "Couldn't give the article to a connection\n") ;
      
      delArticle (extraRef) ;
          
      remArticle (article,&host->processed,&host->processedTail) ;
      if (!cxnCheckstate (cxn))
        {
          host->artsToTape++ ;
          host->gArtsToTape++ ;
          tapeTakeArticle (host->myTape,article) ;
          return ;
        }
    }

  /* either all the per connection queues were full or we already had
     a backlog, so there was no sense in checking. */
  queueArticle (article,&host->queued,&host->queuedTail) ;
    
  host->backlog++ ;
  backlogToTape (host) ;
}







/*
 * called by the Host's connection when the remote is refusing postings
 * from us becasue we're not allowed (banner code 400).
 */
void hostCxnBlocked (Host host, Connection cxn, char *reason)
{
  ASSERT(host->params != NULL);
#ifndef NDEBUG
  {
    u_int i ;
    
    for (i = 0 ; i < host->maxConnections ; i++)
      if (host->connections [i] == cxn)
        ASSERT (host->cxnActive [i] == false) ;
  }
#endif

  if (host->blockedReason == NULL)
    host->blockedReason = strdup (reason) ;
  
  if (host->activeCxns == 0 && host->spoolTime == 0)
    {
      host->blockedCxn = cxn ;  /* to limit log notices */
      syslog (LOG_NOTICE,REMOTE_BLOCKED, host->params->peerName, reason) ;
    }
  else if (host->activeCxns > 0 && !host->notifiedChangedRemBlckd)
    {
      syslog (LOG_NOTICE,CHANGED_REMOTE_BLOCKED, host->params->peerName,reason) ;
      host->notifiedChangedRemBlckd = true ;
    }
  else if (host->spoolTime != 0 && host->blockedCxn == cxn)
    {
      syslog (LOG_NOTICE,REMOTE_STILL_BLOCKED, host->params->peerName, reason) ;
    }
  
}







/*
 * Called by the Connection when it gets a response back to the MODE
 * STREAM command. It's now that we consider the connection usable.
 */
void hostRemoteStreams (Host host, Connection cxn, bool doesStreaming)
{
  u_int i ;

  host->blockedCxn = NULL ;
  if (host->blockedReason != NULL)
    FREE (host->blockedReason) ;
  host->blockedReason = NULL ;
  
  /* we may have told the connection to quit while it was in the middle
     of connecting */
  if (amClosing (host))
    return ;
  
  if (host->connectTime == 0)   /* first connection for this cycle. */
    {
      if (doesStreaming && host->params->wantStreaming)
        syslog (LOG_NOTICE, REMOTE_DOES_STREAMING, host->params->peerName);
      else if (doesStreaming)
        syslog (LOG_NOTICE, REMOTE_STREAMING_OFF, host->params->peerName);
      else
        syslog (LOG_NOTICE, REMOTE_NO_STREAMING, host->params->peerName);

      if (host->spoolTime > 0)
        hostStopSpooling (host) ;

      /* set up the callback for statistics logging. */
      if (host->statsId != 0)
        clearTimer (host->statsId) ;
      host->statsId = prepareSleep (hostStatsTimeoutCbk, statsPeriod, host) ;

      if (host->ChkCxnsId != 0)
      clearTimer (host->ChkCxnsId);
      host->ChkCxnsId = prepareSleep (hostChkCxns, 30, host) ;

      host->remoteStreams = (host->params->wantStreaming ? doesStreaming : false) ;

      host->connectTime = theTime() ;
      if (host->firstConnectTime == 0)
        host->firstConnectTime = host->connectTime ;
    }
  else if (host->remoteStreams != doesStreaming && host->params->wantStreaming)
    syslog (LOG_NOTICE,STREAMING_CHANGE,host->params->peerName) ;

  for (i = 0 ; i < host->maxConnections ; i++)
    if (host->connections [i] == cxn)
      {
        host->cxnActive [i] = true ;
        if (host->cxnSleeping [i])
          host->sleepingCxns-- ;
        host->cxnSleeping [i] = false ;
        break ;
      }

  ASSERT (i != host->maxConnections) ;

  host->activeCxns++ ;

  hostLogStatus () ;
}







/*
 * Called by the connection when it is no longer connected to the
 * remote. Perhaps due to getting a code 400 to an IHAVE, or due to a
 * periodic close.
 */
void hostCxnDead (Host host, Connection cxn)
{
  u_int i ;
    
  for (i = 0 ; i < host->maxConnections ; i++)
    if (host->connections [i] == cxn)
      {
        if (host->cxnActive [i]) /* won't be active if got 400 on banner */
          {
            host->cxnActive [i] = false ;
            host->activeCxns-- ;

            if (!amClosing (host) && host->activeCxns == 0)
              {
                clearTimer (host->statsId) ;
                clearTimer (host->ChkCxnsId) ;
                hostLogStats (host,true) ;
                host->connectTime = 0 ;
              }
          }
        else if (host->cxnSleeping [i]) /* cxnNuke can be called on sleepers  */
          {
            host->cxnSleeping [i] = false ;
            host->sleepingCxns-- ;
          }

        break ;
      }

  ASSERT (i < host->maxConnections) ;
  hostLogStatus () ;
}







/*
 * Called by the Connection when it is going to sleep so the Host won't
 * bother trying to give it Articles
 */
void hostCxnSleeping (Host host, Connection cxn)
{
  u_int i ;

  for (i = 0 ; i < host->maxConnections ; i++)
    if (host->connections [i] == cxn)
      {
        if (!host->cxnSleeping [i]) 
          {
            host->cxnSleeping [i] = true ;
            host->sleepingCxns++ ;
          }

        if (host->spoolTime == 0 && host->sleepingCxns >= host->maxConnections)
          hostStartSpooling (host) ;

        break ;
      }

  ASSERT (i < host->maxConnections) ;

  hostLogStatus () ;
}







/*
 * Called by the Connection when it goes into the waiting state.
 */
void hostCxnWaiting (Host host, Connection cxn)
{
  u_int i ;

  for (i = 0 ; i < host->maxConnections ; i++)
    if (host->connections [i] == cxn)
      {
        if (host->cxnSleeping [i])
          host->sleepingCxns-- ;
        host->cxnSleeping [i] = false ;
        break ;
      }

  ASSERT (i < host->maxConnections) ;

  if (host->spoolTime > 0)
    hostStopSpooling (host) ;

  hostLogStatus () ;
}







/*
 * Called by the Connection when it is about to delete itself.
 */
bool hostCxnGone (Host host, Connection cxn)
{
  u_int i;
  bool oneThere = false ;

  /* forget about the Connection and see if we are still holding any live
     connections still. */
  for (i = 0 ; i < host->maxConnections ; i++)
    if (host->connections [i] == cxn)
      {
        if (!amClosing (host))
          syslog (LOG_ERR,CONNECTION_DISAPPEARING,host->params->peerName,i) ;
        host->connections [i] = NULL ;
        if (host->cxnActive [i])
          {
            host->cxnActive [i] = false ;
            host->activeCxns-- ;
          }
        else if (host->cxnSleeping [i])
          {
            host->cxnSleeping [i] = false ;
            host->sleepingCxns-- ;
          }
      }
    else if (host->connections [i] != NULL)
      oneThere = true ;

  /* remove the host if it has no connexions */
  if ( !oneThere )
    {
      time_t now = theTime() ;
      u_int hostsLeft ;

      if (host->firstConnectTime > 0)
        syslog (LOG_NOTICE,REALLY_FINAL_STATS,
                host->params->peerName,
                (long) (now - host->firstConnectTime),
                host->gArtsOffered, host->gArtsAccepted,
                host->gArtsNotWanted, host->gArtsRejected,
                host->gArtsMissing) ;

      hostsLeft = listenerHostGone (host->listener, host) ;
      delHost (host) ;

      if (hostsLeft == 0)
        syslog (LOG_NOTICE,PROCESS_FINAL_STATS,
                (long) (now - start),
                procArtsOffered, procArtsAccepted,
                procArtsNotWanted,procArtsRejected,
                procArtsMissing) ;
      
      /* return true if that was the last host */
      return (hostsLeft == 0 ? true : false) ;
    }

  /* return false because there is still at least one host (this one) */
  return false ;
}







/*
 * The connections has offered an article to the remote.
 */
void hostArticleOffered (Host host, Connection cxn) 
{
  (void) cxn ;                  /* keep lint happy. */
  
  host->artsOffered++ ;
  host->gArtsOffered++ ;
  procArtsOffered++ ;
}







/*
 * Article was succesfully transferred.
 */
void hostArticleAccepted (Host host, Connection cxn, Article article)
{
  const char *filename = artFileName (article) ;
  const char *msgid = artMsgId (article) ;

  dprintf (5,"Article %s (%s) was transferred\n", msgid, filename) ;
  
  host->artsAccepted++ ;
  host->gArtsAccepted++ ;
  procArtsAccepted++ ;

  /* host has two references to the article here... the parameter `article'
     and the queue */

  delArticle (article) ;        /* drop the parameter reference */

  if (!amClosing (host))
    articleGone (host,cxn,article) ; /* and the one in the queue */
}







/*
 * remote said no thanks to an article.
 */
void hostArticleNotWanted (Host host, Connection cxn, Article article)
{
  const char *filename = artFileName (article) ;
  const char *msgid = artMsgId (article) ;

  dprintf (5,"Article %s (%s) was not wanted\n", msgid, filename) ;
  
  host->artsNotWanted++ ;
  host->gArtsNotWanted++ ;
  procArtsNotWanted++ ;
  
  
  /* host has two references to the article here... `article' and the
     queue */

  delArticle (article) ;        /* drop the `article' reference */
  
  if (!amClosing (host)) 
    articleGone (host,cxn,article) ; /* and the one in the queue */
}







/*
 * remote rejected the article after it was was transferred
 */
void hostArticleRejected (Host host, Connection cxn, Article article) 
{
  const char *filename = artFileName (article) ;
  const char *msgid = artMsgId (article) ;

  dprintf (5,"Article %s (%s) was rejected\n", msgid, filename) ;
  
  host->artsRejected++ ;
  host->gArtsRejected++ ;
  procArtsRejected++ ;

  /* host has two references to the article here... `article' and the queue */

  delArticle (article) ;        /* drop the `article' reference */

  if (!amClosing (host))
    articleGone (host,cxn,article) ;
}







/*
 * The remote wants us to retry the article later.
 */
void hostArticleDeferred (Host host, Connection cxn, Article article) 
{
  host->artsDeferred++ ;
  host->gArtsDeferred++ ;
  procArtsDeferred++ ;


  if (!amClosing (host))
    {
      Article extraRef ;

      extraRef = artTakeRef (article) ; /* hold a reference until requeued */
      articleGone (host,cxn,article) ; /* drop from the queue */
      hostSendArticle (host, article) ; /* requeue it */
      delArticle (extraRef) ;
    }
  else
    delArticle(article); /*drop parameter reference if not sent to tape*/
}







/*
 * The Connection is giving the article back to the Host, but it doesn't
 * want a new one in return.
 */
void hostTakeBackArticle (Host host, Connection cxn, Article article) 
{
  (void) cxn ;                  /* keep lint happy */
  
  if (!amClosing (host)) 
    {
      Article extraRef ;

      host->artsCxnDrop++ ;
      host->gArtsCxnDrop++ ;
      extraRef = artTakeRef (article) ; /* hold a reference until requeued */
      articleGone (host,NULL,article) ; /* drop from the queue */
      host->notThisCxn = cxn;
      hostSendArticle (host, article) ; /* requeue it */
      host->notThisCxn = NULL;
      delArticle (extraRef) ;
    }
  else
    delArticle(article); /*drop parameter reference if not sent to tape*/

}







/*
 * The disk file for the article is no longer valid
 */
void hostArticleIsMissing (Host host, Connection cxn, Article article)
{
  const char *filename = artFileName (article) ;
  const char *msgid = artMsgId (article) ;

  dprintf (5, "%s article is missing %s %s\n", host->params->peerName, msgid, filename) ;
    
  host->artsMissing++ ;
  host->gArtsMissing++ ;
  procArtsMissing++ ;

  /* host has two references to the article here... `article' and the
     queue */

  delArticle (article) ;        /* drop the `article' reference */

  if (!amClosing (host))
    articleGone (host,cxn,article) ; /* and the one in the queue */
}







/* The Connection wants something to do. This is called by the Connection
 * after it has transferred an article. This is what keeps the pipes full
 * of data off the tapes if the input from inn is idle.
 */
bool hostGimmeArticle (Host host, Connection cxn)
{
  Article article = NULL ;
  bool gaveSomething = false ;
  size_t amtToGive = cxnQueueSpace (cxn) ; /* may be more than one */

  if (amClosing (host))
    {
      dprintf (5,"%s no article to give due to closing\n",host->params->peerName) ;

      return false ;
    }

  if (amtToGive == 0)
    dprintf (5,"%s Queue space is zero....\n",host->params->peerName) ;
  
  while (amtToGive > 0)
    {
      bool tookIt ;
      
      if ((article = remHead (&host->queued,&host->queuedTail)) != NULL)
        {
          host->backlog-- ;
          tookIt = cxnQueueArticle (cxn,artTakeRef (article)) ;

          ASSERT (tookIt == true) ;

          queueArticle (article,&host->processed,&host->processedTail) ;
          amtToGive-- ;

          gaveSomething = true ;
        }
      else if ((article = getArticle (host->myTape)) != NULL) 
        {                       /* go to the tapes */
          tookIt = cxnQueueArticle (cxn,artTakeRef (article)) ;

          ASSERT (tookIt == true) ;

          host->artsFromTape++ ;
          host->gArtsFromTape++ ;
          queueArticle (article,&host->processed,&host->processedTail) ;
          amtToGive-- ;

          gaveSomething = true ;
        }
      else
        {
          /* we had nothing left to give... */
          
          if (host->processed == NULL) /* and if nothing outstanding... */
            listenerHostIsIdle (host->listener,host) ; /* tell our owner */
  
          amtToGive = 0 ;
        }
    }

  return gaveSomething ;
}







/*
 * get the name that INN uses for this host
 */
const char *hostPeerName (Host host)
{
  ASSERT (host != NULL) ;
    
  return host->params->peerName ;
}


/* return true if the Connections for this host should attempt to do
   streaming. */
bool hostWantsStreaming (Host host)
{
  return host->params->wantStreaming ;
}

u_int hostMaxChecks (Host host)
{
  return host->params->maxChecks ;
}







/**********************************************************************/
/**                       CLASS FUNCTIONS                            **/
/**********************************************************************/

/*
 * Set the state of whether each Connection is told to log its stats when
 * its controlling Host logs its stats.
 */
void hostLogConnectionStats (bool val)
{
  logConnectionStats = val ;
}


bool hostLogConnectionStatsP (void)
{
  return logConnectionStats ;
}



/*
 * Called by one of the Host's Connection's when it (the Connection)
 * switches into or out of no-CHECK mode.
 */
void hostLogNoCheckMode (Host host, bool on, double low, double cur, double high)
{
  if (on && host->loggedModeOn == false)
    {
      syslog (LOG_NOTICE, STREAMING_MODE_SWITCH, host->params->peerName, low, cur, high) ;
      host->loggedModeOn = true ;
    }
  else if (!on && host->loggedModeOff == false) 
    {
      syslog (LOG_NOTICE, STREAMING_MODE_UNDO, host->params->peerName, low, cur, high) ;
      host->loggedModeOff = true ;
    }
}



void hostSetStatusFile (const char *filename)
{
  FILE *fp ;
  
  if (filename == NULL)
    die ("Can't set status file name with a NULL filename\n") ;
  else if (*filename == '\0')
    die ("Can't set status file name with a empty string\n") ;

  if (*filename == '/')
    statusFile = strdup (filename) ;
  else
    {
      const char *tapeDir = getTapeDirectory() ;
      
      statusFile = malloc (strlen (tapeDir) + strlen (filename) + 2) ;
      sprintf (statusFile,"%s/%s",tapeDir,filename) ;
    }

  if ((fp = fopen (statusFile,"w")) == NULL)
    {
      syslog (LOG_ERR,"Status file is not a valid pathname: %s",
              statusFile) ;
      FREE (statusFile) ;
      statusFile = NULL ;
    }
  else
    fclose (fp) ;
}



/**********************************************************************/
/**                      PRIVATE FUNCTIONS                           **/
/**********************************************************************/




#define INHERIT	1
#define NO_INHERIT 0


static HostParams hostDetails (scope *s,
			       char *name,
			       bool isDefault,
			       FILE *fp)
{
  long iv ;
  int bv, vival, inherit ;
  HostParams p;
  char * q;
  double rv, l, h ;
  value * v;

  p=newHostParams(isDefault?NULL:defaultParams);

  if (isDefault)
    {
      ASSERT (name==NULL);
    }
  else
    {
      if (name)
	{
	  p->peerName=strdup(name);
	}
  
      if (s != NULL)
	if (getString (s,IP_NAME,&q,NO_INHERIT))
	  p->ipName = q ;
	else
	  p->ipName = strdup (name) ;
    }


  /* check required global defaults are there and have good values */
  

#define GETINT(sc,f,n,min,max,req,val,inh)              \
  vival = validateInteger(f,n,min,max,req,val,sc,inh);  \
  if (isDefault) do{                                    \
    if(vival==VALUE_WRONG_TYPE)                         \
      {                                                 \
        logOrPrint(LOG_CRIT,fp,"cannot continue");      \
        exit(1);                                        \
      }                                                 \
    else if(vival != VALUE_OK)                          \
      val = 0;                                          \
  } while(0);                                           \
  iv = 0 ;                                              \
  (void) getInteger (sc,n,&iv,inh) ;                    \
  val = (u_int) iv ;                                    \

#define GETREAL(sc,f,n,min,max,req,val,inh)             \
  vival = validateReal(f,n,min,max,req,val,sc,inh);     \
  if (isDefault) do{                                    \
    if(vival==VALUE_WRONG_TYPE)                         \
      {                                                 \
        logOrPrint(LOG_CRIT,fp,"cannot continue");      \
        exit(1);                                        \
      }                                                 \
    else if(vival != VALUE_OK)                          \
      rv = 0;                                           \
  } while(0);                                           \
  rv = 0 ;                                              \
  (void) getReal (sc,n,&rv,inh) ;                       \
  val = rv ;                                            \

#define GETBOOL(sc,f,n,req,val,inh)                     \
  vival = validateBool(f,n,req,val,sc,inh);             \
  if (isDefault) do{                                    \
    if(vival==VALUE_WRONG_TYPE)                         \
      {                                                 \
        logOrPrint(LOG_CRIT,fp,"cannot continue");      \
        exit(1);                                        \
      }                                                 \
    else if(vival != VALUE_OK)                          \
      bv = 0;                                           \
  } while(0);                                           \
  bv = 0 ;                                              \
  (void) getBool (sc,n,&bv,inh)  ;                      \
  val = (bv ? true : false);                            \

  inherit = isDefault?NO_INHERIT:INHERIT;
  GETINT(s,fp,"article-timeout",0,LONG_MAX,REQ,p->articleTimeout, inherit);
  GETINT(s,fp,"response-timeout",0,LONG_MAX,REQ,p->responseTimeout, inherit);
  GETINT(s,fp,"close-period",0,LONG_MAX,REQ,p->closePeriod, inherit);
  GETINT(s,fp,"initial-connections",0,LONG_MAX,REQ,p->initialConnections, inherit);
  GETINT(s,fp,"max-connections",0,LONG_MAX,REQ,p->absMaxConnections, inherit);
  GETINT(s,fp,"max-queue-size",1,LONG_MAX,REQ,p->maxChecks, inherit);
  GETBOOL(s,fp,"streaming",REQ,p->wantStreaming, inherit);
  GETREAL(s,fp,"no-check-high",0.0,100.0,REQ,p->lowPassHigh, inherit);
  GETREAL(s,fp,"no-check-low",0.0,100.0,REQ,p->lowPassLow, inherit);
  GETREAL(s,fp,"no-check-filter",0.1,DBL_MAX,REQ,p->lowPassFilter, inherit);
  GETINT(s,fp,"port-number",0,LONG_MAX,REQ,p->portNum, inherit);
  GETINT(s,fp,"backlog-limit",0,LONG_MAX,REQ,p->backlogLimit, inherit);

  if (findValue (s,"backlog-factor",inherit) == NULL &&
      findValue (s,"backlog-limit-high",inherit) == NULL)
    {
      logOrPrint (LOG_ERR,fp,NOFACTORHIGH,"backlog-factor",LIMIT_FUDGE) ;
      addReal (s,"backlog-factor",LIMIT_FUDGE) ;
      rv = 0 ;
    }

  GETINT(s,fp,"backlog-limit-high",0,LONG_MAX,NOTREQNOADD,p->backlogLimitHigh, inherit);
  GETREAL(s,fp,"backlog-factor",1.0,DBL_MAX,NOTREQNOADD,p->backlogFactor, inherit);

  GETINT(s,fp,"dynamic-method",0,3,REQ,p->dynamicMethod, inherit);
  GETREAL(s,fp,"dynamic-backlog-filter",0.0,DBL_MAX,REQ,p->dynBacklogFilter, inherit);
  GETREAL(s,fp,"dynamic-backlog-low",0.0,100.0,REQ,p->dynBacklogLowWaterMark, inherit);
  GETREAL(s,fp,"dynamic-backlog-high",0.0,100.0,REQ,p->dynBacklogHighWaterMark, inherit);

  l=p->lowPassLow;
  h=p->lowPassHigh;
  if (l > h)
    {
      logOrPrint (LOG_ERR,fp,NOCK_LOWVSHIGH,l,h,NOCHECKLOW,NOCHECKHIGH) ;
      rv = 0 ;
      v = findValue (s,"no-check-low",NO_INHERIT) ;
      v->v.real_val = p->lowPassLow = NOCHECKLOW ;
      v = findValue (s,"no-check-high",NO_INHERIT) ;
      v->v.real_val = p->lowPassHigh = NOCHECKHIGH ;
    }
  else if (h - l < 5.0)
    logOrPrint (LOG_WARNING,fp,NOCK_LOWHIGHCLOSE,l,h) ;

  return p;
}




static HostParams getHostInfo (void)
{
  static int idx = 0 ;
  value *v ;
  scope *s ;
  HostParams p=NULL;

  bool isGood = false ;

  if (topScope == NULL)
    return false ;
  
  while ((v = getNextPeer (&idx)) != NULL) 
    {
      if (!ISPEER (v))
        continue ;

      s = v->v.scope_val ;

      p=hostDetails(s,v->name,false,NULL);

      isGood = true ;
      
      break ;
    }

  if (v == NULL)
    idx = 0 ;                   /* start over next time around */

  return p;
}


/*
 * fully delete and clean up the Host object.
 */
void delHost (Host host)
{
  Host h,q ;

  for (h = gHostList, q = NULL ; h != NULL ; q = h, h = h->next)
    if (h == host)
      {
        if (gHostList == h)
          gHostList = gHostList->next ;
        else
          q->next = h->next ;
        break ;
      }

  ASSERT (h != NULL) ;
        
  delTape (host->myTape) ;
  
  FREE (host->connections) ;
  FREE (host->cxnActive) ;
  FREE (host->cxnSleeping) ;
  FREE (host->params->peerName) ;
  FREE (host->params->ipName) ;

  if (host->ipAddrs)
    FREE (host->ipAddrs) ;

  FREE (host) ;
  gHostCount-- ;
}



static Host findHostByName (char *name) 
{
  Host h;

  for (h = gHostList; h != NULL; h = h->next)
    if ( strcmp(h->params->peerName, name) == 0 )
      return h;

  return NULL;
}



/* 
 * the article can be dropped from the process queue and the connection can
 * take a new article if there are any to be had.
 */
static void articleGone (Host host, Connection cxn, Article article)
{
  if ( !remArticle (article,&host->processed,&host->processedTail) )
    die ("remArticle in articleGone failed") ;

  delArticle (article) ;

  if (cxn != NULL)
    hostGimmeArticle (host,cxn) ; /* may not give anything over */
}







/*
 * One of the Connections for this Host has reestablished itself, so stop
 * spooling article info to disk.
 */
static void hostStopSpooling (Host host)
{
  ASSERT (host->spoolTime != 0) ;
  
  clearTimer (host->statsId) ;
  hostLogStats (host,true) ;
 
  host->spoolTime = 0 ;
}







/*
 * No connections are active and we're getting response 201 or 400 (or some
 * such) so that we need to start spooling article info to disk.
 */
static void hostStartSpooling (Host host)
{
  ASSERT (host->spoolTime == 0) ;

  queuesToTape (host) ;

  hostLogStats (host,true) ;
  
  host->spoolTime = theTime() ;
  if (host->firstConnectTime == 0)
    host->firstConnectTime = host->spoolTime ;

  /* don't want to log too frequently */
  if (SPOOL_LOG_PERIOD > 0 &&
      (host->spoolTime - host->lastSpoolTime) > SPOOL_LOG_PERIOD)
    {
      syslog (LOG_NOTICE,SPOOLING,host->params->peerName) ;
      host->lastSpoolTime = host->spoolTime ;
    }
  
  host->connectTime = 0 ;

  host->notifiedChangedRemBlckd = false ;

  clearTimer (host->statsId) ;
  host->statsId = prepareSleep (hostStatsTimeoutCbk, statsPeriod, host) ;
}







/*
 * Time to log the statistics for the Host. If FINAL is true then the
 * counters will be reset.
 */
static void hostLogStats (Host host, bool final)
{
  time_t now = theTime() ;
  time_t *startPeriod ;
  double cnt = (host->blCount) ? (host->blCount) : 1.0;

  if (host->spoolTime == 0 && host->connectTime == 0)
    return ;        /* host has never connected and never started spooling*/

  startPeriod = (host->spoolTime != 0 ? &host->spoolTime : &host->connectTime);

  if (now - *startPeriod >= statsResetPeriod)
    final = true ;
  
  if (host->spoolTime != 0)
    syslog (LOG_NOTICE, HOST_SPOOL_STATS, host->params->peerName,
            (final ? "final" : "checkpoint"),
            (long) (now - host->spoolTime), host->artsToTape,
            host->artsHostClose, host->artsHostSleep) ;
  else
    syslog (LOG_NOTICE, HOST_STATS_MSG, host->params->peerName, 
            (final ? "final" : "checkpoint"),
            (long) (now - host->connectTime),
            host->artsOffered, host->artsAccepted,
            host->artsNotWanted, host->artsRejected,
            host->artsMissing, host->artsToTape,
            host->artsHostClose, host->artsFromTape,
            host->artsDeferred, host->artsCxnDrop,
            (double)host->blAccum/cnt, hostHighwater,
            (100.0*host->blNone)/cnt,
            (100.0*host->blQuartile[0])/cnt, (100.0*host->blQuartile[1])/cnt,
            (100.0*host->blQuartile[2])/cnt, (100.0*host->blQuartile[3])/cnt,
            (100.0*host->blFull)/cnt) ;

  if (logConnectionStats) 
    {
      u_int i ;
      
      for (i = 0 ; i < host->maxConnections ; i++)
        if (host->connections [i] != NULL && host->cxnActive [i])
          cxnLogStats (host->connections [i],final) ;
    }

  /* one 'spooling backlog' message per stats logging period */
  host->loggedBacklog = false ;
  host->loggedModeOn = host->loggedModeOff = false ;

  if (final)
    {
      host->artsOffered = 0 ;
      host->artsAccepted = 0 ;
      host->artsNotWanted = 0 ;
      host->artsRejected = 0 ;
      host->artsDeferred = 0 ;
      host->artsMissing = 0 ;
      host->artsToTape = 0 ;
      host->artsQueueOverflow = 0 ;
      host->artsCxnDrop = 0 ;
      host->artsHostSleep = 0 ;
      host->artsHostClose = 0 ;
      host->artsFromTape = 0 ;
      
      *startPeriod = theTime () ; /* in of case STATS_RESET_PERIOD */
    }

    /* reset these each log period */
    host->blNone = 0 ;
    host->blFull = 0 ;
    host->blQuartile[0] = host->blQuartile[1] = host->blQuartile[2] =
                          host->blQuartile[3] = 0;
    host->blAccum = 0;
    host->blCount = 0;

#if 0
  /* XXX turn this section on to get a snapshot at each log period. */
  if (gPrintInfo != NULL)
    gPrintInfo () ;
#endif
}







/*
 * Log the status of the Hosts.
 */
extern char *versionInfo ;
static void hostLogStatus (void)
{
  FILE *fp = NULL ;
  Host h ;
  bool anyToLog = false ;
  u_int peerNum = 0, actConn = 0, slpConn = 0, maxcon = 0 ;
  static bool logged = false ;
  static bool flogged = false ;


  if (statusFile == NULL && !logged)
    {
      syslog (LOG_ERR,"No status file to write to") ;
      logged = true ;
      return ;
    }

  logged = false ;
    
  for (h = gHostList ; h != NULL ; h = h->next)
    if (h->myTape != NULL)   /* the host deletes its tape when it's closing */
      {
        anyToLog = true ;
        peerNum++ ;
        actConn += h->activeCxns ;
        slpConn += h->sleepingCxns ;
        maxcon += h->maxConnections ;
      }

  if (!anyToLog)
    return ;

  lastStatusLog = theTime() ;
  
  if ((fp = fopen (statusFile,"w")) == NULL)
    {
      if ( !flogged )
        syslog (LOG_ERR,NO_STATUS,statusFile) ;
      flogged = true ;
    }
  else
    {
      char timeString [30] ;
      time_t now ;

      flogged = false ;
      
      now = time (NULL) ;
      strcpy (timeString,ctime (&now)) ;

      if (genHtml)
        fprintf (fp,"<HTML><META HTTP-EQUIV=\"Refresh\" CONTENT=\"20;\"><PRE>\n\n") ;

      fprintf (fp,"%s\npid %d started %s\nUpdated: %s",
               versionInfo,(int) myPid,startTime,timeString) ;
      fprintf (fp,"(peers: %d active-cxns: %d sleeping-cxns: %d idle-cxns: %d)\n\n",
               peerNum, actConn, slpConn,(maxcon - (actConn + slpConn))) ;

      fprintf (fp,"Configuration file: %s\n\n",configFile) ;

      mainLogStatus (fp) ;
      listenerLogStatus (fp) ;

/*
Default peer configuration parameters:
    article timeout: 600       initial connections: 1
   response timeout: 300           max connections: 5
       close period: 6000               max checks: 25
     want streaming: true           dynamic method: 1
        no-check on: 95.0%     dynamic backlog low: 25%
       no-check off: 90.0%    dynamic backlog high: 50%
    no-check filter: 50.0   dynamic backlog filter: 0.7
  backlog low limit: 1024                 port num: 119
 backlog high limit: 1280
     backlog factor: 1.1
*/
      
      fprintf(fp,"Default peer configuration parameters:\n") ;
      fprintf(fp,"    article timeout: %-5d     initial connections: %d\n",
	    defaultParams->articleTimeout,
	    defaultParams->initialConnections) ;
      fprintf(fp,"   response timeout: %-5d         max connections: %d\n",
	    defaultParams->responseTimeout,
	    defaultParams->absMaxConnections) ;
      fprintf(fp,"       close period: %-5d              max checks: %d\n",
	    defaultParams->closePeriod,
	    defaultParams->maxChecks) ;
      fprintf(fp,"     want streaming: %-5s          dynamic method: %d\n",
	    defaultParams->wantStreaming ? "true " : "false",
	    defaultParams->dynamicMethod) ;
      fprintf(fp,"        no-check on: %-2.1f%%     dynamic backlog low: %-2.1f%%\n",
	    defaultParams->lowPassHigh,
	    defaultParams->dynBacklogLowWaterMark) ;
      fprintf(fp,"       no-check off: %-2.1f%%    dynamic backlog high: %-2.1f%%\n",
	    defaultParams->lowPassLow,
	    defaultParams->dynBacklogHighWaterMark) ;
      fprintf(fp,"    no-check filter: %-2.1f   dynamic backlog filter: %-2.1f\n",
	    defaultParams->lowPassFilter,
	    defaultParams->dynBacklogFilter) ;
      fprintf(fp,"  backlog limit low: %-5d\n",
	    defaultParams->backlogLimit);
      fprintf(fp," backlog limit high: %-5d\n",
	    defaultParams->backlogLimitHigh);
      fprintf(fp,"     backlog factor: %1.1f\n\n",
	    defaultParams->backlogFactor);

      tapeLogGlobalStatus (fp) ;

      fprintf (fp,"\n") ;
      fprintf (fp,"global (process)\n") ;
      
      fprintf (fp, "   seconds: %-7ld\n", (long) (now - start)) ;
      fprintf (fp, "   offered: %-7ld\n", procArtsOffered) ;
      fprintf (fp, "  accepted: %-7ld\n", procArtsAccepted) ;
      fprintf (fp, "   refused: %-7ld\n", procArtsNotWanted) ;
      fprintf (fp, "  rejected: %-7ld\n", procArtsRejected) ;
      fprintf (fp, "   missing: %-7ld\n", procArtsMissing) ;
      fprintf (fp, "  deferred: %-7ld\n", procArtsDeferred) ;
      fprintf (fp, "\n");
      
      for (h = gHostList ; h != NULL ; h = h->next)
        hostPrintStatus (h,fp) ;

      if (genHtml) 
        fprintf (fp,"</PRE></HTML>\n") ;
      
      fclose (fp) ;
    }
}

/*
 * This prints status information for each host.  An example of the
 * format of the output is:
 *
 * sitename
 *   seconds: 351       art. timeout: 400          ip name: foo.bar
 *   offered: 1194     resp. timeout: 240             port: 119
 *  accepted: 178     want streaming: yes      active cxns: 6
 *   refused: 948       is streaming: yes    sleeping cxns: 0
 *  rejected: 31          max checks: 25      initial cxns: 5
 *   missing: 0          no-check on: 95.0%      idle cxns: 4
 *  deferred: 0         no-check off: 95.0%       max cxns: 8/10
 *  requeued: 0        no-check fltr: 50.0    queue length: 0
 *   spooled: 0                                      empty: 100.0%
 *[overflow]: 0        dyn b'log low: 25%          >0%-25%: 0.0%
 *[on_close]: 0       dyn b'log high: 50%          25%-50%: 0.0%
 *[sleeping]: 0       dyn b'log stat: 37%          50%-75%: 0.0%
 * unspooled: 0       dyn b'log fltr: 0.7        75%-<100%: 0.0%
 *                                                    full: 0.0%
 *                 backlog low limit: 1000000
 *                backlog high limit: 2000000     (factor 2.0)
 *                 backlog shrinkage: 0 bytes (from current file)
 *
 */
static void hostPrintStatus (Host host, FILE *fp)
{
  time_t now = theTime() ;
  double cnt = (host->blCount) ? (host->blCount) : 1.0;

  ASSERT (host != NULL) ;
  ASSERT (fp != NULL) ;

  fprintf (fp,"%s",host->params->peerName);

  if (host->blockedReason != NULL)
    fprintf (fp,"  (remote status: ``%s'')",host->blockedReason) ;

  fputc ('\n',fp) ;

  fprintf (fp, "   seconds: %-7ld   art. timeout: %-5d        ip name: %s\n",
	   host->firstConnectTime > 0 ? (long)(now - host->firstConnectTime) : 0,
	   host->params->articleTimeout, host->params->ipName) ;
           
  fprintf (fp, "   offered: %-7ld  resp. timeout: %-5d           port: %d\n",
	   (long) host->gArtsOffered, host->params->responseTimeout,
	   host->params->portNum);

  fprintf (fp, "  accepted: %-7ld want streaming: %s      active cxns: %d\n",
	   (long) host->gArtsAccepted, 
           (host->params->wantStreaming ? "yes" : "no "),
	   host->activeCxns) ;

  fprintf (fp, "   refused: %-7ld   is streaming: %s    sleeping cxns: %d\n",
	   (long) host->gArtsNotWanted,
           (host->remoteStreams ? "yes" : "no "),
	   host->sleepingCxns) ;

  fprintf (fp, "  rejected: %-7ld     max checks: %-5d   initial cxns: %d\n",
	   (long) host->gArtsRejected, host->params->maxChecks,
	   host->params->initialConnections) ;

  fprintf (fp, "   missing: %-7ld    no-check on: %-3.1f%%      idle cxns: %d\n",
	   (long) host->gArtsMissing, host->params->lowPassHigh,
           host->maxConnections - (host->activeCxns + host->sleepingCxns)) ;

  fprintf (fp, "  deferred: %-7ld   no-check off: %-3.1f%%       max cxns: %d/%d\n",
	   (long) host->gArtsDeferred, host->params->lowPassLow,
	   host->maxConnections, host->params->absMaxConnections) ;

  fprintf (fp, "  requeued: %-7ld  no-check fltr: %-3.1f    queue length: %-3.1f\n",
	   (long) host->gArtsCxnDrop, host->params->lowPassFilter,
	   (double)host->blAccum / cnt) ;

  fprintf (fp, "   spooled: %-7ld dynamic method: %-5d          empty: %-3.1f%%\n",
	   (long) host->gArtsToTape,
	   host->params->dynamicMethod,
	   100.0 * host->blNone / cnt) ;

  fprintf (fp, "[overflow]: %-7ld  dyn b'log low: %-3.1f%%        >0%%-25%%: %-3.1f%%\n",
	   (long) host->gArtsQueueOverflow, 
	   host->params->dynBacklogLowWaterMark,
	   100.0 * host->blQuartile[0] / cnt) ;

  fprintf (fp, "[on_close]: %-7ld dyn b'log high: %-3.1f%%        25%%-50%%: %-3.1f%%\n",
	   (long) host->gArtsHostClose,
	   host->params->dynBacklogHighWaterMark,
	   100.0 * host->blQuartile[1] / cnt) ;

  fprintf (fp, "[sleeping]: %-7ld dyn b'log stat: %-3.1f%%        50%%-75%%: %-3.1f%%\n",
	   (long) host->gArtsHostSleep,
	   host->backlogFilter*100.0*(1.0-host->params->dynBacklogFilter),
	   100.0 * host->blQuartile[2] / cnt) ;

  fprintf (fp, " unspooled: %-7ld dyn b'log fltr: %-3.1f       75%%-<100%%: %-3.1f%%\n",
	   (long) host->gArtsFromTape,
	   host->params->dynBacklogLowWaterMark,
	   100.0 * host->blQuartile[3] / cnt) ;

  fprintf (fp, "                                                    full: %-3.1f%%\n",
	   100.0 * host->blFull / cnt) ;

  tapeLogStatus (host->myTape,fp) ;
#ifdef        XXX_STATSHACK
  {
  time_t      now = time(NULL), sec = (long) (now - host->connectTime);
  float               or, ar, rr, jr;

  if (sec != 0) {
      or = (float) host->artsOffered / (float) sec;
      ar = (float) host->artsAccepted / (float) sec;
      rr = (float) host->artsNotWanted / (float) sec;
      jr = (float) host->artsRejected / (float) sec;
      fprintf(fp, "\t\tor %02.2f ar %02.2f rr %02.2f jr %02.2f\n",
              or, ar, rr, jr);
  }
  fprintf(fp, "\tmissing %d spooled %d\n",
      host->artsMissing,host->backlogSpooled);
  }
#endif        /* XXX_STATSHACK */
  
  fprintf (fp, "\n\n");
}







/*
 * The callback function for the statistics timer to call.
 */
static void hostStatsTimeoutCbk (TimeoutId tid, void *data)
{
  Host host = (Host) data ;
  time_t now = theTime () ;

  (void) tid ;                  /* keep lint happy */

  ASSERT (tid == host->statsId) ;
  
  if (!amClosing (host))
    hostLogStats (host, false) ;

  if (now - lastStatusLog >= statsPeriod)
    hostLogStatus () ;
  
  
  host->statsId = prepareSleep (hostStatsTimeoutCbk, statsPeriod, host) ;
}


/* if the host has too many unprocessed articles so we send some to the tape. */
static void backlogToTape (Host host)
{
  Article article ;

  while (host->backlog > hostHighwater)
    {
      if (!host->loggedBacklog)
	{
#if 0               /* this message is pretty useless and confuses people */
	  syslog (LOG_NOTICE,BACKLOG_TO_TAPE,host->params->peerName /* ,host->backlog */) ;
#endif
	  host->loggedBacklog = true ;
	}
  
      article = remHead (&host->queued,&host->queuedTail) ;

      ASSERT(article != NULL);

      host->artsQueueOverflow++ ;
      host->gArtsQueueOverflow++ ;
      host->artsToTape++ ;
      host->gArtsToTape++ ;
      host->backlog--;
      tapeTakeArticle (host->myTape,article) ;
    }
}







/*
 * Returns true of the Host is in the middle of closing down.
 */
static bool amClosing (Host host)
{
  return (host->myTape == NULL ? true : false) ;
}







/*
 * flush all queued articles all the way out to disk.
 */
static void queuesToTape (Host host)
{
  Article art ;
  
  while ((art = remHead (&host->processed,&host->processedTail)) != NULL)
    {
      host->artsHostClose++ ;
      host->gArtsHostClose++ ;
      host->artsToTape++ ;
      host->gArtsToTape++ ;
      tapeTakeArticle (host->myTape,art) ;
    }
  
  while ((art = remHead (&host->queued,&host->queuedTail)) != NULL)
    {
      host->backlog-- ;
      host->artsHostClose++ ;
      host->gArtsHostClose++ ;
      host->artsToTape++ ;
      host->gArtsToTape++ ;
      tapeTakeArticle (host->myTape,art) ;
    }
}







#define QUEUE_ELEM_POOL_SIZE ((4096 - 2 * (sizeof (void *))) / (sizeof (struct proc_q_elem)))

static ProcQElem queueElemPool ;

/*
 * Add an article to the given queue.
 */
static void queueArticle (Article article, ProcQElem *head, ProcQElem *tail)
{
  ProcQElem elem ;

  if (queueElemPool == NULL)
    {
      int i ;

      queueElemPool = ALLOC (struct proc_q_elem, QUEUE_ELEM_POOL_SIZE) ;
      ASSERT (queueElemPool != NULL) ;

      for (i = 0; i < QUEUE_ELEM_POOL_SIZE - 1; i++)
        queueElemPool[i] . next = &(queueElemPool [i + 1]) ;
      queueElemPool [QUEUE_ELEM_POOL_SIZE-1] . next = NULL ;
    }

  elem = queueElemPool ;
  ASSERT (elem != NULL) ;
  queueElemPool = queueElemPool->next ;

  elem->article = article ;
  elem->next = NULL ;
  elem->prev = *tail ;
  if (*tail != NULL)
    (*tail)->next = elem ;
  else
    *head = elem ;
  *tail = elem ;  
}







/*
 * remove the article from the queue
 */
static bool remArticle (Article article, ProcQElem *head, ProcQElem *tail)
{
  ProcQElem elem ;

  ASSERT (head != NULL) ;
  ASSERT (tail != NULL) ;

  /* we go backwards down the list--probably faster */
  elem = *tail ;
  while (elem != NULL && elem->article != article)
    elem = elem->prev ;

  if (elem != NULL)
    {
      if (elem->prev != NULL)
        elem->prev->next = elem->next ;
      if (elem->next != NULL)
        elem->next->prev = elem->prev ;
      if (*head == elem)
        *head = elem->next ;
      if (*tail == elem)
        *tail = elem->prev ;

      elem->next = queueElemPool ;
      queueElemPool = elem ;
      
      return true ;
    }
  else
    return false ;
}







/*
 * remove the article that's at the head of the queue and return
 * it. Returns NULL if the queue is empty.
 */
static Article remHead (ProcQElem *head, ProcQElem *tail)
{
  ProcQElem elem ;
  Article art ;

  ASSERT (head != NULL) ;
  ASSERT (tail != NULL) ;
  ASSERT ((*head == NULL && *tail == NULL) ||
          (*head != NULL && *tail != NULL)) ;

  if (*head == NULL)
    return NULL ;

  elem = *head ;
  art = elem->article ;
  *head = elem->next ;
  if (elem->next != NULL)
    elem->next->prev = NULL ;

  if (*tail == elem)
    *tail = NULL ;

  elem->next = queueElemPool ;
  queueElemPool = elem ;

  return art ;
}



static int validateInteger (FILE *fp, const char *name,
                     long low, long high, int required, long setval,
		     scope * sc, u_int inh)
{
  int rval = VALUE_OK ;
  value *v ;
  scope *s ;
  char *p = strrchr (name,':') ;
  
  v = findValue (sc,name,inh) ;
  if (v == NULL && required != NOTREQNOADD)
    {
      s = findScope (sc,name,0) ;
      addInteger (s,p ? p + 1 : name,setval) ;
      if (required == REQ)
        {
          rval = VALUE_MISSING ;
          logOrPrint (LOG_ERR,fp,NODEFN,name) ;
        }
      else if (required)
        logOrPrint (LOG_INFO,fp,ADDMISSINGINT,name,setval) ;
    }
  else if (v != NULL && v->type != intval)
    {
      rval = VALUE_WRONG_TYPE ;
      logOrPrint (LOG_ERR,fp,NOTINT,name) ;
    }
  else if (v != NULL && low != LONG_MIN && v->v.int_val < low)
    {
      rval = VALUE_TOO_LOW ;
      logOrPrint (LOG_ERR,fp,INT_TO_LOW,name,v->v.int_val,
                  "global scope",low,low) ;
      v->v.int_val = low ;
    }
  else if (v != NULL && high != LONG_MAX && v->v.int_val > high)
    {
      rval = VALUE_TOO_HIGH ;
      logOrPrint(LOG_ERR,fp,INT_TO_HIGH,name,v->v.int_val,
                 "global scope",high,high);
      v->v.int_val = high ;
    }
  
  return rval ;
}



static int validateReal (FILE *fp, const char *name, double low,
                         double high, int required, double setval,
			 scope * sc, u_int inh)
{
  int rval = VALUE_OK ;
  value *v ;
  scope *s ;
  char *p = strrchr (name,':') ;
  
  v = findValue (sc,name,inh) ;
  if (v == NULL && required != NOTREQNOADD)
    {
      s = findScope (sc,name,0) ;
      addReal (s,p ? p + 1 : name,setval) ;
      if (required == REQ)
        {
          rval = VALUE_MISSING ;
          logOrPrint (LOG_ERR,fp,NODEFN,name) ;
        }
      else
        logOrPrint (LOG_INFO,fp,ADDMISSINGREAL,name,setval) ;
    }
  else if (v != NULL && v->type != realval)
    {
      rval = VALUE_WRONG_TYPE ;
      logOrPrint (LOG_ERR,fp,NOTREAL,name) ;
    }
  else if (v != NULL && low != -DBL_MAX && v->v.real_val < low)
    {
      logOrPrint (LOG_ERR,fp,REALTOLOW,name,v->v.real_val,low) ; /* bleh */
      v->v.real_val = setval ;
    }
  else if (high != DBL_MAX && v->v.real_val > high)
    {
      logOrPrint (LOG_ERR,fp,REALTOHIGH,name,v->v.real_val,high) ;
      v->v.real_val = setval ;
    }
    
  return rval ;
}



static int validateBool (FILE *fp, const char *name, int required, bool setval,
			 scope * sc, u_int inh)
{
  int rval = VALUE_OK ;
  value *v ;
  scope *s ;
  char *p = strrchr (name,':') ;
  
  v = findValue (sc,name,inh) ;
  if (v == NULL && required != NOTREQNOADD)
    {
      s = findScope (sc,name,0) ;
      addBoolean (s,p ? p + 1 : name, setval ? 1 : 0)  ;
      if (required == REQ)
        {
          rval = VALUE_MISSING ;
          logOrPrint (LOG_ERR,fp,NODEFN,name) ;
        }
      else
        logOrPrint (LOG_INFO,fp,ADDMISSINGBOOL,name,(setval?"true":"false")) ;
    }
  else if (v != NULL && v->type != boolval)
    {
      rval = VALUE_WRONG_TYPE ;
      logOrPrint (LOG_ERR,fp,NOTBOOLEAN,name) ;
    }
  
  return rval ;
}


void gCalcHostBlStat (void)
{
  Host h ;
  
  for (h = gHostList ; h != NULL ; h = h->next)
    {
      h->blAccum += h->backlog ;
      if (h->backlog == 0)
	   h->blNone++ ;
      else if (h->backlog >= hostHighwater)
	   h->blFull++ ;
      else
	   h->blQuartile[(4*h->backlog) / hostHighwater]++ ;
      h->blCount++ ;
    }
}
static void hostCleanup (void)
{
  if (statusFile != NULL)
    FREE (statusFile) ;
}