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

PowerDNS / pdns / 12508806594

24 Dec 2024 09:40AM UTC coverage: 62.638% (-2.2%) from 64.807%
12508806594

push

github

web-flow
Merge pull request #14997 from rgacogne/ddist-fix-doc-action-typos

dnsdist: Fix some small issues in the documentation for actions

51566 of 129650 branches covered (39.77%)

Branch coverage included in aggregate %.

144003 of 182573 relevant lines covered (78.87%)

4648027.86 hits per line

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

0.0
/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) {
×
31
  if (rr->d_ttl != 0)
×
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)
×
36
    return RCode::FormErr;
×
37

38
  bool foundRecord=false;
×
39
  DNSResourceRecord rec;
×
40
  di->backend->lookup(QType(QType::ANY), rr->d_name, di->id);
×
41
  while(di->backend->get(rec)) {
×
42
    if (!rec.qtype.getCode())
×
43
      continue;
×
44
    if ((rr->d_type != QType::ANY && rec.qtype == rr->d_type) || rr->d_type == QType::ANY)
×
45
      foundRecord=true;
×
46
  }
×
47

48
  // Section 3.2.1
49
  if (rr->d_class == QClass::ANY && !foundRecord) {
×
50
    if (rr->d_type == QType::ANY)
×
51
      return RCode::NXDomain;
×
52
    if (rr->d_type != QType::ANY)
×
53
      return RCode::NXRRSet;
×
54
  }
×
55

56
  // Section 3.2.2
57
  if (rr->d_class == QClass::NONE && foundRecord) {
×
58
    if (rr->d_type == QType::ANY)
×
59
      return RCode::YXDomain;
×
60
    if (rr->d_type != QType::ANY)
×
61
      return RCode::YXRRSet;
×
62
  }
×
63

64
  return RCode::NoError;
×
65
}
×
66

67

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

75
  QType qtype = QType(rr->d_type);
×
76

77
  if (!qtype.isSupportedType()) {
×
78
    return RCode::FormErr;
×
79
  }
×
80

81
  if ((rr->d_class == QClass::NONE || rr->d_class == QClass::ANY) && rr->d_ttl != 0) {
×
82
    return RCode::FormErr;
×
83
  }
×
84

85
  if (rr->d_class == QClass::ANY && rr->d_clen != 0) {
×
86
    return RCode::FormErr;
×
87
  }
×
88

89
  if (qtype.isMetadataType()) {
×
90
    return RCode::FormErr;
×
91
  }
×
92

93
  if (rr->d_class != QClass::ANY && qtype.getCode() == QType::ANY) {
×
94
    return RCode::FormErr;
×
95
  }
×
96

97
  return RCode::NoError;
×
98
}
×
99

100

101
// Implements section 3.4.2 of RFC2136
102
uint PacketHandler::performUpdate(const string &msgPrefix, const DNSRecord *rr, DomainInfo *di, bool isPresigned, bool* narrow, bool* haveNSEC3, NSEC3PARAMRecordContent *ns3pr, bool *updatedSerial) {
×
103

104
  QType rrType = QType(rr->d_type);
×
105

106
  if (rrType == QType::NSEC || rrType == QType::NSEC3) {
×
107
    g_log<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rr->d_name<<"|"<<rrType.toString()<<". These are generated records, ignoring!"<<endl;
×
108
    return 0;
×
109
  }
×
110

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

116
  if ((rrType == QType::NSEC3PARAM || rrType == QType::DNSKEY) && rr->d_name != di->zone) {
×
117
    g_log<<Logger::Warning<<msgPrefix<<"Trying to add/update/delete "<<rr->d_name<<"|"<<rrType.toString()<<", "<<rrType.toString()<<" must be at zone apex, ignoring!"<<endl;
×
118
    return 0;
×
119
  }
×
120

121

122
  uint changedRecords = 0;
×
123
  DNSResourceRecord rec;
×
124
  vector<DNSResourceRecord> rrset, recordsToDelete;
×
125
  set<DNSName> delnonterm, insnonterm; // used to (at the end) fix ENT records.
×
126

127

128
  if (rr->d_class == QClass::IN) { // 3.4.2.2 QClass::IN means insert or update
×
129
    DLOG(g_log<<msgPrefix<<"Add/Update record (QClass == IN) "<<rr->d_name<<"|"<<rrType.toString()<<endl);
×
130

131
    if (rrType == QType::NSEC3PARAM) {
×
132
      g_log<<Logger::Notice<<msgPrefix<<"Adding/updating NSEC3PARAM for zone, resetting ordernames."<<endl;
×
133

134
      *ns3pr = NSEC3PARAMRecordContent(rr->getContent()->getZoneRepresentation(), di->zone);
×
135
      *narrow = false; // adding a NSEC3 will cause narrow mode to be dropped, as you cannot specify that in a NSEC3PARAM record
×
136
      d_dk.setNSEC3PARAM(di->zone, *ns3pr, (*narrow));
×
137
      *haveNSEC3 = true;
×
138

139
      string error;
×
140
      string info;
×
141
      if (!d_dk.rectifyZone(di->zone, error, info, false)) {
×
142
        throw PDNSException("Failed to rectify '" + di->zone.toLogString() + "': " + error);
×
143
      }
×
144
      return 1;
×
145
    }
×
146

147

148

149
    bool foundRecord = false;
×
150
    di->backend->lookup(rrType, rr->d_name, di->id);
×
151
    while (di->backend->get(rec)) {
×
152
      rrset.push_back(rec);
×
153
      foundRecord = true;
×
154
    }
×
155

156
    if (foundRecord) {
×
157

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

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

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

225
      // ReplaceRRSet dumps our ordername and auth flag, so we need to correct it if we have changed records.
226
      // We can take the auth flag from the first RR in the set, as the name is different, so should the auth be.
227
      if (changedRecords > 0) {
×
228
        bool auth = rrset.front().auth;
×
229

230
        if(*haveNSEC3) {
×
231
          DNSName ordername;
×
232
          if(! *narrow)
×
233
            ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr->d_name)));
×
234

235
          if (*narrow)
×
236
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), auth);
×
237
          else
