• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PowerDNS / pdns / 17210411594

25 Aug 2025 01:33PM UTC coverage: 65.973% (+0.2%) from 65.814%
17210411594

Pull #15874

github

web-flow
Merge 6ac7c5514 into 9eeac00a7
Pull Request #15874: dnsdist: Only check the freshness of the configuration when needed

42140 of 92460 branches covered (45.58%)

Branch coverage included in aggregate %.

59 of 73 new or added lines in 19 files covered. (80.82%)

5421 existing lines in 75 files now uncovered.

128091 of 165573 relevant lines covered (77.36%)

4808876.23 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

72.94
/pdns/rfc2136handler.cc
1
#include "dnswriter.hh"
2
#ifdef HAVE_CONFIG_H
3
#include "config.h"
4
#endif
5
#include "packethandler.hh"
6
#include "qtype.hh"
7
#include "dnspacket.hh"
8
#include "auth-caches.hh"
9
#include "statbag.hh"
10
#include "dnsseckeeper.hh"
11
#include "base64.hh"
12
#include "base32.hh"
13

14
#include "misc.hh"
15
#include "arguments.hh"
16
#include "resolver.hh"
17
#include "dns_random.hh"
18
#include "backends/gsql/ssql.hh"
19
#include "communicator.hh"
20
#include "query-local-address.hh"
21
#include "gss_context.hh"
22
#include "auth-main.hh"
23

24
extern StatBag S;
25
extern CommunicatorClass Communicator;
26

27
std::mutex PacketHandler::s_rfc2136lock;
28

29
// Implement section 3.2.1 and 3.2.2 of RFC2136
30
int PacketHandler::checkUpdatePrerequisites(const DNSRecord *rr, DomainInfo *di) {
418✔
31
  if (rr->d_ttl != 0)
418!
32
    return RCode::FormErr;
×
33

34
  // 3.2.1 and 3.2.2 check content length.
35
  if ( (rr->d_class == QClass::NONE || rr->d_class == QClass::ANY) && rr->d_clen != 0)
418!
36
    return RCode::FormErr;
×
37

38
  bool foundRecord=false;
418✔
39
  DNSResourceRecord rec;
418✔
40
  di->backend->lookup(QType(QType::ANY), rr->d_name, di->id);
418✔
41
  while(di->backend->get(rec)) {
440✔
42
    if (!rec.qtype.getCode())
330✔
43
      continue;
22✔
44
    if ((rr->d_type != QType::ANY && rec.qtype == rr->d_type) || rr->d_type == QType::ANY) {
308!
45
      foundRecord=true;
308✔
46
      di->backend->lookupEnd();
308✔
47
      break;
308✔
48
    }
308✔
49
  }
308✔
50

51
  // Section 3.2.1
52
  if (rr->d_class == QClass::ANY && !foundRecord) {
418✔
53
    if (rr->d_type == QType::ANY)
66✔
54
      return RCode::NXDomain;
44✔
55
    if (rr->d_type != QType::ANY)
22!
56
      return RCode::NXRRSet;
22✔
57
  }
22✔
58

59
  // Section 3.2.2
60
  if (rr->d_class == QClass::NONE && foundRecord) {
352✔
61
    if (rr->d_type == QType::ANY)
44✔
62
      return RCode::YXDomain;
22✔
63
    if (rr->d_type != QType::ANY)
22!
64
      return RCode::YXRRSet;
22✔
65
  }
22✔
66

67
  return RCode::NoError;
308✔
68
}
352✔
69

70

71
// Method implements section 3.4.1 of RFC2136
72
int PacketHandler::checkUpdatePrescan(const DNSRecord *rr) {
5,006✔
73
  // The RFC stats that d_class != ZCLASS, but we only support the IN class.
74
  if (rr->d_class != QClass::IN && rr->d_class != QClass::NONE && rr->d_class != QClass::ANY) {
5,006!
UNCOV
75
    return RCode::FormErr;
×
UNCOV
76
  }
×
77

78
  QType qtype = QType(rr->d_type);
5,006✔
79

80
  if (!qtype.isSupportedType()) {
5,006!
UNCOV
81
    return RCode::FormErr;
×
82
  }
×
83

84
  if ((rr->d_class == QClass::NONE || rr->d_class == QClass::ANY) && rr->d_ttl != 0) {
5,006!
UNCOV
85
    return RCode::FormErr;
×
86
  }
×
87

88
  if (rr->d_class == QClass::ANY && rr->d_clen != 0) {
5,006!
UNCOV
89
    return RCode::FormErr;
×
90
  }
×
91

92
  if (qtype.isMetadataType()) {
5,006!
UNCOV
93
    return RCode::FormErr;
×
UNCOV
94
  }
×
95

96
  if (rr->d_class != QClass::ANY && qtype.getCode() == QType::ANY) {
5,006✔
97
    return RCode::FormErr;
22✔
98
  }
22✔
99

100
  return RCode::NoError;
4,984✔
101
}
5,006✔
102

103

