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

PowerDNS / pdns / 26302933215

22 May 2026 05:40PM UTC coverage: 71.068% (+4.1%) from 66.988%
26302933215

Pull #17249

github

web-flow
Merge a73252e72 into 407e72ccc
Pull Request #17249: Refactor Dockerfiles + add healthchecks

46252 of 81366 branches covered (56.84%)

Branch coverage included in aggregate %.

132746 of 170501 relevant lines covered (77.86%)

6306931.71 hits per line

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

58.03
/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
{
15,607✔
87
  d_loaded = false;
15,607✔
88
  d_lastcheck = 0;
15,607✔
89
  d_checknow = false;
15,607✔
90
  d_status = "Unknown";
15,607✔
91
}
15,607✔
92

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

98
bool BB2DomainInfo::current()
99
{
4,152✔
100
  if (d_checknow) {
4,152✔
101
    return false;
6✔
102
  }
6✔
103

104
  if (!d_checkinterval)
4,146!
105
    return true;
4,146✔
106

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

110
  d_lastcheck = time(nullptr);
×
111
  // Our data is still current if all the files it has been obtained from have
112
  // their modification times unchanged since the last parse.
113
  return std::all_of(d_fileinfo.cbegin(), d_fileinfo.cend(),
×
114
                     [](const auto& fileinfo) { return getCtime(fileinfo.first) == fileinfo.second; });
×
115
}
×
116

117
time_t BB2DomainInfo::getCtime(const std::string& filename)
118
{
×
119
  struct stat buf;
×
120

121
  if (filename.empty() || stat(filename.c_str(), &buf) < 0) {
×
122
    return 0;
×
123
  }
×
124
  return buf.st_ctime;
×
125
}
×
126

127
void BB2DomainInfo::updateCtime()
128
{
×
129
  struct stat buf;
×
130

131
  for (auto& fileinfo : d_fileinfo) {
×
132
    if (stat(fileinfo.first.c_str(), &buf) < 0) {
×
133
      buf.st_ctime = 0;
×
134
    }
×
135
    fileinfo.second = buf.st_ctime;
×
136
  }
×
137
}
×
138

139
// NOLINTNEXTLINE(readability-identifier-length)
140
bool Bind2Backend::safeGetBBDomainInfo(domainid_t id, BB2DomainInfo* bbd)
141
{
11,240✔
142
  auto state = s_state.read_lock();
11,240✔
143
  state_t::const_iterator iter = state->find(id);
11,240✔
144
  if (iter == state->end()) {
11,240!
145
    return false;
×
146
  }
×
147
  *bbd = *iter;
11,240✔
148
  return true;
11,240✔
149
}
11,240✔
150

151
bool Bind2Backend::safeGetBBDomainInfo(const ZoneName& name, BB2DomainInfo* bbd)
152
{
4,374✔
153
  auto state = s_state.read_lock();
4,374✔
154
  const auto& nameindex = boost::multi_index::get<NameTag>(*state);
4,374✔
155
  auto iter = nameindex.find(name);
4,374✔
156
  if (iter == nameindex.end()) {
4,374✔
157
    return false;
3,327✔
158
  }
3,327✔
159
  *bbd = *iter;
1,047✔
160
  return true;
1,047✔
161
}
4,374✔
162

163
bool Bind2Backend::safeRemoveBBDomainInfo(const ZoneName& name)
164
{
×
165
  auto state = s_state.write_lock();
×
166
  using nameindex_t = state_t::index<NameTag>::type;
×
167
  nameindex_t& nameindex = boost::multi_index::get<NameTag>(*state);
×
168

169
  nameindex_t::iterator iter = nameindex.find(name);
×
170
  if (iter == nameindex.end()) {
×
171
    return false;
×
172
  }
×
173
  nameindex.erase(iter);
×
174
  return true;
×
175
}
×
176

177
void Bind2Backend::safePutBBDomainInfo(const BB2DomainInfo& bbd)
178
{
2,815✔
179
  auto state = s_state.write_lock();
2,815✔
180
  replacing_insert(*state, bbd);
2,815✔
181
}
2,815✔
182

183
// NOLINTNEXTLINE(readability-identifier-length)
184
void Bind2Backend::setNotified(domainid_t id, uint32_t serial)
185
{
×
186
  BB2DomainInfo bbd;
×
187
  if (!safeGetBBDomainInfo(id, &bbd))
×
188
    return;
×
189
  bbd.d_lastnotified = serial;
×
190
  safePutBBDomainInfo(bbd);
×
191
}
×
192

193
// NOLINTNEXTLINE(readability-identifier-length)
194
void Bind2Backend::setLastCheck(domainid_t domain_id, time_t lastcheck)
195
{
72✔
196
  BB2DomainInfo bbd;
72✔
197
  if (safeGetBBDomainInfo(domain_id, &bbd)) {
72!
198
    bbd.d_lastcheck = lastcheck;
72✔
199
    safePutBBDomainInfo(bbd);
72✔
200
  }
72✔
201
}
72✔
202

203
void Bind2Backend::setStale(domainid_t domain_id)
204
{
×
205
  Bind2Backend::setLastCheck(domain_id, 0);
×
206
}
×
207

208
void Bind2Backend::setFresh(domainid_t domain_id)
209
{
72✔
210
  Bind2Backend::setLastCheck(domain_id, time(nullptr));
72✔
211
}
72✔
212

213
bool Bind2Backend::startTransaction(const ZoneName& qname, domainid_t domainId)
214
{
221✔
215
  if (domainId == UnknownDomainID) {
221✔
216
    d_transaction_tmpname.clear();
149✔
217
    d_transaction_id = UnknownDomainID;
149✔
218
    // No support for domain contents deletion
219
    return false;
149✔
220
  }
149✔
221
  if (domainId == 0) {
72!
222
    throw DBException("domain_id 0 is invalid for this backend.");
×
223
  }
×
224

225
  d_transaction_id = domainId;
72✔
226
  d_transaction_qname = qname;
72✔
227
  BB2DomainInfo bbd;
72✔
228
  if (safeGetBBDomainInfo(domainId, &bbd)) {
72!
229
    d_transaction_tmpname = bbd.main_filename() + "XXXXXX";
72✔
230
    int fd = mkstemp(&d_transaction_tmpname.at(0));
72✔
231
    if (fd == -1) {
72!
232
      throw DBException("Unable to create a unique temporary zonefile '" + d_transaction_tmpname + "': " + stringerror());
×
233
    }
×
234

235
    d_of = std::make_unique<ofstream>(d_transaction_tmpname);
72✔
236
    if (!*d_of) {
72!
237
      unlink(d_transaction_tmpname.c_str());
×
238
      close(fd);
×
239
      fd = -1;
×
240
      d_of.reset();
×
241
      throw DBException("Unable to open temporary zonefile '" + d_transaction_tmpname + "': " + stringerror());
×
242
    }
×
243
    close(fd);
72✔
244
    fd = -1;
72✔
245

246
    *d_of << "; Written by PowerDNS, don't edit!" << endl;
72✔
247
    *d_of << "; Zone '" << bbd.d_name << "' retrieved from primary " << endl
72✔
248
          << "; at " << nowTime() << endl; // insert primary info here again
72✔
249

250
    return true;
72✔
251
  }
72✔
252
  return false;
×
253
}
72✔
254

255
bool Bind2Backend::commitTransaction()
256
{
221✔
257
  // d_transaction_id is only set to a valid domain id if we are actually
258
  // setting up a replacement zone file with the updated data.
259
  if (d_transaction_id == UnknownDomainID) {
221✔
260
    return false;
149✔
261
  }
149✔
262
  d_of.reset();
72✔
263

264
  BB2DomainInfo bbd;
72✔
265
  if (safeGetBBDomainInfo(d_transaction_id, &bbd)) {
72!
266
    if (rename(d_transaction_tmpname.c_str(), bbd.main_filename().c_str()) < 0) {
72!
267
      throw DBException("Unable to commit (rename to: '" + bbd.main_filename() + "') AXFRed zone: " + stringerror());
×
268
    }
×
269
    queueReloadAndStore(bbd.d_id);
72✔
270
  }
72✔
271

272
  d_transaction_id = UnknownDomainID;
72✔
273

274
  return true;
72✔
275
}
72✔
276

277
bool Bind2Backend::abortTransaction()
278
{
×
279
  // d_transaction_id is only set to a valid domain id if we are actually
280
  // setting up a replacement zone file with the updated data.
281
  if (d_transaction_id != UnknownDomainID) {
×
282
    unlink(d_transaction_tmpname.c_str());
×
283
    d_of.reset();
×
284
    d_transaction_id = UnknownDomainID;
×
285
  }
×
286

287
  return true;
×
288
}
×
289

290
/** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */
291
static bool endsOn(const string& domain, const string& suffix)
292
{
416✔
293
  if (domain.size() <= suffix.size()) {
416✔
294
    return false;
52✔
295
  }
52✔
296

297
  string::size_type dpos = domain.size() - suffix.size() - 1;
364✔
298
  if (domain[dpos++] != '.') {
364✔
299
    return false;
88✔
300
  }
88✔
301
  // That dot might have been escaped. So we now need to count how many '\'
302
  // characters we can find in a row before it; if their number is odd, the
303
  // dot is escaped and we are not a proper suffix.
304
  size_t slashes{0};
276✔
305
  while (dpos >= 2 + slashes && domain.at(dpos - 2 - slashes) == '\\') {
276!
306
    ++slashes;
×
307
  }
×
308
  if ((slashes % 2) != 0) {
276!
309
    return false;
×
310
  }
×
311

312
  string::size_type spos = 0;
276✔
313
  for (; dpos < domain.size(); ++dpos, ++spos) {
3,928✔
314
    if (!pdns_iequals_ch(domain[dpos], suffix[spos])) {
3,664✔
315
      return false;
12✔
316
    }
12✔
317
  }
3,664✔
318

319
  return true;
264✔
320
}
276✔
321

