aboutsummaryrefslogtreecommitdiffstats
path: root/src/lua/lua_config.c
blob: 9f7952cc3ad522dbbddd3ef1de68f498edcbc31d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
/*-
 * Copyright 2016 Vsevolod Stakhov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "lua_common.h"
#include "libmime/message.h"
#include "libutil/expression.h"
#include "libserver/composites.h"
#include "libserver/cfg_file_private.h"
#include "libmime/lang_detection.h"
#include "lua/lua_map.h"
#include "lua/lua_thread_pool.h"
#include "utlist.h"
#include <math.h>

/***
 * This module is used to configure rspamd and is normally available as global
 * variable named `rspamd_config`. Unlike other modules, it is not necessary to
 * require it before usage.
 * @module rspamd_config
 * @example
-- Register some callback symbol
local function foo(task)
    -- do something
end
rspamd_config:register_symbol('SYMBOL', 1.0, foo)

-- Get configuration
local tab = rspamd_config:get_all_opt('module') -- get table for module's options
local opts = rspamd_config:get_key('options') -- get content of the specified key in rspamd configuration
 */

/* Config file methods */
/***
 * @method rspamd_config:get_module_opt(mname, optname)
 * Returns value of specified option `optname` for a module `mname`,
 * @param {string} mname name of module
 * @param {string} optname option to get
 * @return {string or table} value of the option or `nil` if option is not found
 */
LUA_FUNCTION_DEF (config, get_module_opt);
/***
 * @method rspamd_config:get_all_opt(mname)
 * Returns value of all options for a module `mname`, flattening values into a single table consisting
 * of all sections with such a name.
 * @param {string} mname name of module
 * @return {table} table of all options for `mname` or `nil` if a module's configuration is not found
 */
LUA_FUNCTION_DEF (config, get_all_opt);

/***
 * @method rspamd_config:get_ucl()
 * Returns full configuration as a native Lua object (ucl to lua conversion).
 * This method uses caching if possible.
 * @return {table} table of all options in the configuration
 */
LUA_FUNCTION_DEF (config, get_ucl);
/***
 * @method rspamd_config:get_mempool()
 * Returns static configuration memory pool.
 * @return {mempool} [memory pool](mempool.md) object
 */
LUA_FUNCTION_DEF (config, get_mempool);
/***
 * @method rspamd_config:get_resolver()
 * Returns DNS resolver.
 * @return {dns_resolver} opaque DNS resolver pointer if any
 */
LUA_FUNCTION_DEF (config, get_resolver);
/***
 * @method rspamd_config:add_radix_map(mapline[, description])
 * Creates new dynamic map of IP/mask addresses.
 * @param {string} mapline URL for a map
 * @param {string} description optional map description
 * @return {map} radix tree object
 * @example
local ip_map = rspamd_config:add_radix_map ('file:///path/to/file', 'my radix map')
...
local function foo(task)
	local ip = task:get_from_ip()
	if ip_map:get_key(ip) then
		return true
	end
	return false
end
 */

/***
 * @method rspamd_config:radix_from_config(mname, optname)
 * Creates new embedded map of IP/mask addresses from config.
 * @param {string} mname name of module
 * @param {string} optname option to get
 * @return {map} radix tree object
 * @example
local ip_map = rspamd_config:radix_from_config ('mymodule', 'ips')
...
local function foo(task)
	local ip = task:get_from_ip()
	if ip_map:get_key(ip) then
		return true
	end
	return false
end
 */
/***
* @method rspamd_config:radix_from_ucl(obj)
* Creates new embedded map of IP/mask addresses from object.
* @param {ucl} obj object
* @return {map} radix tree object
*/
/***
 * @method rspamd_config:add_hash_map(mapline[, description])
 * Creates new dynamic map string objects.
 * @param {string} mapline URL for a map
 * @param {string} description optional map description
 * @return {map} hash set object
 * @example
local hash_map = rspamd_config:add_hash_map ('file:///path/to/file', 'my hash map')
...
local function foo(task)
	local from = task:get_from()
	if hash_map:get_key(from['user']) then
		return true
	end
	return false
end
 */
/***
 * @method rspamd_config:add_kv_map(mapline[, description])
 * Creates new dynamic map of key/values associations.
 * @param {string} mapline URL for a map
 * @param {string} description optional map description
 * @return {map} hash table object
 * @example
local kv_map = rspamd_config:add_kv_map ('file:///path/to/file', 'my kv map')
...
local function foo(task)
	local from = task:get_from()
	if from then
		local value = kv_map:get_key(from['user'])
		if value then
			return true,value
		end
	end
	return false
end
 */
/***
 * @method rspamd_config:add_map({args})
 * Creates new dynamic map according to the attributes passed.
 *
 * - `type`: type of map to be created, can be one of the following set:
 *   + `set`: set of strings
 *   + `radix`: map of IP addresses to strings
 *   + `map`: map of strings to strings
 *   + `regexp`: map of regexps to strings
 *   + `callback`: map processed by lua callback
 * - `url`: url to load map from
 * - `description`: map's description
 * - `callback`: lua callback for the map
 *
 * @return {map} `true` if map has been added
 * @example

local str = ''
local function process_map(in)
	str = in
end

rspamd_config:add_map('http://example.com/map', "settings map", process_map)
 */
/***
* @method rspamd_config:get_maps()
* Get all maps defined as an array of rspamd{map} objects
 *
* @return {table|rspamd{map}}
*/
/***
 * @method rspamd_config:get_classifier(name)
 * Returns classifier config.
 * @param {string} name name of classifier (e.g. `bayes`)
 * @return {classifier} classifier object or `nil`
 */
LUA_FUNCTION_DEF (config, get_classifier);
/***
 * @method rspamd_config:register_symbol(table)
 * Register symbol of a specified type in rspamd. This function accepts table of arguments:
 *
 * - `name`: name of symbol (can be missing for callback symbols)
 * - `callback`: function to be called for symbol's check (can be absent for virtual symbols)
 * - `weight`: weight of symbol (should normally be 1 or missing)
 * - `priority`: priority of symbol (normally 0 or missing)
 * - `type`: type of symbol: `normal` (default), `virtual` or `callback`
 * - `flags`: various flags split by commas or spaces:
 *     + `nice` if symbol can produce negative score;
 *     + `empty` if symbol can be called for empty messages
 *     + `skip` if symbol should be skipped now
 *     + `nostat` if symbol should be excluded from stat tokens
 *     + `trivial` symbol is trivial (e.g. no network requests)
 *     + `explicit_disable` requires explicit disabling (e.g. via settings)
 *     + `ignore_passthrough` executed even if passthrough result has been set
 * - `parent`: id of parent symbol (useful for virtual symbols)
 *
 * @return {number} id of symbol registered
 */
LUA_FUNCTION_DEF (config, register_symbol);
/***
 * @method rspamd_config:register_symbols(callback, [weight], callback_name, [, symbol, ...])
 * Register callback function to be called for a set of symbols with initial weight.
 * @param {function} callback callback function to be called for a specified symbol
 * @param {number} weight initial weight of symbol (can be less than zero to specify non-spam symbols)
 * @param {string} callback_name symbolic name of callback
 * @param {list of strings} symbol list of symbols registered by this function
 */
LUA_FUNCTION_DEF (config, register_symbols);
/***
 * @method rspamd_config:register_virtual_symbol(name, weight,)
 * Register virtual symbol that is not associated with any callback.
 *
 * **This method is deprecated and should not be used in newly written code **
 * @param {string} virtual name symbol's name
 * @param {number} weight initial weight of symbol (can be less than zero to specify non-spam symbols)
 */
LUA_FUNCTION_DEF (config, register_virtual_symbol);
/***
 * @method rspamd_config:register_callback_symbol(name, weight, callback)
 * Register callback function to be called for a specified symbol with initial weight. Symbol itself is
 * not registered in the metric and is not intended to be visible by a user.
 *
 * **This method is deprecated and should not be used in newly written code **
 * @param {string} name symbol's name (just for unique id purposes)
 * @param {number} weight initial weight of symbol (can be less than zero to specify non-spam symbols)
 * @param {function} callback callback function to be called for a specified symbol
 */
LUA_FUNCTION_DEF (config, register_callback_symbol);
LUA_FUNCTION_DEF (config, register_callback_symbol_priority);

/***
 * @method rspamd_config:register_dependency(id, dep)
 * Create a dependency between symbol identified by `id` and a symbol identified
 * by some symbolic name `dep`
 * @param {number|string} id id or name of source (numeric id is returned by all register_*_symbol)
 * @param {string} dep dependency name
 * @example
local function cb(task)
...
end

local id = rspamd_config:register_symbol('SYM', 1.0, cb)
rspamd_config:register_dependency(id, 'OTHER_SYM')
-- Alternative form
rspamd_config:register_dependency('SYMBOL_FROM', 'SYMBOL_TO')
 */
LUA_FUNCTION_DEF (config, register_dependency);

/***
 * @method rspamd_config:get_symbol_flags(name)
 * Returns symbol flags
 * @param {string} name symbols's name
 * @return {table|string} list of flags for symbol or nil
 */
LUA_FUNCTION_DEF (config, get_symbol_flags);

/***
 * @method rspamd_config:add_symbol_flags(name, flags)
 * Adds flags to a symbol
 * @param {string} name symbols's name
 * @param {table|string} flags flags to add
 * @return {table|string} new set of flags
 */
LUA_FUNCTION_DEF (config, add_symbol_flags);

/**
 * @method rspamd_config:register_re_selector(name, selector_str)
 * Registers selector with the specific name to use in regular expressions in form
 * name=/re/$ or name=/re/{selector}
 * @param {string} name name of the selector
 * @param {selector_str} selector string
 * @return true if selector has been registered
 */
LUA_FUNCTION_DEF (config, register_re_selector);

/**
 * @method rspamd_config:set_symbol({table})
 * Sets the value of a specified symbol in a metric. This function accepts table with the following elements:
 *
 * - `name`: name of symbol (string)
 * - `score`: score for symbol (number)
 * - `metric`: name of metric (string, optional)
 * - `description`: description of symbol (string, optional)
 * - `group`: name of group for symbol (string, optional)
 * - `one_shot`: turn off multiple hits for a symbol (boolean, optional)
 * - `one_param`: turn off multiple options for a symbol (boolean, optional)
 * - `flags`: comma separated string of flags:
 *    + `ignore`: do not strictly check validity of symbol and corresponding rule
 *    + `one_shot`: turn off multiple hits for a symbol
 *    + `one_param`: allow only one parameter for a symbol
 * - `priority`: priority of symbol's definition
 */
LUA_FUNCTION_DEF (config, set_metric_symbol);

/**
 * @method rspamd_config:set_action({table})
 * Sets the score of a specified action in a metric. This function accepts table with the following elements:
 *
 * - `action`: name of action (string)
 * - `score`: score for action (number)
 * - `metric`: name of metric (string, optional)
 * - `priority`: priority of action's definition
 */
LUA_FUNCTION_DEF (config, set_metric_action);

/**
 * @method rspamd_config:get_symbol(name)
 * Gets metric data for a specific symbol identified by `name`:
 *
 * - `score`: score for symbol (number)
 * - `description`: description of symbol (string, optional)
 * - `group`: name of group for symbol (string, optional)
 * - `one_shot`: turn off multiple hits for a symbol (boolean, optional)
 * - `flags`: comma separated string of flags:
 *    + `ignore`: do not strictly check validity of symbol and corresponding rule
 *    + `one_shot`: turn off multiple hits for a symbol
 *
 * @param {string} name name of symbol
 * @return {table} symbol's definition or nil in case of undefined symbol
 */
LUA_FUNCTION_DEF (config, get_metric_symbol);

/**
 * @method rspamd_config:get_action(name)
 * Gets data for a specific action in config. This function returns number reperesenting action's score
 *
 * @param {string} name name of action
 * @return {number} action's score or nil in case of undefined score or action
 */
LUA_FUNCTION_DEF (config, get_metric_action);

/**
 * @method rspamd_config:get_all_actions()
 * Gets data for all action in config
 * @return {table|str->num} action's score or nil in case of undefined score or action
 */
LUA_FUNCTION_DEF (config, get_all_actions);

/**
 * @method rspamd_config:add_composite(name, expression)
 * @param {string} name name of composite symbol
 * @param {string} expression symbolic expression of the composite rule
 * @return {bool} true if a composite has been added successfully
 */
LUA_FUNCTION_DEF (config, add_composite);
/***
 * @method rspamd_config:register_pre_filter(callback[, order])
 * Register function to be called prior to symbols processing.
 * @param {function} callback callback function
 * @param {number} order filters are called from lower orders to higher orders, order is equal to 0 by default
 * @example
local function check_function(task)
	-- It is possible to manipulate the task object here: set settings, set pre-action and so on
	...
end

rspamd_config:register_pre_filter(check_function)
 */
LUA_FUNCTION_DEF (config, register_pre_filter);
/***
 * @method rspamd_config:register_post_filter(callback[, order])
 * Register function to be called after symbols are processed.
 *
 * @param {function} callback callback function
 * @param {number} order filters are called from lower orders to higher orders, order is equal to 0 by default
 */
LUA_FUNCTION_DEF (config, register_post_filter);
/* XXX: obsoleted */
LUA_FUNCTION_DEF (config, register_module_option);
/* XXX: not needed now */
LUA_FUNCTION_DEF (config, get_api_version);
/***
 * @method rspamd_config:get_key(name)
 * Returns configuration section with the specified `name`.
 * @param {string} name name of config section
 * @return {variant} specific value of section
 * @example

local set_section = rspamd_config:get_key("settings")
if type(set_section) == "string" then
  -- Just a map of ucl
  if rspamd_config:add_map(set_section, "settings map", process_settings_map) then
    rspamd_config:register_pre_filter(check_settings)
  end
elseif type(set_section) == "table" then
  if process_settings_table(set_section) then
    rspamd_config:register_pre_filter(check_settings)
  end
end
 */
LUA_FUNCTION_DEF (config, get_key);

/***
 * @method rspamd_config:add_condition(symbol, condition)
 * Adds condition callback for specified symbol
 * @param {string} symbol symbol's name
 * @param {function} condition condition callback
 * @return {boolean} true if condition has been added
 * @example

rspamd_config:add_condition('FUZZY_DENIED', function(task)
  if some_map:find_key(task:get_from()) then return false end
  return true
end)
 */
LUA_FUNCTION_DEF (config, add_condition);