104
// Implements section 3.4.2 of RFC2136
105
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
106
uint PacketHandler::performUpdate(const string &msgPrefix, const DNSRecord *rr, DomainInfo *di, bool isPresigned, bool* narrow, bool* haveNSEC3, NSEC3PARAMRecordContent *ns3pr, bool *updatedSerial) {
4,852✔
107

108
  QType rrType = QType(rr->d_type);
4,852✔
109

110
  if (rrType == QType::NSEC || rrType == QType::NSEC3) {
4,852!
UNCOV
111
    g_log<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rr->d_name<<"|"<<rrType.toString()<<". These are generated records, ignoring!"<<endl;
×
UNCOV
112
    return 0;
×
113
  }
×
114

115
  if (!isPresigned && rrType == QType::RRSIG) {
4,852!
UNCOV
116
    g_log<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rr->d_name<<"|"<<rrType.toString()<<" in non-presigned zone, ignoring!"<<endl;
×
UNCOV
117
    return 0;
×
118
  }
×
119

120
  if ((rrType == QType::NSEC3PARAM || rrType == QType::DNSKEY) && rr->d_name != di->zone.operator const DNSName&()) {
4,852!
UNCOV
121
    g_log<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rr->d_name<<"|"<<rrType.toString()<<", "<<rrType.toString()<<" must be at zone apex, ignoring!"<<endl;
×
UNCOV
122
    return 0;
×
UNCOV
123
  }
×
124

125

126
  uint changedRecords = 0;
4,852✔
127
  DNSResourceRecord rec;
4,852✔
128
  vector<DNSResourceRecord> rrset, recordsToDelete;
4,852✔
129
  set<DNSName> delnonterm, insnonterm; // used to (at the end) fix ENT records.
4,852✔
130

131

132
  if (rr->d_class == QClass::IN) { // 3.4.2.2 QClass::IN means insert or update
4,852✔
133
    DLOG(g_log<<msgPrefix<<"Add/Update record (QClass == IN) "<<rr->d_name<<"|"<<rrType.toString()<<endl);
3,644✔
134

135
    if (rrType == QType::NSEC3PARAM) {
3,644✔
136
      g_log<<Logger::Notice<<msgPrefix<<"Adding/updating NSEC3PARAM for zone, resetting ordernames."<<endl;
44✔
137

138
      *ns3pr = NSEC3PARAMRecordContent(rr->getContent()->getZoneRepresentation(), di->zone);
44✔
139
      *narrow = false; // adding a NSEC3 will cause narrow mode to be dropped, as you cannot specify that in a NSEC3PARAM record
44✔
140
      d_dk.setNSEC3PARAM(di->zone, *ns3pr, (*narrow));
44✔
141
      *haveNSEC3 = true;
44✔
142

143
      string error;
44✔
144
      string info;
44✔
145
      if (!d_dk.rectifyZone(di->zone, error, info, false)) {
44!
UNCOV
146
        throw PDNSException("Failed to rectify '" + di->zone.toLogString() + "': " + error);
×
UNCOV
147
      }
×
148
      return 1;
44✔
149
    }
44✔
150

151

152

153
    bool foundRecord = false;
3,600✔
154
    di->backend->lookup(rrType, rr->d_name, di->id);
3,600✔
155
    while (di->backend->get(rec)) {
110,828✔
156
      rrset.push_back(rec);
107,228✔
157
      foundRecord = true;
107,228✔
158
    }
107,228✔
159

160
    if (foundRecord) {
3,600✔
161

162
      if (rrType == QType::SOA) { // SOA updates require the serial to be higher than the current
2,552✔
163
        SOAData sdOld, sdUpdate;
88✔
164
        DNSResourceRecord *oldRec = &rrset.front();
88✔
165
        fillSOAData(oldRec->content, sdOld);
88✔
166
        oldRec->setContent(rr->getContent()->getZoneRepresentation());
88✔
167
        fillSOAData(oldRec->content, sdUpdate);
88✔
168
        if (rfc1982LessThan(sdOld.serial, sdUpdate.serial)) {
88✔
169
          di->backend->replaceRRSet(di->id, oldRec->qname, oldRec->qtype, rrset);
44✔
170
          *updatedSerial = true;
44✔
171
          changedRecords++;
44✔
172
          g_log<<Logger::Notice<<msgPrefix<<"Replacing SOA record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
44✔
173
        } else {
44✔
174
          g_log<<Logger::Notice<<msgPrefix<<"Provided serial ("<<sdUpdate.serial<<") is older than the current serial ("<<sdOld.serial<<"), ignoring SOA update."<<endl;
44✔
175
        }
44✔
176

177
      // It's not possible to have multiple CNAME's with the same NAME. So we always update.
178
      } else if (rrType == QType::CNAME) {
2,464✔
179
        int changedCNames = 0;
44✔
180
        for (auto& i : rrset) {
44✔
181
          if (i.ttl != rr->d_ttl || i.content != rr->getContent()->getZoneRepresentation()) {
44!
182
            i.ttl = rr->d_ttl;
44✔
183
            i.setContent(rr->getContent()->getZoneRepresentation());
44✔
184
            changedCNames++;
44✔
185
          }
44✔
186
        }
44✔
187
        if (changedCNames > 0) {
44!
188
          di->backend->replaceRRSet(di->id, rr->d_name, rrType, rrset);
44✔
189
          g_log<<Logger::Notice<<msgPrefix<<"Replacing CNAME record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
44✔
190
          changedRecords += changedCNames;
44✔
191
        } else {
44✔
UNCOV
192
          g_log<<Logger::Notice<<msgPrefix<<"Replace for CNAME record "<<rr->d_name<<"|"<<rrType.toString()<<" requested, but no changes made."<<endl;
×
UNCOV
193
        }
×
194

195
      // In any other case, we must check if the TYPE and RDATA match to provide an update (which effectively means a update of TTL)
196
      } else {
2,420✔
197
        int updateTTL=0;
2,420✔
198
        foundRecord = false;
2,420✔
199
        bool lowerCase = false;
2,420✔
200
        if (rrType.getCode() == QType::PTR ||
2,420✔
201
            rrType.getCode() == QType::MX ||
2,420✔
202
            rrType.getCode() == QType::SRV) {
2,420✔
203
          lowerCase = true;
154✔
204
        }
154✔
205
        string content = rr->getContent()->getZoneRepresentation();
2,420✔
206
        if (lowerCase) content = toLower(content);
2,420✔
207
        for (auto& i : rrset) {
107,096✔
208
          string icontent = i.getZoneRepresentation();
107,096✔
209
          if (lowerCase) icontent = toLower(icontent);
107,096✔
210
          if (rrType == i.qtype.getCode()) {
107,096!
211
            if (icontent == content) {
107,096✔
212
              foundRecord=true;
132✔
213
            }
132✔
214
            if (i.ttl != rr->d_ttl)  {
107,096✔
215
              i.ttl = rr->d_ttl;
264✔
216
              updateTTL++;
264✔
217
            }
264✔
218
          }
107,096✔
219
        }
107,096✔
220
        if (updateTTL > 0) {
2,420✔
221
          di->backend->replaceRRSet(di->id, rr->d_name, rrType, rrset);
154✔
222
          g_log<<Logger::Notice<<msgPrefix<<"Updating TTLs for "<<rr->d_name<<"|"<<rrType.toString()<<endl;
154✔
223
          changedRecords += updateTTL;
154✔
224
        } else {
2,266✔
225
          g_log<<Logger::Notice<<msgPrefix<<"Replace for recordset "<<rr->d_name<<"|"<<rrType.toString()<<" requested, but no changes made."<<endl;
2,266✔
226
        }
2,266✔
227
      }
2,420✔
228

229
      // ReplaceRRSet dumps our ordername and auth flag, so we need to correct it if we have changed records.
230
      // We can take the auth flag from the first RR in the set, as the name is different, so should the auth be.
231
      if (changedRecords > 0) {
2,552✔
232
        bool auth = rrset.front().auth;
242✔
233

234
        if(*haveNSEC3) {
242✔
235
          DNSName ordername;
132✔
236
          if(! *narrow)
132✔
237
            ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr->d_name)));
88✔
238

239
          if (*narrow) {
132✔
240
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), auth, QType::ANY, false);
44✔
241
          }
44✔
242
          else {
88✔
243
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth, QType::ANY, true);
88✔
244
          }
88✔
245
          if(!auth || rrType == QType::DS) {
132!
246
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::NS, !*narrow);
×
UNCOV
247
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A, !*narrow);
×
UNCOV
248
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA, !*narrow);
×
UNCOV
249
          }
×
250

251
        } else { // NSEC
132✔
252
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, rr->d_name.makeRelative(di->zone), auth, QType::ANY, false);
110✔
253
          if(!auth || rrType == QType::DS) {
110!
UNCOV
254
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A, false);
×
UNCOV
255
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA, false);
×
UNCOV
256
          }
×
257
        }
110✔
258
      }
242✔
259

260
    } // if (foundRecord)
2,552✔
261

262
    // If we haven't found a record that matches, we must add it.
263
    if (! foundRecord) {
3,600✔
264
      g_log<<Logger::Notice<<msgPrefix<<"Adding record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
3,336✔
265
      delnonterm.insert(rr->d_name); // always remove any ENT's in the place where we're going to add a record.
3,336✔
266
      auto newRec = DNSResourceRecord::fromWire(*rr);
3,336✔
267
      newRec.domain_id = di->id;
3,336✔
268
      newRec.auth = (rr->d_name == di->zone.operator const DNSName&() || rrType.getCode() != QType::NS);
3,336✔
269
      di->backend->feedRecord(newRec, DNSName());
3,336✔
270
      changedRecords++;
3,336✔
271

272

273
      // because we added a record, we need to fix DNSSEC data.
274
      DNSName shorter(rr->d_name);
3,336✔
275
      bool auth=newRec.auth;
3,336✔
276
      bool fixDS = (rrType == QType::DS);
3,336✔
277

278
      if (di->zone.operator const DNSName&() != shorter) { // Everything at APEX is auth=1 && no ENT's
3,336✔
279
        do {
6,672✔
280

281
          if (di->zone.operator const DNSName&() == shorter) {
6,672✔
282
            break;
2,882✔
283
          }
2,882✔
284

285
          bool foundShorter = false;
3,790✔
286
          di->backend->lookup(QType(QType::ANY), shorter, di->id);
3,790✔
287
          while (di->backend->get(rec)) {
114,280✔
288
            if (rec.qname == rr->d_name && rec.qtype == QType::DS)
110,490✔
289
              fixDS = true;
66✔
290
            if (shorter != rr->d_name) {
110,490✔
291
              foundShorter = true;
366✔
292
            }
366✔
293
            if (rec.qtype == QType::NS) // are we inserting below a delegate?
110,490✔
294
              auth=false;
550✔
295
          }
110,490✔
296

297
          if (!foundShorter && auth && shorter != rr->d_name) { // haven't found any record at current level, insert ENT.
3,790✔
298
            insnonterm.insert(shorter);
220✔
299
          }
220✔
300
          if (foundShorter)
3,790✔
301
            break; // if we find a shorter record, we can stop searching
278✔
302
        } while(shorter.chopOff());
3,790!
303
      }
3,160✔
304

305
      if(*haveNSEC3)
3,336✔
306
      {
1,826✔
307
        DNSName ordername;
1,826✔
308
        if(! *narrow)
1,826✔
309
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr->d_name)));
1,222✔
310

