File: syncres.cc

package info (click to toggle)
pdns-recursor 4.8.8-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 9,620 kB
  • sloc: cpp: 95,714; javascript: 20,651; sh: 4,679; makefile: 652; xml: 37
file content (5990 lines) | stat: -rw-r--r-- 226,346 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "arguments.hh"
#include "aggressive_nsec.hh"
#include "cachecleaner.hh"
#include "dns_random.hh"
#include "dnsparser.hh"
#include "dnsrecords.hh"
#include "ednssubnet.hh"
#include "logger.hh"
#include "lua-recursor4.hh"
#include "rec-lua-conf.hh"
#include "syncres.hh"
#include "dnsseckeeper.hh"
#include "validate-recursor.hh"
#include "rec-taskqueue.hh"

template<class T>
class fails_t : public boost::noncopyable
{
public:
  typedef uint64_t counter_t;
  struct value_t {
    value_t(const T &a) : key(a) {}
    T key;
    mutable counter_t value{0};
    time_t last{0};
  };

  typedef multi_index_container<value_t,
                                indexed_by<
                                  ordered_unique<tag<T>, member<value_t, T, &value_t::key>>,
                                  ordered_non_unique<tag<time_t>, member<value_t, time_t, &value_t::last>>
                                  >> cont_t;

  cont_t getMapCopy() const {
    return d_cont;
  }

  counter_t value(const T& t) const
  {
    auto i = d_cont.find(t);

    if (i == d_cont.end()) {
      return 0;
    }
    return i->value;
  }

  counter_t incr(const T& key, const struct timeval& now)
  {
    auto i = d_cont.insert(key).first;

    if (i->value < std::numeric_limits<counter_t>::max()) {
      i->value++;
    }
    auto &ind = d_cont.template get<T>();
    time_t tm = now.tv_sec;
    ind.modify(i, [tm](value_t &val) { val.last = tm; });
    return i->value;
  }

  void clear(const T& a)
  {
    d_cont.erase(a);
  }

  void clear()
  {
    d_cont.clear();
  }

  size_t size() const
  {
    return d_cont.size();
  }

  void prune(time_t cutoff) {
    auto &ind = d_cont.template get<time_t>();
    ind.erase(ind.begin(), ind.upper_bound(cutoff));
  }

private:
  cont_t d_cont;
};

/** Class that implements a decaying EWMA.
    This class keeps an exponentially weighted moving average which, additionally, decays over time.
    The decaying is only done on get.
*/

//! This represents a number of decaying Ewmas, used to store performance per nameserver-name.
/** Modelled to work mostly like the underlying DecayingEwma */
class DecayingEwmaCollection
{
private:
  struct DecayingEwma
  {
  public:
    void submit(int arg, const struct timeval& last, const struct timeval& now)
    {
      d_last = arg;
      auto val = static_cast<float>(arg);
      if (d_val == 0) {
        d_val = val;
      }
      else {
        auto diff = makeFloat(last - now);
        auto factor = expf(diff) / 2.0f; // might be '0.5', or 0.0001
        d_val = (1.0f - factor) * val + factor * d_val;
      }
    }

    float get(float factor)
    {
      return d_val *= factor;
    }

    float peek(void) const
    {
      return d_val;
    }

    int last(void) const
    {
      return d_last;
    }

    float d_val{0};
    int d_last{0};
  };

public:
  DecayingEwmaCollection(const DNSName& name, const struct timeval ts = {0, 0})
    : d_name(name), d_lastget(ts)
  {
  }

  void submit(const ComboAddress& remote, int usecs, const struct timeval& now) const
  {
    d_collection[remote].submit(usecs, d_lastget, now);
  }

  float getFactor(const struct timeval &now) const
  {
    float diff = makeFloat(d_lastget - now);
    return expf(diff / 60.0f); // is 1.0 or less
  }

  bool stale(time_t limit) const
  {
    return limit > d_lastget.tv_sec;
  }

  void purge(const std::map<ComboAddress, float>& keep) const
  {
    for (auto iter = d_collection.begin(); iter != d_collection.end(); ) {
      if (keep.find(iter->first) != keep.end()) {
        ++iter;
      }
      else {
        iter = d_collection.erase(iter);
      }
    }
  }

  // d_collection is the modifyable part of the record, we index on DNSName and timeval, and DNSName never changes
  mutable std::map<ComboAddress, DecayingEwma> d_collection;
  const DNSName d_name;
  struct timeval d_lastget;
};

class nsspeeds_t :
  public multi_index_container<DecayingEwmaCollection,
                               indexed_by<
                                 hashed_unique<tag<DNSName>, member<DecayingEwmaCollection, const DNSName, &DecayingEwmaCollection::d_name>>,
                                 ordered_non_unique<tag<timeval>, member<DecayingEwmaCollection, timeval, &DecayingEwmaCollection::d_lastget>>
                                 >>
{
public:
  const auto& find_or_enter(const DNSName& name, const struct timeval& now)
  {
    const auto it = insert(DecayingEwmaCollection{name, now}).first;
    return *it;
  }

  const auto& find_or_enter(const DNSName& name)
  {
    const auto it = insert(DecayingEwmaCollection{name}).first;
    return *it;
  }

  float fastest(const DNSName& name, const struct timeval& now)
  {
    auto& ind = get<DNSName>();
    auto it = insert(DecayingEwmaCollection{name, now}).first;
    if (it->d_collection.empty()) {
      return 0;
    }
    // This could happen if find(DNSName) entered an entry; it's used only by test code
    if (it->d_lastget.tv_sec == 0 && it->d_lastget.tv_usec == 0) {
      ind.modify(it, [&](DecayingEwmaCollection& d) { d.d_lastget = now; });
    }

    float ret = std::numeric_limits<float>::max();
    const float factor = it->getFactor(now);
    for (auto& entry : it->d_collection) {
      if (float tmp = entry.second.get(factor); tmp < ret) {
        ret = tmp;
      }
    }
    ind.modify(it, [&](DecayingEwmaCollection& d) { d.d_lastget = now; });
    return ret;
  }
};

static LockGuarded <nsspeeds_t> s_nsSpeeds;

template<class Thing> class Throttle : public boost::noncopyable
{
public:

  struct entry_t
  {
    entry_t(const Thing& thing_, time_t ttd_, unsigned int count_) : thing(thing_), ttd(ttd_), count(count_)
    {
    }
    Thing thing;
    time_t ttd;
    mutable unsigned int count;
  };
  typedef multi_index_container<entry_t,
                                indexed_by<
                                  ordered_unique<tag<Thing>, member<entry_t, Thing, &entry_t::thing>>,
                                  ordered_non_unique<tag<time_t>, member<entry_t, time_t, &entry_t::ttd>>
                                  >> cont_t;

  bool shouldThrottle(time_t now, const Thing &t)
  {
    auto i = d_cont.find(t);
    if (i == d_cont.end()) {
      return false;
    }
    if (now > i->ttd || i->count == 0) {
      d_cont.erase(i);
      return false;
    }
    i->count--;

    return true; // still listed, still blocked
  }

  void throttle(time_t now, const Thing &t, time_t ttl, unsigned int count)
  {
    auto i = d_cont.find(t);
    time_t ttd = now + ttl;
    if (i == d_cont.end()) {
      d_cont.emplace(t, ttd, count);
    } else if (ttd > i->ttd || count > i->count) {
      ttd = std::max(i->ttd, ttd);
      count = std::max(i->count, count);
      auto &ind = d_cont.template get<Thing>();
      ind.modify(i, [ttd,count](entry_t &e) { e.ttd = ttd; e.count = count; });
    }
  }

  size_t size() const
  {
    return d_cont.size();
  }

  cont_t getThrottleMap() const
  {
    return d_cont;
  }

  void clear()
  {
    d_cont.clear();
  }

  void prune(time_t now) {
    auto &ind = d_cont.template get<time_t>();
    ind.erase(ind.begin(), ind.upper_bound(now));
  }

private:
  cont_t d_cont;
};

static LockGuarded<Throttle<std::tuple<ComboAddress,DNSName,QType>>> s_throttle;

struct SavedParentEntry
{
  SavedParentEntry(const DNSName& name, map<DNSName, vector<ComboAddress>>&& nsAddresses, time_t ttd)
    : d_domain(name), d_nsAddresses(nsAddresses), d_ttd(ttd)
  {
  }
  DNSName d_domain;
  map<DNSName, vector<ComboAddress>> d_nsAddresses;
  time_t d_ttd;
  mutable uint64_t d_count{0};
};

typedef multi_index_container<
  SavedParentEntry,
  indexed_by<ordered_unique<tag<DNSName>, member<SavedParentEntry, DNSName, &SavedParentEntry::d_domain>>,
             ordered_non_unique<tag<time_t>, member<SavedParentEntry, time_t, &SavedParentEntry::d_ttd>>
             >> SavedParentNSSetBase;

class SavedParentNSSet : public SavedParentNSSetBase
{
public:
  void prune(time_t now)
  {
    auto &ind = get<time_t>();
    ind.erase(ind.begin(), ind.upper_bound(now));
  }
  void inc(const DNSName& name)
  {
    auto it = find(name);
    if (it != end()) {
      ++(*it).d_count;
    }
  }
  SavedParentNSSet getMapCopy() const
  {
    return *this;
  }
};

static LockGuarded <SavedParentNSSet> s_savedParentNSSet;

thread_local SyncRes::ThreadLocalStorage SyncRes::t_sstorage;
thread_local std::unique_ptr<addrringbuf_t> t_timeouts;

std::unique_ptr<NetmaskGroup> SyncRes::s_dontQuery{nullptr};
NetmaskGroup SyncRes::s_ednslocalsubnets;
NetmaskGroup SyncRes::s_ednsremotesubnets;
SuffixMatchNode SyncRes::s_ednsdomains;
EDNSSubnetOpts SyncRes::s_ecsScopeZero;
string SyncRes::s_serverID;
SyncRes::LogMode SyncRes::s_lm;
const std::unordered_set<QType> SyncRes::s_redirectionQTypes = {QType::CNAME, QType::DNAME};
static LockGuarded<fails_t<ComboAddress>> s_fails;
static LockGuarded<fails_t<DNSName>> s_nonresolving;

struct DoTStatus
{
  DoTStatus(const ComboAddress& ip, const DNSName& auth, time_t ttd) :
    d_address(ip), d_auth(auth), d_ttd(ttd)
  {
  }
  enum Status : uint8_t { Unknown, Busy, Bad, Good };
  const ComboAddress d_address;
  const DNSName d_auth;
  time_t d_ttd;
  mutable uint64_t d_count{0};
  mutable Status d_status{Unknown};
  std::string toString() const
  {
    const std::array<std::string, 4> n{ "Unknown", "Busy", "Bad", "Good" };
    unsigned int v = static_cast<unsigned int>(d_status);
    return v >= n.size() ? "?" : n[v];
  }
};

struct DoTMap
{
  multi_index_container<DoTStatus,
                        indexed_by<
                          ordered_unique<tag<ComboAddress>, member<DoTStatus, const ComboAddress, &DoTStatus::d_address>>,
                          ordered_non_unique<tag<time_t>, member<DoTStatus, time_t, &DoTStatus::d_ttd>>
                          >> d_map;
  uint64_t d_numBusy{0};

  void prune(time_t cutoff) {
    auto &ind = d_map.template get<time_t>();
    ind.erase(ind.begin(), ind.upper_bound(cutoff));
  }
};


static LockGuarded<DoTMap> s_dotMap;

static const time_t dotFailWait = 24 * 3600;
static const time_t dotSuccessWait = 3 * 24 * 3600;
static bool shouldDoDoT(ComboAddress address, time_t now);

unsigned int SyncRes::s_maxnegttl;
unsigned int SyncRes::s_maxbogusttl;
unsigned int SyncRes::s_maxcachettl;
unsigned int SyncRes::s_maxqperq;
unsigned int SyncRes::s_maxnsperresolve;
unsigned int SyncRes::s_maxnsaddressqperq;
unsigned int SyncRes::s_maxtotusec;
unsigned int SyncRes::s_maxdepth;
unsigned int SyncRes::s_minimumTTL;
unsigned int SyncRes::s_minimumECSTTL;
unsigned int SyncRes::s_packetcachettl;
unsigned int SyncRes::s_packetcacheservfailttl;
unsigned int SyncRes::s_serverdownmaxfails;
unsigned int SyncRes::s_serverdownthrottletime;
unsigned int SyncRes::s_nonresolvingnsmaxfails;
unsigned int SyncRes::s_nonresolvingnsthrottletime;
unsigned int SyncRes::s_ecscachelimitttl;
unsigned int SyncRes::s_maxvalidationsperq;
unsigned int SyncRes::s_maxnsec3iterationsperq;
pdns::stat_t SyncRes::s_authzonequeries;
pdns::stat_t SyncRes::s_queries;
pdns::stat_t SyncRes::s_outgoingtimeouts;
pdns::stat_t SyncRes::s_outgoing4timeouts;
pdns::stat_t SyncRes::s_outgoing6timeouts;
pdns::stat_t SyncRes::s_outqueries;
pdns::stat_t SyncRes::s_tcpoutqueries;
pdns::stat_t SyncRes::s_dotoutqueries;
pdns::stat_t SyncRes::s_throttledqueries;
pdns::stat_t SyncRes::s_dontqueries;
pdns::stat_t SyncRes::s_qnameminfallbacksuccess;
pdns::stat_t SyncRes::s_unreachables;
pdns::stat_t SyncRes::s_ecsqueries;
pdns::stat_t SyncRes::s_ecsresponses;
std::map<uint8_t, pdns::stat_t> SyncRes::s_ecsResponsesBySubnetSize4;
std::map<uint8_t, pdns::stat_t> SyncRes::s_ecsResponsesBySubnetSize6;

uint8_t SyncRes::s_ecsipv4limit;
uint8_t SyncRes::s_ecsipv6limit;
uint8_t SyncRes::s_ecsipv4cachelimit;
uint8_t SyncRes::s_ecsipv6cachelimit;
bool SyncRes::s_ecsipv4nevercache;
bool SyncRes::s_ecsipv6nevercache;

bool SyncRes::s_doIPv4;
bool SyncRes::s_doIPv6;
bool SyncRes::s_rootNXTrust;
bool SyncRes::s_noEDNS;
bool SyncRes::s_qnameminimization;
SyncRes::HardenNXD SyncRes::s_hardenNXD;
unsigned int SyncRes::s_refresh_ttlperc;
unsigned int SyncRes::s_locked_ttlperc;
int SyncRes::s_tcp_fast_open;
bool SyncRes::s_tcp_fast_open_connect;
bool SyncRes::s_dot_to_port_853;
int SyncRes::s_event_trace_enabled;
bool SyncRes::s_save_parent_ns_set;
unsigned int SyncRes::s_max_busy_dot_probes;

#define LOG(x) if(d_lm == Log) { g_log <<Logger::Warning << x; } else if(d_lm == Store) { d_trace << x; }

// A helper function to print a double with specific printf format.
// Not using boost::format since it is not thread safe while calling
// into locale handling code according to tsan.
// This allocates a string, but that's nothing compared to what
// boost::format is doing and may even be optimized away anyway.
static inline std::string fmtfloat(const char* fmt, double f)
{
  char buf[20];
  int ret = snprintf(buf, sizeof(buf), fmt, f);
  if (ret < 0 || ret >= static_cast<int>(sizeof(buf))) {
    return "?";
  }
  return std::string(buf, ret);
}

static inline void accountAuthLatency(uint64_t usec, int family)
{
  if (family == AF_INET) {
    g_stats.auth4Answers(usec);
    g_stats.cumulativeAuth4Answers(usec);
  } else  {
    g_stats.auth6Answers(usec);
    g_stats.cumulativeAuth6Answers(usec);
  }
}


SyncRes::SyncRes(const struct timeval& now) :  d_authzonequeries(0), d_outqueries(0), d_tcpoutqueries(0), d_dotoutqueries(0), d_throttledqueries(0), d_timeouts(0), d_unreachables(0),
					       d_totUsec(0), d_now(now),
					       d_cacheonly(false), d_doDNSSEC(false), d_doEDNS0(false), d_qNameMinimization(s_qnameminimization), d_lm(s_lm)
{
  d_validationContext.d_nsec3IterationsRemainingQuota = s_maxnsec3iterationsperq > 0 ? s_maxnsec3iterationsperq : std::numeric_limits<decltype(d_validationContext.d_nsec3IterationsRemainingQuota)>::max();
}

static void allowAdditionalEntry(std::unordered_set<DNSName>& allowedAdditionals, const DNSRecord& rec);

void SyncRes::resolveAdditionals(const DNSName& qname, QType qtype, AdditionalMode mode, std::vector<DNSRecord>& additionals, unsigned int depth, bool& additionalsNotInCache)
{
  vector<DNSRecord> addRecords;

  vState state = vState::Indeterminate;
  switch (mode) {
  case AdditionalMode::ResolveImmediately: {
    set<GetBestNSAnswer> beenthere;
    int res = doResolve(qname, qtype, addRecords, depth, beenthere, state);
    if (res != 0) {
      return;
    }
    // We're conservative here. We do not add Bogus records in any circumstance, we add Indeterminates only if no
    // validation is required.
    if (vStateIsBogus(state)) {
      return;
    }
    if (shouldValidate() && state != vState::Secure && state != vState::Insecure) {
      return;
    }
    for (auto& rec : addRecords) {
      if (rec.d_place == DNSResourceRecord::ANSWER) {
        additionals.push_back(std::move(rec));
      }
    }
    break;
  }
  case AdditionalMode::CacheOnly:
  case AdditionalMode::CacheOnlyRequireAuth: {
    // Peek into cache
    MemRecursorCache::Flags flags = mode == AdditionalMode::CacheOnlyRequireAuth ? MemRecursorCache::RequireAuth : MemRecursorCache::None;
    if (g_recCache->get(d_now.tv_sec, qname, qtype, flags, &addRecords, d_cacheRemote, d_routingTag, nullptr, nullptr, nullptr, &state) <= 0) {
      return;
    }
    // See the comment for the ResolveImmediately case
    if (vStateIsBogus(state)) {
      return;
    }
    if (shouldValidate() && state != vState::Secure && state != vState::Insecure) {
      return;
    }
    for (auto& rec : addRecords) {
      if (rec.d_place == DNSResourceRecord::ANSWER) {
        rec.d_ttl -= d_now.tv_sec ;
        additionals.push_back(std::move(rec));
      }
    }
    break;
  }
  case AdditionalMode::ResolveDeferred: {
    const bool oldCacheOnly = setCacheOnly(true);
    set<GetBestNSAnswer> beenthere;
    int res = doResolve(qname, qtype, addRecords, depth, beenthere, state);
    setCacheOnly(oldCacheOnly);
    if (res == 0 && addRecords.size() > 0) {
      // We're conservative here. We do not add Bogus records in any circumstance, we add Indeterminates only if no
      // validation is required.
      if (vStateIsBogus(state)) {
        return;
      }
      if (shouldValidate() && state != vState::Secure && state != vState::Insecure) {
        return;
      }
      bool found = false;
      for (auto& rec : addRecords) {
        if (rec.d_place == DNSResourceRecord::ANSWER) {
          found = true;
          additionals.push_back(std::move(rec));
        }
      }
      if (found) {
        return;
      }
    }
    // Not found in cache, check negcache and push task if also not in negcache
    NegCache::NegCacheEntry ne;
    bool inNegCache = g_negCache->get(qname, qtype, d_now, ne, false);
    if (!inNegCache) {
      // There are a few cases where an answer is neither stored in the record cache nor in the neg cache.
      // An example is a SOA-less NODATA response. Rate limiting will kick in if those tasks are pushed too often.
      // We might want to fix these cases (and always either store positive or negative) some day.
      pushResolveTask(qname, qtype, d_now.tv_sec, d_now.tv_sec + 60);
      additionalsNotInCache = true;
    }
    break;
  }
  case AdditionalMode::Ignore:
    break;
  }
}

// The main (recursive) function to add additionals
// qtype: the original query type to expand
// start: records to start from
// This function uses to state sets to avoid infinite recursion and allow depulication
// depth is the main recursion depth
// additionaldepth is the depth for addAdditionals itself
void SyncRes::addAdditionals(QType qtype, const vector<DNSRecord>&start, vector<DNSRecord>&additionals, std::set<std::pair<DNSName, QType>>& uniqueCalls, std::set<std::tuple<DNSName, QType, QType>>& uniqueResults, unsigned int depth, unsigned additionaldepth, bool& additionalsNotInCache)
{
  if (additionaldepth >= 5 || start.empty()) {
    return;
  }

  auto luaLocal = g_luaconfs.getLocal();
  const auto it = luaLocal->allowAdditionalQTypes.find(qtype);
  if (it == luaLocal->allowAdditionalQTypes.end()) {
    return;
  }
  std::unordered_set<DNSName> addnames;
  for (const auto& rec : start) {
    if (rec.d_place == DNSResourceRecord::ANSWER) {
      // currently, this function only knows about names, we could also take the target types that are dependent on
      // record contents into account
      // e.g. for NAPTR records, go only for SRV for flag value "s", or A/AAAA for flag value "a"
      allowAdditionalEntry(addnames, rec);
    }
  }

  // We maintain two sets for deduplication:
  // - uniqueCalls makes sure we never resolve a qname/qtype twice
  // - uniqueResults makes sure we never add the same qname/qytype RRSet to the result twice,
  //   but note that that set might contain multiple elements.

  auto mode = it->second.second;
  for (const auto& targettype : it->second.first) {
    for (const auto& addname : addnames) {
      std::vector<DNSRecord> records;
      bool inserted = uniqueCalls.emplace(addname, targettype).second;
      if (inserted) {
        resolveAdditionals(addname, targettype, mode, records, depth, additionalsNotInCache);
      }
      if (!records.empty()) {
        for (auto r = records.begin(); r != records.end(); ) {
          QType covered = QType::ENT;
          if (r->d_type == QType::RRSIG) {
            if (auto rsig = getRR<RRSIGRecordContent>(*r); rsig != nullptr) {
              covered = rsig->d_type;
            }
          }
          if (uniqueResults.count(std::tuple(r->d_name, QType(r->d_type), covered)) > 0) {
            // A bit expensive for vectors, but they are small
            r = records.erase(r);
          } else {
            ++r;
          }
        }
        for (const auto& r : records) {
          additionals.push_back(r);
          QType covered = QType::ENT;
          if (r.d_type == QType::RRSIG) {
            if (auto rsig = getRR<RRSIGRecordContent>(r); rsig != nullptr) {
              covered = rsig->d_type;
            }
          }
          uniqueResults.emplace(r.d_name, r.d_type, covered);
        }
        addAdditionals(targettype, records, additionals, uniqueCalls, uniqueResults, depth, additionaldepth + 1, additionalsNotInCache);
      }
    }
  }
}

// The entry point for other code
bool SyncRes::addAdditionals(QType qtype, vector<DNSRecord>&ret, unsigned int depth)
{
  // The additional records of interest
  std::vector<DNSRecord> additionals;

  // We only call resolve for a specific name/type combo once
  std::set<std::pair<DNSName, QType>> uniqueCalls;

  // Collect multiple name/qtype from a single resolve but do not add a new set from new resolve calls
  // For RRSIGs, the type covered is stored in the second Qtype
  std::set<std::tuple<DNSName, QType, QType>> uniqueResults;

  bool additionalsNotInCache = false;
  addAdditionals(qtype, ret, additionals, uniqueCalls, uniqueResults, depth, 0, additionalsNotInCache);

  for (auto& rec : additionals) {
    rec.d_place = DNSResourceRecord::ADDITIONAL;
    ret.push_back(std::move(rec));
  }
  return additionalsNotInCache;
}

/** everything begins here - this is the entry point just after receiving a packet */
int SyncRes::beginResolve(const DNSName &qname, const QType qtype, QClass qclass, vector<DNSRecord>&ret, unsigned int depth)
{
  d_eventTrace.add(RecEventTrace::SyncRes);
  vState state = vState::Indeterminate;
  s_queries++;
  d_wasVariable=false;
  d_wasOutOfBand=false;
  d_cutStates.clear();

  if (doSpecialNamesResolve(qname, qtype, qclass, ret)) {
    d_queryValidationState = vState::Insecure; // this could fool our stats into thinking a validation took place
    return 0;                          // so do check before updating counters (we do now)
  }

  if (isUnsupported(qtype)) {
    return -1;
  }

  if(qclass==QClass::ANY)
    qclass=QClass::IN;
  else if(qclass!=QClass::IN)
    return -1;

  if (qtype == QType::DS) {
    d_externalDSQuery = qname;
  }
  else {
    d_externalDSQuery.clear();
  }

  set<GetBestNSAnswer> beenthere;
  int res=doResolve(qname, qtype, ret, depth, beenthere, state);
  d_queryValidationState = state;

  if (shouldValidate()) {
    if (d_queryValidationState != vState::Indeterminate) {
      g_stats.dnssecValidations++;
    }
    auto xdnssec = g_xdnssec.getLocal();
    if (xdnssec->check(qname)) {
      increaseXDNSSECStateCounter(d_queryValidationState);
    } else {
      increaseDNSSECStateCounter(d_queryValidationState);
    }
  }

  // Avoid calling addAdditionals() if we know we won't find anything
  auto luaLocal = g_luaconfs.getLocal();
  if (res == 0 && qclass == QClass::IN && luaLocal->allowAdditionalQTypes.find(qtype) != luaLocal->allowAdditionalQTypes.end()) {
    bool additionalsNotInCache = addAdditionals(qtype, ret, depth);
    if (additionalsNotInCache) {
      d_wasVariable = true;
    }
  }
  d_eventTrace.add(RecEventTrace::SyncRes, res, false);
  return res;
}

/*! Handles all special, built-in names
 * Fills ret with an answer and returns true if it handled the query.
 *
 * Handles the following queries (and their ANY variants):
 *
 * - localhost. IN A
 * - localhost. IN AAAA
 * - 1.0.0.127.in-addr.arpa. IN PTR
 * - 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa. IN PTR
 * - version.bind. CH TXT
 * - version.pdns. CH TXT
 * - id.server. CH TXT
 * - trustanchor.server CH TXT
 * - negativetrustanchor.server CH TXT
 */
bool SyncRes::doSpecialNamesResolve(const DNSName &qname, const QType qtype, const QClass qclass, vector<DNSRecord> &ret)
{
  static const DNSName arpa("1.0.0.127.in-addr.arpa."), ip6_arpa("1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa."),
    localhost("localhost."), versionbind("version.bind."), idserver("id.server."), versionpdns("version.pdns."), trustanchorserver("trustanchor.server."),
    negativetrustanchorserver("negativetrustanchor.server.");

  bool handled = false;
  vector<pair<QType::typeenum, string> > answers;

  if ((qname == arpa || qname == ip6_arpa) &&
      qclass == QClass::IN) {
    handled = true;
    if (qtype == QType::PTR || qtype == QType::ANY)
      answers.emplace_back(QType::PTR, "localhost.");
  }

  if (qname.isPartOf(localhost) &&
      qclass == QClass::IN) {
    handled = true;
    if (qtype == QType::A || qtype == QType::ANY)
      answers.emplace_back(QType::A, "127.0.0.1");
    if (qtype == QType::AAAA || qtype == QType::ANY)
      answers.emplace_back(QType::AAAA, "::1");
  }

  if ((qname == versionbind || qname == idserver || qname == versionpdns) &&
      qclass == QClass::CHAOS) {
    handled = true;
    if (qtype == QType::TXT || qtype == QType::ANY) {
      if(qname == versionbind || qname == versionpdns)
        answers.emplace_back(QType::TXT, "\"" + ::arg()["version-string"] + "\"");
      else if (s_serverID != "disabled")
        answers.emplace_back(QType::TXT, "\"" + s_serverID + "\"");
    }
  }

  if (qname == trustanchorserver && qclass == QClass::CHAOS &&
      ::arg().mustDo("allow-trust-anchor-query")) {
    handled = true;
    if (qtype == QType::TXT || qtype == QType::ANY) {
      auto luaLocal = g_luaconfs.getLocal();
      for (auto const &dsAnchor : luaLocal->dsAnchors) {
        ostringstream ans;
        ans<<"\"";
        ans<<dsAnchor.first.toString(); // Explicit toString to have a trailing dot
        for (auto const &dsRecord : dsAnchor.second) {
          ans<<" ";
          ans<<dsRecord.d_tag;
        }
        ans << "\"";
        answers.emplace_back(QType::TXT, ans.str());
      }
    }
  }

  if (qname == negativetrustanchorserver && qclass == QClass::CHAOS &&
      ::arg().mustDo("allow-trust-anchor-query")) {
    handled = true;
    if (qtype == QType::TXT || qtype == QType::ANY) {
      auto luaLocal = g_luaconfs.getLocal();
      for (auto const &negAnchor : luaLocal->negAnchors) {
        ostringstream ans;
        ans<<"\"";
        ans<<negAnchor.first.toString(); // Explicit toString to have a trailing dot
        if (negAnchor.second.length())
          ans<<" "<<negAnchor.second;
        ans << "\"";
        answers.emplace_back(QType::TXT, ans.str());
      }
    }
  }

  if (handled && !answers.empty()) {
    ret.clear();
    d_wasOutOfBand=true;

    DNSRecord dr;
    dr.d_name = qname;
    dr.d_place = DNSResourceRecord::ANSWER;
    dr.d_class = qclass;
    dr.d_ttl = 86400;
    for (const auto& ans : answers) {
      dr.d_type = ans.first;
      dr.d_content = DNSRecordContent::mastermake(ans.first, qclass, ans.second);
      ret.push_back(dr);
    }
  }

  return handled;
}


//! This is the 'out of band resolver', in other words, the authoritative server
void SyncRes::AuthDomain::addSOA(std::vector<DNSRecord>& records) const
{
  SyncRes::AuthDomain::records_t::const_iterator ziter = d_records.find(std::make_tuple(getName(), QType::SOA));
  if (ziter != d_records.end()) {
    DNSRecord dr = *ziter;
    dr.d_place = DNSResourceRecord::AUTHORITY;
    records.push_back(dr);
  }
  else {
    // cerr<<qname<<": can't find SOA record '"<<getName()<<"' in our zone!"<<endl;
  }
}

