File: scheduler.c

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

/*
 * ZMailer transport scheduler.
 */

#include <stdio.h>
#include <sfio.h>
#include <sys/param.h>
#include "hostenv.h"
#include <ctype.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "mail.h"
#include <string.h>
#include "ta.h"
#include "sysexits.h"

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef HAVE_DIRENT_H
# include <dirent.h>
#else /* not HAVE_DIRENT_H */
# define dirent direct
# ifdef HAVE_SYS_NDIR_H
#  include <sys/ndir.h>
# endif /* HAVE_SYS_NDIR_H */
# ifdef HAVE_SYS_DIR_H
#  include <sys/dir.h>
# endif /* HAVE_SYS_DIR_H */
# ifdef HAVE_NDIR_H
#  include <ndir.h>
# endif /* HAVE_NDIR_H */
#endif /* HAVE_DIRENT_H */

#include "zmsignal.h"
#ifdef HAVE_MMAP
#include <sys/mman.h>
#endif

#include "scheduler.h"
#include "prototypes.h"
#include "zsyslog.h"
#include "libz.h"
#include <grp.h>

extern int optind;
extern char *optarg;

#ifndef	MAXNAMLEN /* POSIX.1 ... */
#define MAXNAMLEN NAME_MAX
#endif

#ifndef	_IOLBF
# define _IOLBF 0200
#endif	/* !_IOLBF */

#ifdef	HONEYBUM/* not really SVID, just this stupid honeywell compiler */
# define MAX_ENTRIES 3000
#else	/* sane pcc */
# define MAX_ENTRIES 10000
#endif	/* honeywell pcc */

struct sptree *spt_mesh[SIZE_L];

#ifdef	MALLOC_TRACE
struct conshell *envarlist = NULL;
#endif	/* MALLOC_TRACE */

#define TRANSPORTMAXNOFILES 32 /* Number of files a transporter may
				  need open -- or any of its children.. */
int	transportmaxnofiles = TRANSPORTMAXNOFILES; /* Default value */
const char * progname;
extern const char * postoffice;
const char * rendezvous;
const char * pidfile = PID_SCHEDULER;
const char * mailshare;
const char * logfn;
const char * statusfn;
Sfio_t     * statuslog = NULL;
int	slow_shutdown = 0;
extern int readsockcnt; /* from transport.c: mux() */
 
static int mustexit = 0;
static int gotalarm = 0;
static int dumpq    = 0;
static int canexit  = 0;
static int rereadcf = 0;
static int dlyverbose = 0;
time_t	sched_starttime;
int	do_syslog = 0;
int	verbose = 0;
int	querysocket = -1;	/* fd of TCP socket to listen for queries */
int	D_alloc = 0;
int	hungry_childs = 0;
int	global_wrkcnt = 0;
int	mailq_Q_mode = 0;
int	syncstart = 0;		/* while set, the thread subsystem shall start
				   no childs! */
int	freeze = 0;		/* For debugging, complete disable of child
				   running.. */
int	hashlevels = 0;		/* How many levels of hashes are supported
				   at the transport directory ?  (To speed
				   up the directory processing, file opens,
				   etc.. ) */
char * procselect = NULL;	/* Non-null defines  channel/host specifier
				   that is ALLOWED TO RUN, specifying this
				   (by means of '-P chan/host' -option) will
				   prevent running anything else, and also
				   prevent running error processing, or
				   job-specifier deletions. */
char *  procselhost = NULL;	/* Just spliced out 'host'-part of the above */
extern int forkrate_limit;	/* How many forks per second ? */
int	mailqmode = 1;		/* ZMailer v1.0 mode on mailq */
const char *  mailqsock = NULL;

static int vtxprep_skip      = 0;
static int vtxprep_skip_any  = 0;
static int vtxprep_skip_lock = 0;
static time_t next_dirscan     = 0;
static time_t next_idlecleanup = 0;
static time_t next_interim_report_time = 0;
static struct sptree *dirscan_mesh = NULL;
static int newents_limit = 400;
extern int default_full_content; /* on conf.c */

#include "memtypes.h"
extern memtypes stickymem;

static struct ctlfile *schedule __((int fd, const char *file, long ino, const int));
static struct ctlfile *vtxprep __((struct ctlfile *, const char *, const int));
static int  vtxmatch __((struct vertex *, struct config_entry *));
static void link_in __((int flag, struct vertex *vp, const char *s));
static int  lockverify __((struct ctlfile *, const char *, const int));
static int  globmatch   __((const char *, const char*));
static void vtxdo   __((struct vertex *, struct config_entry *, const char *));

extern void  cfp_mksubdirs __((const char *, const char*));
extern const char *cfpdirname __((int));

static RETSIGTYPE sig_exit   __((int sig));
static RETSIGTYPE sig_quit   __((int sig));
static RETSIGTYPE sig_alarm  __((int sig));
static RETSIGTYPE sig_iot    __((int sig));
static RETSIGTYPE sig_readcf __((int sig));

extern char *strerror __((int err));

static struct MIB_MtaEntry MIBMtaEntryLocal = {0,};
struct MIB_MtaEntry *MIBMtaEntry = &MIBMtaEntryLocal;


static int    timeserver_pid = 0;
extern time_t mytime          __((time_t *));
static void   init_timeserver __((void));

#ifdef HAVE_SELECT /* Well, not exactly kosher assumption.. */
/* extern int gettimeofday __((struct timeval *,)); */
#else
extern time_t time __((time_t *));
#endif

static int loginitsched __((int));
static int loginitsched(sig)
int sig;
{
	int flags;

	if (logfn != NULL) {
	  sfsync(sfstdout);
	  sfseek(sfstdout, 0, 0);
	  sfsync(sfstderr);
	  sfseek(sfstderr, 0, 0);
	  if (sfopen(sfstdout, logfn, "a") != sfstdout
	      || dup2(sffileno(sfstdout), sffileno(sfstderr)) < 0) {	/* sigh */
	    /* XX: stderr might be closed at this point... */
	    sfprintf(sfstderr, "%s: cannot open log: %s, errno=%d\n", progname, logfn, errno);
	    return -1;
	  }
#if	defined(F_SETFL) && defined(O_APPEND)
	  flags = fcntl(sffileno(sfstdout), F_GETFL, 0);
	  flags |= O_APPEND;
	  fcntl(sffileno(sfstdout), F_SETFL, flags);
#endif	/* F_SETFL */
#if defined(F_SETFD)
	  fcntl(sffileno(sfstdout), F_SETFD, 1); /* close-on-exec */
#endif
	  sfset(sfstdout, SF_LINE, 1);
	  sfset(sfstderr, SF_LINE, 1);
	}
	if (statusfn != NULL && statuslog != NULL) {
	  sfsync(statuslog);
	  if (sfopen(statuslog, statusfn, "a") != statuslog) {
	    sfprintf(sfstderr,"%s: cannot open statuslog: %s, errno=%d\n", progname, statusfn, errno);
	    return -1;
	  }
	  sfset(statuslog, SF_WHOLE, 1);
#if defined(F_SETFD)
	  fcntl(sffileno(statuslog), F_SETFD, 1); /* close-on-exec */
#endif
	}
	SIGNAL_HANDLE(SIGHUP, (RETSIGTYPE(*)__((int))) loginitsched);
	return 0;
}

struct dirstatname {
	struct stat st;
	long ino;
	time_t	not_before;
	char name[1]; /* Allocate enough size */
};
struct dirqueue {
	int	wrksum;
	int	sorted;
	int	wrkcount;
	int	wrkspace;
	int	wrkcount2; /* Back-pushed material a *2 -queue */
	int	wrkspace2;
	struct dirstatname **stats;
	struct dirstatname **stats2;
};

static int dirqueuescan __((const char *dir,struct dirqueue *dq, int subdirs));
int syncweb __((struct dirqueue *dq));

int global_maxkids = 1000;
time_t now;

Sfio_t * vfp_open(cfp)
struct ctlfile *cfp;
{
	Sfio_t *vfp;
	int fd;

	if (!cfp->vfpfn) return NULL;

	/* Open the vfp *ONLY* if the logging file exists,
	   and can be written to.  If the file does not
	   exist, no logging shall happen! */

	setreuid(0, cfp->uid);
	fd = open(cfp->vfpfn, O_WRONLY|O_APPEND, 0);
	setreuid(0, 0);
	if (fd < 0) return NULL; /* Can't open it! */
	vfp = sfnew(NULL, NULL, 0, fd, SF_WRITE|SF_APPEND|SF_LINE);
	if (!vfp) return NULL; /* Failure to open */

	sfseek(vfp, (Sfoff_t)0, SEEK_END);
	return vfp;
}


static void cfp_free __((struct ctlfile *cfp, struct spblk *spl));
static void cfp_free0 __((struct ctlfile *cfp));

static void cfp_free0(cfp)
struct ctlfile *cfp;
{

	struct vertex *vp, *nvp;

	/* Delete from memory */

	if (cfp->vfpfn) {
	  Sfio_t *vfp = vfp_open(cfp);
	  if (vfp) {
	    sfprintf(vfp,
		     "ordered deletion of task file from scheduler memory (%s)\n",
		     cfp->mid);
	    sfclose(vfp);
	  }
	}

	/* Throw all way, if no vertices.. */
	if (!cfp->head) {
	  /* This should *not* be happening.. */
	  unctlfile(cfp, 1);
	  return;
	}

	for (vp = cfp->head; vp != NULL; vp = nvp) {
	  /* Stash the next pointer, because the CFP content
	     may become trashed at the end of the run. */
	  nvp = vp->next[L_CTLFILE];

	  MIBMtaEntry->mtaStoredRecipients     -= vp->ngroup;
	  MIBMtaEntry->mtaReceivedRecipientsSc -= vp->ngroup;
	  vp->ngroup = 0;
	  unvertex(vp,1,1); /* Don't unlink()! Just free()! */
	}
	/* CFP freeup happens at last vertex's unvertex() */
}

static void cfp_free(cfp, spl)
struct ctlfile *cfp;
struct spblk   *spl;
{
	/* Delete from the  spt_mesh[]  */

	if (spl == NULL && cfp->id)
	  spl = sp_lookup((u_long)(cfp->id), spt_mesh[L_CTLFILE]);
	if (spl != NULL)
	  sp_delete(spl, spt_mesh[L_CTLFILE]);

	/* And from the memory */

	cfp_free0(cfp);
}


static int ctl_free __((struct spblk *spl));
static int ctl_free(spl)
struct spblk *spl;
{
	cfp_free((struct ctlfile *)spl->data, NULL);
	return 0;
}


/*
 *  free_cfp_memory(cfp) -- release all of the memory associated with the
 *  control file -- some of it is conditionally allocated, or perhaps
 *  previously released..  (cfp->contents, for example)
 */
void free_cfp_memory(cfp)
struct ctlfile *cfp;
{
	if (cfp->contents)	free(cfp->contents);
	if (cfp->vfpfn)		free(cfp->vfpfn);
	if (cfp->mid)		free(cfp->mid);
	if (cfp->erroraddr)	free(cfp->erroraddr);
	if (cfp->logident)	free(cfp->logident);
	if (cfp->envid)		free(cfp->envid);

memset(cfp, 0x55, sizeof(*cfp));

	free((char *)cfp);
}


struct dirqueue dirqb = { 0, };
struct dirqueue *dirq = &dirqb;

const char **ArgvSave;

extern int main __((int, const char **));

static struct config_entry *cehead = NULL;


/* #define GLIBC_MALLOC_DEBUG__ */
#ifdef GLIBC_MALLOC_DEBUG__ /* memory allocation debugging with GLIBC */

#include <malloc.h> /* GLIBC malloc.h ! */

/* Global variables used to hold underlaying hook values.  */
static void *(*old_malloc_hook) (size_t, const void * );
static void *(*old_realloc_hook) (void *, size_t, const void *);
static void (*old_free_hook) (void*, const void *);
static void *(*old_memalign_hook) (size_t, size_t, const void *);