311
        if (*narrow) {
1,826✔
312
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), auth, QType::ANY, false);
604✔
313
        }
604✔
314
        else {
1,222✔
315
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth, QType::ANY, true);
1,222✔
316
        }
1,222✔
317

318
        if (fixDS) {
1,826✔
319
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, true, QType::DS, !*narrow);
36✔
320
        }
36✔
321

322
        if(!auth) {
1,826✔
323
          if (ns3pr->d_flags != 0) {
228✔
324
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::NS, !*narrow);
152✔
325
          }
152✔
326
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A, !*narrow);
228✔
327
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA, !*narrow);
228✔
328
        }
228✔
329
      }
1,826✔
330
      else { // NSEC
1,510✔
331
        DNSName ordername=rr->d_name.makeRelative(di->zone);
1,510✔
332
        di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth, QType::ANY, false);
1,510✔
333
        if (fixDS) {
1,510✔
334
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, true, QType::DS, false);
30✔
335
        }
30✔
336
        if(!auth) {
1,510✔
337
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A, false);
190✔
338
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA, false);
190✔
339
        }
190✔
340
      }
1,510✔
341

342

343
      // If we insert an NS, all the records below it become non auth - so, we're inserting a delegate.
344
      // Auth can only be false when the rr->d_name is not the zone
345
      if (auth == false && rrType == QType::NS) {
3,336✔
346
        DLOG(g_log<<msgPrefix<<"Going to fix auth flags below "<<rr->d_name<<endl);
242✔
347
        insnonterm.clear(); // No ENT's are needed below delegates (auth=0)
242✔
348
        vector<DNSName> qnames;
242✔
349
        di->backend->listSubZone(ZoneName(rr->d_name), di->id);
242✔
350
        while(di->backend->get(rec)) {
726✔
351
          if (rec.qtype.getCode() && rec.qtype.getCode() != QType::DS && rr->d_name != rec.qname) // Skip ENT, DS and our already corrected record.
484✔
352
            qnames.push_back(rec.qname);
132✔
353
        }
484✔
354
        for(const auto & qname : qnames) {
242✔
355
          if(*haveNSEC3)  {
132✔
356
            DNSName ordername;
72✔
357
            if(! *narrow)
72✔
358
              ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, qname)));
48✔
359

360
            if (*narrow) {
72✔
361
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), auth, QType::ANY, false);
24✔
362
            }
24✔
363
            else {
48✔
364
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, auth, QType::ANY, true);
48✔
365
            }
48✔
366

367
            if (ns3pr->d_flags != 0) {
72✔
368
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::NS, !*narrow);
48✔
369
            }
48✔
370
          }
72✔
371
          else { // NSEC
60✔
372
            DNSName ordername=DNSName(qname).makeRelative(di->zone);
60✔
373
            di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, false, QType::NS, false);
60✔
374
          }
60✔
375

376
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::A, *haveNSEC3 && !*narrow);
132✔
377
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::AAAA, *haveNSEC3 && !*narrow);
132✔
378
        }
132✔
379
      }
242✔
380
    }
3,336✔
381
  } // rr->d_class == QClass::IN
3,600✔
382

383

384
  // Delete records - section 3.4.2.3 and 3.4.2.4 with the exception of the 'always leave 1 NS rule' as that's handled by
385
  // the code that calls this performUpdate().
386
  if ((rr->d_class == QClass::ANY || rr->d_class == QClass::NONE) && rrType != QType::SOA) { // never delete a SOA.
4,808✔
387
    DLOG(g_log<<msgPrefix<<"Deleting records: "<<rr->d_name<<"; QClass:"<<rr->d_class<<"; rrType: "<<rrType.toString()<<endl);
1,186✔
388

389
    if (rrType == QType::NSEC3PARAM) {
1,186✔
390
      g_log<<Logger::Notice<<msgPrefix<<"Deleting NSEC3PARAM from zone, resetting ordernames."<<endl;
28✔
391
      // Be sure to use a ZoneName with a variant matching the domain we are
392
      // working on, for the sake of unsetNSEC3PARAM.
393
      ZoneName zonename(rr->d_name, di->zone.getVariant());
28✔
394
      if (rr->d_class == QClass::ANY) {
28!
395
        d_dk.unsetNSEC3PARAM(zonename);
28✔
396
      }
28✔
397
      else if (rr->d_class == QClass::NONE) {
×
398
        NSEC3PARAMRecordContent nsec3rr(rr->getContent()->getZoneRepresentation(), di->zone);
×
399
        if (*haveNSEC3 && ns3pr->getZoneRepresentation() == nsec3rr.getZoneRepresentation())
×
400
          d_dk.unsetNSEC3PARAM(zonename);
×
401
        else
×
UNCOV
402
          return 0;
×
UNCOV
403
      } else
×
UNCOV
404
        return 0;
×
405

406
      // Update NSEC3 variables, other RR's in this update package might need them as well.
407
      *haveNSEC3 = false;
28✔
408
      *narrow = false;
28✔
409

410
      string error;
28✔
411
      string info;
28✔
412
      if (!d_dk.rectifyZone(di->zone, error, info, false)) {
28!
UNCOV
413
        throw PDNSException("Failed to rectify '" + di->zone.toLogString() + "': " + error);
×
UNCOV
414
      }
×
415
      return 1;
28✔
416
    } // end of NSEC3PARAM delete block
28✔
417

418

419
    di->backend->lookup(rrType, rr->d_name, di->id);
1,158✔
420
    while(di->backend->get(rec)) {
4,736✔
421
      if (rr->d_class == QClass::ANY) { // 3.4.2.3
3,578✔
422
        if (rec.qname == di->zone.operator const DNSName&() && (rec.qtype == QType::NS || rec.qtype == QType::SOA)) { // Never delete all SOA and NS's
2,992!
423
          rrset.push_back(rec);
44✔
424
        }
44✔
425
        else
2,948✔
426
          recordsToDelete.push_back(rec);
2,948✔
427
      }
2,992✔
428
      if (rr->d_class == QClass::NONE) { // 3.4.2.4
3,578✔
429
        auto repr = rec.getZoneRepresentation();
586✔
430
        if (rec.qtype == QType::TXT) {
586✔
431
          DLOG(g_log<<msgPrefix<<"Adjusting TXT content from ["<<repr<<"]"<<endl);
66✔
432
          auto drc = DNSRecordContent::make(rec.qtype.getCode(), QClass::IN, repr);
66✔
433
          auto ser = drc->serialize(rec.qname, true, true);
66✔
434
          auto rc = DNSRecordContent::deserialize(rec.qname, rec.qtype.getCode(), ser);
66✔
435
          repr = rc->getZoneRepresentation(true);
66✔
436
          DLOG(g_log<<msgPrefix<<"Adjusted TXT content to ["<<repr<<"]"<<endl);
66✔
437
        }
66✔
438
        DLOG(g_log<<msgPrefix<<"Matching RR in RRset - (adjusted) representation from request=["<<repr<<"], rr->getContent()->getZoneRepresentation()=["<<rr->getContent()->getZoneRepresentation()<<"]"<<endl);
586✔
439
        if (rrType == rec.qtype && repr == rr->getContent()->getZoneRepresentation())
586!
440
          recordsToDelete.push_back(rec);
410✔
441
        else
176✔
442
          rrset.push_back(rec);
176✔
443
      }
586✔
444
    }
3,578✔
445
  
446
    if (recordsToDelete.size()) {
1,158✔
447
      di->backend->replaceRRSet(di->id, rr->d_name, rrType, rrset);
1,114✔
448
      g_log<<Logger::Notice<<msgPrefix<<"Deleting record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
1,114✔
449
      changedRecords += recordsToDelete.size();
1,114✔
450

451

452
      // If we've removed a delegate, we need to reset ordername/auth for some records.
453
      if (rrType == QType::NS && rr->d_name != di->zone.operator const DNSName&()) { 
1,114✔
454
        vector<DNSName> belowOldDelegate, nsRecs, updateAuthFlag;
154✔
455
        di->backend->listSubZone(ZoneName(rr->d_name), di->id);
154✔
456
        while (di->backend->get(rec)) {
396✔
457
          if (rec.qtype.getCode()) // skip ENT records, they are always auth=false
242!
458
            belowOldDelegate.push_back(rec.qname);
242✔
459
          if (rec.qtype.getCode() == QType::NS && rec.qname != rr->d_name)
242!
460
            nsRecs.push_back(rec.qname);
22✔
461
        }
242✔
462

463
        for(auto &belowOldDel: belowOldDelegate)
154✔
464
        {
242✔
465
          bool isBelowDelegate = false;
242✔
466
          for(const auto & ns: nsRecs) {
242✔
467
            if (ns.isPartOf(belowOldDel)) {
66✔
468
              isBelowDelegate=true;
22✔
469
              break;
22✔
470
            }
22✔
471
          }
66✔
472
          if (!isBelowDelegate)
242✔
473
            updateAuthFlag.push_back(belowOldDel);
220✔
474
        }
242✔
475

476
        for (const auto &changeRec:updateAuthFlag) {
220✔
477
          DNSName ordername;
220✔
478
          if(*haveNSEC3)  {
220✔
479
            if(! *narrow) {
120✔
480
              ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, changeRec)));
80✔
481
            }
80✔
482
          }
120✔
483
          else { // NSEC
100✔
484
            ordername=changeRec.makeRelative(di->zone);
100✔
485
          }
100✔
486
          di->backend->updateDNSSECOrderNameAndAuth(di->id, changeRec, ordername, true, QType::ANY, *haveNSEC3 && !*narrow);
220✔
487
        }
