summaryrefslogtreecommitdiffstats
path: root/src/libserver/cfg_rcl.c
blob: 08c7c7868cee217712c7ee7cf11c38f9b431c538 (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
/*-
 * 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 "cfg_rcl.h"
#include "rspamd.h"
#include "../../contrib/mumhash/mum.h"
#define HASH_CASELESS
#include "uthash_strcase.h"
#include "utlist.h"
#include "cfg_file.h"
#include "lua/lua_common.h"
#include "expression.h"
#include "composites.h"
#include "libserver/worker_util.h"
#include "unix-std.h"
#include "cryptobox.h"
#include "libutil/multipattern.h"
#include "libmime/email_addr.h"
#include "libmime/lang_detection.h"

#ifdef HAVE_SYSLOG_H
#include <syslog.h>
#endif

#ifdef HAVE_GLOB_H
#include <glob.h>
#endif

#include <math.h>

struct rspamd_rcl_default_handler_data {
	struct rspamd_rcl_struct_parser pd;
	gchar *key;
	rspamd_rcl_default_handler_t handler;
	UT_hash_handle hh;
};

struct rspamd_rcl_section {
	const gchar *name;                  /**< name of section */
	const gchar *key_attr;
	const gchar *default_key;
	rspamd_rcl_handler_t handler;       /**< handler of section attributes */
	enum ucl_type type;         /**< type of attribute */
	gboolean required;                  /**< whether this param is required */
	gboolean strict_type;               /**< whether we need strict type */
	UT_hash_handle hh;                  /** hash handle */
	struct rspamd_rcl_section *subsections; /**< hash table of subsections */
	struct rspamd_rcl_default_handler_data *default_parser; /**< generic parsing fields */
	rspamd_rcl_section_fin_t fin; /** called at the end of section parsing */
	gpointer fin_ud;
	ucl_object_t *doc_ref;       /**< reference to the section's documentation */
};

struct rspamd_worker_param_key {
	const gchar *name;
	gpointer ptr;
};

struct rspamd_worker_param_parser {
	rspamd_rcl_default_handler_t handler;           /**< handler function									*/
	struct rspamd_rcl_struct_parser parser;         /**< parser attributes									*/

	struct rspamd_worker_param_key key;
};

struct rspamd_worker_cfg_parser {
	GHashTable *parsers;                            /**< parsers hash										*/
	gint type;                                      /**< workers quark										*/
	gboolean (*def_obj_parser)(ucl_object_t *obj, gpointer ud);   /**<
 														 default object parser								*/
	gpointer def_ud;
};

static gboolean rspamd_rcl_process_section (struct rspamd_config *cfg,
		struct rspamd_rcl_section *sec,
		gpointer ptr, const ucl_object_t *obj, rspamd_mempool_t *pool,
		GError **err);

/*
 * Common section handlers
 */
static gboolean
rspamd_rcl_logging_handler (rspamd_mempool_t *pool, const ucl_object_t *obj,
	const gchar *key, gpointer ud, struct rspamd_rcl_section *section,
	GError **err)
{
	const ucl_object_t *val;
	const gchar *facility = NULL, *log_type = NULL, *log_level = NULL;
	struct rspamd_config *cfg = ud;

	val = ucl_object_lookup (obj, "type");
	if (val != NULL && ucl_object_tostring_safe (val, &log_type)) {
		if (g_ascii_strcasecmp (log_type, "file") == 0) {
			/* Need to get filename */
			val = ucl_object_lookup (obj, "filename");
			if (val == NULL || val->type != UCL_STRING) {
				g_set_error (err,
					CFG_RCL_ERROR,
					ENOENT,
					"filename attribute must be specified for file logging type");
				return FALSE;
			}
			cfg->log_type = RSPAMD_LOG_FILE;
			cfg->log_file = rspamd_mempool_strdup (cfg->cfg_pool,
					ucl_object_tostring (val));
		}
		else if (g_ascii_strcasecmp (log_type, "syslog") == 0) {
			/* Need to get facility */
#ifdef HAVE_SYSLOG_H
			cfg->log_facility = LOG_DAEMON;
			cfg->log_type = RSPAMD_LOG_SYSLOG;
			val = ucl_object_lookup (obj, "facility");
			if (val != NULL && ucl_object_tostring_safe (val, &facility)) {
				if (g_ascii_strcasecmp (facility, "LOG_AUTH") == 0 ||
					g_ascii_strcasecmp (facility, "auth") == 0 ) {
					cfg->log_facility = LOG_AUTH;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_CRON") == 0 ||
					g_ascii_strcasecmp (facility, "cron") == 0 ) {
					cfg->log_facility = LOG_CRON;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_DAEMON") == 0 ||
					g_ascii_strcasecmp (facility, "daemon") == 0 ) {
					cfg->log_facility = LOG_DAEMON;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_MAIL") == 0 ||
					g_ascii_strcasecmp (facility, "mail") == 0) {
					cfg->log_facility = LOG_MAIL;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_USER") == 0 ||
					g_ascii_strcasecmp (facility, "user") == 0 ) {
					cfg->log_facility = LOG_USER;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_LOCAL0") == 0 ||
					g_ascii_strcasecmp (facility, "local0") == 0) {
					cfg->log_facility = LOG_LOCAL0;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_LOCAL1") == 0 ||
					g_ascii_strcasecmp (facility, "local1") == 0) {
					cfg->log_facility = LOG_LOCAL1;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_LOCAL2") == 0 ||
					g_ascii_strcasecmp (facility, "local2") == 0) {
					cfg->log_facility = LOG_LOCAL2;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_LOCAL3") == 0 ||
					g_ascii_strcasecmp (facility, "local3") == 0) {
					cfg->log_facility = LOG_LOCAL3;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_LOCAL4") == 0 ||
					g_ascii_strcasecmp (facility, "local4") == 0) {
					cfg->log_facility = LOG_LOCAL4;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_LOCAL5") == 0 ||
					g_ascii_strcasecmp (facility, "local5") == 0) {
					cfg->log_facility = LOG_LOCAL5;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_LOCAL6") == 0 ||
					g_ascii_strcasecmp (facility, "local6") == 0) {
					cfg->log_facility = LOG_LOCAL6;
				}
				else if (g_ascii_strcasecmp (facility, "LOG_LOCAL7") == 0 ||
					g_ascii_strcasecmp (facility, "local7") == 0) {
					cfg->log_facility = LOG_LOCAL7;
				}
				else {
					g_set_error (err,
						CFG_RCL_ERROR,
						EINVAL,
						"invalid log facility: %s",
						facility);
					return FALSE;
				}
			}
#endif
		}
		else if (g_ascii_strcasecmp (log_type,
			"stderr") == 0 || g_ascii_strcasecmp (log_type, "console") == 0) {
			cfg->log_type = RSPAMD_LOG_CONSOLE;
		}
		else {
			g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"invalid log type: %s",
				log_type);
			return FALSE;
		}
	}
	else {
		/* No type specified */
		msg_warn_config (
			"logging type is not specified correctly, log output to the console");
	}

	/* Handle log level */
	val = ucl_object_lookup (obj, "level");
	if (val != NULL && ucl_object_tostring_safe (val, &log_level)) {
		if (g_ascii_strcasecmp (log_level, "error") == 0) {
			cfg->log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
		}
		else if (g_ascii_strcasecmp (log_level, "warning") == 0) {
			cfg->log_level = G_LOG_LEVEL_WARNING;
		}
		else if (g_ascii_strcasecmp (log_level, "info") == 0) {
			cfg->log_level = G_LOG_LEVEL_INFO | G_LOG_LEVEL_MESSAGE;
		}
		else if (g_ascii_strcasecmp (log_level, "debug") == 0) {
			cfg->log_level = G_LOG_LEVEL_DEBUG;
		}
		else {
			g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"invalid log level: %s",
				log_level);
			return FALSE;
		}
	}

	/* Handle flags */
	val = ucl_object_lookup_any (obj, "color", "log_color", NULL);
	if (val && ucl_object_toboolean (val)) {
		cfg->log_flags |= RSPAMD_LOG_FLAG_COLOR;
	}

	val = ucl_object_lookup_any (obj, "systemd", "log_systemd", NULL);
	if (val && ucl_object_toboolean (val)) {
		cfg->log_flags |= RSPAMD_LOG_FLAG_SYSTEMD;
	}

	val = ucl_object_lookup (obj, "log_re_cache");
	if (val && ucl_object_toboolean (val)) {
		cfg->log_flags |= RSPAMD_LOG_FLAG_RE_CACHE;
	}

	val = ucl_object_lookup_any (obj, "usec", "log_usec", NULL);
	if (val && ucl_object_toboolean (val)) {
		cfg->log_flags |= RSPAMD_LOG_FLAG_USEC;
	}

	return rspamd_rcl_section_parse_defaults (cfg, section, cfg->cfg_pool, obj,
			cfg, err);
}

static gboolean
rspamd_rcl_options_handler (rspamd_mempool_t *pool, const ucl_object_t *obj,
	const gchar *key, gpointer ud,
	struct rspamd_rcl_section *section, GError **err)
{
	const ucl_object_t *dns, *upstream, *neighbours;
	struct rspamd_config *cfg = ud;
	struct rspamd_rcl_section *dns_section, *upstream_section, *neighbours_section;

	HASH_FIND_STR (section->subsections, "dns", dns_section);

	dns = ucl_object_lookup (obj, "dns");
	if (dns_section != NULL && dns != NULL) {
		if (!rspamd_rcl_section_parse_defaults (cfg,
				dns_section, cfg->cfg_pool, dns,
				cfg, err)) {
			return FALSE;
		}
	}

	HASH_FIND_STR (section->subsections, "upstream", upstream_section);

	upstream = ucl_object_lookup (obj, "upstream");
	if (upstream_section != NULL && upstream != NULL) {
		if (!rspamd_rcl_section_parse_defaults (cfg,
				upstream_section, cfg->cfg_pool,
				upstream, cfg, err)) {
			return FALSE;
		}
	}

	HASH_FIND_STR (section->subsections, "neighbours", neighbours_section);

	neighbours = ucl_object_lookup (obj, "neighbours");
	if (neighbours_section != NULL && neighbours != NULL) {
		const ucl_object_t *cur;

		LL_FOREACH (neighbours, cur) {
			if (!rspamd_rcl_process_section (cfg, neighbours_section, cfg, cur,
					pool, err)) {
				return FALSE;
			}
		}
	}

	if (rspamd_rcl_section_parse_defaults (cfg,
			section, cfg->cfg_pool, obj,
			cfg, err)) {
		/* We need to init this early */
		rspamd_multipattern_library_init (cfg->hs_cache_dir);

		return TRUE;
	}

	return FALSE;
}

struct rspamd_rcl_symbol_data {
	struct rspamd_symbols_group *gr;
	struct rspamd_config *cfg;
};

static gboolean
rspamd_rcl_group_handler (rspamd_mempool_t *pool, const ucl_object_t *obj,
		const gchar *key, gpointer ud,
		struct rspamd_rcl_section *section, GError **err)
{
	struct rspamd_config *cfg = ud;
	struct rspamd_symbols_group *gr;
	const ucl_object_t *val;
	struct rspamd_rcl_section *subsection;
	struct rspamd_rcl_symbol_data sd;

	g_assert (key != NULL);

	gr = g_hash_table_lookup (cfg->groups, key);

	if (gr == NULL) {
		gr = rspamd_config_new_group (cfg, key);
	}

	if (!rspamd_rcl_section_parse_defaults (cfg, section, pool, obj,
			gr, err)) {
		return FALSE;
	}

	sd.gr = gr;
	sd.cfg = cfg;

	/* Handle symbols */
	val = ucl_object_lookup (obj, "symbols");
	if (val != NULL && ucl_object_type (val) == UCL_OBJECT) {
		HASH_FIND_STR (section->subsections, "symbols", subsection);
		g_assert (subsection != NULL);
		if (!rspamd_rcl_process_section (cfg, subsection, &sd, val,
				pool, err)) {

			return FALSE;
		}
	}

	return TRUE;
}

static gboolean
rspamd_rcl_symbol_handler (rspamd_mempool_t *pool, const ucl_object_t *obj,
		const gchar *key, gpointer ud,
		struct rspamd_rcl_section *section, GError **err)
{
	struct rspamd_rcl_symbol_data *sd = ud;
	struct rspamd_config *cfg;
	const ucl_object_t *elt;
	const gchar *description = NULL;
	gdouble score = 0.0;
	guint priority = 1, flags = 0;
	gint nshots;

	g_assert (key != NULL);
	cfg = sd->cfg;
	nshots = cfg->default_max_shots;

	if ((elt = ucl_object_lookup (obj, "one_shot")) != NULL) {
		if (ucl_object_toboolean (elt)) {
			nshots = 1;
		}
	}

	if ((elt = ucl_object_lookup (obj, "any_shot")) != NULL) {
		if (ucl_object_toboolean (elt)) {
			nshots = -1;
		}
	}

	if ((elt = ucl_object_lookup (obj, "one_param")) != NULL) {
		if (ucl_object_toboolean (elt)) {
			flags |= RSPAMD_SYMBOL_FLAG_ONEPARAM;
		}
	}

	if ((elt = ucl_object_lookup (obj, "ignore")) != NULL) {
		if (ucl_object_toboolean (elt)) {
			flags |= RSPAMD_SYMBOL_FLAG_IGNORE;
		}
	}

	if ((elt = ucl_object_lookup (obj, "nshots")) != NULL) {
		nshots = ucl_object_toint (elt);
	}

	elt = ucl_object_lookup_any (obj, "score", "weight", NULL);
	if (elt) {
		score = ucl_object_todouble (elt);
	}

	elt = ucl_object_lookup (obj, "priority");
	if (elt) {
		priority = ucl_object_toint (elt);
	}
	else {
		priority = ucl_object_get_priority (obj) + 1;
	}

	elt = ucl_object_lookup (obj, "description");
	if (elt) {
		description = ucl_object_tostring (elt);
	}

	if (sd->gr) {
		rspamd_config_add_symbol (cfg, key, score,
				description, sd->gr->name, flags, priority, nshots);
	}
	else {
		rspamd_config_add_symbol (cfg, key, score,
				description, NULL, flags, priority, nshots);
	}

	return TRUE;
}

static gboolean
rspamd_rcl_actions_handler (rspamd_mempool_t *pool, const ucl_object_t *obj,
		const gchar *key, gpointer ud,
		struct rspamd_rcl_section *section, GError **err)
{
	gdouble action_score;
	struct rspamd_config *cfg = ud;
	gint action_value;
	const ucl_object_t *cur;
	ucl_object_iter_t it;

	it = ucl_object_iterate_new (obj);