/* Prototypes for our hooks.  */
static void *my_malloc_hook  (size_t, const void*);
static void *my_realloc_hook (void *,size_t, const void*);
static void  my_free_hook    (void*, const void*);
static void *my_memalign_hook  (size_t, size_t, const void*);
     
static void *
my_malloc_hook (size_t size, const void *CALLER)
{
  void *result;
  /* Restore all old hooks */
  __malloc_hook = old_malloc_hook;
  __free_hook   = old_free_hook;
  /* Call recursively */
  result = malloc (size);
  /* Save underlaying hooks */
  old_malloc_hook = __malloc_hook;
  old_free_hook   = __free_hook;
  /* `printf' might call `malloc', so protect it too. */
  sfprintf(sfstderr,"# malloc (%u) returns %p @%p\n",
	   (unsigned int) size, result, CALLER);
  /* Restore our own hooks */
  __malloc_hook = my_malloc_hook;
  __free_hook = my_free_hook;
  return result;
}

static void *
my_realloc_hook (void *ptr, size_t size, const void *CALLER)
{
  void *result;
  /* Restore all old hooks */
  __realloc_hook = old_realloc_hook;
  __malloc_hook = old_malloc_hook;
  __free_hook = old_free_hook;
  /* Call recursively */
  result = realloc (ptr, size);
  /* Save underlaying hooks */
  old_realloc_hook = __realloc_hook;
  old_malloc_hook  = __malloc_hook;
  old_free_hook    = __free_hook;
  /* `printf' might call `malloc', so protect it too. */
  sfprintf(sfstderr,"# realloc (%p,%u) returns %p @%p\n", ptr, (unsigned int) size, result, CALLER);
  /* Restore our own hooks */
  __realloc_hook = my_realloc_hook;
  __malloc_hook  = my_malloc_hook;
  __free_hook    = my_free_hook;
  return result;
}

static void *
my_memalign_hook (size_t align, size_t size, const void *CALLER)
{
  void *result;
  /* Restore all old hooks */
  __memalign_hook = old_memalign_hook;
  __malloc_hook = old_malloc_hook;
  __free_hook = old_free_hook;
  /* Call recursively */
  result = memalign (align, size);
  /* Save underlaying hooks */
  old_memalign_hook = __memalign_hook;
  old_malloc_hook  = __malloc_hook;
  old_free_hook    = __free_hook;
  /* `printf' might call `malloc', so protect it too. */
  sfprintf(sfstderr,"# memalign (%u,%u) returns %p @%p\n",
	   (unsigned)align, (unsigned)size, result, CALLER);
  /* Restore our own hooks */
  __memalign_hook = my_memalign_hook;
  __malloc_hook  = my_malloc_hook;
  __free_hook    = my_free_hook;
  return result;
}
     
static void
my_free_hook (void *ptr, const void *CALLER)
{
  /* Restore all old hooks */
  __malloc_hook = old_malloc_hook;
  __free_hook = old_free_hook;
  /* Call recursively */
  free (ptr);
  /* Save underlaying hooks */
  old_malloc_hook = __malloc_hook;
  old_free_hook = __free_hook;
  /* `printf' might call `free', so protect it too. */
  sfprintf(sfstderr,"# freed pointer %p @%p\n", ptr, CALLER);
  /* Restore our own hooks */
  __malloc_hook = my_malloc_hook;
  __free_hook = my_free_hook;
}
#endif

int
main(argc, argv)
	int argc;
	const char *argv[];
{
	struct ctlfile *cfp;
	const char *config, *cp;
	int i, daemonflg, c, errflg, version, fd;
	long offout, offerr;

	const char *t, *syslogflg;

#ifdef GLIBC_MALLOC_DEBUG__ /* memory allocation debugging with GLIBC */
	old_malloc_hook = __malloc_hook;
	__malloc_hook = my_malloc_hook;
	old_memalign_hook = __memalign_hook;
	__memalign_hook = my_memalign_hook;
	old_realloc_hook = __realloc_hook;
	__realloc_hook = my_realloc_hook;
	old_free_hook = __free_hook;
	__free_hook = my_free_hook;
#endif

	syslogflg = getzenv("SYSLOGFLG");
	if (syslogflg == NULL)
	  syslogflg = "";
	t = syslogflg;
	for ( ; *t ; ++t ) {
	  if (*t == 'c' || *t == 'C')
	    break;
	}
	do_syslog = (*t != '\0');

#ifdef HAVE_SETGROUPS
	/* We null supplementary groups list entirely */
	setgroups(0, NULL);
#endif

	freeze = 0;
	/* setlinebuf(stderr);  -- no need for this ? */

	ArgvSave = argv;

	mytime(&sched_starttime);

	memset(&dirqb,0,sizeof(dirqb));
	dirscan_mesh = sp_init();

	if ((progname = strrchr(argv[0], '/')) == NULL)
		progname = argv[0];
	else
		++progname;

	stickymem = MEM_MALLOC;

	resources_maximize_nofiles();

	/* The theory is, that scheduler needs circa 30 fd's for its own uses,
	   and it will use all others on child-process communication fifos. */
	/* Of these, 20 are for MQ2 sockets */

	global_maxkids = resources_query_nofiles()-30;

	/* Probe how many FDs each TA needs! */

	{
	  int to[2], from[2];
	  pipes_create(to,from);

	  close(to[0]); close(to[1]);

	  if (to[0] != from[1]) {

	    /* Two pipes! */
	    close(from[0]); close(from[1]);

	    global_maxkids >>= 1; /* Half the MAXKIDS count */

	  } /* else
	       Socketpair or equivalent bidirectional one!
	       Only one FD per child is used!               */
	}

	postoffice = rendezvous = logfn = statusfn = config = NULL;
	daemonflg = 1;
	dlyverbose = 0;
	syncstart = 0;
	verbose = errflg = version = 0;
	for (;;) {
		c = getopt(argc, (char*const*)argv,
			   "divE:f:Fl:HL:M:nN:p:P:q:QR:SVW");
		if (c == EOF)
		  break;
		switch (c) {
		case 'f':	/* override default config file */
			config = optarg;
			break;
		case 'E':
			newents_limit = atoi(optarg);
			if (newents_limit < 10)
			  newents_limit = 10;
			break;
		case 'F':
			freeze = 1;
			break;
		case 'l':
			statusfn = optarg;
			statuslog = sfopen(NULL, statusfn, "a");
			if (!statuslog) {
			  perror("Can't open statistics log file (-l)");
			  exit(1);
			}
			sfset(statuslog, SF_LINE, 1);
#if defined(F_SETFD)
			fcntl(sffileno(statuslog), F_SETFD, 1);
			/* close-on-exec */
#endif
			break;
		case 'H':
			if (hashlevels < 2)
				++hashlevels;
			break;
		case 'L':	/* override default log file */
			logfn = optarg;
			break;
		case 'M':
			mailqmode = atoi(optarg);
			if (mailqmode < 1 || mailqmode > 2) {
			  sfprintf(sfstderr,"scheduler: -M parameter is either 1, or 2\n");
			  exit(EX_USAGE);
			}
			break;
		case 'n':
			default_full_content = !default_full_content;
			break;
		case 'N':
			if ((transportmaxnofiles = atoi(optarg)) < 10)
				transportmaxnofiles = TRANSPORTMAXNOFILES;
			break;
		case 'p':
			procselect  = optarg;
			procselhost = strchr(procselect,'/');
			if (procselhost)
			  *procselhost++ = 0;
			else {
			  sfprintf(sfstderr,"scheduler: -p parameter is of form: channel/host\n");
			  exit(64);
			}
			break;
		case 'P':	/* override default postoffice */
			postoffice = optarg;
			break;
		case 'Q':
			mailq_Q_mode = 1;
			break;
		case 'q':	/* override default mail queue rendezvous */
			rendezvous = optarg;
			break;
		case 'R':	/* How many new childs per second to be spawned ? */
			forkrate_limit = atoi(optarg);
			if (forkrate_limit < 1)
			  forkrate_limit = 1;
			break;
		case 'v':	/* be verbose and synchronous */
			++verbose;
			daemonflg = 0;
			break;
		case 'W':
			dlyverbose = verbose;
			verbose = 0;
			break;
		case 'd':	/* daemon again */
			daemonflg = 1;
			break;
		case 'i':	/* interactive */
			daemonflg = 0;
			break;
		case 'V':
			version = 1;
			daemonflg = 0;
			break;
		case 'S':
			syncstart = 1;
			break;
		case '?':
		default:
			errflg++;
			break;
		}
	}

	if (errflg) {
	  sfprintf(sfstderr,
		   "Usage: %s [-dHisvV -M (1|2) -f configfile -L logfile -P postoffice -Q rendezvous]\n",
		   progname);
	  exit(128+errflg);
	}
	cp = getzenv("SCHEDULERDIRHASH");
	if (cp){
	  if ((cp[0] == '1' || cp[0] == '2') &&
	      cp[1] == 0)
	    hashlevels = cp[0] - '0';
	  else
	    hashlevels = 0;
	}

	mailshare = getzenv("MAILSHARE");
	if (mailshare == NULL)
	  mailshare = MAILSHARE;
	cp = getzenv("LOGDIR");
	if (cp != NULL)
	  qlogdir = cp;
	if (daemonflg && logfn == NULL) {
	  logfn = emalloc(2 + (u_int)(strlen(qlogdir) + strlen(progname)));
	  sprintf((char*)logfn, "%s/%s", qlogdir, progname);
	}
	if (logfn != NULL) {
	  /* loginit is a signal handler, so can't pass log */
	  if (loginitsched(SIGHUP) < 0) /* do setlinebuf() there */
	    die(1, "log initialization failure");
	  /* close and reopen log files */
	  SIGNAL_HANDLE(SIGHUP, (RETSIGTYPE(*)__((int))) loginitsched);
	} else {
	  SIGNAL_IGNORE(SIGHUP); /* no surprises please */
	  sfset(sfstdout, SF_LINE, 1);
	}
#ifdef USE_SIGREAPER
# ifdef SIGCLD
	SIGNAL_HANDLE(SIGCLD,  sig_chld);
# else
	SIGNAL_HANDLE(SIGCHLD, sig_chld);
# endif
#else
# ifdef SIGCLD
	SIGNAL_HANDLE(SIGCLD,SIG_IGN);		/* Auto-reap the kids.. */
# else
	SIGNAL_HANDLE(SIGCHLD,SIG_IGN);
# endif
#endif

#ifdef	SIGUSR1
	SIGNAL_HANDLE(SIGUSR1, sig_readcf);
#endif	/* SIGUSR1 */
	if (verbose || version) {
	  prversion("scheduler");
	  if (version)
	    exit(0);
	  sfputc(sfstderr, '\n');
	}
	offout = sftell(sfstdout);
	offerr = sftell(sfstderr);
	if (config == NULL) {
	  config = emalloc(3 + (u_int)(strlen(mailshare)
				       + strlen(progname)
				       + strlen(qcf_suffix)));
	  sprintf((char*)config, "%s/%s.%s", mailshare, progname, qcf_suffix);
	}
	cehead = readconfig(config);
	if (cehead == NULL) {
	  cp = emalloc(strlen(config)+50);
	  sprintf((char*)cp, "null control file, probably errors in it: %s", config);
	  die(1, cp);
	  /* NOTREACHED */
	}

	if (postoffice == NULL && (postoffice = getzenv("POSTOFFICE")) == NULL)
	  postoffice = POSTOFFICE;

	if (chdir(postoffice) < 0 || chdir(TRANSPORTDIR) < 0)
	  sfprintf(sfstderr, "%s: cannot chdir to %s/%s.\n",
		   progname, postoffice, TRANSPORTDIR);

	if (rendezvous == NULL && (rendezvous = getzenv("RENDEZVOUS")) == NULL)
	  rendezvous = qoutputfile;
	if (daemonflg) {
	  /* X: check if another daemon is running already */
	  if (!verbose
	      && (offout < sftell(sfstdout) || offerr < sftell(sfstderr))) {
	    sfprintf(sfstderr, "%ld %ld %ld %ld\n", offout, sftell(sfstdout),
		     offerr, sftell(sfstderr));
	    sfprintf(sfstderr, "%s: daemon not started.\n", progname);
	    die(1, "too many scheduler daemons");
	    /* NOTREACHED */
	  }
	  detach();		/* leave worldy matters behind */
	  mytime(&now);
	  sfprintf(sfstdout, "%s: scheduler daemon (%s)\n\tpid %d started at %s\n",
		   progname, Version, (int)getpid(), (char *)rfc822date(&now));
	}
	/* Actually we want this to act as daemon,
	   even when not in daemon mode.. */
	if (killprevious(SIGTERM, pidfile) != 0) {
	  sfprintf(sfstdout, "%s: Can't write my pid to a file ?? Out of diskspace ??\n",progname);
	  die(1,"Can't write scheduler pid to a file!?");
	  /* NOTREACHED */
	}

	for (i = 0; i < SIZE_L; ++i) {
	  spt_mesh[i] = sp_init();
	  spt_mesh[i]->symbols = sp_init();
	}
	zopenlog("scheduler", LOG_PID, LOG_MAIL);
	if (optind < argc) {
	  /* process the specified control files only */
	  for (; optind < argc; ++optind) {
	    long ino = atol(argv[optind]);
	    if ((fd = eopen(argv[optind], O_RDWR, 0)) < 0)
	      continue;
	    /* the close(fd) is done in vtxprep */
	    cfp = schedule(fd, argv[optind], ino, 0);
	    if (cfp == NULL) {
	      if (verbose)
		sfprintf(sfstderr, "Nothing scheduled for %s!\n",
			 argv[optind]);
	    } else
	      eunlink(argv[optind], "sch-argv");
	  }
	  doagenda();
	  killpidfile(pidfile);
	  exit(0);
	}
	mustexit = gotalarm = dumpq = rereadcf = 0;
	canexit = 0;
	SIGNAL_IGNORE(SIGPIPE);
	SIGNAL_HANDLE(SIGALRM, sig_alarm);	/* process agenda */
	SIGNAL_HANDLE(SIGUSR2, sig_iot);	/* dump queue info */

	/* call it to create the timeserver -- if possible */
	init_timeserver(); /* Will take around 3-4 secs.. */

	queryipcinit();

	dirqueuescan(".", dirq, 1);

	vtxprep_skip_lock = 0;
	syncweb(dirq);


	canexit = 1;
	SIGNAL_HANDLE(SIGTERM, sig_exit);	/* split */
	SIGNAL_HANDLE(SIGQUIT, sig_quit);	/* Slow shutdown */
#ifdef	MALLOC_TRACE
	mal_leaktrace(1);
#endif	/* MALLOC_TRACE */

	/* If we do a sync-start, we are synchronous.. */

	if (syncstart) {
	  int startcount;
	  dirqueuescan(".", dirq, 1);
	  startcount = dirq->wrksum;
	  while (dirq->wrksum > 0 && !mustexit) {
	    if (syncweb(dirq) < 0)
	      break;
	    queryipccheck();
	  }
	  sfprintf(sfstderr,"Synchronous startup completed, messages: %d (%d skipped) recipients: %d\n",
		   global_wrkcnt, startcount - global_wrkcnt, thread_count_recipients());
	  sfprintf(sfstderr,"***********************************************************************\n");
	  syncstart = 0;
	}

	if (dlyverbose) verbose = dlyverbose;

	do {
	  time_t timeout;

	  mytime(&now);

	  canexit = 0;

	  if (now >= next_dirscan) {
	    /* Directory scan time for new jobs ..    */
	    /* Do it recursively every now and then,
	       so that if we forget some jobs, they will
	       become relearned soon enough.          */
	    if (dirqueuescan(".", dirq, 
#if 1 /* Do recursively every time */
			     1
#else
			     (now >= next_idlecleanup)
#endif
			     ) < 150) {
	      /* If we have more things to scan, don't quit yet! */
	      next_dirscan = now + sweepinterval;  /* 10 seconds interval */
	      if (dirq->wrksum > 100)
		next_dirscan = now + 60; /* Lots of work, pick new jobs
					    less frequently */
	    }
	  }

	  if (now >= next_idlecleanup) {
	    next_idlecleanup = now + 20; /* 20 second interval */
	    idle_cleanup();
	  }

	  if (now >= next_interim_report_time) {
	    next_interim_report_time = now + 120; /* every 2 minutes */
	    interim_report_run();
	  }

	  /* See when to timeout from mux() */
	  timeout = next_dirscan;

	  /* If we still have things in pre-scheduler queue... */
	  if (dirq->wrksum > 0 &&
	      dirq->wrkcount > 0 &&
	      dirq->stats[ dirq->wrkcount-1 ]->not_before <= now)
	    timeout = now;

	  /* Submit possible new jobs (unless frozen) */
	  if (!freeze && !syncstart && doagenda() != 0)
	    timeout = now;	/* we still have some jobs avail for start */

	  gotalarm = 0;
	  canexit = 1;

	  /* mux on the stdout of children */
	  for (;;) {
	    if (dumpq) {
	      qprint(-1);
	      dumpq = 0;
	    }
	    if (rereadcf) {
	      cehead = rereadconfig(cehead, config);
	      rereadcf = 0;
	    }
	    mytime(&now);

	    /* Submit one item from pre-scheduler-queue into the scheduler */
	    if (dirq->wrksum > 1 ) {
	      /* If more things in queue, submit them up to 200 pieces, or
		 until spent two seconds at it! */
	      time_t now0 = now + 2;
	      for (i=0; i < 200 && now > now0; ++i) {
		if (syncweb(dirq) < 0)
		  break; /* Out of queue! */
		mytime(&now);
	      }
	    }
	    if (dirq->wrksum > 0)
	      syncweb(dirq);

	    if (slow_shutdown) {
	      timeout = now+2;
	      shutdown_kids();  /* If there are any to shut down.. */
	    }
	    if (!(mux(timeout) == 0 && !gotalarm &&
		  dirq->wrksum == 0 && !mustexit && timeout > now))
	      break;
	    if (readsockcnt == 0 && slow_shutdown) {
	      /* No more childs to read, hop hop die away! */
	      mustexit = 1;
	      break;
	    }
	  }
	} while (!mustexit);

	/* Doing nicely we would kill the childs here, but we are not
	   such a nice people -- we just discard incore data, and crash out.. */

	sp_scan(ctl_free, NULL, spt_mesh[L_CTLFILE]);

#ifdef	MALLOC_TRACE
	mal_dumpleaktrace(stderr);
#endif	/* MALLOC_TRACE */

	killpidfile(pidfile);

	if (mustexit)
		die(0, "signal");
	return 0;
}