220✔
488
      }
154✔
489

490
      // Fix ENT records.
491
      // We must check if we have a record below the current level and if we removed the 'last' record
492
      // on that level. If so, we must insert an ENT record.
493
      // We take extra care here to not 'include' the record that we just deleted. Some backends will still return it as they only reload on a commit.
494
      bool foundDeeper = false, foundOtherWithSameName = false;
1,114✔
495
      di->backend->listSubZone(ZoneName(rr->d_name), di->id);
1,114✔
496
      while (di->backend->get(rec)) {
6,328✔
497
        if (rec.qname == rr->d_name && !count(recordsToDelete.begin(), recordsToDelete.end(), rec))
5,214!
498
          foundOtherWithSameName = true;
946✔
499
        if (rec.qname != rr->d_name && rec.qtype.getCode() != QType::NS) //Skip NS records, as this would be a delegate that we can ignore as this does not require us to create a ENT
5,214✔
500
          foundDeeper = true;
3,872✔
501
      }
5,214✔
502

503
      if (foundDeeper && !foundOtherWithSameName) {
1,114✔
504
        insnonterm.insert(rr->d_name);
132✔
505
      } else if (!foundOtherWithSameName) {
982✔
506
        // If we didn't have to insert an ENT, we might have deleted a record at very deep level
507
        // and we must then clean up the ENT's above the deleted record.
508
        DNSName shorter(rr->d_name);
718✔
509
        while (shorter != di->zone.operator const DNSName&()) {
1,114!
510
          shorter.chopOff();
1,114✔
511
          bool foundRealRR = false;
1,114✔
512
          bool foundEnt = false;
1,114✔
513

514
          // The reason for a listSubZone here is because might go up the tree and find the ENT of another branch
515
          // consider these non ENT-records:
516
          // b.c.d.e.test.com
517
          // b.d.e.test.com
518
          // if we delete b.c.d.e.test.com, we go up to d.e.test.com and then find b.d.e.test.com because that's below d.e.test.com.
519
          // At that point we can stop deleting ENT's because the tree is in tact again.
520
          di->backend->listSubZone(ZoneName(shorter), di->id);
1,114✔
521

522
          while (di->backend->get(rec)) {
15,170✔
523
            if (rec.qtype.getCode())
14,056✔
524
              foundRealRR = true;
12,150✔
525
            else
1,906✔
526
              foundEnt = true;
1,906✔
527
          }
14,056✔
528
          if (!foundRealRR) {
1,114✔
529
            if (foundEnt) // only delete the ENT if we actually found one.
396✔
530
              delnonterm.insert(shorter);
330✔
531
          } else
396✔
532
            break;
718✔
533
        }
1,114✔
534
      }
718✔
535
    } else { // if (recordsToDelete.size())
1,114✔
536
      g_log<<Logger::Notice<<msgPrefix<<"Deletion for record "<<rr->d_name<<"|"<<rrType.toString()<<" requested, but not found."<<endl;
44✔
537
    }
44✔
538
  } // (End of delete block d_class == ANY || d_class == NONE
1,158✔
539
  
540

541

542
  //Insert and delete ENT's
543
  if (insnonterm.size() > 0 || delnonterm.size() > 0) {
4,780✔
544
    DLOG(g_log<<msgPrefix<<"Updating ENT records - "<<insnonterm.size()<<"|"<<delnonterm.size()<<endl);
3,644✔
545
    di->backend->updateEmptyNonTerminals(di->id, insnonterm, delnonterm, false);
3,644✔
546
    for (const auto &i: insnonterm) {
3,644✔
547
      string hashed;
352✔
548
      if(*haveNSEC3)
352✔
549
      {
192✔
550
        DNSName ordername;
192✔
551
        if(! *narrow) {
192✔
552
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, i)));
128✔
553
        }
128✔
554
        di->backend->updateDNSSECOrderNameAndAuth(di->id, i, ordername, true, QType::ANY, !*narrow);
192✔
555
      }
192✔
556
    }
352✔
557
  }
3,644✔
558

559
  return changedRecords;
4,780✔
560
}
4,808✔
561

