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

PowerDNS / pdns / 14221392056

02 Apr 2025 01:53PM UTC coverage: 62.559% (-0.9%) from 63.455%
14221392056

push

github

web-flow
Merge pull request #15385 from rgacogne/ddist-enable-quiche-sni-tests

dnsdist: Enable the DoQ and DoH3 parts of the SNI tests in our CI

40728 of 99708 branches covered (40.85%)

Branch coverage included in aggregate %.

125683 of 166300 relevant lines covered (75.58%)

3310189.27 hits per line

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

40.75
/modules/bindbackend/bindbackend2.cc
1
/*
2
 * This file is part of PowerDNS or dnsdist.
3
 * Copyright -- PowerDNS.COM B.V. and its contributors
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of version 2 of the GNU General Public License as
7
 * published by the Free Software Foundation.
8
 *
9
 * In addition, for the avoidance of any doubt, permission is granted to
10
 * link this program with OpenSSL and to (re)distribute the binaries
11
 * produced as the result of such linking.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
 */
22

23
#ifdef HAVE_CONFIG_H
24
#include "config.h"
25
#endif
26
#include <cerrno>
27
#include <string>
28
#include <set>
29
#include <sys/types.h>
30
#include <sys/stat.h>
31
#include <unistd.h>
32
#include <fstream>
33
#include <fcntl.h>
34
#include <sstream>
35
#include <boost/algorithm/string.hpp>
36
#include <system_error>
37
#include <unordered_map>
38
#include <unordered_set>
39

40
#include "pdns/dnsseckeeper.hh"
41
#include "pdns/dnssecinfra.hh"
42
#include "pdns/base32.hh"
43
#include "pdns/namespaces.hh"
44
#include "pdns/dns.hh"
45
#include "pdns/dnsbackend.hh"
46
#include "bindbackend2.hh"
47
#include "pdns/dnspacket.hh"
48
#include "pdns/zoneparser-tng.hh"
49
#include "pdns/bindparserclasses.hh"
50
#include "pdns/logger.hh"
51
#include "pdns/arguments.hh"
52
#include "pdns/qtype.hh"
53
#include "pdns/misc.hh"
54
#include "pdns/dynlistener.hh"
55
#include "pdns/lock.hh"
56
#include "pdns/auth-zonecache.hh"
57
#include "pdns/auth-caches.hh"
58

59
/*
60
   All instances of this backend share one s_state, which is indexed by zone name and zone id.
61
   The s_state is protected by a read/write lock, and the goal it to only interact with it briefly.
62
   When a query comes in, we take a read lock and COPY the best zone to answer from s_state (BB2DomainInfo object)
63
   All answers are served from this copy.
64

65
   To interact with s_state, use safeGetBBDomainInfo (search on name or id), safePutBBDomainInfo (to update)
66
   or safeRemoveBBDomainInfo. These all lock as they should.
67

68
   Several functions need to traverse s_state to get data for the rest of PowerDNS. When doing so,
69
   you need to manually take the lock (read).
70

71
   Parsing zones happens with parseZone(), which fills a BB2DomainInfo object. This can then be stored with safePutBBDomainInfo.
72

73
   Finally, the BB2DomainInfo contains all records as a LookButDontTouch object. This makes sure you only look, but don't touch, since
74
   the records might be in use in other places.
75
*/
76

77
SharedLockGuarded<Bind2Backend::state_t> Bind2Backend::s_state;
78
int Bind2Backend::s_first = 1;
79
bool Bind2Backend::s_ignore_broken_records = false;
80

81
std::mutex Bind2Backend::s_autosecondary_config_lock; // protects writes to config file
82
std::mutex Bind2Backend::s_startup_lock;
83
string Bind2Backend::s_binddirectory;
84

85
BB2DomainInfo::BB2DomainInfo()
86
{
629✔
87
  d_loaded = false;
629✔
88
  d_lastcheck = 0;
629✔
89
  d_checknow = false;
629✔
90
  d_status = "Unknown";
629✔
91
}
629✔
92

93
void BB2DomainInfo::setCheckInterval(time_t seconds)
94
{
7✔
95
  d_checkinterval = seconds;
7✔
96
}
7✔
97

98
bool BB2DomainInfo::current()
99
{
33✔
100
  if (d_checknow) {
33!
101
    return false;
×
102
  }
×
103

104
  if (!d_checkinterval)
33!
105
    return true;
33✔
106

107
  if (time(nullptr) - d_lastcheck < d_checkinterval)
×
108
    return true;
×
109

110
  if (d_filename.empty())
×
111
    return true;
×
112

113
  return (getCtime() == d_ctime);
×
114
}
×
115

116
time_t BB2DomainInfo::getCtime()
117
{
×
118
  struct stat buf;
×
119

120
  if (d_filename.empty() || stat(d_filename.c_str(), &buf) < 0)
×
121
    return 0;
×
122
  d_lastcheck = time(nullptr);
×
123
  return buf.st_ctime;
×
124
}
×
125

126
void BB2DomainInfo::setCtime()
127
{
7✔
128
  struct stat buf;
7✔
129
  if (stat(d_filename.c_str(), &buf) < 0)
7!
130
    return;
×
131
  d_ctime = buf.st_ctime;
7✔
132
}
7✔
133

134
bool Bind2Backend::safeGetBBDomainInfo(int id, BB2DomainInfo* bbd)
135
{
28✔
136
  auto state = s_state.read_lock();
28✔
137
  state_t::const_iterator iter = state->find(id);
28✔
138
  if (iter == state->end()) {
28!
139
    return false;
×
140
  }
×
141
  *bbd = *iter;
28✔
142
  return true;
28✔
143
}
28✔
144

145
bool Bind2Backend::safeGetBBDomainInfo(const DNSName& name, BB2DomainInfo* bbd)
146
{
604✔
147
  auto state = s_state.read_lock();
604✔
148
  const auto& nameindex = boost::multi_index::get<NameTag>(*state);
604✔
149
  auto iter = nameindex.find(name);
604✔
150
  if (iter == nameindex.end()) {
604✔
151
    return false;
589✔
152
  }
589✔
153
  *bbd = *iter;
15✔
154
  return true;
15✔
155
}
604✔
156

157
bool Bind2Backend::safeRemoveBBDomainInfo(const DNSName& name)
158
{
×
159
  auto state = s_state.write_lock();
×
160
  using nameindex_t = state_t::index<NameTag>::type;
×
161
  nameindex_t& nameindex = boost::multi_index::get<NameTag>(*state);
×
162

163
  nameindex_t::iterator iter = nameindex.find(name);
×
164
  if (iter == nameindex.end()) {
×
165
    return false;
×
166
  }
×
167
  nameindex.erase(iter);
×
168
  return true;
×
169
}
×
170

171
void Bind2Backend::safePutBBDomainInfo(const BB2DomainInfo& bbd)
172
{
7✔
173
  auto state = s_state.write_lock();
7✔
174
  replacing_insert(*state, bbd);
7✔
175
}
7✔
176

177
void Bind2Backend::setNotified(uint32_t id, uint32_t serial)
178
{
×
179
  BB2DomainInfo bbd;
×
180
  if (!safeGetBBDomainInfo(id, &bbd))
×
181
    return;
×
182
  bbd.d_lastnotified = serial;
×
183
  safePutBBDomainInfo(bbd);
×
184
}
×
185

186
void Bind2Backend::setLastCheck(uint32_t domain_id, time_t lastcheck)
187
{
×
188
  BB2DomainInfo bbd;
×
189
  if (safeGetBBDomainInfo(domain_id, &bbd)) {
×
190
    bbd.d_lastcheck = lastcheck;
×
191
    safePutBBDomainInfo(bbd);
×
192
  }
×
193
}
×
194

195
void Bind2Backend::setStale(uint32_t domain_id)
196
{
×
197
  setLastCheck(domain_id, 0);
×
198
}
×
199

200
void Bind2Backend::setFresh(uint32_t domain_id)
201
{
×
202
  setLastCheck(domain_id, time(nullptr));
×
203
}
×
204

