aboutsummaryrefslogtreecommitdiffstats
path: root/src/libserver/maps/map.c
blob: b0801cbf3bcec7f4523242ccdf132526aaa55e18 (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
/*-
 * Copyright 2019 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.
 */
/*
 * Implementation of map files handling
 */

#include "config.h"
#include "map.h"
#include "map_private.h"
#include "libserver/http/http_connection.h"
#include "libserver/http/http_private.h"
#include "rspamd.h"
#include "contrib/zstd/zstd.h"
#include "contrib/libev/ev.h"
#include "contrib/uthash/utlist.h"

#undef MAP_DEBUG_REFS
#ifdef MAP_DEBUG_REFS
#define MAP_RETAIN(x, t) do { \
	msg_err (G_GNUC_PRETTY_FUNCTION ": " t ": retain ref %p, refcount: %d -> %d", (x), (x)->ref.refcount, (x)->ref.refcount + 1); \
	REF_RETAIN(x);	\
} while (0)

#define MAP_RELEASE(x, t) do { \
	msg_err (G_GNUC_PRETTY_FUNCTION ": " t ": release ref %p, refcount: %d -> %d", (x), (x)->ref.refcount, (x)->ref.refcount - 1); \
	REF_RELEASE(x);	\
} while (0)
#else
#define MAP_RETAIN(x, t) REF_RETAIN(x)
#define MAP_RELEASE(x, t) REF_RELEASE(x)
#endif

enum rspamd_map_periodic_opts {
	RSPAMD_MAP_SCHEDULE_NORMAL = 0,
	RSPAMD_MAP_SCHEDULE_ERROR = (1u << 0u),
	RSPAMD_MAP_SCHEDULE_LOCKED = (1u << 1u),
	RSPAMD_MAP_SCHEDULE_INIT = (1u << 2u),
};

static void free_http_cbdata_common (struct http_callback_data *cbd,
									 gboolean plan_new);
static void free_http_cbdata_dtor (gpointer p);
static void free_http_cbdata (struct http_callback_data *cbd);
static void rspamd_map_process_periodic (struct map_periodic_cbdata *cbd);
static void rspamd_map_schedule_periodic (struct rspamd_map *map, int how);
static gboolean read_map_file_chunks (struct rspamd_map *map,
									  struct map_cb_data *cbdata,
									  const gchar *fname,
									  gsize len,
									  goffset off);
static gboolean rspamd_map_save_http_cached_file (struct rspamd_map *map,
												  struct rspamd_map_backend *bk,
												  struct http_map_data *htdata,
												  const guchar *data,
												  gsize len);
static gboolean rspamd_map_update_http_cached_file (struct rspamd_map *map,
												  struct rspamd_map_backend *bk,
												  struct http_map_data *htdata);

guint rspamd_map_log_id = (guint)-1;
RSPAMD_CONSTRUCTOR(rspamd_map_log_init)
{
	rspamd_map_log_id = rspamd_logger_add_debug_module("map");
}

/**
 * Write HTTP request
 */
static void
write_http_request (struct http_callback_data *cbd)
{
	gchar datebuf[128];
	struct rspamd_http_message *msg;

	msg = rspamd_http_new_message (HTTP_REQUEST);

	if (cbd->bk->protocol == MAP_PROTO_HTTPS) {
		msg->flags |= RSPAMD_HTTP_FLAG_SSL;
	}

	if (cbd->check) {
		msg->method = HTTP_HEAD;
	}

	msg->url = rspamd_fstring_append (msg->url,
			cbd->data->path, strlen (cbd->data->path));

	if (cbd->check) {
		if (cbd->data->last_modified != 0) {
			rspamd_http_date_format (datebuf, sizeof (datebuf),
					cbd->data->last_modified);
			rspamd_http_message_add_header (msg, "If-Modified-Since",
					datebuf);
		}
		if (cbd->data->etag) {
			rspamd_http_message_add_header_len (msg, "If-None-Match",
					cbd->data->etag->str, cbd->data->etag->len);
		}
	}

	msg->url = rspamd_fstring_append (msg->url, cbd->data->rest,
			strlen (cbd->data->rest));

	if (cbd->data->userinfo) {
		rspamd_http_message_add_header (msg, "Authorization",
				cbd->data->userinfo);
	}

	MAP_RETAIN (cbd, "http_callback_data");
	rspamd_http_connection_write_message (cbd->conn,
			msg,
			cbd->data->host,
			NULL,
			cbd,
			cbd->timeout);
}

/**
 * Callback for destroying HTTP callback data
 */
static void
free_http_cbdata_common (struct http_callback_data *cbd, gboolean plan_new)
{
	struct map_periodic_cbdata *periodic = cbd->periodic;

	if (cbd->shmem_data) {
		rspamd_http_message_shmem_unref (cbd->shmem_data);
	}

	if (cbd->pk) {
		rspamd_pubkey_unref (cbd->pk);
	}

	if (cbd->conn) {
		rspamd_http_connection_unref (cbd->conn);
		cbd->conn = NULL;
	}

	if (cbd->addrs) {
		rspamd_inet_addr_t *addr;
		guint i;

		PTR_ARRAY_FOREACH (cbd->addrs, i, addr) {
			rspamd_inet_address_free (addr);
		}

		g_ptr_array_free (cbd->addrs, TRUE);
	}


	MAP_RELEASE (cbd->bk, "rspamd_map_backend");

	if (periodic) {
		/* Detached in case of HTTP error */
		MAP_RELEASE (periodic, "periodic");
	}

	g_free (cbd);
}

static void
free_http_cbdata (struct http_callback_data *cbd)
{
	cbd->map->tmp_dtor = NULL;
	cbd->map->tmp_dtor_data = NULL;

	free_http_cbdata_common (cbd, TRUE);
}

static void
free_http_cbdata_dtor (gpointer p)
{
	struct http_callback_data *cbd = p;
	struct rspamd_map *map;

	map = cbd->map;
	if (cbd->stage == http_map_http_conn) {
		REF_RELEASE (cbd);
	}
	else {
		/* We cannot terminate DNS requests sent */
		cbd->stage = http_map_terminated;
	}

	msg_warn_map ("%s: "
				  "connection with http server is terminated: worker is stopping",
			map->name);
}

/*
 * HTTP callbacks
 */
static void
http_map_error (struct rspamd_http_connection *conn,
	GError *err)
{
	struct http_callback_data *cbd = conn->ud;
	struct rspamd_map *map;

	map = cbd->map;

	if (cbd->periodic) {
		cbd->periodic->errored = TRUE;
		msg_err_map ("error reading %s(%s): "
					 "connection with http server terminated incorrectly: %e",
				cbd->bk->uri,
				cbd->addr ? rspamd_inet_address_to_string_pretty (cbd->addr) : "",
				err);

		rspamd_map_process_periodic (cbd->periodic);
	}

	MAP_RELEASE (cbd, "http_callback_data");
}

static void
rspamd_map_cache_cb (struct ev_loop *loop, ev_timer *w, int revents)
{
	struct rspamd_http_map_cached_cbdata *cache_cbd = (struct rspamd_http_map_cached_cbdata *)
			w->data;
	struct rspamd_map *map;
	struct http_map_data *data;

	map = cache_cbd->map;
	data = cache_cbd->data;

	if (cache_cbd->gen != cache_cbd->data->gen) {
		/* We have another update, so this cache element is obviously expired */
		/*
		 * Important!: we do not set cache availability to zero here, as there
		 * might be fresh cache
		 */
		msg_info_map ("cached data is now expired (gen mismatch %L != %L) for %s",
				cache_cbd->gen, cache_cbd->data->gen, map->name);
		MAP_RELEASE (cache_cbd->shm, "rspamd_http_map_cached_cbdata");
		ev_timer_stop (loop, &cache_cbd->timeout);
		g_free (cache_cbd);
	}
	else if (cache_cbd->data->last_checked >= cache_cbd->last_checked) {
		/*
		 * We checked map but we have not found anything more recent,
		 * reschedule cache check
		 */
		if (cache_cbd->map->poll_timeout >
			rspamd_get_calendar_ticks () - cache_cbd->data->last_checked) {
			w->repeat = cache_cbd->map->poll_timeout -
						(rspamd_get_calendar_ticks () - cache_cbd->data->last_checked);
		}
		else {
			w->repeat = cache_cbd->map->poll_timeout;
		}

		cache_cbd->last_checked = cache_cbd->data->last_checked;
		msg_debug_map ("cached data is up to date for %s", map->name);
		ev_timer_again (loop, &cache_cbd->timeout);
	}
	else {
		data->cur_cache_cbd = NULL;
		g_atomic_int_set (&data->cache->available, 0);
		MAP_RELEASE (cache_cbd->shm, "rspamd_http_map_cached_cbdata");
		msg_info_map ("cached data is now expired for %s", map->name);
		ev_timer_stop (loop, &cache_cbd->timeout);
		g_free (cache_cbd);
	}
}

static int
http_map_finish (struct rspamd_http_connection *conn,
		struct rspamd_http_message *msg)
{
	struct http_callback_data *cbd = conn->ud;
	struct rspamd_map *map;
	struct rspamd_map_backend *bk;
	struct http_map_data *data;
	struct rspamd_http_map_cached_cbdata *cache_cbd;
	const rspamd_ftok_t *expires_hdr, *etag_hdr;
	char next_check_date[128];
	guchar *in = NULL;
	gsize dlen = 0;

	map = cbd->map;
	bk = cbd->bk;
	data = bk->data.hd;