	while ((cur = ucl_object_iterate_safe (it, true)) != NULL) {
		if (!rspamd_action_from_str (ucl_object_key (cur), &action_value)) {
			continue;
		}
		else {
			if (ucl_object_type (cur) == UCL_NULL) {
				action_score = NAN;
			}
			else {
				if (!ucl_object_todouble_safe (cur, &action_score)) {
					g_set_error (err,
							CFG_RCL_ERROR,
							EINVAL,
							"invalid action definition: '%s'",
							ucl_object_key (cur));
					ucl_object_iterate_free (it);

					return FALSE;
				}
			}

			rspamd_config_set_action_score (cfg,
					ucl_object_key (cur),
					action_score,
					ucl_object_get_priority (cur));
		}
	}

	ucl_object_iterate_free (it);

	return rspamd_rcl_section_parse_defaults (cfg, section, pool, obj, cfg, err);
}

static gboolean
rspamd_rcl_worker_handler (rspamd_mempool_t *pool, const ucl_object_t *obj,
		const gchar *key, gpointer ud,
		struct rspamd_rcl_section *section, GError **err)
{
	const ucl_object_t *val, *cur, *cur_obj;
	ucl_object_t *robj;
	ucl_object_iter_t it = NULL;
	const gchar *worker_type, *worker_bind;
	struct rspamd_config *cfg = ud;
	GQuark qtype;
	struct rspamd_worker_conf *wrk;
	struct rspamd_worker_cfg_parser *wparser;
	struct rspamd_worker_param_parser *whandler;
	struct rspamd_worker_param_key srch;

	g_assert (key != NULL);
	worker_type = key;

	qtype = g_quark_try_string (worker_type);
	if (qtype != 0) {
		wrk = rspamd_config_new_worker (cfg, NULL);
		wrk->options = ucl_object_copy (obj);
		wrk->worker = rspamd_get_worker_by_type (cfg, qtype);

		if (wrk->worker == NULL) {
			g_set_error (err,
					CFG_RCL_ERROR,
					EINVAL,
					"unknown worker type: %s",
					worker_type);
			return FALSE;
		}

		wrk->type = qtype;

		if (wrk->worker->worker_init_func) {
			wrk->ctx = wrk->worker->worker_init_func (cfg);
		}
	}
	else {
		msg_err_config ("unknown worker type: %s", worker_type);
		return TRUE;
	}

	val = ucl_object_lookup_any (obj, "bind_socket", "listen", "bind", NULL);
	/* This name is more logical */
	if (val != NULL) {
		it = ucl_object_iterate_new (val);

		while ((cur = ucl_object_iterate_safe (it, true)) != NULL) {
			if (!ucl_object_tostring_safe (cur, &worker_bind)) {
				continue;
			}
			if (!rspamd_parse_bind_line (cfg, wrk, worker_bind)) {
				g_set_error (err,
					CFG_RCL_ERROR,
					EINVAL,
					"cannot parse bind line: %s",
					worker_bind);
				ucl_object_iterate_free (it);
				return FALSE;
			}
		}

		ucl_object_iterate_free (it);
	}

	if (!rspamd_rcl_section_parse_defaults (cfg, section, cfg->cfg_pool, obj,
			wrk, err)) {
		return FALSE;
	}

	/* Parse other attributes */
	wparser = g_hash_table_lookup (cfg->wrk_parsers, &qtype);

	if (wparser != NULL && obj->type == UCL_OBJECT) {
		it = ucl_object_iterate_new (obj);

		while ((cur = ucl_object_iterate_full (it, UCL_ITERATE_EXPLICIT)) != NULL) {
			srch.name = ucl_object_key (cur);
			srch.ptr = wrk->ctx; /* XXX: is it valid? */
			whandler = g_hash_table_lookup (wparser->parsers, &srch);

			if (whandler != NULL) {

				LL_FOREACH (cur, cur_obj) {
					if (!whandler->handler (cfg->cfg_pool,
							cur_obj,
							&whandler->parser,
							section,
							err)) {

						ucl_object_iterate_free (it);
						return FALSE;
					}

					if (!(whandler->parser.flags & RSPAMD_CL_FLAG_MULTIPLE)) {
						break;
					}
				}
			}
		}

		ucl_object_iterate_free (it);

		if (wparser->def_obj_parser != NULL) {
			robj = ucl_object_ref (obj);

			if (!wparser->def_obj_parser (robj, wparser->def_ud)) {
				ucl_object_unref (robj);

				return FALSE;
			}

			ucl_object_unref (robj);
		}
	}

	cfg->workers = g_list_prepend (cfg->workers, wrk);

	return TRUE;
}

#define RSPAMD_CONFDIR_INDEX "CONFDIR"
#define RSPAMD_RUNDIR_INDEX "RUNDIR"
#define RSPAMD_DBDIR_INDEX "DBDIR"
#define RSPAMD_LOGDIR_INDEX "LOGDIR"
#define RSPAMD_PLUGINSDIR_INDEX "PLUGINSDIR"
#define RSPAMD_RULESDIR_INDEX "RULESDIR"
#define RSPAMD_LUALIBDIR_INDEX "LUALIBDIR"
#define RSPAMD_WWWDIR_INDEX "WWWDIR"
#define RSPAMD_PREFIX_INDEX "PREFIX"
#define RSPAMD_VERSION_INDEX "VERSION"

static gint
rspamd_rcl_cmp_components (const gchar *comp1, const gchar *comp2)
{
	guint v1, v2;

	v1 = strtoul (comp1, NULL, 10);
	v2 = strtoul (comp2, NULL, 10);

	return v1 - v2;
}

static int
rspamd_rcl_lua_version_cmp (lua_State *L)
{
	const gchar *ver;
	gchar **components;
	gint ret = 0;

	if (lua_type (L, 2) == LUA_TSTRING) {
		ver = lua_tostring (L, 2);

		components = g_strsplit_set (ver, ".-_", -1);

		if (!components) {
			return luaL_error (L, "invalid arguments to 'cmp': %s", ver);
		}

		if (components[0]) {
			ret = rspamd_rcl_cmp_components (components[0], RSPAMD_VERSION_MAJOR);
		}

		if (ret) {
			goto set;
		}

		if (components[1]) {
			ret = rspamd_rcl_cmp_components (components[1], RSPAMD_VERSION_MINOR);
		}

		if (ret) {
			goto set;
		}

		if (components[2]) {
			ret = rspamd_rcl_cmp_components (components[2], RSPAMD_VERSION_PATCH);
		}

		/*
		 * XXX: we don't compare git releases assuming that it is meaningless
		 */
	}
	else {
		return luaL_error (L, "invalid arguments to 'cmp'");
	}

set:
	g_strfreev (components);
	lua_pushnumber (L, ret);

	return 1;
}

static int
rspamd_rcl_lua_version_numeric (lua_State *L)
{
	static gint64 version_num = RSPAMD_VERSION_NUM;
	const gchar *type;

	if (lua_gettop (L) >= 2 && lua_type (L, 1) == LUA_TSTRING) {
		type = lua_tostring (L, 1);
		if (g_ascii_strcasecmp (type, "short") == 0) {
			version_num = RSPAMD_VERSION_MAJOR_NUM * 1000 +
					RSPAMD_VERSION_MINOR_NUM * 100 + RSPAMD_VERSION_PATCH_NUM * 10;
		}
		else if (g_ascii_strcasecmp (type, "main") == 0) {
			version_num = RSPAMD_VERSION_MAJOR_NUM * 1000 +
						RSPAMD_VERSION_MINOR_NUM * 100;
		}
		else if (g_ascii_strcasecmp (type, "major") == 0) {
			version_num = RSPAMD_VERSION_MAJOR_NUM;
		}
		else if (g_ascii_strcasecmp (type, "minor") == 0) {
			version_num = RSPAMD_VERSION_MINOR_NUM;
		}
		else if (g_ascii_strcasecmp (type, "patch") == 0) {
			version_num = RSPAMD_VERSION_PATCH_NUM;
		}
	}

	lua_pushnumber (L, version_num);

	return 1;
}

static int
rspamd_rcl_lua_version (lua_State *L)
{
	const gchar *result = NULL, *type;

	if (lua_gettop (L) == 0) {
		result = RVERSION;
	}
	else if (lua_gettop (L) >= 1 && lua_type (L, 1) == LUA_TSTRING) {
		/* We got something like string */
		type = lua_tostring (L, 1);

		if (g_ascii_strcasecmp (type, "short") == 0) {
			result = RSPAMD_VERSION_MAJOR
					"." RSPAMD_VERSION_MINOR
					"." RSPAMD_VERSION_PATCH;
		}
		else if (g_ascii_strcasecmp (type, "main") == 0) {
			result = RSPAMD_VERSION_MAJOR "." RSPAMD_VERSION_MINOR;
		}
		else if (g_ascii_strcasecmp (type, "major") == 0) {
			result = RSPAMD_VERSION_MAJOR;
		}
		else if (g_ascii_strcasecmp (type, "minor") == 0) {
			result = RSPAMD_VERSION_MINOR;
		}
		else if (g_ascii_strcasecmp (type, "patch") == 0) {
			result = RSPAMD_VERSION_PATCH;
		}
		else if (g_ascii_strcasecmp (type, "id") == 0) {
			result = RID;
		}
		else if (g_ascii_strcasecmp (type, "num") == 0) {
			return rspamd_rcl_lua_version_numeric (L);
		}
		else if (g_ascii_strcasecmp (type, "cmp") == 0) {
			return rspamd_rcl_lua_version_cmp (L);
		}
	}

	lua_pushstring (L, result);

	return 1;
}

static void
rspamd_rcl_set_lua_globals (struct rspamd_config *cfg, lua_State *L,
		GHashTable *vars)
{
	struct rspamd_config **pcfg;

	/* First check for global variable 'config' */
	lua_getglobal (L, "config");
	if (lua_isnil (L, -1)) {
		/* Assign global table to set up attributes */
		lua_newtable (L);
		lua_setglobal (L, "config");
	}

	lua_getglobal (L, "metrics");
	if (lua_isnil (L, -1)) {
		lua_newtable (L);
		lua_setglobal (L, "metrics");
	}

	lua_getglobal (L, "composites");
	if (lua_isnil (L, -1)) {
		lua_newtable (L);
		lua_setglobal (L, "composites");
	}

	lua_getglobal (L, "rspamd_classifiers");
	if (lua_isnil (L, -1)) {
		lua_newtable (L);
		lua_setglobal (L, "rspamd_classifiers");
	}

	lua_getglobal (L, "classifiers");
	if (lua_isnil (L, -1)) {
		lua_newtable (L);
		lua_setglobal (L, "classifiers");
	}

	lua_getglobal (L, "rspamd_version");
	if (lua_isnil (L, -1)) {
		lua_pushcfunction (L, rspamd_rcl_lua_version);
		lua_setglobal (L, "rspamd_version");
	}

	pcfg = lua_newuserdata (L, sizeof (struct rspamd_config *));
	rspamd_lua_setclass (L, "rspamd{config}", -1);
	*pcfg = cfg;
	lua_setglobal (L, "rspamd_config");

	/* Clear stack from globals */
	lua_pop (L, 4);

	rspamd_lua_set_path (L, cfg->rcl_obj, vars);

	/* Set known paths as rspamd_paths global */
	lua_getglobal (L, "rspamd_paths");
	if (lua_isnil (L, -1)) {
		const gchar *confdir = RSPAMD_CONFDIR, *rundir = RSPAMD_RUNDIR,
				*dbdir = RSPAMD_DBDIR, *logdir = RSPAMD_LOGDIR,
				*wwwdir = RSPAMD_WWWDIR, *pluginsdir = RSPAMD_PLUGINSDIR,
				*rulesdir = RSPAMD_RULESDIR, *lualibdir = RSPAMD_LUALIBDIR,
				*prefix = RSPAMD_PREFIX;
		const gchar *t;

		/* Try environment */
		t = getenv ("PLUGINSDIR");
		if (t) {
			pluginsdir = t;
		}

		t = getenv ("RULESDIR");
		if (t) {
			rulesdir = t;
		}

		t = getenv ("DBDIR");
		if (t) {
			dbdir = t;
		}

		t = getenv ("RUNDIR");
		if (t) {
			rundir = t;
		}

		t = getenv ("LUALIBDIR");
		if (t) {
			lualibdir = t;
		}

		t = getenv ("LOGDIR");
		if (t) {
			logdir = t;
		}

		t = getenv ("WWWDIR");
		if (t) {
			wwwdir = t;
		}

		t = getenv ("CONFDIR");
		if (t) {
			confdir = t;
		}


		if (vars) {
			t = g_hash_table_lookup (vars, "PLUGINSDIR");
			if (t) {
				pluginsdir = t;
			}

			t = g_hash_table_lookup (vars, "RULESDIR");
			if (t) {
				rulesdir = t;
			}

			t = g_hash_table_lookup (vars, "LUALIBDIR");
			if (t) {
				lualibdir = t;
			}

			t = g_hash_table_lookup (vars, "RUNDIR");
			if (t) {
				rundir = t;
			}

			t = g_hash_table_lookup (vars, "WWWDIR");
			if (t) {
				wwwdir = t;
			}

			t = g_hash_table_lookup (vars, "CONFDIR");
			if (t) {
				confdir = t;
			}

			t = g_hash_table_lookup (vars, "DBDIR");
			if (t) {
				dbdir = t;
			}

			t = g_hash_table_lookup (vars, "LOGDIR");
			if (t) {
				logdir = t;
			}
		}

		lua_createtable (L, 0, 9);

		rspamd_lua_table_set (L, RSPAMD_CONFDIR_INDEX, confdir);
		rspamd_lua_table_set (L, RSPAMD_RUNDIR_INDEX, rundir);
		rspamd_lua_table_set (L, RSPAMD_DBDIR_INDEX, dbdir);
		rspamd_lua_table_set (L, RSPAMD_LOGDIR_INDEX, logdir);
		rspamd_lua_table_set (L, RSPAMD_WWWDIR_INDEX, wwwdir);
		rspamd_lua_table_set (L, RSPAMD_PLUGINSDIR_INDEX, pluginsdir);
		rspamd_lua_table_set (L, RSPAMD_RULESDIR_INDEX, rulesdir);
		rspamd_lua_table_set (L, RSPAMD_LUALIBDIR_INDEX, lualibdir);
		rspamd_lua_table_set (L, RSPAMD_PREFIX_INDEX, prefix);

		lua_setglobal (L, "rspamd_paths");
	}
}

static gboolean
rspamd_rcl_lua_handler (rspamd_mempool_t *pool, const ucl_object_t *obj,
		const gchar *key, gpointer ud,
		struct rspamd_rcl_section *section, GError **err)
{
	struct rspamd_config *cfg = ud;
	const gchar *lua_src = rspamd_mempool_strdup (pool,
			ucl_object_tostring (obj));
	gchar *cur_dir, *lua_dir, *lua_file, *tmp1, *tmp2;
	lua_State *L = cfg->lua_state;
	GString *tb;
	gint err_idx;

	tmp1 = g_strdup (lua_src);
	tmp2 = g_strdup (lua_src);
	lua_dir = dirname (tmp1);
	lua_file = basename (tmp2);