205
bool Bind2Backend::startTransaction(const DNSName& qname, int id)
206
{
×
207
  if (id < 0) {
×
208
    d_transaction_tmpname.clear();
×
209
    d_transaction_id = id;
×
210
    return false;
×
211
  }
×
212
  if (id == 0) {
×
213
    throw DBException("domain_id 0 is invalid for this backend.");
×
214
  }
×
215

216
  d_transaction_id = id;
×
217
  d_transaction_qname = qname;
×
218
  BB2DomainInfo bbd;
×
219
  if (safeGetBBDomainInfo(id, &bbd)) {
×
220
    d_transaction_tmpname = bbd.d_filename + "XXXXXX";
×
221
    int fd = mkstemp(&d_transaction_tmpname.at(0));
×
222
    if (fd == -1) {
×
223
      throw DBException("Unable to create a unique temporary zonefile '" + d_transaction_tmpname + "': " + stringerror());
×
224
    }
×
225

226
    d_of = std::make_unique<ofstream>(d_transaction_tmpname);
×
227
    if (!*d_of) {
×
228
      unlink(d_transaction_tmpname.c_str());
×
229
      close(fd);
×
230
      fd = -1;
×
231
      d_of.reset();
×
232
      throw DBException("Unable to open temporary zonefile '" + d_transaction_tmpname + "': " + stringerror());
×
233
    }
×
234
    close(fd);
×
235
    fd = -1;
×
236

237
    *d_of << "; Written by PowerDNS, don't edit!" << endl;
×
238
    *d_of << "; Zone '" << bbd.d_name << "' retrieved from primary " << endl
×
239
          << "; at " << nowTime() << endl; // insert primary info here again
×
240

241
    return true;
×
242
  }
×
243
  return false;
×
244
}
×
245

246
bool Bind2Backend::commitTransaction()
247
{
×
248
  if (d_transaction_id < 0)
×
249
    return false;
×
250
  d_of.reset();
×
251

252
  BB2DomainInfo bbd;
×
253
  if (safeGetBBDomainInfo(d_transaction_id, &bbd)) {
×
254
    if (rename(d_transaction_tmpname.c_str(), bbd.d_filename.c_str()) < 0)
×
255
      throw DBException("Unable to commit (rename to: '" + bbd.d_filename + "') AXFRed zone: " + stringerror());
×
256
    queueReloadAndStore(bbd.d_id);
×
257
  }
×
258

259
  d_transaction_id = 0;
×
260

261
  return true;
×
262
}
×
263

264
bool Bind2Backend::abortTransaction()
265
{
×
266
  // -1 = dnssec speciality
267
  // 0  = invalid transact
268
  // >0 = actual transaction
269
  if (d_transaction_id > 0) {
×
270
    unlink(d_transaction_tmpname.c_str());
×
271
    d_of.reset();
×
272
    d_transaction_id = 0;
×
273
  }
×
274

275
  return true;
×
276
}
×
277

278
bool Bind2Backend::feedRecord(const DNSResourceRecord& rr, const DNSName& /* ordername */, bool /* ordernameIsNSEC3 */)
279
{
×
280
  if (d_transaction_id < 1) {
×
281
    throw DBException("Bind2Backend::feedRecord() called outside of transaction");
×
282
  }
×
283

284
  string qname;
×
285
  if (d_transaction_qname.empty()) {
×
286
    qname = rr.qname.toString();
×
287
  }
×
288
  else if (rr.qname.isPartOf(d_transaction_qname)) {
×
289
    if (rr.qname == d_transaction_qname) {
×
290
      qname = "@";
×
291
    }
×
292
    else {
×
293
      DNSName relName = rr.qname.makeRelative(d_transaction_qname);
×
294
      qname = relName.toStringNoDot();
×
295
    }
×
296
  }
×
297
  else {
×
298
    throw DBException("out-of-zone data '" + rr.qname.toLogString() + "' during AXFR of zone '" + d_transaction_qname.toLogString() + "'");
×
299
  }
×
300

301
  shared_ptr<DNSRecordContent> drc(DNSRecordContent::make(rr.qtype.getCode(), QClass::IN, rr.content));
×
302
  string content = drc->getZoneRepresentation();
×
303

304
  // SOA needs stripping too! XXX FIXME - also, this should not be here I think
305
  switch (rr.qtype.getCode()) {
×
306
  case QType::MX:
×
307
  case QType::SRV:
×
308
  case QType::CNAME:
×
309
  case QType::DNAME:
×
310
  case QType::NS:
×
311
    stripDomainSuffix(&content, d_transaction_qname.toString());
×
312
    // fallthrough
313
  default:
×
314
    if (d_of && *d_of) {
×
315
      *d_of << qname << "\t" << rr.ttl << "\t" << rr.qtype.toString() << "\t" << content << endl;
×
316
    }
×
317
  }
×
318
  return true;
×
319
}
×
320

321
void Bind2Backend::getUpdatedPrimaries(vector<DomainInfo>& changedDomains, std::unordered_set<DNSName>& /* catalogs */, CatalogHashMap& /* catalogHashes */)
322
{
×
323
  vector<DomainInfo> consider;
×
324
  {
×
325
    auto state = s_state.read_lock();
×
326

327
    for (const auto& i : *state) {
×
328
      if (i.d_kind != DomainInfo::Primary && this->alsoNotify.empty() && i.d_also_notify.empty())
×
329
        continue;
×
330

331
      DomainInfo di;
×
332
      di.id = i.d_id;
×
333
      di.zone = i.d_name;
×
334
      di.last_check = i.d_lastcheck;
×
335
      di.notified_serial = i.d_lastnotified;
×
336
      di.backend = this;
×
337
      di.kind = DomainInfo::Primary;
×
338
      consider.push_back(std::move(di));
×
339
    }
×
340
  }
×
341

342
  SOAData soadata;
×
343
  for (DomainInfo& di : consider) {
×
344
    soadata.serial = 0;
×
345
    try {
×
346
      this->getSOA(di.zone, soadata); // we might not *have* a SOA yet, but this might trigger a load of it
×
347
    }
×
348
    catch (...) {
×
349
      continue;
×
350
    }
×
351
    if (di.notified_serial != soadata.serial) {
×
352
      BB2DomainInfo bbd;
×
353
      if (safeGetBBDomainInfo(di.id, &bbd)) {
×
354
        bbd.d_lastnotified = soadata.serial;
×
355
        safePutBBDomainInfo(bbd);
×
356
      }
×
357
      if (di.notified_serial) { // don't do notification storm on startup
×
358
        di.serial = soadata.serial;
×
359
        changedDomains.push_back(std::move(di));
×
360
      }
×
361
    }
×
362
  }
×
363
}
×
364

365
void Bind2Backend::getAllDomains(vector<DomainInfo>* domains, bool getSerial, bool /* include_disabled */)
366
{
70✔
367
  SOAData soadata;
70✔
368

369
  // prevent deadlock by using getSOA() later on
370
  {
70✔
371
    auto state = s_state.read_lock();
70✔
372
    domains->reserve(state->size());
70✔
373

374
    for (const auto& i : *state) {
70✔
375
      DomainInfo di;
5✔
376
      di.id = i.d_id;
5✔
377
      di.zone = i.d_name;
5✔
378
      di.last_check = i.d_lastcheck;
5✔
379
      di.kind = i.d_kind;
5✔
380
      di.primaries = i.d_primaries;
5✔
381
      di.backend = this;
5✔
382
      domains->push_back(std::move(di));
5✔
383
    };
5✔
384
  }
70✔
385

386
  if (getSerial) {
70✔
387
    for (DomainInfo& di : *domains) {
1,313✔
388
      // do not corrupt di if domain supplied by another backend.
389
      if (di.backend != this)
1,313!
390
        continue;
1,313✔
391
      try {
×
392
        this->getSOA(di.zone, soadata);
×
393
      }
×
394
      catch (...) {
×
395
        continue;
×
396
      }
×
397
      di.serial = soadata.serial;
×
398
    }
×
399
  }
40✔
400
}
70✔
401

402
void Bind2Backend::getUnfreshSecondaryInfos(vector<DomainInfo>* unfreshDomains)
403
{
×
404
  vector<DomainInfo> domains;
×
405
  {
×
406
    auto state = s_state.read_lock();
×
407
    domains.reserve(state->size());
×
408
    for (const auto& i : *state) {
×
409
      if (i.d_kind != DomainInfo::Secondary)
×
410
        continue;
×
411
      DomainInfo sd;
×
412
      sd.id = i.d_id;
×
413
      sd.zone = i.d_name;
×
414
      sd.primaries = i.d_primaries;
×
415
      sd.last_check = i.d_lastcheck;
×
416
      sd.backend = this;
×
417
      sd.kind = DomainInfo::Secondary;
×
418
      domains.push_back(std::move(sd));
×
419
    }
×
420
  }
×
421
  unfreshDomains->reserve(domains.size());
×
422

423
  for (DomainInfo& sd : domains) {
×
424
    SOAData soadata;
×
425
    soadata.refresh = 0;
×
426
    soadata.serial = 0;
×
427
    try {
×
428
      getSOA(sd.zone, soadata); // we might not *have* a SOA yet
×
429
    }
×
430
    catch (...) {
×
431
    }
×
432
    sd.serial = soadata.serial;
×
433
    // coverity[store_truncates_time_t]
434
    if (sd.last_check + soadata.refresh < (unsigned int)time(nullptr))
×
435
      unfreshDomains->push_back(std::move(sd));
×
436
  }
×
437
}
×
438