static RETSIGTYPE sig_exit(sig)
int sig;
{
	
	if (querysocket >= 0) {		/* give up mailq socket asap */
		close(querysocket);
		querysocket = -1;
	}
	if (canexit)
		die(0, "signal");
	mustexit = 1;
}

static RETSIGTYPE sig_quit(sig)
int sig;
{
	slow_shutdown = 1;
	freeze = 1;
}


#ifdef SIGUSR2
static RETSIGTYPE sig_iot(sig)
int sig;
{
	dumpq = 1;
	SIGNAL_HANDLE(SIGUSR2, sig_iot);
}
#endif

#ifdef SIGUSR1
static RETSIGTYPE sig_readcf(sig)
int sig;
{
	rereadcf = 1;
	SIGNAL_HANDLE(SIGUSR1, sig_readcf);
}
#endif

/*
 * Absorb any new files that showed up in our directory.
 */

int
dq_insert(DQ, ino, file, delay)
	void *DQ;
	long ino;
	const char *file;
	int delay;
{
	struct stat stbuf;
	struct dirstatname *dsn;
	struct dirqueue *dq = DQ;

	if (!ino) return 1; /* Well, actually it isn't, but we "makebelieve" */

	mytime(&now);

	if (dq == NULL)
	  dq = dirq;

	if (lstat(file,&stbuf) != 0 ||
	    !S_ISREG(stbuf.st_mode)) {
	  /* Not a regular file.. Let it be there for the manager
	     to wonder.. */
	  return -1;
	}

	/* 
	   if (DQ == NULL)
	   sfprintf(sfstderr,"dq_insert(NULL,ino=%ld, file='%s', delay=%d)\n",
	   ino,file,delay);
	 */

	/* Is it already in the database ? */
	if (sp_lookup((u_long)ino,dirscan_mesh) != NULL) {
	  sfprintf(sfstderr,"scheduler: tried to dq_insert(ino=%ld, file='%s') already in queue\n",ino, file);
	  return 1; /* It is! */
	}

	/* Now store the entry */
	dsn = (struct dirstatname*)emalloc(sizeof(*dsn)+strlen(file)+1);
	memcpy(&(dsn->st),&stbuf,sizeof(stbuf));
	dsn->ino = ino;
	dsn->not_before = now + delay;
	strcpy(dsn->name,file);

	sp_install(ino, (void *)dsn, 0, dirscan_mesh);

	/* Put the new entry into the normal queue, unless there
	   is stuff at the delayed queue, OR the delay is positive! */

	if (delay <= 0 && dq->wrkcount2 == 0) {
	  /* Into the normal queue */
	  if (dq->wrkspace <= dq->wrkcount) {
	    /* Increase the space */
	    dq->wrkspace = dq->wrkspace ? dq->wrkspace << 1 : 8;
	    /* malloc(size) = realloc(NULL,size) */
	    dq->stats = (struct dirstatname**)erealloc(dq->stats,
						       sizeof(void*) *
						       dq->wrkspace);
	  }
	  dq->stats[dq->wrkcount] = dsn;
	  dq->wrkcount += 1;
	  dq->wrksum   += 1;
	  dq->sorted    = 0;
	} else {
	  /* Into the DELAYED QUEUE */
	  if (dq->wrkspace2 <= dq->wrkcount2) {
	    /* Increase the space */
	    dq->wrkspace2 = dq->wrkspace2 ? dq->wrkspace2 << 1 : 8;
	    /* malloc(size) = realloc(NULL,size) */
	    dq->stats2 = (struct dirstatname**)erealloc(dq->stats2,
							sizeof(void*) *
							dq->wrkspace2);
	  }
	  dq->stats2[dq->wrkcount2] = dsn;
	  dq->wrkcount2 += 1;
	  dq->wrksum    += 1;
	}
	++MIBMtaEntry->mtaReceivedMessagesSc;
	return 0;
}

int in_dirscanqueue(DQ,ino)
	void *DQ;
	long ino;
{
	struct dirqueue *dq = DQ;

	if (dq == NULL)
	  dq = dirq;

	/* Return 1, if can find the "ino" in the queue */

	if (dq->wrksum == 0 || dirscan_mesh == NULL) return 0;
	if (sp_lookup((u_long)ino,dirscan_mesh) != NULL) return 1;
	return 0;
}

static int dq_ctimecompare __((const void *, const void *));
static int dq_ctimecompare(b,a) /* we want oldest entry LAST */
const void *a; const void *b;
{
	const struct dirstatname **A = (const struct dirstatname **)a;
	const struct dirstatname **B = (const struct dirstatname **)b;
	int rc;

#if 0
	if ((*A)->not_before > now) return  1;
	if ((*B)->not_before > now) return -1;
#endif

	rc = ((*A)->st.st_ctime - (*B)->st.st_ctime);
	return rc;
}

