File: recursor_cache.cc

package info (click to toggle)
pdns-recursor 5.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,108 kB
  • sloc: cpp: 109,513; javascript: 20,651; python: 5,657; sh: 5,069; makefile: 780; ansic: 582; xml: 37
file content (1278 lines) | stat: -rw-r--r-- 46,299 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
/*
 * 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.
 */

#include "config.h"

#include <cinttypes>
#include <protozero/pbf_builder.hpp>
#include <protozero/pbf_message.hpp>

#include "recursor_cache.hh"
#include "misc.hh"
#include "dnsrecords.hh"
#include "syncres.hh"
#include "namespaces.hh"
#include "cachecleaner.hh"
#include "rec-taskqueue.hh"
#include "version.hh"
#include "protozero-helpers.hh"

/*
 * SERVE-STALE: the general approach
 *
 * The general switch to enable serve-stale is s_maxServedStaleExtensions. If this value is zero, no
 * serve-stale is done. If it is positive, it determines how many times the serve-stale status of a
 * record can be extended.
 *
 * Each record in the cache has a field d_servedStale. If this value is zero, no special handling is
 * done. If it is positive, the record is being served stale. The value determines how many times
 * the serve-stale status was extended. Each time an extension happens, the value is incremented and
 * a task to see if the record resolves will be pushed. When the served-stale status is extended,
 * the TTD of a record is also changed so the record will be considered not-expired by the get()
 * function. The TTD will be s_serveStaleExtensionPeriod in the future, unless the original TTL was
 * smaller than that. If d_servedStale reaches s_maxServedStaleExtensions the serve-stale status
 * will no longer be extended and the record will be considered really expired.
 *
 * With s_serveStaleExtensionPeriod of 30 seconds, setting s_maxServedStaleExtensions to 1440 will
 * cause a record to be served stale a maximum of 30s * 1440 = 12 hours. If the original TTL is
 * smaller than 30, this period will be shorter. If there was a long time between serve-stale
 * extensions, the value of d_servedStale will be incremented by more than one to account for the
 * longer period.
 *
 * If serve-stale is enabled, the resolving process first will try to resolve a record in the
 * ordinary way, with the difference that a timeout will not lead to an ImmediateServFailException
 * being passed to the caller, but the resolving will be tried again with a flag to allow marking
 * records as served-stale. If the second time around a timeout happens, an
 * ImmediateServFailException *will* be passed to the caller.
 *
 * When serving stale, records are only wiped from the cache if they are older than
 * s_maxServedStaleExtensions * s_serveStaleExtensionPeriod. See isStale(). This is to have a good
 * chance of records being available for marking stale if a name server has an issue.
 *
 * The tasks to see if nameservers are reachable again do a resolve in refresh mode, considering
 * served-stale records as expired. When a record resolves again, the d_servedStale field will be
 * reset.
 */

uint16_t MemRecursorCache::s_maxServedStaleExtensions;
uint16_t MemRecursorCache::s_maxRRSetSize = 256;
bool MemRecursorCache::s_limitQTypeAny = true;

const MemRecursorCache::AuthRecs MemRecursorCache::s_emptyAuthRecs = std::make_shared<MemRecursorCache::AuthRecsVec>();
const MemRecursorCache::SigRecs MemRecursorCache::s_emptySigRecs = std::make_shared<MemRecursorCache::SigRecsVec>();

void MemRecursorCache::resetStaticsForTests()
{
  s_maxServedStaleExtensions = 0;
  SyncRes::s_refresh_ttlperc = 0;
  SyncRes::s_locked_ttlperc = 0;
  SyncRes::s_minimumTTL = 0;
  s_maxRRSetSize = 256;
  s_limitQTypeAny = true;
}

MemRecursorCache::MemRecursorCache(size_t mapsCount) :
  d_maps(mapsCount == 0 ? 1 : mapsCount)
{
}

size_t MemRecursorCache::size() const
{
  size_t count = 0;
  for (const auto& shard : d_maps) {
    count += shard.getEntriesCount();
  }
  return count;
}

pair<uint64_t, uint64_t> MemRecursorCache::stats()
{
  uint64_t contended = 0;
  uint64_t acquired = 0;
  for (auto& shard : d_maps) {
    auto lockedShard = shard.lock();
    contended += lockedShard->d_contended_count;
    acquired += lockedShard->d_acquired_count;
  }
  return {contended, acquired};
}

size_t MemRecursorCache::ecsIndexSize()
{
  // XXX!
  size_t count = 0;
  for (auto& shard : d_maps) {
    auto lockedShard = shard.lock();
    count += lockedShard->d_ecsIndex.size();
  }
  return count;
}

size_t MemRecursorCache::CacheEntry::authRecsSizeEstimate() const
{
  size_t ret = 0;
  if (d_authorityRecs) {
    for (const auto& record : *d_authorityRecs) {
      ret += record.sizeEstimate();
    }
  }
  return ret;
}

size_t MemRecursorCache::CacheEntry::sigRecsSizeEstimate() const
{
  size_t ret = 0;
  if (d_signatures) {
    for (const auto& record : *d_signatures) {
      ret += record->sizeEstimate();
    }
  }
  return ret;
}

size_t MemRecursorCache::CacheEntry::sizeEstimate() const
{
  auto ret = sizeof(struct CacheEntry);
  ret += d_qname.sizeEstimate();
  ret += d_authZone.sizeEstimate();
  for (const auto& record : d_records) {
    ret += record->sizeEstimate();
  }
  ret += authRecsSizeEstimate();
  ret += sigRecsSizeEstimate();
  return ret;
}

// this function is too slow to poll!
size_t MemRecursorCache::bytes()
{
  size_t ret = 0;
  for (auto& shard : d_maps) {
    auto lockedShard = shard.lock();
    for (const auto& entry : lockedShard->d_map) {
      ret += entry.sizeEstimate();
    }
  }
  return ret;
}

static void updateDNSSECValidationStateFromCache(boost::optional<vState>& state, const vState stateUpdate)
{
  // if there was no state it's easy */
  if (state == boost::none) {
    state = stateUpdate;
    return;
  }

  if (stateUpdate == vState::TA) {
    state = vState::Secure;
  }
  else if (stateUpdate == vState::NTA) {
    state = vState::Insecure;
  }
  else if (vStateIsBogus(stateUpdate) || stateUpdate == vState::Indeterminate) {
    state = stateUpdate;
  }
  else if (stateUpdate == vState::Insecure || stateUpdate == vState::Secure) {
    if (!vStateIsBogus(*state) && *state != vState::Indeterminate) {
      state = stateUpdate;
    }
  }
}