322
/** strips a domain suffix from a domain */
323
static void stripDomainSuffix(string* qname, const ZoneName& zonename)
324
{
432✔
325
  std::string domain = zonename.operator const DNSName&().toString();
432✔
326

327
  if (domain.empty()) {
432!
328
    return;
×
329
  }
×
330
  if (pdns_iequals(*qname, domain)) {
432✔
331
    *qname = "@";
16✔
332
    return;
16✔
333
  }
16✔
334
  if (endsOn(*qname, domain)) {
416✔
335
    auto prefix = qname->size() - domain.size();
264✔
336
    qname->resize(prefix - 1); // also strip dot
264✔
337
  }
264✔
338
}
416✔
339

340
// Perform adequate escaping of characters which have special meaning in
341
// Bind zone files.
342
// Note that the input is supposed to be a DNSName::toString() - or any of
343
// its variants - so we assume \ and . have been correctly escaped by
344
// DNSName::appendEscapedLabel already.
345
static const std::string bindEscape(const std::string& name)
346
{
202,172✔
347
  std::string ret;
202,172✔
348
  std::array<char, 5> ebuf{};
202,172✔
349

350
  for (char letter : name) {
2,818,960✔
351
    switch (letter) {
2,818,960✔
352
    case '$':
×
353
    case '@':
×
354
    case '"':
×
355
    case ';':
×
356
    case '(':
×
357
    case ')':
×
358
      snprintf(ebuf.data(), ebuf.size(), "\\%03u", static_cast<unsigned char>(letter));
×
359
      ret += ebuf.data();
×
360
      break;
×
361
    default:
2,818,960!
362
      ret += letter;
2,818,960✔
363
      break;
2,818,960✔
364
    }
2,818,960✔
365
  }
2,818,960✔
366
  return ret;
202,172✔
367
}
202,172✔
368

369
bool Bind2Backend::feedRecord(const DNSResourceRecord& rr, const DNSName& /* ordername */, bool /* ordernameIsNSEC3 */)
370
{
202,805✔
371
  if (d_transaction_id == UnknownDomainID) {
202,805!
372
    throw DBException("Bind2Backend::feedRecord() called outside of transaction");
×
373
  }
×
374

375
  string qname;
202,805✔
376
  if (d_transaction_qname.empty()) {
202,805!
377
    qname = bindEscape(rr.qname.toString());
×
378
  }
×
379
  else if (rr.qname.isPartOf(d_transaction_qname)) {
202,805!
380
    if (rr.qname == d_transaction_qname.operator const DNSName&()) {
202,805✔
381
      qname = "@";
633✔
382
    }
633✔
383
    else {
202,172✔
384
      DNSName relName = rr.qname.makeRelative(d_transaction_qname);
202,172✔
385
      qname = bindEscape(relName.toStringNoDot());
202,172✔
386
    }
202,172✔
387
  }
202,805✔
388
  else {
×
389
    throw DBException("out-of-zone data '" + rr.qname.toLogString() + "' during AXFR of zone '" + d_transaction_qname.toLogString() + "'");
×
390
  }
×
391

392
  shared_ptr<DNSRecordContent> drc(DNSRecordContent::make(rr.qtype.getCode(), QClass::IN, rr.content));
202,805✔
393
  string content = drc->getZoneRepresentation();
202,805✔
394

395
  // SOA needs stripping too! XXX FIXME - also, this should not be here I think
396
  switch (rr.qtype.getCode()) {
202,805✔
397
  case QType::MX:
56✔
398
  case QType::SRV:
76✔
399
  case QType::CNAME:
208✔
400
  case QType::DNAME:
212✔
401
  case QType::NS:
432✔
402
    stripDomainSuffix(&content, d_transaction_qname);
432✔
403
    [[fallthrough]];
432✔
404
  default:
202,805✔
405
    if (d_of && *d_of) {
202,805!
406
      *d_of << qname << "\t" << rr.ttl << "\t" << rr.qtype.toString() << "\t" << content << endl;
202,805✔
407
    }
202,805✔
408
  }
202,805✔
409
  return true;
202,805✔
410
}
202,805✔
411

412
void Bind2Backend::getUpdatedPrimaries(vector<DomainInfo>& changedDomains, std::unordered_set<DNSName>& /* catalogs */, CatalogHashMap& /* catalogHashes */)
413
{
×
414
  vector<DomainInfo> consider;
×
415
  {
×
416
    auto state = s_state.read_lock();
×
417

418
    for (const auto& i : *state) {
×
419
      if (i.d_kind != DomainInfo::Primary && this->alsoNotify.empty() && i.d_also_notify.empty())
×
420
        continue;
×
421

422
      DomainInfo di;
×
423
      di.id = i.d_id;
×
424
      di.zone = i.d_name;
×
425
      di.last_check = i.d_lastcheck;
×
426
      di.notified_serial = i.d_lastnotified;
×
427
      di.backend = this;
×
428
      di.kind = DomainInfo::Primary;
×
429
      consider.push_back(std::move(di));
×
430
    }
×
431
  }
×
432

433
  SOAData soadata;
×
434
  for (DomainInfo& di : consider) {
×
435
    soadata.serial = 0;
×
436
    try {
×
437
      this->getSOA(di.zone, di.id, soadata); // we might not *have* a SOA yet, but this might trigger a load of it
×
438
    }
×
439
    catch (...) {
×
440
      continue;
×
441
    }
×
442
    if (di.notified_serial != soadata.serial) {
×
443
      BB2DomainInfo bbd;
×
444
      if (safeGetBBDomainInfo(di.id, &bbd)) {
×
445
        bbd.d_lastnotified = soadata.serial;
×
446
        safePutBBDomainInfo(bbd);
×
447
      }
×
448
      if (di.notified_serial) { // don't do notification storm on startup
×
449
        di.serial = soadata.serial;
×
450
        changedDomains.push_back(std::move(di));
×
451
      }
×
452
    }
×
453
  }
×
454
}
×
455

456
void Bind2Backend::getAllDomains(vector<DomainInfo>* domains, bool getSerial, bool /* include_disabled */)
457
{
119✔
458
  SOAData soadata;
119✔
459

460
  // prevent deadlock by using getSOA() later on
461
  {
119✔
462
    auto state = s_state.read_lock();
119✔
463
    domains->reserve(state->size());
119✔
464

465
    for (const auto& i : *state) {
279✔
466
      DomainInfo di;
185✔
467
      di.id = i.d_id;
185✔
468
      di.zone = i.d_name;
185✔
469
      di.last_check = i.d_lastcheck;
185✔
470
      di.kind = i.d_kind;
185✔
471
      di.primaries = i.d_primaries;
185✔
472
      di.backend = this;
185✔
473
      domains->push_back(std::move(di));
185✔
474
    };
185✔
475
  }
119✔
476

477
  if (getSerial) {
119✔
478
    for (DomainInfo& di : *domains) {
1,509✔
479
      // do not corrupt di if domain supplied by another backend.
480
      if (di.backend != this)
1,509!
481
        continue;
1,509✔
482
      try {
×
483
        this->getSOA(di.zone, di.id, soadata);
×
484
      }
×
485
      catch (...) {
×
486
        continue;
×
487
      }
×
488
      di.serial = soadata.serial;
×
489
    }
×
490
  }
42✔
491
}
119✔
492

493
void Bind2Backend::getUnfreshSecondaryInfos(vector<DomainInfo>* unfreshDomains)
494
{
8✔
495
  vector<DomainInfo> domains;
8✔
496
  {
8✔
497
    auto state = s_state.read_lock();
8✔
498
    domains.reserve(state->size());
8✔
499
    for (const auto& i : *state) {
72✔
500
      if (i.d_kind != DomainInfo::Secondary)
72!
501
        continue;
×
502
      DomainInfo sd;
72✔
503
      sd.id = i.d_id;
72✔
504
      sd.zone = i.d_name;
72✔
505
      sd.primaries = i.d_primaries;
72✔
506
      sd.last_check = i.d_lastcheck;
72✔
507
      sd.backend = this;
72✔
508
      sd.kind = DomainInfo::Secondary;
72✔
509
      domains.push_back(std::move(sd));
72✔
510
    }
72✔
511
  }
8✔
512
  unfreshDomains->reserve(domains.size());
8✔
513

514
  for (DomainInfo& sd : domains) {
72✔
515
    SOAData soadata;
72✔
516
    soadata.refresh = 0;
72✔
517
    soadata.serial = 0;
72✔
518
    try {
72✔
519
      getSOA(sd.zone, sd.id, soadata); // we might not *have* a SOA yet
72✔
520
    }
72✔
521
    catch (...) {
72✔
522
    }
72✔
523
    sd.serial = soadata.serial;
72✔
524
    if (sd.last_check + soadata.refresh < time(nullptr))
72!
525
      unfreshDomains->push_back(std::move(sd));
72✔
526
  }
72✔
527
}
8✔
528

529
bool Bind2Backend::getDomainInfo(const ZoneName& domain, DomainInfo& info, bool getSerial)
530
{
1,080✔
531
  BB2DomainInfo bbd;
1,080✔
532
  if (!safeGetBBDomainInfo(domain, &bbd))
1,080✔
533
    return false;
635✔
534

535
  info.id = bbd.d_id;
445✔
536
  info.zone = domain;
445✔
537
  info.primaries = bbd.d_primaries;
445✔
538
  info.last_check = bbd.d_lastcheck;
445✔
539
  info.backend = this;
445✔
540
  info.kind = bbd.d_kind;
445✔
541
  info.serial = 0;
445✔
542
  if (getSerial) {
445✔
543
    try {
135✔
544
      SOAData sd;
135✔
545
      sd.serial = 0;
135✔
546

547
      getSOA(bbd.d_name, bbd.d_id, sd); // we might not *have* a SOA yet
135✔
548
      info.serial = sd.serial;
135✔
549
    }
135✔
550
    catch (...) {
135✔
551
    }
72✔
552
  }
135✔
553

554
  return true;
445✔
555
}
445✔
556

