summaryrefslogtreecommitdiffstats
path: root/src/libserver/dkim.c
blob: 4318e87ad1043bf0631fe289396f699d32c455a5 (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
/*-
 * 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 "config.h"
#include "rspamd.h"
#include "message.h"
#include "dkim.h"
#include "dns.h"
#include "utlist.h"
#include "unix-std.h"
#include "mempool_vars_internal.h"

#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>

/* special DNS tokens */
#define DKIM_DNSKEYNAME "_domainkey"

/* ed25519 key lengths */
#define ED25519_B64_BYTES 45
#define ED25519_BYTES 32

/* Canonization methods */
#define DKIM_CANON_UNKNOWN (-1) /* unknown method */
#define DKIM_CANON_SIMPLE 0     /* as specified in DKIM spec */
#define DKIM_CANON_RELAXED 1    /* as specified in DKIM spec */

#define DKIM_CANON_DEFAULT DKIM_CANON_SIMPLE

#define RSPAMD_SHORT_BH_LEN 8

/* Params */
enum rspamd_dkim_param_type {
	DKIM_PARAM_UNKNOWN = -1,
	DKIM_PARAM_SIGNATURE = 0,
	DKIM_PARAM_SIGNALG,
	DKIM_PARAM_DOMAIN,
	DKIM_PARAM_CANONALG,
	DKIM_PARAM_QUERYMETHOD,
	DKIM_PARAM_SELECTOR,
	DKIM_PARAM_HDRLIST,
	DKIM_PARAM_VERSION,
	DKIM_PARAM_IDENTITY,
	DKIM_PARAM_TIMESTAMP,
	DKIM_PARAM_EXPIRATION,
	DKIM_PARAM_COPIEDHDRS,
	DKIM_PARAM_BODYHASH,
	DKIM_PARAM_BODYLENGTH,
	DKIM_PARAM_IDX,
	DKIM_PARAM_CV,
	DKIM_PARAM_IGNORE
};

#define RSPAMD_DKIM_MAX_ARC_IDX 10

#define msg_err_dkim(...) rspamd_default_log_function(G_LOG_LEVEL_CRITICAL,       \
													  "dkim", ctx->pool->tag.uid, \
													  RSPAMD_LOG_FUNC,            \
													  __VA_ARGS__)
#define msg_warn_dkim(...) rspamd_default_log_function(G_LOG_LEVEL_WARNING,        \
													   "dkim", ctx->pool->tag.uid, \
													   RSPAMD_LOG_FUNC,            \
													   __VA_ARGS__)
#define msg_info_dkim(...) rspamd_default_log_function(G_LOG_LEVEL_INFO,           \
													   "dkim", ctx->pool->tag.uid, \
													   RSPAMD_LOG_FUNC,            \
													   __VA_ARGS__)
#define msg_debug_dkim(...) rspamd_conditional_debug_fast(NULL, NULL,                                     \
														  rspamd_dkim_log_id, "dkim", ctx->pool->tag.uid, \
														  RSPAMD_LOG_FUNC,                                \
														  __VA_ARGS__)
#define msg_debug_dkim_taskless(...) rspamd_conditional_debug_fast(NULL, NULL,                     \
																   rspamd_dkim_log_id, "dkim", "", \
																   RSPAMD_LOG_FUNC,                \
																   __VA_ARGS__)

INIT_LOG_MODULE(dkim)

#define RSPAMD_DKIM_FLAG_OVERSIGN (1u << 0u)
#define RSPAMD_DKIM_FLAG_OVERSIGN_EXISTING (1u << 1u)

union rspamd_dkim_header_stat {
	struct _st {
		guint16 count;
		guint16 flags;
	} s;
	guint32 n;
};

struct rspamd_dkim_common_ctx {
	rspamd_mempool_t *pool;
	guint64 sig_hash;
	gsize len;
	GPtrArray *hlist;
	GHashTable *htable; /* header -> count mapping */
	EVP_MD_CTX *headers_hash;
	EVP_MD_CTX *body_hash;
	enum rspamd_dkim_type type;
	guint idx;
	gint header_canon_type;
	gint body_canon_type;
	guint body_canonicalised;
	guint headers_canonicalised;
	gboolean is_sign;
};

enum rspamd_arc_seal_cv {
	RSPAMD_ARC_UNKNOWN = 0,
	RSPAMD_ARC_NONE,
	RSPAMD_ARC_INVALID,
	RSPAMD_ARC_FAIL,
	RSPAMD_ARC_PASS
};


struct rspamd_dkim_context_s {
	struct rspamd_dkim_common_ctx common;
	rspamd_mempool_t *pool;
	struct rspamd_dns_resolver *resolver;
	gsize blen;
	gsize bhlen;
	gint sig_alg;
	guint ver;
	time_t timestamp;
	time_t expiration;
	gchar *domain;
	gchar *selector;
	gint8 *b;
	gchar *short_b;
	gint8 *bh;
	gchar *dns_key;
	enum rspamd_arc_seal_cv cv;
	const gchar *dkim_header;
};

#define RSPAMD_DKIM_KEY_ID_LEN 16

struct rspamd_dkim_key_s {
	guint8 *keydata;
	guint8 *raw_key;
	gsize keylen;
	gsize decoded_len;
	gchar key_id[RSPAMD_DKIM_KEY_ID_LEN];
	union {
		RSA *key_rsa;
		EC_KEY *key_ecdsa;
		guchar *key_eddsa;
	} key;
	BIO *key_bio;
	EVP_PKEY *key_evp;
	time_t mtime;
	guint ttl;
	enum rspamd_dkim_key_type type;
	ref_entry_t ref;
};

struct rspamd_dkim_sign_context_s {
	struct rspamd_dkim_common_ctx common;
	rspamd_dkim_sign_key_t *key;
};

struct rspamd_dkim_header {
	const gchar *name;
	gint count;
};

/* Parser of dkim params */
typedef gboolean (*dkim_parse_param_f)(rspamd_dkim_context_t *ctx,
									   const gchar *param, gsize len, GError **err);

static gboolean rspamd_dkim_parse_signature(rspamd_dkim_context_t *ctx,
											const gchar *param,
											gsize len,
											GError **err);
static gboolean rspamd_dkim_parse_signalg(rspamd_dkim_context_t *ctx,
										  const gchar *param,
										  gsize len,
										  GError **err);
static gboolean rspamd_dkim_parse_domain(rspamd_dkim_context_t *ctx,
										 const gchar *param,
										 gsize len,
										 GError **err);
static gboolean rspamd_dkim_parse_canonalg(rspamd_dkim_context_t *ctx,
										   const gchar *param,
										   gsize len,
										   GError **err);
static gboolean rspamd_dkim_parse_ignore(rspamd_dkim_context_t *ctx,
										 const gchar *param,
										 gsize len,
										 GError **err);
static gboolean rspamd_dkim_parse_selector(rspamd_dkim_context_t *ctx,
										   const gchar *param,
										   gsize len,
										   GError **err);
static gboolean rspamd_dkim_parse_hdrlist(rspamd_dkim_context_t *ctx,
										  const gchar *param,
										  gsize len,
										  GError **err);
static gboolean rspamd_dkim_parse_version(rspamd_dkim_context_t *ctx,
										  const gchar *param,
										  gsize len,
										  GError **err);
static gboolean rspamd_dkim_parse_timestamp(rspamd_dkim_context_t *ctx,
											const gchar *param,
											gsize len,
											GError **err);
static gboolean rspamd_dkim_parse_expiration(rspamd_dkim_context_t *ctx,
											 const gchar *param,
											 gsize len,
											 GError **err);
static gboolean rspamd_dkim_parse_bodyhash(rspamd_dkim_context_t *ctx,
										   const gchar *param,
										   gsize len,
										   GError **err);
static gboolean rspamd_dkim_parse_bodylength(rspamd_dkim_context_t *ctx,
											 const gchar *param,
											 gsize len,
											 GError **err);
static gboolean rspamd_dkim_parse_idx(rspamd_dkim_context_t *ctx,
									  const gchar *param,
									  gsize len,
									  GError **err);
static gboolean rspamd_dkim_parse_cv(rspamd_dkim_context_t *ctx,
									 const gchar *param,
									 gsize len,
									 GError **err);


static const dkim_parse_param_f parser_funcs[] = {
	[DKIM_PARAM_SIGNATURE] = rspamd_dkim_parse_signature,
	[DKIM_PARAM_SIGNALG] = rspamd_dkim_parse_signalg,
	[DKIM_PARAM_DOMAIN] = rspamd_dkim_parse_domain,
	[DKIM_PARAM_CANONALG] = rspamd_dkim_parse_canonalg,
	[DKIM_PARAM_QUERYMETHOD] = rspamd_dkim_parse_ignore,
	[DKIM_PARAM_SELECTOR] = rspamd_dkim_parse_selector,
	[DKIM_PARAM_HDRLIST] = rspamd_dkim_parse_hdrlist,
	[DKIM_PARAM_VERSION] = rspamd_dkim_parse_version,
	[DKIM_PARAM_IDENTITY] = rspamd_dkim_parse_ignore,
	[DKIM_PARAM_TIMESTAMP] = rspamd_dkim_parse_timestamp,
	[DKIM_PARAM_EXPIRATION] = rspamd_dkim_parse_expiration,
	[DKIM_PARAM_COPIEDHDRS] = rspamd_dkim_parse_ignore,
	[DKIM_PARAM_BODYHASH] = rspamd_dkim_parse_bodyhash,
	[DKIM_PARAM_BODYLENGTH] = rspamd_dkim_parse_bodylength,
	[DKIM_PARAM_IDX] = rspamd_dkim_parse_idx,
	[DKIM_PARAM_CV] = rspamd_dkim_parse_cv,
	[DKIM_PARAM_IGNORE] = rspamd_dkim_parse_ignore,
};

#define DKIM_ERROR dkim_error_quark()
GQuark
dkim_error_quark(void)
{
	return g_quark_from_static_string("dkim-error-quark");
}

/* Parsers implementation */
static gboolean
rspamd_dkim_parse_signature(rspamd_dkim_context_t *ctx,
							const gchar *param,
							gsize len,
							GError **err)
{
	ctx->b = rspamd_mempool_alloc0(ctx->pool, len);
	ctx->short_b = rspamd_mempool_alloc0(ctx->pool, RSPAMD_SHORT_BH_LEN + 1);
	rspamd_strlcpy(ctx->short_b, param, MIN(len, RSPAMD_SHORT_BH_LEN + 1));
	(void) rspamd_cryptobox_base64_decode(param, len, ctx->b, &ctx->blen);

	return TRUE;
}

static gboolean
rspamd_dkim_parse_signalg(rspamd_dkim_context_t *ctx,
						  const gchar *param,
						  gsize len,
						  GError **err)
{
	/* XXX: ugly size comparison, improve this code style some day */
	if (len == 8) {
		if (memcmp(param, "rsa-sha1", len) == 0) {
			ctx->sig_alg = DKIM_SIGN_RSASHA1;
			return TRUE;
		}
	}
	else if (len == 10) {
		if (memcmp(param, "rsa-sha256", len) == 0) {
			ctx->sig_alg = DKIM_SIGN_RSASHA256;
			return TRUE;
		}
		else if (memcmp(param, "rsa-sha512", len) == 0) {
			ctx->sig_alg = DKIM_SIGN_RSASHA512;
			return TRUE;
		}
	}
	else if (len == 15) {
		if (memcmp(param, "ecdsa256-sha256", len) == 0) {
			ctx->sig_alg = DKIM_SIGN_ECDSASHA256;
			return TRUE;
		}
		else if (memcmp(param, "ecdsa256-sha512", len) == 0) {
			ctx->sig_alg = DKIM_SIGN_ECDSASHA512;
			return TRUE;
		}
	}
	else if (len == 14) {
		if (memcmp(param, "ed25519-sha256", len) == 0) {
			ctx->sig_alg = DKIM_SIGN_EDDSASHA256;
			return TRUE;
		}
	}

	g_set_error(err,
				DKIM_ERROR,
				DKIM_SIGERROR_INVALID_A,
				"invalid dkim sign algorithm");
	return FALSE;
}

static gboolean
rspamd_dkim_parse_domain(rspamd_dkim_context_t *ctx,
						 const gchar *param,
						 gsize len,
						 GError **err)
{
	if (!rspamd_str_has_8bit(param, len)) {
		ctx->domain = rspamd_mempool_alloc(ctx->pool, len + 1);
		rspamd_strlcpy(ctx->domain, param, len + 1);
	}
	else {
		ctx->domain = rspamd_dns_resolver_idna_convert_utf8(ctx->resolver,
															ctx->pool, param, len, NULL);

		if (!ctx->domain) {
			g_set_error(err,
						DKIM_ERROR,
						DKIM_SIGERROR_INVALID_H,
						"invalid dkim domain tag %.*s: idna failed",
						(int) len, param);

			return FALSE;
		}
	}

	return TRUE;
}