/***
 * @method rspamd_config:enable_symbol(symbol)
 * Enables execution for the specified symbol
 * @param {string} symbol symbol's name
 */
LUA_FUNCTION_DEF (config, enable_symbol);

/***
 * @method rspamd_config:disable_symbol(symbol)
 * Disables execution for the specified symbol
 * @param {string} symbol symbol's name
 */
LUA_FUNCTION_DEF (config, disable_symbol);

/***
 * @method rspamd_config:get_symbol_parent(symbol)
 * Returns a parent symbol for specific symbol (or symbol itself if top level)
 * @param {string} symbol symbol's name
 */
LUA_FUNCTION_DEF (config, get_symbol_parent);

/***
 * @method rspamd_config:get_group_symbols(group)
 * Returns list of symbols for a specific group
 * @param {string} group group's name
 * @available 2.0+
 * @return {list|string} list of all symbols in a specific group
 */
LUA_FUNCTION_DEF (config, get_group_symbols);

/***
 * @method rspamd_config:register_settings_id(name, symbols_enabled, symbols_disabled)
 * Register new static settings id in config
 * @param {string} name id name (not numeric!)
 * @param {map|string->string} symbols_enabled map from symbol's name to boolean (currently)
 * @param {map|string->string} symbols_disabled map from symbol's name to boolean (currently)
 * @available 2.0+
 */
LUA_FUNCTION_DEF (config, register_settings_id);

/***
 * @method rspamd_config:__newindex(name, callback)
 * This metamethod is called if new indicies are added to the `rspamd_config` object.
 * Technically, it is the equivalent of @see rspamd_config:register_symbol where `weight` is 1.0.
 * There is also table form invocation that allows to control more things:
 *
 * - `callback`: has the same meaning and acts as function of task
 * - `score`: default score for a symbol
 * - `group`: default group for a symbol
 * - `description`: default symbol's description
 * - `priority`: additional priority value
 * - `one_shot`: default value for one shot attribute
 * - `condition`: function of task that can enable or disable this specific rule's execution
 * @param {string} name index name
 * @param {function/table} callback callback to be called
 * @return {number} id of the new symbol added
 * @example
rspamd_config.R_EMPTY_IMAGE = function (task)
	parts = task:get_text_parts()
	if parts then
		for _,part in ipairs(parts) do
			if part:is_empty() then
				images = task:get_images()
				if images then
					-- Symbol `R_EMPTY_IMAGE` is inserted
					return true
				end
				return false
			end
		end
	end
	return false
end

rspamd_config.SYMBOL = {
	callback = function(task)
 	...
 	end,
 	score = 5.1,
 	description = 'sample symbol',
 	group = 'sample symbols',
 	condition = function(task)
 		if task:get_from()[1]['addr'] == 'user@example.com' then
 			return false
 		end
 		return true
 	end
}
 */
LUA_FUNCTION_DEF (config, newindex);

/***
 * @method rspamd_config:register_regexp(params)
 * Registers new re for further cached usage
 * Params is the table with the following fields (mandatory fields are marked with `*`):
 * - `re`* : regular expression object
 * - `type`*: type of regular expression:
 *   + `mime`: mime regexp
 *   + `rawmime`: raw mime regexp
 *   + `header`: header regexp
 *   + `rawheader`: raw header expression
 *   + `body`: raw body regexp
 *   + `url`: url regexp
 * - `header`: for header and rawheader regexp means the name of header
 * - `pcre_only`: flag regexp as pcre only regexp
 */
LUA_FUNCTION_DEF (config, register_regexp);

/***
 * @method rspamd_config:replace_regexp(params)
 * Replaces regexp with a new one
 * Params is the table with the following fields (mandatory fields are marked with `*`):
 * - `old_re`* : old regular expression object (must be in the cache)
 * - `new_re`* : old regular expression object (must not be in the cache)
 */
LUA_FUNCTION_DEF (config, replace_regexp);

/***
 * @method rspamd_config:register_worker_script(worker_type, script)
 * Registers the following script for workers of a specified type. The exact type
 * of script function depends on worker type
 * @param {string} worker_type worker type (e.g. "normal")
 * @param {function} script script for a worker
 * @return {boolean} `true` if a script has been registered
 */
LUA_FUNCTION_DEF (config, register_worker_script);

/***
 * @method rspamd_config:add_on_load(function(cfg, ev_base, worker) ... end)
 * Registers the following script to be executed when configuration is completely loaded
 * and the worker is already started (forked)
 * @param {function} script function to be executed
 * @example
rspamd_config:add_on_load(function(cfg, ev_base, worker)
	rspamd_config:add_periodic(ev_base, 1.0, function(cfg, ev_base)
		local logger = require "rspamd_logger"
		logger.infox(cfg, "periodic function in worker %s", worker:get_name())
		return true
	end)
end)
 */
LUA_FUNCTION_DEF (config, add_on_load);

/***
 * @method rspamd_config:add_periodic(event_base, timeout, function(cfg, ev_base) ... end, [jitter = false])
 * Registers function to be periodically executed by Rspamd
 * @param {ev_base} event_base event base that is needed for async events
 * @param {number} timeout time in seconds (could be fractional)
 * @param {function} script function to be executed
 * @param {boolean} jitter `true` if timeout jittering is needed
 * @example
rspamd_config:add_on_load(function(cfg, ev_base)
	rspamd_config:add_periodic(ev_base, 1.0, function(cfg, ev_base)
		local logger = require "rspamd_logger"
		logger.infox(cfg, "periodic function")
		return true -- if return false, then the periodic event is removed
	end)
end)
 */
LUA_FUNCTION_DEF (config, add_periodic);

/***
 * @method rspamd_config:add_post_init(function(cfg) ... end)
 * Registers the following script to be executed when configuration is completely loaded
 * @available 2.0+
 * @param {function} script function to be executed
 */
LUA_FUNCTION_DEF (config, add_post_init);

/***
 * @method rspamd_config:add_config_unload(function(cfg) ... end)
 * Registers the following script to be executed when configuration is unloaded
 * @available 2.0+
 * @param {function} script function to be executed
 */
LUA_FUNCTION_DEF (config, add_config_unload);

/***
 * @method rspamd_config:get_symbols_count()
 * Returns number of symbols registered in rspamd configuration
 * @return {number} number of symbols registered in the configuration
 */
LUA_FUNCTION_DEF (config, get_symbols_count);

/***
 * @method rspamd_config:get_symbols_cksum()
 * Returns checksum for all symbols in the cache
 * @return {int64} boxed value of the 64 bit checksum
 */
LUA_FUNCTION_DEF (config, get_symbols_cksum);

/***
 * @method rspamd_config:get_symbols_counters()
 * Returns table of all counters in the cache (weights, frequencies etc)
 * @return {table|tables} all symbols indexed by name
 */
LUA_FUNCTION_DEF (config, get_symbols_counters);

/***
 * @method rspamd_config:get_symbols_scores()
 * Returns table of all scores defined in config
 * @return {table|tables} all symbols indexed by name
 */
LUA_FUNCTION_DEF (config, get_symbols_scores);

/***
 * @method rspamd_config:get_symbol_callback(name)
 * Returns callback function for the specified symbol if it is a lua registered callback
 * @return {function} callback function or nil
 */
LUA_FUNCTION_DEF (config, get_symbol_callback);

/***
 * @method rspamd_config:get_symbol_stat(name)
 * Returns table with statistics for a specific symbol:
 * - `frequency`: frequency for symbol's hits
 * - `stddev`: standard deviation of `frequency`
 * - `time`: average time in seconds (floating point)
 * - `count`: total number of hits
 * @return {table} symbol stats
 */
LUA_FUNCTION_DEF (config, get_symbol_stat);

/***
 * @method rspamd_config:set_symbol_callback(name, callback)
 * Sets callback for the specified symbol
 * @return {boolean} true if function has been replaced
 */
LUA_FUNCTION_DEF (config, set_symbol_callback);

/***
 * @method rspamd_config:register_finish_script(callback)
 * Adds new callback that is called on worker process termination when all
 * tasks pending are processed
 *
 * @param callback {function} a function with one argument (rspamd_task)
 */
LUA_FUNCTION_DEF (config, register_finish_script);

/***
 * @method rspamd_config:register_monitored(url, type, [{params}])
 * Registers monitored resource to watch its availability. Supported types:
 *
 * - `dns`: DNS monitored object
 *
 * Params are optional table specific for each type. For DNS it supports the
 * following options:
 *
 * - `prefix`: prefix to add before making request
 * - `type`: type of request (e.g. 'a' or 'txt')
 * - `ipnet`: array of ip/networks to expect on reply
 * - `rcode`: expected return code (e.g. `nxdomain`)
 *
 * Returned object has the following methods:
 *
 * - `alive`: returns `true` if monitored resource is alive
 * - `offline`: returns number of seconds of the current offline period (or 0 if alive)
 * - `total_offline`: returns number of seconds of the overall offline
 * - `latency`: returns the current average latency in seconds (or 0 if offline)
 *
 * @param {string} url resource to monitor
 * @param {string} type type of monitoring
 * @param {table} opts optional parameters
 * @return {rspamd_monitored} rspamd monitored object
 */
LUA_FUNCTION_DEF (config, register_monitored);

/***
 * @method rspamd_config:add_doc(path, option, doc_string, [{params}])
 * Adds new documentation string for an option `option` at path `path`
 * Options defines optional params, such as:
 *
 * - `default`: default option value
 * - `type`: type of an option (`string`, `number`, `object`, `array` etc)
 * - `reqired`: if an option is required
 *
 * @param {string} path documentation path (e.g. module name)
 * @param {string} option name of the option
 * @param {string} doc_string documentation string
 * @param {table} params optional parameters
 */
LUA_FUNCTION_DEF (config, add_doc);

/***
 * @method rspamd_config:add_example(path, option, doc_string, example)
 * Adds new documentation
 *
 * @param {string} path documentation path (e.g. module name or nil for top)
 * @param {string} option name of the option
 * @param {string} doc_string documentation string
 * @param {string} example example in ucl format, comments are also parsed
 */
LUA_FUNCTION_DEF (config, add_example);

/***
 * @method rspamd_config:set_peak_cb(function)
 * Sets a function that will be called when frequency of some symbol goes out of
 * stddev * 2 over the last period of refreshment.
 *
 * @example
rspamd_config:set_peak_cb(function(ev_base, sym, mean, stddev, value, error)
  -- ev_base: event base for async events (e.g. redis)
  -- sym: symbol's name
  -- mean: mean frequency value
  -- stddev: standard deviation of frequency
  -- value: current frequency value
  -- error: squared error
  local logger = require "rspamd_logger"
  logger.infox(rspamd_config, "symbol %s has changed frequency significantly: %s(%s) over %s(%s)",
      sym, value, error, mean, stddev)
end)
 */
LUA_FUNCTION_DEF (config, set_peak_cb);
/***
 *  @method rspamd_config:get_cpu_flags()
 * Returns architecture dependent flags supported by the CPU
 * Currently, only x86 flags are supported:
 * - 'ssse3'
 * - 'sse42'
 * - 'avx'
 * - 'avx2'
 * @return {table} flag -> true table
 */
LUA_FUNCTION_DEF (config, get_cpu_flags);

/***
 * @method rspamd_config:has_torch()
 * Returns true if Rspamd is compiled with torch support and the runtime CPU
 * supports sse4.2 required for torch.
 * @return {boolean} true if torch is compiled and supported
 */
LUA_FUNCTION_DEF (config, has_torch);

/***
 * @method rspamd_config:experimental_enabled()
 * Returns true if experimental plugins are enabled
 * @return {boolean} true if experimental plugins are enabled
 */
LUA_FUNCTION_DEF (config, experimental_enabled);

/***
 * @method rspamd_config:load_ucl(filename[, include_trace])
 * Loads config from the UCL file (but does not perform parsing using rcl)
 * @param {string} filename file to load
 * @return true or false + error message
 */
LUA_FUNCTION_DEF (config, load_ucl);

/***
 * @method rspamd_config:parse_rcl([skip_sections])
 * Parses RCL using loaded ucl file
 * @param {table|string} sections to skip
 * @return true or false + error message
 */
LUA_FUNCTION_DEF (config, parse_rcl);

/***
 * @method rspamd_config:init_modules()
 * Initialize lua and internal modules
 * @return true or false
 */
LUA_FUNCTION_DEF (config, init_modules);

/***
 * @method rspamd_config:init_subsystem(str)
 * Initialize config subsystem from a comma separated list:
 * - `modules` - init modules
 * - `langdet` - language detector
 * - `dns` - DNS resolver
 * - TODO: add more
 */
LUA_FUNCTION_DEF (config, init_subsystem);

/***
 * @method rspamd_config:get_tld_path()
 * Returns path to TLD file
 * @return {string} path to tld file
 */
LUA_FUNCTION_DEF (config, get_tld_path);