bool SyncRes::AuthDomain::operator==(const AuthDomain& rhs) const
{
  return d_records == rhs.d_records
    && d_servers == rhs.d_servers
    && d_name == rhs.d_name
    && d_rdForward == rhs.d_rdForward;
}

[[nodiscard]] std::string SyncRes::AuthDomain::print(const std::string& indent,
                                                     const std::string& indentLevel) const
{
  std::stringstream s;
  s << indent << "DNSName = " << d_name << std::endl;
  s << indent << "rdForward = " << d_rdForward << std::endl;
  s << indent << "Records {" << std::endl;
  auto recordContentIndentation = indent;
  recordContentIndentation += indentLevel;
  recordContentIndentation += indentLevel;
  for (const auto& record : d_records) {
    s << indent << indentLevel << "Record `" << record.d_name << "` {" << std::endl;
    s << record.print(recordContentIndentation);
    s << indent << indentLevel << "}" << std::endl;
  }
  s << indent << "}" << std::endl;
  s << indent << "Servers {" << std::endl;
  for (const auto& server : d_servers) {
    s << indent << indentLevel << server.toString() << std::endl;
  }
  s << indent << "}" << std::endl;
  return s.str();
}

int SyncRes::AuthDomain::getRecords(const DNSName& qname, const QType qtype, std::vector<DNSRecord>& records) const
{
  int result = RCode::NoError;
  records.clear();

  // partial lookup
  std::pair<records_t::const_iterator,records_t::const_iterator> range = d_records.equal_range(std::tie(qname));

  SyncRes::AuthDomain::records_t::const_iterator ziter;
  bool somedata = false;

  for(ziter = range.first; ziter != range.second; ++ziter) {
    somedata = true;

    if(qtype == QType::ANY || ziter->d_type == qtype || ziter->d_type == QType::CNAME) {
      // let rest of nameserver do the legwork on this one
      records.push_back(*ziter);
    }
    else if (ziter->d_type == QType::NS && ziter->d_name.countLabels() > getName().countLabels()) {
      // we hit a delegation point!
      DNSRecord dr = *ziter;
      dr.d_place=DNSResourceRecord::AUTHORITY;
      records.push_back(dr);
    }
  }

  if (!records.empty()) {
    /* We have found an exact match, we're done */
    // cerr<<qname<<": exact match in zone '"<<getName()<<"'"<<endl;
    return result;
  }

  if (somedata) {
    /* We have records for that name, but not of the wanted qtype */
    // cerr<<qname<<": found record in '"<<getName()<<"', but nothing of the right type, sending SOA"<<endl;
    addSOA(records);

    return result;
  }

  // cerr<<qname<<": nothing found so far in '"<<getName()<<"', trying wildcards"<<endl;
  DNSName wcarddomain(qname);
  while(wcarddomain != getName() && wcarddomain.chopOff()) {
    // cerr<<qname<<": trying '*."<<wcarddomain<<"' in "<<getName()<<endl;
    range = d_records.equal_range(std::make_tuple(g_wildcarddnsname + wcarddomain));
    if (range.first==range.second)
      continue;

    for(ziter = range.first; ziter != range.second; ++ziter) {
      DNSRecord dr = *ziter;
      // if we hit a CNAME, just answer that - rest of recursor will do the needful & follow
      if(dr.d_type == qtype || qtype == QType::ANY || dr.d_type == QType::CNAME) {
        dr.d_name = qname;
        dr.d_place = DNSResourceRecord::ANSWER;
        records.push_back(dr);
      }
    }

    if (records.empty()) {
      addSOA(records);
    }

    // cerr<<qname<<": in '"<<getName()<<"', had wildcard match on '*."<<wcarddomain<<"'"<<endl;
    return result;
  }

  /* Nothing for this name, no wildcard, let's see if there is some NS */
  DNSName nsdomain(qname);
  while (nsdomain.chopOff() && nsdomain != getName()) {
    range = d_records.equal_range(std::make_tuple(nsdomain,QType::NS));
    if(range.first == range.second)
      continue;

    for(ziter = range.first; ziter != range.second; ++ziter) {
      DNSRecord dr = *ziter;
      dr.d_place = DNSResourceRecord::AUTHORITY;
      records.push_back(dr);
    }
  }

  if(records.empty()) {
    // cerr<<qname<<": no NS match in zone '"<<getName()<<"' either, handing out SOA"<<endl;
    addSOA(records);
    result = RCode::NXDomain;
  }

  return result;
}

bool SyncRes::doOOBResolve(const AuthDomain& domain, const DNSName &qname, const QType qtype, vector<DNSRecord>&ret, int& res)
{
  d_authzonequeries++;
  s_authzonequeries++;

  res = domain.getRecords(qname, qtype, ret);
  return true;
}

bool SyncRes::doOOBResolve(const DNSName &qname, const QType qtype, vector<DNSRecord>&ret, unsigned int depth, int& res)
{
  string prefix;
  if(doLog()) {
    prefix=d_prefix;
    prefix.append(depth, ' ');
  }

  DNSName authdomain(qname);
  domainmap_t::const_iterator iter=getBestAuthZone(&authdomain);
  if(iter==t_sstorage.domainmap->end() || !iter->second.isAuth()) {
    LOG(prefix<<qname<<": auth storage has no zone for this query!"<<endl);
    return false;
  }

  LOG(prefix<<qname<<": auth storage has data, zone='"<<authdomain<<"'"<<endl);
  return doOOBResolve(iter->second, qname, qtype, ret, res);
}

bool SyncRes::isRecursiveForwardOrAuth(const DNSName &qname) const {
  DNSName authname(qname);
  domainmap_t::const_iterator iter = getBestAuthZone(&authname);
  return iter != t_sstorage.domainmap->end() && (iter->second.isAuth() || iter->second.shouldRecurse());
}

bool SyncRes::isForwardOrAuth(const DNSName &qname) const {
  DNSName authname(qname);
  domainmap_t::const_iterator iter = getBestAuthZone(&authname);
  return iter != t_sstorage.domainmap->end();
}

// Will be needed in the future
static const char* timestamp(const struct timeval& tv, char* buf, size_t sz)
{
  const std::string s_timestampFormat = "%Y-%m-%dT%T";
  struct tm tm;
  size_t len = strftime(buf, sz, s_timestampFormat.c_str(), localtime_r(&tv.tv_sec, &tm));
  if (len == 0) {
    int ret = snprintf(buf, sz, "%lld", static_cast<long long>(tv.tv_sec));
    if (ret < 0 || static_cast<size_t>(ret) >= sz) {
      if (sz > 0) {
        buf[0] = '\0';
      }
      return buf;
    }
    len = ret;
  }

  if (sz > len + 4) {
    snprintf(buf + len, sz - len, ".%03ld", static_cast<long>(tv.tv_usec) / 1000);
  }
  return buf;
}

static const char* timestamp(time_t t, char* buf, size_t sz)
{
  const std::string s_timestampFormat = "%Y-%m-%dT%T";
  struct tm tm;
  size_t len = strftime(buf, sz, s_timestampFormat.c_str(), localtime_r(&t, &tm));
  if (len == 0) {
    int ret = snprintf(buf, sz, "%lld", static_cast<long long>(t));
    if (ret < 0 || static_cast<size_t>(ret) >= sz) {
      if (sz > 0) {
        buf[0] = '\0';
      }
    }
  }
  return buf;
}

struct ednsstatus_t : public multi_index_container<SyncRes::EDNSStatus,
                                                   indexed_by<
                                                     ordered_unique<tag<ComboAddress>, member<SyncRes::EDNSStatus, ComboAddress, &SyncRes::EDNSStatus::address>>,
                                                     ordered_non_unique<tag<time_t>, member<SyncRes::EDNSStatus, time_t, &SyncRes::EDNSStatus::ttd>>
                                                     >>
{
  // Get a copy
  ednsstatus_t getMap() const
  {
    return *this;
  }

  void setMode(index<ComboAddress>::type &ind, iterator it, SyncRes::EDNSStatus::EDNSMode mode, time_t ts)
  {
    if (it->mode != mode || it->ttd == 0) {
      ind.modify(it, [=](SyncRes::EDNSStatus &s) { s.mode = mode; s.ttd = ts + Expire; });
    }
  }

  void prune(time_t now)
  {
    auto &ind = get<time_t>();
    ind.erase(ind.begin(), ind.upper_bound(now));
  }

  static const time_t Expire = 7200;
};

static LockGuarded<ednsstatus_t> s_ednsstatus;

SyncRes::EDNSStatus::EDNSMode SyncRes::getEDNSStatus(const ComboAddress& server)
{
  auto lock = s_ednsstatus.lock();
  const auto& it = lock->find(server);
  if (it == lock->end()) {
    return EDNSStatus::EDNSOK;
  }
  return it->mode;
}

uint64_t SyncRes::getEDNSStatusesSize()
{
  return s_ednsstatus.lock()->size();
}

void SyncRes::clearEDNSStatuses()
{
  s_ednsstatus.lock()->clear();
}

void SyncRes::pruneEDNSStatuses(time_t cutoff)
{
  s_ednsstatus.lock()->prune(cutoff);
}

uint64_t SyncRes::doEDNSDump(int fd)
{
  int newfd = dup(fd);
  if (newfd == -1) {
    return 0;
  }
  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose);
  if (!fp) {
    close(newfd);
    return 0;
  }
  uint64_t count = 0;

  fprintf(fp.get(),"; edns dump follows\n; ip\tstatus\tttd\n");
  const auto copy = s_ednsstatus.lock()->getMap();
  for (const auto& eds : copy) {
    count++;
    char tmp[26];
    fprintf(fp.get(), "%s\t%s\t%s\n", eds.address.toString().c_str(), eds.toString().c_str(), timestamp(eds.ttd, tmp, sizeof(tmp)));
  }
  return count;
}

void SyncRes::pruneNSSpeeds(time_t limit)
{
  auto lock = s_nsSpeeds.lock();
  auto &ind = lock->get<timeval>();
  ind.erase(ind.begin(), ind.upper_bound(timeval{limit, 0}));
}

uint64_t SyncRes::getNSSpeedsSize()
{
  return s_nsSpeeds.lock()->size();
}

void SyncRes::submitNSSpeed(const DNSName& server, const ComboAddress& ca, uint32_t usec, const struct timeval& now)
{
  auto lock = s_nsSpeeds.lock();
  lock->find_or_enter(server, now).submit(ca, usec, now);
}

void SyncRes::clearNSSpeeds()
{
  s_nsSpeeds.lock()->clear();
}

float SyncRes::getNSSpeed(const DNSName& server, const ComboAddress& ca)
{
  auto lock = s_nsSpeeds.lock();
  return lock->find_or_enter(server).d_collection[ca].peek();
}

uint64_t SyncRes::doDumpNSSpeeds(int fd)
{
  int newfd = dup(fd);
  if (newfd == -1) {
    return 0;
  }
  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose);
  if (!fp) {
    close(newfd);
    return 0;
  }

  fprintf(fp.get(), "; nsspeed dump follows\n; nsname\ttimestamp\t[ip/decaying-ms/last-ms...]\n");
  uint64_t count = 0;

  // Create a copy to avoid holding the lock while doing I/O
  for (const auto& i : *s_nsSpeeds.lock()) {
    count++;

    // an <empty> can appear hear in case of authoritative (hosted) zones
    char tmp[26];
    fprintf(fp.get(), "%s\t%s\t", i.d_name.toLogString().c_str(), timestamp(i.d_lastget, tmp, sizeof(tmp)));
    bool first = true;
    for (const auto& j : i.d_collection) {
      fprintf(fp.get(), "%s%s/%.3f/%.3f", first ? "" : "\t", j.first.toStringWithPortExcept(53).c_str(), j.second.peek() / 1000.0f, j.second.last() / 1000.0f);
      first = false;
    }
    fprintf(fp.get(), "\n");
  }
  return count;
}

uint64_t SyncRes::getThrottledServersSize()
{
  return s_throttle.lock()->size();
}

void SyncRes::pruneThrottledServers(time_t now)
{
  s_throttle.lock()->prune(now);
}

void SyncRes::clearThrottle()
{
  s_throttle.lock()->clear();
}

bool SyncRes::isThrottled(time_t now, const ComboAddress& server, const DNSName& target, QType qtype)
{
  return s_throttle.lock()->shouldThrottle(now, std::make_tuple(server, target, qtype));
}

bool SyncRes::isThrottled(time_t now, const ComboAddress& server)
{
  return s_throttle.lock()->shouldThrottle(now, std::make_tuple(server, g_rootdnsname, 0));
}

void SyncRes::doThrottle(time_t now, const ComboAddress& server, time_t duration, unsigned int tries)
{
  s_throttle.lock()->throttle(now, std::make_tuple(server, g_rootdnsname, 0), duration, tries);
}

void SyncRes::doThrottle(time_t now, const ComboAddress& server, const DNSName&name, QType qtype, time_t duration, unsigned int tries)
{
  s_throttle.lock()->throttle(now, std::make_tuple(server, name, qtype), duration, tries);
}

uint64_t SyncRes::doDumpThrottleMap(int fd)
{
  int newfd = dup(fd);
  if (newfd == -1) {
    return 0;
  }
  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose);
  if (!fp) {
    close(newfd);
    return 0;
  }
  fprintf(fp.get(), "; throttle map dump follows\n");
  fprintf(fp.get(), "; remote IP\tqname\tqtype\tcount\tttd\n");
  uint64_t count=0;

  // Get a copy to avoid holding the lock while doing I/O
  const auto throttleMap = s_throttle.lock()->getThrottleMap();
  for(const auto& i : throttleMap)
  {
    count++;
    char tmp[26];
    // remote IP, dns name, qtype, count, ttd
    fprintf(fp.get(), "%s\t%s\t%s\t%u\t%s\n", std::get<0>(i.thing).toString().c_str(), std::get<1>(i.thing).toLogString().c_str(), std::get<2>(i.thing).toString().c_str(), i.count, timestamp(i.ttd, tmp, sizeof(tmp)));
  }

  return count;
}

uint64_t SyncRes::getFailedServersSize()
{
  return s_fails.lock()->size();
}

void SyncRes::clearFailedServers()
{
  s_fails.lock()->clear();
}

void SyncRes::pruneFailedServers(time_t cutoff)
{
  s_fails.lock()->prune(cutoff);
}

unsigned long SyncRes::getServerFailsCount(const ComboAddress& server)
{
  return s_fails.lock()->value(server);
}

uint64_t SyncRes::doDumpFailedServers(int fd)
{
  int newfd = dup(fd);
  if (newfd == -1) {
    return 0;
  }
  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose);
  if (!fp) {
    close(newfd);
    return 0;
  }
  fprintf(fp.get(), "; failed servers dump follows\n");
  fprintf(fp.get(), "; remote IP\tcount\ttimestamp\n");
  uint64_t count=0;

  // We get a copy, so the I/O does not need to happen while holding the lock
  for (const auto& i : s_fails.lock()->getMapCopy())
  {
    count++;
    char tmp[26];
    fprintf(fp.get(), "%s\t%" PRIu64 "\t%s\n", i.key.toString().c_str(), i.value, timestamp(i.last, tmp, sizeof(tmp)));
  }

  return count;
}

uint64_t SyncRes::getNonResolvingNSSize()
{
  return s_nonresolving.lock()->size();
}

void SyncRes::clearNonResolvingNS()
{
  s_nonresolving.lock()->clear();
}

void SyncRes::pruneNonResolving(time_t cutoff)
{
  s_nonresolving.lock()->prune(cutoff);
}

uint64_t SyncRes::doDumpNonResolvingNS(int fd)
{
  int newfd = dup(fd);
  if (newfd == -1) {
    return 0;
  }
  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose);
  if (!fp) {
    close(newfd);
    return 0;
  }
  fprintf(fp.get(), "; non-resolving nameserver dump follows\n");
  fprintf(fp.get(), "; name\tcount\ttimestamp\n");
  uint64_t count=0;

  // We get a copy, so the I/O does not need to happen while holding the lock
  for (const auto& i : s_nonresolving.lock()->getMapCopy())
  {
    count++;
    char tmp[26];
    fprintf(fp.get(), "%s\t%" PRIu64 "\t%s\n", i.key.toString().c_str(), i.value, timestamp(i.last, tmp, sizeof(tmp)));
  }

  return count;
}

void SyncRes::clearSaveParentsNSSets()
{
  s_savedParentNSSet.lock()->clear();
}

size_t SyncRes::getSaveParentsNSSetsSize()
{
  return s_savedParentNSSet.lock()->size();
}

void SyncRes::pruneSaveParentsNSSets(time_t now)
{
  s_savedParentNSSet.lock()->prune(now);
}

uint64_t SyncRes::doDumpSavedParentNSSets(int fd)
{
  int newfd = dup(fd);
  if (newfd == -1) {
    return 0;
  }
  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose);
  if (!fp) {
    close(newfd);
    return 0;
  }
  fprintf(fp.get(), "; dump of saved parent nameserver sets succesfully used follows\n");
  fprintf(fp.get(), "; total entries: %zu\n", s_savedParentNSSet.lock()->size());
  fprintf(fp.get(), "; domain\tsuccess\tttd\n");
  uint64_t count=0;

  // We get a copy, so the I/O does not need to happen while holding the lock
  for (const auto& i : s_savedParentNSSet.lock()->getMapCopy())
  {
    if (i.d_count == 0) {
      continue;
    }
    count++;
    char tmp[26];
    fprintf(fp.get(), "%s\t%" PRIu64 "\t%s\n", i.d_domain.toString().c_str(), i.d_count, timestamp(i.d_ttd, tmp, sizeof(tmp)));
  }
  return count;
}

void SyncRes::pruneDoTProbeMap(time_t cutoff)
{
  auto lock = s_dotMap.lock();
  auto& ind = lock->d_map.get<time_t>();

  for (auto i = ind.begin(); i != ind.end(); ) {
    if (i->d_ttd >= cutoff) {
      // We're done as we loop ordered by d_ttd
      break;
    }
    if (i->d_status == DoTStatus::Status::Busy) {
      lock->d_numBusy--;
    }
    i = ind.erase(i);
  }
}

uint64_t SyncRes::doDumpDoTProbeMap(int fd)
{
  int newfd = dup(fd);
  if (newfd == -1) {
    return 0;
  }
  auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose);
  if (!fp) {
    close(newfd);
    return 0;
  }
  fprintf(fp.get(), "; DoT probing map follows\n");
  fprintf(fp.get(), "; ip\tdomain\tcount\tstatus\tttd\n");
  uint64_t count=0;

  // We get a copy, so the I/O does not need to happen while holding the lock
  DoTMap copy;
  {
    copy = *s_dotMap.lock();
  }
  fprintf(fp.get(), "; %" PRIu64 " Busy entries\n", copy.d_numBusy);
  for (const auto& i : copy.d_map) {
    count++;
    char tmp[26];
    fprintf(fp.get(), "%s\t%s\t%" PRIu64 "\t%s\t%s\n", i.d_address.toString().c_str(), i.d_auth.toString().c_str(), i.d_count, i.toString().c_str(), timestamp(i.d_ttd, tmp, sizeof(tmp)));
  }
  return count;
}

/* so here is the story. First we complete the full resolution process for a domain name. And only THEN do we decide
   to also do DNSSEC validation, which leads to new queries. To make this simple, we *always* ask for DNSSEC records
   so that if there are RRSIGs for a name, we'll have them.

   However, some hosts simply can't answer questions which ask for DNSSEC. This can manifest itself as:
   * No answer
   * FormErr
   * Nonsense answer

   The cause of "No answer" may be fragmentation, and it is tempting to probe if smaller answers would get through.
   Another cause of "No answer" may simply be a network condition.
   Nonsense answers are a clearer indication this host won't be able to do DNSSEC evah.

   Previous implementations have suffered from turning off DNSSEC questions for an authoritative server based on timeouts.
   A clever idea is to only turn off DNSSEC if we know a domain isn't signed anyhow. The problem with that really
   clever idea however is that at this point in PowerDNS, we may simply not know that yet. All the DNSSEC thinking happens
   elsewhere. It may not have happened yet.

   For now this means we can't be clever, but will turn off DNSSEC if you reply with FormError or gibberish.
*/

LWResult::Result SyncRes::asyncresolveWrapper(const ComboAddress& ip, bool ednsMANDATORY, const DNSName& domain, const DNSName& auth, int type, bool doTCP, bool sendRDQuery, struct timeval* now, boost::optional<Netmask>& srcmask, LWResult* res, bool* chained, const DNSName& nsName) const
{
  /* what is your QUEST?
     the goal is to get as many remotes as possible on the best level of EDNS support
     The levels are:

     1) EDNSOK: Honors EDNS0, absent from table
     2) EDNSIGNORANT: Ignores EDNS0, gives replies without EDNS0
     3) NOEDNS: Generates FORMERR on EDNS queries

     Everybody starts out assumed to be EDNSOK.
     If EDNSOK, send out EDNS0
        If you FORMERR us, go to NOEDNS, 
        If no EDNS in response, go to EDNSIGNORANT
     If EDNSIGNORANT, keep on including EDNS0, see what happens
        Same behaviour as EDNSOK
     If NOEDNS, send bare queries
  */

  // Read current status, defaulting to OK
  SyncRes::EDNSStatus::EDNSMode mode = EDNSStatus::EDNSOK;
  {
    auto lock = s_ednsstatus.lock();
    auto ednsstatus = lock->find(ip); // does this include port? YES
    if (ednsstatus != lock->end()) {
      if (ednsstatus->ttd && ednsstatus->ttd < d_now.tv_sec) {
        lock->erase(ednsstatus);
      } else {
        mode = ednsstatus->mode;
      }
    }
  }

  int EDNSLevel = 0;
  auto luaconfsLocal = g_luaconfs.getLocal();
  ResolveContext ctx;
  ctx.d_initialRequestId = d_initialRequestId;
  ctx.d_nsName = nsName;
#ifdef HAVE_FSTRM
  ctx.d_auth = auth;
#endif

  LWResult::Result ret;

  for (int tries = 0; tries < 2; ++tries) {

    if (mode == EDNSStatus::NOEDNS) {
      g_stats.noEdnsOutQueries++;
      EDNSLevel = 0; // level != mode
    }
    else if (ednsMANDATORY || mode != EDNSStatus::NOEDNS) {
      EDNSLevel = 1;
    }

    DNSName sendQname(domain);
    if (g_lowercaseOutgoing) {
      sendQname.makeUsLowerCase();
    }

    if (d_asyncResolve) {
      ret = d_asyncResolve(ip, sendQname, type, doTCP, sendRDQuery, EDNSLevel, now, srcmask, ctx, res, chained);
    }
    else {
      ret = asyncresolve(ip, sendQname, type, doTCP, sendRDQuery, EDNSLevel, now, srcmask, ctx, d_outgoingProtobufServers, d_frameStreamServers, luaconfsLocal->outgoingProtobufExportConfig.exportTypes, res, chained);
    }

    if (ret == LWResult::Result::PermanentError || ret == LWResult::Result::OSLimitError || ret == LWResult::Result::Spoofed) {
      break; // transport error, nothing to learn here
    }

    if (ret == LWResult::Result::Timeout) { // timeout, not doing anything with it now
      break;
    }

    if (EDNSLevel == 1) {
      // We sent out with EDNS
      // ret is LWResult::Result::Success
      // ednsstatus in table might be pruned or changed by another request/thread, so do a new lookup/insert if needed
      auto lock = s_ednsstatus.lock(); // all three branches below need a lock

      // Determine new mode
      if (res->d_validpacket && !res->d_haveEDNS && res->d_rcode == RCode::FormErr)  {
        mode = EDNSStatus::NOEDNS;
        auto ednsstatus = lock->insert(ip).first;
        auto &ind = lock->get<ComboAddress>();
        lock->setMode(ind, ednsstatus, mode, d_now.tv_sec);
        // This is the only path that re-iterates the loop
        continue;
      }
      else if (!res->d_haveEDNS) {
        auto ednsstatus = lock->insert(ip).first;
        auto &ind = lock->get<ComboAddress>();
        lock->setMode(ind, ednsstatus, EDNSStatus::EDNSIGNORANT, d_now.tv_sec);
      }
      else {
        // New status is EDNSOK
        lock->erase(ip);
      }
    }

    break;
  }
  return ret;
}

#define QLOG(x) LOG(prefix << " child=" <<  child << ": " << x << endl)

/* The parameters from rfc9156. */
/* maximum number of QNAME minimisation iterations */
static const unsigned int s_max_minimise_count = 10;
/* number of queries that should only have one label appended */
static const unsigned int s_minimise_one_lab = 4;

static unsigned int qmStepLen(unsigned int labels, unsigned int qnamelen, unsigned int i)
{
    unsigned int step;

    if (i < s_minimise_one_lab) {
      step = 1;
    } else if (i < s_max_minimise_count) {
      step = std::max(1U, (qnamelen - labels) / (10 - i));
    } else {
      step = qnamelen - labels;
    }
    unsigned int targetlen = std::min(labels + step, qnamelen);
    return targetlen;
}

int SyncRes::doResolve(const DNSName &qname, const QType qtype, vector<DNSRecord>&ret, unsigned int depth, set<GetBestNSAnswer>& beenthere, vState& state) {

  string prefix = d_prefix;
  prefix.append(depth, ' ');
  auto luaconfsLocal = g_luaconfs.getLocal();

  /* Apply qname (including CNAME chain) filtering policies */
  if (d_wantsRPZ && !d_appliedPolicy.wasHit()) {
    if (luaconfsLocal->dfe.getQueryPolicy(qname, d_discardedPolicies, d_appliedPolicy)) {
      mergePolicyTags(d_policyTags, d_appliedPolicy.getTags());
      bool done = false;
      int rcode = RCode::NoError;
      handlePolicyHit(prefix, qname, qtype, ret, done, rcode, depth);
      if (done) {
        return rcode;
      }
    }
  }

  initZoneCutsFromTA(qname);

  // In the auth or recursive forward case, it does not make sense to do qname-minimization
  if (!getQNameMinimization() || isRecursiveForwardOrAuth(qname)) {
    return doResolveNoQNameMinimization(qname, qtype, ret, depth, beenthere, state);
  }

  // The qname minimization algorithm is a simplified version of the one in RFC 7816 (bis).
  // It could be simplified because the cache maintenance (both positive and negative)
  // is already done by doResolveNoQNameMinimization().
  //
  // Sketch of algorithm:
  // Check cache
  //  If result found: done
  //  Otherwise determine closes ancestor from cache data
  //    Repeat querying A, adding more labels of the original qname
  //    If we get a delegation continue at ancestor determination
  //    Until we have the full name.
  //
  // The algorithm starts with adding a single label per iteration, and
  // moves to three labels per iteration after three iterations.

  DNSName child;
  prefix.append(string("QM ") + qname.toString() + "|" + qtype.toString());

  QLOG("doResolve");

  // Look in cache only
  vector<DNSRecord> retq;
  bool old = setCacheOnly(true);
  bool fromCache = false;
  // For cache peeking, we tell doResolveNoQNameMinimization not to consider the (non-recursive) forward case.
  // Otherwise all queries in a forward domain will be forwarded, while we want to consult the cache.
  // The out-of-band cases for doResolveNoQNameMinimization() should be reconsidered and redone some day.
  int res = doResolveNoQNameMinimization(qname, qtype, retq, depth, beenthere, state, &fromCache, nullptr, false);
  setCacheOnly(old);
  if (fromCache) {
    QLOG("Step0 Found in cache");
    if (d_appliedPolicy.d_type != DNSFilterEngine::PolicyType::None && (d_appliedPolicy.d_kind == DNSFilterEngine::PolicyKind::NXDOMAIN || d_appliedPolicy.d_kind == DNSFilterEngine::PolicyKind::NODATA)) {
      ret.clear();
    }
    ret.insert(ret.end(), retq.begin(), retq.end());

    return res;
  }
  QLOG("Step0 Not cached");

  const unsigned int qnamelen = qname.countLabels();

  DNSName fwdomain(qname);
  const bool forwarded = getBestAuthZone(&fwdomain) != t_sstorage.domainmap->end();
  if (forwarded) {
    QLOG("Step0 qname is in a forwarded domain " << fwdomain);
  }

  for (unsigned int i = 0; i <= qnamelen; ) {

    // Step 1
    vector<DNSRecord> bestns;
    DNSName nsdomain(qname);
    if (qtype == QType::DS) {
      nsdomain.chopOff();
    }
    // the two retries allow getBestNSFromCache&co to reprime the root
    // hints, in case they ever go missing
    for (int tries = 0; tries < 2 && bestns.empty(); ++tries) {
      bool flawedNSSet = false;
      set<GetBestNSAnswer> beenthereIgnored;
      getBestNSFromCache(nsdomain, qtype, bestns, &flawedNSSet, depth, beenthereIgnored, boost::make_optional(forwarded, fwdomain));
      if (forwarded) {
        break;
      }
    }

    if (bestns.size() == 0) {
      if (!forwarded) {
        // Something terrible is wrong
        QLOG("Step1 No ancestor found return ServFail");
        return RCode::ServFail;
      }
      child = fwdomain;
    } else {
      QLOG("Step1 Ancestor from cache is " << bestns[0].d_name);
      if (forwarded) {
        child = bestns[0].d_name.isPartOf(fwdomain) ? bestns[0].d_name : fwdomain;
        QLOG("Step1 Final Ancestor (using forwarding info) is " << child);
      } else {
        child = bestns[0].d_name;
      }
    }
    for (; i <= qnamelen; i++) {
      // Step 2
      unsigned int labels = child.countLabels();
      unsigned int targetlen = qmStepLen(labels, qnamelen, i);

      while (labels < targetlen) {
        child.prependRawLabel(qname.getRawLabel(qnamelen - labels - 1));
        labels++;
      }
      // rfc9156 section-2.3, append labels if they start with an underscore
      while (labels < qnamelen) {
        auto prependLabel = qname.getRawLabel(qnamelen - labels - 1);
        if (prependLabel.at(0) != '_') {
          break;
        }
        child.prependRawLabel(prependLabel);
        labels++;
      }

      QLOG("Step2 New child");

      // Step 3 resolve
      if (child == qname) {
        QLOG("Step3 Going to do final resolve");
        res = doResolveNoQNameMinimization(qname, qtype, ret, depth, beenthere, state);
        QLOG("Step3 Final resolve: " << RCode::to_s(res) << "/" << ret.size());
        return res;
      }

      // Step 4
      QLOG("Step4 Resolve A for child");
      bool oldFollowCNAME = d_followCNAME;
      d_followCNAME = false;
      retq.resize(0);
      StopAtDelegation stopAtDelegation = Stop;
      res = doResolveNoQNameMinimization(child, QType::A, retq, depth, beenthere, state, nullptr, &stopAtDelegation);
      d_followCNAME = oldFollowCNAME;
      QLOG("Step4 Resolve A result is " << RCode::to_s(res) << "/" << retq.size() << "/" << stopAtDelegation);
      if (stopAtDelegation == Stopped) {
        QLOG("Delegation seen, continue at step 1");
        break;
      }

      if (res != RCode::NoError) {
        // Case 5: unexpected answer
        QLOG("Step5: other rcode, last effort final resolve");
        setQNameMinimization(false);
        setQMFallbackMode(true);

        // We might have hit a depth level check, but we still want to allow some recursion levels in the fallback
        // no-qname-minimization case. This has the effect that a qname minimization fallback case might reach 150% of
        // maxdepth.
        res = doResolveNoQNameMinimization(qname, qtype, ret, depth/2, beenthere, state);

        if(res == RCode::NoError) {
          s_qnameminfallbacksuccess++;
        }

        QLOG("Step5 End resolve: " << RCode::to_s(res) << "/" << ret.size());
        return res;
      }
    }
  }

  // Should not be reached
  QLOG("Max iterations reached, return ServFail");
  return RCode::ServFail;
}