439
bool Bind2Backend::getDomainInfo(const DNSName& domain, DomainInfo& di, bool getSerial)
440
{
560✔
441
  BB2DomainInfo bbd;
560✔
442
  if (!safeGetBBDomainInfo(domain, &bbd))
560✔
443
    return false;
555✔
444

445
  di.id = bbd.d_id;
5✔
446
  di.zone = domain;
5✔
447
  di.primaries = bbd.d_primaries;
5✔
448
  di.last_check = bbd.d_lastcheck;
5✔
449
  di.backend = this;
5✔
450
  di.kind = bbd.d_kind;
5✔
451
  di.serial = 0;
5✔
452
  if (getSerial) {
5✔
453
    try {
1✔
454
      SOAData sd;
1✔
455
      sd.serial = 0;
1✔
456

457
      getSOA(bbd.d_name, sd); // we might not *have* a SOA yet
1✔
458
      di.serial = sd.serial;
1✔
459
    }
1✔
460
    catch (...) {
1✔
461
    }
×
462
  }
1✔
463

464
  return true;
5✔
465
}
5✔
466

467
void Bind2Backend::alsoNotifies(const DNSName& domain, set<string>* ips)
468
{
4✔
469
  // combine global list with local list
470
  for (const auto& i : this->alsoNotify) {
4!
471
    (*ips).insert(i);
×
472
  }
×
473
  // check metadata too if available
474
  vector<string> meta;
4✔
475
  if (getDomainMetadata(domain, "ALSO-NOTIFY", meta)) {
4!
476
    for (const auto& str : meta) {
×
477
      (*ips).insert(str);
×
478
    }
×
479
  }
×
480
  auto state = s_state.read_lock();
4✔
481
  for (const auto& i : *state) {
4!
482
    if (i.d_name == domain) {
×
483
      for (const auto& it : i.d_also_notify) {
×
484
        (*ips).insert(it);
×
485
      }
×
486
      return;
×
487
    }
×
488
  }
×
489
}
4✔
490

491
// only parses, does NOT add to s_state!
492
void Bind2Backend::parseZoneFile(BB2DomainInfo* bbd)
493
{
7✔
494
  NSEC3PARAMRecordContent ns3pr;
7✔
495
  bool nsec3zone = false;
7✔
496
  if (d_hybrid) {
7!
497
    DNSSECKeeper dk;
×
498
    nsec3zone = dk.getNSEC3PARAM(bbd->d_name, &ns3pr);
×
499
  }
×
500
  else
7✔
501
    nsec3zone = getNSEC3PARAMuncached(bbd->d_name, &ns3pr);
7✔
502

503
  auto records = std::make_shared<recordstorage_t>();
7✔
504
  ZoneParserTNG zpt(bbd->d_filename, bbd->d_name, s_binddirectory, d_upgradeContent);
7✔
505
  zpt.setMaxGenerateSteps(::arg().asNum("max-generate-steps"));
7✔
506
  zpt.setMaxIncludes(::arg().asNum("max-include-depth"));
7✔
507
  DNSResourceRecord rr;
7✔
508
  string hashed;
7✔
509
  while (zpt.get(rr)) {
69✔
510
    if (rr.qtype.getCode() == QType::NSEC || rr.qtype.getCode() == QType::NSEC3 || rr.qtype.getCode() == QType::NSEC3PARAM)
62!
511
      continue; // we synthesise NSECs on demand
×
512

513
    insertRecord(records, bbd->d_name, rr.qname, rr.qtype, rr.content, rr.ttl, "");
62✔
514
  }
62✔
515
  fixupOrderAndAuth(records, bbd->d_name, nsec3zone, ns3pr);
7✔
516
  doEmptyNonTerminals(records, bbd->d_name, nsec3zone, ns3pr);
7✔
517
  bbd->setCtime();
7✔
518
  bbd->d_loaded = true;
7✔
519
  bbd->d_checknow = false;
7✔
520
  bbd->d_status = "parsed into memory at " + nowTime();
7✔
521
  bbd->d_records = LookButDontTouch<recordstorage_t>(std::move(records));
7✔
522
  bbd->d_nsec3zone = nsec3zone;
7✔
523
  bbd->d_nsec3param = std::move(ns3pr);
7✔
524
}
7✔
525

526
/** THIS IS AN INTERNAL FUNCTION! It does moadnsparser prio impedance matching
527
    Much of the complication is due to the efforts to benefit from std::string reference counting copy on write semantics */
528
void Bind2Backend::insertRecord(std::shared_ptr<recordstorage_t>& records, const DNSName& zoneName, const DNSName& qname, const QType& qtype, const string& content, int ttl, const std::string& hashed, bool* auth)
529
{
68✔
530
  Bind2DNSRecord bdr;
68✔
531
  bdr.qname = qname;
68✔
532

533
  if (zoneName.empty())
68!
534
    ;
×
535
  else if (bdr.qname.isPartOf(zoneName))
68!
536
    bdr.qname.makeUsRelative(zoneName);
68✔
537
  else {
×
538
    string msg = "Trying to insert non-zone data, name='" + bdr.qname.toLogString() + "', qtype=" + qtype.toString() + ", zone='" + zoneName.toLogString() + "'";
×
539
    if (s_ignore_broken_records) {
×
540
      g_log << Logger::Warning << msg << " ignored" << endl;
×
541
      return;
×
542
    }
×
543
    else
×
544
      throw PDNSException(msg);
×
545
  }
×
546

547
  //  bdr.qname.swap(bdr.qname);
548

549
  if (!records->empty() && bdr.qname == boost::prior(records->end())->qname)
68✔
550
    bdr.qname = boost::prior(records->end())->qname;
16✔
551

552
  bdr.qname = bdr.qname;
68✔
553
  bdr.qtype = qtype.getCode();
68✔
554
  bdr.content = content;
68✔
555
  bdr.nsec3hash = hashed;
68✔
556

557
  if (auth != nullptr) // Set auth on empty non-terminals
68✔
558
    bdr.auth = *auth;
6✔
559
  else
62✔
560
    bdr.auth = true;
62✔
561

562
  bdr.ttl = ttl;
68✔
563
  records->insert(std::move(bdr));
68✔
564
}
68✔
565

566
string Bind2Backend::DLReloadNowHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
567
{
×
568
  ostringstream ret;
×
569

570
  for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
571
    BB2DomainInfo bbd;
×
572
    DNSName zone(*i);
×
573
    if (safeGetBBDomainInfo(zone, &bbd)) {
×
574
      Bind2Backend bb2;
×
575
      bb2.queueReloadAndStore(bbd.d_id);
×
576
      if (!safeGetBBDomainInfo(zone, &bbd)) // Read the *new* domain status
×
577
        ret << *i << ": [missing]\n";
×
578
      else
×
579
        ret << *i << ": " << (bbd.d_wasRejectedLastReload ? "[rejected]" : "") << "\t" << bbd.d_status << "\n";
×
580
      purgeAuthCaches(zone.toString() + "$");
×
581
      DNSSECKeeper::clearMetaCache(zone);
×
582
    }
×
583
    else
×
584
      ret << *i << " no such domain\n";
×
585
  }
×
586
  if (ret.str().empty())
×
587
    ret << "no domains reloaded";
×
588
  return ret.str();
×
589
}
×
590

591
string Bind2Backend::DLDomStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
592
{
4✔
593
  ostringstream ret;
4✔
594

595
  if (parts.size() > 1) {
4!
596
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
597
      BB2DomainInfo bbd;
×
598
      if (safeGetBBDomainInfo(DNSName(*i), &bbd)) {
×
599
        ret << *i << ": " << (bbd.d_loaded ? "" : "[rejected]") << "\t" << bbd.d_status << "\n";
×
600
      }
×
601
      else {
×
602
        ret << *i << " no such domain\n";
×
603
      }
×
604
    }
×
605
  }
×
606
  else {
4✔
607
    auto state = s_state.read_lock();
4✔
608
    for (const auto& i : *state) {
4✔
609
      ret << i.d_name << ": " << (i.d_loaded ? "" : "[rejected]") << "\t" << i.d_status << "\n";
4!
610
    }
4✔
611
  }
4✔
612

613
  if (ret.str().empty())
4!
614
    ret << "no domains passed";
×
615

616
  return ret.str();
4✔
617
}
4✔
618

619
static void printDomainExtendedStatus(ostringstream& ret, const BB2DomainInfo& info)
620
{
×
621
  ret << info.d_name << ": " << std::endl;
×
622
  ret << "\t Status: " << info.d_status << std::endl;
×
623
  ret << "\t Internal ID: " << info.d_id << std::endl;
×
624
  ret << "\t On-disk file: " << info.d_filename << " (" << info.d_ctime << ")" << std::endl;
×
625
  ret << "\t Kind: ";
×
626
  switch (info.d_kind) {
×
627
  case DomainInfo::Primary:
×
628
    ret << "Primary";
×
629
    break;
×
630
  case DomainInfo::Secondary:
×
631
    ret << "Secondary";
×
632
    break;
×
633
  default:
×
634
    ret << "Native";
×
635
  }
×
636
  ret << std::endl;
×
637
  ret << "\t Primaries: " << std::endl;
×
638
  for (const auto& primary : info.d_primaries) {
×
639
    ret << "\t\t - " << primary.toStringWithPort() << std::endl;
×
640
  }
×
641
  ret << "\t Also Notify: " << std::endl;
×
642
  for (const auto& also : info.d_also_notify) {
×
643
    ret << "\t\t - " << also << std::endl;
×
644
  }
×
645
  ret << "\t Number of records: " << info.d_records.getEntriesCount() << std::endl;
×
646
  ret << "\t Loaded: " << info.d_loaded << std::endl;
×
647
  ret << "\t Check now: " << info.d_checknow << std::endl;
×
648
  ret << "\t Check interval: " << info.getCheckInterval() << std::endl;
×
649
  ret << "\t Last check: " << info.d_lastcheck << std::endl;
×
650
  ret << "\t Last notified: " << info.d_lastnotified << std::endl;
×
651
}
×
652

653
string Bind2Backend::DLDomExtendedStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
654
{
×
655
  ostringstream ret;
×
656

657
  if (parts.size() > 1) {
×
658
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
659
      BB2DomainInfo bbd;
×
660
      if (safeGetBBDomainInfo(DNSName(*i), &bbd)) {
×
661
        printDomainExtendedStatus(ret, bbd);
×
662
      }
×
663
      else {
×
664
        ret << *i << " no such domain" << std::endl;
×
665
      }
×
666
    }
×
667
  }
×
668
  else {
×
669
    auto rstate = s_state.read_lock();
×
670
    for (const auto& state : *rstate) {
×
671
      printDomainExtendedStatus(ret, state);
×
672
    }
×
673
  }
×
674

675
  if (ret.str().empty()) {
×
676
    ret << "no domains passed" << std::endl;
×
677
  }
×
678

679
  return ret.str();
×
680
}
×
681

682
string Bind2Backend::DLListRejectsHandler(const vector<string>& /* parts */, Utility::pid_t /* ppid */)
683
{
×
684
  ostringstream ret;
×
685
  auto rstate = s_state.read_lock();
×
686
  for (const auto& i : *rstate) {
×
687
    if (!i.d_loaded)
×
688
      ret << i.d_name << "\t" << i.d_status << endl;
×
689
  }
×
690
  return ret.str();
×
691
}
×
692

693
string Bind2Backend::DLAddDomainHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
694
{
×
695
  if (parts.size() < 3)
×
696
    return "ERROR: Domain name and zone filename are required";
×
697

698
  DNSName domainname(parts[1]);
×
699
  const string& filename = parts[2];
×
700
  BB2DomainInfo bbd;
×
701
  if (safeGetBBDomainInfo(domainname, &bbd))
×
702
    return "Already loaded";
×
703

704
  if (!boost::starts_with(filename, "/") && ::arg()["chroot"].empty())
×
705
    return "Unable to load zone " + domainname.toLogString() + " from " + filename + " as the filename is not absolute.";
×
706

707
  struct stat buf;
×
708
  if (stat(filename.c_str(), &buf) != 0)
×
709
    return "Unable to load zone " + domainname.toLogString() + " from " + filename + ": " + strerror(errno);
×
710

711
  Bind2Backend bb2; // createdomainentry needs access to our configuration
×
712
  bbd = bb2.createDomainEntry(domainname, filename);
×
713
  bbd.d_filename = filename;
×
714
  bbd.d_checknow = true;
×
715
  bbd.d_loaded = true;
×
716
  bbd.d_lastcheck = 0;
×
717
  bbd.d_status = "parsing into memory";
×
718
  bbd.setCtime();
×
719

720
  safePutBBDomainInfo(bbd);
×
721

722
  g_zoneCache.add(domainname, bbd.d_id); // make new zone visible
×
723

724
  g_log << Logger::Warning << "Zone " << domainname << " loaded" << endl;
×
725
  return "Loaded zone " + domainname.toLogString() + " from " + filename;
×
726
}
×
727

728
Bind2Backend::Bind2Backend(const string& suffix, bool loadZones)
729
{
1,801✔
730
  d_getAllDomainMetadataQuery_stmt = nullptr;
1,801✔
731
  d_getDomainMetadataQuery_stmt = nullptr;
1,801✔
732
  d_deleteDomainMetadataQuery_stmt = nullptr;
1,801✔
733
  d_insertDomainMetadataQuery_stmt = nullptr;
1,801✔
734
  d_getDomainKeysQuery_stmt = nullptr;
1,801✔
735
  d_deleteDomainKeyQuery_stmt = nullptr;
1,801✔
736
  d_insertDomainKeyQuery_stmt = nullptr;
1,801✔
737
  d_GetLastInsertedKeyIdQuery_stmt = nullptr;
1,801✔
738
  d_activateDomainKeyQuery_stmt = nullptr;
1,801✔
739
  d_deactivateDomainKeyQuery_stmt = nullptr;
1,801✔
740
  d_getTSIGKeyQuery_stmt = nullptr;
1,801✔
741
  d_setTSIGKeyQuery_stmt = nullptr;
1,801✔
742
  d_deleteTSIGKeyQuery_stmt = nullptr;
1,801✔
743
  d_getTSIGKeysQuery_stmt = nullptr;
1,801✔
744

745
  setArgPrefix("bind" + suffix);
1,801✔
746
  d_logprefix = "[bind" + suffix + "backend]";
1,801✔
747
  d_hybrid = mustDo("hybrid");
1,801✔
748
  if (d_hybrid && g_zoneCache.isEnabled()) {
1,801!
749
    throw PDNSException("bind-hybrid and the zone cache currently interoperate badly. Please disable the zone cache or stop using bind-hybrid");
×
750
  }
×
751

752
  d_transaction_id = 0;
1,801✔
753
  s_ignore_broken_records = mustDo("ignore-broken-records");
1,801✔
754
  d_upgradeContent = ::arg().mustDo("upgrade-unknown-types");
1,801✔
755

756
  if (!loadZones && d_hybrid)
1,801!
757
    return;
×
758

759
  std::lock_guard<std::mutex> l(s_startup_lock);
1,801✔
760

761
  setupDNSSEC();
1,801✔
762
  if (s_first == 0) {
1,801✔
763
    return;
1,438✔
764
  }
1,438✔
765

766
  if (loadZones) {
363✔
767
    loadConfig();
138✔
768
    s_first = 0;
138✔
769
  }
138✔
770

771
  DynListener::registerFunc("BIND-RELOAD-NOW", &DLReloadNowHandler, "bindbackend: reload domains", "<domains>");
363✔
772
  DynListener::registerFunc("BIND-DOMAIN-STATUS", &DLDomStatusHandler, "bindbackend: list status of all domains", "[domains]");
363✔
773
  DynListener::registerFunc("BIND-DOMAIN-EXTENDED-STATUS", &DLDomExtendedStatusHandler, "bindbackend: list the extended status of all domains", "[domains]");
363✔
774
  DynListener::registerFunc("BIND-LIST-REJECTS", &DLListRejectsHandler, "bindbackend: list rejected domains");
363✔
775
  DynListener::registerFunc("BIND-ADD-ZONE", &DLAddDomainHandler, "bindbackend: add zone", "<domain> <filename>");
363✔
776
}
363✔
777

778
Bind2Backend::~Bind2Backend()
779
{
1,765✔
780
  freeStatements();
1,765✔
781
} // deallocate statements
1,765✔
782

783
void Bind2Backend::rediscover(string* status)
784
{
×
785
  loadConfig(status);
×
786
}
×
787

788
void Bind2Backend::reload()
789
{
×
790
  auto state = s_state.write_lock();
×
791
  for (const auto& i : *state) {
×
792
    i.d_checknow = true; // being a bit cheeky here, don't index state_t on this (mutable)
×
793
  }
×
794
}
×
795

796
void Bind2Backend::fixupOrderAndAuth(std::shared_ptr<recordstorage_t>& records, const DNSName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
797
{
7✔
798
  bool skip;
7✔
799
  DNSName shorter;
7✔
800
  set<DNSName> nssets, dssets;
7✔
801

802
  for (const auto& bdr : *records) {
62✔
803
    if (!bdr.qname.isRoot() && bdr.qtype == QType::NS)
62✔
804
      nssets.insert(bdr.qname);
2✔
805
    else if (bdr.qtype == QType::DS)
60!
806
      dssets.insert(bdr.qname);
×
807
  }
62✔
808

809
  for (auto iter = records->begin(); iter != records->end(); iter++) {
69✔
810
    skip = false;
62✔
811
    shorter = iter->qname;
62✔
812

813
    if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
62!
814
      do {
57✔
815
        if (nssets.count(shorter) != 0u) {
57!
816
          skip = true;
×
817
          break;
×
818
        }
×
819
      } while (shorter.chopOff() && !iter->qname.isRoot());
57!
820
    }
39✔
821

822
    iter->auth = (!skip && (iter->qtype == QType::DS || iter->qtype == QType::RRSIG || (nssets.count(iter->qname) == 0u)));
62!
823

824
    if (!skip && nsec3zone && iter->qtype != QType::RRSIG && (iter->auth || (iter->qtype == QType::NS && (ns3pr.d_flags == 0u)) || (dssets.count(iter->qname) != 0u))) {
62!
825
      Bind2DNSRecord bdr = *iter;
×
826
      bdr.nsec3hash = toBase32Hex(hashQNameWithSalt(ns3pr, bdr.qname + zoneName));
×
827
      records->replace(iter, bdr);
×
828
    }
×
829

830
    // cerr<<iter->qname<<"\t"<<QType(iter->qtype).toString()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
831
  }
62✔
832
}
7✔
833

834
void Bind2Backend::doEmptyNonTerminals(std::shared_ptr<recordstorage_t>& records, const DNSName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
835
{
7✔
836
  bool auth = false;
7✔
837
  DNSName shorter;
7✔
838
  std::unordered_set<DNSName> qnames;
7✔
839
  std::unordered_map<DNSName, bool> nonterm;
7✔
840

841
  uint32_t maxent = ::arg().asNum("max-ent-entries");
7✔
842

843
  for (const auto& bdr : *records)
7✔
844
    qnames.insert(bdr.qname);
62✔
845

846
  for (const auto& bdr : *records) {
62✔
847

848
    if (!bdr.auth && bdr.qtype == QType::NS)
62✔
849
      auth = (!nsec3zone || (ns3pr.d_flags == 0u));
2!
850
    else
60✔
851
      auth = bdr.auth;
60✔
852

853
    shorter = bdr.qname;
62✔
854
    while (shorter.chopOff()) {
119✔
855
      if (qnames.count(shorter) == 0u) {
57✔
856
        if (!(maxent)) {
17!
857
          g_log << Logger::Error << "Zone '" << zoneName << "' has too many empty non terminals." << endl;
×
858
          return;
×
859
        }
×
860

861
        if (nonterm.count(shorter) == 0u) {
17✔
862
          nonterm.emplace(shorter, auth);
6✔
863
          --maxent;
6✔
864
        }
6✔
865
        else if (auth)
11!
866
          nonterm[shorter] = true;
11✔
867
      }
17✔
868
    }
57✔
869
  }
62✔
870

871
  DNSResourceRecord rr;
7✔
872
  rr.qtype = "#0";
7✔
873
  rr.content = "";
7✔
874
  rr.ttl = 0;
7✔
875
  for (auto& nt : nonterm) {
7✔
876
    string hashed;
6✔
877
    rr.qname = nt.first + zoneName;
6✔
878
    if (nsec3zone && nt.second)
6!
879
      hashed = toBase32Hex(hashQNameWithSalt(ns3pr, rr.qname));
×
880
    insertRecord(records, zoneName, rr.qname, rr.qtype, rr.content, rr.ttl, hashed, &nt.second);
6✔
881

882
    // cerr<<rr.qname<<"\t"<<rr.qtype.toString()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
883
  }
6✔
884
}
7✔
885

886
void Bind2Backend::loadConfig(string* status) // NOLINT(readability-function-cognitive-complexity) 13379 https://github.com/PowerDNS/pdns/issues/13379 Habbie: zone2sql.cc, bindbackend2.cc: reduce complexity
887
{
138✔
888
  static int domain_id = 1;
138✔
889

890
  if (!getArg("config").empty()) {
138!
891
    BindParser BP;
138✔
892
    try {
138✔
893
      BP.parse(getArg("config"));
138✔
894
    }
138✔
895
    catch (PDNSException& ae) {
138✔
896
      g_log << Logger::Error << "Error parsing bind configuration: " << ae.reason << endl;
×
897
      throw;
×
898
    }
×
899

900
    vector<BindDomainInfo> domains = BP.getDomains();
138✔
901
    this->alsoNotify = BP.getAlsoNotify();
138✔
902

903
    s_binddirectory = BP.getDirectory();
138✔
904
    //    ZP.setDirectory(d_binddirectory);
905

906
    g_log << Logger::Warning << d_logprefix << " Parsing " << domains.size() << " domain(s), will report when done" << endl;
138✔
907

908
    set<DNSName> oldnames, newnames;
138✔
909
    {
138✔
910
      auto state = s_state.read_lock();
138✔
911
      for (const BB2DomainInfo& bbd : *state) {
138!
912
        oldnames.insert(bbd.d_name);
×
913
      }
×
914
    }
138✔
915
    int rejected = 0;
138✔
916
    int newdomains = 0;
138✔
917

918
    struct stat st;
138✔
919

920
    for (auto& domain : domains) {
138✔
921
      if (stat(domain.filename.c_str(), &st) == 0) {
7!
922
        domain.d_dev = st.st_dev;
7✔
923
        domain.d_ino = st.st_ino;
7✔
924
      }
7✔
925
    }
7✔
926

927
    sort(domains.begin(), domains.end()); // put stuff in inode order
138✔
928
    for (const auto& domain : domains) {
138✔
929
      if (!(domain.hadFileDirective)) {
7!
930
        g_log << Logger::Warning << d_logprefix << " Zone '" << domain.name << "' has no 'file' directive set in " << getArg("config") << endl;
×
931
        rejected++;
×
932
        continue;
×
933
      }
×
934

935
      if (domain.type.empty()) {
7!
936
        g_log << Logger::Notice << d_logprefix << " Zone '" << domain.name << "' has no type specified, assuming 'native'" << endl;
×
937
      }
×
938
      if (domain.type != "primary" && domain.type != "secondary" && domain.type != "native" && !domain.type.empty() && domain.type != "master" && domain.type != "slave") {
7!
939
        g_log << Logger::Warning << d_logprefix << " Warning! Skipping zone '" << domain.name << "' because type '" << domain.type << "' is invalid" << endl;
×
940
        rejected++;
×
941
        continue;
×
942
      }
×
943

944
      BB2DomainInfo bbd;
7✔
945
      bool isNew = false;
7✔
946

947
      if (!safeGetBBDomainInfo(domain.name, &bbd)) {
7!
948
        isNew = true;
7✔
949
        bbd.d_id = domain_id++;
7✔
950
        bbd.setCheckInterval(getArgAsNum("check-interval"));
7✔
951
        bbd.d_lastnotified = 0;
7✔
952
        bbd.d_loaded = false;
7✔
953
      }
7✔
954

955
      // overwrite what we knew about the domain
956
      bbd.d_name = domain.name;
7✔
957
      bool filenameChanged = (bbd.d_filename != domain.filename);
7✔
958
      bool addressesChanged = (bbd.d_primaries != domain.primaries || bbd.d_also_notify != domain.alsoNotify);
7!
959
      bbd.d_filename = domain.filename;
7✔
960
      bbd.d_primaries = domain.primaries;
7✔
961
      bbd.d_also_notify = domain.alsoNotify;
7✔
962

963
      DomainInfo::DomainKind kind = DomainInfo::Native;
7✔
964
      if (domain.type == "primary" || domain.type == "master") {
7!
965
        kind = DomainInfo::Primary;
7✔
966
      }
7✔
967
      if (domain.type == "secondary" || domain.type == "slave") {
7!
968
        kind = DomainInfo::Secondary;
×
969
      }
×
970

971
      bool kindChanged = (bbd.d_kind != kind);
7✔
972
      bbd.d_kind = kind;
7✔
973

974
      newnames.insert(bbd.d_name);
7✔
975
      if (filenameChanged || !bbd.d_loaded || !bbd.current()) {
7!
976
        g_log << Logger::Info << d_logprefix << " parsing '" << domain.name << "' from file '" << domain.filename << "'" << endl;
7✔
977

978
        try {
7✔
979
          parseZoneFile(&bbd);
7✔
980
        }
7✔
981
        catch (PDNSException& ae) {
7✔
982
          ostringstream msg;
×
983
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.reason;
×
984

985
          if (status != nullptr)
×
986
            *status += msg.str();
×
987
          bbd.d_status = msg.str();
×
988

989
          g_log << Logger::Warning << d_logprefix << msg.str() << endl;
×
990
          rejected++;
×
991
        }
×
992
        catch (std::system_error& ae) {
7✔
993
          ostringstream msg;
×
994
          if (ae.code().value() == ENOENT && isNew && domain.type == "slave")
×
995
            msg << " error at " + nowTime() << " no file found for new secondary domain '" << domain.name << "'. Has not been AXFR'd yet";
×
996
          else
×
997
            msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
×
998

999
          if (status != nullptr)
×
1000
            *status += msg.str();
×
1001
          bbd.d_status = msg.str();
×
1002
          g_log << Logger::Warning << d_logprefix << msg.str() << endl;
×
1003
          rejected++;
×
1004
        }
×
1005
        catch (std::exception& ae) {
7✔
1006
          ostringstream msg;
×
1007
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
×
1008

1009
          if (status != nullptr)
×
1010
            *status += msg.str();
×
1011
          bbd.d_status = msg.str();
×
1012

1013
          g_log << Logger::Warning << d_logprefix << msg.str() << endl;
×
1014
          rejected++;
×
1015
        }
×
1016
        safePutBBDomainInfo(bbd);
7✔
1017
      }
7✔
1018
      else if (addressesChanged || kindChanged) {
×
1019
        safePutBBDomainInfo(bbd);
×
1020
      }
×
1021
    }
7✔
1022
    vector<DNSName> diff;
138✔
1023

1024
    set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
138✔
1025
    unsigned int remdomains = diff.size();
138✔
1026

1027
    for (const DNSName& name : diff) {
138!
1028
      safeRemoveBBDomainInfo(name);
×
1029
    }
×
1030

1031
    // count number of entirely new domains
1032
    diff.clear();
138✔
1033
    set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
138✔
1034
    newdomains = diff.size();
138✔
1035

1036
    ostringstream msg;
138✔
1037
    msg << " Done parsing domains, " << rejected << " rejected, " << newdomains << " new, " << remdomains << " removed";
138✔
1038
    if (status != nullptr)
138!
1039
      *status = msg.str();
×
1040

1041
    g_log << Logger::Error << d_logprefix << msg.str() << endl;
138✔
1042
  }
138✔
1043
}
138✔
1044

1045
void Bind2Backend::queueReloadAndStore(unsigned int id)
1046
{
×
1047
  BB2DomainInfo bbold;
×
1048
  try {
×
1049
    if (!safeGetBBDomainInfo(id, &bbold))
×
1050
      return;
×
1051
    bbold.d_checknow = false;
×
1052
    BB2DomainInfo bbnew(bbold);
×
1053
    /* make sure that nothing will be able to alter the existing records,
1054
       we will load them from the zone file instead */
1055
    bbnew.d_records = LookButDontTouch<recordstorage_t>();
×
1056
    parseZoneFile(&bbnew);
×
1057
    bbnew.d_wasRejectedLastReload = false;
×
1058
    safePutBBDomainInfo(bbnew);
×
1059
    g_log << Logger::Warning << "Zone '" << bbnew.d_name << "' (" << bbnew.d_filename << ") reloaded" << endl;
×
1060
  }
×
1061
  catch (PDNSException& ae) {
×
1062
    ostringstream msg;
×
1063
    msg << " error at " + nowTime() + " parsing '" << bbold.d_name << "' from file '" << bbold.d_filename << "': " << ae.reason;
×
1064
    g_log << Logger::Warning << "Error parsing '" << bbold.d_name << "' from file '" << bbold.d_filename << "': " << ae.reason << endl;
×
1065
    bbold.d_status = msg.str();
×
1066
    bbold.d_lastcheck = time(nullptr);
×
1067
    bbold.d_wasRejectedLastReload = true;
×
1068
    safePutBBDomainInfo(bbold);
×
1069
  }
×
1070
  catch (std::exception& ae) {
×
1071
    ostringstream msg;
×
1072
    msg << " error at " + nowTime() + " parsing '" << bbold.d_name << "' from file '" << bbold.d_filename << "': " << ae.what();
×
1073
    g_log << Logger::Warning << "Error parsing '" << bbold.d_name << "' from file '" << bbold.d_filename << "': " << ae.what() << endl;
×
1074
    bbold.d_status = msg.str();
×
1075
    bbold.d_lastcheck = time(nullptr);
×
1076
    bbold.d_wasRejectedLastReload = true;
×
1077
    safePutBBDomainInfo(bbold);
×
1078
  }
×
1079
}
×
1080

1081
bool Bind2Backend::findBeforeAndAfterUnhashed(std::shared_ptr<const recordstorage_t>& records, const DNSName& qname, DNSName& /* unhashed */, DNSName& before, DNSName& after)
1082
{
1✔
1083
  // for(const auto& record: *records)
1084
  //   cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
1085

1086
  recordstorage_t::const_iterator iterBefore, iterAfter;
1✔
1087

1088
  iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
1✔
1089

1090
  if (iterBefore != records->begin())
1!
1091
    --iterBefore;
1✔
1092
  while ((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
1!
1093
    --iterBefore;
×
1094
  before = iterBefore->qname;
1✔
1095

1096
  if (iterAfter == records->end()) {
1!
1097
    iterAfter = records->begin();
1✔
1098
  }
1✔
1099
  else {
×
1100
    while ((!iterAfter->auth && iterAfter->qtype != QType::NS) || !iterAfter->qtype) {
×
1101
      ++iterAfter;
×
1102
      if (iterAfter == records->end()) {
×
1103
        iterAfter = records->begin();
×
1104
        break;
×
1105
      }
×
1106
    }
×
1107
  }
×
1108
  after = iterAfter->qname;
1✔
1109

1110
  return true;
1✔
1111
}
1✔
1112

1113
bool Bind2Backend::getBeforeAndAfterNamesAbsolute(uint32_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
1114
{
1✔
1115
  BB2DomainInfo bbd;
1✔
1116
  if (!safeGetBBDomainInfo(id, &bbd))
1!
1117
    return false;
×
1118

1119
  shared_ptr<const recordstorage_t> records = bbd.d_records.get();
1✔
1120
  if (!bbd.d_nsec3zone) {
1!
1121
    return findBeforeAndAfterUnhashed(records, qname, unhashed, before, after);
1✔
1122
  }
1✔
1123
  else {
×
1124
    const auto& hashindex = boost::multi_index::get<NSEC3Tag>(*records);
×
1125

1126
    // for(auto iter = first; iter != hashindex.end(); iter++)
1127
    //  cerr<<iter->nsec3hash<<endl;
1128

1129
    auto first = hashindex.upper_bound("");
×
1130
    auto iter = hashindex.upper_bound(qname.toStringNoDot());
×
1131

1132
    if (iter == hashindex.end()) {
×
1133
      --iter;
×
1134
      before = DNSName(iter->nsec3hash);
×
1135
      after = DNSName(first->nsec3hash);
×
1136
    }
×
1137
    else {
×
1138
      after = DNSName(iter->nsec3hash);
×
1139
      if (iter != first)
×
1140
        --iter;
×
1141
      else
×
1142
        iter = --hashindex.end();
×
1143
      before = DNSName(iter->nsec3hash);
×
1144
    }
×
1145
    unhashed = iter->qname + bbd.d_name;
×
1146

1147
    return true;
×
1148
  }
×
1149
}
1✔
1150

1151
void Bind2Backend::lookup(const QType& qtype, const DNSName& qname, int zoneId, DNSPacket* /* pkt_p */)
1152
{
57✔
1153
  d_handle.reset();
57✔
1154

1155
  static bool mustlog = ::arg().mustDo("query-logging");
57✔
1156

1157
  bool found = false;
57✔
1158
  DNSName domain;
57✔
1159
  BB2DomainInfo bbd;
57✔
1160

1161
  if (mustlog)
57!
1162
    g_log << Logger::Warning << "Lookup for '" << qtype.toString() << "' of '" << qname << "' within zoneID " << zoneId << endl;
×
1163

1164
  if (zoneId >= 0) {
57✔
1165
    if ((found = (safeGetBBDomainInfo(zoneId, &bbd) && qname.isPartOf(bbd.d_name)))) {
23!
1166
      domain = std::move(bbd.d_name);
23✔
1167
    }
23✔
1168
  }
23✔
1169
  else {
34✔
1170
    domain = qname;
34✔
1171
    do {
37✔
1172
      found = safeGetBBDomainInfo(domain, &bbd);
37✔
1173
    } while (!found && qtype != QType::SOA && domain.chopOff());
37✔
1174
  }
34✔
1175

1176
  if (!found) {
57✔
1177
    if (mustlog)
24!
1178
      g_log << Logger::Warning << "Found no authoritative zone for '" << qname << "' and/or id " << zoneId << endl;
×
1179
    d_handle.d_list = false;
24✔
1180
    return;
24✔
1181
  }
24✔
1182

1183
  if (mustlog)
33!
1184
    g_log << Logger::Warning << "Found a zone '" << domain << "' (with id " << bbd.d_id << ") that might contain data " << endl;
×
1185

1186
  d_handle.id = bbd.d_id;
33✔
1187
  d_handle.qname = qname.makeRelative(domain); // strip domain name
33✔
1188
  d_handle.qtype = qtype;
33✔
1189
  d_handle.domain = std::move(domain);
33✔
1190

1191
  if (!bbd.current()) {
33!
1192
    g_log << Logger::Warning << "Zone '" << d_handle.domain << "' (" << bbd.d_filename << ") needs reloading" << endl;
×
1193
    queueReloadAndStore(bbd.d_id);
×
1194
    if (!safeGetBBDomainInfo(d_handle.domain, &bbd))
×
1195
      throw DBException("Zone '" + bbd.d_name.toLogString() + "' (" + bbd.d_filename + ") gone after reload"); // if we don't throw here, we crash for some reason
×
1196
  }
×
1197

1198
  if (!bbd.d_loaded) {
33!
1199
    d_handle.reset();
×
1200
    throw DBException("Zone for '" + d_handle.domain.toLogString() + "' in '" + bbd.d_filename + "' not loaded (file missing, corrupt or primary dead)"); // fsck
×
1201
  }
×
1202

1203
  d_handle.d_records = bbd.d_records.get();
33✔
1204

1205
  if (d_handle.d_records->empty())
33!
1206
    DLOG(g_log << "Query with no results" << endl);
×
1207

1208
  d_handle.mustlog = mustlog;
33✔
1209

1210
  const auto& hashedidx = boost::multi_index::get<UnorderedNameTag>(*d_handle.d_records);
33✔
1211
  auto range = hashedidx.equal_range(d_handle.qname);
33✔
1212

1213
  d_handle.d_list = false;
33✔
1214
  d_handle.d_iter = range.first;
33✔
1215
  d_handle.d_end_iter = range.second;
33✔
1216
}
33✔
1217

1218
Bind2Backend::handle::handle()
1219
{
1,801✔
1220
  mustlog = false;
1,801✔
1221
}
1,801✔
1222

1223
bool Bind2Backend::get(DNSResourceRecord& r)
1224
{
139✔
1225
  if (!d_handle.d_records) {
139✔
1226
    if (d_handle.mustlog)
24!
1227
      g_log << Logger::Warning << "There were no answers" << endl;
×
1228
    return false;
24✔
1229
  }
24✔
1230

1231
  if (!d_handle.get(r)) {
115✔
1232
    if (d_handle.mustlog)
37!
1233
      g_log << Logger::Warning << "End of answers" << endl;
×
1234

1235
    d_handle.reset();
37✔
1236

1237
    return false;
37✔
1238
  }
37✔
1239
  if (d_handle.mustlog)
78!
1240
    g_log << Logger::Warning << "Returning: '" << r.qtype.toString() << "' of '" << r.qname << "', content: '" << r.content << "'" << endl;
×
1241
  return true;
78✔
1242
}
115✔
1243

1244
bool Bind2Backend::handle::get(DNSResourceRecord& r)
1245
{
115✔
1246
  if (d_list)
115✔
1247
    return get_list(r);
16✔
1248
  else
99✔
1249
    return get_normal(r);
99✔
1250
}
115✔
1251

1252
void Bind2Backend::handle::reset()
1253
{
98✔
1254
  d_records.reset();
98✔
1255
  qname.clear();
98✔
1256
  mustlog = false;
98✔
1257
}
98✔
1258

1259
//#define DLOG(x) x
1260
bool Bind2Backend::handle::get_normal(DNSResourceRecord& r)
1261
{
99✔
1262
  DLOG(g_log << "Bind2Backend get() was called for " << qtype.toString() << " record for '" << qname << "' - " << d_records->size() << " available in total!" << endl);
99✔
1263

1264
  if (d_iter == d_end_iter) {
99✔
1265
    return false;
33✔
1266
  }
33✔
1267

1268
  while (d_iter != d_end_iter && !(qtype.getCode() == QType::ANY || (d_iter)->qtype == qtype.getCode())) {
86!
1269
    DLOG(g_log << Logger::Warning << "Skipped " << qname << "/" << QType(d_iter->qtype).toString() << ": '" << d_iter->content << "'" << endl);
20✔
1270
    d_iter++;
20✔
1271
  }
20✔
1272
  if (d_iter == d_end_iter) {
66!
1273
    return false;
×
1274
  }
×
1275
  DLOG(g_log << "Bind2Backend get() returning a rr with a " << QType(d_iter->qtype).getCode() << endl);
66✔
1276

1277
  r.qname = qname.empty() ? domain : (qname + domain);
66!
1278
  r.domain_id = id;
66✔
1279
  r.content = (d_iter)->content;
66✔
1280
  //  r.domain_id=(d_iter)->domain_id;
1281
  r.qtype = (d_iter)->qtype;
66✔
1282
  r.ttl = (d_iter)->ttl;
66✔
1283

1284
  //if(!d_iter->auth && r.qtype.getCode() != QType::A && r.qtype.getCode()!=QType::AAAA && r.qtype.getCode() != QType::NS)
1285
  //  cerr<<"Warning! Unauth response for qtype "<< r.qtype.toString() << " for '"<<r.qname<<"'"<<endl;
1286
  r.auth = d_iter->auth;
66✔
1287

1288
  d_iter++;
66✔
1289

1290
  return true;
66✔
1291
}
66✔
1292

1293
bool Bind2Backend::list(const DNSName& /* target */, int id, bool /* include_disabled */)
1294
{
4✔
1295
  BB2DomainInfo bbd;
4✔
1296

1297
  if (!safeGetBBDomainInfo(id, &bbd))
4!
1298
    return false;
×
1299

1300
  d_handle.reset();
4✔
1301
  DLOG(g_log << "Bind2Backend constructing handle for list of " << id << endl);
4✔
1302

1303
  if (!bbd.d_loaded) {
4!
1304
    throw PDNSException("zone was not loaded, perhaps because of: " + bbd.d_status);
×
1305
  }
×
1306

1307
  d_handle.d_records = bbd.d_records.get(); // give it a copy, which will stay around
4✔
1308
  d_handle.d_qname_iter = d_handle.d_records->begin();
4✔
1309
  d_handle.d_qname_end = d_handle.d_records->end(); // iter now points to a vector of pointers to vector<BBResourceRecords>
4✔
1310

1311
  d_handle.id = id;
4✔
1312
  d_handle.domain = bbd.d_name;
4✔
1313
  d_handle.d_list = true;
4✔
1314
  return true;
4✔
1315
}
4✔
1316

1317
bool Bind2Backend::handle::get_list(DNSResourceRecord& r)
1318
{
16✔
1319
  if (d_qname_iter != d_qname_end) {
16✔
1320
    r.qname = d_qname_iter->qname.empty() ? domain : (d_qname_iter->qname + domain);
12!
1321
    r.domain_id = id;
12✔
1322
    r.content = (d_qname_iter)->content;
12✔
1323
    r.qtype = (d_qname_iter)->qtype;
12✔
1324
    r.ttl = (d_qname_iter)->ttl;
12✔
1325
    r.auth = d_qname_iter->auth;
12✔
1326
    d_qname_iter++;
12✔
1327
    return true;
12✔
1328
  }
12✔
1329
  return false;
4✔
1330
}
16✔
1331

1332
bool Bind2Backend::autoPrimariesList(std::vector<AutoPrimary>& primaries)
1333
{
×
1334
  if (getArg("autoprimary-config").empty())
×
1335
    return false;
×
1336

1337
  ifstream c_if(getArg("autoprimaries"), std::ios::in);
×
1338
  if (!c_if) {
×
1339
    g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl;
×
1340
    return false;
×
1341
  }
×
1342

1343
  string line, sip, saccount;
×
1344
  while (getline(c_if, line)) {
×
1345
    std::istringstream ii(line);
×
1346
    ii >> sip;
×
1347
    if (!sip.empty()) {
×
1348
      ii >> saccount;
×
1349
      primaries.emplace_back(sip, "", saccount);
×
1350
    }
×
1351
  }
×
1352

1353
  c_if.close();
×
1354
  return true;
×
1355
}
×
1356

1357
bool Bind2Backend::autoPrimaryBackend(const string& ip, const DNSName& /* domain */, const vector<DNSResourceRecord>& /* nsset */, string* /* nameserver */, string* account, DNSBackend** db)
1358
{
×
1359
  // Check whether we have a configfile available.
1360
  if (getArg("autoprimary-config").empty())
×
1361
    return false;
×
1362

1363
  ifstream c_if(getArg("autoprimaries").c_str(), std::ios::in); // this was nocreate?
×
1364
  if (!c_if) {
×
1365
    g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl;
×
1366
    return false;
×
1367
  }
×
1368

1369
  // Format:
1370
  // <ip> <accountname>
1371
  string line, sip, saccount;
×
1372
  while (getline(c_if, line)) {
×
1373
    std::istringstream ii(line);
×
1374
    ii >> sip;
×
1375
    if (sip == ip) {
×
1376
      ii >> saccount;
×
1377
      break;
×
1378
    }
×
1379
  }
×
1380
  c_if.close();
×
1381

1382
  if (sip != ip) // ip not found in authorization list - reject
×
1383
    return false;
×
1384

1385
  // ip authorized as autoprimary - accept
1386
  *db = this;
×
1387
  if (saccount.length() > 0)
×
1388
    *account = saccount.c_str();
×
1389

1390
  return true;
×
1391
}
×
1392

1393
BB2DomainInfo Bind2Backend::createDomainEntry(const DNSName& domain, const string& filename)
1394
{
×
1395
  int newid = 1;
×
1396
  { // Find a free zone id nr.
×
1397
    auto state = s_state.read_lock();
×
1398
    if (!state->empty()) {
×
1399
      // older (1.53) versions of boost have an expression for s_state.rbegin()
1400
      // that is ambiguous in C++17. So construct it explicitly
1401
      newid = boost::make_reverse_iterator(state->end())->d_id + 1;
×
1402
    }
×
1403
  }
×
1404

1405
  BB2DomainInfo bbd;
×
1406
  bbd.d_kind = DomainInfo::Native;
×
1407
  bbd.d_id = newid;
×
1408
  bbd.d_records = std::make_shared<recordstorage_t>();
×
1409
  bbd.d_name = domain;
×
1410
  bbd.setCheckInterval(getArgAsNum("check-interval"));
×
1411
  bbd.d_filename = filename;
×
1412

1413
  return bbd;
×
1414
}
×
1415

1416
bool Bind2Backend::createSecondaryDomain(const string& ip, const DNSName& domain, const string& /* nameserver */, const string& account)
1417
{
×
1418
  string filename = getArg("autoprimary-destdir") + '/' + domain.toStringNoDot();
×
1419

1420
  g_log << Logger::Warning << d_logprefix
×
1421
        << " Writing bind config zone statement for superslave zone '" << domain
×
1422
        << "' from autoprimary " << ip << endl;
×
1423

1424
  {
×
1425
    std::lock_guard<std::mutex> l2(s_autosecondary_config_lock);
×
1426

1427
    ofstream c_of(getArg("autoprimary-config").c_str(), std::ios::app);
×
1428
    if (!c_of) {
×
1429
      g_log << Logger::Error << "Unable to open autoprimary configfile for append: " << stringerror() << endl;
×
1430
      throw DBException("Unable to open autoprimary configfile for append: " + stringerror());
×
1431
    }
×
1432

1433
    c_of << endl;
×
1434
    c_of << "# AutoSecondary zone '" << domain.toString() << "' (added: " << nowTime() << ") (account: " << account << ')' << endl;
×
1435
    c_of << "zone \"" << domain.toStringNoDot() << "\" {" << endl;
×
1436
    c_of << "\ttype secondary;" << endl;
×
1437
    c_of << "\tfile \"" << filename << "\";" << endl;
×
1438
    c_of << "\tprimaries { " << ip << "; };" << endl;
×
1439
    c_of << "};" << endl;
×
1440
    c_of.close();
×
1441
  }
×
1442

1443
  BB2DomainInfo bbd = createDomainEntry(domain, filename);
×
1444
  bbd.d_kind = DomainInfo::Secondary;
×
1445
  bbd.d_primaries.push_back(ComboAddress(ip, 53));
×
1446
  bbd.setCtime();
×
1447
  safePutBBDomainInfo(bbd);
×
1448

1449
  return true;
×
1450
}
×
1451

1452
bool Bind2Backend::searchRecords(const string& pattern, size_t maxResults, vector<DNSResourceRecord>& result)
1453
{
18✔
1454
  SimpleMatch sm(pattern, true);
18✔
1455
  static bool mustlog = ::arg().mustDo("query-logging");
18✔
1456
  if (mustlog)
18!
1457
    g_log << Logger::Warning << "Search for pattern '" << pattern << "'" << endl;
×
1458

1459
  {
18✔
1460
    auto state = s_state.read_lock();
18✔
1461

1462
    for (const auto& i : *state) {
18!
1463
      BB2DomainInfo h;
×
1464
      if (!safeGetBBDomainInfo(i.d_id, &h)) {
×
1465
        continue;
×
1466
      }
×
1467

1468
      if (!h.d_loaded) {
×
1469
        continue;
×
1470
      }
×
1471

1472
      shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
×
1473

1474
      for (recordstorage_t::const_iterator ri = rhandle->begin(); result.size() < maxResults && ri != rhandle->end(); ri++) {
×
1475
        DNSName name = ri->qname.empty() ? i.d_name : (ri->qname + i.d_name);
×
1476
        if (sm.match(name) || sm.match(ri->content)) {
×
1477
          DNSResourceRecord r;
×
1478
          r.qname = std::move(name);
×
1479
          r.domain_id = i.d_id;
×
1480
          r.content = ri->content;
×
1481
          r.qtype = ri->qtype;
×
1482
          r.ttl = ri->ttl;
×
1483
          r.auth = ri->auth;
×
1484
          result.push_back(std::move(r));
×
1485
        }
×
1486
      }
×
1487
    }
×
1488
  }
18✔
1489

1490
  return true;
18✔
1491
}
18✔
1492

1493
class Bind2Factory : public BackendFactory
1494
{
1495
public:
1496
  Bind2Factory() :
1497
    BackendFactory("bind") {}
2,851✔
1498

1499
  void declareArguments(const string& suffix = "") override
1500
  {
250✔
1501
    declare(suffix, "ignore-broken-records", "Ignore records that are out-of-bound for the zone.", "no");
250✔
1502
    declare(suffix, "config", "Location of named.conf", "");
250✔
1503
    declare(suffix, "check-interval", "Interval for zonefile changes", "0");
250✔
1504
    declare(suffix, "autoprimary-config", "Location of (part of) named.conf where pdns can write zone-statements to", "");
250✔
1505
    declare(suffix, "autoprimaries", "List of IP-addresses of autoprimaries", "");
250✔
1506
    declare(suffix, "autoprimary-destdir", "Destination directory for newly added secondary zones", ::arg()["config-dir"]);
250✔
1507
    declare(suffix, "dnssec-db", "Filename to store & access our DNSSEC metadatabase, empty for none", "");
250✔
1508
    declare(suffix, "dnssec-db-journal-mode", "SQLite3 journal mode", "WAL");
250✔
1509
    declare(suffix, "hybrid", "Store DNSSEC metadata in other backend", "no");
250✔
1510
  }
250✔
1511

1512
  DNSBackend* make(const string& suffix = "") override
1513
  {
1,564✔
1514
    assertEmptySuffix(suffix);
1,564✔
1515
    return new Bind2Backend(suffix);
1,564✔
1516
  }
1,564✔
1517

1518
  DNSBackend* makeMetadataOnly(const string& suffix = "") override
1519
  {
237✔
1520
    assertEmptySuffix(suffix);
237✔
1521
    return new Bind2Backend(suffix, false);
237✔
1522
  }
237✔
1523

1524
private:
1525
  void assertEmptySuffix(const string& suffix)
1526
  {
1,801✔
1527
    if (!suffix.empty())
1,801!
1528
      throw PDNSException("launch= suffixes are not supported on the bindbackend");
×
1529
  }
1,801✔
1530
};
1531

1532
//! Magic class that is activated when the dynamic library is loaded
1533
class Bind2Loader
1534
{
1535
public:
1536
  Bind2Loader()
1537
  {
2,851✔
1538
    BackendMakers().report(std::make_unique<Bind2Factory>());
2,851✔
1539
    g_log << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
2,851✔
1540
#ifndef REPRODUCIBLE
2,851✔
1541
          << " (" __DATE__ " " __TIME__ ")"
2,851✔
1542
#endif
2,851✔
1543
#ifdef HAVE_SQLITE3
2,851✔
1544
          << " (with bind-dnssec-db support)"
2,851✔
1545
#endif
2,851✔
1546
          << " reporting" << endl;
2,851✔
1547
  }
2,851✔
1548
};
1549
static Bind2Loader bind2loader;
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

© 2025 Coveralls, Inc