~hww3/caudium

ref: 478ede2aed39dc8d4514b860c9f732a1f095db52 caudium/server/base_server/configuration.pike -rw-r--r-- 109.6 KiB
478ede2aWilliam Welliver beginning of support for SNI virtual hosting 1 year, 22 days ago
                                                                                
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
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
/*
 * Caudium - An extensible World Wide Web server
 * Copyright � 2000-2005 The Caudium Group
 * Copyright � 1994-2001 Roxen Internet Software
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
/*
 * $Id$
 */

constant cvs_version = "$Id$";
#include <module.h>
#include <caudium.h>
#ifdef PROFILE
mapping profile_map = ([]);
#endif

#define CATCH(X)  do { mixed err; if(err = catch{X;}) report_error(describe_backtrace(err)); } while(0)


#ifdef REQUEST_DEBUG
# define REQUEST_WERR(X) report_debug("CONFIG: "+X+"\n")
#else
# define REQUEST_WERR(X)
#endif

/* A configuration.. */

inherit Configuration;

inherit "caudiumlib14";

public string real_file(string file, object id);


function store = caudium->store;
function retrieve = caudium->retrieve;
function remove = caudium->remove;
function do_dest = caudium->do_dest;
function create_listen_socket = caudium->create_listen_socket;

object logger = Logging.Logger();

#if constant(_Protocols_DNS_SD.Service)
//! an object for service announcements using Bonjour (aka Zeroconf)
Protocols.DNS_SD.Service bonjour;
#endif

//! the parser module for this configuration
object   parse_module;

//! the content-types module for this configuration
object   types_module;

//! the master authentication module for this configuration 
object   auth_module;

//! the directory listing module for this configuration
object   dir_module;

//! the content-type function from the types_module
function types_fun;

//! the authentication function from the authentication module
function auth_fun;

//! the name for the configuration
string name;

/* Since the main module (Roxen, formerly Spinner, alias spider), does
 * not have any clones its settings must be stored somewhere else.
 * This looked like a likely spot.. :)
 */
mapping variables = ([]); 

//! Retrieve (query) a variable from the configuration variable store.
//!
//! @param var
//!  Variable name
//!
//! @returns
//!  The variable value
public mixed query(string var)
{
  if(var && variables[var])
    return variables[var][ VAR_VALUE ];
  if(!var) return variables;
  error("query("+var+"): Unknown variable.\n");
}

//! Set the variable value for a variable in the configuration variable
//! store.
//!
//! @param var
//!  The variable name
//!
//! @param val
//!  The value to be assigned to the variable.
//!
//! @returns
//!  The value assigned to the function
mixed set(string var, mixed val)
{
#if DEBUG_LEVEL > 30
  perror(sprintf("MAIN: set(\"%s\", %O)\n", var, val));
#endif
  if(variables[var])
  {
#if DEBUG_LEVEL > 28
    perror("MAIN:    Setting global variable.\n");
#endif
    return variables[var][VAR_VALUE] = val;
  }
  error("set("+var+"). Unknown variable.\n");
}

int setvars( mapping (string:mixed) vars )
{
  string v;
//  perror("Setting variables to %O\n", vars);
  foreach( indices( vars ), v )
    if(variables[v])
      variables[v][ VAR_VALUE ] = vars[ v ];
  return 1;
}

//! Kill a variable.
void killvar(string name)
{
  m_delete(variables, name);
}

protected class ConfigurableWrapper
{
  int mode;
  function f;
  int check()
  {
    if ((mode & VAR_EXPERT) &&
        (!caudium->configuration_interface()->expert_mode)) {
      return 1;
    }
    if ((mode & VAR_MORE) &&
        (!caudium->configuration_interface()->more_mode)) {
      return 1;
    }
    return(f());
  }
  void create(int mode_, function f_)
  {
    mode = mode_;
    f = f_;
  }
};

//! Create a Defvar for Configuration interface
int defvar(string var, mixed value, string name, int type,
           string|void doc_str, mixed|void misc,
           int|function|void not_in_config)
{
  variables[var]                      = allocate( VAR_SIZE );
  variables[var][ VAR_VALUE ]         = value;
  variables[var][ VAR_TYPE ]          = type & VAR_TYPE_MASK;
  variables[var][ VAR_DOC_STR ]       = doc_str;
  variables[var][ VAR_NAME ]          = name;
  variables[var][ VAR_MISC ]          = misc;
  
  type &= ~VAR_TYPE_MASK;   // Probably not needed, but...
  type &= (VAR_EXPERT | VAR_MORE);
  if (functionp(not_in_config)) {
    if (type) {
      variables[var][ VAR_CONFIGURABLE ] = ConfigurableWrapper(type, not_in_config)->check;
    } else {
      variables[var][ VAR_CONFIGURABLE ] = not_in_config;
    }
  } else if (type) {
    variables[var][ VAR_CONFIGURABLE ] = type;
  } else if(intp(not_in_config)) {
    variables[var][ VAR_CONFIGURABLE ] = !not_in_config;
  }

  variables[var][ VAR_SHORTNAME ] = var;
}

//!
int definvisvar(string var, mixed value, int type)
{
  return defvar(var, value, "", type, "", 0, 1);
}

//!
string query_internal_location(object|void mod)
{
  return QUERY(InternalLoc)+(mod? replace(otomod[mod]||"", "#", "!")+"/":"");
}

//!
string query_name()
{
  if(strlen(QUERY(name))) return QUERY(name);
  return name;
}

//!
string comment()
{
  return QUERY(comment);
}

//!
class Priority 
{
  array (object) url_modules = ({ });
  array (object) logger_modules = ({ });
  array (object) location_modules = ({ });
  array (object) filter_modules = ({ });
  array (object) last_modules = ({ });
  array (object) first_modules = ({ });
  array (object) precache_modules = ({ });
  array (object) error_modules = ({ }); 
  
  mapping (string:array(object)) extension_modules = ([ ]);
  mapping (string:array(object)) file_extension_modules = ([ ]);
  mapping (object:multiset) provider_modules = ([ ]);


  void stop()
  {
    foreach(url_modules, object m)               CATCH(m->stop && m->stop());
    foreach(logger_modules, object m)            CATCH(m->stop && m->stop());
    foreach(filter_modules, object m)            CATCH(m->stop && m->stop());
    foreach(location_modules, object m)          CATCH(m->stop && m->stop());
    foreach(last_modules, object m)              CATCH(m->stop && m->stop());
    foreach(first_modules, object m)             CATCH(m->stop && m->stop());
    foreach(precache_modules, object m)          CATCH(m->stop && m->stop());
    foreach(indices(provider_modules), object m) CATCH(m->stop && m->stop());
    foreach(error_modules, object m)             CATCH(m->stop && m->stop());
  }
}



//! A 'pri' is one of the ten priority objects. Each one holds a list
//! of modules for that priority. They are all merged into one list for
//! performance reasons later on.
array (object) allocate_pris()
{
  int a;
  array (object) tmp;
  tmp=allocate(10);
  for(a=0; a<10; a++)  tmp[a]=Priority();
  return tmp;
}

#ifndef __AUTO_BIGNUM__
//!
class Bignum {
#if constant(Gmp.mpz) // Perfect. :-)
  object gmp = Gmp.mpz();
  float mb()
  {
    return (float)(gmp/1024)/1024.0;
  }

  object `+(int i)
  {
    gmp = gmp+i;
    return this_object();
  }

  object `-(int i)
  {
    gmp = gmp-i;
    return this_object();
  }

  mixed cast(string what) {
    switch(what) {
        case "int":
          return (int)gmp;
        case "float":
          return (float)gmp;
        case "string":
          return (string)gmp;
    }
  }
#else
  int msb;
  int lsb=-0x7ffffffe;