static gboolean
rspamd_dkim_parse_canonalg(rspamd_dkim_context_t *ctx,
						   const gchar *param,
						   gsize len,
						   GError **err)
{
	const gchar *p, *slash = NULL, *end = param + len;
	gsize sl = 0;

	p = param;
	while (p != end) {
		if (*p == '/') {
			slash = p;
			break;
		}
		p++;
		sl++;
	}

	if (slash == NULL) {
		/* Only check header */
		if (len == 6 && memcmp(param, "simple", len) == 0) {
			ctx->common.header_canon_type = DKIM_CANON_SIMPLE;
			return TRUE;
		}
		else if (len == 7 && memcmp(param, "relaxed", len) == 0) {
			ctx->common.header_canon_type = DKIM_CANON_RELAXED;
			return TRUE;
		}
	}
	else {
		/* First check header */
		if (sl == 6 && memcmp(param, "simple", sl) == 0) {
			ctx->common.header_canon_type = DKIM_CANON_SIMPLE;
		}
		else if (sl == 7 && memcmp(param, "relaxed", sl) == 0) {
			ctx->common.header_canon_type = DKIM_CANON_RELAXED;
		}
		else {
			goto err;
		}
		/* Check body */
		len -= sl + 1;
		slash++;
		if (len == 6 && memcmp(slash, "simple", len) == 0) {
			ctx->common.body_canon_type = DKIM_CANON_SIMPLE;
			return TRUE;
		}
		else if (len == 7 && memcmp(slash, "relaxed", len) == 0) {
			ctx->common.body_canon_type = DKIM_CANON_RELAXED;
			return TRUE;
		}
	}

err:
	g_set_error(err,
				DKIM_ERROR,
				DKIM_SIGERROR_INVALID_A,
				"invalid dkim canonization algorithm");
	return FALSE;
}

static gboolean
rspamd_dkim_parse_ignore(rspamd_dkim_context_t *ctx,
						 const gchar *param,
						 gsize len,
						 GError **err)
{
	/* Just ignore unused params */
	return TRUE;
}

static gboolean
rspamd_dkim_parse_selector(rspamd_dkim_context_t *ctx,
						   const gchar *param,
						   gsize len,
						   GError **err)
{

	if (!rspamd_str_has_8bit(param, len)) {
		ctx->selector = rspamd_mempool_alloc(ctx->pool, len + 1);
		rspamd_strlcpy(ctx->selector, param, len + 1);
	}
	else {
		ctx->selector = rspamd_dns_resolver_idna_convert_utf8(ctx->resolver,
															  ctx->pool, param, len, NULL);

		if (!ctx->selector) {
			g_set_error(err,
						DKIM_ERROR,
						DKIM_SIGERROR_INVALID_H,
						"invalid dkim selector tag %.*s: idna failed",
						(int) len, param);

			return FALSE;
		}
	}

	return TRUE;
}

static void
rspamd_dkim_hlist_free(void *ud)
{
	GPtrArray *a = ud;

	g_ptr_array_free(a, TRUE);
}

static gboolean
rspamd_dkim_parse_hdrlist_common(struct rspamd_dkim_common_ctx *ctx,
								 const gchar *param,
								 gsize len,
								 gboolean sign,
								 GError **err)
{
	const gchar *c, *p, *end = param + len;
	gchar *h;
	gboolean from_found = FALSE, oversign, existing;
	guint count = 0;
	struct rspamd_dkim_header *new;
	gpointer found;
	union rspamd_dkim_header_stat u;

	p = param;
	while (p <= end) {
		if ((p == end || *p == ':')) {
			count++;
		}
		p++;
	}

	if (count > 0) {
		ctx->hlist = g_ptr_array_sized_new(count);
	}
	else {
		return FALSE;
	}

	c = param;
	p = param;
	ctx->htable = g_hash_table_new(rspamd_strcase_hash, rspamd_strcase_equal);

	while (p <= end) {
		if ((p == end || *p == ':') && p - c > 0) {
			oversign = FALSE;
			existing = FALSE;
			h = rspamd_mempool_alloc(ctx->pool, p - c + 1);
			rspamd_strlcpy(h, c, p - c + 1);

			g_strstrip(h);

			if (sign) {
				if (rspamd_lc_cmp(h, "(o)", 3) == 0) {
					oversign = TRUE;
					h += 3;
					msg_debug_dkim("oversign header: %s", h);
				}
				else if (rspamd_lc_cmp(h, "(x)", 3) == 0) {
					oversign = TRUE;
					existing = TRUE;
					h += 3;
					msg_debug_dkim("oversign existing header: %s", h);
				}
			}

			/* Check mandatory from */
			if (!from_found && g_ascii_strcasecmp(h, "from") == 0) {
				from_found = TRUE;
			}

			new = rspamd_mempool_alloc(ctx->pool,
									   sizeof(struct rspamd_dkim_header));
			new->name = h;
			new->count = 0;
			u.n = 0;

			g_ptr_array_add(ctx->hlist, new);
			found = g_hash_table_lookup(ctx->htable, h);

			if (oversign) {
				if (found) {
					msg_err_dkim("specified oversigned header more than once: %s",
								 h);
				}

				u.s.flags |= RSPAMD_DKIM_FLAG_OVERSIGN;

				if (existing) {
					u.s.flags |= RSPAMD_DKIM_FLAG_OVERSIGN_EXISTING;
				}

				u.s.count = 0;
			}
			else {
				if (found != NULL) {
					u.n = GPOINTER_TO_UINT(found);
					new->count = u.s.count;
					u.s.count++;
				}
				else {
					/* Insert new header order to the list */
					u.s.count = new->count + 1;
				}
			}

			g_hash_table_insert(ctx->htable, h, GUINT_TO_POINTER(u.n));

			c = p + 1;
			p++;
		}
		else {
			p++;
		}
	}

	if (!ctx->hlist) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_INVALID_H,
					"invalid dkim header list");
		return FALSE;
	}
	else {
		if (!from_found) {
			g_ptr_array_free(ctx->hlist, TRUE);
			g_set_error(err,
						DKIM_ERROR,
						DKIM_SIGERROR_INVALID_H,
						"invalid dkim header list, from header is missing");
			return FALSE;
		}

		rspamd_mempool_add_destructor(ctx->pool,
									  (rspamd_mempool_destruct_t) rspamd_dkim_hlist_free,
									  ctx->hlist);
		rspamd_mempool_add_destructor(ctx->pool,
									  (rspamd_mempool_destruct_t) g_hash_table_unref,
									  ctx->htable);
	}

	return TRUE;
}

static gboolean
rspamd_dkim_parse_hdrlist(rspamd_dkim_context_t *ctx,
						  const gchar *param,
						  gsize len,
						  GError **err)
{
	return rspamd_dkim_parse_hdrlist_common(&ctx->common, param, len, FALSE, err);
}

static gboolean
rspamd_dkim_parse_version(rspamd_dkim_context_t *ctx,
						  const gchar *param,
						  gsize len,
						  GError **err)
{
	if (len != 1 || *param != '1') {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_VERSION,
					"invalid dkim version");
		return FALSE;
	}

	ctx->ver = 1;
	return TRUE;
}

static gboolean
rspamd_dkim_parse_timestamp(rspamd_dkim_context_t *ctx,
							const gchar *param,
							gsize len,
							GError **err)
{
	gulong val;

	if (!rspamd_strtoul(param, len, &val)) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_UNKNOWN,
					"invalid dkim timestamp");
		return FALSE;
	}
	ctx->timestamp = val;

	return TRUE;
}

static gboolean
rspamd_dkim_parse_expiration(rspamd_dkim_context_t *ctx,
							 const gchar *param,
							 gsize len,
							 GError **err)
{
	gulong val;

	if (!rspamd_strtoul(param, len, &val)) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_UNKNOWN,
					"invalid dkim expiration");
		return FALSE;
	}
	ctx->expiration = val;

	return TRUE;
}

static gboolean
rspamd_dkim_parse_bodyhash(rspamd_dkim_context_t *ctx,
						   const gchar *param,
						   gsize len,
						   GError **err)
{
	ctx->bh = rspamd_mempool_alloc0(ctx->pool, len);
	(void) rspamd_cryptobox_base64_decode(param, len, ctx->bh, &ctx->bhlen);

	return TRUE;
}

static gboolean
rspamd_dkim_parse_bodylength(rspamd_dkim_context_t *ctx,
							 const gchar *param,
							 gsize len,
							 GError **err)
{
	gulong val;

	if (!rspamd_strtoul(param, len, &val)) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_INVALID_L,
					"invalid dkim body length");
		return FALSE;
	}
	ctx->common.len = val;

	return TRUE;
}

static gboolean
rspamd_dkim_parse_idx(rspamd_dkim_context_t *ctx,
					  const gchar *param,
					  gsize len,
					  GError **err)
{
	gulong val;

	if (!rspamd_strtoul(param, len, &val)) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_INVALID_L,
					"invalid ARC idx");
		return FALSE;
	}
	ctx->common.idx = val;

	return TRUE;
}

static gboolean
rspamd_dkim_parse_cv(rspamd_dkim_context_t *ctx,
					 const gchar *param,
					 gsize len,
					 GError **err)
{

	/* Only check header */
	if (len == 4 && memcmp(param, "fail", len) == 0) {
		ctx->cv = RSPAMD_ARC_FAIL;
		return TRUE;
	}
	else if (len == 4 && memcmp(param, "pass", len) == 0) {
		ctx->cv = RSPAMD_ARC_PASS;
		return TRUE;
	}
	else if (len == 4 && memcmp(param, "none", len) == 0) {
		ctx->cv = RSPAMD_ARC_NONE;
		return TRUE;
	}
	else if (len == 7 && memcmp(param, "invalid", len) == 0) {
		ctx->cv = RSPAMD_ARC_INVALID;
		return TRUE;
	}

	g_set_error(err,
				DKIM_ERROR,
				DKIM_SIGERROR_UNKNOWN,
				"invalid arc seal verification result");

	return FALSE;
}


static void
rspamd_dkim_add_arc_seal_headers(rspamd_mempool_t *pool,
								 struct rspamd_dkim_common_ctx *ctx)
{
	struct rspamd_dkim_header *hdr;
	gint count = ctx->idx, i;

	ctx->hlist = g_ptr_array_sized_new(count * 3 - 1);

	for (i = 0; i < count; i++) {
		/* Authentication results */
		hdr = rspamd_mempool_alloc(pool, sizeof(*hdr));
		hdr->name = RSPAMD_DKIM_ARC_AUTHHEADER;
		hdr->count = -(i + 1);
		g_ptr_array_add(ctx->hlist, hdr);

		/* Arc signature */
		hdr = rspamd_mempool_alloc(pool, sizeof(*hdr));
		hdr->name = RSPAMD_DKIM_ARC_SIGNHEADER;
		hdr->count = -(i + 1);
		g_ptr_array_add(ctx->hlist, hdr);

		/* Arc seal (except last one) */
		if (i != count - 1) {
			hdr = rspamd_mempool_alloc(pool, sizeof(*hdr));
			hdr->name = RSPAMD_DKIM_ARC_SEALHEADER;
			hdr->count = -(i + 1);
			g_ptr_array_add(ctx->hlist, hdr);
		}
	}

	rspamd_mempool_add_destructor(ctx->pool,
								  (rspamd_mempool_destruct_t) rspamd_dkim_hlist_free,
								  ctx->hlist);
}

/**
 * Create new dkim context from signature
 * @param sig message's signature
 * @param pool pool to allocate memory from
 * @param err pointer to error object
 * @return new context or NULL
 */