UNCOV
562
int PacketHandler::forwardPacket(const string &msgPrefix, const DNSPacket& p, const DomainInfo& di) {
×
563
  vector<string> forward;
×
564
  B.getDomainMetadata(p.qdomainzone, "FORWARD-DNSUPDATE", forward);
×
565

566
  if (forward.size() == 0 && ! ::arg().mustDo("forward-dnsupdate")) {
×
UNCOV
567
    g_log << Logger::Notice << msgPrefix << "Not configured to forward to primary, returning Refused." << endl;
×
568
    return RCode::Refused;
×
569
  }
×
570

571
  for (const auto& remote : di.primaries) {
×
572
    g_log << Logger::Notice << msgPrefix << "Forwarding packet to primary " << remote << endl;
×
573

574
    if (!pdns::isQueryLocalAddressFamilyEnabled(remote.sin4.sin_family)) {
×
575
      continue;
×
576
    }
×
577
    auto local = pdns::getQueryLocalAddress(remote.sin4.sin_family, 0);
×
578
    int sock = makeQuerySocket(local, false); // create TCP socket. RFC2136 section 6.2 seems to be ok with this.
×
579
    if(sock < 0) {
×
UNCOV
580
      g_log<<Logger::Error<<msgPrefix<<"Error creating socket: "<<stringerror()<<endl;
×
581
      continue;
×
582
    }
×
583

584
    if( connect(sock, (struct sockaddr*)&remote, remote.getSocklen()) < 0 ) {
×
585
      g_log<<Logger::Error<<msgPrefix<<"Failed to connect to "<<remote.toStringWithPort()<<": "<<stringerror()<<endl;
×
586
      try {
×
587
        closesocket(sock);
×
588
      }
×
589
      catch(const PDNSException& e) {
×
590
        g_log << Logger::Error << "Error closing primary forwarding socket after connect() failed: " << e.reason << endl;
×
UNCOV
591
      }
×
592
      continue;
×
593
    }
×
594

595
    DNSPacket l_forwardPacket(p);
×
596
    l_forwardPacket.setID(dns_random_uint16());
×
597
    l_forwardPacket.setRemote(&remote);
×
598
    uint16_t len=htons(l_forwardPacket.getString().length());
×
599
    string buffer((const char*)&len, 2);
×
600
    buffer.append(l_forwardPacket.getString());
×
601
    if(write(sock, buffer.c_str(), buffer.length()) < 0) {
×
602
      g_log<<Logger::Error<<msgPrefix<<"Unable to forward update message to "<<remote.toStringWithPort()<<", error:"<<stringerror()<<endl;
×
603
      try {
×
604
        closesocket(sock);
×
605
      }
×
606
      catch(const PDNSException& e) {
×
607
        g_log << Logger::Error << "Error closing primary forwarding socket after write() failed: " << e.reason << endl;
×
UNCOV
608
      }
×
609
      continue;
×
610
    }
×
611

612
    int res = waitForData(sock, 10, 0);
×
613
    if (!res) {
×
614
      g_log << Logger::Error << msgPrefix << "Timeout waiting for reply from primary at " << remote.toStringWithPort() << endl;
×
615
      try {
×
616
        closesocket(sock);
×
617
      }
×
618
      catch(const PDNSException& e) {
×
619
        g_log << Logger::Error << "Error closing primary forwarding socket after a timeout occurred: " << e.reason << endl;
×
620
      }
×
621
      continue;
×
622
    }
×
623
    if (res < 0) {
×
624
      g_log << Logger::Error << msgPrefix << "Error waiting for answer from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
625
      try {
×
626
        closesocket(sock);
×
627
      }
×
628
      catch(const PDNSException& e) {
×
629
        g_log << Logger::Error << "Error closing primary forwarding socket after an error occurred: " << e.reason << endl;
×
UNCOV
630
      }
×
631
      continue;
×
632
    }
×
633

634
    unsigned char lenBuf[2];
×
635
    ssize_t recvRes;
×
636
    recvRes = recv(sock, &lenBuf, sizeof(lenBuf), 0);
×
637
    if (recvRes < 0 || static_cast<size_t>(recvRes) < sizeof(lenBuf)) {
×
638
      g_log << Logger::Error << msgPrefix << "Could not receive data (length) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
639
      try {
×
640
        closesocket(sock);
×
641
      }
×
642
      catch(const PDNSException& e) {
×
643
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
×
644
      }
×
UNCOV
645
      continue;
×
646
    }
×
647
    size_t packetLen = lenBuf[0]*256+lenBuf[1];
×
648

649
    buffer.resize(packetLen);
×
650
    recvRes = recv(sock, &buffer.at(0), packetLen, 0);
×
651
    if (recvRes < 0) {
×
652
      g_log << Logger::Error << msgPrefix << "Could not receive data (dnspacket) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
653
      try {
×
654
        closesocket(sock);
×
655
      }
×
656
      catch(const PDNSException& e) {
×
657
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
×
658
      }
×
659
      continue;
×
660
    }
×
661
    try {
×
662
      closesocket(sock);
×
663
    }
×
UNCOV
664
    catch(const PDNSException& e) {
×
665
      g_log << Logger::Error << "Error closing primary forwarding socket: " << e.reason << endl;
×
666
    }
×
667

668
    try {
×
669
      MOADNSParser mdp(false, buffer.data(), static_cast<unsigned int>(recvRes));
×
670
      g_log<<Logger::Info<<msgPrefix<<"Forward update message to "<<remote.toStringWithPort()<<", result was RCode "<<mdp.d_header.rcode<<endl;
×
671
      return mdp.d_header.rcode;
×
672
    }
×
673
    catch (...) {
×
674
      g_log << Logger::Error << msgPrefix << "Failed to parse response packet from primary at " << remote.toStringWithPort() << endl;
×
675
      continue;
×
676
    }
×
UNCOV
677
  }
×
678
  g_log << Logger::Error << msgPrefix << "Failed to forward packet to primary(s). Returning ServFail." << endl;
×
UNCOV
679
  return RCode::ServFail;
×
680

UNCOV
681
}
×
682