/*! This function will check the cache and go out to the internet if the answer is not in cache
 *
 * \param qname The name we need an answer for
 * \param qtype
 * \param ret The vector of DNSRecords we need to fill with the answers
 * \param depth The recursion depth we are in
 * \param beenthere
 * \param fromCache tells the caller the result came from the cache, may be nullptr
 * \param stopAtDelegation if non-nullptr and pointed-to value is Stop requests the callee to stop at a delegation, if so pointed-to value is set to Stopped
 * \return DNS RCODE or -1 (Error)
 */
int SyncRes::doResolveNoQNameMinimization(const DNSName &qname, const QType qtype, vector<DNSRecord>&ret, unsigned int depth, set<GetBestNSAnswer>& beenthere, vState& state, bool *fromCache, StopAtDelegation *stopAtDelegation, bool considerforwards)
{
  string prefix;
  if(doLog()) {
    prefix=d_prefix;
    prefix.append(depth, ' ');
  }

  LOG(prefix<<qname<<": Wants "<< (d_doDNSSEC ? "" : "NO ") << "DNSSEC processing, "<<(d_requireAuthData ? "" : "NO ")<<"auth data in query for "<<qtype<<endl);

  if (s_maxdepth && depth > s_maxdepth) {
    string msg = "More than " + std::to_string(s_maxdepth) + " (max-recursion-depth) levels of recursion needed while resolving " + qname.toLogString();
    LOG(prefix << qname << ": " << msg << endl);
    throw ImmediateServFailException(msg);
  }
  int res=0;


  const int iterations = !d_refresh && MemRecursorCache::s_maxServedStaleExtensions > 0 ? 2 : 1;
  for (int loop = 0; loop < iterations; loop++) {

    d_serveStale = loop == 1;

    // This is a difficult way of expressing "this is a normal query", i.e. not getRootNS.
    if(!(d_updatingRootNS && qtype.getCode()==QType::NS && qname.isRoot())) {
      if(d_cacheonly) { // very limited OOB support
        LWResult lwr;
        LOG(prefix<<qname<<": Recursion not requested for '"<<qname<<"|"<<qtype<<"', peeking at auth/forward zones"<<endl);
        DNSName authname(qname);
        domainmap_t::const_iterator iter=getBestAuthZone(&authname);
        if(iter != t_sstorage.domainmap->end()) {
          if(iter->second.isAuth()) {
            ret.clear();
            d_wasOutOfBand = doOOBResolve(qname, qtype, ret, depth, res);
            if (fromCache)
              *fromCache = d_wasOutOfBand;
            return res;
          }
          else if (considerforwards) {
            const vector<ComboAddress>& servers = iter->second.d_servers;
            const ComboAddress remoteIP = servers.front();
            LOG(prefix<<qname<<": forwarding query to hardcoded nameserver '"<< remoteIP.toStringWithPort()<<"' for zone '"<<authname<<"'"<<endl);

            boost::optional<Netmask> nm;
            bool chained = false;
            // forwardes are "anonymous", so plug in an empty name; some day we might have a fancier config language...
            auto resolveRet = asyncresolveWrapper(remoteIP, d_doDNSSEC, qname, authname, qtype.getCode(), false, false, &d_now, nm, &lwr, &chained, DNSName());

            d_totUsec += lwr.d_usec;
            accountAuthLatency(lwr.d_usec, remoteIP.sin4.sin_family);
            ++g_stats.authRCode.at(lwr.d_rcode);
            if (fromCache)
              *fromCache = true;

            // filter out the good stuff from lwr.result()
            if (resolveRet == LWResult::Result::Success) {
              for(const auto& rec : lwr.d_records) {
                if(rec.d_place == DNSResourceRecord::ANSWER)
                  ret.push_back(rec);
              }
              return 0;
            }
            else {
              return RCode::ServFail;
            }
          }
        }
      }

      DNSName authname(qname);
      bool wasForwardedOrAuthZone = false;
      bool wasAuthZone = false;
      bool wasForwardRecurse = false;
      domainmap_t::const_iterator iter = getBestAuthZone(&authname);
      if(iter != t_sstorage.domainmap->end()) {
        const auto& domain = iter->second;
        wasForwardedOrAuthZone = true;

        if (domain.isAuth()) {
          wasAuthZone = true;
        } else if (domain.shouldRecurse()) {
          wasForwardRecurse = true;
        }
      }

      /* When we are looking for a DS, we want to the non-CNAME cache check first
         because we can actually have a DS (from the parent zone) AND a CNAME (from
         the child zone), and what we really want is the DS */
      if (qtype != QType::DS && doCNAMECacheCheck(qname, qtype, ret, depth, res, state, wasAuthZone, wasForwardRecurse)) { // will reroute us if needed
        d_wasOutOfBand = wasAuthZone;
        // Here we have an issue. If we were prevented from going out to the network (cache-only was set, possibly because we
        // are in QM Step0) we might have a CNAME but not the corresponding target.
        // It means that we will sometimes go to the next steps when we are in fact done, but that's fine since
        // we will get the records from the cache, resulting in a small overhead.
        // This might be a real problem if we had a RPZ hit, though, because we do not want the processing to continue, since
        // RPZ rules will not be evaluated anymore (we already matched).
        const bool stoppedByPolicyHit = d_appliedPolicy.wasHit();

        if (fromCache && (!d_cacheonly || stoppedByPolicyHit)) {
          *fromCache = true;
        }
        /* Apply Post filtering policies */

        if (d_wantsRPZ && !stoppedByPolicyHit) {
          auto luaLocal = g_luaconfs.getLocal();
          if (luaLocal->dfe.getPostPolicy(ret, d_discardedPolicies, d_appliedPolicy)) {
            mergePolicyTags(d_policyTags, d_appliedPolicy.getTags());
            bool done = false;
            handlePolicyHit(prefix, qname, qtype, ret, done, res, depth);
            if (done && fromCache) {
              *fromCache = true;
            }
          }
        }
        return res;
      }

      if (doCacheCheck(qname, authname, wasForwardedOrAuthZone, wasAuthZone, wasForwardRecurse, qtype, ret, depth, res, state)) {
        // we done
        d_wasOutOfBand = wasAuthZone;
        if (fromCache) {
          *fromCache = true;
        }

        if (d_wantsRPZ && !d_appliedPolicy.wasHit()) {
          auto luaLocal = g_luaconfs.getLocal();
          if (luaLocal->dfe.getPostPolicy(ret, d_discardedPolicies, d_appliedPolicy)) {
            mergePolicyTags(d_policyTags, d_appliedPolicy.getTags());
            bool done = false;
            handlePolicyHit(prefix, qname, qtype, ret, done, res, depth);
          }
        }

        return res;
      }

      /* if we have not found a cached DS (or denial of), now is the time to look for a CNAME */
      if (qtype == QType::DS && doCNAMECacheCheck(qname, qtype, ret, depth, res, state, wasAuthZone, wasForwardRecurse)) { // will reroute us if needed
        d_wasOutOfBand = wasAuthZone;
        // Here we have an issue. If we were prevented from going out to the network (cache-only was set, possibly because we
        // are in QM Step0) we might have a CNAME but not the corresponding target.
        // It means that we will sometimes go to the next steps when we are in fact done, but that's fine since
        // we will get the records from the cache, resulting in a small overhead.
        // This might be a real problem if we had a RPZ hit, though, because we do not want the processing to continue, since
        // RPZ rules will not be evaluated anymore (we already matched).
        const bool stoppedByPolicyHit = d_appliedPolicy.wasHit();

        if (fromCache && (!d_cacheonly || stoppedByPolicyHit)) {
          *fromCache = true;
        }
        /* Apply Post filtering policies */

        if (d_wantsRPZ && !stoppedByPolicyHit) {
          auto luaLocal = g_luaconfs.getLocal();
          if (luaLocal->dfe.getPostPolicy(ret, d_discardedPolicies, d_appliedPolicy)) {
            mergePolicyTags(d_policyTags, d_appliedPolicy.getTags());
            bool done = false;
            handlePolicyHit(prefix, qname, qtype, ret, done, res, depth);
            if (done && fromCache) {
              *fromCache = true;
            }
          }
        }

        return res;
      }
    }

    if (d_cacheonly) {
      return 0;
    }
    // When trying to serve-stale, we also only look at the cache. Don't look at d_serveStale, it
    // might be changed by recursive calls (this should be fixed in a better way!).
    if (loop == 1) {
      return res;
    }

    LOG(prefix<<qname<<": No cache hit for '"<<qname<<"|"<<qtype<<"', trying to find an appropriate NS record"<<endl);

    DNSName subdomain(qname);
    if (qtype == QType::DS) subdomain.chopOff();

    NsSet nsset;
    bool flawedNSSet=false;

    // the two retries allow getBestNSNamesFromCache&co to reprime the root
    // hints, in case they ever go missing
    for(int tries=0;tries<2 && nsset.empty();++tries) {
      subdomain=getBestNSNamesFromCache(subdomain, qtype, nsset, &flawedNSSet, depth, beenthere); //  pass beenthere to both occasions
    }

    res = doResolveAt(nsset, subdomain, flawedNSSet, qname, qtype, ret, depth, beenthere, state, stopAtDelegation, nullptr);

    if (res == -1 && s_save_parent_ns_set) {
      // It did not work out, lets check if we have a saved parent NS set
      map<DNSName, vector<ComboAddress>> fallBack;
      {
        auto lock = s_savedParentNSSet.lock();
        auto domainData= lock->find(subdomain);
        if (domainData != lock->end() && domainData->d_nsAddresses.size() > 0) {
          nsset.clear();
          // Build the nsset arg and fallBack data for the fallback doResolveAt() attempt
          // Take a copy to be able to release the lock, NsSet is actually a map, go figure
          for (const auto& ns : domainData->d_nsAddresses) {
            nsset.emplace(ns.first, pair(std::vector<ComboAddress>(), false));
            fallBack.emplace(ns.first, ns.second);
          }
        }
      }
      if (fallBack.size() > 0) {
        LOG(prefix<<qname<<": Failure, but we have a saved parent NS set, trying that one"<< endl)
          res = doResolveAt(nsset, subdomain, flawedNSSet, qname, qtype, ret, depth, beenthere, state, stopAtDelegation, &fallBack);
        if (res == 0) {
          // It did work out
          s_savedParentNSSet.lock()->inc(subdomain);
        }
      }
    }
    /* Apply Post filtering policies */
    if (d_wantsRPZ && !d_appliedPolicy.wasHit()) {
      auto luaLocal = g_luaconfs.getLocal();
      if (luaLocal->dfe.getPostPolicy(ret, d_discardedPolicies, d_appliedPolicy)) {
        mergePolicyTags(d_policyTags, d_appliedPolicy.getTags());
        bool done = false;
        handlePolicyHit(prefix, qname, qtype, ret, done, res, depth);
      }
    }

    if (!res) {
      return 0;
    }

    LOG(prefix<<qname<<": failed (res="<<res<<")"<<endl);
    if (res >= 0) {
      break;
    }
  }
  return res<0 ? RCode::ServFail : res;
}

#if 0
// for testing purposes
static bool ipv6First(const ComboAddress& a, const ComboAddress& b)
{
  return !(a.sin4.sin_family < a.sin4.sin_family);
}
#endif

struct speedOrderCA
{
  speedOrderCA(std::map<ComboAddress,float>& speeds): d_speeds(speeds) {}
  bool operator()(const ComboAddress& a, const ComboAddress& b) const
  {
    return d_speeds[a] < d_speeds[b];
  }
  std::map<ComboAddress, float>& d_speeds;
};

/** This function explicitly goes out for A or AAAA addresses
*/
vector<ComboAddress> SyncRes::getAddrs(const DNSName &qname, unsigned int depth, set<GetBestNSAnswer>& beenthere, bool cacheOnly, unsigned int& addressQueriesForNS)
{
  typedef vector<DNSRecord> res_t;
  typedef vector<ComboAddress> ret_t;
  ret_t ret;

  bool oldCacheOnly = setCacheOnly(cacheOnly);
  bool oldRequireAuthData = d_requireAuthData;
  bool oldValidationRequested = d_DNSSECValidationRequested;
  bool oldFollowCNAME = d_followCNAME;
  bool seenV6 = false;
  const unsigned int startqueries = d_outqueries;
  d_requireAuthData = false;
  d_DNSSECValidationRequested = false;
  d_followCNAME = true;

  MemRecursorCache::Flags flags = MemRecursorCache::None;
  if (d_serveStale) {
    flags |= MemRecursorCache::ServeStale;
  }
  try {
    // First look for both A and AAAA in the cache
    res_t cset;
    if (s_doIPv4 && g_recCache->get(d_now.tv_sec, qname, QType::A, flags, &cset, d_cacheRemote, d_routingTag) > 0) {
      for (const auto &i : cset) {
        if (auto rec = getRR<ARecordContent>(i)) {
          ret.push_back(rec->getCA(53));
        }
      }
    }
    if (s_doIPv6 && g_recCache->get(d_now.tv_sec, qname, QType::AAAA, flags, &cset, d_cacheRemote, d_routingTag) > 0) {
      for (const auto &i : cset) {
        if (auto rec = getRR<AAAARecordContent>(i)) {
          seenV6 = true;
          ret.push_back(rec->getCA(53));
        }
      }
    }
    if (ret.empty()) {
      // Neither A nor AAAA in the cache...
      vState newState = vState::Indeterminate;
      cset.clear();
      // Go out to get A's
      if (s_doIPv4 && doResolve(qname, QType::A, cset, depth+1, beenthere, newState) == 0) {  // this consults cache, OR goes out
        for (auto const &i : cset) {
          if (i.d_type == QType::A) {
            if (auto rec = getRR<ARecordContent>(i)) {
              ret.push_back(rec->getCA(53));
            }
          }
        }
      }
      if (s_doIPv6) { // s_doIPv6 **IMPLIES** pdns::isQueryLocalAddressFamilyEnabled(AF_INET6) returned true
        if (ret.empty()) {
          // We only go out immediately to find IPv6 records if we did not find any IPv4 ones.
          newState = vState::Indeterminate;
          cset.clear();
          if (doResolve(qname, QType::AAAA, cset, depth+1, beenthere, newState) == 0) {  // this consults cache, OR goes out
            for (const auto &i : cset) {
              if (i.d_type == QType::AAAA) {
                if (auto rec = getRR<AAAARecordContent>(i)) {
                  seenV6 = true;
                  ret.push_back(rec->getCA(53));
                }
              }
            }
          }
        } else {
          // We have some IPv4 records, consult the cache, we might have encountered some IPv6 glue
          cset.clear();
          if (g_recCache->get(d_now.tv_sec, qname, QType::AAAA, flags, &cset, d_cacheRemote, d_routingTag) > 0) {
            for (const auto &i : cset) {
              if (auto rec = getRR<AAAARecordContent>(i)) {
                seenV6 = true;
                ret.push_back(rec->getCA(53));
              }
            }
          }
        }
      }
    }
    if (s_doIPv6 && !seenV6 && !cacheOnly) {
      // No IPv6 records in cache, check negcache and submit async task if negache does not have the data
      // so that the next time the cache or the negcache will have data
      NegCache::NegCacheEntry ne;
      bool inNegCache = g_negCache->get(qname, QType::AAAA, d_now, ne, false);
      if (!inNegCache) {
        pushResolveTask(qname, QType::AAAA, d_now.tv_sec, d_now.tv_sec + 60);
      }
    }
  }
  catch (const PolicyHitException&) {
    // We ignore a policy hit while trying to retrieve the addresses
    // of a NS and keep processing the current query
  }

  if (ret.empty() && d_outqueries > startqueries) {
    // We did 1 or more outgoing queries to resolve this NS name but returned empty handed
    addressQueriesForNS++;
  }
  d_requireAuthData = oldRequireAuthData;
  d_DNSSECValidationRequested = oldValidationRequested;
  setCacheOnly(oldCacheOnly);
  d_followCNAME = oldFollowCNAME;

  if (s_max_busy_dot_probes > 0 && s_dot_to_port_853) {
    for (auto& add : ret) {
      if (shouldDoDoT(add, d_now.tv_sec)) {
        add.setPort(853);
      }
    }
  }
  /* we need to remove from the nsSpeeds collection the existing IPs
     for this nameserver that are no longer in the set, even if there
     is only one or none at all in the current set.
  */
  map<ComboAddress, float> speeds;
  {
    auto lock = s_nsSpeeds.lock();
    auto& collection = lock->find_or_enter(qname, d_now);
    float factor = collection.getFactor(d_now);
    for(const auto& val: ret) {
      speeds[val] = collection.d_collection[val].get(factor);
    }
    collection.purge(speeds);
  }

  if (ret.size() > 1) {
    shuffle(ret.begin(), ret.end(), pdns::dns_random_engine());
    speedOrderCA so(speeds);
    stable_sort(ret.begin(), ret.end(), so);
  }

  if(doLog()) {
    string prefix=d_prefix;
    prefix.append(depth, ' ');
    LOG(prefix<<"Nameserver "<<qname<<" IPs: ");
    bool first = true;
    for(const auto& addr : ret) {
      if (first) {
        first = false;
      }
      else {
        LOG(", ");
      }
      LOG((addr.toString())<<"(" << fmtfloat("%0.2f", speeds[addr]/1000.0) <<"ms)");
    }
    LOG(endl);
  }

  return ret;
}

void SyncRes::getBestNSFromCache(const DNSName &qname, const QType qtype, vector<DNSRecord>& bestns, bool* flawedNSSet, unsigned int depth, set<GetBestNSAnswer>& beenthere, const boost::optional<DNSName>& cutOffDomain)
{
  string prefix;
  DNSName subdomain(qname);
  if(doLog()) {
    prefix=d_prefix;
    prefix.append(depth, ' ');
  }
  bestns.clear();
  bool brokeloop;
  MemRecursorCache::Flags flags = MemRecursorCache::None;
  if (d_serveStale) {
    flags |= MemRecursorCache::ServeStale;
  }
  do {
    if (cutOffDomain && (subdomain == *cutOffDomain || !subdomain.isPartOf(*cutOffDomain))) {
      break;
    }
    brokeloop=false;
    LOG(prefix<<qname<<": Checking if we have NS in cache for '"<<subdomain<<"'"<<endl);
    vector<DNSRecord> ns;
    *flawedNSSet = false;

    if (g_recCache->get(d_now.tv_sec, subdomain, QType::NS, flags, &ns, d_cacheRemote, d_routingTag) > 0) {
      if (s_maxnsperresolve > 0 && ns.size() > s_maxnsperresolve) {
        vector<DNSRecord> selected;
        selected.reserve(s_maxnsperresolve);
        std::sample(ns.cbegin(), ns.cend(), std::back_inserter(selected), s_maxnsperresolve, pdns::dns_random_engine());
        ns = selected;
      }
      bestns.reserve(ns.size());

      for(auto k=ns.cbegin();k!=ns.cend(); ++k) {
        if(k->d_ttl > (unsigned int)d_now.tv_sec ) {
          vector<DNSRecord> aset;
          QType nsqt{QType::ADDR};
          if (s_doIPv4 && !s_doIPv6) {
            nsqt = QType::A;
          } else if (!s_doIPv4 && s_doIPv6) {
            nsqt = QType::AAAA;
          }

          const DNSRecord& dr=*k;
	  auto nrr = getRR<NSRecordContent>(dr);
          if(nrr && (!nrr->getNS().isPartOf(subdomain) || g_recCache->get(d_now.tv_sec, nrr->getNS(), nsqt,
                                                                          flags, doLog() ? &aset : 0, d_cacheRemote, d_routingTag) > 0)) {
            bestns.push_back(dr);
            LOG(prefix<<qname<<": NS (with ip, or non-glue) in cache for '"<<subdomain<<"' -> '"<<nrr->getNS()<<"'"<<endl);
            LOG(prefix<<qname<<": within bailiwick: "<< nrr->getNS().isPartOf(subdomain));
            if(!aset.empty()) {
              LOG(",  in cache, ttl="<<(unsigned int)(((time_t)aset.begin()->d_ttl- d_now.tv_sec ))<<endl);
            }
            else {
              LOG(", not in cache / did not look at cache"<<endl);
            }
          }
          else {
            *flawedNSSet=true;
            LOG(prefix<<qname<<": NS in cache for '"<<subdomain<<"', but needs glue ("<<nrr->getNS()<<") which we miss or is expired"<<endl);
          }
        }
      }

      if(!bestns.empty()) {
        GetBestNSAnswer answer;
        answer.qname=qname;
	answer.qtype=qtype.getCode();
	for(const auto& dr : bestns) {
          if (auto nsContent = getRR<NSRecordContent>(dr)) {
            answer.bestns.emplace(dr.d_name, nsContent->getNS());
          }
        }

        auto insertionPair = beenthere.insert(std::move(answer));
        if(!insertionPair.second) {
	  brokeloop=true;
          LOG(prefix<<qname<<": We have NS in cache for '"<<subdomain<<"' but part of LOOP (already seen "<<answer.qname<<")! Trying less specific NS"<<endl);
	  ;
          if(doLog())
            for( set<GetBestNSAnswer>::const_iterator j=beenthere.begin();j!=beenthere.end();++j) {
	      bool neo = (j == insertionPair.first);
	      LOG(prefix<<qname<<": beenthere"<<(neo?"*":"")<<": "<<j->qname<<"|"<<DNSRecordContent::NumberToType(j->qtype)<<" ("<<(unsigned int)j->bestns.size()<<")"<<endl);
            }
          bestns.clear();
        }
        else {
          LOG(prefix<<qname<<": We have NS in cache for '"<<subdomain<<"' (flawedNSSet="<<*flawedNSSet<<")"<<endl);
          return;
        }
      }
    }
    LOG(prefix<<qname<<": no valid/useful NS in cache for '"<<subdomain<<"'"<<endl);

    if(subdomain.isRoot() && !brokeloop) {
      // We lost the root NS records
      primeHints();
      LOG(prefix<<qname<<": reprimed the root"<<endl);
      /* let's prevent an infinite loop */
      if (!d_updatingRootNS) {
        auto log = g_slog->withName("housekeeping");
        getRootNS(d_now, d_asyncResolve, depth, log);
      }
    }
  } while(subdomain.chopOff());
}

SyncRes::domainmap_t::const_iterator SyncRes::getBestAuthZone(DNSName* qname) const
{
  if (t_sstorage.domainmap->empty()) {
    return t_sstorage.domainmap->end();
  }

  SyncRes::domainmap_t::const_iterator ret;
  do {
    ret=t_sstorage.domainmap->find(*qname);
    if(ret!=t_sstorage.domainmap->end())
      break;
  }while(qname->chopOff());
  return ret;
}

/** doesn't actually do the work, leaves that to getBestNSFromCache */
DNSName SyncRes::getBestNSNamesFromCache(const DNSName &qname, const QType qtype, NsSet& nsset, bool* flawedNSSet, unsigned int depth, set<GetBestNSAnswer>&beenthere)
{
  string prefix;
  if (doLog()) {
    prefix = d_prefix;
    prefix.append(depth, ' ');
  }
  DNSName authOrForwDomain(qname);

  domainmap_t::const_iterator iter = getBestAuthZone(&authOrForwDomain);
  // We have an auth, forwarder of forwarder-recurse
  if (iter != t_sstorage.domainmap->end()) {
    if (iter->second.isAuth()) {
      // this gets picked up in doResolveAt, the empty DNSName, combined with the
      // empty vector means 'we are auth for this zone'
      nsset.insert({DNSName(), {{}, false}});
      return authOrForwDomain;
    }
    else {
      if (iter->second.shouldRecurse()) {
        // Again, picked up in doResolveAt. An empty DNSName, combined with a
        // non-empty vector of ComboAddresses means 'this is a forwarded domain'
        // This is actually picked up in retrieveAddressesForNS called from doResolveAt.
        nsset.insert({DNSName(), {iter->second.d_servers, true }});
        return authOrForwDomain;
      }
    }
  }

  // We might have a (non-recursive) forwarder, but maybe the cache already contains
  // a better NS
  vector<DNSRecord> bestns;
  DNSName nsFromCacheDomain(g_rootdnsname);
  getBestNSFromCache(qname, qtype, bestns, flawedNSSet, depth, beenthere);

  // Pick up the auth domain
  for (const auto& k : bestns) {
    const auto nsContent = getRR<NSRecordContent>(k);
    if (nsContent) {
      nsFromCacheDomain = k.d_name;
      break;
    }
  }

  if (iter != t_sstorage.domainmap->end()) {
    if (doLog()) {
      LOG(prefix << qname << " authOrForwDomain: " << authOrForwDomain << " nsFromCacheDomain: " << nsFromCacheDomain << " isPartof: " << authOrForwDomain.isPartOf(nsFromCacheDomain) << endl);
    }

    // If the forwarder is better or equal to what's found in the cache, use forwarder. Note that name.isPartOf(name).
    // So queries that get NS for authOrForwDomain itself go to the forwarder
    if (authOrForwDomain.isPartOf(nsFromCacheDomain)) {
      if (doLog()) {
        LOG(prefix << qname << ": using forwarder as NS" << endl);
      }
      nsset.insert({DNSName(), {iter->second.d_servers, false }});
      return authOrForwDomain;
    } else {
      if (doLog()) {
        LOG(prefix << qname << ": using NS from cache" << endl);
      }
    }
  }
  for (auto k = bestns.cbegin(); k != bestns.cend(); ++k) {
    // The actual resolver code will not even look at the ComboAddress or bool
    const auto nsContent = getRR<NSRecordContent>(*k);
    if (nsContent) {
      nsset.insert({nsContent->getNS(), {{}, false}});
    }
  }
  return nsFromCacheDomain;
}

void SyncRes::updateValidationStatusInCache(const DNSName &qname, const QType qt, bool aa, vState newState) const
{
  if (qt == QType::ANY || qt == QType::ADDR) {
    // not doing that
    return;
  }

  if (vStateIsBogus(newState)) {
    g_recCache->updateValidationStatus(d_now.tv_sec, qname, qt, d_cacheRemote, d_routingTag, aa, newState, s_maxbogusttl + d_now.tv_sec);
  }
  else {
    g_recCache->updateValidationStatus(d_now.tv_sec, qname, qt, d_cacheRemote, d_routingTag, aa, newState, boost::none);
  }
}

static bool scanForCNAMELoop(const DNSName& name, const vector<DNSRecord>& records)
{
  for (const auto& record: records) {
    if (record.d_type == QType::CNAME && record.d_place == DNSResourceRecord::ANSWER) {
      if (name == record.d_name) {
        return true;
      }
    }
  }
  return false;
}