template <typename T>
static void ptrAssign(T* ptr, const T& value)
{
  if (ptr != nullptr) {
    *ptr = value;
  }
}

time_t MemRecursorCache::handleHit(time_t now, MapCombo::LockedContent& content, OrderedTagIterator_t& entry, const DNSName& qname, uint32_t& origTTL, vector<DNSRecord>* res, SigRecs* signatures, AuthRecs* authorityRecs, bool* variable, boost::optional<vState>& state, bool* wasAuth, DNSName* fromAuthZone, ComboAddress* fromAuthIP)
{
  // MUTEX SHOULD BE ACQUIRED (as indicated by the reference to the content which is protected by a lock)
  if (entry->d_tooBig) {
    throw ImmediateServFailException("too many records in RRSet");
  }
  time_t ttd = entry->d_ttd;
  if (ttd <= now) {
    // Expired, don't bother returning contents. Callers *MUST* check return value of get(), and only look at the entry
    // if it returned > 0
    return ttd;
  }
  origTTL = entry->d_orig_ttl;

  if (!entry->d_netmask.empty() || entry->d_rtag) {
    ptrAssign(variable, true);
  }

  if (res != nullptr) {
    if (s_limitQTypeAny && res->size() + entry->d_records.size() > s_maxRRSetSize) {
      throw ImmediateServFailException("too many records in result");
    }

    res->reserve(res->size() + entry->d_records.size());

    for (const auto& record : entry->d_records) {
      DNSRecord result;
      result.d_name = qname;
      result.d_type = entry->d_qtype;
      result.d_class = QClass::IN;
      result.setContent(record);
      // coverity[store_truncates_time_t]
      result.d_ttl = static_cast<uint32_t>(entry->d_ttd);
      result.d_place = DNSResourceRecord::ANSWER;
      res->push_back(std::move(result));
    }
  }

  if (signatures != nullptr) {
    if (*signatures && !(*signatures)->empty() && entry->d_signatures && !entry->d_signatures->empty()) {
      // Return a new vec if we need to append to a non-empty vector
      SigRecsVec vec(**signatures);
      vec.insert(vec.end(), entry->d_signatures->cbegin(), entry->d_signatures->cend());
      *signatures = std::make_shared<SigRecsVec>(std::move(vec));
    }
    else {
      *signatures = entry->d_signatures ? entry->d_signatures : s_emptySigRecs;
    }
  }

  if (authorityRecs != nullptr) {
    // XXX Might need to be adapted like sigs to handle a non-empty incoming authorityRecs
    assert(*authorityRecs == nullptr || (*authorityRecs)->empty());
    *authorityRecs = entry->d_authorityRecs ? entry->d_authorityRecs : s_emptyAuthRecs;
  }

  updateDNSSECValidationStateFromCache(state, entry->d_state);

  if (wasAuth != nullptr) {
    *wasAuth = *wasAuth && entry->d_auth;
  }
  ptrAssign(fromAuthZone, entry->d_authZone);
  ptrAssign(fromAuthIP, entry->d_from);

  moveCacheItemToBack<SequencedTag>(content.d_map, entry);

  return ttd;
}

static void pushRefreshTask(const DNSName& qname, QType qtype, time_t deadline, const Netmask& netmask)
{
  if (qtype == QType::ADDR) {
    pushAlmostExpiredTask(qname, QType::A, deadline, netmask);
    pushAlmostExpiredTask(qname, QType::AAAA, deadline, netmask);
  }
  else {
    pushAlmostExpiredTask(qname, qtype, deadline, netmask);
  }
}

void MemRecursorCache::updateStaleEntry(time_t now, MemRecursorCache::OrderedTagIterator_t& entry)
{
  // We need to take care a infrequently access stale item cannot be extended past
  // s_maxServedStaleExtension * s_serveStaleExtensionPeriod
  // We look how old the entry is, and increase d_servedStale accordingly, taking care not to overflow
  const time_t howlong = std::max(static_cast<time_t>(1), now - entry->d_ttd);
  const uint32_t extension = std::max(1U, std::min(entry->d_orig_ttl, s_serveStaleExtensionPeriod));
  entry->d_servedStale = std::min(entry->d_servedStale + 1 + howlong / extension, static_cast<time_t>(s_maxServedStaleExtensions));
  entry->d_ttd = now + extension;

  pushRefreshTask(entry->d_qname, entry->d_qtype, entry->d_ttd, entry->d_netmask);
}

// If we are serving this record stale (or *should*) and the ttd has
// passed increase ttd to the future and remember that we did. Also
// push a refresh task.
void MemRecursorCache::handleServeStaleBookkeeping(time_t now, bool serveStale, MemRecursorCache::OrderedTagIterator_t& entry)
{
  if ((serveStale || entry->d_servedStale > 0) && entry->d_ttd <= now && entry->d_servedStale < s_maxServedStaleExtensions) {
    updateStaleEntry(now, entry);
  }
}

MemRecursorCache::cache_t::const_iterator MemRecursorCache::getEntryUsingECSIndex(MapCombo::LockedContent& map, time_t now, const DNSName& qname, const QType qtype, bool requireAuth, const ComboAddress& who, bool serveStale)
{
  // MUTEX SHOULD BE ACQUIRED (as indicated by the reference to the content which is protected by a lock)
  auto ecsIndexKey = std::tie(qname, qtype);
  auto ecsIndex = map.d_ecsIndex.find(ecsIndexKey);
  if (ecsIndex != map.d_ecsIndex.end() && !ecsIndex->isEmpty()) {
    /* we have netmask-specific entries, let's see if we match one */
    while (true) {
      const Netmask best = ecsIndex->lookupBestMatch(who);
      if (best.empty()) {
        /* we have nothing more specific for you */
        break;
      }
      auto key = std::tuple(qname, qtype, boost::none, best);
      auto entry = map.d_map.find(key);
      if (entry == map.d_map.end()) {
        /* ecsIndex is not up-to-date */
        ecsIndex->removeNetmask(best);
        if (ecsIndex->isEmpty()) {
          map.d_ecsIndex.erase(ecsIndex);
          break;
        }
        continue;
      }
      handleServeStaleBookkeeping(now, serveStale, entry);

      if (entry->d_ttd > now) {
        if (!requireAuth || entry->d_auth) {
          return entry;
        }
        /* we need auth data and the best match is not authoritative */
        return map.d_map.end();
      }
      /* this netmask-specific entry has expired */
      moveCacheItemToFront<SequencedTag>(map.d_map, entry);
      // XXX when serving stale, it should be kept, but we don't want a match wth lookupBestMatch()...
      ecsIndex->removeNetmask(best);
      if (ecsIndex->isEmpty()) {
        map.d_ecsIndex.erase(ecsIndex);
        break;
      }
    }
  }

  /* we have nothing specific, let's see if we have a generic one */
  auto key = std::tuple(qname, qtype, boost::none, Netmask());
  auto entry = map.d_map.find(key);
  if (entry != map.d_map.end()) {
    handleServeStaleBookkeeping(now, serveStale, entry);
    if (entry->d_ttd > now) {
      if (!requireAuth || entry->d_auth) {
        return entry;
      }
    }
    else {
      moveCacheItemToFront<SequencedTag>(map.d_map, entry);
    }
  }

  /* nothing for you, sorry */
  return map.d_map.end();
}

MemRecursorCache::Entries MemRecursorCache::getEntries(MapCombo::LockedContent& map, const DNSName& qname, const QType /* qtype */, const OptTag& rtag)
{
  // MUTEX SHOULD BE ACQUIRED
  if (!map.d_cachecachevalid || map.d_cachedqname != qname || map.d_cachedrtag != rtag) {
    map.d_cachedqname = qname;
    map.d_cachedrtag = rtag;
    const auto& idx = map.d_map.get<NameAndRTagOnlyHashedTag>();
    map.d_cachecache = idx.equal_range(std::tie(qname, rtag));
    map.d_cachecachevalid = true;
  }
  return map.d_cachecache;
}

bool MemRecursorCache::entryMatches(MemRecursorCache::OrderedTagIterator_t& entry, const QType qtype, bool requireAuth, const ComboAddress& who)
{
  // This code assumes that if a routing tag is present, it matches
  // MUTEX SHOULD BE ACQUIRED
  if (requireAuth && !entry->d_auth) {
    return false;
  }

  bool match = (entry->d_qtype == qtype || qtype == QType::ANY || (qtype == QType::ADDR && (entry->d_qtype == QType::A || entry->d_qtype == QType::AAAA)))
    && (entry->d_netmask.empty() || entry->d_netmask.match(who));
  return match;
}

// Fake a cache miss if more than refreshTTLPerc of the original TTL has passed
time_t MemRecursorCache::fakeTTD(MemRecursorCache::OrderedTagIterator_t& entry, const DNSName& qname, QType qtype, time_t ret, time_t now, uint32_t origTTL, bool refresh)
{
  time_t ttl = ret - now;
  // If we are checking an entry being served stale in refresh mode,
  // we always consider it stale so a real refresh attempt will be
  // kicked by SyncRes
  if (refresh && entry->d_servedStale > 0) {
    return -1;
  }
  if (ttl > 0 && SyncRes::s_refresh_ttlperc > 0) {
    const uint32_t deadline = origTTL * SyncRes::s_refresh_ttlperc / 100;
    // coverity[store_truncates_time_t]
    const bool almostExpired = static_cast<uint32_t>(ttl) <= deadline;
    if (almostExpired && qname != g_rootdnsname) {
      if (refresh) {
        return -1;
      }
      if (!entry->d_submitted) {
        pushRefreshTask(qname, qtype, entry->d_ttd, entry->d_netmask);
        entry->d_submitted = true;
      }
    }
  }
  return ttl;
}

// returns -1 for no hits
time_t MemRecursorCache::get(time_t now, const DNSName& qname, const QType qtype, Flags flags, vector<DNSRecord>* res, const ComboAddress& who, const OptTag& routingTag, SigRecs* signatures, AuthRecs* authorityRecs, bool* variable, vState* state, bool* wasAuth, DNSName* fromAuthZone, ComboAddress* fromAuthIP) // NOLINT(readability-function-cognitive-complexity)
{
  bool requireAuth = (flags & RequireAuth) != 0;
  bool refresh = (flags & Refresh) != 0;
  bool serveStale = (flags & ServeStale) != 0;

  boost::optional<vState> cachedState{boost::none};
  uint32_t origTTL = 0;

  if (res != nullptr) {
    res->clear();
  }

  // we might retrieve more than one entry, we need to set that to true
  // so it will be set to false if at least one entry is not auth
  ptrAssign(wasAuth, true);

  auto& shard = getMap(qname);
  auto lockedShard = shard.lock();

  /* If we don't have any netmask-specific entries at all, let's just skip this
     to be able to use the nice d_cachecache hack. */
  if (qtype != QType::ANY && !lockedShard->d_ecsIndex.empty() && !routingTag) {
    if (qtype == QType::ADDR) {
      time_t ret = -1;

      auto entryA = getEntryUsingECSIndex(*lockedShard, now, qname, QType::A, requireAuth, who, serveStale);
      if (entryA != lockedShard->d_map.end()) {
        ret = handleHit(now, *lockedShard, entryA, qname, origTTL, res, signatures, authorityRecs, variable, cachedState, wasAuth, fromAuthZone, fromAuthIP);
      }
      auto entryAAAA = getEntryUsingECSIndex(*lockedShard, now, qname, QType::AAAA, requireAuth, who, serveStale);
      if (entryAAAA != lockedShard->d_map.end()) {
        time_t ttdAAAA = handleHit(now, *lockedShard, entryAAAA, qname, origTTL, res, signatures, authorityRecs, variable, cachedState, wasAuth, fromAuthZone, fromAuthIP);
        if (ret > 0) {
          ret = std::min(ret, ttdAAAA);
        }
        else {
          ret = ttdAAAA;
        }
      }

      if (cachedState && ret > 0) {
        ptrAssign(state, *cachedState);
      }

      return ret > 0 ? (ret - now) : ret;
    }
    auto entry = getEntryUsingECSIndex(*lockedShard, now, qname, qtype, requireAuth, who, serveStale);
    if (entry != lockedShard->d_map.end()) {
      time_t ret = handleHit(now, *lockedShard, entry, qname, origTTL, res, signatures, authorityRecs, variable, cachedState, wasAuth, fromAuthZone, fromAuthIP);
      if (cachedState && ret > now) {
        ptrAssign(state, *cachedState);
      }
      return fakeTTD(entry, qname, qtype, ret, now, origTTL, refresh);
    }
    return -1;
  }

  if (routingTag) {
    auto entries = getEntries(*lockedShard, qname, qtype, routingTag);
    unsigned int found = 0;
    time_t ttd{};

    if (entries.first != entries.second) {
      OrderedTagIterator_t firstIndexIterator;
      for (auto i = entries.first; i != entries.second; ++i) {
        firstIndexIterator = lockedShard->d_map.project<OrderedTag>(i);

        // When serving stale, we consider expired records
        if (!i->isEntryUsable(now, serveStale)) {
          moveCacheItemToFront<SequencedTag>(lockedShard->d_map, firstIndexIterator);
          continue;
        }

        if (!entryMatches(firstIndexIterator, qtype, requireAuth, who)) {
          continue;
        }
        ++found;

        handleServeStaleBookkeeping(now, serveStale, firstIndexIterator);

        ttd = handleHit(now, *lockedShard, firstIndexIterator, qname, origTTL, res, signatures, authorityRecs, variable, cachedState, wasAuth, fromAuthZone, fromAuthIP);

        if (qtype == QType::ADDR && found == 2) {
          break;
        }
        if (qtype != QType::ANY) { // normally if we have a hit, we are done
          break;
        }
      }
      if (found > 0) {
        if (cachedState && ttd > now) {
          ptrAssign(state, *cachedState);
        }
        return fakeTTD(firstIndexIterator, qname, qtype, ttd, now, origTTL, refresh);
      }
      return -1;
    }
  }
  // Try (again) without tag
  auto entries = getEntries(*lockedShard, qname, qtype, boost::none);

  if (entries.first != entries.second) {
    OrderedTagIterator_t firstIndexIterator;
    unsigned int found = 0;
    time_t ttd{};

    for (auto i = entries.first; i != entries.second; ++i) {
      firstIndexIterator = lockedShard->d_map.project<OrderedTag>(i);

      // When serving stale, we consider expired records
      if (!i->isEntryUsable(now, serveStale)) {
        moveCacheItemToFront<SequencedTag>(lockedShard->d_map, firstIndexIterator);
        continue;
      }

      if (!entryMatches(firstIndexIterator, qtype, requireAuth, who)) {
        continue;
      }
      ++found;

      handleServeStaleBookkeeping(now, serveStale, firstIndexIterator);

      ttd = handleHit(now, *lockedShard, firstIndexIterator, qname, origTTL, res, signatures, authorityRecs, variable, cachedState, wasAuth, fromAuthZone, fromAuthIP);

      if (qtype == QType::ADDR && found == 2) {
        break;
      }
      if (qtype != QType::ANY) { // normally if we have a hit, we are done
        break;
      }
    }
    if (found > 0) {
      if (cachedState && ttd > now) {
        ptrAssign(state, *cachedState);
      }
      return fakeTTD(firstIndexIterator, qname, qtype, ttd, now, origTTL, refresh);
    }
  }
  return -1;
}

bool MemRecursorCache::CacheEntry::shouldReplace(time_t now, bool auth, vState state, bool refresh)
{
  if (!auth && d_auth) { // unauth data came in, we have some auth data, but is it fresh?
    // an auth entry that is going to expire while we are resolving can hurt, as it prevents infra
    // records (which might be unauth) to be updated. So apply a safety margin.
    const time_t margin = 5;
    if (d_ttd - margin > now) { // we still have valid data, ignore unauth data
      return false;
    }
    d_auth = false; // new data won't be auth
  }

  if (auth) {
    /* we don't want to keep a non-auth entry while we have an auth one */
    if (vStateIsBogus(state) && (!vStateIsBogus(d_state) && d_state != vState::Indeterminate) && d_ttd > now) {
      /* the new entry is Bogus, the existing one is not and is still valid, let's keep the existing one */
      return false;
    }
    // Always allow upgrade unauth data to auth
    if (!d_auth) {
      return true;
    }
  }

  if (SyncRes::s_locked_ttlperc > 0) {
    // Override locking if existing data is stale or new data is Secure or refreshing
    if (d_ttd <= now || state == vState::Secure || refresh) {
      return true;
    }
    const uint32_t percentage = 100 - SyncRes::s_locked_ttlperc;
    const time_t ttl = d_ttd - now;
    const uint32_t lockline = d_orig_ttl * percentage / 100;
    // We know ttl is > 0 as d_ttd > now
    // coverity[store_truncates_time_t]
    const bool locked = static_cast<uint32_t>(ttl) > lockline;
    if (locked) {
      return false;
    }
  }

  return true;
}

bool MemRecursorCache::replace(CacheEntry&& entry)
{
  if (!entry.d_netmask.empty() || entry.d_rtag) {
    // We don't handle that yet
    return false;
  }
  auto& shard = getMap(entry.d_qname);
  auto lockedShard = shard.lock();

  lockedShard->d_cachecachevalid = false;
  entry.d_submitted = false;
  if (lockedShard->d_map.emplace(std::move(entry)).second) {
    shard.incEntriesCount();
    return true;
  }
  return false;
}

void MemRecursorCache::replace(time_t now, const DNSName& qname, const QType qtype, const vector<DNSRecord>& content, const SigRecsVec& signatures, const AuthRecsVec& authorityRecs, bool auth, const DNSName& authZone, boost::optional<Netmask> ednsmask, const OptTag& routingTag, vState state, boost::optional<ComboAddress> from, bool refresh, time_t ttl_time)
{
  auto& shard = getMap(qname);
  auto lockedShard = shard.lock();

  lockedShard->d_cachecachevalid = false;
  if (ednsmask) {
    ednsmask = ednsmask->getNormalized();
  }

  // We only store with a tag if we have an ednsmask and the tag is available
  // We only store an ednsmask if we do not have a tag and we do have a mask.
  auto key = std::tuple(qname, qtype.getCode(), ednsmask ? routingTag : boost::none, (ednsmask && !routingTag) ? *ednsmask : Netmask());
  bool isNew = false;
  cache_t::iterator stored = lockedShard->d_map.find(key);
  if (stored == lockedShard->d_map.end()) {
    stored = lockedShard->d_map.insert(CacheEntry(key, auth)).first;
    shard.incEntriesCount();
    isNew = true;
  }

  /* if we are inserting a new entry or updating an expired one (in which case the
     ECS index might have been removed but the entry still exists because it has not
     been garbage collected yet) we might need to update the ECS index.
     Otherwise it should already be indexed and we don't need to update it.
  */
  if (isNew || stored->d_ttd <= now) {
    /* don't bother building an ecsIndex if we don't have any netmask-specific entries */
    if (!routingTag && ednsmask && !ednsmask->empty()) {
      auto ecsIndexKey = std::tuple(qname, qtype.getCode());
      auto ecsIndex = lockedShard->d_ecsIndex.find(ecsIndexKey);
      if (ecsIndex == lockedShard->d_ecsIndex.end()) {
        ecsIndex = lockedShard->d_ecsIndex.insert(ECSIndexEntry(qname, qtype.getCode())).first;
      }
      ecsIndex->addMask(*ednsmask);
    }
  }

  time_t maxTTD = std::numeric_limits<time_t>::max();
  CacheEntry cacheEntry = *stored; // this is a COPY
  cacheEntry.d_qtype = qtype.getCode();

  if (!isNew && !cacheEntry.shouldReplace(now, auth, state, refresh)) {
    return;
  }

  cacheEntry.d_state = state;

  // refuse any attempt to *raise* the TTL of auth NS records, as it would make it possible
  // for an auth to keep a "ghost" zone alive forever, even after the delegation is gone from
  // the parent
  // BUT make sure that we CAN refresh the root
  if (cacheEntry.d_auth && auth && qtype == QType::NS && !isNew && !qname.isRoot()) {
    maxTTD = cacheEntry.d_ttd;
  }

  if (auth) {
    cacheEntry.d_auth = true;
  }

  if (!signatures.empty()) {
    cacheEntry.d_signatures = std::make_shared<const SigRecsVec>(signatures);
  }
  else {
    cacheEntry.d_signatures = nullptr;
  }
  if (!authorityRecs.empty()) {
    cacheEntry.d_authorityRecs = std::make_shared<const AuthRecsVec>(authorityRecs);
  }
  else {
    cacheEntry.d_authorityRecs = nullptr;
  }
  cacheEntry.d_records.clear();
  cacheEntry.d_authZone = authZone;
  if (from) {
    cacheEntry.d_from = *from;
  }
  else {
    cacheEntry.d_from = ComboAddress();
  }

  size_t toStore = content.size();
  if (toStore <= s_maxRRSetSize) {
    cacheEntry.d_tooBig = false;
  }
  else {
    toStore = 1; // record cache does not like empty RRSets
    cacheEntry.d_tooBig = true;
  }
  cacheEntry.d_records.reserve(toStore);
  for (const auto& record : content) {
    /* Yes, we have altered the d_ttl value by adding time(nullptr) to it
       prior to calling this function, so the TTL actually holds a TTD. */
    cacheEntry.d_ttd = min(maxTTD, static_cast<time_t>(record.d_ttl)); // XXX this does weird things if TTLs differ in the set

    // coverity[store_truncates_time_t]
    cacheEntry.d_orig_ttl = cacheEntry.d_ttd - ttl_time;
    // Even though we record the time the ttd was computed, there still seems to be a case where the computed
    // d_orig_ttl can wrap.
    // So santize the computed ce.d_orig_ttl to be on the safe side
    if (cacheEntry.d_orig_ttl < SyncRes::s_minimumTTL || cacheEntry.d_orig_ttl > SyncRes::s_maxcachettl) {
      cacheEntry.d_orig_ttl = SyncRes::s_minimumTTL;
    }
    cacheEntry.d_records.push_back(record.getContent());
    if (--toStore == 0) {
      break;
    }
  }

  if (!isNew) {
    moveCacheItemToBack<SequencedTag>(lockedShard->d_map, stored);
  }
  cacheEntry.d_submitted = false;
  cacheEntry.d_servedStale = 0;
  lockedShard->d_map.replace(stored, cacheEntry);
}

size_t MemRecursorCache::doWipeCache(const DNSName& name, bool sub, const QType qtype)
{
  size_t count = 0;

  if (!sub) {
    auto& shard = getMap(name);
    auto lockedShard = shard.lock();
    lockedShard->d_cachecachevalid = false;
    auto& idx = lockedShard->d_map.get<OrderedTag>();
    auto range = idx.equal_range(name);
    auto iter = range.first;
    while (iter != range.second) {
      if (iter->d_qtype == qtype || qtype == 0xffff) {
        iter = idx.erase(iter);
        count++;
        shard.decEntriesCount();
      }
      else {
        ++iter;
      }
    }

    if (qtype == 0xffff) {
      auto& ecsIdx = lockedShard->d_ecsIndex.get<OrderedTag>();
      auto ecsIndexRange = ecsIdx.equal_range(name);
      ecsIdx.erase(ecsIndexRange.first, ecsIndexRange.second);
    }
    else {
      auto& ecsIdx = lockedShard->d_ecsIndex.get<HashedTag>();
      auto ecsIndexRange = ecsIdx.equal_range(std::tie(name, qtype));
      ecsIdx.erase(ecsIndexRange.first, ecsIndexRange.second);
    }
  }
  else {
    for (auto& content : d_maps) {
      auto map = content.lock();
      map->d_cachecachevalid = false;
      auto& idx = map->d_map.get<OrderedTag>();
      for (auto i = idx.lower_bound(name); i != idx.end();) {
        if (!i->d_qname.isPartOf(name)) {
          break;
        }
        if (i->d_qtype == qtype || qtype == 0xffff) {
          count++;
          i = idx.erase(i);
          content.decEntriesCount();
        }
        else {
          ++i;
        }
      }
      auto& ecsIdx = map->d_ecsIndex.get<OrderedTag>();
      for (auto i = ecsIdx.lower_bound(name); i != ecsIdx.end();) {
        if (!i->d_qname.isPartOf(name)) {
          break;
        }
        if (i->d_qtype == qtype || qtype == 0xffff) {
          i = ecsIdx.erase(i);
        }
        else {
          ++i;
        }
      }
    }
  }
  return count;
}

// Name should be doLimitTime or so
bool MemRecursorCache::doAgeCache(time_t now, const DNSName& name, const QType qtype, uint32_t newTTL)
{
  auto& shard = getMap(name);
  auto lockedShard = shard.lock();
  cache_t::iterator iter = lockedShard->d_map.find(std::tie(name, qtype));
  if (iter == lockedShard->d_map.end()) {
    return false;
  }

  CacheEntry cacheEntry = *iter;
  if (cacheEntry.d_ttd < now) {
    return false; // would be dead anyhow
  }

  // coverity[store_truncates_time_t]
  auto maxTTL = static_cast<uint32_t>(cacheEntry.d_ttd - now);
  if (maxTTL > newTTL) {
    lockedShard->d_cachecachevalid = false;

    time_t newTTD = now + newTTL;

    if (cacheEntry.d_ttd > newTTD) {
      cacheEntry.d_ttd = newTTD;
      lockedShard->d_map.replace(iter, cacheEntry);
    }
    return true;
  }
  return false;
}

bool MemRecursorCache::updateValidationStatus(time_t now, const DNSName& qname, const QType qtype, const ComboAddress& who, const OptTag& routingTag, bool requireAuth, vState newState, boost::optional<time_t> capTTD)
{
  if (qtype == QType::ANY) {
    throw std::runtime_error("Trying to update the DNSSEC validation status of all (via ANY) records for " + qname.toLogString());
  }
  if (qtype == QType::ADDR) {
    throw std::runtime_error("Trying to update the DNSSEC validation status of several (via ADDR) records for " + qname.toLogString());
  }

  auto& content = getMap(qname);
  auto map = content.lock();

  bool updated = false;
  if (!map->d_ecsIndex.empty() && !routingTag) {
    auto entry = getEntryUsingECSIndex(*map, now, qname, qtype, requireAuth, who, false); // XXX serveStale?
    if (entry == map->d_map.end()) {
      return false;
    }

    entry->d_state = newState;
    if (capTTD) {
      entry->d_ttd = std::min(entry->d_ttd, *capTTD);
    }
    return true;
  }

  auto entries = getEntries(*map, qname, qtype, routingTag);

  for (auto i = entries.first; i != entries.second; ++i) {
    auto firstIndexIterator = map->d_map.project<OrderedTag>(i);

    if (!entryMatches(firstIndexIterator, qtype, requireAuth, who)) {
      continue;
    }

    i->d_state = newState;
    if (capTTD) {
      i->d_ttd = std::min(i->d_ttd, *capTTD);
    }
    updated = true;

    break;
  }

  return updated;
}

uint64_t MemRecursorCache::doDump(int fileDesc, size_t maxCacheEntries)
{
  int newfd = dup(fileDesc);
  if (newfd == -1) {
    return 0;
  }
  auto filePtr = pdns::UniqueFilePtr(fdopen(newfd, "w"));
  if (!filePtr) { // dup probably failed
    close(newfd);
    return 0;
  }

  fprintf(filePtr.get(), "; main record cache dump follows\n;\n");
  uint64_t count = 0;
  size_t shardNumber = 0;
  size_t min = std::numeric_limits<size_t>::max();
  size_t max = 0;
  for (auto& shard : d_maps) {
    auto lockedShard = shard.lock();
    const auto shardSize = lockedShard->d_map.size();
    size_t bytes = 0;
    for (const auto& entry : lockedShard->d_map) {
      bytes += entry.sizeEstimate();
    }
    fprintf(filePtr.get(), "; record cache shard %zu; size %zu bytes %zu\n", shardNumber, shardSize, bytes);
    min = std::min(min, shardSize);
    max = std::max(max, shardSize);
    shardNumber++;
    const auto& sidx = lockedShard->d_map.get<SequencedTag>();
    time_t now = time(nullptr);
    for (const auto& recordSet : sidx) {
      for (const auto& record : recordSet.d_records) {
        count++;
        try {
          fprintf(filePtr.get(), "%s %" PRIu32 " %" PRId64 " IN %s %s ; (%s) auth=%i zone=%s from=%s nm=%s rtag=%s ss=%hd%s\n", recordSet.d_qname.toString().c_str(), recordSet.d_orig_ttl, static_cast<int64_t>(recordSet.d_ttd - now), recordSet.d_qtype.toString().c_str(), record->getZoneRepresentation().c_str(), vStateToString(recordSet.d_state).c_str(), static_cast<int>(recordSet.d_auth), recordSet.d_authZone.toLogString().c_str(), recordSet.d_from.toString().c_str(), recordSet.d_netmask.empty() ? "" : recordSet.d_netmask.toString().c_str(), !recordSet.d_rtag ? "" : recordSet.d_rtag.get().c_str(), recordSet.d_servedStale, recordSet.d_tooBig ? " (too big!)" : "");
        }
        catch (...) {
          fprintf(filePtr.get(), "; error printing '%s'\n", recordSet.d_qname.empty() ? "EMPTY" : recordSet.d_qname.toString().c_str());
        }
      }
      if (recordSet.d_signatures) {
        for (const auto& sig : *recordSet.d_signatures) {
          count++;
          try {
            fprintf(filePtr.get(), "%s %" PRIu32 " %" PRId64 " IN RRSIG %s ; %s\n", recordSet.d_qname.toString().c_str(), recordSet.d_orig_ttl, static_cast<int64_t>(recordSet.d_ttd - now), sig->getZoneRepresentation().c_str(), recordSet.d_netmask.empty() ? "" : recordSet.d_netmask.toString().c_str());
          }
          catch (...) {
            fprintf(filePtr.get(), "; error printing '%s'\n", recordSet.d_qname.empty() ? "EMPTY" : recordSet.d_qname.toString().c_str());
          }
        }
      }
    }
  }
  fprintf(filePtr.get(), "; main record cache size: %zu/%zu shards: %zu min/max shard size: %zu/%zu\n", size(), maxCacheEntries, d_maps.size(), min, max);
  return count;
}

void MemRecursorCache::doPrune(time_t now, size_t keep)
{
  size_t cacheSize = size();
  pruneMutexCollectionsVector<SequencedTag>(now, d_maps, keep, cacheSize);
}

enum class PBCacheDump : protozero::pbf_tag_type
{
  required_string_version = 1,
  required_string_identity = 2,
  required_uint64_protocolVersion = 3,
  required_int64_time = 4,
  required_string_type = 5,
  repeated_message_cacheEntry = 6,
};

enum class PBCacheEntry : protozero::pbf_tag_type
{
  repeated_bytes_record = 1,
  repeated_bytes_sig = 2,
  repeated_message_authRecord = 3,
  required_bytes_name = 4,
  required_bytes_authZone = 5,
  required_message_from = 6,
  optional_bytes_netmask = 7,
  optional_bytes_rtag = 8,
  required_uint32_state = 9,
  required_int64_ttd = 10,
  required_uint32_orig_ttl = 11,
  required_uint32_servedStale = 12,
  required_uint32_qtype = 13,
  required_bool_auth = 14,
  required_bool_submitted = 15,
  required_bool_tooBig = 16,
};

enum class PBAuthRecord : protozero::pbf_tag_type
{
  required_bytes_name = 1,
  required_bytes_rdata = 2,
  required_uint32_type = 3,
  required_uint32_class = 4,
  required_uint32_ttl = 5,
  required_uint32_place = 6,
  required_uint32_clen = 7,
};

template <typename T, typename U>
void MemRecursorCache::getRecordSet(T& message, U recordSet)
{
  // Two fields below must come before the other fields
  message.add_bytes(PBCacheEntry::required_bytes_name, recordSet->d_qname.toString());
  message.add_uint32(PBCacheEntry::required_uint32_qtype, recordSet->d_qtype);
  for (const auto& record : recordSet->d_records) {
    message.add_bytes(PBCacheEntry::repeated_bytes_record, record->serialize(recordSet->d_qname, true));
  }
  if (recordSet->d_signatures) {
    for (const auto& record : *recordSet->d_signatures) {
      message.add_bytes(PBCacheEntry::repeated_bytes_sig, record->serialize(recordSet->d_qname, true));
    }
  }
  if (recordSet->d_authorityRecs) {
    for (const auto& authRec : *recordSet->d_authorityRecs) {
      protozero::pbf_builder<PBAuthRecord> auth(message, PBCacheEntry::repeated_message_authRecord);
      auth.add_bytes(PBAuthRecord::required_bytes_name, authRec.d_name.toString());
      auth.add_bytes(PBAuthRecord::required_bytes_rdata, authRec.getContent()->serialize(authRec.d_name, true));
      auth.add_uint32(PBAuthRecord::required_uint32_type, authRec.d_type);
      auth.add_uint32(PBAuthRecord::required_uint32_class, authRec.d_class);
      auth.add_uint32(PBAuthRecord::required_uint32_ttl, authRec.d_ttl);
      auth.add_uint32(PBAuthRecord::required_uint32_place, authRec.d_place);
      auth.add_uint32(PBAuthRecord::required_uint32_clen, authRec.d_clen);
    }
  }
  message.add_bytes(PBCacheEntry::required_bytes_authZone, recordSet->d_authZone.toString());
  encodeComboAddress(message, PBCacheEntry::required_message_from, recordSet->d_from);
  encodeNetmask(message, PBCacheEntry::optional_bytes_netmask, recordSet->d_netmask);
  if (recordSet->d_rtag) {
    message.add_bytes(PBCacheEntry::optional_bytes_rtag, *recordSet->d_rtag);
  }
  message.add_uint32(PBCacheEntry::required_uint32_state, static_cast<uint32_t>(recordSet->d_state));
  message.add_int64(PBCacheEntry::required_int64_ttd, recordSet->d_ttd);
  message.add_uint32(PBCacheEntry::required_uint32_orig_ttl, recordSet->d_orig_ttl);
  message.add_uint32(PBCacheEntry::required_uint32_servedStale, recordSet->d_servedStale);
  message.add_bool(PBCacheEntry::required_bool_auth, recordSet->d_auth);
  message.add_bool(PBCacheEntry::required_bool_submitted, recordSet->d_submitted);
  message.add_bool(PBCacheEntry::required_bool_tooBig, recordSet->d_tooBig);
}

size_t MemRecursorCache::getRecordSets(size_t perShard, size_t maxSize, std::string& ret)
{
  auto log = g_slog->withName("recordcache")->withValues("perShard", Logging::Loggable(perShard), "maxSize", Logging::Loggable(maxSize));
  log->info(Logr::Info, "Producing cache dump");

  // A size estimate is hard: size() returns the number of record *sets*. Each record set can have
  // multiple records, plus other associated records like signatures. 150 seems to works ok.
  size_t estimate = maxSize == 0 ? size() * 150 : maxSize + 4096; // We may overshoot (will be rolled back)

  if (perShard == 0) {
    perShard = std::numeric_limits<size_t>::max();
  }
  if (maxSize == 0) {
    maxSize = std::numeric_limits<size_t>::max();
  }
  protozero::pbf_builder<PBCacheDump> full(ret);
  full.add_string(PBCacheDump::required_string_version, getPDNSVersion());
  full.add_string(PBCacheDump::required_string_identity, SyncRes::s_serverID);
  full.add_uint64(PBCacheDump::required_uint64_protocolVersion, 1);
  full.add_int64(PBCacheDump::required_int64_time, time(nullptr));
  full.add_string(PBCacheDump::required_string_type, "PBCacheDump");

  size_t count = 0;
  ret.reserve(estimate);

  for (auto& shard : d_maps) {
    auto lockedShard = shard.lock();
    const auto& sidx = lockedShard->d_map.get<SequencedTag>();
    size_t thisShardCount = 0;
    for (auto recordSet = sidx.rbegin(); recordSet != sidx.rend(); ++recordSet) {
      protozero::pbf_builder<PBCacheEntry> message(full, PBCacheDump::repeated_message_cacheEntry);
      getRecordSet(message, recordSet);
      if (ret.size() > maxSize) {
        message.rollback();
        log->info(Logr::Info, "Produced cache dump (max size reached)", "size", Logging::Loggable(ret.size()), "count", Logging::Loggable(count));
        return count;
      }
      ++count;
      ++thisShardCount;
      if (thisShardCount >= perShard) {
        break;
      }
    }
  }
  log->info(Logr::Info, "Produced cache dump", "size", Logging::Loggable(ret.size()), "count", Logging::Loggable(count));
  return count;
}