rspamd_dkim_context_t *
rspamd_create_dkim_context(const gchar *sig,
						   rspamd_mempool_t *pool,
						   struct rspamd_dns_resolver *resolver,
						   guint time_jitter,
						   enum rspamd_dkim_type type,
						   GError **err)
{
	const gchar *p, *c, *tag = NULL, *end;
	gint taglen;
	gint param = DKIM_PARAM_UNKNOWN;
	const EVP_MD *md_alg;
	time_t now;
	rspamd_dkim_context_t *ctx;
	enum {
		DKIM_STATE_TAG = 0,
		DKIM_STATE_AFTER_TAG,
		DKIM_STATE_VALUE,
		DKIM_STATE_SKIP_SPACES = 99,
		DKIM_STATE_ERROR = 100
	} state,
		next_state;


	if (sig == NULL) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_EMPTY_B,
					"empty signature");
		return NULL;
	}

	ctx = rspamd_mempool_alloc0(pool, sizeof(rspamd_dkim_context_t));
	ctx->pool = pool;
	ctx->resolver = resolver;

	if (type == RSPAMD_DKIM_ARC_SEAL) {
		ctx->common.header_canon_type = DKIM_CANON_RELAXED;
		ctx->common.body_canon_type = DKIM_CANON_RELAXED;
	}
	else {
		ctx->common.header_canon_type = DKIM_CANON_DEFAULT;
		ctx->common.body_canon_type = DKIM_CANON_DEFAULT;
	}

	ctx->sig_alg = DKIM_SIGN_UNKNOWN;
	ctx->common.pool = pool;
	ctx->common.type = type;
	/* A simple state machine of parsing tags */
	state = DKIM_STATE_SKIP_SPACES;
	next_state = DKIM_STATE_TAG;
	taglen = 0;
	p = sig;
	c = sig;
	end = p + strlen(p);
	ctx->common.sig_hash = rspamd_cryptobox_fast_hash(sig, end - sig,
													  rspamd_hash_seed());

	msg_debug_dkim("create dkim context sig = %L", ctx->common.sig_hash);

	while (p <= end) {
		switch (state) {
		case DKIM_STATE_TAG:
			if (g_ascii_isspace(*p)) {
				taglen = (int) (p - c);
				while (*p && g_ascii_isspace(*p)) {
					/* Skip spaces before '=' sign */
					p++;
				}
				if (*p != '=') {
					g_set_error(err,
								DKIM_ERROR,
								DKIM_SIGERROR_UNKNOWN,
								"invalid dkim param");
					state = DKIM_STATE_ERROR;
				}
				else {
					state = DKIM_STATE_SKIP_SPACES;
					next_state = DKIM_STATE_AFTER_TAG;
					param = DKIM_PARAM_UNKNOWN;
					p++;
					tag = c;
				}
			}
			else if (*p == '=') {
				state = DKIM_STATE_SKIP_SPACES;
				next_state = DKIM_STATE_AFTER_TAG;
				param = DKIM_PARAM_UNKNOWN;
				p++;
				tag = c;
			}
			else {
				taglen++;

				if (taglen > G_MAXINT8) {
					g_set_error(err,
								DKIM_ERROR,
								DKIM_SIGERROR_UNKNOWN,
								"too long dkim tag");
					state = DKIM_STATE_ERROR;
				}
				else {
					p++;
				}
			}
			break;
		case DKIM_STATE_AFTER_TAG:
			/* We got tag at tag and len at taglen */
			switch (taglen) {
			case 0:
				g_set_error(err,
							DKIM_ERROR,
							DKIM_SIGERROR_UNKNOWN,
							"zero length dkim param");
				state = DKIM_STATE_ERROR;
				break;
			case 1:
				/* 1 character tags */
				switch (*tag) {
				case 'v':
					if (type == RSPAMD_DKIM_NORMAL) {
						param = DKIM_PARAM_VERSION;
					}
					else {
						g_set_error(err,
									DKIM_ERROR,
									DKIM_SIGERROR_UNKNOWN,
									"invalid ARC v param");
						state = DKIM_STATE_ERROR;
						break;
					}
					break;
				case 'a':
					param = DKIM_PARAM_SIGNALG;
					break;
				case 'b':
					param = DKIM_PARAM_SIGNATURE;
					break;
				case 'c':
					param = DKIM_PARAM_CANONALG;
					break;
				case 'd':
					param = DKIM_PARAM_DOMAIN;
					break;
				case 'h':
					if (type == RSPAMD_DKIM_ARC_SEAL) {
						g_set_error(err,
									DKIM_ERROR,
									DKIM_SIGERROR_UNKNOWN,
									"ARC seal must NOT have h= tag");
						state = DKIM_STATE_ERROR;
						break;
					}
					else {
						param = DKIM_PARAM_HDRLIST;
					}
					break;
				case 'i':
					if (type == RSPAMD_DKIM_NORMAL) {
						param = DKIM_PARAM_IDENTITY;
					}
					else {
						param = DKIM_PARAM_IDX;
					}
					break;
				case 'l':
					param = DKIM_PARAM_BODYLENGTH;
					break;
				case 'q':
					param = DKIM_PARAM_QUERYMETHOD;
					break;
				case 's':
					param = DKIM_PARAM_SELECTOR;
					break;
				case 't':
					param = DKIM_PARAM_TIMESTAMP;
					break;
				case 'x':
					param = DKIM_PARAM_EXPIRATION;
					break;
				case 'z':
					param = DKIM_PARAM_COPIEDHDRS;
					break;
				case 'r':
					param = DKIM_PARAM_IGNORE;
					break;
				default:
					param = DKIM_PARAM_UNKNOWN;
					msg_debug_dkim("unknown DKIM param %c, ignoring it", *tag);
					break;
				}
				break;
			case 2:
				/* Two characters tags, e.g. `bh` */
				if (tag[0] == 'b' && tag[1] == 'h') {
					if (type == RSPAMD_DKIM_ARC_SEAL) {
						g_set_error(err,
									DKIM_ERROR,
									DKIM_SIGERROR_UNKNOWN,
									"ARC seal must NOT have bh= tag");
						state = DKIM_STATE_ERROR;
					}
					else {
						param = DKIM_PARAM_BODYHASH;
					}
				}
				else if (tag[0] == 'c' && tag[1] == 'v') {
					if (type != RSPAMD_DKIM_ARC_SEAL) {
						g_set_error(err,
									DKIM_ERROR,
									DKIM_SIGERROR_UNKNOWN,
									"cv tag is valid for ARC-Seal only");
						state = DKIM_STATE_ERROR;
					}
					else {
						param = DKIM_PARAM_CV;
					}
				}
				else {
					param = DKIM_PARAM_UNKNOWN;
					msg_debug_dkim("unknown DKIM param %*s, ignoring it", taglen, tag);
				}
				break;
			default:
				/* Long and unknown (yet) DKIM tag */
				param = DKIM_PARAM_UNKNOWN;
				msg_debug_dkim("unknown DKIM param %*s, ignoring it", taglen, tag);
				break;
			}

			if (state != DKIM_STATE_ERROR) {
				/* Skip spaces */
				state = DKIM_STATE_SKIP_SPACES;
				next_state = DKIM_STATE_VALUE;
			}
			break;
		case DKIM_STATE_VALUE:
			if (*p == ';') {
				if (p - c == 0 || c > p) {
					state = DKIM_STATE_ERROR;
				}
				else {
					/* Cut trailing spaces for value */
					gint tlen = p - c;
					const gchar *tmp = p - 1;

					while (tlen > 0) {
						if (!g_ascii_isspace(*tmp)) {
							break;
						}
						tlen--;
						tmp--;
					}

					if (param != DKIM_PARAM_UNKNOWN) {
						if (!parser_funcs[param](ctx, c, tlen, err)) {
							state = DKIM_STATE_ERROR;
						}
						else {
							state = DKIM_STATE_SKIP_SPACES;
							next_state = DKIM_STATE_TAG;
							p++;
							taglen = 0;
						}
					}
					else {
						/* Unknown param has been ignored */
						msg_debug_dkim("ignored unknown tag parameter value: %*s = %*s",
									   taglen, tag, tlen, c);
						state = DKIM_STATE_SKIP_SPACES;
						next_state = DKIM_STATE_TAG;
						p++;
						taglen = 0;
					}
				}
			}
			else if (p == end) {
				/* Last parameter with no `;` character */
				gint tlen = p - c;
				const gchar *tmp = p - 1;

				while (tlen > 0) {
					if (!g_ascii_isspace(*tmp)) {
						break;
					}
					tlen--;
					tmp--;
				}

				if (param != DKIM_PARAM_UNKNOWN) {
					if (!parser_funcs[param](ctx, c, tlen, err)) {
						state = DKIM_STATE_ERROR;
					}
				}
				else {
					msg_debug_dkim("ignored unknown tag parameter value: %*s: %*s",
								   taglen, tag, tlen, c);
				}

				if (state == DKIM_STATE_ERROR) {
					/*
					 * We need to return from here as state machine won't
					 * do any more steps after p == end
					 */
					if (err) {
						msg_info_dkim("dkim parse failed: %e", *err);
					}

					return NULL;
				}
				/* Finish processing */
				p++;
			}
			else {
				p++;
			}
			break;
		case DKIM_STATE_SKIP_SPACES:
			if (g_ascii_isspace(*p)) {
				p++;
			}
			else {
				c = p;
				state = next_state;
			}
			break;
		case DKIM_STATE_ERROR:
			if (err && *err) {
				msg_info_dkim("dkim parse failed: %s", (*err)->message);
				return NULL;
			}
			else {
				msg_info_dkim("dkim parse failed: unknown error when parsing %c tag",
							  tag ? *tag : '?');
				return NULL;
			}
			break;
		}
	}

	if (type == RSPAMD_DKIM_ARC_SEAL) {
		rspamd_dkim_add_arc_seal_headers(pool, &ctx->common);
	}

	/* Now check validity of signature */
	if (ctx->b == NULL) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_EMPTY_B,
					"b parameter missing");
		return NULL;
	}
	if (ctx->common.type != RSPAMD_DKIM_ARC_SEAL && ctx->bh == NULL) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_EMPTY_BH,
					"bh parameter missing");
		return NULL;
	}
	if (ctx->domain == NULL) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_EMPTY_D,
					"domain parameter missing");
		return NULL;
	}
	if (ctx->selector == NULL) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_EMPTY_S,
					"selector parameter missing");
		return NULL;
	}
	if (ctx->common.type == RSPAMD_DKIM_NORMAL && ctx->ver == 0) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_EMPTY_V,
					"v parameter missing");
		return NULL;
	}
	if (ctx->common.hlist == NULL) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_EMPTY_H,
					"h parameter missing");
		return NULL;
	}
	if (ctx->sig_alg == DKIM_SIGN_UNKNOWN) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_EMPTY_S,
					"s parameter missing");
		return NULL;
	}

	if (type != RSPAMD_DKIM_ARC_SEAL) {
		if (ctx->sig_alg == DKIM_SIGN_RSASHA1) {
			/* Check bh length */
			if (ctx->bhlen != (guint) EVP_MD_size(EVP_sha1())) {
				g_set_error(err,
							DKIM_ERROR,
							DKIM_SIGERROR_BADSIG,
							"signature has incorrect length: %zu",
							ctx->bhlen);
				return NULL;
			}
		}
		else if (ctx->sig_alg == DKIM_SIGN_RSASHA256 ||
				 ctx->sig_alg == DKIM_SIGN_ECDSASHA256) {
			if (ctx->bhlen !=
				(guint) EVP_MD_size(EVP_sha256())) {
				g_set_error(err,
							DKIM_ERROR,
							DKIM_SIGERROR_BADSIG,
							"signature has incorrect length: %zu",
							ctx->bhlen);
				return NULL;
			}
		}
		else if (ctx->sig_alg == DKIM_SIGN_RSASHA512 ||
				 ctx->sig_alg == DKIM_SIGN_ECDSASHA512) {
			if (ctx->bhlen !=
				(guint) EVP_MD_size(EVP_sha512())) {
				g_set_error(err,
							DKIM_ERROR,
							DKIM_SIGERROR_BADSIG,
							"signature has incorrect length: %zu",
							ctx->bhlen);
				return NULL;
			}
		}
	}

	/* Check expiration */
	now = time(NULL);
	if (ctx->timestamp && now < ctx->timestamp && ctx->timestamp - now > (gint) time_jitter) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_FUTURE,
					"signature was made in future, ignoring");
		return NULL;
	}
	if (ctx->expiration && ctx->expiration < now) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_EXPIRED,
					"signature has expired");
		return NULL;
	}

	if (ctx->common.type != RSPAMD_DKIM_NORMAL && (ctx->common.idx == 0 ||
												   ctx->common.idx > RSPAMD_DKIM_MAX_ARC_IDX)) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_UNKNOWN,
					"i parameter missing or invalid for ARC");
		return NULL;
	}

	if (ctx->common.type == RSPAMD_DKIM_ARC_SEAL) {
		if (ctx->cv == RSPAMD_ARC_UNKNOWN) {
			g_set_error(err,
						DKIM_ERROR,
						DKIM_SIGERROR_UNKNOWN,
						"cv parameter missing or invalid for ARC");
			return NULL;
		}
	}

	/* Now create dns key to request further */
	gsize dnslen = strlen(ctx->domain) + strlen(ctx->selector) +
				   sizeof(DKIM_DNSKEYNAME) + 2;
	ctx->dns_key = rspamd_mempool_alloc(ctx->pool, dnslen);
	rspamd_snprintf(ctx->dns_key,
					dnslen,
					"%s.%s.%s",
					ctx->selector,
					DKIM_DNSKEYNAME,
					ctx->domain);

	/* Create checksums for further operations */
	if (ctx->sig_alg == DKIM_SIGN_RSASHA1) {
		md_alg = EVP_sha1();
	}
	else if (ctx->sig_alg == DKIM_SIGN_RSASHA256 ||
			 ctx->sig_alg == DKIM_SIGN_ECDSASHA256 ||
			 ctx->sig_alg == DKIM_SIGN_EDDSASHA256) {
		md_alg = EVP_sha256();
	}
	else if (ctx->sig_alg == DKIM_SIGN_RSASHA512 ||
			 ctx->sig_alg == DKIM_SIGN_ECDSASHA512) {
		md_alg = EVP_sha512();
	}
	else {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_BADSIG,
					"signature has unsupported signature algorithm");

		return NULL;
	}
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
	ctx->common.body_hash = EVP_MD_CTX_create();
	EVP_DigestInit_ex(ctx->common.body_hash, md_alg, NULL);
	ctx->common.headers_hash = EVP_MD_CTX_create();
	EVP_DigestInit_ex(ctx->common.headers_hash, md_alg, NULL);
	rspamd_mempool_add_destructor(pool,
								  (rspamd_mempool_destruct_t) EVP_MD_CTX_destroy, ctx->common.body_hash);
	rspamd_mempool_add_destructor(pool,
								  (rspamd_mempool_destruct_t) EVP_MD_CTX_destroy, ctx->common.headers_hash);
#else
	ctx->common.body_hash = EVP_MD_CTX_new();
	EVP_DigestInit_ex(ctx->common.body_hash, md_alg, NULL);
	ctx->common.headers_hash = EVP_MD_CTX_new();
	EVP_DigestInit_ex(ctx->common.headers_hash, md_alg, NULL);
	rspamd_mempool_add_destructor(pool,
								  (rspamd_mempool_destruct_t) EVP_MD_CTX_free, ctx->common.body_hash);
	rspamd_mempool_add_destructor(pool,
								  (rspamd_mempool_destruct_t) EVP_MD_CTX_free, ctx->common.headers_hash);
#endif
	ctx->dkim_header = sig;

	return ctx;
}

struct rspamd_dkim_key_cbdata {
	rspamd_dkim_context_t *ctx;
	dkim_key_handler_f handler;
	gpointer ud;
};