bool SyncRes::doCNAMECacheCheck(const DNSName &qname, const QType qtype, vector<DNSRecord>& ret, unsigned int depth, int &res, vState& state, bool wasAuthZone, bool wasForwardRecurse)
{
  string prefix;
  if(doLog()) {
    prefix=d_prefix;
    prefix.append(depth, ' ');
  }

  if((depth>9 && d_outqueries>10 && d_throttledqueries>5) || depth > 15) {
    LOG(prefix<<qname<<": recursing (CNAME or other indirection) too deep, depth="<<depth<<endl);
    res=RCode::ServFail;
    return true;
  }

  vector<DNSRecord> cset;
  vector<std::shared_ptr<RRSIGRecordContent>> signatures;
  vector<std::shared_ptr<DNSRecord>> authorityRecs;
  bool wasAuth;
  uint32_t capTTL = std::numeric_limits<uint32_t>::max();
  DNSName foundName;
  DNSName authZone;
  QType foundQT = QType::ENT;

  /* we don't require auth data for forward-recurse lookups */
  MemRecursorCache::Flags flags = MemRecursorCache::None;
  if (!wasForwardRecurse && d_requireAuthData) {
    flags |= MemRecursorCache::RequireAuth;
  }
  if (d_refresh) {
    flags |= MemRecursorCache::Refresh;
  }
  if (d_serveStale) {
    flags |= MemRecursorCache::ServeStale;
  }
  if (g_recCache->get(d_now.tv_sec, qname, QType::CNAME, flags, &cset, d_cacheRemote, d_routingTag, d_doDNSSEC ? &signatures : nullptr, d_doDNSSEC ? &authorityRecs : nullptr, &d_wasVariable, &state, &wasAuth, &authZone, &d_fromAuthIP) > 0) {
    foundName = qname;
    foundQT = QType::CNAME;
  }

  if (foundName.empty() && qname != g_rootdnsname) {
    // look for a DNAME cache hit
    auto labels = qname.getRawLabels();
    DNSName dnameName(g_rootdnsname);

    do {
      dnameName.prependRawLabel(labels.back());
      labels.pop_back();
      if (dnameName == qname && qtype != QType::DNAME) { // The client does not want a DNAME, but we've reached the QNAME already. So there is no match
        break;
      }
      if (g_recCache->get(d_now.tv_sec, dnameName, QType::DNAME, flags, &cset, d_cacheRemote, d_routingTag, d_doDNSSEC ? &signatures : nullptr, d_doDNSSEC ? &authorityRecs : nullptr, &d_wasVariable, &state, &wasAuth, &authZone, &d_fromAuthIP) > 0) {
        foundName = dnameName;
        foundQT = QType::DNAME;
        break;
      }
    } while(!labels.empty());
  }

  if (foundName.empty()) {
    return false;
  }

  if (qtype == QType::DS && authZone == qname) {
    /* CNAME at APEX of the child zone, we can't use that to prove that
       there is no DS */
    LOG(prefix<<qname<<": Found a "<<foundQT.toString()<<" cache hit of '"<< qname <<"' from "<<authZone<<", but such a record at the apex of the child zone does not prove that there is no DS in the parent zone"<<endl);
    return false;
  }

  for(auto const &record : cset) {
    if (record.d_class != QClass::IN) {
      continue;
    }

    if(record.d_ttl > (unsigned int) d_now.tv_sec) {

      if (!wasAuthZone && shouldValidate() && (wasAuth || wasForwardRecurse) && state == vState::Indeterminate && d_requireAuthData) {
        /* This means we couldn't figure out the state when this entry was cached */

        vState recordState = getValidationStatus(foundName, !signatures.empty(), qtype == QType::DS, depth);
        if (recordState == vState::Secure) {
          LOG(prefix<<qname<<": got vState::Indeterminate state from the "<<foundQT.toString()<<" cache, validating.."<<endl);
          state = SyncRes::validateRecordsWithSigs(depth, qname, qtype, foundName, foundQT, cset, signatures);
          if (state != vState::Indeterminate) {
            LOG(prefix<<qname<<": got vState::Indeterminate state from the "<<foundQT.toString()<<" cache, new validation result is "<<state<<endl);
            if (vStateIsBogus(state)) {
              capTTL = s_maxbogusttl;
            }
            updateValidationStatusInCache(foundName, foundQT, wasAuth, state);
          }
        }
      }

      LOG(prefix<<qname<<": Found cache "<<foundQT.toString()<<" hit for '"<< foundName << "|"<<foundQT.toString()<<"' to '"<<record.d_content->getZoneRepresentation()<<"', validation state is "<<state<<endl);

      DNSRecord dr = record;
      dr.d_ttl -= d_now.tv_sec;
      dr.d_ttl = std::min(dr.d_ttl, capTTL);
      const uint32_t ttl = dr.d_ttl;
      ret.reserve(ret.size() + 2 + signatures.size() + authorityRecs.size());
      ret.push_back(dr);

      for(const auto& signature : signatures) {
        DNSRecord sigdr;
        sigdr.d_type=QType::RRSIG;
        sigdr.d_name=foundName;
        sigdr.d_ttl=ttl;
        sigdr.d_content=signature;
        sigdr.d_place=DNSResourceRecord::ANSWER;
        sigdr.d_class=QClass::IN;
        ret.push_back(sigdr);
      }

      for(const auto& rec : authorityRecs) {
        DNSRecord authDR(*rec);
        authDR.d_ttl=ttl;
        ret.push_back(authDR);
      }

      DNSName newTarget;
      if (foundQT == QType::DNAME) {
        if (qtype == QType::DNAME && qname == foundName) { // client wanted the DNAME, no need to synthesize a CNAME
          res = RCode::NoError;
          return true;
        }
        // Synthesize a CNAME
        auto dnameRR = getRR<DNAMERecordContent>(record);
        if (dnameRR == nullptr) {
          throw ImmediateServFailException("Unable to get record content for "+foundName.toLogString()+"|DNAME cache entry");
        }
        const auto& dnameSuffix = dnameRR->getTarget();
        DNSName targetPrefix = qname.makeRelative(foundName);
        try {
          dr.d_type = QType::CNAME;
          dr.d_name = targetPrefix + foundName;
          newTarget = targetPrefix + dnameSuffix;
          dr.d_content = std::make_shared<CNAMERecordContent>(CNAMERecordContent(newTarget));
          ret.push_back(dr);
        } catch (const std::exception &e) {
          // We should probably catch an std::range_error here and set the rcode to YXDOMAIN (RFC 6672, section 2.2)
          // But this is consistent with processRecords
          throw ImmediateServFailException("Unable to perform DNAME substitution(DNAME owner: '" + foundName.toLogString() +
              "', DNAME target: '" + dnameSuffix.toLogString() + "', substituted name: '" +
              targetPrefix.toLogString() + "." + dnameSuffix.toLogString() +
              "' : " + e.what());
        }

        LOG(prefix<<qname<<": Synthesized "<<dr.d_name<<"|CNAME "<<newTarget<<endl);
      }

      if(qtype == QType::CNAME) { // perhaps they really wanted a CNAME!
        res = RCode::NoError;
        return true;
      }

      if (qtype == QType::DS || qtype == QType::DNSKEY) {
        res = RCode::NoError;
        return true;
      }

      // We have a DNAME _or_ CNAME cache hit and the client wants something else than those two.
      // Let's find the answer!
      if (foundQT == QType::CNAME) {
        const auto cnameContent = getRR<CNAMERecordContent>(record);
        if (cnameContent == nullptr) {
          throw ImmediateServFailException("Unable to get record content for "+foundName.toLogString()+"|CNAME cache entry");
        }
        newTarget = cnameContent->getTarget();
      }

      if (qname == newTarget) {
        string msg = "got a CNAME referral (from cache) to self";
        LOG(prefix<<qname<<": "<<msg<<endl);
        throw ImmediateServFailException(msg);
      }

      if (newTarget.isPartOf(qname)) {
        // a.b.c. CNAME x.a.b.c will go to great depths with QM on
        string msg = "got a CNAME referral (from cache) to child, disabling QM";
        LOG(prefix<<qname<<": "<<msg<<endl);
        setQNameMinimization(false);
      }

      if (!d_followCNAME) {
        res = RCode::NoError;
        return true;
      }

      // Check to see if we already have seen the new target as a previous target
      if (scanForCNAMELoop(newTarget, ret)) {
        string msg = "got a CNAME referral (from cache) that causes a loop";
        LOG(prefix<<qname<<": status="<<msg<<endl);
        throw ImmediateServFailException(msg);
      }

      set<GetBestNSAnswer>beenthere;
      vState cnameState = vState::Indeterminate;
      // Be aware that going out on the network might be disabled (cache-only), for example because we are in QM Step0,
      // so you can't trust that a real lookup will have been made.
      res = doResolve(newTarget, qtype, ret, depth+1, beenthere, cnameState);
      LOG(prefix<<qname<<": updating validation state for response to "<<qname<<" from "<<state<<" with the state from the DNAME/CNAME quest: "<<cnameState<<endl);
      updateValidationState(state, cnameState);

      return true;
    }
  }
  throw ImmediateServFailException("Could not determine whether or not there was a CNAME or DNAME in cache for '" + qname.toLogString() + "'");
}

namespace {
struct CacheEntry
{
  vector<DNSRecord> records;
  vector<shared_ptr<RRSIGRecordContent>> signatures;
  uint32_t signaturesTTL{std::numeric_limits<uint32_t>::max()};
};
struct CacheKey
{
  DNSName name;
  QType type;
  DNSResourceRecord::Place place;
  bool operator<(const CacheKey& rhs) const {
    return std::tie(type, place, name) < std::tie(rhs.type, rhs.place, rhs.name);
  }
};
typedef map<CacheKey, CacheEntry> tcache_t;
}

static void reapRecordsFromNegCacheEntryForValidation(tcache_t& tcache, const vector<DNSRecord>& records)
{
  for (const auto& rec : records) {
    if (rec.d_type == QType::RRSIG) {
      auto rrsig = getRR<RRSIGRecordContent>(rec);
      if (rrsig) {
        tcache[{rec.d_name, rrsig->d_type, rec.d_place}].signatures.push_back(rrsig);
      }
    } else {
      tcache[{rec.d_name,rec.d_type,rec.d_place}].records.push_back(rec);
    }
  }
}

static bool negativeCacheEntryHasSOA(const NegCache::NegCacheEntry& ne)
{
  return !ne.authoritySOA.records.empty();
}

static void reapRecordsForValidation(std::map<QType, CacheEntry>& entries, const vector<DNSRecord>& records)
{
  for (const auto& rec : records) {
    entries[rec.d_type].records.push_back(rec);
  }
}

static void reapSignaturesForValidation(std::map<QType, CacheEntry>& entries, const vector<std::shared_ptr<RRSIGRecordContent>>& signatures)
{
  for (const auto& sig : signatures) {
    entries[sig->d_type].signatures.push_back(sig);
  }
}

/*!
 * Convenience function to push the records from records into ret with a new TTL
 *
 * \param records DNSRecords that need to go into ret
 * \param ttl     The new TTL for these records
 * \param ret     The vector of DNSRecords that should contain the records with the modified TTL
 */
static void addTTLModifiedRecords(vector<DNSRecord>& records, const uint32_t ttl, vector<DNSRecord>& ret) {
  for (auto& rec : records) {
    rec.d_ttl = ttl;
    ret.push_back(std::move(rec));
  }
}

void SyncRes::computeNegCacheValidationStatus(const NegCache::NegCacheEntry& ne, const DNSName& qname, const QType qtype, const int res, vState& state, unsigned int depth)
{
  tcache_t tcache;
  reapRecordsFromNegCacheEntryForValidation(tcache, ne.authoritySOA.records);
  reapRecordsFromNegCacheEntryForValidation(tcache, ne.authoritySOA.signatures);
  reapRecordsFromNegCacheEntryForValidation(tcache, ne.DNSSECRecords.records);
  reapRecordsFromNegCacheEntryForValidation(tcache, ne.DNSSECRecords.signatures);

  for (const auto& entry : tcache) {
    // this happens when we did store signatures, but passed on the records themselves
    if (entry.second.records.empty()) {
      continue;
    }

    const DNSName& owner = entry.first.name;

    vState recordState = getValidationStatus(owner, !entry.second.signatures.empty(), qtype == QType::DS, depth);
    if (state == vState::Indeterminate) {
      state = recordState;
    }

    if (recordState == vState::Secure) {
      recordState = SyncRes::validateRecordsWithSigs(depth, qname, qtype, owner, QType(entry.first.type), entry.second.records, entry.second.signatures);
    }

    if (recordState != vState::Indeterminate && recordState != state) {
      updateValidationState(state, recordState);
      if (state != vState::Secure) {
        break;
      }
    }
  }

  if (state == vState::Secure) {
    vState neValidationState = ne.d_validationState;
    dState expectedState = res == RCode::NXDomain ? dState::NXDOMAIN : dState::NXQTYPE;
    dState denialState = getDenialValidationState(ne, expectedState, false);
    updateDenialValidationState(neValidationState, ne.d_name, state, denialState, expectedState, qtype == QType::DS, depth);
  }
  if (state != vState::Indeterminate) {
    /* validation succeeded, let's update the cache entry so we don't have to validate again */
    boost::optional<time_t> capTTD = boost::none;
    if (vStateIsBogus(state)) {
      capTTD = d_now.tv_sec + s_maxbogusttl;
    }
    g_negCache->updateValidationStatus(ne.d_name, ne.d_qtype, state, capTTD);
  }
}

bool SyncRes::doCacheCheck(const DNSName &qname, const DNSName& authname, bool wasForwardedOrAuthZone, bool wasAuthZone, bool wasForwardRecurse, QType qtype, vector<DNSRecord>&ret, unsigned int depth, int &res, vState& state)
{
  bool giveNegative=false;

  string prefix;
  if(doLog()) {
    prefix=d_prefix;
    prefix.append(depth, ' ');
  }

  // sqname and sqtype are used contain 'higher' names if we have them (e.g. powerdns.com|SOA when we find a negative entry for doesnotexist.powerdns.com|A)
  DNSName sqname(qname);
  QType sqt(qtype);
  uint32_t sttl=0;
  //  cout<<"Lookup for '"<<qname<<"|"<<qtype.toString()<<"' -> "<<getLastLabel(qname)<<endl;
  vState cachedState;
  NegCache::NegCacheEntry ne;

  if(s_rootNXTrust &&
     g_negCache->getRootNXTrust(qname, d_now, ne, d_serveStale, d_refresh) &&
      ne.d_auth.isRoot() &&
      !(wasForwardedOrAuthZone && !authname.isRoot())) { // when forwarding, the root may only neg-cache if it was forwarded to.
    sttl = ne.d_ttd - d_now.tv_sec;
    LOG(prefix<<qname<<": Entire name '"<<qname<<"', is negatively cached via '"<<ne.d_auth<<"' & '"<<ne.d_name<<"' for another "<<sttl<<" seconds"<<endl);
    res = RCode::NXDomain;
    giveNegative = true;
    cachedState = ne.d_validationState;
  } else if (g_negCache->get(qname, qtype, d_now, ne, false, d_serveStale, d_refresh)) {
    /* If we are looking for a DS, discard NXD if auth == qname
       and ask for a specific denial instead */
    if (qtype != QType::DS || ne.d_qtype.getCode() || ne.d_auth != qname ||
        g_negCache->get(qname, qtype, d_now, ne, true, d_serveStale, d_refresh))
    {
      /* Careful! If the client is asking for a DS that does not exist, we need to provide the SOA along with the NSEC(3) proof
         and we might not have it if we picked up the proof from a delegation, in which case we need to keep on to do the actual DS
         query. */
      if (qtype == QType::DS && ne.d_qtype.getCode() && !d_externalDSQuery.empty() && qname == d_externalDSQuery && !negativeCacheEntryHasSOA(ne)) {
        giveNegative = false;
      }
      else {
        res = RCode::NXDomain;
        sttl = ne.d_ttd - d_now.tv_sec;
        giveNegative = true;
        cachedState = ne.d_validationState;
        if (ne.d_qtype.getCode()) {
          LOG(prefix<<qname<<": "<<qtype<<" is negatively cached via '"<<ne.d_auth<<"' for another "<<sttl<<" seconds"<<endl);
          res = RCode::NoError;
        } else {
          LOG(prefix<<qname<<": Entire name '"<<qname<<"' is negatively cached via '"<<ne.d_auth<<"' for another "<<sttl<<" seconds"<<endl);
        }
      }
    }
  } else if (s_hardenNXD != HardenNXD::No && !qname.isRoot() && !wasForwardedOrAuthZone) {
    auto labels = qname.getRawLabels();
    DNSName negCacheName(g_rootdnsname);
    negCacheName.prependRawLabel(labels.back());
    labels.pop_back();
    while(!labels.empty()) {
      if (g_negCache->get(negCacheName, QType::ENT, d_now, ne, true, d_serveStale, d_refresh)) {
        if (ne.d_validationState == vState::Indeterminate && validationEnabled()) {
          // LOG(prefix << negCacheName <<  " negatively cached and vState::Indeterminate, trying to validate NXDOMAIN" << endl);
          // ...
          // And get the updated ne struct
          //t_sstorage.negcache.get(negCacheName, QType(0), d_now, ne, true);
        }
        if ((s_hardenNXD == HardenNXD::Yes && !vStateIsBogus(ne.d_validationState)) || ne.d_validationState == vState::Secure) {
          res = RCode::NXDomain;
          sttl = ne.d_ttd - d_now.tv_sec;
          giveNegative = true;
          cachedState = ne.d_validationState;
          LOG(prefix<<qname<<": Name '"<<negCacheName<<"' and below, is negatively cached via '"<<ne.d_auth<<"' for another "<<sttl<<" seconds"<<endl);
          break;
        }
      }
      negCacheName.prependRawLabel(labels.back());
      labels.pop_back();
    }
  }

  if (giveNegative) {

    state = cachedState;

    if (!wasAuthZone && shouldValidate() && state == vState::Indeterminate) {
      LOG(prefix<<qname<<": got vState::Indeterminate state for records retrieved from the negative cache, validating.."<<endl);
      computeNegCacheValidationStatus(ne, qname, qtype, res, state, depth);

      if (state != cachedState && vStateIsBogus(state)) {
        sttl = std::min(sttl, s_maxbogusttl);
      }
    }

    // Transplant SOA to the returned packet
    addTTLModifiedRecords(ne.authoritySOA.records, sttl, ret);
    if(d_doDNSSEC) {
      addTTLModifiedRecords(ne.authoritySOA.signatures, sttl, ret);
      addTTLModifiedRecords(ne.DNSSECRecords.records, sttl, ret);
      addTTLModifiedRecords(ne.DNSSECRecords.signatures, sttl, ret);
    }

    LOG(prefix<<qname<<": updating validation state with negative cache content for "<<qname<<" to "<<state<<endl);
    return true;
  }

  vector<DNSRecord> cset;
  bool found=false, expired=false;
  vector<std::shared_ptr<RRSIGRecordContent>> signatures;
  vector<std::shared_ptr<DNSRecord>> authorityRecs;
  uint32_t ttl=0;
  uint32_t capTTL = std::numeric_limits<uint32_t>::max();
  bool wasCachedAuth;
  MemRecursorCache::Flags flags = MemRecursorCache::None;
  if (!wasForwardRecurse && d_requireAuthData) {
    flags |= MemRecursorCache::RequireAuth;
  }
  if (d_serveStale) {
    flags |= MemRecursorCache::ServeStale;
  }
  if (d_refresh) {
    flags |= MemRecursorCache::Refresh;
  }
  if(g_recCache->get(d_now.tv_sec, sqname, sqt, flags, &cset, d_cacheRemote, d_routingTag, d_doDNSSEC ? &signatures : nullptr, d_doDNSSEC ? &authorityRecs : nullptr, &d_wasVariable, &cachedState, &wasCachedAuth, nullptr, &d_fromAuthIP) > 0) {

    LOG(prefix<<sqname<<": Found cache hit for "<<sqt.toString()<<": ");

    if (!wasAuthZone && shouldValidate() && (wasCachedAuth || wasForwardRecurse) && cachedState == vState::Indeterminate && d_requireAuthData) {

      /* This means we couldn't figure out the state when this entry was cached */
      vState recordState = getValidationStatus(qname, !signatures.empty(), qtype == QType::DS, depth);

      if (recordState == vState::Secure) {
        LOG(prefix<<sqname<<": got vState::Indeterminate state from the cache, validating.."<<endl);
        if (sqt == QType::DNSKEY && sqname == getSigner(signatures)) {
          cachedState = validateDNSKeys(sqname, cset, signatures, depth);
        }
        else {
          if (sqt == QType::ANY) {
            std::map<QType, CacheEntry> types;
            reapRecordsForValidation(types, cset);
            reapSignaturesForValidation(types, signatures);

            for (const auto& type : types) {
              vState cachedRecordState;
              if (type.first == QType::DNSKEY && sqname == getSigner(type.second.signatures)) {
                cachedRecordState = validateDNSKeys(sqname, type.second.records, type.second.signatures, depth);
              }
              else {
                cachedRecordState = SyncRes::validateRecordsWithSigs(depth, qname, qtype, sqname, type.first, type.second.records, type.second.signatures);
              }
              updateDNSSECValidationState(cachedState, cachedRecordState);
            }
          }
          else {
            cachedState = SyncRes::validateRecordsWithSigs(depth, qname, qtype, sqname, sqt, cset, signatures);
          }
        }
      }
      else {
        cachedState = recordState;
      }

      if (cachedState != vState::Indeterminate) {
        LOG(prefix<<qname<<": got vState::Indeterminate state from the cache, validation result is "<<cachedState<<endl);
        if (vStateIsBogus(cachedState)) {
          capTTL = s_maxbogusttl;
        }
        if (sqt != QType::ANY && sqt != QType::ADDR) {
          updateValidationStatusInCache(sqname, sqt, wasCachedAuth, cachedState);
        }
      }
    }

    for(auto j=cset.cbegin() ; j != cset.cend() ; ++j) {

      LOG(j->d_content->getZoneRepresentation());

      if (j->d_class != QClass::IN) {
        continue;
      }

      if(j->d_ttl>(unsigned int) d_now.tv_sec) {
        DNSRecord dr=*j;
        dr.d_ttl -= d_now.tv_sec;
        dr.d_ttl = std::min(dr.d_ttl, capTTL);
        ttl = dr.d_ttl;
        ret.push_back(dr);
        LOG("[ttl="<<dr.d_ttl<<"] ");
        found=true;
      }
      else {
        LOG("[expired] ");
        expired=true;
      }
    }

    ret.reserve(ret.size() + signatures.size() + authorityRecs.size());

    for(const auto& signature : signatures) {
      DNSRecord dr;
      dr.d_type=QType::RRSIG;
      dr.d_name=sqname;
      dr.d_ttl=ttl;
      dr.d_content=signature;
      dr.d_place = DNSResourceRecord::ANSWER;
      dr.d_class=QClass::IN;
      ret.push_back(dr);
    }

    for(const auto& rec : authorityRecs) {
      DNSRecord dr(*rec);
      dr.d_ttl=ttl;
      ret.push_back(dr);
    }

    LOG(endl);
    if(found && !expired) {
      if (!giveNegative)
        res=0;
      LOG(prefix<<qname<<": updating validation state with cache content for "<<qname<<" to "<<cachedState<<endl);
      state = cachedState;
      return true;
    }
    else
      LOG(prefix<<qname<<": cache had only stale entries"<<endl);
  }

  /* let's check if we have a NSEC covering that record */
  if (g_aggressiveNSECCache && !wasForwardedOrAuthZone) {
    if (g_aggressiveNSECCache->getDenial(d_now.tv_sec, qname, qtype, ret, res, d_cacheRemote, d_routingTag, d_doDNSSEC, d_validationContext)) {
      state = vState::Secure;
      return true;
    }
  }

  return false;
}

bool SyncRes::moreSpecificThan(const DNSName& a, const DNSName &b) const
{
  return (a.isPartOf(b) && a.countLabels() > b.countLabels());
}

struct speedOrder
{
  bool operator()(const std::pair<DNSName, float> &a, const std::pair<DNSName, float> &b) const
  {
    return a.second < b.second;
  }
};

inline std::vector<std::pair<DNSName, float>> SyncRes::shuffleInSpeedOrder(NsSet &tnameservers, const string &prefix)
{
  std::vector<std::pair<DNSName, float>> rnameservers;
  rnameservers.reserve(tnameservers.size());
  for(const auto& tns: tnameservers) {
    float speed = s_nsSpeeds.lock()->fastest(tns.first, d_now);
    rnameservers.emplace_back(tns.first, speed);
    if(tns.first.empty()) // this was an authoritative OOB zone, don't pollute the nsSpeeds with that
      return rnameservers;
  }

  shuffle(rnameservers.begin(),rnameservers.end(), pdns::dns_random_engine());
  speedOrder so;
  stable_sort(rnameservers.begin(),rnameservers.end(), so);

  if(doLog()) {
    LOG(prefix<<"Nameservers: ");
    for(auto i=rnameservers.begin();i!=rnameservers.end();++i) {
      if(i!=rnameservers.begin()) {
        LOG(", ");
        if(!((i-rnameservers.begin())%3)) {
          LOG(endl<<prefix<<"             ");
        }
      }
      LOG(i->first.toLogString()<<"(" << fmtfloat("%0.2f", i->second/1000.0) <<"ms)");
    }
    LOG(endl);
  }
  return rnameservers;
}

inline vector<ComboAddress> SyncRes::shuffleForwardSpeed(const vector<ComboAddress> &rnameservers, const string &prefix, const bool wasRd)
{
  vector<ComboAddress> nameservers = rnameservers;
  map<ComboAddress, float> speeds;

  for(const auto& val: nameservers) {
    DNSName nsName = DNSName(val.toStringWithPort());
    float speed = s_nsSpeeds.lock()->fastest(nsName, d_now);
    speeds[val] = speed;
  }
  shuffle(nameservers.begin(),nameservers.end(), pdns::dns_random_engine());
  speedOrderCA so(speeds);
  stable_sort(nameservers.begin(),nameservers.end(), so);

  if(doLog()) {
    LOG(prefix<<"Nameservers: ");
    for(vector<ComboAddress>::const_iterator i=nameservers.cbegin();i!=nameservers.cend();++i) {
      if(i!=nameservers.cbegin()) {
        LOG(", ");
        if(!((i-nameservers.cbegin())%3)) {
          LOG(endl<<prefix<<"             ");
        }
      }
      LOG((wasRd ? string("+") : string("-")) << i->toStringWithPort() <<"(" << fmtfloat("%0.2f", speeds[*i]/1000.0) <<"ms)");
    }
    LOG(endl);
  }
  return nameservers;
}

static uint32_t getRRSIGTTL(const time_t now, const std::shared_ptr<RRSIGRecordContent>& rrsig)
{
  uint32_t res = 0;
  if (now < rrsig->d_sigexpire) {
    res = static_cast<uint32_t>(rrsig->d_sigexpire) - now;
  }
  return res;
}

static const set<QType> nsecTypes = {QType::NSEC, QType::NSEC3};

/* Fills the authoritySOA and DNSSECRecords fields from ne with those found in the records
 *
 * \param records The records to parse for the authority SOA and NSEC(3) records
 * \param ne      The NegCacheEntry to be filled out (will not be cleared, only appended to
 */
static void harvestNXRecords(const vector<DNSRecord>& records, NegCache::NegCacheEntry& ne, const time_t now, uint32_t* lowestTTL) {
  for (const auto& rec : records) {
    if (rec.d_place != DNSResourceRecord::AUTHORITY) {
      // RFC 4035 section 3.1.3. indicates that NSEC records MUST be placed in
      // the AUTHORITY section. Section 3.1.1 indicates that that RRSIGs for
      // records MUST be in the same section as the records they cover.
      // Hence, we ignore all records outside of the AUTHORITY section.
      continue;
    }

    if (rec.d_type == QType::RRSIG) {
      auto rrsig = getRR<RRSIGRecordContent>(rec);
      if (rrsig) {
        if (rrsig->d_type == QType::SOA) {
          ne.authoritySOA.signatures.push_back(rec);
          if (lowestTTL && isRRSIGNotExpired(now, rrsig)) {
            *lowestTTL = min(*lowestTTL, rec.d_ttl);
            *lowestTTL = min(*lowestTTL, getRRSIGTTL(now, rrsig));
          }
        }
        if (nsecTypes.count(rrsig->d_type)) {
          ne.DNSSECRecords.signatures.push_back(rec);
          if (lowestTTL && isRRSIGNotExpired(now, rrsig)) {
            *lowestTTL = min(*lowestTTL, rec.d_ttl);
            *lowestTTL = min(*lowestTTL, getRRSIGTTL(now, rrsig));
          }
        }
      }
      continue;
    }
    if (rec.d_type == QType::SOA) {
      ne.authoritySOA.records.push_back(rec);
      if (lowestTTL) {
        *lowestTTL = min(*lowestTTL, rec.d_ttl);
      }
      continue;
    }
    if (nsecTypes.count(rec.d_type)) {
      ne.DNSSECRecords.records.push_back(rec);
      if (lowestTTL) {
        *lowestTTL = min(*lowestTTL, rec.d_ttl);
      }
      continue;
    }
  }
}

static cspmap_t harvestCSPFromNE(const NegCache::NegCacheEntry& ne)
{
  cspmap_t cspmap;
  for(const auto& rec : ne.DNSSECRecords.signatures) {
    if(rec.d_type == QType::RRSIG) {
      auto rrc = getRR<RRSIGRecordContent>(rec);
      if (rrc) {
        cspmap[{rec.d_name,rrc->d_type}].signatures.push_back(rrc);
      }
    }
  }
  for(const auto& rec : ne.DNSSECRecords.records) {
    cspmap[{rec.d_name, rec.d_type}].records.insert(rec.d_content);
  }
  return cspmap;
}

// TODO remove after processRecords is fixed!
// Adds the RRSIG for the SOA and the NSEC(3) + RRSIGs to ret
static void addNXNSECS(vector<DNSRecord>&ret, const vector<DNSRecord>& records)
{
  NegCache::NegCacheEntry ne;
  harvestNXRecords(records, ne, 0, nullptr);
  ret.insert(ret.end(), ne.authoritySOA.signatures.begin(), ne.authoritySOA.signatures.end());
  ret.insert(ret.end(), ne.DNSSECRecords.records.begin(), ne.DNSSECRecords.records.end());
  ret.insert(ret.end(), ne.DNSSECRecords.signatures.begin(), ne.DNSSECRecords.signatures.end());
}

static bool rpzHitShouldReplaceContent(const DNSName& qname, const QType qtype, const std::vector<DNSRecord>& records)
{
  if (qtype == QType::CNAME) {
    return true;
  }

  for (const auto& record : records) {
    if (record.d_type == QType::CNAME) {
      if (auto content = getRR<CNAMERecordContent>(record)) {
        if (qname == content->getTarget()) {
          /* we have a CNAME whose target matches the entry we are about to
             generate, so it will complete the current records, not replace
             them
          */
          return false;
        }
      }
    }
  }

  return true;
}

static void removeConflictingRecord(std::vector<DNSRecord>& records, const DNSName& name, const QType dtype)
{
  for (auto it = records.begin(); it != records.end(); ) {
    bool remove = false;

    if (it->d_class == QClass::IN &&
        (it->d_type == QType::CNAME || dtype == QType::CNAME || it->d_type == dtype) &&
        it->d_name == name) {
      remove = true;
    }
    else if (it->d_class == QClass::IN &&
             it->d_type == QType::RRSIG &&
             it->d_name == name) {
      if (auto rrc = getRR<RRSIGRecordContent>(*it)) {
        if (rrc->d_type == QType::CNAME || rrc->d_type == dtype) {
          /* also remove any RRSIG that could conflict */
          remove = true;
        }
      }
    }

    if (remove) {
      it = records.erase(it);
    }
    else {
      ++it;
    }
  }
}

void SyncRes::handlePolicyHit(const std::string& prefix, const DNSName& qname, const QType qtype, std::vector<DNSRecord>& ret, bool& done, int& rcode, unsigned int depth)
{
  if (d_pdl && d_pdl->policyHitEventFilter(d_requestor, qname, qtype, d_queryReceivedOverTCP, d_appliedPolicy, d_policyTags, d_discardedPolicies)) {
    /* reset to no match */
    d_appliedPolicy = DNSFilterEngine::Policy();
    return;
  }

  /* don't account truncate actions for TCP queries, since they are not applied */
  if (d_appliedPolicy.d_kind != DNSFilterEngine::PolicyKind::Truncate || !d_queryReceivedOverTCP) {
    ++g_stats.policyResults[d_appliedPolicy.d_kind];
    ++(g_stats.policyHits.lock()->operator[](d_appliedPolicy.getName()));
  }

  if (d_appliedPolicy.d_type != DNSFilterEngine::PolicyType::None) {
    LOG(prefix << qname << "|" << qtype << d_appliedPolicy.getLogString() << endl);
  }

  switch (d_appliedPolicy.d_kind) {

  case DNSFilterEngine::PolicyKind::NoAction:
      return;

  case DNSFilterEngine::PolicyKind::Drop:
    ++g_stats.policyDrops;
    throw ImmediateQueryDropException();

  case DNSFilterEngine::PolicyKind::NXDOMAIN:
    ret.clear();
    rcode = RCode::NXDomain;
    done = true;
    return;

  case DNSFilterEngine::PolicyKind::NODATA:
    ret.clear();
    rcode = RCode::NoError;
    done = true;
    return;

  case DNSFilterEngine::PolicyKind::Truncate:
    if (!d_queryReceivedOverTCP) {
      ret.clear();
      rcode = RCode::NoError;
      throw SendTruncatedAnswerException();
    }
    return;

  case DNSFilterEngine::PolicyKind::Custom:
    {
      if (rpzHitShouldReplaceContent(qname, qtype, ret)) {
        ret.clear();
      }

      rcode = RCode::NoError;
      done = true;
      auto spoofed = d_appliedPolicy.getCustomRecords(qname, qtype.getCode());
      for (auto& dr : spoofed) {
        removeConflictingRecord(ret, dr.d_name, dr.d_type);
      }

      for (auto& dr : spoofed) {
        ret.push_back(dr);

        if (dr.d_name == qname && dr.d_type == QType::CNAME && qtype != QType::CNAME) {
          if (auto content = getRR<CNAMERecordContent>(dr)) {
            vState newTargetState = vState::Indeterminate;
            handleNewTarget(prefix, qname, content->getTarget(), qtype.getCode(), ret, rcode, depth, {}, newTargetState);
          }
        }
      }
    }
  }
}

bool SyncRes::nameserversBlockedByRPZ(const DNSFilterEngine& dfe, const NsSet& nameservers)
{
  /* we skip RPZ processing if:
     - it was disabled (d_wantsRPZ is false) ;
     - we already got a RPZ hit (d_appliedPolicy.d_type != DNSFilterEngine::PolicyType::None) since
     the only way we can get back here is that it was a 'pass-thru' (NoAction) meaning that we should not
     process any further RPZ rules. Except that we need to process rules of higher priority..
  */
  if (d_wantsRPZ && !d_appliedPolicy.wasHit()) {
    for (auto const &ns : nameservers) {
      bool match = dfe.getProcessingPolicy(ns.first, d_discardedPolicies, d_appliedPolicy);
      if (match) {
        mergePolicyTags(d_policyTags, d_appliedPolicy.getTags());
        if (d_appliedPolicy.d_kind != DNSFilterEngine::PolicyKind::NoAction) { // client query needs an RPZ response
          LOG(", however nameserver "<<ns.first<<" was blocked by RPZ policy '"<<d_appliedPolicy.getName()<<"'"<<endl);
          return true;
        }
      }

      // Traverse all IP addresses for this NS to see if they have an RPN NSIP policy
      for (auto const &address : ns.second.first) {
        match = dfe.getProcessingPolicy(address, d_discardedPolicies, d_appliedPolicy);
        if (match) {
          mergePolicyTags(d_policyTags, d_appliedPolicy.getTags());
          if (d_appliedPolicy.d_kind != DNSFilterEngine::PolicyKind::NoAction) { // client query needs an RPZ response
            LOG(", however nameserver "<<ns.first<<" IP address "<<address.toString()<<" was blocked by RPZ policy '"<<d_appliedPolicy.getName()<<"'"<<endl);
            return true;
          }
        }
      }
    }
  }
  return false;
}

bool SyncRes::nameserverIPBlockedByRPZ(const DNSFilterEngine& dfe, const ComboAddress& remoteIP)
{
  /* we skip RPZ processing if:
     - it was disabled (d_wantsRPZ is false) ;
     - we already got a RPZ hit (d_appliedPolicy.d_type != DNSFilterEngine::PolicyType::None) since
     the only way we can get back here is that it was a 'pass-thru' (NoAction) meaning that we should not
     process any further RPZ rules. Except that we need to process rules of higher priority..
  */
  if (d_wantsRPZ && !d_appliedPolicy.wasHit()) {
    bool match = dfe.getProcessingPolicy(remoteIP, d_discardedPolicies, d_appliedPolicy);
    if (match) {
      mergePolicyTags(d_policyTags, d_appliedPolicy.getTags());
      if (d_appliedPolicy.d_kind != DNSFilterEngine::PolicyKind::NoAction) {
        LOG(" (blocked by RPZ policy '" + d_appliedPolicy.getName() + "')");
        return true;
      }
    }
  }
  return false;
}

vector<ComboAddress> SyncRes::retrieveAddressesForNS(const std::string& prefix, const DNSName& qname, std::vector<std::pair<DNSName, float>>::const_iterator& tns, const unsigned int depth, set<GetBestNSAnswer>& beenthere, const vector<std::pair<DNSName, float>>& rnameservers, NsSet& nameservers, bool& sendRDQuery, bool& pierceDontQuery, bool& flawedNSSet, bool cacheOnly, unsigned int &nretrieveAddressesForNS)
{
  vector<ComboAddress> result;

  size_t nonresolvingfails = 0;
  if (!tns->first.empty()) {
    if (s_nonresolvingnsmaxfails > 0) {
      nonresolvingfails = s_nonresolving.lock()->value(tns->first);
      if (nonresolvingfails >= s_nonresolvingnsmaxfails) {
        LOG(prefix<<qname<<": NS "<<tns->first<< " in non-resolving map, skipping"<<endl);
        return result;
      }
    }

    LOG(prefix<<qname<<": Trying to resolve NS '"<<tns->first<< "' ("<<1+tns-rnameservers.begin()<<"/"<<(unsigned int)rnameservers.size()<<")"<<endl);
    const unsigned int oldOutQueries = d_outqueries;
    try {
      result = getAddrs(tns->first, depth, beenthere, cacheOnly, nretrieveAddressesForNS);
    }
    // Other exceptions should likely not throttle...
    catch (const ImmediateServFailException& ex) {
      if (s_nonresolvingnsmaxfails > 0 && d_outqueries > oldOutQueries) {
        auto dontThrottleNames = g_dontThrottleNames.getLocal();
        if (!dontThrottleNames->check(tns->first)) {
          s_nonresolving.lock()->incr(tns->first, d_now);
        }
      }
      throw ex;
    }
    if (s_nonresolvingnsmaxfails > 0 && d_outqueries > oldOutQueries) {
      if (result.empty()) {
        auto dontThrottleNames = g_dontThrottleNames.getLocal();
        if (!dontThrottleNames->check(tns->first)) {
          s_nonresolving.lock()->incr(tns->first, d_now);
        }
      }
      else if (nonresolvingfails > 0) {
        // Succeeding resolve, clear memory of recent failures
        s_nonresolving.lock()->clear(tns->first);
      }
    }
    pierceDontQuery=false;
  }
  else {
    LOG(prefix<<qname<<": Domain has hardcoded nameserver");

    if(nameservers[tns->first].first.size() > 1) {
      LOG("s");
    }
    LOG(endl);

    sendRDQuery = nameservers[tns->first].second;
    result = shuffleForwardSpeed(nameservers[tns->first].first, doLog() ? (prefix+qname.toString()+": ") : string(), sendRDQuery);
    pierceDontQuery=true;
  }
  return result;
}

void SyncRes::checkMaxQperQ(const DNSName& qname) const
{
  if (d_outqueries + d_throttledqueries > s_maxqperq) {
    throw ImmediateServFailException("more than " + std::to_string(s_maxqperq) + " (max-qperq) queries sent or throttled while resolving " + qname.toLogString());
  }
}

bool SyncRes::throttledOrBlocked(const std::string& prefix, const ComboAddress& remoteIP, const DNSName& qname, const QType qtype, bool pierceDontQuery)
{
  if (isThrottled(d_now.tv_sec, remoteIP)) {
    LOG(prefix<<qname<<": server throttled "<<endl);
    s_throttledqueries++; d_throttledqueries++;
    return true;
  }
  else if (isThrottled(d_now.tv_sec, remoteIP, qname, qtype)) {
    LOG(prefix<<qname<<": query throttled "<<remoteIP.toString()<<", "<<qname<<"; "<<qtype<<endl);
    s_throttledqueries++; d_throttledqueries++;
    return true;
  }
  else if(!pierceDontQuery && s_dontQuery && s_dontQuery->match(&remoteIP)) {
    // We could have retrieved an NS from the cache in a forwarding domain
    // Even in the case of !pierceDontQuery we still want to allow that NS
    DNSName forwardCandidate(qname);
    auto it = getBestAuthZone(&forwardCandidate);
    if (it == t_sstorage.domainmap->end()) {
      LOG(prefix<<qname<<": not sending query to " << remoteIP.toString() << ", blocked by 'dont-query' setting" << endl);
      s_dontqueries++;
      return true;
    } else {
      // The name (from the cache) is forwarded, but is it forwarded to an IP in known forwarders?
      const auto& ips = it->second.d_servers;
      if (std::find(ips.cbegin(), ips.cend(), remoteIP) == ips.cend()) {
        LOG(prefix<<qname<<": not sending query to " << remoteIP.toString() << ", blocked by 'dont-query' setting" << endl);
        s_dontqueries++;
        return true;
      } else {
        LOG(prefix<<qname<<": sending query to " << remoteIP.toString() << ", blocked by 'dont-query' but a forwarding/auth case" << endl);
      }
    }
  }
  return false;
}

bool SyncRes::validationEnabled() const
{
  return g_dnssecmode != DNSSECMode::Off && g_dnssecmode != DNSSECMode::ProcessNoValidate;
}

uint32_t SyncRes::computeLowestTTD(const std::vector<DNSRecord>& records, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures, uint32_t signaturesTTL, const std::vector<std::shared_ptr<DNSRecord>>& authorityRecs) const
{
  uint32_t lowestTTD = std::numeric_limits<uint32_t>::max();
  for (const auto& record : records) {
    lowestTTD = min(lowestTTD, record.d_ttl);
  }

  /* even if it was not requested for that request (Process, and neither AD nor DO set),
     it might be requested at a later time so we need to be careful with the TTL. */
  if (validationEnabled() && !signatures.empty()) {
    /* if we are validating, we don't want to cache records after their signatures expire. */
    /* records TTL are now TTD, let's add 'now' to the signatures lowest TTL */
    lowestTTD = min(lowestTTD, static_cast<uint32_t>(signaturesTTL + d_now.tv_sec));

    for(const auto& sig : signatures) {
      if (isRRSIGNotExpired(d_now.tv_sec, sig)) {
        // we don't decrement d_sigexpire by 'now' because we actually want a TTD, not a TTL */
        lowestTTD = min(lowestTTD, static_cast<uint32_t>(sig->d_sigexpire));
      }
    }
  }

  for (const auto& entry : authorityRecs) {
    /* be careful, this is still a TTL here */
    lowestTTD = min(lowestTTD, static_cast<uint32_t>(entry->d_ttl + d_now.tv_sec));

    if (entry->d_type == QType::RRSIG && validationEnabled()) {
      auto rrsig = getRR<RRSIGRecordContent>(*entry);
      if (rrsig) {
        if (isRRSIGNotExpired(d_now.tv_sec, rrsig)) {
          // we don't decrement d_sigexpire by 'now' because we actually want a TTD, not a TTL */
          lowestTTD = min(lowestTTD, static_cast<uint32_t>(rrsig->d_sigexpire));
        }
      }
    }
  }

  return lowestTTD;
}

void SyncRes::updateValidationState(vState& state, const vState stateUpdate)
{
  LOG(d_prefix<<"validation state was "<<state<<", state update is "<<stateUpdate);
  updateDNSSECValidationState(state, stateUpdate);
  LOG(", validation state is now "<<state<<endl);
}

vState SyncRes::getTA(const DNSName& zone, dsmap_t& ds)
{
  auto luaLocal = g_luaconfs.getLocal();

  if (luaLocal->dsAnchors.empty()) {
    LOG(d_prefix<<": No trust anchors configured, everything is Insecure"<<endl);
    /* We have no TA, everything is insecure */
    return vState::Insecure;
  }

  std::string reason;
  if (haveNegativeTrustAnchor(luaLocal->negAnchors, zone, reason)) {
    LOG(d_prefix<<": got NTA for '"<<zone<<"'"<<endl);
    return vState::NTA;
  }

  if (getTrustAnchor(luaLocal->dsAnchors, zone, ds)) {
    LOG(d_prefix<<": got TA for '"<<zone<<"'"<<endl);
    return vState::TA;
  }
  else {
    LOG(d_prefix<<": no TA found for '"<<zone<<"' among "<< luaLocal->dsAnchors.size()<<endl);
  }

  if (zone.isRoot()) {
    /* No TA for the root */
    return vState::Insecure;
  }

  return vState::Indeterminate;
}

static size_t countSupportedDS(const dsmap_t& dsmap)
{
  size_t count = 0;

  for (const auto& ds : dsmap) {
    if (isSupportedDS(ds)) {
      count++;
    }
  }

  return count;
}

void SyncRes::initZoneCutsFromTA(const DNSName& from)
{
  DNSName zone(from);
  do {
    dsmap_t ds;
    vState result = getTA(zone, ds);
    if (result != vState::Indeterminate) {
      if (result == vState::TA) {
        if (countSupportedDS(ds) == 0) {
          ds.clear();
          result = vState::Insecure;
        }
        else {
          result = vState::Secure;
        }
      }
      else if (result == vState::NTA) {
        result = vState::Insecure;
      }

      d_cutStates[zone] = result;
    }
  }
  while (zone.chopOff());
}

vState SyncRes::getDSRecords(const DNSName& zone, dsmap_t& ds, bool taOnly, unsigned int depth, bool bogusOnNXD, bool* foundCut)
{
  vState result = getTA(zone, ds);

  if (result != vState::Indeterminate || taOnly) {
    if (foundCut) {
      *foundCut = (result != vState::Indeterminate);
    }

    if (result == vState::TA) {
      if (countSupportedDS(ds) == 0) {
        ds.clear();
        result = vState::Insecure;
      }
      else {
        result = vState::Secure;
      }
    }
    else if (result == vState::NTA) {
      result = vState::Insecure;
    }

    return result;
  }

  std::set<GetBestNSAnswer> beenthere;
  std::vector<DNSRecord> dsrecords;

  vState state = vState::Indeterminate;
  const bool oldCacheOnly = setCacheOnly(false);
  const bool oldQM = setQNameMinimization(!getQMFallbackMode());
  int rcode = doResolve(zone, QType::DS, dsrecords, depth + 1, beenthere, state);
  setCacheOnly(oldCacheOnly);
  setQNameMinimization(oldQM);

  if (rcode == RCode::ServFail) {
    throw ImmediateServFailException("Server Failure while retrieving DS records for " + zone.toLogString());
  }

  if (rcode == RCode::NoError || (rcode == RCode::NXDomain && !bogusOnNXD)) {
    uint8_t bestDigestType = 0;

    bool gotCNAME = false;
    for (const auto& record : dsrecords) {
      if (record.d_type == QType::DS) {
        const auto dscontent = getRR<DSRecordContent>(record);
        if (dscontent && isSupportedDS(*dscontent)) {
          // Make GOST a lower prio than SHA256
          if (dscontent->d_digesttype == DNSSECKeeper::DIGEST_GOST && bestDigestType == DNSSECKeeper::DIGEST_SHA256) {
            continue;
          }
          if (dscontent->d_digesttype > bestDigestType || (bestDigestType == DNSSECKeeper::DIGEST_GOST && dscontent->d_digesttype == DNSSECKeeper::DIGEST_SHA256)) {
            bestDigestType = dscontent->d_digesttype;
          }
          ds.insert(*dscontent);
        }
      }
      else if (record.d_type == QType::CNAME && record.d_name == zone) {
        gotCNAME = true;
      }
    }

    /* RFC 4509 section 3: "Validator implementations SHOULD ignore DS RRs containing SHA-1
     * digests if DS RRs with SHA-256 digests are present in the DS RRset."
     * We interpret that as: do not use SHA-1 if SHA-256 or SHA-384 is available
     */
    for (auto dsrec = ds.begin(); dsrec != ds.end(); ) {
      if (dsrec->d_digesttype == DNSSECKeeper::DIGEST_SHA1 && dsrec->d_digesttype != bestDigestType) {
        dsrec = ds.erase(dsrec);
      }
      else {
        ++dsrec;
      }
    }

    if (rcode == RCode::NoError) {
      if (ds.empty()) {
        /* we have no DS, it's either:
           - a delegation to a non-DNSSEC signed zone
           - no delegation, we stay in the same zone
        */
        if (gotCNAME || denialProvesNoDelegation(zone, dsrecords, d_validationContext)) {
          /* we are still inside the same zone */

          if (foundCut) {
            *foundCut = false;
          }
          return state;
        }

        d_cutStates[zone] = state == vState::Secure ? vState::Insecure : state;
        /* delegation with no DS, might be Secure -> Insecure */
        if (foundCut) {
          *foundCut = true;
        }

        /* a delegation with no DS is either:
           - a signed zone (Secure) to an unsigned one (Insecure)
           - an unsigned zone to another unsigned one (Insecure stays Insecure, Bogus stays Bogus)
        */
        return state == vState::Secure ? vState::Insecure : state;
      } else {
        /* we have a DS */
        d_cutStates[zone] = state;
        if (foundCut) {
          *foundCut = true;
        }
      }
    }

    return state;
  }

  LOG(d_prefix<<": returning Bogus state from "<<__func__<<"("<<zone<<")"<<endl);
  return vState::BogusUnableToGetDSs;
}

vState SyncRes::getValidationStatus(const DNSName& name, bool wouldBeValid, bool typeIsDS, unsigned int depth)
{
  vState result = vState::Indeterminate;

  if (!shouldValidate()) {
    return result;
  }

  DNSName subdomain(name);
  if (typeIsDS) {
    subdomain.chopOff();
  }

  {
    const auto& it = d_cutStates.find(subdomain);
    if (it != d_cutStates.cend()) {
      LOG(d_prefix<<": got status "<<it->second<<" for name "<<subdomain<<endl);
      return it->second;
    }
  }

  /* look for the best match we have */
  DNSName best(subdomain);
  while (best.chopOff()) {
    const auto& it = d_cutStates.find(best);
    if (it != d_cutStates.cend()) {
      result = it->second;
      if (vStateIsBogus(result) || result == vState::Insecure) {
        LOG(d_prefix<<": got status "<<result<<" for name "<<best<<endl);
        return result;
      }
      break;
    }
  }

  /* by now we have the best match, it's likely Secure (otherwise we would not be there)
     but we don't know if we missed a cut (or several).
     We could see if we have DS (or denial of) in cache but let's not worry for now,
     we will if we don't have a signature, or if the signer doesn't match what we expect */
  if (!wouldBeValid && best != subdomain) {
    /* no signatures or Bogus, we likely missed a cut, let's try to find it */
    LOG(d_prefix<<": no or invalid signature/proof for "<<name<<", we likely missed a cut between "<<best<<" and "<<subdomain<<", looking for it"<<endl);
    DNSName ds(best);
    std::vector<string> labelsToAdd = subdomain.makeRelative(ds).getRawLabels();

    while (!labelsToAdd.empty()) {

      ds.prependRawLabel(labelsToAdd.back());
      labelsToAdd.pop_back();
      LOG(d_prefix<<": - Looking for a DS at "<<ds<<endl);

      bool foundCut = false;
      dsmap_t results;
      vState dsState = getDSRecords(ds, results, false, depth, false, &foundCut);

      if (foundCut) {
        LOG(d_prefix<<": - Found cut at "<<ds<<endl);
        LOG(d_prefix<<": New state for "<<ds<<" is "<<dsState<<endl);
        d_cutStates[ds] = dsState;

        if (dsState != vState::Secure) {
          return dsState;
        }
      }
    }

    /* we did not miss a cut, good luck */
    return result;
  }

#if 0
  /* we don't need this, we actually do the right thing later */
  DNSName signer = getSigner(signatures);

  if (!signer.empty() && name.isPartOf(signer)) {
    if (signer == best) {
      return result;
    }
    /* the zone cut is not the one we expected,
       this is fine because we will retrieve the needed DNSKEYs and DSs
       later, and even go Insecure if we missed a cut to Insecure (no DS)
       and the signatures do not validate (we should not go Bogus in that
       case) */
  }
  /* something is not right, but let's not worry about that for now.. */
#endif

  return result;
}

vState SyncRes::validateDNSKeys(const DNSName& zone, const std::vector<DNSRecord>& dnskeys, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures, unsigned int depth)
{
  dsmap_t ds;
  if (signatures.empty()) {
    LOG(d_prefix<<": we have "<<std::to_string(dnskeys.size())<<" DNSKEYs but no signature, going Bogus!"<<endl);
    return vState::BogusNoRRSIG;
  }

  DNSName signer = getSigner(signatures);

  if (!signer.empty() && zone.isPartOf(signer)) {
    vState state = getDSRecords(signer, ds, false, depth);

    if (state != vState::Secure) {
      return state;
    }
  }
  else {
    LOG(d_prefix<<": we have "<<std::to_string(dnskeys.size())<<" DNSKEYs but the zone ("<<zone<<") is not part of the signer ("<<signer<<"), check that we did not miss a zone cut"<<endl);
    /* try again to get the missed cuts, harder this time */
    auto zState = getValidationStatus(zone, false, false, depth);
    if (zState == vState::Secure) {
      /* too bad */
      LOG(d_prefix<<": after checking the zone cuts again, we still have "<<std::to_string(dnskeys.size())<<" DNSKEYs and the zone ("<<zone<<") is still not part of the signer ("<<signer<<"), going Bogus!"<<endl);
      return vState::BogusNoValidRRSIG;
    }
    else {
      return zState;
    }
  }

  skeyset_t tentativeKeys;
  sortedRecords_t toSign;

  for (const auto& dnskey : dnskeys) {
    if (dnskey.d_type == QType::DNSKEY) {
      auto content = getRR<DNSKEYRecordContent>(dnskey);
      if (content) {
        tentativeKeys.insert(content);
        toSign.insert(content);
      }
    }
  }

  LOG(d_prefix<<": trying to validate "<<std::to_string(tentativeKeys.size())<<" DNSKEYs with "<<std::to_string(ds.size())<<" DS"<<endl);
  skeyset_t validatedKeys;
  auto state = validateDNSKeysAgainstDS(d_now.tv_sec, zone, ds, tentativeKeys, toSign, signatures, validatedKeys, d_validationContext);
  if (s_maxvalidationsperq != 0 && d_validationContext.d_validationsCounter > s_maxvalidationsperq) {
   throw ImmediateServFailException("Server Failure while validating DNSKEYs, too many signature validations for this query");
 }

  LOG(d_prefix<<": we now have "<<std::to_string(validatedKeys.size())<<" DNSKEYs"<<endl);

  /* if we found at least one valid RRSIG covering the set,
     all tentative keys are validated keys. Otherwise it means
     we haven't found at least one DNSKEY and a matching RRSIG
     covering this set, this looks Bogus. */
  if (validatedKeys.size() != tentativeKeys.size()) {
    LOG(d_prefix<<": let's check whether we missed a zone cut before returning a Bogus state from "<<__func__<<"("<<zone<<")"<<endl);
    /* try again to get the missed cuts, harder this time */
    auto zState = getValidationStatus(zone, false, false, depth);
    if (zState == vState::Secure) {
      /* too bad */
      LOG(d_prefix<<": after checking the zone cuts we are still in a Secure zone, returning Bogus state from "<<__func__<<"("<<zone<<")"<<endl);
      return state;
    }
    else {
      return zState;
    }
  }

  return state;
}

vState SyncRes::getDNSKeys(const DNSName& signer, skeyset_t& keys, bool& servFailOccurred, unsigned int depth)
{
  std::vector<DNSRecord> records;
  std::set<GetBestNSAnswer> beenthere;
  LOG(d_prefix<<"Retrieving DNSKeys for "<<signer<<endl);

  vState state = vState::Indeterminate;
  const bool oldCacheOnly = setCacheOnly(false);
  int rcode = doResolve(signer, QType::DNSKEY, records, depth + 1, beenthere, state);
  setCacheOnly(oldCacheOnly);

  if (rcode == RCode::ServFail) {
    servFailOccurred = true;
    return vState::BogusUnableToGetDNSKEYs;
  }

  if (rcode == RCode::NoError) {
    if (state == vState::Secure) {
      for (const auto& key : records) {
        if (key.d_type == QType::DNSKEY) {
          auto content = getRR<DNSKEYRecordContent>(key);
          if (content) {
            keys.insert(content);
          }
        }
      }
    }
    LOG(d_prefix<<"Retrieved "<<keys.size()<<" DNSKeys for "<<signer<<", state is "<<state<<endl);
    return state;
  }

  if (state == vState::Insecure) {
    return state;
  }

  LOG(d_prefix<<"Returning Bogus state from "<<__func__<<"("<<signer<<")"<<endl);
  return vState::BogusUnableToGetDNSKEYs;
}

vState SyncRes::validateRecordsWithSigs(unsigned int depth, const DNSName& qname, const QType qtype, const DNSName& name, const QType type, const std::vector<DNSRecord>& records, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures)
{
  skeyset_t keys;
  if (signatures.empty()) {
    LOG(d_prefix<<"Bogus!"<<endl);
    return vState::BogusNoRRSIG;
  }

  const DNSName signer = getSigner(signatures);
  bool dsFailed = false;
  if (!signer.empty() && name.isPartOf(signer)) {
    vState state = vState::Secure;

    if ((qtype == QType::DNSKEY || qtype == QType::DS) && signer == qname) {
      /* we are already retrieving those keys, sorry */
      if (type == QType::DS && signer == name && !signer.isRoot()) {
        /* Unless we are getting the DS of the root zone, we should never see a
           DS (or a denial of a DS) signed by the DS itself, since we should be
           requesting it from the parent zone. Something is very wrong */
        LOG(d_prefix<<"The DS for "<<qname<<" is signed by itself"<<endl);
        state = vState::BogusSelfSignedDS;
        dsFailed = true;
      }
      else if (qtype == QType::DS && signer == qname && !signer.isRoot()) {
        if (type == QType::SOA || type == QType::NSEC || type == QType::NSEC3) {
        /* if we are trying to validate the DS or more likely NSEC(3)s proving that it does not exist, we have a problem.
           In that case let's go Bogus (we will check later if we missed a cut)
        */
          state = vState::BogusSelfSignedDS;
          dsFailed = true;
        }
        else if (type == QType::CNAME) {
          state = vState::BogusUnableToGetDSs;
          dsFailed = true;
        }
      }
      else if (qtype == QType::DNSKEY && signer == qname) {
        /* that actually does happen when a server returns NS records in authority
           along with the DNSKEY, leading us to trying to validate the RRSIGs for
           the NS with the DNSKEY that we are about to process. */
        if ((name == signer && type == QType::NSEC) || type == QType::NSEC3) {
          /* if we are trying to validate the DNSKEY (should not happen here),
             or more likely NSEC(3)s proving that it does not exist, we have a problem.
             In that case let's see if the DS does exist, and if it does let's go Bogus
          */
          dsmap_t results;
          vState dsState = getDSRecords(signer, results, false, depth, true);
          if (vStateIsBogus(dsState) || dsState == vState::Insecure) {
            state = dsState;
            if (vStateIsBogus(dsState)) {
              dsFailed = true;
            }
          }
          else {
            LOG(d_prefix<<"Unable to get the DS for "<<signer<<endl);
            state = vState::BogusUnableToGetDNSKEYs;
            dsFailed = true;
          }
        }
        else {
          /* return immediately since looking at the cuts is not going to change the
             fact that we are looking at a signature done with the key we are trying to
             obtain */
          LOG(d_prefix<<"we are looking at a signature done with the key we are trying to obtain "<<signer<<endl);
          return vState::Indeterminate;
        }
      }
    }
    bool servFailOccurred = false;
    if (state == vState::Secure) {
      LOG(d_prefix<<"retrieving the DNSKEYs for "<<signer<<endl);
      state = getDNSKeys(signer, keys, servFailOccurred, depth);
    }

    if (state != vState::Secure) {
      if (!vStateIsBogus(state)) {
        return state;
      }
      /* try again to get the missed cuts, harder this time */
      LOG(d_prefix<<"checking whether we missed a zone cut for "<<signer<<" before returning a Bogus state for "<<name<<"|"<<type.toString()<<endl);
      auto zState = getValidationStatus(signer, false, dsFailed, depth);
      if (zState == vState::Secure) {
        if (state == vState::BogusUnableToGetDNSKEYs && servFailOccurred) {
          throw ImmediateServFailException("Server Failure while retrieving DNSKEY records for " + signer.toLogString());
        }
        /* too bad */
        LOG(d_prefix<<"we are still in a Secure zone, returning "<<vStateToString(state)<<endl);
        return state;
      }
      else {
        return zState;
      }
    }
  }

  sortedRecords_t recordcontents;
  for (const auto& record : records) {
    recordcontents.insert(record.d_content);
  }

  LOG(d_prefix<<"Going to validate "<<recordcontents.size()<< " record contents with "<<signatures.size()<<" sigs and "<<keys.size()<<" keys for "<<name<<"|"<<type.toString()<<endl);
  vState state = validateWithKeySet(d_now.tv_sec, name, recordcontents, signatures, keys, d_validationContext, false);
  if (s_maxvalidationsperq != 0 && d_validationContext.d_validationsCounter > s_maxvalidationsperq) {
    throw ImmediateServFailException("Server Failure while validating records, too many signature validations for this query");
  }

  if (state == vState::Secure) {
    LOG(d_prefix<<"Secure!"<<endl);
    return vState::Secure;
  }

  LOG(d_prefix<<vStateToString(state)<<"!"<<endl);
  /* try again to get the missed cuts, harder this time */
  auto zState = getValidationStatus(name, false, type == QType::DS, depth);
  LOG(d_prefix<<"checking whether we missed a zone cut before returning a Bogus state"<<endl);
  if (zState == vState::Secure) {
    /* too bad */
    LOG(d_prefix<<"we are still in a Secure zone, returning "<<vStateToString(state)<<endl);
    return state;
  }
  else {
    return zState;
  }
}