557
void Bind2Backend::alsoNotifies(const ZoneName& domain, set<string>* ips)
558
{
4✔
559
  // combine global list with local list
560
  for (const auto& i : this->alsoNotify) {
4!
561
    (*ips).insert(i);
×
562
  }
×
563
  // check metadata too if available
564
  vector<string> meta;
4✔
565
  if (getDomainMetadata(domain, "ALSO-NOTIFY", meta)) {
4!
566
    for (const auto& str : meta) {
×
567
      (*ips).insert(str);
×
568
    }
×
569
  }
×
570
  auto state = s_state.read_lock();
4✔
571
  for (const auto& i : *state) {
4!
572
    if (i.d_name == domain) {
×
573
      for (const auto& it : i.d_also_notify) {
×
574
        (*ips).insert(it);
×
575
      }
×
576
      return;
×
577
    }
×
578
  }
×
579
}
4✔
580

581
// only parses, does NOT add to s_state!
582
void Bind2Backend::parseZoneFile(BB2DomainInfo* bbd)
583
{
2,737✔
584
  NSEC3PARAMRecordContent ns3pr;
2,737✔
585
  bool nsec3zone = false;
2,737✔
586
  if (d_hybrid) {
2,737!
587
    DNSSECKeeper dk(d_slog);
×
588
    nsec3zone = dk.getNSEC3PARAM(bbd->d_name, &ns3pr);
×
589
  }
×
590
  else
2,737✔
591
    nsec3zone = getNSEC3PARAMuncached(bbd->d_name, &ns3pr);
2,737✔
592

593
  auto records = std::make_shared<recordstorage_t>();
2,737✔
594
  ZoneParserTNG zpt(bbd->main_filename(), bbd->d_name, s_binddirectory, d_upgradeContent);
2,737✔
595
  zpt.setMaxGenerateSteps(::arg().asNum("max-generate-steps"));
2,737✔
596
  zpt.setMaxIncludes(::arg().asNum("max-include-depth"));
2,737✔
597
  DNSResourceRecord rr;
2,737✔
598
  string hashed;
2,737✔
599
  while (zpt.get(rr)) {
3,277,596✔
600
    if (rr.qtype.getCode() == QType::NSEC || rr.qtype.getCode() == QType::NSEC3 || rr.qtype.getCode() == QType::NSEC3PARAM)
3,274,859!
601
      continue; // we synthesise NSECs on demand
×
602

603
    insertRecord(records, bbd->d_name, rr.qname, rr.qtype, rr.content, rr.ttl, "");
3,274,859✔
604
  }
3,274,859✔
605
  fixupOrderAndAuth(records, bbd->d_name, nsec3zone, ns3pr);
2,737✔
606
  doEmptyNonTerminals(records, bbd->d_name, nsec3zone, ns3pr);
2,737✔
607
  bbd->d_fileinfo = zpt.getFileset();
2,737✔
608
  bbd->d_loaded = true;
2,737✔
609
  bbd->d_checknow = false;
2,737✔
610
  bbd->d_status = "parsed into memory at " + nowTime();
2,737✔
611
  bbd->d_records = LookButDontTouch<recordstorage_t>(std::move(records));
2,737✔
612
  bbd->d_nsec3zone = nsec3zone;
2,737✔
613
  bbd->d_nsec3param = std::move(ns3pr);
2,737✔
614
}
2,737✔
615

616
/** THIS IS AN INTERNAL FUNCTION! It does moadnsparser prio impedance matching
617
    Much of the complication is due to the efforts to benefit from std::string reference counting copy on write semantics */
618
void Bind2Backend::insertRecord(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, const DNSName& qname, const QType& qtype, const string& content, int ttl, const std::string& hashed, const bool* auth)
619
{
3,279,630✔
620
  Bind2DNSRecord bdr;
3,279,630✔
621
  bdr.qname = qname;
3,279,630✔
622

623
  if (zoneName.empty())
3,279,630!
624
    ;
×
625
  else if (bdr.qname.isPartOf(zoneName))
3,279,630✔
626
    bdr.qname.makeUsRelative(zoneName);
3,279,328✔
627
  else {
302✔
628
    string msg = "Trying to insert non-zone data, name='" + bdr.qname.toLogString() + "', qtype=" + qtype.toString() + ", zone='" + zoneName.toLogString() + "'";
302✔
629
    if (s_ignore_broken_records) {
302!
630
      SLOG(g_log << Logger::Warning << msg << " ignored" << endl,
302!
631
           d_slog->info(Logr::Warning, "Non-zone data record ignored", "zone", Logging::Loggable(zoneName), "name", Logging::Loggable(bdr.qname), "qtype", Logging::Loggable(qtype)));
302✔
632
      return;
302✔
633
    }
302✔
634
    throw PDNSException(std::move(msg));
×
635
  }
302✔
636

637
  //  bdr.qname.swap(bdr.qname);
638

639
  if (!records->empty() && bdr.qname == boost::prior(records->end())->qname)
3,279,328✔
640
    bdr.qname = boost::prior(records->end())->qname;
8,853✔
641

642
  bdr.qname = bdr.qname;
3,279,328✔
643
  bdr.qtype = qtype.getCode();
3,279,328✔
644
  bdr.content = content;
3,279,328✔
645
  bdr.nsec3hash = hashed;
3,279,328✔
646

647
  if (auth != nullptr) // Set auth on empty non-terminals
3,279,328✔
648
    bdr.auth = *auth;
4,771✔
649
  else
3,274,557✔
650
    bdr.auth = true;
3,274,557✔
651

652
  bdr.ttl = ttl;
3,279,328✔
653
  records->insert(std::move(bdr));
3,279,328✔
654
}
3,279,328✔
655

656
string Bind2Backend::DLReloadNowHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
657
{
×
658
  ostringstream ret;
×
659

660
  for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
661
    BB2DomainInfo bbd;
×
662
    ZoneName zone(*i);
×
663
    if (safeGetBBDomainInfo(zone, &bbd)) {
×
664
      Bind2Backend bb2;
×
665
      bb2.queueReloadAndStore(bbd.d_id);
×
666
      if (!safeGetBBDomainInfo(zone, &bbd)) // Read the *new* domain status
×
667
        ret << *i << ": [missing]\n";
×
668
      else
×
669
        ret << *i << ": " << (bbd.d_wasRejectedLastReload ? "[rejected]" : "") << "\t" << bbd.d_status << "\n";
×
670
      purgeAuthCaches(zone.operator const DNSName&().toString() + "$");
×
671
      DNSSECKeeper::clearMetaCache(zone);
×
672
    }
×
673
    else
×
674
      ret << *i << " no such domain\n";
×
675
  }
×
676
  if (ret.str().empty())
×
677
    ret << "no domains reloaded";
×
678
  return ret.str();
×
679
}
×
680

681
string Bind2Backend::DLDomStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
682
{
27✔
683
  ostringstream ret;
27✔
684

685
  if (parts.size() > 1) {
27!
686
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
687
      BB2DomainInfo bbd;
×
688
      if (safeGetBBDomainInfo(ZoneName(*i), &bbd)) {
×
689
        ret << *i << ": " << (bbd.d_loaded ? "" : "[rejected]") << "\t" << bbd.d_status << "\n";
×
690
      }
×
691
      else {
×
692
        ret << *i << " no such domain\n";
×
693
      }
×
694
    }
×
695
  }
×
696
  else {
27✔
697
    auto state = s_state.read_lock();
27✔
698
    for (const auto& i : *state) {
235✔
699
      ret << i.d_name << ": " << (i.d_loaded ? "" : "[rejected]") << "\t" << i.d_status << "\n";
235✔
700
    }
235✔
701
  }
27✔
702

703
  if (ret.str().empty())
27!
704
    ret << "no domains passed";
×
705

706
  return ret.str();
27✔
707
}
27✔
708

709
static void printDomainExtendedStatus(ostringstream& ret, const BB2DomainInfo& info)
710
{
×
711
  ret << info.d_name << ": " << std::endl;
×
712
  ret << "\t Status: " << info.d_status << std::endl;
×
713
  ret << "\t Internal ID: " << info.d_id << std::endl;
×
714
  ret << "\t On-disk file: " << info.main_filename() << " (" << info.d_fileinfo.front().second << ")" << std::endl;
×
715
  ret << "\t Kind: ";
×
716
  switch (info.d_kind) {
×
717
  case DomainInfo::Primary:
×
718
    ret << "Primary";
×
719
    break;
×
720
  case DomainInfo::Secondary:
×
721
    ret << "Secondary";
×
722
    break;
×
723
  default:
×
724
    ret << "Native";
×
725
  }
×
726
  ret << std::endl;
×
727
  ret << "\t Primaries: " << std::endl;
×
728
  for (const auto& primary : info.d_primaries) {
×
729
    ret << "\t\t - " << primary.toStringWithPort() << std::endl;
×
730
  }
×
731
  ret << "\t Also Notify: " << std::endl;
×
732
  for (const auto& also : info.d_also_notify) {
×
733
    ret << "\t\t - " << also << std::endl;
×
734
  }
×
735
  ret << "\t Number of records: " << info.d_records.getEntriesCount() << std::endl;
×
736
  ret << "\t Loaded: " << info.d_loaded << std::endl;
×
737
  ret << "\t Check now: " << info.d_checknow << std::endl;
×
738
  ret << "\t Check interval: " << info.getCheckInterval() << std::endl;
×
739
  ret << "\t Last check: " << info.d_lastcheck << std::endl;
×
740
  ret << "\t Last notified: " << info.d_lastnotified << std::endl;
×
741
}
×
742

743
string Bind2Backend::DLDomExtendedStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
744
{
×
745
  ostringstream ret;
×
746

747
  if (parts.size() > 1) {
×
748
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
749
      BB2DomainInfo bbd;
×
750
      if (safeGetBBDomainInfo(ZoneName(*i), &bbd)) {
×
751
        printDomainExtendedStatus(ret, bbd);
×
752
      }
×
753
      else {
×
754
        ret << *i << " no such domain" << std::endl;
×
755
      }
×
756
    }
×
757
  }
×
758
  else {
×
759
    auto rstate = s_state.read_lock();
×
760
    for (const auto& state : *rstate) {
×
761
      printDomainExtendedStatus(ret, state);
×
762
    }
×
763
  }
×
764

765
  if (ret.str().empty()) {
×
766
    ret << "no domains passed" << std::endl;
×
767
  }
×
768

769
  return ret.str();
×
770
}
×
771