	if (lua_dir && lua_file) {
		cur_dir = g_malloc (PATH_MAX);
		if (getcwd (cur_dir, PATH_MAX) != NULL && chdir (lua_dir) != -1) {
			/* Push traceback function */
			lua_pushcfunction (L, &rspamd_lua_traceback);
			err_idx = lua_gettop (L);

			/* Load file */
			if (luaL_loadfile (L, lua_file) != 0) {
				g_set_error (err,
					CFG_RCL_ERROR,
					EINVAL,
					"cannot load lua file %s: %s",
					lua_src,
					lua_tostring (L, -1));
				if (chdir (cur_dir) == -1) {
					msg_err_config ("cannot chdir to %s: %s", cur_dir,
						strerror (errno));
				}
				g_free (cur_dir);
				g_free (tmp1);
				g_free (tmp2);
				return FALSE;
			}

			/* Now do it */
			if (lua_pcall (L, 0, 0, err_idx) != 0) {
				tb = lua_touserdata (L, -1);
				g_set_error (err,
						CFG_RCL_ERROR,
						EINVAL,
						"cannot init lua file %s: %s",
						lua_src,
						tb->str);
				g_string_free (tb, TRUE);
				lua_pop (L, 2);

				if (chdir (cur_dir) == -1) {
					msg_err_config ("cannot chdir to %s: %s", cur_dir,
						strerror (errno));
				}

				g_free (cur_dir);
				g_free (tmp1);
				g_free (tmp2);

				return FALSE;
			}

			lua_pop (L, 1);
		}
		else {
			g_set_error (err, CFG_RCL_ERROR, ENOENT, "cannot chdir to %s: %s",
					lua_dir, strerror (errno));
			if (chdir (cur_dir) == -1) {
				msg_err_config ("cannot chdir to %s: %s", cur_dir, strerror (errno));
			}
			g_free (cur_dir);
			g_free (tmp1);
			g_free (tmp2);
			return FALSE;

		}
		if (chdir (cur_dir) == -1) {
			msg_err_config ("cannot chdir to %s: %s", cur_dir, strerror (errno));
		}
		g_free (cur_dir);
		g_free (tmp1);
		g_free (tmp2);
	}
	else {
		g_free (tmp1);
		g_free (tmp2);
		g_set_error (err, CFG_RCL_ERROR, ENOENT, "cannot find to %s: %s",
			lua_src, strerror (errno));
		return FALSE;
	}

	return TRUE;
}

gboolean
rspamd_rcl_add_lua_plugins_path (struct rspamd_config *cfg,
		const gchar *path,
		GError **err)
{
	struct stat st;
	struct script_module *cur_mod;
	glob_t globbuf;
	gchar *pattern, *ext_pos;
	size_t len;
	guint i;

	if (stat (path, &st) == -1) {
		g_set_error (err,
			CFG_RCL_ERROR,
			errno,
			"cannot stat path %s, %s",
			path,
			strerror (errno));
		return FALSE;
	}

	/* Handle directory */
	if (S_ISDIR (st.st_mode)) {
		globbuf.gl_offs = 0;
		len = strlen (path) + sizeof ("*.lua");
		pattern = g_malloc (len);
		rspamd_snprintf (pattern, len, "%s%s", path, "*.lua");

		if (glob (pattern, GLOB_DOOFFS, NULL, &globbuf) == 0) {
			for (i = 0; i < globbuf.gl_pathc; i++) {
				cur_mod =
					rspamd_mempool_alloc (cfg->cfg_pool,
						sizeof (struct script_module));
				cur_mod->path = rspamd_mempool_strdup (cfg->cfg_pool,
						globbuf.gl_pathv[i]);
				cur_mod->name = g_path_get_basename (cur_mod->path);
				rspamd_mempool_add_destructor (cfg->cfg_pool, g_free,
						cur_mod->name);
				ext_pos = strstr (cur_mod->name, ".lua");

				if (ext_pos != NULL) {
					*ext_pos = '\0';
				}

				if (cfg->script_modules == NULL) {
					cfg->script_modules = g_list_append (cfg->script_modules,
							cur_mod);
					rspamd_mempool_add_destructor (cfg->cfg_pool,
							(rspamd_mempool_destruct_t)g_list_free,
							cfg->script_modules);
				}
				else {
					cfg->script_modules = g_list_append (cfg->script_modules,
							cur_mod);
				}
			}
			globfree (&globbuf);
			g_free (pattern);
		}
		else {
			g_set_error (err,
				CFG_RCL_ERROR,
				errno,
				"glob failed for %s, %s",
				pattern,
				strerror (errno));
			g_free (pattern);
			return FALSE;
		}
	}
	else {
		/* Handle single file */
		cur_mod =
			rspamd_mempool_alloc (cfg->cfg_pool, sizeof (struct script_module));
		cur_mod->path = rspamd_mempool_strdup (cfg->cfg_pool, path);
		cur_mod->name = g_path_get_basename (cur_mod->path);
		rspamd_mempool_add_destructor (cfg->cfg_pool, g_free,
				cur_mod->name);
		ext_pos = strstr (cur_mod->name, ".lua");

		if (ext_pos != NULL) {
			*ext_pos = '\0';
		}

		if (cfg->script_modules == NULL) {
			cfg->script_modules = g_list_append (cfg->script_modules,
					cur_mod);
			rspamd_mempool_add_destructor (cfg->cfg_pool,
					(rspamd_mempool_destruct_t)g_list_free,
					cfg->script_modules);
		}
		else {
			cfg->script_modules = g_list_append (cfg->script_modules,
					cur_mod);
		}
	}

	return TRUE;
}

static gboolean
rspamd_rcl_modules_handler (rspamd_mempool_t *pool, const ucl_object_t *obj,
		const gchar *key, gpointer ud,
		struct rspamd_rcl_section *section, GError **err)
{
	const ucl_object_t *val, *cur;
	struct rspamd_config *cfg = ud;
	const gchar *data;

	if (obj->type == UCL_OBJECT) {
		val = ucl_object_lookup (obj, "path");

		LL_FOREACH (val, cur)
		{
			if (ucl_object_tostring_safe (cur, &data)) {
				if (!rspamd_rcl_add_lua_plugins_path (cfg,
						rspamd_mempool_strdup (cfg->cfg_pool, data), err)) {
					return FALSE;
				}
			}
		}
	}
	else if (ucl_object_tostring_safe (obj, &data)) {
		if (!rspamd_rcl_add_lua_plugins_path (cfg,
				rspamd_mempool_strdup (cfg->cfg_pool, data), err)) {
			return FALSE;
		}
	}
	else {
		g_set_error (err,
			CFG_RCL_ERROR,
			EINVAL,
			"module parameter has wrong type (must be an object or a string)");
		return FALSE;
	}

	return TRUE;
}

struct statfile_parser_data {
	struct rspamd_config *cfg;
	struct rspamd_classifier_config *ccf;
};

static gboolean
rspamd_rcl_statfile_handler (rspamd_mempool_t *pool, const ucl_object_t *obj,
		const gchar *key, gpointer ud,
		struct rspamd_rcl_section *section, GError **err)
{
	struct statfile_parser_data *stud = ud;
	struct rspamd_classifier_config *ccf;
	struct rspamd_config *cfg;
	const ucl_object_t *val;
	struct rspamd_statfile_config *st;
	GList *labels;

	g_assert (key != NULL);

	cfg = stud->cfg;
	ccf = stud->ccf;

	st = rspamd_config_new_statfile (cfg, NULL);
	st->symbol = rspamd_mempool_strdup (cfg->cfg_pool, key);

	if (rspamd_rcl_section_parse_defaults (cfg, section, pool, obj, st, err)) {
		ccf->statfiles = rspamd_mempool_glist_prepend (pool, ccf->statfiles, st);

		if (st->label != NULL) {
			labels = g_hash_table_lookup (ccf->labels, st->label);
			if (labels != NULL) {
				labels = g_list_append (labels, st);
			}
			else {
				g_hash_table_insert (ccf->labels, st->label,
					g_list_prepend (NULL, st));
			}
		}

		if (st->symbol != NULL) {
			g_hash_table_insert (cfg->classifiers_symbols, st->symbol, st);
		}
		else {
			g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"statfile must have a symbol defined");
			return FALSE;
		}

		st->opts = (ucl_object_t *)obj;
		st->clcf = ccf;

		val = ucl_object_lookup (obj, "spam");
		if (val == NULL) {
			msg_info_config (
				"statfile %s has no explicit 'spam' setting, trying to guess by symbol",
				st->symbol);
			if (rspamd_substring_search_caseless (st->symbol,
					strlen (st->symbol),"spam", 4) != -1) {
				st->is_spam = TRUE;
			}
			else if (rspamd_substring_search_caseless (st->symbol,
					strlen (st->symbol),"ham", 3) != -1) {
				st->is_spam = FALSE;
			}
			else {
				g_set_error (err,
					CFG_RCL_ERROR,
					EINVAL,
					"cannot guess spam setting from %s",
					st->symbol);
				return FALSE;
			}
			msg_info_config ("guessed that statfile with symbol %s is %s",
				st->symbol,
				st->is_spam ?
				"spam" : "ham");
		}
		return TRUE;
	}

	return FALSE;
}

static gboolean
rspamd_rcl_classifier_handler (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	const gchar *key,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	const ucl_object_t *val, *cur;
	ucl_object_iter_t it = NULL;
	struct rspamd_config *cfg = ud;
	struct statfile_parser_data stud;
	const gchar *st_key;
	struct rspamd_classifier_config *ccf;
	gboolean res = TRUE;
	struct rspamd_rcl_section *stat_section;
	struct rspamd_tokenizer_config *tkcf = NULL;
	lua_State *L;

	g_assert (key != NULL);
	ccf = rspamd_config_new_classifier (cfg, NULL);

	ccf->classifier = rspamd_mempool_strdup (cfg->cfg_pool, key);

	if (rspamd_rcl_section_parse_defaults (cfg, section, cfg->cfg_pool, obj,
			ccf, err)) {

		HASH_FIND_STR (section->subsections, "statfile", stat_section);

		if (ccf->classifier == NULL) {
			ccf->classifier = "bayes";
		}

		if (ccf->name == NULL) {
			ccf->name = ccf->classifier;
		}

		it = ucl_object_iterate_new (obj);

		while ((val = ucl_object_iterate_safe (it, true)) != NULL && res) {
			st_key = ucl_object_key (val);

			if (st_key != NULL) {
				if (g_ascii_strcasecmp (st_key, "statfile") == 0) {
					LL_FOREACH (val, cur) {
						stud.cfg = cfg;
						stud.ccf = ccf;
						res = rspamd_rcl_process_section (cfg, stat_section, &stud,
								cur, cfg->cfg_pool, err);

						if (!res) {
							ucl_object_iterate_free (it);

							return FALSE;
						}
					}
				}
				else if (g_ascii_strcasecmp (st_key, "tokenizer") == 0) {
					tkcf = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*tkcf));

					if (ucl_object_type (val) == UCL_STRING) {
						tkcf->name = ucl_object_tostring (val);
					}
					else if (ucl_object_type (val) == UCL_OBJECT) {
						cur = ucl_object_lookup (val, "name");
						if (cur != NULL) {
							tkcf->name = ucl_object_tostring (cur);
							tkcf->opts = val;
						}
						else {
							cur = ucl_object_lookup (val, "type");
							if (cur != NULL) {
								tkcf->name = ucl_object_tostring (cur);
								tkcf->opts = val;
							}
						}
					}
				}
			}
		}

		ucl_object_iterate_free (it);
	}
	else {
		msg_err_config ("fatal configuration error, cannot parse statfile definition");
	}

	if (tkcf == NULL) {
		tkcf = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (*tkcf));
		tkcf->name = NULL;

	}

	ccf->tokenizer = tkcf;

	/* Handle lua conditions */
	val = ucl_object_lookup_any (obj, "condition", "learn_condition", NULL);

	if (val) {
		LL_FOREACH (val, cur) {
			if (ucl_object_type (cur) == UCL_STRING) {
				const gchar *lua_script;
				gsize slen;
				gint err_idx, ref_idx;
				GString *tb = NULL;

				lua_script = ucl_object_tolstring (cur, &slen);
				L = cfg->lua_state;
				lua_pushcfunction (L, &rspamd_lua_traceback);
				err_idx = lua_gettop (L);


				/* Load file */
				if (luaL_loadbuffer (L, lua_script, slen, "learn_condition") != 0) {
					g_set_error (err,
							CFG_RCL_ERROR,
							EINVAL,
							"cannot load lua condition script: %s",
							lua_tostring (L, -1));
					lua_settop (L, 0); /* Error function */

					return FALSE;
				}

				/* Now do it */
				if (lua_pcall (L, 0, 1, err_idx) != 0) {
					tb = lua_touserdata (L, -1);
					g_set_error (err,
							CFG_RCL_ERROR,
							EINVAL,
							"cannot init lua condition script: %s",
							tb->str);
					g_string_free (tb, TRUE);
					lua_settop (L, 0);

					return FALSE;
				}

				if (!lua_isfunction (L, -1)) {
					g_set_error (err,
							CFG_RCL_ERROR,
							EINVAL,
							"cannot init lua condition script: "
							"must return function");
					lua_settop (L, 0);

					return FALSE;
				}

				ref_idx = luaL_ref (L, LUA_REGISTRYINDEX);
				rspamd_lua_add_ref_dtor (L, cfg->cfg_pool, ref_idx);
				ccf->learn_conditions = rspamd_mempool_glist_append (
						cfg->cfg_pool,
						ccf->learn_conditions,
						GINT_TO_POINTER (ref_idx));
				lua_settop (L, 0);
			}
		}
	}

	ccf->opts = (ucl_object_t *)obj;
	cfg->classifiers = g_list_prepend (cfg->classifiers, ccf);

	return res;
}