	if (msg->code == 200) {

		if (cbd->check) {
			msg_info_map ("need to reread map from %s", cbd->bk->uri);
			cbd->periodic->need_modify = TRUE;
			/* Reset the whole chain */
			cbd->periodic->cur_backend = 0;
			/* Reset cache, old cached data will be cleaned on timeout */
			g_atomic_int_set (&data->cache->available, 0);
			data->cur_cache_cbd = NULL;

			rspamd_map_process_periodic (cbd->periodic);
			MAP_RELEASE (cbd, "http_callback_data");

			return 0;
		}

		cbd->data->last_checked = msg->date;

		if (msg->last_modified) {
			cbd->data->last_modified = msg->last_modified;
		}
		else {
			cbd->data->last_modified = msg->date;
		}


		/* Unsigned version - just open file */
		cbd->shmem_data = rspamd_http_message_shmem_ref (msg);
		cbd->data_len = msg->body_buf.len;

		if (cbd->data_len == 0) {
			msg_err_map ("cannot read empty map");
			goto err;
		}

		g_assert (cbd->shmem_data != NULL);

		in = rspamd_shmem_xmap (cbd->shmem_data->shm_name, PROT_READ, &dlen);

		if (in == NULL) {
			msg_err_map ("cannot read tempfile %s: %s",
					cbd->shmem_data->shm_name,
					strerror (errno));
			goto err;
		}

		/* Check for expires */
		double cached_timeout = map->poll_timeout * 2;

		expires_hdr = rspamd_http_message_find_header (msg, "Expires");

		if (expires_hdr) {
			time_t hdate;

			hdate = rspamd_http_parse_date (expires_hdr->begin, expires_hdr->len);

			if (hdate != (time_t)-1 && hdate > msg->date) {
				cached_timeout = map->next_check - msg->date +
								 map->poll_timeout * 2;

				map->next_check = hdate;
			}
		}

		/* Check for etag */
		etag_hdr = rspamd_http_message_find_header (msg, "ETag");

		if (etag_hdr) {
			if (cbd->data->etag) {
				/* Remove old etag */
				rspamd_fstring_free (cbd->data->etag);
			}

			cbd->data->etag = rspamd_fstring_new_init (etag_hdr->begin,
					etag_hdr->len);
		}
		else {
			if (cbd->data->etag) {
				/* Remove and clear old etag */
				rspamd_fstring_free (cbd->data->etag);
				cbd->data->etag = NULL;
			}
		}

		MAP_RETAIN (cbd->shmem_data, "shmem_data");
		cbd->data->gen ++;
		/*
		 * We know that a map is in the locked state
		 */
		g_atomic_int_set (&data->cache->available, 1);
		/* Store cached data */
		rspamd_strlcpy (data->cache->shmem_name, cbd->shmem_data->shm_name,
				sizeof (data->cache->shmem_name));
		data->cache->len = cbd->data_len;
		data->cache->last_modified = cbd->data->last_modified;
		cache_cbd = g_malloc0 (sizeof (*cache_cbd));
		cache_cbd->shm = cbd->shmem_data;
		cache_cbd->event_loop = cbd->event_loop;
		cache_cbd->map = map;
		cache_cbd->data = cbd->data;
		cache_cbd->last_checked = cbd->data->last_checked;
		cache_cbd->gen = cbd->data->gen;
		MAP_RETAIN (cache_cbd->shm, "shmem_data");

		ev_timer_init (&cache_cbd->timeout, rspamd_map_cache_cb, cached_timeout,
				0.0);
		ev_timer_start (cbd->event_loop, &cache_cbd->timeout);
		cache_cbd->timeout.data = cache_cbd;
		data->cur_cache_cbd = cache_cbd;

		if (map->next_check) {
			rspamd_http_date_format (next_check_date, sizeof (next_check_date),
					map->next_check);
		}
		else {
			rspamd_http_date_format (next_check_date, sizeof (next_check_date),
					rspamd_get_calendar_ticks () + map->poll_timeout);
		}


		if (cbd->bk->is_compressed) {
			ZSTD_DStream *zstream;
			ZSTD_inBuffer zin;
			ZSTD_outBuffer zout;
			guchar *out;
			gsize outlen, r;

			zstream = ZSTD_createDStream ();
			ZSTD_initDStream (zstream);

			zin.pos = 0;
			zin.src = in;
			zin.size = dlen;

			if ((outlen = ZSTD_getDecompressedSize (zin.src, zin.size)) == 0) {
				outlen = ZSTD_DStreamOutSize ();
			}

			out = g_malloc (outlen);

			zout.dst = out;
			zout.pos = 0;
			zout.size = outlen;

			while (zin.pos < zin.size) {
				r = ZSTD_decompressStream (zstream, &zout, &zin);

				if (ZSTD_isError (r)) {
					msg_err_map ("%s(%s): cannot decompress data: %s",
							cbd->bk->uri,
							rspamd_inet_address_to_string_pretty (cbd->addr),
							ZSTD_getErrorName (r));
					ZSTD_freeDStream (zstream);
					g_free (out);
					MAP_RELEASE (cbd->shmem_data, "shmem_data");
					goto err;
				}

				if (zout.pos == zout.size) {
					/* We need to extend output buffer */
					zout.size = zout.size * 2 + 1.0;
					out = g_realloc (zout.dst, zout.size);
					zout.dst = out;
				}
			}

			ZSTD_freeDStream (zstream);
			msg_info_map ("%s(%s): read map data %z bytes compressed, "
					"%z uncompressed, next check at %s",
					cbd->bk->uri,
					rspamd_inet_address_to_string_pretty (cbd->addr),
					dlen, zout.pos, next_check_date);
			map->read_callback (out, zout.pos, &cbd->periodic->cbdata, TRUE);
			rspamd_map_save_http_cached_file (map, bk, cbd->data, out, zout.pos);
			g_free (out);
		}
		else {
			msg_info_map ("%s(%s): read map data %z bytes, next check at %s",
					cbd->bk->uri,
					rspamd_inet_address_to_string_pretty (cbd->addr),
					dlen, next_check_date);
			rspamd_map_save_http_cached_file (map, bk, cbd->data, in, cbd->data_len);
			map->read_callback (in, cbd->data_len, &cbd->periodic->cbdata, TRUE);
		}

		MAP_RELEASE (cbd->shmem_data, "shmem_data");

		cbd->periodic->cur_backend ++;
		munmap (in, dlen);
		rspamd_map_process_periodic (cbd->periodic);
	}
	else if (msg->code == 304 && cbd->check) {
		cbd->data->last_checked = msg->date;

		if (msg->last_modified) {
			cbd->data->last_modified = msg->last_modified;
		}
		else {
			cbd->data->last_modified = msg->date;
		}

		expires_hdr = rspamd_http_message_find_header (msg, "Expires");

		if (expires_hdr) {
			time_t hdate;

			hdate = rspamd_http_parse_date (expires_hdr->begin, expires_hdr->len);
			if (hdate != (time_t)-1 && hdate > msg->date) {
				map->next_check = hdate;
			}
		}

		etag_hdr = rspamd_http_message_find_header (msg, "ETag");

		if (etag_hdr) {
			if (cbd->data->etag) {
				/* Remove old etag */
				rspamd_fstring_free (cbd->data->etag);
				cbd->data->etag = rspamd_fstring_new_init (etag_hdr->begin,
						etag_hdr->len);
			}
		}

		if (map->next_check) {
			rspamd_http_date_format (next_check_date, sizeof (next_check_date),
					map->next_check);
			msg_info_map ("data is not modified for server %s, next check at %s "
						  "(http cache based)",
					cbd->data->host, next_check_date);
		}
		else {
			rspamd_http_date_format (next_check_date, sizeof (next_check_date),
					rspamd_get_calendar_ticks () + map->poll_timeout);
			msg_info_map ("data is not modified for server %s, next check at %s "
						  "(timer based)",
					cbd->data->host, next_check_date);
		}

		rspamd_map_update_http_cached_file (map, bk, cbd->data);
		cbd->periodic->cur_backend ++;
		rspamd_map_process_periodic (cbd->periodic);
	}
	else {
		msg_info_map ("cannot load map %s from %s: HTTP error %d",
				bk->uri, cbd->data->host, msg->code);
		goto err;
	}

	MAP_RELEASE (cbd, "http_callback_data");
	return 0;

err:
	cbd->periodic->errored = 1;
	rspamd_map_process_periodic (cbd->periodic);
	MAP_RELEASE (cbd, "http_callback_data");

	return 0;
}

static gboolean
read_map_file_chunks (struct rspamd_map *map, struct map_cb_data *cbdata,
		const gchar *fname, gsize len, goffset off)
{
	gint fd;
	gssize r, avail;
	gsize buflen = 1024 * 1024;
	gchar *pos, *bytes;

	fd = rspamd_file_xopen (fname, O_RDONLY, 0, TRUE);

	if (fd == -1) {
		msg_err_map ("can't open map for buffered reading %s: %s",
				fname, strerror (errno));
		return FALSE;
	}

	if (lseek (fd, off, SEEK_SET) == -1) {
		msg_err_map ("can't seek in map to pos %d for buffered reading %s: %s",
				(gint)off, fname, strerror (errno));
		return FALSE;
	}

	buflen = MIN (len, buflen);
	bytes = g_malloc (buflen);
	avail = buflen;
	pos = bytes;

	while ((r = read (fd, pos, avail)) > 0) {
		gchar *end = bytes + (pos - bytes) + r;
		msg_debug_map ("%s: read map chunk, %z bytes", fname,
				r);
		pos = map->read_callback (bytes, end - bytes, cbdata, r == len);

		if (pos && pos > bytes && pos < end) {
			guint remain = end - pos;

			memmove (bytes, pos, remain);
			pos = bytes + remain;
			/* Need to preserve the remain */
			avail = ((gssize)buflen) - remain;

			if (avail <= 0) {
				/* Try realloc, too large element */
				g_assert (buflen >= remain);
				bytes = g_realloc (bytes, buflen * 2);

				pos = bytes + remain; /* Adjust */
				avail += buflen;
				buflen *= 2;
			}
		}
		else {
			avail = buflen;
			pos = bytes;
		}

		len -= r;
	}

	if (r == -1) {
		msg_err_map ("can't read from map %s: %s", fname, strerror (errno));
		close (fd);
		g_free (bytes);

		return FALSE;
	}

	close (fd);
	g_free (bytes);

	return TRUE;
}

static gboolean
rspamd_map_check_sig_pk_mem (const guchar *sig,
							 gsize siglen,
							 struct rspamd_map *map,
							 const guchar *input,
							 gsize inlen,
							 struct rspamd_cryptobox_pubkey *pk)
{
	GString *b32_key;
	gboolean ret = TRUE;

	if (siglen != rspamd_cryptobox_signature_bytes (RSPAMD_CRYPTOBOX_MODE_25519)) {
		msg_err_map ("can't open signature for %s: invalid size: %z", map->name, siglen);

		ret = FALSE;
	}

	if (ret && !rspamd_cryptobox_verify (sig, siglen, input, inlen,
			rspamd_pubkey_get_pk (pk, NULL), RSPAMD_CRYPTOBOX_MODE_25519)) {
		msg_err_map ("can't verify signature for %s: incorrect signature", map->name);

		ret = FALSE;
	}

	if (ret) {
		b32_key = rspamd_pubkey_print (pk,
				RSPAMD_KEYPAIR_BASE32 | RSPAMD_KEYPAIR_PUBKEY);
		msg_info_map ("verified signature for %s using trusted key %v",
				map->name, b32_key);
		g_string_free (b32_key, TRUE);
	}

	return ret;
}

static gboolean
rspamd_map_check_file_sig (const char *fname,
						   struct rspamd_map *map,
						   struct rspamd_map_backend *bk,
						   const guchar *input,
						   gsize inlen) {
	guchar *data;
	struct rspamd_cryptobox_pubkey *pk = NULL;
	GString *b32_key;
	gboolean ret = TRUE;
	gsize len = 0;
	gchar fpath[PATH_MAX];

	if (bk->trusted_pubkey == NULL) {
		/* Try to load and check pubkey */
		rspamd_snprintf (fpath, sizeof (fpath), "%s.pub", fname);
		data = rspamd_file_xmap (fpath, PROT_READ, &len, TRUE);

		if (data == NULL) {
			msg_err_map ("can't open pubkey %s: %s", fpath, strerror (errno));
			return FALSE;
		}

		pk = rspamd_pubkey_from_base32 (data, len, RSPAMD_KEYPAIR_SIGN,
				RSPAMD_CRYPTOBOX_MODE_25519);
		munmap (data, len);

		if (pk == NULL) {
			msg_err_map ("can't load pubkey %s", fpath);
			return FALSE;
		}

		/* We just check pk against the trusted db of keys */
		b32_key = rspamd_pubkey_print (pk,
				RSPAMD_KEYPAIR_BASE32 | RSPAMD_KEYPAIR_PUBKEY);
		g_assert (b32_key != NULL);

		if (g_hash_table_lookup (map->cfg->trusted_keys, b32_key->str) == NULL) {
			msg_err_map ("pubkey loaded from %s is untrusted: %v", fpath,
					b32_key);
			g_string_free (b32_key, TRUE);
			rspamd_pubkey_unref (pk);

			return FALSE;
		}

		g_string_free (b32_key, TRUE);
	}
	else {
		pk = rspamd_pubkey_ref (bk->trusted_pubkey);
	}

	rspamd_snprintf (fpath, sizeof (fpath), "%s.sig", fname);
	data = rspamd_shmem_xmap (fpath, PROT_READ, &len);

	if (data == NULL) {
		msg_err_map ("can't open signature %s: %s", fpath, strerror (errno));
		ret = FALSE;
	}

	if (ret) {
		ret = rspamd_map_check_sig_pk_mem (data, len, map, input, inlen, pk);
		munmap (data, len);
	}

	rspamd_pubkey_unref (pk);

	return ret;
}