static int dirqueuescan(dir, dq, subdirs)
	const char *dir;
	struct dirqueue *dq;
	int subdirs;
{
	DIR *dirp;
	struct dirent *dp;
	struct stat stbuf;
	char file[MAXNAMLEN+1];
	int newents = 0;

#if 0
	static time_t modtime = 0;

	/* Any changes lately ? */
	if (estat(dir, &stbuf) < 0)
	  return -1;	/* Could not stat.. */
	if (stbuf.st_mtime == modtime)
	  return 0;	/* any changes lately ? */
	modtime = stbuf.st_mtime;
#endif

	if (verbose && dir[0] == '.') {
	  sfprintf(sfstdout, "dirqueuescan(dir='%s') ",dir);
	  sfsync(sfstdout);
	}

	/* Some changes lately, open the dir and read it */

	dirp = opendir(dir);
	if (!dirp) {
	  sfprintf(sfstderr,"A 'this can never fail' opendir('%s') failed!; errno=%d (%s)\n",dir,errno,strerror(errno));
	  return 0;
	}

	for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
	  /* Scan filenames into memory */

	  /* Here we are presuming the time retrieval is essentially
	     _free_ in form of shared memory segment.. */
	  queryipccheck();

	  if (!syncstart && newents > newents_limit)
	    break; /* At most NNN per one go */

	  if (subdirs &&
	      dp->d_name[0] >= 'A' &&
	      dp->d_name[0] <= 'Z' &&
	      dp->d_name[1] ==  0 ) {
	    /* We do this recursively.. */
	    if (dir[0] == '.' && dir[1] == 0)
	      strcpy(file, dp->d_name);
	    else
	      sprintf(file, "%s/%s", dir, dp->d_name);

	    if (lstat(file,&stbuf) != 0 ||
		!S_ISDIR(stbuf.st_mode)) {
	      /* Not a directory.. Let it be there for the manager
		 to wonder.. */
	      continue;
	    }
	    /* Recurse into levels below.. */
	    newents += dirqueuescan(file, dq, subdirs);
	    continue;
	  } /* End of directories of names "A" .. "Z" */

	  if (dp->d_name[0] >= '0' &&
	      dp->d_name[0] <= '9') {
	    /* A file whose name STARTS with a number (digit) */

	    long ino = atol(dp->d_name);
	    if (in_dirscanqueue(dq,ino))
	      /* Already in pre-schedule-queue */
	      continue;

	    if (dir[0] == '.' && dir[1] == 0)
	      strcpy(file, dp->d_name);
	    else
	      sprintf(file, "%s/%s", dir, dp->d_name);

	    /* We may have this file in processing state...  */
	    {
	      struct spblk *spl;
	      spl = sp_lookup((u_long)ino, spt_mesh[L_CTLFILE]);
	      if (spl != NULL) {
		/* Already in processing, don't touch.. */
		/*printf("File: %s active (not previously locked)\n",file);*/
		++vtxprep_skip_any;
		continue;
	      }
	    }

	    if (dq_insert(dq, ino, file, -1))
	      continue;

	    ++newents;
	  } /* ... end of "filename starts with a [0-9]" */
	}

#ifdef	BUGGY_CLOSEDIR
	/*
	 * Major serious bug time here;  some closedir()'s
	 * free dirp before referring to dirp->dd_fd. GRRR.
	 * XX: remove this when bug is eradicated from System V's.
	 */
	close(dirp->dd_fd);
#endif
	closedir(dirp);

	if (verbose && dir[0] == '.')
	  sfprintf(sfstdout,"wrksum=%d new=%d\n",dq->wrksum,newents);

	return newents;
}

int syncweb(dq)
	struct dirqueue *dq;
{
	struct stat *stbuf;
	char *file;
	struct dirstatname *dqstats;
	struct spblk *spl;
	int wrkcnt = 0;
	int wrkidx = dq->wrkcount -1;
	long ino;

	/* Any work to do ? */
	if (dq->wrksum == 0) return -1;

	/* Be responsive, check query channel */
	queryipccheck();

	if (dq->wrkcount == 0 && dq->wrkcount2 > 0) {
	  /* Ok, the primary queue is empty, move the delayed
	     queue into the primary one. */
	  if (dq->stats != NULL) free(dq->stats);
	  dq->stats = dq->stats2;
	  dq->stats2 = NULL;
	  dq->wrkcount  = dq->wrkcount2;
	  dq->wrkcount2 = 0;
	  dq->wrkspace  = dq->wrkspace2;
	  dq->wrkspace2 = 0;
	  dq->sorted = 0;
	}

	if (!dq->sorted && dq->wrkcount > 1) {
	  /* Sort the dq->stats[] per file ctime -- LATEST on slot 0.
	     (we drain this queue from the END) */
	  mytime(&now);
	  qsort((void*)dq->stats,
		dq->wrkcount,
		sizeof(void*),
		dq_ctimecompare );
	  dq->sorted = 1;
	}

	mytime(&now);

	for (; wrkidx >= 0; --wrkidx) {

	  /* Process only one -- from the tail -- but leave
	     'not_before' things behind... */
	  if (dq->stats[wrkidx]->not_before > now)
	    continue; /* WAIT! */

	  break;
	}

	/* Ok some, decrement the count to change it to index */
	dq->wrkcount -= 1;
	dq->wrksum   -= 1;

	dqstats = dq->stats[wrkidx];
	file  =   dqstats->name;
	stbuf = &(dqstats->st);
	ino   =   dqstats->ino;

	if (dq->wrkcount > wrkidx) {
	  /* Skipped some ! Compact the array ! */
	  memcpy( &dq->stats[wrkidx], &dq->stats[wrkidx+1],
		  sizeof(dq->stats[0]) * (dq->wrkcount - wrkidx));
	}
	dq->stats[dq->wrkcount] = NULL;

	/* Now we have pointers */

	/* Deletion from the  dirscan_mesh  should ALWAYS succeed.. */
	spl = sp_lookup((u_long)ino, dirscan_mesh);
	if (spl != NULL)
	  sp_delete(spl,dirscan_mesh);

	/* Sometimes we may get files already in processing
	   into our pre-schedule queue */

	/* Already in processing ? */
	spl = sp_lookup((u_long)ino, spt_mesh[L_CTLFILE]);
	if (spl == NULL) {
	  /* Not yet in processing! */
	  int fd;

	  /* Can open ? */
	  if ((fd = eopen(file, O_RDWR, 0)) < 0) {
	    if (getuid() == 0)
	      eunlink(file,"sch-syncweb");	/* hrmpf! */
	  } else {
	    /* Ok, schedule! */
	    if (schedule(fd, file, ino, 0) != NULL) {
	      /* Success, increment counters */
	      ++wrkcnt;
	    }
	  }
	}

	/* Free the pre-schedule queue entry */
	free(dqstats);

	return wrkcnt;
}


static int sync_cfps __((struct ctlfile *,struct ctlfile *,struct procinfo*));
static int sync_cfps(oldcfp, newcfp, proc)
     struct ctlfile *oldcfp, *newcfp;
     struct procinfo *proc;
{
	struct vertex *ovp,  *nvp;
	struct vertex *novp, *nnvp;
	int ovp_count = 0;

	/* Scan both files thru their   vp->next[L_CTLFILE]  vertex chains.
	   If oldcfp has things that newcfp does not have, remove those from
	   oldcfp chains.

	   Chains start at  *cfp->head  pointer.

	   Comparisons can be done in linear order with respective
	   vp->orig[L_CHANNEL] and vp->orig[L_HOST] pointers to struct web..

	   We presume the  newcfp  will not contain objects that oldcfp does
	   not have -- while theorethically possible, it is not supported
	   skenario..
	*/

	if (verbose) {
	  sfprintf(sfstdout,"sync_cfps() OLDVTXES =");
	  for (ovp = oldcfp->head; ovp; ovp = ovp->next[L_CTLFILE])
	    sfprintf(sfstdout," %p{%p %p}", ovp, ovp->orig[L_CHANNEL], ovp->orig[L_HOST]);
	  sfprintf(sfstdout,"\n");
	  sfprintf(sfstdout,"sync_cfps() NEWVTXES =");
	  for (nvp = newcfp->head; nvp; nvp = nvp->next[L_CTLFILE])
	    sfprintf(sfstdout," %p{%p %p}", nvp, nvp->orig[L_CHANNEL], nvp->orig[L_HOST]);
	  sfprintf(sfstdout,"\n");
	}

	ovp = oldcfp->head;
	nvp = newcfp->head;


	while (ovp != NULL && nvp != NULL) {
	  ++ovp_count;

	  /* Always prepare for removal of the ovp object..
	     Pick the next-ovp pointer now */
	  novp  = ovp->next[L_CTLFILE];
	  nnvp  = nvp->next[L_CTLFILE];

	  /* Does this exist also on NVP chain ? */

#define VTXMATCH(ovp,nvp) (((ovp)->orig[L_CHANNEL] == (nvp)->orig[L_CHANNEL]) && ((ovp)->orig[L_HOST] == (nvp)->orig[L_HOST]))

	  if (VTXMATCH(ovp, nvp)) {
	    /* Verify/adjust OVP so that OVP and NVP have same
	       address indexes in them. */
	    int i, j, id;
	    if (verbose) {
	      sfprintf(sfstdout, " OLD ngroup=%d {", ovp->ngroup);
	      for(i = 0; i < ovp->ngroup; ++i)
		sfprintf(sfstdout, " %d", ovp->index[i]);
	      sfprintf(sfstdout, " }\n");
	      sfprintf(sfstdout, " NEW ngroup=%d {", nvp->ngroup);
	      for(i = 0; i < nvp->ngroup; ++i)
		sfprintf(sfstdout, " %d", nvp->index[i]);
	      sfprintf(sfstdout, " }\n");
	    }
	    for (i = ovp->ngroup -1; i >= 0; --i) {
	      id = ovp->index[i];
	      for (j = nvp->ngroup -1; j >= 0; --j) {
		if (nvp->index[j] == id)
		  goto next_i;
	      }
	      /* ovp index elt not found in new set! */
	      for (j = i+1; j < ovp->ngroup; ++j)
		ovp->index[j-1] = ovp->index[j];
	      ovp->ngroup -= 1;
	      MIBMtaEntry->mtaStoredRecipients -= 1;
	    next_i:;
	    }
	    if (ovp->ngroup <= 0)
	      unvertex(ovp,-1,1); /* Don't unlink()! free() *just* ovp! */

	    ovp = novp;
	    nvp = nnvp;
	    continue;
	  }

	  if (!VTXMATCH(ovp,nvp)) {

	    struct vertex *vp;
	    int i;

	    /* Uugh... Does not match :-( */

	    vp = ovp;

	    while (vp && !VTXMATCH(vp,nvp))
	      vp = vp->next[L_CTLFILE];

	    if (vp == NULL) {
	      /* New not in old at all ??? */
	      if (verbose)
		sfprintf(sfstdout," -- NEW vertex %p NOT in OLD set!\n", nvp);
	      /* Ok, skip it, and retry with OLD vs. new NEW */
	      nvp = nnvp;
	      continue;
	    }

	    /* All OVP instances before matching NVP
	       are to be removed from OVP chains */
	    i = 0;
	    while (ovp && ovp != vp) {
	      novp = ovp->next[L_CTLFILE];

	      MIBMtaEntry->mtaStoredRecipients -= vp->ngroup;
	      ovp->ngroup = 0;
	      unvertex(ovp,-1,1); /* Don't unlink()! free() *just* ovp! */

	      ++i;
	      ++ovp_count;
	      ovp = novp;
	    }
	    if (verbose)
	      sfprintf(sfstdout," -- Deleted %d OLD vertices\n", i);
	    /* Adjust NOVP variable too */
	    novp = NULL;
	    if (ovp)
	      novp = ovp->next[L_CTLFILE];
	  }

	  ovp = novp;
	  nvp = nnvp;
	}

	/* Ok,  'ovp' might be non-NULL while 'nvp' is already NULL */
	while (ovp) {
	  novp = ovp->next[L_CTLFILE];

	  MIBMtaEntry->mtaStoredRecipients -= ovp->ngroup;
	  ovp->ngroup = 0;
	  unvertex(ovp,-1,1); /* Don't unlink()! free() *just* ovp! */
	  /* Leaves CFP unharmed */

	  ovp = novp;
	}
	

	if (verbose)
	  sfprintf(sfstdout," -- Synced %d OLD vertices\n", ovp_count);

