aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/lua/dmarc.lua
blob: 1bac6fb297000fdd8d2c5074bf07f4069c461479 (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
--[[
Copyright (c) 2011-2016, Vsevolod Stakhov <vsevolod@highsecure.ru>
Copyright (c) 2015-2016, Andrew Lewis <nerf@judo.za.org>

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.
]]--

-- Dmarc policy filter

local rspamd_logger = require "rspamd_logger"
local mempool = require "rspamd_mempool"
local rspamd_tcp = require "rspamd_tcp"
local rspamd_url = require "rspamd_url"
local rspamd_util = require "rspamd_util"
local rspamd_redis = require "lua_redis"
local lua_util = require "lua_util"
local check_local = false
local check_authed = false

if confighelp then
  return
end

local N = 'dmarc'
local no_sampling_domains
local no_reporting_domains
local statefile = string.format('%s/%s', rspamd_paths['DBDIR'], 'dmarc_reports_last_sent')
local VAR_NAME = 'dmarc_reports_last_sent'
local INTERVAL = 86400
local pool

local report_settings = {
  helo = 'rspamd',
  hscan_count = 1000,
  smtp = '127.0.0.1',
  smtp_port = 25,
  retries = 2,
  from_name = 'Rspamd',
}
local report_template = [[From: "%s" <%s>
To: %s
Subject: Report Domain: %s
	Submitter: %s
	Report-ID: <%s>
Date: %s
MIME-Version: 1.0
Message-ID: <%s>
Content-Type: multipart/mixed;
	boundary="----=_NextPart_000_024E_01CC9B0A.AFE54C00"

This is a multipart message in MIME format.

------=_NextPart_000_024E_01CC9B0A.AFE54C00
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit

This is an aggregate report from %s.

------=_NextPart_000_024E_01CC9B0A.AFE54C00
Content-Type: application/gzip
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
	filename="%s!%s!%s!%s.xml.gz"

]]
local report_footer = [[

------=_NextPart_000_024E_01CC9B0A.AFE54C00--]]

local symbols = {
  spf_allow_symbol = 'R_SPF_ALLOW',
  spf_deny_symbol = 'R_SPF_FAIL',
  spf_softfail_symbol = 'R_SPF_SOFTFAIL',
  spf_neutral_symbol = 'R_SPF_NEUTRAL',
  spf_tempfail_symbol = 'R_SPF_DNSFAIL',
  spf_permfail_symbol = 'R_SPF_PERMFAIL',
  spf_na_symbol = 'R_SPF_NA',

  dkim_allow_symbol = 'R_DKIM_ALLOW',
  dkim_deny_symbol = 'R_DKIM_REJECT',
  dkim_tempfail_symbol = 'R_DKIM_TEMPFAIL',
  dkim_na_symbol = 'R_DKIM_NA',
  dkim_permfail_symbol = 'R_DKIM_PERMFAIL',
}

local dmarc_symbols = {
  allow = 'DMARC_POLICY_ALLOW',
  badpolicy = 'DMARC_BAD_POLICY',
  dnsfail = 'DMARC_DNSFAIL',
  na = 'DMARC_NA',
  reject = 'DMARC_POLICY_REJECT',
  softfail = 'DMARC_POLICY_SOFTFAIL',
  quarantine = 'DMARC_POLICY_QUARANTINE',
}

local redis_keys = {
  index_prefix = 'dmarc_idx',
  report_prefix = 'dmarc',
  join_char = ';',
}

local function gen_xml_grammar()
  local lpeg = require 'lpeg'
  local lt = lpeg.P('<') / '&lt;'
  local gt = lpeg.P('>') / '&gt;'
  local amp = lpeg.P('&') / '&amp;'
  local quot = lpeg.P('"') / '&quot;'
  local apos = lpeg.P("'") / '&apos;'
  local special = lt + gt + amp + quot + apos
  local grammar = lpeg.Cs((special + 1)^0)
  return grammar
end

local xml_grammar = gen_xml_grammar()

local function escape_xml(goo)
  return xml_grammar:match(goo)
end

-- Default port for redis upstreams
local redis_params = nil
-- 2 days
local dmarc_reporting = false
local dmarc_actions = {}

local E = {}

local take_report_id
local take_report_script = [[
local index_key = KEYS[1]
local report_key = KEYS[2]
local dmarc_domain = ARGV[1]
local report = ARGV[2]
redis.call('SADD', index_key, report_key)
redis.call('EXPIRE', index_key, 172800)
redis.call('HINCRBY', report_key, report, 1)
redis.call('EXPIRE', report_key, 172800)
]]

-- return the timezone offset in seconds, as it was on the time given by ts
-- Eric Feliksik
local function get_timezone_offset(ts)
  local utcdate   = os.date("!*t", ts)
  local localdate = os.date("*t", ts)
  localdate.isdst = false -- this is the trick
  return os.difftime(os.time(localdate), os.time(utcdate))
end

local tz_offset = get_timezone_offset(os.time())

local function gen_dmarc_grammar()
  local lpeg = require "lpeg"
  lpeg.locale(lpeg)
  local space = lpeg.space^0
  local name = lpeg.C(lpeg.alpha^1) * space
  local sep = lpeg.S("\\;") * space
  local value = lpeg.C(lpeg.P(lpeg.graph - sep)^1)
  local pair = lpeg.Cg(name * "=" * space * value) * sep^-1
  local list = lpeg.Cf(lpeg.Ct("") * pair^0, rawset)
  local version = lpeg.P("v") * space * lpeg.P("=") * space * lpeg.P("DMARC1")
  local record = version * space * sep * list

  return record
end

local dmarc_grammar = gen_dmarc_grammar()

local function dmarc_report(task, spf_ok, dkim_ok, disposition,
    sampled_out, hfromdom, spfdom, dres, spf_result)
  local ip = task:get_from_ip()
  if not ip:is_valid() then
    return nil
  end
  local rspamd_lua_utils = require "lua_util"
  if rspamd_lua_utils.is_rspamc_or_controller(task) then return end
  local dkim_pass = table.concat(dres.pass or E, '|')
  local dkim_fail = table.concat(dres.fail or E, '|')
  local dkim_temperror = table.concat(dres.temperror or E, '|')
  local dkim_permerror = table.concat(dres.permerror or E, '|')
  local res = table.concat({
    ip:to_string(), spf_ok, dkim_ok,
    disposition, (sampled_out and 'sampled_out' or ''), hfromdom,
    dkim_pass, dkim_fail, dkim_temperror, dkim_permerror, spfdom, spf_result}, ',')

  return res
end

local function maybe_force_action(task, disposition)
  if disposition then
    local force_action = dmarc_actions[disposition]
    if force_action then
      -- Don't do anything if pre-result has been already set
      if task:has_pre_result() then return end
      task:set_pre_result(force_action, 'Action set by DMARC', N)
    end
  end
end

--[[
-- Used to check dmarc record, check elements and produce dmarc policy processed
-- result.
-- Returns:
--     false,false - record is garbadge
--     false,error_message - record is invalid
--     true,policy_table - record is valid and parsed
]]
local function dmarc_check_record(task, record, is_tld)
  local failed_policy
  local result = {
    dmarc_policy = 'none'
  }

  local elts = dmarc_grammar:match(record)
  lua_util.debugm(N, task, "got DMARC record: %s, tld_flag=%s, processed=%s",
      record, is_tld, elts)

  if elts then
    local dkim_pol = elts['adkim']
    if dkim_pol then
      if dkim_pol == 's' then
        result.strict_dkim = true
      elseif dkim_pol ~= 'r' then
        failed_policy = 'adkim tag has invalid value: ' .. dkim_pol
        return false,failed_policy
      end
    end

    local spf_pol = elts['aspf']
    if spf_pol then
      if spf_pol == 's' then
        result.strict_spf = true
      elseif spf_pol ~= 'r' then
        failed_policy = 'aspf tag has invalid value: ' .. spf_pol
        return false,failed_policy
      end
    end

    local policy = elts['p']
    if policy then
      if (policy == 'reject') then
        result.dmarc_policy = 'reject'
      elseif (policy == 'quarantine') then
        result.dmarc_policy = 'quarantine'
      elseif (policy ~= 'none') then
        failed_policy = 'p tag has invalid value: ' .. policy
        return false,failed_policy
      end
    end

    -- Adjust policy if we are in tld mode
    local subdomain_policy = elts['sp']
    if elts['sp'] and is_tld then
      result.subdomain_policy = elts['sp']

      if (subdomain_policy == 'reject') then
        result.dmarc_policy = 'reject'
      elseif (subdomain_policy == 'quarantine') then
        result.dmarc_policy = 'quarantine'
      elseif (subdomain_policy == 'none') then
        result.dmarc_policy = 'none'
      elseif (subdomain_policy ~= 'none') then
        failed_policy = 'sp tag has invalid value: ' .. subdomain_policy
        return false,failed_policy
      end
    end
    result.pct = elts['pct']
    if result.pct then
      result.pct = tonumber(result.pct)
    end

    if elts.rua then
      result.rua = elts['rua']
    end
  else
    return false,false -- Ignore garbadge
  end

  return true, result
end

local function dmarc_validate_policy(task, policy, hdrfromdom, dmarc_esld)
  local reason = {}

  -- Check dkim and spf symbols
  local spf_ok = false
  local dkim_ok = false
  local spf_tmpfail = false
  local dkim_tmpfail = false

  local spf_domain = ((task:get_from(1) or E)[1] or E).domain

  if not spf_domain or spf_domain == '' then
    spf_domain = task:get_helo() or ''
  end

  if task:has_symbol(symbols['spf_allow_symbol']) then
    if policy.strict_spf then
      if rspamd_util.strequal_caseless(spf_domain, hdrfromdom) then
        spf_ok = true
      else
        table.insert(reason, "SPF not aligned (strict)")
      end
    else
      local spf_tld = rspamd_util.get_tld(spf_domain)
      if rspamd_util.strequal_caseless(spf_tld, dmarc_esld) then
        spf_ok = true
      else
        table.insert(reason, "SPF not aligned (relaxed)")
      end
    end
  else
    if task:has_symbol(symbols['spf_tempfail_symbol']) then
      if policy.strict_spf then
        if rspamd_util.strequal_caseless(spf_domain, hdrfromdom) then
          spf_tmpfail = true
        end
      else
        local spf_tld = rspamd_util.get_tld(spf_domain)
        if rspamd_util.strequal_caseless(spf_tld, dmarc_esld) then
          spf_tmpfail = true
        end
      end
    end

    table.insert(reason, "No valid SPF")
  end


  local opts = ((task:get_symbol('DKIM_TRACE') or E)[1] or E).options
  local dkim_results = {
    pass = {},
    temperror = {},
    permerror = {},
    fail = {},
  }


  if opts then
    dkim_results.pass = {}
    local dkim_violated

    for _,opt in ipairs(opts) do
      local check_res = string.sub(opt, -1)
      local domain = string.sub(opt, 1, -3)

      if check_res == '+' then
        table.insert(dkim_results.pass, domain)

        if policy.strict_dkim then
          if rspamd_util.strequal_caseless(hdrfromdom, domain) then
            dkim_ok = true
          else
            dkim_violated = "DKIM not aligned (strict)"
          end
        else
          local dkim_tld = rspamd_util.get_tld(domain)

          if rspamd_util.strequal_caseless(dkim_tld, dmarc_esld) then
            dkim_ok = true
          else
            dkim_violated = "DKIM not aligned (relaxed)"
          end
        end
      elseif check_res == '?' then
        -- Check for dkim tempfail
        if not dkim_ok then
          if policy.strict_dkim then
            if rspamd_util.strequal_caseless(hdrfromdom, domain) then
              dkim_tmpfail = true
            end
          else
            local dkim_tld = rspamd_util.get_tld(domain)

            if rspamd_util.strequal_caseless(dkim_tld, dmarc_esld) then
              dkim_tmpfail = true
            end
          end
        end
        table.insert(dkim_results.temperror, domain)
      elseif check_res == '-' then
        table.insert(dkim_results.fail, domain)
      else
        table.insert(dkim_results.permerror, domain)
      end
    end

    if not dkim_ok and dkim_violated then
      table.insert(reason, dkim_violated)
    end
  else
    table.insert(reason, "No valid DKIM")
  end

  lua_util.debugm(N, task, "validated dmarc policy for %s: %s; dkim_ok=%s, dkim_tempfail=%s, spf_ok=%s, spf_tempfail=%s",
      policy.domain, policy.dmarc_policy,
      dkim_ok, dkim_tmpfail,
      spf_ok, spf_tmpfail)

  local disposition = 'none'
  local sampled_out = false

  local function handle_dmarc_failure(what, reason_str)
    if not policy.pct or policy.pct == 100 then
      task:insert_result(dmarc_symbols[what], 1.0,
          policy.domain .. ' : ' .. reason_str, policy.dmarc_policy)
      disposition = what
    else
      local coin = math.random(100)
      if (coin > policy.pct) then
        if (not no_sampling_domains or
            not no_sampling_domains:get_key(policy.domain)) then

          if what == 'reject' then
            disposition = 'quarantine'
          else
            disposition = 'softfail'
          end

          task:insert_result(dmarc_symbols[disposition], 1.0,
              policy.domain .. ' : ' .. reason_str, policy.dmarc_policy, "sampled_out")
          sampled_out = true
          lua_util.debugm(N, task,
              'changed dmarc policy from %s to %s, sampled out: %s < %s',
              what, disposition, coin, policy.pct)
        else
          task:insert_result(dmarc_symbols[what], 1.0,
              policy.domain .. ' : ' .. reason_str, policy.dmarc_policy, "local_policy")
          disposition = what
        end
      else
        task:insert_result(dmarc_symbols[what], 1.0,
            policy.domain .. ' : ' .. reason_str, policy.dmarc_policy)
        disposition = what
      end
    end

    maybe_force_action(task, disposition)
  end

  if spf_ok or dkim_ok then
    --[[
    https://tools.ietf.org/html/rfc7489#section-6.6.2
    DMARC evaluation can only yield a "pass" result after one of the
    underlying authentication mechanisms passes for an aligned
    identifier.
    ]]--
    task:insert_result(dmarc_symbols['allow'], 1.0, policy.domain,
        policy.dmarc_policy)
  else
    --[[
    https://tools.ietf.org/html/rfc7489#section-6.6.2

    If neither passes and one or both of them fail due to a
    temporary error, the Receiver evaluating the message is unable to
    conclude that the DMARC mechanism had a permanent failure; they
    therefore cannot apply the advertised DMARC policy.
    ]]--
    if spf_tmpfail or dkim_tmpfail then
      task:insert_result(dmarc_symbols['dnsfail'], 1.0, policy.domain..
          ' : ' .. 'SPF/DKIM temp error', policy.dmarc_policy)
    else
      -- We can now check the failed policy and maybe send report data elt
      local reason_str = table.concat(reason, ', ')

      if policy.dmarc_policy == 'quarantine' then
        handle_dmarc_failure('quarantine', reason_str)
      elseif policy.dmarc_policy == 'reject' then
        handle_dmarc_failure('reject', reason_str)
      else
        task:insert_result(dmarc_symbols['softfail'], 1.0,
            policy.domain .. ' : ' .. reason_str,
            policy.dmarc_policy)
      end
    end
  end

  if policy.rua and redis_params and dmarc_reporting then
    if no_reporting_domains then
      if no_reporting_domains:get_key(policy.domain) or
          no_reporting_domains:get_key(rspamd_util.get_tld(policy.domain)) then
        rspamd_logger.infox(task, 'DMARC reporting suppressed for %1', policy.domain)
        return
      end
    end

    local function dmarc_report_cb(err)
      if not err then
        rspamd_logger.infox(task, '<%1> dmarc report saved for %2',
            task:get_message_id(), hdrfromdom)
      else
        rspamd_logger.errx(task, '<%1> dmarc report is not saved for %2: %3',
            task:get_message_id(), hdrfromdom, err)
      end
    end

    local spf_result
    if spf_ok then
      spf_result = 'pass'
    elseif spf_tmpfail then
      spf_result = 'temperror'
    else
      if task:get_symbol(symbols.spf_deny_symbol) then
        spf_result = 'fail'
      elseif task:get_symbol(symbols.spf_softfail_symbol) then
        spf_result = 'softfail'
      elseif task:get_symbol(symbols.spf_neutral_symbol) then
        spf_result = 'neutral'
      elseif task:get_symbol(symbols.spf_permfail_symbol) then
        spf_result = 'permerror'
      else
        spf_result = 'none'
      end
    end

    -- Prepare and send redis report element
    local period = os.date('%Y%m%d',
        task:get_date({format = 'connect', gmt = true}))
    local dmarc_domain_key = table.concat(
        {redis_keys.report_prefix, hdrfromdom, period}, redis_keys.join_char)
    local report_data = dmarc_report(task,
        spf_ok and 'pass' or 'fail',
        dkim_ok and 'pass' or 'fail',
        disposition,
        sampled_out,
        hdrfromdom,
        spf_domain,
        dkim_results,
        spf_result)

    local idx_key = table.concat({redis_keys.index_prefix, period},
        redis_keys.join_char)

    if report_data then
      rspamd_redis.exec_redis_script(take_report_id,
          {task = task, is_write = true},
          dmarc_report_cb,
          {idx_key, dmarc_domain_key},
          {hdrfromdom, report_data})
    end
  end
end

local function dmarc_callback(task)
  local from = task:get_from(2)
  local hfromdom = ((from or E)[1] or E).domain
  local dmarc_domain
  local ip_addr = task:get_ip()
  local dmarc_checks = task:get_mempool():get_variable('dmarc_checks', 'int') or 0
  local seen_invalid = false

  if dmarc_checks ~= 2 then
    rspamd_logger.infox(task, "skip DMARC checks as either SPF or DKIM were not checked");
    return
  end

  if ((not check_authed and task:get_user()) or
      (not check_local and ip_addr and ip_addr:is_local())) then
    rspamd_logger.infox(task, "skip DMARC checks for local networks and authorized users");
    return
  end

  -- Do some initial sanity checks, detect tld domain if different
  if hfromdom and hfromdom ~= '' and not (from or E)[2] then
    dmarc_domain = rspamd_util.get_tld(hfromdom)
  elseif (from or E)[2] then
    task:insert_result(dmarc_symbols['na'], 1.0, 'Duplicate From header')
    return maybe_force_action(task, 'na')
  elseif (from or E)[1] then
    task:insert_result(dmarc_symbols['na'], 1.0, 'No domain in From header')
    return maybe_force_action(task,'na')
  else
    task:insert_result(dmarc_symbols['na'], 1.0, 'No From header')
    return maybe_force_action(task,'na')
  end


  local dns_checks_inflight = 0
  local dmarc_domain_policy = {}
  local dmarc_tld_policy = {}

  local function process_dmarc_policy(policy, final)
    lua_util.debugm(N, task, "validate DMARC policy (final=%s): %s",
        true, policy)
    if policy.err and policy.symbol then
      -- In case of fatal errors or final check for tld, we give up and
      -- insert result
      if final or policy.fatal then
        task:insert_result(policy.symbol, 1.0, policy.err)
        maybe_force_action(task, policy.disposition)

        return true
      end
    elseif policy.dmarc_policy then
      dmarc_validate_policy(task, policy, hfromdom, dmarc_domain)

      return true -- We have a more specific version, use it
    end

    return false -- Missing record
  end

  local function gen_dmarc_cb(lookup_domain, is_tld)
    local policy_target = dmarc_domain_policy
    if is_tld then
      policy_target = dmarc_tld_policy
    end

    return function (_, _, results, err)
      dns_checks_inflight = dns_checks_inflight - 1

      if not seen_invalid then
        policy_target.domain = lookup_domain

        if err then
          if (err ~= 'requested record is not found' and
              err ~= 'no records with this name') then
            policy_target.err = lookup_domain .. ' : ' .. err
            policy_target.symbol = dmarc_symbols['dnsfail']
          else
            policy_target.err = lookup_domain
            policy_target.symbol = dmarc_symbols['na']
          end
        else
          local has_valid_policy = false

          for _,rec in ipairs(results) do
            local ret,results_or_err = dmarc_check_record(task, rec, is_tld)

            if not ret then
              if results_or_err then
                -- We have a fatal parsing error, give up
                policy_target.err = lookup_domain .. ' : ' .. results_or_err
                policy_target.symbol = dmarc_symbols['badpolicy']
                policy_target.fatal = true
                seen_invalid = true
              end
            else
              if has_valid_policy then
                policy_target.err = lookup_domain .. ' : ' ..
                    'Multiple policies defined in DNS'
                policy_target.symbol = dmarc_symbols['badpolicy']
                policy_target.fatal = true
                seen_invalid = true
              end
              has_valid_policy = true

              for k,v in pairs(results_or_err) do
                policy_target[k] = v
              end
            end
          end
        end
      end

      if dns_checks_inflight == 0 then
        lua_util.debugm(N, task, "finished DNS queries, validate policies")
        -- We have checked both tld and real domain (if different)
        if not process_dmarc_policy(dmarc_domain_policy, false) then
          -- Try tld policy as well
          if not process_dmarc_policy(dmarc_tld_policy, true) then
            process_dmarc_policy(dmarc_domain_policy, true)
          end
        end
      end
    end
  end

  local resolve_name = '_dmarc.' .. hfromdom

  task:get_resolver():resolve_txt({
    task=task,
    name = resolve_name,
    callback = gen_dmarc_cb(hfromdom, false),
    forced = true
  })
  dns_checks_inflight = dns_checks_inflight + 1

  if dmarc_domain ~= hfromdom then
    resolve_name = '_dmarc.' .. dmarc_domain

    task:get_resolver():resolve_txt({
      task=task,
      name = resolve_name,
      callback = gen_dmarc_cb(dmarc_domain, true),
      forced = true
    })

    dns_checks_inflight = dns_checks_inflight + 1
  end
end


local function try_opts(where)
  local ret = false
  local opts = rspamd_config:get_all_opt(where)
  if type(opts) == 'table' then
    if type(opts['check_local']) == 'boolean' then
      check_local = opts['check_local']
      ret = true
    end
    if type(opts['check_authed']) == 'boolean' then
      check_authed = opts['check_authed']
      ret = true
    end
  end

  return ret
end

if not try_opts(N) then try_opts('options') end

local opts = rspamd_config:get_all_opt('dmarc')
if not opts or type(opts) ~= 'table' then
  return
end
no_sampling_domains = rspamd_map_add(N, 'no_sampling_domains', 'map', 'Domains not to apply DMARC sampling to')
no_reporting_domains = rspamd_map_add(N, 'no_reporting_domains', 'map', 'Domains not to apply DMARC reporting to')

if opts['symbols'] then
  for k,_ in pairs(dmarc_symbols) do
    if opts['symbols'][k] then
      dmarc_symbols[k] = opts['symbols'][k]
    end
  end
end

-- XXX: rework this shitty code some day please
if opts['reporting'] == true then
  redis_params = rspamd_parse_redis_server('dmarc')
  if not redis_params then
    rspamd_logger.errx(rspamd_config, 'cannot parse servers parameter')
  elseif not opts['send_reports'] then
    dmarc_reporting = true
    take_report_id = rspamd_redis.add_redis_script(take_report_script, redis_params)
  else
    dmarc_reporting = true
    if type(opts['report_settings']) == 'table' then
      for k, v in pairs(opts['report_settings']) do
        report_settings[k] = v
      end
    end
    for _, e in ipairs({'email', 'domain', 'org_name'}) do
      if not report_settings[e] then
        rspamd_logger.errx(rspamd_config, 'Missing required setting: report_settings.%s', e)
        return
      end
    end
    take_report_id = rspamd_redis.add_redis_script(take_report_script, redis_params)
    rspamd_config:add_on_load(function(cfg, ev_base, worker)
      if not worker:is_primary_controller() then return end
      pool = mempool.create()
      rspamd_config:register_finish_script(function ()
        local stamp = pool:get_variable(VAR_NAME, 'double')
        if not stamp then
          rspamd_logger.warnx(rspamd_config, 'No last DMARC report information to persist to disk')
          return
        end
        local f, err = io.open(statefile, 'w')
        if err then
          rspamd_logger.errx(rspamd_config, 'Unable to write statefile to disk: %s', err)
          return
        end
        assert(f:write(pool:get_variable(VAR_NAME, 'double')))
        assert(f:close())
        pool:destroy()
      end)
      local get_reporting_domain, reporting_domain, report_start, report_end, report_id, want_period, report_key
      local reporting_addr = {}
      local domain_policy = {}
      local to_verify = {}
      local cursor = 0
      local function entry_to_xml(data)
        local buf = {
          table.concat({
            '<record><row><source_ip>', data.ip, '</source_ip><count>',
            data.count, '</count><policy_evaluated><disposition>',
            data.disposition, '</disposition><dkim>', data.dkim_disposition,
            '</dkim><spf>', data.spf_disposition, '</spf>'
          }),
        }
        if data.override ~= '' then
          table.insert(buf, string.format('<reason>%s</reason>', data.override))
        end
        table.insert(buf, table.concat({
          '</policy_evaluated></row><identifiers><header_from>', data.header_from,
          '</header_from></identifiers>',
        }))
        table.insert(buf, '<auth_results>')
        if data.dkim_results[1] then
          for _, d in ipairs(data.dkim_results) do
            table.insert(buf, table.concat({
              '<dkim><domain>', d.domain, '</domain><result>',
              d.result, '</result></dkim>',
            }))
          end
        end
        table.insert(buf, table.concat({
          '<spf><domain>', data.spf_domain, '</domain><result>',
          data.spf_result, '</result></spf></auth_results></record>',
        }))
        return table.concat(buf)
      end
      local function dmarc_report_xml()
        local entries = {}
        report_id = string.format('%s.%d.%d', reporting_domain, report_start, report_end)
        lua_util.debugm(N, rspamd_config, 'new report: %s', report_id)
        local actions = {
          push = function(t)
            local data = t[1]
            local split = rspamd_str_split(data, ',')
            local row = {
              ip = split[1],
              spf_disposition = split[2],
              dkim_disposition = split[3],
              disposition = split[4],
              override = split[5],
              header_from = split[6],
              dkim_results = {},
              spf_domain = split[11],
              spf_result = split[12],
              count = t[2],
            }
            if split[7] and split[7] ~= '' then
              local tmp = rspamd_str_split(split[7], '|')
              for _, d in ipairs(tmp) do
                table.insert(row.dkim_results, {domain = d, result = 'pass'})
              end
            end
            if split[8] and split[8] ~= '' then
              local tmp = rspamd_str_split(split[8], '|')
              for _, d in ipairs(tmp) do
                table.insert(row.dkim_results, {domain = d, result = 'fail'})
              end
            end
            if split[9] and split[9] ~= '' then
              local tmp = rspamd_str_split(split[9], '|')
              for _, d in ipairs(tmp) do
                table.insert(row.dkim_results, {domain = d, result = 'temperror'})
              end
            end
            if split[10] and split[10] ~= '' then
              local tmp = rspamd_str_split(split[10], '|')
              for _, d in ipairs(tmp) do
                table.insert(row.dkim_results, {domain = d, result = 'permerror'})
              end
            end
            table.insert(entries, row)
          end,
          header = function()
              return table.concat({
                '<?xml version="1.0" encoding="utf-8"?><feedback><report_metadata><org_name>',
                escape_xml(report_settings.org_name), '</org_name><email>',
                escape_xml(report_settings.email), '</email><report_id>',
                report_id, '</report_id><date_range><begin>', report_start,
                '</begin><end>', report_end, '</end></date_range></report_metadata><policy_published><domain>',
                reporting_domain, '</domain><adkim>', escape_xml(domain_policy.adkim), '</adkim><aspf>',
                escape_xml(domain_policy.aspf), '</aspf><p>', escape_xml(domain_policy.p),
                '</p><sp>', escape_xml(domain_policy.sp), '</sp><pct>', escape_xml(domain_policy.pct),
                '</pct></policy_published>'
              })
          end,
          footer = function()
            return [[</feedback>]]
          end,
          entries = function()
            local buf = {}
            for _, e in pairs(entries) do
              table.insert(buf, entry_to_xml(e))
            end
            return table.concat(buf, '')
          end,
        }
        return function(action, p)
          local f = actions[action]
          if not f then error('invalid action: ' .. action) end
          return f(p)
        end
      end
      local function send_report_via_email(xmlf, retry)
        if not retry then retry = 0 end
        if retry > report_settings.retries then
          rspamd_logger.errx(rspamd_config, "Couldn't send mail for %s: retries exceeded", reporting_domain)
          return get_reporting_domain()
        end
        local tmp_addr = {}
        for k in pairs(reporting_addr) do
          table.insert(tmp_addr, k)
        end
        local encoded = rspamd_util.encode_base64(rspamd_util.gzip_compress(
              table.concat(
                {xmlf('header'),
                 xmlf('entries'),
                 xmlf('footer')})), 78)
        local function mail_cb(err, data, conn)
          local function no_error(merr, mdata, wantcode)
            wantcode = wantcode or '2'
            if merr then
              rspamd_logger.errx(ev_base, 'got error in tcp callback: %s', merr)
              if conn then
                conn:close()
              end
              send_report_via_email(xmlf, retry+1)
              return false
            end
            if mdata then
              if type(mdata) ~= 'string' then
                mdata = tostring(mdata)
              end
              if string.sub(mdata, 1, 1) ~= wantcode then
                rspamd_logger.errx(ev_base, 'got bad smtp response: %s', mdata)
                if conn then
                  conn:close()
                end
                send_report_via_email(xmlf, retry+1)
                return false
              end
            else
              rspamd_logger.errx(ev_base, 'no data')
              if conn then
                conn:close()
              end
              send_report_via_email(xmlf, retry+1)
              return false
            end
            return true
          end
          local function all_done_cb(merr, mdata)
            if conn then
              conn:close()
            end
            get_reporting_domain()
            return true
          end
          local function quit_done_cb(merr, mdata)
            conn:add_read(all_done_cb, '\r\n')
          end
          local function quit_cb(merr, mdata)
            if no_error(merr, mdata) then
              conn:add_write(quit_done_cb, 'QUIT\r\n')
            end
          end
          local function pre_quit_cb(merr, mdata)
            if no_error(merr, '2') then
              conn:add_read(quit_cb, '\r\n')
            end
          end
          local function data_done_cb(merr, mdata)
            if no_error(merr, mdata, '3') then
              local atmp = {}
              for k in pairs(reporting_addr) do
                table.insert(atmp, k)
              end
              local addr_string = table.concat(atmp, ', ')
              local rhead = string.format(report_template,
		  report_settings.from_name,
                  report_settings.email,
                  addr_string,
                  reporting_domain,
                  report_settings.domain,
                  report_id,
                  rspamd_util.time_to_string(rspamd_util.get_time()),
                  rspamd_util.random_hex(12) .. '@rspamd',
                  report_settings.domain,
                  report_settings.domain,
                  reporting_domain,
                  report_start, report_end)
              conn:add_write(pre_quit_cb, {rhead,
                                           encoded,
                                           report_footer,
                                           '\r\n.\r\n'})
            end
          end
          local function data_cb(merr, mdata)
            if no_error(merr, '2') then
              conn:add_read(data_done_cb, '\r\n')
            end
          end
          local function rcpt_done_cb(merr, mdata)
            if no_error(merr, mdata) then
              conn:add_write(data_cb, 'DATA\r\n')
            end
          end
          local from_done_cb
          local function rcpt_cb(merr, mdata)
            if no_error(merr, '2') then
              if tmp_addr[1] then
                conn:add_read(from_done_cb, '\r\n')
              else
                conn:add_read(rcpt_done_cb, '\r\n')
              end
            end
          end
          from_done_cb = function(merr, mdata)
            if no_error(merr, mdata) then
              conn:add_write(rcpt_cb, {'RCPT TO: <', table.remove(tmp_addr), '>\r\n'})
            end
          end
          local function from_cb(merr, mdata)
            if no_error(merr, '2') then
              conn:add_read(from_done_cb, '\r\n')
            end
          end
            local function hello_done_cb(merr, mdata)
            if no_error(merr, mdata) then
              conn:add_write(from_cb, {'MAIL FROM: <', report_settings.email, '>\r\n'})
            end
          end
          local function hello_cb(merr)
            if no_error(merr, '2') then
              conn:add_read(hello_done_cb, '\r\n')
            end
          end
          if no_error(err, data) then
            conn:add_write(hello_cb, {'HELO ', report_settings.helo, '\r\n'})
          end
        end
        rspamd_tcp.request({
          ev_base = ev_base,
          callback = mail_cb,
          config = rspamd_config,
          stop_pattern = '\r\n',
          host = report_settings.smtp,
          port = report_settings.smtp_port,
          resolver = rspamd_config:get_resolver(),
        })
      end
      local function make_report()
        if type(report_settings.override_address) == 'string' then
          reporting_addr = {[report_settings.override_address] = true}
        end
        if type(report_settings.additional_address) == 'string' then
          reporting_addr[report_settings.additional_address] = true
        end
        rspamd_logger.infox(ev_base, 'sending report for %s <%s>', reporting_domain, table.concat(reporting_addr, ','))
        local dmarc_xml = dmarc_report_xml()
        local dmarc_push_cb
        dmarc_push_cb = function(err, data)
          if err then
            rspamd_logger.errx(ev_base, 'Redis request failed: %s', err)
            -- XXX: data is orphaned; replace key or delete data
            get_reporting_domain()
          elseif type(data) == 'table' then
            cursor = tonumber(data[1])
            for i = 1, #data[2], 2 do
              dmarc_xml('push', {data[2][i], data[2][i+1]})
            end
            if cursor ~= 0 then
              local ret = rspamd_redis.redis_make_request_taskless(ev_base,
                rspamd_config,
                redis_params,
                nil,
                false, -- is write
                dmarc_push_cb, --callback
                'HSCAN', -- command
                {report_key, cursor, 'COUNT', report_settings.hscan_count}
              )
              if not ret then
                rspamd_logger.errx(ev_base, 'Failed to schedule redis request')
                get_reporting_domain()
              end
            else
              send_report_via_email(dmarc_xml)
            end
          end
        end
        local ret = rspamd_redis.redis_make_request_taskless(ev_base,
          rspamd_config,
          redis_params,
          nil,
          false, -- is write
          dmarc_push_cb, --callback
          'HSCAN', -- command
          {report_key, cursor, 'COUNT', report_settings.hscan_count}
        )
        if not ret then
          rspamd_logger.errx(rspamd_config, 'Failed to schedule redis request')
          -- XXX: data is orphaned; replace key or delete data
          get_reporting_domain()
        end
      end
      local function delete_reports()
        local function delete_reports_cb(err)
          if err then
            rspamd_logger.errx(rspamd_config, 'Error deleting reports: %s', err)
          end
          rspamd_logger.infox(rspamd_config, 'Deleted reports for %s', reporting_domain)
          get_reporting_domain()
        end
        local ret = rspamd_redis.redis_make_request_taskless(ev_base,
          rspamd_config,
          redis_params,
          nil,
          true, -- is write
          delete_reports_cb, --callback
          'DEL', -- command
          {report_key}
        )
        if not ret then
          rspamd_logger.errx(rspamd_config, 'Failed to schedule redis request')
          get_reporting_domain()
        end
      end
      local function verify_reporting_address()
        local function verifier(test_addr, vdom)
          local retry = 0
          local function verify_cb(resolver, to_resolve, results, err, _, authenticated)
            if err then
              if err == 'no records with this name' or err == 'requested record is not found' then
                rspamd_logger.infox(rspamd_config, 'Reports to %s for %s not authorised', test_addr, reporting_domain)
                to_verify[test_addr] = nil
              else
                rspamd_logger.errx(rspamd_config, 'Lookup error [%s]: %s', to_resolve, err)
                if retry < report_settings.retries then
                  retry = retry + 1
                  rspamd_config:get_resolver():resolve('txt', {
                    ev_base = ev_base,
                    name = string.format('%s._report._dmarc.%s',
                        reporting_domain, vdom),
                    callback = verify_cb,
                  })
                else
                  delete_reports()
                end
              end
            else
              local is_authed = false
              -- XXX: reporting address could be overridden
              for _, r in ipairs(results) do
                if string.match(r, 'v=DMARC1') then
                  is_authed = true
                  break
                end
              end
              if not is_authed then
                to_verify[test_addr] = nil
                rspamd_logger.infox(rspamd_config, 'Reports to %s for %s not authorised', test_addr, reporting_domain)
              else
                to_verify[test_addr] = nil
                reporting_addr[test_addr] = true
              end
            end
            local t, nvdom = next(to_verify)
            if not t then
              if next(reporting_addr) then
                make_report()
              else
                rspamd_logger.infox(rspamd_config, 'No valid reporting addresses for %s', reporting_domain)
                delete_reports()
              end
            else
              verifier(t, nvdom)
            end
          end
          rspamd_config:get_resolver():resolve('txt', {
            ev_base = ev_base,
            name = string.format('%s._report._dmarc.%s',
                reporting_domain, vdom),
            callback = verify_cb,
          })
        end
        local t, vdom = next(to_verify)
        verifier(t, vdom)
      end
      local function get_reporting_address()
        local retry = 0
        local esld = rspamd_util.get_tld(reporting_domain)
        local function check_addr_cb(resolver, to_resolve, results, err, _, authenticated)
          if err then
            if err == 'no records with this name' or err == 'requested record is not found' then
              if reporting_domain ~= esld then
                rspamd_config:get_resolver():resolve('txt', {
                  ev_base = ev_base,
                  name = string.format('_dmarc.%s', esld),
                  callback = check_addr_cb,
                })
              else
                rspamd_logger.errx(rspamd_config, 'No DMARC record found for %s', reporting_domain)
                delete_reports()
              end
            else
              rspamd_logger.errx(rspamd_config, 'Lookup error [%s]: %s', to_resolve, err)
              if retry < report_settings.retries then
                retry = retry + 1
                rspamd_config:get_resolver():resolve('txt', {
                  ev_base = ev_base,
                  name = to_resolve,
                  callback = check_addr_cb,
                })
              else
                rspamd_logger.errx(rspamd_config, "Couldn't get reporting address for %s: retries exceeded", reporting_domain)
                delete_reports()
              end
            end
          else
            local policy
            local found_policy, failed_policy = false, false
            for _, r in ipairs(results) do
              local elts = dmarc_grammar:match(r)
              if elts and found_policy then
                failed_policy = true
              elseif elts then
                found_policy = true
                policy = elts
              end
            end
            if not found_policy then
              rspamd_logger.errx(rspamd_config, 'No policy: %s', to_resolve)
              if reporting_domain ~= esld then
                rspamd_config:get_resolver():resolve('txt', {
                  ev_base = ev_base,
                  name = string.format('_dmarc.%s', esld),
                  callback = check_addr_cb,
                })
              else
                delete_reports()
              end
            elseif failed_policy then
              rspamd_logger.errx(rspamd_config, 'Duplicate policies: %s', to_resolve)
              delete_reports()
            elseif not policy['rua'] then
              rspamd_logger.errx(rspamd_config, 'No reporting address: %s', to_resolve)
              delete_reports()
            else
              local upool = mempool.create()
              local split = rspamd_str_split(policy['rua'], ',')
              for _, m in ipairs(split) do
                local url = rspamd_url.create(upool, m)
                if not url then
                  rspamd_logger.errx(rspamd_config, 'Couldnt extract reporting address: %s', policy['rua'])
                else
                  local urlt = url:to_table()
                  if urlt['protocol'] ~= 'mailto' then
                    rspamd_logger.errx(rspamd_config, 'Invalid URL: %s', url)
                  else
                    if urlt['tld'] == rspamd_util.get_tld(reporting_domain) then
                      reporting_addr[string.format('%s@%s', urlt['user'], urlt['host'])] = true
                    else
                      to_verify[string.format('%s@%s', urlt['user'], urlt['host'])] = urlt['host']
                    end
                  end
                end
              end
              upool:destroy()
              domain_policy['pct'] = policy['pct'] or 100
              domain_policy['adkim'] = policy['adkim'] or 'r'
              domain_policy['aspf'] = policy['aspf'] or 'r'
              domain_policy['p'] = policy['p'] or 'none'
              domain_policy['sp'] = policy['sp'] or 'none'
              if next(to_verify) then
                verify_reporting_address()
              elseif next(reporting_addr) then
                make_report()
              else
                rspamd_logger.errx(rspamd_config, 'No reporting address for %s', reporting_domain)
                delete_reports()
              end
            end
          end
        end

        rspamd_config:get_resolver():resolve('txt', {
          ev_base = ev_base,
          name = string.format('_dmarc.%s', reporting_domain),
          callback = check_addr_cb,
        })
      end
      get_reporting_domain = function()
        reporting_domain = nil
        reporting_addr = {}
        domain_policy = {}
        cursor = 0
        local function get_reporting_domain_cb(err, data)
          if err then
            rspamd_logger.errx(cfg, 'Unable to get DMARC domain: %s', err)
          else
            if type(data) == 'userdata' then
              reporting_domain = nil
            else
              report_key = data
              local tmp = rspamd_str_split(data, redis_keys.join_char)
              reporting_domain = tmp[2]
            end
            if not reporting_domain then
              rspamd_logger.infox(cfg, 'No more domains to generate reports for')
            else
              get_reporting_address()
            end
          end
        end
        local idx_key = table.concat({redis_keys.index_prefix, want_period}, redis_keys.join_char)
        local ret = rspamd_redis.redis_make_request_taskless(ev_base,
          rspamd_config,
          redis_params,
          nil,
          true, -- is write
          get_reporting_domain_cb, --callback
          'SPOP', -- command
          {idx_key}
        )
        if not ret then
          rspamd_logger.errx(cfg, 'Unable to get DMARC domain')
        end
      end
      local function send_reports(time)
        rspamd_logger.infox(ev_base, 'sending reports ostensibly %1', time)
        pool:set_variable(VAR_NAME, time)
        local yesterday = os.date('!*t', rspamd_util.get_time() - INTERVAL)
        local today = os.date('!*t', rspamd_util.get_time())
        report_start = os.time({year = yesterday.year, month = yesterday.month, day = yesterday.day, hour = 0}) + tz_offset
        report_end = os.time({year = today.year, month = today.month, day = today.day, hour = 0}) + tz_offset
        want_period = table.concat({
          yesterday.year,
          string.format('%02d', yesterday.month),
          string.format('%02d', yesterday.day)
        })
        get_reporting_domain()
      end
      -- Push reports at regular intervals
      local function schedule_regular_send()
        rspamd_config:add_periodic(ev_base, INTERVAL, function ()
          send_reports()
          return true
        end)
      end
      -- Push reports to backend and reschedule check
      local function schedule_intermediate_send(when)
        rspamd_config:add_periodic(ev_base, when, function ()
          schedule_regular_send()
          send_reports(rspamd_util.get_time())
          return false
        end)
      end
      -- Try read statefile on startup
      local stamp
      local f, err = io.open(statefile, 'r')
      if err then
        rspamd_logger.errx('Failed to open statefile: %s', err)
      end
      if f then
        io.input(f)
        stamp = tonumber(io.read())
        pool:set_variable(VAR_NAME, stamp)
      end
      local time = rspamd_util.get_time()
      if not stamp then
        lua_util.debugm(N, rspamd_config, 'No state found - sending reports immediately')
        schedule_regular_send()
        send_reports(time)
        return
      end
      local delta = stamp - time + INTERVAL
      if delta <= 0 then
        lua_util.debugm(N, rspamd_config, 'Last send is too old - sending reports immediately')
        schedule_regular_send()
        send_reports(time)
        return
      end
      lua_util.debugm(N, rspamd_config, 'Scheduling next send in %s seconds', delta)
      schedule_intermediate_send(delta)
    end)
  end
end
if type(opts['actions']) == 'table' then
  dmarc_actions = opts['actions']
end
if type(opts['report_settings']) == 'table' then
  for k, v in pairs(opts['report_settings']) do
    report_settings[k] = v
  end
end
if opts['send_reports'] then
  for _, e in ipairs({'email', 'domain', 'org_name'}) do
    if not report_settings[e] then
      rspamd_logger.errx(rspamd_config, 'Missing required setting: report_settings.%s', e)
      return
    end
  end
end

-- Check spf and dkim sections for changed symbols
local function check_mopt(var, m_opts, name)
  if m_opts[name] then
    symbols[var] = tostring(m_opts[name])
  end
end

local spf_opts = rspamd_config:get_all_opt('spf')
if spf_opts then
  check_mopt('spf_deny_symbol', spf_opts, 'symbol_fail')
  check_mopt('spf_allow_symbol', spf_opts, 'symbol_allow')
  check_mopt('spf_softfail_symbol', spf_opts, 'symbol_softfail')
  check_mopt('spf_neutral_symbol', spf_opts, 'symbol_neutral')
  check_mopt('spf_tempfail_symbol', spf_opts, 'symbol_dnsfail')
  check_mopt('spf_na_symbol', spf_opts, 'symbol_na')
end

local dkim_opts = rspamd_config:get_all_opt('dkim')
if dkim_opts then
  check_mopt('dkim_deny_symbol', dkim_opts, 'symbol_reject')
  check_mopt('dkim_allow_symbol', dkim_opts, 'symbol_allow')
  check_mopt('dkim_tempfail_symbol', dkim_opts, 'symbol_tempfail')
  check_mopt('dkim_na_symbol', dkim_opts, 'symbol_na')
end

local id = rspamd_config:register_symbol({
  name = 'DMARC_CALLBACK',
  type = 'callback',
  group = 'policies',
  groups = {'dmarc'},
  callback = dmarc_callback
})
rspamd_config:register_symbol({
  name = dmarc_symbols['allow'],
  flags = 'nice',
  parent = id,
  group = 'policies',
  groups = {'dmarc'},
  type = 'virtual'
})
rspamd_config:register_symbol({
  name = dmarc_symbols['reject'],
  parent = id,
  group = 'policies',
  groups = {'dmarc'},
  type = 'virtual'
})
rspamd_config:register_symbol({
  name = dmarc_symbols['quarantine'],
  parent = id,
  group = 'policies',
  groups = {'dmarc'},
  type = 'virtual'
})
rspamd_config:register_symbol({
  name = dmarc_symbols['softfail'],
  parent = id,
  group = 'policies',
  groups = {'dmarc'},
  type = 'virtual'
})
rspamd_config:register_symbol({
  name = dmarc_symbols['dnsfail'],
  parent = id,
  group = 'policies',
  groups = {'dmarc'},
  type = 'virtual'
})
rspamd_config:register_symbol({
  name = dmarc_symbols['na'],
  parent = id,
  group = 'policies',
  groups = {'dmarc'},
  type = 'virtual'
})

rspamd_config:register_dependency('DMARC_CALLBACK', symbols['spf_allow_symbol'])
rspamd_config:register_dependency('DMARC_CALLBACK', symbols['dkim_allow_symbol'])