×
238
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth);
×
239
          if(!auth || rrType == QType::DS) {
×
240
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::NS);
×
241
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A);
×
242
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA);
×
243
          }
×
244

245
        } else { // NSEC
×
246
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, rr->d_name.makeRelative(di->zone), auth);
×
247
          if(!auth || rrType == QType::DS) {
×
248
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A);
×
249
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA);
×
250
          }
×
251
        }
×
252
      }
×
253

254
    } // if (foundRecord)
×
255

256
    // If we haven't found a record that matches, we must add it.
257
    if (! foundRecord) {
×
258
      g_log<<Logger::Notice<<msgPrefix<<"Adding record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
×
259
      delnonterm.insert(rr->d_name); // always remove any ENT's in the place where we're going to add a record.
×
260
      auto newRec = DNSResourceRecord::fromWire(*rr);
×
261
      newRec.domain_id = di->id;
×
262
      newRec.auth = (rr->d_name == di->zone || rrType.getCode() != QType::NS);
×
263
      di->backend->feedRecord(newRec, DNSName());
×
264
      changedRecords++;
×
265

266

267
      // because we added a record, we need to fix DNSSEC data.
268
      DNSName shorter(rr->d_name);
×
269
      bool auth=newRec.auth;
×
270
      bool fixDS = (rrType == QType::DS);
×
271

272
      if (di->zone != shorter) { // Everything at APEX is auth=1 && no ENT's
×
273
        do {
×
274

275
          if (di->zone == shorter)
×
276
            break;
×
277

278
          bool foundShorter = false;
×
279
          di->backend->lookup(QType(QType::ANY), shorter, di->id);
×
280
          while (di->backend->get(rec)) {
×
281
            if (rec.qname == rr->d_name && rec.qtype == QType::DS)
×
282
              fixDS = true;
×
283
            if (shorter != rr->d_name)
×
284
              foundShorter = true;
×
285
            if (rec.qtype == QType::NS) // are we inserting below a delegate?
×
286
              auth=false;
×
287
          }
×
288

289
          if (!foundShorter && auth && shorter != rr->d_name) // haven't found any record at current level, insert ENT.
×
290
            insnonterm.insert(shorter);
×
291
          if (foundShorter)
×
292
            break; // if we find a shorter record, we can stop searching
×
293
        } while(shorter.chopOff());
×
294
      }
×
295

296
      if(*haveNSEC3)
×
297
      {
×
298
        DNSName ordername;
×
299
        if(! *narrow)
×
300
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr->d_name)));
×
301

302
        if (*narrow)
×
303
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), auth);
×
304
        else
×
305
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth);
×
306

307
        if (fixDS)
×
308
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, true, QType::DS);
×
309

310
        if(!auth)
×
311
        {
×
312
          if (ns3pr->d_flags)
×
313
            di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::NS);
×
314
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A);
×
315
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA);
×
316
        }
×
317
      }
×
318
      else // NSEC
×
319
      {
×
320
        DNSName ordername=rr->d_name.makeRelative(di->zone);
×
321
        di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, auth);
×
322
        if (fixDS) {
×
323
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, ordername, true, QType::DS);
×
324
        }
×
325
        if(!auth) {
×
326
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::A);
×
327
          di->backend->updateDNSSECOrderNameAndAuth(di->id, rr->d_name, DNSName(), false, QType::AAAA);
×
328
        }
×
329
      }
×
330

331

332
      // If we insert an NS, all the records below it become non auth - so, we're inserting a delegate.
333
      // Auth can only be false when the rr->d_name is not the zone
334
      if (auth == false && rrType == QType::NS) {
×
335
        DLOG(g_log<<msgPrefix<<"Going to fix auth flags below "<<rr->d_name<<endl);
×
336
        insnonterm.clear(); // No ENT's are needed below delegates (auth=0)
×
337
        vector<DNSName> qnames;
×
338
        di->backend->listSubZone(rr->d_name, di->id);
×
339
        while(di->backend->get(rec)) {
×
340
          if (rec.qtype.getCode() && rec.qtype.getCode() != QType::DS && rr->d_name != rec.qname) // Skip ENT, DS and our already corrected record.
×
341
            qnames.push_back(rec.qname);
×
342
        }
×
343
        for(const auto & qname : qnames) {
×
344
          if(*haveNSEC3)  {
×
345
            DNSName ordername;
×
346
            if(! *narrow)
×
347
              ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, qname)));
×
348

349
            if (*narrow)
×
350
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), auth);
×
351
            else
×
352
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, auth);
×
353

354
            if (ns3pr->d_flags)
×
355
              di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::NS);
×
356
          }
×
357
          else { // NSEC
×
358
            DNSName ordername=DNSName(qname).makeRelative(di->zone);
×
359
            di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, ordername, false, QType::NS);
×
360
          }
×
361

362
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::A);
×
363
          di->backend->updateDNSSECOrderNameAndAuth(di->id, qname, DNSName(), false, QType::AAAA);
×
364
        }
×
365
      }
×
366
    }
×
367
  } // rr->d_class == QClass::IN
×
368

369

370
  // 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
371
  // the code that calls this performUpdate().
372
  if ((rr->d_class == QClass::ANY || rr->d_class == QClass::NONE) && rrType != QType::SOA) { // never delete a SOA.
×
373
    DLOG(g_log<<msgPrefix<<"Deleting records: "<<rr->d_name<<"; QClass:"<<rr->d_class<<"; rrType: "<<rrType.toString()<<endl);
×
374

375
    if (rrType == QType::NSEC3PARAM) {
×
376
      g_log<<Logger::Notice<<msgPrefix<<"Deleting NSEC3PARAM from zone, resetting ordernames."<<endl;
×
377
      if (rr->d_class == QClass::ANY)
×
378
        d_dk.unsetNSEC3PARAM(rr->d_name);
×
379
      else if (rr->d_class == QClass::NONE) {
×
380
        NSEC3PARAMRecordContent nsec3rr(rr->getContent()->getZoneRepresentation(), di->zone);
×
381
        if (*haveNSEC3 && ns3pr->getZoneRepresentation() == nsec3rr.getZoneRepresentation())
×
382
          d_dk.unsetNSEC3PARAM(rr->d_name);
×
383
        else
×
384
          return 0;
×
385
      } else
×
386
        return 0;
×
387

388
      // Update NSEC3 variables, other RR's in this update package might need them as well.
389
      *haveNSEC3 = false;
×
390
      *narrow = false;
×
391

392
      string error;
×
393
      string info;
×
394
      if (!d_dk.rectifyZone(di->zone, error, info, false)) {
×
395
        throw PDNSException("Failed to rectify '" + di->zone.toLogString() + "': " + error);
×
396
      }
×
397
      return 1;
×
398
    } // end of NSEC3PARAM delete block
×
399

400

401
    di->backend->lookup(rrType, rr->d_name, di->id);
×
402
    while(di->backend->get(rec)) {
×
403
      if (rr->d_class == QClass::ANY) { // 3.4.2.3
×
404
        if (rec.qname == di->zone && (rec.qtype == QType::NS || rec.qtype == QType::SOA)) // Never delete all SOA and NS's
×
405
          rrset.push_back(rec);
×
406
        else
×
407
          recordsToDelete.push_back(rec);
×
408
      }
×
409
      if (rr->d_class == QClass::NONE) { // 3.4.2.4
×
410
        auto repr = rec.getZoneRepresentation();
×
411
        if (rec.qtype == QType::TXT) {
×
412
          DLOG(g_log<<msgPrefix<<"Adjusting TXT content from ["<<repr<<"]"<<endl);
×
413
          auto drc = DNSRecordContent::make(rec.qtype.getCode(), QClass::IN, repr);
×
414
          auto ser = drc->serialize(rec.qname, true, true);
×
415
          auto rc = DNSRecordContent::deserialize(rec.qname, rec.qtype.getCode(), ser);
×
416
          repr = rc->getZoneRepresentation(true);
×
417
          DLOG(g_log<<msgPrefix<<"Adjusted TXT content to ["<<repr<<"]"<<endl);
×
418
        }
×
419
        DLOG(g_log<<msgPrefix<<"Matching RR in RRset - (adjusted) representation from request=["<<repr<<"], rr->getContent()->getZoneRepresentation()=["<<rr->getContent()->getZoneRepresentation()<<"]"<<endl);
×
420
        if (rrType == rec.qtype && repr == rr->getContent()->getZoneRepresentation())
×
421
          recordsToDelete.push_back(rec);
×
422
        else
×
423
          rrset.push_back(rec);
×
424
      }
×
425
    }
×
426
  
427
    if (recordsToDelete.size()) {
×
428
      di->backend->replaceRRSet(di->id, rr->d_name, rrType, rrset);
×
429
      g_log<<Logger::Notice<<msgPrefix<<"Deleting record "<<rr->d_name<<"|"<<rrType.toString()<<endl;
×
430
      changedRecords += recordsToDelete.size();
×
431

432

433
      // If we've removed a delegate, we need to reset ordername/auth for some records.
434
      if (rrType == QType::NS && rr->d_name != di->zone) { 
×
435
        vector<DNSName> belowOldDelegate, nsRecs, updateAuthFlag;
×
436
        di->backend->listSubZone(rr->d_name, di->id);
×
437
        while (di->backend->get(rec)) {
×
438
          if (rec.qtype.getCode()) // skip ENT records, they are always auth=false
×
439
            belowOldDelegate.push_back(rec.qname);
×
440
          if (rec.qtype.getCode() == QType::NS && rec.qname != rr->d_name)
×
441
            nsRecs.push_back(rec.qname);
×
442
        }
×
443

444
        for(auto &belowOldDel: belowOldDelegate)
×
445
        {
×
446
          bool isBelowDelegate = false;
×
447
          for(const auto & ns: nsRecs) {
×
448
            if (ns.isPartOf(belowOldDel)) {
×
449
              isBelowDelegate=true;
×
450
              break;
×
451
            }
×
452
          }
×
453
          if (!isBelowDelegate)
×
454
            updateAuthFlag.push_back(belowOldDel);
×
455
        }
×
456

457
        for (const auto &changeRec:updateAuthFlag) {
×
458
          if(*haveNSEC3)  {
×
459
            DNSName ordername;
×
460
            if(! *narrow)
×
461
              ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, changeRec)));
×
462

463
            di->backend->updateDNSSECOrderNameAndAuth(di->id, changeRec, ordername, true);
×
464
          }
×
465
          else { // NSEC
×
466
            DNSName ordername=changeRec.makeRelative(di->zone);
×
467
            di->backend->updateDNSSECOrderNameAndAuth(di->id, changeRec, ordername, true);
×
468
          }
×
469
        }
×
470
      }
×
471

472
      // Fix ENT records.
473
      // We must check if we have a record below the current level and if we removed the 'last' record
474
      // on that level. If so, we must insert an ENT record.
475
      // 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.
476
      bool foundDeeper = false, foundOtherWithSameName = false;
×
477
      di->backend->listSubZone(rr->d_name, di->id);
×
478
      while (di->backend->get(rec)) {
×
479
        if (rec.qname == rr->d_name && !count(recordsToDelete.begin(), recordsToDelete.end(), rec))
×
480
          foundOtherWithSameName = true;
×
481
        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
×
482
          foundDeeper = true;
×
483
      }
×
484

485
      if (foundDeeper && !foundOtherWithSameName) {
×
486
        insnonterm.insert(rr->d_name);
×
487
      } else if (!foundOtherWithSameName) {
×
488
        // If we didn't have to insert an ENT, we might have deleted a record at very deep level
489
        // and we must then clean up the ENT's above the deleted record.
490
        DNSName shorter(rr->d_name);
×
491
        while (shorter != di->zone) {
×
492
          shorter.chopOff();
×
493
          bool foundRealRR = false;
×
494
          bool foundEnt = false;
×
495

496
          // The reason for a listSubZone here is because might go up the tree and find the ENT of another branch
497
          // consider these non ENT-records:
498
          // b.c.d.e.test.com
499
          // b.d.e.test.com
500
          // 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.
501
          // At that point we can stop deleting ENT's because the tree is in tact again.
502
          di->backend->listSubZone(shorter, di->id);
×
503

504
          while (di->backend->get(rec)) {
×
505
            if (rec.qtype.getCode())
×
506
              foundRealRR = true;
×
507
            else
×
508
              foundEnt = true;
×
509
          }
×
510
          if (!foundRealRR) {
×
511
            if (foundEnt) // only delete the ENT if we actually found one.
×
512
              delnonterm.insert(shorter);
×
513
          } else
×
514
            break;
×
515
        }
×
516
      }
×
517
    } else { // if (recordsToDelete.size())
×
518
      g_log<<Logger::Notice<<msgPrefix<<"Deletion for record "<<rr->d_name<<"|"<<rrType.toString()<<" requested, but not found."<<endl;
×
519
    }
×
520
  } // (End of delete block d_class == ANY || d_class == NONE
×
521
  
522

523

524
  //Insert and delete ENT's
525
  if (insnonterm.size() > 0 || delnonterm.size() > 0) {
×
526
    DLOG(g_log<<msgPrefix<<"Updating ENT records - "<<insnonterm.size()<<"|"<<delnonterm.size()<<endl);
×
527
    di->backend->updateEmptyNonTerminals(di->id, insnonterm, delnonterm, false);
×
528
    for (const auto &i: insnonterm) {
×
529
      string hashed;
×
530
      if(*haveNSEC3)
×
531
      {
×
532
        DNSName ordername;
×
533
        if(! *narrow)
×
534
          ordername=DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, i)));
×
535
        di->backend->updateDNSSECOrderNameAndAuth(di->id, i, ordername, true);
×
536
      }
×
537
    }
×
538
  }
×
539

540
  return changedRecords;
×
541
}
×
542

543
int PacketHandler::forwardPacket(const string &msgPrefix, const DNSPacket& p, const DomainInfo& di) {
×
544
  vector<string> forward;
×
545
  B.getDomainMetadata(p.qdomain, "FORWARD-DNSUPDATE", forward);
×
546

547
  if (forward.size() == 0 && ! ::arg().mustDo("forward-dnsupdate")) {
×
548
    g_log << Logger::Notice << msgPrefix << "Not configured to forward to primary, returning Refused." << endl;
×
549
    return RCode::Refused;
×
550
  }
×
551

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

555
    if (!pdns::isQueryLocalAddressFamilyEnabled(remote.sin4.sin_family)) {
×
556
      continue;
×
557
    }
×
558
    auto local = pdns::getQueryLocalAddress(remote.sin4.sin_family, 0);
×
559
    int sock = makeQuerySocket(local, false); // create TCP socket. RFC2136 section 6.2 seems to be ok with this.
×
560
    if(sock < 0) {
×
561
      g_log<<Logger::Error<<msgPrefix<<"Error creating socket: "<<stringerror()<<endl;
×
562
      continue;
×
563
    }
×
564

565
    if( connect(sock, (struct sockaddr*)&remote, remote.getSocklen()) < 0 ) {
×
566
      g_log<<Logger::Error<<msgPrefix<<"Failed to connect to "<<remote.toStringWithPort()<<": "<<stringerror()<<endl;
×
567
      try {
×
568
        closesocket(sock);
×
569
      }
×
570
      catch(const PDNSException& e) {
×
571
        g_log << Logger::Error << "Error closing primary forwarding socket after connect() failed: " << e.reason << endl;
×
572
      }
×
573
      continue;
×
574
    }
×
575

576
    DNSPacket l_forwardPacket(p);
×
577
    l_forwardPacket.setID(dns_random_uint16());
×
578
    l_forwardPacket.setRemote(&remote);
×
579
    uint16_t len=htons(l_forwardPacket.getString().length());
×
580
    string buffer((const char*)&len, 2);
×
581
    buffer.append(l_forwardPacket.getString());
×
582
    if(write(sock, buffer.c_str(), buffer.length()) < 0) {
×
583
      g_log<<Logger::Error<<msgPrefix<<"Unable to forward update message to "<<remote.toStringWithPort()<<", error:"<<stringerror()<<endl;
×
584
      try {
×
585
        closesocket(sock);
×
586
      }
×
587
      catch(const PDNSException& e) {
×
588
        g_log << Logger::Error << "Error closing primary forwarding socket after write() failed: " << e.reason << endl;
×
589
      }
×
590
      continue;
×
591
    }
×
592

593
    int res = waitForData(sock, 10, 0);
×
594
    if (!res) {
×
595
      g_log << Logger::Error << msgPrefix << "Timeout waiting for reply from primary at " << remote.toStringWithPort() << endl;
×
596
      try {
×
597
        closesocket(sock);
×
598
      }
×
599
      catch(const PDNSException& e) {
×
600
        g_log << Logger::Error << "Error closing primary forwarding socket after a timeout occurred: " << e.reason << endl;
×
601
      }
×
602
      continue;
×
603
    }
×
604
    if (res < 0) {
×
605
      g_log << Logger::Error << msgPrefix << "Error waiting for answer from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
606
      try {
×
607
        closesocket(sock);
×
608
      }
×
609
      catch(const PDNSException& e) {
×
610
        g_log << Logger::Error << "Error closing primary forwarding socket after an error occurred: " << e.reason << endl;
×
611
      }
×
612
      continue;
×
613
    }
×
614

615
    unsigned char lenBuf[2];
×
616
    ssize_t recvRes;
×
617
    recvRes = recv(sock, &lenBuf, sizeof(lenBuf), 0);
×
618
    if (recvRes < 0 || static_cast<size_t>(recvRes) < sizeof(lenBuf)) {
×
619
      g_log << Logger::Error << msgPrefix << "Could not receive data (length) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
620
      try {
×
621
        closesocket(sock);
×
622
      }
×
623
      catch(const PDNSException& e) {
×
624
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
×
625
      }
×
626
      continue;
×
627
    }
×
628
    size_t packetLen = lenBuf[0]*256+lenBuf[1];
×
629

630
    buffer.resize(packetLen);
×
631
    recvRes = recv(sock, &buffer.at(0), packetLen, 0);
×
632
    if (recvRes < 0) {
×
633
      g_log << Logger::Error << msgPrefix << "Could not receive data (dnspacket) from primary at " << remote.toStringWithPort() << ", error:" << stringerror() << endl;
×
634
      try {
×
635
        closesocket(sock);
×
636
      }
×
637
      catch(const PDNSException& e) {
×
638
        g_log << Logger::Error << "Error closing primary forwarding socket after recv() failed: " << e.reason << endl;
×
639
      }
×
640
      continue;
×
641
    }
×
642
    try {
×
643
      closesocket(sock);
×
644
    }
×
645
    catch(const PDNSException& e) {
×
646
      g_log << Logger::Error << "Error closing primary forwarding socket: " << e.reason << endl;
×
647
    }
×
648

649
    try {
×
650
      MOADNSParser mdp(false, buffer.data(), static_cast<unsigned int>(recvRes));
×
651
      g_log<<Logger::Info<<msgPrefix<<"Forward update message to "<<remote.toStringWithPort()<<", result was RCode "<<mdp.d_header.rcode<<endl;
×
652
      return mdp.d_header.rcode;
×
653
    }
×
654
    catch (...) {
×
655
      g_log << Logger::Error << msgPrefix << "Failed to parse response packet from primary at " << remote.toStringWithPort() << endl;
×
656
      continue;
×
657
    }
×
658
  }
×
659
  g_log << Logger::Error << msgPrefix << "Failed to forward packet to primary(s). Returning ServFail." << endl;
×
660
  return RCode::ServFail;
×
661

662
}
×
663

664
int PacketHandler::processUpdate(DNSPacket& packet) { // NOLINT(readability-function-cognitive-complexity)
×
665
  if (! ::arg().mustDo("dnsupdate"))
×
666
    return RCode::Refused;
×
667

668
  string msgPrefix="UPDATE (" + std::to_string(packet.d.id) + ") from " + packet.getRemoteString() + " for " + packet.qdomain.toLogString() + ": ";
×
669
  g_log<<Logger::Info<<msgPrefix<<"Processing started."<<endl;
×
670

671
  // if there is policy, we delegate all checks to it
672
  if (this->d_update_policy_lua == nullptr) {
×
673

674
    // Check permissions - IP based
675
    vector<string> allowedRanges;
×
676
    B.getDomainMetadata(packet.qdomain, "ALLOW-DNSUPDATE-FROM", allowedRanges);
×
677
    if (! ::arg()["allow-dnsupdate-from"].empty())
×
678
      stringtok(allowedRanges, ::arg()["allow-dnsupdate-from"], ", \t" );
×
679

680
    NetmaskGroup ng;
×
681
    for(const auto& i: allowedRanges) {
×
682
      ng.addMask(i);
×
683
    }
×
684

685
    if ( ! ng.match(packet.getInnerRemote())) {
×
686
      g_log<<Logger::Error<<msgPrefix<<"Remote not listed in allow-dnsupdate-from or domainmetadata. Sending REFUSED"<<endl;
×
687
      return RCode::Refused;
×
688
    }
×
689

690

691
    // Check permissions - TSIG based.
692
    vector<string> tsigKeys;
×
693
    B.getDomainMetadata(packet.qdomain, "TSIG-ALLOW-DNSUPDATE", tsigKeys);
×
694
    if (tsigKeys.size() > 0) {
×
695
      bool validKey = false;
×
696

697
      TSIGRecordContent trc;
×
698
      DNSName inputkey;
×
699
      string message;
×
700
      if (! packet.getTSIGDetails(&trc,  &inputkey)) {
×
701
        g_log<<Logger::Error<<msgPrefix<<"TSIG key required, but packet does not contain key. Sending REFUSED"<<endl;
×
702
        return RCode::Refused;
×
703
      }
×
704
#ifdef ENABLE_GSS_TSIG
×
705
      if (g_doGssTSIG && packet.d_tsig_algo == TSIG_GSS) {
×
706
        GssName inputname(packet.d_peer_principal); // match against principal since GSS requires that
×
707
        for(const auto& key: tsigKeys) {
×
708
          if (inputname.match(key)) {
×
709
            validKey = true;
×
710
            break;
×
711
          }
×
712
        }
×
713
      }
×
714
      else
×
715
#endif
×
716
        {
×
717
        for(const auto& key: tsigKeys) {
×
718
          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.
×
719
            validKey=true;
×
720
            break;
×
721
          }
×
722
        }
×
723
      }
×
724

725
      if (!validKey) {
×
726
        g_log<<Logger::Error<<msgPrefix<<"TSIG key ("<<inputkey<<") required, but no matching key found in domainmetadata, tried "<<tsigKeys.size()<<". Sending REFUSED"<<endl;
×
727
        return RCode::Refused;
×
728
      }
×
729
    } else if(::arg().mustDo("dnsupdate-require-tsig")) {
×
730
      g_log<<Logger::Error<<msgPrefix<<"TSIG key required, but domain is not secured with TSIG. Sending REFUSED"<<endl;
×
731
      return RCode::Refused;
×
732
    }
×
733

734
    if (tsigKeys.empty() && packet.d_havetsig) {
×
735
      g_log<<Logger::Warning<<msgPrefix<<"TSIG is provided, but domain is not secured with TSIG. Processing continues"<<endl;
×
736
    }
×
737

738
  }
×
739

740
  // RFC2136 uses the same DNS Header and Message as defined in RFC1035.
741
  // This means we can use the MOADNSParser to parse the incoming packet. The result is that we have some different
742
  // variable names during the use of our MOADNSParser.
743
  MOADNSParser mdp(false, packet.getString());
×
744
  if (mdp.d_header.qdcount != 1) {
×
745
    g_log<<Logger::Warning<<msgPrefix<<"Zone Count is not 1, sending FormErr"<<endl;
×
746
    return RCode::FormErr;
×
747
  }
×
748

749
  if (packet.qtype.getCode() != QType::SOA) { // RFC2136 2.3 - ZTYPE must be SOA
×
750
    g_log<<Logger::Warning<<msgPrefix<<"Query ZTYPE is not SOA, sending FormErr"<<endl;
×
751
    return RCode::FormErr;
×
752
  }
×
753

754
  if (packet.qclass != QClass::IN) {
×
755
    g_log<<Logger::Warning<<msgPrefix<<"Class is not IN, sending NotAuth"<<endl;
×
756
    return RCode::NotAuth;
×
757
  }
×
758

759
  DomainInfo di;
×
760
  di.backend=nullptr;
×
761
  if(!B.getDomainInfo(packet.qdomain, di) || (di.backend == nullptr)) {
×
762
    g_log<<Logger::Error<<msgPrefix<<"Can't determine backend for domain '"<<packet.qdomain<<"' (or backend does not support DNS update operation)"<<endl;
×
763
    return RCode::NotAuth;
×
764
  }
×
765

766
  if (di.kind == DomainInfo::Secondary)
×
767
    return forwardPacket(msgPrefix, packet, di);
×
768

769
  // Check if all the records provided are within the zone
770
  for(const auto & answer : mdp.d_answers) {
×
771
    const DNSRecord *dnsRecord = &answer;
×
772
    // Skip this check for other field types (like the TSIG -  which is in the additional section)
773
    // For a TSIG, the label is the dnskey, so it does not pass the endOn validation.
774
    if (dnsRecord->d_place != DNSResourceRecord::ANSWER && dnsRecord->d_place != DNSResourceRecord::AUTHORITY) {
×
775
      continue;
×
776
    }
×
777

778
    if (!dnsRecord->d_name.isPartOf(di.zone)) {
×
779
      g_log<<Logger::Error<<msgPrefix<<"Received update/record out of zone, sending NotZone."<<endl;
×
780
      return RCode::NotZone;
×
781
    }
×
782
  }
×
783

784

785
  std::lock_guard<std::mutex> l(s_rfc2136lock); //TODO: i think this lock can be per zone, not for everything
×
786
  g_log<<Logger::Info<<msgPrefix<<"starting transaction."<<endl;
×
787
  if (!di.backend->startTransaction(packet.qdomain, -1)) { // Not giving the domain_id means that we do not delete the existing records.
×
788
    g_log<<Logger::Error<<msgPrefix<<"Backend for domain "<<packet.qdomain<<" does not support transaction. Can't do Update packet."<<endl;
×
789
    return RCode::NotImp;
×
790
  }
×
791

792
  // 3.2.1 and 3.2.2 - Prerequisite check
793
  for(const auto & answer : mdp.d_answers) {
×
794
    const DNSRecord *dnsRecord = &answer;
×
795
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
×
796
      int res = checkUpdatePrerequisites(dnsRecord, &di);
×
797
      if (res>0) {
×
798
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check for "<<dnsRecord->d_name<<", returning "<<RCode::to_s(res)<<endl;
×
799
        di.backend->abortTransaction();
×
800
        return res;
×
801
      }
×
802
    }
×
803
  }
×
804

805
  // 3.2.3 - Prerequisite check - this is outside of updatePrerequisitesCheck because we check an RRSet and not the RR.
806
  typedef pair<DNSName, QType> rrSetKey_t;
×
807
  typedef vector<DNSResourceRecord> rrVector_t;
×
808
  typedef std::map<rrSetKey_t, rrVector_t> RRsetMap_t;
×
809
  RRsetMap_t preReqRRsets;
×
810
  for(const auto& i: mdp.d_answers) {
×
811
    const DNSRecord* dnsRecord = &i;
×
812
    if (dnsRecord->d_place == DNSResourceRecord::ANSWER) {
×
813
      // Last line of 3.2.3
814
      if (dnsRecord->d_class != QClass::IN && dnsRecord->d_class != QClass::NONE && dnsRecord->d_class != QClass::ANY) {
×
815
        return RCode::FormErr;
×
816
      }
×
817

818
      if (dnsRecord->d_class == QClass::IN) {
×
819
        rrSetKey_t key = {dnsRecord->d_name, QType(dnsRecord->d_type)};
×
820
        rrVector_t *vec = &preReqRRsets[key];
×
821
        vec->push_back(DNSResourceRecord::fromWire(*dnsRecord));
×
822
      }
×
823
    }
×
824
  }
×
825

826
  if (preReqRRsets.size() > 0) {
×
827
    RRsetMap_t zoneRRsets;
×
828
    for (auto & preReqRRset : preReqRRsets) {
×
829
      rrSetKey_t rrSet=preReqRRset.first;
×
830
      rrVector_t *vec = &preReqRRset.second;
×
831

832
      DNSResourceRecord rec;
×
833
      di.backend->lookup(QType(QType::ANY), rrSet.first, di.id);
×
834
      uint16_t foundRR=0, matchRR=0;
×
835
      while (di.backend->get(rec)) {
×
836
        if (rec.qtype == rrSet.second) {
×
837
          foundRR++;
×
838
          for(auto & rrItem : *vec) {
×
839
            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.
×
840
            if (rrItem == rec)
×
841
              matchRR++;
×
842
          }
×
843
        }
×
844
      }
×
845
      if (matchRR != foundRR || foundRR != vec->size()) {
×
846
        g_log<<Logger::Error<<msgPrefix<<"Failed PreRequisites check (RRs differ), returning NXRRSet"<<endl;
×
847
        di.backend->abortTransaction();
×
848
        return RCode::NXRRSet;
×
849
      }
×
850
    }
×
851
  }
×
852

853

854

855
  // 3.4 - Prescan & Add/Update/Delete records - is all done within a try block.
856
  try {
×
857
    uint changedRecords = 0;
×
858
    // 3.4.1 - Prescan section
859
    for(const auto & answer : mdp.d_answers) {
×
860
      const DNSRecord *dnsRecord = &answer;
×
861
      if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
×
862
        int res = checkUpdatePrescan(dnsRecord);
×
863
        if (res>0) {
×
864
          g_log<<Logger::Error<<msgPrefix<<"Failed prescan check, returning "<<res<<endl;
×
865
          di.backend->abortTransaction();
×
866
          return res;
×
867
        }
×
868
      }
×
869
    }
×
870

871
    bool updatedSerial=false;
×
872
    NSEC3PARAMRecordContent ns3pr;
×
873
    bool narrow=false;
×
874
    bool haveNSEC3 = d_dk.getNSEC3PARAM(di.zone, &ns3pr, &narrow);
×
875
    bool isPresigned = d_dk.isPresigned(di.zone);
×
876
    string soaEditSetting;
×
877
    d_dk.getSoaEdit(di.zone, soaEditSetting);
×
878

879
    // 3.4.2 - Perform the updates.
880
    // There's a special condition where deleting the last NS record at zone apex is never deleted (3.4.2.4)
881
    // This means we must do it outside the normal performUpdate() because that focusses only on a separate RR.
882
    vector<const DNSRecord *> nsRRtoDelete;
×
883

884
    // Another special case is the addition of both a CNAME and a non-CNAME for the same name (#6270)
885
    set<DNSName> cn, nocn;
×
886
    for (const auto &rr : mdp.d_answers) {
×
887
      if (rr.d_place == DNSResourceRecord::AUTHORITY && rr.d_class == QClass::IN && rr.d_ttl > 0) {
×
888
        // Addition
889
        if (rr.d_type == QType::CNAME) {
×
890
          cn.insert(rr.d_name);
×
891
        } else if (rr.d_type != QType::RRSIG) {
×
892
          nocn.insert(rr.d_name);
×
893
        }
×
894
      }
×
895
    }
×
896
    for (auto const &n : cn) {
×
897
      if (nocn.count(n) > 0) {
×
898
        g_log<<Logger::Error<<msgPrefix<<"Refusing update, found CNAME and non-CNAME addition"<<endl;
×
899
        di.backend->abortTransaction();
×
900
        return RCode::FormErr;
×
901
      }
×
902
    }
×
903

904
    vector<const DNSRecord *> cnamesToAdd, nonCnamesToAdd;
×
905
    for(const auto & answer : mdp.d_answers) {
×
906
      const DNSRecord *dnsRecord = &answer;
×
907
      if (dnsRecord->d_place == DNSResourceRecord::AUTHORITY) {
×
908
        /* see if it's permitted by policy */
909
        if (this->d_update_policy_lua != nullptr) {
×
910
          if (!this->d_update_policy_lua->updatePolicy(dnsRecord->d_name, QType(dnsRecord->d_type), di.zone, packet)) {
×
911
            g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Not permitted by policy"<<endl;
×
912
            continue;
×
913
          } else {
×
914
            g_log<<Logger::Debug<<msgPrefix<<"Accepting update for " << dnsRecord->d_name << "/" << QType(dnsRecord->d_type).toString() << ": Permitted by policy"<<endl;
×
915
          }
×
916
        }
×
917

918
        if (dnsRecord->d_class == QClass::NONE  && dnsRecord->d_type == QType::NS && dnsRecord->d_name == di.zone) {
×
919
          nsRRtoDelete.push_back(dnsRecord);
×
920
        }
×
921
        else if (dnsRecord->d_class == QClass::IN &&  dnsRecord->d_ttl > 0) {
×
922
          if (dnsRecord->d_type == QType::CNAME) {
×
923
            cnamesToAdd.push_back(dnsRecord);
×
924
          } else {
×
925
            nonCnamesToAdd.push_back(dnsRecord);
×
926
          }
×
927
        }
×
928
        else
×
929
          changedRecords += performUpdate(msgPrefix, dnsRecord, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
×
930
      }
×
931
    }
×
932
    for (const auto &rr : cnamesToAdd) {
×
933
      DNSResourceRecord rec;
×
934
      di.backend->lookup(QType(QType::ANY), rr->d_name, di.id);
×
935
      while (di.backend->get(rec)) {
×
936
        if (rec.qtype != QType::CNAME && rec.qtype != QType::ENT && rec.qtype != QType::RRSIG) {
×
937
          // leave database handle in a consistent state
938
          while (di.backend->get(rec))
×
939
            ;
×
940
          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;
×
941
          di.backend->abortTransaction();
×
942
          return RCode::Refused;
×
943
        }
×
944
      }
×
945
      changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
×
946
    }
×
947
    for (const auto &rr : nonCnamesToAdd) {
×
948
      DNSResourceRecord rec;
×
949
      di.backend->lookup(QType(QType::CNAME), rr->d_name, di.id);
×
950
      while (di.backend->get(rec)) {
×
951
        if (rec.qtype == QType::CNAME && rr->d_type != QType::RRSIG) {
×
952
          // leave database handle in a consistent state
953
          while (di.backend->get(rec))
×
954
            ;
×
955
          g_log<<Logger::Warning<<msgPrefix<<"Refusing update for " << rr->d_name << "/" << QType(rr->d_type).toString() << ": CNAME exists for the same name"<<endl;
×
956
          di.backend->abortTransaction();
×
957
          return RCode::Refused;
×
958
        }
×
959
      }
×
960
      changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
×
961
    }
×
962
    if (nsRRtoDelete.size()) {
×
963
      vector<DNSResourceRecord> nsRRInZone;
×
964
      DNSResourceRecord rec;
×
965
      di.backend->lookup(QType(QType::NS), di.zone, di.id);
×
966
      while (di.backend->get(rec)) {
×
967
        nsRRInZone.push_back(rec);
×
968
      }
×
969
      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)
×
970
        for (auto& inZone: nsRRInZone) {
×
971
          for (auto& rr: nsRRtoDelete) {
×
972
            if (inZone.getZoneRepresentation() == (rr)->getContent()->getZoneRepresentation())
×
973
              changedRecords += performUpdate(msgPrefix, rr, &di, isPresigned, &narrow, &haveNSEC3, &ns3pr, &updatedSerial);
×
974
          }
×
975
        }
×
976
      }
×
977
    }
×
978

979
    // Section 3.6 - Update the SOA serial - outside of performUpdate because we do a SOA update for the complete update message
980
    if (changedRecords > 0 && !updatedSerial) {
×
981
      increaseSerial(msgPrefix, &di, soaEditSetting, haveNSEC3, narrow, &ns3pr);
×
982
      changedRecords++;
×
983
    }
×
984

985
    if (changedRecords > 0) {
×
986
      if (!di.backend->commitTransaction()) {
×
987
       g_log<<Logger::Error<<msgPrefix<<"Failed to commit updates!"<<endl;
×
988
        return RCode::ServFail;
×
989
      }
×
990

991
      S.deposit("dnsupdate-changes", changedRecords);
×
992

993
      d_dk.clearMetaCache(di.zone);
×
994
      // Purge the records!
995
      string zone(di.zone.toString());
×
996
      zone.append("$");
×
997
      purgeAuthCaches(zone);
×
998

999
      // Notify secondaries
1000
      if (di.kind == DomainInfo::Primary) {
×
1001
        vector<string> notify;
×
1002
        B.getDomainMetadata(packet.qdomain, "NOTIFY-DNSUPDATE", notify);
×
1003
        if (!notify.empty() && notify.front() == "1") {
×
1004
          Communicator.notifyDomain(di.zone, &B);
×
1005
        }
×
1006
      }
×
1007

1008
      g_log<<Logger::Info<<msgPrefix<<"Update completed, "<<changedRecords<<" changed records committed."<<endl;
×
1009
    } else {
×
1010
      //No change, no commit, we perform abort() because some backends might like this more.
1011
      g_log<<Logger::Info<<msgPrefix<<"Update completed, 0 changes, rolling back."<<endl;
×
1012
      di.backend->abortTransaction();
×
1013
    }
×
1014
    return RCode::NoError; //rfc 2136 3.4.2.5
×
1015
  }
×
1016
  catch (SSqlException &e) {
×
1017
    g_log<<Logger::Error<<msgPrefix<<"Caught SSqlException: "<<e.txtReason()<<"; Sending ServFail!"<<endl;
×
1018
    di.backend->abortTransaction();
×
1019
    return RCode::ServFail;
×
1020
  }
×
1021
  catch (DBException &e) {
×
1022
    g_log<<Logger::Error<<msgPrefix<<"Caught DBException: "<<e.reason<<"; Sending ServFail!"<<endl;
×
1023
    di.backend->abortTransaction();
×
1024
    return RCode::ServFail;
×
1025
  }
×
1026
  catch (PDNSException &e) {
×
1027
    g_log<<Logger::Error<<msgPrefix<<"Caught PDNSException: "<<e.reason<<"; Sending ServFail!"<<endl;
×
1028
    di.backend->abortTransaction();
×
1029
    return RCode::ServFail;
×
1030
  }
×
1031
  catch(std::exception &e) {
×
1032
    g_log<<Logger::Error<<msgPrefix<<"Caught std:exception: "<<e.what()<<"; Sending ServFail!"<<endl;
×
1033
    di.backend->abortTransaction();
×
1034
    return RCode::ServFail;
×
1035
  }
×
1036
  catch (...) {
×
1037
    g_log<<Logger::Error<<msgPrefix<<"Caught unknown exception when performing update. Sending ServFail!"<<endl;
×
1038
    di.backend->abortTransaction();
×
1039
    return RCode::ServFail;
×
1040
  }
×
1041
}
×
1042

1043
void PacketHandler::increaseSerial(const string &msgPrefix, const DomainInfo *di, const string& soaEditSetting,  bool haveNSEC3, bool narrow, const NSEC3PARAMRecordContent *ns3pr) {
×
1044
  SOAData sd;
×
1045
  if (!di->backend->getSOA(di->zone, sd)) {
×
1046
    throw PDNSException("SOA-Serial update failed because there was no SOA. Wowie.");
×
1047
  }
×
1048

1049
  uint32_t oldSerial = sd.serial;
×
1050

1051
  vector<string> soaEdit2136Setting;
×
1052
  B.getDomainMetadata(di->zone, "SOA-EDIT-DNSUPDATE", soaEdit2136Setting);
×
1053
  string soaEdit2136 = "DEFAULT";
×
1054
  string soaEdit;
×
1055
  if (!soaEdit2136Setting.empty()) {
×
1056
    soaEdit2136 = soaEdit2136Setting[0];
×
1057
    if (pdns_iequals(soaEdit2136, "SOA-EDIT") || pdns_iequals(soaEdit2136,"SOA-EDIT-INCREASE") ){
×
1058
      if (soaEditSetting.empty()) {
×
1059
        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;
×
1060
        soaEdit2136 = "DEFAULT";
×
1061
      } else
×
1062
        soaEdit = soaEditSetting;
×
1063
    }
×
1064
  }
×
1065

1066
  DNSResourceRecord rr;
×
1067
  if (makeIncreasedSOARecord(sd, soaEdit2136, soaEdit, rr)) {
×
1068
    di->backend->replaceRRSet(di->id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr));
×
1069
    g_log << Logger::Notice << msgPrefix << "Increasing SOA serial (" << oldSerial << " -> " << sd.serial << ")" << endl;
×
1070

1071
    //Correct ordername + auth flag
1072
    if (haveNSEC3) {
×
1073
      DNSName ordername;
×
1074
      if (!narrow)
×
1075
        ordername = DNSName(toBase32Hex(hashQNameWithSalt(*ns3pr, rr.qname)));
×
1076

1077
      di->backend->updateDNSSECOrderNameAndAuth(di->id, rr.qname, ordername, true);
×
1078
    } else { // NSEC
×
1079
      DNSName ordername = rr.qname.makeRelative(di->zone);
×
1080
      di->backend->updateDNSSECOrderNameAndAuth(di->id, rr.qname, ordername, true);
×
1081
    }
×
1082
  }
×
1083
}
×
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