static void putAuthRecord(protozero::pbf_message<PBCacheEntry>& message, const DNSName& qname, std::vector<DNSRecord>& authRecs)
{
  protozero::pbf_message<PBAuthRecord> auth = message.get_message();
  DNSRecord authRecord;
  while (auth.next()) {
    switch (auth.tag()) {
    case PBAuthRecord::required_bytes_name:
      authRecord.d_name = DNSName(auth.get_bytes());
      break;
    case PBAuthRecord::required_bytes_rdata: {
      auto ptr = DNSRecordContent::deserialize(qname, authRecord.d_type, auth.get_bytes());
      authRecord.setContent(ptr);
      break;
    }
    case PBAuthRecord::required_uint32_class:
      authRecord.d_class = auth.get_uint32();
      break;
    case PBAuthRecord::required_uint32_type:
      authRecord.d_type = auth.get_uint32();
      break;
    case PBAuthRecord::required_uint32_ttl:
      authRecord.d_ttl = auth.get_uint32();
      break;
    case PBAuthRecord::required_uint32_place:
      authRecord.d_place = static_cast<DNSResourceRecord::Place>(auth.get_uint32());
      break;
    case PBAuthRecord::required_uint32_clen:
      authRecord.d_clen = auth.get_uint32();
      break;
    default:
      break;
    }
  }
  authRecs.emplace_back(authRecord);
}

template <typename T>
bool MemRecursorCache::putRecordSet(T& message)
{
  AuthRecsVec authRecs;
  SigRecsVec sigRecs;
  CacheEntry cacheEntry{{g_rootdnsname, QType::A, boost::none, Netmask()}, false};
  while (message.next()) {
    switch (message.tag()) {
    case PBCacheEntry::repeated_bytes_record: {
      auto ptr = DNSRecordContent::deserialize(cacheEntry.d_qname, cacheEntry.d_qtype, message.get_bytes());
      cacheEntry.d_records.emplace_back(ptr);
      break;
    }
    case PBCacheEntry::repeated_bytes_sig: {
      auto ptr = DNSRecordContent::deserialize(cacheEntry.d_qname, QType::RRSIG, message.get_bytes());
      sigRecs.emplace_back(std::dynamic_pointer_cast<RRSIGRecordContent>(ptr));
      break;
    }
    case PBCacheEntry::repeated_message_authRecord:
      putAuthRecord(message, cacheEntry.d_qname, authRecs);
      break;
    case PBCacheEntry::required_bytes_name:
      cacheEntry.d_qname = DNSName(message.get_bytes());
      break;
    case PBCacheEntry::required_bytes_authZone:
      cacheEntry.d_authZone = DNSName(message.get_bytes());
      break;
    case PBCacheEntry::required_message_from:
      decodeComboAddress(message, cacheEntry.d_from);
      break;
    case PBCacheEntry::optional_bytes_netmask:
      decodeNetmask(message, cacheEntry.d_netmask);
      break;
    case PBCacheEntry::optional_bytes_rtag:
      cacheEntry.d_rtag = message.get_bytes();
      break;
    case PBCacheEntry::required_uint32_state:
      cacheEntry.d_state = static_cast<vState>(message.get_uint32());
      break;
    case PBCacheEntry::required_int64_ttd:
      cacheEntry.d_ttd = message.get_int64();
      break;
    case PBCacheEntry::required_uint32_orig_ttl:
      cacheEntry.d_orig_ttl = message.get_uint32();
      break;
    case PBCacheEntry::required_uint32_servedStale:
      cacheEntry.d_servedStale = message.get_uint32();
      break;
    case PBCacheEntry::required_uint32_qtype:
      cacheEntry.d_qtype = message.get_uint32();
      break;
    case PBCacheEntry::required_bool_auth:
      cacheEntry.d_auth = message.get_bool();
      break;
    case PBCacheEntry::required_bool_submitted:
      cacheEntry.d_submitted = message.get_bool();
      cacheEntry.d_submitted = false; // actually not
      break;
    case PBCacheEntry::required_bool_tooBig:
      cacheEntry.d_tooBig = message.get_bool();
      break;
    default:
      break;
    }
  }
  if (!authRecs.empty()) {
    cacheEntry.d_authorityRecs = std::make_shared<const AuthRecsVec>(std::move(authRecs));
  }
  if (!sigRecs.empty()) {
    cacheEntry.d_signatures = std::make_shared<const SigRecsVec>(std::move(sigRecs));
  }
  return replace(std::move(cacheEntry));
}

size_t MemRecursorCache::putRecordSets(const std::string& pbuf)
{
  auto log = g_slog->withName("recordcache")->withValues("size", Logging::Loggable(pbuf.size()));
  log->info(Logr::Debug, "Processing cache dump");

  protozero::pbf_message<PBCacheDump> full(pbuf);
  size_t count = 0;
  size_t inserted = 0;
  try {
    bool protocolVersionSeen = false;
    bool typeSeen = false;
    while (full.next()) {
      switch (full.tag()) {
      case PBCacheDump::required_string_version: {
        auto version = full.get_string();
        log = log->withValues("version", Logging::Loggable(version));
        break;
      }
      case PBCacheDump::required_string_identity: {
        auto identity = full.get_string();
        log = log->withValues("identity", Logging::Loggable(identity));
        break;
      }
      case PBCacheDump::required_uint64_protocolVersion: {
        auto protocolVersion = full.get_uint64();
        log = log->withValues("protocolVersion", Logging::Loggable(protocolVersion));
        if (protocolVersion != 1) {
          throw std::runtime_error("Protocol version mismatch");
        }
        protocolVersionSeen = true;
        break;
      }
      case PBCacheDump::required_int64_time: {
        auto time = full.get_int64();
        log = log->withValues("time", Logging::Loggable(time));
        break;
      }
      case PBCacheDump::required_string_type: {
        auto type = full.get_string();
        if (type != "PBCacheDump") {
          throw std::runtime_error("Data type mismatch");
        }
        typeSeen = true;
        break;
      }
      case PBCacheDump::repeated_message_cacheEntry: {
        if (!protocolVersionSeen || !typeSeen) {
          throw std::runtime_error("Required field missing");
        }
        protozero::pbf_message<PBCacheEntry> message = full.get_message();
        if (putRecordSet(message)) {
          ++inserted;
        }
        ++count;
        break;
      }
      }
    }
    log->info(Logr::Info, "Processed cache dump", "processed", Logging::Loggable(count), "inserted", Logging::Loggable(inserted));
    return inserted;
  }
  catch (const std::runtime_error& e) {
    log->error(Logr::Error, e.what(), "Runtime exception processing cache dump");
  }
  catch (const std::exception& e) {
    log->error(Logr::Error, e.what(), "Exception processing cache dump");
  }
  catch (...) {
    log->error(Logr::Error, "Other exception processing cache dump");
  }
  return 0;
}

namespace boost
{
size_t hash_value(const MemRecursorCache::OptTag& rtag)
{
  return rtag ? hash_value(rtag.get()) : 0xcafebaaf;
}
}