  object `-(int i);
  object `+(int i)
  {
    if(!i) return this_object();
    if(i<0) return `-(-i);
    object res = object_program(this_object())(lsb+i,msb,2);
    if(res->lsb < lsb) res->msb++;
    return res;
  }

  object `-(int i)
  {
    if(!i) return this_object();
    if(i<0) return `+(-i);
    object res = object_program(this_object())(lsb-i,msb,2);
    if(res->lsb > lsb) res->msb--;
    return res;
  }

  float mb()
  {
    return ((((float)lsb/1024.0/1024.0)+2048.0)+(msb*4096.0));
  }

  void create(int|void num, int|void bnum, int|void d)
  {
    if(!d)
      lsb = num-0x7ffffffe;
    else
      lsb = num;
    msb = bnum;
  }
#endif
}
#endif


//! Request used for debug and statistics info only
int requests;

//! Protocol specific statistics.
mapping(string:mixed) extra_statistics = ([]);

//! Even more protocol specific statistics
mapping(string:mixed) misc = ([]); 

#ifdef __AUTO_BIGNUM__
int sent, hsent, received;
#else
//! Sent data
object sent=Bignum();

//! Sent headers
object hsent=Bignum();

//! Received data
object received=Bignum();
#endif
object this = this_object();


// Used to store 'parser' modules before the main parser module
// is added to the configuration.
private array(object) _toparse_modules = ({});

//! Will write a line to the log-file. This will probably be replaced
//! entirely by log-modules in the future, since this would be much
//! cleaner.
int|function log_function;

//! The last time an item was logged. Used to determine if the log file
//! descriptor should be closed 
int last_log_time;

// A list of priority objects (used like a 'struct' in C, really)
private array (object) pri = allocate_pris();

// All enabled modules in this virtual server.
// The format is "module":([ module_info ])
public mapping (string:mapping(string:mixed)) modules = ([]);

// A mapping from objects to module names
public mapping (object:string) otomod = ([]);


// Caches to speed up the handling of the module search.
// They are all sorted in priority order, and created by the functions
// below.
private array (function) url_module_cache, last_module_cache, error_module_cache;
private array (function) logger_module_cache, first_module_cache;
private array (function) filter_module_cache, precache_module_cache;
private array (array (string|function)) location_module_cache;
private mapping (string:array (function)) extension_module_cache=([]);
private mapping (string:array (function)) file_extension_module_cache=([]);
private mapping (string:array (object)) provider_module_cache=([]);


//! Call stop in all modules.
void stop()
{
  CATCH(parse_module && parse_module->stop && parse_module->stop());
  CATCH(types_module && types_module->stop && types_module->stop());
  CATCH(auth_module && auth_module->stop && auth_module->stop());
  CATCH(dir_module && dir_module->stop && dir_module->stop());
  for(int i=0; i<10; i++) CATCH(pri[i] && pri[i]->stop && pri[i]->stop());
}

//! returns the content-type for the given filename. if "to" is set,
//! then returns the content-encoding as well.
//! ok, so this fun changes according to the new MODULE_TYPE API.
//! basically, from now on this is just a dummy function. the old one tried to play voodoo magic
//! with data it didn't really have, so...
public array|string type_from_filename( string file, int|void to ) {

  // the defaultest (grah) content-type and content-encoding. never ever EVER dare to change this, or else...
  array retval = ({ "application/octet-stream", 0 });

  if( !types_fun )
    return to ? retval : retval[ 0 ];

//   while(file[-1] == '/') 
//     file = file[0..strlen(file)-2]; // Security patch? 

  retval = types_fun( file );
  // hmm, all else is being taken care of inside types_fun...
  return to ? retval : retval[ 0 ];
}

//! Return an array with all provider modules that provides "provides".
//! @fixme
//!   Is there any way to clear this cache ? (grubba 1998-05-28)
//!   Yes, it is zapped together with the rest in invalidate_cache()
array (object) get_providers(string provides)
{
  if(!provider_module_cache[provides])
  { 
    int i;
    provider_module_cache[provides]  = ({ });
    for(i = 9; i >= 0; i--)
    {
      foreach(indices(pri[i]->provider_modules), object d) 
        if(pri[i]->provider_modules[ d ][ provides ]) 
          provider_module_cache[provides] += ({ d });
    }
  }
  return provider_module_cache[provides];
}

//! Return the first provider module that provides "provides".
object get_provider(string provides)
{
  array (object) prov = get_providers(provides);
  if(sizeof(prov))
    return prov[0];
  return 0;
}

//! map the function "fun" over all matching provider modules.
array(mixed) map_providers(string provides, string fun, mixed ... args)
{
  array (object) prov = get_providers(provides);
  array error;
  array a=({ });
  mixed m;
  foreach(prov, object mod) 
  {
    if(!objectp(mod))
      continue;
    if(functionp(mod[fun])) 
      error = catch(m=mod[fun](@args));
    if(arrayp(error)) {
      error[0] = "Error in map_providers(): "+error[0];
      roxen_perror(describe_backtrace(error));
    }
    else
      a += ({ m });
    error = 0;
  }
  return a;
}

//! map the function "fun" over all matching provider modules and
//! return the first positive response.
mixed call_provider(string provides, string fun, mixed ... args)
{
  foreach(get_providers(provides), object mod) {
    function f;
    if(objectp(mod) && functionp(f = mod[fun])) {
      mixed error;
      if (arrayp(error = catch {
        mixed ret;
        if (ret = f(@args)) {
          return(ret);
        }
      })) {
        error[0] = "Error in call_provider(): "+error[0];
        throw(error);
      }
    }
  }
}

//!
array (function) extension_modules(string ext, object id)
{
  if(!extension_module_cache[ext])
  { 
    int i;
    extension_module_cache[ext]  = ({ });
    for(i=9; i>=0; i--)
    {
      object p;
      array(object) d;
      if(d = pri[i]->extension_modules[ext])
        foreach(d, p)
          extension_module_cache[ext] += ({ p->handle_extension });
    }
  }
  return extension_module_cache[ext];
}

//!
array (function) file_extension_modules(string ext, object id)
{
  if(!file_extension_module_cache[ext])
  { 
    int i;
    file_extension_module_cache[ext]  = ({ });
    for(i=9; i>=0; i--)
    {
      object p;
      array(object) d;
      if(d = pri[i]->file_extension_modules[ext])
        foreach(d, p)
          file_extension_module_cache[ext] += ({ p->handle_file_extension });
    }
  }
  return file_extension_module_cache[ext];
}

//!
array (function) url_modules(object id)
{
  if(!url_module_cache)
  {
    int i;
    url_module_cache=({ });
    for(i=9; i>=0; i--)
    {
      object p;
      array(object) d;
      if(d=pri[i]->url_modules)
        foreach(d, p)
          url_module_cache += ({ p->remap_url });
    }
  }
  return url_module_cache;
}

//!
mapping api_module_cache = ([]);

//!
mapping api_functions(object id)
{
  return copy_value(api_module_cache);
}

//!
array (function) logger_modules(object id)
{
  if(!logger_module_cache)
  {
    int i;
    logger_module_cache=({ });
    for(i=9; i>=0; i--)
    {
      object p;
      array(object) d;
      if(d=pri[i]->logger_modules)
        foreach(d, p)
          if(p->log)
            logger_module_cache += ({ p->log });
    }
  }
  return logger_module_cache;
}

//!
array (function) last_modules(object id)
{
  if(!last_module_cache)
  {
    int i;
    last_module_cache=({ });
    for(i=9; i>=0; i--)
    {
      object p;
      array(object) d;
      if(d=pri[i]->last_modules)
        foreach(d, p)
          if(p->last_resort)
            last_module_cache += ({ p->last_resort });
    }
  }
  return last_module_cache;
}

//! Used for error modules
//!
//! @note
//!   Non RIS calls
array (function) error_modules(object id)
{
if(!error_module_cache)
  {  
    int i;
    error_module_cache=({ });
    for(i=9; i>=0; i--)
    {
      object p;
      array(object) d;
      if(d=pri[i]->error_modules)
        foreach(d, p)
          if(p->handle_error)
            error_module_cache += ({ p->handle_error });
    }  
  } 
  return error_module_cache;
}

//!
array (function) first_modules(object id)
{
  if(!first_module_cache)
  {
    int i;
    first_module_cache=({
    });
    for(i=9; i>=0; i--)
    {
      object p;
      array(object) d;
      if(d=pri[i]->first_modules) {
        foreach(d, p) {
          if(p->first_try) {
            first_module_cache += ({ p->first_try });
          }
        }
      }
    }
  }

  return first_module_cache;
}

//!
array (function) precache_modules(object id)
{
  if(!precache_module_cache)
  {
    int i;
    precache_module_cache = ({ });
    for(i = 9; i >= 0; i--)
    {
      object p;
      array(object) d;
      if(d=pri[i]->precache_modules) {
        foreach(d, p) {
          if(p->precache_rewrite) {
            precache_module_cache += ({ p->precache_rewrite });
          }
        }
      }
    }
  }
  return precache_module_cache;
}

//!
array location_modules(object id)
{
  if(!location_module_cache)
  {
    int i;
    array new_location_module_cache=({ });
    for(i=9; i>=0; i--)
    {
      object p;
      array(object) d;
      if(d=pri[i]->location_modules) {
        array level_find_files = ({});
        array level_locations = ({});
        foreach(d, p) {
          string location;
          // FIXME: Should there be a catch() here?
          if(p->find_file && (location = p->query_location())) {
            level_find_files += ({ p->find_file });
            level_locations += ({ location });
          }
        }
        sort(level_locations, level_find_files);
        int j;
        for (j = sizeof(level_locations); j--;) {
          // Order after longest path first.
          new_location_module_cache += ({ ({ level_locations[j],
                                             level_find_files[j] }) });
        }
      }
    }
    location_module_cache = new_location_module_cache;
  }
  return location_module_cache;
}

//!
array filter_modules(object id)
{
  if(!filter_module_cache)
  {
    int i;
    filter_module_cache=({ });
    for(i=9; i>=0; i--)
    {
      object p;
      array(object) d;
      if(d=pri[i]->filter_modules)
        foreach(d, p)
          if(p->filter)
            filter_module_cache+=({ p->filter });
    }
  }
  return filter_module_cache;
}

string cache_hostname=gethostname();

//!
int init_log_file(int|void force_open, void|object id)
{
  int t = time(1);
  remove_call_out(init_log_file);
  
  if(functionp(log_function))
  {
    destruct(function_object(log_function)); 
    // Free the old one.
  }
  // Here we close the log file since it hasn't been used for
  // 'max_open_time' seconds, and we don't need it open, i.e
  // this open call is not from the logging.p
  if(!force_open && QUERY(max_open_time) && 
     (t - last_log_time) > QUERY(max_open_time)) {
    log_function = 0;
    return 0;
  }
  if(query("Log")) // Only try to open the log file if logging is enabled!!
  {
    mapping m = localtime(t);
    string logfile = QUERY(LogFile);
    m->year += 1900;  /* Adjust for years being counted since 1900 */
    m->mon++;   /* Adjust for months being counted 0-11 */
    if(m->mon < 10) m->mon = "0"+m->mon;
    if(m->mday < 10) m->mday = "0"+m->mday;
    if(m->hour < 10) m->hour = "0"+m->hour;
    logfile = replace(logfile,({"%d","%m","%y","%h","%H","%V"}),
                      ({ (string)m->mday, (string)(m->mon),
                         (string)(m->year),(string)m->hour,cache_hostname,
                         (id && id->host)?id->host:"NONE"}));
    if(strlen(logfile))
    {
      do {
        object lf=open( logfile, "wac");
        if(!lf) {
          Stdio.mkdirhier(dirname(logfile));
          if(!(lf=open( logfile, "wac"))) {
            report_error("Failed to open logfile. ("+logfile+")\n" +
                         "No logging will take place!\n");
            log_function=-1;
            return 0;
          }
        }
        log_function=lf->write; 
        // Function pointer, speeds everything up (a little..).
        lf=0;
      } while(0);
    } else {
      log_function=-1;
      return 0;
    }
    // Call out to this to reopen or close (if that feature is enabled)
    // the log file. reopening is done in case the file name has changed
    // or in case the file has been removed. A random(20) is added to avoid
    // getting ALL virtual servers calling this at the same time. Reopening
    // 500 files at once is expensive. :-)
    call_out(init_log_file, 60 + random(20));
    return 1;
  } else {
    log_function=-1;
    return 0;
  }
}

#ifdef THREADS
private object log_file_mutex = Thread.Mutex();
#endif

public void log(mapping file, object request_id)
{
//    _debug(2);
  object fobj;
  function f;

  foreach(logger_modules(request_id), f) // Call all logging functions
    if(f(request_id,file)) return;

  if(log_function == -1 || !request_id ||
     (QUERY(NoLog) && Caudium._match(request_id->remoteaddr, QUERY(NoLog))))
    return;
  if(!log_function) {
#ifdef THREADS
    object key = log_file_mutex->lock(1);
    // Second if to avoid call the function if it was already done by previous
    // locker, if any. 
    if(!log_function)
#endif
      init_log_file(1, request_id);
#ifdef THREADS
    destruct(key);
#endif
  }
  if(functionp(log_function)) {
    if(!(fobj = logger->log_format_objs[(string)file->error]))
      if(!(fobj = logger->log_format_objs["*"]))
        return; // no logging for this one.
    last_log_time = time(1);
    if(fobj->hashost)
      caudium->ip_to_host(request_id->remoteaddr, Logging.write_to_log,
                          fobj->format_log(file, request_id),
                          request_id->remoteaddr, log_function);
    else
      log_function(fobj->format_log(file, request_id));
  }
}

// These are here for statistics and debug reasons only.
public string status()
{
  float tmp;
  string res = "<table>";
#ifdef __AUTO_BIGNUM__
  tmp = (sent/(float)(time(1)-caudium->start_time+1));
  res += sprintf("<tr align=right><td><b>Sent data:</b></td><td>%s"
                 "</td><td>%.2f Kbit/sec</td>",
                 Caudium.sizetostring(sent),tmp/128.0);
  
  res += sprintf("<td><b>Sent headers:</b></td><td>%s</td></tr>\n",
                 Caudium.sizetostring(hsent));
  
  tmp=(requests*600.0)/((time(1)-caudium->start_time)+1);

  res += sprintf("<tr align=right><td><b>Number of requests:</b></td>"
                 "<td>%8d</td><td>%.2f/min</td>"
                 "<td><b>Received data:</b></td><td>%s</td></tr>\n",
                 requests, tmp/10.0, Caudium.sizetostring(received));
#else
  if(!sent||!received||!hsent)
    return "Fatal error in status(): Bignum object gone.\n";

  tmp = (sent->mb()/(float)(time(1)-caudium->start_time+1));
  res += sprintf("<tr align=right><td><b>Sent data:</b></td><td>%.2fMB"
                 "</td><td>%.2f Kbit/sec</td>",
                 sent->mb(),tmp * 8192.0);
  
  res += sprintf("<td><b>Sent headers:</b></td><td>%.2fMB</td></tr>\n",
                 hsent->mb());
  
  tmp=(((float)requests*(float)600)/
       (float)((time(1)-caudium->start_time)+1));

  res += sprintf("<tr align=right><td><b>Number of requests:</b></td>"
                 "<td>%8d</td><td>%.2f/min</td>"
                 "<td><b>Received data:</b></td><td>%.2fMB</td></tr>\n",
                 requests, (float)tmp/(float)10, received->mb());
#endif
#ifdef ENABLE_RAM_CACHE
  if(datacache && (datacache->hits || datacache->misses)) {
    res += sprintf("<tr align=right><td><b>Cache Requests:</b></td>"
                   "<td>%d hits</td><td>%d misses</td></td>"
                   "<td><b>Cache Hitrate:</b></td>"
                   "<td>%.1f%%</td></tr>",
                   datacache->hits, datacache->misses,
                   datacache->misses ?
                   (datacache->hits / (float)(datacache->hits +
                                              datacache->misses))*100 :  100);
    
    res += sprintf("<tr align=right><td><b>Cache Utilization:</b></td>"
                   "<td>%s</td><td>%.1f%% free</td>"
                   "<td><b>Cache Entries:</b></td>"
                   "<td>%d</td></tr>",
                   Caudium.sizetostring(datacache->current_size),
                   ((datacache->max_size - datacache->current_size)/
                    (float)datacache->max_size)*100, sizeof(datacache->cache));
  }
#endif

  return res + "</table>";
}

//! @deprecated
public array(string) userinfo(string u, object|void id)
{
  report_warning("Calls to conf->userinfo() are deprecated and may not exist in future releases of this software.\n");
  if(auth_module) return auth_module->userinfo(u);
  else report_warning(sprintf("userinfo(): No authorization module\n"
                              "%s\n", describe_backtrace(backtrace())));
}

//! @deprecated
public array(string) userlist(object|void id)
{
  report_warning("Calls to conf->userlist() are deprecated and may not exist in future releases of this software.\n");
  if(auth_module) return auth_module->userlist();
  else report_warning(sprintf("userlist(): No authorization module\n"
                              "%s\n", describe_backtrace(backtrace())));
}

//! @deprecated
public array(string) user_from_uid(int u, object|void id)
{
  report_warning("Calls to conf->user_from_uid() are deprecated and may not exist in future releases of this software.\n");
  if(auth_module)
    return auth_module->user_from_uid(u);
  else report_warning(sprintf("user_from_uid(): No authorization module\n"
                              "%s\n", describe_backtrace(backtrace())));
}

// Some clients does _not_ handle the magic 'internal-gopher-...'.
// So, lets do it here instead.
private mapping internal_gopher_image(string from)
{
  sscanf(from, "%s.gif", from);
  sscanf(from, "%s.jpg", from);
  from -= ".";
  // Disallow "internal-gopher-..", it won't really do much harm, but a list of
  // all files in '..' might be retrieved (that is, the actual directory
  // file was sent to the browser)
  return (["file":open("caudium-images/dir/"+from+".gif","r"),
           "type":"image/gif"]);
}

protected int nest = 0;
  
#ifdef MODULE_LEVEL_SECURITY
private mapping misc_cache=([]);

//!
int|mapping check_security(function a, object id, void|int slevel)
{
  array level;
  array seclevels;
  int ip_ok = 0;  // Unknown
  int auth_ok = 0;  // Unknown
  // NOTE:
  //   ip_ok and auth_ok are three-state variables.
  //   Valid contents for them are:
  //     0  Unknown state -- No such restriction encountered yet.
  //     1  May be bad -- Restriction encountered, and test failed.
  //    ~0  OK -- Test passed.
  
  if(!(seclevels = misc_cache[ a ])) {
    int seclvl;
    mixed secgroup;
    if(!function_object(a)->query_seclevels)
      return 0;
    catch { seclvl = function_object(a)->query("_seclvl"); };
    catch { secgroup = function_object(a)->query("_sec_group"); };
    misc_cache[ a ] = seclevels = ({
      function_object(a)->query_seclevels(),
      seclvl, secgroup
    });
  }
  if (sizeof(seclevels[0]) && seclevels[0][0] != MOD_USER_SECLEVEL)
    if(slevel && (seclevels[1] > slevel)) // "Trustlevel" to low.
      return 1;
  
  if(!sizeof(seclevels[0]))
    return 0; // Ok if there are no patterns.

  mixed err;
  err = catch {
    foreach(seclevels[0], level) {
      
      switch(level[0]) {
          case MOD_ALLOW: // allow ip=...
            if(level[1](id->remoteaddr)) {
              ip_ok = ~0; // Match. It's ok.
            } else {
              ip_ok |= 1; // IP may be bad.
            }
            break;
  
          case MOD_DENY: // deny ip=...
            if(level[1](id->remoteaddr))
              return Caudium.HTTP.low_answer(403, "<h2>Access forbidden</h2>");
            break;

          case MOD_USER: // allow user=...
            if(id->auth && id->auth[0] && level[1](id->auth[1])) {
              auth_ok = ~0; // Match. It's ok.
            } else {
              auth_ok |= 1; // Auth may be bad.
            }
            break;
  
          case MOD_PROXY_USER: // allow user=...
            if (ip_ok != 1) {
              // IP is OK as of yet.
              if(id->misc->proxyauth && id->misc->proxyauth[0] && 
                 level[1](id->misc->proxyauth[1])) return 0;
              return Caudium.HTTP.proxy_auth_required(seclevels[2]);
            } else {
              // Bad IP.
              return(1);
            }
            break;

          case MOD_ACCEPT: // accept ip=...
            // Short-circuit version on allow.
            if(level[1](id->remoteaddr)) {
              // Match. It's ok.
              return(0);
            } else {
              ip_ok |= 1; // IP may be bad.
            }
            break;

          case MOD_ACCEPT_USER: // accept user=...
            // Short-circuit version on allow.
            if(id->auth && id->auth[0] && level[1](id->auth[1])) {
              // Match. It's ok.
              return(0);
            } else {
              if (id->auth) {
                auth_ok |= 1; // Auth may be bad.
              } else {
                // No auth yet, get some.
                return Caudium.HTTP.auth_required(seclevels[2],QUERY(ZAuthenticationFailed));
              }
            }
            break;

          case MOD_ACCEPT_GROUP:
            if (id->auth && id->auth[0] && sizeof(id->auth) >= 4 && level[1](id->auth[3])) {
              return 0;
            } else {
              if (id->auth)
                auth_ok |= 1;
              else
                return Caudium.HTTP.auth_required(seclevels[2],QUERY(ZAuthenticationFailed));
            }
            break;
            
          case MOD_USER_SECLEVEL: // secuname=...
            mapping(string:int)  usrlist = level[1];

            if(id->auth && id->auth[0]) {
              int  mylevel = -1000;
      
              if (usrlist["any"]) {
                report_notice("Any match on User Seclevel\n");
                mylevel = usrlist["any"];
                report_notice("Security level will be set to " + mylevel + "\n");
              } else if (usrlist[id->auth[1]]) {
                report_notice("User match on User Seclevel (" + id->auth[1] + ")\n");
                mylevel = usrlist[id->auth[1]];
              }
              if (mylevel != -1000)
                misc_cache[a][1] = mylevel;
            } else {
              if (id->auth) {
                auth_ok |= 1; // Auth may be bad.
              } else {
                // No auth yet, get some.
                return Caudium.HTTP.auth_required(seclevels[2],QUERY(ZAuthenticationFailed));
              }
            }
            break;
      }
    }
  };

  if (err) {
    report_error(sprintf("Error during module security check:\n"
                         "%s\n", describe_backtrace(err)));
    return(1);
  }

  if (ip_ok == 1) {
    // Bad IP.
    return(1);
  } else {
    // IP OK, or no IP restrictions.
    if (auth_ok == 1) {
      // Bad authentication.
      // Query for authentication.
      return  Caudium.HTTP.auth_required(seclevels[2],QUERY(ZAuthenticationFailed));
    } else {
      // No auth required, or authentication OK.
      return(0);
    }
  }
}
#endif

//! Empty all the caches above.
void invalidate_cache()
{
  last_module_cache = 0;
  filter_module_cache = 0;
  first_module_cache = 0;
  precache_module_cache = 0;
  url_module_cache = 0;
  location_module_cache = 0;
  logger_module_cache = 0;
  extension_module_cache      = ([]);
  file_extension_module_cache = ([]);
  provider_module_cache = ([]);
  error_module_cache = 0;
#ifdef MODULE_LEVEL_SECURITY
  if(misc_cache)
    misc_cache = ([ ]);
#endif
}

//! Empty all the caches above AND the ones in the loaded modules.
void clear_memory_caches()
{
  invalidate_cache();
  foreach(indices(otomod), object m) {
    if (m && m->clear_memory_caches) {
      mixed err = catch {
        m->clear_memory_caches();
      };
      if (err) {
        report_error(sprintf("clear_memory_caches() failed for module %O:\n"
                             "%s\n",
                             otomod[m], describe_backtrace(err)));
      }
    }
  }
}

//!
string draw_saturation_bar(int hue,int brightness, int where)
{
  object bar=Image.Image(30,256);

  for(int i=0;i<128;i++)
  {
    int j = i*2;
    bar->line(0,j,29,j,@Colors.hsv_to_rgb(hue,255-j,brightness));
    bar->line(0,j+1,29,j+1,@Colors.hsv_to_rgb(hue,255-j,brightness));
  }

  where = 255-where;
  bar->line(0,where,29,where, 255,255,255);

  return Image.GIF.encode(bar);
//  return bar->togif(255,255,255);
}


// Inspired by the internal-gopher-... thingie, this is the for internal
// Caudium images, like logos etc.
private mapping internal_caudium_image(string from)
{
  int hue,bright,w;

#if 0
  string ext;

  sscanf(from, "%s.%s", from, ext);
//  sscanf(from, "%s.gif", from);
//  sscanf(from, "%s.jpg", from);
//  sscanf(from, "%s.xcf", from);
  if (!ext)
    ext = "any";
  
  // Disallow "internal-caudium-..", it won't really do much harm, but a list of
  // all files in '..' might be retrieved (that is, the actual directory
  // file was sent to the browser)
  // /internal-caudium-../.. was never possible, since that would be remapped to
  // /..
  from -= ".";
#endif
  
  // New idea: Automatically generated colorbar. Used by wizard code...
  if(sscanf(from, "%*s:%d,%d,%d", hue, bright,w)==4)
    return Caudium.HTTP.string_answer(draw_saturation_bar(hue,bright,w),"image/gif");
  from = replace(from, "roxen", "caudium");

#if 0
  // If the requested image had .xcf extension then we should treat
  // it especially. It differs from the other types in that it's a
  // layered image, and not a flat bitmap. Since some code asks
  // for .xcf it is highly probable it needs the layers (like gbutton,
  // for example). So, in case of XCF we either find the exact file
  // or return null.
  
  mapping img_types = ([
    "gif":"image/gif",
    "png":"image/png",
    "jpg":"image/jpeg",
    "jpeg":"image/jpeg",
    "xcf":"image/x-xcf",
    "ico":"image/x-icon",
  ]);
  
  switch(ext) {
      case "any":
      case "png":
      case "jpg":
      case "gif":
      case "jpeg":
        foreach(indices(img_types) - ({"xcf"}), string e)
          if(img = open("caudium-images/"+from+"."+e, "r")) 
            return (["  file": img, "type":img_types[e]]);
        break;
          
      case "xcf":
        if(img = open("caudium-images/"+from+"."+ext, "r")) 
          return (["file": img, "type":img_types[ext]]);
        break;
  }
#endif
  mapping ret = caudium->IFiles->get("image://" + from);
  if (!ret) {
    mapping err = caudium->IFiles->get("html://no_internal_image.html");
    return Caudium.HTTP.string_answer(err->data);
  }
  return ret;
}

//! The function that actually tries to find the data requested.  All
//! modules are mapped, in order, and the first one that returns a
//! suitable responce is used.
mapping (mixed:function|int) locks = ([]);

#ifdef THREADS
// import Thread;

mapping locked = ([]), thread_safe = ([]);

object _lock(object|function f)
{
  object key;
  function|int l;

  if (functionp(f)) {
    f = function_object(f);
  }
  if (l = locks[f])
  {
    if (l != -1)
    {
      // Allow recursive locks.
      catch{
        //perror("lock %O\n", f);
        locked[f]++;
        key = l();
      };
    } else
      thread_safe[f]++;
  } else if ((!catch(f->thread_safe)) && (f->thread_safe)) {
    locks[f]=-1;
    thread_safe[f]++;
  } else {
    if (!locks[f])
    {
      // Needed to avoid race-condition.
      l = Thread.Mutex()->lock;
      if (!locks[f]) {
        locks[f]=l;
      }
    }
    //perror("lock %O\n", f);
    locked[f]++;
    key = l();
  }
  return key;
}

#define LOCK(X) key=_lock(X)
#define UNLOCK() do{key=0;}while(0)
#else
#define LOCK(X)
#define UNLOCK()
#endif


#define TRACE_ENTER(A,B) do{if(id->misc->trace_enter)id->misc->trace_enter((A),(B));}while(0)
#define TRACE_LEAVE(A) do{if(id->misc->trace_leave)id->misc->trace_leave((A));}while(0)

//!
string examine_return_mapping(mapping m)
{
  string res;

  if (m->extra_heads)
    m->extra_heads=mkmapping(Array.map(indices(m->extra_heads),
                                       lower_case),
                             values(m->extra_heads));
  else
    m->extra_heads=([]);

  switch (m->error||200)
  {
      case 302: // redirect
        if (m->extra_heads && 
            (m->extra_heads->location))
          res 
            = "Returned <i><b>redirect</b></i>;<br>&nbsp;&nbsp;&nbsp;to "
            "<a href="+(m->extra_heads->location)+">"
            "<font color=darkgreen><tt>"+
            (m->extra_heads->location)+
            "</tt></font></a><br>";
        else
          res = "Returned redirect, but no location header\n";
        break;

      case 401:
        if (m->extra_heads["www-authenticate"])
          res
            = "Returned <i><b>authentication failed</b></i>;"
            "<br>&nbsp;&nbsp;&nbsp;<tt>"+
            m->extra_heads["www-authenticate"]+"</tt><br>";
        else
          res 
            = "Returned <i><b>authentication failed</b></i>.<br>";
        break;

      case 200:
        res
          = "Returned <i><b>ok</b></i><br>\n";
        break;
   
      default:
        res
          = "Returned <b><tt>"+m->error+"</tt></b>.<br>\n";
  }

  if (!zero_type(m->len))
    if (m->len<0)
      res+="No data ";
    else
      res+=m->len+" bytes ";
  else if (stringp(m->data))
    res+=strlen(m->data)+" bytes";
  else if (objectp(m->file))
    if (catch {
      array a=(array(int))m->file->stat();
      res+=(a[1]-m->file->tell())+" bytes ";
    }) res+="? bytes";

  if (m->data) res+=" (protected)";
  else if (m->file) res+="(open file)";

  if (stringp(m->extra_heads["http-content-type"]))
    res+=" of <tt>"+m->type+"</tt>\n";
  else if (stringp(m->type))
    res+=" of <tt>"+m->type+"</tt>\n";

  res+="<br>";

  return res;
}

//!
mapping|int low_get_file(object id, int|void no_magic)
{
#ifdef MODULE_LEVEL_SECURITY
  int slevel;
#endif

#ifdef THREADS
  object key;
#endif
  TRACE_ENTER("Request for "+id->not_query, 0);

  string file=id->not_query;
  string loc, type;
  function funp;
  mixed tmp, tmp2;
  mapping|object fid;

  if (!id->misc)
    id->misc = ([]);

  switch(QUERY(use_scopes)) {
      case "Off":
        id->misc->_use_scopes = 0;
        id->misc->_scope_status = 0;
        break;

      case "On":
        id->misc->_use_scopes = 1;
        id->misc->_scope_status = 1;
        break;

      case "Off/Conditional":
        id->misc->_use_scopes = 2;
        id->misc->_scope_status = 0;
        break;

      case "On/Conditional":
        id->misc->_use_scopes = 3;
        id->misc->_scope_status = 1;
        break;

      default:
        id->misc->_use_scopes = 0;
        id->misc->_scope_status = 0;
        break;
  }
    
  // Simplify the path to ensure that the file never points under the
  // current directory. Generally not needed, but it's a cheap
  // operation considering the security problems it stops.
  file = combine_path("/", file);
  
  if(!no_magic)
  {
      if (id->prestate->internal && id->prestate->image)
        return internal_caudium_image(file);
   
      
#ifndef NO_INTERNAL_HACK 
    // No, this is not beautiful... :) 

    if(sscanf(file, "%*s/internal-%s-%s", type, loc) == 3)
    {
      switch(type) {
          case "gopher":
            TRACE_LEAVE("Magic internal gopher image");
            return internal_gopher_image(loc);

          case "caudium":
          case "roxen":
          case "spinner":
            TRACE_LEAVE("Magic internal Caudium image");
            return internal_caudium_image(loc);
      }
    }
#endif

    if(id->prestate->diract && dir_module)
    {
      LOCK(dir_module);
      TRACE_ENTER("Directory module", dir_module);
      tmp = dir_module->parse_directory(id);
      UNLOCK();
      if(mappingp(tmp)) 
      {
        TRACE_LEAVE("");
        TRACE_LEAVE("Returning data");
        return tmp;
      }
      TRACE_LEAVE("");
    }

    if(!search(file, QUERY(InternalLoc))) 
    {
      object module;
      string name, rest;
      function find_internal;
      if(2==sscanf(file[strlen(QUERY(InternalLoc))..], "%s/%s", name, rest) &&
         (module = find_module(replace(name, "!", "#"))) &&
         (find_internal = module->find_internal))
      {
        LOCK(find_internal);
        fid=find_internal( rest, id );
        UNLOCK();
        if(mappingp(fid))
          return fid;
      }
    }
  }

  // Well, this just _might_ be somewhat over-optimized, since it is
  // quite unreadable, but, you cannot win them all.. 
#ifdef URL_MODULES
  // Map URL-modules
  foreach(url_modules(id), funp)
  {
    LOCK(funp);
    TRACE_ENTER("URL Module", funp);
    tmp=funp( id, file );
    UNLOCK();
    
    if(mappingp(tmp)) 
    {
      TRACE_LEAVE("");
      TRACE_LEAVE("Returning data");
      return tmp;
    }
    if(objectp( tmp ))
    {
      array err;

      nest ++;
      err = catch {
        if( nest < 20 )
          tmp = (id->conf || this_object())->low_get_file( tmp, no_magic );
        else
        {
          TRACE_LEAVE("Too deep recursion");
          error("Too deep recursion in roxen::get_file() while mapping "
                +file+".\n");
        }
      };
      nest = 0;
      if(err) throw(err);
      TRACE_LEAVE("");
      TRACE_LEAVE("Returned data");
      return tmp;
    }
    TRACE_LEAVE("");
  }
#endif
#ifdef EXTENSION_MODULES  
  if(tmp=extension_modules(loc=extension(file), id))
  {
    foreach(tmp, funp)
    {
      TRACE_ENTER("Extension Module ["+loc+"] ", funp);
      LOCK(funp);
      tmp=funp(loc, id);
      UNLOCK();
      if(tmp)
      {
        if(!objectp(tmp)) 
        {
          TRACE_LEAVE("Returing data");
          return tmp;
        }
        fid = tmp;
#ifdef MODULE_LEVEL_SECURITY
        slevel = function_object(funp)->query("_seclvl");
#endif
        TRACE_LEAVE("Retured open filedescriptor."
#ifdef MODULE_LEVEL_SECURITY
                    +(slevel != id->misc->seclevel?
                      ". The security level is now "+slevel:"")
#endif
                   );
#ifdef MODULE_LEVEL_SECURITY
        id->misc->seclevel = slevel;
#endif
        break;
      } else
        TRACE_LEAVE("");
    }
  }
#endif 
 
  foreach(location_modules(id), tmp)
  {
    loc = tmp[0];
    if(!search(file, loc)) 
    {
      TRACE_ENTER("Location Module ["+loc+"] ", tmp[1]);
#ifdef MODULE_LEVEL_SECURITY
      if(tmp2 = check_security(tmp[1], id, slevel))
        if(intp(tmp2))
        {
          TRACE_LEAVE("Permission to access module denied");
          continue;
        } else {
          TRACE_LEAVE("Request denied.");
          return tmp2;
        }
#endif
      TRACE_ENTER("Calling find_file()...", 0);
      LOCK(tmp[1]);
      fid=tmp[1]( file[ strlen(loc) .. ] + id->extra_extension, id);
      UNLOCK();
      TRACE_LEAVE(sprintf("find_file has returned %O", fid));
      if(fid)
      {
        id->virtfile = loc;

        if(mappingp(fid))
        {
          TRACE_LEAVE("");
          TRACE_LEAVE(examine_return_mapping(fid));
          return fid;
        }
        else
        {
#ifdef MODULE_LEVEL_SECURITY
          int oslevel = slevel;
          slevel = misc_cache[ tmp[1] ][1];
          // misc_cache from
          // check_security
          id->misc->seclevel = slevel;
#endif
          if(objectp(fid))
            TRACE_LEAVE("Returned open file"
#ifdef MODULE_LEVEL_SECURITY
                        +(slevel != oslevel?
                          ". The security level is now "+slevel:"")
#endif
      
                        +".");
          else
            TRACE_LEAVE("Returned directory indicator"
#ifdef MODULE_LEVEL_SECURITY
                        +(oslevel != slevel?
                          ". The security level is now "+slevel:"")
#endif
                       );
          break;
        }
      } else
        TRACE_LEAVE("");
    } else if(strlen(loc)-1==strlen(file)) {
      // This one is here to allow accesses to /local, even if 
      // the mountpoint is /local/. It will slow things down, but...
      if(file+"/" == loc) 
      {
        TRACE_ENTER("Automatic redirect to location module", tmp[1]);
        TRACE_LEAVE("Returning data");
        return Caudium.HTTP.redirect(id->not_query + "/", id);
      }
    }
  }
  
  if(fid == -1)
  {
    if(no_magic)
    {
      TRACE_LEAVE("No magic requested. Returning -1");
      return -1;
    }
    if(dir_module)
    {
      LOCK(dir_module);
      TRACE_ENTER("Directory module", dir_module);
      fid = dir_module->parse_directory(id);
      UNLOCK();
    }
    else
    {
      TRACE_LEAVE("No directory module. Returning 'no such file'");
      return 0;
    }
    if(mappingp(fid)) 
    {
      TRACE_LEAVE("Returned data");
      return (mapping)fid;
    }
  }
  
  // Map the file extensions, but only if there is a file...
  if(objectp(fid)&&
     (tmp=file_extension_modules(loc=Caudium.extension(id->not_query), id)))
    foreach(tmp, funp)
    {
      TRACE_ENTER("Extension module", funp);
#ifdef MODULE_LEVEL_SECURITY
      if(tmp=check_security(funp, id, slevel))
        if(intp(tmp))
        {
          TRACE_LEAVE("Permission to access module denied");
          continue;
        }
        else
        {
          TRACE_LEAVE("");
          TRACE_LEAVE("Permission denied");
          return tmp;
        }
#endif
      LOCK(funp);
      tmp=funp(fid, loc, id);
      UNLOCK();
      if(tmp)
      {
        if(!objectp(tmp))
        {
          TRACE_LEAVE("");
          TRACE_LEAVE("Returning data");
          return tmp;
        }
        if(fid)
          destruct(fid);
        TRACE_LEAVE("Returned new open file");
        fid = tmp;
        break;
      } else
        TRACE_LEAVE("");
    }
  
  if(objectp(fid))
  {
    if(stringp(id->extension))
      id->not_query += id->extension;


    TRACE_ENTER("Content-type mapping module", types_module);
    tmp=type_from_filename(id->not_query, 1);
    TRACE_LEAVE(tmp?"Returned type "+tmp[0]+" "+tmp[1]:"Missing");
    if(tmp)
    {
      TRACE_LEAVE("");
      return ([ "file":fid, "type":tmp[0], "encoding":tmp[1] ]);
    }    
    TRACE_LEAVE("");
    return ([ "file":fid, ]);
  }
  if(!fid)
    TRACE_LEAVE("Returning 'no such file'");
  else
    TRACE_LEAVE("Returning data");
  return fid;
}

//! Call the precache_rewrite function in all MODULE_PRECACHE, if any.
//! This is done before the any raw caching is done and can be used for
//! virtual hosting and creation of a custom cache key.
void handle_precache(object id) {
  foreach(precache_module_cache||precache_modules(id), function funp)
  {
    funp( id );
    if(id->conf != this_object()) {
      REQUEST_WERR("handle_request(): Redirected (2)");
      if(!id->conf->inited) { id->conf->enable_all_modules(); }
      id->conf->handle_precache(id);
      return;
    }
  }
}

//! Call the handle_error function in all MODULE_ERROR, if any.
//! This is done at the end of request if there is nothing from others module
//!
//! @param id
//!   Caudium Object id
//!
//! @returns 
//!   object or data from @[Caudium.HTTP.low_answer] function or 0 if error
//!
//! @note
//!   Non RIS implementation
mixed handle_error_request( object id ) {
  REQUEST_WERR("handle_error_request(): called");
  mixed out, ret;
  foreach(error_module_cache||error_modules(id), function funp) {
    REQUEST_WERR("handle_error_request(): try module");
    if(ret = funp(id)) break;
    REQUEST_WERR(sprintf("handle_error_request(): get %O",ret));
    if(ret == 1) {
      REQUEST_WERR("handle_error_request(): Recurse");
      return handle_error_request(id);
    }
  } 
  out = ret;
  REQUEST_WERR("handle_error_request(): Done");
  return out;
}

//! This function handle the request for the server.
//! All request goes thru this function
//!
//! @param id
//!   Caudium Object id
//!
//! @returns
//!   To be documented
//!
//! @note
//!   RIS Implmentation with some additions
//!
//! @fixme 
//!   To be documented
mixed handle_request(object id)
{
  function funp;
  mixed file;
  REQUEST_WERR("handle_request()");
  foreach(first_module_cache||first_modules(id), funp)
  {
    if(file = funp( id ))
      break;
    if(id->conf != this_object()) {
      REQUEST_WERR("handle_request(): Redirected (2)");
      return id->conf->handle_request(id);
    }
  }
  if(!mappingp(file) && !mappingp(file = get_file(id)))
  {
    mixed ret;
    foreach(last_module_cache||last_modules(id), funp)
      if(ret = funp(id)) break;
    if (ret == 1) {
      REQUEST_WERR("handle_request(): Recurse");
      return handle_request(id);
    }
    file = ret;
  }
  REQUEST_WERR("handle_request(): Done");
  return file;
}

//! Get the file in probably VFS
//!
//! @param id
//!   Caudium ID object
//!
//! @param no_magic
//!   Undocumented.
//!
//! @returns
//!   Undocumented.
//!
//! @note
//!   RIS implementation
//!
//! @fixme
//!   Undocumented
mixed get_file(object id, int|void no_magic)  
{
  mixed res, res2;
  function tmp;
  res = low_get_file(id, no_magic);
  // finally map all filter type modules.
  // Filter modules are like TYPE_LAST modules, but they get called
  // for _all_ files.
  foreach(filter_modules(id), tmp)
  {
    TRACE_ENTER("Filter module", tmp);
    if(res2=tmp(res,id))
    {
      if(res && res->file && (res2->file != res->file))
        destruct(res->file);
      TRACE_LEAVE("Rewrote result");
      res=res2;
    } else
      TRACE_LEAVE("");
  }
  return res;
}

public array find_dir(string file, object id)
{
  string loc;
  array dir = ({ }), tmp;
  array | mapping d;
  TRACE_ENTER("List directory "+file, 0);
  file=replace(file, "//", "/");
  
  if(file[0] != '/')
    file = "/" + file;

#ifdef URL_MODULES
#ifdef THREADS
  object key;
#endif
  // Map URL-modules
  foreach(url_modules(id), function funp)
  {
    string of = id->not_query;
    id->not_query = file;
    LOCK(funp);
    TRACE_ENTER("URL module", funp);
    tmp=funp( id, file );
    UNLOCK();

    if(mappingp( tmp ))
    {
      id->not_query=of;
      TRACE_LEAVE("Returned 'no thanks'");
      TRACE_LEAVE("");
      return 0;
    }
    if(objectp( tmp ))
    {
      array err;
      nest ++;
      
      TRACE_LEAVE("Recursing");
      file = id->not_query;
      err = catch {
        if( nest < 20 )
          tmp = (id->conf || this_object())->find_dir( file, id );
        else
          error("Too deep recursion in roxen::find_dir() while mapping "
                +file+".\n");
      };
      nest = 0;
      TRACE_LEAVE("");
      if(err)
        throw(err);
      return tmp;
    }
    id->not_query=of;
  }
#endif /* URL_MODULES */

  foreach(location_modules(id), tmp)
  {
    loc = tmp[0];
    if(!search(file, loc)) {
      /* file == loc + subpath */
      TRACE_ENTER("Location module", tmp[1]);
#ifdef MODULE_LEVEL_SECURITY
      if(check_security(tmp[1], id)) {
        TRACE_LEAVE("Permission denied");
        continue;
      }
#endif
      if(d=function_object(tmp[1])->find_dir(file[strlen(loc)..], id))
      {
        if(mappingp(d))
        {
          if(d->files) { 
            dir |= d->files;
            TRACE_LEAVE("Got exclusive directory.");
            TRACE_LEAVE("Returning list of "+sizeof(dir)+" files");
            return dir;
          } else
            TRACE_LEAVE("");
        } else {
          TRACE_LEAVE("Got files");
          dir |= d;
        }
      } else
        TRACE_LEAVE("");
    } else if((search(loc, file)==0) && (loc[strlen(file)-1]=='/') &&
              (loc[0]==loc[-1]) && (loc[-1]=='/') &&
              (function_object(tmp[1])->stat_file(".", id))) {
      /* loc == file + "/" + subpath + "/"
       * and stat_file(".") returns non-zero.
       */
      TRACE_ENTER("Location module", tmp[1]);
      loc=loc[strlen(file)..];
      sscanf(loc, "%s/", loc);
      dir += ({ loc });
      TRACE_LEAVE("Added module mountpoint");
    }
  }
  if(sizeof(dir))
  {
    TRACE_LEAVE("Returning list of "+sizeof(dir)+" files");
    return dir;
  } 
  TRACE_LEAVE("Returning 'no such directory'");
}

// Stat a virtual file. 
public array stat_file(string file, object id)
{
  string loc;
  array s, tmp;
  TRACE_ENTER("Stat file "+file, 0);
  
  file=replace(file, "//", "/"); // "//" is really "/" here...

#ifdef URL_MODULES
#ifdef THREADS
  object key;
#endif
  // Map URL-modules
  foreach(url_modules(id), function funp)
  {
    string of = id->not_query;
    id->not_query = file;

    TRACE_ENTER("URL module", funp);
    LOCK(funp);
    tmp=funp( id, file );
    UNLOCK();

    if(mappingp( tmp )) {
      id->not_query = of;
      TRACE_LEAVE("");
      TRACE_LEAVE("said 'No thanks'");
      return 0;
    }
    if(objectp( tmp ))
    {
      file = id->not_query;

      array err;
      nest ++;
      TRACE_LEAVE("Recursing");
      err = catch {
        if( nest < 20 )
          tmp = (id->conf || this_object())->stat_file( file, id );
        else
          error("Too deep recursion in roxen::stat_file() while mapping "
                +file+".\n");
      };
      nest = 0;
      if(err)
        throw(err);
      TRACE_LEAVE("");
      TRACE_LEAVE("Returning data");
      return tmp;
    }
    TRACE_LEAVE("");
    id->not_query = of;
  }
#endif
    
  // Map location-modules.
  foreach(location_modules(id), tmp)
  {
    loc = tmp[0];
    if((file == loc) || ((file+"/")==loc))
    {
      TRACE_ENTER("Location module", tmp[1]);
      TRACE_LEAVE("Exact match");
      TRACE_LEAVE("");
      return ({ 0775, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
    }
    if(!search(file, loc)) 
    {
      TRACE_ENTER("Location module", tmp[1]);
#ifdef MODULE_LEVEL_SECURITY
      if(check_security(tmp[1], id)) {
        TRACE_LEAVE("");
        TRACE_LEAVE("Permission denied");
        continue;
      }
#endif
      if(s=function_object(tmp[1])->stat_file(file[strlen(loc)..], id))
      {
        TRACE_LEAVE("");
        TRACE_LEAVE("Stat ok");
        return s;
      }
      TRACE_LEAVE("");
    }
  }
  TRACE_LEAVE("Returning 'no such file'");
}

//!
class StringFile
{
  string data;
  int offset;

  //!
  string read(int nbytes)
  {
    if(!nbytes)
    {
      offset = strlen(data);
      return data;
    }
    string d = data[offset..offset+nbytes-1];
    offset += strlen(d);
    return d;
  }

  //!
  void write(mixed ... args)
  {
    throw( ({ "File not open for write", backtrace() }) );
  }

  //!
  void seek(int to)
  {
    offset = to;
  }

  //!
  void create(string d)
  {
    data = d;
  }

}

// this is not as trivial as it sounds. Consider gtext. :-)
public array open_file(string fname, string mode, object id)
{
  object oc = id->conf;
  string oq = id->not_query;
  function funp;
  mixed file;

  id->not_query = fname;
  foreach(oc->first_modules(), funp)
    if(file = funp( id )) 
      break;
    else if(id->conf != oc) 
    {
      if(!id->conf->inited) { id->conf->enable_all_modules(); }
      id->not_query = fname;
      return open_file(fname, mode,id);
    }
  fname = id->not_query;

  if(search(mode, "R")!=-1) //  raw (as in not parsed..)
  {
    string f;
    mode -= "R";
    if(f = real_file(fname, id))
    {
      //      report_debug("opening "+fname+" in raw mode.\n");
      return ({ open(f, mode), ([]) });
    }
//     return ({ 0, (["error":302]) });
  }

  if(mode=="r")
  {
    if(!file)
    {
      file = oc->get_file( id );
      if(!file) {
        foreach(oc->last_modules(), funp) if(file = funp( id ))
          break;
        if (file == 1) {
          // Recurse.
          return open_file(id->not_query, mode, id);
        }
      }
    }

    if(!mappingp(file))
    {
      if(!id->misc->error_request) {
        file = caudium->http_error->process_error (id);
        id->not_query = oq;
        return ({ 0, file });
      }
      return ({ 0, 0 });
    }

    if(file->data) 
    {
      file->file = StringFile(file->data);
      m_delete(file, "data");
    } 
    id->not_query = oq;
    return ({ file->file, file });
  }
  id->not_query = oq;
  return ({ 0,(["error":501,"data":"Not implemented"]) });
}

public mapping(string:array(mixed)) find_dir_stat(string file, object id)
{
  string loc;
  mapping(string:array(mixed)) dir = ([]);
  mixed d, tmp;

  file=replace(file, "//", "/");
  
  if(file[0] != '/')
    file = "/" + file;

  // FIXME: Should I append a "/" to file if missing?

  TRACE_ENTER("Request for directory and stat's \""+file+"\"", 0);

#ifdef URL_MODULES
#ifdef THREADS
  object key;
#endif
  // Map URL-modules
  foreach(url_modules(id), function funp)
  {
    string of = id->not_query;
    id->not_query = file;
    LOCK(funp);
    TRACE_ENTER("URL Module", funp);
    tmp=funp( id, file );
    UNLOCK();

    if(mappingp( tmp ))
    {
      id->not_query=of;
#ifdef MODULE_DEBUG
      roxen_perror(sprintf("conf->find_dir_stat(\"%s\"): url_module returned mapping:%O\n", 
                           file, tmp));
#endif /* MODULE_DEBUG */
      TRACE_LEAVE("URL Module returned mapping");
      TRACE_LEAVE("Empty directory");
      return 0;
    }
    if(objectp( tmp ))
    {
      array err;
      nest ++;
      
      file = id->not_query;
      err = catch {
        if( nest < 20 )
          tmp = (id->conf || this_object())->find_dir_stat( file, id );
        else {
          TRACE_LEAVE("Too deep recursion");
          error("Too deep recursion in roxen::find_dir_stat() while mapping "
                +file+".\n");
        }
      };
      nest = 0;
      if(err)
        throw(err);
#ifdef MODULE_DEBUG
      roxen_perror(sprintf("conf->find_dir_stat(\"%s\"): url_module returned object:\n", 
                           file));
#endif /* MODULE_DEBUG */
      TRACE_LEAVE("URL Module returned object");
      TRACE_LEAVE("Returning it");
      return tmp; // FIXME: Return 0 instead?
    }
    id->not_query=of;
    TRACE_LEAVE("");
  }
#endif /* URL_MODULES */

  foreach(location_modules(id), tmp)
  {
    loc = tmp[0];

    TRACE_ENTER("Trying location module mounted on "+loc, 0);
    /* Note that only new entries are added. */
    if(!search(file, loc))
    {
      /* file == loc + subpath */
#ifdef MODULE_LEVEL_SECURITY
      if(check_security(tmp[1], id)) continue;
#endif
      object c = function_object(tmp[1]);
      string f = file[strlen(loc)..];
      if (c->find_dir_stat) {
        TRACE_ENTER("Has find_dir_stat()", 0);
        if (d = c->find_dir_stat(f, id)) {
          TRACE_ENTER("find_dir_stat() returned mapping", 0);
          dir = d | dir;
          TRACE_LEAVE("");
        }
        TRACE_LEAVE("");
      } else if(d = c->find_dir(f, id)) {
        TRACE_ENTER("find_dir() returned array", 0);
        dir = mkmapping(d, Array.map(d, lambda(string f, string base,
                                               object c, object id) {
                                          return(c->stat_file(base + f, id));
                                        }, f, c, id)) | dir;
        TRACE_LEAVE("");
      }
    } else if(search(loc, file)==0 && loc[strlen(file)-1]=='/' &&
              (loc[0]==loc[-1]) && loc[-1]=='/' &&
              (function_object(tmp[1])->stat_file(".", id))) {
      /* loc == file + "/" + subpath + "/"
       * and stat_file(".") returns non-zero.
       */
      TRACE_ENTER("file is on the path to the mountpoint", 0);
      loc=loc[strlen(file)..];
      sscanf(loc, "%s/", loc);
      if (!dir[loc]) {
        dir[loc] = ({ 0775, -3, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
      }
      TRACE_LEAVE("");
    }
    TRACE_LEAVE("");
  }
  if(sizeof(dir))
    return dir;
}


// Access a virtual file?
public array|string access(string file, object id)
{
  string loc;
  array s, tmp;
  
  file=replace(file, "//", "/"); // "//" is really "/" here...
    
  // Map location-modules.
  foreach(location_modules(id), tmp)
  {
    loc = tmp[0];
    if((file+"/")==loc)
      return file += "/";
    if(!search(file, loc)) 
    {
#ifdef MODULE_LEVEL_SECURITY
      if(check_security(tmp[1], id)) continue;
#endif
      if(s=function_object(tmp[1])->access(file[strlen(loc)..], id))
        return s;
    }
  }
}

//! Return the @b{real@} filename of a virtual file, if any.
//!
//! @param file
//!  Path to the @b{virtual@} file.
//!
//! @param id
//!  The request object
//!
//! @returns
//!  The real file corresponding to the virtual one.
public string real_file(string file, object id)
{
  string loc;
  string s;
  array tmp;
  file=replace(file, "//", "/"); // "//" is really "/" here...
    
  if(!id) error("No id passed to real_file");

  // Map location-modules.
  foreach(location_modules(id), tmp)
  {
    loc = tmp[0];
    if(!search(file, loc)) 
    {
#ifdef MODULE_LEVEL_SECURITY
      if(check_security(tmp[1], id)) continue;
#endif
      // FIXME: NOTE: Limits filename length to 1000000 bytes.
      //  /grubba 1997-10-03
      if(s=function_object(tmp[1])->real_file(file[strlen(loc)..1000000], id))
        return s;
    }
  }
}

//!  Convenience function used in quite a lot of modules. Tries to read a file
//!  into memory, and then returns the resulting string. Note that a 'file' 
//!  can be a CGI script, which will executed, resulting in a horrible delay.
//! @param s
//!  The file to read.
//! @param id
//!  The Caudium Object Id
//! @param status
//!  Ask the function to return 1 if file exist or 0 if it doesn't.
//! @param nocache
//!  Set to 1 if you don't want to cache or use the caudium cache for this
//!  access.
//! @returns
//!  A string with the content of file or int if you ask a status of the file
public mixed try_get_file(string s, object id, int|void status, int|void nocache)
{
  string res, q;
  object fake_id;
  mapping m;


  if(objectp(id)) {
    // id->misc->common makes it possible to pass information to
    // the originating request.
    if ( !id->misc )
      id->misc = ([]);
    if ( !id->misc->common )
      id->misc->common = ([]);

    fake_id = id->clone_me();

    fake_id->misc->common = id->misc->common;
  } else
    error("No ID passed to 'try_get_file'\n");

  if(!id->pragma["no-cache"] && !nocache && !id->auth)
    if(res = cache_lookup("file:"+id->site_id, s))
      return res;

  if(sscanf(s, "%s?%s", s, q))
  {
    Caudium.parse_query_string(q, fake_id->variables, fake_id->empty_variables);
    foreach(indices(fake_id->empty_variables), string varname)
      fake_id->variables[varname] = "";
    fake_id->query=q;
  }

  fake_id->raw_url=s;
  fake_id->not_query=s;
  fake_id->misc->internal_get=1;

  if(!(m = get_file(fake_id)))
  {
    fake_id->end();
    return 0;
  }
  fake_id->end();
  
  if (!(< 0, 200, 201, 202, 203 >)[m->error]) return 0;
  
  if(status) return 1;

#ifdef COMPAT
  if(m["string"])  res = m["string"]; // Compability..
  else
#endif
    if(m->data) res = m->data;
    else res="";
  m->data = 0;
  
  if(m->file)
  {
    res += m->file->read();
    destruct(m->file);
    m->file = 0;
  }
  
  if(m->raw)
  {
    res -= "\r";
    if(!sscanf(res, "%*s\n\n%s", res))
      sscanf(res, "%*s\n%s", res);
  }
  cache_set("file:"+id->site_id, s, res);
  return res;
}

//!  Is 'what' a file in ou virtual filesystem ?
//! @param what
//!  The file to test
//! @param id
//!  The Caudium Object Id
//! @returns
//!  1 if this a file. 0 otherwise.
public int is_file(string what, object id)
{
  return !!stat_file(what, id);
}

//! A quick hack to generate correct protocol references
protected string make_proto_name(string p)
{
  // Note these are only the protocols that
  // Caudium can directly use
  multiset(string) known_protos = (<"http", "https", "ssl3">);
  multiset(string) telnet_protos = (<"smtp", "pop", "pop2", "pop3", "imap", "tetris">);
    
  if (known_protos[p])
    return p;
  
  if (telnet_protos[p])
    return "telnet";

  foreach(indices(known_protos), string proto) {
    string ret;
  
    ret = String.common_prefix(({proto, p}));
    if (ret && ret != "")
      return ret;
  }
    
  foreach(indices(telnet_protos), string proto) {
    string ret;
  
    ret = String.common_prefix(({proto, p}));
    if (ret && ret != "")
      return "telnet";
  }
    
  return "about";
}

//!
string MKPORTKEY(array(string) p)
{
  if (sizeof(p[3])) {
    return(sprintf("%s://%s:%s/(%s)",
                   make_proto_name(p[1]), p[2], (string)p[0],
                   replace(p[3], ({"\n", "\r"}), ({ " ", " " }))));
  } else {
    return(sprintf("%s://%s:%s/",
                   make_proto_name(p[1]), p[2], (string)p[0]));
  }
}

//! Caudium opened ports.
mapping(string:object) server_ports = ([]);

int ports_changed = 1;

//!
void start(int num, void|object conf_id, array|void args)
{
  // Note: This may be run before uid:gid is changed.

  string server_name = query_name();
  array port;
  int err=0;
  mapping new=([]);
#ifdef ENABLE_RAM_CACHE
  if(!datacache)
    datacache = DataCache(query( "data_cache_size" ) * 1024,
                          query( "data_cache_file_max_size" ) * 1024,
                          query( "data_cache_gc_cleanup") / 100.0);
  else
    datacache->init_from_variables(query( "data_cache_size" ) * 1024,
                                   query( "data_cache_file_max_size" ) * 1024,
                                   query( "data_cache_gc_cleanup") / 100.0);
#endif

#if 0
  // Doesn't seem to be set correctly.
  //  /grubba 1998-05-18
  if (!ports_changed) {
    return;
  }
#endif /* 0 */

  ports_changed = 0;

  // First find out if we have any new ports.
  mapping(string:array(string)) new_ports = ([]);

  //Make it possible to set variables from start.
  if(args)
    foreach(args, string variable)
    {
      string name, c, v;
      if(sscanf(variable, "%s:%s=%s", name, c, v) == 3)
        if(server_name == replace(name,"_"," "))
          if(variables[c])
            variables[c][VAR_VALUE]=compile_string(
                                                   "mixed f(){ return"+v+";}")()->f();
          else
            perror("Unknown variable: "+c+"\n");
    }

  foreach(query("Ports"), port) {
    if ((< "ssl", "ssleay" >)[port[1]]) {
      // Obsolete versions of the SSL protocol.
      report_warning(sprintf("%s: Obsolete SSL protocol-module \"%s\".\n"
                             "Converted to SSL3.\n",
                             server_name, port[1]));
      // Note: Change in-place.
      port[1] = "ssl3";
      // FIXME: Should probably mark node as changed.
    }
    if ((< "http2" >)[port[1]]) {
      // http2 is old and unused protocol.
      report_warning("%s: Obsolete HTTP2 protocol-module \"%s\".\n"
                     "Converted to HTTP.\n",server_name, port[1]);
      // Note: change in-place
      port[1] = "http";
    }
    string key = MKPORTKEY(port);
    if (!server_ports[key]) {
      report_notice(sprintf("%s: New port: %s\n", server_name, key));
      new_ports[key] = port;
    } else {
      // This is needed not to delete old unchanged ports.
      new_ports[key] = 0;
    }
  }

  // Then disable the old ones that are no more.
  foreach(indices(server_ports), string key) {
    if (zero_type(new_ports[key])) {
      report_notice(sprintf("%s: Disabling port: %s...\n", server_name, key));
      object o = server_ports[key];
      m_delete(server_ports, key);
      mixed err;
      if (err = catch{
        destruct(o);
      }) {
        report_warning(sprintf("%s: Error disabling port: %s:\n"
                               "%s\n",
                               server_name, key, describe_backtrace(err)));
      }
      o = 0;    // Be sure that there are no references left...
    }
  }

  // Now we can create the new ports.
  roxen_perror(sprintf("Opening ports for %s... \n", server_name));
  foreach(indices(new_ports), string key) {
    port = new_ports[key];
    if (port) {
      array old = port;
      mixed erro;
      erro = catch {
        program requestprogram = (program)(getcwd()+"/protocols/"+port[1]);
        function rp;
        array tmp;
        if(!requestprogram) {
          report_error(sprintf("%s: No request program for %s\n",
                               server_name, port[1]));
          continue;
        }
        if(rp = requestprogram()->real_port)
          if(tmp = rp(port, this_object()))
            port = tmp;

        object privs;
        if(port[0] < 1024)
          privs = Privs("Opening listen port below 1024");

        object o;
        if(o=create_listen_socket(port[0], this_object(), port[2],
                                  requestprogram, port)) {
          report_notice(sprintf("%s: Opening port: %s\n", server_name, key));
          server_ports[key] = o;
        } else {
          report_error(sprintf("%s: The port %s could not be opened\n",
                               server_name, key));
        }
        if (privs) {
          destruct(privs);  // Paranoia.
        }
      };
      if (erro) {
        report_error(sprintf("%s: Failed to open port %s:\n"
                             "%s\n", server_name, key,
                             (stringp(erro)?erro:describe_backtrace(erro))));
      }
    }
  }
  if (sizeof(query("Ports")) && !sizeof(server_ports)) {
    report_error("No ports available for "+name+"\n"
                 "Tried:\n"
                 "Port  Protocol   IP-Number \n"
                 "---------------------------\n"
                 + Array.map(query("Ports"),
                             lambda(array p) {
                               return sprintf("%5d %-10s %-20s\n", @p);
                             })*"");
  }
  logger->parse_log_formats(QUERY(LogFormat));
  // We are not automatically opening the logfile until it's needed
  // to save file descriptors.
  // init_log_file();
  log_function = 0;
}



//! Save this configuration. If @[all] is present, save all the
//! configuration  global variables as well, otherwise only all module
//! variables.
//!
//! @param all
//!  If present, all the global variables are saved, only the module ones
//!  otherwise.
void save(int|void all)
{
  mapping mod;
  if(all)
  {
    store("spider.lpc#0", variables, 0, this);
    start(2);
  }
  
  foreach(values(modules), mod)
  {
    if(mod->enabled)
    {
      store(mod->sname+"#0", mod->master->query(), 0, this);
      mod->enabled->start(2, this);
    } else if(mod->copies) {
      int i;
      foreach(indices(mod->copies), i)
      {
        store(mod->sname+"#"+i, mod->copies[i]->query(), 0, this);
        mod->copies[i]->start(2, this);
      }
    }
  }
  invalidate_cache();
}

//! Save all variables in _one_ module.
int save_one( object o )
{
  mapping mod;
  if(!o) 
  {
    store("spider#0", variables, 0, this);
    start(2);
    return 1;
  }
  foreach(values(modules), mod)
  {
    if( mod->enabled == o)
    {
      store(mod->sname+"#0", o->query(), 0, this);
      o->start(2, this);
      invalidate_cache();
      return 1;
    } else if(mod->copies) {
      int i;
      foreach(indices(mod->copies), i)
      {
        if(mod->copies[i] == o)
        {
          store(mod->sname+"#"+i, o->query(), 0, this);
          o->start(2, this);
          invalidate_cache();
          return 1;
        }
      }
    }
  }
}

mapping _hooks=([ ]);

//!
void hooks_for( string modname, object mod )
{
  array hook;
  if(_hooks[modname])
  {
#ifdef MODULE_DEBUG
    perror("Module hooks...");
#endif
    foreach(_hooks[modname], hook)
      hook[0]( @hook[1], mod );
  }
}

//! enable a module in this configuration
object enable_module( string modname )
{
  string id;
  mapping module;
  mapping enabled_modules;
  caudium->current_configuration = this_object();
  modname = replace(modname, ".lpc#","#");
  
  sscanf(modname, "%s#%s", modname, id );

  module = modules[ modname ];
  if(!module)
  {
    load_module(modname);
    module = modules[ modname ];
  }

#if constant(gethrtime)
  int start_time = gethrtime();
#endif
  if (!module) {
    return 0;
  }

  object me;
  int pr;
  array err;

#ifdef MODULE_DEBUG
  perror("Enabling "+module->name+" # "+id+" ... ");
#endif

  if(module->copies)
  {
    if (err = catch(me = module["program"](this_object()))) {
      report_error("Couldn't clone module \"" + module->name + "\"\n" +
                   describe_backtrace(err));
      if (module->copies[id]) {
#ifdef MODULE_DEBUG
        perror("Keeping old copy\n");
#endif
      }
      return(module->copies[id]);
    }
    if(module->copies[id]) {
#ifdef MODULE_DEBUG
      perror("Disabling old copy ... ");
#endif
      if (err = catch{
        module->copies[id]->stop();
      }) {
        report_error("Error during disabling of module \"" + module->name +
                     "\"\n" + describe_backtrace(err));
      }
      destruct(module->copies[id]);
    }
  } else {
    if(objectp(module->master)) {
      me = module->master;
    } else {
      if (err = catch(me = module["program"](this_object()))) {
        report_error("Couldn't clone module \"" + module->name + "\"\n" +
                     describe_backtrace(err));
        return(0);
      }
    }
  }

  me->set_configuration(this_object());
#ifdef MODULE_DEBUG
  //    perror("Initializing ");
#endif
  if (module->type & (MODULE_LOCATION | MODULE_EXTENSION |
                      MODULE_FILE_EXTENSION | MODULE_LOGGER |
                      MODULE_URL | MODULE_LAST | MODULE_PROVIDER |
                      MODULE_FILTER | MODULE_PARSER | MODULE_FIRST |
                      MODULE_PRECACHE | MODULE_ERROR))
  {
    me->defvar("_priority", 5, "Priority", TYPE_INT_LIST,
               "The priority of the module. "
       	       "This allow to call the modules of a same type in a defined "
               "order. 9 is highest priority (called first) and "
               "0 is lowest priority (called last)."
               " Modules with the same priority can be assumed to be"
               " called in random order."
               "<p>You have to restart Caudium to ensure that the new"
               " priority is applied.",
               ({ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }));
      
    if(!(module->type & (MODULE_LOGGER | MODULE_PROVIDER | MODULE_PRECACHE)))
    {
      if(!(module->type & MODULE_PROXY))
      {
        me->defvar("_sec_group", "user", "Security: Realm", TYPE_STRING,
                   "The realm to use when requesting password from the "
                   "client. Usually used as an informative message to the "
                   "user.");
        me->defvar("_seclvl",  0, "Security: Security level", TYPE_INT, 
                   "The modules security level is used to determine if a "
                   " request should be handled by the module."
                   "\n<p><h2>Security level vs Trust level</h2>"
                   " Each module has a configurable <i>security level</i>."
                   " Each request has an assigned trust level. Higher"
                   " <i>trust levels</i> grants access to modules with higher"
                   " <i>security levels</i>."
                   "\n<p><h2>Definitions</h2><ul>"
                   " <li>A requests initial Trust level is infinitely high."
                   " <li> A request will only be handled by a module if its"
                   "     <i>trust level</i> is higher or equal to the"
                   "     <i>security level</i> of the module."
                   " <li> Each time the request is handled by a module the"
                   "     <i>trust level</i> of the module will be set to the"
                   "      lower of its <i>trust level</i> and the modules"
                   "     <i>security level</i>."
                   " </ul>"
                   "\n<p><h2>Example</h2>"
                   " Modules:<ul>"
                   " <li>  User filesystem, <i>security level</i> 1"
                   " <li>  Filesystem module, <i>security level</i> 3"
                   " <li>  CGI module, <i>security level</i> 2"
                   " </ul>"
                   "\n<p>A request handled by \"User filesystem\" is assigned"
                   " a <i>trust level</i> of one after the <i>security"
                   " level</i> of that module. That request can then not be"
                   " handled by the \"CGI module\" since that module has a"
                   " higher <i>security level</i> than the requests trust"
                   " level."
                   "\n<p>On the other hand, a request handled by the the"
                   " \"Filsystem module\" could later be handled by the"
                   " \"CGI module\".");

        me->defvar("_seclevels", "", "Security: Patterns", TYPE_TEXT_FIELD,
                   "This is the 'security level=value' list.<br>"
                   "Each security level can be any or more from this list:"
                   "<hr noshade>"
                   "accept ip=<i>IP</i>/<i>bits</i><br>"
                   "accept ip=<i>IP</i>:<i>mask</i><br>"
                   "accept ip=<i>pattern</i><br>"
                   "accept user=<i>username</i>,...<br>"
                   "accept group=<i>groupname</i>,...<br>"
                   "allow ip=<i>IP</i>/<i>bits</i><br>"
                   "allow ip=<i>IP</i>:<i>mask</i><br>"
                   "allow ip=<i>pattern</i><br>"
                   "allow user=<i>username</i>,...<br>"
                   "deny ip=<i>IP</i>/<i>bits</i><br>"
                   "deny ip=<i>IP</i>:<i>mask</i><br>"
                   "deny ip=<i>pattern</i><br>"
                   "secuname=<i>username:level</i>,...<br>"
                   "<hr noshade>"
                   "In patterns: * matches one or more characters, "
                   "and ? matches one character.<p>"
                   "In username: 'any' stands for any valid account "
                   "(from .htaccess or an authentication module.) "
                   "<p>allow and deny are short-circuit rules."
                   "<p>The default (used when _no_ "
                   "entries are present) is 'allow ip=*', allowing"
                   " everyone to access the module");
    
      } else {
        me->definvisvar("_seclvl", -10, TYPE_INT); /* A very low one */
    
        me->defvar("_sec_group", "user", "Proxy Security: Realm", TYPE_STRING,
                   "The realm to use when requesting password from the "
                   "client. Usually used as an informative message to the "
                   "user.");
        me->defvar("_seclevels", "", "Proxy security: Patterns",
                   TYPE_TEXT_FIELD,
                   "This is the 'security level=value' list.<br>"
                   "Each security level can be any or more from this list:"
                   "<hr noshade>"
                   "accept ip=<i>IP</i>/<i>bits</i><br>"
                   "accept ip=<i>IP</i>:<i>mask</i><br>"
                   "accept ip=<i>pattern</i><br>"
                   "accept user=<i>username</i>,...<br>"
                   "allow ip=<i>IP</i>/<i>bits</i><br>"
                   "allow ip=<i>IP</i>:<i>mask</i><br>"
                   "allow ip=<i>pattern</i><br>"
                   "allow user=<i>username</i>,...<br>"
                   "deny ip=<i>IP</i>/<i>bits</i><br>"
                   "deny ip=<i>IP</i>:<i>mask</i><br>"
                   "deny ip=<i>pattern</i><br>"
                   "secuname=<i>username:level</i>,...<br>"
                   "secgname=<i>groupname:level</i>,...<br>"
                   "<hr noshade>"
                   "In patterns: * matches one or more characters, "
                   "and ? matches one character.<p>"
                   "In username: 'any' stands for any valid account "
                   "(from .htaccess or an authentication module.) "
                   "<p>allow and deny are short-circuit rules."
                   "<p>The default (used when _no_ "
                   "entries are present) is 'deny ip=*', allowing"
                   " everyone to access the module");
      }
    }
  } else {
    me->defvar("_priority", 0, "", TYPE_INT, "", 0, 1);
  }
  
  me->defvar("_comment", "", " Comment", TYPE_TEXT_FIELD|VAR_MORE,
             "An optional comment. This has no effect on the module, it "
             "is only a text field for comments that the administrator "
             "might have (why the module are here, etc.)");

  me->defvar("_name", "", " Module name", TYPE_STRING|VAR_MORE,
             "An optional name. Set to something to remind you what "
             "the module really does.");
  
  me->setvars(retrieve(modname + "#" + id, this));

  if(module->copies)
    module->copies[(int)id] = me;
  else
    module->enabled = me;

  otomod[ me ] = modname;
      
  if((me->start) && (err = catch{
    me->start(0, this);
  })) {
    report_error("Error while initiating module copy of " +
                 module->name + "\n" + describe_backtrace(err));

    /* Clean up some broken references to this module. */
    m_delete(otomod, me);

    if(module->copies)
      m_delete(module->copies, (int)id);
    else
      m_delete(module, "enabled");
    
    destruct(me);
    
    return 0;
  }
    
  if (err = catch(pr = me->query("_priority"))) {
    report_error("Error while initiating module copy of " +
                 module->name + "\n" + describe_backtrace(err));
    pr = 3;
  }

  api_module_cache |= me->api_functions();

  if(module->type & MODULE_EXTENSION) {
    if (err = catch {
      array arr = me->query_extensions();
      if (arrayp(arr)) {
        string foo;
        foreach( arr, foo )
          if(pri[pr]->extension_modules[ foo ])
            pri[pr]->extension_modules[foo] += ({ me });
          else
            pri[pr]->extension_modules[foo] = ({ me });
      }
    }) {
      report_error("Error while initiating module copy of " +
                   module->name + "\n" + describe_backtrace(err));
    }
  }   

  if(module->type & MODULE_FILE_EXTENSION) {
    if (err = catch {
      array arr = me->query_file_extensions();
      if (arrayp(arr)) {
        string foo;
        foreach( me->query_file_extensions(), foo )
          if(pri[pr]->file_extension_modules[foo] ) 
            pri[pr]->file_extension_modules[foo]+=({me});
          else
            pri[pr]->file_extension_modules[foo]=({me});
      }
    }) {
      report_error("Error while initiating module copy of " +
                   module->name + "\n" + describe_backtrace(err));
    }
  }

  if(module->type & MODULE_PROVIDER) {
    if (err = catch {
      mixed provs = me->query_provides();
      if(stringp(provs))  provs = (< provs >);
      else if(arrayp(provs))  provs = mkmultiset(provs);
      if (multisetp(provs)) pri[pr]->provider_modules [ me ] = provs;
    }) {
      report_error("Error while initiating module copy of " +
                   module->name + "\n" + describe_backtrace(err));
    }
  }
    
  if(module->type & MODULE_TYPES)
  {
    types_module = me;
    types_fun = me->type_from_filename;
  }
  
  if((module->type & MODULE_MAIN_PARSER))
  {
    parse_module = me;
    if (_toparse_modules) {
      Array.map(_toparse_modules,
                lambda(object o, object me, mapping module)
                {
                  array err;
                  if (err = catch {
                    me->add_parse_module(o);
                  }) {
                    report_error("Error while initiating module copy of " +
                                 module->name + "\n" +
                                 describe_backtrace(err));
                  }
                }, me, module);
    }
  }

  if(module->type & MODULE_PARSER)
  {
    if(parse_module) {
      if (err = catch {
        parse_module->add_parse_module( me );
      }) {
        report_error("Error while initiating module copy of " +
                     module->name + "\n" + describe_backtrace(err));
      }
    }
    _toparse_modules += ({ me });
  }

  if(module->type & MODULE_AUTH)
  {
    auth_module = me;
    auth_fun = me->authenticate;
  }

  if(module->type & MODULE_DIRECTORIES)
    dir_module = me;

  if(module->type & MODULE_LOCATION)
    pri[pr]->location_modules += ({ me });

  if(module->type & MODULE_LOGGER) 
    pri[pr]->logger_modules += ({ me });

  if(module->type & MODULE_URL)
    pri[pr]->url_modules += ({ me });

  if(module->type & MODULE_LAST)
    pri[pr]->last_modules += ({ me });

  if(module->type & MODULE_FILTER)
    pri[pr]->filter_modules += ({ me });

  if(module->type & MODULE_FIRST) 
    pri[pr]->first_modules += ({ me });

  if(module->type & MODULE_PRECACHE) 
    pri[pr]->precache_modules += ({ me });
  
  if(module->type & MODULE_ERROR)
    pri[pr]->error_modules += ({ me });
  
  hooks_for(module->sname+"#"+id, me);
      
  enabled_modules = retrieve("EnabledModules", this);

  if(!enabled_modules[modname+"#"+id])
  {
#ifdef MODULE_DEBUG
    perror("New module...");
#endif
    enabled_modules[modname+"#"+id] = 1;
    store( "EnabledModules", enabled_modules, 1, this);
  }
  invalidate_cache();
#ifdef MODULE_DEBUG
#if constant(gethrtime)
  perror(" Done (%3.3f seconds).\n", (gethrtime()-start_time)/1000000.0);
#else
  perror(" Done.\n");
#endif
#endif
  return me;
}

//! Called from the configuration interface.
string check_variable(string name, string value)
{
 werror("check_variable(%O, %O)\n", name, value);
  switch(name)
  {
      case "AdminUsers":
        array x = value/"\n";
        foreach(x;int i; string j)
          x[i] = String.trim_whites(j);
          x-=({""});
          if(value != (x*"\n"))
            return "User list must not contain extra spaces or blank lines.";
        return 0;
      case "Ports":
        ports_changed=1; 
        return 0;
      case "MyWorldLocation":
        if(strlen(value)<7 || value[-1] != '/' ||
           !(sscanf(value,"%*s://%*s/")==2))
          return "The URL should follow this format: protocol://computer[:port]/";
        return 0;
  }
}


// This is used to update the server-global and module variables
// between Roxen releases. It enables the poor roxen administrator to
// reuse the configuration file from a previous release. without any
// fuss. Configuration files from Roxen 1.0�11 pre 11 and earlier
// are not differentiated, but since that release is quite old already
// when I write this, that is not really a problem....


#define perr(X) do { report += X; perror(X); } while(0)

//! Used to hide some variables when logging is not enabled.
int log_is_not_enabled()
{
  return !QUERY(Log);
}

//! Used to hide the default charset variable
int default_charset_not_used()
{
  return !QUERY(set_default_charset);
}

//!
int disable_module( string modname )
{
  mapping module;
  mapping enabled_modules;
  object me;
  int pr;
  int id;

  sscanf(modname, "%s#%d", modname, id );

  module = modules[ modname ];

  if(!module) 
  {
    report_error("Failed to disable module\n"
                 "No module by that name: \""+modname+"\".\n");
    return 0;
  }

  if(module->copies)
  {
    me = module->copies[id];
    m_delete(module->copies, id);
    if(!sizeof(module->copies))
      unload_module(modname);
  } else {
    me = module->enabled || module->master;
    module->enabled=module->master = 0;
    unload_module(modname);
  }

  invalidate_cache();

  if(!me)
  {
    report_error("Failed to Disable "+module->name+" # "+id+"\n");
    return 0;
  }

  if(me->stop) me->stop();

#ifdef MODULE_DEBUG
  perror("Disabling "+module->name+" # "+id+"\n");
#endif

  if(module["type"] & MODULE_EXTENSION)
  {
    string foo;
    for(pr=0; pr<10; pr++)
      foreach( indices (pri[pr]->extension_modules), foo )
        pri[pr]->extension_modules[ foo ]-= ({ me });
  }

  if(module["type"] & MODULE_FILE_EXTENSION)
  {
    string foo;
    for(pr=0; pr<10; pr++)
      foreach( indices (pri[pr]->file_extension_modules), foo )
        pri[pr]->file_extension_modules[foo]-=({me});
  }

  if(module->type & MODULE_PROVIDER) {
    for(pr=0; pr<10; pr++)
      m_delete(pri[pr]->provider_modules, me);
  }
  if(module->type & MODULE_PRECACHE) {
    for(pr=0; pr<10; pr++)
      pri[pr]->precache_modules -= ({ me });
  }
  
  if(module["type"] & MODULE_TYPES)
  {
    types_module = 0;
    types_fun = 0;
  }

  if(module->type & MODULE_MAIN_PARSER)
    parse_module = 0;

  if(module->type & MODULE_PARSER)
  {
    if(parse_module)
      parse_module->remove_parse_module( me );
    _toparse_modules -= ({ me, 0 });
  }

  if( module->type & MODULE_AUTH )
  {
    auth_module = 0;
    auth_fun = 0;
  }

  if( module->type & MODULE_DIRECTORIES )
    dir_module = 0;


  if( module->type & MODULE_LOCATION )
    for(pr=0; pr<10; pr++)
      pri[pr]->location_modules -= ({ me });

  if( module->type & MODULE_URL )
    for(pr=0; pr<10; pr++)
      pri[pr]->url_modules -= ({ me });

  if( module->type & MODULE_LAST )
    for(pr=0; pr<10; pr++)
      pri[pr]->last_modules -= ({ me });

  if( module->type & MODULE_FILTER )
    for(pr=0; pr<10; pr++)
      pri[pr]->filter_modules -= ({ me });

  if( module->type & MODULE_FIRST ) {
    for(pr=0; pr<10; pr++)
      pri[pr]->first_modules -= ({ me });
  }

  if( module->type & MODULE_LOGGER )
    for(pr=0; pr<10; pr++)
      pri[pr]->logger_modules -= ({ me });

  if( module->type & MODULE_ERROR )
    for(pr=0; pr<10; pr++)
      pri[pr]->error_modules -= ({ me });

  enabled_modules=retrieve("EnabledModules", this);

  if(enabled_modules[modname+"#"+id])
  {
    m_delete( enabled_modules, modname + "#" + id );
    store( "EnabledModules",enabled_modules, 1, this);
  }
  destruct(me);
  return 1;
}

//! find a module
//! @param name
//!   the name of the module to find, where name is the base filename (foo if the file is called foo.pike).
//! @returns
//!  the module, or the first of multiple modules, or zero if the module does not exist.
object|string find_module(string name)
{
  int id;
  sscanf(name, "%s#%d", name, id);
  if(modules[name])
  {
    if(modules[name]->copies)
      return modules[name]->copies[id];
    else 
      if(modules[name]->enabled)
        return modules[name]->enabled;
  }
  return 0;
}

//!
void register_module_load_hook( string modname, function fun, mixed ... args )
{
  object o;
#ifdef MODULE_DEBUG
  perror("Registering a hook for the module "+modname+"\n");
#endif
  if(o=find_module(modname))
  {
#ifdef MODULE_DEBUG
    perror("Already there!\n");
#endif
    fun( @args, o );
  } else
    if(!_hooks[modname])
      _hooks[modname] = ({ ({ fun, args }) });
    else
      _hooks[modname] += ({ ({ fun, args }) });
}

//!
int load_module(string module_file)
{
  int foo;
  mixed err;
  array module_data;
  object obj;
  program prog;
#if constant(gethrtime)
  int start_time = gethrtime();
#endif
  // It is not thread-safe to use this.
  caudium->current_configuration = this_object();
#ifdef MODULE_DEBUG
  perror("\nLoading " + module_file + "... ");
#endif
 
#if 0
  if(prog = cache_lookup("modules", module_file)) {
    err = catch {
      obj = prog(this_object());
    };
  } else 
#endif /* 0 */
  {
    object e = ErrorContainer();
    master()->set_inhibit_compile_errors(e);
    err = catch {
      obj = caudium->load_from_dirs(caudium->QUERY(ModuleDirs), module_file,
                                    this_object());
      prog = object_program(obj);
    };
    if(strlen(e->get())) {
      report_error("Failed to compile module "+module_file+":\n"+e->get());
      return 0;
    }
    e->print_warnings("Warnings while compiling module "+module_file+":");
  }

  if (err) {
    report_error("Error while enabling module (" + module_file + "):\n" +
                 describe_backtrace(err) + "\n");
    return(0);
  } else if(!obj) {
    report_error("*** Module load failed: " + module_file + " (not found?)\n");
    return 0;
  }

  if (err = catch (module_data = obj->register_module(this_object()))) {
#ifdef MODULE_DEBUG
    perror("FAILED\n" + describe_backtrace( err ));
#endif
    report_error("Module loaded, but register_module() failed (" 
                 + module_file + ").\n"  +
                 describe_backtrace( err ));
    return 0;
  }

  err = "";
  caudium->somemodules[module_file]=
    ({ module_data[1], module_data[2]+"<p><i>"+
       replace(obj->file_name_and_stuff(),"0<br>", module_file+"<br>")
       +"</i>", module_data[0] });
  if (!arrayp( module_data ))
    err = "Register_module didn't return an array.\n";
  else switch (sizeof( module_data ))
  {
      case 5:
        foo = module_data[4];
        module_data = module_data[0..3];
      case 4:
        if (module_data[3] && !arrayp( module_data[3] ))
          err = "The fourth element of the array register_module returned "
            "(extra_buttons) wasn't an array.\n" + err;
      case 3:
        if (!stringp( module_data[2] ))
          err = "The third element of the array register_module returned "
            "(documentation) wasn't a string.\n" + err;
        if (!stringp( module_data[1] ))
          err = "The second element of the array register_module returned "
            "(name) wasn't a string.\n" + err;
        if (!intp( module_data[0] ))
          err = "The first element of the array register_module returned "
            "(type) wasn't an integer.\n" + err;
        break;

      default:
        err = "The array register_module returned was too small/large. "
          "It should have been three or four elements (type, name, "
          "documentation and extra buttons (optional))\n";
  }
  if (strlen(err))
  {
#ifdef MODULE_DEBUG
    perror("FAILED\n"+err);
#endif
    report_error( "Tried to load module " + module_file + ", but:\n" + err );
    if(obj) destruct( obj );
    return 0;
  } 
    
  if (sizeof(module_data) == 3)
    module_data += ({ 0 }); 

  if(!foo)
  {
    destruct(obj);
    obj=0;
  } else {
    otomod[obj] = module_file;
  }

  if(!modules[ module_file ])
    modules[ module_file ] = ([]);

  mapping tmpp = modules[ module_file ];

  tmpp->type  = module_data[0];
  tmpp->name  = module_data[1];
  tmpp->doc = module_data[2];
  tmpp->extra = module_data[3];
  tmpp->master  = obj;
  tmpp->copies  = (foo ? 0 : (tmpp->copies || ([])));
  tmpp->sname = module_file;
  tmpp["program"] = prog;
      
#ifdef MODULE_DEBUG
#if constant(gethrtime)
  perror(" Done (%3.3f seconds).\n", (gethrtime()-start_time)/1000000.0);
#else
  perror(" Done.\n");
#endif
#endif
#if 0
  cache_set("modules", module_file, modules[module_file]["program"], -1); // Chanhed to store cached module for ever.
#endif /* 0 */
  return 1;
}

//�
int unload_module(string module_file)
{
  mapping module;

  module = modules[ module_file ];

  if(!module) 
    return 0;

  if(objectp(module->master)) 
    destruct(module->master);

  cache_remove("modules", module_file);
  
  m_delete(modules, module_file);

  return 1;
}

//! add a set of modules to this configuration.
//! @param mods
//!   an array of module names to add, where the module name is the base name of the module file, minus any file extensions.
int add_modules (array(string) mods)
{
  foreach (mods, string mod)
    if(!modules[mod] || !modules[mod]->copies && !modules[mod]->master)
      enable_module(mod+"#0");
  if(caudium->root)
    caudium->configuration_interface()->build_root(caudium->root);
}

//!
int port_open(array prt)
{
  return(server_ports[MKPORTKEY(prt)] != 0);
}

//!
string desc()
{
  string res="";
  array (string|int) port;

  if(!sizeof(QUERY(Ports)))
  {
/*    array ips = caudium->configuration_interface()->ip_number_list;*/
/*    if(!ips) caudium->configuration_interface()->init_ip_list;*/
/*    ips = caudium->configuration_interface()->ip_number_list;*/
/*    foreach(ips||({}), string ip)*/
/*    {*/
      
/*    }*/

    array handlers = ({});
    foreach(caudium->configurations, object c)
      if(c->modules["ip-less_hosts"] || c->modules["hostmatch"])
        handlers+=({({Caudium.http_encode_string("/Configurations/"+c->name),
                      strlen(c->query("name"))?c->query("name"):c->name})});

    
    if(sizeof(handlers)==1)
    {
      res = "This server is handled by the ports in <a href=\""+handlers[0][0]+
        "\">"+handlers[0][1]+"</a><br>\n";
    } else if(sizeof(handlers)) {
      res = "This server is handled by the ports in any of the following servers:<br>";
      foreach(handlers, array h)
        res += "<a href=\""+h[0]+"\">"+h[1]+"</a><br>\n";
    } else
      res=("There are no ports configured, and no virtual server seems "
           "to have support for ip-less virtual hosting enabled<br>\n");
  }
  
  foreach(QUERY(Ports), port)
  {
    string prt, prtfile, modprt;
    
    prtfile = port[1] + "://";
    switch(port[1][0..2])
    {
        case "ssl":
          prt = "https://";
          break;
      
        default:
          prt = (modprt = make_proto_name(port[1]))+"://";
    }
    
    if(port[2] && port[2]!="ANY") {
      prt += port[2];
      prtfile += port[2] ;
    } 
#if constant(gethostname)
    else {
      prt += (gethostname()/".")[0] + "." + QUERY(Domain);
      prtfile = modprt ? replace(prt, modprt, port[1]) : prt;
    }
#endif
    prt += ":"+port[0]+"/";
    prtfile += ":" + port[0] + "/";

    if(port_open( port ))
      res += "<font color=darkblue><b>Open:</b></font> <a target=server_view href=\""+prt+"\">"+prtfile+"</a> \n<br>";
    else
      res += "<font color=red><b>Not open:</b> <a target=server_view href=\""+
        prt+"\">"+prtfile+"</a></font> <br>\n";
  }
  return (res+"<font color=darkgreen>Server URL:</font> <a target=server_view "
          "href=\""+query("MyWorldLocation")+"\">"+query("MyWorldLocation")+"</a><p>");
}

// BEGIN SQL

//! The SQL urls 
mapping(string:string) sql_urls = ([]);

//! The SQL Cache
mapping(string|object:mapping|object) sql_cache = ([]);

//!
object sql_cache_get(string what)
{
#ifdef THREADS
#if !constant(this_thread)
  return Sql.Sql( what );
#else
  string key;
#if defined(__MAJOR__) && __MAJOR__ >= 7 
  // Reports has come in that this_thread() might return different
  // objects even if the thread is the same. We avoid this problem by using
  // the textual representation which includes the thread id. Only works
  // in Pike 7.0 where _sprintf is supported.
  key = sprintf("%O\n", this_thread());
#else
  key = this_thread();
#endif
  if(sql_cache[what] && sql_cache[what][key])
    return sql_cache[what][key];
  if(!sql_cache[what])
    sql_cache[what] =  ([ key:Sql.Sql( what ) ]);
  else
    sql_cache[what][ key ] = Sql.Sql( what );
  return sql_cache[what][ key ];
#endif   /* !this_thread */
#else /* !THREADS */
  if(!sql_cache[what])
    sql_cache[what] =  Sql.Sql( what );
  return sql_cache[what];
#endif
}

//! Backend use to do thread safe connect to SQL
//! @seealso
//!  @[SqlDB]
object sql_connect(string db)
{
  if (sql_urls[db]) {
    return(sql_cache_get(sql_urls[db]));
  } else {
    return(sql_cache_get(db));
  }
}

// END SQL

// This is the most likely URL for a virtual server.
private string get_my_url()
{
  string s;
#if constant(gethostname)
  s = (gethostname()/".")[0] + "." + query("Domain");
  s -= "\n";
#else
  s = "localhost";
#endif
  return "http://" + s + "/";
}
#ifdef THREADS
Thread.Mutex enable_modules_mutex = Thread.Mutex();
#define MODULE_LOCK() \
  Thread.MutexKey enable_modules_lock = enable_modules_mutex->lock (2)
#else
#define MODULE_LOCK()
#endif

int inited;

//! Enable all modules
void enable_all_modules()
{
  MODULE_LOCK();
  array err;
  inited = 1;
  if(err = catch { low_enable_all_modules();  })
    report_notice("Error while loading modules in configuration "+
                  name+":\n"+ describe_backtrace(err)+"\n");
  
}

//!
void low_enable_all_modules() {
#if constant(gethrtime)
  int start_time = gethrtime();
#endif
  array modules_to_process=sort(indices(retrieve("EnabledModules",this)));
  string tmp_string;

  logger->parse_log_formats(QUERY(LogFormat));
  // Don't automatically open the log file until it's used.
  //  init_log_file();
  perror("\nEnabling all modules for "+query_name()+"... \n");

#if constant(_compiler_trace)
  // _compiler_trace(1);
#endif /* !constant(_compiler_trace) */
  
  // Always enable the user database module first.
  if(search(modules_to_process, "userdb#0")>-1)
    modules_to_process = (({"userdb#0"})+(modules_to_process-({"userdb#0"})));


  array err;
  foreach( modules_to_process, tmp_string )
    if(err = catch( enable_module( tmp_string ) ))
      report_error("Failed to enable the module "+tmp_string+". Skipping\n"
#ifdef MODULE_DEBUG
                   +describe_backtrace(err)+"\n"
#endif
                  );
  if(parse_module) parse_module->build_callers();
  caudium->current_configuration = 0;
#if constant(gethrtime)
  perror("\nAll modules for %s enabled in %4.3f seconds\n\n", query_name(),
         (gethrtime()-start_time)/1000000.0);
#endif
}

#ifdef ENABLE_RAM_CACHE
//! Cacher for super request speed.
class DataCache
{
  mapping(string:array(string|mapping(string:mixed))) cache = ([]);

  int current_size;
  int max_size, gc_size;
  int max_file_size;
  
  int hits, misses;

  //!
  protected void clear_some_cache()
  {
    int i;
    array q = indices( cache );
    while(current_size > gc_size && i < sizeof(q))
    {
      current_size -= strlen( cache[ q[i] ][0] );
      m_delete( cache, q[i] );
      i++;
    }
  }

  //!
  void expire_entry( string url )
  {
    if( cache[ url ] )
    {
      current_size -= strlen(cache[url][0]);
      m_delete( cache, url );
    }
  }

  //!
  void set( string url, string data, mapping meta, int expire )
  {
    remove_call_out(url);
    call_out( expire_entry, expire, url );
    current_size += strlen(data);
    if(current_size > max_size)
      clear_some_cache();
    cache[url] = ({ data, meta });
  }
  
  //!
  array(string|mapping(string:mixed)) get( string url, mapping request_headers )
  {
    mixed res;
    
    if( res = cache[ url ] ) {
      // Fixme: we need ETag (If-Match, If-None-Match and Vary) processing here
      hits++;
    } else
      misses++;
    return res;
  }

  //!
  void init_from_variables(int _size, int _fsize, float gc_cleanup)
  {
    max_size = _size;
    max_file_size = _fsize;
    gc_size = (int)(max_size * (1 - gc_cleanup));
    while( current_size > max_size )
      clear_some_cache();
  }

  //!
  protected void create(int _size, int _fsize, float gc_cleanup )
  {
    init_from_variables(_size,_fsize, gc_cleanup);
  }
};

object(DataCache) datacache;
#endif

//!
void create(string config)
{
  int|array currentipaddress = gethostbyname(gethostname()); // The ip address
                                                             // of this machine
  caudium->current_configuration = this;
  name=config;

  perror("Creating virtual server '"+config+"'\n");

  defvar("set_default_charset", 0, "Set the default charset", TYPE_FLAG,
         "If set then Caudium will set the specified charset "
	 "for the served document. The value can be overriden only by setting "
	 "a per-file character set from within RXML or Pike code.");
  
  defvar("content_charset", "iso-8859-1", "Default content charset", TYPE_STRING,
         "This variable specifies the default content charset for this server. "
         "This value is sent in the <strong>Content-Type</strong> response "
         "header. <strong>If this option is used, the &lt;meta&gt; tag which sets "
	 "the character set will be ignored.</strong><br>"
         "The format for this option is a valid ISO character set value in "
         "lowercase.", 0, default_charset_not_used);
  
#if constant(_Protocols_DNS_SD.Service)
  defvar("bonjour_announce", 0, "Announce Virtual Server via Bonjour", TYPE_FLAG,
         "If set, Caudium will announce this virtual server via the Bonjour (Zeroconf/Rendezvous) protocol.");
#endif
  
#ifdef ENABLE_RAM_CACHE
// for now only theese two. In the future there might be more variables.
  defvar( "data_cache_size", 2048, "Data Cache:Cache size",
          TYPE_INT,"The size of the data cache used to speed up requests "
          "for commonly requested files, in KBytes");

  defvar( "data_cache_file_max_size", 50, "Data Cache:Max file size",
          TYPE_INT, "The maximum size of a file that is to be "
          "considered for the cache");
  defvar( "data_cache_gc_cleanup", 25, "Data Cache:Garbage Collection Percentage",
          TYPE_INT_LIST, "The amount of the cache space to clean up during "
          "a garbage collection run in percent. If you have a large cache, "
          "you can make this value lower. With a small cache and a small "
          "percentage the GC routine will run more often.",
          ({ 5, 10, 15, 20, 25, 30, 35, 40, 50 }));
#endif

  //TODO: Remove all this and user Error module
  defvar("ErrorTheme", "", "Error Theme", TYPE_STRING,
         "This is the theme to apply to any error messages generated " +
         "automatically by this server. Please enter an absolute path on the virtual " +
         "filesystem(s), otherwise the system-wide default will be used." );
  
  //TODO: Move that to error module
  defvar("ZAuthenticationFailed", "<h1>Authentication Failed.</h1>\n",
         "Authentication Failed Message - Error 401", TYPE_TEXT_FIELD,
         "What to return when authentication has failed");

  defvar("AdminUsers", "",
         "Admin Users", TYPE_TEXT_FIELD,
         "A list of users who are granted administrative access to this virtual server. " +
         "Place one username on each line.");

  defvar("comment", "", "Virtual server comment",
         TYPE_TEXT_FIELD|VAR_MORE,
         "This text will be visible in the configuration interface, it "
         " can be quite useful to use as a memory helper.");
  defvar("sni_tls_config", "", "SNI TLS Configuration",
         TYPE_SSL_CONFIG,
         "Configuration for TLS-SNI based virtual hosting."); 
  defvar("name", "", "Virtual server name",
         TYPE_STRING|VAR_MORE,
         "This is the name that will be used in the configuration "
         "interface. If this is left empty, the actual name of the "
         "virtual server will be used");
  defvar("LogFormat", 
         "*: $host - $user [$cern_date] \"$method $resource $protocol\" $response $length \"$referer\" \"$agent_unquoted\""
         ,
         "Logging: Format", 
         TYPE_TEXT_FIELD,  
         "What format to use for logging. The syntax is:\n"
         "<pre>"
         "response-code or *: Log format for that response acode\n\n"
         "Log format is normal characters, or one or more of the "
         "variables below:\n"
         "\n"
         "$host          -- The remote host name, or ip number.\n"
         "$ip_number     -- The remote ip number.\n"
         "$bin-ip_number -- The remote host id as a binary integer number.\n"
         "\n"
         "$cern_date     -- Cern Common Log file format date.\n"
         "$bin-date      -- Time, but as an 32 bit iteger in network byteorder\n"
         "\n"
         "$method        -- Request method\n"
         "$resource      -- Resource identifier\n"
         "$full_resource -- The full requested resource, with query fields and all\n"
         "$protocol      -- The protocol used (normally HTTP/1.0)\n"
         "$response      -- The response code sent\n"
         "$bin-response  -- The response code sent as a binary short number\n"
         "$length        -- The length of the data section of the reply\n"
         "$bin-length    -- Same, but as an 32 bit iteger in network byteorder\n"
         "$request-time  -- The time the request took (seconds)\n"
         "$referer       -- the header 'referer' from the request, or '-'.\n"
         "$user_agent    -- the header 'User-Agent' from the request, or '-'.\n\n"
         "$agent_unquoted -- the unquoted header 'User-Agent' from the request, or '-'.\n\n"
         "$site_id       -- the site ID used for 2nd level virtual hosting\n"
         "$user          -- the name of the auth user used, if any\n"
         "$user_id       -- A unique user ID, if cookies are supported,\n"
         "                  by the client, otherwise '0'\n"
         "</pre>", 0, log_is_not_enabled);
  
  defvar("max_open_time", 300, "Logging: Maximum idle time before closing",
         TYPE_INT_LIST,
         "This variables sets the idle timeout before in seconds an opened "
         "log file is closed. The benefit of this variable is that little "
         "used virtual servers won't waste file descriptors. Set to zero "
         "to disable this feature.", ({ 0, 60, 120, 180,240,300,400,500,600 }),
         log_is_not_enabled);
  defvar("PostBodySize", POST_MAX_BODY_SIZE, 
	 "Maximum body size for a POST request",
	 TYPE_INT, "This variable determines how large (in bytes) a body of a POST "
	 "request could become before rejecting the request. If the value is -1 the size is "
         "unlimited. A value of 0 ignores the body completely.");

  defvar("Log", 1, "Logging: Enabled", TYPE_FLAG, "Log requests");
  
  defvar("LogFile", caudium->QUERY(logdirprefix)+
         Caudium.short_name(name)+"/Log", 

         "Logging: Log file", TYPE_FILE, "The log file. "
         ""
         "A file name. May be relative to "+getcwd()+"."
         " Some substitutions will be done:"
         "<pre>"
         "%y    Year  (i.e. '1997')\n"
         "%m    Month (i.e. '08')\n"
         "%d    Date  (i.e. '10' for the tenth)\n"
         "%h    Hour  (i.e. '00')\n"
         "%H    The hostname of the server machine.\n"
         "%V    The full domain of the HTTP request.\n"
         "</pre>"
         ,0, log_is_not_enabled);
  
  defvar("NoLog", ({ }), 
         "Logging: No Logging for", TYPE_STRING_LIST|VAR_MORE,
         "Don't log requests from hosts with an IP number which matches any "
         "of the patterns in this list. This also affects the access counter "
         "log.\n",0, log_is_not_enabled);
  
  defvar("Domain", caudium->get_domain(), "Domain", TYPE_STRING,
         "Your domainname, should be set automatically, if not, "
         "enter the correct domain name here, and send a bug report to "
         "<a href=\"mailto:caudium-bugs@caudium.net\">caudium-bugs@caudium.net"
         "</a>");

  defvar("Ports", ({ }), 
         "Listen ports", TYPE_PORTS,
         "The ports this virtual instance of Caudium will bind to.\n");

  defvar("MyWorldLocation", get_my_url(), 
         "Server URL", TYPE_STRING,
         "This is where your start page is located.");

  defvar("InternalLoc", "/_internal/", 
         "Internal module resource mountpoint", TYPE_LOCATION|VAR_MORE,
         "Some modules may want to create links to internal resources.  "
         "This setting configures an internally handled location that can "
         "be used for such purposes.  Simply select a location that you are "
         "not likely to use for regular resources.");
   
  defvar("use_scopes", "On/Conditional", "Scopes compatibility", TYPE_STRING_LIST,
         "<p>This compatibility option manages the new feature of the Caudium Webserver "
         "known as <em>scopes</em>.</p>"
         "<p>Under Roxen 1.3, variable names can contain periods "
         "(such as \"new.form.variable\") but with Caudium the "
         "scope-parsing code will attempt to make this a variable "
         "called \"form.variable\" in the \"new\" scope - and since "
         "there is no scope called \"new\", the action will fail - "
         "this breaks compatibility with existing RXML. A small example "
         "to illustrate the situation:</p>"
         "<blockquote><pre>"
         "&lt;if variable=\"new.formvar is \"&gt;\n"
         "\t&lt;set variable=\"new.formvar\" value=\"blargh\"&gt;\n"
         "&lt;/if&gt;\n"
         "&lt;formoutput&gt;\n"
         "\t&lt;form&gt;\n"
         "\t\t&lt;input name=\"new.formvar\""
         "value=\"#new.formvar#\"&gt;&lt;\n"
         "\t/form&gt;\n"
         "&lt;/formoutput&gt;"
         "</pre></blockquote>",
         ({ "On", "Off", "On/Conditional", "Off/Conditional" }));

  /* CONFIGS LOADER IS HERE!! AND I CURSE WHOMEVER CREATED THAT MESS! /grendel :P */
  
setvars(retrieve("spider#0", this));

#if constant(_Protocols_DNS_SD.Service)
  if(QUERY(bonjour_announce))
  {
     int my_port;

     foreach(query("Ports"), array port)
       if(port[0])
       {
         my_port = port[0];
         break; 
       }
    
     if(my_port)
       bonjour = Protocols.DNS_SD.Service(query_name(),
                     "_http._tcp", "", my_port);
  }
#endif

}

//! Used to print all configuration for a virtual server
string _sprintf( )
{
  return "Configuration("+name+")";
}

/*
 * Local Variables:
 * c-basic-offset: 2
 * End:
 *
 * vim: softtabstop=2 tabstop=2 expandtab autoindent formatoptions=croqlt smartindent cindent shiftwidth=2
 */