static gboolean
rspamd_rcl_composite_handler (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	const gchar *key,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	const ucl_object_t *val;
	struct rspamd_expression *expr;
	struct rspamd_config *cfg = ud;
	struct rspamd_composite *composite;
	const gchar *composite_name, *composite_expression, *group,
		*description;
	gdouble score;
	gboolean new = TRUE;

	g_assert (key != NULL);

	composite_name = key;

	val = ucl_object_lookup (obj, "enabled");
	if (val != NULL && !ucl_object_toboolean (val)) {
		msg_info_config ("composite %s is disabled", composite_name);
		return TRUE;
	}

	if (g_hash_table_lookup (cfg->composite_symbols, composite_name) != NULL) {
		msg_warn_config ("composite %s is redefined", composite_name);
		new = FALSE;
	}

	val = ucl_object_lookup (obj, "expression");
	if (val == NULL || !ucl_object_tostring_safe (val, &composite_expression)) {
		g_set_error (err,
			CFG_RCL_ERROR,
			EINVAL,
			"composite must have an expression defined");
		return FALSE;
	}

	if (!rspamd_parse_expression (composite_expression, 0, &composite_expr_subr,
				NULL, cfg->cfg_pool, err, &expr)) {
		if (err && *err) {
			msg_err_config ("cannot parse composite expression for %s: %e",
				composite_name, *err);
		}
		else {
			msg_err_config ("cannot parse composite expression for %s: unknown error",
				composite_name);
		}

		return 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 = composite_expression;
	composite->sym = composite_name;

	val = ucl_object_lookup (obj, "score");
	if (val != NULL && ucl_object_todouble_safe (val, &score)) {
		/* Also set score in the metric */

		val = ucl_object_lookup (obj, "group");
		if (val != NULL) {
			group = ucl_object_tostring (val);
		}
		else {
			group = "composite";
		}

		val = ucl_object_lookup (obj, "description");
		if (val != NULL) {
			description = ucl_object_tostring (val);
		}
		else {
			description = composite_expression;
		}

		rspamd_config_add_symbol (cfg, composite_name, score,
				description, group, FALSE, FALSE,
				1);
	}

	val = ucl_object_lookup (obj, "policy");

	if (val) {
		composite->policy = rspamd_composite_policy_from_str (
				ucl_object_tostring (val));

		if (composite->policy == RSPAMD_COMPOSITE_POLICY_UNKNOWN) {
			g_set_error (err,
					CFG_RCL_ERROR,
					EINVAL,
					"composite %s has incorrect policy", composite_name);
			return FALSE;
		}
	}

	g_hash_table_insert (cfg->composite_symbols,
			(gpointer)composite_name,
			composite);

	if (new) {
		rspamd_symbols_cache_add_symbol (cfg->cache, composite_name, 0,
				NULL, NULL, SYMBOL_TYPE_COMPOSITE, -1);
	}

	return TRUE;
}

static gboolean
rspamd_rcl_composites_handler (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	const gchar *key,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	ucl_object_iter_t it = NULL;
	const ucl_object_t *cur;
	gboolean success = TRUE;

	it = ucl_object_iterate_new (obj);

	while ((cur = ucl_object_iterate_safe (it, true))) {
		success = rspamd_rcl_composite_handler(pool, cur,
				ucl_object_key(cur), ud, section, err);
		if (!success) {
			break;
		}
	}

	ucl_object_iterate_free (it);

	return success;
}

static gboolean
rspamd_rcl_neighbours_handler (rspamd_mempool_t *pool,
		const ucl_object_t *obj,
		const gchar *key,
		gpointer ud,
		struct rspamd_rcl_section *section,
		GError **err)
{
	struct rspamd_config *cfg = ud;
	const ucl_object_t *hostval, *pathval;
	ucl_object_t *neigh;
	gboolean has_port = FALSE, has_proto = FALSE;
	GString *urlstr;
	const gchar *p;

	if (key == NULL) {
		g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"missing name for neighbour");
		return FALSE;
	}

	hostval = ucl_object_lookup (obj, "host");

	if (hostval == NULL || ucl_object_type (hostval) != UCL_STRING) {
		g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"missing host for neighbour: %s", ucl_object_key (obj));
		return FALSE;
	}

	neigh = ucl_object_typed_new (UCL_OBJECT);
	ucl_object_insert_key (neigh, ucl_object_copy (hostval), "host", 0, false);

	if ((p = strrchr (ucl_object_tostring (hostval), ':')) != NULL) {
		if (g_ascii_isdigit (p[1])) {
			has_port = TRUE;
		}
	}

	if (strstr (ucl_object_tostring (hostval), "://") != NULL) {
		has_proto = TRUE;
	}

	/* Now make url */
	urlstr = g_string_sized_new (63);
	pathval = ucl_object_lookup (obj, "path");

	if (!has_proto) {
		g_string_append_len (urlstr, "http://", sizeof ("http://") - 1);
	}

	g_string_append (urlstr, ucl_object_tostring (hostval));

	if (!has_port) {
		g_string_append (urlstr, ":11334");
	}

	if (pathval == NULL) {
		g_string_append (urlstr, "/");
	}
	else {
		g_string_append (urlstr,  ucl_object_tostring (pathval));
	}

	ucl_object_insert_key (neigh,
			ucl_object_fromlstring (urlstr->str, urlstr->len),
			"url", 0, false);
	g_string_free (urlstr, TRUE);
	ucl_object_insert_key (cfg->neighbours, neigh, key, 0, true);

	return TRUE;
}


struct rspamd_rcl_section *
rspamd_rcl_add_section (struct rspamd_rcl_section **top,
	const gchar *name, const gchar *key_attr, rspamd_rcl_handler_t handler,
	enum ucl_type type, gboolean required, gboolean strict_type)
{
	struct rspamd_rcl_section *new;
	ucl_object_t *parent_doc;

	new = g_malloc0 (sizeof (struct rspamd_rcl_section));
	new->name = name;
	new->key_attr = key_attr;
	new->handler = handler;
	new->type = type;
	new->strict_type = strict_type;

	if (*top == NULL) {
		parent_doc = NULL;
		new->doc_ref = NULL;
	}
	else {
		parent_doc = (*top)->doc_ref;
		new->doc_ref = ucl_object_ref (rspamd_rcl_add_doc_obj (parent_doc,
				NULL,
				name,
				type,
				NULL,
				0,
				NULL,
				0));
	}

	HASH_ADD_KEYPTR (hh, *top, new->name, strlen (new->name), new);
	return new;
}

struct rspamd_rcl_section *
rspamd_rcl_add_section_doc (struct rspamd_rcl_section **top,
		const gchar *name, const gchar *key_attr, rspamd_rcl_handler_t handler,
		enum ucl_type type, gboolean required, gboolean strict_type,
		ucl_object_t *doc_target,
		const gchar *doc_string)
{
	struct rspamd_rcl_section *new_section;

	new_section = g_malloc0 (sizeof (struct rspamd_rcl_section));
	new_section->name = name;
	new_section->key_attr = key_attr;
	new_section->handler = handler;
	new_section->type = type;
	new_section->strict_type = strict_type;

	new_section->doc_ref =  ucl_object_ref (rspamd_rcl_add_doc_obj (doc_target,
			doc_string,
			name,
			type,
			NULL,
			0,
			NULL,
			0));

	HASH_ADD_KEYPTR (hh, *top, new_section->name, strlen (new_section->name), new_section);
	return new_section;
}

struct rspamd_rcl_default_handler_data *
rspamd_rcl_add_default_handler (struct rspamd_rcl_section *section,
		const gchar *name,
		rspamd_rcl_default_handler_t handler,
		goffset offset,
		gint flags,
		const gchar *doc_string)
{
	struct rspamd_rcl_default_handler_data *nhandler;

	nhandler = g_malloc0 (sizeof (struct rspamd_rcl_default_handler_data));
	nhandler->key = g_strdup (name);
	nhandler->handler = handler;
	nhandler->pd.offset = offset;
	nhandler->pd.flags = flags;

	if (section->doc_ref != NULL) {
		rspamd_rcl_add_doc_obj (section->doc_ref,
				doc_string,
				name,
				UCL_NULL,
				handler,
				flags,
				NULL,
				0);
	}

	HASH_ADD_KEYPTR (hh, section->default_parser, nhandler->key, strlen (
			nhandler->key), nhandler);
	return nhandler;
}

struct rspamd_rcl_section *
rspamd_rcl_config_init (struct rspamd_config *cfg)
{
	struct rspamd_rcl_section *new = NULL, *sub, *ssub;

	/*
	 * Important notice:
	 * the order of parsing is equal to order of this initialization, therefore
	 * it is possible to init some portions of config prior to others
	 */

	/**
	 * Logging section
	 */
	sub = rspamd_rcl_add_section_doc (&new,
			"logging", NULL,
			rspamd_rcl_logging_handler,
			UCL_OBJECT,
			FALSE,
			TRUE,
			cfg->doc_strings,
			"Configure rspamd logging");
	/* Default handlers */
	rspamd_rcl_add_default_handler (sub,
			"log_buffer",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, log_buf_size),
			RSPAMD_CL_FLAG_INT_32,
			"Size of log buffer in bytes (for file logging)");
	rspamd_rcl_add_default_handler (sub,
			"log_urls",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, log_urls),
			0,
			"Write each URL found in a message to the log file");
	rspamd_rcl_add_default_handler (sub,
			"debug_ip",
			rspamd_rcl_parse_struct_ucl,
			G_STRUCT_OFFSET (struct rspamd_config, debug_ip_map),
			0,
			"Enable debugging log for the specified IP addresses");
	rspamd_rcl_add_default_handler (sub,
			"debug_symbols",
			rspamd_rcl_parse_struct_string_list,
			G_STRUCT_OFFSET (struct rspamd_config, debug_symbols),
			0,
			"Enable debug for the specified symbols");
	rspamd_rcl_add_default_handler (sub,
			"debug_modules",
			rspamd_rcl_parse_struct_string_list,
			G_STRUCT_OFFSET (struct rspamd_config, debug_modules),
			RSPAMD_CL_FLAG_STRING_LIST_HASH,
			"Enable debugging for the specified modules");
	rspamd_rcl_add_default_handler (sub,
			"log_format",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, log_format_str),
			0,
			"Specify format string for the task logging output "
					"(https://rspamd.com/doc/configuration/logging.html "
					"for details)");
	rspamd_rcl_add_default_handler (sub,
			"encryption_key",
			rspamd_rcl_parse_struct_pubkey,
			G_STRUCT_OFFSET (struct rspamd_config, log_encryption_key),
			0,
			"Encrypt sensitive information in logs using this pubkey");
	rspamd_rcl_add_default_handler (sub,
			"error_elts",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, log_error_elts),
			RSPAMD_CL_FLAG_UINT,
			"Size of circular buffer for last errors (10 by default)");
	rspamd_rcl_add_default_handler (sub,
			"error_maxlen",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, log_error_elt_maxlen),
			RSPAMD_CL_FLAG_UINT,
			"Size of each element in error log buffer (1000 by default)");

	/* Documentation only options, handled in log_handler to map flags */
	rspamd_rcl_add_doc_by_path (cfg,
			"logging",
			"Enable colored output (for console logging)",
			"log_color",
			UCL_BOOLEAN,
			NULL,
			0,
			NULL,
			0);
	rspamd_rcl_add_doc_by_path (cfg,
			"logging",
			"Enable systemd compatible logging",
			"systemd",
			UCL_BOOLEAN,
			NULL,
			0,
			NULL,
			0);
	rspamd_rcl_add_doc_by_path (cfg,
			"logging",
			"Write statistics of regexp processing to log (useful for hyperscan)",
			"log_re_cache",
			UCL_BOOLEAN,
			NULL,
			0,
			NULL,
			0);
	rspamd_rcl_add_doc_by_path (cfg,
			"logging",
			"Use microseconds resolution for timestamps",
			"log_usec",
			UCL_BOOLEAN,
			NULL,
			0,
			NULL,
			0);
	/**
	 * Options section
	 */
	sub = rspamd_rcl_add_section_doc (&new,
			"options", NULL,
			rspamd_rcl_options_handler,
			UCL_OBJECT,
			FALSE,
			TRUE,
			cfg->doc_strings,
			"Global rspamd options");
	rspamd_rcl_add_default_handler (sub,
			"cache_file",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, cache_filename),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Path to the cache file");
	rspamd_rcl_add_default_handler (sub,
			"cache_reload",
			rspamd_rcl_parse_struct_time,
			G_STRUCT_OFFSET (struct rspamd_config, cache_reload_time),
			RSPAMD_CL_FLAG_TIME_FLOAT,
			"How often cache reload should be performed");
	/* Old DNS configuration */
	rspamd_rcl_add_default_handler (sub,
			"dns_nameserver",
			rspamd_rcl_parse_struct_ucl,
			G_STRUCT_OFFSET (struct rspamd_config, nameservers),
			0,
			"Legacy option for DNS servers used");
	rspamd_rcl_add_default_handler (sub,
			"dns_timeout",
			rspamd_rcl_parse_struct_time,
			G_STRUCT_OFFSET (struct rspamd_config, dns_timeout),
			RSPAMD_CL_FLAG_TIME_FLOAT,
			"Legacy option for DNS request timeout");
	rspamd_rcl_add_default_handler (sub,
			"dns_retransmits",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, dns_retransmits),
			RSPAMD_CL_FLAG_INT_32,
			"Legacy option for DNS retransmits count");
	rspamd_rcl_add_default_handler (sub,
			"dns_sockets",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, dns_io_per_server),
			RSPAMD_CL_FLAG_INT_32,
			"Legacy option for DNS sockets per server count");
	rspamd_rcl_add_default_handler (sub,
			"dns_max_requests",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, dns_max_requests),
			RSPAMD_CL_FLAG_INT_32,
			"Legacy option for DNS maximum requests per task count");
	rspamd_rcl_add_default_handler (sub,
			"classify_headers",
			rspamd_rcl_parse_struct_string_list,
			G_STRUCT_OFFSET (struct rspamd_config, classify_headers),
			0,
			"List of headers used for classifiers");
	rspamd_rcl_add_default_handler (sub,
			"control_socket",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, control_socket_path),
			0,
			"Path to the control socket");
	rspamd_rcl_add_default_handler (sub,
			"explicit_modules",
			rspamd_rcl_parse_struct_string_list,
			G_STRUCT_OFFSET (struct rspamd_config, explicit_modules),
			RSPAMD_CL_FLAG_STRING_LIST_HASH,
			"Always load these modules even if they are not configured explicitly");
	rspamd_rcl_add_default_handler (sub,
			"allow_raw_input",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, allow_raw_input),
			0,
			"Allow non MIME input for rspamd");
	rspamd_rcl_add_default_handler (sub,
			"raw_mode",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, raw_mode),
			0,
			"Don't try to convert all messages to utf8");
	rspamd_rcl_add_default_handler (sub,
			"one_shot",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, one_shot_mode),
			0,
			"Add all symbols only once per message");
	rspamd_rcl_add_default_handler (sub,
			"check_attachements",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, check_text_attachements),
			0,
			"Treat text attachments as normal text parts");
	rspamd_rcl_add_default_handler (sub,
			"check_attachments",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, check_text_attachements),
			0,
			"Treat text attachments as normal text parts");
	rspamd_rcl_add_default_handler (sub,
			"tempdir",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, temp_dir),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Directory for temporary files");
	rspamd_rcl_add_default_handler (sub,
			"pidfile",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, pid_file),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Path to the pid file");
	rspamd_rcl_add_default_handler (sub,
			"filters",
			rspamd_rcl_parse_struct_string_list,
			G_STRUCT_OFFSET (struct rspamd_config, filters),
			0,
			"List of internal filters enabled");
	rspamd_rcl_add_default_handler (sub,
			"max_diff",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, max_diff),
			RSPAMD_CL_FLAG_INT_SIZE,
			"Legacy option, do not use");
	rspamd_rcl_add_default_handler (sub,
			"map_watch_interval",
			rspamd_rcl_parse_struct_time,
			G_STRUCT_OFFSET (struct rspamd_config, map_timeout),
			RSPAMD_CL_FLAG_TIME_FLOAT,
			"Interval for checking maps");
	rspamd_rcl_add_default_handler (sub,
			"map_file_watch_multiplier",
			rspamd_rcl_parse_struct_double,
			G_STRUCT_OFFSET (struct rspamd_config, map_file_watch_multiplier),
			0,
			"Multiplier for map watch interval when map is file");
	rspamd_rcl_add_default_handler (sub,
			"monitoring_watch_interval",
			rspamd_rcl_parse_struct_time,
			G_STRUCT_OFFSET (struct rspamd_config, monitored_interval),
			RSPAMD_CL_FLAG_TIME_FLOAT,
			"Interval for checking monitored instances");
	rspamd_rcl_add_default_handler (sub,
			"disable_monitoring",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, disable_monitored),
			0,
			"Disable monitoring completely");
	rspamd_rcl_add_default_handler (sub,
			"dynamic_conf",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, dynamic_conf),
			0,
			"Path to the dynamic configuration");
	rspamd_rcl_add_default_handler (sub,
			"rrd",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, rrd_file),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Path to RRD file");
	rspamd_rcl_add_default_handler (sub,
			"history_file",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, history_file),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Path to history file");
	rspamd_rcl_add_default_handler (sub,
			"check_all_filters",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, check_all_filters),
			0,
			"Always check all filters");
	rspamd_rcl_add_default_handler (sub,
			"enable_experimental",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, enable_experimental),
			0,
			"Enable experimental plugins");
	rspamd_rcl_add_default_handler (sub,
			"all_filters",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, check_all_filters),
			0,
			"Always check all filters");
	rspamd_rcl_add_default_handler (sub,
			"min_word_len",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, min_word_len),
			RSPAMD_CL_FLAG_UINT,
			"Minimum length of the word to be considered in statistics/fuzzy");
	rspamd_rcl_add_default_handler (sub,
			"max_word_len",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, max_word_len),
			RSPAMD_CL_FLAG_UINT,
			"Maximum length of the word to be considered in statistics/fuzzy");
	rspamd_rcl_add_default_handler (sub,
			"words_decay",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, words_decay),
			RSPAMD_CL_FLAG_UINT,
			"Start skipping words at this amount");
	rspamd_rcl_add_default_handler (sub,
			"url_tld",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, tld_file),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Path to the TLD file for urls detector");
	rspamd_rcl_add_default_handler (sub,
			"tld",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, tld_file),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Path to the TLD file for urls detector");
	rspamd_rcl_add_default_handler (sub,
			"hs_cache_dir",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, hs_cache_dir),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Path directory where rspamd would save hyperscan cache");
	rspamd_rcl_add_default_handler (sub,
			"history_rows",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, history_rows),
			RSPAMD_CL_FLAG_UINT,
			"Number of records in the history file");
	rspamd_rcl_add_default_handler (sub,
			"disable_hyperscan",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, disable_hyperscan),
			0,
			"Disable hyperscan optimizations for regular expressions");
	rspamd_rcl_add_default_handler (sub,
			"vectorized_hyperscan",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, vectorized_hyperscan),
			0,
			"Use hyperscan in vectorized mode (experimental)");
	rspamd_rcl_add_default_handler (sub,
			"cores_dir",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, cores_dir),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Path to the directory where rspamd core files are intended to be dumped");
	rspamd_rcl_add_default_handler (sub,
			"max_cores_size",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, max_cores_size),
			RSPAMD_CL_FLAG_INT_SIZE,
			"Limit of joint size of all files in `cores_dir`");
	rspamd_rcl_add_default_handler (sub,
			"max_cores_count",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, max_cores_count),
			RSPAMD_CL_FLAG_INT_SIZE,
			"Limit of files count in `cores_dir`");
	rspamd_rcl_add_default_handler (sub,
			"local_addrs",
			rspamd_rcl_parse_struct_ucl,
			G_STRUCT_OFFSET (struct rspamd_config, local_addrs),
			0,
			"Use the specified addresses as local ones");
	rspamd_rcl_add_default_handler (sub,
			"local_networks",
			rspamd_rcl_parse_struct_ucl,
			G_STRUCT_OFFSET (struct rspamd_config, local_addrs),
			0,
			"Use the specified addresses as local ones (alias for `local_addrs`)");
	rspamd_rcl_add_default_handler (sub,
			"trusted_keys",
			rspamd_rcl_parse_struct_string_list,
			G_STRUCT_OFFSET (struct rspamd_config, trusted_keys),
			RSPAMD_CL_FLAG_STRING_LIST_HASH,
			"List of trusted public keys used for signatures in base32 encoding");
	rspamd_rcl_add_default_handler (sub,
			"enable_shutdown_workaround",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, enable_shutdown_workaround),
			0,
			"Enable workaround for legacy clients");
	rspamd_rcl_add_default_handler (sub,
			"ignore_received",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, ignore_received),
			0,
			"Ignore data from the first received header");
	rspamd_rcl_add_default_handler (sub,
			"ssl_ca_path",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, ssl_ca_path),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Path to ssl CA file");
	rspamd_rcl_add_default_handler (sub,
			"ssl_ciphers",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, ssl_ciphers),
			0,
			"List of ssl ciphers (e.g. HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4)");
	rspamd_rcl_add_default_handler (sub,
			"magic_file",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, magic_file),
			0,
			"Path to a custom libmagic file");
	rspamd_rcl_add_default_handler (sub,
			"max_message",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, max_message),
			RSPAMD_CL_FLAG_INT_SIZE,
			"Maximum size of the message to be scanned (50Mb by default)");
	rspamd_rcl_add_default_handler (sub,
			"max_pic",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, max_pic_size),
			RSPAMD_CL_FLAG_INT_SIZE,
			"Maximum size of the picture to be normalized (1Mb by default)");
	rspamd_rcl_add_default_handler (sub,
			"images_cache",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, max_pic_size),
			RSPAMD_CL_FLAG_INT_SIZE,
			"Size of DCT data cache for images (256 elements by default)");
	rspamd_rcl_add_default_handler (sub,
			"zstd_input_dictionary",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, zstd_input_dictionary),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Dictionary for zstd inbound protocol compression");
	rspamd_rcl_add_default_handler (sub,
			"zstd_output_dictionary",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, zstd_output_dictionary),
			RSPAMD_CL_FLAG_STRING_PATH,
			"Dictionary for outbound zstd compression");
	rspamd_rcl_add_default_handler (sub,
			"compat_messages",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, compat_messages),
			0,
			"Use pre 1.4 style of messages in the protocol");
	rspamd_rcl_add_default_handler (sub,
			"max_shots",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, default_max_shots),
			0,
			"Maximum number of hits per a single symbol (default: 100)");
	rspamd_rcl_add_default_handler (sub,
			"sessions_cache",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, enable_sessions_cache),
			0,
			"Enable sessions cache to debug dangling sessions");
	rspamd_rcl_add_default_handler (sub,
			"max_sessions_cache",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, max_sessions_cache),
			0,
			"Maximum number of sessions in cache before warning (default: 100)");

	/* Neighbours configuration */
	rspamd_rcl_add_section_doc (&sub->subsections, "neighbours", "name",
			rspamd_rcl_neighbours_handler,
			UCL_OBJECT, FALSE, TRUE,
			cfg->doc_strings,
			"List of members of Rspamd cluster");

	/* New DNS configuration */
	ssub = rspamd_rcl_add_section_doc (&sub->subsections, "dns", NULL, NULL,
			UCL_OBJECT, FALSE, TRUE,
			cfg->doc_strings,
			"Options for DNS resolver");
	rspamd_rcl_add_default_handler (ssub,
			"nameserver",
			rspamd_rcl_parse_struct_ucl,
			G_STRUCT_OFFSET (struct rspamd_config, nameservers),
			0,
			"List of DNS servers");
	rspamd_rcl_add_default_handler (ssub,
			"server",
			rspamd_rcl_parse_struct_ucl,
			G_STRUCT_OFFSET (struct rspamd_config, nameservers),
			0,
			"List of DNS servers");
	rspamd_rcl_add_default_handler (ssub,
			"timeout",
			rspamd_rcl_parse_struct_time,
			G_STRUCT_OFFSET (struct rspamd_config, dns_timeout),
			RSPAMD_CL_FLAG_TIME_FLOAT,
			"DNS request timeout");
	rspamd_rcl_add_default_handler (ssub,
			"retransmits",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, dns_retransmits),
			RSPAMD_CL_FLAG_INT_32,
			"DNS request retransmits");
	rspamd_rcl_add_default_handler (ssub,
			"sockets",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, dns_io_per_server),
			RSPAMD_CL_FLAG_INT_32,
			"Number of sockets per DNS server");
	rspamd_rcl_add_default_handler (ssub,
			"connections",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, dns_io_per_server),
			RSPAMD_CL_FLAG_INT_32,
			"Number of sockets per DNS server");
	rspamd_rcl_add_default_handler (ssub,
			"enable_dnssec",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_config, enable_dnssec),
			0,
			"Enable DNSSEC support in Rspamd");


	/* New upstreams configuration */
	ssub = rspamd_rcl_add_section_doc (&sub->subsections, "upstream", NULL, NULL,
			UCL_OBJECT, FALSE, TRUE,
			cfg->doc_strings,
			"Upstreams configuration parameters");
	rspamd_rcl_add_default_handler (ssub,
			"max_errors",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_config, upstream_max_errors),
			RSPAMD_CL_FLAG_UINT,
			"Maximum number of errors during `error_time` to consider upstream down");
	rspamd_rcl_add_default_handler (ssub,
			"error_time",
			rspamd_rcl_parse_struct_time,
			G_STRUCT_OFFSET (struct rspamd_config, upstream_error_time),
			RSPAMD_CL_FLAG_TIME_FLOAT,
			"Time frame to check errors");
	rspamd_rcl_add_default_handler (ssub,
			"revive_time",
			rspamd_rcl_parse_struct_time,
			G_STRUCT_OFFSET (struct rspamd_config, upstream_revive_time),
			RSPAMD_CL_FLAG_TIME_FLOAT,
			"Time before attempting to recover upstream after an error");

	/**
	 * Symbols and actions sections
	 */
	sub = rspamd_rcl_add_section_doc (&new,
			"actions", NULL,
			rspamd_rcl_actions_handler,
			UCL_OBJECT,
			FALSE,
			TRUE,
			cfg->doc_strings,
			"Actions configuration");
	rspamd_rcl_add_default_handler (sub,
			"unknown_weight",
			rspamd_rcl_parse_struct_double,
			G_STRUCT_OFFSET (struct rspamd_config, unknown_weight),
			0,
			"Accept unknown symbols with the specified weight");
	rspamd_rcl_add_default_handler (sub,
			"grow_factor",
			rspamd_rcl_parse_struct_double,
			G_STRUCT_OFFSET (struct rspamd_config, grow_factor),
			0,
			"Multiply the subsequent symbols by this number "
					"(does not affect symbols with score less or "
					"equal to zero)");
	rspamd_rcl_add_default_handler (sub,
			"subject",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_config, subject),
			0,
			"Rewrite subject with this value");

	sub = rspamd_rcl_add_section_doc (&new,
			"group", "name",
			rspamd_rcl_group_handler,
			UCL_OBJECT,
			FALSE,
			TRUE,
			cfg->doc_strings,
			"Symbol groups configuration");
	ssub = rspamd_rcl_add_section_doc (&sub->subsections, "symbols", "name",
			rspamd_rcl_symbol_handler,
			UCL_OBJECT, FALSE, TRUE,
			cfg->doc_strings,
			"Symbols configuration");

	/* Group part */
	rspamd_rcl_add_default_handler (sub,
			"disabled",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_symbols_group, disabled),
			0,
			"Disable symbols group");
	rspamd_rcl_add_default_handler (sub,
			"enabled",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_symbols_group, disabled),
			RSPAMD_CL_FLAG_BOOLEAN_INVERSE,
			"Enable or disable symbols group");
	rspamd_rcl_add_default_handler (sub,
			"max_score",
			rspamd_rcl_parse_struct_double,
			G_STRUCT_OFFSET (struct rspamd_symbols_group, max_score),
			0,
			"Maximum score that could be reached by this symbols group");

	/**
	 * Worker section
	 */
	sub = rspamd_rcl_add_section_doc (&new,
			"worker", "type",
			rspamd_rcl_worker_handler,
			UCL_OBJECT,
			FALSE,
			TRUE,
			cfg->doc_strings,
			"Workers common options");
	rspamd_rcl_add_default_handler (sub,
			"count",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_worker_conf, count),
			RSPAMD_CL_FLAG_INT_16,
			"Number of workers to spawn");
	rspamd_rcl_add_default_handler (sub,
			"max_files",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_worker_conf, rlimit_nofile),
			RSPAMD_CL_FLAG_INT_32,
			"Maximum number of opened files per worker");
	rspamd_rcl_add_default_handler (sub,
			"max_core",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_worker_conf, rlimit_maxcore),
			RSPAMD_CL_FLAG_INT_32,
			"Max size of core file in bytes");
	rspamd_rcl_add_default_handler (sub,
			"enabled",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_worker_conf, enabled),
			0,
			"Enable or disable a worker (true by default)");

	/**
	 * Modules handler
	 */
	sub = rspamd_rcl_add_section_doc (&new,
			"modules", NULL,
			rspamd_rcl_modules_handler,
			UCL_OBJECT,
			FALSE,
			FALSE,
			cfg->doc_strings,
			"Lua plugins to load");

	/**
	 * Classifiers handler
	 */
	sub = rspamd_rcl_add_section_doc (&new,
			"classifier", "type",
			rspamd_rcl_classifier_handler,
			UCL_OBJECT,
			FALSE,
			TRUE,
			cfg->doc_strings,
			"CLassifier options");
	/* Default classifier is 'bayes' for now */
	sub->default_key = "bayes";

	rspamd_rcl_add_default_handler (sub,
			"min_tokens",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_classifier_config, min_tokens),
			RSPAMD_CL_FLAG_INT_32,
			"Minimum count of tokens (words) to be considered for statistics");
	rspamd_rcl_add_default_handler (sub,
			"max_tokens",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_classifier_config, max_tokens),
			RSPAMD_CL_FLAG_INT_32,
			"Maximum count of tokens (words) to be considered for statistics");
	rspamd_rcl_add_default_handler (sub,
			"min_learns",
			rspamd_rcl_parse_struct_integer,
			G_STRUCT_OFFSET (struct rspamd_classifier_config, min_learns),
			RSPAMD_CL_FLAG_UINT,
			"Minimum number of learns for each statfile to use this classifier");
	rspamd_rcl_add_default_handler (sub,
			"backend",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_classifier_config, backend),
			0,
			"Statfiles engine");
	rspamd_rcl_add_default_handler (sub,
			"name",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_classifier_config, name),
			0,
			"Name of classifier");

	/*
	 * Statfile defaults
	 */
	ssub = rspamd_rcl_add_section_doc (&sub->subsections,
			"statfile", "symbol",
			rspamd_rcl_statfile_handler,
			UCL_OBJECT,
			TRUE,
			TRUE,
			sub->doc_ref,
			"Statfiles options");
	rspamd_rcl_add_default_handler (ssub,
			"label",
			rspamd_rcl_parse_struct_string,
			G_STRUCT_OFFSET (struct rspamd_statfile_config, label),
			0,
			"Statfile unique label");
	rspamd_rcl_add_default_handler (ssub,
			"spam",
			rspamd_rcl_parse_struct_boolean,
			G_STRUCT_OFFSET (struct rspamd_statfile_config, is_spam),
			0,
			"Sets if this statfile contains spam samples");

	/**
	 * Composites handlers
	 */
	sub = rspamd_rcl_add_section_doc (&new,
			"composite", "name",
			rspamd_rcl_composite_handler,
			UCL_OBJECT,
			FALSE,
			TRUE,
			cfg->doc_strings,
			"Rspamd composite symbols");
	sub = rspamd_rcl_add_section_doc (&new,
			"composites", NULL,
			rspamd_rcl_composites_handler,
			UCL_OBJECT,
			FALSE,
			TRUE,
			cfg->doc_strings,
			"Rspamd composite symbols");

	/**
	 * Lua handler
	 */
	sub = rspamd_rcl_add_section_doc (&new,
			"lua", NULL,
			rspamd_rcl_lua_handler,
			UCL_STRING,
			FALSE,
			TRUE,
			cfg->doc_strings,
			"Lua files to load");

	return new;
}

struct rspamd_rcl_section *
rspamd_rcl_config_get_section (struct rspamd_rcl_section *top,
	const char *path)
{
	struct rspamd_rcl_section *cur, *found = NULL;
	char **path_components;
	gint ncomponents, i;


	if (path == NULL) {
		return top;
	}

	path_components = g_strsplit_set (path, "/", -1);
	ncomponents = g_strv_length (path_components);

	cur = top;
	for (i = 0; i < ncomponents; i++) {
		if (cur == NULL) {
			g_strfreev (path_components);
			return NULL;
		}
		HASH_FIND_STR (cur, path_components[i], found);
		if (found == NULL) {
			g_strfreev (path_components);
			return NULL;
		}
		cur = found;
	}

	g_strfreev (path_components);
	return found;
}

static gboolean
rspamd_rcl_process_section (struct rspamd_config *cfg,
		struct rspamd_rcl_section *sec,
		gpointer ptr, const ucl_object_t *obj, rspamd_mempool_t *pool,
		GError **err)
{
	ucl_object_iter_t it;
	const ucl_object_t *cur;
	gboolean is_nested = TRUE;
	const gchar *key = NULL;

	g_assert (obj != NULL);
	g_assert (sec->handler != NULL);

	if (sec->key_attr != NULL) {
		it = ucl_object_iterate_new (obj);

		while ((cur = ucl_object_iterate_full (it, UCL_ITERATE_EXPLICIT)) != NULL) {
			if (ucl_object_type (cur) != UCL_OBJECT) {
				is_nested = FALSE;
				break;
			}
		}

		ucl_object_iterate_free (it);
	}
	else {
		is_nested = FALSE;
	}

	if (is_nested) {
		/* Just reiterate on all subobjects */
		it = ucl_object_iterate_new (obj);

		while ((cur = ucl_object_iterate_full (it, UCL_ITERATE_EXPLICIT)) != NULL) {
			if (!sec->handler (pool, cur, ucl_object_key (cur), ptr, sec, err)) {
				ucl_object_iterate_free (it);

				return FALSE;
			}
		}

		ucl_object_iterate_free (it);

		return TRUE;
	}
	else {
		if (sec->key_attr != NULL) {
			/* First of all search for required attribute and use it as a key */
			cur = ucl_object_lookup (obj, sec->key_attr);

			if (cur == NULL) {
				if (sec->default_key == NULL) {
					g_set_error (err, CFG_RCL_ERROR, EINVAL, "required attribute "
							"'%s' is missing for section '%s', current key: %s",
							sec->key_attr,
							sec->name,
							ucl_object_emit (obj, UCL_EMIT_CONFIG));

					return FALSE;
				}
				else {
					msg_info ("using default key '%s' for mandatory field '%s' "
							"for section '%s'", sec->default_key, sec->key_attr,
							sec->name);
					key = sec->default_key;
				}
			}
			else if (ucl_object_type (cur) != UCL_STRING) {
				g_set_error (err, CFG_RCL_ERROR, EINVAL, "required attribute %s"
						" is not a string for section %s",
						sec->key_attr, sec->name);

				return FALSE;
			}
			else {
				key = ucl_object_tostring (cur);
			}
		}
	}

	return sec->handler (pool, obj, key, ptr, sec, err);
}

gboolean
rspamd_rcl_parse (struct rspamd_rcl_section *top,
		struct rspamd_config *cfg,
		gpointer ptr, rspamd_mempool_t *pool,
		const ucl_object_t *obj, GError **err)
{
	const ucl_object_t *found, *cur_obj;
	struct rspamd_rcl_section *cur, *tmp, *found_sec;

	if (obj->type != UCL_OBJECT) {
		g_set_error (err,
			CFG_RCL_ERROR,
			EINVAL,
			"top configuration must be an object");
		return FALSE;
	}

	/* Iterate over known sections and ignore unknown ones */
	HASH_ITER (hh, top, cur, tmp)
	{
		if (strcmp (cur->name, "*") == 0) {
			/* Default section handler */
			LL_FOREACH (obj, cur_obj) {
				HASH_FIND_STR (top, ucl_object_key (cur_obj), found_sec);

				if (found_sec == NULL) {
					if (cur->handler != NULL) {
						if (!rspamd_rcl_process_section (cfg, cur, ptr, cur_obj,
								pool, err)) {
							return FALSE;
						}
					}
					else {
						rspamd_rcl_section_parse_defaults (cfg,
								cur,
								pool,
								cur_obj,
								ptr,
								err);
					}
				}
			}
		}
		else {
			found = ucl_object_lookup (obj, cur->name);
			if (found == NULL) {
				if (cur->required) {
					g_set_error (err, CFG_RCL_ERROR, ENOENT,
							"required section %s is missing", cur->name);
					return FALSE;
				}
			}
			else {
				/* Check type */
				if (cur->strict_type) {
					if (cur->type != found->type) {
						g_set_error (err, CFG_RCL_ERROR, EINVAL,
								"object in section %s has invalid type", cur->name);
						return FALSE;
					}
				}

				LL_FOREACH (found, cur_obj) {
					if (cur->handler != NULL) {
						if (!rspamd_rcl_process_section (cfg, cur, ptr, cur_obj,
								pool, err)) {
							return FALSE;
						}
					}
					else {
						rspamd_rcl_section_parse_defaults (cfg, cur,
								pool,
								cur_obj,
								ptr,
								err);
					}
				}
			}
		}
		if (cur->fin) {
			cur->fin (pool, cur->fin_ud);
		}
	}

	return TRUE;
}

gboolean
rspamd_rcl_section_parse_defaults (struct rspamd_config *cfg,
		struct rspamd_rcl_section *section,
		rspamd_mempool_t *pool, const ucl_object_t *obj, gpointer ptr,
		GError **err)
{
	const ucl_object_t *found, *cur_obj;
	struct rspamd_rcl_default_handler_data *cur, *tmp;

	if (obj->type != UCL_OBJECT) {
		g_set_error (err,
			CFG_RCL_ERROR,
			EINVAL,
			"default configuration must be an object for section %s "
					"(actual type is %s)",
				section->name, ucl_object_type_to_string (obj->type));
		return FALSE;
	}

	HASH_ITER (hh, section->default_parser, cur, tmp)
	{
		found = ucl_object_lookup (obj, cur->key);
		if (found != NULL) {
			cur->pd.user_struct = ptr;
			cur->pd.cfg = cfg;

			LL_FOREACH (found, cur_obj) {
				if (!cur->handler (pool, cur_obj, &cur->pd, section, err)) {
					return FALSE;
				}

				if (!(cur->pd.flags & RSPAMD_CL_FLAG_MULTIPLE)) {
					break;
				}
			}
		}
	}

	return TRUE;
}

gboolean
rspamd_rcl_parse_struct_string (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	gchar **target;
	const gsize num_str_len = 32;

	target = (gchar **)(((gchar *)pd->user_struct) + pd->offset);
	switch (obj->type) {
	case UCL_STRING:
		*target =
			rspamd_mempool_strdup (pool, ucl_copy_value_trash (obj));
		break;
	case UCL_INT:
		*target = rspamd_mempool_alloc (pool, num_str_len);
		rspamd_snprintf (*target, num_str_len, "%L", obj->value.iv);
		break;
	case UCL_FLOAT:
		*target = rspamd_mempool_alloc (pool, num_str_len);
		rspamd_snprintf (*target, num_str_len, "%f", obj->value.dv);
		break;
	case UCL_BOOLEAN:
		*target = rspamd_mempool_alloc (pool, num_str_len);
		rspamd_snprintf (*target, num_str_len, "%B", (gboolean)obj->value.iv);
		break;
	default:
		g_set_error (err,
			CFG_RCL_ERROR,
			EINVAL,
			"cannot convert object or array to string");
		return FALSE;
	}

	return TRUE;
}

gboolean
rspamd_rcl_parse_struct_integer (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	union {
		gint *ip;
		gint32 *i32p;
		gint16 *i16p;
		gint64 *i64p;
		guint *up;
		gsize *sp;
	} target;
	int64_t val;

	if (pd->flags == RSPAMD_CL_FLAG_INT_32) {
		target.i32p = (gint32 *)(((gchar *)pd->user_struct) + pd->offset);
		if (!ucl_object_toint_safe (obj, &val)) {
			g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"cannot convert param to integer");
			return FALSE;
		}
		*target.i32p = val;
	}
	else if (pd->flags == RSPAMD_CL_FLAG_INT_64) {
		target.i64p = (gint64 *)(((gchar *)pd->user_struct) + pd->offset);
		if (!ucl_object_toint_safe (obj, &val)) {
			g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"cannot convert param to integer");
			return FALSE;
		}
		*target.i64p = val;
	}
	else if (pd->flags == RSPAMD_CL_FLAG_INT_SIZE) {
		target.sp = (gsize *)(((gchar *)pd->user_struct) + pd->offset);
		if (!ucl_object_toint_safe (obj, &val)) {
			g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"cannot convert param to integer");
			return FALSE;
		}
		*target.sp = val;
	}
	else if (pd->flags == RSPAMD_CL_FLAG_INT_16) {
		target.i16p = (gint16 *)(((gchar *)pd->user_struct) + pd->offset);
		if (!ucl_object_toint_safe (obj, &val)) {
			g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"cannot convert param to integer");
			return FALSE;
		}
		*target.i16p = val;
	}
	else if (pd->flags == RSPAMD_CL_FLAG_UINT) {
		target.up = (guint *)(((gchar *)pd->user_struct) + pd->offset);
		if (!ucl_object_toint_safe (obj, &val)) {
			g_set_error (err,
					CFG_RCL_ERROR,
					EINVAL,
					"cannot convert param to integer");
			return FALSE;
		}
		*target.up = val;
	}
	else {
		target.ip = (gint *)(((gchar *)pd->user_struct) + pd->offset);
		if (!ucl_object_toint_safe (obj, &val)) {
			g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"cannot convert param to integer");
			return FALSE;
		}
		*target.ip = val;
	}

	return TRUE;
}

gboolean
rspamd_rcl_parse_struct_double (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	gdouble *target;

	target = (gdouble *)(((gchar *)pd->user_struct) + pd->offset);

	if (!ucl_object_todouble_safe (obj, target)) {
		g_set_error (err,
			CFG_RCL_ERROR,
			EINVAL,
			"cannot convert param %s to double", ucl_object_key (obj));
		return FALSE;
	}

	return TRUE;
}

gboolean
rspamd_rcl_parse_struct_time (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	union {
		gint *psec;
		guint32 *pu32;
		gdouble *pdv;
		struct timeval *ptv;
		struct timespec *pts;
	} target;
	gdouble val;

	if (!ucl_object_todouble_safe (obj, &val)) {
		g_set_error (err,
			CFG_RCL_ERROR,
			EINVAL,
				"cannot convert param %s to double", ucl_object_key (obj));
		return FALSE;
	}

	if (pd->flags == RSPAMD_CL_FLAG_TIME_TIMEVAL) {
		target.ptv =
			(struct timeval *)(((gchar *)pd->user_struct) + pd->offset);
		target.ptv->tv_sec = (glong)val;
		target.ptv->tv_usec = (val - (glong)val) * 1000000;
	}
	else if (pd->flags == RSPAMD_CL_FLAG_TIME_TIMESPEC) {
		target.pts =
			(struct timespec *)(((gchar *)pd->user_struct) + pd->offset);
		target.pts->tv_sec = (glong)val;
		target.pts->tv_nsec = (val - (glong)val) * 1000000000000LL;
	}
	else if (pd->flags == RSPAMD_CL_FLAG_TIME_FLOAT) {
		target.pdv = (double *)(((gchar *)pd->user_struct) + pd->offset);
		*target.pdv = val;
	}
	else if (pd->flags == RSPAMD_CL_FLAG_TIME_INTEGER) {
		target.psec = (gint *)(((gchar *)pd->user_struct) + pd->offset);
		*target.psec = val * 1000;
	}
	else if (pd->flags == RSPAMD_CL_FLAG_TIME_UINT_32) {
		target.pu32 = (guint32 *)(((gchar *)pd->user_struct) + pd->offset);
		*target.pu32 = val * 1000;
	}
	else {
		g_set_error (err,
			CFG_RCL_ERROR,
			EINVAL,
			"invalid flags to parse time value in %s", ucl_object_key (obj));
		return FALSE;
	}

	return TRUE;
}

gboolean
rspamd_rcl_parse_struct_keypair (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	struct rspamd_cryptobox_keypair **target, *kp;

	target = (struct rspamd_cryptobox_keypair **)(((gchar *)pd->user_struct) +
			pd->offset);
	if (obj->type == UCL_OBJECT) {
		kp = rspamd_keypair_from_ucl (obj);

		if (kp != NULL) {
			rspamd_mempool_add_destructor (pool,
					(rspamd_mempool_destruct_t)rspamd_keypair_unref, kp);
			*target = kp;
		}
		else {
			g_set_error (err,
					CFG_RCL_ERROR,
					EINVAL,
					"cannot load the keypair specified: %s",
					ucl_object_key (obj));
			return FALSE;
		}
	}
	else {
		g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"no sane pubkey or privkey found in the keypair: %s",
				ucl_object_key (obj));
		return FALSE;
	}

	return TRUE;
}

gboolean
rspamd_rcl_parse_struct_pubkey (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	struct rspamd_cryptobox_pubkey **target, *pk;
	gsize len;
	const gchar *str;
	gint keypair_type = RSPAMD_KEYPAIR_KEX,
			keypair_mode = RSPAMD_CRYPTOBOX_MODE_25519;

	if (pd->flags & RSPAMD_CL_FLAG_SIGNKEY) {
		keypair_type = RSPAMD_KEYPAIR_SIGN;
	}
	if (pd->flags & RSPAMD_CL_FLAG_NISTKEY) {
		keypair_mode = RSPAMD_CRYPTOBOX_MODE_NIST;
	}

	target = (struct rspamd_cryptobox_pubkey **)(((gchar *)pd->user_struct) +
			pd->offset);
	if (obj->type == UCL_STRING) {
		str = ucl_object_tolstring (obj, &len);
		pk = rspamd_pubkey_from_base32 (str, len, keypair_type,
				keypair_mode);

		if (pk != NULL) {
			*target = pk;
		}
		else {
			g_set_error (err,
					CFG_RCL_ERROR,
					EINVAL,
					"cannot load the pubkey specified: %s",
					ucl_object_key (obj));
			return FALSE;
		}
	}
	else {
		g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"no sane pubkey found in the element: %s",
				ucl_object_key (obj));
		return FALSE;
	}

	rspamd_mempool_add_destructor (pool,
			(rspamd_mempool_destruct_t)rspamd_pubkey_unref, pk);

	return TRUE;
}

static void
rspamd_rcl_insert_string_list_item (gpointer *target, rspamd_mempool_t *pool,
		const gchar *src, gboolean is_hash)
{
	union {
		GHashTable *hv;
		GList *lv;
		gpointer p;
	} d;
	gchar *val;

	d.p = *target;

	if (is_hash) {
		if (d.hv == NULL) {
			d.hv = g_hash_table_new (rspamd_str_hash, rspamd_str_equal);
			rspamd_mempool_add_destructor (pool,
					(rspamd_mempool_destruct_t)g_hash_table_unref, d.hv);
		}

		val = rspamd_mempool_strdup (pool, src);
		g_hash_table_insert (d.hv, val, val);
	}
	else {
		val = rspamd_mempool_strdup (pool, src);
		d.lv = g_list_prepend (d.lv, val);
	}

	*target = d.p;
}

gboolean
rspamd_rcl_parse_struct_string_list (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	gpointer *target;
	gchar *val, **strvec, **cvec;
	const ucl_object_t *cur;
	const gsize num_str_len = 32;
	ucl_object_iter_t iter = NULL;
	gboolean is_hash, need_destructor = TRUE;


	is_hash = pd->flags & RSPAMD_CL_FLAG_STRING_LIST_HASH;
	target = (gpointer *)(((gchar *)pd->user_struct) + pd->offset);

	if (!is_hash && *target != NULL) {
		need_destructor = FALSE;
	}

	iter = ucl_object_iterate_new (obj);

	while ((cur = ucl_object_iterate_safe (iter, true)) != NULL) {
		switch (cur->type) {
		case UCL_STRING:
			strvec = g_strsplit_set (ucl_object_tostring (cur), ",", -1);
			cvec = strvec;

			while (*cvec) {
				rspamd_rcl_insert_string_list_item (target, pool, *cvec, is_hash);
				cvec ++;
			}

			g_strfreev (strvec);
			/* Go to the next object */
			continue;
		case UCL_INT:
			val = rspamd_mempool_alloc (pool, num_str_len);
			rspamd_snprintf (val, num_str_len, "%L", cur->value.iv);
			break;
		case UCL_FLOAT:
			val = rspamd_mempool_alloc (pool, num_str_len);
			rspamd_snprintf (val, num_str_len, "%f", cur->value.dv);
			break;
		case UCL_BOOLEAN:
			val = rspamd_mempool_alloc (pool, num_str_len);
			rspamd_snprintf (val, num_str_len, "%B", (gboolean)cur->value.iv);
			break;
		default:
			g_set_error (err,
					CFG_RCL_ERROR,
					EINVAL,
					"cannot convert an object or array to string: %s",
					ucl_object_key (obj));
			ucl_object_iterate_free (iter);

			return FALSE;
		}

		rspamd_rcl_insert_string_list_item (target, pool, val, is_hash);
	}

	ucl_object_iterate_free (iter);

	if (*target == NULL) {
		g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"non-empty array of strings is expected: %s, "
				"got: %s, of length: %d",
				ucl_object_key (obj), ucl_object_type_to_string (obj->type),
				obj->len);
		return FALSE;
	}

	if (!is_hash && *target != NULL) {
		*target = g_list_reverse (*target);

		if (need_destructor) {
			rspamd_mempool_add_destructor (pool,
					(rspamd_mempool_destruct_t) g_list_free,
					*target);
		}
	}

	return TRUE;
}

gboolean
rspamd_rcl_parse_struct_ucl (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	const ucl_object_t **target;

	target = (const ucl_object_t **)(((gchar *)pd->user_struct) + pd->offset);

	*target = obj;

	return TRUE;
}

gboolean
rspamd_rcl_parse_struct_iplist (rspamd_mempool_t *pool,
		const ucl_object_t *obj,
		gpointer ud,
		struct rspamd_rcl_section *section,
		GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	radix_compressed_t **target;

	target = (radix_compressed_t **)(((gchar *)pd->user_struct) + pd->offset);

	return rspamd_config_radix_from_ucl (pd->cfg, obj,
			ucl_object_key (obj), target, err);
}


gboolean
rspamd_rcl_parse_struct_boolean (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	gboolean *target;

	target = (gboolean *)(((gchar *)pd->user_struct) + pd->offset);

	if (obj->type == UCL_BOOLEAN) {
		*target = obj->value.iv;
	}
	else if (obj->type == UCL_INT) {
		*target = obj->value.iv;
	}
	else {
		g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"cannot convert an object to boolean: %s",
				ucl_object_key (obj));
		return FALSE;
	}

	if (pd->flags & RSPAMD_CL_FLAG_BOOLEAN_INVERSE) {
		*target = !*target;
	}

	return TRUE;
}

gboolean
rspamd_rcl_parse_struct_addr (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	rspamd_inet_addr_t **target;
	const gchar *val;

	target = (rspamd_inet_addr_t **)(((gchar *)pd->user_struct) + pd->offset);

	if (ucl_object_type (obj) == UCL_STRING) {
		val = ucl_object_tostring (obj);

		if (!rspamd_parse_inet_address (target, val, 0)) {
			g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"cannot parse inet address: %s", val);
			return FALSE;
		}
	}
	else {
		g_set_error (err,
				CFG_RCL_ERROR,
				EINVAL,
				"cannot convert an object to inet address: %s",
				ucl_object_key (obj));
		return FALSE;
	}

	return TRUE;
}

gboolean
rspamd_rcl_parse_struct_mime_addr (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_rcl_struct_parser *pd = ud;
	GPtrArray **target, *tmp_addr = NULL;
	const gchar *val;
	ucl_object_iter_t it;
	const ucl_object_t *cur;

	target = (GPtrArray **)(((gchar *)pd->user_struct) + pd->offset);
	it = ucl_object_iterate_new (obj);

	while ((cur = ucl_object_iterate_safe (it, true)) != NULL) {
		if (ucl_object_type (cur) == UCL_STRING) {
			val = ucl_object_tostring (obj);
			tmp_addr = rspamd_email_address_from_mime (pool, val,
					strlen (val), tmp_addr);
		}
		else {
			g_set_error (err,
					CFG_RCL_ERROR,
					EINVAL,
					"cannot get inet address from ucl object in %s",
					ucl_object_key (obj));
			ucl_object_iterate_free (it);

			return FALSE;
		}
	}

	ucl_object_iterate_free (it);
	*target = tmp_addr;

	return TRUE;
}

static guint
rspamd_worker_param_key_hash (gconstpointer p)
{
	const struct rspamd_worker_param_key *k = p;
	rspamd_cryptobox_fast_hash_state_t st;

	rspamd_cryptobox_fast_hash_init (&st, rspamd_hash_seed ());
	rspamd_cryptobox_fast_hash_update (&st, k->name, strlen (k->name));
	rspamd_cryptobox_fast_hash_update (&st, &k->ptr, sizeof (gpointer));

	return rspamd_cryptobox_fast_hash_final (&st);
}

static gboolean
rspamd_worker_param_key_equal (gconstpointer p1, gconstpointer p2)
{
	const struct rspamd_worker_param_key *k1 = p1, *k2 = p2;

	if (k1->ptr == k2->ptr) {
		return strcmp (k1->name, k2->name) == 0;
	}

	return FALSE;
}

void
rspamd_rcl_register_worker_option (struct rspamd_config *cfg,
		GQuark type,
		const gchar *name,
		rspamd_rcl_default_handler_t handler,
		gpointer target,
		glong offset,
		gint flags,
		const gchar *doc_string)
{
	struct rspamd_worker_param_parser *nhandler;
	struct rspamd_worker_cfg_parser *nparser;
	struct rspamd_worker_param_key srch;
	const ucl_object_t *doc_workers, *doc_target;
	ucl_object_t *doc_obj;

	nparser = g_hash_table_lookup (cfg->wrk_parsers, &type);

	if (nparser == NULL) {
		rspamd_rcl_register_worker_parser (cfg, type, NULL, NULL);
		nparser = g_hash_table_lookup (cfg->wrk_parsers, &type);

		g_assert (nparser != NULL);
	}

	srch.name = name;
	srch.ptr = target;

	nhandler = g_hash_table_lookup (nparser->parsers, &srch);
	if (nhandler != NULL) {
		msg_warn_config (
			"handler for parameter %s is already registered for worker type %s",
			name,
			g_quark_to_string (type));
		return;
	}

	nhandler =
		rspamd_mempool_alloc0 (cfg->cfg_pool,
			sizeof (struct rspamd_worker_param_parser));
	nhandler->key.name = name;
	nhandler->key.ptr = target;
	nhandler->parser.flags = flags;
	nhandler->parser.offset = offset;
	nhandler->parser.user_struct = target;
	nhandler->handler = handler;

	g_hash_table_insert (nparser->parsers, &nhandler->key, nhandler);

	doc_workers = ucl_object_lookup (cfg->doc_strings, "workers");

	if (doc_workers == NULL) {
		doc_obj = ucl_object_typed_new (UCL_OBJECT);
		ucl_object_insert_key (cfg->doc_strings, doc_obj, "workers", 0, false);
		doc_workers = doc_obj;
	}

	doc_target = ucl_object_lookup (doc_workers, g_quark_to_string (type));

	if (doc_target == NULL) {
		doc_obj = ucl_object_typed_new (UCL_OBJECT);
		ucl_object_insert_key ((ucl_object_t *)doc_workers, doc_obj,
				g_quark_to_string (type), 0, true);
		doc_target = doc_obj;
	}

	rspamd_rcl_add_doc_obj ((ucl_object_t *) doc_target,
			doc_string,
			name,
			UCL_NULL,
			handler,
			flags,
			NULL,
			0);
}


void
rspamd_rcl_register_worker_parser (struct rspamd_config *cfg, gint type,
	gboolean (*func)(ucl_object_t *, gpointer), gpointer ud)
{
	struct rspamd_worker_cfg_parser *nparser;

	nparser = g_hash_table_lookup (cfg->wrk_parsers, &type);

	if (nparser == NULL) {
		/* Allocate new parser for this worker */
		nparser =
			rspamd_mempool_alloc0 (cfg->cfg_pool,
				sizeof (struct rspamd_worker_cfg_parser));
		nparser->type = type;
		nparser->parsers = g_hash_table_new (rspamd_worker_param_key_hash,
				rspamd_worker_param_key_equal);
		rspamd_mempool_add_destructor (cfg->cfg_pool,
				(rspamd_mempool_destruct_t)g_hash_table_unref, nparser->parsers);

		g_hash_table_insert (cfg->wrk_parsers, &nparser->type, nparser);
	}

	nparser->def_obj_parser = func;
	nparser->def_ud = ud;
}

/* Checksum functions */
static int
rspamd_rcl_emitter_append_c (unsigned char c, size_t nchars, void *ud)
{
	rspamd_cryptobox_hash_state_t *hs = ud;
	guint64 d[2];

	d[0] = nchars;
	d[1] = c;

	rspamd_cryptobox_hash_update (hs, (const guchar *)d, sizeof (d));

	return 0;
}

static int
rspamd_rcl_emitter_append_len (unsigned const char *str, size_t len, void *ud)
{
	rspamd_cryptobox_hash_state_t *hs = ud;

	rspamd_cryptobox_hash_update (hs, str, len);

	return 0;
}
static int
rspamd_rcl_emitter_append_int (int64_t elt, void *ud)
{
	rspamd_cryptobox_hash_state_t *hs = ud;

	rspamd_cryptobox_hash_update (hs, (const guchar *)&elt, sizeof (elt));

	return 0;
}

static int
rspamd_rcl_emitter_append_double (double elt, void *ud)
{
	rspamd_cryptobox_hash_state_t *hs = ud;

	rspamd_cryptobox_hash_update (hs, (const guchar *)&elt, sizeof (elt));

	return 0;
}

static void
rspamd_rcl_section_free (gpointer p)
{
	struct rspamd_rcl_section *top = p, *cur, *tmp;
	struct rspamd_rcl_default_handler_data *dh, *dhtmp;

	HASH_ITER (hh, top, cur, tmp) {
		HASH_DEL (top, cur);

		if (cur->subsections) {
			rspamd_rcl_section_free (cur->subsections);
		}

		HASH_ITER (hh, cur->default_parser, dh, dhtmp) {
			HASH_DEL (cur->default_parser, dh);
			g_free (dh->key);
			g_free (dh);
		}

		ucl_object_unref (cur->doc_ref);
		g_free (cur);
	}
}

/**
 * Calls for an external lua function to apply potential config transformations
 * if needed. This function can change the cfg->rcl_obj.
 *
 * Example of transformation function:
 *
 * function(obj)
 *   if obj.something == 'foo' then
 *     obj.something = "bla"
 *     return true, obj
 *   end
 *
 *   return false, nil
 * end
 *
 * If function returns 'false' then rcl_obj is not touched. Otherwise,
 * it is changed, then rcl_obj is imported from lua. Old config is dereferenced.
 * @param cfg
 */
static void
rspamd_rcl_maybe_apply_lua_transform (struct rspamd_config *cfg)
{
	lua_State *L = cfg->lua_state;
	gint err_idx, ret;
	GString *tb;
	gchar str[PATH_MAX];
	static const char *transform_script = "lua_cfg_transform";

	g_assert (L != NULL);

	rspamd_snprintf (str, sizeof (str), "return require \"%s\"",
			transform_script);

	if (luaL_dostring (L, str) != 0) {
		msg_warn_config ("cannot execute lua script %s: %s",
				str, lua_tostring (L, -1));
		return;
	}
	else {
		if (lua_type (L, -1) != LUA_TFUNCTION) {
			msg_warn_config ("lua script must return "
					"function and not %s",
					lua_typename (L, lua_type (L, -1)));

			return;
		}
	}

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

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

	/* Push the existing config */
	ucl_object_push_lua (L, cfg->rcl_obj, true);

	if ((ret = lua_pcall (L, 1, 2, err_idx)) != 0) {
		tb = lua_touserdata (L, -1);
		msg_err ("call to rspamadm lua script failed (%d): %v", ret, tb);

		if (tb) {
			g_string_free (tb, TRUE);
		}

		lua_settop (L, 0);

		return;
	}

	if (lua_toboolean (L, -2) && lua_type (L, -1) == LUA_TTABLE) {
		ucl_object_t *old_cfg = cfg->rcl_obj;

		msg_info_config ("configuration has been transformed in Lua");
		cfg->rcl_obj = ucl_object_lua_import (L, -1);
		ucl_object_unref (old_cfg);
	}

	/* error function */
	lua_settop (L, 0);
}

gboolean
rspamd_config_read (struct rspamd_config *cfg, const gchar *filename,
	const gchar *convert_to, rspamd_rcl_section_fin_t logger_fin,
	gpointer logger_ud, GHashTable *vars)
{
	struct stat st;
	gint fd;
	gchar *data;
	GError *err = NULL;
	struct rspamd_rcl_section *top, *logger_section;
	struct ucl_parser *parser;
	const ucl_object_t *logger_obj;
	rspamd_cryptobox_hash_state_t hs;
	unsigned char cksumbuf[rspamd_cryptobox_HASHBYTES];
	struct ucl_emitter_functions f;

	if (stat (filename, &st) == -1) {
		msg_err_config_forced ("cannot stat %s: %s", filename, strerror (errno));
		return FALSE;
	}
	if ((fd = open (filename, O_RDONLY)) == -1) {
		msg_err_config_forced ("cannot open %s: %s", filename, strerror (errno));
		return FALSE;

	}
	/* Now mmap this file to simplify reading process */
	if ((data =
		mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
		msg_err_config_forced ("cannot mmap %s: %s", filename, strerror (errno));
		close (fd);
		return FALSE;
	}

	close (fd);

	rspamd_cryptobox_hash_init (&hs, NULL, 0);
	parser = ucl_parser_new (UCL_PARSER_SAVE_COMMENTS);
	rspamd_ucl_add_conf_variables (parser, vars);
	rspamd_ucl_add_conf_macros (parser, cfg);

	if (!ucl_parser_add_chunk (parser, data, st.st_size)) {
		msg_err_config_forced ("ucl parser error: %s", ucl_parser_get_error (parser));
		ucl_parser_free (parser);
		munmap (data, st.st_size);
		return FALSE;
	}

	munmap (data, st.st_size);
	cfg->rcl_obj = ucl_parser_get_object (parser);
	cfg->config_comments = ucl_object_ref (ucl_parser_get_comments (parser));
	ucl_parser_free (parser);

	top = rspamd_rcl_config_init (cfg);
	rspamd_lua_set_path (cfg->lua_state, cfg->rcl_obj, vars);
	rspamd_rcl_set_lua_globals (cfg, cfg->lua_state, vars);
	rspamd_mempool_add_destructor (cfg->cfg_pool, rspamd_rcl_section_free, top);
	err = NULL;

	if (logger_fin != NULL) {
		HASH_FIND_STR (top, "logging", logger_section);

		if (logger_section != NULL) {
			logger_obj = ucl_object_lookup_any (cfg->rcl_obj, "logging",
					"logger", NULL);

			if (logger_obj == NULL) {
				logger_fin (cfg->cfg_pool, logger_ud);
			}
			else {
				if (!rspamd_rcl_process_section (cfg, logger_section, cfg,
						logger_obj, cfg->cfg_pool, &err)) {
					msg_err_config_forced ("cannot init logger: %e", err);
					g_error_free (err);

					return FALSE;
				} else {
					logger_fin (cfg->cfg_pool, logger_ud);
				}
			}

			HASH_DEL (top, logger_section);
		}
	}

	/* Transform config if needed */
	rspamd_rcl_maybe_apply_lua_transform (cfg);

	/* Calculate checksum */
	f.ucl_emitter_append_character = rspamd_rcl_emitter_append_c;
	f.ucl_emitter_append_double = rspamd_rcl_emitter_append_double;
	f.ucl_emitter_append_int = rspamd_rcl_emitter_append_int;
	f.ucl_emitter_append_len = rspamd_rcl_emitter_append_len;
	f.ucl_emitter_free_func = NULL;
	f.ud = &hs;
	ucl_object_emit_full (cfg->rcl_obj, UCL_EMIT_MSGPACK,
			&f, cfg->config_comments);
	rspamd_cryptobox_hash_final (&hs, cksumbuf);
	cfg->checksum = rspamd_encode_base32 (cksumbuf, sizeof (cksumbuf));
	/* Also change the tag of cfg pool to be equal to the checksum */
	rspamd_strlcpy (cfg->cfg_pool->tag.uid, cfg->checksum,
			MIN (sizeof (cfg->cfg_pool->tag.uid), strlen (cfg->checksum)));


	if (!rspamd_rcl_parse (top, cfg, cfg, cfg->cfg_pool, cfg->rcl_obj, &err)) {
		msg_err_config ("rcl parse error: %e", err);
		g_error_free (err);
		return FALSE;
	}

	cfg->lang_det = rspamd_language_detector_init (cfg);

	return TRUE;
}

static void
rspamd_rcl_doc_obj_from_handler (ucl_object_t *doc_obj,
		rspamd_rcl_default_handler_t handler,
		gint flags)
{
	gboolean has_example = FALSE, has_type = FALSE;
	const gchar *type = NULL;

	if (ucl_object_lookup (doc_obj, "example") != NULL) {
		has_example = TRUE;
	}

	if (ucl_object_lookup (doc_obj, "type") != NULL) {
		has_type = TRUE;
	}

	if (handler == rspamd_rcl_parse_struct_string) {
		if (!has_type) {
			ucl_object_insert_key (doc_obj, ucl_object_fromstring ("string"),
					"type", 0, false);
		}
	}
	else if (handler == rspamd_rcl_parse_struct_integer) {
		type = "int";

		if (flags & RSPAMD_CL_FLAG_INT_16) {
			type = "int16";
		}
		else if (flags & RSPAMD_CL_FLAG_INT_32) {
			type = "int32";
		}
		else if (flags & RSPAMD_CL_FLAG_INT_64) {
			type = "int64";
		}
		else if (flags & RSPAMD_CL_FLAG_INT_SIZE) {
			type = "size";
		}
		else if (flags & RSPAMD_CL_FLAG_UINT) {
			type = "uint";
		}

		if (!has_type) {
			ucl_object_insert_key (doc_obj, ucl_object_fromstring (type),
					"type", 0, false);
		}
	}
	else if (handler == rspamd_rcl_parse_struct_double) {
		if (!has_type) {
			ucl_object_insert_key (doc_obj, ucl_object_fromstring ("double"),
					"type", 0, false);
		}
	}
	else if (handler == rspamd_rcl_parse_struct_time) {
		type = "time";

		if (!has_type) {
			ucl_object_insert_key (doc_obj, ucl_object_fromstring (type),
					"type", 0, false);
		}
	}
	else if (handler == rspamd_rcl_parse_struct_string_list) {
		if (!has_type) {
			ucl_object_insert_key (doc_obj, ucl_object_fromstring ("string list"),
					"type", 0, false);
		}
		if (!has_example) {
			ucl_object_insert_key (doc_obj,
					ucl_object_fromstring_common ("param = \"str1, str2, str3\" OR "
							"param = [\"str1\", \"str2\", \"str3\"]", 0, 0),
					"example",
					0,
					false);
		}
	}
	else if (handler == rspamd_rcl_parse_struct_boolean) {
		if (!has_type) {
			ucl_object_insert_key (doc_obj,
					ucl_object_fromstring ("bool"),
					"type",
					0,
					false);
		}
	}
	else if (handler == rspamd_rcl_parse_struct_keypair) {
		if (!has_type) {
			ucl_object_insert_key (doc_obj,
					ucl_object_fromstring ("keypair"),
					"type",
					0,
					false);
		}
		if (!has_example) {
			ucl_object_insert_key (doc_obj,
					ucl_object_fromstring ("keypair { "
							"pubkey = <base32_string>;"
							" privkey = <base32_string>; "
							"}"),
					"example",
					0,
					false);
		}
	}
	else if (handler == rspamd_rcl_parse_struct_addr) {
		if (!has_type) {
			ucl_object_insert_key (doc_obj,
					ucl_object_fromstring ("socket address"),
					"type",
					0,
					false);
		}
	}
	else if (handler == rspamd_rcl_parse_struct_mime_addr) {
		if (!has_type) {
			ucl_object_insert_key (doc_obj,
					ucl_object_fromstring ("email address"),
					"type",
					0,
					false);
		}
	}
}

ucl_object_t *
rspamd_rcl_add_doc_obj (ucl_object_t *doc_target,
		const char *doc_string,
		const char *doc_name,
		ucl_type_t type,
		rspamd_rcl_default_handler_t handler,
		gint flags,
		const char *default_value,
		gboolean required)
{
	ucl_object_t *doc_obj;

	if (doc_target == NULL || doc_name == NULL) {
		return NULL;
	}

	doc_obj = ucl_object_typed_new (UCL_OBJECT);

	/* Insert doc string itself */
	if (doc_string) {
		ucl_object_insert_key (doc_obj,
				ucl_object_fromstring_common (doc_string, 0, 0),
				"data", 0, false);
	}
	else {
		ucl_object_insert_key (doc_obj, ucl_object_fromstring ("undocumented"),
				"data", 0, false);
	}

	if (type != UCL_NULL) {
		ucl_object_insert_key (doc_obj,
				ucl_object_fromstring (ucl_object_type_to_string (type)),
				"type", 0, false);
	}

	rspamd_rcl_doc_obj_from_handler (doc_obj, handler, flags);

	ucl_object_insert_key (doc_obj,
			ucl_object_frombool (required),
			"required", 0, false);

	if (default_value) {
		ucl_object_insert_key (doc_obj,
				ucl_object_fromstring_common (default_value, 0, 0),
				"default", 0, false);
	}

	ucl_object_insert_key (doc_target, doc_obj, doc_name, 0, true);

	return doc_obj;
}

ucl_object_t *
rspamd_rcl_add_doc_by_path (struct rspamd_config *cfg,
		const gchar *doc_path,
		const char *doc_string,
		const char *doc_name,
		ucl_type_t type,
		rspamd_rcl_default_handler_t handler,
		gint flags,
		const char *default_value,
		gboolean required)
{
	const ucl_object_t *found, *cur;
	ucl_object_t *obj;
	gchar **path_components, **comp;

	if (doc_path == NULL) {
		/* Assume top object */
		return rspamd_rcl_add_doc_obj (cfg->doc_strings,
				doc_string,
				doc_name,
				type,
				handler,
				flags,
				default_value,
				required);
	}
	else {
		found = ucl_object_lookup_path (cfg->doc_strings, doc_path);

		if (found != NULL) {
			return rspamd_rcl_add_doc_obj ((ucl_object_t *) found,
					doc_string,
					doc_name,
					type,
					handler,
					flags,
					default_value,
					required);
		}

		/* Otherwise we need to insert all components of the path */
		path_components = g_strsplit_set (doc_path, ".", -1);
		cur = cfg->doc_strings;

		for (comp = path_components; *comp != NULL; comp++) {
			if (ucl_object_type (cur) != UCL_OBJECT) {
				msg_err_config ("Bad path while lookup for '%s' at %s",
						doc_path, *comp);
				return NULL;
			}

			found = ucl_object_lookup (cur, *comp);

			if (found == NULL) {
				obj = ucl_object_typed_new (UCL_OBJECT);
				ucl_object_insert_key ((ucl_object_t *) cur,
						obj,
						*comp,
						0,
						true);
				cur = obj;
			}
			else {
				cur = found;
			}
		}
	}

	return rspamd_rcl_add_doc_obj (ucl_object_ref (cur),
			doc_string,
			doc_name,
			type,
			handler,
			flags,
			default_value,
			required);
}

static void
rspamd_rcl_add_doc_from_comments (struct rspamd_config *cfg,
		ucl_object_t *top_doc, const ucl_object_t *obj,
		const ucl_object_t *comments, gboolean is_top)
{
	ucl_object_iter_t it = NULL;
	const ucl_object_t *cur, *cmt;
	ucl_object_t *cur_doc;

	if (ucl_object_type (obj) == UCL_OBJECT) {
		while ((cur = ucl_object_iterate (obj, &it, true)) != NULL) {
			cur_doc = NULL;

			if ((cmt = ucl_comments_find (comments, cur)) != NULL) {
				cur_doc = rspamd_rcl_add_doc_obj (top_doc,
						ucl_object_tostring (cmt), ucl_object_key (cur),
						ucl_object_type (cur), NULL, 0, NULL, FALSE);
			}

			if (ucl_object_type (cur) == UCL_OBJECT) {
				if (cur_doc) {
					rspamd_rcl_add_doc_from_comments (cfg, cur_doc, cur,
							comments,
							FALSE);
				}
				else {
					rspamd_rcl_add_doc_from_comments (cfg, top_doc, cur,
							comments,
							FALSE);
				}
			}
		}
	}
	else if (!is_top) {
		if ((cmt = ucl_comments_find (comments, obj)) != NULL) {
			rspamd_rcl_add_doc_obj (top_doc,
					ucl_object_tostring (cmt), ucl_object_key (obj),
					ucl_object_type (obj), NULL, 0, NULL, FALSE);
		}

	}
}

ucl_object_t *
rspamd_rcl_add_doc_by_example (struct rspamd_config *cfg,
		const gchar *root_path,
		const gchar *doc_string,
		const gchar *doc_name,
		const gchar *example_data, gsize example_len)
{
	struct ucl_parser *parser;
	ucl_object_t *top, *top_doc;
	const ucl_object_t *comments;

	parser = ucl_parser_new (UCL_PARSER_NO_FILEVARS|UCL_PARSER_SAVE_COMMENTS);

	if (!ucl_parser_add_chunk (parser, example_data, example_len)) {
		msg_err_config ("cannot parse example: %s",
				ucl_parser_get_error (parser));
		ucl_parser_free (parser);

		return NULL;
	}

	top = ucl_parser_get_object (parser);
	comments = ucl_parser_get_comments (parser);

	/* Add top object */
	top_doc = rspamd_rcl_add_doc_by_path (cfg, root_path, doc_string,
			doc_name, ucl_object_type (top), NULL, 0, NULL, FALSE);
	ucl_object_insert_key (top_doc,
			ucl_object_fromstring_common (example_data, example_len, 0),
			"example", 0, false);

	rspamd_rcl_add_doc_from_comments (cfg, top_doc, top, comments, TRUE);

	return top_doc;
}