/* This function will check whether the answer should have the AA bit set, and will set if it should be set and isn't.
   This is unfortunately needed to deal with very crappy so-called DNS servers */
void SyncRes::fixupAnswer(const std::string& prefix, LWResult& lwr, const DNSName& qname, const QType qtype, const DNSName& auth, bool wasForwarded, bool rdQuery)
{
  const bool wasForwardRecurse = wasForwarded && rdQuery;

  if (wasForwardRecurse || lwr.d_aabit) {
    /* easy */
    return;
  }

  for (const auto& rec : lwr.d_records) {

    if (rec.d_type == QType::OPT) {
      continue;
    }

    if (rec.d_class != QClass::IN) {
      continue;
    }

    if (rec.d_type == QType::ANY) {
      continue;
    }

    if (rec.d_place == DNSResourceRecord::ANSWER && (rec.d_type == qtype || rec.d_type == QType::CNAME || qtype == QType::ANY) && rec.d_name == qname && rec.d_name.isPartOf(auth)) {
      /* This is clearly an answer to the question we were asking, from an authoritative server that is allowed to send it.
         We are going to assume this server is broken and does not know it should set the AA bit, even though it is DNS 101 */
      LOG(prefix<<"Received a record for "<<rec.d_name<<"|"<<DNSRecordContent::NumberToType(rec.d_type)<<" in the answer section from "<<auth<<", without the AA bit set. Assuming this server is clueless and setting the AA bit."<<endl);
      lwr.d_aabit = true;
      return;
    }

    if (rec.d_place != DNSResourceRecord::ANSWER) {
      /* we have scanned all the records in the answer section, if any, we are done */
      return;
    }
  }
}

static void allowAdditionalEntry(std::unordered_set<DNSName>& allowedAdditionals, const DNSRecord& rec)
{
  switch(rec.d_type) {
  case QType::MX:
    if (auto mxContent = getRR<MXRecordContent>(rec)) {
      allowedAdditionals.insert(mxContent->d_mxname);
    }
    break;
  case QType::NS:
    if (auto nsContent = getRR<NSRecordContent>(rec)) {
      allowedAdditionals.insert(nsContent->getNS());
    }
    break;
  case QType::SRV:
    if (auto srvContent = getRR<SRVRecordContent>(rec)) {
      allowedAdditionals.insert(srvContent->d_target);
    }
    break;
  case QType::SVCB: /* fall-through */
  case QType::HTTPS:
    if (auto svcbContent = getRR<SVCBBaseRecordContent>(rec)) {
      if (svcbContent->getPriority() > 0) {
        DNSName target = svcbContent->getTarget();
        if (target.isRoot()) {
          target = rec.d_name;
        }
        allowedAdditionals.insert(target);
      }
      else {
        // FIXME: Alias mode not implemented yet
      }
    }
    break;
  case QType::NAPTR:
    if (auto naptrContent = getRR<NAPTRRecordContent>(rec)) {
      auto flags = naptrContent->getFlags();
      toLowerInPlace(flags);
      if (flags.find('a') != string::npos || flags.find('s') != string::npos) {
        allowedAdditionals.insert(naptrContent->getReplacement());
      }
    }
    break;
  default:
    break;
  }
}