683
int PacketHandler::processUpdate(DNSPacket& packet) { // NOLINT(readability-function-cognitive-complexity)
2,294✔
684
  if (! ::arg().mustDo("dnsupdate"))
2,294!
UNCOV
685
    return RCode::Refused;
×
686

687
  string msgPrefix="UPDATE (" + std::to_string(packet.d.id) + ") from " + packet.getRemoteString() + " for " + packet.qdomainzone.toLogString() + ": ";
2,294✔
688
  g_log<<Logger::Info<<msgPrefix<<"Processing started."<<endl;
2,294✔
689

690
  // if there is policy, we delegate all checks to it
691
  if (this->d_update_policy_lua == nullptr) {
2,294!
692

693
    // Check permissions - IP based
694
    vector<string> allowedRanges;
2,294✔
695
    B.getDomainMetadata(packet.qdomainzone, "ALLOW-DNSUPDATE-FROM", allowedRanges);
2,294✔
696
    if (! ::arg()["allow-dnsupdate-from"].empty())
2,294!
697
      stringtok(allowedRanges, ::arg()["allow-dnsupdate-from"], ", \t" );
2,294✔
698

699
    NetmaskGroup ng;
2,294✔
700
    for(const auto& i: allowedRanges) {
4,588✔
701
      ng.addMask(i);
4,588✔
702
    }
4,588✔
703

704
    if ( ! ng.match(packet.getInnerRemote())) {
2,294!
UNCOV
705
      g_log<<Logger::Error<<msgPrefix<<"Remote not listed in allow-dnsupdate-from or domainmetadata. Sending REFUSED"<<endl;
×
UNCOV
706
      return RCode::Refused;
×
UNCOV
707
    }
×
708

709

710
    // Check permissions - TSIG based.
711
    vector<string> tsigKeys;
2,294✔
712
    B.getDomainMetadata(packet.qdomainzone, "TSIG-ALLOW-DNSUPDATE", tsigKeys);
2,294✔
713
    if (tsigKeys.size() > 0) {
2,294!
714
      bool validKey = false;
×
715

716
      TSIGRecordContent trc;
×
717
      DNSName inputkey;
×
718
      string message;
×
719
      if (! packet.getTSIGDetails(&trc,  &inputkey)) {
×
720
        g_log<<Logger::Error<<msgPrefix<<"TSIG key required, but packet does not contain key. Sending REFUSED"<<endl;
×
721
        return RCode::Refused;
×
722
      }
×
723
#ifdef ENABLE_GSS_TSIG
×
724
      if (g_doGssTSIG && packet.d_tsig_algo == TSIG_GSS) {
×
725
        GssName inputname(packet.d_peer_principal); // match against principal since GSS requires that
×
726
        for(const auto& key: tsigKeys) {
×
727
          if (inputname.match(key)) {
×
728
            validKey = true;
×
729
            break;
×
730
          }
×
731
        }
×
732
      }
×
733
      else
×
734
#endif
×
735
        {
×
736
        for(const auto& key: tsigKeys) {
×
737
          if (inputkey == DNSName(key)) { // because checkForCorrectTSIG has already been performed earlier on, if the name of the key matches with the domain given it is valid.
×
738
            validKey=true;
×
739
            break;
×
UNCOV
740
          }
×
741
        }
×
742
      }
×
743

744
      if (!validKey) {
×
UNCOV
745
        g_log<<Logger::Error<<msgPrefix<<"TSIG key ("<<inputkey<<") required, but no matching key found in domainmetadata, tried "<<tsigKeys.size()<<". Sending REFUSED"<<endl;
×
746
        return RCode::Refused;
×
747
      }
×
748
    } else if(::arg().mustDo("dnsupdate-require-tsig")) {
2,294!
UNCOV
749
      g_log<<Logger::Error<<msgPrefix<<"TSIG key required, but domain is not secured with TSIG. Sending REFUSED"<<endl;
×
UNCOV
750
      return RCode::Refused;
×
751
    }
×
752

753
    if (tsigKeys.empty() && packet.d_havetsig) {
2,294!
UNCOV
754
      g_log<<Logger::Warning<<msgPrefix<<"TSIG is provided, but domain is not secured with TSIG. Processing continues"<<endl;
×
UNCOV
755
    }
×
756

757
  }
2,294✔
758

759
  // RFC2136 uses the same DNS Header and Message as defined in RFC1035.
760
  // This means we can use the MOADNSParser to parse the incoming packet. The result is that we have some different
761
  // variable names during the use of our MOADNSParser.
762
  MOADNSParser mdp(false, packet.getString());
2,294✔
763
  if (mdp.d_header.qdcount != 1) {
2,294!
UNCOV
764
    g_log<<Logger::Warning<<msgPrefix<<"Zone Count is not 1, sending FormErr"<<endl;
×
UNCOV
765
    return RCode::FormErr;
×
766
  }
×
767

768
  if (packet.qtype.getCode() != QType::SOA) { // RFC2136 2.3 - ZTYPE must be SOA
2,294!
UNCOV
769
    g_log<<Logger::Warning<<msgPrefix<<"Query ZTYPE is not SOA, sending FormErr"<<endl;
×
UNCOV
770
    return RCode::FormErr;
×
771
  }
×
772

773
  if (packet.qclass != QClass::IN) {
2,294!
UNCOV
774
    g_log<<Logger::Warning<<msgPrefix<<"Class is not IN, sending NotAuth"<<endl;
×
UNCOV
775
    return RCode::NotAuth;
×
UNCOV
776
  }
×
777

778
  DomainInfo di;
2,294✔
779
  di.backend=nullptr;
2,294✔
780
  if(!B.getDomainInfo(packet.qdomainzone, di) || (di.backend == nullptr)) {
2,294!
781
    g_log<<Logger::Error<<msgPrefix<<"Can't determine backend for domain '"<<packet.qdomainzone<<"' (or backend does not support DNS update operation)"<<endl;
22✔
782
    return RCode::NotAuth;
22✔
783
  }
22✔
784

785
  if (di.kind == DomainInfo::Secondary)
2,272!
UNCOV
786
    return forwardPacket(msgPrefix, packet, di);
×
787

788
  // Check if all the records provided are within the zone
789
  for(const auto & answer : mdp.d_answers) {
5,556✔
790
    const DNSRecord *dnsRecord = &answer;
5,556✔
791
    // Skip this check for other field types (like the TSIG -  which is in the additional section)
792
    // For a TSIG, the label is the dnskey, so it does not pass the endOn validation.
793
    if (dnsRecord->d_place != DNSResourceRecord::ANSWER && dnsRecord->d_place != DNSResourceRecord::AUTHORITY) {
5,556!
UNCOV
794
      continue;
×
UNCOV
795
    }
×
796

797
    if (!dnsRecord->d_name.isPartOf(di.zone)) {
5,556✔
798
      g_log<<Logger::Error<<msgPrefix<<"Received update/record out of zone, sending NotZone."<<endl;
44✔
799
      return RCode::NotZone;
44✔
800
    }
44✔
801
  }
5,556✔
802

803

804
  auto lock = std::scoped_lock(s_rfc2136lock); //TODO: i think this lock can be per zone, not for everything
2,228✔
805
  g_log<<Logger::Info<<msgPrefix<<"starting transaction."<<endl;
2,228✔
806
  if (!di.backend->startTransaction(packet.qdomainzone, UnknownDomainID)) { // Not giving the domain_id means that we do not delete the existing records.
2,228!
UNCOV
807
    g_log<<Logger::Error<<msgPrefix<<"Backend for domain "<<packet.qdomainzone<<" does not support transaction. Can't do Update packet."<<endl;
×
UNCOV
808
    return RCode::NotImp;
×
UNCOV
809
  }
×
810

811
  // 3.2.1 and 3.2.2 - Prerequisite check
812
  for(const auto & answer : mdp.d_answers) {
5,424✔
813
    const DNSRecord *dnsRecord = &answer;
5,424✔
814
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
5,424✔
815
      int res = checkUpdatePrerequisites(dnsRecord, &di);
418✔
816
      if (res>0) {
418✔
817
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check for "<<dnsRecord->d_name<<", returning "<<RCode::to_s(res)<<endl;
110✔
818
        di.backend->abortTransaction();
110✔
819
        return res;
110✔
820
      }
110✔
821
    }
418✔
822
  }
5,424✔
823

824
  // 3.2.3 - Prerequisite check - this is outside of updatePrerequisitesCheck because we check an RRSet and not the RR.
825
  typedef pair<DNSName, QType> rrSetKey_t;
2,118✔
826
  typedef vector<DNSResourceRecord> rrVector_t;
2,118✔
827
  typedef std::map<rrSetKey_t, rrVector_t> RRsetMap_t;
2,118✔
828
  RRsetMap_t preReqRRsets;
2,118✔
829
  for(const auto& i: mdp.d_answers) {
5,314✔
830
    const DNSRecord* dnsRecord = &i;
5,314✔
831
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
5,314✔
832
      // Last line of 3.2.3
833
      if (dnsRecord->d_class != QClass::IN && dnsRecord->d_class != QClass::NONE && dnsRecord->d_class != QClass::ANY) {
308!
UNCOV
834
        di.backend->abortTransaction();
×
UNCOV
835
        return RCode::FormErr;
×
UNCOV
836
      }
×
837

838
      if (dnsRecord->d_class == QClass::IN) {
308✔
839
        rrSetKey_t key = {dnsRecord->d_name, QType(dnsRecord->d_type)};
198✔
840
        rrVector_t *vec = &preReqRRsets[key];
198✔
841
        vec->push_back(DNSResourceRecord::fromWire(*dnsRecord));
198✔
842
      }
198✔
843
    }