static const struct luaL_reg configlib_m[] = {
	LUA_INTERFACE_DEF (config, get_module_opt),
	LUA_INTERFACE_DEF (config, get_mempool),
	LUA_INTERFACE_DEF (config, get_resolver),
	LUA_INTERFACE_DEF (config, get_all_opt),
	LUA_INTERFACE_DEF (config, get_ucl),
	LUA_INTERFACE_DEF (config, add_radix_map),
	LUA_INTERFACE_DEF (config, radix_from_config),
	LUA_INTERFACE_DEF (config, radix_from_ucl),
	LUA_INTERFACE_DEF (config, add_hash_map),
	LUA_INTERFACE_DEF (config, add_kv_map),
	LUA_INTERFACE_DEF (config, add_map),
	LUA_INTERFACE_DEF (config, get_maps),
	LUA_INTERFACE_DEF (config, get_classifier),
	LUA_INTERFACE_DEF (config, register_symbol),
	LUA_INTERFACE_DEF (config, register_symbols),
	LUA_INTERFACE_DEF (config, register_virtual_symbol),
	LUA_INTERFACE_DEF (config, register_callback_symbol),
	LUA_INTERFACE_DEF (config, register_callback_symbol_priority),
	LUA_INTERFACE_DEF (config, register_dependency),
	LUA_INTERFACE_DEF (config, register_settings_id),
	LUA_INTERFACE_DEF (config, get_symbol_flags),
	LUA_INTERFACE_DEF (config, add_symbol_flags),
	LUA_INTERFACE_DEF (config, set_metric_symbol),
	{"set_symbol", lua_config_set_metric_symbol},
	LUA_INTERFACE_DEF (config, set_metric_action),
	{"set_action", lua_config_set_metric_action},
	LUA_INTERFACE_DEF (config, get_metric_symbol),
	{"get_symbol", lua_config_get_metric_symbol},
	LUA_INTERFACE_DEF (config, get_metric_action),
	{"get_action", lua_config_get_metric_action},
	LUA_INTERFACE_DEF (config, get_all_actions),
	LUA_INTERFACE_DEF (config, add_composite),
	LUA_INTERFACE_DEF (config, register_module_option),
	LUA_INTERFACE_DEF (config, register_pre_filter),
	LUA_INTERFACE_DEF (config, register_post_filter),
	LUA_INTERFACE_DEF (config, get_api_version),
	LUA_INTERFACE_DEF (config, get_key),
	LUA_INTERFACE_DEF (config, add_condition),
	LUA_INTERFACE_DEF (config, enable_symbol),
	LUA_INTERFACE_DEF (config, disable_symbol),
	LUA_INTERFACE_DEF (config, register_regexp),
	LUA_INTERFACE_DEF (config, replace_regexp),
	LUA_INTERFACE_DEF (config, register_worker_script),
	LUA_INTERFACE_DEF (config, register_re_selector),
	LUA_INTERFACE_DEF (config, add_on_load),
	LUA_INTERFACE_DEF (config, add_periodic),
	LUA_INTERFACE_DEF (config, add_post_init),
	LUA_INTERFACE_DEF (config, add_config_unload),
	LUA_INTERFACE_DEF (config, get_symbols_count),
	LUA_INTERFACE_DEF (config, get_symbols_cksum),
	LUA_INTERFACE_DEF (config, get_symbols_counters),
	LUA_INTERFACE_DEF (config, get_symbols_scores),
	LUA_INTERFACE_DEF (config, get_symbol_callback),
	LUA_INTERFACE_DEF (config, set_symbol_callback),
	LUA_INTERFACE_DEF (config, get_symbol_stat),
	LUA_INTERFACE_DEF (config, get_symbol_parent),
	LUA_INTERFACE_DEF (config, get_group_symbols),
	LUA_INTERFACE_DEF (config, register_finish_script),
	LUA_INTERFACE_DEF (config, register_monitored),
	LUA_INTERFACE_DEF (config, add_doc),
	LUA_INTERFACE_DEF (config, add_example),
	LUA_INTERFACE_DEF (config, set_peak_cb),
	LUA_INTERFACE_DEF (config, get_cpu_flags),
	LUA_INTERFACE_DEF (config, has_torch),
	LUA_INTERFACE_DEF (config, experimental_enabled),
	LUA_INTERFACE_DEF (config, load_ucl),
	LUA_INTERFACE_DEF (config, parse_rcl),
	LUA_INTERFACE_DEF (config, init_modules),
	LUA_INTERFACE_DEF (config, init_subsystem),
	LUA_INTERFACE_DEF (config, get_tld_path),
	{"__tostring", rspamd_lua_class_tostring},
	{"__newindex", lua_config_newindex},
	{NULL, NULL}
};

LUA_FUNCTION_DEF (monitored, alive);
LUA_FUNCTION_DEF (monitored, latency);
LUA_FUNCTION_DEF (monitored, offline);
LUA_FUNCTION_DEF (monitored, total_offline);

static const struct luaL_reg monitoredlib_m[] = {
	LUA_INTERFACE_DEF (monitored, alive),
	LUA_INTERFACE_DEF (monitored, latency),
	LUA_INTERFACE_DEF (monitored, offline),
	LUA_INTERFACE_DEF (monitored, total_offline),
	{"__tostring", rspamd_lua_class_tostring},
	{NULL, NULL}
};

static const guint64 rspamd_lua_callback_magic = 0x32c118af1e3263c7ULL;

struct rspamd_config *
lua_check_config (lua_State * L, gint pos)
{
	void *ud = rspamd_lua_check_udata (L, pos, "rspamd{config}");
	luaL_argcheck (L, ud != NULL, pos, "'config' expected");
	return ud ? *((struct rspamd_config **)ud) : NULL;
}

static struct rspamd_monitored *
lua_check_monitored (lua_State * L, gint pos)
{
	void *ud = rspamd_lua_check_udata (L, pos, "rspamd{monitored}");
	luaL_argcheck (L, ud != NULL, pos, "'monitored' expected");
	return ud ? *((struct rspamd_monitored **)ud) : NULL;
}

/*** Config functions ***/
static gint
lua_config_get_api_version (lua_State *L)
{
	msg_warn ("get_api_version is deprecated, do not use it");
	lua_pushnumber (L, 100);

	return 1;
}

static gint
lua_config_get_module_opt (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *mname, *optname;
	const ucl_object_t *obj;

	if (cfg) {
		mname = luaL_checkstring (L, 2);
		optname = luaL_checkstring (L, 3);

		if (mname && optname) {
			obj = rspamd_config_get_module_opt (cfg, mname, optname);
			if (obj) {
				return ucl_object_push_lua (L, obj, TRUE);
			}
		}
	}
	lua_pushnil (L);
	return 1;
}

static int
lua_config_get_mempool (lua_State * L)
{
	LUA_TRACE_POINT;
	rspamd_mempool_t **ppool;
	struct rspamd_config *cfg = lua_check_config (L, 1);

	if (cfg != NULL) {
		ppool = lua_newuserdata (L, sizeof (rspamd_mempool_t *));
		rspamd_lua_setclass (L, "rspamd{mempool}", -1);
		*ppool = cfg->cfg_pool;
	}
	else {
		lua_pushnil (L);
	}
	return 1;
}

static int
lua_config_get_resolver (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_dns_resolver **pres;
	struct rspamd_config *cfg = lua_check_config (L, 1);

	if (cfg != NULL && cfg->dns_resolver) {
		pres = lua_newuserdata (L, sizeof (*pres));
		rspamd_lua_setclass (L, "rspamd{resolver}", -1);
		*pres = cfg->dns_resolver;
	}
	else {
		lua_pushnil (L);
	}

	return 1;
}

static gint
lua_config_get_all_opt (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *mname;
	const ucl_object_t *obj, *cur, *cur_elt;
	ucl_object_iter_t it = NULL;
	gint i;

	if (cfg) {
		mname = luaL_checkstring (L, 2);

		if (mname) {
			obj = ucl_obj_get_key (cfg->rcl_obj, mname);
			/* Flatten object */
			if (obj != NULL && (ucl_object_type (obj) == UCL_OBJECT ||
					ucl_object_type (obj) == UCL_ARRAY)) {

				lua_newtable (L);
				it = ucl_object_iterate_new (obj);

				LL_FOREACH (obj, cur) {
					it = ucl_object_iterate_reset (it, cur);

					while ((cur_elt = ucl_object_iterate_safe (it, true))) {
						lua_pushstring (L, ucl_object_key (cur_elt));
						ucl_object_push_lua (L, cur_elt, true);
						lua_settable (L, -3);
					}
				}

				ucl_object_iterate_free (it);

				return 1;
			}
			else if (obj != NULL) {
				lua_newtable (L);
				i = 1;

				LL_FOREACH (obj, cur) {
					lua_pushinteger (L, i++);
					ucl_object_push_lua (L, cur, true);
					lua_settable (L, -3);
				}

				return 1;
			}
		}
	}
	lua_pushnil (L);

	return 1;
}

struct rspamd_lua_cached_config {
	lua_State *L;
	gint ref;
};

static void
lua_config_ucl_dtor (gpointer p)
{
	struct rspamd_lua_cached_config *cached = p;

	luaL_unref (cached->L, LUA_REGISTRYINDEX, cached->ref);
}

static gint
lua_config_get_ucl (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_lua_cached_config *cached;

	if (cfg) {
		cached = rspamd_mempool_get_variable (cfg->cfg_pool, "ucl_cached");

		if (cached) {
			lua_rawgeti (L, LUA_REGISTRYINDEX, cached->ref);
		}
		else {
			ucl_object_push_lua (L, cfg->rcl_obj, true);
			lua_pushvalue (L, -1);
			cached = rspamd_mempool_alloc (cfg->cfg_pool, sizeof (*cached));
			cached->L = L;
			cached->ref = luaL_ref (L, LUA_REGISTRYINDEX);
			rspamd_mempool_set_variable (cfg->cfg_pool, "ucl_cached",
					cached, lua_config_ucl_dtor);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}


static gint
lua_config_get_classifier (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_classifier_config *clc = NULL, **pclc = NULL;
	const gchar *name;
	GList *cur;

	if (cfg) {
		name = luaL_checkstring (L, 2);

		cur = g_list_first (cfg->classifiers);
		while (cur) {
			clc = cur->data;
			if (g_ascii_strcasecmp (clc->name, name) == 0) {
				pclc = &clc;
				break;
			}
			cur = g_list_next (cur);
		}
		if (pclc) {
			pclc = lua_newuserdata (L,
					sizeof (struct rspamd_classifier_config *));
			rspamd_lua_setclass (L, "rspamd{classifier}", -1);
			*pclc = clc;
			return 1;
		}
	}

	lua_pushnil (L);
	return 1;

}

struct lua_callback_data {
	guint64 magic;
	lua_State *L;
	gchar *symbol;

	union {
		gchar *name;
		gint ref;
	} callback;
	gboolean cb_is_ref;

	/* Dynamic data */
	gint stack_level;
	gint order;
	struct rspamd_symcache_item *item;
};

/*
 * Unref symbol if it is local reference
 */
static void
lua_destroy_cfg_symbol (gpointer ud)
{
	struct lua_callback_data *cd = ud;

	/* Unref callback */
	if (cd->cb_is_ref) {
		luaL_unref (cd->L, LUA_REGISTRYINDEX, cd->callback.ref);
	}
}

static gint
lua_config_register_module_option (lua_State *L)
{
	return 0;
}

static gint
rspamd_compare_order_func (gconstpointer a, gconstpointer b)
{
	const struct lua_callback_data *cb1 = a, *cb2 = b;

	/* order of call goes from lower to higher */
	return cb2->order - cb1->order;
}

static void
lua_metric_symbol_callback (struct rspamd_task *task,
							struct rspamd_symcache_item *item,
							gpointer ud)
{
	struct lua_callback_data *cd = ud;
	struct rspamd_task **ptask;
	gint level = lua_gettop (cd->L), nresults, err_idx, ret;
	lua_State *L = cd->L;
	struct rspamd_symbol_result *s;

	cd->item = item;
	rspamd_symcache_item_async_inc (task, item, "lua symbol");
	lua_pushcfunction (L, &rspamd_lua_traceback);
	err_idx = lua_gettop (L);

	level ++;

	if (cd->cb_is_ref) {
		lua_rawgeti (L, LUA_REGISTRYINDEX, cd->callback.ref);
	}
	else {
		lua_getglobal (L, cd->callback.name);
	}

	ptask = lua_newuserdata (L, sizeof (struct rspamd_task *));
	rspamd_lua_setclass (L, "rspamd{task}", -1);
	*ptask = task;

	if ((ret = lua_pcall (L, 1, LUA_MULTRET, err_idx)) != 0) {
		msg_err_task ("call to (%s) failed (%d): %s", cd->symbol, ret,
				lua_tostring (L, -1));
		lua_settop (L, err_idx); /* Not -1 here, as err_func is popped below */
	}
	else {
		nresults = lua_gettop (L) - level;

		if (nresults >= 1) {
			/* Function returned boolean, so maybe we need to insert result? */
			gint res = 0;
			gint i;
			gdouble flag = 1.0;
			gint type;

			type = lua_type (cd->L, level + 1);

			if (type == LUA_TBOOLEAN) {
				res = lua_toboolean (L, level + 1);
			}
			else if (type == LUA_TNUMBER) {
				res = lua_tonumber (L, level + 1);
			}
			else if (type == LUA_TNIL) {
				/* Can happen sometimes... */
				res = FALSE;
			}
			else {
				g_assert_not_reached ();
			}

			if (res) {
				gint first_opt = 2;

				if (lua_type (L, level + 2) == LUA_TNUMBER) {
					flag = lua_tonumber (L, level + 2);
					/* Shift opt index */
					first_opt = 3;
				}
				else {
					flag = res;
				}

				s = rspamd_task_insert_result (task, cd->symbol, flag, NULL);

				if (s) {
					guint last_pos = lua_gettop (L);

					for (i = level + first_opt; i <= last_pos; i++) {
						if (lua_type (L, i) == LUA_TSTRING) {
							const char *opt = lua_tostring (L, i);

							rspamd_task_add_result_option (task, s, opt);
						}
						else if (lua_type (L, i) == LUA_TTABLE) {
							lua_pushvalue (L, i);

							for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
								const char *opt = lua_tostring (L, -1);

								rspamd_task_add_result_option (task, s, opt);
							}

							lua_pop (L, 1);
						}
					}
				}

			}

			lua_pop (L, nresults);
		}
	}

	lua_pop (L, 1); /* Error function */
	rspamd_symcache_item_async_dec_check (task, cd->item, "lua symbol");
	g_assert (lua_gettop (L) == level - 1);
}

static void lua_metric_symbol_callback_return (struct thread_entry *thread_entry,
											   int ret);

static void lua_metric_symbol_callback_error (struct thread_entry *thread_entry,
											  int ret,
											  const char *msg);

static void
lua_metric_symbol_callback_coro (struct rspamd_task *task,
							struct rspamd_symcache_item *item,
							gpointer ud)
{
	struct lua_callback_data *cd = ud;
	struct rspamd_task **ptask;
	struct thread_entry *thread_entry;

	rspamd_symcache_item_async_inc (task, item, "lua coro symbol");
	thread_entry = lua_thread_pool_get_for_task (task);

	g_assert(thread_entry->cd == NULL);
	thread_entry->cd = cd;

	lua_State *thread = thread_entry->lua_state;
	cd->stack_level = lua_gettop (thread);
	cd->item = item;

	if (cd->cb_is_ref) {
		lua_rawgeti (thread, LUA_REGISTRYINDEX, cd->callback.ref);
	}
	else {
		lua_getglobal (thread, cd->callback.name);
	}

	ptask = lua_newuserdata (thread, sizeof (struct rspamd_task *));
	rspamd_lua_setclass (thread, "rspamd{task}", -1);
	*ptask = task;

	thread_entry->finish_callback = lua_metric_symbol_callback_return;
	thread_entry->error_callback = lua_metric_symbol_callback_error;

	lua_thread_call (thread_entry, 1);
}

static void
lua_metric_symbol_callback_error (struct thread_entry *thread_entry,
								  int ret,
								  const char *msg)
{
	struct lua_callback_data *cd = thread_entry->cd;
	struct rspamd_task *task = thread_entry->task;
	msg_err_task ("call to coroutine (%s) failed (%d): %s", cd->symbol, ret, msg);

	rspamd_symcache_item_async_dec_check (task, cd->item, "lua coro symbol");
}

static void
lua_metric_symbol_callback_return (struct thread_entry *thread_entry, int ret)
{
	struct lua_callback_data *cd = thread_entry->cd;
	struct rspamd_task *task = thread_entry->task;
	int nresults;
	struct rspamd_symbol_result *s;

	(void)ret;

	lua_State *L = thread_entry->lua_state;

	nresults = lua_gettop (L) - cd->stack_level;

	if (nresults >= 1) {
		/* Function returned boolean, so maybe we need to insert result? */
		gint res = 0;
		gint i;
		gdouble flag = 1.0;
		gint type;

		type = lua_type (L, cd->stack_level + 1);

		if (type == LUA_TBOOLEAN) {
			res = lua_toboolean (L, cd->stack_level + 1);
		}
		else if (type == LUA_TFUNCTION) {
			g_assert_not_reached ();
		}
		else {
			res = lua_tonumber (L, cd->stack_level + 1);
		}

		if (res) {
			gint first_opt = 2;

			if (lua_type (L, cd->stack_level + 2) == LUA_TNUMBER) {
				flag = lua_tonumber (L, cd->stack_level + 2);
				/* Shift opt index */
				first_opt = 3;
			}
			else {
				flag = res;
			}

			s = rspamd_task_insert_result (task, cd->symbol, flag, NULL);

			if (s) {
				guint last_pos = lua_gettop (L);

				for (i = cd->stack_level + first_opt; i <= last_pos; i++) {
					if (lua_type (L, i) == LUA_TSTRING) {
						const char *opt = lua_tostring (L, i);

						rspamd_task_add_result_option (task, s, opt);
					}
					else if (lua_type (L, i) == LUA_TTABLE) {
						lua_pushvalue (L, i);

						for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
							const char *opt = lua_tostring (L, -1);

							rspamd_task_add_result_option (task, s, opt);
						}

						lua_pop (L, 1);
					}
				}
			}

		}

		lua_pop (L, nresults);
	}

	g_assert (lua_gettop (L) == cd->stack_level); /* we properly cleaned up the stack */

	cd->stack_level = 0;
	rspamd_symcache_item_async_dec_check (task, cd->item, "lua coro symbol");
}

static guint32*
rspamd_process_id_list (const gchar *entries, guint32 *plen)
{
	gchar **sym_elts;
	guint32 *ids, nids;

	sym_elts = g_strsplit_set (entries, ",;", -1);
	nids = g_strv_length (sym_elts);

	ids = g_malloc (nids * sizeof (guint32));

	for (guint i = 0; i < nids; i ++) {
		ids[i] = rspamd_config_name_to_id (sym_elts[i], strlen (sym_elts[i]));
	}

	*plen = nids;
	g_strfreev (sym_elts);

	return ids;
}

static gint
rspamd_register_symbol_fromlua (lua_State *L,
		struct rspamd_config *cfg,
		const gchar *name,
		gint ref,
		gdouble weight,
		gint priority,
		enum rspamd_symbol_type type,
		gint parent,
		const gchar *allowed_ids,
		const gchar *forbidden_ids,
		gboolean optional)
{
	struct lua_callback_data *cd;
	gint ret = -1;
	guint32 *ids, nids;

	if (priority == 0 && weight < 0) {
		priority = 1;
	}

	if ((ret = rspamd_symcache_find_symbol (cfg->cache, name)) != -1) {
		if (optional) {
			msg_debug_config ("duplicate symbol: %s, skip registering", name);

			return ret;
		}
		else {
			msg_err_config ("duplicate symbol: %s, skip registering", name);

			return -1;
		}
	}

	if (allowed_ids && !(type & SYMBOL_TYPE_EXPLICIT_DISABLE)) {
		/* Mark symbol as explicit allow */
		msg_info_config ("mark symbol %s as explicit enable as its execution is"
				   "allowed merely on specific settings ids", name);
		type |= SYMBOL_TYPE_EXPLICIT_ENABLE;
	}

	if (ref != -1) {
		cd = rspamd_mempool_alloc0 (cfg->cfg_pool,
				sizeof (struct lua_callback_data));
		cd->magic = rspamd_lua_callback_magic;
		cd->cb_is_ref = TRUE;
		cd->callback.ref = ref;
		cd->L = L;

		if (name) {
			cd->symbol = rspamd_mempool_strdup (cfg->cfg_pool, name);
		}

		if (type & SYMBOL_TYPE_USE_CORO) {
			ret = rspamd_symcache_add_symbol (cfg->cache,
					name,
					priority,
					lua_metric_symbol_callback_coro,
					cd,
					type,
					parent);
		}
		else {
			ret = rspamd_symcache_add_symbol (cfg->cache,
					name,
					priority,
					lua_metric_symbol_callback,
					cd,
					type,
					parent);
		}
		rspamd_mempool_add_destructor (cfg->cfg_pool,
				(rspamd_mempool_destruct_t)lua_destroy_cfg_symbol,
				cd);
	}
	else {
		/* No callback */
		ret = rspamd_symcache_add_symbol (cfg->cache,
				name,
				priority,
				NULL,
				NULL,
				type,
				parent);
	}

	if (allowed_ids) {
		ids = rspamd_process_id_list (allowed_ids, &nids);

		if (nids > 0) {
			rspamd_symcache_set_allowed_settings_ids (cfg->cache, name,
					ids, nids);

			g_free (ids);
		}
	}

	if (forbidden_ids) {
		ids = rspamd_process_id_list (forbidden_ids, &nids);

		if (nids > 0) {
			rspamd_symcache_set_forbidden_settings_ids (cfg->cache, name,
					ids, nids);

			g_free (ids);
		}
	}

	return ret;
}

static gint
lua_config_register_post_filter (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	gint order = 0, cbref, ret;

	if (cfg) {
		if (lua_type (L, 3) == LUA_TNUMBER) {
			order = lua_tonumber (L, 3);
		}

		if (lua_type (L, 2) == LUA_TFUNCTION) {
			lua_pushvalue (L, 2);
			/* Get a reference */
			cbref = luaL_ref (L, LUA_REGISTRYINDEX);
		}
		else {
			return luaL_error (L, "invalid type for callback: %s",
					lua_typename (L, lua_type (L, 2)));
		}

		msg_warn_config ("register_post_filter function is deprecated, "
				"use register_symbol instead");

		ret = rspamd_register_symbol_fromlua (L,
				cfg,
				NULL,
				cbref,
				1.0,
				order,
				SYMBOL_TYPE_POSTFILTER|SYMBOL_TYPE_CALLBACK,
				-1,
				NULL, NULL,
				FALSE);

		lua_pushboolean (L, ret);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_register_pre_filter (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	gint order = 0, cbref, ret;

	if (cfg) {
		if (lua_type (L, 3) == LUA_TNUMBER) {
			order = lua_tonumber (L, 3);
		}

		if (lua_type (L, 2) == LUA_TFUNCTION) {
			lua_pushvalue (L, 2);
			/* Get a reference */
			cbref = luaL_ref (L, LUA_REGISTRYINDEX);
		}
		else {
			return luaL_error (L, "invalid type for callback: %s",
					lua_typename (L, lua_type (L, 2)));
		}

		msg_warn_config ("register_pre_filter function is deprecated, "
				"use register_symbol instead");

		ret = rspamd_register_symbol_fromlua (L,
				cfg,
				NULL,
				cbref,
				1.0,
				order,
				SYMBOL_TYPE_PREFILTER|SYMBOL_TYPE_CALLBACK,
				-1,
				NULL, NULL,
				FALSE);

		lua_pushboolean (L, ret);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_get_key (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *name;
	size_t namelen;
	const ucl_object_t *val;

	name = luaL_checklstring(L, 2, &namelen);
	if (name && cfg) {
		val = ucl_object_lookup_len(cfg->rcl_obj, name, namelen);
		if (val != NULL) {
			ucl_object_push_lua (L, val, val->type != UCL_ARRAY);
		}
		else {
			lua_pushnil (L);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static guint
lua_parse_symbol_flags (const gchar *str)
{
	guint ret = 0;

	if (str) {
		if (strstr (str, "fine") != NULL) {
			ret |= SYMBOL_TYPE_FINE;
		}
		if (strstr (str, "nice") != NULL) {
			ret |= SYMBOL_TYPE_FINE;
		}
		if (strstr (str, "empty") != NULL) {
			ret |= SYMBOL_TYPE_EMPTY;
		}
		if (strstr (str, "skip") != NULL) {
			ret |= SYMBOL_TYPE_SKIPPED;
		}
		if (strstr (str, "nostat") != NULL) {
			ret |= SYMBOL_TYPE_NOSTAT;
		}
		if (strstr (str, "idempotent") != NULL) {
			ret |= SYMBOL_TYPE_IDEMPOTENT;
		}
		if (strstr (str, "trivial") != NULL) {
			ret |= SYMBOL_TYPE_TRIVIAL;
		}
		if (strstr (str, "ghost") != NULL) {
			ret |= SYMBOL_TYPE_GHOST;
		}
		if (strstr (str, "mime") != NULL) {
			ret |= SYMBOL_TYPE_MIME_ONLY;
		}
		if (strstr (str, "ignore_passthrough") != NULL) {
			ret |= SYMBOL_TYPE_IGNORE_PASSTHROUGH;
		}
		if (strstr (str, "explicit_disable") != NULL) {
			ret |= SYMBOL_TYPE_EXPLICIT_DISABLE;
		}
		if (strstr (str, "explicit_enable") != NULL) {
			ret |= SYMBOL_TYPE_EXPLICIT_ENABLE;
		}
		if (strstr (str, "coro") != NULL) {
			ret |= SYMBOL_TYPE_USE_CORO;
		}
	}

	return ret;
}

static guint
lua_parse_symbol_type (const gchar *str)
{
	guint ret = SYMBOL_TYPE_NORMAL;
	gchar **vec;
	guint i, l;

	if (str) {
		vec = g_strsplit_set (str, ",;", -1);

		if (vec) {
			l = g_strv_length (vec);

			for (i = 0; i < l; i ++) {
				str = vec[i];

				if (g_ascii_strcasecmp (str, "virtual") == 0) {
					ret = SYMBOL_TYPE_VIRTUAL;
				} else if (g_ascii_strcasecmp (str, "callback") == 0) {
					ret = SYMBOL_TYPE_CALLBACK;
				} else if (g_ascii_strcasecmp (str, "normal") == 0) {
					ret = SYMBOL_TYPE_NORMAL;
				} else if (g_ascii_strcasecmp (str, "prefilter") == 0) {
					ret = SYMBOL_TYPE_PREFILTER | SYMBOL_TYPE_GHOST;
				} else if (g_ascii_strcasecmp (str, "postfilter") == 0) {
					ret = SYMBOL_TYPE_POSTFILTER | SYMBOL_TYPE_GHOST;
				} else if (g_ascii_strcasecmp (str, "idempotent") == 0) {
					ret = SYMBOL_TYPE_POSTFILTER | SYMBOL_TYPE_GHOST |
							SYMBOL_TYPE_IDEMPOTENT;
				} else {
					gint fl = 0;

					fl = lua_parse_symbol_flags (str);

					if (fl == 0) {
						msg_warn ("bad type: %s", str);
					}
					else {
						ret |= fl;
					}
				}
			}

			g_strfreev (vec);
		}
	}

	return ret;
}

static void
lua_push_symbol_flags (lua_State *L, guint flags)
{
	guint i = 1;

	lua_newtable (L);

	if (flags & SYMBOL_TYPE_FINE) {
		lua_pushstring (L, "fine");
		lua_rawseti (L, -2, i++);
	}

	if (flags & SYMBOL_TYPE_EMPTY) {
		lua_pushstring (L, "empty");
		lua_rawseti (L, -2, i++);
	}

	if (flags & SYMBOL_TYPE_EXPLICIT_DISABLE) {
		lua_pushstring (L, "explicit_disable");
		lua_rawseti (L, -2, i++);
	}

	if (flags & SYMBOL_TYPE_EXPLICIT_ENABLE) {
		lua_pushstring (L, "explicit_enable");
		lua_rawseti (L, -2, i++);
	}

	if (flags & SYMBOL_TYPE_IGNORE_PASSTHROUGH) {
		lua_pushstring (L, "ignore_passthrough");
		lua_rawseti (L, -2, i++);
	}

	if (flags & SYMBOL_TYPE_NOSTAT) {
		lua_pushstring (L, "nostat");
		lua_rawseti (L, -2, i++);
	}

	if (flags & SYMBOL_TYPE_IDEMPOTENT) {
		lua_pushstring (L, "idempotent");
		lua_rawseti (L, -2, i++);
	}

	if (flags & SYMBOL_TYPE_MIME_ONLY) {
		lua_pushstring (L, "mime");
		lua_rawseti (L, -2, i++);
	}

	if (flags & SYMBOL_TYPE_TRIVIAL) {
		lua_pushstring (L, "trivial");
		lua_rawseti (L, -2, i++);
	}

	if (flags & SYMBOL_TYPE_SKIPPED) {
		lua_pushstring (L, "skip");
		lua_rawseti (L, -2, i++);
	}
}

static gint
lua_config_get_symbol_flags (lua_State *L)
{
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *name = luaL_checkstring (L, 2);
	guint flags;

	if (cfg && name) {
		flags = rspamd_symcache_get_symbol_flags (cfg->cache,
				name);

		if (flags != 0) {
			lua_push_symbol_flags (L, flags);
		}
		else {
			lua_pushnil (L);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_add_symbol_flags (lua_State *L)
{
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *name = luaL_checkstring (L, 2);
	guint flags, new_flags = 0;

	if (cfg && name && lua_istable (L, 3)) {

		for (lua_pushnil (L); lua_next (L, 3); lua_pop (L, 1)) {
			new_flags |= lua_parse_symbol_flags (lua_tostring (L, -1));
		}

		flags = rspamd_symcache_get_symbol_flags (cfg->cache,
				name);

		if (flags != 0) {
			rspamd_symcache_add_symbol_flags (cfg->cache, name, new_flags);
			/* Push old flags */
			lua_push_symbol_flags (L, flags);
		}
		else {
			lua_pushnil (L);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_register_symbol (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *name = NULL, *flags_str = NULL, *type_str = NULL,
			*description = NULL, *group = NULL, *allowed_ids = NULL,
			*forbidden_ids = NULL;
	double weight = 0, score = NAN, parent_float = NAN;
	gboolean one_shot = FALSE;
	gint ret = -1, cbref = -1, type, flags = 0;
	gint64 parent = 0, priority = 0, nshots = 0;
	GError *err = NULL;

	if (cfg) {
		if (!rspamd_lua_parse_table_arguments (L, 2, &err,
				"name=S;weight=N;callback=F;flags=S;type=S;priority=I;parent=D;"
				"score=D;description=S;group=S;one_shot=B;nshots=I;"
				"allowed_ids=S;forbidden_ids=S",
				&name, &weight, &cbref, &flags_str, &type_str,
				&priority, &parent_float,
				&score, &description, &group, &one_shot, &nshots,
				&allowed_ids, &forbidden_ids)) {
			msg_err_config ("bad arguments: %e", err);
			g_error_free (err);

			return luaL_error (L, "invalid arguments");
		}

		if (nshots == 0) {
			nshots = cfg->default_max_shots;
		}

		type = lua_parse_symbol_type (type_str);

		if (!name && !(type & SYMBOL_TYPE_CALLBACK)) {
			return luaL_error (L, "no symbol name but type is not callback");
		}
		else if (!(type & SYMBOL_TYPE_VIRTUAL) && cbref == -1) {
			return luaL_error (L, "no callback for symbol %s", name);
		}

		if (flags_str) {
			type |= lua_parse_symbol_flags (flags_str);
		}

		if (isnan (parent_float)) {
			parent = -1;
		}
		else {
			parent = parent_float;
		}

		ret = rspamd_register_symbol_fromlua (L,
				cfg,
				name,
				cbref,
				weight == 0 ? 1.0 : weight,
				priority,
				type,
				parent,
				allowed_ids, forbidden_ids,
				FALSE);

		if (!isnan (score) || group) {
			if (one_shot) {
				nshots = 1;
			}

			if (!isnan (score)) {
				rspamd_config_add_symbol (cfg, name,
						score, description, group, flags,
						(guint) priority, nshots);
			}
			else {
				rspamd_config_add_symbol (cfg, name,
						0.0, description, group, flags,
						(guint) priority, nshots);
			}

			lua_pushstring (L, "groups");
			lua_gettable (L, 2);

			if (lua_istable (L, -1)) {
				for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
					if (lua_isstring (L, -1)) {
						rspamd_config_add_symbol_group (cfg, name,
								lua_tostring (L, -1));
					}
					else {
						return luaL_error (L, "invalid groups element");
					}
				}
			}

			lua_pop (L, 1);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	lua_pushinteger (L, ret);

	return 1;
}

static gint
lua_config_register_symbols (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	gint i, top, idx, ret = -1;
	const gchar *sym;
	gdouble weight = 1.0;

	if (lua_gettop (L) < 3) {
		if (cfg) {
			msg_err_config ("not enough arguments to register a function");
		}

		lua_error (L);

		return 0;
	}
	if (cfg) {
		if (lua_type (L, 2) == LUA_TSTRING) {
			lua_getglobal (L, luaL_checkstring (L, 2));
		}
		else {
			lua_pushvalue (L, 2);
		}
		idx = luaL_ref (L, LUA_REGISTRYINDEX);

		if (lua_type (L, 3) == LUA_TNUMBER) {
			weight = lua_tonumber (L, 3);
			top = 4;
		}
		else {
			top = 3;
		}
		sym = luaL_checkstring (L, top ++);
		ret = rspamd_register_symbol_fromlua (L,
				cfg,
				sym,
				idx,
				weight,
				0,
				SYMBOL_TYPE_CALLBACK,
				-1,
				NULL, NULL,
				FALSE);

		for (i = top; i <= lua_gettop (L); i++) {
			if (lua_type (L, i) == LUA_TTABLE) {
				lua_pushvalue (L, i);
				lua_pushnil (L);
				while (lua_next (L, -2)) {
					lua_pushvalue (L, -2);
					sym = luaL_checkstring (L, -2);
					rspamd_symcache_add_symbol (cfg->cache, sym,
							0, NULL, NULL,
							SYMBOL_TYPE_VIRTUAL, ret);
					lua_pop (L, 2);
				}
				lua_pop (L, 1);
			}
			else if (lua_type (L, i) == LUA_TSTRING) {
				sym = luaL_checkstring (L, i);
				rspamd_symcache_add_symbol (cfg->cache, sym,
						0, NULL, NULL,
						SYMBOL_TYPE_VIRTUAL, ret);
			}
		}
	}

	lua_pushinteger (L, ret);

	return 1;
}

static gint
lua_config_register_virtual_symbol (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *name;
	double weight;
	gint ret = -1, parent = -1;

	if (cfg) {
		name = luaL_checkstring (L, 2);
		weight = luaL_checknumber (L, 3);

		if (lua_gettop (L) > 3) {
			parent = lua_tonumber (L, 4);
		}

		if (name) {
			ret = rspamd_symcache_add_symbol (cfg->cache, name,
					weight > 0 ? 0 : -1, NULL, NULL,
					SYMBOL_TYPE_VIRTUAL, parent);
		}
	}

	lua_pushinteger (L, ret);

	return 1;
}

static gint
lua_config_register_callback_symbol (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *name = NULL;
	double weight;
	gint ret = -1, top = 2;

	if (cfg) {
		if (lua_type (L, 2) == LUA_TSTRING) {
			/* Legacy syntax */
			name = luaL_checkstring (L, 2);
			top ++;
		}

		weight = luaL_checknumber (L, top);

		if (lua_type (L, top + 1) == LUA_TSTRING) {
			lua_getglobal (L, luaL_checkstring (L, top + 1));
		}
		else {
			lua_pushvalue (L, top + 1);
		}
		ret = rspamd_register_symbol_fromlua (L,
				cfg,
				name,
				luaL_ref (L, LUA_REGISTRYINDEX),
				weight,
				0,
				SYMBOL_TYPE_CALLBACK,
				-1,
				NULL, NULL,
				FALSE);
	}

	lua_pushinteger (L, ret);

	return 1;
}

static gint
lua_config_register_callback_symbol_priority (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *name = NULL;
	double weight;
	gint priority, ret = -1, top = 2;

	if (cfg) {
		if (lua_type (L, 2) == LUA_TSTRING) {
			/* Legacy syntax */
			name = luaL_checkstring (L, 2);
			top ++;
		}

		weight = luaL_checknumber (L, top);
		priority = luaL_checknumber (L, top + 1);

		if (lua_type (L, top + 2) == LUA_TSTRING) {
			lua_getglobal (L, luaL_checkstring (L, top + 2));
		}
		else {
			lua_pushvalue (L, top + 2);
		}

		ret = rspamd_register_symbol_fromlua (L,
				cfg,
				name,
				luaL_ref (L, LUA_REGISTRYINDEX),
				weight,
				priority,
				SYMBOL_TYPE_CALLBACK,
				-1,
				NULL, NULL,
				FALSE);
	}

	lua_pushinteger (L, ret);

	return 1;
}


static gint
lua_config_register_dependency (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *parent = NULL, *child = NULL;
	gint child_id;

	if (cfg == NULL) {
		lua_error (L);
		return 0;
	}

	if (lua_type (L, 2) == LUA_TNUMBER) {
		child_id = luaL_checknumber (L, 2);
		parent = luaL_checkstring (L, 3);

		msg_warn_config ("calling for obsolete method to register deps for symbol %d->%s",
				child_id, parent);

		if (child_id > 0 && parent != NULL) {

			rspamd_symcache_add_dependency (cfg->cache, child_id, parent);
		}
	}
	else {
		child = luaL_checkstring (L,2);
		parent = luaL_checkstring (L, 3);

		if (child != NULL && parent != NULL) {
			rspamd_symcache_add_delayed_dependency (cfg->cache, child,
					parent);
		}
	}

	return 0;
}

static gint
lua_config_set_metric_symbol (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *description = NULL,
			*group = NULL, *name = NULL, *flags_str = NULL;
	double weight;
	gboolean one_shot = FALSE, one_param = FALSE;
	GError *err = NULL;
	gdouble priority = 0.0;
	guint flags = 0;
	gint64 nshots = 0;

	if (cfg) {

		if (lua_type (L, 2) == LUA_TTABLE) {
			if (!rspamd_lua_parse_table_arguments (L, 2, &err,
					"*name=S;score=N;description=S;"
					"group=S;one_shot=B;one_param=B;priority=N;flags=S;"
					"nshots=I",
					&name, &weight, &description,
					&group, &one_shot, &one_param,
					&priority, &flags_str, &nshots)) {
				msg_err_config ("bad arguments: %e", err);
				g_error_free (err);

				return 0;
			}
		}
		else {
			name = luaL_checkstring (L, 2);
			weight = luaL_checknumber (L, 3);

			if (lua_gettop (L) > 3 && lua_type (L, 4) == LUA_TSTRING) {
				description = luaL_checkstring (L, 4);
			}
			if (lua_gettop (L) > 4 && lua_type (L, 5) == LUA_TSTRING) {
				/* XXX: metrics */
			}
			if (lua_gettop (L) > 5 && lua_type (L, 6) == LUA_TSTRING) {
				group = luaL_checkstring (L, 6);
			}
			if (lua_gettop (L) > 6 && lua_type (L, 7) == LUA_TBOOLEAN) {
				one_shot = lua_toboolean (L, 7);
			}
		}

		if (nshots == 0) {
			nshots = cfg->default_max_shots;
		}

		if (one_shot) {
			nshots = 1;
		}
		if (one_param) {
			flags |= RSPAMD_SYMBOL_FLAG_ONEPARAM;
		}

		if (flags_str) {
			if (strstr (flags_str, "one_shot") != NULL) {
				nshots = 1;
			}
			if (strstr (flags_str, "ignore") != NULL) {
				flags |= RSPAMD_SYMBOL_FLAG_IGNORE;
			}
			if (strstr (flags_str, "one_param") != NULL) {
				flags |= RSPAMD_SYMBOL_FLAG_ONEPARAM;
			}
		}

		rspamd_config_add_symbol (cfg, name,
				weight, description, group, flags, (guint) priority, nshots);


		if (lua_type (L, 2) == LUA_TTABLE) {
			lua_pushstring (L, "groups");
			lua_gettable (L, 2);

			if (lua_istable (L, -1)) {
				for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
					if (lua_isstring (L, -1)) {
						rspamd_config_add_symbol_group (cfg, name,
								lua_tostring (L, -1));
					} else {
						return luaL_error (L, "invalid groups element");
					}
				}
			}

			lua_pop (L, 1);
		}
	}
	else {
		return luaL_error (L, "invalid arguments, rspamd_config expected");
	}

	return 0;
}

static gint
lua_config_get_metric_symbol (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *sym_name = luaL_checkstring (L, 2);
	struct rspamd_symbol *sym_def;
	struct rspamd_symbols_group *sym_group;
	guint i;

	if (cfg && sym_name) {
		sym_def = g_hash_table_lookup (cfg->symbols, sym_name);

		if (sym_def == NULL) {
			lua_pushnil (L);
		}
		else {
			lua_createtable (L, 0, 3);
			lua_pushstring (L, "score");
			lua_pushnumber (L, sym_def->score);
			lua_settable (L, -3);

			if (sym_def->description) {
				lua_pushstring (L, "description");
				lua_pushstring (L, sym_def->description);
				lua_settable (L, -3);
			}

			if (sym_def->gr) {
				lua_pushstring (L, "group");
				lua_pushstring (L, sym_def->gr->name);
				lua_settable (L, -3);
			}

			lua_pushstring (L, "groups");
			lua_createtable (L, sym_def->groups->len, 0);

			PTR_ARRAY_FOREACH (sym_def->groups, i, sym_group) {
				lua_pushstring (L, sym_group->name);
				lua_rawseti (L, -2, i + 1);
			}

			lua_settable (L, -3);
		}
	}
	else {
		luaL_error (L, "Invalid arguments");
	}

	return 1;
}

static gint
lua_config_set_metric_action (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *name = NULL;
	double threshold = NAN;
	GError *err = NULL;
	gdouble priority = 0.0;
	ucl_object_t *obj_tbl = NULL;

	if (cfg) {

		if (lua_type (L, 2) == LUA_TTABLE) {
			if (!rspamd_lua_parse_table_arguments (L, 2, &err,
					"*action=S;score=N;"
					"priority=N",
					&name, &threshold,
					&priority)) {
				msg_err_config ("bad arguments: %e", err);
				g_error_free (err);

				return 0;
			}
		}
		else if (lua_type (L, 2) == LUA_TSTRING && lua_type (L, 3) == LUA_TTABLE) {
			name = lua_tostring (L, 2);
			obj_tbl = ucl_object_lua_import (L, 3);

			if (obj_tbl) {
				if (name) {
					rspamd_config_set_action_score (cfg, name, obj_tbl);
					ucl_object_unref (obj_tbl);
				}
				else {
					ucl_object_unref (obj_tbl);
					return luaL_error (L, "invalid first argument, action name expected");
				}
			}
			else {
				return luaL_error (L, "invalid second argument, table expected");
			}
		}
		else {
			return luaL_error (L, "invalid arguments, table expected");
		}

		if (name != NULL && !isnan (threshold) && threshold != 0) {
			obj_tbl = ucl_object_typed_new (UCL_OBJECT);
			ucl_object_insert_key (obj_tbl, ucl_object_fromdouble (threshold),
					"score", 0, false);
			ucl_object_insert_key (obj_tbl, ucl_object_fromdouble (priority),
					"priority", 0, false);
			rspamd_config_set_action_score (cfg, name, obj_tbl);
			ucl_object_unref (obj_tbl);
		}
	}
	else {
		return luaL_error (L, "invalid arguments, rspamd_config expected");
	}

	return 0;
}

static gint
lua_config_get_metric_action (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *act_name = luaL_checkstring (L, 2);
	struct rspamd_action *act;

	if (cfg && act_name) {
		act = rspamd_config_get_action (cfg, act_name);

		if (act) {
			if (!isnan (act->threshold)) {
				lua_pushnumber (L, act->threshold);
			}
			else {
				lua_pushnil (L);
			}
		}
		else {
			lua_pushnil (L);
		}
	}
	else {
		return luaL_error (L, "invalid arguments, rspamd_config expected");
	}

	return 1;
}

static gint
lua_config_get_all_actions (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_action *act, *tmp;

	if (cfg) {
		lua_createtable (L, 0, HASH_COUNT (cfg->actions));

		HASH_ITER (hh, cfg->actions, act, tmp) {
			if (!isnan (act->threshold)) {
				lua_pushstring (L, act->name);
				lua_pushnumber (L, act->threshold);
				lua_settable (L, -3);
			}
		}
	}
	else {
		return luaL_error (L, "invalid arguments, rspamd_config expected");
	}

	return 1;
}

static gint
lua_config_add_composite (lua_State * L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_expression *expr;
	gchar *name;
	const gchar *expr_str;
	struct rspamd_composite *composite;
	gboolean ret = FALSE, new = TRUE;
	GError *err = NULL;

	if (cfg) {
		name = rspamd_mempool_strdup (cfg->cfg_pool, luaL_checkstring (L, 2));
		expr_str = luaL_checkstring (L, 3);

		if (name && expr_str) {
			if (!rspamd_parse_expression (expr_str, 0, &composite_expr_subr,
					NULL, cfg->cfg_pool, &err, &expr)) {
				msg_err_config ("cannot parse composite expression %s: %e",
						expr_str,
						err);
				g_error_free (err);
			}
			else {
				if (g_hash_table_lookup (cfg->composite_symbols, name) != NULL) {
					msg_warn_config ("composite %s is redefined", name);
					new = FALSE;
				}

				composite = rspamd_mempool_alloc0 (cfg->cfg_pool,
						sizeof (struct rspamd_composite));
				composite->expr = expr;
				composite->id = g_hash_table_size (cfg->composite_symbols);
				composite->str_expr = rspamd_mempool_strdup (cfg->cfg_pool,
						expr_str);
				composite->sym = name;
				g_hash_table_insert (cfg->composite_symbols,
						(gpointer)name,
						composite);

				if (new) {
					rspamd_symcache_add_symbol (cfg->cache, name,
							0, NULL, composite, SYMBOL_TYPE_COMPOSITE, -1);
				}

				ret = TRUE;
			}
		}
	}

	lua_pushboolean (L, ret);

	return 1;
}

static gint
lua_config_newindex (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *name, *allowed_ids = NULL, *forbidden_ids = NULL;
	gint id, nshots, flags = 0;
	gboolean optional = FALSE;

	name = luaL_checkstring (L, 2);

	if (cfg != NULL && name != NULL && lua_gettop (L) == 3) {

		if (lua_type (L, 3) == LUA_TFUNCTION) {
			/* Normal symbol from just a function */
			lua_pushvalue (L, 3);
			rspamd_register_symbol_fromlua (L,
					cfg,
					name,
					luaL_ref (L, LUA_REGISTRYINDEX),
					1.0,
					0,
					SYMBOL_TYPE_NORMAL,
					-1,
					NULL, NULL,
					FALSE);
		}
		else if (lua_type (L, 3) == LUA_TTABLE) {
			gint type = SYMBOL_TYPE_NORMAL, priority = 0, idx;
			gdouble weight = 1.0, score = NAN;
			const char *type_str, *group = NULL, *description = NULL;

			/*
			 * Table can have the following attributes:
			 * "callback" - should be a callback function
			 * "weight" - optional weight
			 * "priority" - optional priority
			 * "type" - optional type (normal, virtual, callback)
			 * "flags" - optional flags
			 * -- Metric options
			 * "score" - optional default score (overridden by metric)
			 * "group" - optional default group
			 * "one_shot" - optional one shot mode
			 * "description" - optional description
			 */
			lua_pushvalue (L, 3);
			lua_pushstring (L, "callback");
			lua_gettable (L, -2);

			if (lua_type (L, -1) != LUA_TFUNCTION) {
				lua_pop (L, 2);
				msg_info_config ("cannot find callback definition for %s",
						name);
				return 0;
			}
			idx = luaL_ref (L, LUA_REGISTRYINDEX);

			/* Optional fields */
			lua_pushstring (L, "weight");
			lua_gettable (L, -2);

			if (lua_type (L, -1) == LUA_TNUMBER) {
				weight = lua_tonumber (L, -1);
			}
			lua_pop (L, 1);

			lua_pushstring (L, "priority");
			lua_gettable (L, -2);

			if (lua_type (L, -1) == LUA_TNUMBER) {
				priority = lua_tonumber (L, -1);
			}
			lua_pop (L, 1);

			lua_pushstring (L, "optional");
			lua_gettable (L, -2);

			if (lua_type (L, -1) == LUA_TBOOLEAN) {
				optional = lua_toboolean (L, -1);
			}
			lua_pop (L, 1);

			lua_pushstring (L, "type");
			lua_gettable (L, -2);

			if (lua_type (L, -1) == LUA_TSTRING) {
				type_str = lua_tostring (L, -1);
				type = lua_parse_symbol_type (type_str);
			}
			lua_pop (L, 1);

			lua_pushstring (L, "flags");
			lua_gettable (L, -2);

			if (lua_type (L, -1) == LUA_TSTRING) {
				type_str = lua_tostring (L, -1);
				type |= lua_parse_symbol_flags (type_str);
			}
			lua_pop (L, 1);

			lua_pushstring (L, "allowed_ids");
			lua_gettable (L, -2);

			if (lua_type (L, -1) == LUA_TSTRING) {
				allowed_ids = lua_tostring (L, -1);
			}
			lua_pop (L, 1);

			lua_pushstring (L, "forbidden_ids");
			lua_gettable (L, -2);

			if (lua_type (L, -1) == LUA_TSTRING) {
				forbidden_ids = lua_tostring (L, -1);
			}
			lua_pop (L, 1);

			id = rspamd_register_symbol_fromlua (L,
					cfg,
					name,
					idx,
					weight,
					priority,
					type,
					-1,
					allowed_ids, forbidden_ids,
					optional);

			if (id != -1) {
				/* Check for condition */
				lua_pushstring (L, "condition");
				lua_gettable (L, -2);

				if (lua_type (L, -1) == LUA_TFUNCTION) {
					gint condref;

					/* Here we pop function from the stack, so no lua_pop is required */
					condref = luaL_ref (L, LUA_REGISTRYINDEX);
					g_assert (name != NULL);
					rspamd_symcache_add_condition_delayed (cfg->cache,
							name, L, condref);
				}
				else {
					lua_pop (L, 1);
				}
			}

			/*
			 * Now check if a symbol has not been registered in any metric and
			 * insert default value if applicable
			 */
			if (g_hash_table_lookup (cfg->symbols, name) == NULL) {
				nshots = cfg->default_max_shots;

				lua_pushstring (L, "score");
				lua_gettable (L, -2);
				if (lua_type (L, -1) == LUA_TNUMBER) {
					score = lua_tonumber (L, -1);

				}
				lua_pop (L, 1);

				lua_pushstring (L, "group");
				lua_gettable (L, -2);
				if (lua_type (L, -1) == LUA_TSTRING) {
					group = lua_tostring (L, -1);
				}
				lua_pop (L, 1);

				if (!isnan (score) || group != NULL) {
					lua_pushstring (L, "description");
					lua_gettable (L, -2);

					if (lua_type (L, -1) == LUA_TSTRING) {
						description = lua_tostring (L, -1);
					}
					lua_pop (L, 1);

					lua_pushstring (L, "one_shot");
					lua_gettable (L, -2);

					if (lua_type (L, -1) == LUA_TBOOLEAN) {
						if (lua_toboolean (L, -1)) {
							nshots = 1;
						}
					}
					lua_pop (L, 1);

					lua_pushstring (L, "one_param");
					lua_gettable (L, -2);

					if (lua_type (L, -1) == LUA_TBOOLEAN) {
						if (lua_toboolean (L, -1)) {
							flags |= RSPAMD_SYMBOL_FLAG_ONEPARAM;
						}
					}
					lua_pop (L, 1);

					/*
					 * Do not override the existing symbols (using zero priority),
					 * since we are defining default values here
					 */
					if (!isnan (score)) {
						rspamd_config_add_symbol (cfg, name, score,
								description, group, flags, 0, nshots);
					}
					else if (group) {
						/* Add with zero score */
						rspamd_config_add_symbol (cfg, name, 0.0,
								description, group, flags, 0, nshots);
					}

					lua_pushstring (L, "groups");
					lua_gettable (L, -2);

					if (lua_istable (L, -1)) {
						for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
							if (lua_isstring (L, -1)) {
								rspamd_config_add_symbol_group (cfg, name,
										lua_tostring (L, -1));
							}
							else {
								return luaL_error (L, "invalid groups element");
							}
						}
					}

					lua_pop (L, 1);
				}
			}

			/* Remove table from stack */
			lua_pop (L, 1);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 0;
}

static gint
lua_config_add_condition (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *sym = luaL_checkstring (L, 2);
	gboolean ret = FALSE;
	gint condref;

	if (cfg && sym && lua_type (L, 3) == LUA_TFUNCTION) {
		lua_pushvalue (L, 3);
		condref = luaL_ref (L, LUA_REGISTRYINDEX);

		ret = rspamd_symcache_add_condition_delayed (cfg->cache, sym, L,
				condref);

		if (!ret) {
			luaL_unref (L, LUA_REGISTRYINDEX, condref);
		}
	}

	lua_pushboolean (L, ret);
	return 1;
}

static gint
lua_config_set_peak_cb (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	gint condref;

	if (cfg && lua_type (L, 2) == LUA_TFUNCTION) {
		lua_pushvalue (L, 2);
		condref = luaL_ref (L, LUA_REGISTRYINDEX);
		rspamd_symcache_set_peak_callback (cfg->cache,
				condref);
	}

	return 0;
}

static gint
lua_config_enable_symbol (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *sym = luaL_checkstring (L, 2);

	if (cfg && sym) {
		rspamd_symcache_enable_symbol_perm (cfg->cache, sym);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 0;
}

static gint
lua_config_disable_symbol (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *sym = luaL_checkstring (L, 2);

	if (cfg && sym) {
		rspamd_symcache_disable_symbol_perm (cfg->cache, sym);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 0;
}

static gint
lua_config_register_regexp (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_lua_regexp *re = NULL;
	rspamd_regexp_t *cache_re;
	const gchar *type_str = NULL, *header_str = NULL;
	gsize header_len = 0;
	GError *err = NULL;
	enum rspamd_re_type type = RSPAMD_RE_BODY;
	gboolean pcre_only = FALSE;
	guint old_flags;

	/*
	 * - `re`* : regular expression object
 	 * - `type`*: type of regular expression:
	 *   + `mime`: mime regexp
	 *   + `rawmime`: raw mime regexp
	 *   + `header`: header regexp
	 *   + `rawheader`: raw header expression
	 *   + `body`: raw body regexp
	 *   + `url`: url regexp
	 * - `header`: for header and rawheader regexp means the name of header
	 * - `pcre_only`: allow merely pcre for this regexp
	 */
	if (cfg != NULL) {
		if (!rspamd_lua_parse_table_arguments (L, 2, &err,
				"*re=U{regexp};*type=S;header=S;pcre_only=B",
				&re, &type_str, &header_str, &pcre_only)) {
			msg_err_config ("cannot get parameters list: %e", err);

			if (err) {
				g_error_free (err);
			}
		}
		else {
			type = rspamd_re_cache_type_from_string (type_str);

			if ((type == RSPAMD_RE_HEADER ||
					type == RSPAMD_RE_RAWHEADER ||
					type == RSPAMD_RE_MIMEHEADER) &&
					header_str == NULL) {
				msg_err_config (
						"header argument is mandatory for header/rawheader regexps");
			}
			else {
				if (pcre_only) {
					old_flags = rspamd_regexp_get_flags (re->re);
					old_flags |= RSPAMD_REGEXP_FLAG_PCRE_ONLY;
					rspamd_regexp_set_flags (re->re, old_flags);
				}

				if (header_str != NULL) {
					/* Include the last \0 */
					header_len = strlen (header_str) + 1;
				}

				cache_re = rspamd_re_cache_add (cfg->re_cache, re->re, type,
						(gpointer) header_str, header_len);

				/*
				 * XXX: here are dragons!
				 * Actually, lua regexp contains internal rspamd_regexp_t
				 * and it owns it.
				 * However, after this operation we have some OTHER regexp,
				 * which we really would like to use.
				 * So we do the following:
				 * 1) Remove old re and unref it
				 * 2) Replace the internal re with cached one
				 * 3) Increase its refcount to share ownership between cache and
				 *   lua object
				 */
				if (cache_re != re->re) {
					rspamd_regexp_unref (re->re);
					re->re = rspamd_regexp_ref (cache_re);
				}
			}
		}
	}

	return 0;
}

static gint
lua_config_replace_regexp (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_lua_regexp *old_re = NULL, *new_re = NULL;
	GError *err = NULL;

	if (cfg != NULL) {
		if (!rspamd_lua_parse_table_arguments (L, 2, &err,
				"*old_re=U{regexp};*new_re=U{regexp}",
				&old_re, &new_re)) {
			msg_err_config ("cannot get parameters list: %e", err);

			if (err) {
				g_error_free (err);
			}
		}
		else {
			rspamd_re_cache_replace (cfg->re_cache, old_re->re, new_re->re);
		}
	}

	return 0;
}

static gint
lua_config_register_worker_script (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *worker_type = luaL_checkstring (L, 2), *wtype;
	struct rspamd_worker_conf *cf;
	GList *cur;
	struct rspamd_worker_lua_script *sc;
	gboolean found = FALSE;

	if (cfg == NULL || worker_type == NULL || lua_type (L, 3) != LUA_TFUNCTION) {
		return luaL_error (L, "invalid arguments");
	}

	for (cur = g_list_first (cfg->workers); cur != NULL; cur = g_list_next (cur)) {
		cf = cur->data;
		wtype = g_quark_to_string (cf->type);

		if (g_ascii_strcasecmp (wtype, worker_type) == 0) {
			sc = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*sc));
			lua_pushvalue (L, 3);
			sc->cbref = luaL_ref (L, LUA_REGISTRYINDEX);
			DL_APPEND (cf->scripts, sc);
			found = TRUE;
		}
	}

	lua_pushboolean (L, found);

	return 1;
}

static gint
lua_config_add_on_load (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_config_cfg_lua_script *sc;

	if (cfg == NULL || lua_type (L, 2) != LUA_TFUNCTION) {
		return luaL_error (L, "invalid arguments");
	}

	sc = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*sc));
	lua_pushvalue (L, 2);
	sc->cbref = luaL_ref (L, LUA_REGISTRYINDEX);
	DL_APPEND (cfg->on_load_scripts, sc);

	return 0;
}

static gint
lua_config_add_post_init (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_config_cfg_lua_script *sc;

	if (cfg == NULL || lua_type (L, 2) != LUA_TFUNCTION) {
		return luaL_error (L, "invalid arguments");
	}

	sc = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*sc));
	lua_pushvalue (L, 2);
	sc->cbref = luaL_ref (L, LUA_REGISTRYINDEX);
	DL_APPEND (cfg->post_init_scripts, sc);

	return 0;
}

static gint
lua_config_add_config_unload (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_config_cfg_lua_script *sc;

	if (cfg == NULL || lua_type (L, 2) != LUA_TFUNCTION) {
		return luaL_error (L, "invalid arguments");
	}

	sc = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*sc));
	lua_pushvalue (L, 2);
	sc->cbref = luaL_ref (L, LUA_REGISTRYINDEX);
	DL_APPEND (cfg->config_unload_scripts, sc);

	return 0;
}


static void lua_periodic_callback_finish (struct thread_entry *thread, int ret);
static void lua_periodic_callback_error (struct thread_entry *thread, int ret, const char *msg);

struct rspamd_lua_periodic {
	struct ev_loop *event_loop;
	struct rspamd_config *cfg;
	lua_State *L;
	gdouble timeout;
	ev_timer ev;
	gint cbref;
	gboolean need_jitter;
};

static void
lua_periodic_callback (struct ev_loop *loop, ev_timer *w, int revents)
{
	struct rspamd_lua_periodic *periodic = (struct rspamd_lua_periodic *)w->data;
	struct rspamd_config **pcfg, *cfg;
	struct ev_loop **pev_base;
	struct thread_entry *thread;
	lua_State *L;

	thread = lua_thread_pool_get_for_config (periodic->cfg);
	thread->cd = periodic;
	thread->finish_callback = lua_periodic_callback_finish;
	thread->error_callback = lua_periodic_callback_error;

	L = thread->lua_state;

	lua_rawgeti (L, LUA_REGISTRYINDEX, periodic->cbref);
	pcfg = lua_newuserdata (L, sizeof (*pcfg));
	rspamd_lua_setclass (L, "rspamd{config}", -1);
	cfg = periodic->cfg;
	*pcfg = cfg;
	pev_base = lua_newuserdata (L, sizeof (*pev_base));
	rspamd_lua_setclass (L, "rspamd{ev_base}", -1);
	*pev_base = periodic->event_loop;

	lua_thread_call (thread, 2);
}

static void
lua_periodic_callback_finish (struct thread_entry *thread, int ret)
{
	lua_State *L;
	struct rspamd_lua_periodic *periodic = thread->cd;
	gboolean plan_more = FALSE;
	gdouble timeout = 0.0;

	L = thread->lua_state;

	ev_now_update (periodic->event_loop);
#ifdef HAVE_EVENT_NO_CACHE_TIME_FUNC
	event_base_update_cache_time (periodic->ev_base);
#endif

	if (ret == 0) {
		if (lua_type (L, -1) == LUA_TBOOLEAN) {
			plan_more = lua_toboolean (L, -1);
			timeout = periodic->timeout;
		}
		else if (lua_type (L, -1) == LUA_TNUMBER) {
			timeout = lua_tonumber (L, -1);
			plan_more = timeout > 0 ? TRUE : FALSE;
		}

		lua_pop (L, 1); /* Return value */
	}
	if (plan_more) {
		if (periodic->need_jitter) {
			timeout = rspamd_time_jitter (timeout, 0.0);
		}

		periodic->ev.repeat = timeout;
		ev_timer_again (periodic->event_loop, &periodic->ev);
	}
	else {
		luaL_unref (L, LUA_REGISTRYINDEX, periodic->cbref);
		ev_timer_stop (periodic->event_loop, &periodic->ev);
		g_free (periodic);
	}
}

static void
lua_periodic_callback_error (struct thread_entry *thread, int ret, const char *msg)
{
	struct rspamd_config *cfg;
	struct rspamd_lua_periodic *periodic = thread->cd;
	cfg = periodic->cfg;

	msg_err_config ("call to finishing script failed: %s", msg);

	lua_periodic_callback_finish (thread, ret);
}


static gint
lua_config_add_periodic (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct ev_loop *ev_base = lua_check_ev_base (L, 2);
	gdouble timeout = lua_tonumber (L, 3);
	struct rspamd_lua_periodic *periodic;
	gboolean need_jitter = FALSE;

	if (cfg == NULL || timeout < 0 || lua_type (L, 4) != LUA_TFUNCTION) {
		return luaL_error (L, "invalid arguments");
	}

	if (lua_type (L, 5) == LUA_TBOOLEAN) {
		need_jitter = lua_toboolean (L, 5);
	}

	periodic = g_malloc0 (sizeof (*periodic));
	periodic->timeout = timeout;
	periodic->L = L;
	periodic->cfg = cfg;
	periodic->event_loop = ev_base;
	periodic->need_jitter = need_jitter;
	lua_pushvalue (L, 4);
	periodic->cbref = luaL_ref (L, LUA_REGISTRYINDEX);

	if (need_jitter) {
		timeout = rspamd_time_jitter (timeout, 0.0);
	}

	ev_timer_init (&periodic->ev, lua_periodic_callback, timeout, 0.0);
	periodic->ev.data = periodic;
	ev_timer_start (ev_base, &periodic->ev);

	return 0;
}

static gint
lua_config_get_symbols_count (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	guint res = 0;

	if (cfg != NULL) {
		res = rspamd_symcache_stats_symbols_count (cfg->cache);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	lua_pushinteger (L, res);

	return 1;
}

static gint
lua_config_get_symbols_cksum (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	guint64 res = 0, *pres;

	if (cfg != NULL) {
		res = rspamd_symcache_get_cksum (cfg->cache);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	pres = lua_newuserdata (L, sizeof (res));
	*pres = res;
	rspamd_lua_setclass (L, "rspamd{int64}", -1);

	return 1;
}

static gint
lua_config_get_symbols_counters (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	ucl_object_t *counters;

	if (cfg != NULL) {
		counters = rspamd_symcache_counters (cfg->cache);
		ucl_object_push_lua (L, counters, true);
		ucl_object_unref (counters);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}
static void
lua_metric_symbol_inserter (gpointer k, gpointer v, gpointer ud)
{
	lua_State *L = (lua_State *) ud;
	const gchar *sym = k;
	struct rspamd_symbol *s = (struct rspamd_symbol *) v;

	lua_pushstring (L, sym);

	lua_createtable (L, 0, 3); /* TODO: add more if needed */
	lua_pushstring (L, "score");
	lua_pushnumber (L, s->score);
	lua_settable (L, -3);
	lua_pushstring (L, "description");
	lua_pushstring (L, s->description);
	lua_settable (L, -3);

	lua_settable (L, -3);
}

static gint
lua_config_get_symbols_scores (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);

	if (cfg != NULL) {
		lua_createtable (L, 0, g_hash_table_size (cfg->symbols));
		g_hash_table_foreach (cfg->symbols,
				lua_metric_symbol_inserter,
				L);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}


static gint
lua_config_get_symbol_callback (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *sym = luaL_checkstring (L, 2);
	struct rspamd_abstract_callback_data *abs_cbdata;
	struct lua_callback_data *cbd;

	if (cfg != NULL && sym != NULL) {
		abs_cbdata = rspamd_symcache_get_cbdata (cfg->cache, sym);

		if (abs_cbdata == NULL || abs_cbdata->magic != rspamd_lua_callback_magic) {
			lua_pushnil (L);
		}
		else {
			cbd = (struct lua_callback_data *)abs_cbdata;

			if (cbd->cb_is_ref) {
				lua_rawgeti (L, LUA_REGISTRYINDEX, cbd->callback.ref);
			}
			else {
				lua_getglobal (L, cbd->callback.name);
			}
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_set_symbol_callback (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *sym = luaL_checkstring (L, 2);
	struct rspamd_abstract_callback_data *abs_cbdata;
	struct lua_callback_data *cbd;

	if (cfg != NULL && sym != NULL && lua_type (L, 3) == LUA_TFUNCTION) {
		abs_cbdata = rspamd_symcache_get_cbdata (cfg->cache, sym);

		if (abs_cbdata == NULL || abs_cbdata->magic != rspamd_lua_callback_magic) {
			lua_pushboolean (L, FALSE);
		}
		else {
			cbd = (struct lua_callback_data *)abs_cbdata;

			if (cbd->cb_is_ref) {
				luaL_unref (L, LUA_REGISTRYINDEX, cbd->callback.ref);
			}
			else {
				cbd->cb_is_ref = TRUE;
			}

			lua_pushvalue (L, 3);
			cbd->callback.ref = luaL_ref (L, LUA_REGISTRYINDEX);
			lua_pushboolean (L, TRUE);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_get_symbol_stat (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *sym = luaL_checkstring (L, 2);
	gdouble freq, stddev, tm;
	guint hits;

	if (cfg != NULL && sym != NULL) {
		if (!rspamd_symcache_stat_symbol (cfg->cache, sym, &freq,
				&stddev, &tm, &hits)) {
			lua_pushnil (L);
		}
		else {
			lua_createtable (L, 0, 4);
			lua_pushstring (L, "frequency");
			lua_pushnumber (L, freq);
			lua_settable (L, -3);
			lua_pushstring (L, "sttdev");
			lua_pushnumber (L, stddev);
			lua_settable (L, -3);
			lua_pushstring (L, "time");
			lua_pushnumber (L, tm);
			lua_settable (L, -3);
			lua_pushstring (L, "hits");
			lua_pushinteger (L, hits);
			lua_settable (L, -3);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_get_symbol_parent (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *sym = luaL_checkstring (L, 2), *parent;

	if (cfg != NULL && sym != NULL) {
		parent = rspamd_symcache_get_parent (cfg->cache, sym);

		if (parent) {
			lua_pushstring (L, parent);
		}
		else {
			lua_pushnil (L);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_get_group_symbols (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *gr_name = luaL_checkstring (L, 2);

	if (cfg != NULL && gr_name != NULL) {
		struct rspamd_symbols_group *group;

		group = g_hash_table_lookup (cfg->groups, gr_name);

		if (group == NULL) {
			lua_pushnil (L);
		}
		else {
			guint i = 1;
			gpointer k, v;
			GHashTableIter it;

			lua_createtable (L, g_hash_table_size (group->symbols), 0);
			g_hash_table_iter_init (&it, group->symbols);

			while (g_hash_table_iter_next (&it, &k, &v)) {
				lua_pushstring (L, k);
				lua_rawseti (L, -2, i);
				i ++;
			}
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_register_finish_script (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_config_cfg_lua_script *sc;

	if (cfg != NULL && lua_type (L, 2) == LUA_TFUNCTION) {
		sc = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*sc));
		lua_pushvalue (L, 2);
		sc->cbref = luaL_ref (L, LUA_REGISTRYINDEX);
		DL_APPEND (cfg->on_term_scripts, sc);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 0;
}

static gint
lua_config_register_settings_id (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *settings_name = luaL_checkstring (L, 2);

	if (cfg != NULL && settings_name) {
		ucl_object_t *sym_enabled, *sym_disabled;

		sym_enabled = ucl_object_lua_import (L, 3);

		if (sym_enabled != NULL && ucl_object_type (sym_enabled) != UCL_OBJECT) {
			ucl_object_unref (sym_enabled);

			return luaL_error (L, "invalid symbols enabled");
		}

		sym_disabled = ucl_object_lua_import (L, 4);

		if (sym_disabled != NULL && ucl_object_type (sym_disabled) != UCL_OBJECT) {
			ucl_object_unref (sym_enabled);
			ucl_object_unref (sym_disabled);

			return luaL_error (L, "invalid symbols enabled");
		}

		rspamd_config_register_settings_id (cfg, settings_name, sym_enabled,
				sym_disabled);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 0;
}

static gint
lua_config_register_monitored (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_monitored *m, **pm;
	const gchar *url, *type;
	ucl_object_t *params = NULL;

	url = lua_tostring (L, 2);
	type = lua_tostring (L, 3);

	if (cfg != NULL && url != NULL && type != NULL) {
		if (g_ascii_strcasecmp (type, "dns") == 0) {
			lua_Debug ar;

			if (lua_type (L, 4) == LUA_TTABLE) {
				params = ucl_object_lua_import (L, 4);
			}

			/* Get lua line and source */
			lua_getstack (L, 1, &ar);
			lua_getinfo (L, "nSl", &ar);

			m = rspamd_monitored_create_ (cfg->monitored_ctx, url,
					RSPAMD_MONITORED_DNS, RSPAMD_MONITORED_DEFAULT,
					params, ar.short_src);

			if (m) {
				pm = lua_newuserdata (L, sizeof (*pm));
				*pm = m;
				rspamd_lua_setclass (L, "rspamd{monitored}", -1);
			}
			else {
				lua_pushnil (L);
			}

			if (params) {
				ucl_object_unref (params);
			}
		}
		else {
			return luaL_error (L, "invalid monitored type: %s", type);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_add_doc (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg;
	const gchar *path = NULL, *option, *doc_string;
	const gchar *type_str = NULL, *default_value = NULL;
	ucl_type_t type = UCL_NULL;
	gboolean required = FALSE;
	GError *err = NULL;

	cfg = lua_check_config (L, 1);

	if (lua_type (L, 2 ) == LUA_TSTRING) {
		path = luaL_checkstring (L, 2);
	}

	option = luaL_checkstring (L, 3);
	doc_string = luaL_checkstring (L, 4);

	if (cfg && option && doc_string) {
		if (lua_type (L, 5) == LUA_TTABLE) {
			if (!rspamd_lua_parse_table_arguments (L, 5, &err,
					"type=S;default=S;required=B",
					&type_str, &default_value, &required)) {
				msg_err_config ("cannot get parameters list: %e", err);

				if (err) {
					g_error_free (err);
				}

				if (type_str) {
					if (!ucl_object_string_to_type (type_str, &type)) {
						msg_err_config ("invalid type: %s", type_str);
					}
				}
			}
		}

		rspamd_rcl_add_doc_by_path (cfg, path, doc_string, option,
				type, NULL, 0, default_value, required);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 0;
}

static gint
lua_config_add_example (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg;
	const gchar *path = NULL, *option, *doc_string, *example;
	gsize example_len;

	cfg = lua_check_config (L, 1);

	if (lua_type (L, 2 ) == LUA_TSTRING) {
		path = luaL_checkstring (L, 2);
	}

	option = luaL_checkstring (L, 3);
	doc_string = luaL_checkstring (L, 4);
	example = luaL_checklstring (L, 5, &example_len);

	if (cfg && option && doc_string && example) {

		rspamd_rcl_add_doc_by_example (cfg, path, doc_string, option,
				example, example_len);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 0;
}

static gint
lua_config_get_cpu_flags (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_cryptobox_library_ctx *crypto_ctx;

	if (cfg != NULL) {
		crypto_ctx = cfg->libs_ctx->crypto_ctx;
		lua_newtable (L);

		if (crypto_ctx->cpu_config & CPUID_SSSE3) {
			lua_pushstring (L, "ssse3");
			lua_pushboolean (L, true);
			lua_settable (L, -3);
		}
		if (crypto_ctx->cpu_config & CPUID_SSE41) {
			lua_pushstring (L, "sse41");
			lua_pushboolean (L, true);
			lua_settable (L, -3);
		}
		if (crypto_ctx->cpu_config & CPUID_SSE42) {
			lua_pushstring (L, "sse42");
			lua_pushboolean (L, true);
			lua_settable (L, -3);
		}
		if (crypto_ctx->cpu_config & CPUID_SSE2) {
			lua_pushstring (L, "sse2");
			lua_pushboolean (L, true);
			lua_settable (L, -3);
		}
		if (crypto_ctx->cpu_config & CPUID_SSE3) {
			lua_pushstring (L, "sse3");
			lua_pushboolean (L, true);
			lua_settable (L, -3);
		}
		if (crypto_ctx->cpu_config & CPUID_AVX) {
			lua_pushstring (L, "avx");
			lua_pushboolean (L, true);
			lua_settable (L, -3);
		}
		if (crypto_ctx->cpu_config & CPUID_AVX2) {
			lua_pushstring (L, "avx2");
			lua_pushboolean (L, true);
			lua_settable (L, -3);
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_has_torch (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	struct rspamd_cryptobox_library_ctx *crypto_ctx;

	if (cfg != NULL) {
		crypto_ctx = cfg->libs_ctx->crypto_ctx;
#if !defined(WITH_TORCH) || !defined(WITH_LUAJIT)
		lua_pushboolean (L, false);
		(void)crypto_ctx;
#else
		if (crypto_ctx->cpu_config & CPUID_SSE2) {
			lua_pushboolean (L, true);
		}
		else {
			lua_pushboolean (L, false);
		}
#endif
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_experimental_enabled (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);

	if (cfg != NULL) {
		lua_pushboolean (L, cfg->enable_experimental);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

struct rspamd_lua_include_trace_cbdata {
	lua_State *L;
	gint cbref;
};

static void
lua_include_trace_cb (struct ucl_parser *parser,
					  const ucl_object_t *parent,
					  const ucl_object_t *args,
					  const char *path,
					  size_t pathlen,
					  void *user_data)
{
	struct rspamd_lua_include_trace_cbdata *cbdata =
			(struct rspamd_lua_include_trace_cbdata *)user_data;
	gint err_idx;
	lua_State *L;

	L = cbdata->L;
	lua_pushcfunction (L, &rspamd_lua_traceback);
	err_idx = lua_gettop (L);

	lua_rawgeti (L, LUA_REGISTRYINDEX, cbdata->cbref);
	/* Current filename */
	lua_pushstring (L, ucl_parser_get_cur_file (parser));
	/* Included filename */
	lua_pushlstring (L, path, pathlen);
	/* Params */
	if (args) {
		ucl_object_push_lua (L, args, true);
	}
	else {
		lua_newtable (L);
	}
	/* Parent */
	if (parent) {
		lua_pushstring (L, ucl_object_key (parent));
	}
	else {
		lua_pushnil (L);
	}

	if (lua_pcall (L, 4, 0, err_idx) != 0) {
		msg_err ("lua call to local include trace failed: %s", lua_tostring (L, -1));
	}

	lua_settop (L, err_idx - 1);
}

#define LUA_TABLE_TO_HASH(htb, idx) do { \
	lua_pushstring (L, (idx)); \
	lua_gettable (L, -2); \
	if (lua_isstring (L, -1)) { \
		g_hash_table_insert ((htb), (idx), g_strdup (lua_tostring (L, -1))); \
	} \
	lua_pop (L, 1); \
} while(0)

static gint
lua_config_load_ucl (lua_State *L)
{
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *filename;
	GHashTable *paths = g_hash_table_new_full (rspamd_str_hash, rspamd_str_equal,
			NULL, g_free);
	GError *err = NULL;

	if (cfg) {
		if (lua_isstring (L, 2)) {
			filename = lua_tostring (L, 2);
		}
		else {
			filename = RSPAMD_CONFDIR "/rspamd.conf";
		}

		/* Convert rspamd_paths */
		lua_getglobal (L, "rspamd_paths");

		if (lua_istable (L, -1)) {
			LUA_TABLE_TO_HASH(paths, RSPAMD_CONFDIR_INDEX);
			LUA_TABLE_TO_HASH(paths, RSPAMD_LOCAL_CONFDIR_INDEX);
			LUA_TABLE_TO_HASH(paths, RSPAMD_RUNDIR_INDEX);
			LUA_TABLE_TO_HASH(paths, RSPAMD_DBDIR_INDEX);
			LUA_TABLE_TO_HASH(paths, RSPAMD_LOGDIR_INDEX);
			LUA_TABLE_TO_HASH(paths, RSPAMD_WWWDIR_INDEX);
			LUA_TABLE_TO_HASH(paths, RSPAMD_PLUGINSDIR_INDEX);
			LUA_TABLE_TO_HASH(paths, RSPAMD_RULESDIR_INDEX);
			LUA_TABLE_TO_HASH(paths, RSPAMD_LUALIBDIR_INDEX);
			LUA_TABLE_TO_HASH(paths, RSPAMD_PREFIX_INDEX);
		}

		lua_pop (L, 1);

		if (lua_isfunction (L, 3)) {
			struct rspamd_lua_include_trace_cbdata cbd;

			lua_pushvalue (L, 3);
			cbd.cbref = luaL_ref (L, LUA_REGISTRYINDEX);
			cbd.L = L;

			if (!rspamd_config_parse_ucl (cfg, filename, paths,
					lua_include_trace_cb, &cbd, lua_toboolean (L, 4), &err)) {
				luaL_unref (L, LUA_REGISTRYINDEX, cbd.cbref);
				lua_pushboolean (L, false);
				lua_pushfstring (L, "failed to load config: %s", err->message);
				g_error_free (err);
				g_hash_table_unref (paths);

				return 2;
			}

			luaL_unref (L, LUA_REGISTRYINDEX, cbd.cbref);
		}
		else {
			if (!rspamd_config_parse_ucl (cfg, filename, paths, NULL, NULL,
					lua_toboolean (L, 3), &err)) {
				lua_pushboolean (L, false);
				lua_pushfstring (L, "failed to load config: %s", err->message);
				g_error_free (err);
				g_hash_table_unref (paths);

				return 2;
			}
		}

		rspamd_rcl_maybe_apply_lua_transform (cfg);
		rspamd_config_calculate_cksum (cfg);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	g_hash_table_unref (paths);
	lua_pushboolean (L, true);

	return 1;
}

#undef IDX_TO_HASH

static gint
lua_config_parse_rcl (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	GHashTable *excluded = g_hash_table_new_full (rspamd_str_hash, rspamd_str_equal,
			g_free, NULL);
	GError *err = NULL;
	struct rspamd_rcl_section *top;

	if (cfg) {
		if (lua_istable (L, 2)) {
			lua_pushvalue (L, 2);

			for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
				g_hash_table_insert (excluded, g_strdup (lua_tostring (L, -1)),
						GINT_TO_POINTER (-1));
			}

			lua_pop (L, 1);
		}

		top = rspamd_rcl_config_init (cfg, excluded);

		if (!rspamd_rcl_parse (top, cfg, cfg, cfg->cfg_pool, cfg->rcl_obj, &err)) {
			lua_pushboolean (L, false);
			lua_pushfstring (L, "failed to load config: %s", err->message);
			g_error_free (err);
			g_hash_table_unref (excluded);
			rspamd_rcl_section_free (top);

			return 2;
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	g_hash_table_unref (excluded);
	rspamd_rcl_section_free (top);
	lua_pushboolean (L, true);

	return 1;
}

static gint
lua_config_init_modules (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);

	if (cfg != NULL) {
		rspamd_lua_post_load_config (cfg);
		lua_pushboolean (L, rspamd_init_filters (cfg, FALSE));
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_config_init_subsystem (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *subsystem = luaL_checkstring (L, 2);
	gchar **parts;
	guint nparts, i;

	if (cfg != NULL && subsystem != NULL) {
		parts = g_strsplit_set (subsystem, ";,", -1);
		nparts = g_strv_length (parts);

		for (i = 0; i < nparts; i ++) {
			if (strcmp (parts[i], "filters") == 0) {
				rspamd_lua_post_load_config (cfg);
				rspamd_init_filters (cfg, FALSE);
			}
			else if (strcmp (parts[i], "langdet") == 0) {
				cfg->lang_det = rspamd_language_detector_init (cfg);
			}
			else if (strcmp (parts[i], "stat") == 0) {
				rspamd_stat_init (cfg, NULL);
			}
			else if (strcmp (parts[i], "dns") == 0) {
				struct ev_loop *ev_base = lua_check_ev_base (L, 3);

				if (ev_base) {
					cfg->dns_resolver = rspamd_dns_resolver_init (rspamd_logger_get_singleton (),
							ev_base,
							cfg);
				}
				else {
					g_strfreev (parts);

					return luaL_error (L, "no event base specified");
				}
			}
			else {
				g_strfreev (parts);

				return luaL_error (L, "invalid param: %s", parts[i]);
			}
		}

		g_strfreev (parts);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 0;
}

static gint
lua_config_register_re_selector (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);
	const gchar *name = luaL_checkstring (L, 2);
	const gchar *selector_str = luaL_checkstring (L, 3);
	const gchar *delimiter = "";
	gint top = lua_gettop (L);
	bool res = false;

	if (cfg && name && selector_str) {
		if (lua_gettop (L) >= 4) {
			delimiter = luaL_checkstring (L, 4);
		}

		if (luaL_dostring (L, "return require \"lua_selectors\"") != 0) {
			msg_warn_config ("cannot require lua_selectors: %s",
					lua_tostring (L, -1));
		}
		else {
			if (lua_type (L, -1) != LUA_TTABLE) {
				msg_warn_config ("lua selectors must return "
								 "table and not %s",
						lua_typename (L, lua_type (L, -1)));
			}
			else {
				lua_pushstring (L, "create_selector_closure");
				lua_gettable (L, -2);

				if (lua_type (L, -1) != LUA_TFUNCTION) {
					msg_warn_config ("create_selector_closure must return "
									 "function and not %s",
							lua_typename (L, lua_type (L, -1)));
				}
				else {
					gint err_idx, ret;
					struct rspamd_config **pcfg;

					lua_pushcfunction (L, &rspamd_lua_traceback);
					err_idx = lua_gettop (L);

					/* Push function */
					lua_pushvalue (L, -2);

					pcfg = lua_newuserdata (L, sizeof (*pcfg));
					rspamd_lua_setclass (L, "rspamd{config}", -1);
					*pcfg = cfg;
					lua_pushstring (L, selector_str);
					lua_pushstring (L, delimiter);

					if ((ret = lua_pcall (L, 3, 1, err_idx)) != 0) {
						msg_err_config ("call to create_selector_closure lua "
										"script failed (%d): %s", ret,
										lua_tostring (L, -1));
					}
					else {
						if (lua_type (L, -1) != LUA_TFUNCTION) {
							msg_warn_config ("create_selector_closure "
											 "invocation must return "
											 "function and not %s",
									lua_typename (L, lua_type (L, -1)));
						}
						else {
							ret = luaL_ref (L, LUA_REGISTRYINDEX);
							rspamd_re_cache_add_selector (cfg->re_cache,
									name, ret);
							res = true;
						}
					}
				}
			}
		}
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	lua_settop (L, top);
	lua_pushboolean (L, res);

	if (res) {
		msg_info_config ("registered regexp selector %s", name);
	}

	return 1;
}

static gint
lua_config_get_tld_path (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_config *cfg = lua_check_config (L, 1);

	if (cfg != NULL) {
		lua_pushstring (L, cfg->tld_file);
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_monitored_alive (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_monitored *m = lua_check_monitored (L, 1);

	if (m) {
		lua_pushboolean (L, rspamd_monitored_alive (m));
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_monitored_offline (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_monitored *m = lua_check_monitored (L, 1);

	if (m) {
		lua_pushnumber (L, rspamd_monitored_offline_time (m));
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_monitored_total_offline (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_monitored *m = lua_check_monitored (L, 1);

	if (m) {
		lua_pushnumber (L, rspamd_monitored_total_offline_time (m));
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

static gint
lua_monitored_latency (lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_monitored *m = lua_check_monitored (L, 1);

	if (m) {
		lua_pushnumber (L, rspamd_monitored_latency (m));
	}
	else {
		return luaL_error (L, "invalid arguments");
	}

	return 1;
}

void
luaopen_config (lua_State * L)
{
	rspamd_lua_new_class (L, "rspamd{config}", configlib_m);

	lua_pop (L, 1);

	rspamd_lua_new_class (L, "rspamd{monitored}", monitoredlib_m);

	lua_pop (L, 1);
}

void
lua_call_finish_script (struct rspamd_config_cfg_lua_script *sc,
		struct rspamd_task *task) {

	struct rspamd_task **ptask;
	struct thread_entry *thread;

	thread = lua_thread_pool_get_for_task (task);
	thread->task = task;

	lua_State *L = thread->lua_state;

	lua_rawgeti (L, LUA_REGISTRYINDEX, sc->cbref);

	ptask = lua_newuserdata (L, sizeof (struct rspamd_task *));
	rspamd_lua_setclass (L, "rspamd{task}", - 1);
	*ptask = task;

	lua_thread_call (thread, 1);
}