/**
 * Callback for reading data from file
 */
static gboolean
read_map_file (struct rspamd_map *map, struct file_map_data *data,
		struct rspamd_map_backend *bk, struct map_periodic_cbdata *periodic)
{
	gchar *bytes;
	gsize len;
	struct stat st;

	if (map->read_callback == NULL || map->fin_callback == NULL) {
		msg_err_map ("%s: bad callback for reading map file",
				data->filename);
		return FALSE;
	}

	if (stat (data->filename, &st) == -1) {
		/* File does not exist, skipping */
		if (errno != ENOENT) {
			msg_err_map ("%s: map file is unavailable for reading: %s",
					data->filename, strerror (errno));

			return FALSE;
		}
		else {
			msg_info_map ("%s: map file is not found; "
						  "it will be read automatically if created",
					data->filename);
			return TRUE;
		}
	}

	ev_stat_stat (map->event_loop, &data->st_ev);
	len = st.st_size;

	if (bk->is_signed) {
		bytes = rspamd_file_xmap (data->filename, PROT_READ, &len, TRUE);

		if (bytes == NULL) {
			msg_err_map ("can't open map %s: %s", data->filename, strerror (errno));
			return FALSE;
		}

		if (!rspamd_map_check_file_sig (data->filename, map, bk, bytes, len)) {
			munmap (bytes, len);

			return FALSE;
		}

		munmap (bytes, len);
	}

	if (len > 0) {
		if (map->no_file_read) {
			/* We just call read callback with backend name */
			map->read_callback (data->filename, strlen (data->filename),
					&periodic->cbdata, TRUE);
		}
		else {
			if (bk->is_compressed) {
				bytes = rspamd_file_xmap (data->filename, PROT_READ, &len, TRUE);

				if (bytes == NULL) {
					msg_err_map ("can't open map %s: %s", data->filename, strerror (errno));
					return FALSE;
				}

				ZSTD_DStream *zstream;
				ZSTD_inBuffer zin;
				ZSTD_outBuffer zout;
				guchar *out;
				gsize outlen, r;

				zstream = ZSTD_createDStream ();
				ZSTD_initDStream (zstream);

				zin.pos = 0;
				zin.src = bytes;
				zin.size = len;

				if ((outlen = ZSTD_getDecompressedSize (zin.src, zin.size)) == 0) {
					outlen = ZSTD_DStreamOutSize ();
				}

				out = g_malloc (outlen);

				zout.dst = out;
				zout.pos = 0;
				zout.size = outlen;

				while (zin.pos < zin.size) {
					r = ZSTD_decompressStream (zstream, &zout, &zin);

					if (ZSTD_isError (r)) {
						msg_err_map ("%s: cannot decompress data: %s",
								data->filename,
								ZSTD_getErrorName (r));
						ZSTD_freeDStream (zstream);
						g_free (out);
						munmap (bytes, len);
						return FALSE;
					}

					if (zout.pos == zout.size) {
						/* We need to extend output buffer */
						zout.size = zout.size * 2 + 1;
						out = g_realloc (zout.dst, zout.size);
						zout.dst = out;
					}
				}

				ZSTD_freeDStream (zstream);
				msg_info_map ("%s: read map data, %z bytes compressed, "
							  "%z uncompressed)", data->filename,
						len, zout.pos);
				map->read_callback (out, zout.pos, &periodic->cbdata, TRUE);
				g_free (out);

				munmap (bytes, len);
			}
			else {
				/* Perform buffered read: fail-safe */
				if (!read_map_file_chunks (map, &periodic->cbdata, data->filename,
						len, 0)) {
					return FALSE;
				}
			}
		}
	}
	else {
		/* Empty map */
		map->read_callback (NULL, 0, &periodic->cbdata, TRUE);
	}

	return TRUE;
}

static gboolean
read_map_static (struct rspamd_map *map, struct static_map_data *data,
		struct rspamd_map_backend *bk, struct map_periodic_cbdata *periodic)
{
	guchar *bytes;
	gsize len;

	if (map->read_callback == NULL || map->fin_callback == NULL) {
		msg_err_map ("%s: bad callback for reading map file", map->name);
		data->processed = TRUE;
		return FALSE;
	}

	bytes = data->data;
	len = data->len;

	if (len > 0) {
		if (bk->is_compressed) {
			ZSTD_DStream *zstream;
			ZSTD_inBuffer zin;
			ZSTD_outBuffer zout;
			guchar *out;
			gsize outlen, r;

			zstream = ZSTD_createDStream ();
			ZSTD_initDStream (zstream);

			zin.pos = 0;
			zin.src = bytes;
			zin.size = len;

			if ((outlen = ZSTD_getDecompressedSize (zin.src, zin.size)) == 0) {
				outlen = ZSTD_DStreamOutSize ();
			}

			out = g_malloc (outlen);

			zout.dst = out;
			zout.pos = 0;
			zout.size = outlen;

			while (zin.pos < zin.size) {
				r = ZSTD_decompressStream (zstream, &zout, &zin);

				if (ZSTD_isError (r)) {
					msg_err_map ("%s: cannot decompress data: %s",
							map->name,
							ZSTD_getErrorName (r));
					ZSTD_freeDStream (zstream);
					g_free (out);

					return FALSE;
				}

				if (zout.pos == zout.size) {
					/* We need to extend output buffer */
					zout.size = zout.size * 2 + 1;
					out = g_realloc (zout.dst, zout.size);
					zout.dst = out;
				}
			}

			ZSTD_freeDStream (zstream);
			msg_info_map ("%s: read map data, %z bytes compressed, "
					"%z uncompressed)",
					map->name,
					len, zout.pos);
			map->read_callback (out, zout.pos, &periodic->cbdata, TRUE);
			g_free (out);
		}
		else {
			msg_info_map ("%s: read map data, %z bytes",
					map->name, len);
			map->read_callback (bytes, len, &periodic->cbdata, TRUE);
		}
	}
	else {
		map->read_callback (NULL, 0, &periodic->cbdata, TRUE);
	}

	data->processed = TRUE;

	return TRUE;
}

static void
rspamd_map_periodic_dtor (struct map_periodic_cbdata *periodic)
{
	struct rspamd_map *map;

	map = periodic->map;
	msg_debug_map ("periodic dtor %p", periodic);

	if (periodic->need_modify) {
		/* We are done */
		periodic->map->fin_callback (&periodic->cbdata, periodic->map->user_data);
	}
	else {
		/* Not modified */
	}

	if (periodic->locked) {
		g_atomic_int_set (periodic->map->locked, 0);
		msg_debug_map ("unlocked map %s", periodic->map->name);

		if (periodic->map->wrk->state == rspamd_worker_state_running) {
			rspamd_map_schedule_periodic (periodic->map,
					RSPAMD_SYMBOL_RESULT_NORMAL);
		}
		else {
			msg_debug_map ("stop scheduling periodics for %s; terminating state",
					periodic->map->name);
		}
	}

	g_free (periodic);
}

/* Called on timer execution */
static void
rspamd_map_periodic_callback (struct ev_loop *loop, ev_timer *w, int revents)
{
	struct map_periodic_cbdata *cbd = (struct map_periodic_cbdata *)w->data;

	MAP_RETAIN (cbd, "periodic");
	ev_timer_stop (loop, w);
	rspamd_map_process_periodic (cbd);
	MAP_RELEASE (cbd, "periodic");
}

static void
rspamd_map_schedule_periodic (struct rspamd_map *map, int how)
{
	const gdouble error_mult = 20.0, lock_mult = 0.1;
	static const gdouble min_timer_interval = 2.0;
	const gchar *reason = "unknown reason";
	gdouble jittered_sec;
	gdouble timeout;
	struct map_periodic_cbdata *cbd;

	if (map->scheduled_check || (map->wrk &&
			map->wrk->state != rspamd_worker_state_running)) {
		/*
		 * Do not schedule check if some check is already scheduled or
		 * if worker is going to die
		 */
		return;
	}

	if (!(how & RSPAMD_MAP_SCHEDULE_INIT) && map->static_only) {
		/* No need to schedule anything for static maps */
		return;
	}

	if (map->non_trivial && map->next_check != 0) {
		timeout = map->next_check - rspamd_get_calendar_ticks ();

		if (timeout > 0 && timeout < map->poll_timeout) {
			/* Early check case, jitter */
			gdouble poll_timeout = map->poll_timeout;

			if (how & RSPAMD_MAP_SCHEDULE_ERROR) {
				poll_timeout = map->poll_timeout * error_mult;
				reason = "early active non-trivial check (after error)";
			}
			else if (how & RSPAMD_MAP_SCHEDULE_LOCKED) {
				poll_timeout = map->poll_timeout * lock_mult;
				reason = "early active non-trivial check (after being locked)";
			}
			else {
				reason = "early active non-trivial check";
			}

			jittered_sec = MIN (timeout, poll_timeout);

		}
		else if (timeout <= 0) {
			/* Data is already expired, need to check */
			jittered_sec = 0.0;
			reason = "expired non-trivial data";
		}
		else {
			/* No need to check now, wait till next_check */
			jittered_sec = timeout;
			reason = "valid non-trivial data";
		}
	}
	else {
		timeout = map->poll_timeout;

		if (how & RSPAMD_MAP_SCHEDULE_INIT) {
			if (map->active_http) {
				/* Spill maps load to get better chances to hit ssl cache */
				timeout = rspamd_time_jitter (0.0, 2.0);
			}
			else {
				timeout = 0.0;
			}

			reason = "init scheduled check";
		}
		else {
			if (how & RSPAMD_MAP_SCHEDULE_ERROR) {
				timeout = map->poll_timeout * error_mult;
				reason = "errored scheduled check";
			}
			else if (how & RSPAMD_MAP_SCHEDULE_LOCKED) {
				timeout = map->poll_timeout * lock_mult;
				reason = "locked scheduled check";
			}
			else {
				reason = "normal scheduled check";
			}
		}

		jittered_sec = rspamd_time_jitter (timeout, 0);
	}

	/* Now, we do some sanity checks for jittered seconds */
	if (!(how & RSPAMD_MAP_SCHEDULE_INIT)) {
		/* Never allow too low interval between timer checks, it is epxensive */
		if (jittered_sec < min_timer_interval) {
			jittered_sec = rspamd_time_jitter (min_timer_interval, 0);
		}

		if (map->non_trivial) {
			/*
			 * Even if we are reported that we need to reload cache often, we
			 * still want to be sane in terms of events...
			 */
			if (jittered_sec < min_timer_interval * 2.0) {
				if (map->nelts > 0) {
					jittered_sec = min_timer_interval * 3.0;
				}
			}
		}
	}

	cbd = g_malloc0 (sizeof (*cbd));
	cbd->cbdata.state = 0;
	cbd->cbdata.prev_data = *map->user_data;
	cbd->cbdata.cur_data = NULL;
	cbd->cbdata.map = map;
	cbd->map = map;
	map->scheduled_check = cbd;
	REF_INIT_RETAIN (cbd, rspamd_map_periodic_dtor);

	cbd->ev.data = cbd;
	ev_timer_init (&cbd->ev, rspamd_map_periodic_callback, jittered_sec, 0.0);
	ev_timer_start (map->event_loop, &cbd->ev);

	msg_debug_map ("schedule new periodic event %p in %.3f seconds for %s; reason: %s",
			cbd, jittered_sec, map->name, reason);
}

static void
rspamd_map_dns_callback (struct rdns_reply *reply, void *arg)
{
	struct http_callback_data *cbd = arg;
	struct rdns_reply_entry *cur_rep;
	struct rspamd_map *map;
	guint flags = RSPAMD_HTTP_CLIENT_SIMPLE|RSPAMD_HTTP_CLIENT_SHARED;

	map = cbd->map;

	msg_debug_map ("got dns reply with code %s on stage %d",
			rdns_strerror (reply->code), cbd->stage);

	if (cbd->stage == http_map_terminated) {
		MAP_RELEASE (cbd, "http_callback_data");
		return;
	}

	if (reply->code == RDNS_RC_NOERROR) {
		/*
		 * We just get the first address hoping that a resolver performs
		 * round-robin rotation well
		 */

		DL_FOREACH (reply->entries, cur_rep) {
			rspamd_inet_addr_t *addr;
			addr = rspamd_inet_address_from_rnds (reply->entries);

			if (addr != NULL) {
				rspamd_inet_address_set_port (addr, cbd->data->port);
				g_ptr_array_add (cbd->addrs, (void *)addr);
			}
		}

		if (cbd->stage == http_map_resolve_host2) {
			/* We have still one request pending */
			cbd->stage = http_map_resolve_host1;
		}
		else if (cbd->stage == http_map_resolve_host1) {
			cbd->stage = http_map_http_conn;
		}
	}
	else if (cbd->stage < http_map_http_conn) {
		if (cbd->stage == http_map_resolve_host2) {
			/* We have still one request pending */
			cbd->stage = http_map_resolve_host1;
		}
		else if (cbd->addrs->len == 0) {
			/* We could not resolve host, so cowardly fail here */
			msg_err_map ("cannot resolve %s: %s", cbd->data->host,
					rdns_strerror (reply->code));
			cbd->periodic->errored = 1;
			rspamd_map_process_periodic (cbd->periodic);
		}
		else {
			/* We have at least one address, so we can continue... */
			cbd->stage = http_map_http_conn;
		}
	}

	if (cbd->stage == http_map_http_conn && cbd->addrs->len > 0) {
		guint selected_addr_idx;

		selected_addr_idx = rspamd_random_uint64_fast () % cbd->addrs->len;
		cbd->addr = (rspamd_inet_addr_t *)g_ptr_array_index (cbd->addrs,
				selected_addr_idx);

		msg_debug_map ("open http connection to %s",
				rspamd_inet_address_to_string_pretty (cbd->addr));
		cbd->conn = rspamd_http_connection_new_client (NULL,
				NULL,
				http_map_error,
				http_map_finish,
				flags,
				cbd->addr);

		if (cbd->conn != NULL) {
			write_http_request (cbd);
		}
		else {
			cbd->periodic->errored = TRUE;
			msg_err_map ("error reading %s(%s): "
						 "connection with http server terminated incorrectly: %s",
					cbd->bk->uri,
					cbd->addr ? rspamd_inet_address_to_string_pretty (cbd->addr) : "",
					strerror (errno));

			rspamd_map_process_periodic (cbd->periodic);
		}
	}

	MAP_RELEASE (cbd, "http_callback_data");
}

static gboolean
rspamd_map_read_cached (struct rspamd_map *map, struct rspamd_map_backend *bk,
		struct map_periodic_cbdata *periodic, const gchar *host)
{
	gsize len;
	gpointer in;
	struct http_map_data *data;

	data = bk->data.hd;

	in = rspamd_shmem_xmap (data->cache->shmem_name, PROT_READ, &len);

	if (in == NULL) {
		msg_err ("cannot map cache from %s: %s", data->cache->shmem_name,
				strerror (errno));
		return FALSE;
	}

	if (len < data->cache->len) {
		msg_err ("cannot map cache from %s: bad length %z, %z expected",
				data->cache->shmem_name,
				len, data->cache->len);
		munmap (in, len);

		return FALSE;
	}

	if (bk->is_compressed) {
		ZSTD_DStream *zstream;
		ZSTD_inBuffer zin;
		ZSTD_outBuffer zout;
		guchar *out;
		gsize outlen, r;

		zstream = ZSTD_createDStream ();
		ZSTD_initDStream (zstream);

		zin.pos = 0;
		zin.src = in;
		zin.size = len;

		if ((outlen = ZSTD_getDecompressedSize (zin.src, zin.size)) == 0) {
			outlen = ZSTD_DStreamOutSize ();
		}

		out = g_malloc (outlen);

		zout.dst = out;
		zout.pos = 0;
		zout.size = outlen;

		while (zin.pos < zin.size) {
			r = ZSTD_decompressStream (zstream, &zout, &zin);

			if (ZSTD_isError (r)) {
				msg_err_map ("%s: cannot decompress data: %s",
						bk->uri,
						ZSTD_getErrorName (r));
				ZSTD_freeDStream (zstream);
				g_free (out);
				munmap (in, len);
				return FALSE;
			}

			if (zout.pos == zout.size) {
				/* We need to extend output buffer */
				zout.size = zout.size * 2 + 1;
				out = g_realloc (zout.dst, zout.size);
				zout.dst = out;
			}
		}

		ZSTD_freeDStream (zstream);
		msg_info_map ("%s: read map data cached %z bytes compressed, "
				"%z uncompressed", bk->uri,
				len, zout.pos);
		map->read_callback (out, zout.pos, &periodic->cbdata, TRUE);
		g_free (out);
	}
	else {
		msg_info_map ("%s: read map data cached %z bytes", bk->uri,
				len);
		map->read_callback (in, len, &periodic->cbdata, TRUE);
	}

	munmap (in, len);

	return TRUE;
}

static gboolean
rspamd_map_has_http_cached_file (struct rspamd_map *map,
								 struct rspamd_map_backend *bk)
{
	gchar path[PATH_MAX];
	guchar digest[rspamd_cryptobox_HASHBYTES];
	struct rspamd_config *cfg = map->cfg;
	struct stat st;

	if (cfg->maps_cache_dir == NULL || cfg->maps_cache_dir[0] == '\0') {
		return FALSE;
	}

	rspamd_cryptobox_hash (digest, bk->uri, strlen (bk->uri), NULL, 0);
	rspamd_snprintf (path, sizeof (path), "%s%c%*xs.map", cfg->maps_cache_dir,
			G_DIR_SEPARATOR, 20, digest);

	if (stat (path, &st) != -1 && st.st_size >
								  sizeof (struct rspamd_http_file_data)) {
		return TRUE;
	}

	return FALSE;
}

static gboolean
rspamd_map_save_http_cached_file (struct rspamd_map *map,
								  struct rspamd_map_backend *bk,
								  struct http_map_data *htdata,
								  const guchar *data,
								  gsize len)
{
	gchar path[PATH_MAX];
	guchar digest[rspamd_cryptobox_HASHBYTES];
	struct rspamd_config *cfg = map->cfg;
	gint fd;
	struct rspamd_http_file_data header;

	if (cfg->maps_cache_dir == NULL || cfg->maps_cache_dir[0] == '\0') {
		return FALSE;
	}

	rspamd_cryptobox_hash (digest, bk->uri, strlen (bk->uri), NULL, 0);
	rspamd_snprintf (path, sizeof (path), "%s%c%*xs.map", cfg->maps_cache_dir,
			G_DIR_SEPARATOR, 20, digest);

	fd = rspamd_file_xopen (path, O_WRONLY | O_TRUNC | O_CREAT,
			00600, FALSE);

	if (fd == -1) {
		return FALSE;
	}

	if (!rspamd_file_lock (fd, FALSE)) {
		msg_err_map ("cannot lock file %s: %s", path, strerror (errno));
		close (fd);

		return FALSE;
	}

	memcpy (header.magic, rspamd_http_file_magic, sizeof (rspamd_http_file_magic));
	header.mtime = htdata->last_modified;
	header.next_check = map->next_check;
	header.data_off = sizeof (header);

	if (htdata->etag) {
		header.data_off += RSPAMD_FSTRING_LEN (htdata->etag);
		header.etag_len = RSPAMD_FSTRING_LEN (htdata->etag);
	}
	else {
		header.etag_len = 0;
	}

	if (write (fd, &header, sizeof (header)) != sizeof (header)) {
		msg_err_map ("cannot write file %s (header stage): %s", path, strerror (errno));
		rspamd_file_unlock (fd, FALSE);
		close (fd);

		return FALSE;
	}

	if (header.etag_len > 0) {
		if (write (fd, RSPAMD_FSTRING_DATA (htdata->etag), header.etag_len) !=
			header.etag_len) {
			msg_err_map ("cannot write file %s (etag stage): %s", path, strerror (errno));
			rspamd_file_unlock (fd, FALSE);
			close (fd);

			return FALSE;
		}
	}

	/* Now write the rest */
	if (write (fd, data, len) != len) {
		msg_err_map ("cannot write file %s (data stage): %s", path, strerror (errno));
		rspamd_file_unlock (fd, FALSE);
		close (fd);

		return FALSE;
	}

	rspamd_file_unlock (fd, FALSE);
	close (fd);

	msg_info_map ("saved data from %s in %s, %uz bytes", bk->uri, path, len +
																		sizeof (header) + header.etag_len);

	return TRUE;
}

static gboolean
rspamd_map_update_http_cached_file (struct rspamd_map *map,
								  struct rspamd_map_backend *bk,
								  struct http_map_data *htdata)
{
	gchar path[PATH_MAX];
	guchar digest[rspamd_cryptobox_HASHBYTES];
	struct rspamd_config *cfg = map->cfg;
	gint fd;
	struct rspamd_http_file_data header;

	if (!rspamd_map_has_http_cached_file (map, bk)) {
		return FALSE;
	}

	rspamd_cryptobox_hash (digest, bk->uri, strlen (bk->uri), NULL, 0);
	rspamd_snprintf (path, sizeof (path), "%s%c%*xs.map", cfg->maps_cache_dir,
			G_DIR_SEPARATOR, 20, digest);

	fd = rspamd_file_xopen (path, O_WRONLY,
			00600, FALSE);

	if (fd == -1) {
		return FALSE;
	}

	if (!rspamd_file_lock (fd, FALSE)) {
		msg_err_map ("cannot lock file %s: %s", path, strerror (errno));
		close (fd);

		return FALSE;
	}

	memcpy (header.magic, rspamd_http_file_magic, sizeof (rspamd_http_file_magic));
	header.mtime = htdata->last_modified;
	header.next_check = map->next_check;
	header.data_off = sizeof (header);

	if (htdata->etag) {
		header.data_off += RSPAMD_FSTRING_LEN (htdata->etag);
		header.etag_len = RSPAMD_FSTRING_LEN (htdata->etag);
	}
	else {
		header.etag_len = 0;
	}

	if (write (fd, &header, sizeof (header)) != sizeof (header)) {
		msg_err_map ("cannot update file %s (header stage): %s", path, strerror (errno));
		rspamd_file_unlock (fd, FALSE);
		close (fd);

		return FALSE;
	}

	if (header.etag_len > 0) {
		if (write (fd, RSPAMD_FSTRING_DATA (htdata->etag), header.etag_len) !=
			header.etag_len) {
			msg_err_map ("cannot update file %s (etag stage): %s", path, strerror (errno));
			rspamd_file_unlock (fd, FALSE);
			close (fd);

			return FALSE;
		}
	}

	rspamd_file_unlock (fd, FALSE);
	close (fd);

	return TRUE;
}


static gboolean
rspamd_map_read_http_cached_file (struct rspamd_map *map,
								  struct rspamd_map_backend *bk,
								  struct http_map_data *htdata,
								  struct map_cb_data *cbdata)
{
	gchar path[PATH_MAX];
	guchar digest[rspamd_cryptobox_HASHBYTES];
	struct rspamd_config *cfg = map->cfg;
	gint fd;
	struct stat st;
	struct rspamd_http_file_data header;

	if (cfg->maps_cache_dir == NULL || cfg->maps_cache_dir[0] == '\0') {
		return FALSE;
	}

	rspamd_cryptobox_hash (digest, bk->uri, strlen (bk->uri), NULL, 0);
	rspamd_snprintf (path, sizeof (path), "%s%c%*xs.map", cfg->maps_cache_dir,
			G_DIR_SEPARATOR, 20, digest);

	fd = rspamd_file_xopen (path, O_RDONLY, 00600, FALSE);

	if (fd == -1) {
		return FALSE;
	}

	if (!rspamd_file_lock (fd, FALSE)) {
		msg_err_map ("cannot lock file %s: %s", path, strerror (errno));
		close (fd);

		return FALSE;
	}

	(void)fstat (fd, &st);

	if (read (fd, &header, sizeof (header)) != sizeof (header)) {
		msg_err_map ("cannot read file %s (header stage): %s", path, strerror (errno));
		rspamd_file_unlock (fd, FALSE);
		close (fd);

		return FALSE;
	}

	if (memcmp (header.magic, rspamd_http_file_magic,
			sizeof (rspamd_http_file_magic)) != 0) {
		msg_warn_map ("invalid or old version magic in file %s; ignore it", path);
		rspamd_file_unlock (fd, FALSE);
		close (fd);

		return FALSE;
	}

	map->next_check = header.next_check;
	htdata->last_modified = header.mtime;

	if (header.etag_len > 0) {
		rspamd_fstring_t *etag = rspamd_fstring_sized_new (header.etag_len);

		if (read (fd, RSPAMD_FSTRING_DATA (etag), header.etag_len) != header.etag_len) {
			msg_err_map ("cannot read file %s (etag stage): %s", path,
					strerror (errno));
			rspamd_file_unlock (fd, FALSE);
			rspamd_fstring_free (etag);
			close (fd);

			return FALSE;
		}

		etag->len = header.etag_len;

		if (htdata->etag) {
			/* FIXME: should be dealt somehow better */
			msg_warn_map ("etag is already defined as %V; cached is %V; ignore cached",
					htdata->etag, etag);
			rspamd_fstring_free (etag);
		}
		else {
			htdata->etag = etag;
		}
	}

	rspamd_file_unlock (fd, FALSE);
	close (fd);

	/* Now read file data */
	/* Perform buffered read: fail-safe */
	if (!read_map_file_chunks (map, cbdata, path,
			st.st_size - header.data_off, header.data_off)) {
		return FALSE;
	}

	struct tm tm;
	gchar ncheck_buf[32], lm_buf[32];

	rspamd_localtime (map->next_check, &tm);
	strftime (ncheck_buf, sizeof (ncheck_buf) - 1, "%Y-%m-%d %H:%M:%S", &tm);
	rspamd_localtime (htdata->last_modified, &tm);
	strftime (lm_buf, sizeof (lm_buf) - 1, "%Y-%m-%d %H:%M:%S", &tm);

	msg_info_map ("read cached data for %s from %s, %uz bytes; next check at: %s;"
				  " last modified on: %s; etag: %V",
			bk->uri,
			path,
			(size_t)(st.st_size - header.data_off),
			ncheck_buf,
			lm_buf,
			htdata->etag);

	return TRUE;
}

/**
 * Async HTTP callback
 */
static void
rspamd_map_common_http_callback (struct rspamd_map *map,
		struct rspamd_map_backend *bk,
		struct map_periodic_cbdata *periodic,
		gboolean check)
{
	struct http_map_data *data;
	struct http_callback_data *cbd;
	guint flags = RSPAMD_HTTP_CLIENT_SIMPLE|RSPAMD_HTTP_CLIENT_SHARED;

	data = bk->data.hd;

	if (g_atomic_int_get (&data->cache->available) == 1) {
		/* Read cached data */
		if (check) {
			if (data->last_modified < data->cache->last_modified) {
				periodic->need_modify = TRUE;
				/* Reset the whole chain */
				periodic->cur_backend = 0;
				rspamd_map_process_periodic (periodic);
			}
			else {
				if (map->active_http) {
					/* Check even if there is a cached version */
					goto check;
				}
				else {
					/* Switch to the next backend */
					periodic->cur_backend++;
					rspamd_map_process_periodic (periodic);
				}
			}

			return;
		}
		else {
			if (map->active_http &&
					data->last_modified > data->cache->last_modified) {
				goto check;
			}
			else if (rspamd_map_read_cached (map, bk, periodic, data->host)) {
				/* Switch to the next backend */
				periodic->cur_backend++;
				data->last_modified = data->cache->last_modified;
				rspamd_map_process_periodic (periodic);

				return;
			}
		}
	}
	else if (!map->active_http) {
		/* Switch to the next backend */
		periodic->cur_backend ++;
		rspamd_map_process_periodic (periodic);

		return;
	}

check:
	cbd = g_malloc0 (sizeof (struct http_callback_data));

	cbd->event_loop = map->event_loop;
	cbd->addrs = g_ptr_array_sized_new (4);
	cbd->map = map;
	cbd->data = data;
	cbd->check = check;
	cbd->periodic = periodic;
	MAP_RETAIN (periodic, "periodic");
	cbd->bk = bk;
	MAP_RETAIN (bk, "rspamd_map_backend");
	cbd->stage = http_map_terminated;
	REF_INIT_RETAIN (cbd, free_http_cbdata);

	msg_debug_map ("%s map data from %s", check ? "checking" : "reading",
			data->host);

	/* Try address */
	rspamd_inet_addr_t *addr = NULL;

	if (rspamd_parse_inet_address (&addr, data->host,
			strlen (data->host), RSPAMD_INET_ADDRESS_PARSE_DEFAULT)) {
		rspamd_inet_address_set_port (addr, cbd->data->port);
		g_ptr_array_add (cbd->addrs, (void *)addr);
		cbd->conn = rspamd_http_connection_new_client (
				NULL,
				NULL,
				http_map_error,
				http_map_finish,
				flags,
				addr);

		if (cbd->conn != NULL) {
			cbd->stage = http_map_http_conn;
			write_http_request (cbd);
			cbd->addr = addr;
			MAP_RELEASE (cbd, "http_callback_data");
		}
		else {
			msg_warn_map ("cannot load map: cannot connect to %s: %s",
					data->host, strerror (errno));
			MAP_RELEASE (cbd, "http_callback_data");
		}

		return;
	}
	else if (map->r->r) {
		/* Send both A and AAAA requests */
		guint nreq = 0;

		if (rdns_make_request_full (map->r->r, rspamd_map_dns_callback, cbd,
				map->cfg->dns_timeout, map->cfg->dns_retransmits, 1,
				data->host, RDNS_REQUEST_A)) {
			MAP_RETAIN (cbd, "http_callback_data");
			nreq ++;
		}
		if (rdns_make_request_full (map->r->r, rspamd_map_dns_callback, cbd,
				map->cfg->dns_timeout, map->cfg->dns_retransmits, 1,
				data->host, RDNS_REQUEST_AAAA)) {
			MAP_RETAIN (cbd, "http_callback_data");
			nreq ++;
		}

		if (nreq == 2) {
			cbd->stage = http_map_resolve_host2;
		}
		else if (nreq == 1) {
			cbd->stage = http_map_resolve_host1;
		}

		map->tmp_dtor = free_http_cbdata_dtor;
		map->tmp_dtor_data = cbd;
	}
	else {
		msg_warn_map ("cannot load map: DNS resolver is not initialized");
		cbd->periodic->errored = TRUE;
	}

	MAP_RELEASE (cbd, "http_callback_data");
}

static void
rspamd_map_http_check_callback (struct map_periodic_cbdata *cbd)
{
	struct rspamd_map *map;
	struct rspamd_map_backend *bk;

	map = cbd->map;
	bk = g_ptr_array_index (cbd->map->backends, cbd->cur_backend);

	rspamd_map_common_http_callback (map, bk, cbd, TRUE);
}

static void
rspamd_map_http_read_callback (struct map_periodic_cbdata *cbd)
{
	struct rspamd_map *map;
	struct rspamd_map_backend *bk;

	map = cbd->map;
	bk = g_ptr_array_index (cbd->map->backends, cbd->cur_backend);
	rspamd_map_common_http_callback (map, bk, cbd, FALSE);
}

static void
rspamd_map_file_check_callback (struct map_periodic_cbdata *periodic)
{
	struct rspamd_map *map;
	struct file_map_data *data;
	struct rspamd_map_backend *bk;

	map = periodic->map;
	bk = g_ptr_array_index (map->backends, periodic->cur_backend);
	data = bk->data.fd;

	if (data->need_modify) {
		periodic->need_modify = TRUE;
		periodic->cur_backend = 0;
		data->need_modify = FALSE;

		rspamd_map_process_periodic (periodic);

		return;
	}

	map = periodic->map;
	/* Switch to the next backend as the rest is handled by ev_stat */
	periodic->cur_backend ++;
	rspamd_map_process_periodic (periodic);
}

static void
rspamd_map_static_check_callback (struct map_periodic_cbdata *periodic)
{
	struct rspamd_map *map;
	struct static_map_data *data;
	struct rspamd_map_backend *bk;

	map = periodic->map;
	bk = g_ptr_array_index (map->backends, periodic->cur_backend);
	data = bk->data.sd;

	if (!data->processed) {
		periodic->need_modify = TRUE;
		periodic->cur_backend = 0;

		rspamd_map_process_periodic (periodic);

		return;
	}

	/* Switch to the next backend */
	periodic->cur_backend ++;
	rspamd_map_process_periodic (periodic);
}

static void
rspamd_map_file_read_callback (struct map_periodic_cbdata *periodic)
{
	struct rspamd_map *map;
	struct file_map_data *data;
	struct rspamd_map_backend *bk;

	map = periodic->map;

	bk = g_ptr_array_index (map->backends, periodic->cur_backend);
	data = bk->data.fd;

	msg_info_map ("rereading map file %s", data->filename);

	if (!read_map_file (map, data, bk, periodic)) {
		periodic->errored = TRUE;
	}

	/* Switch to the next backend */
	periodic->cur_backend ++;
	rspamd_map_process_periodic (periodic);
}

static void
rspamd_map_static_read_callback (struct map_periodic_cbdata *periodic)
{
	struct rspamd_map *map;
	struct static_map_data *data;
	struct rspamd_map_backend *bk;

	map = periodic->map;

	bk = g_ptr_array_index (map->backends, periodic->cur_backend);
	data = bk->data.sd;

	msg_info_map ("rereading static map");

	if (!read_map_static (map, data, bk, periodic)) {
		periodic->errored = TRUE;
	}

	/* Switch to the next backend */
	periodic->cur_backend ++;
	rspamd_map_process_periodic (periodic);
}

static void
rspamd_map_process_periodic (struct map_periodic_cbdata *cbd)
{
	struct rspamd_map_backend *bk;
	struct rspamd_map *map;

	map = cbd->map;
	map->scheduled_check = NULL;

	if (!map->file_only && !cbd->locked) {
		if (!g_atomic_int_compare_and_exchange (cbd->map->locked,
				0, 1)) {
			msg_debug_map (
					"don't try to reread map %s as it is locked by other process, "
					"will reread it later", cbd->map->name);
			rspamd_map_schedule_periodic (map, RSPAMD_MAP_SCHEDULE_LOCKED);
			MAP_RELEASE (cbd, "periodic");

			return;
		}
		else {
			msg_debug_map ("locked map %s", cbd->map->name);
			cbd->locked = TRUE;
		}
	}

	if (cbd->errored) {
		/* We should not check other backends if some backend has failed */
		rspamd_map_schedule_periodic (cbd->map, RSPAMD_MAP_SCHEDULE_ERROR);

		if (cbd->locked) {
			g_atomic_int_set (cbd->map->locked, 0);
			cbd->locked = FALSE;
		}

		msg_debug_map ("unlocked map %s, refcount=%d", cbd->map->name,
				cbd->ref.refcount);
		MAP_RELEASE (cbd, "periodic");

		return;
	}

	/* For each backend we need to check for modifications */
	if (cbd->cur_backend >= cbd->map->backends->len) {
		/* Last backend */
		msg_debug_map ("finished map: %d of %d", cbd->cur_backend,
				cbd->map->backends->len);
		MAP_RELEASE (cbd, "periodic");

		return;
	}

	if (cbd->map->wrk && cbd->map->wrk->state == rspamd_worker_state_running) {
		bk = g_ptr_array_index (cbd->map->backends, cbd->cur_backend);
		g_assert (bk != NULL);

		if (cbd->need_modify) {
			/* Load data from the next backend */
			switch (bk->protocol) {
			case MAP_PROTO_HTTP:
			case MAP_PROTO_HTTPS:
				rspamd_map_http_read_callback (cbd);
				break;
			case MAP_PROTO_FILE:
				rspamd_map_file_read_callback (cbd);
				break;
			case MAP_PROTO_STATIC:
				rspamd_map_static_read_callback (cbd);
				break;
			}
		} else {
			/* Check the next backend */
			switch (bk->protocol) {
			case MAP_PROTO_HTTP:
			case MAP_PROTO_HTTPS:
				rspamd_map_http_check_callback (cbd);
				break;
			case MAP_PROTO_FILE:
				rspamd_map_file_check_callback (cbd);
				break;
			case MAP_PROTO_STATIC:
				rspamd_map_static_check_callback (cbd);
				break;
			}
		}
	}
}

static void
rspamd_map_on_stat (struct ev_loop *loop, ev_stat *w, int revents)
{
	struct rspamd_map *map = (struct rspamd_map *)w->data;

	if (w->attr.st_nlink > 0) {

		if (w->attr.st_mtime > w->prev.st_mtime) {
			msg_info_map ("old mtime is %t (size = %Hz), "
				 "new mtime is %t (size = %Hz) for map file %s",
					w->prev.st_mtime, (gsize)w->prev.st_size,
					w->attr.st_mtime, (gsize)w->attr.st_size,
					w->path);

			/* Fire need modify flag */
			struct rspamd_map_backend *bk;
			guint i;

			PTR_ARRAY_FOREACH (map->backends, i, bk) {
				if (bk->protocol == MAP_PROTO_FILE) {
					bk->data.fd->need_modify = TRUE;
				}
			}

			map->next_check = 0;

			if (map->scheduled_check) {
				ev_timer_stop (map->event_loop, &map->scheduled_check->ev);
				MAP_RELEASE (map->scheduled_check, "rspamd_map_on_stat");
				map->scheduled_check = NULL;
			}

			rspamd_map_schedule_periodic (map, RSPAMD_MAP_SCHEDULE_INIT);
		}
	}
}

/* Start watching event for all maps */
void
rspamd_map_watch (struct rspamd_config *cfg,
				  struct ev_loop *event_loop,
				  struct rspamd_dns_resolver *resolver,
				  struct rspamd_worker *worker,
				  enum rspamd_map_watch_type how)
{
	GList *cur = cfg->maps;
	struct rspamd_map *map;
	struct rspamd_map_backend *bk;
	guint i;

	g_assert (how > RSPAMD_MAP_WATCH_MIN && how < RSPAMD_MAP_WATCH_MAX);

	/* First of all do synced read of data */
	while (cur) {
		map = cur->data;
		map->event_loop = event_loop;
		map->r = resolver;

		if (map->wrk == NULL && how != RSPAMD_MAP_WATCH_WORKER) {
			/* Generic scanner map */
			map->wrk = worker;

			if (how == RSPAMD_MAP_WATCH_PRIMARY_CONTROLLER) {
				map->active_http = TRUE;
			}
			else {
				map->active_http = FALSE;
			}
		}
		else if (map->wrk != NULL && map->wrk == worker) {
			/* Map is bound to a specific worker */
			map->active_http = TRUE;
		}
		else {
			/* Skip map for this worker as irrelevant */
			cur = g_list_next (cur);
			continue;
		}

		if (!map->active_http) {
			/* Check cached version more frequently as it is cheap */

			if (map->poll_timeout >= cfg->map_timeout &&
					cfg->map_file_watch_multiplier < 1.0) {
				map->poll_timeout =
						map->poll_timeout * cfg->map_file_watch_multiplier;
			}
		}

		map->file_only = TRUE;
		map->static_only = TRUE;

		PTR_ARRAY_FOREACH (map->backends, i, bk) {
			bk->event_loop = event_loop;

			if (bk->protocol == MAP_PROTO_FILE) {
				struct file_map_data *data;

				data = bk->data.fd;

				ev_stat_init (&data->st_ev, rspamd_map_on_stat,
						data->filename, map->poll_timeout * cfg->map_file_watch_multiplier);
				data->st_ev.data = map;
				ev_stat_start (event_loop, &data->st_ev);
				map->static_only = FALSE;
			}
			else if ((bk->protocol == MAP_PROTO_HTTP ||
					  bk->protocol == MAP_PROTO_HTTPS)) {
				if (map->active_http) {
					map->non_trivial = TRUE;
				}

				map->static_only = FALSE;
				map->file_only = FALSE;
			}
		}

		rspamd_map_schedule_periodic (map, RSPAMD_MAP_SCHEDULE_INIT);

		cur = g_list_next (cur);
	}
}

void
rspamd_map_preload (struct rspamd_config *cfg)
{
	GList *cur = cfg->maps;
	struct rspamd_map *map;
	struct rspamd_map_backend *bk;
	guint i;
	gboolean map_ok;

	/* First of all do synced read of data */
	while (cur) {
		map = cur->data;
		map_ok = TRUE;

		PTR_ARRAY_FOREACH (map->backends, i, bk) {
			if (!(bk->protocol == MAP_PROTO_FILE ||
				  bk->protocol == MAP_PROTO_STATIC)) {

				if (bk->protocol == MAP_PROTO_HTTP ||
						bk->protocol == MAP_PROTO_HTTPS) {
					if (!rspamd_map_has_http_cached_file (map, bk)) {

						if (!map->fallback_backend) {
							map_ok = FALSE;
						}
						break;
					}
					else {
						continue; /* We are yet fine */
					}
				}
				map_ok = FALSE;
				break;
			}
		}

		if (map_ok) {
			struct map_periodic_cbdata fake_cbd;
			gboolean succeed = TRUE;

			memset (&fake_cbd, 0, sizeof (fake_cbd));
			fake_cbd.cbdata.state = 0;
			fake_cbd.cbdata.prev_data = *map->user_data;
			fake_cbd.cbdata.cur_data = NULL;
			fake_cbd.cbdata.map = map;
			fake_cbd.map = map;

			PTR_ARRAY_FOREACH (map->backends, i, bk) {
				fake_cbd.cur_backend = i;

				if (bk->protocol == MAP_PROTO_FILE) {
					if (!read_map_file (map, bk->data.fd, bk, &fake_cbd)) {
						succeed = FALSE;
						break;
					}
				}
				else if (bk->protocol == MAP_PROTO_STATIC) {
					if (!read_map_static (map, bk->data.sd, bk, &fake_cbd)) {
						succeed = FALSE;
						break;
					}
				}
				else if (bk->protocol == MAP_PROTO_HTTP ||
						 bk->protocol == MAP_PROTO_HTTPS) {
					if (!rspamd_map_read_http_cached_file (map, bk, bk->data.hd,
							&fake_cbd.cbdata)) {

						if (map->fallback_backend) {
							/* Try fallback */
							g_assert (map->fallback_backend->protocol ==
									  MAP_PROTO_FILE);
							if (!read_map_file (map,
									map->fallback_backend->data.fd,
									map->fallback_backend, &fake_cbd)) {
								succeed = FALSE;
								break;
							}
						}
						else {
							succeed = FALSE;
							break;
						}
					}
				}
				else {
					g_assert_not_reached ();
				}
			}

			if (succeed) {
				map->fin_callback (&fake_cbd.cbdata, map->user_data);
			}
			else {
				msg_info_map ("preload of %s failed", map->name);
			}

		}

		cur = g_list_next (cur);
	}
}

void
rspamd_map_remove_all (struct rspamd_config *cfg)
{
	struct rspamd_map *map;
	GList *cur;
	struct rspamd_map_backend *bk;
	struct map_cb_data cbdata;
	guint i;

	for (cur = cfg->maps; cur != NULL; cur = g_list_next (cur)) {
		map = cur->data;

		if (map->tmp_dtor) {
			map->tmp_dtor (map->tmp_dtor_data);
		}

		if (map->dtor) {
			cbdata.prev_data = NULL;
			cbdata.map = map;
			cbdata.cur_data = *map->user_data;

			map->dtor (&cbdata);
			*map->user_data = NULL;
		}

		for (i = 0; i < map->backends->len; i ++) {
			bk = g_ptr_array_index (map->backends, i);

			MAP_RELEASE (bk, "rspamd_map_backend");
		}

		if (map->fallback_backend) {
			MAP_RELEASE (map->fallback_backend, "rspamd_map_backend");
		}
	}

	g_list_free (cfg->maps);
	cfg->maps = NULL;
}

static const gchar *
rspamd_map_check_proto (struct rspamd_config *cfg,
		const gchar *map_line, struct rspamd_map_backend *bk)
{
	const gchar *pos = map_line, *end, *end_key;

	g_assert (bk != NULL);
	g_assert (pos != NULL);

	end = pos + strlen (pos);

	/* Static check */
	if (g_ascii_strcasecmp (pos, "static") == 0) {
		bk->protocol = MAP_PROTO_STATIC;
		bk->uri = g_strdup (pos);

		return pos;
	}
	else if (g_ascii_strcasecmp (pos, "zst+static") == 0) {
		bk->protocol = MAP_PROTO_STATIC;
		bk->uri = g_strdup (pos + 4);
		bk->is_compressed = TRUE;

		return pos + 4;
	}

	for (;;) {
		if (g_ascii_strncasecmp (pos, "sign+", sizeof ("sign+") - 1) == 0) {
			bk->is_signed = TRUE;
			pos += sizeof ("sign+") - 1;
		}
		else if (g_ascii_strncasecmp (pos, "fallback+", sizeof ("fallback+") - 1) == 0) {
			bk->is_fallback = TRUE;
			pos += sizeof ("fallback+") - 1;
		}
		else if (g_ascii_strncasecmp (pos, "key=", sizeof ("key=") - 1) == 0) {
			pos += sizeof ("key=") - 1;
			end_key = memchr (pos, '+', end - pos);

			if (end_key != NULL) {
				bk->trusted_pubkey = rspamd_pubkey_from_base32 (pos, end_key - pos,
						RSPAMD_KEYPAIR_SIGN, RSPAMD_CRYPTOBOX_MODE_25519);

				if (bk->trusted_pubkey == NULL) {
					msg_err_config ("cannot read pubkey from map: %s",
							map_line);
					return NULL;
				}
				pos = end_key + 1;
			} else if (end - pos > 64) {
				/* Try hex encoding */
				bk->trusted_pubkey = rspamd_pubkey_from_hex (pos, 64,
						RSPAMD_KEYPAIR_SIGN, RSPAMD_CRYPTOBOX_MODE_25519);

				if (bk->trusted_pubkey == NULL) {
					msg_err_config ("cannot read pubkey from map: %s",
							map_line);
					return NULL;
				}
				pos += 64;
			} else {
				msg_err_config ("cannot read pubkey from map: %s",
						map_line);
				return NULL;
			}

			if (*pos == '+' || *pos == ':') {
				pos++;
			}
		}
		else {
			/* No known flags */
			break;
		}
	}

	bk->protocol = MAP_PROTO_FILE;

	if (g_ascii_strncasecmp (pos, "http://", sizeof ("http://") - 1) == 0) {
		bk->protocol = MAP_PROTO_HTTP;
		/* Include http:// */
		bk->uri = g_strdup (pos);
		pos += sizeof ("http://") - 1;
	}
	else if (g_ascii_strncasecmp (pos, "https://", sizeof ("https://") - 1) == 0) {
		bk->protocol = MAP_PROTO_HTTPS;
		/* Include https:// */
		bk->uri = g_strdup (pos);
		pos += sizeof ("https://") - 1;
	}
	else if (g_ascii_strncasecmp (pos, "file://", sizeof ("file://") - 1) == 0) {
		pos += sizeof ("file://") - 1;
		/* Exclude file:// */
		bk->uri = g_strdup (pos);
	}
	else if (*pos == '/') {
		/* Trivial file case */
		bk->uri = g_strdup (pos);
	}
	else {
		msg_err_config ("invalid map fetching protocol: %s", map_line);

		return NULL;
	}

	if (bk->protocol != MAP_PROTO_FILE && bk->is_signed) {
		msg_err_config ("signed maps are no longer supported for HTTP(s): %s", map_line);
	}

	return pos;
}

gboolean
rspamd_map_is_map (const gchar *map_line)
{
	gboolean ret = FALSE;

	g_assert (map_line != NULL);

	if (map_line[0] == '/') {
		ret = TRUE;
	}
	else if (g_ascii_strncasecmp (map_line, "sign+", sizeof ("sign+") - 1) == 0) {
		ret = TRUE;
	}
	else if (g_ascii_strncasecmp (map_line, "fallback+", sizeof ("fallback+") - 1) == 0) {
		ret = TRUE;
	}
	else if (g_ascii_strncasecmp (map_line, "file://", sizeof ("file://") - 1) == 0) {
		ret = TRUE;
	}
	else if (g_ascii_strncasecmp (map_line, "http://", sizeof ("http://") - 1) == 0) {
		ret = TRUE;
	}
	else if (g_ascii_strncasecmp (map_line, "https://", sizeof ("https://") - 1) == 0) {
		ret = TRUE;
	}

	return ret;
}

static void
rspamd_map_backend_dtor (struct rspamd_map_backend *bk)
{
	g_free (bk->uri);

	switch (bk->protocol) {
	case MAP_PROTO_FILE:
		if (bk->data.fd) {
			ev_stat_stop (bk->event_loop, &bk->data.fd->st_ev);
			g_free (bk->data.fd->filename);
			g_free (bk->data.fd);
		}
		break;
	case MAP_PROTO_STATIC:
		if (bk->data.sd) {
			if (bk->data.sd->data) {
				g_free (bk->data.sd->data);
			}

			g_free (bk->data.sd);
		}
		break;
	case MAP_PROTO_HTTP:
	case MAP_PROTO_HTTPS:
		if (bk->data.hd) {
			struct http_map_data *data = bk->data.hd;

			g_free (data->host);
			g_free (data->path);
			g_free (data->rest);

			if (data->userinfo) {
				g_free (data->userinfo);
			}

			if (data->etag) {
				rspamd_fstring_free (data->etag);
			}

			if (g_atomic_int_compare_and_exchange (&data->cache->available, 1, 0)) {
				if (data->cur_cache_cbd) {
					MAP_RELEASE (data->cur_cache_cbd->shm,
							"rspamd_http_map_cached_cbdata");
					ev_timer_stop (data->cur_cache_cbd->event_loop,
							&data->cur_cache_cbd->timeout);
					g_free (data->cur_cache_cbd);
					data->cur_cache_cbd = NULL;
				}

				unlink (data->cache->shmem_name);
			}

			g_free (bk->data.hd);
		}
		break;
	}

	if (bk->trusted_pubkey) {
		rspamd_pubkey_unref (bk->trusted_pubkey);
	}

	g_free (bk);
}

static struct rspamd_map_backend *
rspamd_map_parse_backend (struct rspamd_config *cfg, const gchar *map_line)
{
	struct rspamd_map_backend *bk;
	struct file_map_data *fdata = NULL;
	struct http_map_data *hdata = NULL;
	struct static_map_data *sdata = NULL;
	struct http_parser_url up;
	const gchar *end, *p;
	rspamd_ftok_t tok;

	bk = g_malloc0 (sizeof (*bk));
	REF_INIT_RETAIN (bk, rspamd_map_backend_dtor);

	if (!rspamd_map_check_proto (cfg, map_line, bk)) {
		goto err;
	}

	if (bk->is_fallback && bk->protocol != MAP_PROTO_FILE) {
		msg_err_config ("fallback backend must be file for %s", bk->uri);

		goto err;
	}

	end = map_line + strlen (map_line);
	if (end - map_line > 5) {
		p = end - 5;
		if (g_ascii_strcasecmp (p, ".zstd") == 0) {
			bk->is_compressed = TRUE;
		}
		p = end - 4;
		if (g_ascii_strcasecmp (p, ".zst") == 0) {
			bk->is_compressed = TRUE;
		}
	}

	/* Now check for each proto separately */
	if (bk->protocol == MAP_PROTO_FILE) {
		fdata = g_malloc0 (sizeof (struct file_map_data));

		if (access (bk->uri, R_OK) == -1) {
			if (errno != ENOENT) {
				msg_err_config ("cannot open file '%s': %s", bk->uri, strerror (errno));
				goto err;
			}

			msg_info_config (
					"map '%s' is not found, but it can be loaded automatically later",
					bk->uri);
		}

		fdata->filename = g_strdup (bk->uri);
		bk->data.fd = fdata;
	}
	else if (bk->protocol == MAP_PROTO_HTTP || bk->protocol == MAP_PROTO_HTTPS) {
		hdata = g_malloc0 (sizeof (struct http_map_data));

		memset (&up, 0, sizeof (up));
		if (http_parser_parse_url (bk->uri, strlen (bk->uri), FALSE,
				&up) != 0) {
			msg_err_config ("cannot parse HTTP url: %s", bk->uri);
			goto err;
		}
		else {
			if (!(up.field_set & 1u << UF_HOST)) {
				msg_err_config ("cannot parse HTTP url: %s: no host", bk->uri);
				goto err;
			}

			tok.begin = bk->uri + up.field_data[UF_HOST].off;
			tok.len = up.field_data[UF_HOST].len;
			hdata->host = rspamd_ftokdup (&tok);

			if (up.field_set & (1u << UF_PORT)) {
				hdata->port = up.port;
			}
			else {
				if (bk->protocol == MAP_PROTO_HTTP) {
					hdata->port = 80;
				}
				else {
					hdata->port = 443;
				}
			}

			if (up.field_set & (1u << UF_PATH)) {
				tok.begin = bk->uri + up.field_data[UF_PATH].off;
				tok.len = up.field_data[UF_PATH].len;

				hdata->path = rspamd_ftokdup (&tok);

				/* We also need to check query + fragment */
				if (up.field_set & ((1u << UF_QUERY) | (1u << UF_FRAGMENT))) {
					tok.begin = bk->uri + up.field_data[UF_PATH].off +
							up.field_data[UF_PATH].len;
					tok.len = strlen (tok.begin);
					hdata->rest = rspamd_ftokdup (&tok);
				}
				else {
					hdata->rest = g_strdup ("");
				}
			}

			if (up.field_set & (1u << UF_USERINFO)) {
				/* Create authorisation header for basic auth */
				guint len = sizeof ("Basic ") +
							up.field_data[UF_USERINFO].len * 8 / 5 + 4;
				hdata->userinfo = g_malloc (len);
				rspamd_snprintf (hdata->userinfo, len, "Basic %*Bs",
						(int)up.field_data[UF_USERINFO].len,
						bk->uri + up.field_data[UF_USERINFO].off);
			}
		}

		hdata->cache = rspamd_mempool_alloc0_shared (cfg->cfg_pool,
						sizeof (*hdata->cache));

		bk->data.hd = hdata;
	}
	else if (bk->protocol == MAP_PROTO_STATIC) {
		sdata = g_malloc0 (sizeof (*sdata));
		bk->data.sd = sdata;
	}

	bk->id = rspamd_cryptobox_fast_hash_specific (RSPAMD_CRYPTOBOX_T1HA,
			bk->uri, strlen (bk->uri), 0xdeadbabe);

	return bk;

err:
	MAP_RELEASE (bk, "rspamd_map_backend");

	if (hdata) {
		g_free (hdata);
	}

	return NULL;
}

static void
rspamd_map_calculate_hash (struct rspamd_map *map)
{
	struct rspamd_map_backend *bk;
	guint i;
	rspamd_cryptobox_hash_state_t st;
	gchar *cksum_encoded, cksum[rspamd_cryptobox_HASHBYTES];

	rspamd_cryptobox_hash_init (&st, NULL, 0);

	for (i = 0; i < map->backends->len; i ++) {
		bk = g_ptr_array_index (map->backends, i);
		rspamd_cryptobox_hash_update (&st, bk->uri, strlen (bk->uri));
	}

	rspamd_cryptobox_hash_final (&st, cksum);
	cksum_encoded = rspamd_encode_base32 (cksum, sizeof (cksum), RSPAMD_BASE32_DEFAULT);
	rspamd_strlcpy (map->tag, cksum_encoded, sizeof (map->tag));
	g_free (cksum_encoded);
}

static gboolean
rspamd_map_add_static_string (struct rspamd_config *cfg,
		const ucl_object_t *elt,
		GString *target)
{
	gsize sz;
	const gchar *dline;

	if (ucl_object_type (elt) != UCL_STRING) {
		msg_err_config ("map has static backend but `data` is "
						"not string like: %s",
				ucl_object_type_to_string (elt->type));
		return FALSE;
	}

	/* Otherwise, we copy data to the backend */
	dline = ucl_object_tolstring (elt, &sz);

	if (sz == 0) {
		msg_err_config ("map has static backend but empty no data");
		return FALSE;
	}

	g_string_append_len (target, dline, sz);
	g_string_append_c (target, '\n');

	return TRUE;
}

struct rspamd_map *
rspamd_map_add (struct rspamd_config *cfg,
				const gchar *map_line,
				const gchar *description,
				map_cb_t read_callback,
				map_fin_cb_t fin_callback,
				map_dtor_t dtor,
				void **user_data,
				struct rspamd_worker *worker,
				int flags)
{
	struct rspamd_map *map;
	struct rspamd_map_backend *bk;

	bk = rspamd_map_parse_backend (cfg, map_line);
	if (bk == NULL) {
		return NULL;
	}

	if (bk->is_fallback) {
		msg_err_config ("cannot add map with fallback only backend: %s", bk->uri);
		REF_RELEASE (bk);

		return NULL;
	}

	map = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (struct rspamd_map));
	map->read_callback = read_callback;
	map->fin_callback = fin_callback;
	map->dtor = dtor;
	map->user_data = user_data;
	map->cfg = cfg;
	map->id = rspamd_random_uint64_fast ();
	map->locked =
		rspamd_mempool_alloc0_shared (cfg->cfg_pool, sizeof (gint));
	map->backends = g_ptr_array_sized_new (1);
	map->wrk = worker;
	rspamd_mempool_add_destructor (cfg->cfg_pool, rspamd_ptr_array_free_hard,
			map->backends);
	g_ptr_array_add (map->backends, bk);
	map->name = rspamd_mempool_strdup (cfg->cfg_pool, map_line);
	map->no_file_read = (flags & RSPAMD_MAP_FILE_NO_READ);

	if (bk->protocol == MAP_PROTO_FILE) {
		map->poll_timeout = (cfg->map_timeout * cfg->map_file_watch_multiplier);
	} else {
		map->poll_timeout = cfg->map_timeout;
	}

	if (description != NULL) {
		map->description = rspamd_mempool_strdup (cfg->cfg_pool, description);
	}

	rspamd_map_calculate_hash (map);
	msg_info_map ("added map %s", bk->uri);

	cfg->maps = g_list_prepend (cfg->maps, map);

	return map;
}

static inline void
rspamd_map_add_backend (struct rspamd_map *map, struct rspamd_map_backend *bk)
{
	if (bk->is_fallback) {
		if (map->fallback_backend) {
			msg_warn_map ("redefining fallback backend from %s to %s",
					map->fallback_backend->uri, bk->uri);
		}

		map->fallback_backend = bk;
	}
	else {
		g_ptr_array_add (map->backends, bk);
	}
}

struct rspamd_map*
rspamd_map_add_from_ucl (struct rspamd_config *cfg,
						 const ucl_object_t *obj,
						 const gchar *description,
						 map_cb_t read_callback,
						 map_fin_cb_t fin_callback,
						 map_dtor_t dtor,
						 void **user_data,
						 struct rspamd_worker *worker,
						 gint flags)
{
	ucl_object_iter_t it = NULL;
	const ucl_object_t *cur, *elt;
	struct rspamd_map *map;
	struct rspamd_map_backend *bk;
	guint i;

	g_assert (obj != NULL);

	if (ucl_object_type (obj) == UCL_STRING) {
		/* Just a plain string */
		return rspamd_map_add (cfg, ucl_object_tostring (obj), description,
				read_callback, fin_callback, dtor, user_data, worker, flags);
	}

	map = rspamd_mempool_alloc0 (cfg->cfg_pool, sizeof (struct rspamd_map));
	map->read_callback = read_callback;
	map->fin_callback = fin_callback;
	map->dtor = dtor;
	map->user_data = user_data;
	map->cfg = cfg;
	map->id = rspamd_random_uint64_fast ();
	map->locked =
			rspamd_mempool_alloc0_shared (cfg->cfg_pool, sizeof (gint));
	map->backends = g_ptr_array_new ();
	map->wrk = worker;
	map->no_file_read = (flags & RSPAMD_MAP_FILE_NO_READ);
	rspamd_mempool_add_destructor (cfg->cfg_pool, rspamd_ptr_array_free_hard,
			map->backends);
	map->poll_timeout = cfg->map_timeout;

	if (description) {
		map->description = rspamd_mempool_strdup (cfg->cfg_pool, description);
	}

	if (ucl_object_type (obj) == UCL_ARRAY) {
		/* Add array of maps as multiple backends */
		while ((cur = ucl_object_iterate (obj, &it, true)) != NULL) {
			if (ucl_object_type (cur) == UCL_STRING) {
				bk = rspamd_map_parse_backend (cfg, ucl_object_tostring (cur));

				if (bk != NULL) {
					rspamd_map_add_backend (map, bk);

					if (!map->name) {
						map->name = rspamd_mempool_strdup (cfg->cfg_pool,
								ucl_object_tostring (cur));
					}
				}
			}
			else {
				msg_err_config ("bad map element type: %s",
						ucl_object_type_to_string (ucl_object_type (cur)));
			}
		}

		if (map->backends->len == 0) {
			msg_err_config ("map has no urls to be loaded: empty list");
			goto err;
		}
	}
	else if (ucl_object_type (obj) == UCL_OBJECT) {
		elt = ucl_object_lookup (obj, "name");
		if (elt && ucl_object_type (elt) == UCL_STRING) {
			map->name = rspamd_mempool_strdup (cfg->cfg_pool,
					ucl_object_tostring (elt));
		}

		elt = ucl_object_lookup (obj, "description");
		if (elt && ucl_object_type (elt) == UCL_STRING) {
			map->description = rspamd_mempool_strdup (cfg->cfg_pool,
					ucl_object_tostring (elt));
		}

		elt = ucl_object_lookup_any (obj, "timeout", "poll", "poll_time",
				"watch_interval", NULL);
		if (elt) {
			map->poll_timeout = ucl_object_todouble (elt);
		}

		elt = ucl_object_lookup_any (obj, "upstreams", "url", "urls", NULL);
		if (elt == NULL) {
			msg_err_config ("map has no urls to be loaded: no elt");
			goto err;
		}

		if (ucl_object_type (elt) == UCL_ARRAY) {
			/* Add array of maps as multiple backends */
			it = ucl_object_iterate_new (elt);

			while ((cur = ucl_object_iterate_safe (it, true)) != NULL) {
				if (ucl_object_type (cur) == UCL_STRING) {
					bk = rspamd_map_parse_backend (cfg, ucl_object_tostring (cur));

					if (bk != NULL) {
						rspamd_map_add_backend (map, bk);

						if (!map->name) {
							map->name = rspamd_mempool_strdup (cfg->cfg_pool,
									ucl_object_tostring (cur));
						}
					}
				}
				else {
					msg_err_config ("bad map element type: %s",
							ucl_object_type_to_string (ucl_object_type (cur)));
					ucl_object_iterate_free (it);
					goto err;
				}
			}

			ucl_object_iterate_free (it);

			if (map->backends->len == 0) {
				msg_err_config ("map has no urls to be loaded: empty object list");
				goto err;
			}
		}
		else if (ucl_object_type (elt) == UCL_STRING) {
			bk = rspamd_map_parse_backend (cfg, ucl_object_tostring (elt));

			if (bk != NULL) {
				rspamd_map_add_backend (map, bk);

				if (!map->name) {
					map->name = rspamd_mempool_strdup (cfg->cfg_pool,
							ucl_object_tostring (elt));
				}
			}
		}

		if (!map->backends || map->backends->len == 0) {
			msg_err_config ("map has no urls to be loaded: no valid backends");
			goto err;
		}
	}
	else {
		msg_err_config ("map has invalid type for value: %s",
				ucl_object_type_to_string (ucl_object_type (obj)));
		goto err;
	}

	gboolean all_local = TRUE;

	PTR_ARRAY_FOREACH (map->backends, i, bk) {
		if (bk->protocol == MAP_PROTO_STATIC) {
			GString *map_data;
			/* We need data field in ucl */
			elt = ucl_object_lookup (obj, "data");

			if (elt == NULL) {
				msg_err_config ("map has static backend but no `data` field");
				goto err;
			}


			if (ucl_object_type (elt) == UCL_STRING) {
				map_data = g_string_sized_new (32);

				if (rspamd_map_add_static_string (cfg, elt, map_data)) {
					bk->data.sd->data = map_data->str;
					bk->data.sd->len = map_data->len;
					g_string_free (map_data, FALSE);
				}
				else {
					g_string_free (map_data, TRUE);
					msg_err_config ("map has static backend with invalid `data` field");
					goto err;
				}
			}
			else if (ucl_object_type (elt) == UCL_ARRAY) {
				map_data = g_string_sized_new (32);
				it = ucl_object_iterate_new (elt);

				while ((cur = ucl_object_iterate_safe (it, true))) {
					if (!rspamd_map_add_static_string (cfg, cur, map_data)) {
						g_string_free (map_data, TRUE);
						msg_err_config ("map has static backend with invalid "
										"`data` field");
						ucl_object_iterate_free (it);
						goto err;
					}
				}

				ucl_object_iterate_free (it);
				bk->data.sd->data = map_data->str;
				bk->data.sd->len = map_data->len;
				g_string_free (map_data, FALSE);
			}
		}
		else if (bk->protocol != MAP_PROTO_FILE) {
			all_local = FALSE;
		}
	}

	if (all_local) {
		map->poll_timeout = (map->poll_timeout *
							 cfg->map_file_watch_multiplier);
	}

	rspamd_map_calculate_hash (map);
	msg_debug_map ("added map from ucl");

	cfg->maps = g_list_prepend (cfg->maps, map);

	return map;

err:

	if (map) {
		PTR_ARRAY_FOREACH (map->backends, i, bk) {
			MAP_RELEASE (bk, "rspamd_map_backend");
		}
	}

	return NULL;
}

rspamd_map_traverse_function
rspamd_map_get_traverse_function (struct rspamd_map *map)
{
	if (map) {
		return map->traverse_function;
	}

	return NULL;
}

void
rspamd_map_traverse (struct rspamd_map *map, rspamd_map_traverse_cb cb,
		gpointer cbdata, gboolean reset_hits)
{
	if (*map->user_data && map->traverse_function) {
		map->traverse_function (*map->user_data, cb, cbdata, reset_hits);
	}
}