	oldcfp->rcpnts_failed = newcfp->rcpnts_failed;
	oldcfp->haderror |= newcfp->haderror;

	/* Now  oldcfp->head  might be NULL -> bad news.. */

	return 0;
}


void resync_file(proc, file)
	struct procinfo *proc;
	const char *file;
{
	struct stat stbuf;
	struct spblk *spl;
	long ino;
	const char *s;
	int fd;
	struct ctlfile *oldcfp, *newcfp;

	queryipccheck();

	lstat(file,&stbuf);

	s = strrchr(file,'/');
	if (s) ++s; else s = file;
	ino = atoi(s);

	/* Sometimes we may get reports of files
	   already deleted from processing.. */

	/* Already in processing ? */
	spl = sp_lookup((u_long)ino, spt_mesh[L_CTLFILE]);
	if (spl == NULL) {
#if 0
	  if (!in_dirscanqueue(NULL,ino)) {
	    sfprintf(sfstdout,"Resyncing file \"%s\" (ino=%ld)", file, ino);
	    sfprintf(sfstdout," .. not in processing database\n");
	  }
#endif
	  /* Not (anymore) in processing! */
	  return;
	}

	oldcfp = (struct ctlfile *)(spl->data);
	oldcfp->id = 0; /* Don't scramble spt_mesh[] latter below */

	if (spl != NULL)
	  sp_delete(spl, spt_mesh[L_CTLFILE]);
	spl = NULL;

	oldcfp->resynccount += 1;

	sfprintf(sfstdout, "Resyncing file \"%s\" (ino=%d pid=%d of=%d ho='%s') reqcnt=%d\n",
		 file, (int) ino, proc->pid, proc->overfed,
		 (proc->ho ? proc->ho->name : "<NULL>"), oldcfp->resynccount);
	/* sfprintf(sfstdout, " .. in processing db\n"); */

	if (oldcfp->resynccount > MAXRESYNCS) {
	  /* Sigh.. Throw everything away :-( */
	  oldcfp->id = ino;
	  cfp_free(oldcfp, NULL);
	  sfprintf(sfstdout, " ... too many Resync attempts this way, throwing  it away...\n");
	  return;
	}

	/* cfp_free()->unvertex()->unctlfile() will do reinsertion */
	/* dq_insert(NULL,ino,file,31); */

	/* Now read it back! */
	fd = eopen(file, O_RDWR, 0);
	if (fd < 0) {
	  /* ???? */
	  sfprintf(sfstdout," .. FILE OPEN FAILED!\n");

	  /* Delete it from memory */
	  cfp_free(oldcfp, NULL);
	  return;
	}


	newcfp = schedule(fd, file, ino, 1); /* rereading */

	if (newcfp != NULL) {
	  /* ????  What ever, it succeeds, or it fails, all will be well */

	  sync_cfps(oldcfp, newcfp, proc);
	  newcfp->id = 0; /* Don't scramble spt_mesh[] below */

	  spl = sp_lookup((u_long)ino, spt_mesh[L_CTLFILE]);
	  if (spl)
	    sp_delete(spl, spt_mesh[L_CTLFILE]);
	  oldcfp->id = ino;
	  sp_install(oldcfp->id, (void *)oldcfp, 0, spt_mesh[L_CTLFILE]);

	  /* Delete it from memory */
	  cfp_free0(newcfp);

	  if (oldcfp->head == NULL) {
	    cfp_free(oldcfp,spl);
	    if (verbose)
	      sfprintf(sfstdout," .. LOST in resync ?!\n");
	  } else
	    if (verbose)
	      sfprintf(sfstdout," .. resynced!\n");

	} else {

	  if (verbose)
	    sfprintf(sfstdout," .. NOT resynced!\n");

	  /* Sigh.. Throw everything away :-( */
	  oldcfp->id = ino;
	  cfp_free(oldcfp, NULL);
	}
}


/*
 * The schedule() function is in charge of reading the control file from
 * the scheduler directory, and creating all the appropriate links to the
 * control file.
 * Since it is convenient to do so here, it also goes through the list
 * of transport directives and schedules the appropriate things to be
 * done at the appropriate time in the future.
 */
static struct ctlfile *schedule(fd, file, ino, reread)
	int fd;
	const char *file;
	long ino;
	const int reread;
{
	struct ctlfile *cfp;
	struct vertex *vp;

	/* read and process the control file */
	cfp = vtxprep(slurp(fd, ino), file, reread);
	if (cfp == NULL) {
	  if (!vtxprep_skip) {	/* Unless skipped.. */
	    eunlink(file,"sch-sch-done");	/* everything here has been processed */
	    if (verbose)
	      sfprintf(sfstdout,"completed, unlink %s\n",file);
	    return NULL;
	  }
	  vtxprep_skip_any += vtxprep_skip;
	  return NULL;
	}

	++MIBMtaEntry->mtaStoredMessages;
	++global_wrkcnt;

	if (cfp->head == NULL) {
	  unctlfile(cfp, 0); /* Delete the file.
				(decrements those counters above!) */
	  return NULL;
	}

	if (!reread) {
	  sp_install(cfp->id, (void *)cfp, 0, spt_mesh[L_CTLFILE]);

	  for (vp = cfp->head; vp != NULL; vp = vp->next[L_CTLFILE]) {
	    /* Put into the schedules */
	    vtxdo(vp, cehead, file);
	  }
	}

	/* Now we have no more need for the contents in core */
	if (cfp->contents != NULL) {
	  free(cfp->contents);
	  cfp->contents = NULL;
	}

	return cfp;
}

/*
 * slurp() gets in the job-descriptor file, and does initial
 *         parsing on it.
 */

struct ctlfile *
slurp(fd, ino)
	int fd;
	long ino;
{
	register char *s;
	register int i;
	char *contents;
	int *offset, *ip, *lp;
	int offsetspace;
	struct stat stbuf;
	struct ctlfile *cfp;

	if (fd < 0)
	  return NULL;
	if (efstat(fd, &stbuf) < 0) {
	  close(fd);
	  return NULL;
	}
	if (!S_ISREG(stbuf.st_mode)) {
	  close(fd);
	  return NULL;	/* XX: give error */
	}
	contents = emalloc((int)stbuf.st_size + 1);
	if (eread(fd, contents, stbuf.st_size) != stbuf.st_size) { /* slurp */
	  close(fd);
	  free(contents); /* Failed to read ?!?! */
	  return NULL;
	}
	contents[stbuf.st_size] = 0;

	cfp = (struct ctlfile *)emalloc(sizeof(struct ctlfile));
	memset((void*)cfp, 0, sizeof(struct ctlfile));

	cfp->fd = fd;
	cfp->dirind = -1; /* Not known -- or top-level */
	cfp->uid = stbuf.st_uid;
	cfp->envctime = stbuf.st_ctime;
	cfp->contents = contents;
	/* 
	   cfp->vfpfn = NULL;
	   cfp->head = NULL;
	   cfp->mark = V_NONE;
	   cfp->haderror = 0;
	   cfp->mid      = NULL;
	   cfp->envid    = NULL;
	   cfp->logident = NULL;
	   cfp->erroraddr = NULL;
	   cfp->msgbodyoffset = 0;
	 */

	/* go through the file and mark it off */
	i = 0;
	offsetspace = 100;
	offset = (int*)emalloc(sizeof(int)*offsetspace);
	offset[i++] = 0L;
	for (s = contents; s - contents < stbuf.st_size; ++s) {
	  if (*s == '\n') {
	    *s++ = '\0';
	    if (s - contents < stbuf.st_size) {
	      if (i >= offsetspace-1) {
		offsetspace += 20;
		offset = (int*)erealloc(offset,sizeof(int)*offsetspace);
	      }
	      offset[i++] = s - contents;
	      if (*s == _CF_MSGHEADERS ||
		  *s == _CF_MIMESTRUCT) {
		/* find a \n\n combination */
		while (!(*s == '\n' && *(s+1) == '\n'))
		  if (s-contents < stbuf.st_size)
		    ++s;
		  else
		    break;
		if (s - contents >= stbuf.st_size) {
		  /* XX: header ran off file */
		}
	      } else if (*s == _CF_BODYOFFSET) {
		cfp->msgbodyoffset = atoi(s+2);
	      } else if (*s == _CF_DSNENVID) {
		/* cfp->envid = strsave(s+2); */
	      } else if (*s == _CF_DSNRETMODE) {
		/* cfp->dsnretmode = strsave(s+2); */
	      } else if (*s == _CF_MESSAGEID) {
		/* cfp->mid = strsave(s+2); */
	      } else if (*s == _CF_LOGIDENT) {
		/* cfp->logident = strsave(s+2); */
	      } else if (*s == _CF_ERRORADDR) {
		/* cfp->erroraddr = strsave(s+2); */
	      } else if (*s == _CF_TURNME) {
		/* Umm... it is a bit complex */
		/* sfprintf(sfstdout,"An ETRN request for target '%s'\n",s+2); */
	      }
	    }
	  }
	}
	cfp->nlines = i;
	/* closing fd must be done in vtxprep(), so we can unlock stuff easy */
	cfp = (struct ctlfile *)erealloc((void*)cfp,
					 (u_int) (sizeof(struct ctlfile) +
						  i * (sizeof offset[0])));
	lp = &(cfp->offset[0]);
	ip = &(offset[0]);
	/* copy over the offsets */
	while (--i >= 0)
	  *lp++ = *ip++;
	cfp->id = ino;
	/* cfp->mid = NULL; */
	free(offset);	/* release the block */
	return cfp;
}

struct offsort {
	int	offset;
	int	myidx;
	int	headeroffset;
	int	drptoffset;
	int	delayslot;
	int	notifyflg;
	char	*sender;
	/* char	*dsnrecipient; */
	time_t	wakeup;
};

/* ``bcfcn'' is used by the qsort comparison routine,
   bcp points to the control file bytes
 */

static char *bcp;

static int bcfcn __((const void *, const void *));
static int bcfcn(a, b)
     const void *a, *b;
{
	const struct offsort *aa = a, *bb = b;
	return strcmp(bcp + aa->offset, bcp + bb->offset);
}


static int
lockverify(cfp,cp,verbflg)	/* Return 1 when lock process does not exist */
	struct ctlfile *cfp;	/* Call only when the lock is marked active! */
	const char *cp;
	const int verbflg;
{
	char	lockbuf[1+_CFTAG_RCPTPIDSIZE];
	int	lockpid;
	int	sig = 0;

#if 0
# ifdef SIGCONT	/* OSF/1 acts differently if we use SIGNAL 0 :-( */
	sig = SIGCONT;
# endif
#endif

	++cp;
	if (!(*cp == ' ' ||
	      (*cp >= '0' && *cp <= '9'))) return 1; /* Old-style entry */
	memcpy(lockbuf,cp,_CFTAG_RCPTPIDSIZE);
	lockbuf[sizeof(lockbuf)-1] = 0;
	if (sscanf(lockbuf,"%d",&lockpid) != 1) return 1; /* Bad value ? */
	if (kill(lockpid,sig) != 0) return 1; /* PID does not exist, or
					       other error.. */
	if (verbflg)
	  sfprintf(sfstderr,"lockverify: Lock with PID=%d is active on %s:%s\n",
		   lockpid, cfp->mid, cp+_CFTAG_RCPTPIDSIZE);
	return 0;	/* Locking PID does exist.. */
}


/*
 *  The  vtxprep() does deeper analysis on jobs described at the file.
 *  It verifies possible locks (if they are still valid), and gathers
 *  all of the information regarding senders and recipients.
 *
 *  All "recipient"-lines are sorted to ease searching of vertices with
 *  identical channel, and host definitions.  If there are more than one
 *  recipient with given (channel, host)-tuple, all such recipients are
 *  wrapped into same vertex node with its respective ``recipient group''.
 *
 */