308✔
844
  }
5,314✔
845

846
  if (preReqRRsets.size() > 0) {
2,118✔
847
    RRsetMap_t zoneRRsets;
66✔
848
    for (auto & preReqRRset : preReqRRsets) {
66✔
849
      rrSetKey_t rrSet=preReqRRset.first;
66✔
850
      rrVector_t *vec = &preReqRRset.second;
66✔
851

852
      DNSResourceRecord rec;
66✔
853
      di.backend->lookup(QType(QType::ANY), rrSet.first, di.id);
66✔
854
      uint16_t foundRR=0, matchRR=0;
66✔
855
      while (di.backend->get(rec)) {
264✔
856
        if (rec.qtype == rrSet.second) {
198!
857
          foundRR++;
198✔
858
          for(auto & rrItem : *vec) {
594✔
859
            rrItem.ttl = rec.ttl; // The compare one line below also compares TTL, so we make them equal because TTL is not user within prerequisite checks.
594✔
860
            if (rrItem == rec)
594✔
861
              matchRR++;
198✔
862
          }
594✔
863
        }
198✔
864
      }
198✔
865
      if (matchRR != foundRR || foundRR != vec->size()) {
66!
866
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check (RRs differ), returning NXRRSet"<<endl;
44✔
867
        di.backend->abortTransaction();
44✔
868
        return RCode::NXRRSet;
44✔
869
      }
44✔
870
    }
66✔
871
  }
66✔
872

873

874

875
  // 3.4 - Prescan & Add/Update/Delete records - is all done within a try block.
876
  try {
2,074✔
877
    uint changedRecords = 0;
2,074✔
878
    // 3.4.1 - Prescan section
879
    for(const auto & answer : mdp.d_answers) {
5,182✔
880
      const DNSRecord *dnsRecord = &answer;
5,182✔
881
      if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
5,182✔
882
        int res = checkUpdatePrescan(dnsRecord);
5,006✔
883
        if (res>0) {
5,006✔
884
          g_log<<Logger::Error<<msgPrefix<<"Failed prescan check, returning "<<res<<endl;
22✔
885
          di.backend->abortTransaction();
22✔
886
          return res;
22✔
887
        }
22✔
888
      }
5,006✔
889
    }
5,182✔
890

891
    bool updatedSerial=false;
2,052✔
892
    NSEC3PARAMRecordContent ns3pr;
2,052✔
893
    bool narrow=false;
2,052✔
894
    bool haveNSEC3 = d_dk.getNSEC3PARAM(di.zone, &ns3pr, &narrow);
2,052✔
895
    bool isPresigned = d_dk.isPresigned(di.zone);
2,052✔
896
    string soaEditSetting;
2,052✔
897
    d_dk.getSoaEdit(di.zone, soaEditSetting);
2,052✔
898

899
    // 3.4.2 - Perform the updates.
900
    // There's a special condition where deleting the last NS record at zone apex is never deleted (3.4.2.4)
901
    // This means we must do it outside the normal performUpdate() because that focusses only on a separate RR.
902
    vector<const DNSRecord *> nsRRtoDelete;
2,052✔
903

904
    // Another special case is the addition of both a CNAME and a non-CNAME for the same name (#6270)
905
    set<DNSName> cn, nocn;
2,052✔
906
    for (const auto &rr : mdp.d_answers) {
5,160✔
907
      if (rr.d_place == DNSResourceRecord::AUTHORITY && rr.d_class == QClass::IN && rr.d_ttl > 0) {
5,160!
908
        // Addition
909
        if (rr.d_type == QType::CNAME) {
3,732✔
910
          cn.insert(rr.d_name);
176✔
911
        } else if (rr.d_type != QType::RRSIG) {
3,556!
912
          nocn.insert(rr.d_name);
3,556✔
913
        }
3,556✔
914
      }
3,732✔
915
    }
5,160✔
916
    for (auto const &n : cn) {
2,052✔
917
      if (nocn.count(n) > 0) {
176✔
918
        g_log<<Logger::Error<<msgPrefix<<"Refusing update, found CNAME and non-CNAME addition"<<endl;
22✔
919
        di.backend->abortTransaction();
22✔
920
        return RCode::FormErr;
22✔
921
      }
22✔
922
    }
176✔
923

924
    vector<const DNSRecord *> cnamesToAdd, nonCnamesToAdd;
2,030✔
925
    for(const auto & answer : mdp.d_answers) {
5,116✔
926
      const DNSRecord *dnsRecord = &answer;
5,116✔
927
      if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
5,116✔
928
        /* see if it's permitted by policy */
929
        if (this->d_update_policy_lua != nullptr) {
4,940!
930
          if (!this->d_update_policy_lua->updatePolicy(dnsRecord->d_name, QType(dnsRecord->d_type), di.zone.operator const DNSName&(), packet)) {
×
931
            g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Not permitted by policy"<<endl;
×
932
            continue;
×
933
          } else {
×
UNCOV
934
            g_log<<Logger::Debug<<msgPrefix<<"Accepting update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Permitted by policy"<<endl;
×
UNCOV
935
          }
×
UNCOV
936
        }
×
937

938
        if (dnsRecord->d_class == QClass::NONE  && dnsRecord->d_type == QType::NS && dnsRecord->d_name == di.zone.operator const DNSName&()) {
4,940!
939
          nsRRtoDelete.push_back(dnsRecord);
66✔
940
        }
66✔
941
        else if (dnsRecord->d_class == QClass::IN &&  dnsRecord->d_ttl > 0) {
4,874!
942
          if (dnsRecord->d_type == QType::CNAME) {
3,688✔
943
            cnamesToAdd.push_back(dnsRecord);
154✔
944
          } else {
3,534✔
945
            nonCnamesToAdd.push_back(dnsRecord);
3,534✔
946
          }
3,534✔
947
        }
3,688✔
948
        else
1,186✔
949
          changedRecords += performUpdate(msgPrefix, dnsRecord, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
1,186✔
950
      }
4,940✔
951
    }
5,116✔
952
    for (const auto &rr : cnamesToAdd) {
2,030✔
953
      DNSResourceRecord rec;
154✔
954
      di.backend->lookup(QType(QType::ANY), rr->d_name, di.id);
154✔
955
      while (di.backend->get(rec)) {
220✔
956
        if (rec.qtype != QType::CNAME && rec.qtype != QType::ENT && rec.qtype != QType::RRSIG) {
88!
957
          // leave database handle in a consistent state
958
          di.backend->lookupEnd();
22✔
959
          g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << rr->d_name << "/" << QType(rr->d_type).toString() << ": Data other than CNAME exists for the same name"<<endl;
22✔
960
          di.backend->abortTransaction();
22✔
961
          return RCode::Refused;
22✔
962
        }
22✔
963
      }
88✔
964
      changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
132✔
965
    }
132✔
966
    for (const auto &rr : nonCnamesToAdd) {
3,534✔
967
      DNSResourceRecord rec;
3,534✔
968
      di.backend->lookup(QType(QType::CNAME), rr->d_name, di.id);
3,534✔
969
      while (di.backend->get(rec)) {
3,534✔
970
        if (rec.qtype == QType::CNAME && rr->d_type != QType::RRSIG) {
22!
971
          // leave database handle in a consistent state
972
          di.backend->lookupEnd();
22✔
973
          g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << rr->d_name << "/" << QType(rr->d_type).toString() << ": CNAME exists for the same name"<<endl;
22✔
974
          di.backend->abortTransaction();
22✔
975
          return RCode::Refused;
22✔
976
        }
22✔
977
      }
22✔
978
      changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
3,512✔
979
    }