772
string Bind2Backend::DLListRejectsHandler(const vector<string>& /* parts */, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
773
{
×
774
  ostringstream ret;
×
775
  auto rstate = s_state.read_lock();
×
776
  for (const auto& i : *rstate) {
×
777
    if (!i.d_loaded)
×
778
      ret << i.d_name << "\t" << i.d_status << endl;
×
779
  }
×
780
  return ret.str();
×
781
}
×
782

783
string Bind2Backend::DLAddDomainHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
784
{
12✔
785
  if (parts.size() < 3)
12!
786
    return "ERROR: Domain name and zone filename are required";
×
787

788
  ZoneName domainname(parts[1]);
12✔
789
  const string& filename = parts[2];
12✔
790
  BB2DomainInfo bbd;
12✔
791
  if (safeGetBBDomainInfo(domainname, &bbd))
12✔
792
    return "Already loaded";
6✔
793

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

797
  struct stat buf;
6✔
798
  if (stat(filename.c_str(), &buf) != 0)
6!
799
    return "Unable to load zone " + domainname.toLogString() + " from " + filename + ": " + strerror(errno);
×
800

801
  Bind2Backend bb2; // createdomainentry needs access to our configuration
6✔
802
  bbd = bb2.createDomainEntry(domainname);
6✔
803
  bbd.d_fileinfo.emplace_back(std::make_pair(filename, buf.st_ctime));
6✔
804
  bbd.d_checknow = true;
6✔
805
  bbd.d_loaded = true;
6✔
806
  bbd.d_lastcheck = 0;
6✔
807
  bbd.d_status = "parsing into memory";
6✔
808

809
  safePutBBDomainInfo(bbd);
6✔
810

811
  g_zoneCache.add(domainname, bbd.d_id); // make new zone visible
6✔
812

813
  SLOG(g_log << Logger::Warning << "Zone " << domainname << " loaded" << endl,
6!
814
       bb2.d_slog->info(Logr::Info, "Zone loaded", "zone", Logging::Loggable(domainname), "file", Logging::Loggable(filename)));
6✔
815
  return "Loaded zone " + domainname.toLogString() + " from " + filename;
6✔
816
}
6✔
817

818
Bind2Backend::Bind2Backend(const string& suffix, bool loadZones)
819
{
3,460✔
820
  d_getAllDomainMetadataQuery_stmt = nullptr;
3,460✔
821
  d_getDomainMetadataQuery_stmt = nullptr;
3,460✔
822
  d_deleteDomainMetadataQuery_stmt = nullptr;
3,460✔
823
  d_insertDomainMetadataQuery_stmt = nullptr;
3,460✔
824
  d_getDomainKeysQuery_stmt = nullptr;
3,460✔
825
  d_deleteDomainKeyQuery_stmt = nullptr;
3,460✔
826
  d_insertDomainKeyQuery_stmt = nullptr;
3,460✔
827
  d_GetLastInsertedKeyIdQuery_stmt = nullptr;
3,460✔
828
  d_activateDomainKeyQuery_stmt = nullptr;
3,460✔
829
  d_deactivateDomainKeyQuery_stmt = nullptr;
3,460✔
830
  d_getTSIGKeyQuery_stmt = nullptr;
3,460✔
831
  d_setTSIGKeyQuery_stmt = nullptr;
3,460✔
832
  d_deleteTSIGKeyQuery_stmt = nullptr;
3,460✔
833
  d_getTSIGKeysQuery_stmt = nullptr;
3,460✔
834

835
  setArgPrefix("bind" + suffix);
3,460✔
836
  d_logprefix = "[bind" + suffix + "backend]";
3,460✔
837
  if (g_slogStructured) {
3,460!
838
    d_slog = g_slog->withName("bind" + suffix);
×
839
    d_handle.setSLog(d_slog);
×
840
  }
×
841
  d_hybrid = mustDo("hybrid");
3,460✔
842
  if (d_hybrid && g_zoneCache.isEnabled()) {
3,460!
843
    throw PDNSException("bind-hybrid and the zone cache currently interoperate badly. Please disable the zone cache or stop using bind-hybrid");
×
844
  }
×
845

846
  d_transaction_id = UnknownDomainID;
3,460✔
847
  s_ignore_broken_records = mustDo("ignore-broken-records");
3,460✔
848
  d_upgradeContent = ::arg().mustDo("upgrade-unknown-types");
3,460✔
849

850
  if (!loadZones && d_hybrid)
3,460!
851
    return;
×
852

853
  auto lock = std::scoped_lock(s_startup_lock);
3,460✔
854

855
  setupDNSSEC();
3,460✔
856
  if (s_first == 0) {
3,460✔
857
    return;
2,699✔
858
  }
2,699✔
859

860
  if (loadZones) {
761✔
861
    loadConfig();
311✔
862
    s_first = 0;
311✔
863
  }
311✔
864

865
  DynListener::registerFunc("BIND-ADD-ZONE", &DLAddDomainHandler, "bindbackend: add zone", "<domain> <filename>");
761✔
866
  DynListener::registerFunc("BIND-DOMAIN-EXTENDED-STATUS", &DLDomExtendedStatusHandler, "bindbackend: list the extended status of all domains", "[domains]");
761✔
867
  DynListener::registerFunc("BIND-DOMAIN-STATUS", &DLDomStatusHandler, "bindbackend: list status of all domains", "[domains]");
761✔
868
  DynListener::registerFunc("BIND-LIST-REJECTS", &DLListRejectsHandler, "bindbackend: list rejected domains");
761✔
869
  DynListener::registerFunc("BIND-RELOAD-NOW", &DLReloadNowHandler, "bindbackend: reload domains", "<domains>");
761✔
870
}
761✔
871

872
Bind2Backend::~Bind2Backend()
873
{
3,335✔
874
  freeStatements();
3,335✔
875
} // deallocate statements
3,335✔
876

877
void Bind2Backend::rediscover(string* status)
878
{
×
879
  loadConfig(status);
×
880
}
×
881

882
void Bind2Backend::reload()
883
{
×
884
  auto state = s_state.write_lock();
×
885
  for (const auto& i : *state) {
×
886
    i.d_checknow = true; // being a bit cheeky here, don't index state_t on this (mutable)
×
887
  }
×
888
}
×
889

890
void Bind2Backend::fixupOrderAndAuth(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
891
{
2,665✔
892
  bool skip;
2,665✔
893
  DNSName shorter;
2,665✔
894
  set<DNSName> nssets, dssets;
2,665✔
895

896
  for (const auto& bdr : *records) {
3,274,557✔
897
    if (!bdr.qname.isRoot() && bdr.qtype == QType::NS)
3,274,557✔
898
      nssets.insert(bdr.qname);
3,010✔
899
    else if (bdr.qtype == QType::DS)
3,271,547✔
900
      dssets.insert(bdr.qname);
499✔
901
  }
3,274,557✔
902

903
  for (auto iter = records->begin(); iter != records->end(); iter++) {
3,277,222✔
904
    skip = false;
3,274,557✔
905
    shorter = iter->qname;
3,274,557✔
906

907
    if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
3,274,557!
908
      do {
3,273,483✔
909
        if (nssets.count(shorter) != 0u) {
3,273,483✔
910
          skip = true;
1,359✔
911
          break;
1,359✔
912
        }
1,359✔
913
      } while (shorter.chopOff() && !iter->qname.isRoot());
3,273,483!
914
    }
3,263,426✔
915

916
    iter->auth = (!skip && (iter->qtype == QType::DS || iter->qtype == QType::RRSIG || (nssets.count(iter->qname) == 0u)));
3,274,557✔
917

918
    if (!skip && nsec3zone && iter->qtype != QType::RRSIG && (iter->auth || (iter->qtype == QType::NS && (ns3pr.d_flags == 0u)) || (dssets.count(iter->qname) != 0u))) {
3,274,557✔
919
      Bind2DNSRecord bdr = *iter;
1,439,658✔
920
      bdr.nsec3hash = toBase32Hex(hashQNameWithSalt(ns3pr, bdr.qname + zoneName.operator const DNSName&()));
1,439,658✔
921
      records->replace(iter, bdr);
1,439,658✔
922
    }
1,439,658✔
923

924
    // cerr<<iter->qname<<"\t"<<QType(iter->qtype).toString()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
925
  }
3,274,557✔
926
}
2,665✔
927

928
void Bind2Backend::doEmptyNonTerminals(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
929
{
2,665✔
930
  bool auth = false;
2,665✔
931
  DNSName shorter;
2,665✔
932
  std::unordered_set<DNSName> qnames;
2,665✔
933
  std::unordered_map<DNSName, bool> nonterm;
2,665✔
934

935
  uint32_t maxent = ::arg().asNum("max-ent-entries");
2,665✔
936

937
  for (const auto& bdr : *records)
2,665✔
938
    qnames.insert(bdr.qname);
3,274,557✔
939

940
  for (const auto& bdr : *records) {
3,274,557✔
941

942
    if (!bdr.auth && bdr.qtype == QType::NS)
3,274,557✔
943
      auth = (!nsec3zone || (ns3pr.d_flags == 0u));
3,010✔
944
    else
3,271,547✔
945
      auth = bdr.auth;
3,271,547✔
946

947
    shorter = bdr.qname;
3,274,557✔
948
    while (shorter.chopOff()) {
6,549,399✔
949
      if (qnames.count(shorter) == 0u) {
3,274,842✔
950
        if (!(maxent)) {
9,891!
951
          SLOG(g_log << Logger::Error << "Zone '" << zoneName << "' has too many empty non terminals." << endl,
×
952
               d_slog->info(Logr::Error, "Zone has too many empty non terminals.", "zone", Logging::Loggable(zoneName)));
×
953
          return;
×
954
        }
×
955

956
        if (nonterm.count(shorter) == 0u) {
9,891✔
957
          nonterm.emplace(shorter, auth);
4,771✔
958
          --maxent;
4,771✔
959
        }
4,771✔
960
        else if (auth)
5,120✔
961
          nonterm[shorter] = true;
5,024✔
962
      }
9,891✔
963
    }
3,274,842✔
964
  }
3,274,557✔
965

966
  DNSResourceRecord rr;
2,665✔
967
  rr.qtype = "#0";
2,665✔
968
  rr.content = "";
2,665✔
969
  rr.ttl = 0;
2,665✔
970
  for (auto& nt : nonterm) {
4,772✔
971
    string hashed;
4,771✔
972
    rr.qname = nt.first + zoneName.operator const DNSName&();
4,771✔
973
    if (nsec3zone && nt.second)
4,771✔
974
      hashed = toBase32Hex(hashQNameWithSalt(ns3pr, rr.qname));
1,853✔
975
    insertRecord(records, zoneName, rr.qname, rr.qtype, rr.content, rr.ttl, hashed, &nt.second);
4,771✔
976

977
    // cerr<<rr.qname<<"\t"<<rr.qtype.toString()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
978
  }
4,771✔
979
}
2,665✔
980

981
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
982
{
311✔
983
  static domainid_t domain_id = 1;
311✔
984

985
  if (!getArg("config").empty()) {
311!
986
    BindParser BP;
311✔
987
    try {
311✔
988
      BP.parse(getArg("config"));
311✔
989
    }
311✔
990
    catch (PDNSException& ae) {
311✔
991
      SLOG(g_log << Logger::Error << "Error parsing bind configuration: " << ae.reason << endl,
×
992
           d_slog->error(Logr::Error, ae.reason, "Error parsing bind configuration"));
×
993
      throw;
×
994
    }
×
995

996
    vector<BindDomainInfo> domains = BP.getDomains();
311✔
997
    this->alsoNotify = BP.getAlsoNotify();
311✔
998

999
    s_binddirectory = BP.getDirectory();
311✔
1000
    //    ZP.setDirectory(d_binddirectory);
1001

1002
    SLOG(g_log << Logger::Warning << d_logprefix << " Parsing " << domains.size() << " domain(s), will report when done" << endl,
311!
1003
         d_slog->info(Logr::Info, "Parsing " + std::to_string(domains.size()) + " domain(s), will report when done"));
311✔
1004

1005
    set<ZoneName> oldnames;
311✔
1006
    set<ZoneName> newnames;
311✔
1007
    {
311✔
1008
      auto state = s_state.read_lock();
311✔
1009
      for (const BB2DomainInfo& bbd : *state) {
311!
1010
        oldnames.insert(bbd.d_name);
×
1011
      }
×
1012
    }
311✔
1013
    int rejected = 0;
311✔
1014
    int newdomains = 0;
311✔
1015

1016
    struct stat st;
311✔
1017

1018
    for (auto& domain : domains) {
2,791✔
1019
      if (stat(domain.filename.c_str(), &st) == 0) {
2,659✔
1020
        domain.d_dev = st.st_dev;
2,587✔
1021
        domain.d_ino = st.st_ino;
2,587✔
1022
      }
2,587✔
1023
    }
2,659✔
1024

1025
    sort(domains.begin(), domains.end()); // put stuff in inode order
311✔
1026
    for (const auto& domain : domains) {
2,791✔
1027
      if (!(domain.hadFileDirective)) {
2,659!
1028
        SLOG(g_log << Logger::Warning << d_logprefix << " Zone '" << domain.name << "' has no 'file' directive set in " << getArg("config") << endl,
×
1029
             d_slog->info(Logr::Warning, "Zone has no 'file' directive set", "zone", Logging::Loggable(domain.name), "filename", Logging::Loggable(getArg("config"))));
×
1030
        rejected++;
×
1031
        continue;
×
1032
      }
×
1033

1034
      if (domain.type.empty()) {
2,659!
1035
        SLOG(g_log << Logger::Notice << d_logprefix << " Zone '" << domain.name << "' has no type specified, assuming 'native'" << endl,
×
1036
             d_slog->info(Logr::Notice, "Zone has no type specified, assuming 'native'", "zone", Logging::Loggable(domain.name)));
×
1037
      }
×
1038
      if (domain.type != "primary" && domain.type != "secondary" && domain.type != "native" && !domain.type.empty() && domain.type != "master" && domain.type != "slave") {
2,659!
1039
        SLOG(g_log << Logger::Warning << d_logprefix << " Warning! Skipping zone '" << domain.name << "' because type '" << domain.type << "' is invalid" << endl,
×
1040
             d_slog->info(Logr::Warning, "Skipping zone because type is invalid", "zone", Logging::Loggable(domain.name), "type", Logging::Loggable(domain.type)));
×
1041
        rejected++;
×
1042
        continue;
×
1043
      }
×
1044

1045
      BB2DomainInfo bbd;
2,659✔
1046
      bool isNew = false;
2,659✔
1047

1048
      if (!safeGetBBDomainInfo(domain.name, &bbd)) {
2,659!
1049
        isNew = true;
2,659✔
1050
        bbd.d_id = domain_id++;
2,659✔
1051
        bbd.setCheckInterval(getArgAsNum("check-interval"));
2,659✔
1052
        bbd.d_lastnotified = 0;
2,659✔
1053
        bbd.d_loaded = false;
2,659✔
1054
      }
2,659✔
1055

1056
      // overwrite what we knew about the domain
1057
      bbd.d_name = domain.name;
2,659✔
1058
      bool filenameChanged = bbd.d_fileinfo.empty() || (bbd.main_filename() != domain.filename);
2,659!
1059
      bool addressesChanged = (bbd.d_primaries != domain.primaries || bbd.d_also_notify != domain.alsoNotify);
2,659!
1060
      // Preserve existing fileinfo in case we won't reread anything.
1061
      if (filenameChanged) {
2,659!
1062
        bbd.d_fileinfo.clear();
2,659✔
1063
        bbd.d_fileinfo.emplace_back(std::make_pair(domain.filename, 0));
2,659✔
1064
      }
2,659✔
1065
      bbd.d_primaries = domain.primaries;
2,659✔
1066
      bbd.d_also_notify = domain.alsoNotify;
2,659✔
1067

1068
      DomainInfo::DomainKind kind = DomainInfo::Native;
2,659✔
1069
      if (domain.type == "primary" || domain.type == "master") {
2,659!
1070
        kind = DomainInfo::Primary;
2,587✔
1071
      }
2,587✔
1072
      if (domain.type == "secondary" || domain.type == "slave") {
2,659!
1073
        kind = DomainInfo::Secondary;
72✔
1074
      }
72✔
1075

1076
      bool kindChanged = (bbd.d_kind != kind);
2,659✔
1077
      bbd.d_kind = kind;
2,659✔
1078

1079
      newnames.insert(bbd.d_name);
2,659✔
1080
      if (filenameChanged || !bbd.d_loaded || !bbd.current()) {
2,659!
1081
        SLOG(g_log << Logger::Info << d_logprefix << " parsing '" << domain.name << "' from file '" << domain.filename << "'" << endl,
2,659!
1082
             d_slog->info(Logr::Info, "Parsing zone from file", "zone", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
2,659✔
1083

1084
        try {
2,659✔
1085
          parseZoneFile(&bbd);
2,659✔
1086
        }
2,659✔
1087
        catch (PDNSException& ae) {
2,659✔
1088
          ostringstream msg;
×
1089
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.reason;
×
1090

1091
          if (status != nullptr)
×
1092
            *status += msg.str();
×
1093
          bbd.d_status = msg.str();
×
1094

1095
          SLOG(g_log << Logger::Warning << d_logprefix << msg.str() << endl,
×
1096
               d_slog->error(Logr::Error, ae.reason, "Error in zone file", "zone", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
×
1097
          rejected++;
×
1098
        }
×
1099
        catch (std::system_error& ae) {
2,659✔
1100
          ostringstream msg;
72✔
1101
          bool missingNewSecondary = ae.code().value() == ENOENT && isNew && kind == DomainInfo::Secondary;
72!
1102
          if (missingNewSecondary) {
72!
1103
            msg << " error at " + nowTime() << " no file found for new secondary domain '" << domain.name << "'. Has not been AXFR'd yet";
72✔
1104
          }
72✔
1105
          else {
×
1106
            msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
×
1107
          }
×
1108

1109
          if (status != nullptr)
72!
1110
            *status += msg.str();
×
1111
          bbd.d_status = msg.str();
72✔
1112
          SLOG(
72!
1113
            g_log << Logger::Warning << d_logprefix << msg.str() << endl,
72✔
1114
            if (missingNewSecondary) {
72✔
1115
              d_slog->error(Logr::Warning, ae.what(), "Secondary domain has not been AXFR'd yet", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename));
72✔
1116
            } else {
72✔
1117
              d_slog->error(Logr::Warning, ae.what(), "Parse error", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename));
72✔
1118
            });
72✔
1119
          rejected++;
72✔
1120
        }
72✔
1121
        catch (std::exception& ae) {
2,659✔
1122
          ostringstream msg;
×
1123
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
×
1124

1125
          if (status != nullptr)
×
1126
            *status += msg.str();
×
1127
          bbd.d_status = msg.str();
×
1128

1129
          SLOG(g_log << Logger::Warning << d_logprefix << msg.str() << endl,
×
1130
               d_slog->error(Logr::Warning, ae.what(), "Parse error", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
×
1131
          rejected++;
×
1132
        }
×
1133
        safePutBBDomainInfo(bbd);
2,659✔
1134
      }
2,659✔
1135
      else if (addressesChanged || kindChanged) {
×
1136
        safePutBBDomainInfo(bbd);
×
1137
      }
×
1138
    }
2,659✔
1139
    vector<ZoneName> diff;
311✔
1140

1141
    set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
311✔
1142
    unsigned int remdomains = diff.size();
311✔
1143

1144
    for (const ZoneName& name : diff) {
311!
1145
      safeRemoveBBDomainInfo(name);
×
1146
    }
×
1147

1148
    // count number of entirely new domains
1149
    diff.clear();
311✔
1150
    set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
311✔
1151
    newdomains = diff.size();
311✔
1152

1153
    ostringstream msg;
311✔
1154
    msg << " Done parsing domains, " << rejected << " rejected, " << newdomains << " new, " << remdomains << " removed";
311✔
1155
    if (status != nullptr)
311!
1156
      *status = msg.str();
×
1157

1158
    SLOG(
311!
1159
      g_log << Logger::Error << d_logprefix << msg.str() << endl,
311✔
1160
      if (rejected == 0) {
311✔
1161
        d_slog->info(Logr::Info, "Done parsing domains", "new", Logging::Loggable(newdomains), "removed", Logging::Loggable(remdomains));
311✔
1162
      } else {
311✔
1163
        d_slog->info(Logr::Error, "Done parsing domains", "new", Logging::Loggable(newdomains), "removed", Logging::Loggable(remdomains), "rejected", Logging::Loggable(rejected));
311✔
1164
      });
311✔
1165
  }
311✔
1166
}
311✔
1167

1168
// NOLINTNEXTLINE(readability-identifier-length)
1169
void Bind2Backend::queueReloadAndStore(domainid_t id)
1170
{
78✔
1171
  BB2DomainInfo bbold;
78✔
1172
  try {
78✔
1173
    if (!safeGetBBDomainInfo(id, &bbold))
78!
1174
      return;
×
1175
    bbold.d_checknow = false;
78✔
1176
    BB2DomainInfo bbnew(bbold);
78✔
1177
    /* make sure that nothing will be able to alter the existing records,
1178
       we will load them from the zone file instead */
1179
    bbnew.d_records = LookButDontTouch<recordstorage_t>();
78✔
1180
    parseZoneFile(&bbnew);
78✔
1181
    bbnew.d_wasRejectedLastReload = false;
78✔
1182
    safePutBBDomainInfo(bbnew);
78✔
1183
    SLOG(g_log << Logger::Warning << "Zone '" << bbnew.d_name << "' (" << bbnew.main_filename() << ") reloaded" << endl,
78!
1184
         d_slog->info(Logr::Info, "Zone reloaded", "zone", Logging::Loggable(bbnew.d_name), "file", Logging::Loggable(bbnew.main_filename())));
78✔
1185
  }
78✔
1186
  catch (PDNSException& ae) {
78✔
1187
    ostringstream msg;
×
1188
    msg << " error at " + nowTime() + " parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.reason;
×
1189
    SLOG(g_log << Logger::Warning << "Error parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.reason << endl,
×
1190
         d_slog->error(Logr::Error, ae.reason, "Error reloading zone", "zone", Logging::Loggable(bbold.d_name), "file", Logging::Loggable(bbold.main_filename())));
×
1191
    bbold.d_status = msg.str();
×
1192
    bbold.d_lastcheck = time(nullptr);
×
1193
    bbold.d_wasRejectedLastReload = true;
×
1194
    safePutBBDomainInfo(bbold);
×
1195
  }
×
1196
  catch (std::exception& ae) {
78✔
1197
    ostringstream msg;
×
1198
    msg << " error at " + nowTime() + " parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.what();
×
1199
    SLOG(g_log << Logger::Warning << "Error parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.what() << endl,
×
1200
         d_slog->error(Logr::Error, ae.what(), "Error reloading zone", "zone", Logging::Loggable(bbold.d_name), "file", Logging::Loggable(bbold.main_filename())));
×
1201
    bbold.d_status = msg.str();
×
1202
    bbold.d_lastcheck = time(nullptr);
×
1203
    bbold.d_wasRejectedLastReload = true;
×
1204
    safePutBBDomainInfo(bbold);
×
1205
  }
×
1206
}
78✔
1207

1208
bool Bind2Backend::findBeforeAndAfterUnhashed(std::shared_ptr<const recordstorage_t>& records, const DNSName& qname, DNSName& /* unhashed */, DNSName& before, DNSName& after)
1209
{
2,713✔
1210
  // for(const auto& record: *records)
1211
  //   cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
1212

1213
  recordstorage_t::const_iterator iterBefore, iterAfter;
2,713✔
1214

1215
  iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
2,713✔
1216

1217
  if (iterBefore != records->begin())
2,713✔
1218
    --iterBefore;
2,714✔
1219
  while ((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
3,242✔
1220
    --iterBefore;
529✔
1221
  before = iterBefore->qname;
2,713✔
1222

1223
  if (iterAfter == records->end()) {
2,713✔
1224
    iterAfter = records->begin();
376✔
1225
  }
376✔
1226
  else {
2,337✔
1227
    while ((!iterAfter->auth && iterAfter->qtype != QType::NS) || !iterAfter->qtype) {
3,520✔
1228
      ++iterAfter;
1,183✔
1229
      if (iterAfter == records->end()) {
1,183!
1230
        iterAfter = records->begin();
×
1231
        break;
×
1232
      }
×
1233
    }
1,183✔
1234
  }
2,337✔
1235
  after = iterAfter->qname;
2,713✔
1236

1237
  return true;
2,713✔
1238
}
2,713✔
1239

1240
// NOLINTNEXTLINE(readability-identifier-length)
1241
bool Bind2Backend::getBeforeAndAfterNamesAbsolute(domainid_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
1242
{
7,051✔
1243
  BB2DomainInfo bbd;
7,051✔
1244
  if (!safeGetBBDomainInfo(id, &bbd))
7,051!
1245
    return false;
×
1246

1247
  shared_ptr<const recordstorage_t> records = bbd.d_records.get();
7,051✔
1248
  if (!bbd.d_nsec3zone) {
7,051✔
1249
    return findBeforeAndAfterUnhashed(records, qname, unhashed, before, after);
2,713✔
1250
  }
2,713✔
1251
  else {
4,338✔
1252
    const auto& hashindex = boost::multi_index::get<NSEC3Tag>(*records);
4,338✔
1253

1254
    // for(auto iter = first; iter != hashindex.end(); iter++)
1255
    //  cerr<<iter->nsec3hash<<endl;
1256

1257
    auto first = hashindex.upper_bound("");
4,338✔
1258
    auto iter = hashindex.upper_bound(qname.toStringNoDot());
4,338✔
1259

1260
    if (iter == hashindex.end()) {
4,338✔
1261
      --iter;
349✔
1262
      before = DNSName(iter->nsec3hash);
349✔
1263
      after = DNSName(first->nsec3hash);
349✔
1264
    }
349✔
1265
    else {
3,989✔
1266
      after = DNSName(iter->nsec3hash);
3,989✔
1267
      if (iter != first)
3,989✔
1268
        --iter;
3,897✔
1269
      else
92✔
1270
        iter = --hashindex.end();
92✔
1271
      before = DNSName(iter->nsec3hash);
3,989✔
1272
    }
3,989✔
1273
    unhashed = iter->qname + bbd.d_name.operator const DNSName&();
4,338✔
1274

1275
    return true;
4,338✔
1276
  }
4,338✔
1277
}
7,051✔
1278

1279
void Bind2Backend::lookup(const QType& qtype, const DNSName& qname, domainid_t zoneId, DNSPacket* /* pkt_p */)
1280
{
4,176✔
1281
  d_handle.reset();
4,176✔
1282

1283
  static bool mustlog = ::arg().mustDo("query-logging");
4,176✔
1284

1285
  bool found = false;
4,176✔
1286
  ZoneName domain;
4,176✔
1287
  BB2DomainInfo bbd;
4,176✔
1288

1289
  if (mustlog) {
4,176!
1290
    SLOG(g_log << Logger::Warning << "Lookup for '" << qtype.toString() << "' of '" << qname << "' within zoneID " << zoneId << endl,
×
1291
         d_slog->info(Logr::Warning, "Record lookup", "name", Logging::Loggable(qname), "qtype", Logging::Loggable(qtype), "zone id", Logging::Loggable(zoneId)));
×
1292
  }
×
1293

1294
  if (zoneId != UnknownDomainID) {
4,176✔
1295
    if ((found = (safeGetBBDomainInfo(zoneId, &bbd) && qname.isPartOf(bbd.d_name)))) {
3,562!
1296
      domain = std::move(bbd.d_name);
3,562✔
1297
    }
3,562✔
1298
  }
3,562✔
1299
  else {
614✔
1300
    domain = ZoneName(qname);
614✔
1301
    do {
617✔
1302
      found = safeGetBBDomainInfo(domain, &bbd);
617✔
1303
    } while (!found && qtype != QType::SOA && domain.chopOff());
617✔
1304
  }
614✔
1305

1306
  if (!found) {
4,176✔
1307
    if (mustlog) {
24!
1308
      SLOG(g_log << Logger::Warning << "Found no authoritative zone for '" << qname << "' and/or id " << zoneId << endl,
×
1309
           d_slog->info(Logr::Warning, "Found no authoritative zone", "name", Logging::Loggable(qname), "zone id", Logging::Loggable(zoneId)));
×
1310
    }
×
1311
    d_handle.d_list = false;
24✔
1312
    return;
24✔
1313
  }
24✔
1314

1315
  if (mustlog) {
4,152!
1316
    SLOG(g_log << Logger::Warning << "Found a zone '" << domain << "' (with id " << bbd.d_id << ") that might contain data " << endl,
×
1317
         d_slog->info(Logr::Warning, "Found authoritative zone", "zone", Logging::Loggable(domain), "zone id", Logging::Loggable(bbd.d_id)));
×
1318
  }
×
1319

1320
  d_handle.id = bbd.d_id;
4,152✔
1321
  d_handle.qname = qname.makeRelative(domain); // strip domain name
4,152✔
1322
  d_handle.qtype = qtype;
4,152✔
1323
  d_handle.domain = std::move(domain);
4,152✔
1324

1325
  if (!bbd.current()) {
4,152✔
1326
    SLOG(g_log << Logger::Warning << "Zone '" << d_handle.domain << "' (" << bbd.main_filename() << ") needs reloading" << endl,
6!
1327
         d_slog->info(Logr::Warning, "Zone needs reloading", "zone", Logging::Loggable(d_handle.domain), "file", Logging::Loggable(bbd.main_filename())));
6✔
1328
    queueReloadAndStore(bbd.d_id);
6✔
1329
    if (!safeGetBBDomainInfo(d_handle.domain, &bbd))
6!
1330
      throw DBException("Zone '" + bbd.d_name.toLogString() + "' (" + bbd.main_filename() + ") gone after reload"); // if we don't throw here, we crash for some reason
×
1331
  }
6✔
1332

1333
  if (!bbd.d_loaded) {
4,152✔
1334
    d_handle.reset();
216✔
1335
    throw DBException("Zone for '" + d_handle.domain.toLogString() + "' in '" + bbd.main_filename() + "' not loaded (file missing, corrupt or primary dead)"); // fsck
216✔
1336
  }
216✔
1337

1338
  d_handle.d_records = bbd.d_records.get();
3,936✔
1339

1340
  if (d_handle.d_records->empty()) {
3,936!
1341
    DLOG(SLOG(g_log << "Query with no results" << endl,
×
1342
              d_slog->info(Logr::Debug, "No results", "name", Logging::Loggable(qname), "qtype", Logging::Loggable(qtype))));
×
1343
  }
×
1344

1345
  d_handle.mustlog = mustlog;
3,936✔
1346

1347
  const auto& hashedidx = boost::multi_index::get<UnorderedNameTag>(*d_handle.d_records);
3,936✔
1348
  auto range = hashedidx.equal_range(d_handle.qname);
3,936✔
1349

1350
  d_handle.d_list = false;
3,936✔
1351
  d_handle.d_iter = range.first;
3,936✔
1352
  d_handle.d_end_iter = range.second;
3,936✔
1353
}
3,936✔
1354

1355
bool Bind2Backend::get(DNSResourceRecord& r)
1356
{
198,041✔
1357
  if (!d_handle.d_records) {
198,041✔
1358
    if (d_handle.mustlog) {
24!
1359
      SLOG(g_log << Logger::Warning << "There were no answers" << endl,
×
1360
           d_slog->info(Logr::Warning, "No answers"));
×
1361
    }
×
1362
    return false;
24✔
1363
  }
24✔
1364

1365
  if (!d_handle.get(r)) {
198,017✔
1366
    if (d_handle.mustlog) {
4,239!
1367
      SLOG(g_log << Logger::Warning << "End of answers" << endl,
×
1368
           d_slog->info(Logr::Warning, "No more answers"));
×
1369
    }
×
1370

1371
    d_handle.reset();
4,239✔
1372

1373
    return false;
4,239✔
1374
  }
4,239✔
1375
  if (d_handle.mustlog) {
193,778!
1376
    SLOG(g_log << Logger::Warning << "Returning: '" << r.qtype.toString() << "' of '" << r.qname << "', content: '" << r.content << "'" << endl,
×
1377
         d_slog->info(Logr::Warning, "Returning record", "name", Logging::Loggable(r.qname), "type", Logging::Loggable(r.qtype), "content", Logging::Loggable(r.content)));
×
1378
  }
×
1379
  return true;
193,778✔
1380
}
198,017✔
1381

1382
void Bind2Backend::lookupEnd()
1383
{
28✔
1384
  d_handle.reset();
28✔
1385
}
28✔
1386

1387
bool Bind2Backend::handle::get(DNSResourceRecord& r)
1388
{
198,017✔
1389
  if (d_list)
198,017✔
1390
    return get_list(r);
188,936✔
1391
  else
9,081✔
1392
    return get_normal(r);
9,081✔
1393
}
198,017✔
1394

1395
void Bind2Backend::handle::reset()
1396
{
8,990✔
1397
  d_records.reset();
8,990✔
1398
  qname.clear();
8,990✔
1399
  mustlog = false;
8,990✔
1400
}
8,990✔
1401

1402
bool Bind2Backend::handle::get_normal(DNSResourceRecord& r)
1403
{
9,081✔
1404
  DLOG(SLOG(g_log << "Bind2Backend get() was called for " << qtype.toString() << " record for '" << qname << "' - " << d_records->size() << " available in total!" << endl,
9,081✔
1405
            d_slog->info(Logr::Debug, "Bind2Backend get() invoked", "name", Logging::Loggable(qname), "type", Logging::Loggable(qtype), "results", Logging::Loggable(d_records->size()))));
9,081✔
1406

1407
  if (d_iter == d_end_iter) {
9,081✔
1408
    return false;
3,908✔
1409
  }
3,908✔
1410

1411
  while (d_iter != d_end_iter && !(qtype.getCode() == QType::ANY || (d_iter)->qtype == qtype.getCode())) {
7,906!
1412
    DLOG(SLOG(g_log << Logger::Warning << "Skipped " << qname << "/" << QType(d_iter->qtype).toString() << ": '" << d_iter->content << "'" << endl,
2,733✔
1413
              d_slog->info(Logr::Debug, "Skipped record", "name", Logging::Loggable(qname), "type", Logging::Loggable(d_iter->qtype), "content", Logging::Loggable(d_iter->content))));
2,733✔
1414
    d_iter++;
2,733✔
1415
  }
2,733✔
1416
  if (d_iter == d_end_iter) {
5,173!
1417
    return false;
×
1418
  }
×
1419
  DLOG(SLOG(g_log << "Bind2Backend get() returning a rr with a " << QType(d_iter->qtype).getCode() << endl,
5,173✔
1420
            d_slog->info(Logr::Debug, "Bind2Backend get() returning a rr", "type", Logging::Loggable(d_iter->qtype))));
5,173✔
1421

1422
  const DNSName& domainName(domain);
5,173✔
1423
  r.qname = qname.empty() ? domainName : (qname + domainName);
5,173!
1424
  r.domain_id = id;
5,173✔
1425
  r.content = (d_iter)->content;
5,173✔
1426
  //  r.domain_id=(d_iter)->domain_id;
1427
  r.qtype = (d_iter)->qtype;
5,173✔
1428
  r.ttl = (d_iter)->ttl;
5,173✔
1429

1430
  //if(!d_iter->auth && r.qtype.getCode() != QType::A && r.qtype.getCode()!=QType::AAAA && r.qtype.getCode() != QType::NS)
1431
  //  cerr<<"Warning! Unauth response for qtype "<< r.qtype.toString() << " for '"<<r.qname<<"'"<<endl;
1432
  r.auth = d_iter->auth;
5,173✔
1433

1434
  d_iter++;
5,173✔
1435

1436
  return true;
5,173✔
1437
}
5,173✔
1438

1439
bool Bind2Backend::list(const ZoneName& /* target */, domainid_t domainId, bool /* include_disabled */)
1440
{
331✔
1441
  BB2DomainInfo bbd;
331✔
1442

1443
  if (!safeGetBBDomainInfo(domainId, &bbd)) {
331!
1444
    return false;
×
1445
  }
×
1446

1447
  d_handle.reset();
331✔
1448
  DLOG(SLOG(g_log << "Bind2Backend constructing handle for list of " << domainId << endl,
331✔
1449
            d_slog->info(Logr::Debug, "Bind2Backend constructing handle for zone list", "zone id", Logging::Loggable(domainId))));
331✔
1450

1451
  if (!bbd.d_loaded) {
331!
1452
    throw PDNSException("zone was not loaded, perhaps because of: " + bbd.d_status);
×
1453
  }
×
1454

1455
  d_handle.d_records = bbd.d_records.get(); // give it a copy, which will stay around
331✔
1456
  d_handle.d_qname_iter = d_handle.d_records->begin();
331✔
1457
  d_handle.d_qname_end = d_handle.d_records->end(); // iter now points to a vector of pointers to vector<BBResourceRecords>
331✔
1458

1459
  d_handle.id = domainId;
331✔
1460
  d_handle.domain = bbd.d_name;
331✔
1461
  d_handle.d_list = true;
331✔
1462
  return true;
331✔
1463
}
331✔
1464

1465
bool Bind2Backend::handle::get_list(DNSResourceRecord& r)
1466
{
188,936✔
1467
  if (d_qname_iter != d_qname_end) {
188,936✔
1468
    const DNSName& domainName(domain);
188,605✔
1469
    r.qname = d_qname_iter->qname.empty() ? domainName : (d_qname_iter->qname + domainName);
188,605!
1470
    r.domain_id = id;
188,605✔
1471
    r.content = (d_qname_iter)->content;
188,605✔
1472
    r.qtype = (d_qname_iter)->qtype;
188,605✔
1473
    r.ttl = (d_qname_iter)->ttl;
188,605✔
1474
    r.auth = d_qname_iter->auth;
188,605✔
1475
    d_qname_iter++;
188,605✔
1476
    return true;
188,605✔
1477
  }
188,605✔
1478
  return false;
331✔
1479
}
188,936✔
1480

1481
bool Bind2Backend::autoPrimariesList(std::vector<AutoPrimary>& primaries)
1482
{
×
1483
  if (getArg("autoprimary-config").empty())
×
1484
    return false;
×
1485

1486
  std::string filename(getArg("autoprimaries"));
×
1487
  ifstream c_if(filename, std::ios::in);
×
1488
  if (!c_if) {
×
1489
    SLOG(g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl,
×
1490
         d_slog->error(Logr::Error, errno, "Unable to open autoprimaries file", "file", Logging::Loggable(filename)));
×
1491
    return false;
×
1492
  }
×
1493

1494
  string line, sip, saccount;
×
1495
  while (getline(c_if, line)) {
×
1496
    std::istringstream ii(line);
×
1497
    ii >> sip;
×
1498
    if (!sip.empty()) {
×
1499
      ii >> saccount;
×
1500
      primaries.emplace_back(sip, "", saccount);
×
1501
    }
×
1502
  }
×
1503

1504
  c_if.close();
×
1505
  return true;
×
1506
}
×
1507

1508
bool Bind2Backend::autoPrimaryBackend(const string& ipAddress, const ZoneName& /* domain */, const vector<DNSResourceRecord>& /* nsset */, string* /* nameserver */, string* account, DNSBackend** backend)
1509
{
×
1510
  // Check whether we have a configfile available.
1511
  if (getArg("autoprimary-config").empty())
×
1512
    return false;
×
1513

1514
  std::string filename(getArg("autoprimaries"));
×
1515
  ifstream c_if(filename.c_str(), std::ios::in); // this was nocreate?
×
1516
  if (!c_if) {
×
1517
    SLOG(g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl,
×
1518
         d_slog->error(Logr::Error, errno, "Unable to open autoprimaries file", "file", Logging::Loggable(filename)));
×
1519
    return false;
×
1520
  }
×
1521

1522
  // Format:
1523
  // <ip> <accountname>
1524
  string line, sip, saccount;
×
1525
  while (getline(c_if, line)) {
×
1526
    std::istringstream ii(line);
×
1527
    ii >> sip;
×
1528
    if (sip == ipAddress) {
×
1529
      ii >> saccount;
×
1530
      break;
×
1531
    }
×
1532
  }
×
1533
  c_if.close();
×
1534

1535
  if (sip != ipAddress) { // ip not found in authorization list - reject
×
1536
    return false;
×
1537
  }
×
1538

1539
  // ip authorized as autoprimary - accept
1540
  *backend = this;
×
1541
  if (saccount.length() > 0)
×
1542
    *account = saccount.c_str();
×
1543

1544
  return true;
×
1545
}
×
1546

1547
BB2DomainInfo Bind2Backend::createDomainEntry(const ZoneName& domain)
1548
{
6✔
1549
  domainid_t newid = 1;
6✔
1550
  { // Find a free zone id nr.
6✔
1551
    auto state = s_state.read_lock();
6✔
1552
    if (!state->empty()) {
6!
1553
      newid = state->rbegin()->d_id + 1;
6✔
1554
    }
6✔
1555
  }
6✔
1556

1557
  BB2DomainInfo bbd;
6✔
1558
  bbd.d_kind = DomainInfo::Native;
6✔
1559
  bbd.d_id = newid;
6✔
1560
  bbd.d_records = std::make_shared<recordstorage_t>();
6✔
1561
  bbd.d_name = domain;
6✔
1562
  bbd.setCheckInterval(getArgAsNum("check-interval"));
6✔
1563

1564
  return bbd;
6✔
1565
}
6✔
1566

1567
bool Bind2Backend::createSecondaryDomain(const string& ipAddress, const ZoneName& domain, const string& /* nameserver */, const string& account)
1568
{
×
1569
  std::string domainname = domain.toStringNoDot();
×
1570

1571
  // Reject domain name if it embeds quotes; this may happen if 8bit-dns is
1572
  // used, and bind currently does not allow for character escapes in zone
1573
  // names.
1574
  if (domainname.find_first_of("\"") != std::string::npos) {
×
1575
    SLOG(g_log << Logger::Error << d_logprefix
×
1576
               << " Unable to accept autosecondary zone '" << domain
×
1577
               << "' from autoprimary " << ipAddress
×
1578
               << " due to unauthorized characters in domain name for bind configuration file"
×
1579
               << endl,
×
1580
         d_slog->error(Logr::Error, "unauthorized characters in domain name for bind configuration file", "Unable to accept autosecondary zone", "zone", Logging::Loggable(domain), "autoprimary address", Logging::Loggable(ipAddress)));
×
1581
    throw PDNSException("Unauthorized characters in domain name for bind configuration file");
×
1582
  }
×
1583

1584
  string filename = getArg("autoprimary-destdir") + '/';
×
1585
  if (domainname.empty()) {
×
1586
    filename.append("rootzone.");
×
1587
  }
×
1588
  else {
×
1589
    // Make sure the zone file name does not contain path separators.
1590
    filename.append(boost::replace_all_copy(domainname, "/", "\\047"));
×
1591
  }
×
1592

1593
  SLOG(g_log << Logger::Warning << d_logprefix
×
1594
             << " Writing bind config zone statement for autosecondary zone '" << domain
×
1595
             << "' from autoprimary " << ipAddress << endl,
×
1596
       d_slog->info(Logr::Warning, "Writing bind config zone statement for autosecondary zone", "zone", Logging::Loggable(domain), "autoprimary address", Logging::Loggable(ipAddress)));
×
1597

1598
  {
×
1599
    auto lock = std::scoped_lock(s_autosecondary_config_lock);
×
1600

1601
    std::string configfile(getArg("autoprimary-config"));
×
1602
    ofstream c_of(configfile.c_str(), std::ios::app);
×
1603
    if (!c_of) {
×
1604
      int err = errno;
×
1605
      auto errorMessage = stringerror();
×
1606
      SLOG(g_log << Logger::Error << "Unable to open autoprimary configfile for append: " << errorMessage << endl,
×
1607
           d_slog->error(Logr::Error, err, "Unable to open autoprimary configuration file for append", "file", Logging::Loggable(configfile)));
×
1608
      throw DBException("Unable to open autoprimary configfile for append: " + errorMessage);
×
1609
    }
×
1610

1611
    c_of << endl;
×
1612
    c_of << "# AutoSecondary zone '" << domainname << "' (added: " << nowTime() << ") (account: " << account << ')' << endl;
×
1613
    c_of << "zone \"" << domainname << "\" {" << endl;
×
1614
    c_of << "\ttype secondary;" << endl;
×
1615
    c_of << "\tfile \"" << filename << "\";" << endl;
×
1616
    c_of << "\tprimaries { " << ipAddress << "; };" << endl;
×
1617
    c_of << "};" << endl;
×
1618
    c_of.close();
×
1619
  }
×
1620

1621
  BB2DomainInfo bbd = createDomainEntry(domain);
×
1622
  bbd.d_kind = DomainInfo::Secondary;
×
1623
  bbd.d_primaries.emplace_back(ComboAddress(ipAddress, 53));
×
1624
  bbd.d_fileinfo.emplace_back(std::make_pair(filename, 0));
×
1625
  bbd.updateCtime();
×
1626
  safePutBBDomainInfo(bbd);
×
1627

1628
  return true;
×
1629
}
×
1630

1631
bool Bind2Backend::searchRecords(const string& pattern, size_t maxResults, vector<DNSResourceRecord>& result)
1632
{
24✔
1633
  SimpleMatch sm(pattern, true);
24✔
1634
  static bool mustlog = ::arg().mustDo("query-logging");
24✔
1635
  if (mustlog) {
24!
1636
    SLOG(g_log << Logger::Warning << "Search for pattern '" << pattern << "'" << endl,
×
1637
         d_slog->info(Logr::Debug, "Search for pattern", "pattern", Logging::Loggable(pattern)));
×
1638
  }
×
1639

1640
  {
24✔
1641
    auto state = s_state.read_lock();
24✔
1642

1643
    for (const auto& i : *state) {
24!
1644
      BB2DomainInfo h;
×
1645
      if (!safeGetBBDomainInfo(i.d_id, &h)) {
×
1646
        continue;
×
1647
      }
×
1648

1649
      if (!h.d_loaded) {
×
1650
        continue;
×
1651
      }
×
1652

1653
      shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
×
1654

1655
      for (recordstorage_t::const_iterator ri = rhandle->begin(); result.size() < maxResults && ri != rhandle->end(); ri++) {
×
1656
        const DNSName& domainName(i.d_name);
×
1657
        DNSName name = ri->qname.empty() ? domainName : (ri->qname + domainName);
×
1658
        if (sm.match(name) || sm.match(ri->content)) {
×
1659
          DNSResourceRecord r;
×
1660
          r.qname = std::move(name);
×
1661
          r.domain_id = i.d_id;
×
1662
          r.content = ri->content;
×
1663
          r.qtype = ri->qtype;
×
1664
          r.ttl = ri->ttl;
×
1665
          r.auth = ri->auth;
×
1666
          result.push_back(std::move(r));
×
1667
        }
×
1668
      }
×
1669
    }
×
1670
  }
24✔
1671

1672
  return true;
24✔
1673
}
24✔
1674

1675
class Bind2Factory : public BackendFactory
1676
{
1677
public:
1678
  Bind2Factory() :
1679
    BackendFactory("bind") {}
6,011✔
1680

1681
  void declareArguments(const string& suffix = "") override
1682
  {
572✔
1683
    declare(suffix, "ignore-broken-records", "Ignore records that are out-of-bound for the zone.", "no");
572✔
1684
    declare(suffix, "config", "Location of named.conf", "");
572✔
1685
    declare(suffix, "check-interval", "Interval for zonefile changes", "0");
572✔
1686
    declare(suffix, "autoprimary-config", "Location of (part of) named.conf where pdns can write zone-statements to", "");
572✔
1687
    declare(suffix, "autoprimaries", "List of IP-addresses of autoprimaries", "");
572✔
1688
    declare(suffix, "autoprimary-destdir", "Destination directory for newly added secondary zones", ::arg()["config-dir"]);
572✔
1689
    declare(suffix, "dnssec-db", "Filename to store & access our DNSSEC metadatabase, empty for none", "");
572✔
1690
    declare(suffix, "dnssec-db-journal-mode", "SQLite3 journal mode", "WAL");
572✔
1691
    declare(suffix, "hybrid", "Store DNSSEC metadata in other backend", "no");
572✔
1692
  }
572✔
1693

1694
  DNSBackend* make(const string& suffix = "") override
1695
  {
2,547✔
1696
    assertEmptySuffix(suffix);
2,547✔
1697
    return new Bind2Backend(suffix);
2,547✔
1698
  }
2,547✔
1699

1700
  DNSBackend* makeMetadataOnly(const string& suffix = "") override
1701
  {
907✔
1702
    assertEmptySuffix(suffix);
907✔
1703
    return new Bind2Backend(suffix, false);
907✔
1704
  }
907✔
1705

1706
private:
1707
  void assertEmptySuffix(const string& suffix)
1708
  {
3,454✔
1709
    if (!suffix.empty())
3,454!
1710
      throw PDNSException("launch= suffixes are not supported on the bindbackend");
×
1711
  }
3,454✔
1712
};
1713

1714
//! Magic class that is activated when the dynamic library is loaded
1715
class Bind2Loader
1716
{
1717
public:
1718
  Bind2Loader()
1719
  {
6,011✔
1720
    BackendMakers().report(std::make_unique<Bind2Factory>());
6,011✔
1721
    // If this module is not loaded dynamically at runtime, this code runs
1722
    // as part of a global constructor, before the structured logger has a
1723
    // chance to be set up, so fallback to simple logging.
1724
    g_log << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
6,011✔
1725
#ifndef REPRODUCIBLE
6,011✔
1726
          << " (" __DATE__ " " __TIME__ ")"
6,011✔
1727
#endif
6,011✔
1728
#ifdef HAVE_SQLITE3
6,011✔
1729
          << " (with bind-dnssec-db support)"
6,011✔
1730
#endif
6,011✔
1731
          << " reporting" << endl;
6,011✔
1732
  }
6,011✔
1733
};
1734
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

© 2026 Coveralls, Inc