static struct ctlfile *vtxprep(cfp, file, rereading)
	struct ctlfile *cfp;
	const char *file;
	const int rereading;
{
	register int i, opcnt;
	register int *lp;
	int svn;
	int c_echannel, c_ehost, c_l_echannel, c_l_ehost;
	char *cp, *channel, *host, *l_channel, *l_host;
	char *echannel, *ehost, *l_echannel, *l_ehost, mfpath[100], flagstr[2];
	char *latest_sender = NULL;
	char *senderchannel = NULL;
	struct vertex *vp, *pvp, **pvpp, *head;
	struct stat stbuf;
	struct offsort *offarr;
	int offspc, mypid;
	int prevrcpt = -1;
	int is_turnme = 0;
	time_t wakeuptime;
	long format = 0;

	char fpath[128], path[128], path2[128];

	if (cfp == NULL)
	  return NULL;

	mytime(&now);

	strcpy(fpath, file);

	channel = host = NULL;

	/* copy offsets into local array */
	offspc = 16;
	offarr = (struct offsort *)emalloc(offspc * sizeof(struct offsort));

	mypid = getpid();
	opcnt = 0;
	svn = 0;
	vtxprep_skip = 0;
	lp = &cfp->offset[0];
	for (i = 0; i < cfp->nlines; ++i, ++lp) {
	  cp = cfp->contents + *lp + 1;
	  wakeuptime = 0;
	  if (*cp == _CFTAG_LOCK) {
	    /*
	     * This can happen when we restart the scheduler, and
	     * some previous transporter is still running.
	     * (and DEFINITELY during resync! when we simply ignore locks)
	     */
	    if (!lockverify(cfp, cp, !rereading)) {
#if 0
	      long ino = 0;
	      /*
	       * IMO we are better off by forgetting for a while that
	       * this spool-file exists at all.  Thus very least we
	       * won't errorneously delete it.
	       */
	      close(cfp->fd);	/* Was opened on  schedule() */
	      if (cfp->vfpfn != NULL) {
		Sfio_t *vfp = vfp_open(cfp);
		if (vfp) {
		  sfprintf(vfp,
			   "scheduler: Skipped a job-file because it is held locked by PID=%6.6s\n",cp+1);
		  sfclose(vfp);
		}
	      }
	      cfp_free(cfp, NULL);
	      ++vtxprep_skip;
	      ++vtxprep_skip_lock;
	      free(offarr);

	      /* XXX: Should we  dq_insert()  this back in ?
		      Or do we let the occasional recursive
		      scanner to check things deeply ? */
	      cp = strrchr(file,'/');
	      if (cp) ino = atol(cp+1); else ino = atol(file);
	      dq_insert(NULL, ino, file, 32);

	      return NULL;
#else
	      /* We can't simply forget this, we must do something
		 smarter -- We use approach of marking the vertex
		 non-startable until one hour from now. */
	      wakeuptime = now + 3600; /* 1 hour */
#endif
	    } else {
	      if (*cp != _CFTAG_NORMAL) {
		*cp = _CFTAG_NORMAL; /* unlock it */
		lockaddr(cfp->fd, NULL, (long) (cp - cfp->contents),
			 _CFTAG_LOCK, _CFTAG_NORMAL, cfp->mid,
			 cp+_CFTAG_RCPTPIDSIZE, mypid);
	      }
	    }
	  }
	  /* Calculate summary info */
	  if (cp[-1] == _CF_RECIPIENT) {
	    ++cfp->rcpnts_total;
	    if (*cp == _CFTAG_NOTOK) {
#if 0
	      ++cfp->rcpnts_failed;
	      ++MIBMtaEntry->mtaReceivedRecipientsSc,
	      ++MIBMtaEntry->mtaTransmittedRecipientsSc;
#endif
	      prevrcpt = -1;
	    } else if (*cp != _CFTAG_OK) {
	      ++cfp->rcpnts_work;
	    } else { /* _CFTAG_OK */
#if 0
	      ++MIBMtaEntry->mtaReceivedRecipientsSc,
	      ++MIBMtaEntry->mtaTransmittedRecipientsSc;
#endif
	    }
	  }
	  if (*cp == _CFTAG_NORMAL ||
	      (rereading && *cp == _CFTAG_LOCK) ||
	      *cp == '\n' /* This appears for msg-header entries.. */ ) {
	    ++cp;
	    switch (cp[-2]) {
	    case _CF_FORMAT:
	      sscanf(cp,"%li",&format);
	      if (format & (~_CF_FORMAT_KNOWN_SET)) {

		sfprintf(sfstderr,"%s: ** FILE: '%s' has unknown/unsupported format set: 0x%08lx !\n",
			 progname, file, format);

		cfp_free(cfp, NULL);
		free(offarr);
		return NULL;
	      }
	      cfp->format = format;
	      break;
	    case _CF_SENDER:
	      while (*cp == ' ') ++cp;
	      senderchannel = cp;
	      while (*cp != 0 && *cp != ' ') ++cp; 
	      if (*cp == ' ') *cp++ = 0;
	      while (*cp == ' ') ++cp;
	      /* Scan over the sender 'host' */
	      cp = skip821address(cp);
	      while (*cp == ' ') ++cp;
	      /* Scan over the sender 'user' */
	      latest_sender = cp;
	      cp = skip821address(cp);
	      *cp = 0;
	      if (cfp->erroraddr)  free(cfp->erroraddr);
	      cfp->erroraddr = strsave(latest_sender);
	      if (strcmp(senderchannel,"error")==0) {
		cfp->iserrmesg = 1;
		cfp->erroraddr[0] = 0; /* Make it '<>' */
	      } break;
	    case _CF_RECIPIENT:
	      if (opcnt >= offspc-1) {
		offspc *= 2;
		offarr = (struct offsort *)erealloc(offarr,
						    sizeof(struct offsort) *
						    offspc);
	      }
	      offarr[opcnt].offset = *lp + 2;
	      strlower(cp);
	      if ((format & _CF_FORMAT_TA_PID) || *cp == ' ' ||
		  (*cp >= '0' && *cp <= '9')) {
		/* New PID locking scheme.. */
		offarr[opcnt].offset += _CFTAG_RCPTPIDSIZE;
		cp += _CFTAG_RCPTPIDSIZE;
	      }
	      if ((format & _CF_FORMAT_DELAY1) || *cp == ' ' ||
		  (*cp >= '0' && *cp <= '9')) {
		/* Newer DELAY data slot - _CFTAG_RCPTDELAYSIZE bytes */
		offarr[opcnt].delayslot = offarr[opcnt].offset;
		offarr[opcnt].offset += _CFTAG_RCPTDELAYSIZE;
		cp += _CFTAG_RCPTDELAYSIZE;
	      } else
		offarr[opcnt].delayslot = 0;
	      offarr[opcnt].wakeup = wakeuptime;
	      offarr[opcnt].myidx = i;
	      offarr[opcnt].headeroffset = -1;
	      offarr[opcnt].drptoffset = -1;
	      offarr[opcnt].sender = latest_sender;
	      offarr[opcnt].notifyflg = NOT_FAILURE;
	      prevrcpt = opcnt;
	      ++opcnt;

	      /* Account for all yet to be delivered recipients */
	      ++MIBMtaEntry->mtaStoredRecipients;
	      ++MIBMtaEntry->mtaReceivedRecipientsSc;

	      break;
	    case _CF_RCPTNOTARY:
	      /* IETF-NOTARY-DRPT+NOTIFY DATA! */
	      if (prevrcpt >= 0) {
		offarr[prevrcpt].drptoffset = *lp + 2;
		/* Lets parse the input, we want NOTIFY= flags */
		while (*cp != 0) {
		  while (*cp == ' ' || *cp == '\t') ++cp;
		  if (CISTREQN("NOTIFY=",cp,7)) {
		    offarr[prevrcpt].notifyflg = 0;
		    cp += 7;
		    while (*cp) {
		      if (CISTREQN(cp,"NEVER",5)) {
			cp += 5;
			offarr[prevrcpt].notifyflg |= NOT_NEVER;
		      } else if (CISTREQN(cp,"DELAY",5)) {
			cp += 5;
			offarr[prevrcpt].notifyflg |= NOT_DELAY;
		      } else if (CISTREQN(cp,"FAILURE",7)) {
			cp += 7;
			offarr[prevrcpt].notifyflg |= NOT_FAILURE;
		      } else if (CISTREQN(cp,"SUCCESS",7)) {
			cp += 7;
			offarr[prevrcpt].notifyflg |= NOT_SUCCESS;
		      } else if (CISTREQN(cp,"TRACE",  5)) {
			cp += 5;
			offarr[prevrcpt].notifyflg |= NOT_TRACE;
		      } else {
			break; /* Burp ?? */
		      }
		      if (*cp == ',') ++cp;
		    }
		  } else if (CISTREQN("BY=",cp,7)) {
		    /* FIXME: Parse the BY= parameter! */
		    while (*cp && *cp != ' ' && *cp != '\t') ++cp;
		  } else {
		    while (*cp && *cp != ' ' && *cp != '\t') ++cp;
		  }
		}
	      }
	      prevrcpt = -1; /* Add ONCE! */
	      break;
	    case _CF_MSGHEADERS:
	      for (/* we count up.. */; svn < opcnt; ++svn)
		offarr[svn].headeroffset = *lp + 2;
	      break;
	    case _CF_DSNRETMODE:
	      if (cfp->dsnretmode) free(cfp->dsnretmode);
	      cfp->dsnretmode = strsave(cp);
	      break;
	    case _CF_DSNENVID:
	      if (cfp->envid) free(cfp->envid); /* shouldn't happen.. */
	      cfp->envid = strsave(cp);
	      break;
	    case _CF_DIAGNOSTIC:
	      cfp->haderror = 1;
	      break;
	    case _CF_MESSAGEID:
	      if (cfp->mid != NULL) free(cfp->mid); /* shouldn't happen.. */
	      cfp->mid = strsave(cp);
	      break;
	    case _CF_BODYOFFSET:
	      cfp->msgbodyoffset = atoi(cp);
	      break;
	    case _CF_LOGIDENT:
	      if (cfp->logident) free(cfp->logident); /* shouldn't happen..*/
	      cfp->logident = strsave(cp);
	      break;
	    case _CF_ERRORADDR:
	      if (cfp->erroraddr) free(cfp->erroraddr); /* could happen */
	      cfp->erroraddr = strsave(cp);
	      break;
	    case _CF_OBSOLETES:
	      deletemsg(cp, cfp);
	      break;
	    case _CF_VERBOSE:
	      cfp->vfpfn = strsave(cp);
	      break;
	    case _CF_TURNME:
	      sfprintf(sfstdout,"%s ETRN: %s\n", timestring(), cp);
	      strlower(cp);
	      turnme(cp);
	      is_turnme = 1;
	      break;
	    }
	  }
	}
	close(cfp->fd);	/* closes the fd opened in schedule() */

	if (fpath[0] >= 'A') {
	  /* Prefixed with a subdir path */
	  int hash = 0;
	  char *s = fpath;

	  while (*s >= 'A' && *s <= 'Z') {
	    hash <<= 8;
	    hash |= (*s) & 0xff;
	    ++s;
	    if (*s != '/') break;
	    ++s;
	  }
	  cfp->dirind = hash;

	} else { /* Not at subdirs */

	  if (cfp->mid && hashlevels > 0) {
	    /* We have a desire to use subdirs, now the magic of hashing
	       into subdirs...  inode number ? */

	    int hash;

	    if (hashlevels > 1) {
	      hash = atol(cfp->mid) % (26*26);
	      hash = (('A' + hash / 26) << 8) | ('A' + hash % 26);
	    } else {
	      hash = (atol(cfp->mid) % 26) + 'A';
	    }
	    cfp->dirind = hash;
	    /* Ok, we have the hash values, now move the file
	       to match with our hashes.. */
	    sprintf(path, "%s/%s", cfpdirname(hash), fpath);
	    if (rename(fpath, path) != 0) {
	      /* Failed, why ? */
	      if (errno != ENOENT) {
		/* For any other than 'no such (target) directory' */
		cfp->dirind = -1;
	      } else {
		cfp_mksubdirs("",cfpdirname(hash));
		if (rename(fpath, path) != 0)
		  cfp->dirind = -1; /* Failed for any reason */
		else
		  strcpy(fpath, path);
	      }
	    } else
		strcpy(fpath, path);

	    if (cfp->dirind >= 0) {
	      /* Successfully renamed the transport file to a subdir,
		 now do the same to the queue directory! */
	      sprintf(path,  "../%s/%s", QUEUEDIR, cfp->mid);
	      sprintf(path2, "../%s/%s/%s",
		      QUEUEDIR, cfpdirname(cfp->dirind), cfp->mid);

	      if (rename(path,path2) != 0) {
		if (errno == ENOENT) {
		  /* No dirs ?? */
		  cfp_mksubdirs(QUEUEDIR,cfpdirname(hash));
		  rename(path, path2);
		}
	      }
	      /* If failed, it will be reported below */
	    }
	  }
	}


	if (cfp->mid != NULL) {
	  if (cfp->dirind >= 0)
	    sprintf(mfpath, "../%s/%s/%s",
		    QUEUEDIR, cfpdirname(cfp->dirind), cfp->mid);
	  else
	    sprintf(mfpath, "../%s/%s", QUEUEDIR, cfp->mid);
	}
	if (cfp->mid == NULL || cfp->logident == NULL ||
	    estat(mfpath, &stbuf) < 0) {
	  if (!is_turnme) {
	    Sfio_t *vfp = vfp_open(cfp);
	    if (vfp) {
	      sfprintf(vfp, "aborted due to missing information\n");
	      sfclose(vfp);
	    }
	  }
	  cfp_free(cfp, NULL);
	  free(offarr);
	  return NULL;
	}
	cfp->mtime = stbuf.st_mtime; /* instead of ctime, we use mtime
					at the queue-dir accesses, this
					way we can move the spool to
					another machine, and run things
					in there, and still have same
					expiration times.. */
	cfp->fd = -1;
	/* sort it to get channels and channel/hosts together */
	bcp = cfp->contents;
	if (opcnt > 1)
	  qsort((char *)offarr, opcnt, sizeof (struct offsort), bcfcn);
	/*
	 * Loop through them; whenever either channel or host changes,
	 * make a new vertex. All such vertices must be linked together.
	 */
	strcpy(flagstr," ");
	l_channel = l_echannel = l_host = l_ehost = flagstr;
	c_echannel = c_ehost = c_l_echannel = c_l_ehost = 0;
	svn = 0;
	pvp = NULL;
	head = NULL;
	pvpp = &head;
	for (i = 0; i < opcnt; ++i) {
	  channel = bcp + offarr[i].offset /* - 2 */;
	  while (*channel == ' ') ++channel; /* Skip possible space(s) */
	  host = echannel = skip821address(channel);
	  c_l_echannel = *host; if (c_l_echannel) *host++ = '\0';
	  while (*host == ' ') ++host; /* Skip space(s) */
#if 1
	  /* [mea]   channel ((mx.target)(mx.target mx.target)) rest.. */
	  cp = host;
	  if (*cp == '(') {
	    while(*cp == '(')
	      ++cp;
	    while(*cp && *cp != ' ' && *cp != '\t' && *cp != ')')
	      ++cp;
	    if (*cp)
	      ehost = cp;
	    else
	      continue;		/* error! */
	    /* Ok, found ehost, now parsing past parenthesis.. */
	    cp = host;
	    while(*host == '(')  ++host;
	    if (*cp == '(') {
	      ++cp;
	      while(*cp == '(') {
		/* Find ending ')', and skip it */
		while(*cp && *cp != ')') ++cp;
		if (*cp == ')') ++cp;
	      }
	      /* Ok, scanned past all inner parenthesis, now ASSUME
		 next one is ending outer parenthesis, and skip it */
	      ++cp;
	    }
	    if (*cp != ' ' && *cp != '\t')
	      continue;		/* Not proper separator.. error! */
	  } else
#endif
	    {
	      ehost = skip821address(host);
	      strlower(host);
	      if (ehost == NULL || ehost == host) /* error! */
		continue;
	    }

	  c_ehost = *ehost; *ehost = '\0';
	  /* compare with the last ones */
	  if (strcmp(channel, l_channel) || strcmp(host, l_host)) {
	    /* wrap and tie the old vertex node */
	    if (i != svn) {
	      u_int alloc_size = (u_int) (sizeof (struct vertex) +
					  (i - svn - 1) * sizeof (int));
	      vp = (struct vertex *)emalloc(alloc_size);
	      memset((char*)vp, 0, alloc_size);
	      vp->cfp             = cfp;
	      vp->next[L_CTLFILE] = NULL;
	      vp->prev[L_CTLFILE] = pvp;
#if 0
	      vp->thread          = NULL;
	      vp->web[L_CTLFILE]  = NULL;
	      vp->message         = NULL;
	      vp->retryindex      = 0;
	      vp->nextitem        = NULL;
	      vp->previtem        = NULL;
	      vp->proc            = NULL;
	      vp->attempts        = 0;
	      vp->notary          = NULL;
#endif
	      vp->ngroup       = i - svn;
	      /* vp->sender       = strsave(offarr[svn].sender); */
	      vp->wakeup       = offarr[svn].wakeup;
	      vp->headeroffset = offarr[svn].headeroffset; /*They are similar*/
	      vp->drptoffset   = offarr[svn].drptoffset;
	      vp->notaryflg    = offarr[svn].notifyflg;
	      while (svn < i) {
		vp->index[i-svn-1] = offarr[svn].myidx;
		++svn;
	      }
	      *pvpp = vp;
	      pvpp = &vp->next[L_CTLFILE];
	      pvp = vp;
	      link_in(L_HOST,    vp, l_host);
	      link_in(L_CHANNEL, vp, l_channel);
	    }
	    /* create a new vertex node */
	    svn = i;
	  }
	  /* stick the current 'r'ecipient  line into the current vertex */
	  /* restore the characters */
	  *l_echannel  = c_l_echannel;
	  *l_ehost     = c_l_ehost;
	  l_echannel   = echannel;
	  l_ehost      = ehost;
	  c_l_echannel = c_echannel;
	  c_l_ehost    = c_ehost;
	  l_channel    = channel;
	  l_host       = host;
	} /* for( .. i < opcnt .. ) */

	/* wrap and tie the old vertex node (this is a copy of code above) */
	if (i != svn) {
	  u_int alloc_size = (u_int) (sizeof (struct vertex) +
				      (i - svn - 1) * sizeof (int));
	  vp = (struct vertex *)emalloc(alloc_size);
	  memset((void*)vp, 0, alloc_size);
	  vp->cfp = cfp;
	  vp->next[L_CTLFILE] = NULL;
	  vp->prev[L_CTLFILE] = pvp;
#if 0
	  vp->message = NULL;
	  vp->retryindex = 0;
	  vp->nextitem = NULL;
	  vp->previtem = NULL;
	  vp->proc = NULL;
	  vp->attempts     = 0;
	  vp->notary       = NULL;
#endif
	  vp->ngroup = i - svn;
	  /* vp->sender = strsave(offarr[snv].sender); */
	  vp->wakeup       = offarr[svn].wakeup;
	  vp->headeroffset = offarr[svn].headeroffset; /* Just any of them will do */
	  vp->drptoffset = offarr[svn].drptoffset;
	  vp->notaryflg  = offarr[svn].notifyflg;
	  while (svn < i) {
	    vp->index[i-svn-1] = offarr[svn].myidx;
	    ++svn;
	  }
	  *pvpp = vp;
	  pvpp = &vp->next[L_CTLFILE];
	  pvp = vp;
	  link_in(L_HOST, vp, host);
	  link_in(L_CHANNEL, vp, channel);
	}

	*l_echannel = c_l_echannel;
	*l_ehost    = c_l_ehost;

	/*
	   for (vp = head; vp != NULL; vp = vp->next[L_CTLFILE]) {
	     sfprintf(sfstdout,"--\n");
	     for (i = 0; i < vp->ngroup; ++i)
	       sfprintf(sfstdout,"\t%s\n", cfp->contents+cfp->offset[vp->index[i]]);
	   }
	*/

	cfp->head = head;
	free(offarr);
	if (verbose) {
	  int completed = cfp->rcpnts_total - cfp->rcpnts_work -
			  cfp->rcpnts_failed;
	  sfprintf(sfstdout,"vtxprep: msg %s rcptns total %d work %d failed %d done %d\n  vertices:",
		 cfp->mid, cfp->rcpnts_total, cfp->rcpnts_work,
		 cfp->rcpnts_failed, completed );
	  vp = cfp->head;
	  for (vp = cfp->head; vp; vp = vp->next[L_CTLFILE]) {
	    sfprintf(sfstdout," %p", vp);
	  }
	  sfprintf(sfstdout,"\n");
	}

	{
	  Sfio_t *vfp = vfp_open(cfp);
	  if (vfp != NULL && cfp->mid != NULL)
	    sfprintf(vfp, "scheduler processing %s\n", cfp->mid);
	  if (vfp) sfclose(vfp);
	}

	return cfp;
}

/*
 *  The  vtxmatch()  is a subroutine to  vtxdo()  matching for
 *  scheduler definition entries from the scheduler configuration table.
 *
 */

static int vtxmatch(vp, tp)
	struct vertex *vp;
	struct config_entry *tp;
{
	/* if the channel doesn't match, there's no hope! */
	if (verbose>1)
	  sfprintf(sfstdout,"ch? %s %s\n", vp->orig[L_CHANNEL]->name, tp->channel);
	if (tp->channel[0] == '*' && tp->channel[1] == '\0')
	  return 0; /* Never match the defaults entry! */
	if (!globmatch(tp->channel, vp->orig[L_CHANNEL]->name))
	  return 0;

	if (!(tp->host == NULL || tp->host[0] == '\0' ||
	      (tp->host[0] == '*' && tp->host[1] == '\0'))) {
	  if (!globmatch(tp->host, vp->orig[L_HOST]->name))
	    return 0;
	}

	if (verbose>1)
	  sfprintf(sfstdout,"host %s %s\n", vp->orig[L_HOST]->name, tp->host);

	return 1;
}

static void ce_fillin __((struct threadgroup *, struct config_entry *));
static void ce_fillin(thg,cep)
	struct threadgroup *thg;
	struct config_entry *cep;
{
	struct config_entry *ce = &(thg->ce);

	defaultconfigentry( ce,cep );

	if (cep->interval != -1) ce->interval = cep->interval;
	if (cep->idlemax  != -1) ce->idlemax  = cep->idlemax;
	if (cep->expiry   != -1) ce->expiry   = cep->expiry;
	ce->expiryform     = cep->expiryform;
	if (cep->uid      != -1) ce->uid = cep->uid;
	if (cep->gid      != -1) ce->gid = cep->gid;
	if (cep->maxkids  != -1) ce->maxkids = cep->maxkids;
	if (cep->maxkidChannel != -1) ce->maxkidChannel = cep->maxkidChannel;
	if (cep->maxkidThreads != -1) ce->maxkidThreads = cep->maxkidThreads;
	if (cep->nretries > 0) {
	  ce->nretries = cep->nretries;
	  ce->retries  = cep->retries;
	}
	if (cep->command != NULL) {
	  ce->command = cep->command;
	  ce->argv    = cep->argv;
	}
	ce->flags |= cep->flags; /* XX: Grumble.. additive only.. */
	ce->host   = cep->host;
	if (cep->skew > 0) ce->skew = cep->skew;

	if (ce->interval == -1)
	  ce->interval = 3600;
	if (ce->idlemax == -1)
	  ce->idlemax = ce->interval * 3;
	if (ce->maxkids == -1)
	  ce->maxkids = global_maxkids;
	if (ce->maxkidChannel == -1)
	  ce->maxkidChannel = global_maxkids;
	if (ce->maxkidThreads == -1)
	  ce->maxkidThreads = global_maxkids;
}


/*
 *  The  vtxdo()  tries thru all scheduler configuration entries
 *  looking for a matching one which to fill in for the input vertex.
 *
 *  In the end it calls  reschedule()  to place the vertex into scheduling
 *  queues (threads)
 *
 */

static void vtxdo(vp, cehdr, path)
	struct vertex *vp;
	struct config_entry *cehdr;
	const char *path;
{
	struct config_entry *tp;
	int n;
	int cnt = 0;

	/*
	 * go through scheduler control file entries and
	 * fill in the blanks in the vertex specification
	 */
	n = 0;
	for (tp = cehdr; tp != NULL; tp = tp->next) {
	  ++cnt;
	  if (vtxmatch(vp, tp)) {
	    /* tp points to the selected config entry */
	    n = 1;
	    break;
	  }
	}
	if (n == 0) {
	  sfprintf(sfstderr, "%s: no pattern matched %s/%s address\n",
		   progname, vp->orig[L_CHANNEL]->name,vp->orig[L_HOST]->name);
	  /* XX: memory leak here? */
	  return;
	}
	if (verbose)
	  sfprintf(sfstdout, "Matched %dth config entry with: %s/%s\n", cnt,
		   vp->orig[L_CHANNEL]->name, vp->orig[L_HOST]->name);

	/* set default values */
	if (tp->expiry > 0)
	  vp->ce_expiry = tp->expiry + vp->cfp->mtime;
	else
	  vp->ce_expiry = 0;

	if (tp->reporttimes[0])
	  vp->nextrprttime = now + tp->reporttimes[0];
	else
	  vp->nextrprttime = now + global_report_interval;

	thread_linkin(vp,tp,cnt,ce_fillin);

	if (verbose>1)
	  vtxprint(vp);
}


int vtxredo(spl)
        struct spblk *spl;
{
        struct ctlfile *cfp = (struct ctlfile *)spl->data;
	struct vertex *vp;

        /* assert cfp != NULL */
	for (vp = cfp->head ; vp != NULL ; vp = vp->next[L_CTLFILE]) {
	  vtxdo(vp, rrcf_head, NULL);
	}
        return 0;
}


/* Shell-GLOB-style matching */
static int globmatch(pattern, string)
	register const char	*pattern;
	register const char	*string;
{
	while (1) {
	  switch (*pattern) {
	  case '{':
	    {
	      const char *p = pattern+1;
	      const char *s = string;

	      /* This matches at the END of the pattern:  '*.{fii,foo,faa}' */

	      for ( ; *p != 0 && *p != '}'; ++p) {
		if (*p == ',') {
		  if (*s == '\0')
		    return 1; /* We have MATCH! */
		  s = string;
		  continue;
		}
		if (*s != *p) {
		  /* Not the same .. */
		  s = string;
		  /* Ok, perhaps next pattern segment ? */
		  while (*p != '\0' && *p != '}' && *p != ',')
		    ++p;
		  if (*p != ',')
		    return 0; /* No next pattern ?
				 We definitely have no match! */
		  continue;
		}
		if (*s != 0)
		  ++s;
	      }
	      if (*p == '\0' || *p == '}')
		if (*s == 0)
		  return 1;
	      return 0;

	    }
	    break;
	  case '*':
	    ++pattern;
	    if (*pattern == 0) {
	      /* pattern ended with '*', we can accept any string trail.. */
	      return 1;
	    }
	    /* We do 'common case' optimization here, but will loose some
	       performance, if somebody gives '*foo*' as a pattern.. */
	    {
	      const char *p = pattern;
	      int i = 0, c;
	      while ((c = *p++) != 0) {
		/* Scan for special chars in pattern.. */
		if (c == '*' || c == '[' || c == '{' || c == '\\' || c == '?') {
		  i = 1; /* Found! */
		  break;
		}
	      }
	      if (!i) { /* No specials, match from end of string */
		int len = strlen(string);
		i = strlen(pattern);
		if (i > len) return 0; /* Tough.. pattern longer than string */
		if (memcmp(string + len - i, pattern, i) == 0)
		  return 1; /* MATCH! */
	      }
	    }
	    do {
	      if (globmatch(pattern, string))
		return 1;
	    } while (*string++ != '\0');
	    return 0;
	  case '\\':
	    ++pattern;
	    if (*pattern == 0 ||
		*pattern != *string)
	      return 0;
	    break;
	  case '[':
	    if (*string == '\0')
	      return 0;
	    if (*(pattern+1) == '^') {
	      ++pattern;
	      while ((*++pattern != ']')
		     && (*pattern != *string))
		if (*pattern == '\0')
		  return 0;
	      if (*pattern != ']')
		return 0;
	      string++;
	      break;
	    }
	    while ((*++pattern != ']') && (*pattern != *string))
	      if (*pattern == '\0')
		return 0;
	    if (*pattern == ']')
	      return 0;
	    while (*pattern++ != ']')
	      if (*pattern == '\0')
		return 0;
	    string++;
	    break;
	  case '?':
	    ++pattern;
	    if (*string++ == '\0')
	      return 0;
	    break;
	  case '\0':
	    return (*string == '\0');
	  default:
	    if (*pattern++ != *string++)
	      return 0;
	  }
	}
}

/*
 * This routine links a group of addresses (described by what vp points at)
 * into the Tholian Web (err, our matrix). The flag (either L_HOST or
 * L_CHANNEL) selects a namespace of strings pointed at by s. It just
 * happens we need 2 (host and channel names), and we don't care what
 * they are as long as they are in separate spaces.
 */
static void link_in(flag, vp, s)
	int flag;
	struct vertex *vp;
	const char *s;
{
	struct web *wp = web_findcreate(flag,s);

	wp->linkcnt += 1;

	vp->next[flag] = NULL;
	vp->prev[flag] = wp->lastlink;
	vp->orig[flag] = wp;
	if (wp->lastlink != NULL)
	  wp->lastlink->next[flag] = vp;
	wp->lastlink = vp;
	if (wp->link == NULL)
	  wp->link = vp;
}

/*
 * time-string to be prepended to logged messages
 */
char *
timestring()
{
	static char timebuf[40];
	struct tm *tp;

	mytime(&now);
	tp = localtime(&now);
	sprintf(timebuf,"%d%02d%02d%02d%02d%02d",
		tp->tm_year+1900, tp->tm_mon+1, tp->tm_mday,
		tp->tm_hour, tp->tm_min, tp->tm_sec);
	return timebuf;
}

static int running_on_alarm;
static time_t alarm_time;

static RETSIGTYPE sig_alarm(sig)
int sig;
{
	time(&alarm_time);
	SIGNAL_HANDLE(SIGALRM, sig_alarm);
	alarm(1);
}


#if defined(HAVE_MMAP)
struct timeserver {
	int	pid;
#ifdef HAVE_SELECT
	struct timeval tv;
#else
	time_t	time_sec;
#endif
#define MAPSIZE 16*1024 /* Should work at all systems ? */
};
struct timeserver *timeserver_segment = NULL;
static void init_timeserver()
{
	int ppid;

#if !defined(MAP_ANONYMOUS) || defined(__linux__)
	/* must have a file ? (SunOS 4.1, et.al.) */
	int fd = -1;
	char blk[1024];
	int i;
	Sfio_t *fp = sftmp(0); /* Create the backing file fairly reliably. */

	if (fp)
	  fd = sffileno(fp);
	if (fd < 0) {
	  perror("init_timeserver() didn't create tempfile ??");
	  return; /* Brr! */ 
	}

	memset(blk,0,sizeof(blk));
	for (i=0; i < MAPSIZE; i += sizeof(blk))
	  sfwrite(fp, blk, sizeof(blk));
	sfsync(fp);
	sfseek(fp, 0, 0);

#ifndef MAP_FILE
# define MAP_FILE 0 /* SunOS 4.1 does not have this */
#endif
	timeserver_segment = (void*)mmap(NULL, MAPSIZE, PROT_READ|PROT_WRITE,
					 MAP_FILE|MAP_SHARED, fd, 0);
	sfclose(fp);
	
#else
#ifndef MAP_VARIABLE
# define MAP_VARIABLE 0 /* Some system have MAP_ANONYMOUS, but
			   no MAP_VARIABLE.. */
#endif
	/* This MAP_ANONYMOUS does work at DEC OSF/1 ... */
	timeserver_segment = (void*)mmap(NULL, MAPSIZE, PROT_READ|PROT_WRITE,
					 MAP_VARIABLE|MAP_ANONYMOUS|MAP_SHARED,
					 -1, 0);
#endif
	if (-1L == (long)timeserver_segment
	    || timeserver_segment == NULL) {
	  perror("mmap() of timeserver segment gave");
	  timeserver_segment = NULL;
	  return; /* Brr.. */
	}

	ppid = fork();
	if (ppid > 0) {
	  time_t now2;
	  timeserver_pid = ppid;
	  timeserver_segment->pid = ppid;

	  time(&now);
	  sleep(3);

#ifdef HAVE_SELECT
	  now2 = timeserver_segment->tv.tv_sec;
#else
	  now2 = timeserver_segment->time_sec;
#endif
	  if (now2 == 0 || now2 == now) {
	    /* HUH ?! No incrementation in 3 seconds ?? */
	    /* Start ticking in alarm() mode! */
	    kill (ppid, SIGTERM);
	    timeserver_pid = 0;
	    timeserver_segment = NULL;
	    alarm(1);
	  }

	  return;
	}
	if (ppid < 0) return; /* Error ?? brr.. */

	ArgvSave[1] = NULL;
	strcpy((char*)ArgvSave[0],"TimeServer");

	ppid = getppid(); /* who is our parent ? */

#ifdef HAVE_SELECT
	gettimeofday(&timeserver_segment->tv, NULL);
#else
	time(&timeserver_segment->time_sec);
#endif

	for(;;) {
#ifdef HAVE_SELECT
	  struct timeval tv;
	  int rc;

	  tv.tv_sec = 0;
	  tv.tv_usec = 300000;

	  gettimeofday(&timeserver_segment->tv, NULL);

	  rc = select(0,NULL,NULL,NULL,&tv);
#else
	  time(&timeserver_segment->time_sec);
	  sleep(1);
#endif
	  /* Is the parent still alive ?? */
	  if (kill(ppid, 0) != 0)
	    break; /* No ?? Out! */
	}
	_exit(0);
}
#else
static void init_timeserver()
{
  /* Do nothing.. */
}

#endif

time_t mytime(timep)
time_t *timep;
{
#if defined(HAVE_MMAP)
	if (timeserver_pid) {
	  time_t t;
#ifdef HAVE_SELECT
	  t = timeserver_segment->tv.tv_sec;
#else
	  t = timeserver_segment->time_sec;
#endif
	  if (timep != NULL)
	    *timep = t;
	  return t;
	}
#endif
	if (running_on_alarm) {
	  if (timep)
	    *timep = alarm_time;
	  return alarm_time;
	}
#ifdef HAVE_GETTIMEOFDAY
	{
	  struct timeval tv;
	  gettimeofday(&tv,NULL);
	  if (timep)
	    *timep = tv.tv_sec;
	  return tv.tv_sec;
	}
#else
	return time(timep); /* The classical old version.. */
#endif
}

const char *
cfpdirname(hash)
int hash;
{
	static char dirbuf[8];

	if (hash < 0)
	  return ".";
	if (hash < 256) {
	  sprintf(dirbuf, "%c", hash);
	} else {
	  sprintf(dirbuf, "%c/%c", (hash >> 8) & 0xff, hash & 0xff);
	}
	return dirbuf;
}


/* We make one, or at most two subdirs */

void
cfp_mksubdirs(topdir,newpath)
const char *topdir, *newpath;
{
	char path[256];
	int omask = umask(022);

	if (*topdir != 0)
	  sprintf(path, "../%s/%s", topdir, newpath);
	else
	  strcpy(path, newpath);

	if (mkdir(path,0755) != 0) {
	  char *s = strrchr(path,'/');
	  if (s) *s = 0;
	  mkdir(path,0755);
	  if (s) *s = '/';
	  mkdir(path,0755);
	}
	umask(omask);
}