void SyncRes::sanitizeRecords(const std::string& prefix, LWResult& lwr, const DNSName& qname, const QType qtype, const DNSName& auth, bool wasForwarded, bool rdQuery)
{
  const bool wasForwardRecurse = wasForwarded && rdQuery;
  /* list of names for which we will allow A and AAAA records in the additional section
     to remain */
  std::unordered_set<DNSName> allowedAdditionals = { qname };
  bool haveAnswers = false;
  bool isNXDomain = false;
  bool isNXQType = false;

  for(auto rec = lwr.d_records.begin(); rec != lwr.d_records.end(); ) {

    if (rec->d_type == QType::OPT) {
      ++rec;
      continue;
    }

    if (rec->d_class != QClass::IN) {
      LOG(prefix<<"Removing non internet-classed data received from "<<auth<<endl);
      rec = lwr.d_records.erase(rec);
      continue;
    }

    if (rec->d_type == QType::ANY) {
      LOG(prefix<<"Removing 'ANY'-typed data received from "<<auth<<endl);
      rec = lwr.d_records.erase(rec);
      continue;
    }

    if (!rec->d_name.isPartOf(auth)) {
      LOG(prefix<<"Removing record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the "<<(int)rec->d_place<<" section received from "<<auth<<endl);
      rec = lwr.d_records.erase(rec);
      continue;
    }

    /* dealing with the records in answer */
    if (!(lwr.d_aabit || wasForwardRecurse) && rec->d_place == DNSResourceRecord::ANSWER) {
      /* for now we allow a CNAME for the exact qname in ANSWER with AA=0, because Amazon DNS servers
         are sending such responses */
      if (!(rec->d_type == QType::CNAME && qname == rec->d_name)) {
        LOG(prefix<<"Removing record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the answer section without the AA bit set received from "<<auth<<endl);
        rec = lwr.d_records.erase(rec);
        continue;
      }
    }

    if (rec->d_type == QType::DNAME && (rec->d_place != DNSResourceRecord::ANSWER || !qname.isPartOf(rec->d_name))) {
      LOG(prefix<<"Removing invalid DNAME record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the "<<(int)rec->d_place<<" section received from "<<auth<<endl);
      rec = lwr.d_records.erase(rec);
      continue;
    }

    if (rec->d_place == DNSResourceRecord::ANSWER && (qtype != QType::ANY && rec->d_type != qtype.getCode() && s_redirectionQTypes.count(rec->d_type) == 0 && rec->d_type != QType::SOA && rec->d_type != QType::RRSIG)) {
      LOG(prefix<<"Removing irrelevant record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the ANSWER section received from "<<auth<<endl);
      rec = lwr.d_records.erase(rec);
      continue;
    }

    if (rec->d_place == DNSResourceRecord::ANSWER && !haveAnswers) {
      haveAnswers = true;
    }

    if (rec->d_place == DNSResourceRecord::ANSWER) {
      allowAdditionalEntry(allowedAdditionals, *rec);
    }

    /* dealing with the records in authority */
    if (rec->d_place == DNSResourceRecord::AUTHORITY && rec->d_type != QType::NS && rec->d_type != QType::DS && rec->d_type != QType::SOA && rec->d_type != QType::RRSIG && rec->d_type != QType::NSEC && rec->d_type != QType::NSEC3) {
      LOG(prefix<<"Removing irrelevant record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the AUTHORITY section received from "<<auth<<endl);
      rec = lwr.d_records.erase(rec);
      continue;
    }

    if (rec->d_place == DNSResourceRecord::AUTHORITY && rec->d_type == QType::SOA) {
      if (!qname.isPartOf(rec->d_name)) {
        LOG(prefix<<"Removing irrelevant SOA record '"<<rec->d_name<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the AUTHORITY section received from "<<auth<<endl);
        rec = lwr.d_records.erase(rec);
        continue;
      }

      if (!(lwr.d_aabit || wasForwardRecurse)) {
        LOG(prefix<<"Removing irrelevant record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the AUTHORITY section received from "<<auth<<endl);
        rec = lwr.d_records.erase(rec);
        continue;
      }

      if (!haveAnswers) {
        if (lwr.d_rcode == RCode::NXDomain) {
          isNXDomain = true;
        }
        else if (lwr.d_rcode == RCode::NoError) {
          isNXQType = true;
        }
      }
    }

    if (rec->d_place == DNSResourceRecord::AUTHORITY && rec->d_type == QType::NS && (isNXDomain || isNXQType)) {
      /*
       * We don't want to pick up NS records in AUTHORITY and their ADDITIONAL sections of NXDomain answers
       * because they are somewhat easy to insert into a large, fragmented UDP response
       * for an off-path attacker by injecting spoofed UDP fragments. So do not add these to allowedAdditionals.
       */
      LOG(prefix<<"Removing NS record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the "<<(int)rec->d_place<<" section of a "<<(isNXDomain ? "NXD" : "NXQTYPE")<<" response received from "<<auth<<endl);
      rec = lwr.d_records.erase(rec);
      continue;
    }

    if (rec->d_place == DNSResourceRecord::AUTHORITY && rec->d_type == QType::NS && !d_updatingRootNS && rec->d_name == g_rootdnsname) {
      /*
       * We don't want to pick up root NS records in AUTHORITY and their associated ADDITIONAL sections of random queries.
       * So don't add them to allowedAdditionals.
       */
      LOG(prefix<<"Removing NS record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the "<<(int)rec->d_place<<" section of a response received from "<<auth<<endl);
      rec = lwr.d_records.erase(rec);
      continue;
    }

    if (rec->d_place == DNSResourceRecord::AUTHORITY && rec->d_type == QType::NS) {
      allowAdditionalEntry(allowedAdditionals, *rec);
    }

    /* dealing with the records in additional */
    if (rec->d_place == DNSResourceRecord::ADDITIONAL && rec->d_type != QType::A && rec->d_type != QType::AAAA && rec->d_type != QType::RRSIG) {
      LOG(prefix<<"Removing irrelevant record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the ADDITIONAL section received from "<<auth<<endl);
      rec = lwr.d_records.erase(rec);
      continue;
    }

    if (rec->d_place == DNSResourceRecord::ADDITIONAL && allowedAdditionals.count(rec->d_name) == 0) {
      LOG(prefix<<"Removing irrelevant additional record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the ADDITIONAL section received from "<<auth<<endl);
      rec = lwr.d_records.erase(rec);
      continue;
    }

    ++rec;
  }
}


void SyncRes::rememberParentSetIfNeeded(const DNSName& domain, const vector<DNSRecord>& newRecords, unsigned int depth)
{
  vector<DNSRecord> existing;
  bool wasAuth = false;
  auto ttl = g_recCache->get(d_now.tv_sec, domain, QType::NS, MemRecursorCache::None, &existing, d_cacheRemote, d_routingTag, nullptr, nullptr, nullptr, nullptr, &wasAuth);

  if (ttl <= 0 || wasAuth) {
    return;
  }
  {
    auto lock = s_savedParentNSSet.lock();
    if (lock->find(domain) != lock->end()) {
      // no relevant data, or we already stored the parent data
      return;
    }
  }

  set<DNSName> authSet;
  for (const auto& ns : newRecords) {
    auto content = getRR<NSRecordContent>(ns);
    authSet.insert(content->getNS());
  }
  // The glue IPs could also differ, but we're not checking that yet, we're only looking for parent NS records not
  // in the child set
  bool shouldSave = false;
  for (const auto& ns : existing) {
    auto content = getRR<NSRecordContent>(ns);
    if (authSet.count(content->getNS()) == 0) {
      LOG(d_prefix << domain << ": at least one parent-side NS was not in the child-side NS set, remembering parent NS set and cached IPs" << endl);
      shouldSave = true;
      break;
    }
  }

  if (shouldSave) {
    map<DNSName, vector<ComboAddress>> entries;
    for (const auto& ns : existing) {
      auto content = getRR<NSRecordContent>(ns);
      const DNSName& name = content->getNS();
      set<GetBestNSAnswer> beenthereIgnored;
      unsigned int nretrieveAddressesForNSIgnored;
      auto addresses = getAddrs(name, depth, beenthereIgnored, true, nretrieveAddressesForNSIgnored);
      entries.emplace(name, addresses);
    }
    s_savedParentNSSet.lock()->emplace(domain, std::move(entries), d_now.tv_sec + ttl);
  }
}

RCode::rcodes_ SyncRes::updateCacheFromRecords(unsigned int depth, LWResult& lwr, const DNSName& qname, const QType qtype, const DNSName& auth, bool wasForwarded, const boost::optional<Netmask> ednsmask, vState& state, bool& needWildcardProof, bool& gatherWildcardProof, unsigned int& wildcardLabelsCount, bool rdQuery, const ComboAddress& remoteIP)
{
  bool wasForwardRecurse = wasForwarded && rdQuery;
  tcache_t tcache;

  string prefix;
  if(doLog()) {
    prefix=d_prefix;
    prefix.append(depth, ' ');
  }

  fixupAnswer(prefix, lwr, qname, qtype, auth, wasForwarded, rdQuery);
  sanitizeRecords(prefix, lwr, qname, qtype, auth, wasForwarded, rdQuery);

  std::vector<std::shared_ptr<DNSRecord>> authorityRecs;
  bool isCNAMEAnswer = false;
  bool isDNAMEAnswer = false;
  DNSName seenAuth;

  // names that might be expanded from a wildcard, and thus require denial of existence proof
  // this is the queried name and any part of the CNAME chain from the queried name
  // the key is the name itself, the value is initially false and is set to true once we have
  // confirmed it was actually expanded from a wildcard
  std::map<DNSName, bool> wildcardCandidates{{qname, false}};

  if (rdQuery) {
    std::unordered_map<DNSName, DNSName> cnames;
    for (const auto& rec : lwr.d_records) {
      if (rec.d_type != QType::CNAME || rec.d_class != QClass::IN) {
        continue;
      }
      if (auto content = getRR<CNAMERecordContent>(rec)) {
        cnames[rec.d_name] = DNSName(content->getTarget());
      }
    }
    auto initial = qname;
    while (true) {
      auto cnameIt = cnames.find(initial);
      if (cnameIt == cnames.end()) {
        break;
      }
      initial = cnameIt->second;
      if (!wildcardCandidates.emplace(initial, false).second) {
        // CNAME loop
        break;
      }
    }
  }

  for (auto& rec : lwr.d_records) {
    if (rec.d_type == QType::OPT || rec.d_class != QClass::IN) {
      continue;
    }

    rec.d_ttl = min(s_maxcachettl, rec.d_ttl);

    if (!isCNAMEAnswer && rec.d_place == DNSResourceRecord::ANSWER && rec.d_type == QType::CNAME && (!(qtype==QType::CNAME)) && rec.d_name == qname && !isDNAMEAnswer) {
      isCNAMEAnswer = true;
    }
    if (!isDNAMEAnswer && rec.d_place == DNSResourceRecord::ANSWER && rec.d_type == QType::DNAME && qtype != QType::DNAME && qname.isPartOf(rec.d_name)) {
      isDNAMEAnswer = true;
      isCNAMEAnswer = false;
    }

    if (rec.d_type == QType::SOA && rec.d_place == DNSResourceRecord::AUTHORITY && qname.isPartOf(rec.d_name)) {
      seenAuth = rec.d_name;
    }

    const auto labelCount = rec.d_name.countLabels();
    if (rec.d_type == QType::RRSIG) {
      auto rrsig = getRR<RRSIGRecordContent>(rec);
      if (rrsig) {
        /* As illustrated in rfc4035's Appendix B.6, the RRSIG label
           count can be lower than the name's label count if it was
           synthesized from the wildcard. Note that the difference might
           be > 1. */
        if (auto wcIt = wildcardCandidates.find(rec.d_name); wcIt != wildcardCandidates.end() && isWildcardExpanded(labelCount, rrsig)) {
          wcIt->second = true;
          gatherWildcardProof = true;
          if (!isWildcardExpandedOntoItself(rec.d_name, labelCount, rrsig)) {
            /* if we have a wildcard expanded onto itself, we don't need to prove
               that the exact name doesn't exist because it actually does.
               We still want to gather the corresponding NSEC/NSEC3 records
               to pass them to our client in case it wants to validate by itself.
            */
            LOG(prefix<<qname<<": RRSIG indicates the name was synthesized from a wildcard, we need a wildcard proof"<<endl);
            needWildcardProof = true;
          }
          else {
            LOG(prefix<<qname<<": RRSIG indicates the name was synthesized from a wildcard expanded onto itself, we need to gather wildcard proof"<<endl);
          }
          wildcardLabelsCount = rrsig->d_labels;
        }

        // cerr<<"Got an RRSIG for "<<DNSRecordContent::NumberToType(rrsig->d_type)<<" with name '"<<rec.d_name<<"' and place "<<rec.d_place<<endl;
        tcache[{rec.d_name, rrsig->d_type, rec.d_place}].signatures.push_back(rrsig);
        tcache[{rec.d_name, rrsig->d_type, rec.d_place}].signaturesTTL = std::min(tcache[{rec.d_name, rrsig->d_type, rec.d_place}].signaturesTTL, rec.d_ttl);
      }
    }
  }

  /* if we have a positive answer synthesized from a wildcard,
     we need to store the corresponding NSEC/NSEC3 records proving
     that the exact name did not exist in the negative cache */
  if (gatherWildcardProof) {
    for (const auto& rec : lwr.d_records) {
      if (rec.d_type == QType::OPT || rec.d_class != QClass::IN) {
        continue;
      }

      if (nsecTypes.count(rec.d_type)) {
        authorityRecs.push_back(std::make_shared<DNSRecord>(rec));
      }
      else if (rec.d_type == QType::RRSIG) {
        auto rrsig = getRR<RRSIGRecordContent>(rec);
        if (rrsig && nsecTypes.count(rrsig->d_type)) {
          authorityRecs.push_back(std::make_shared<DNSRecord>(rec));
        }
      }
    }
  }

  // reap all answers from this packet that are acceptable
  for (auto& rec : lwr.d_records) {
    if(rec.d_type == QType::OPT) {
      LOG(prefix<<qname<<": OPT answer '"<<rec.d_name<<"' from '"<<auth<<"' nameservers" <<endl);
      continue;
    }

    LOG(prefix<<qname<<": accept answer '"<<rec.d_name<<"|"<<DNSRecordContent::NumberToType(rec.d_type)<<"|"<<rec.d_content->getZoneRepresentation()<<"' from '"<<auth<<"' nameservers? ttl="<<rec.d_ttl<<", place="<<(int)rec.d_place<<" ");

    // We called sanitizeRecords before, so all ANY, non-IN and non-aa/non-forwardrecurse answer records are already removed

    if(rec.d_name.isPartOf(auth)) {
      if (rec.d_type == QType::RRSIG) {
        LOG("RRSIG - separate"<<endl);
      }
      else if (rec.d_type == QType::DS && rec.d_name == auth) {
        LOG("NO - DS provided by child zone"<<endl);
      }
      else {
        bool haveLogged = false;
        if (isDNAMEAnswer && rec.d_type == QType::CNAME) {
          LOG("NO - we already have a DNAME answer for this domain"<<endl);
          continue;
        }
        if (!t_sstorage.domainmap->empty()) {
          // Check if we are authoritative for a zone in this answer
          DNSName tmp_qname(rec.d_name);
          // We may be auth for domain example.com, but the DS record needs to come from the parent (.com) nameserver
          if (rec.d_type == QType::DS) {
            tmp_qname.chopOff();
          }
          auto auth_domain_iter=getBestAuthZone(&tmp_qname);
          if(auth_domain_iter!=t_sstorage.domainmap->end() &&
             auth.countLabels() <= auth_domain_iter->first.countLabels()) {
            if (auth_domain_iter->first != auth) {
              LOG("NO! - we are authoritative for the zone "<<auth_domain_iter->first<<endl);
              continue;
            } else {
              LOG("YES! - This answer was ");
              if (!wasForwarded) {
                LOG("retrieved from the local auth store.");
              } else {
                LOG("received from a server we forward to.");
              }
              haveLogged = true;
              LOG(endl);
            }
          }
        }
        if (!haveLogged) {
          LOG("YES!"<<endl);
        }

        rec.d_ttl=min(s_maxcachettl, rec.d_ttl);

        DNSRecord dr(rec);
        dr.d_ttl += d_now.tv_sec;
        dr.d_place=DNSResourceRecord::ANSWER;
        tcache[{rec.d_name,rec.d_type,rec.d_place}].records.push_back(dr);
      }
    }
    else
      LOG("NO!"<<endl);
  }

  // supplant
  for (auto& entry : tcache) {
    if ((entry.second.records.size() + entry.second.signatures.size() + authorityRecs.size()) > 1) {  // need to group the ttl to be the minimum of the RRSET (RFC 2181, 5.2)
      uint32_t lowestTTD = computeLowestTTD(entry.second.records, entry.second.signatures, entry.second.signaturesTTL, authorityRecs);

      for (auto& record : entry.second.records) {
        record.d_ttl = lowestTTD; // boom
      }
    }

//		cout<<"Have "<<i->second.records.size()<<" records and "<<i->second.signatures.size()<<" signatures for "<<i->first.name;
//		cout<<'|'<<DNSRecordContent::NumberToType(i->first.type)<<endl;
  }

  for(tcache_t::iterator i = tcache.begin(); i != tcache.end(); ++i) {

    if (i->second.records.empty()) // this happens when we did store signatures, but passed on the records themselves
      continue;

    /* Even if the AA bit is set, additional data cannot be considered
       as authoritative. This is especially important during validation
       because keeping records in the additional section is allowed even
       if the corresponding RRSIGs are not included, without setting the TC
       bit, as stated in rfc4035's section 3.1.1.  Including RRSIG RRs in a Response:
       "When placing a signed RRset in the Additional section, the name
       server MUST also place its RRSIG RRs in the Additional section.
       If space does not permit inclusion of both the RRset and its
       associated RRSIG RRs, the name server MAY retain the RRset while
       dropping the RRSIG RRs.  If this happens, the name server MUST NOT
       set the TC bit solely because these RRSIG RRs didn't fit."
    */
    bool isAA = lwr.d_aabit && i->first.place != DNSResourceRecord::ADDITIONAL;
    /* if we forwarded the query to a recursor, we can expect the answer to be signed,
       even if the answer is not AA. Of course that's not only true inside a Secure
       zone, but we check that below. */
    bool expectSignature = i->first.place == DNSResourceRecord::ANSWER || ((lwr.d_aabit || wasForwardRecurse) && i->first.place != DNSResourceRecord::ADDITIONAL);
    /* in a non authoritative answer, we only care about the DS record (or lack of)  */
    if (!isAA && (i->first.type == QType::DS || i->first.type == QType::NSEC || i->first.type == QType::NSEC3) && i->first.place == DNSResourceRecord::AUTHORITY) {
      expectSignature = true;
    }

    if (isCNAMEAnswer && (i->first.place != DNSResourceRecord::ANSWER || i->first.type != QType::CNAME || i->first.name != qname)) {
      /*
        rfc2181 states:
        Note that the answer section of an authoritative answer normally
        contains only authoritative data.  However when the name sought is an
        alias (see section 10.1.1) only the record describing that alias is
        necessarily authoritative.  Clients should assume that other records
        may have come from the server's cache.  Where authoritative answers
        are required, the client should query again, using the canonical name
        associated with the alias.
      */
      isAA = false;
      expectSignature = false;
    }
    else if (isDNAMEAnswer && (i->first.place != DNSResourceRecord::ANSWER || i->first.type != QType::DNAME || !qname.isPartOf(i->first.name))) {
      /* see above */
      isAA = false;
      expectSignature = false;
    }

    if ((isCNAMEAnswer || isDNAMEAnswer) && i->first.place == DNSResourceRecord::AUTHORITY && i->first.type == QType::NS && auth == i->first.name) {
      /* These NS can't be authoritative since we have a CNAME/DNAME answer for which (see above) only the
         record describing that alias is necessarily authoritative.
         But if we allow the current auth, which might be serving the child zone, to raise the TTL
         of non-authoritative NS in the cache, they might be able to keep a "ghost" zone alive forever,
         even after the delegation is gone from the parent.
         So let's just do nothing with them, we can fetch them directly if we need them.
      */
      LOG(d_prefix<<": skipping authority NS from '"<<auth<<"' nameservers in CNAME/DNAME answer "<<i->first.name<<"|"<<DNSRecordContent::NumberToType(i->first.type)<<endl);
      continue;
    }

    /*
     * RFC 6672 section 5.3.1
     *  In any response, a signed DNAME RR indicates a non-terminal
     *  redirection of the query.  There might or might not be a server-
     *  synthesized CNAME in the answer section; if there is, the CNAME will
     *  never be signed.  For a DNSSEC validator, verification of the DNAME
     *  RR and then that the CNAME was properly synthesized is sufficient
     *  proof.
     *
     * We do the synthesis check in processRecords, here we make sure we
     * don't validate the CNAME.
     */
    if (isDNAMEAnswer && i->first.type == QType::CNAME) {
      expectSignature = false;
    }

    vState recordState = vState::Indeterminate;

    if (expectSignature && shouldValidate()) {
      vState initialState = getValidationStatus(i->first.name, !i->second.signatures.empty(), i->first.type == QType::DS, depth);
      LOG(d_prefix<<": got initial zone status "<<initialState<<" for record "<<i->first.name<<"|"<<DNSRecordContent::NumberToType(i->first.type)<<endl);

      if (initialState == vState::Secure) {
        if (i->first.type == QType::DNSKEY && i->first.place == DNSResourceRecord::ANSWER && i->first.name == getSigner(i->second.signatures)) {
          LOG(d_prefix<<"Validating DNSKEY for "<<i->first.name<<endl);
          recordState = validateDNSKeys(i->first.name, i->second.records, i->second.signatures, depth);
        }
        else {
          LOG(d_prefix<<"Validating non-additional "<<QType(i->first.type).toString()<<" record for "<<i->first.name<<endl);
          recordState = validateRecordsWithSigs(depth, qname, qtype, i->first.name, QType(i->first.type), i->second.records, i->second.signatures);
        }
      }
      else {
        recordState = initialState;
        LOG(d_prefix<<"Skipping validation because the current state is "<<recordState<<endl);
      }

      LOG(d_prefix<<"Validation result is "<<recordState<<", current state is "<<state<<endl);
      if (state != recordState) {
        updateValidationState(state, recordState);
      }
    }

    if (vStateIsBogus(recordState)) {
      /* this is a TTD by now, be careful */
      for(auto& record : i->second.records) {
        record.d_ttl = std::min(record.d_ttl, static_cast<uint32_t>(s_maxbogusttl + d_now.tv_sec));
      }
    }

    /* We don't need to store NSEC3 records in the positive cache because:
       - we don't allow direct NSEC3 queries
       - denial of existence proofs in wildcard expanded positive responses are stored in authorityRecs
       - denial of existence proofs for negative responses are stored in the negative cache
       We also don't want to cache non-authoritative data except for:
       - records coming from non forward-recurse servers (those will never be AA)
       - DS (special case)
       - NS, A and AAAA (used for infra queries)
    */
    if (i->first.type != QType::NSEC3 && (i->first.type == QType::DS || i->first.type == QType::NS || i->first.type == QType::A || i->first.type == QType::AAAA || isAA || wasForwardRecurse)) {

      bool doCache = true;
      if (i->first.place == DNSResourceRecord::ANSWER && ednsmask) {
        const bool isv4 = ednsmask->isIPv4();
        if ((isv4 && s_ecsipv4nevercache) || (!isv4 && s_ecsipv6nevercache)) {
          doCache = false;
        }
        // If ednsmask is relevant, we do not want to cache if the scope prefix length is large and TTL is small
        if (doCache && s_ecscachelimitttl > 0) {
          bool manyMaskBits = (isv4 && ednsmask->getBits() > s_ecsipv4cachelimit) ||
            (!isv4 && ednsmask->getBits() > s_ecsipv6cachelimit);

          if (manyMaskBits) {
            uint32_t minttl = UINT32_MAX;
            for (const auto &it : i->second.records) {
              if (it.d_ttl < minttl)
                minttl = it.d_ttl;
            }
            bool ttlIsSmall = minttl < s_ecscachelimitttl + d_now.tv_sec;
            if (ttlIsSmall) {
              // Case: many bits and ttlIsSmall
              doCache = false;
            }
          }
        }
      }

      d_fromAuthIP = remoteIP;

      if (doCache) {
        // Check if we are going to replace a non-auth (parent) NS recordset
        if (isAA && i->first.type == QType::NS && s_save_parent_ns_set) {
          rememberParentSetIfNeeded(i->first.name, i->second.records, depth);
        }
        bool thisRRNeedsWildcardProof = false;
        if (gatherWildcardProof) {
          if (auto wcIt = wildcardCandidates.find(i->first.name); wcIt != wildcardCandidates.end() && wcIt->second) {
            thisRRNeedsWildcardProof = true;
          }
        }
        g_recCache->replace(d_now.tv_sec, i->first.name, i->first.type, i->second.records, i->second.signatures,  thisRRNeedsWildcardProof ? authorityRecs : std::vector<std::shared_ptr<DNSRecord>>(), i->first.type == QType::DS ? true : isAA, auth, i->first.place == DNSResourceRecord::ANSWER ? ednsmask : boost::none, d_routingTag, recordState, remoteIP, d_refresh);

        // Delete potential negcache entry. When a record recovers with serve-stale the negcache entry can cause the wrong entry to
        // be served, as negcache entries are checked before record cache entries
        if (NegCache::s_maxServedStaleExtensions > 0) {
          g_negCache->wipeTyped(i->first.name, i->first.type);
        }

        if (g_aggressiveNSECCache && thisRRNeedsWildcardProof && recordState == vState::Secure && i->first.place == DNSResourceRecord::ANSWER && i->first.name == qname && !i->second.signatures.empty() && !d_routingTag && !ednsmask) {
          /* we have an answer synthesized from a wildcard and aggressive NSEC is enabled, we need to store the
             wildcard in its non-expanded form in the cache to be able to synthesize wildcard answers later */
          const auto& rrsig = i->second.signatures.at(0);
          const auto labelCount = i->first.name.countLabels();

          if (isWildcardExpanded(labelCount, rrsig) && !isWildcardExpandedOntoItself(i->first.name, labelCount, rrsig)) {
            DNSName realOwner = getNSECOwnerName(i->first.name, i->second.signatures);

            std::vector<DNSRecord> content;
            content.reserve(i->second.records.size());
            for (const auto& record : i->second.records) {
              DNSRecord nonExpandedRecord(record);
              nonExpandedRecord.d_name = realOwner;
              content.push_back(std::move(nonExpandedRecord));
            }

            g_recCache->replace(d_now.tv_sec, realOwner, QType(i->first.type), content, i->second.signatures, /* no additional records in that case */ {}, i->first.type == QType::DS ? true : isAA, auth, boost::none, boost::none, recordState, remoteIP, d_refresh);
          }
        }
      }
    }

    if (seenAuth.empty() && !i->second.signatures.empty()) {
      seenAuth = getSigner(i->second.signatures);
    }

    if (g_aggressiveNSECCache && (i->first.type == QType::NSEC || i->first.type == QType::NSEC3) && recordState == vState::Secure && !seenAuth.empty()) {
      // Good candidate for NSEC{,3} caching
      g_aggressiveNSECCache->insertNSEC(seenAuth, i->first.name, i->second.records.at(0), i->second.signatures, i->first.type == QType::NSEC3);
    }

    if (i->first.place == DNSResourceRecord::ANSWER && ednsmask) {
      d_wasVariable=true;
    }
  }

  if (gatherWildcardProof) {
    if (auto wcIt = wildcardCandidates.find(qname); wcIt != wildcardCandidates.end() && !wcIt->second) {
      // the queried name was not expanded from a wildcard, a record in the CNAME chain was, so we don't need to gather wildcard proof now: we will do that when looking up the CNAME chain
      gatherWildcardProof = false;
    }
  }

  return RCode::NoError;
}

void SyncRes::updateDenialValidationState(vState& neValidationState, const DNSName& neName, vState& state, const dState denialState, const dState expectedState, bool isDS, unsigned int depth)
{
  if (denialState == expectedState) {
    neValidationState = vState::Secure;
  }
  else {
    if (denialState == dState::OPTOUT) {
      LOG(d_prefix<<"OPT-out denial found for "<<neName<<endl);
      /* rfc5155 states:
         "The AD bit, as defined by [RFC4035], MUST NOT be set when returning a
         response containing a closest (provable) encloser proof in which the
         NSEC3 RR that covers the "next closer" name has the Opt-Out bit set.

         This rule is based on what this closest encloser proof actually
         proves: names that would be covered by the Opt-Out NSEC3 RR may or
         may not exist as insecure delegations.  As such, not all the data in
         responses containing such closest encloser proofs will have been
         cryptographically verified, so the AD bit cannot be set."

         At best the Opt-Out NSEC3 RR proves that there is no signed DS (so no
         secure delegation).
      */
      neValidationState = vState::Insecure;
    }
    else if (denialState == dState::INSECURE) {
      LOG(d_prefix<<"Insecure denial found for "<<neName<<", returning Insecure"<<endl);
      neValidationState = vState::Insecure;
    }
    else {
      LOG(d_prefix<<"Invalid denial found for "<<neName<<", res="<<denialState<<", expectedState="<<expectedState<<", checking whether we have missed a zone cut before returning a Bogus state"<<endl);
      /* try again to get the missed cuts, harder this time */
      auto zState = getValidationStatus(neName, false, isDS, depth);
      if (zState != vState::Secure) {
        neValidationState = zState;
      }
      else {
        LOG(d_prefix<<"Still in a secure zone with an invalid denial for "<<neName<<", returning "<<vStateToString(vState::BogusInvalidDenial)<<endl);
        neValidationState = vState::BogusInvalidDenial;
      }
    }
  }
  updateValidationState(state, neValidationState);
}

dState SyncRes::getDenialValidationState(const NegCache::NegCacheEntry& ne, const dState expectedState, bool referralToUnsigned)
{
  cspmap_t csp = harvestCSPFromNE(ne);
  return getDenial(csp, ne.d_name, ne.d_qtype.getCode(), referralToUnsigned, expectedState == dState::NXQTYPE, d_validationContext);
}

bool SyncRes::processRecords(const std::string& prefix, const DNSName& qname, const QType qtype, const DNSName& auth, LWResult& lwr, const bool sendRDQuery, vector<DNSRecord>& ret, set<DNSName>& nsset, DNSName& newtarget, DNSName& newauth, bool& realreferral, bool& negindic, vState& state, const bool needWildcardProof, const bool gatherWildcardProof, const unsigned int wildcardLabelsCount, int& rcode, bool& negIndicHasSignatures, unsigned int depth)
{
  bool done = false;
  DNSName dnameTarget, dnameOwner;
  uint32_t dnameTTL = 0;
  bool referralOnDS = false;

  for (auto& rec : lwr.d_records) {
    if (rec.d_type == QType::OPT || rec.d_class != QClass::IN) {
      continue;
    }

    if (rec.d_place == DNSResourceRecord::ANSWER && !(lwr.d_aabit || sendRDQuery)) {
      /* for now we allow a CNAME for the exact qname in ANSWER with AA=0, because Amazon DNS servers
         are sending such responses */
      if (!(rec.d_type == QType::CNAME && rec.d_name == qname)) {
        continue;
      }
    }
    const bool negCacheIndication = rec.d_place == DNSResourceRecord::AUTHORITY && rec.d_type == QType::SOA &&
      lwr.d_rcode == RCode::NXDomain && qname.isPartOf(rec.d_name) && rec.d_name.isPartOf(auth);

    bool putInNegCache = true;
    if (negCacheIndication && qtype == QType::DS && isForwardOrAuth(qname)) {
      // #10189, a NXDOMAIN to a DS query for a forwarded or auth domain should not NXDOMAIN the whole domain
      putInNegCache = false;
    }

    if (negCacheIndication) {
      LOG(prefix<<qname<<": got negative caching indication for name '"<<qname<<"' (accept="<<rec.d_name.isPartOf(auth)<<"), newtarget='"<<newtarget<<"'"<<endl);

      rec.d_ttl = min(rec.d_ttl, s_maxnegttl);
      // only add a SOA if we're not going anywhere after this
      if (newtarget.empty()) {
        ret.push_back(rec);
      }

      NegCache::NegCacheEntry ne;

      uint32_t lowestTTL = rec.d_ttl;
      /* if we get an NXDomain answer with a CNAME, the name
         does exist but the target does not */
      ne.d_name = newtarget.empty() ? qname : newtarget;
      ne.d_qtype = QType::ENT; // this encodes 'whole record'
      ne.d_auth = rec.d_name;
      harvestNXRecords(lwr.d_records, ne, d_now.tv_sec, &lowestTTL);

      if (vStateIsBogus(state)) {
        ne.d_validationState = state;
      }
      else {
        /* here we need to get the validation status of the zone telling us that the domain does not
           exist, ie the owner of the SOA */
        auto recordState = getValidationStatus(rec.d_name, !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(), false, depth);
        if (recordState == vState::Secure) {
          dState denialState = getDenialValidationState(ne, dState::NXDOMAIN, false);
          updateDenialValidationState(ne.d_validationState, ne.d_name, state, denialState, dState::NXDOMAIN, false, depth);
        }
        else {
          ne.d_validationState = recordState;
          updateValidationState(state, ne.d_validationState);
        }
      }

      if (vStateIsBogus(ne.d_validationState)) {
        lowestTTL = min(lowestTTL, s_maxbogusttl);
      }

      ne.d_ttd = d_now.tv_sec + lowestTTL;
      ne.d_orig_ttl = lowestTTL;
      /* if we get an NXDomain answer with a CNAME, let's not cache the
         target, even the server was authoritative for it,
         and do an additional query for the CNAME target.
         We have a regression test making sure we do exactly that.
      */
      if (newtarget.empty() && putInNegCache) {
        g_negCache->add(ne);
        // doCNAMECacheCheck() checks record cache and does not look into negcache. That means that an old record might be found if
        // serve-stale is active. Avoid that by explicitly zapping that CNAME record.
        if (qtype == QType::CNAME && MemRecursorCache::s_maxServedStaleExtensions > 0) {
          g_recCache->doWipeCache(qname, false, qtype);
        }
        if (s_rootNXTrust && ne.d_auth.isRoot() && auth.isRoot() && lwr.d_aabit) {
          ne.d_name = ne.d_name.getLastLabel();
          g_negCache->add(ne);
        }
      }

      negIndicHasSignatures = !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty();
      negindic = true;
    }
    else if (rec.d_place == DNSResourceRecord::ANSWER && s_redirectionQTypes.count(rec.d_type) > 0 && // CNAME or DNAME answer
             s_redirectionQTypes.count(qtype.getCode()) == 0) { // But not in response to a CNAME or DNAME query
      if (rec.d_type == QType::CNAME && rec.d_name == qname) {
        if (!dnameOwner.empty()) { // We synthesize ourselves
          continue;
        }
        ret.push_back(rec);
        if (auto content = getRR<CNAMERecordContent>(rec)) {
          newtarget = DNSName(content->getTarget());
        }
      } else if (rec.d_type == QType::DNAME && qname.isPartOf(rec.d_name)) { // DNAME
        ret.push_back(rec);
        if (auto content = getRR<DNAMERecordContent>(rec)) {
          dnameOwner = rec.d_name;
          dnameTarget = content->getTarget();
          dnameTTL = rec.d_ttl;
          if (!newtarget.empty()) { // We had a CNAME before, remove it from ret so we don't cache it
            ret.erase(std::remove_if(
                  ret.begin(),
                  ret.end(),
                  [&qname](DNSRecord& rr) {
                    return (rr.d_place == DNSResourceRecord::ANSWER && rr.d_type == QType::CNAME && rr.d_name == qname);
                  }),
                  ret.end());
          }
          try {
            newtarget = qname.makeRelative(dnameOwner) + dnameTarget;
          } catch (const std::exception &e) {
            // We should probably catch an std::range_error here and set the rcode to YXDOMAIN (RFC 6672, section 2.2)
            // But there is no way to set the RCODE from this function
            throw ImmediateServFailException("Unable to perform DNAME substitution(DNAME owner: '" + dnameOwner.toLogString() +
                                             "', DNAME target: '" + dnameTarget.toLogString() + "', substituted name: '" +
                                             qname.makeRelative(dnameOwner).toLogString() + "." + dnameTarget.toLogString() +
                                             "' : " + e.what());
          }
        }
      }
    }
    /* if we have a positive answer synthesized from a wildcard, we need to
       return the corresponding NSEC/NSEC3 records from the AUTHORITY section
       proving that the exact name did not exist.
       Except if this is a NODATA answer because then we will gather the NXNSEC records later */
    else if (gatherWildcardProof && !negindic && (rec.d_type == QType::RRSIG || rec.d_type == QType::NSEC || rec.d_type == QType::NSEC3) && rec.d_place == DNSResourceRecord::AUTHORITY) {
      ret.push_back(rec); // enjoy your DNSSEC
    }
    // for ANY answers we *must* have an authoritative answer, unless we are forwarding recursively
    else if (rec.d_place == DNSResourceRecord::ANSWER && rec.d_name == qname &&
            (
              rec.d_type == qtype.getCode() || ((lwr.d_aabit || sendRDQuery) && qtype == QType::ANY)
              )
      )
    {
      LOG(prefix<<qname<<": answer is in: resolved to '"<< rec.d_content->getZoneRepresentation()<<"|"<<DNSRecordContent::NumberToType(rec.d_type)<<"'"<<endl);

      done = true;
      rcode = RCode::NoError;

      if (needWildcardProof) {
        /* positive answer synthesized from a wildcard */
        NegCache::NegCacheEntry ne;
        ne.d_name = qname;
        ne.d_qtype = QType::ENT; // this encodes 'whole record'
        uint32_t lowestTTL = rec.d_ttl;
        harvestNXRecords(lwr.d_records, ne, d_now.tv_sec, &lowestTTL);

        if (vStateIsBogus(state)) {
          ne.d_validationState = state;
        }
        else {
          auto recordState = getValidationStatus(qname, !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(), false, depth);

          if (recordState == vState::Secure) {
            /* We have a positive answer synthesized from a wildcard, we need to check that we have
               proof that the exact name doesn't exist so the wildcard can be used,
               as described in section 5.3.4 of RFC 4035 and 5.3 of RFC 7129.
            */
            cspmap_t csp = harvestCSPFromNE(ne);
            dState res = getDenial(csp, qname, ne.d_qtype.getCode(), false, false, d_validationContext, false, wildcardLabelsCount);
            if (res != dState::NXDOMAIN) {
              vState st = vState::BogusInvalidDenial;
              if (res == dState::INSECURE || res == dState::OPTOUT) {
                /* Some part could not be validated, for example a NSEC3 record with a too large number of iterations,
                   this is not enough to warrant a Bogus, but go Insecure. */
                st = vState::Insecure;
                LOG(d_prefix<<"Unable to validate denial in wildcard expanded positive response found for "<<qname<<", returning Insecure, res="<<res<<endl);
              }
              else {
                LOG(d_prefix<<"Invalid denial in wildcard expanded positive response found for "<<qname<<", returning Bogus, res="<<res<<endl);
                rec.d_ttl = std::min(rec.d_ttl, s_maxbogusttl);
              }

              updateValidationState(state, st);
              /* we already stored the record with a different validation status, let's fix it */
              updateValidationStatusInCache(qname, qtype, lwr.d_aabit, st);
            }
          }
        }
      }

      ret.push_back(rec);
    }
    else if ((rec.d_type == QType::RRSIG || rec.d_type == QType::NSEC || rec.d_type == QType::NSEC3) && rec.d_place == DNSResourceRecord::ANSWER) {
      if (rec.d_type != QType::RRSIG || rec.d_name == qname) {
        ret.push_back(rec); // enjoy your DNSSEC
      } else if (rec.d_type == QType::RRSIG && qname.isPartOf(rec.d_name)) {
        auto rrsig = getRR<RRSIGRecordContent>(rec);
        if (rrsig != nullptr && rrsig->d_type == QType::DNAME) {
          ret.push_back(rec);
        }
      }
    }
    else if (rec.d_place == DNSResourceRecord::AUTHORITY && rec.d_type == QType::NS && qname.isPartOf(rec.d_name)) {
      if (moreSpecificThan(rec.d_name,auth)) {
        newauth = rec.d_name;
        LOG(prefix<<qname<<": got NS record '"<<rec.d_name<<"' -> '"<<rec.d_content->getZoneRepresentation()<<"'"<<endl);

        /* check if we have a referral from the parent zone to a child zone for a DS query, which is not right */
        if (qtype == QType::DS && (newauth.isPartOf(qname) || qname == newauth)) {
          /* just got a referral from the parent zone when asking for a DS, looks like this server did not get the DNSSEC memo.. */
          referralOnDS = true;
        }
        else {
          realreferral = true;
          if (auto content = getRR<NSRecordContent>(rec)) {
            nsset.insert(content->getNS());
          }
        }
      }
      else {
        LOG(prefix<<qname<<": got upwards/level NS record '"<<rec.d_name<<"' -> '"<<rec.d_content->getZoneRepresentation()<<"', had '"<<auth<<"'"<<endl);
        if (auto content = getRR<NSRecordContent>(rec)) {
          nsset.insert(content->getNS());
        }
      }
    }
    else if (rec.d_place==DNSResourceRecord::AUTHORITY && rec.d_type==QType::DS && qname.isPartOf(rec.d_name)) {
      LOG(prefix<<qname<<": got DS record '"<<rec.d_name<<"' -> '"<<rec.d_content->getZoneRepresentation()<<"'"<<endl);
    }
    else if (realreferral && rec.d_place == DNSResourceRecord::AUTHORITY && (rec.d_type == QType::NSEC || rec.d_type == QType::NSEC3) && newauth.isPartOf(auth)) {
      /* we might have received a denial of the DS, let's check */
      NegCache::NegCacheEntry ne;
      uint32_t lowestTTL = rec.d_ttl;
      harvestNXRecords(lwr.d_records, ne, d_now.tv_sec, &lowestTTL);

      if (!vStateIsBogus(state)) {
        auto recordState = getValidationStatus(newauth, !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(), true, depth);

        if (recordState == vState::Secure) {
          ne.d_auth = auth;
          ne.d_name = newauth;
          ne.d_qtype = QType::DS;
          rec.d_ttl = min(s_maxnegttl, rec.d_ttl);

          dState denialState = getDenialValidationState(ne, dState::NXQTYPE, true);

          if (denialState == dState::NXQTYPE || denialState == dState::OPTOUT || denialState == dState::INSECURE) {
            ne.d_ttd = lowestTTL + d_now.tv_sec;
            ne.d_orig_ttl = lowestTTL;
            ne.d_validationState = vState::Secure;
            if (denialState == dState::OPTOUT) {
              ne.d_validationState = vState::Insecure;
            }
            LOG(prefix<<qname<<": got negative indication of DS record for '"<<newauth<<"'"<<endl);

            g_negCache->add(ne);

            /* Careful! If the client is asking for a DS that does not exist, we need to provide the SOA along with the NSEC(3) proof
               and we might not have it if we picked up the proof from a delegation, in which case we need to keep on to do the actual DS
               query. */
            if (qtype == QType::DS && qname == newauth && (d_externalDSQuery.empty() || qname != d_externalDSQuery)) {
              /* we are actually done! */
              negindic = true;
              negIndicHasSignatures = !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty();
              nsset.clear();
            }
          }
        }
      }
    }
    else if (!done && rec.d_place == DNSResourceRecord::AUTHORITY && rec.d_type == QType::SOA &&
            lwr.d_rcode == RCode::NoError && qname.isPartOf(rec.d_name)) {
      LOG(prefix<<qname<<": got negative caching indication for '"<< qname<<"|"<<qtype<<"'"<<endl);

      if (!newtarget.empty()) {
        LOG(prefix<<qname<<": Hang on! Got a redirect to '"<<newtarget<<"' already"<<endl);
      }
      else {
        rec.d_ttl = min(s_maxnegttl, rec.d_ttl);

        NegCache::NegCacheEntry ne;
        ne.d_auth = rec.d_name;
        uint32_t lowestTTL = rec.d_ttl;
        ne.d_name = qname;
        ne.d_qtype = qtype;
        harvestNXRecords(lwr.d_records, ne, d_now.tv_sec, &lowestTTL);

        if (vStateIsBogus(state)) {
          ne.d_validationState = state;
        }
        else {
          auto recordState = getValidationStatus(qname, !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(), qtype == QType::DS, depth);
          if (recordState == vState::Secure) {
            dState denialState = getDenialValidationState(ne, dState::NXQTYPE, false);
            updateDenialValidationState(ne.d_validationState, ne.d_name, state, denialState, dState::NXQTYPE, qtype == QType::DS, depth);
          } else {
            ne.d_validationState = recordState;
            updateValidationState(state, ne.d_validationState);
          }
        }

        if (vStateIsBogus(ne.d_validationState)) {
          lowestTTL = min(lowestTTL, s_maxbogusttl);
          rec.d_ttl = min(rec.d_ttl, s_maxbogusttl);
        }
        ne.d_ttd = d_now.tv_sec + lowestTTL;
        ne.d_orig_ttl = lowestTTL;
        if (qtype.getCode()) {  // prevents us from NXDOMAIN'ing a whole domain
          // doCNAMECacheCheck() checks record cache and does not look into negcache. That means that an old record might be found if
          // serve-stale is active. Avoid that by explicitly zapping that CNAME record.
          if (qtype == QType::CNAME && MemRecursorCache::s_maxServedStaleExtensions > 0) {
            g_recCache->doWipeCache(qname, false, qtype);
          }
          g_negCache->add(ne);
        }

        ret.push_back(rec);
        negindic = true;
        negIndicHasSignatures = !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty();
      }
    }
  }

  if (!dnameTarget.empty()) {
    // Synthesize a CNAME
    auto cnamerec = DNSRecord();
    cnamerec.d_name = qname;
    cnamerec.d_type = QType::CNAME;
    cnamerec.d_ttl = dnameTTL;
    cnamerec.d_content = std::make_shared<CNAMERecordContent>(CNAMERecordContent(newtarget));
    ret.push_back(std::move(cnamerec));
  }

  /* If we have seen a proper denial, let's forget that we also had a referral for a DS query.
     Otherwise we need to deal with it. */
  if (referralOnDS && !negindic) {
    LOG(prefix<<qname<<": got a referral to the child zone for a DS query without a negative indication (missing SOA in authority), treating that as a NODATA"<<endl);
    if (!vStateIsBogus(state)) {
      auto recordState = getValidationStatus(qname, false, true, depth);
      if (recordState == vState::Secure) {
        /* we are in a secure zone, got a referral to the child zone on a DS query, no denial, that's wrong */
        LOG(prefix<<qname<<": NODATA without a negative indication (missing SOA in authority) in a DNSSEC secure zone, going Bogus"<<endl);
        updateValidationState(state, vState::BogusMissingNegativeIndication);
      }
    }
    negindic = true;
    negIndicHasSignatures = false;
  }

  return done;
}


static void submitTryDotTask(ComboAddress address, const DNSName& auth, const DNSName nsname, time_t now)
{
  if (address.getPort() == 853) {
    return;
  }
  address.setPort(853);
  auto lock = s_dotMap.lock();
  if (lock->d_numBusy >= SyncRes::s_max_busy_dot_probes) {
    return;
  }
  auto it = lock->d_map.emplace(DoTStatus{address, auth, now + dotFailWait}).first;
  if (it->d_status == DoTStatus::Busy) {
    return;
  }
  if (it->d_ttd > now) {
    if (it->d_status == DoTStatus::Bad) {
      return;
    }
    if (it->d_status == DoTStatus::Good) {
      return;
    }
    // We only want to probe auths that we have seen before, auth that only come around once are not interesting
    if (it->d_status == DoTStatus::Unknown && it->d_count == 0) {
      return;
    }
  }
  lock->d_map.modify(it, [=] (DoTStatus& st){ st.d_ttd = now + dotFailWait; });
  bool pushed = pushTryDoTTask(auth, QType::SOA, address, std::numeric_limits<time_t>::max(), nsname);
  if (pushed) {
    it->d_status = DoTStatus::Busy;
    ++lock->d_numBusy;
  }
}

static bool shouldDoDoT(ComboAddress address, time_t now)
{
  address.setPort(853);
  auto lock = s_dotMap.lock();
  auto it = lock->d_map.find(address);
  if (it == lock->d_map.end()) {
    return false;
  }
  it->d_count++;
  if (it->d_status == DoTStatus::Good && it->d_ttd > now) {
    return true;
  }
  return false;
}

static void updateDoTStatus(ComboAddress address, DoTStatus::Status status, time_t time, bool updateBusy = false)
{
  address.setPort(853);
  auto lock = s_dotMap.lock();
  auto it = lock->d_map.find(address);
  if (it != lock->d_map.end()) {
    it->d_status = status;
    lock->d_map.modify(it, [=] (DoTStatus& st) { st.d_ttd = time; });
    if (updateBusy) {
      --lock->d_numBusy;
    }
  }
}

bool SyncRes::tryDoT(const DNSName& qname, const QType qtype, const DNSName& nsName, ComboAddress address, time_t now)
{
  auto log = g_slog->withName("taskq")->withValues("method", Logging::Loggable("tryDoT"), "name", Logging::Loggable(qname), "qtype", Logging::Loggable(QType(qtype).toString()), "ip", Logging::Loggable(address));

  auto logHelper1 = [&log](const string& ename) {
    log->info(Logr::Debug, "Failed to probe DoT records, got an exception", "exception", Logging::Loggable(ename));
  };
  auto logHelper2 = [&log](const string& msg, const string& ename) {
    log->error(Logr::Debug, msg, "Failed to probe DoT records, got an exception", "exception", Logging::Loggable(ename));
  };
  LWResult lwr;
  bool truncated;
  bool spoofed;
  boost::optional<Netmask> nm;
  address.setPort(853);
  // We use the fact that qname equals auth
  bool ok = false;
  try {
    ok = doResolveAtThisIP("", qname, qtype, lwr, nm, qname, false, false, nsName, address, true, true, truncated, spoofed, true);
    ok = ok && lwr.d_rcode == RCode::NoError && lwr.d_records.size() > 0;
  }
  catch(const PDNSException& e) {
    logHelper2(e.reason, "PDNSException");
  }
  catch(const ImmediateServFailException& e) {
    logHelper2(e.reason, "ImmediateServFailException");
  }
  catch(const PolicyHitException& e) {
    logHelper1("PolicyHitException");
  }
  catch(const std::exception& e) {
    logHelper2(e.what(), "std::exception");
  }
  catch(...) {
    logHelper1("other");
  }
  updateDoTStatus(address, ok ? DoTStatus::Good : DoTStatus::Bad, now + (ok ? dotSuccessWait : dotFailWait), true);
  return ok;
}

bool SyncRes::doResolveAtThisIP(const std::string& prefix, const DNSName& qname, const QType qtype, LWResult& lwr, boost::optional<Netmask>& ednsmask, const DNSName& auth, bool const sendRDQuery, const bool wasForwarded, const DNSName& nsName, const ComboAddress& remoteIP, bool doTCP, bool doDoT, bool& truncated, bool& spoofed, bool dontThrottle)
{
  bool chained = false;
  LWResult::Result resolveret = LWResult::Result::Success;
  s_outqueries++;
  d_outqueries++;
  checkMaxQperQ(qname);

  if(s_maxtotusec && d_totUsec > s_maxtotusec) {
    throw ImmediateServFailException("Too much time waiting for "+qname.toLogString()+"|"+qtype.toString()+", timeouts: "+std::to_string(d_timeouts) +", throttles: "+std::to_string(d_throttledqueries) + ", queries: "+std::to_string(d_outqueries)+", "+std::to_string(d_totUsec/1000)+"msec");
  }

  if(doTCP) {
    if (doDoT) {
      LOG(prefix<<qname<<": using DoT with "<< remoteIP.toStringWithPort() <<endl);
      s_dotoutqueries++;
      d_dotoutqueries++;
    } else {
      LOG(prefix<<qname<<": using TCP with "<< remoteIP.toStringWithPort() <<endl);
      s_tcpoutqueries++;
      d_tcpoutqueries++;
    }
  }

  int preOutQueryRet = RCode::NoError;
  if(d_pdl && d_pdl->preoutquery(remoteIP, d_requestor, qname, qtype, doTCP, lwr.d_records, preOutQueryRet, d_eventTrace, timeval{0, 0})) {
    LOG(prefix<<qname<<": query handled by Lua"<<endl);
  }
  else {
    ednsmask=getEDNSSubnetMask(qname, remoteIP);
    if(ednsmask) {
      LOG(prefix<<qname<<": Adding EDNS Client Subnet Mask "<<ednsmask->toString()<<" to query"<<endl);
      s_ecsqueries++;
    }
    resolveret = asyncresolveWrapper(remoteIP, d_doDNSSEC, qname, auth, qtype.getCode(),
                                     doTCP, sendRDQuery, &d_now, ednsmask, &lwr, &chained, nsName);    // <- we go out on the wire!
    if(ednsmask) {
      s_ecsresponses++;
      LOG(prefix<<qname<<": Received EDNS Client Subnet Mask "<<ednsmask->toString()<<" on response"<<endl);
      if (ednsmask->getBits() > 0) {
        if (ednsmask->isIPv4()) {
          ++SyncRes::s_ecsResponsesBySubnetSize4.at(ednsmask->getBits()-1);
        }
        else {
          ++SyncRes::s_ecsResponsesBySubnetSize6.at(ednsmask->getBits()-1);
        }
      }
    }
  }

  /* preoutquery killed the query by setting dq.rcode to -3 */
  if (preOutQueryRet == -3) {
    throw ImmediateServFailException("Query killed by policy");
  }

  d_totUsec += lwr.d_usec;

  if (resolveret == LWResult::Result::Spoofed) {
    spoofed = true;
    return false;
  }

  accountAuthLatency(lwr.d_usec, remoteIP.sin4.sin_family);
  ++g_stats.authRCode.at(lwr.d_rcode);

  if (!dontThrottle) {
    auto dontThrottleNames = g_dontThrottleNames.getLocal();
    auto dontThrottleNetmasks = g_dontThrottleNetmasks.getLocal();
    dontThrottle = dontThrottleNames->check(nsName) || dontThrottleNetmasks->match(remoteIP);
  }

  if (resolveret != LWResult::Result::Success) {
    /* Error while resolving */
    if (resolveret == LWResult::Result::Timeout) {
      /* Time out */

      LOG(prefix<<qname<<": timeout resolving after "<<lwr.d_usec/1000.0<<"msec "<< (doTCP ? "over TCP" : "")<<endl);
      d_timeouts++;
      s_outgoingtimeouts++;

      if(remoteIP.sin4.sin_family == AF_INET)
        s_outgoing4timeouts++;
      else
        s_outgoing6timeouts++;

      if(t_timeouts)
        t_timeouts->push_back(remoteIP);
    }
    else if (resolveret == LWResult::Result::OSLimitError) {
      /* OS resource limit reached */
      LOG(prefix<<qname<<": hit a local resource limit resolving"<< (doTCP ? " over TCP" : "")<<", probable error: "<<stringerror()<<endl);
      g_stats.resourceLimits++;
    }
    else {
      /* LWResult::Result::PermanentError */
      s_unreachables++;
      d_unreachables++;
      // XXX questionable use of errno
      LOG(prefix<<qname<<": error resolving from "<<remoteIP.toString()<< (doTCP ? " over TCP" : "") <<", possible error: "<<stringerror()<< endl);
    }

    if (resolveret != LWResult::Result::OSLimitError && !chained && !dontThrottle) {
      // don't account for resource limits, they are our own fault
      // And don't throttle when the IP address is on the dontThrottleNetmasks list or the name is part of dontThrottleNames
      s_nsSpeeds.lock()->find_or_enter(nsName.empty()? DNSName(remoteIP.toStringWithPort()) : nsName, d_now).submit(remoteIP, 1000000, d_now); // 1 sec

      // code below makes sure we don't filter COM or the root
      if (s_serverdownmaxfails > 0 && (auth != g_rootdnsname) && s_fails.lock()->incr(remoteIP, d_now) >= s_serverdownmaxfails) {
        LOG(prefix<<qname<<": Max fails reached resolving on "<< remoteIP.toString() <<". Going full throttle for "<< s_serverdownthrottletime <<" seconds" <<endl);
        // mark server as down
        doThrottle(d_now.tv_sec, remoteIP, s_serverdownthrottletime, 10000);
      }
      else if (resolveret == LWResult::Result::PermanentError) {
        // unreachable, 1 minute or 100 queries
        doThrottle(d_now.tv_sec, remoteIP, qname, qtype, 60, 100);
      }
      else {
        // timeout, 10 seconds or 5 queries
       doThrottle(d_now.tv_sec, remoteIP, qname, qtype, 10, 5);
      }
    }

    return false;
  }

  if (lwr.d_validpacket == false) {
    LOG(prefix<<qname<<": "<<nsName<<" ("<<remoteIP.toString()<<") returned a packet we could not parse over " << (doTCP ? "TCP" : "UDP") << ", trying sibling IP or NS"<<endl);
    if (!chained && !dontThrottle) {

      // let's make sure we prefer a different server for some time, if there is one available
      s_nsSpeeds.lock()->find_or_enter(nsName.empty()? DNSName(remoteIP.toStringWithPort()) : nsName, d_now).submit(remoteIP, 1000000, d_now); // 1 sec

      if (doTCP) {
        // we can be more heavy-handed over TCP
        doThrottle(d_now.tv_sec, remoteIP, qname, qtype, 60, 10);
      }
      else {
        doThrottle(d_now.tv_sec, remoteIP, qname, qtype, 10, 2);
      }
    }
    return false;
  }
  else {
    /* we got an answer */
    if (lwr.d_rcode != RCode::NoError && lwr.d_rcode != RCode::NXDomain) {
      LOG(prefix<<qname<<": "<<nsName<<" ("<<remoteIP.toString()<<") returned a "<< RCode::to_s(lwr.d_rcode) << ", trying sibling IP or NS"<<endl);
      if (!chained && !dontThrottle) {
        if (wasForwarded && lwr.d_rcode == RCode::ServFail) {
          // rather than throttling what could be the only server we have for this destination, let's make sure we try a different one if there is one available
          // on the other hand, we might keep hammering a server under attack if there is no other alternative, or the alternative is overwhelmed as well, but
          // at the very least we will detect that if our packets stop being answered
          s_nsSpeeds.lock()->find_or_enter(nsName.empty()? DNSName(remoteIP.toStringWithPort()) : nsName, d_now).submit(remoteIP, 1000000, d_now); // 1 sec
        }
        else {
          doThrottle(d_now.tv_sec, remoteIP, qname, qtype, 60, 3);
        }
      }
      return false;
    }
  }

  /* this server sent a valid answer, mark it backup up if it was down */
  if(s_serverdownmaxfails > 0) {
    s_fails.lock()->clear(remoteIP);
  }

  if (lwr.d_tcbit) {
    truncated = true;

    if (doTCP) {
      LOG(prefix<<qname<<": truncated bit set, over TCP?"<<endl);
      if (!dontThrottle) {
        /* let's treat that as a ServFail answer from this server */
        doThrottle(d_now.tv_sec, remoteIP, qname, qtype, 60, 3);
      }
      return false;
    }
    LOG(prefix<<qname<<": truncated bit set, over UDP"<<endl);

    return true;
  }

  return true;
}

void SyncRes::handleNewTarget(const std::string& prefix, const DNSName& qname, const DNSName& newtarget, const QType qtype, std::vector<DNSRecord>& ret, int& rcode, int depth, const std::vector<DNSRecord>& recordsFromAnswer, vState& state)
{
  if (newtarget == qname) {
    LOG(prefix<<qname<<": status=got a CNAME referral to self, returning SERVFAIL"<<endl);
    ret.clear();
    rcode = RCode::ServFail;
    return;
  }
  if (newtarget.isPartOf(qname)) {
    // a.b.c. CNAME x.a.b.c will go to great depths with QM on
    LOG(prefix<<qname<<": status=got a CNAME referral to child, disabling QM"<<endl);
    setQNameMinimization(false);
  }

  if (depth > 10) {
    LOG(prefix<<qname<<": status=got a CNAME referral, but recursing too deep, returning SERVFAIL"<<endl);
    rcode = RCode::ServFail;
    return;
  }

  if (!d_followCNAME) {
    rcode = RCode::NoError;
    return;
  }

  // Check to see if we already have seen the new target as a previous target
  if (scanForCNAMELoop(newtarget, ret)) {
    LOG(prefix<<qname<<": status=got a CNAME referral that causes a loop, returning SERVFAIL"<<endl);
    ret.clear();
    rcode = RCode::ServFail;
    return;
  }

  if (qtype == QType::DS || qtype == QType::DNSKEY) {
    LOG(prefix<<qname<<": status=got a CNAME referral, but we are looking for a DS or DNSKEY"<<endl);

    if (d_doDNSSEC) {
      addNXNSECS(ret, recordsFromAnswer);
    }

    rcode = RCode::NoError;
    return;
  }

  LOG(prefix<<qname<<": status=got a CNAME referral, starting over with "<<newtarget<<endl);

  set<GetBestNSAnswer> beenthere;
  vState cnameState = vState::Indeterminate;
  rcode = doResolve(newtarget, qtype, ret, depth + 1, beenthere, cnameState);
  LOG(prefix<<qname<<": updating validation state for response to "<<qname<<" from "<<state<<" with the state from the CNAME quest: "<<cnameState<<endl);
  updateValidationState(state, cnameState);
}

bool SyncRes::processAnswer(unsigned int depth, LWResult& lwr, const DNSName& qname, const QType qtype, DNSName& auth, bool wasForwarded, const boost::optional<Netmask> ednsmask, bool sendRDQuery, NsSet &nameservers, std::vector<DNSRecord>& ret, const DNSFilterEngine& dfe, bool* gotNewServers, int* rcode, vState& state, const ComboAddress& remoteIP)
{
  string prefix;
  if(doLog()) {
    prefix=d_prefix;
    prefix.append(depth, ' ');
  }

  if(s_minimumTTL) {
    for(auto& rec : lwr.d_records) {
      rec.d_ttl = max(rec.d_ttl, s_minimumTTL);
    }
  }

  /* if the answer is ECS-specific, a minimum TTL is set for this kind of answers
     and it's higher than the global minimum TTL */
  if (ednsmask && s_minimumECSTTL > 0 && (s_minimumTTL == 0 || s_minimumECSTTL > s_minimumTTL)) {
    for(auto& rec : lwr.d_records) {
      if (rec.d_place == DNSResourceRecord::ANSWER) {
        rec.d_ttl = max(rec.d_ttl, s_minimumECSTTL);
      }
    }
  }

  bool needWildcardProof = false;
  bool gatherWildcardProof = false;
  unsigned int wildcardLabelsCount = 0;
  *rcode = updateCacheFromRecords(depth, lwr, qname, qtype, auth, wasForwarded, ednsmask, state, needWildcardProof, gatherWildcardProof, wildcardLabelsCount, sendRDQuery, remoteIP);
  if (*rcode != RCode::NoError) {
    return true;
  }

  LOG(prefix<<qname<<": determining status after receiving this packet"<<endl);

  set<DNSName> nsset;
  bool realreferral = false;
  bool negindic = false;
  bool negIndicHasSignatures = false;
  DNSName newauth;
  DNSName newtarget;

  bool done = processRecords(prefix, qname, qtype, auth, lwr, sendRDQuery, ret, nsset, newtarget, newauth, realreferral, negindic, state, needWildcardProof, gatherWildcardProof, wildcardLabelsCount, *rcode, negIndicHasSignatures, depth);

  if (done){
    LOG(prefix<<qname<<": status=got results, this level of recursion done"<<endl);
    LOG(prefix<<qname<<": validation status is "<<state<<endl);
    return true;
  }

  if (!newtarget.empty()) {
    handleNewTarget(prefix, qname, newtarget, qtype.getCode(), ret, *rcode, depth, lwr.d_records, state);
    return true;
  }

  if (lwr.d_rcode == RCode::NXDomain) {
    LOG(prefix<<qname<<": status=NXDOMAIN, we are done "<<(negindic ? "(have negative SOA)" : "")<<endl);

    auto tempState = getValidationStatus(qname, negIndicHasSignatures, qtype == QType::DS, depth);
    if (tempState == vState::Secure && (lwr.d_aabit || sendRDQuery) && !negindic) {
      LOG(prefix<<qname<<": NXDOMAIN without a negative indication (missing SOA in authority) in a DNSSEC secure zone, going Bogus"<<endl);
      updateValidationState(state, vState::BogusMissingNegativeIndication);
    }
    else {
      /* we might not have validated any record, because we did get a NXDOMAIN without any SOA
         from an insecure zone, for example */
      updateValidationState(state, tempState);
    }

    if (d_doDNSSEC) {
      addNXNSECS(ret, lwr.d_records);
    }

    *rcode = RCode::NXDomain;
    return true;
  }

  if (nsset.empty() && !lwr.d_rcode && (negindic || lwr.d_aabit || sendRDQuery)) {
    LOG(prefix<<qname<<": status=noerror, other types may exist, but we are done "<<(negindic ? "(have negative SOA) " : "")<<(lwr.d_aabit ? "(have aa bit) " : "")<<endl);

    auto tempState = getValidationStatus(qname, negIndicHasSignatures, qtype == QType::DS, depth);
    if (tempState == vState::Secure && (lwr.d_aabit || sendRDQuery) && !negindic) {
      LOG(prefix<<qname<<": NODATA without a negative indication (missing SOA in authority) in a DNSSEC secure zone, going Bogus"<<endl);
      updateValidationState(state, vState::BogusMissingNegativeIndication);
    }
    else {
      /* we might not have validated any record, because we did get a NODATA without any SOA
         from an insecure zone, for example */
      updateValidationState(state, tempState);
    }

    if (d_doDNSSEC) {
      addNXNSECS(ret, lwr.d_records);
    }

    *rcode = RCode::NoError;
    return true;
  }

  if(realreferral) {
    LOG(prefix<<qname<<": status=did not resolve, got "<<(unsigned int)nsset.size()<<" NS, ");

    nameservers.clear();
    for (auto const &nameserver : nsset) {
      if (d_wantsRPZ && !d_appliedPolicy.wasHit()) {
        bool match = dfe.getProcessingPolicy(nameserver, d_discardedPolicies, d_appliedPolicy);
        if (match) {
          mergePolicyTags(d_policyTags, d_appliedPolicy.getTags());
          if (d_appliedPolicy.d_kind != DNSFilterEngine::PolicyKind::NoAction) { // client query needs an RPZ response
            if (d_pdl && d_pdl->policyHitEventFilter(d_requestor, qname, qtype, d_queryReceivedOverTCP, d_appliedPolicy, d_policyTags, d_discardedPolicies)) {
              /* reset to no match */
              d_appliedPolicy = DNSFilterEngine::Policy();
            }
            else {
              LOG("however "<<nameserver<<" was blocked by RPZ policy '"<<d_appliedPolicy.getName()<<"'"<<endl);
              throw PolicyHitException();
            }
          }
        }
      }
      nameservers.insert({nameserver, {{}, false}});
    }
    LOG("looping to them"<<endl);
    *gotNewServers = true;
    auth=newauth;

    return false;
  }

  return false;
}

bool SyncRes::doDoTtoAuth(const DNSName& ns) const
{
  return g_DoTToAuthNames.getLocal()->check(ns);
}

/** returns:
 *  -1 in case of no results
 *  rcode otherwise
 */
int SyncRes::doResolveAt(NsSet &nameservers, DNSName auth, bool flawedNSSet, const DNSName &qname, const QType qtype,
                         vector<DNSRecord>&ret,
                         unsigned int depth, set<GetBestNSAnswer>&beenthere, vState& state, StopAtDelegation* stopAtDelegation,
                         map<DNSName, vector<ComboAddress>>* fallBack)
{
  auto luaconfsLocal = g_luaconfs.getLocal();
  string prefix;
  if(doLog()) {
    prefix=d_prefix;
    prefix.append(depth, ' ');
  }

  LOG(prefix<<qname<<": Cache consultations done, have "<<(unsigned int)nameservers.size()<<" NS to contact");

  if (nameserversBlockedByRPZ(luaconfsLocal->dfe, nameservers)) {
    /* RPZ hit */
    if (d_pdl && d_pdl->policyHitEventFilter(d_requestor, qname, qtype, d_queryReceivedOverTCP, d_appliedPolicy, d_policyTags, d_discardedPolicies)) {
      /* reset to no match */
      d_appliedPolicy = DNSFilterEngine::Policy();
    }
    else {
      throw PolicyHitException();
    }
  }

  LOG(endl);

  unsigned int addressQueriesForNS = 0;
  for(;;) { // we may get more specific nameservers
    auto rnameservers = shuffleInSpeedOrder(nameservers, doLog() ? (prefix+qname.toString()+": ") : string() );

    // We allow s_maxnsaddressqperq (default 10) queries with empty responses when resolving NS names.
    // If a zone publishes many (more than s_maxnsaddressqperq) NS records, we allow less.
    // This is to "punish" zones that publish many non-resolving NS names.
    // We always allow 5 NS name resolving attempts with empty results.
    unsigned int nsLimit = s_maxnsaddressqperq;
    if (rnameservers.size() > nsLimit) {
      int newLimit = static_cast<int>(nsLimit) - (rnameservers.size() - nsLimit);
      nsLimit = std::max(5, newLimit);
    }

    for(auto tns=rnameservers.cbegin();;++tns) {
      if (addressQueriesForNS >= nsLimit) {
        throw ImmediateServFailException(std::to_string(nsLimit)+" (adjusted max-ns-address-qperq) or more queries with empty results for NS addresses sent resolving "+qname.toLogString());
      }
      if(tns==rnameservers.cend()) {
        LOG(prefix<<qname<<": Failed to resolve via any of the "<<(unsigned int)rnameservers.size()<<" offered NS at level '"<<auth<<"'"<<endl);
        if(!auth.isRoot() && flawedNSSet) {
          LOG(prefix<<qname<<": Ageing nameservers for level '"<<auth<<"', next query might succeed"<<endl);

          if(g_recCache->doAgeCache(d_now.tv_sec, auth, QType::NS, 10))
            g_stats.nsSetInvalidations++;
        }
        return -1;
      }

      bool cacheOnly = false;
      // this line needs to identify the 'self-resolving' behaviour
      if(qname == tns->first && (qtype.getCode() == QType::A || qtype.getCode() == QType::AAAA)) {
        /* we might have a glue entry in cache so let's try this NS
           but only if we have enough in the cache to know how to reach it */
        LOG(prefix<<qname<<": Using NS to resolve itself, but only using what we have in cache ("<<(1+tns-rnameservers.cbegin())<<"/"<<rnameservers.size()<<")"<<endl);
        cacheOnly = true;
      }

      typedef vector<ComboAddress> remoteIPs_t;
      remoteIPs_t remoteIPs;
      remoteIPs_t::iterator remoteIP;
      bool pierceDontQuery=false;
      bool sendRDQuery=false;
      boost::optional<Netmask> ednsmask;
      LWResult lwr;
      const bool wasForwarded = tns->first.empty() && (!nameservers[tns->first].first.empty());
      int rcode = RCode::NoError;
      bool gotNewServers = false;

      if (tns->first.empty() && !wasForwarded) {
        static ComboAddress const s_oobRemote("255.255.255.255");
        LOG(prefix<<qname<<": Domain is out-of-band"<<endl);
        /* setting state to indeterminate since validation is disabled for local auth zone,
           and Insecure would be misleading. */
        state = vState::Indeterminate;
        d_wasOutOfBand = doOOBResolve(qname, qtype, lwr.d_records, depth, lwr.d_rcode);
        lwr.d_tcbit=false;
        lwr.d_aabit=true;

        /* we have received an answer, are we done ? */
        bool done = processAnswer(depth, lwr, qname, qtype, auth, false, ednsmask, sendRDQuery, nameservers, ret, luaconfsLocal->dfe, &gotNewServers, &rcode, state, s_oobRemote);
        if (done) {
          return rcode;
        }
        if (gotNewServers) {
          if (stopAtDelegation && *stopAtDelegation == Stop) {
            *stopAtDelegation = Stopped;
            return rcode;
          }
          break;
        }
      }
      else {
        if (fallBack != nullptr) {
          if (auto it = fallBack->find(tns->first); it != fallBack->end()) {
            remoteIPs = it->second;
          }
        }
        if (remoteIPs.size() == 0) {
          remoteIPs = retrieveAddressesForNS(prefix, qname, tns, depth, beenthere, rnameservers, nameservers, sendRDQuery, pierceDontQuery, flawedNSSet, cacheOnly, addressQueriesForNS);
        }

        if(remoteIPs.empty()) {
          LOG(prefix<<qname<<": Failed to get IP for NS "<<tns->first<<", trying next if available"<<endl);
          flawedNSSet=true;
          continue;
        }
        else {
          bool hitPolicy{false};
          LOG(prefix<<qname<<": Resolved '"<<auth<<"' NS "<<tns->first<<" to: ");
          for(remoteIP = remoteIPs.begin(); remoteIP != remoteIPs.end(); ++remoteIP) {
            if(remoteIP != remoteIPs.begin()) {
              LOG(", ");
            }
            LOG(remoteIP->toString());
            if(nameserverIPBlockedByRPZ(luaconfsLocal->dfe, *remoteIP)) {
              hitPolicy = true;
            }
          }
          LOG(endl);
          if (hitPolicy) { //implies d_wantsRPZ
            /* RPZ hit */
            if (d_pdl && d_pdl->policyHitEventFilter(d_requestor, qname, qtype, d_queryReceivedOverTCP, d_appliedPolicy, d_policyTags, d_discardedPolicies)) {
              /* reset to no match */
              d_appliedPolicy = DNSFilterEngine::Policy();
            }
            else {
              throw PolicyHitException();
            }
          }
        }

        for(remoteIP = remoteIPs.begin(); remoteIP != remoteIPs.end(); ++remoteIP) {
          LOG(prefix<<qname<<": Trying IP "<< remoteIP->toStringWithPort() <<", asking '"<<qname<<"|"<<qtype<<"'"<<endl);

          if (throttledOrBlocked(prefix, *remoteIP, qname, qtype, pierceDontQuery)) {
            // As d_throttledqueries might be increased, check the max-qperq condition
            checkMaxQperQ(qname);
            continue;
          }

          bool truncated = false;
          bool spoofed = false;
          bool gotAnswer = false;
          bool doDoT = false;

          if (doDoTtoAuth(tns->first)) {
            remoteIP->setPort(853);
            doDoT = true;
          }
          if (SyncRes::s_dot_to_port_853 && remoteIP->getPort() == 853) {
            doDoT = true;
          }
          bool forceTCP = doDoT;

          if (!doDoT && s_max_busy_dot_probes > 0) {
            submitTryDotTask(*remoteIP, auth, tns->first, d_now.tv_sec);
          }
          if (!forceTCP) {
            gotAnswer = doResolveAtThisIP(prefix, qname, qtype, lwr, ednsmask, auth, sendRDQuery, wasForwarded,
                                          tns->first, *remoteIP, false, false, truncated, spoofed);
          }
          if (forceTCP || (spoofed || (gotAnswer && truncated))) {
            /* retry, over TCP this time */
            gotAnswer = doResolveAtThisIP(prefix, qname, qtype, lwr, ednsmask, auth, sendRDQuery, wasForwarded,
                                          tns->first, *remoteIP, true, doDoT, truncated, spoofed);
          }

          if (!gotAnswer) {
            if (doDoT && s_max_busy_dot_probes > 0) {
              // This is quite pessimistic...
              updateDoTStatus(*remoteIP, DoTStatus::Bad, d_now.tv_sec + dotFailWait);
            }
            continue;
          }

          LOG(prefix<<qname<<": Got "<<(unsigned int)lwr.d_records.size()<<" answers from "<<tns->first<<" ("<< remoteIP->toString() <<"), rcode="<<lwr.d_rcode<<" ("<<RCode::to_s(lwr.d_rcode)<<"), aa="<<lwr.d_aabit<<", in "<<lwr.d_usec/1000<<"ms"<<endl);

          if (doDoT && s_max_busy_dot_probes > 0) {
            updateDoTStatus(*remoteIP, DoTStatus::Good, d_now.tv_sec + dotSuccessWait);
          }
          /*  // for you IPv6 fanatics :-)
              if(remoteIP->sin4.sin_family==AF_INET6)
              lwr.d_usec/=3;
          */
          //        cout<<"msec: "<<lwr.d_usec/1000.0<<", "<<g_avgLatency/1000.0<<'\n';

          s_nsSpeeds.lock()->find_or_enter(tns->first.empty()? DNSName(remoteIP->toStringWithPort()) : tns->first, d_now).submit(*remoteIP, lwr.d_usec, d_now);

          /* we have received an answer, are we done ? */
          bool done = processAnswer(depth, lwr, qname, qtype, auth, wasForwarded, ednsmask, sendRDQuery, nameservers, ret, luaconfsLocal->dfe, &gotNewServers, &rcode, state, *remoteIP);
          if (done) {
            return rcode;
          }
          if (gotNewServers) {
            if (stopAtDelegation && *stopAtDelegation == Stop) {
              *stopAtDelegation = Stopped;
              return rcode;
            }
            break;
          }
          /* was lame */
          doThrottle(d_now.tv_sec, *remoteIP, qname, qtype, 60, 100);
        }

        if (gotNewServers) {
          break;
        }

        if(remoteIP == remoteIPs.cend())  // we tried all IP addresses, none worked
          continue;

      }
    }
  }
  return -1;
}

void SyncRes::setQuerySource(const Netmask& netmask)
{
  if (!netmask.empty()) {
    d_outgoingECSNetwork = netmask;
  }
  else {
    d_outgoingECSNetwork = boost::none;
  }
}

void SyncRes::setQuerySource(const ComboAddress& requestor, boost::optional<const EDNSSubnetOpts&> incomingECS)
{
  d_requestor = requestor;

  if (incomingECS && incomingECS->source.getBits() > 0) {
    d_cacheRemote = incomingECS->source.getMaskedNetwork();
    uint8_t bits = std::min(incomingECS->source.getBits(), (incomingECS->source.isIPv4() ? s_ecsipv4limit : s_ecsipv6limit));
    ComboAddress trunc = incomingECS->source.getNetwork();
    trunc.truncate(bits);
    d_outgoingECSNetwork = boost::optional<Netmask>(Netmask(trunc, bits));
  } else {
    d_cacheRemote = d_requestor;
    if(!incomingECS && s_ednslocalsubnets.match(d_requestor)) {
      ComboAddress trunc = d_requestor;
      uint8_t bits = d_requestor.isIPv4() ? 32 : 128;
      bits = std::min(bits, (trunc.isIPv4() ? s_ecsipv4limit : s_ecsipv6limit));
      trunc.truncate(bits);
      d_outgoingECSNetwork = boost::optional<Netmask>(Netmask(trunc, bits));
    } else if (s_ecsScopeZero.source.getBits() > 0) {
      /* RFC7871 says we MUST NOT send any ECS if the source scope is 0.
         But using an empty ECS in that case would mean inserting
         a non ECS-specific entry into the cache, preventing any further
         ECS-specific query to be sent.
         So instead we use the trick described in section 7.1.2:
         "The subsequent Recursive Resolver query to the Authoritative Nameserver
         will then either not include an ECS option or MAY optionally include
         its own address information, which is what the Authoritative
         Nameserver will almost certainly use to generate any Tailored
         Response in lieu of an option.  This allows the answer to be handled
         by the same caching mechanism as other queries, with an explicit
         indicator of the applicable scope.  Subsequent Stub Resolver queries
         for /0 can then be answered from this cached response.
      */
      d_outgoingECSNetwork = boost::optional<Netmask>(s_ecsScopeZero.source.getMaskedNetwork());
      d_cacheRemote = s_ecsScopeZero.source.getNetwork();
    } else {
      // ECS disabled because no scope-zero address could be derived.
      d_outgoingECSNetwork = boost::none;
    }
  }
}

boost::optional<Netmask> SyncRes::getEDNSSubnetMask(const DNSName& dn, const ComboAddress& rem)
{
  if(d_outgoingECSNetwork && (s_ednsdomains.check(dn) || s_ednsremotesubnets.match(rem))) {
    return d_outgoingECSNetwork;
  }
  return boost::none;
}

void SyncRes::parseEDNSSubnetAllowlist(const std::string& alist)
{
  vector<string> parts;
  stringtok(parts, alist, ",; ");
  for(const auto& a : parts) {
    try {
      s_ednsremotesubnets.addMask(Netmask(a));
    }
    catch(...) {
      s_ednsdomains.add(DNSName(a));
    }
  }
}

void SyncRes::parseEDNSSubnetAddFor(const std::string& subnetlist)
{
  vector<string> parts;
  stringtok(parts, subnetlist, ",; ");
  for(const auto& a : parts) {
    s_ednslocalsubnets.addMask(a);
  }
}

// used by PowerDNSLua - note that this neglects to add the packet count & statistics back to pdns_recursor.cc
int directResolve(const DNSName& qname, const QType qtype, const QClass qclass, vector<DNSRecord>& ret, shared_ptr<RecursorLua4> pdl, Logr::log_t log)
{
  return directResolve(qname, qtype, qclass, ret, pdl, SyncRes::s_qnameminimization, log);
}

int directResolve(const DNSName& qname, const QType qtype, const QClass qclass, vector<DNSRecord>& ret, shared_ptr<RecursorLua4> pdl, bool qm, Logr::log_t slog)
{
  auto log = slog->withValues("qname", Logging::Loggable(qname), "qtype", Logging::Loggable(qtype));

  struct timeval now;
  gettimeofday(&now, 0);

  SyncRes sr(now);
  sr.setQNameMinimization(qm);
  if (pdl) {
    sr.setLuaEngine(pdl);
  }

  int res = -1;
  const std::string msg = "Exception while resolving";
  try {
    res = sr.beginResolve(qname, qtype, qclass, ret, 0);
  }
  catch(const PDNSException& e) {
    SLOG(g_log<<Logger::Error<<"Failed to resolve "<<qname<<", got pdns exception: "<<e.reason<<endl,
         log->error(Logr::Error, e.reason, msg, "exception", Logging::Loggable("PDNSException")));
    ret.clear();
  }
  catch(const ImmediateServFailException& e) {
    SLOG(g_log<<Logger::Error<<"Failed to resolve "<<qname<<", got ImmediateServFailException: "<<e.reason<<endl,
         log->error(Logr::Error, e.reason, msg, "exception", Logging::Loggable("ImmediateServFailException")));
    ret.clear();
  }
  catch(const PolicyHitException& e) {
    SLOG(g_log<<Logger::Error<<"Failed to resolve "<<qname<<", got a policy hit"<<endl,
         log->info(Logr::Error, msg, "exception", Logging::Loggable("PolicyHitException")));
    ret.clear();
  }
  catch(const std::exception& e) {
    SLOG(g_log<<Logger::Error<<"Failed to resolve "<<qname<<", got STL error: "<<e.what()<<endl,
         log->error(Logr::Error, e.what(), msg, "exception", Logging::Loggable("std::exception")));
    ret.clear();
  }
  catch(...) {
    SLOG(g_log<<Logger::Error<<"Failed to resolve "<<qname<<", got an exception"<<endl,
         log->info(Logr::Error, msg));
    ret.clear();
  }

  return res;
}

int SyncRes::getRootNS(struct timeval now, asyncresolve_t asyncCallback, unsigned int depth, Logr::log_t log) {
  SyncRes sr(now);
  sr.setDoEDNS0(true);
  sr.setUpdatingRootNS();
  sr.setDoDNSSEC(g_dnssecmode != DNSSECMode::Off);
  sr.setDNSSECValidationRequested(g_dnssecmode != DNSSECMode::Off && g_dnssecmode != DNSSECMode::ProcessNoValidate);
  sr.setAsyncCallback(asyncCallback);
  sr.setRefreshAlmostExpired(true);

  const string msg = "Failed to update . records";
  vector<DNSRecord> ret;
  int res = -1;
  try {
    res = sr.beginResolve(g_rootdnsname, QType::NS, 1, ret, depth + 1);
    if (g_dnssecmode != DNSSECMode::Off && g_dnssecmode != DNSSECMode::ProcessNoValidate) {
      auto state = sr.getValidationState();
      if (vStateIsBogus(state)) {
        throw PDNSException("Got Bogus validation result for .|NS");
      }
    }
  }
  catch (const PDNSException& e) {
    SLOG(g_log<<Logger::Error<<"Failed to update . records, got an exception: "<<e.reason<<endl,
         log->error(Logr::Error, e.reason, msg, "exception", Logging::Loggable("PDNSException")));
  }
  catch (const ImmediateServFailException& e) {
    SLOG(g_log<<Logger::Error<<"Failed to update . records, got an exception: "<<e.reason<<endl,
         log->error(Logr::Error, e.reason, msg, "exception", Logging::Loggable("ImmediateServFailException")));
  }
  catch (const PolicyHitException& e) {
    SLOG(g_log<<Logger::Error<<"Failed to update . records, got a policy hit"<<endl,
         log->info(Logr::Error, msg, "exception", Logging::Loggable("PolicyHitException")));
    ret.clear();
  }
  catch (const std::exception& e) {
    SLOG(g_log<<Logger::Error<<"Failed to update . records, got an exception: "<<e.what()<<endl,
         log->error(Logr::Error, e.what(), msg, "exception", Logging::Loggable("std::exception")));
  }
  catch (...) {
    SLOG(g_log<<Logger::Error<<"Failed to update . records, got an exception"<<endl,
         log->info(Logr::Error, msg));
  }

  if (res == 0) {
    SLOG(g_log<<Logger::Debug<<"Refreshed . records"<<endl,
         log->info(Logr::Debug, "Refreshed . records"));
  }
  else {
    SLOG(g_log<<Logger::Warning<<"Failed to update root NS records, RCODE="<<res<<endl,
         log->info(Logr::Warning, msg, "rcode", Logging::Loggable(res)));
  }
  return res;
}