3,512✔
980
    if (nsRRtoDelete.size()) {
1,986✔
981
      vector<DNSResourceRecord> nsRRInZone;
44✔
982
      DNSResourceRecord rec;
44✔
983
      di.backend->lookup(QType(QType::NS), di.zone.operator const DNSName&(), di.id);
44✔
984
      while (di.backend->get(rec)) {
132✔
985
        nsRRInZone.push_back(rec);
88✔
986
      }
88✔
987
      if (nsRRInZone.size() > nsRRtoDelete.size()) { // only delete if the NS's we delete are less then what we have in the zone (3.4.2.4)
44✔
988
        for (auto& inZone: nsRRInZone) {
44✔
989
          for (auto& rr: nsRRtoDelete) {
44✔
990
            if (inZone.getZoneRepresentation() == (rr)->getContent()->getZoneRepresentation())
44✔
991
              changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
22✔
992
          }
44✔
993
        }
44✔
994
      }
22✔
995
    }
44✔
996

997
    // Section 3.6 - Update the SOA serial - outside of performUpdate because we do a SOA update for the complete update message
998
    if (changedRecords > 0 && !updatedSerial) {
1,986✔
999
      increaseSerial(msgPrefix, &di, soaEditSetting, haveNSEC3, narrow, &ns3pr);
1,766✔
1000
      changedRecords++;
1,766✔
1001
    }
1,766✔
1002

1003
    if (changedRecords > 0) {
1,986✔
1004
      if (!di.backend->commitTransaction()) {
1,810!
1005
       g_log<<Logger::Error<<msgPrefix<<"Failed to commit updates!"<<endl;
×
1006
        return RCode::ServFail;
×
UNCOV
1007
      }
×
1008

1009
      S.deposit("dnsupdate-changes", changedRecords);
1,810✔
1010

1011
      d_dk.clearMetaCache(di.zone);
1,810✔
1012
      // Purge the records!
1013
      purgeAuthCaches(di.zone.operator const DNSName&().toString() + "$");
1,810✔
1014

1015
      // Notify secondaries
1016
      if (di.kind == DomainInfo::Primary) {
1,810!
1017
        vector<string> notify;
1,810✔
1018
        B.getDomainMetadata(packet.qdomainzone, "NOTIFY-DNSUPDATE", notify);
1,810✔
1019
        if (!notify.empty() && notify.front() == "1") {
1,810!
1020
          Communicator.notifyDomain(di.zone, &B);
×
UNCOV
1021
        }
×
1022
      }
1,810✔
1023

1024
      g_log<<Logger::Info<<msgPrefix<<"Update completed, "<<changedRecords<<" changed records committed."<<endl;
1,810✔
1025
    } else {
1,810✔
1026
      //No change, no commit, we perform abort() because some backends might like this more.
1027
      g_log<<Logger::Info<<msgPrefix<<"Update completed, 0 changes, rolling back."<<endl;
176✔
1028
      di.backend->abortTransaction();
176✔
1029
    }
176✔
1030
    return RCode::NoError; //rfc 2136 3.4.2.5
1,986✔
1031
  }
1,986✔
1032
  catch (SSqlException &e) {
2,074✔
1033
    g_log<<Logger::Error<<msgPrefix<<"Caught SSqlException: "<<e.txtReason()<<"; Sending ServFail!"<<endl;
×
1034
    di.backend->abortTransaction();
×
1035
    return RCode::ServFail;
×
UNCOV
1036
  }
×
1037
  catch (DBException &e) {
2,074✔
1038
    g_log<<Logger::Error<<msgPrefix<<"Caught DBException: "<<e.reason<<"; Sending ServFail!"<<endl;
×
1039
    di.backend->abortTransaction();
×
1040
    return RCode::ServFail;
×
UNCOV
1041
  }
×
1042
  catch (PDNSException &e) {
2,074✔
1043
    g_log<<Logger::Error<<msgPrefix<<"Caught PDNSException: "<<e.reason<<"; Sending ServFail!"<<endl;
×
1044
    di.backend->abortTransaction();
×
1045
    return RCode::ServFail;
×
UNCOV
1046
  }
×
1047
  catch(std::exception &e) {
2,074✔
1048
    g_log<<Logger::Error<<msgPrefix<<"Caught std:exception: "<<e.what()<<"; Sending ServFail!"<<endl;
×
1049
    di.backend->abortTransaction();
×
1050
    return RCode::ServFail;
×
UNCOV
1051
  }
×
1052
  catch (...) {
2,074✔
1053
    g_log<<Logger::Error<<msgPrefix<<"Caught unknown exception when performing update. Sending ServFail!"<<endl;
×
1054
    di.backend->abortTransaction();
×
1055
    return RCode::ServFail;
×
UNCOV
1056
  }
×
1057
}
2,074✔
1058

1059
void PacketHandler::increaseSerial(const string &msgPrefix, const DomainInfo *di, const string& soaEditSetting,  bool haveNSEC3, bool narrow, const NSEC3PARAMRecordContent *ns3pr) {
1,766✔
1060
  SOAData sd;
1,766✔
1061
  if (!di->backend->getSOA(di->zone, di->id, sd)) {
1,766!
1062
    throw PDNSException("SOA-Serial update failed because there was no SOA. Wowie.");
×
UNCOV
1063
  }
×
1064

1065
  uint32_t oldSerial = sd.serial;
1,766✔
1066

1067
  vector<string> soaEdit2136Setting;
1,766✔
1068
  B.getDomainMetadata(di->zone, "SOA-EDIT-DNSUPDATE", soaEdit2136Setting);
1,766✔
1069
  string soaEdit2136 = "DEFAULT";
1,766✔
1070
  string soaEdit;
1,766✔
1071
  if (!soaEdit2136Setting.empty()) {
1,766!
1072
    soaEdit2136 = soaEdit2136Setting[0];
×
1073
    if (pdns_iequals(soaEdit2136, "SOA-EDIT") || pdns_iequals(soaEdit2136,"SOA-EDIT-INCREASE") ){
×
1074
      if (soaEditSetting.empty()) {
×
1075
        g_log<<Logger::Error<<msgPrefix<<"Using "<<soaEdit2136<<" for SOA-EDIT-DNSUPDATE increase on DNS update, but SOA-EDIT is not set for domain \""<< di->zone <<"\". Using DEFAULT for SOA-EDIT-DNSUPDATE"<<endl;
×
1076
        soaEdit2136 = "DEFAULT";
×
1077
      } else
×
1078
        soaEdit = soaEditSetting;
×
1079
    }
×
UNCOV
1080
  }
×
1081

1082
  DNSResourceRecord rr;
1,766✔
1083
  if (makeIncreasedSOARecord(sd, soaEdit2136, soaEdit, rr)) {
1,766!
1084
    di->backend->replaceRRSet(di->id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr));
1,766✔
1085
    g_log << Logger::Notice << msgPrefix << "Increasing SOA serial (" << oldSerial << " -> " << sd.serial << ")" << endl;
1,766✔
1086

1087
    //Correct ordername + auth flag
1088
    DNSName ordername;
1,766✔
1089
    if (haveNSEC3) {
1,766✔
1090
      if (!narrow) {
968✔
1091
        ordername = DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr.qname)));
660✔
1092
      }
660✔
1093
    } else { // NSEC
968✔
1094
      ordername = rr.qname.makeRelative(di->zone);
798✔
1095
    }
798✔
1096
    di->backend->updateDNSSECOrderNameAndAuth(di->id, rr.qname, ordername, true, QType::ANY, haveNSEC3 && !narrow);
1,766✔
1097
  }
1,766✔
1098
}
1,766✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc