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
  
// The Roxen Webserver main program. 
// Copyright © 1996 - 2000, Roxen IS. 
// 
// Per Hedbor, Henrik Grubbström, Pontus Hagland, David Hedbor and others. 
 
// ABS and suicide systems contributed freely by Francesco Chemolli 
constant cvs_version="$Id: roxen.pike,v 1.610 2001/01/19 12:41:35 per Exp $"; 
 
// Used when running threaded to find out which thread is the backend thread, 
// for debug purposes only. 
Thread.Thread backend_thread; 
 
// The argument cache. Used by the image cache. 
ArgCache argcache; 
 
// Some headerfiles 
#define IN_ROXEN 
#include <roxen.h> 
#include <config.h> 
#include <module.h> 
#include <variables.h> 
#include <stat.h> 
 
// Inherits 
inherit "global_variables"; 
inherit "hosts"; 
inherit "disk_cache"; 
// inherit "language"; 
inherit "supports"; 
inherit "module_support"; 
inherit "config_userdb"; 
 
// --- Locale defines --- 
 
//<locale-token project="roxen_start">   LOC_S </locale-token> 
//<locale-token project="roxen_message"> LOC_M </locale-token> 
#define LOC_S(X,Y)    _STR_LOCALE("roxen_start",X,Y) 
#define LOC_M(X,Y)  _STR_LOCALE("roxen_message",X,Y) 
#define CALL_M(X,Y) _LOCALE_FUN("roxen_message",X,Y) 
 
// --- Debug defines --- 
 
#ifdef SSL3_DEBUG 
# define SSL3_WERR(X) werror("SSL3: "+X+"\n") 
#else 
# define SSL3_WERR(X) 
#endif 
 
#ifdef THREAD_DEBUG 
# define THREAD_WERR(X) werror("Thread: "+X+"\n") 
#else 
# define THREAD_WERR(X) 
#endif 
 
#define DDUMP(X) sol( combine_path( __FILE__, "../../" + X ), dump ) 
static function sol = master()->set_on_load; 
 
string query_configuration_dir() 
{ 
  return configuration_dir; 
} 
 
string filename( program|object o ) 
{ 
  if( objectp( o ) ) 
    o = object_program( o ); 
 
  string fname = master()->program_name( o ); 
  if( !fname ) 
    fname = "Unknown Program"; 
  return fname-(getcwd()+"/"); 
} 
 
#ifdef THREADS 
// This mutex is used by Privs 
Thread.Mutex euid_egid_lock = Thread.Mutex(); 
#endif /* THREADS */ 
 
/* 
 * The privilege changer. Works like a mutex lock, but changes the UID/GID 
 * while held. Blocks all threads. 
 *  
 * Based on privs.pike,v 1.36. 
 */ 
int privs_level; 
 
static class Privs 
{ 
#if efun(seteuid) 
 
  int saved_uid; 
  int saved_gid; 
 
  int new_uid; 
  int new_gid; 
 
#define LOGP (variables && variables->audit && variables->audit->query()) 
 
#if constant(geteuid) && constant(getegid) && constant(seteuid) && constant(setegid) 
#define HAVE_EFFECTIVE_USER 
#endif 
 
  static private string _getcwd() 
  { 
    if (catch{return(getcwd());}) { 
      return("Unknown directory (no x-bit on current directory?)"); 
    } 
  } 
 
  static private string dbt(array t) 
  { 
    if(!arrayp(t) || (sizeof(t)<2)) return ""; 
    return (((t[0]||"Unknown program")-(_getcwd()+"/"))-"base_server/")+":"+t[1]+"\n"; 
  } 
 
#ifdef THREADS 
  static mixed mutex_key;     // Only one thread may modify the euid/egid at a time. 
  static object threads_disabled; 
#endif /* THREADS */ 
 
  int p_level; 
 
  void create(string reason, int|string|void uid, int|string|void gid) 
  { 
#ifdef PRIVS_DEBUG 
    werror(sprintf("Privs(%O, %O, %O)\n" 
                   "privs_level: %O\n", 
                   reason, uid, gid, privs_level)); 
#endif /* PRIVS_DEBUG */ 
 
#ifdef HAVE_EFFECTIVE_USER 
    array u; 
 
#ifdef THREADS 
    if (euid_egid_lock) { 
      catch { mutex_key = euid_egid_lock->lock(); }; 
    } 
    threads_disabled = _disable_threads(); 
#endif /* THREADS */ 
 
    p_level = privs_level++; 
 
    if(getuid()) return; 
 
    /* Needs to be here since root-priviliges may be needed to 
     * use getpw{uid,nam}. 
     */ 
    saved_uid = geteuid(); 
    saved_gid = getegid(); 
    seteuid(0); 
 
    /* A string of digits? */ 
    if(stringp(uid) && (replace(uid,"0123456789"/"",({""})*10)=="")) 
      uid = (int)uid; 
 
    if(stringp(gid) && (replace(gid, "0123456789"/"", ({"" })*10) == "")) 
      gid = (int)gid; 
 
    if(!stringp(uid)) 
      u = getpwuid(uid); 
    else 
    { 
      u = getpwnam(uid); 
      if(u) 
        uid = u[2]; 
    } 
 
    if(u && !gid) 
      gid = u[3]; 
 
    if(!u) 
    { 
      if (uid && (uid != "root")) 
      { 
        if (intp(uid) && (uid >= 60000)) 
        { 
          report_warning(sprintf("Privs: User %d is not in the password database.\n" 
                                 "Assuming nobody.\n", uid)); 
          // Nobody. 
          gid = gid || uid;     // Fake a gid also. 
          u = ({ "fake-nobody", "x", uid, gid, "A real nobody", "/", "/sbin/sh" }); 
        } else { 
          error("Unknown user: "+uid+"\n"); 
        } 
      } else { 
        u = ({ "root", "x", 0, gid, "The super-user", "/", "/sbin/sh" }); 
      } 
    } 
 
    if(LOGP) 
      report_notice(LOC_M(1, "Change to %s(%d):%d privs wanted (%s), from %s"), 
                    (string)u[0], (int)uid, (int)gid, 
                    (string)reason, 
                    (string)dbt(backtrace()[-2])); 
 
#if efun(cleargroups) 
    catch { cleargroups(); }; 
#endif /* cleargroups */ 
#if efun(initgroups) 
    catch { initgroups(u[0], u[3]); }; 
#endif 
    gid = gid || getgid(); 
    int err = (int)setegid(new_gid = gid); 
    if (err < 0) { 
      report_warning(LOC_M(2, "Privs: WARNING: Failed to set the " 
                           "effective group id to %d!\n" 
                           "Check that your password database is correct " 
                           "for user %s(%d),\n and that your group " 
                           "database is correct.\n"), 
                     gid, (string)u[0], (int)uid); 
      int gid2 = gid; 
#ifdef HPUX_KLUDGE 
      if (gid >= 60000) { 
        /* HPUX has doesn't like groups higher than 60000, 
         * but has assigned nobody to group 60001 (which isn't even 
         * in /etc/group!). 
         * 
         * HPUX's libc also insists on filling numeric fields it doesn't like 
         * with the value 60001! 
         */ 
        report_debug("Privs: WARNING: Assuming nobody-group.\n" 
               "Trying some alternatives...\n"); 
        // Assume we want the nobody group, and try a couple of alternatives 
        foreach(({ 60001, 65534, -2 }), gid2) { 
          report_debug("%d... ", gid2); 
          if (initgroups(u[0], gid2) >= 0) { 
            if ((err = setegid(new_gid = gid2)) >= 0) { 
              report_debug("Success!\n"); 
              break; 
            } 
          } 
        } 
      } 
#endif /* HPUX_KLUDGE */ 
      if (err < 0) { 
        report_debug("Privs: Failed\n"); 
        throw(({ sprintf("Failed to set EGID to %d\n", gid), backtrace() })); 
      } 
      report_debug("Privs: WARNING: Set egid to %d instead of %d.\n", 
             gid2, gid); 
      gid = gid2; 
    } 
    if(getgid()!=gid) setgid(gid||getgid()); 
    seteuid(new_uid = uid); 
#endif /* HAVE_EFFECTIVE_USER */ 
  } 
 
  void destroy() 
  { 
#ifdef PRIVS_DEBUG 
    werror(sprintf("Privs->destroy()\n" 
                   "privs_level: %O\n", 
                   privs_level)); 
#endif /* PRIVS_DEBUG */ 
 
#ifdef HAVE_EFFECTIVE_USER 
    /* Check that we don't increase the privs level */ 
    if (p_level >= privs_level) { 
      report_error(sprintf("Change back to uid#%d gid#%d from uid#%d gid#%d\n" 
                           "in wrong order! Saved level:%d Current level:%d\n" 
                           "Occurs in:\n%s\n", 
                           saved_uid, saved_gid, new_uid, new_gid, 
                           p_level, privs_level, 
                           describe_backtrace(backtrace()))); 
      return(0); 
    } 
    if (p_level != privs_level-1) { 
      report_error(sprintf("Change back to uid#%d gid#%d from uid#%d gid#%d\n" 
                           "Skips privs level. Saved level:%d Current level:%d\n" 
                           "Occurs in:\n%s\n", 
                           saved_uid, saved_gid, new_uid, new_gid, 
                           p_level, privs_level, 
                           describe_backtrace(backtrace()))); 
    } 
    privs_level = p_level; 
 
    if(LOGP) { 
      catch { 
        array bt = backtrace(); 
        if (sizeof(bt) >= 2) { 
          report_notice(LOC_M(3,"Change back to uid#%d gid#%d, from %s")+"\n", 
                        saved_uid, saved_gid, dbt(bt[-2])); 
        } else { 
          report_notice(LOC_M(4,"Change back to uid#%d gid#%d, " 
                              "from backend")+"\n", saved_uid, saved_gid); 
        } 
      }; 
    } 
 
    if(getuid()) return; 
 
#ifdef PRIVS_DEBUG 
    int uid = geteuid(); 
    if (uid != new_uid) { 
      werror("Privs: UID #%d differs from expected #%d\n" 
             "%s\n", 
             uid, new_uid, describe_backtrace(backtrace())); 
    } 
    int gid = getegid(); 
    if (gid != new_gid) { 
      werror("Privs: GID #%d differs from expected #%d\n" 
             "%s\n", 
             gid, new_gid, describe_backtrace(backtrace())); 
    } 
#endif /* PRIVS_DEBUG */ 
 
    seteuid(0); 
    array u = getpwuid(saved_uid); 
#if efun(cleargroups) 
    catch { cleargroups(); }; 
#endif /* cleargroups */ 
    if(u && (sizeof(u) > 3)) { 
      catch { initgroups(u[0], u[3]); }; 
    } 
    setegid(saved_gid); 
    seteuid(saved_uid); 
#endif /* HAVE_EFFECTIVE_USER */ 
  } 
#else /* efun(seteuid) */ 
  void create(string reason, int|string|void uid, int|string|void gid){} 
#endif /* efun(seteuid) */ 
} 
 
/* Used by read_config.pike, since there seems to be problems with 
 * overloading otherwise. 
 */ 
static Privs PRIVS(string r, int|string|void u, int|string|void g) 
{ 
  return Privs(r, u, g); 
} 
 
// font cache and loading. 
//  
// This will be changed to a list of server global modules, to make it 
// easier to implement new types of fonts (such as PPM color fonts, as 
// an example) 
class Fonts 
{ 
  class Font 
  { 
    Image.Image write( string ... what ); 
    array(int) text_extents( string ... what ); 
  }; 
  array available_font_versions(string name, int size); 
  string describe_font_type(string n); 
  Font get_font(string f, int size, int bold, int italic, 
                string justification, float|int xspace, float|int yspace); 
 
  Font resolve_font(string f, string|void justification); 
  array(string) available_fonts( ); 
} 
Fonts fonts; 
 
// Will replace Configuration after create() is run. 
program _configuration;     /*set in create*/ 
 
array(Configuration) configurations = ({}); 
 
// When true, roxen will shut down as soon as possible. 
local static int die_die_die; 
 
// Function that actually shuts down Roxen. (see low_shutdown). 
private static void really_low_shutdown(int exit_code) 
{ 
  // Die nicely. Catch for paranoia reasons 
#ifdef THREADS 
  catch( stop_handler_threads() ); 
#endif /* THREADS */ 
  exit( exit_code );          // Now we die... 
} 
 
 
// Shutdown Roxen 
//  exit_code = 0     True shutdown 
//  exit_code = -1    Restart 
private static void low_shutdown(int exit_code) 
{ 
  catch 
  { 
    configurations->stop(); 
    int pid; 
    if (exit_code) { 
      report_debug("Restarting Roxen.\n"); 
    } else { 
      report_debug("Shutting down Roxen.\n"); 
      // exit(0); 
    } 
  }; 
  call_out(really_low_shutdown, 0.1, exit_code); 
} 
 
// Perhaps somewhat misnamed, really...  This function will close all 
// listen ports and then quit.  The 'start' script should then start a 
// new copy of roxen automatically. 
void restart(float|void i) 
//! Restart roxen, if the start script is running 
{ 
  werror(describe_backtrace(backtrace())); 
  call_out(low_shutdown, i, -1); 
} 
 
void shutdown(float|void i) 
//! Shut down roxen 
{ 
  call_out(low_shutdown, i, 0); 
} 
 
/* 
 * handle() stuff 
 */ 
 
#ifndef THREADS 
// handle function used when THREADS is not enabled. 
local static void unthreaded_handle(function f, mixed ... args) 
{ 
  f(@args); 
} 
 
function handle = unthreaded_handle; 
#else 
function handle = threaded_handle; 
#endif 
 
/* 
 * THREADS code starts here 
 */ 
#ifdef THREADS 
 
Thread do_thread_create(string id, function f, mixed ... args) 
{ 
  Thread.Thread t = thread_create(f, @args); 
  catch(t->set_name( id )); 
  THREAD_WERR(id+" started"); 
  return t; 
} 
 
// Shamelessly uses facts about pikes preemting algorithm. 
// Might have to be fixed in the future. 
class Queue  
//! Thread.Queue lookalike, which uses some archaic and less 
//! known features of the preempting algorithm in pike to optimize the 
//! read function. 
{ 
  inherit Thread.Condition : r_cond; 
  array buffer=allocate(8); 
  int r_ptr, w_ptr; 
   
  int size()  
  {  
    return w_ptr - r_ptr;   
  } 
   
  mixed read() 
  { 
    while(!(w_ptr - r_ptr)) r_cond::wait(); 
    mixed tmp = buffer[r_ptr]; 
    buffer[r_ptr++] = 0;        // Throw away any references. 
    return tmp; 
  } 
   
  void write(mixed v) 
  { 
    if(w_ptr >= sizeof(buffer)) 
    { 
      buffer=buffer[r_ptr..]+allocate(8); 
      w_ptr-=r_ptr; 
      r_ptr=0; 
    } 
    buffer[w_ptr++]=v; 
    r_cond::signal(); 
  } 
} 
 
#if constant(thread_create) 
// This is easier than when there is no threads. 
// See the discussion below. :-) 
function async_sig_start( function f, int really ) 
{ 
  return lambda( mixed ... args ) { thread_create( f, @args ); }; 
} 
#else 
function async_sig_start( function f, int really ) 
{ 
  class SignalAsyncVerifier( function f ) 
  { 
    static int async_called; 
 
    void really_call( array args ) 
    { 
      async_called = 0; 
      f( @args ); 
    } 
 
    void call( mixed ... args ) 
    { 
      if( async_called ) 
      { 
        report_debug("\n\n" 
                     "Async calling failed for %O, calling synchronous\n", f); 
        report_debug("Backtrace at time of hangup:\n%s\n", 
                     describe_backtrace( backtrace() )); 
        f( @args ); 
        return; 
      } 
      async_called=1; 
      call_out( really_call, 0, args ); 
    } 
  }; 
  // call_out is not really useful here, since we probably want to run 
  // the signal handler immediately, not whenever the backend thread 
  // is available. /per 
  // 
  // Calling directly like this may however lead to recursive mutex 
  // lock errors. The problem cannot be solved using lock(2) since the 
  // internal structures may be in an inconsistent state from the 
  // previous call, and waiting for the lock probably leads to a 
  // deadlock. /noring 
  // 
  // But on the other hand, you are not very likely to have any mutex 
  // locks in an unthreaded pike, since it's quite impossible. /per 
  // 
  // But still, the problems with inconsistent internal states are 
  // there. The API:s for many (thread safe) objects are designed to 
  // only allow one (1) caller at any given time. It's a bug if this 
  // restriction can be circumvented using signals. I suggest that 
  // Thread.Mutex takes care of this problem in non-threaded mode. 
  // /  noring 
  // 
  // Apparantly it already did that. :-) 
  //  
  // I also fixed SIGHUP to be somewhat more asynchronous.   
  // 
  // I also added a rather small amount of magic so that it is called 
  // asynchronously the first time it is received, but repeated 
  // signals are not called asynchronously unless the first signal 
  // handler was actually called. 
  // 
  // Except for the SIGQUIT signal, which dumps a backtrace. It would 
  // be an excercise in futility to call that one asynchronously. 
  // 
  // I hope that this will solve all your problems. /per 
  if( really > 0 ) 
    return lambda( mixed ... args ){ call_out( f, 0, @args ); }; 
  if( really < 0 ) 
    return f; 
  return SignalAsyncVerifier( f )->call; 
} 
#endif 
 
local static Queue handle_queue = Queue(); 
//! Queue of things to handle. 
//! An entry consists of an array(function fp, array args) 
 
local static int thread_reap_cnt; 
//! Number of handler threads that are alive. 
 
local static void handler_thread(int id) 
//! The actual handling function. This functions read function and 
//! parameters from the queue, calls it, then reads another one. There 
//! is a lot of error handling to ensure that nothing serious happens if 
//! the handler function throws an error. 
{ 
  array (mixed) h, q; 
  while(!die_die_die) 
  { 
    if(q=catch { 
      do { 
        THREAD_WERR("Handle thread ["+id+"] waiting for next event"); 
        if((h=handle_queue->read()) && h[0]) { 
          THREAD_WERR(sprintf("Handle thread [%O] calling %O(@%O)...", 
                                id, h[0], h[1..])); 
          set_locale(); 
          h[0](@h[1]); 
          h=0; 
        } else if(!h) { 
          // Roxen is shutting down. 
          report_debug("Handle thread ["+id+"] stopped\n"); 
          thread_reap_cnt--; 
#ifdef NSERIOUS 
        if(!thread_reap_cnt) report_debug("+++ATH\n"); 
#endif 
        return; 
        } 
      } while(1); 
    }) { 
      if (h = catch { 
        report_error(/*LOCALE("", "Uncaught error in handler thread: %s" 
                       "Client will not get any response from Roxen.\n"),*/ 
                     describe_backtrace(q)); 
        if (q = catch {h = 0;}) { 
          report_error(LOC_M(5, "Uncaught error in handler thread: %s Client" 
                             "will not get any response from Roxen.")+"\n", 
                       describe_backtrace(q)); 
        } 
      }) { 
        catch { 
          report_error("Error reporting error:\n"); 
          report_error(sprintf("Raw error: %O\n", h[0])); 
          report_error(sprintf("Original raw error: %O\n", q[0])); 
        }; 
      } 
    } 
  } 
} 
 
local static void threaded_handle(function f, mixed ... args) 
{ 
  handle_queue->write(({f, args })); 
} 
 
int number_of_threads; 
//! The number of handler threads to run. 
static array(object) handler_threads = ({}); 
//! The handler threads, the list is kept for debug reasons. 
 
void start_handler_threads() 
{ 
  if (query("numthreads") <= 1) { 
    set( "numthreads", 1 ); 
    report_notice (LOC_S(1, "Starting one thread to handle requests.")+"\n"); 
  } else {  
    report_notice (LOC_S(2, "Starting %d threads to handle requests.")+"\n", 
                   query("numthreads") ); 
  } 
  array(object) new_threads = ({}); 
  for(; number_of_threads < query("numthreads"); number_of_threads++) 
    new_threads += ({ do_thread_create( "Handle thread [" + 
                                        number_of_threads + "]", 
                                        handler_thread, number_of_threads ) }); 
  handler_threads += new_threads; 
} 
 
void stop_handler_threads() 
//! Stop all the handler threads, but give up if it takes too long. 
{ 
  int timeout=10; 
#if constant(_reset_dmalloc) 
  // DMALLOC slows stuff down a bit... 
  timeout *= 10; 
#endif /* constant(_reset_dmalloc) */ 
  report_debug("Stopping all request handler threads.\n"); 
  while(number_of_threads>0) { 
    number_of_threads--; 
    handle_queue->write(0); 
    thread_reap_cnt++; 
  } 
  handler_threads = ({}); 
  while(thread_reap_cnt) { 
    sleep(0.1); 
    if(--timeout<=0) { 
      report_debug("Giving up waiting on threads!\n"); 
      return; 
    } 
  } 
} 
#endif /* THREADS */ 
 
 
mapping get_port_options( string key ) 
//! Get the options for the key 'key'. 
//! The intepretation of the options is protocol specific. 
{ 
  return (query( "port_options" )[ key ] || ([])); 
} 
 
void set_port_options( string key, mapping value ) 
//! Set the options for the key 'key'. 
//! The intepretation of the options is protocol specific. 
{ 
  mapping q = query("port_options"); 
  q[ key ] = value; 
  set( "port_options" , q ); 
  save( ); 
} 
 
class InternalRequestID 
//! ID for internal requests that are not linked to any real request. 
{ 
  inherit RequestID; 
 
  static void create() 
  { 
    client = ({ "Roxen" }); 
    prot = "INTERNAL"; 
    method = "GET"; 
    variables = ([]); 
    misc = ([]); 
    cookies = ([]); 
    throttle = ([]); 
    client_var = ([]); 
    request_headers = ([]); 
    prestate = (<>); 
    config = (<>); 
    supports = (<>); 
    pragma = (<>); 
    rest_query = ""; 
    extra_extension = ""; 
    remoteaddr = "127.0.0.1"; 
  } 
} 
 
class Protocol 
//! The basic protocol. 
//! Implements reference handling, finding Configuration objects 
//! for URLs, and the bind/accept handling. 
{ 
  inherit Stdio.Port: port; 
  inherit "basic_defvar"; 
  int bound; 
 
  string path; 
  constant name = "unknown"; 
  constant supports_ipless = 0; 
  //! If true, the protocol handles ip-less virtual hosting 
  constant requesthandlerfile = ""; 
  //! Filename of a by-connection handling class. It is also possible 
  //! to set the 'requesthandler' class member in a overloaded create 
  //! function. 
 
  constant default_port = 4711; 
  //! If no port is specified in the URL, use this one 
 
  int port; 
  //! The currently bound portnumber 
  string ip; 
  //! The IP-number (0 for ANY) this port is bound to 
  int refs; 
  //! The number of references to this port 
  program requesthandler; 
  //! The per-connection request handling class 
  array(string) sorted_urls = ({}); 
  //! Sorted by length, longest first 
  mapping(string:mapping) urls = ([]); 
  //! .. url -> ([ "conf":.., ... ]) 
 
  void ref(string name, mapping data) 
  //! Add a ref for the URL 'name' with the data 'data' 
  { 
    if(urls[name]) 
    { 
      urls[name] = data; 
      return; // only ref once per URL 
    } 
    if (!refs) path = data->path; 
    else if (path != (data->path || "")) path = 0; 
    refs++; 
    urls[name] = data; 
    sorted_urls = Array.sort_array(indices(urls),  
                                 lambda(string a, string b) { 
                                   return sizeof(a)<sizeof(b); 
                                 }); 
  } 
 
  void unref(string name) 
  //! Remove a ref for the URL 'name' 
  { 
//     if(!urls[name]) // only unref once 
//       return; 
 
    m_delete(urls, name); 
    if (!path && sizeof (Array.uniq (values (urls)->path)) == 1) 
      path = values (urls)[0]->path; 
    sorted_urls -= ({name}); 
    if( !--refs ) 
      destruct( ); // Close the port. 
  } 
 
  mapping mu; 
  string rrhf; 
  static void got_connection() 
  { 
    Stdio.File q = accept( ); 
    if( q ) 
    { 
      if( !requesthandler ) 
      { 
        requesthandler = (program)(rrhf); 
      } 
      Configuration c; 
      if( refs < 2 ) 
      { 
        if(!mu)  
        { 
          mu = urls[sorted_urls[0]]; 
          if(!(c=mu->conf)->inited ) 
            c->enable_all_modules(); 
        } else 
          c = mu->conf; 
      } 
      requesthandler( q, this_object(), c ); 
    } 
  } 
 
  local function sp_fcfu; 
 
 
 
#define INIT(X) do{mapping _=(X);string __=_->path;c=_->conf;if(__&&id->adjust_for_config_path) id->adjust_for_config_path(__);if(!c->inited)c->enable_all_modules(); } while(0) 
 
  Configuration find_configuration_for_url( string url, RequestID id,  
                                            int|void no_default ) 
  //! Given a url and requestid, try to locate a suitable configuration 
  //! (virtual site) for the request.  
  //! This interface is not at all set in stone, and might change at  
  //! any time. 
  { 
    Configuration c; 
    if( sizeof( urls ) == 1 ) 
    { 
      if(!mu) mu=urls[sorted_urls[0]]; 
      INIT( mu ); 
      return c; 
    } 
 
    url = lower_case( url ); 
    // The URLs are sorted from longest to shortest, so that short 
    // urls (such as http://*/) will not match before more complete 
    // ones (such as http://*.roxen.com/) 
    foreach( sorted_urls, string in ) 
    { 
      if( glob( in+"*", url ) ) 
      { 
        INIT( urls[in] ); 
        return c; 
      } 
    } 
     
    if( no_default ) 
      return 0; 
     
    // No host matched, or no host header was included in the request. 
    // Is the URL in the '*' ports? 
    mixed i; 
    if( !functionp(sp_fcfu) && ( i=open_ports[ name ][ 0 ][ port ] ) ) 
      sp_fcfu = i->find_configuration_for_url; 
     
    if( sp_fcfu && (sp_fcfu != find_configuration_for_url) 
        && (i = sp_fcfu( url, id, 1 ))) 
      return i; 
     
    // No. We have to default to one of the other ports. 
    // It might be that one of the servers is tagged as a default server. 
    multiset choices = (< >); 
    foreach( configurations, Configuration c ) 
      if( c->query( "default_server" ) ) 
        choices |= (< c >); 
     
    if( sizeof( choices ) ) 
    { 
      // First pick default servers bound to this port 
      foreach( values(urls), mapping cc ) 
        if( choices[ cc->conf ] ) 
        { 
          INIT( cc ); 
          return c; 
        } 
 
      // if there is no such servers, pick the first default server 
      // available. FIXME: This makes it impossible to handle the 
      // server path correctly. 
 
      c = ((array)choices)[0]; 
      if(!c->inited) c->enable_all_modules(); 
      return c; 
    } 
 
 
    // if we end up here, there is no default port at all available 
    // so grab the first configuration that is available at all. 
    INIT( urls[sorted_urls[0]] ); 
    id->misc->defaulted=1; 
    return c; 
  } 
 
  mixed query_option( string x ) 
  //! Query the port-option 'x' for this port.  
  { 
    return query( x ); 
  } 
 
  string get_key() 
  //! Return he key used for this port (protocol:ip:portno) 
  { 
    return name+":"+ip+":"+port; 
  } 
 
  void save() 
  //! Save all port options 
  { 
    set_port_options( get_key(), 
                      mkmapping( indices(variables), 
                                 map(indices(variables),query))); 
  } 
 
  void restore() 
  //! Restore all port options from saved values 
  { 
    foreach( (array)get_port_options( get_key() ),  array kv ) 
      set( kv[0], kv[1] ); 
  } 
 
  static void create( int pn, string i ) 
  //! Constructor. Bind to the port 'pn' ip 'i' 
  { 
    port = pn; 
    ip = i; 
 
    restore(); 
    if( file_stat( "../local/"+requesthandlerfile ) ) 
      rrhf = "../local/"+requesthandlerfile; 
    else 
      rrhf = requesthandlerfile; 
    DDUMP( rrhf ); 
#ifdef DEBUG 
    if( !requesthandler ) 
      requesthandler = (program)(rrhf); 
#endif 
    ::create(); 
    if(!bind( port, got_connection, ip )) 
    { 
      report_error(LOC_M(6, "Failed to bind %s://%s:%d/ (%s)")+"\n",  
                   (string)name, (ip||"*"), (int)port, strerror( errno() )); 
      bound = 0; 
    } else 
      bound = 1; 
  } 
 
  static string _sprintf( ) 
  { 
   return "Protocol("+name+"://"+ip+":"+port+")"; 
  } 
} 
 
#if constant(SSL.sslfile) 
class SSLProtocol 
//! Base protocol for SSL ports. Exactly like Port, but uses SSL. 
{ 
  inherit Protocol; 
 
  // SSL context 
  SSL.context ctx; 
 
  class destruct_protected_sslfile 
  { 
    SSL.sslfile sslfile; 
 
    mixed `[](string s) 
    { 
      return sslfile[s]; 
    } 
 
    mixed `[]=(string s, mixed val) 
    { 
      return sslfile[s] = val; 
    } 
 
    mixed `->(string s) 
    { 
      return sslfile[s]; 
    } 
 
    mixed `->=(string s, mixed val) 
    { 
      return sslfile[s] = val; 
    } 
 
    void destroy() 
    { 
      if (sslfile) 
        sslfile->close(); 
    } 
 
    void create(object q) 
    { 
      sslfile = SSL.sslfile(q, ctx); 
    } 
  } 
 
  Stdio.File accept() 
  { 
    Stdio.File q = ::accept(); 
    if (q) 
      return [object(Stdio.File)](object)destruct_protected_sslfile(q); 
    return 0; 
  } 
 
  void create(int pn, string i) 
  { 
    ctx = SSL.context(); 
    set_up_ssl_variables( this_object() ); 
    port = pn; 
    ip = i; 
 
    restore(); 
     
    Privs privs = Privs("Reading cert file"); 
 
    string f, f2; 
 
    if( catch{ f = lopen(query_option("ssl_cert_file"), "r")->read(); } ) 
    { 
      report_error(LOC_M(8,"SSL3: Reading cert-file failed!")+"\n"); 
      destruct(); 
      return; 
    } 
 
    if( strlen(query_option("ssl_key_file")) && 
        catch{ f2 = lopen(query_option("ssl_key_file"),"r")->read(); } ) 
    { 
      report_error(LOC_M(9, "SSL3: Reading key-file failed!")+"\n"); 
      destruct(); 
      return; 
    } 
 
    if (privs) 
      destruct(privs); 
 
    object msg = Tools.PEM.pem_msg()->init( f ); 
    object part = msg->parts["CERTIFICATE"] || msg->parts["X509 CERTIFICATE"]; 
    string cert; 
 
    if (!part || !(cert = part->decoded_body()))  
    { 
      report_error(LOC_M(10, "SSL3: No certificate found.")+"\n"); 
      destruct(); 
      return; 
    } 
 
    if( f2 ) 
      msg = Tools.PEM.pem_msg()->init( f2 ); 
 
    function r = Crypto.randomness.reasonably_random()->read; 
 
    SSL3_WERR(sprintf("key file contains: %O", indices(msg->parts))); 
 
    if (part = msg->parts["RSA PRIVATE KEY"]) 
    { 
      string key; 
 
      if (!(key = part->decoded_body()))  
      { 
        report_error(LOC_M(11,"SSL3: Private rsa key not valid")+" (PEM).\n"); 
        destruct(); 
        return; 
      } 
 
      object rsa = Standards.PKCS.RSA.parse_private_key(key); 
      if (!rsa)  
      { 
        report_error(LOC_M(11, "SSL3: Private rsa key not valid")+" (DER).\n"); 
        destruct(); 
        return; 
      } 
 
      ctx->rsa = rsa; 
 
      SSL3_WERR(sprintf("RSA key size: %d bits", rsa->rsa_size())); 
 
      if (rsa->rsa_size() > 512) 
      { 
        /* Too large for export */ 
        ctx->short_rsa = Crypto.rsa()->generate_key(512, r); 
 
        // ctx->long_rsa = Crypto.rsa()->generate_key(rsa->rsa_size(), r); 
      } 
      ctx->rsa_mode(); 
 
      object tbs = Tools.X509.decode_certificate (cert); 
      if (!tbs)  
      { 
        report_error(LOC_M(13,"SSL3: Certificate not valid (DER).")+"\n"); 
        destruct(); 
        return; 
      } 
      if (!tbs->public_key->rsa->public_key_equal (rsa))  
      { 
        report_error(LOC_M(14, "SSL3: Certificate and private key do not " 
                           "match.")+"\n"); 
        destruct(); 
        return; 
      } 
    } 
    else if (part = msg->parts["DSA PRIVATE KEY"]) 
    { 
      string key; 
 
      if (!(key = part->decoded_body()))  
      { 
        report_error(LOC_M(15,"SSL3: Private dsa key not valid")+" (PEM).\n"); 
        destruct(); 
        return; 
      } 
 
      object dsa = Standards.PKCS.DSA.parse_private_key(key); 
      if (!dsa)  
      { 
        report_error(LOC_M(15,"SSL3: Private dsa key not valid")+" (DER).\n"); 
        destruct(); 
        return; 
      } 
 
      SSL3_WERR(sprintf("Using DSA key.")); 
 
      dsa->use_random(r); 
      ctx->dsa = dsa; 
      /* Use default DH parameters */ 
      ctx->dh_params = SSL.cipher.dh_parameters(); 
 
      ctx->dhe_dss_mode(); 
 
      // FIXME: Add cert <-> private key check. 
    } 
    else  
    { 
      report_error(LOC_M(17,"SSL3: No private key found.")+"\n"); 
      destruct(); 
      return; 
    } 
 
    ctx->certificates = ({ cert }); 
    ctx->random = r; 
 
#if EXPORT 
    ctx->export_mode(); 
#endif 
    ::create(pn, i); 
  } 
 
  string _sprintf( ) 
  { 
    return "SSLProtocol("+name+"://"+ip+":"+port+")"; 
  } 
} 
#endif 
 
mapping(string:Protocol) build_protocols_mapping() 
{ 
  mapping protocols = ([]); 
  int st = gethrtime(); 
  werror("Protocol handlers ... "); 
#ifndef DEBUG 
  class lazy_load( string prog, string name ) 
  { 
    program real; 
    static void realize() 
    { 
      if( catch { 
        DDUMP( prog ); 
        real = (program)prog; 
        protocols[name] = real; 
      } ) 
        report_error("Failed to compile protocol handler for "+name+"\n"); 
    } 
 
    Protocol `()(mixed ... x) 
    { 
      if(!real) realize(); 
      return real(@x); 
    }; 
    mixed `->( string x ) 
    { 
      if(!real) realize(); 
      return predef::`->(real, x); 
    } 
  }; 
#endif 
  foreach( glob( "prot_*.pike", get_dir("protocols") ), string s ) 
  { 
    sscanf( s, "prot_%s.pike", s ); 
#if !constant(SSL.sslfile) 
    switch( s ) 
    { 
      case "https": 
      case "ftps": 
        continue; 
    } 
#endif 
#if !constant(HTTPLoop.prog) 
    if( s == "fhttp" ) continue; 
#endif 
    werror( s+" " ); 
 
    catch 
    { 
#ifdef DEBUG 
      protocols[ s ] = (program)("protocols/prot_"+s+".pike"); 
#else 
      protocols[ s ] = lazy_load( ("protocols/prot_"+s+".pike"),s ); 
#endif 
    }; 
  } 
  foreach( glob("prot_*.pike",get_dir("../local/protocols")||({})), string s ) 
  { 
    sscanf( s, "prot_%s.pike", s ); 
#if !constant(SSL.sslfile) 
    switch( s ) 
    { 
      case "https": 
      case "ftps": 
        continue; 
    } 
#endif 
    werror( s+" " ); 
    catch { 
#ifdef DEBUG 
      protocols[ s ] = (program)("../local/protocols/prot_"+s+".pike"); 
#else 
      protocols[ s ] = lazy_load( ("../local/protocols/prot_"+s+".pike"),s ); 
#endif 
    }; 
  } 
  werror(" [%.1fms]\n", (gethrtime()-st)/1000.0 ); 
  return protocols; 
} 
 
 
mapping protocols; 
 
mapping(string:mapping) open_ports = ([ ]); 
mapping(string:object) urls = ([]); 
array sorted_urls = ({}); 
 
array(string) find_ips_for( string what ) 
{ 
  if( what == "*" || lower_case(what) == "any" ) 
    return 0; 
 
  if( is_ip( what ) ) 
    return ({ what }); 
 
  array res = gethostbyname( what ); 
  if( !res || !sizeof( res[1] ) ) 
    report_error(LOC_M(46, "Cannot possibly bind to %O, that host is " 
                       "unknown. Substituting with ANY")+"\n", what); 
  else 
    return Array.uniq(res[1]); 
} 
 
void unregister_url( string url ) 
{ 
  string ourl = url; 
  url = lower_case( url ); 
  string host, path, protocol; 
  int port; 
  if (!sizeof (url - " " - "\t")) return; 
 
  url = replace( url, "/ANY", "/*" ); 
  url = replace( url, "/any", "/*" ); 
 
  sscanf( url, "%[^:]://%[^/]%s", protocol, host, path ); 
  if (!host || !stringp(host))   return; 
  if( !protocols[ protocol ] )    return; 
 
  sscanf(host, "%[^:]:%d", host, port); 
 
  if( !port ) 
  { 
    port = protocols[ protocol ]->default_port; 
    url = protocol+"://"+host+":"+port+path; 
  } 
 
  report_debug("Unregister "+url+"\n"); 
 
  if( urls[ url ] && urls[ url ]->port ) 
  { 
    urls[ url ]->port->unref(url); 
    m_delete( urls, url ); 
    m_delete( urls, ourl ); 
    sort_urls(); 
  } 
} 
 
array all_ports( ) 
{ 
  return Array.uniq( values( urls )->port )-({0}); 
} 
 
Protocol find_port( string name ) 
{ 
  foreach( all_ports(), Protocol p  ) 
    if( p->get_key() == name ) 
      return p; 
} 
 
void sort_urls() 
{ 
  sorted_urls = indices( urls ); 
  sort( map( map( sorted_urls, strlen ), `-), sorted_urls ); 
} 
 
int register_url( string url, Configuration conf ) 
{ 
  string ourl = url; 
  url = lower_case( url ); 
  if (!sizeof (url - " " - "\t")) return 1; 
  string protocol; 
  string host; 
  int port; 
  string path; 
 
  url = replace( url, "/ANY", "/*" ); 
  url = replace( url, "/any", "/*" ); 
 
  sscanf( url, "%[^:]://%[^/]%s", protocol, host, path ); 
  if (!host || !stringp(host)) 
  { 
    report_error(LOC_M(19,"Bad URL '%s' for server `%s'")+"\n", 
                 url, conf->query_name()); 
    return 0; 
  } 
 
  if( !protocols[ protocol ] ) 
  { 
    report_error(LOC_M(7,"The protocol '%s' is not available")+"\n", protocol); 
    return 0; 
  } 
 
  sscanf(host, "%[^:]:%d", host, port); 
 
  if( !port ) 
  { 
    port = protocols[ protocol ]->default_port; 
    url = protocol+"://"+host+":"+port+path; 
  } 
 
  if( strlen( path ) && ( path[-1] == '/' ) ) 
    path = path[..strlen(path)-2]; 
  if( !strlen( path ) ) 
    path = 0; 
 
  if( urls[ url ] && urls[ url ]->conf ) 
  { 
    if( urls[ url ]->conf != conf ) 
    { 
      report_error(LOC_M(20, "Cannot register URL %s, " 
                            "already registered by %s!")+"\n", 
                   url, urls[ url ]->conf->name); 
      return 0; 
    } 
    urls[ url ]->port->ref(url, urls[url]); 
    return 1; 
  }  
  else if( urls[ url ] )  
  { 
    urls[ url ]->port->unref( url ); 
  } 
 
  Protocol prot; 
 
  if( !( prot = protocols[ protocol ] ) ) 
  { 
    report_error(LOC_M(21, "Cannot register URL %s, " 
                          "cannot find the protocol %s!")+"\n", 
                 url, protocol); 
    return 0; 
  } 
 
  if( !port ) 
    port = prot->default_port; 
 
  array(string) required_hosts; 
 
  if (is_ip(host)) 
    required_hosts = ({ host }); 
  else 
    required_hosts = find_ips_for( host ); 
 
  if (!required_hosts) 
    required_hosts = ({ 0 });   // ANY 
 
  mapping m; 
  if( !( m = open_ports[ protocol ] ) ) 
    // always add 'ANY' (0) here, as an empty mapping, for speed reasons. 
    // There is now no need to check for both open_ports[prot][0] and 
    // open_ports[prot][0][port], we can go directly to the latter 
    // test. 
    m = open_ports[ protocol ] = ([ 0:([]) ]);  
 
  if( sizeof( required_hosts - ({ 0 }) ) // not ANY 
      && m[ 0 ][ port ] 
      && prot->supports_ipless ) 
    // The ANY port is already open for this port, and since this 
    // protocol supports IP-less virtual hosting, there is no need to 
    // open yet another port, that would mosts probably only conflict 
    // with the ANY port anyway. (this is true on most OSes, it works 
    // on Solaris, but fails on linux) 
    required_hosts = ({ 0 }); 
 
 
  urls[ url ] = ([ "conf":conf, "path":path ]); 
  urls[ ourl ] = ([ "conf":conf, "path":path ]); 
  sorted_urls += ({ url }); 
 
  int failures; 
 
  foreach(required_hosts, string required_host) 
  { 
    if( m[ required_host ] && m[ required_host ][ port ] ) 
    { 
      m[required_host][port]->ref(url, urls[url]); 
 
      urls[url]->port = m[required_host][port]; 
      urls[ourl]->port = m[required_host][port]; 
      continue;    /* No need to open a new port */ 
    } 
 
    if( !m[ required_host ] ) 
      m[ required_host ] = ([ ]); 
 
    mixed err; 
    if (err = catch { 
      m[ required_host ][ port ] = prot( port, required_host ); 
    }) { 
      failures++; 
      report_error(sprintf("Initializing the port handler for URL " + 
                           url + " failed!\n" 
                           "%s\n", 
                           describe_backtrace(err))); 
      continue; 
    } 
 
    if( !( m[ required_host ][ port ] ) ) 
    { 
      m_delete( m[ required_host ], port ); 
      failures++; 
      if (required_host) { 
        report_warning(LOC_M(22, "Binding the port on IP %s " 
                              "failed\n   for URL %s!\n"), 
                       url, required_host); 
      } 
      continue; 
    } 
 
 
    urls[ url ]->port = m[ required_host ][ port ]; 
    urls[ ourl ]->port = m[ required_host ][ port ]; 
    m[ required_host ][ port ]->ref(url, urls[url]); 
  
    if( !m[ required_host ][ port ]->bound ) 
      failures++; 
  } 
  if (failures == sizeof(required_hosts))  
  { 
    report_error(LOC_M(23, "Cannot register URL %s!")+"\n", url); 
    return 0; 
  } 
  sort_urls(); 
  report_notice(" "+LOC_S(3, "Registered %s for %s")+"\n", 
                url, conf->query_name() ); 
 
  return 1; 
} 
 
 
Configuration find_configuration( string name ) 
//! Searches for a configuration with a name or fullname like the 
//! given string. See also get_configuration(). 
{ 
  name = replace( lower_case( replace(name,"-"," ") )-" ", "/", "-" ); 
  foreach( configurations, Configuration o ) 
  { 
    if( (lower_case( replace( replace(o->name, "-"," ") - " " , 
                              "/", "-" ) ) == name) || 
        (lower_case( replace( replace(o->query_name(), "-", " ") - " " , 
                              "/", "-" ) ) == name) ) 
      return o; 
  } 
  return 0; 
} 
 
mapping(string:array(int)) error_log=([]); 
 
// Write a string to the administration interface error log and to stderr. 
void nwrite(string s, int|void perr, int|void errtype, 
            object|void mod, object|void conf) 
{ 
  int log_time = time(1); 
  string reference = (mod ? Roxen.get_modname(mod) : conf && conf->name) || ""; 
  string log_index = sprintf("%d,%s,%s", errtype, reference, s); 
  if(!error_log[log_index]) 
    error_log[log_index] = ({ log_time }); 
  else 
    error_log[log_index] += ({ log_time }); 
 
  if( mod ) 
  { 
    if( !mod->error_log ) 
      mod->error_log = ([]); 
    mod->error_log[log_index] += ({ log_time }); 
  } 
  if( conf ) 
  { 
    if( !conf->error_log ) 
      conf->error_log = ([]); 
    conf->error_log[log_index] += ({ log_time }); 
  } 
 
  if(errtype >= 1) 
    report_debug( s ); 
} 
 
// When was Roxen started? 
int boot_time  =time(); 
int start_time =time(); 
 
string version() 
{ 
#ifndef NSERIOUS 
  return query("default_ident")?real_version:query("ident"); 
#else 
  multiset choices=(<>); 
  string version=query("default_ident")?real_version:query("ident"); 
  return version+", "+ ({ 
    "Applier of Templates", 
    "Beautifier of Layouts", 
    "Conqueror of Comdex", 
    "Deliverer of Documents", 
    "Enhancer of Abilities", 
    "Freer of Webmasters", 
    "Generator of Logs", 
    "Helper of Users", 
    "Interpreter of Scripts", 
    "Juggler of Java-code", 
    "Keeper of Databases", 
    "Locator of Keywords", 
    "Manipulator of Data", 
    "Negatiator of Protocols", 
    "Operator of Sites", 
    "Provider of Contents", 
    "Quintessence of Quality", 
    "Responder to Connections", 
    "Server of Webs", 
    "Translator of Texts", 
    "Unifier of Interfaces", 
    "Valet of Visitors", 
    "Watcher for Requests", 
    "Xylem of Services", 
    "Yielder of Information", 
    "Zenith of Extensibility" 
  })[random(26)]; 
#endif 
} 
 
public void log(mapping file, RequestID request_id) 
{ 
  if(!request_id->conf) return; 
  request_id->conf->log(file, request_id); 
} 
 
#if ROXEN_COMPAT < 2.2 
// Support for unique user id's 
private Stdio.File current_user_id_file; 
private int current_user_id_number, current_user_id_file_last_mod; 
 
private void restore_current_user_id_number() 
{ 
  if(!current_user_id_file) 
    current_user_id_file = open(configuration_dir + "LASTUSER~", "rwc"); 
  if(!current_user_id_file) 
  { 
    call_out(restore_current_user_id_number, 2); 
    return; 
  } 
  current_user_id_number = (int)current_user_id_file->read(100); 
  current_user_id_file_last_mod = current_user_id_file->stat()[2]; 
  report_debug("Restoring unique user ID information. (" + current_user_id_number 
               + ")\n"); 
#ifdef FD_DEBUG 
  mark_fd(current_user_id_file->query_fd(), "Unique user ID logfile.\n"); 
#endif 
} 
 
int increase_id() 
{ 
  if(!current_user_id_file) 
  { 
    restore_current_user_id_number(); 
    return current_user_id_number+time(1); 
  } 
  if(current_user_id_file->stat()[2] != current_user_id_file_last_mod) 
    restore_current_user_id_number(); 
  current_user_id_number++; 
  //werror("New unique id: "+current_user_id_number+"\n"); 
  current_user_id_file->seek(0); 
  current_user_id_file->write((string)current_user_id_number); 
  current_user_id_file_last_mod = current_user_id_file->stat()[2]; 
  return current_user_id_number; 
} 
 
private int unique_id_counter; 
string create_unique_id() 
{ 
  object md5 = Crypto.md5(); 
  md5->update(query("server_salt") + (unique_id_counter++) + time(1)); 
  return Crypto.string_to_hex(md5->digest()); 
} 
#endif 
 
#ifndef __NT__ 
static int abs_started; 
 
void restart_if_stuck (int force) 
{ 
  remove_call_out(restart_if_stuck); 
  if (!(query("abs_engage") || force)) 
    return; 
  if(!abs_started) 
  { 
    abs_started = 1; 
    report_debug("Anti-Block System Enabled.\n"); 
  } 
  call_out (restart_if_stuck,10); 
  signal(signum("SIGALRM"), 
         lambda( int n ) { 
           report_debug("**** %s: ABS engaged!\n" 
                        "Trying to dump backlog: \n", 
                        ctime(time()) - "\n"); 
           catch { 
             // Catch for paranoia reasons. 
             describe_all_threads(); 
           }; 
           report_debug("**** %s: ABS exiting roxen!\n\n", 
                        ctime(time())); 
           _exit(1);    // It might now quit correctly otherwise, if it's 
           //  locked up 
         }); 
  alarm (60*query("abs_timeout")+10); 
} 
#endif 
 
 
class ImageCache 
//! The image cache handles the behind-the-scenes caching and 
//! regeneration features of graphics generated on the fly. Besides 
//! being a cache, however, it serves a wide variety of other 
//! interesting image conversion/manipulation functions as well. 
{ 
  Sql.Sql db; 
  string name; 
  string dir; 
  function draw_function; 
  mapping data_cache = ([]); // not normally used. 
  mapping meta_cache = ([]); 
 
  string documentation(void|string tag_n_args) { 
    string doc = Stdio.read_file("base_server/image_cache.xml"); 
    if(!doc) return ""; 
    if(!tag_n_args) 
      return Parser.HTML()->add_container("ex", "")->finish(doc)->read(); 
    return replace(doc, "###", tag_n_args); 
  } 
 
  static mapping meta_cache_insert( string i, mapping what ) 
  { 
    return meta_cache[i] = what; 
  } 
 
  static string data_cache_insert( string i, string what ) 
  { 
    return data_cache[i] = what; 
  } 
 
  static mixed frommapp( mapping what ) 
  { 
    if( !zero_type(what[""]) ) return what[""]; 
    return what; 
  } 
 
  static void draw( string name, RequestID id ) 
  { 
    mixed args = Array.map( Array.map( name/"$", argcache->lookup, id->client ), frommapp); 
    mapping meta; 
    string data; 
 
    mixed reply = draw_function( @copy_value(args), id ); 
 
    if( arrayp( args ) ) 
      args = args[0]; 
 
    if( arrayp( reply ) ) // layers. 
      reply = Image.lay( reply ); 
 
    if( objectp( reply ) && reply->image ) // layer. 
    { 
      reply = ([ 
        "img":reply->image(), 
        "alpha":reply->alpha(), 
      ]); 
    } 
 
 
    if( objectp( reply ) || (mappingp(reply) && reply->img) ) 
    { 
      int quant = (int)args->quant; 
      string format = lower_case(args->format || "gif"); 
      string dither = args->dither; 
      Image.Colortable ct; 
      Image.Color.Color bgcolor; 
      Image.Image alpha; 
      int true_alpha; 
 
      if( args->fs  || dither == "fs" ) 
        dither = "floyd_steinberg"; 
 
      if(  dither == "random" ) 
        dither = "random_dither"; 
 
      if( format == "jpg" ) 
        format = "jpeg"; 
 
      if( dither ) 
        dither = replace( dither, "-", "_" ); 
 
      if(mappingp(reply)) 
      { 
        alpha = reply->alpha; 
        reply = reply->img; 
      } 
 
      if( args["true-alpha"] ) 
        true_alpha = 1; 
 
      if( args["background"] || args["background-color"]) 
        bgcolor = Image.Color( (args["background"]||args["background-color"]) ); 
 
      if( args["opaque-value"] ) 
      { 
        if( !bgcolor ) true_alpha = 1; 
        int ov = (int)(((float)args["opaque-value"])*2.55); 
        if( ov < 0 ) 
          ov = 0; 
        else if( ov > 255 ) 
          ov = 255; 
        if( alpha ) 
          alpha *= ov; 
        else 
          alpha = Image.Image( reply->xsize(), reply->ysize(), ov,ov,ov ); 
      } 
 
      if( args->gamma ) 
        reply = reply->gamma( (float)args->gamma ); 
 
 
      if( bgcolor && alpha && !true_alpha ) 
      { 
        reply = Image.Image( reply->xsize(), 
                             reply->ysize(), bgcolor ) 
              ->paste_mask( reply, alpha ); 
        alpha = alpha->threshold( 4 ); 
      } 
 
      int x0, y0, x1, y1; 
      if( args["x-offset"] || args["xoffset"] ) 
        x0 = (int)(args["x-offset"]||args["xoffset"]); 
      if( args["y-offset"] || args["yoffset"] ) 
        y0 = (int)(args["y-offset"]||args["yoffset"]); 
      if( args["width"] || args["x-size"] ); 
        x1 = (int)(args["x-size"]||args["width"]); 
      if( args["height"] || args["y-size"] ); 
        y1 = (int)(args["y-size"]||args["height"]); 
 
      if( args->crop ) 
      { 
        if( sscanf( args->crop, "%d,%d-%d,%d", x0, y0, x1, y1 ) ) 
        { 
          x1 -= x0; 
          y1 -= y0; 
        } else { 
          [ x0, y0, x1, y1 ] = reply->find_autocrop(); 
          x1 -= x0; 
          y1 -= y0; 
        } 
      } 
 
      if( x0 || x1 || y0 || y1 ) 
      { 
        if( !x1 ) x1 = reply->xsize()-x0; 
        if( !y1 ) y1 = reply->ysize()-y0; 
        reply = reply->copy( x0,y0,x0+x1-1,y0+y1-1 ); 
        if( alpha ) 
          alpha = alpha->copy( x0,y0,x0+x1-1,y0+y1-1 ); 
      } 
 
      if( args->scale ) 
      { 
        int x, y; 
        if( sscanf( args->scale, "%d,%d", x, y ) == 2) 
        { 
          reply = reply->scale( x, y ); 
          if( alpha ) 
            alpha = alpha->scale( x, y ); 
        } 
        else if( (float)args->scale < 3.0) 
        { 
          reply = reply->scale( ((float)args->scale) ); 
          if( alpha ) 
            alpha = alpha->scale( ((float)args->scale) ); 
        } 
      } 
 
      if( args->maxwidth || args->maxheight || 
          args["max-width"] || args["max-height"]) 
      { 
        int x = (int)args->maxwidth||(int)args["max-width"]; 
        int y = (int)args->maxheight||(int)args["max-height"]; 
        if( x && reply->xsize() > x ) 
        { 
          reply = reply->scale( x, 0 ); 
          if( alpha ) 
            alpha = alpha->scale( x, 0 ); 
        } 
        if( y && reply->ysize() > y ) 
        { 
          reply = reply->scale( 0, y ); 
          if( alpha ) 
            alpha = alpha->scale( 0, y ); 
        } 
      } 
 
      if( args["rotate-cw"] || args["rotate-ccw"]) 
      { 
        float degree = (float)(args["rotate-cw"] || args["rotate-ccw"]); 
        switch( args["rotate-unit"] && args["rotate-unit"][0..0] ) 
        { 
         case "r":  degree = (degree / (2*3.1415)) * 360; break; 
         case "d":  break; 
         case "n":  degree = (degree / 400) * 360;        break; 
         case "p":  degree = (degree / 1.0) * 360;        break; 
        } 
        if( args["rotate-cw"] ) 
          degree = -degree; 
        if(!alpha) 
          alpha = reply->copy()->clear(255,255,255); 
        reply = reply->rotate_expand( degree ); 
        alpha = alpha->rotate( degree, 0,0,0 ); 
      } 
 
 
      if( args["mirror-x"] ) 
      { 
        if( alpha ) 
          alpha = alpha->mirrorx(); 
        reply = reply->mirrorx(); 
      } 
 
      if( args["mirror-y"] ) 
      { 
        if( alpha ) 
          alpha = alpha->mirrory(); 
        reply = reply->mirrory(); 
      } 
 
      if( bgcolor && alpha && !true_alpha ) 
      { 
        reply = Image.Image( reply->xsize(), 
                             reply->ysize(), bgcolor ) 
              ->paste_mask( reply, alpha ); 
      } 
 
      if( args["cs-rgb-hsv"] )reply = reply->rgb_to_hsv(); 
      if( args["cs-grey"] )   reply = reply->grey(); 
      if( args["cs-invert"] ) reply = reply->invert(); 
      if( args["cs-hsv-rgb"] )reply = reply->hsv_to_rgb(); 
 
      if( !true_alpha && alpha ) 
        alpha = alpha->threshold( 4 ); 
 
      if( quant || (format=="gif") ) 
      { 
        int ncols = quant; 
        if( format=="gif" ) { 
          ncols = ncols||id->misc->defquant||32; 
          if( ncols > 254 ) 
            ncols = 254; 
        } 
        ct = Image.Colortable( reply, ncols ); 
        if( dither ) 
        { 
          if( dither == "random" )  
            dither = "random_grey"; 
          if( ct[ dither ] ) 
            ct[ dither ](); 
          else 
            ct->ordered(); 
         
        } 
      } 
 
      mapping enc_args = ([]); 
      if( ct ) 
        enc_args->colortable = ct; 
 
      if( alpha ) 
        enc_args->alpha = alpha; 
 
      foreach( glob( "*-*", indices(args)), string n ) 
        if(sscanf(n, "%*[^-]-%s", string opt ) == 2) 
          if( opt != "alpha" ) 
            enc_args[opt] = (int)args[n]; 
 
      switch(format) 
      { 
       case "gif": 
#if constant(Image.GIF) && constant(Image.GIF.encode) 
         if( alpha && true_alpha ) 
         { 
           Image.Colortable bw=Image.Colortable( ({ ({ 0,0,0 }),  
                                                    ({ 255,255,255 }) }) ); 
           bw->floyd_steinberg(); 
           alpha = bw->map( alpha ); 
         } 
         if( catch { 
           if( alpha ) 
             data = Image.GIF.encode_trans( reply, ct, alpha ); 
           else 
             data = Image.GIF.encode( reply, ct ); 
         }) 
           data = Image.GIF.encode( reply ); 
         break; 
 
#else 
         // Fall-through when there is no GIF encoder available -- 
         // use PNG with a colortable instead. 
         format = "png"; 
#endif 
 
       case "png": 
         if( ct ) enc_args->palette = ct; 
         m_delete( enc_args, "colortable" ); 
         if( !(args["png-use-alpha"] || args["true-alpha"]) ) 
           m_delete( enc_args, "alpha" ); 
         else if( enc_args->alpha ) 
           // PNG encoder doesn't handle alpha and palette simultaneously 
           // which is rather sad, since that's the only thing 100% supported 
           // by all common browsers. 
           m_delete( enc_args, "palette"); 
         else 
           m_delete( enc_args, "alpha" ); 
 
       default: 
         if(!Image[upper_case( format )] 
            || !Image[upper_case( format )]->encode ) 
           error("Image format "+format+" unknown\n"); 
         data = Image[upper_case( format )]->encode( reply, enc_args ); 
      } 
 
      meta = 
      ([ 
        "xsize":reply->xsize(), 
        "ysize":reply->ysize(), 
        "type":"image/"+format, 
      ]); 
    } 
    else if( mappingp(reply) ) 
    { 
      meta = reply->meta; 
      data = reply->data; 
      if( !meta || !data ) 
        error("Invalid reply mapping.\n" 
              "Expected ([ \"meta\": ([metadata]), \"data\":\"data\" ])\n" 
              "Got %O\n", reply); 
    } 
    // Avoid throwing and error if the same image is rendered twice. 
    catch(store_data( name, data, meta )); 
  } 
 
  static void store_data( string id, string data, mapping meta ) 
  { 
    if(!stringp(data)) return; 
    meta_cache_insert( id, meta ); 
    string meta_data = encode_value( meta ); 
    db->query( "INSERT INTO "+name+"_data VALUES (%s,%s,%s)", 
               id,meta_data,data); 
    db->query( "INSERT INTO "+name+" VALUES ('"+id+"', "+strlen(data)+ 
               ", UNIX_TIMESTAMP(), UNIX_TIMESTAMP())" ); 
  } 
 
  static mapping restore_meta( string id ) 
  { 
    if( meta_cache[ id ] ) 
      return meta_cache[ id ]; 
 
    array(mapping(string:string)) q = db->query("SELECT meta FROM "+ 
                                                name+"_data WHERE id='"+ 
                                                id+"'"); 
    db->query("UPDATE "+name+" SET atime=UNIX_TIMESTAMP() WHERE id='"+id+"'" ); 
 
    if(!sizeof(q)) 
      return 0; 
    string s = q[0]->meta; 
    mapping m; 
    if (catch (m = decode_value (s))) 
    { 
      report_error( "Corrupt data in cache-entry "+id+".\n" ); 
      db->query( "DELETE FROM "+name+" WHERE id='"+id+"'" ); 
      db->query( "DELETE FROM "+name+"_data WHERE id='"+id+"'" ); 
      return 0; 
    } 
    return meta_cache_insert( id, m ); 
  } 
 
  void flush(int|void age) 
  //! Flush the cache. If an age (an integer as returned by 
  //! <pi>time()</pi>) is provided, only images with their latest access before 
  //! that time are flushed. 
  { 
 
    report_debug("Flushing "+name+" image cache.\n"); 
    if( !age ) 
    { 
      db->query( "DELETE FROM "+name ); 
      db->query( "DELETE FROM "+name+"_data" ); 
      return; 
    } 
 
    array(string) ids = db->query( "SELECT id FROM "+name+" WHERE atime < "+age)->id; 
 
    int q; 
    while(q<sizeof(ids)) { 
      string list = ids[q..q+100] * "','"; 
      q+=100; 
 
      db->query( "DELETE FROM "+name+     " WHERE id in ('"+list+"')" ); 
      db->query( "DELETE FROM "+name+"_data WHERE id in ('"+list+"')" ); 
    } 
 
    catch 
    { 
      // Old versions of Mysql lacks OPTIMIZE. Not that we support 
      // them, really, but it might be nice not to throw an error, at 
      // least. 
      db->query( "OPTIMIZE TABLE "+name+"_data" ); 
      db->query( "OPTIMIZE TABLE "+name ); 
    }; 
 
    data_cache = ([]); 
    meta_cache = ([]); 
  } 
 
  array(int) status(int|void age) 
  //! Return the total number of images in the cache, their cumulative 
  //! sizes in bytes and, if an age time_t was supplied, the number of 
  //! images that has not been accessed after that time is returned 
  //!  (see <ref>flush()</ref>). (Three integers are returned 
  //! regardless of whether an age parameter was given.) 
  { 
    int imgs=0, size=0, aged=0; 
    array(mapping(string:string)) q; 
 
    q=db->query("SHOW TABLE STATUS"); 
    foreach(q, mapping qq) 
      if(has_prefix(qq->Name, name)) { 
        imgs = (int)qq->Rows; 
        size += (int)qq->Data_length; 
      } 
 
    if(age) { 
      q=db->query("select SUM(1) as num from "+name+" where atime < "+age); 
      aged = (int)q[0]->num; 
    } 
    return ({ imgs, size, aged }); 
  } 
 
  static mapping restore( string id ) 
  { 
    mixed f; 
    mapping m; 
 
    if( data_cache[ id ] ) { 
      f = data_cache[ id ]; 
      m = restore_meta( id ); 
 
      if(!m) 
        return 0; 
    } 
    else 
    { 
      array(mapping(string:string)) q = 
        db->query( "SELECT data,meta FROM "+name+"_data WHERE id=%s",id); 
      if( sizeof(q) ) { 
        f = q[0]->data; 
        if( catch( m = decode_value(q[0]->meta) ) ) { 
          report_error( "Corrupt data in cache-entry "+id+".\n" ); 
          db->query( "DELETE FROM "+name+" WHERE id='"+id+"'" ); 
          db->query( "DELETE FROM "+name+"_data WHERE id='"+id+"'" ); 
          return 0; 
        } 
      } 
      else 
        return 0; 
 
      if(m) 
        db->query("UPDATE "+name+" SET atime=UNIX_TIMESTAMP() WHERE id='"+id+"'" ); 
      else 
        return 0; 
    } 
 
    return Roxen.http_string_answer( f, m->type||("image/gif") ); 
  } 
 
 
  string data( array|string|mapping args, RequestID id, int|void nodraw ) 
  //! Returns the actual raw image data of the image rendered from the 
  //! `data' instructions. 
  //! 
  //! A non-zero `nodraw' parameter means an image not already in the 
  //! cache will not be rendered on the fly, but instead return zero. 
  { 
    string na = store( args, id ); 
    mixed res; 
 
    if(!( res = restore( na )) ) 
    { 
      if(nodraw) 
        return 0; 
      draw( na, id ); 
      res = restore( na ); 
    } 
    if( res->file ) 
      return res->file->read(); 
    return res->data; 
  } 
 
  mapping http_file_answer( array|string|mapping data, 
                            RequestID id, 
                            int|void nodraw ) 
  //! Returns a <ref>result mapping</ref> like one generated by 
  //! <ref>Roxen.http_file_answer()</ref> but for the image file 
  //! rendered from the `data' instructions. 
  //! 
  //! Like <ref>metadata</ref>, a non-zero `nodraw' parameter means an 
  //! image not already in the cache will not be rendered on the fly, 
  //! but instead return zero (for request not handled). 
  { 
    string na = store( data,id ); 
    mixed res; 
    if(!( res = restore( na )) ) 
    { 
      if(nodraw) 
        return 0; 
      draw( na, id ); 
      res = restore( na ); 
    } 
    return res; 
  } 
 
  mapping metadata( array|string|mapping data, 
                    RequestID id, 
                    int|void nodraw ) 
  //! Returns a mapping of image metadata for an image generated from 
  //! the data given (as sent to <ref>store()</ref>). If a non-zero 
  //! `nodraw' parameter is given and the image was not in the cache, 
  //! it will not be rendered on the fly to get the correct data. 
  { 
    string na = store( data,id ); 
    if(!restore_meta( na )) 
    { 
      if(nodraw) 
        return 0; 
      draw( na, id ); 
      return restore_meta( na ); 
    } 
    return restore_meta( na ); 
  } 
 
  mapping tomapp( mixed what ) 
  { 
    if( mappingp( what )) 
      return what; 
    return ([ "":what ]); 
  } 
 
  string store( array|string|mapping data, RequestID id ) 
  //! Store the data your draw callback expects to receive as its 
  //! first argument(s). If the data is an array, the draw callback 
  //! will be called like <pi>callback( @data, id )</pi>. 
  { 
    string ci; 
    if( mappingp( data ) ) { 
      if (!data->format) { 
        //  Make implicit format choice explicit 
#if constant(Image.GIF) && constant(Image.GIF.encode) 
      data->format = "gif"; 
#else 
      data->format = "png"; 
#endif 
      } 
      ci = argcache->store( data ); 
    } else if( arrayp( data ) ) { 
      if (!data[0]->format) { 
        //  Make implicit format choice explicit 
#if constant(Image.GIF) && constant(Image.GIF.encode) 
      data[0]->format = "gif"; 
#else 
        data[0]->format = "png"; 
#endif 
      } 
      ci = map( map( data, tomapp ), argcache->store )*"$"; 
    } else 
      ci = data; 
    return ci; 
  } 
 
  void set_draw_function( function to ) 
  //! Set a new draw function. 
  { 
    draw_function = to; 
  } 
 
  static void setup_tables() 
  { 
    if(catch(db->query("select id from "+name+" where id=-1"))) 
    { 
      db->query("CREATE TABLE "+name+" (" 
                "id CHAR(64) NOT NULL PRIMARY KEY, " 
                "size INT UNSIGNED NOT NULL DEFAULT 0, " 
                "ctime INT UNSIGNED NOT NULL DEFAULT 0, " 
                "atime INT UNSIGNED NOT NULL DEFAULT 0)"); 
 
      db->query("CREATE TABLE "+name+"_data (" 
                "id CHAR(64) NOT NULL PRIMARY KEY, " 
                "meta MEDIUMBLOB NOT NULL DEFAULT ''," 
                "data MEDIUMBLOB NOT NULL DEFAULT '')"); 
    } 
  } 
 
   
  void create( string id, function draw_func ) 
  //! Instantiate an image cache of your own, whose image files will 
  //! be stored in a table `id' in the cache mysql database, 
  //! 
  //! The `draw_func' callback passed will be responsible for 
  //! (re)generation of the images in the cache. Your draw callback 
  //! may take any arguments you want, depending on the first argument 
  //! you give the <ref>store()</ref> method, but its final argument 
  //! will be the RequestID object. 
  { 
    db = connect_to_my_mysql( 0, "cache" ); 
    name = id; 
    draw_function = draw_func; 
    catch(setup_tables()); 
  } 
} 
 
 
class ArgCache 
//! Generic cache for storing away a persistent mapping of data to be 
//! refetched later by a short string key. This being a cache, your 
//! data may be thrown away at random when the cache is full. 
{ 
  static Sql.Sql db; 
  static string name; 
 
#define CACHE_VALUE 0 
#define CACHE_SKEY  1 
#define CACHE_SIZE  600 
#define CLEAN_SIZE  100 
 
  static string lq, ulq; 
  class DBLock 
  { 
    static void create() 
    { 
      if(!lq) 
      { 
        lq = "select GET_LOCK('"+name+"', 4)"; 
        ulq = "select RELEASE_LOCK('"+name+"')"; 
      } 
      db->query( lq ); 
    } 
    static void destroy() 
    { 
      db->query( ulq ); 
    } 
  } 
   
# define LOCK() DBLock __ = DBLock() 
 
  static mapping (string:mixed) cache = ([ ]); 
 
  static void setup_table() 
  { 
    if(catch(db->query("SELECT id FROM "+name+" WHERE id=-1"))) 
      db->query("CREATE TABLE "+name+" (" 
                "id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, " 
                "lkey CHAR(10) NOT NULL DEFAULT '', " 
                "atime INT UNSIGNED NOT NULL DEFAULT 0, " 
                "contents BLOB NOT NULL DEFAULT '' " 
                ")"); 
  } 
 
  void create( string _name ) 
  //! Instantiates an argument cache of your own. 
  { 
    name = _name; 
    db = connect_to_my_mysql( 0, "cache" ); 
    setup_table( ); 
  } 
 
  static string read_args( string id ) 
  { 
    array res = db->query("SELECT contents FROM "+name+" WHERE id="+id); 
    if( sizeof(res) ) 
    { 
      db->query("UPDATE "+name+" SET atime='"+time(1)+"' WHERE id="+id); 
      return res[0]->contents; 
    } 
    return 0; 
  } 
 
  static string create_key( string long_key ) 
  { 
    array data = db->query("SELECT id,contents FROM "+name+" WHERE lkey=%s", 
                           long_key[5..14]); 
    foreach( data, mapping m ) 
      if( m->contents == long_key ) 
        return m->id; 
 
    db->query( "INSERT INTO "+name+" (contents,lkey,atime) VALUES " 
               "(%s,%s,UNIX_TIMESTAMP())", 
               name, long_key, long_key[5..14] ); 
    return (string)db->master_sql->insert_id(); 
  } 
 
 
  int key_exists( string key ) 
  //! Does the key 'key' exist in the cache? Returns 1 if it does, 0 
  //! if it was not present. 
  { 
    return sizeof( db->query( "SELECT id FROM "+name+" WHERE id="+(int)key)); 
  } 
 
  string store( mapping args ) 
  //! Store a mapping (of purely encode_value:able data) in the 
  //! argument cache. The string returned is your key to retrieve the 
  //! data later. 
  { 
    array b = values(args), a = sort(indices(args),b); 
    string data = encode_value(({a,b})); 
 
    if( cache[ data ] ) 
      return cache[ data ][ CACHE_SKEY ]; 
 
    if( sizeof( cache ) >= CACHE_SIZE ) 
    { 
      array i = indices(cache); 
      while( sizeof(cache) > CACHE_SIZE-CLEAN_SIZE ) { 
        string idx=i[random(sizeof(i))]; 
        if(arrayp(cache[idx])) { 
          m_delete( cache, cache[idx][CACHE_SKEY] ); 
          m_delete( cache, idx ); 
        } 
        else { 
          m_delete( cache, cache[idx] ); 
          m_delete( cache, idx ); 
        } 
      } 
    } 
 
    LOCK(); 
    string id = create_key( data ); 
    cache[ data ] = ({ 0, 0 }); 
    cache[ data ][ CACHE_VALUE ] = copy_value( args ); 
    cache[ data ][ CACHE_SKEY ] = id; 
    cache[ id ] = data; 
    return id; 
  } 
 
  mapping lookup( string id, array|void client ) 
  //! Recall a mapping stored in the cache. The optional client array 
  //! may be supplied to get an error message stating the browser name 
  //! in the event of the key not being present any more in the cache. 
  { 
    if(cache[id] && cache[ cache[id] ] ) 
      return cache[cache[id]][CACHE_VALUE]; 
 
    string q = read_args( id ); 
 
    if(!q) error("Requesting unknown key\n"); 
 
    mixed data = decode_value(q); 
    data = mkmapping( data[0],data[1] ); 
 
    cache[ q ] = ({0,0}); 
    cache[ q ][ CACHE_VALUE ] = data; 
    cache[ q ][ CACHE_SKEY ] = id; 
    cache[ id ] = q; 
    return data; 
  } 
 
  void delete( string id ) 
  //! Remove the data element stored under the key 'id'. 
  { 
    if(cache[id]) 
    { 
      m_delete( cache, cache[id] ); 
      m_delete( cache, id ); 
    } 
    db->query( "DELETE FROM "+name+" WHERE id="+(int)id ); 
  } 
} 
 
mapping cached_decoders = ([]); 
string decode_charset( string charset, string data ) 
{ 
  // FIXME: This code is probably not thread-safe! 
  if( charset == "iso-8859-1" ) return data; 
  if( !cached_decoders[ charset ] ) 
    cached_decoders[ charset ] = Locale.Charset.decoder( charset ); 
  data = cached_decoders[ charset ]->feed( data )->drain(); 
  cached_decoders[ charset ]->clear(); 
  return data; 
} 
 
void create() 
{ 
  // Register localization projects 
#define __REG_PROJ Locale.register_project 
  __REG_PROJ("roxen_start",   "translations/%L/roxen_start.xml"); 
  __REG_PROJ("roxen_config",  "translations/%L/roxen_config.xml"); 
  __REG_PROJ("roxen_message", "translations/%L/roxen_message.xml"); 
  __REG_PROJ("admin_tasks",   "translations/%L/admin_tasks.xml"); 
  Locale.set_default_project_path("translations/%L/%P.xml"); 
#undef __REG_PROJ 
 
  define_global_variables(); 
 
  // This is currently needed to resolve the circular references in 
  // RXML.pmod correctly. :P 
  master()->resolv ("RXML.refs"); 
  master()->resolv ("RXML.PXml"); 
  master()->resolv ("RXML.PEnt"); 
  foreach(({ "module.pmod","PEnt.pike", "PExpr.pike","PXml.pike", 
             "refs.pmod","utils.pmod" }), string q ) 
    dump( "etc/modules/RXML.pmod/"+ q ); 
  dump( "etc/modules/RXML.pmod/module.pmod" ); 
  // Already loaded. No delayed dump possible. 
  dump( "etc/roxen_master.pike" ); 
  dump( "etc/modules/Roxen.pmod" ); 
  dump( "base_server/config_userdb.pike" ); 
  dump( "base_server/disk_cache.pike" ); 
  dump( "base_server/roxen.pike" ); 
  dump( "base_server/basic_defvar.pike" ); 
  dump( "base_server/newdecode.pike" ); 
  dump( "base_server/read_config.pike" ); 
  dump( "base_server/global_variables.pike" ); 
  dump( "base_server/module_support.pike" ); 
  dump( "base_server/socket.pike" ); 
  dump( "base_server/cache.pike" ); 
  dump( "base_server/supports.pike" ); 
  dump( "base_server/hosts.pike"); 
  dump( "base_server/language.pike"); 
 
#ifndef __NT__ 
  if(!getuid()) 
    add_constant("Privs", Privs); 
  else 
#endif /* !__NT__ */ 
    add_constant("Privs", class { 
      void create(string reason, int|string|void uid, int|string|void gid) {} 
    }); 
 
 
  // for module encoding stuff 
 
  add_constant( "ArgCache", ArgCache ); 
  //add_constant( "roxen.load_image", load_image ); 
 
  add_constant( "roxen", this_object()); 
  //add_constant( "roxen.decode_charset", decode_charset); 
 
  add_constant( "DBManager", ((object)"base_server/dbs.pike") ); 
  dump( "base_server/dbs.pike"); 
 
  add_constant( "RoxenModule", RoxenModule); 
  add_constant( "ModuleInfo", ModuleInfo ); 
 
  add_constant( "load",    load); 
  add_constant( "Roxen.set_locale", set_locale ); 
  add_constant( "Roxen.get_locale", get_locale ); 
 
  add_constant( "roxen.locale", locale ); 
  //add_constant( "roxen.ImageCache", ImageCache ); 
 
//   int s = gethrtime(); 
  _configuration = (program)"configuration"; 
  dump( "base_server/configuration.pike" ); 
  dump( "base_server/rxmlhelp.pike" ); 
  add_constant( "Configuration", _configuration ); 
 
//   report_debug( "[Configuration: %.2fms] ", (gethrtime()-s)/1000.0); 
} 
 
mixed get_locale( ) 
{ 
  return locale->get(); 
} 
 
int set_u_and_gid() 
//! Set the uid and gid to the ones requested by the user. If the 
//! sete* functions are available, and the define SET_EFFECTIVE is 
//! enabled, the euid and egid is set. This might be a minor security 
//! hole, but it will enable roxen to start CGI scripts with the 
//! correct permissions (the ones the owner of that script have). 
{ 
#ifndef __NT__ 
  string u, g; 
  int uid, gid; 
  array pw; 
 
  u=query("User"); 
  sscanf(u, "%s:%s", u, g); 
  if(strlen(u)) 
  { 
    if(getuid()) 
    { 
      report_error(LOC_M(24, "It is only possible to change uid and gid " 
                         "if the server is running as root.")+"\n"); 
    } else { 
      if (g) { 
#if constant(getgrnam) 
      pw = getgrnam (g); 
        if (!pw) 
          if (sscanf (g, "%d", gid)) pw = getgrgid (gid), g = (string) gid; 
          else report_error ("Couldn't resolve group " + g + ".\n"), g = 0; 
        if (pw) g = pw[0], gid = pw[2]; 
#else 
      if (!sscanf (g, "%d", gid)) 
          report_warning ("Can't resolve " + g + " to gid on this system; " 
                          "numeric gid required.\n"); 
#endif 
      } 
 
      pw = getpwnam (u); 
      if (!pw) 
        if (sscanf (u, "%d", uid)) pw = getpwuid (uid), u = (string) uid; 
        else { 
          report_error ("Couldn't resolve user " + u + ".\n"); 
          return 0; 
        } 
      if (pw) { 
        u = pw[0], uid = pw[2]; 
        if (!g) gid = pw[3]; 
      } 
 
#ifdef THREADS 
      Thread.MutexKey mutex_key; 
      catch { mutex_key = euid_egid_lock->lock(); }; 
      object threads_disabled = _disable_threads(); 
#endif 
 
#if constant(seteuid) 
      if (geteuid() != getuid()) seteuid (getuid()); 
#endif 
 
#if constant(initgroups) 
      catch { 
        initgroups(pw[0], gid); 
        // Doesn't always work - David. 
      }; 
#endif 
 
      if (query("permanent_uid")) { 
#if constant(setuid) 
      if (g) { 
#  if constant(setgid) 
        setgid(gid); 
          if (getgid() != gid) { 
            report_error(LOC_M(25, "Failed to set gid.")+"\n"); 
            g = 0; 
          } 
#  else 
        report_warning(LOC_M(26, "Setting gid not supported on this system.") 
                         +"\n"); 
          g = 0; 
#  endif 
      } 
        setuid(uid); 
        if (getuid() != uid) {  
          report_error(LOC_M(27, "Failed to set uid.")+"\n");  
          u = 0; 
        } 
        if (u) report_notice(CALL_M("setting_uid_gid_permanently",  "eng") 
                             (uid, gid, u, g)); 
#else 
      report_warning(LOC_M(28, "Setting uid not supported on this system.") 
                       +"\n"); 
        u = g = 0; 
#endif 
      } 
      else { 
#if constant(seteuid) 
      if (g) { 
#  if constant(setegid) 
        setegid(gid); 
          if (getegid() != gid) { 
            report_error(LOC_M(29, "Failed to set effective gid.")+"\n"); 
            g = 0; 
          } 
#  else 
        report_warning(LOC_M(30, "Setting effective gid not supported on " 
                               "this system.")+"\n"); 
          g = 0; 
#  endif 
      } 
        seteuid(uid); 
        if (geteuid() != uid) { 
          report_error(LOC_M(31, "Failed to set effective uid.")+"\n"); 
          u = 0; 
        } 
        if (u) report_notice(CALL_M("setting_uid_gid", "eng")(uid, gid, u, g)); 
#else 
      report_warning(LOC_M(32, "Setting effective uid not supported on " 
                             "this system.")+"\n"); 
        u = g = 0; 
#endif 
      } 
 
      return !!u; 
    } 
  } 
#endif 
  return 0; 
} 
 
void reload_all_configurations() 
{ 
  Configuration conf; 
  array (object) new_confs = ({}); 
  mapping config_cache = ([]); 
  int modified; 
 
  setvars(retrieve("Variables", 0)); 
 
  foreach(list_all_configurations(), string config) 
  { 
    mixed err; 
    Stat st; 
    conf = find_configuration( config ); 
    if(!(st = config_is_modified(config))) { 
      if(conf) { 
        config_cache[config] = config_stat_cache[config]; 
        new_confs += ({ conf }); 
      } 
      continue; 
    } 
    modified = 1; 
    config_cache[config] = st; 
    if(conf) 
    { 
      conf->stop(); 
      conf->invalidate_cache(); 
      conf->create(conf->name); 
    } else { 
      if(err = catch 
      { 
        conf = enable_configuration(config); 
      }) { 
        string bt=describe_backtrace(err); 
        report_error(LOC_M(33, "Error while enabling configuration %s%s"), 
                     config, (bt ? ":\n"+bt : "\n")); 
        continue; 
      } 
    } 
    if(err = catch 
    { 
      conf->start( 0 ); 
      conf->enable_all_modules(); 
    }) { 
      string bt=describe_backtrace(err); 
      report_error(LOC_M(33, "Error while enabling configuration %s%s"), 
                   config, (bt ? ":\n"+bt : "\n" )); 
      continue; 
    } 
    new_confs += ({ conf }); 
  } 
 
  foreach(configurations - new_confs, conf) 
  { 
    modified = 1; 
    report_notice(LOC_M(34,"Disabling old configuration %s")+"\n", conf->name); 
    conf->stop(); 
    destruct(conf); 
  } 
  if(modified) { 
    configurations = new_confs; 
    fix_config_lookup(); 
    config_stat_cache = config_cache; 
  } 
} 
 
private mapping(string:Configuration) config_lookup = ([]); 
// Maps config name to config object. 
 
void fix_config_lookup() 
{ 
  config_lookup = mkmapping (configurations->name, configurations); 
#ifdef DEBUG 
  if (sizeof (configurations) != sizeof (config_lookup)) 
    error ("Duplicate configuration names in configurations array: %O", 
           configurations->name); 
#endif 
} 
 
Configuration get_configuration (string name) 
//! Gets the configuration with the given identifier name. 
{ 
#ifdef DEBUG 
  if (sizeof (configurations) != sizeof (config_lookup)) 
    error ("config_lookup out of synch with configurations.\n"); 
#endif 
  return config_lookup[name]; 
} 
 
Configuration enable_configuration(string name) 
{ 
#ifdef DEBUG 
  if (get_configuration (name)) 
    error ("A configuration called %O already exists.\n", name); 
#endif 
  Configuration cf = _configuration( name ); 
  configurations += ({ cf }); 
  fix_config_lookup(); 
  return cf; 
} 
 
void disable_configuration (string name) 
{ 
  if (Configuration conf = config_lookup[ name ]) { 
    configurations -= ({conf}); 
    fix_config_lookup(); 
  } 
} 
 
void remove_configuration (string name) 
{ 
  disable_configuration (name); 
  ::remove_configuration (name); 
} 
 
// Enable all configurations 
void enable_configurations() 
{ 
  array err; 
  configurations = ({}); 
  config_lookup = ([]); 
 
  foreach(list_all_configurations(), string config) 
  { 
    int t = gethrtime(); 
    report_debug("\nEnabling the configuration %s ...\n", config); 
    if(err=catch( enable_configuration(config)->start(0) )) 
      report_error("\n"+LOC_M(35, "Error while loading configuration %s%s"), 
                   config+":\n", describe_backtrace(err)+"\n"); 
    report_debug("Enabled %s in %.1fms\n", config, (gethrtime()-t)/1000.0 ); 
  } 
  foreach( configurations, Configuration c ) 
  { 
    if(sizeof( c->registered_urls ) ) 
      return; 
  } 
  report_fatal("No configurations could open any ports. Will shutdown.\n"); 
  shutdown(); 
} 
 
int all_modules_loaded; 
void enable_configurations_modules() 
{ 
  if( all_modules_loaded++ ) return; 
  foreach(configurations, Configuration config) 
    if(mixed err=catch( config->enable_all_modules() )) 
      report_error(LOC_M(36, "Error while loading modules in " 
                         "configuration %s%s"), 
                   config->name+":\n", describe_backtrace(err)+"\n"); 
} 
 
mapping low_decode_image(string data, void|mixed tocolor) 
{ 
  mapping w = Image._decode( data, tocolor ); 
  if( w->image ) return w; 
  return 0; 
} 
 
constant decode_layers = Image.decode_layers; 
 
mapping low_load_image(string f, RequestID id) 
{ 
  string data; 
  Stdio.File file; 
  if(id->misc->_load_image_called < 5) 
  { 
    // We were recursing very badly with the demo module here... 
    id->misc->_load_image_called++; 
    if(!(data=id->conf->try_get_file(f, id))) 
    { 
      file=Stdio.File(); 
      if(!file->open(f,"r") || !(data=file->read())) 
#ifdef THREADS 
        catch 
        { 
          string host = ""; 
          sscanf( f, "http://%[^/]", host ); 
          if( sscanf( host, "%*s:%*d" ) != 2) 
            host += ":80"; 
          mapping hd =  
                  ([ 
                    "User-Agent":version(), 
                    "Host":host, 
                  ]); 
          data = Protocols.HTTP.get_url_data( f, 0, hd ); 
        }; 
#endif 
      if( !data ) 
        return 0; 
    } 
  } 
  id->misc->_load_image_called = 0; 
  if(!data) return 0; 
  return low_decode_image( data ); 
} 
 
array(Image.Layer) load_layers(string f, RequestID id, mapping|void opt) 
{ 
  string data; 
  Stdio.File file; 
  if(id->misc->_load_image_called < 5) 
  { 
    // We were recursing very badly with the demo module here... 
    id->misc->_load_image_called++; 
    if(!(data=id->conf->try_get_file(f, id))) 
    { 
      file=Stdio.File(); 
      if(!file->open(f,"r") || !(data=file->read())) 
#ifdef THREADS 
        catch 
        { 
          data = Protocols.HTTP.get_url_nice( f )[1]; 
        }; 
#endif 
      if( !data ) 
        return 0; 
    } 
  } 
  id->misc->_load_image_called = 0; 
  if(!data) return 0; 
  return decode_layers( data, opt ); 
} 
 
Image.Image load_image(string f, RequestID id) 
{ 
  mapping q = low_load_image( f, id ); 
  if( q ) return q->img; 
  return 0; 
} 
 
// do the chroot() call. This is not currently recommended, since 
// roxen dynamically loads modules, all module files must be 
// available at the new location. 
 
private void fix_root(string to) 
{ 
#ifndef __NT__ 
  if(getuid()) 
  { 
    report_debug("It is impossible to chroot() if the server is not run as root.\n"); 
    return; 
  } 
 
  if(!chroot(to)) 
  { 
    report_debug("Roxen: Cannot chroot to "+to+": "); 
#if efun(real_perror) 
    real_perror(); 
#endif 
    return; 
  } 
  report_debug("Root is now "+to+".\n"); 
#endif 
} 
 
void create_pid_file(string where) 
{ 
#ifndef __NT__ 
  if(!where) return; 
  where = replace(where, ({ "$pid", "$uid" }), 
                  ({ (string)getpid(), (string)getuid() })); 
 
  r_rm(where); 
  if(catch(Stdio.write_file(where, sprintf("%d\n%d", getpid(), getppid())))) 
    report_debug("I cannot create the pid file ("+where+").\n"); 
#endif 
} 
 
program pipe; 
Pipe.pipe shuffle(Stdio.File from, Stdio.File to, 
                       Stdio.File|void to2, 
                       function(:void)|void callback) 
{ 
#if efun(spider.shuffle) 
  if(!to2) 
  { 
    if(!pipe) 
      pipe = ((program)"smartpipe"); 
    object p = pipe( ); 
    p->input(from); 
    p->set_done_callback(callback); 
    p->output(to); 
    return p; 
  } else { 
#endif 
    // 'smartpipe' does not support multiple outputs. 
    Pipe.pipe p = Pipe.pipe(); 
    if (callback) p->set_done_callback(callback); 
    p->output(to); 
    if(to2) p->output(to2); 
    p->input(from); 
    return p; 
#if efun(spider.shuffle) 
  } 
#endif 
} 
 
 
static private int _recurse; 
// FIXME: Ought to use the shutdown code. 
void exit_when_done() 
{ 
  report_debug("Interrupt request received. Exiting,\n"); 
  die_die_die=1; 
 
  if(++_recurse > 4) 
  { 
    report_debug("Exiting roxen (spurious signals received).\n"); 
    configurations->stop(); 
#ifdef THREADS 
    stop_handler_threads(); 
#endif /* THREADS */ 
    exit(-1); // Restart. 
  } 
 
  report_debug("Exiting roxen.\n"); 
  configurations->stop(); 
#ifdef THREADS 
  stop_handler_threads(); 
#endif /* THREADS */ 
  exit(-1);   // Restart. 
} 
 
void exit_it() 
{ 
  report_debug("Recursive signals.\n"); 
  exit(-1);     // Restart. 
} 
 
// Dump all threads to the debug log. 
void describe_all_threads() 
{ 
  array(mixed) all_backtraces; 
#if constant(all_threads) 
  all_backtraces = all_threads()->backtrace(); 
#else /* !constant(all_threads) */ 
  all_backtraces = ({ backtrace() }); 
#endif /* constant(all_threads) */ 
 
  report_debug("Describing all threads:\n"); 
  int i; 
  for(i=0; i < sizeof(all_backtraces); i++) { 
    report_debug("Thread %d:\n" 
                 "%s\n", 
                 i+1, 
                 describe_backtrace(all_backtraces[i])); 
  } 
} 
 
constant dump = roxenloader.dump; 
 
program slowpipe, fastpipe; 
 
void initiate_argcache() 
{ 
  int t = gethrtime(); 
  report_debug( "Initiating argument cache ... "); 
  if( mixed e = catch( argcache = ArgCache("arguments") ) ) 
  { 
    report_fatal( "Failed to initialize the global argument cache:\n" 
                  + (describe_backtrace( e )/"\n")[0]+"\n"); 
    exit(1); 
  } 
  add_constant( "roxen.argcache", argcache ); 
  report_debug("Done [%.2fms]\n", (gethrtime()-t)/1000.0); 
} 
 
int main(int argc, array tmp) 
{ 
  array argv = tmp; 
  tmp = 0; 
 
  slowpipe = ((program)"base_server/slowpipe"); 
  fastpipe = ((program)"base_server/fastpipe"); 
  dump( "base_server/slowpipe.pike" ); 
  dump( "base_server/fastpipe.pike" ); 
  dump( "base_server/throttler.pike" ); 
 
  add_constant( "Protocol", Protocol ); 
#if constant(SSL.sslfile) 
  add_constant( "SSLProtocol", SSLProtocol ); 
#endif 
 
  dump( "etc/modules/Variable.pmod/module.pmod" ); 
  dump( "etc/modules/Variable.pmod/Language.pike" ); 
 
  DDUMP(  "base_server/state.pike" ); 
  DDUMP(  "base_server/highlight_pike.pike" ); 
  DDUMP(  "base_server/wizard.pike" ); 
  DDUMP(  "base_server/proxyauth.pike" ); 
  DDUMP(  "base_server/module.pike" ); 
  DDUMP(  "base_server/throttler.pike" ); 
  DDUMP(  "base_server/smartpipe.pike" ); 
  DDUMP(  "base_server/fastpipe.pike" ); 
 
  mark_fd(0, "Stdin"); 
  mark_fd(1, "Stdout"); 
  mark_fd(2, "Stderr"); 
 
  configuration_dir = 
    Getopt.find_option(argv, "d",({"config-dir","configuration-directory" }), 
             ({ "ROXEN_CONFIGDIR", "CONFIGURATIONS" }), "../configurations"); 
 
  if(configuration_dir[-1] != '/') 
    configuration_dir += "/"; 
 
  restore_global_variables(); // restore settings... 
 
  // Dangerous... 
  mixed tmp_root; 
  if(tmp_root = Getopt.find_option(argv, "r", "root")) fix_root(tmp_root); 
 
  argv -= ({ 0 }); 
  argc = sizeof(argv); 
 
  add_constant( "roxen.fonts", 
                (fonts = ((program)"base_server/fonts.pike")()) ); 
 
 
  DDUMP( "languages/abstract.pike" ); 
  initiate_languages(query("locale")); 
 
  set_locale(); 
 
 
#if efun(syslog) 
  init_logger(); 
#endif 
  init_garber(); 
 
  initiate_supports(); 
  initiate_argcache(); 
  init_configuserdb(); 
 
 
 
  protocols = build_protocols_mapping();   
  enable_configurations(); 
 
  set_u_and_gid(); // Running with the right [e]uid:[e]gid from this point on. 
 
  create_pid_file(Getopt.find_option(argv, "p", "pid-file", "ROXEN_PID_FILE") 
                  || query("pidfile")); 
 
#ifdef RUN_SELF_TEST 
  enable_configurations_modules(); 
#else 
  if( Getopt.find_option( argv, 0, "no-delayed-load" )) 
    enable_configurations_modules(); 
  else 
    foreach( configurations, Configuration c ) 
      if( c->query( "no_delayed_load" ) ) 
        c->enable_all_modules(); 
#endif // RUN_SELF_TEST 
 
#ifdef THREADS 
  start_handler_threads(); 
  catch( this_thread()->set_name("Backend") ); 
  backend_thread = this_thread(); 
#endif /* THREADS */ 
 
  // Signals which cause a restart (exitcode != 0) 
  foreach( ({ "SIGINT", "SIGTERM" }), string sig) 
    catch( signal(signum(sig), async_sig_start(exit_when_done,0)) ); 
 
  catch(signal(signum("SIGHUP"),async_sig_start(reload_all_configurations,1))); 
 
  // Signals which cause Roxen to dump the thread state 
  foreach( ({ "SIGQUIT", "SIGUSR1", "SIGUSR2", "SIGTRAP" }), string sig) 
    catch( signal(signum(sig),async_sig_start(describe_all_threads,-1))); 
 
  start_time=time();            // Used by the "uptime" info later on. 
 
 
  if (query("suicide_engage")) 
    call_out (restart,60*60*24*max(1,query("suicide_timeout"))); 
#ifndef __NT__ 
  restart_if_stuck( 0 ); 
#endif 
#ifdef __RUN_TRACE 
  trace(1); 
#endif 
  return -1; 
} 
 
// Called from the administration interface. 
string check_variable(string name, mixed value) 
{ 
  switch(name) 
  { 
#ifndef __NT__ 
   case "abs_engage": 
    if (value) 
      restart_if_stuck(1); 
    else 
      remove_call_out(restart_if_stuck); 
    break; 
#endif 
 
   case "suicide_engage": 
    if (value) 
      call_out(restart,60*60*24*max(1,query("suicide_timeout"))); 
    else 
      remove_call_out(restart); 
    break; 
  } 
} 
 
int is_ip(string s) 
{ 
  return (sscanf(s,"%*d.%*d.%*d.%*d")==4 && s[-1]>47 && s[-1]<58); 
} 
 
static string _sprintf( ) 
{ 
  return "roxen"; 
} 
 
 
// Support for logging in configurations and modules. 
 
class LogFormat 
{ 
  static string host_ip_to_int(string s) 
  { 
    int a, b, c, d; 
    sscanf(s, "%d.%d.%d.%d", a, b, c, d); 
    return sprintf("%c%c%c%c",a, b, c, d); 
  } 
 
  static string extract_user(string from) 
  { 
    array tmp; 
    if (!from || sizeof(tmp = from/":")<2) 
      return "-"; 
    return tmp[0];      // username only, no password 
  } 
 
  void log( function do_write, RequestID id, mapping file ); 
  static void do_async_write( string host, string data, string ip, function c ) 
  { 
    if( c )  
      c( replace( data, "\4711", (host||ip) ) ); 
  } 
} 
 
static mapping(string:function) compiled_formats = ([ ]); 
 
constant formats =  
({ 
  ({ "ip_number",   "%s",   "(string)request_id->remoteaddr",0 }), 
  ({ "bin-ip_number","%s",  "host_ip_to_int(request_id->remoteaddr)",0 }), 
  ({ "cern_date",   "%s",   "Roxen.cern_http_date( time( 1 ) )",0 }), 
  ({ "bin-date",    "%4c",  "time(1)",0 }), 
  ({ "method",      "%s",   "(string)request_id->method",0 }), 
  ({ "resource",    "%s",   "(string)(request_id->raw_url||request_id->not_query)", 0 }), 
  ({ "full_resource","%s",  "(string)(request_id->raw_url||request_id->not_query)",0 }), 
  ({ "protocol",    "%s",   "(string)request_id->prot",0 }), 
  ({ "response",    "%d",   "(int)(file->error || 200)",0 }), 
  ({ "bin-response","%2c",  "(int)(file->error || 200)",0 }), 
  ({ "length",      "%d",   "(int)file->len",0 }), 
  ({ "bin-length",  "%4c",  "(int)file->len",0 }), 
  ({ "referer",     "%s",     
     "sizeof(request_id->referer||({}))?request_id->referer[0]:\"-\"", 0 }), 
  ({ "user_agent",  "%s",     
     "request_id->client?request_id->client*\"%20\":\"-\"", 0 }), 
  ({ "user",        "%s",    "extract_user( request_id->realauth )",0 }), 
  ({ "user_id",     "%s",    "request_id->cookies->RoxenUserID||\"0\"",0 }), 
  ({ "request-time","%1.2f",  "time(request_id->time )",0 }), 
  ({ "host",        "\4711",    0, 1 }), // unlikely to occur normally 
}); 
 
void run_log_format( string fmt, function c, RequestID id, mapping file ) 
{ 
  (compiled_formats[ fmt ] || compile_log_format( fmt ))(c,id,file); 
} 
 
function compile_log_format( string fmt ) 
{ 
  if( compiled_formats[ fmt ] ) 
    return compiled_formats[ fmt ]; 
 
  array parts = fmt/"$"; 
  string format = parts[0]; 
  array args = ({}); 
  int do_it_async = 0; 
  int add_nl = 1; 
 
  string sr( string s ) { return s[1..strlen(s)-2]; }; 
  // sr(replace(sprintf("%O", X), "%", "%%")) 
 
#define DO_ES(X) replace(X, ({"\\n", "\\r", "\\t", }), ({ "\n", "\r", "\t" }) ) 
 
  foreach( parts[1..], string part ) 
  { 
    int c, processed; 
    foreach( formats, array q ) 
      if( part[..strlen(q[0])-1] == q[0]) 
      { 
        format += q[1] + DO_ES(part[ strlen(q[0]) .. ]); 
        if( q[2] ) args += ({ q[2] }); 
        if( q[3] ) do_it_async = 1; 
        processed=1; 
        break; 
      } 
    if( processed ) 
      continue; 
    if( sscanf( part, "char(%d)%s", c, part ) ) 
      format += sprintf( "%"+(c<0?"-":"")+"c", abs( c ) )+DO_ES(part); 
    else if( sscanf( part, "wchar(%d)%s", c, part ) ) 
      format += sprintf( "%"+(c<0?"-":"")+"2c", abs( c ) )+DO_ES(part); 
    else if( sscanf( part, "int(%d)%s", c, part ) ) 
      format += sprintf( "%"+(c<0?"-":"")+"4c", abs( c ) )+DO_ES(part); 
    else if( part[0] == '^' ) 
    { 
      format += DO_ES(part[1..]); 
      add_nl = 0; 
    } else 
      format += "$"+part; 
  } 
  if( add_nl ) format += "\n"; 
//   werror("Format = %O  args = %{%O,%} async = %d\n", format, args, do_it_async ); 
 
  add_constant( "___LogFormat", LogFormat ); 
  string code = sprintf( 
#" 
  inherit ___LogFormat; 
  void log( function callback, RequestID request_id, mapping file ) 
  { 
     if(!callback) return; 
     string data = sprintf( %O %{, %s%} ); 
", format, args ); 
  
  if( do_it_async ) 
  { 
    code +=  
#" 
     roxen.ip_to_host(request_id->remoteaddr,do_async_write, 
                      data, request_id->remoteaddr, callback ); 
   } 
"; 
  } else 
    code +=  
#"   
   callback( data ); 
  } 
"; 
  return compiled_formats[ fmt ] = compile_string( code )()->log; 
} 
 
 
 
static string cached_hostname = gethostname(); 
 
class LogFile(string fname) 
{ 
  Stdio.File fd; 
  int opened; 
 
  void do_open() 
  { 
    mixed parent; 
    if (catch { parent = function_object(object_program(this_object())); } || 
        !parent) { 
      // Our parent (aka the configuration) has been destructed. 
      // Time to die. 
      remove_call_out(do_open); 
      remove_call_out(do_close); 
      destruct(); 
      return; 
    } 
    string ff = fname; 
    mapping m = localtime(time(1)); 
    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; 
    ff = replace(fname,({"%d","%m","%y","%h", "%H" }), 
                      ({ (string)m->mday, (string)(m->mon), 
                         (string)(m->year),(string)m->hour, 
                         cached_hostname, 
                      })); 
    mkdirhier( ff ); 
    fd = open( ff, "wac" ); 
    if(!fd)  
    { 
      remove_call_out( do_open ); 
      call_out( do_open, 120 );  
      report_error(LOC_M(37, "Failed to open logfile")+" "+fname+" " 
#if constant(strerror) 
                   "(" + strerror(errno()) + ")" 
#endif 
                   "\n"); 
      return; 
    } 
    opened = 1; 
    remove_call_out( do_open ); 
    call_out( do_open, 900 );  
  } 
   
  void do_close() 
  { 
    destruct( fd ); 
    opened = 0; 
  } 
 
  array(string) write_buf = ({}); 
  static void do_the_write( ) 
  { 
    if( !opened ) do_open(); 
    if( !opened ) return 0; 
    fd->write( write_buf ); 
    write_buf = ({}); 
    remove_call_out( do_close ); 
    call_out( do_close, 10.0 ); 
  } 
 
  int write( string what ) 
  { 
    if( !sizeof( write_buf ) ) 
      call_out( do_the_write, 1 ); 
    write_buf += ({what}); 
    return strlen(what);  
  } 
}