rspamd_dkim_key_t *
rspamd_dkim_make_key(const gchar *keydata,
					 guint keylen, enum rspamd_dkim_key_type type, GError **err)
{
	rspamd_dkim_key_t *key = NULL;

	if (keylen < 3) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_KEYFAIL,
					"DKIM key is too short to be valid");
		return NULL;
	}

	key = g_malloc0(sizeof(rspamd_dkim_key_t));
	REF_INIT_RETAIN(key, rspamd_dkim_key_free);
	key->keydata = g_malloc0(keylen + 1);
	key->raw_key = g_malloc(keylen);
	key->decoded_len = keylen;
	key->type = type;

	/* Copy key skipping all spaces and newlines */
	const char *h = keydata;
	guint8 *t = key->raw_key;

	while (h - keydata < keylen) {
		if (!g_ascii_isspace(*h)) {
			*t++ = *h++;
		}
		else {
			h++;
		}
	}

	key->keylen = t - key->raw_key;

	if (!rspamd_cryptobox_base64_decode(key->raw_key, key->keylen, key->keydata,
										&key->decoded_len)) {
		REF_RELEASE(key);
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_KEYFAIL,
					"DKIM key is not a valid base64 string");

		return NULL;
	}

	/* Calculate ID -> md5 */
	EVP_MD_CTX *mdctx = EVP_MD_CTX_create();

#ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
	EVP_MD_CTX_set_flags(mdctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
#endif

	if (EVP_DigestInit_ex(mdctx, EVP_md5(), NULL) == 1) {
		guint dlen = sizeof(key->key_id);

		EVP_DigestUpdate(mdctx, key->keydata, key->decoded_len);
		EVP_DigestFinal_ex(mdctx, key->key_id, &dlen);
	}

	EVP_MD_CTX_destroy(mdctx);

	if (key->type == RSPAMD_DKIM_KEY_EDDSA) {
		key->key.key_eddsa = key->keydata;

		if (key->decoded_len != rspamd_cryptobox_pk_sig_bytes(
									RSPAMD_CRYPTOBOX_MODE_25519)) {
			g_set_error(err,
						DKIM_ERROR,
						DKIM_SIGERROR_KEYFAIL,
						"DKIM key is has invalid length %d for eddsa; expected %d",
						(gint) key->decoded_len,
						rspamd_cryptobox_pk_sig_bytes(RSPAMD_CRYPTOBOX_MODE_25519));
			REF_RELEASE(key);

			return NULL;
		}
	}
	else {
		key->key_bio = BIO_new_mem_buf(key->keydata, key->decoded_len);

		if (key->key_bio == NULL) {
			g_set_error(err,
						DKIM_ERROR,
						DKIM_SIGERROR_KEYFAIL,
						"cannot make ssl bio from key");
			REF_RELEASE(key);

			return NULL;
		}

		key->key_evp = d2i_PUBKEY_bio(key->key_bio, NULL);

		if (key->key_evp == NULL) {
			g_set_error(err,
						DKIM_ERROR,
						DKIM_SIGERROR_KEYFAIL,
						"cannot extract pubkey from bio");
			REF_RELEASE(key);

			return NULL;
		}

		if (type == RSPAMD_DKIM_KEY_RSA) {
			key->key.key_rsa = EVP_PKEY_get1_RSA(key->key_evp);

			if (key->key.key_rsa == NULL) {
				g_set_error(err,
							DKIM_ERROR,
							DKIM_SIGERROR_KEYFAIL,
							"cannot extract rsa key from evp key");
				REF_RELEASE(key);

				return NULL;
			}
		}
		else {
			key->key.key_ecdsa = EVP_PKEY_get1_EC_KEY(key->key_evp);

			if (key->key.key_ecdsa == NULL) {
				g_set_error(err,
							DKIM_ERROR,
							DKIM_SIGERROR_KEYFAIL,
							"cannot extract ecdsa key from evp key");
				REF_RELEASE(key);

				return NULL;
			}
		}
	}

	return key;
}

const guchar *
rspamd_dkim_key_id(rspamd_dkim_key_t *key)
{
	if (key) {
		return key->key_id;
	}

	return NULL;
}

/**
 * Free DKIM key
 * @param key
 */
void rspamd_dkim_key_free(rspamd_dkim_key_t *key)
{
	if (key->key_evp) {
		EVP_PKEY_free(key->key_evp);
	}

	if (key->type == RSPAMD_DKIM_KEY_RSA) {
		if (key->key.key_rsa) {
			RSA_free(key->key.key_rsa);
		}
	}
	else if (key->type == RSPAMD_DKIM_KEY_ECDSA) {
		if (key->key.key_ecdsa) {
			EC_KEY_free(key->key.key_ecdsa);
		}
	}
	/* Nothing in case of eddsa key */
	if (key->key_bio) {
		BIO_free(key->key_bio);
	}

	g_free(key->raw_key);
	g_free(key->keydata);
	g_free(key);
}

void rspamd_dkim_sign_key_free(rspamd_dkim_sign_key_t *key)
{
	if (key->key_evp) {
		EVP_PKEY_free(key->key_evp);
	}
	if (key->type == RSPAMD_DKIM_KEY_RSA) {
		if (key->key.key_rsa) {
			RSA_free(key->key.key_rsa);
		}
	}
	if (key->key_bio) {
		BIO_free(key->key_bio);
	}

	if (key->type == RSPAMD_DKIM_KEY_EDDSA) {
		rspamd_explicit_memzero(key->key.key_eddsa, key->keylen);
		g_free(key->keydata);
	}

	g_free(key);
}

rspamd_dkim_key_t *
rspamd_dkim_parse_key(const gchar *txt, gsize *keylen, GError **err)
{
	const gchar *c, *p, *end, *key = NULL, *alg = "rsa";
	enum {
		read_tag = 0,
		read_tag_before_eqsign,
		read_eqsign,
		read_p_tag,
		read_k_tag,
		ignore_value,
		skip_spaces,
	} state = read_tag,
	  next_state;
	gchar tag = '\0';
	gsize klen = 0, alglen = 0;

	c = txt;
	p = txt;
	end = txt + strlen(txt);

	while (p < end) {
		switch (state) {
		case read_tag:
			if (*p == '=') {
				state = read_eqsign;
			}
			else if (g_ascii_isspace(*p)) {
				state = skip_spaces;

				if (tag != '\0') {
					/* We had tag letter */
					next_state = read_tag_before_eqsign;
				}
				else {
					/* We had no tag letter, so we ignore empty tag */
					next_state = read_tag;
				}
			}
			else {
				tag = *p;
			}
			p++;
			break;
		case read_tag_before_eqsign:
			/* Input: spaces before eqsign
			 * Output: either read a next tag (previous had no value), or read value
			 * p is moved forward
			 */
			if (*p == '=') {
				state = read_eqsign;
			}
			else {
				tag = *p;
				state = read_tag;
			}
			p++;
			break;
		case read_eqsign:
			/* Always switch to skip spaces state and do not advance p */
			state = skip_spaces;

			if (tag == 'p') {
				next_state = read_p_tag;
			}
			else if (tag == 'k') {
				next_state = read_k_tag;
			}
			else {
				/* Unknown tag, ignore */
				next_state = ignore_value;
				tag = '\0';
			}
			break;
		case read_p_tag:
			if (*p == ';') {
				klen = p - c;
				key = c;
				state = read_tag;
				tag = '\0';
				p++;
			}
			else {
				p++;
			}
			break;
		case read_k_tag:
			if (*p == ';') {
				alglen = p - c;
				alg = c;
				state = read_tag;
				tag = '\0';
				p++;
			}
			else if (g_ascii_isspace(*p)) {
				alglen = p - c;
				alg = c;
				state = skip_spaces;
				next_state = read_tag;
				tag = '\0';
			}
			else {
				p++;
			}
			break;
		case ignore_value:
			if (*p == ';') {
				state = read_tag;
				tag = '\0';
				p++;
			}
			else if (g_ascii_isspace(*p)) {
				state = skip_spaces;
				next_state = read_tag;
				tag = '\0';
			}
			else {
				p++;
			}
			break;
		case skip_spaces:
			/* Skip spaces and switch to the next state if needed */
			if (g_ascii_isspace(*p)) {
				p++;
			}
			else {
				c = p;
				state = next_state;
			}
			break;
		default:
			break;
		}
	}

	/* Leftover */
	switch (state) {
	case read_p_tag:
		klen = p - c;
		key = c;
		break;
	case read_k_tag:
		alglen = p - c;
		alg = c;
		break;
	default:
		break;
	}

	if (klen == 0 || key == NULL) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_KEYFAIL,
					"key is missing");

		return NULL;
	}

	if (alglen == 0 || alg == NULL) {
		alg = "rsa"; /* Implicit */
		alglen = 3;
	}

	if (keylen) {
		*keylen = klen;
	}

	if (alglen == 8 && rspamd_lc_cmp(alg, "ecdsa256", alglen) == 0) {
		return rspamd_dkim_make_key(key, klen,
									RSPAMD_DKIM_KEY_ECDSA, err);
	}
	else if (alglen == 7 && rspamd_lc_cmp(alg, "ed25519", alglen) == 0) {
		return rspamd_dkim_make_key(key, klen,
									RSPAMD_DKIM_KEY_EDDSA, err);
	}
	else {
		/* We assume RSA default in all cases */
		return rspamd_dkim_make_key(key, klen,
									RSPAMD_DKIM_KEY_RSA, err);
	}

	g_assert_not_reached();

	return NULL;
}

/* Get TXT request data and parse it */
static void
rspamd_dkim_dns_cb(struct rdns_reply *reply, gpointer arg)
{
	struct rspamd_dkim_key_cbdata *cbdata = arg;
	rspamd_dkim_key_t *key = NULL;
	GError *err = NULL;
	struct rdns_reply_entry *elt;
	gsize keylen = 0;

	if (reply->code != RDNS_RC_NOERROR) {
		gint err_code = DKIM_SIGERROR_NOKEY;
		if (reply->code == RDNS_RC_NOREC) {
			err_code = DKIM_SIGERROR_NOREC;
		}
		else if (reply->code == RDNS_RC_NXDOMAIN) {
			err_code = DKIM_SIGERROR_NOREC;
		}
		g_set_error(&err,
					DKIM_ERROR,
					err_code,
					"dns request to %s failed: %s",
					cbdata->ctx->dns_key,
					rdns_strerror(reply->code));
		cbdata->handler(NULL, 0, cbdata->ctx, cbdata->ud, err);
	}
	else {
		LL_FOREACH(reply->entries, elt)
		{
			if (elt->type == RDNS_REQUEST_TXT) {
				if (err != NULL) {
					/* Free error as it is insignificant */
					g_error_free(err);
					err = NULL;
				}
				key = rspamd_dkim_parse_key(elt->content.txt.data,
											&keylen,
											&err);
				if (key) {
					key->ttl = elt->ttl;
					break;
				}
			}
		}
		cbdata->handler(key, keylen, cbdata->ctx, cbdata->ud, err);
	}
}

/**
 * Make DNS request for specified context and obtain and parse key
 * @param ctx dkim context from signature
 * @param resolver dns resolver object
 * @param s async session to make request
 * @return
 */
gboolean
rspamd_get_dkim_key(rspamd_dkim_context_t *ctx,
					struct rspamd_task *task,
					dkim_key_handler_f handler,
					gpointer ud)
{
	struct rspamd_dkim_key_cbdata *cbdata;

	g_return_val_if_fail(ctx != NULL, FALSE);
	g_return_val_if_fail(ctx->dns_key != NULL, FALSE);

	cbdata =
		rspamd_mempool_alloc(ctx->pool,
							 sizeof(struct rspamd_dkim_key_cbdata));
	cbdata->ctx = ctx;
	cbdata->handler = handler;
	cbdata->ud = ud;

	return rspamd_dns_resolver_request_task_forced(task,
												   rspamd_dkim_dns_cb,
												   cbdata,
												   RDNS_REQUEST_TXT,
												   ctx->dns_key);
}

static gboolean
rspamd_dkim_relaxed_body_step(struct rspamd_dkim_common_ctx *ctx, EVP_MD_CTX *ck,
							  const gchar **start, guint size,
							  gssize *remain)
{
	const gchar *h;
	gchar *t;
	guint len, inlen;
	gssize octets_remain;
	gboolean got_sp, ret = TRUE;
	gchar buf[1024];

	len = size;
	inlen = sizeof(buf) - 1;
	h = *start;
	t = buf;
	got_sp = FALSE;
	octets_remain = *remain;

	while (len > 0 && inlen > 0 && (octets_remain > 0)) {

		if (*h == '\r' || *h == '\n') {
			if (got_sp) {
				/* Ignore spaces at the end of line */
				t--;
			}
			*t++ = '\r';
			*t++ = '\n';

			if (len > 1 && (*h == '\r' && h[1] == '\n')) {
				h += 2;
				len -= 2;
				octets_remain -= 2;
			}
			else {
				h++;
				len--;
				if (octets_remain >= 2) {
					octets_remain -= 2; /* Input has just \n or \r so we actually add more octets */
				}
				else {
					octets_remain--;
					break;
				}
			}
			break;
		}
		else if (g_ascii_isspace(*h)) {
			if (got_sp) {
				/* Ignore multiply spaces */
				h++;
				len--;
				continue;
			}
			else {
				*t++ = ' ';
				h++;
				inlen--;
				len--;
				octets_remain--;
				got_sp = TRUE;
				continue;
			}
		}
		else {
			got_sp = FALSE;
		}

		*t++ = *h++;
		inlen--;
		len--;
		octets_remain--;
	}

	if (octets_remain < 0) {
		/* Absurdic l tag value, but we still need to rewind the t pointer back */
		while (t > buf && octets_remain < 0) {
			t--;
			octets_remain++;
		}

		ret = FALSE;
	}

	*start = h;

	if (t - buf > 0) {
		gsize cklen = t - buf;

		EVP_DigestUpdate(ck, buf, cklen);
		ctx->body_canonicalised += cklen;
		msg_debug_dkim("relaxed update signature with body buffer "
					   "(%z size, %z -> %z remain)",
					   cklen, *remain, octets_remain);
		*remain = octets_remain;
	}

	return ret && ((len > 0) && (octets_remain > 0));
}

static gboolean
rspamd_dkim_simple_body_step(struct rspamd_dkim_common_ctx *ctx,
							 EVP_MD_CTX *ck, const gchar **start, guint size,
							 gssize *remain)
{
	const gchar *h;
	gchar *t;
	guint len, inlen;
	gssize octets_remain;
	gchar buf[1024];

	len = size;
	inlen = sizeof(buf) - 1;
	h = *start;
	t = &buf[0];
	octets_remain = *remain;

	while (len > 0 && inlen > 0 && (octets_remain != 0)) {
		if (*h == '\r' || *h == '\n') {
			*t++ = '\r';
			*t++ = '\n';

			if (len > 1 && (*h == '\r' && h[1] == '\n')) {
				h += 2;
				len -= 2;

				if (octets_remain >= 2) {
					octets_remain -= 2; /* Input has just \n or \r so we actually add more octets */
				}
				else {
					octets_remain--;
				}
			}
			else {
				h++;
				len--;

				if (octets_remain >= 2) {
					octets_remain -= 2; /* Input has just \n or \r so we actually add more octets */
				}
				else {
					octets_remain--;
				}
			}
			break;
		}

		*t++ = *h++;
		octets_remain--;
		inlen--;
		len--;
	}

	*start = h;

	if (t - buf > 0) {
		gsize cklen = t - buf;

		EVP_DigestUpdate(ck, buf, cklen);
		ctx->body_canonicalised += cklen;
		msg_debug_dkim("simple update signature with body buffer "
					   "(%z size, %z -> %z remain)",
					   cklen, *remain, octets_remain);
		*remain = octets_remain;
	}

	return ((len != 0) && (octets_remain != 0));
}

static const gchar *
rspamd_dkim_skip_empty_lines(const gchar *start, const gchar *end,
							 guint type, gboolean sign, gboolean *need_crlf)
{
	const gchar *p = end - 1, *t;
	enum {
		init = 0,
		init_2,
		got_cr,
		got_lf,
		got_crlf,
		test_spaces,
	} state = init;
	guint skip = 0;

	while (p >= start) {
		switch (state) {
		case init:
			if (*p == '\r') {
				state = got_cr;
			}
			else if (*p == '\n') {
				state = got_lf;
			}
			else if (type == DKIM_CANON_RELAXED && *p == ' ') {
				skip = 0;
				state = test_spaces;
			}
			else {
				if (sign || type != DKIM_CANON_RELAXED) {
					*need_crlf = TRUE;
				}

				goto end;
			}
			break;
		case init_2:
			if (*p == '\r') {
				state = got_cr;
			}
			else if (*p == '\n') {
				state = got_lf;
			}
			else if (type == DKIM_CANON_RELAXED && (*p == ' ' || *p == '\t')) {
				skip = 0;
				state = test_spaces;
			}
			else {
				goto end;
			}
			break;
		case got_cr:
			if (p >= start + 1) {
				if (*(p - 1) == '\r') {
					p--;
					state = got_cr;
				}
				else if (*(p - 1) == '\n') {
					if ((*p - 2) == '\r') {
						/* \r\n\r -> we know about one line */
						p -= 1;
						state = got_crlf;
					}
					else {
						/* \n\r -> we know about one line */
						p -= 1;
						state = got_lf;
					}
				}
				else if (type == DKIM_CANON_RELAXED && (*(p - 1) == ' ' ||
														*(p - 1) == '\t')) {
					skip = 1;
					state = test_spaces;
				}
				else {
					goto end;
				}
			}
			else {
				if (g_ascii_isspace(*(p - 1))) {
					if (type == DKIM_CANON_RELAXED) {
						p -= 1;
					}
				}
				goto end;
			}
			break;
		case got_lf:
			if (p >= start + 1) {
				if (*(p - 1) == '\r') {
					state = got_crlf;
				}
				else if (*(p - 1) == '\n') {
					/* We know about one line */
					p--;
					state = got_lf;
				}
				else if (type == DKIM_CANON_RELAXED && (*(p - 1) == ' ' ||
														*(p - 1) == '\t')) {
					skip = 1;
					state = test_spaces;
				}
				else {
					goto end;
				}
			}
			else {
				if (g_ascii_isspace(*(p - 1))) {
					if (type == DKIM_CANON_RELAXED) {
						p -= 1;
					}
				}
				goto end;
			}
			break;
		case got_crlf:
			if (p >= start + 2) {
				if (*(p - 2) == '\r') {
					p -= 2;
					state = got_cr;
				}
				else if (*(p - 2) == '\n') {
					p -= 2;
					state = got_lf;
				}
				else if (type == DKIM_CANON_RELAXED && (*(p - 2) == ' ' ||
														*(p - 2) == '\t')) {
					skip = 2;
					state = test_spaces;
				}
				else {
					goto end;
				}
			}
			else {
				if (g_ascii_isspace(*(p - 2))) {
					if (type == DKIM_CANON_RELAXED) {
						p -= 2;
					}
				}
				goto end;
			}
			break;
		case test_spaces:
			t = p - skip;

			while (t >= start + 2 && (*t == ' ' || *t == '\t')) {
				t--;
			}

			if (*t == '\r') {
				p = t;
				state = got_cr;
			}
			else if (*t == '\n') {
				p = t;
				state = got_lf;
			}
			else {
				goto end;
			}
			break;
		}
	}

end:
	return p;
}

static gboolean
rspamd_dkim_canonize_body(struct rspamd_dkim_common_ctx *ctx,
						  const gchar *start,
						  const gchar *end,
						  gboolean sign)
{
	const gchar *p;
	gssize remain = ctx->len ? ctx->len : G_MAXSSIZE;
	guint total_len = end - start;
	gboolean need_crlf = FALSE;

	if (start == NULL) {
		/* Empty body */
		if (ctx->body_canon_type == DKIM_CANON_SIMPLE) {
			EVP_DigestUpdate(ctx->body_hash, CRLF, sizeof(CRLF) - 1);
			ctx->body_canonicalised += sizeof(CRLF) - 1;
		}
		else {
			EVP_DigestUpdate(ctx->body_hash, "", 0);
		}
	}
	else {
		/* Strip extra ending CRLF */
		p = rspamd_dkim_skip_empty_lines(start, end, ctx->body_canon_type,
										 sign, &need_crlf);
		end = p + 1;

		if (end == start) {
			/* Empty body */
			if (ctx->body_canon_type == DKIM_CANON_SIMPLE) {
				EVP_DigestUpdate(ctx->body_hash, CRLF, sizeof(CRLF) - 1);
				ctx->body_canonicalised += sizeof(CRLF) - 1;
			}
			else {
				EVP_DigestUpdate(ctx->body_hash, "", 0);
			}
		}
		else {
			if (ctx->body_canon_type == DKIM_CANON_SIMPLE) {
				/* Simple canonization */
				while (rspamd_dkim_simple_body_step(ctx, ctx->body_hash,
													&start, end - start, &remain))
					;

				/*
				 * If we have l= tag then we cannot add crlf...
				 */
				if (need_crlf) {
					/* l is evil... */
					if (ctx->len == 0) {
						remain = 2;
					}
					else {
						if (ctx->len <= total_len) {
							/* We don't have enough l to add \r\n */
							remain = 0;
						}
						else {
							if (ctx->len - total_len >= 2) {
								remain = 2;
							}
							else {
								remain = ctx->len - total_len;
							}
						}
					}

					start = "\r\n";
					end = start + 2;

					rspamd_dkim_simple_body_step(ctx, ctx->body_hash,
												 &start, end - start, &remain);
				}
			}
			else {
				while (rspamd_dkim_relaxed_body_step(ctx, ctx->body_hash,
													 &start, end - start, &remain))
					;
				if (need_crlf) {
					start = "\r\n";
					end = start + 2;
					remain = 2;
					rspamd_dkim_relaxed_body_step(ctx, ctx->body_hash,
												  &start, end - start, &remain);
				}
			}
		}
		return TRUE;
	}

	/* TODO: Implement relaxed algorithm */
	return FALSE;
}

/* Update hash converting all CR and LF to CRLF */
static void
rspamd_dkim_hash_update(EVP_MD_CTX *ck, const gchar *begin, gsize len)
{
	const gchar *p, *c, *end;

	end = begin + len;
	p = begin;
	c = p;

	while (p < end) {
		if (*p == '\r') {
			EVP_DigestUpdate(ck, c, p - c);
			EVP_DigestUpdate(ck, CRLF, sizeof(CRLF) - 1);
			p++;

			if (p < end && *p == '\n') {
				p++;
			}
			c = p;
		}
		else if (*p == '\n') {
			EVP_DigestUpdate(ck, c, p - c);
			EVP_DigestUpdate(ck, CRLF, sizeof(CRLF) - 1);
			p++;
			c = p;
		}
		else {
			p++;
		}
	}

	if (p > c) {
		EVP_DigestUpdate(ck, c, p - c);
	}
}

/* Update hash by signature value (ignoring b= tag) */
static void
rspamd_dkim_signature_update(struct rspamd_dkim_common_ctx *ctx,
							 const gchar *begin,
							 guint len)
{
	const gchar *p, *c, *end;
	gboolean tag, skip;

	end = begin + len;
	p = begin;
	c = begin;
	tag = TRUE;
	skip = FALSE;

	while (p < end) {
		if (tag && p[0] == 'b' && p[1] == '=') {
			/* Add to signature */
			msg_debug_dkim("initial update hash with signature part: %*s",
						   (gint) (p - c + 2),
						   c);
			ctx->headers_canonicalised += p - c + 2;
			rspamd_dkim_hash_update(ctx->headers_hash, c, p - c + 2);
			skip = TRUE;
		}
		else if (skip && (*p == ';' || p == end - 1)) {
			skip = FALSE;
			c = p;
		}
		else if (!tag && *p == ';') {
			tag = TRUE;
		}
		else if (tag && *p == '=') {
			tag = FALSE;
		}
		p++;
	}

	p--;
	/* Skip \r\n at the end */
	while ((*p == '\r' || *p == '\n') && p >= c) {
		p--;
	}

	if (p - c + 1 > 0) {
		msg_debug_dkim("final update hash with signature part: %*s",
					   (gint) (p - c + 1), c);
		ctx->headers_canonicalised += p - c + 1;
		rspamd_dkim_hash_update(ctx->headers_hash, c, p - c + 1);
	}
}

goffset
rspamd_dkim_canonize_header_relaxed_str(const gchar *hname,
										const gchar *hvalue,
										gchar *out,
										gsize outlen)
{
	gchar *t;
	const guchar *h;
	gboolean got_sp;

	/* Name part */
	t = out;
	h = hname;

	while (*h && t - out < outlen) {
		*t++ = lc_map[*h++];
	}

	if (t - out >= outlen) {
		return -1;
	}

	*t++ = ':';

	/* Value part */
	h = hvalue;
	/* Skip spaces at the beginning */
	while (g_ascii_isspace(*h)) {
		h++;
	}

	got_sp = FALSE;

	while (*h && (t - out < outlen)) {
		if (g_ascii_isspace(*h)) {
			if (got_sp) {
				h++;
				continue;
			}
			else {
				got_sp = TRUE;
				*t++ = ' ';
				h++;
				continue;
			}
		}
		else {
			got_sp = FALSE;
		}

		*t++ = *h++;
	}

	if (g_ascii_isspace(*(t - 1))) {
		t--;
	}

	if (t - out >= outlen - 2) {
		return -1;
	}

	*t++ = '\r';
	*t++ = '\n';
	*t = '\0';

	return t - out;
}

static gboolean
rspamd_dkim_canonize_header_relaxed(struct rspamd_dkim_common_ctx *ctx,
									const gchar *header,
									const gchar *header_name,
									gboolean is_sign,
									guint count,
									bool is_seal)
{
	static gchar st_buf[8192];
	gchar *buf;
	guint inlen;
	goffset r;
	gboolean allocated = FALSE;

	inlen = strlen(header) + strlen(header_name) + sizeof(":" CRLF);

	if (inlen > sizeof(st_buf)) {
		buf = g_malloc(inlen);
		allocated = TRUE;
	}
	else {
		/* Faster */
		buf = st_buf;
	}

	r = rspamd_dkim_canonize_header_relaxed_str(header_name, header, buf, inlen);

	g_assert(r != -1);

	if (!is_sign) {
		msg_debug_dkim("update %s with header (idx=%d): %s",
					   is_seal ? "seal" : "signature", count, buf);
		EVP_DigestUpdate(ctx->headers_hash, buf, r);
	}
	else {
		rspamd_dkim_signature_update(ctx, buf, r);
	}

	if (allocated) {
		g_free(buf);
	}

	return TRUE;
}


static gboolean
rspamd_dkim_canonize_header(struct rspamd_dkim_common_ctx *ctx,
							struct rspamd_task *task,
							const gchar *header_name,
							gint count,
							const gchar *dkim_header,
							const gchar *dkim_domain)
{
	struct rspamd_mime_header *rh, *cur, *sel = NULL;
	gint hdr_cnt = 0;
	bool use_idx = false, is_sign = ctx->is_sign;

	/*
	 * TODO:
	 * Temporary hack to prevent linked list being misused until refactored
	 */
	const guint max_list_iters = 1000;

	if (count < 0) {
		use_idx = true;
		count = -(count); /* use i= in header content as it is arc stuff */
	}

	if (dkim_header == NULL) {
		rh = rspamd_message_get_header_array(task, header_name,
											 is_sign);

		if (rh) {
			/* Check uniqueness of the header but we count from the bottom to top */
			if (!use_idx) {
				for (cur = rh->prev;; cur = cur->prev) {
					if (hdr_cnt == count) {
						sel = cur;
					}

					hdr_cnt++;

					if (cur == rh || hdr_cnt >= max_list_iters) {
						/* Cycle */
						break;
					}
				}

				if ((rh->flags & RSPAMD_HEADER_UNIQUE) && hdr_cnt > 1) {
					guint64 random_cookie = ottery_rand_uint64();

					msg_warn_dkim("header %s is intended to be unique by"
								  " email standards, but we have %d headers of this"
								  " type, artificially break DKIM check",
								  header_name,
								  hdr_cnt);
					rspamd_dkim_hash_update(ctx->headers_hash,
											(const gchar *) &random_cookie,
											sizeof(random_cookie));
					ctx->headers_canonicalised += sizeof(random_cookie);

					return FALSE;
				}

				if (hdr_cnt <= count) {
					/*
					 * If DKIM has less headers requested than there are in a
					 * message, then it's fine, it allows adding extra headers
					 */
					return TRUE;
				}
			}
			else {
				/*
				 * This branch is used for ARC headers, and it orders them based on
				 * i=<number> string and not their real order in the list of headers
				 */
				gchar idx_buf[16];
				gint id_len, i;

				id_len = rspamd_snprintf(idx_buf, sizeof(idx_buf), "i=%d;",
										 count);

				for (cur = rh->prev, i = 0; i < max_list_iters; cur = cur->prev, i++) {
					if (cur->decoded &&
						rspamd_substring_search(cur->decoded, strlen(cur->decoded),
												idx_buf, id_len) != -1) {
						sel = cur;
						break;
					}

					if (cur == rh) {
						/* Cycle */
						break;
					}
				}

				if (sel == NULL) {
					return FALSE;
				}
			}

			/* Selected header must be non-null if previous condition is false */
			g_assert(sel != NULL);

			if (ctx->header_canon_type == DKIM_CANON_SIMPLE) {
				rspamd_dkim_hash_update(ctx->headers_hash, sel->raw_value,
										sel->raw_len);
				ctx->headers_canonicalised += sel->raw_len;
				msg_debug_dkim("update %s with header (idx=%d): %*s",
							   (use_idx ? "seal" : "signature"),
							   count, (gint) sel->raw_len, sel->raw_value);
			}
			else {
				if (is_sign && (sel->flags & RSPAMD_HEADER_FROM)) {
					/* Special handling of the From handling when rewrite is done */
					gboolean has_rewrite = FALSE;
					guint i;
					struct rspamd_email_address *addr;

					PTR_ARRAY_FOREACH(MESSAGE_FIELD(task, from_mime), i, addr)
					{
						if ((addr->flags & RSPAMD_EMAIL_ADDR_ORIGINAL) && !(addr->flags & RSPAMD_EMAIL_ADDR_ALIASED)) {
							has_rewrite = TRUE;
						}
					}

					if (has_rewrite) {
						PTR_ARRAY_FOREACH(MESSAGE_FIELD(task, from_mime), i, addr)
						{
							if (!(addr->flags & RSPAMD_EMAIL_ADDR_ORIGINAL)) {
								if (!rspamd_dkim_canonize_header_relaxed(ctx, addr->raw,
																		 header_name, FALSE, i, use_idx)) {
									return FALSE;
								}

								return TRUE;
							}
						}
					}
				}

				if (!rspamd_dkim_canonize_header_relaxed(ctx, sel->value,
														 header_name, FALSE, count, use_idx)) {
					return FALSE;
				}
			}
		}
	}
	else {
		/* For signature check just use the saved dkim header */
		if (ctx->header_canon_type == DKIM_CANON_SIMPLE) {
			/* We need to find our own signature and use it */
			rh = rspamd_message_get_header_array(task, header_name, is_sign);

			if (rh) {
				/* We need to find our own signature */
				if (!dkim_domain) {
					msg_err_dkim("cannot verify dkim as we have no dkim domain!");
					return FALSE;
				}

				gboolean found = FALSE;

				DL_FOREACH(rh, cur)
				{
					guint64 th = rspamd_cryptobox_fast_hash(cur->decoded,
															strlen(cur->decoded), rspamd_hash_seed());

					if (th == ctx->sig_hash) {
						rspamd_dkim_signature_update(ctx, cur->raw_value,
													 cur->raw_len);
						found = TRUE;
						break;
					}
				}
				if (!found) {
					msg_err_dkim("BUGON: cannot verify dkim as we have lost our signature"
								 " during simple canonicalisation, expected hash=%L",
								 ctx->sig_hash);
					return FALSE;
				}
			}
			else {
				return FALSE;
			}
		}
		else {
			if (!rspamd_dkim_canonize_header_relaxed(ctx,
													 dkim_header,
													 header_name,
													 TRUE, 0, use_idx)) {
				return FALSE;
			}
		}
	}

	return TRUE;
}

struct rspamd_dkim_cached_hash {
	guchar *digest_normal;
	guchar *digest_cr;
	guchar *digest_crlf;
	gchar *type;
};

static struct rspamd_dkim_cached_hash *
rspamd_dkim_check_bh_cached(struct rspamd_dkim_common_ctx *ctx,
							struct rspamd_task *task, gsize bhlen, gboolean is_sign)
{
	gchar typebuf[64];
	struct rspamd_dkim_cached_hash *res;

	rspamd_snprintf(typebuf, sizeof(typebuf),
					RSPAMD_MEMPOOL_DKIM_BH_CACHE "%z_%s_%d_%z",
					bhlen,
					ctx->body_canon_type == DKIM_CANON_RELAXED ? "1" : "0",
					!!is_sign,
					ctx->len);

	res = rspamd_mempool_get_variable(task->task_pool,
									  typebuf);

	if (!res) {
		res = rspamd_mempool_alloc0(task->task_pool, sizeof(*res));
		res->type = rspamd_mempool_strdup(task->task_pool, typebuf);
		rspamd_mempool_set_variable(task->task_pool,
									res->type, res, NULL);
	}

	return res;
}

static const char *
rspamd_dkim_type_to_string(enum rspamd_dkim_type t)
{
	switch (t) {
	case RSPAMD_DKIM_NORMAL:
		return "dkim";
	case RSPAMD_DKIM_ARC_SIG:
		return "arc_sig";
	case RSPAMD_DKIM_ARC_SEAL:
	default:
		return "arc_seal";
	}
}

/**
 * Check task for dkim context using dkim key
 * @param ctx dkim verify context
 * @param key dkim key (from cache or from dns request)
 * @param task task to check
 * @return
 */
struct rspamd_dkim_check_result *
rspamd_dkim_check(rspamd_dkim_context_t *ctx,
				  rspamd_dkim_key_t *key,
				  struct rspamd_task *task)
{
	const gchar *body_end, *body_start;
	guchar raw_digest[EVP_MAX_MD_SIZE];
	struct rspamd_dkim_cached_hash *cached_bh = NULL;
	EVP_MD_CTX *cpy_ctx = NULL;
	gsize dlen = 0;
	struct rspamd_dkim_check_result *res;
	guint i;
	struct rspamd_dkim_header *dh;
	gint nid;

	g_return_val_if_fail(ctx != NULL, NULL);
	g_return_val_if_fail(key != NULL, NULL);
	g_return_val_if_fail(task->msg.len > 0, NULL);

	/* First of all find place of body */
	body_end = task->msg.begin + task->msg.len;

	body_start = MESSAGE_FIELD(task, raw_headers_content).body_start;

	res = rspamd_mempool_alloc0(task->task_pool, sizeof(*res));
	res->ctx = ctx;
	res->selector = ctx->selector;
	res->domain = ctx->domain;
	res->fail_reason = NULL;
	res->short_b = ctx->short_b;
	res->rcode = DKIM_CONTINUE;

	if (!body_start) {
		res->rcode = DKIM_ERROR;
		return res;
	}

	if (ctx->common.type != RSPAMD_DKIM_ARC_SEAL) {
		dlen = EVP_MD_CTX_size(ctx->common.body_hash);
		cached_bh = rspamd_dkim_check_bh_cached(&ctx->common, task,
												dlen, FALSE);

		if (!cached_bh->digest_normal) {
			/* Start canonization of body part */
			if (!rspamd_dkim_canonize_body(&ctx->common, body_start, body_end,
										   FALSE)) {
				res->rcode = DKIM_RECORD_ERROR;
				return res;
			}
		}
	}

	/* Now canonize headers */
	for (i = 0; i < ctx->common.hlist->len; i++) {
		dh = g_ptr_array_index(ctx->common.hlist, i);
		rspamd_dkim_canonize_header(&ctx->common, task, dh->name, dh->count,
									NULL, NULL);
	}

	/* Canonize dkim signature */
	switch (ctx->common.type) {
	case RSPAMD_DKIM_NORMAL:
		rspamd_dkim_canonize_header(&ctx->common, task, RSPAMD_DKIM_SIGNHEADER, 0,
									ctx->dkim_header, ctx->domain);
		break;
	case RSPAMD_DKIM_ARC_SIG:
		rspamd_dkim_canonize_header(&ctx->common, task, RSPAMD_DKIM_ARC_SIGNHEADER, 0,
									ctx->dkim_header, ctx->domain);
		break;
	case RSPAMD_DKIM_ARC_SEAL:
		rspamd_dkim_canonize_header(&ctx->common, task, RSPAMD_DKIM_ARC_SEALHEADER, 0,
									ctx->dkim_header, ctx->domain);
		break;
	}


	/* Use cached BH for all but arc seal, if it is not NULL we are not in arc seal mode */
	if (cached_bh != NULL) {
		if (!cached_bh->digest_normal) {
			/* Copy md_ctx to deal with broken CRLF at the end */
			cpy_ctx = EVP_MD_CTX_create();
			EVP_MD_CTX_copy(cpy_ctx, ctx->common.body_hash);
			EVP_DigestFinal_ex(cpy_ctx, raw_digest, NULL);

			cached_bh->digest_normal = rspamd_mempool_alloc(task->task_pool,
															sizeof(raw_digest));
			memcpy(cached_bh->digest_normal, raw_digest, sizeof(raw_digest));
		}

		/* Check bh field */
		if (memcmp(ctx->bh, cached_bh->digest_normal, ctx->bhlen) != 0) {
			msg_debug_dkim(
				"bh value mismatch: %*xs versus %*xs, try add LF; try adding CRLF",
				(gint) dlen, ctx->bh,
				(gint) dlen, raw_digest);

			if (cpy_ctx) {
				/* Try add CRLF */
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
				EVP_MD_CTX_cleanup(cpy_ctx);
#else
				EVP_MD_CTX_reset(cpy_ctx);
#endif
				EVP_MD_CTX_copy(cpy_ctx, ctx->common.body_hash);
				EVP_DigestUpdate(cpy_ctx, "\r\n", 2);
				EVP_DigestFinal_ex(cpy_ctx, raw_digest, NULL);
				cached_bh->digest_crlf = rspamd_mempool_alloc(task->task_pool,
															  sizeof(raw_digest));
				memcpy(cached_bh->digest_crlf, raw_digest, sizeof(raw_digest));

				if (memcmp(ctx->bh, raw_digest, ctx->bhlen) != 0) {
					msg_debug_dkim(
						"bh value mismatch after added CRLF: %*xs versus %*xs, try add LF",
						(gint) dlen, ctx->bh,
						(gint) dlen, raw_digest);

					/* Try add LF */
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
					EVP_MD_CTX_cleanup(cpy_ctx);
#else
					EVP_MD_CTX_reset(cpy_ctx);
#endif
					EVP_MD_CTX_copy(cpy_ctx, ctx->common.body_hash);
					EVP_DigestUpdate(cpy_ctx, "\n", 1);
					EVP_DigestFinal_ex(cpy_ctx, raw_digest, NULL);
					cached_bh->digest_cr = rspamd_mempool_alloc(task->task_pool,
																sizeof(raw_digest));
					memcpy(cached_bh->digest_cr, raw_digest, sizeof(raw_digest));

					if (memcmp(ctx->bh, raw_digest, ctx->bhlen) != 0) {
						msg_debug_dkim("bh value mismatch after added LF: %*xs versus %*xs",
									   (gint) dlen, ctx->bh,
									   (gint) dlen, raw_digest);
						res->fail_reason = "body hash did not verify";
						res->rcode = DKIM_REJECT;
					}
				}
			}
			else if (cached_bh->digest_crlf) {
				if (memcmp(ctx->bh, cached_bh->digest_crlf, ctx->bhlen) != 0) {
					msg_debug_dkim("bh value mismatch after added CRLF: %*xs versus %*xs",
								   (gint) dlen, ctx->bh,
								   (gint) dlen, cached_bh->digest_crlf);

					if (cached_bh->digest_cr) {
						if (memcmp(ctx->bh, cached_bh->digest_cr, ctx->bhlen) != 0) {
							msg_debug_dkim(
								"bh value mismatch after added LF: %*xs versus %*xs",
								(gint) dlen, ctx->bh,
								(gint) dlen, cached_bh->digest_cr);

							res->fail_reason = "body hash did not verify";
							res->rcode = DKIM_REJECT;
						}
					}
					else {

						res->fail_reason = "body hash did not verify";
						res->rcode = DKIM_REJECT;
					}
				}
			}
			else {
				msg_debug_dkim(
					"bh value mismatch: %*xs versus %*xs",
					(gint) dlen, ctx->bh,
					(gint) dlen, cached_bh->digest_normal);
				res->fail_reason = "body hash did not verify";
				res->rcode = DKIM_REJECT;
			}
		}

		if (cpy_ctx) {
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
			EVP_MD_CTX_cleanup(cpy_ctx);
#else
			EVP_MD_CTX_reset(cpy_ctx);
#endif
			EVP_MD_CTX_destroy(cpy_ctx);
		}

		if (res->rcode == DKIM_REJECT) {
			msg_info_dkim(
				"%s: bh value mismatch: got %*Bs, expected %*Bs; "
				"body length %d->%d; d=%s; s=%s",
				rspamd_dkim_type_to_string(ctx->common.type),
				(gint) dlen, cached_bh->digest_normal,
				(gint) dlen, ctx->bh,
				(gint) (body_end - body_start), ctx->common.body_canonicalised,
				ctx->domain, ctx->selector);

			return res;
		}
	}

	dlen = EVP_MD_CTX_size(ctx->common.headers_hash);
	EVP_DigestFinal_ex(ctx->common.headers_hash, raw_digest, NULL);
	/* Check headers signature */

	if (ctx->sig_alg == DKIM_SIGN_RSASHA1) {
		nid = NID_sha1;
	}
	else if (ctx->sig_alg == DKIM_SIGN_RSASHA256 ||
			 ctx->sig_alg == DKIM_SIGN_ECDSASHA256 ||
			 ctx->sig_alg == DKIM_SIGN_EDDSASHA256) {
		nid = NID_sha256;
	}
	else if (ctx->sig_alg == DKIM_SIGN_RSASHA512 ||
			 ctx->sig_alg == DKIM_SIGN_ECDSASHA512) {
		nid = NID_sha512;
	}
	else {
		/* Not reached */
		nid = NID_sha1;
	}

	switch (key->type) {
	case RSPAMD_DKIM_KEY_RSA:
		if (RSA_verify(nid, raw_digest, dlen, ctx->b, ctx->blen,
					   key->key.key_rsa) != 1) {
			msg_debug_dkim("headers rsa verify failed");
			ERR_clear_error();
			res->rcode = DKIM_REJECT;
			res->fail_reason = "headers rsa verify failed";

			msg_info_dkim(
				"%s: headers RSA verification failure; "
				"body length %d->%d; headers length %d; d=%s; s=%s; key_md5=%*xs; orig header: %s",
				rspamd_dkim_type_to_string(ctx->common.type),
				(gint) (body_end - body_start), ctx->common.body_canonicalised,
				ctx->common.headers_canonicalised,
				ctx->domain, ctx->selector,
				RSPAMD_DKIM_KEY_ID_LEN, rspamd_dkim_key_id(key),
				ctx->dkim_header);
		}
		break;
	case RSPAMD_DKIM_KEY_ECDSA:
		if (ECDSA_verify(nid, raw_digest, dlen, ctx->b, ctx->blen,
						 key->key.key_ecdsa) != 1) {
			msg_info_dkim(
				"%s: headers ECDSA verification failure; "
				"body length %d->%d; headers length %d; d=%s; s=%s; key_md5=%*xs; orig header: %s",
				rspamd_dkim_type_to_string(ctx->common.type),
				(gint) (body_end - body_start), ctx->common.body_canonicalised,
				ctx->common.headers_canonicalised,
				ctx->domain, ctx->selector,
				RSPAMD_DKIM_KEY_ID_LEN, rspamd_dkim_key_id(key),
				ctx->dkim_header);
			msg_debug_dkim("headers ecdsa verify failed");
			ERR_clear_error();
			res->rcode = DKIM_REJECT;
			res->fail_reason = "headers ecdsa verify failed";
		}
		break;
	case RSPAMD_DKIM_KEY_EDDSA:
		if (!rspamd_cryptobox_verify(ctx->b, ctx->blen, raw_digest, dlen,
									 key->key.key_eddsa, RSPAMD_CRYPTOBOX_MODE_25519)) {
			msg_info_dkim(
				"%s: headers EDDSA verification failure; "
				"body length %d->%d; headers length %d; d=%s; s=%s; key_md5=%*xs; orig header: %s",
				rspamd_dkim_type_to_string(ctx->common.type),
				(gint) (body_end - body_start), ctx->common.body_canonicalised,
				ctx->common.headers_canonicalised,
				ctx->domain, ctx->selector,
				RSPAMD_DKIM_KEY_ID_LEN, rspamd_dkim_key_id(key),
				ctx->dkim_header);
			msg_debug_dkim("headers eddsa verify failed");
			res->rcode = DKIM_REJECT;
			res->fail_reason = "headers eddsa verify failed";
		}
		break;
	}


	if (ctx->common.type == RSPAMD_DKIM_ARC_SEAL && res->rcode == DKIM_CONTINUE) {
		switch (ctx->cv) {
		case RSPAMD_ARC_INVALID:
			msg_info_dkim("arc seal is invalid i=%d", ctx->common.idx);
			res->rcode = DKIM_PERM_ERROR;
			res->fail_reason = "arc seal is invalid";
			break;
		case RSPAMD_ARC_FAIL:
			msg_info_dkim("arc seal failed i=%d", ctx->common.idx);
			res->rcode = DKIM_REJECT;
			res->fail_reason = "arc seal failed";
			break;
		default:
			break;
		}
	}

	return res;
}

struct rspamd_dkim_check_result *
rspamd_dkim_create_result(rspamd_dkim_context_t *ctx,
						  enum rspamd_dkim_check_rcode rcode,
						  struct rspamd_task *task)
{
	struct rspamd_dkim_check_result *res;

	res = rspamd_mempool_alloc0(task->task_pool, sizeof(*res));
	res->ctx = ctx;
	res->selector = ctx->selector;
	res->domain = ctx->domain;
	res->fail_reason = NULL;
	res->short_b = ctx->short_b;
	res->rcode = rcode;

	return res;
}

rspamd_dkim_key_t *
rspamd_dkim_key_ref(rspamd_dkim_key_t *k)
{
	REF_RETAIN(k);

	return k;
}

void rspamd_dkim_key_unref(rspamd_dkim_key_t *k)
{
	REF_RELEASE(k);
}

rspamd_dkim_sign_key_t *
rspamd_dkim_sign_key_ref(rspamd_dkim_sign_key_t *k)
{
	REF_RETAIN(k);

	return k;
}

void rspamd_dkim_sign_key_unref(rspamd_dkim_sign_key_t *k)
{
	REF_RELEASE(k);
}

const gchar *
rspamd_dkim_get_domain(rspamd_dkim_context_t *ctx)
{
	if (ctx) {
		return ctx->domain;
	}

	return NULL;
}

const gchar *
rspamd_dkim_get_selector(rspamd_dkim_context_t *ctx)
{
	if (ctx) {
		return ctx->selector;
	}

	return NULL;
}

guint rspamd_dkim_key_get_ttl(rspamd_dkim_key_t *k)
{
	if (k) {
		return k->ttl;
	}

	return 0;
}

const gchar *
rspamd_dkim_get_dns_key(rspamd_dkim_context_t *ctx)
{
	if (ctx) {
		return ctx->dns_key;
	}

	return NULL;
}

#define PEM_SIG "-----BEGIN"

rspamd_dkim_sign_key_t *
rspamd_dkim_sign_key_load(const gchar *key, gsize len,
						  enum rspamd_dkim_key_format type,
						  GError **err)
{
	guchar *map = NULL, *tmp = NULL;
	gsize maplen;
	rspamd_dkim_sign_key_t *nkey;
	time_t mtime = time(NULL);

	if (type < 0 || type > RSPAMD_DKIM_KEY_UNKNOWN || len == 0 || key == NULL) {
		g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
					"invalid key type to load: %d", type);
		return NULL;
	}

	nkey = g_malloc0(sizeof(*nkey));
	nkey->mtime = mtime;

	msg_debug_dkim_taskless("got public key with length %z and type %d",
							len, type);

	/* Load key file if needed */
	if (type == RSPAMD_DKIM_KEY_FILE) {
		struct stat st;

		if (stat(key, &st) != 0) {
			g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
						"cannot stat key file: '%s' %s", key, strerror(errno));
			g_free(nkey);

			return NULL;
		}

		nkey->mtime = st.st_mtime;
		map = rspamd_file_xmap(key, PROT_READ, &maplen, TRUE);

		if (map == NULL) {
			g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
						"cannot map key file: '%s' %s", key, strerror(errno));
			g_free(nkey);

			return NULL;
		}

		key = map;
		len = maplen;

		if (maplen > sizeof(PEM_SIG) &&
			strncmp(map, PEM_SIG, sizeof(PEM_SIG) - 1) == 0) {
			type = RSPAMD_DKIM_KEY_PEM;
		}
		else if (rspamd_cryptobox_base64_is_valid(map, maplen)) {
			type = RSPAMD_DKIM_KEY_BASE64;
		}
		else {
			type = RSPAMD_DKIM_KEY_RAW;
		}
	}

	if (type == RSPAMD_DKIM_KEY_UNKNOWN) {
		if (len > sizeof(PEM_SIG) &&
			memcmp(key, PEM_SIG, sizeof(PEM_SIG) - 1) == 0) {
			type = RSPAMD_DKIM_KEY_PEM;
		}
		else {
			type = RSPAMD_DKIM_KEY_RAW;
		}
	}

	if (type == RSPAMD_DKIM_KEY_BASE64) {
		type = RSPAMD_DKIM_KEY_RAW;
		tmp = g_malloc(len);
		rspamd_cryptobox_base64_decode(key, len, tmp, &len);
		key = tmp;
	}

	if (type == RSPAMD_DKIM_KEY_RAW && (len == 32 ||
										len == rspamd_cryptobox_sk_sig_bytes(RSPAMD_CRYPTOBOX_MODE_25519))) {
		if (len == 32) {
			/* Seeded key, need scalarmult */
			unsigned char pk[32];
			nkey->type = RSPAMD_DKIM_KEY_EDDSA;
			nkey->key.key_eddsa = g_malloc(
				rspamd_cryptobox_sk_sig_bytes(RSPAMD_CRYPTOBOX_MODE_25519));
			crypto_sign_ed25519_seed_keypair(pk, nkey->key.key_eddsa, key);
			nkey->keylen = rspamd_cryptobox_sk_sig_bytes(RSPAMD_CRYPTOBOX_MODE_25519);
		}
		else {
			/* Full ed25519 key */
			unsigned klen = rspamd_cryptobox_sk_sig_bytes(RSPAMD_CRYPTOBOX_MODE_25519);
			nkey->type = RSPAMD_DKIM_KEY_EDDSA;
			nkey->key.key_eddsa = g_malloc(klen);
			memcpy(nkey->key.key_eddsa, key, klen);
			nkey->keylen = klen;
		}
	}
	else {
		nkey->key_bio = BIO_new_mem_buf(key, len);

		if (type == RSPAMD_DKIM_KEY_RAW) {
			if (d2i_PrivateKey_bio(nkey->key_bio, &nkey->key_evp) == NULL) {
				g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
							"cannot parse raw private key: %s",
							ERR_error_string(ERR_get_error(), NULL));

				rspamd_dkim_sign_key_free(nkey);
				nkey = NULL;

				goto end;
			}
		}
		else {
			if (!PEM_read_bio_PrivateKey(nkey->key_bio, &nkey->key_evp, NULL, NULL)) {
				g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
							"cannot parse pem private key: %s",
							ERR_error_string(ERR_get_error(), NULL));
				rspamd_dkim_sign_key_free(nkey);
				nkey = NULL;

				goto end;
			}
		}
		nkey->key.key_rsa = EVP_PKEY_get1_RSA(nkey->key_evp);
		if (nkey->key.key_rsa == NULL) {
			g_set_error(err,
						DKIM_ERROR,
						DKIM_SIGERROR_KEYFAIL,
						"cannot extract rsa key from evp key");
			rspamd_dkim_sign_key_free(nkey);
			nkey = NULL;

			goto end;
		}
		nkey->type = RSPAMD_DKIM_KEY_RSA;
	}

	REF_INIT_RETAIN(nkey, rspamd_dkim_sign_key_free);

end:

	if (map != NULL) {
		munmap(map, maplen);
	}

	if (tmp != NULL) {
		rspamd_explicit_memzero(tmp, len);
		g_free(tmp);
	}

	return nkey;
}

#undef PEM_SIG

gboolean
rspamd_dkim_sign_key_maybe_invalidate(rspamd_dkim_sign_key_t *key, time_t mtime)
{
	if (mtime > key->mtime) {
		return TRUE;
	}
	return FALSE;
}

rspamd_dkim_sign_context_t *
rspamd_create_dkim_sign_context(struct rspamd_task *task,
								rspamd_dkim_sign_key_t *priv_key,
								gint headers_canon,
								gint body_canon,
								const gchar *headers,
								enum rspamd_dkim_type type,
								GError **err)
{
	rspamd_dkim_sign_context_t *nctx;

	if (headers_canon != DKIM_CANON_SIMPLE && headers_canon != DKIM_CANON_RELAXED) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_INVALID_HC,
					"bad headers canonicalisation");

		return NULL;
	}
	if (body_canon != DKIM_CANON_SIMPLE && body_canon != DKIM_CANON_RELAXED) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_INVALID_BC,
					"bad body canonicalisation");

		return NULL;
	}

	if (!priv_key || (!priv_key->key.key_rsa && !priv_key->key.key_eddsa)) {
		g_set_error(err,
					DKIM_ERROR,
					DKIM_SIGERROR_KEYFAIL,
					"bad key to sign");

		return NULL;
	}

	nctx = rspamd_mempool_alloc0(task->task_pool, sizeof(*nctx));
	nctx->common.pool = task->task_pool;
	nctx->common.header_canon_type = headers_canon;
	nctx->common.body_canon_type = body_canon;
	nctx->common.type = type;
	nctx->common.is_sign = TRUE;

	if (type != RSPAMD_DKIM_ARC_SEAL) {
		if (!rspamd_dkim_parse_hdrlist_common(&nctx->common, headers,
											  strlen(headers), TRUE,
											  err)) {
			return NULL;
		}
	}
	else {
		rspamd_dkim_add_arc_seal_headers(task->task_pool, &nctx->common);
	}

	nctx->key = rspamd_dkim_sign_key_ref(priv_key);

	rspamd_mempool_add_destructor(task->task_pool,
								  (rspamd_mempool_destruct_t) rspamd_dkim_sign_key_unref, priv_key);

#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
	nctx->common.body_hash = EVP_MD_CTX_create();
	EVP_DigestInit_ex(nctx->common.body_hash, EVP_sha256(), NULL);
	nctx->common.headers_hash = EVP_MD_CTX_create();
	EVP_DigestInit_ex(nctx->common.headers_hash, EVP_sha256(), NULL);
	rspamd_mempool_add_destructor(task->task_pool,
								  (rspamd_mempool_destruct_t) EVP_MD_CTX_destroy, nctx->common.body_hash);
	rspamd_mempool_add_destructor(task->task_pool,
								  (rspamd_mempool_destruct_t) EVP_MD_CTX_destroy, nctx->common.headers_hash);
#else
	nctx->common.body_hash = EVP_MD_CTX_new();
	EVP_DigestInit_ex(nctx->common.body_hash, EVP_sha256(), NULL);
	nctx->common.headers_hash = EVP_MD_CTX_new();
	EVP_DigestInit_ex(nctx->common.headers_hash, EVP_sha256(), NULL);
	rspamd_mempool_add_destructor(task->task_pool,
								  (rspamd_mempool_destruct_t) EVP_MD_CTX_free, nctx->common.body_hash);
	rspamd_mempool_add_destructor(task->task_pool,
								  (rspamd_mempool_destruct_t) EVP_MD_CTX_free, nctx->common.headers_hash);
#endif

	return nctx;
}


GString *
rspamd_dkim_sign(struct rspamd_task *task, const gchar *selector,
				 const gchar *domain, time_t expire, gsize len, guint idx,
				 const gchar *arc_cv, rspamd_dkim_sign_context_t *ctx)
{
	GString *hdr;
	struct rspamd_dkim_header *dh;
	const gchar *body_end, *body_start, *hname;
	guchar raw_digest[EVP_MAX_MD_SIZE];
	struct rspamd_dkim_cached_hash *cached_bh = NULL;
	gsize dlen = 0;
	guint i, j;
	gchar *b64_data;
	guchar *sig_buf;
	guint sig_len;
	guint headers_len = 0, cur_len = 0;
	union rspamd_dkim_header_stat hstat;

	g_assert(ctx != NULL);

	/* First of all find place of body */
	body_end = task->msg.begin + task->msg.len;
	body_start = MESSAGE_FIELD(task, raw_headers_content).body_start;

	if (len > 0) {
		ctx->common.len = len;
	}

	if (!body_start) {
		return NULL;
	}

	/* Start canonization of body part */
	if (ctx->common.type != RSPAMD_DKIM_ARC_SEAL) {
		dlen = EVP_MD_CTX_size(ctx->common.body_hash);
		cached_bh = rspamd_dkim_check_bh_cached(&ctx->common, task,
												dlen, TRUE);

		if (!cached_bh->digest_normal) {
			/* Start canonization of body part */
			if (!rspamd_dkim_canonize_body(&ctx->common, body_start, body_end,
										   TRUE)) {
				return NULL;
			}
		}
	}

	hdr = g_string_sized_new(255);

	if (ctx->common.type == RSPAMD_DKIM_NORMAL) {
		rspamd_printf_gstring(hdr, "v=1; a=%s; c=%s/%s; d=%s; s=%s; ",
							  ctx->key->type == RSPAMD_DKIM_KEY_RSA ? "rsa-sha256" : "ed25519-sha256",
							  ctx->common.header_canon_type == DKIM_CANON_RELAXED ? "relaxed" : "simple",
							  ctx->common.body_canon_type == DKIM_CANON_RELAXED ? "relaxed" : "simple",
							  domain, selector);
	}
	else if (ctx->common.type == RSPAMD_DKIM_ARC_SIG) {
		rspamd_printf_gstring(hdr, "i=%d; a=%s; c=%s/%s; d=%s; s=%s; ",
							  idx,
							  ctx->key->type == RSPAMD_DKIM_KEY_RSA ? "rsa-sha256" : "ed25519-sha256",
							  ctx->common.header_canon_type == DKIM_CANON_RELAXED ? "relaxed" : "simple",
							  ctx->common.body_canon_type == DKIM_CANON_RELAXED ? "relaxed" : "simple",
							  domain, selector);
	}
	else {
		g_assert(arc_cv != NULL);
		rspamd_printf_gstring(hdr, "i=%d; a=%s; d=%s; s=%s; cv=%s; ",
							  idx,
							  ctx->key->type == RSPAMD_DKIM_KEY_RSA ? "rsa-sha256" : "ed25519-sha256",
							  domain,
							  selector,
							  arc_cv);
	}

	if (expire > 0) {
		rspamd_printf_gstring(hdr, "x=%t; ", expire);
	}

	if (ctx->common.type != RSPAMD_DKIM_ARC_SEAL) {
		if (len > 0) {
			rspamd_printf_gstring(hdr, "l=%z; ", len);
		}
	}

	rspamd_printf_gstring(hdr, "t=%t; h=", time(NULL));

	/* Now canonize headers */
	for (i = 0; i < ctx->common.hlist->len; i++) {
		struct rspamd_mime_header *rh, *cur;

		dh = g_ptr_array_index(ctx->common.hlist, i);

		/* We allow oversigning if dh->count > number of headers with this name */
		hstat.n = GPOINTER_TO_UINT(g_hash_table_lookup(ctx->common.htable, dh->name));

		if (hstat.s.flags & RSPAMD_DKIM_FLAG_OVERSIGN) {
			/* Do oversigning */
			guint count = 0;

			rh = rspamd_message_get_header_array(task, dh->name, FALSE);

			if (rh) {
				DL_FOREACH(rh, cur)
				{
					/* Sign all existing headers */
					rspamd_dkim_canonize_header(&ctx->common, task, dh->name,
												count,
												NULL, NULL);
					count++;
				}
			}

			/* Now add one more entry to oversign */
			if (count > 0 || !(hstat.s.flags & RSPAMD_DKIM_FLAG_OVERSIGN_EXISTING)) {
				cur_len = (strlen(dh->name) + 1) * (count + 1);
				headers_len += cur_len;

				if (headers_len > 70 && i > 0 && i < ctx->common.hlist->len - 1) {
					rspamd_printf_gstring(hdr, "  ");
					headers_len = cur_len;
				}

				for (j = 0; j < count + 1; j++) {
					rspamd_printf_gstring(hdr, "%s:", dh->name);
				}
			}
		}
		else {
			rh = rspamd_message_get_header_array(task, dh->name, FALSE);

			if (rh) {
				if (hstat.s.count > 0) {

					cur_len = (strlen(dh->name) + 1) * (hstat.s.count);
					headers_len += cur_len;
					if (headers_len > 70 && i > 0 && i < ctx->common.hlist->len - 1) {
						rspamd_printf_gstring(hdr, "  ");
						headers_len = cur_len;
					}

					for (j = 0; j < hstat.s.count; j++) {
						rspamd_printf_gstring(hdr, "%s:", dh->name);
					}
				}


				rspamd_dkim_canonize_header(&ctx->common, task,
											dh->name, dh->count,
											NULL, NULL);
			}
		}

		g_hash_table_remove(ctx->common.htable, dh->name);
	}

	/* Replace the last ':' with ';' */
	hdr->str[hdr->len - 1] = ';';

	if (ctx->common.type != RSPAMD_DKIM_ARC_SEAL) {
		if (!cached_bh->digest_normal) {
			EVP_DigestFinal_ex(ctx->common.body_hash, raw_digest, NULL);
			cached_bh->digest_normal = rspamd_mempool_alloc(task->task_pool,
															sizeof(raw_digest));
			memcpy(cached_bh->digest_normal, raw_digest, sizeof(raw_digest));
		}


		b64_data = rspamd_encode_base64(cached_bh->digest_normal, dlen, 0, NULL);
		rspamd_printf_gstring(hdr, " bh=%s; b=", b64_data);
		g_free(b64_data);
	}
	else {
		rspamd_printf_gstring(hdr, " b=");
	}

	switch (ctx->common.type) {
	case RSPAMD_DKIM_NORMAL:
	default:
		hname = RSPAMD_DKIM_SIGNHEADER;
		break;
	case RSPAMD_DKIM_ARC_SIG:
		hname = RSPAMD_DKIM_ARC_SIGNHEADER;
		break;
	case RSPAMD_DKIM_ARC_SEAL:
		hname = RSPAMD_DKIM_ARC_SEALHEADER;
		break;
	}

	if (ctx->common.header_canon_type == DKIM_CANON_RELAXED) {
		if (!rspamd_dkim_canonize_header_relaxed(&ctx->common,
												 hdr->str,
												 hname,
												 TRUE,
												 0,
												 ctx->common.type == RSPAMD_DKIM_ARC_SEAL)) {

			g_string_free(hdr, TRUE);
			return NULL;
		}
	}
	else {
		/* Will likely have issues with folding */
		rspamd_dkim_hash_update(ctx->common.headers_hash, hdr->str,
								hdr->len);
		ctx->common.headers_canonicalised += hdr->len;
		msg_debug_task("update signature with header: %*s",
					   (gint) hdr->len, hdr->str);
	}

	dlen = EVP_MD_CTX_size(ctx->common.headers_hash);
	EVP_DigestFinal_ex(ctx->common.headers_hash, raw_digest, NULL);
	if (ctx->key->type == RSPAMD_DKIM_KEY_RSA) {
		sig_len = RSA_size(ctx->key->key.key_rsa);
		sig_buf = g_alloca(sig_len);

		if (RSA_sign(NID_sha256, raw_digest, dlen, sig_buf, &sig_len,
					 ctx->key->key.key_rsa) != 1) {
			g_string_free(hdr, TRUE);
			msg_err_task("rsa sign error: %s",
						 ERR_error_string(ERR_get_error(), NULL));

			return NULL;
		}
	}
	else if (ctx->key->type == RSPAMD_DKIM_KEY_EDDSA) {
		sig_len = rspamd_cryptobox_signature_bytes(RSPAMD_CRYPTOBOX_MODE_25519);
		sig_buf = g_alloca(sig_len);

		rspamd_cryptobox_sign(sig_buf, NULL, raw_digest, dlen,
							  ctx->key->key.key_eddsa, RSPAMD_CRYPTOBOX_MODE_25519);
	}
	else {
		g_string_free(hdr, TRUE);
		msg_err_task("unsupported key type for signing");

		return NULL;
	}

	if (task->protocol_flags & RSPAMD_TASK_PROTOCOL_FLAG_MILTER) {
		b64_data = rspamd_encode_base64_fold(sig_buf, sig_len, 70, NULL,
											 RSPAMD_TASK_NEWLINES_LF);
	}
	else {
		b64_data = rspamd_encode_base64_fold(sig_buf, sig_len, 70, NULL,
											 MESSAGE_FIELD(task, nlines_type));
	}

	rspamd_printf_gstring(hdr, "%s", b64_data);
	g_free(b64_data);

	return hdr;
}

gboolean
rspamd_dkim_match_keys(rspamd_dkim_key_t *pk,
					   rspamd_dkim_sign_key_t *sk,
					   GError **err)
{
	if (pk == NULL || sk == NULL) {
		g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
					"missing public or private key");
		return FALSE;
	}
	if (pk->type != sk->type) {
		g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
					"public and private key types do not match");
		return FALSE;
	}

	if (pk->type == RSPAMD_DKIM_KEY_EDDSA) {
		if (memcmp(sk->key.key_eddsa + 32, pk->key.key_eddsa, 32) != 0) {
			g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYHASHMISMATCH,
						"pubkey does not match private key");
			return FALSE;
		}
	}
	else if (EVP_PKEY_cmp(pk->key_evp, sk->key_evp) != 1) {
		g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYHASHMISMATCH,
					"pubkey does not match private key");
		return FALSE;
	}

	return TRUE;
}