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

PowerDNS / pdns / 26160310211

20 May 2026 11:43AM UTC coverage: 61.389% (-1.7%) from 63.049%
26160310211

push

github

web-flow
Merge pull request #17443 from miodvallat/50x.sa_2026_06

auth 5.0: backport SA 2026-06

12955 of 27948 branches covered (46.35%)

Branch coverage included in aggregate %.

127 of 291 new or added lines in 9 files covered. (43.64%)

1088 existing lines in 26 files now uncovered.

41454 of 60682 relevant lines covered (68.31%)

10741642.99 hits per line

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

60.92
/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,359✔
87
  d_loaded = false;
15,359✔
88
  d_lastcheck = 0;
15,359✔
89
  d_checknow = false;
15,359✔
90
  d_status = "Unknown";
15,359✔
91
}
15,359✔
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,109✔
100
  if (d_checknow) {
4,109✔
101
    return false;
6✔
102
  }
6✔
103

104
  if (!d_checkinterval)
4,103!
105
    return true;
4,103✔
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
{
2,671✔
128
  struct stat buf;
2,671✔
129
  if (stat(d_filename.c_str(), &buf) < 0)
2,671!
130
    return;
×
131
  d_ctime = buf.st_ctime;
2,671✔
132
}
2,671✔
133

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

146
bool Bind2Backend::safeGetBBDomainInfo(const ZoneName& name, BB2DomainInfo* bbd)
147
{
4,178✔
148
  auto state = s_state.read_lock();
4,178✔
149
  const auto& nameindex = boost::multi_index::get<NameTag>(*state);
4,178✔
150
  auto iter = nameindex.find(name);
4,178✔
151
  if (iter == nameindex.end()) {
4,178✔
152
    return false;
3,131✔
153
  }
3,131✔
154
  *bbd = *iter;
1,047✔
155
  return true;
1,047✔
156
}
4,178✔
157

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

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

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

178
// NOLINTNEXTLINE(readability-identifier-length)
179
void Bind2Backend::setNotified(domainid_t id, uint32_t serial)
180
{
×
181
  BB2DomainInfo bbd;
×
182
  if (!safeGetBBDomainInfo(id, &bbd))
×
183
    return;
×
184
  bbd.d_lastnotified = serial;
×
185
  safePutBBDomainInfo(bbd);
×
186
}
×
187

188
// NOLINTNEXTLINE(readability-identifier-length)
189
void Bind2Backend::setLastCheck(domainid_t domain_id, time_t lastcheck)
190
{
72✔
191
  BB2DomainInfo bbd;
72✔
192
  if (safeGetBBDomainInfo(domain_id, &bbd)) {
72!
193
    bbd.d_lastcheck = lastcheck;
72✔
194
    safePutBBDomainInfo(bbd);
72✔
195
  }
72✔
196
}
72✔
197

198
void Bind2Backend::setStale(domainid_t domain_id)
199
{
×
200
  Bind2Backend::setLastCheck(domain_id, 0);
×
201
}
×
202

203
void Bind2Backend::setFresh(domainid_t domain_id)
204
{
72✔
205
  Bind2Backend::setLastCheck(domain_id, time(nullptr));
72✔
206
}
72✔
207

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

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

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

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

245
    return true;
72✔
246
  }
72✔
247
  return false;
×
248
}
72✔
249

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

259
  BB2DomainInfo bbd;
72✔
260
  if (safeGetBBDomainInfo(d_transaction_id, &bbd)) {
72!
261
    if (rename(d_transaction_tmpname.c_str(), bbd.d_filename.c_str()) < 0)
72!
262
      throw DBException("Unable to commit (rename to: '" + bbd.d_filename + "') AXFRed zone: " + stringerror());
×
263
    queueReloadAndStore(bbd.d_id);
72✔
264
  }
72✔
265

266
  d_transaction_id = UnknownDomainID;
72✔
267

268
  return true;
72✔
269
}
72✔
270

271
bool Bind2Backend::abortTransaction()
272
{
×
273
  // d_transaction_id is only set to a valid domain id if we are actually
274
  // setting up a replacement zone file with the updated data.
275
  if (d_transaction_id != UnknownDomainID) {
×
276
    unlink(d_transaction_tmpname.c_str());
×
277
    d_of.reset();
×
278
    d_transaction_id = UnknownDomainID;
×
279
  }
×
280

281
  return true;
×
282
}
×
283

284
/** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */
285
static bool endsOn(const string& domain, const string& suffix)
286
{
416✔
287
  if (domain.size() <= suffix.size()) {
416✔
288
    return false;
52✔
289
  }
52✔
290

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

306
  string::size_type spos = 0;
276✔
307
  for (; dpos < domain.size(); ++dpos, ++spos) {
3,928✔
308
    if (!pdns_iequals_ch(domain[dpos], suffix[spos])) {
3,664✔
309
      return false;
12✔
310
    }
12✔
311
  }
3,664✔
312

313
  return true;
264✔
314
}
276✔
315

316
/** strips a domain suffix from a domain */
317
static void stripDomainSuffix(string* qname, const ZoneName& zonename)
318
{
432✔
319
  std::string domain = zonename.operator const DNSName&().toString();
432✔
320

321
  if (domain.empty()) {
432!
322
    return;
×
323
  }
×
324
  if (pdns_iequals(*qname, domain)) {
432✔
325
    *qname = "@";
16✔
326
    return;
16✔
327
  }
16✔
328
  if (endsOn(*qname, domain)) {
416✔
329
    auto prefix = qname->size() - domain.size();
264✔
330
    qname->resize(prefix - 1); // also strip dot
264✔
331
  }
264✔
332
}
416✔
333

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

344
  for (char letter : name) {
2,818,680✔
345
    switch (letter) {
2,818,680✔
NEW
346
    case '$':
×
NEW
347
    case '@':
×
NEW
348
    case '"':
×
NEW
349
    case ';':
×
NEW
350
    case '(':
×
NEW
351
    case ')':
×
NEW
352
      snprintf(ebuf.data(), ebuf.size(), "\\%03u", static_cast<unsigned char>(letter));
×
NEW
353
      ret += ebuf.data();
×
NEW
354
      break;
×
355
    default:
2,818,680!
356
      ret += letter;
2,818,680✔
357
      break;
2,818,680✔
358
    }
2,818,680✔
359
  }
2,818,680✔
360
  return ret;
202,152✔
361
}
202,152✔
362

363
bool Bind2Backend::feedRecord(const DNSResourceRecord& rr, const DNSName& /* ordername */, bool /* ordernameIsNSEC3 */)
364
{
202,785✔
365
  if (d_transaction_id == UnknownDomainID) {
202,785!
366
    throw DBException("Bind2Backend::feedRecord() called outside of transaction");
×
367
  }
×
368

369
  string qname;
202,785✔
370
  if (d_transaction_qname.empty()) {
202,785!
NEW
371
    qname = bindEscape(rr.qname.toString());
×
372
  }
×
373
  else if (rr.qname.isPartOf(d_transaction_qname)) {
202,785!
374
    if (rr.qname == d_transaction_qname.operator const DNSName&()) {
202,785✔
375
      qname = "@";
633✔
376
    }
633✔
377
    else {
202,152✔
378
      DNSName relName = rr.qname.makeRelative(d_transaction_qname);
202,152✔
379
      qname = bindEscape(relName.toStringNoDot());
202,152✔
380
    }
202,152✔
381
  }
202,785✔
382
  else {
×
383
    throw DBException("out-of-zone data '" + rr.qname.toLogString() + "' during AXFR of zone '" + d_transaction_qname.toLogString() + "'");
×
384
  }
×
385

386
  shared_ptr<DNSRecordContent> drc(DNSRecordContent::make(rr.qtype.getCode(), QClass::IN, rr.content));
202,785✔
387
  string content = drc->getZoneRepresentation();
202,785✔
388

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

406
void Bind2Backend::getUpdatedPrimaries(vector<DomainInfo>& changedDomains, std::unordered_set<DNSName>& /* catalogs */, CatalogHashMap& /* catalogHashes */)
407
{
×
408
  vector<DomainInfo> consider;
×
409
  {
×
410
    auto state = s_state.read_lock();
×
411

412
    for (const auto& i : *state) {
×
413
      if (i.d_kind != DomainInfo::Primary && this->alsoNotify.empty() && i.d_also_notify.empty())
×
414
        continue;
×
415

416
      DomainInfo di;
×
417
      di.id = i.d_id;
×
418
      di.zone = i.d_name;
×
419
      di.last_check = i.d_lastcheck;
×
420
      di.notified_serial = i.d_lastnotified;
×
421
      di.backend = this;
×
422
      di.kind = DomainInfo::Primary;
×
423
      consider.push_back(std::move(di));
×
424
    }
×
425
  }
×
426

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

450
void Bind2Backend::getAllDomains(vector<DomainInfo>* domains, bool getSerial, bool /* include_disabled */)
451
{
79✔
452
  SOAData soadata;
79✔
453

454
  // prevent deadlock by using getSOA() later on
455
  {
79✔
456
    auto state = s_state.read_lock();
79✔
457
    domains->reserve(state->size());
79✔
458

459
    for (const auto& i : *state) {
239✔
460
      DomainInfo di;
185✔
461
      di.id = i.d_id;
185✔
462
      di.zone = i.d_name;
185✔
463
      di.last_check = i.d_lastcheck;
185✔
464
      di.kind = i.d_kind;
185✔
465
      di.primaries = i.d_primaries;
185✔
466
      di.backend = this;
185✔
467
      domains->push_back(std::move(di));
185✔
468
    };
185✔
469
  }
79✔
470

471
  if (getSerial) {
79✔
472
    for (DomainInfo& di : *domains) {
1,032✔
473
      // do not corrupt di if domain supplied by another backend.
474
      if (di.backend != this)
1,032!
475
        continue;
1,032✔
476
      try {
×
477
        this->getSOA(di.zone, di.id, soadata);
×
478
      }
×
479
      catch (...) {
×
480
        continue;
×
481
      }
×
482
      di.serial = soadata.serial;
×
483
    }
×
484
  }
30✔
485
}
79✔
486

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

508
  for (DomainInfo& sd : domains) {
72✔
509
    SOAData soadata;
72✔
510
    soadata.refresh = 0;
72✔
511
    soadata.serial = 0;
72✔
512
    try {
72✔
513
      getSOA(sd.zone, sd.id, soadata); // we might not *have* a SOA yet
72✔
514
    }
72✔
515
    catch (...) {
72✔
516
    }
72✔
517
    sd.serial = soadata.serial;
72✔
518
    // coverity[store_truncates_time_t]
519
    if (sd.last_check + soadata.refresh < (unsigned int)time(nullptr))
72!
520
      unfreshDomains->push_back(std::move(sd));
72✔
521
  }
72✔
522
}
8✔
523

524
bool Bind2Backend::getDomainInfo(const ZoneName& domain, DomainInfo& info, bool getSerial)
525
{
889✔
526
  BB2DomainInfo bbd;
889✔
527
  if (!safeGetBBDomainInfo(domain, &bbd))
889✔
528
    return false;
444✔
529

530
  info.id = bbd.d_id;
445✔
531
  info.zone = domain;
445✔
532
  info.primaries = bbd.d_primaries;
445✔
533
  info.last_check = bbd.d_lastcheck;
445✔
534
  info.backend = this;
445✔
535
  info.kind = bbd.d_kind;
445✔
536
  info.serial = 0;
445✔
537
  if (getSerial) {
445✔
538
    try {
135✔
539
      SOAData sd;
135✔
540
      sd.serial = 0;
135✔
541

542
      getSOA(bbd.d_name, bbd.d_id, sd); // we might not *have* a SOA yet
135✔
543
      info.serial = sd.serial;
135✔
544
    }
135✔
545
    catch (...) {
135✔
546
    }
72✔
547
  }
135✔
548

549
  return true;
445✔
550
}
445✔
551

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

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

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

598
    insertRecord(records, bbd->d_name, rr.qname, rr.qtype, rr.content, rr.ttl, "");
3,274,386✔
599
  }
3,274,386✔
600
  fixupOrderAndAuth(records, bbd->d_name, nsec3zone, ns3pr);
2,737✔
601
  doEmptyNonTerminals(records, bbd->d_name, nsec3zone, ns3pr);
2,737✔
602
  bbd->setCtime();
2,737✔
603
  bbd->d_loaded = true;
2,737✔
604
  bbd->d_checknow = false;
2,737✔
605
  bbd->d_status = "parsed into memory at " + nowTime();
2,737✔
606
  bbd->d_records = LookButDontTouch<recordstorage_t>(std::move(records));
2,737✔
607
  bbd->d_nsec3zone = nsec3zone;
2,737✔
608
  bbd->d_nsec3param = std::move(ns3pr);
2,737✔
609
}
2,737✔
610

611
/** THIS IS AN INTERNAL FUNCTION! It does moadnsparser prio impedance matching
612
    Much of the complication is due to the efforts to benefit from std::string reference counting copy on write semantics */
613
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)
614
{
3,279,002✔
615
  Bind2DNSRecord bdr;
3,279,002✔
616
  bdr.qname = qname;
3,279,002✔
617

618
  if (zoneName.empty())
3,279,002!
619
    ;
×
620
  else if (bdr.qname.isPartOf(zoneName))
3,279,002✔
621
    bdr.qname.makeUsRelative(zoneName);
3,278,700✔
622
  else {
302✔
623
    string msg = "Trying to insert non-zone data, name='" + bdr.qname.toLogString() + "', qtype=" + qtype.toString() + ", zone='" + zoneName.toLogString() + "'";
302✔
624
    if (s_ignore_broken_records) {
302!
625
      g_log << Logger::Warning << msg << " ignored" << endl;
302✔
626
      return;
302✔
627
    }
302✔
628
    throw PDNSException(std::move(msg));
×
629
  }
302✔
630

631
  //  bdr.qname.swap(bdr.qname);
632

633
  if (!records->empty() && bdr.qname == boost::prior(records->end())->qname)
3,278,700✔
634
    bdr.qname = boost::prior(records->end())->qname;
8,869✔
635

636
  bdr.qname = bdr.qname;
3,278,700✔
637
  bdr.qtype = qtype.getCode();
3,278,700✔
638
  bdr.content = content;
3,278,700✔
639
  bdr.nsec3hash = hashed;
3,278,700✔
640

641
  if (auth != nullptr) // Set auth on empty non-terminals
3,278,700✔
642
    bdr.auth = *auth;
4,616✔
643
  else
3,274,084✔
644
    bdr.auth = true;
3,274,084✔
645

646
  bdr.ttl = ttl;
3,278,700✔
647
  records->insert(std::move(bdr));
3,278,700✔
648
}
3,278,700✔
649

650
string Bind2Backend::DLReloadNowHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
651
{
×
652
  ostringstream ret;
×
653

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

675
string Bind2Backend::DLDomStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
676
{
30✔
677
  ostringstream ret;
30✔
678

679
  if (parts.size() > 1) {
30!
680
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
681
      BB2DomainInfo bbd;
×
682
      if (safeGetBBDomainInfo(ZoneName(*i), &bbd)) {
×
683
        ret << *i << ": " << (bbd.d_loaded ? "" : "[rejected]") << "\t" << bbd.d_status << "\n";
×
684
      }
×
685
      else {
×
686
        ret << *i << " no such domain\n";
×
687
      }
×
688
    }
×
689
  }
×
690
  else {
30✔
691
    auto state = s_state.read_lock();
30✔
692
    for (const auto& i : *state) {
286✔
693
      ret << i.d_name << ": " << (i.d_loaded ? "" : "[rejected]") << "\t" << i.d_status << "\n";
286✔
694
    }
286✔
695
  }
30✔
696

697
  if (ret.str().empty())
30!
698
    ret << "no domains passed";
×
699

700
  return ret.str();
30✔
701
}
30✔
702

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

737
string Bind2Backend::DLDomExtendedStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
738
{
×
739
  ostringstream ret;
×
740

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

759
  if (ret.str().empty()) {
×
760
    ret << "no domains passed" << std::endl;
×
761
  }
×
762

763
  return ret.str();
×
764
}
×
765

766
string Bind2Backend::DLListRejectsHandler(const vector<string>& /* parts */, Utility::pid_t /* ppid */)
767
{
×
768
  ostringstream ret;
×
769
  auto rstate = s_state.read_lock();
×
770
  for (const auto& i : *rstate) {
×
771
    if (!i.d_loaded)
×
772
      ret << i.d_name << "\t" << i.d_status << endl;
×
773
  }
×
774
  return ret.str();
×
775
}
×
776

777
string Bind2Backend::DLAddDomainHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
778
{
12✔
779
  if (parts.size() < 3)
12!
780
    return "ERROR: Domain name and zone filename are required";
×
781

782
  ZoneName domainname(parts[1]);
12✔
783
  const string& filename = parts[2];
12✔
784
  BB2DomainInfo bbd;
12✔
785
  if (safeGetBBDomainInfo(domainname, &bbd))
12✔
786
    return "Already loaded";
6✔
787

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

791
  struct stat buf;
6✔
792
  if (stat(filename.c_str(), &buf) != 0)
6!
793
    return "Unable to load zone " + domainname.toLogString() + " from " + filename + ": " + strerror(errno);
×
794

795
  Bind2Backend bb2; // createdomainentry needs access to our configuration
6✔
796
  bbd = bb2.createDomainEntry(domainname, filename);
6✔
797
  bbd.d_filename = filename;
6✔
798
  bbd.d_checknow = true;
6✔
799
  bbd.d_loaded = true;
6✔
800
  bbd.d_lastcheck = 0;
6✔
801
  bbd.d_status = "parsing into memory";
6✔
802
  bbd.setCtime();
6✔
803

804
  safePutBBDomainInfo(bbd);
6✔
805

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

808
  g_log << Logger::Warning << "Zone " << domainname << " loaded" << endl;
6✔
809
  return "Loaded zone " + domainname.toLogString() + " from " + filename;
6✔
810
}
6✔
811

812
Bind2Backend::Bind2Backend(const string& suffix, bool loadZones)
813
{
2,825✔
814
  d_getAllDomainMetadataQuery_stmt = nullptr;
2,825✔
815
  d_getDomainMetadataQuery_stmt = nullptr;
2,825✔
816
  d_deleteDomainMetadataQuery_stmt = nullptr;
2,825✔
817
  d_insertDomainMetadataQuery_stmt = nullptr;
2,825✔
818
  d_getDomainKeysQuery_stmt = nullptr;
2,825✔
819
  d_deleteDomainKeyQuery_stmt = nullptr;
2,825✔
820
  d_insertDomainKeyQuery_stmt = nullptr;
2,825✔
821
  d_GetLastInsertedKeyIdQuery_stmt = nullptr;
2,825✔
822
  d_activateDomainKeyQuery_stmt = nullptr;
2,825✔
823
  d_deactivateDomainKeyQuery_stmt = nullptr;
2,825✔
824
  d_getTSIGKeyQuery_stmt = nullptr;
2,825✔
825
  d_setTSIGKeyQuery_stmt = nullptr;
2,825✔
826
  d_deleteTSIGKeyQuery_stmt = nullptr;
2,825✔
827
  d_getTSIGKeysQuery_stmt = nullptr;
2,825✔
828

829
  setArgPrefix("bind" + suffix);
2,825✔
830
  d_logprefix = "[bind" + suffix + "backend]";
2,825✔
831
  d_hybrid = mustDo("hybrid");
2,825✔
832
  if (d_hybrid && g_zoneCache.isEnabled()) {
2,825!
833
    throw PDNSException("bind-hybrid and the zone cache currently interoperate badly. Please disable the zone cache or stop using bind-hybrid");
×
834
  }
×
835

836
  d_transaction_id = UnknownDomainID;
2,825✔
837
  s_ignore_broken_records = mustDo("ignore-broken-records");
2,825✔
838
  d_upgradeContent = ::arg().mustDo("upgrade-unknown-types");
2,825✔
839

840
  if (!loadZones && d_hybrid)
2,825!
841
    return;
×
842

843
  auto lock = std::scoped_lock(s_startup_lock);
2,825✔
844

845
  setupDNSSEC();
2,825✔
846
  if (s_first == 0) {
2,825✔
847
    return;
2,157✔
848
  }
2,157✔
849

850
  if (loadZones) {
668✔
851
    loadConfig();
278✔
852
    s_first = 0;
278✔
853
  }
278✔
854

855
  DynListener::registerFunc("BIND-RELOAD-NOW", &DLReloadNowHandler, "bindbackend: reload domains", "<domains>");
668✔
856
  DynListener::registerFunc("BIND-DOMAIN-STATUS", &DLDomStatusHandler, "bindbackend: list status of all domains", "[domains]");
668✔
857
  DynListener::registerFunc("BIND-DOMAIN-EXTENDED-STATUS", &DLDomExtendedStatusHandler, "bindbackend: list the extended status of all domains", "[domains]");
668✔
858
  DynListener::registerFunc("BIND-LIST-REJECTS", &DLListRejectsHandler, "bindbackend: list rejected domains");
668✔
859
  DynListener::registerFunc("BIND-ADD-ZONE", &DLAddDomainHandler, "bindbackend: add zone", "<domain> <filename>");
668✔
860
}
668✔
861

862
Bind2Backend::~Bind2Backend()
863
{
2,705✔
864
  freeStatements();
2,705✔
865
} // deallocate statements
2,705✔
866

867
void Bind2Backend::rediscover(string* status)
868
{
×
869
  loadConfig(status);
×
870
}
×
871

872
void Bind2Backend::reload()
873
{
×
874
  auto state = s_state.write_lock();
×
875
  for (const auto& i : *state) {
×
876
    i.d_checknow = true; // being a bit cheeky here, don't index state_t on this (mutable)
×
877
  }
×
878
}
×
879

880
void Bind2Backend::fixupOrderAndAuth(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
881
{
2,665✔
882
  bool skip;
2,665✔
883
  DNSName shorter;
2,665✔
884
  set<DNSName> nssets, dssets;
2,665✔
885

886
  for (const auto& bdr : *records) {
3,274,084✔
887
    if (!bdr.qname.isRoot() && bdr.qtype == QType::NS)
3,274,084✔
888
      nssets.insert(bdr.qname);
3,010✔
889
    else if (bdr.qtype == QType::DS)
3,271,074✔
890
      dssets.insert(bdr.qname);
499✔
891
  }
3,274,084✔
892

893
  for (auto iter = records->begin(); iter != records->end(); iter++) {
3,276,749✔
894
    skip = false;
3,274,084✔
895
    shorter = iter->qname;
3,274,084✔
896

897
    if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
3,274,084!
898
      do {
3,272,541✔
899
        if (nssets.count(shorter) != 0u) {
3,272,541✔
900
          skip = true;
1,359✔
901
          break;
1,359✔
902
        }
1,359✔
903
      } while (shorter.chopOff() && !iter->qname.isRoot());
3,272,541!
904
    }
3,262,953✔
905

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

908
    if (!skip && nsec3zone && iter->qtype != QType::RRSIG && (iter->auth || (iter->qtype == QType::NS && (ns3pr.d_flags == 0u)) || (dssets.count(iter->qname) != 0u))) {
3,274,084✔
909
      Bind2DNSRecord bdr = *iter;
1,439,445✔
910
      bdr.nsec3hash = toBase32Hex(hashQNameWithSalt(ns3pr, bdr.qname + zoneName.operator const DNSName&()));
1,439,445✔
911
      records->replace(iter, bdr);
1,439,445✔
912
    }
1,439,445✔
913

914
    // cerr<<iter->qname<<"\t"<<QType(iter->qtype).toString()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
915
  }
3,274,084✔
916
}
2,665✔
917

918
void Bind2Backend::doEmptyNonTerminals(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
919
{
2,665✔
920
  bool auth = false;
2,665✔
921
  DNSName shorter;
2,665✔
922
  std::unordered_set<DNSName> qnames;
2,665✔
923
  std::unordered_map<DNSName, bool> nonterm;
2,665✔
924

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

927
  for (const auto& bdr : *records)
2,665✔
928
    qnames.insert(bdr.qname);
3,274,084✔
929

930
  for (const auto& bdr : *records) {
3,274,084✔
931

932
    if (!bdr.auth && bdr.qtype == QType::NS)
3,274,084✔
933
      auth = (!nsec3zone || (ns3pr.d_flags == 0u));
3,010✔
934
    else
3,271,074✔
935
      auth = bdr.auth;
3,271,074✔
936

937
    shorter = bdr.qname;
3,274,084✔
938
    while (shorter.chopOff()) {
6,547,984✔
939
      if (qnames.count(shorter) == 0u) {
3,273,900✔
940
        if (!(maxent)) {
9,422!
941
          g_log << Logger::Error << "Zone '" << zoneName << "' has too many empty non terminals." << endl;
×
942
          return;
×
943
        }
×
944

945
        if (nonterm.count(shorter) == 0u) {
9,422✔
946
          nonterm.emplace(shorter, auth);
4,616✔
947
          --maxent;
4,616✔
948
        }
4,616✔
949
        else if (auth)
4,806✔
950
          nonterm[shorter] = true;
4,710✔
951
      }
9,422✔
952
    }
3,273,900✔
953
  }
3,274,084✔
954

955
  DNSResourceRecord rr;
2,665✔
956
  rr.qtype = "#0";
2,665✔
957
  rr.content = "";
2,665✔
958
  rr.ttl = 0;
2,665✔
959
  for (auto& nt : nonterm) {
4,617✔
960
    string hashed;
4,616✔
961
    rr.qname = nt.first + zoneName.operator const DNSName&();
4,616✔
962
    if (nsec3zone && nt.second)
4,616✔
963
      hashed = toBase32Hex(hashQNameWithSalt(ns3pr, rr.qname));
1,782✔
964
    insertRecord(records, zoneName, rr.qname, rr.qtype, rr.content, rr.ttl, hashed, &nt.second);
4,616✔
965

966
    // cerr<<rr.qname<<"\t"<<rr.qtype.toString()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
967
  }
4,616✔
968
}
2,665✔
969

970
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
971
{
278✔
972
  static domainid_t domain_id = 1;
278✔
973

974
  if (!getArg("config").empty()) {
278!
975
    BindParser BP;
278✔
976
    try {
278✔
977
      BP.parse(getArg("config"));
278✔
978
    }
278✔
979
    catch (PDNSException& ae) {
278✔
980
      g_log << Logger::Error << "Error parsing bind configuration: " << ae.reason << endl;
×
981
      throw;
×
982
    }
×
983

984
    vector<BindDomainInfo> domains = BP.getDomains();
278✔
985
    this->alsoNotify = BP.getAlsoNotify();
278✔
986

987
    s_binddirectory = BP.getDirectory();
278✔
988
    //    ZP.setDirectory(d_binddirectory);
989

990
    g_log << Logger::Warning << d_logprefix << " Parsing " << domains.size() << " domain(s), will report when done" << endl;
278✔
991

992
    set<ZoneName> oldnames;
278✔
993
    set<ZoneName> newnames;
278✔
994
    {
278✔
995
      auto state = s_state.read_lock();
278✔
996
      for (const BB2DomainInfo& bbd : *state) {
278!
997
        oldnames.insert(bbd.d_name);
×
998
      }
×
999
    }
278✔
1000
    int rejected = 0;
278✔
1001
    int newdomains = 0;
278✔
1002

1003
    struct stat st;
278✔
1004

1005
    for (auto& domain : domains) {
2,758✔
1006
      if (stat(domain.filename.c_str(), &st) == 0) {
2,659✔
1007
        domain.d_dev = st.st_dev;
2,587✔
1008
        domain.d_ino = st.st_ino;
2,587✔
1009
      }
2,587✔
1010
    }
2,659✔
1011

1012
    sort(domains.begin(), domains.end()); // put stuff in inode order
278✔
1013
    for (const auto& domain : domains) {
2,758✔
1014
      if (!(domain.hadFileDirective)) {
2,659!
1015
        g_log << Logger::Warning << d_logprefix << " Zone '" << domain.name << "' has no 'file' directive set in " << getArg("config") << endl;
×
1016
        rejected++;
×
1017
        continue;
×
1018
      }
×
1019

1020
      if (domain.type.empty()) {
2,659!
1021
        g_log << Logger::Notice << d_logprefix << " Zone '" << domain.name << "' has no type specified, assuming 'native'" << endl;
×
1022
      }
×
1023
      if (domain.type != "primary" && domain.type != "secondary" && domain.type != "native" && !domain.type.empty() && domain.type != "master" && domain.type != "slave") {
2,659!
1024
        g_log << Logger::Warning << d_logprefix << " Warning! Skipping zone '" << domain.name << "' because type '" << domain.type << "' is invalid" << endl;
×
1025
        rejected++;
×
1026
        continue;
×
1027
      }
×
1028

1029
      BB2DomainInfo bbd;
2,659✔
1030
      bool isNew = false;
2,659✔
1031

1032
      if (!safeGetBBDomainInfo(domain.name, &bbd)) {
2,659!
1033
        isNew = true;
2,659✔
1034
        bbd.d_id = domain_id++;
2,659✔
1035
        bbd.setCheckInterval(getArgAsNum("check-interval"));
2,659✔
1036
        bbd.d_lastnotified = 0;
2,659✔
1037
        bbd.d_loaded = false;
2,659✔
1038
      }
2,659✔
1039

1040
      // overwrite what we knew about the domain
1041
      bbd.d_name = domain.name;
2,659✔
1042
      bool filenameChanged = (bbd.d_filename != domain.filename);
2,659✔
1043
      bool addressesChanged = (bbd.d_primaries != domain.primaries || bbd.d_also_notify != domain.alsoNotify);
2,659!
1044
      bbd.d_filename = domain.filename;
2,659✔
1045
      bbd.d_primaries = domain.primaries;
2,659✔
1046
      bbd.d_also_notify = domain.alsoNotify;
2,659✔
1047

1048
      DomainInfo::DomainKind kind = DomainInfo::Native;
2,659✔
1049
      if (domain.type == "primary" || domain.type == "master") {
2,659!
1050
        kind = DomainInfo::Primary;
2,587✔
1051
      }
2,587✔
1052
      if (domain.type == "secondary" || domain.type == "slave") {
2,659!
1053
        kind = DomainInfo::Secondary;
72✔
1054
      }
72✔
1055

1056
      bool kindChanged = (bbd.d_kind != kind);
2,659✔
1057
      bbd.d_kind = kind;
2,659✔
1058

1059
      newnames.insert(bbd.d_name);
2,659✔
1060
      if (filenameChanged || !bbd.d_loaded || !bbd.current()) {
2,659!
1061
        g_log << Logger::Info << d_logprefix << " parsing '" << domain.name << "' from file '" << domain.filename << "'" << endl;
2,659✔
1062

1063
        try {
2,659✔
1064
          parseZoneFile(&bbd);
2,659✔
1065
        }
2,659✔
1066
        catch (PDNSException& ae) {
2,659✔
1067
          ostringstream msg;
×
1068
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.reason;
×
1069

1070
          if (status != nullptr)
×
1071
            *status += msg.str();
×
1072
          bbd.d_status = msg.str();
×
1073

1074
          g_log << Logger::Warning << d_logprefix << msg.str() << endl;
×
1075
          rejected++;
×
1076
        }
×
1077
        catch (std::system_error& ae) {
2,659✔
1078
          ostringstream msg;
72✔
1079
          if (ae.code().value() == ENOENT && isNew && domain.type == "slave")
72!
1080
            msg << " error at " + nowTime() << " no file found for new secondary domain '" << domain.name << "'. Has not been AXFR'd yet";
×
1081
          else
72✔
1082
            msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
72✔
1083

1084
          if (status != nullptr)
72!
1085
            *status += msg.str();
×
1086
          bbd.d_status = msg.str();
72✔
1087
          g_log << Logger::Warning << d_logprefix << msg.str() << endl;
72✔
1088
          rejected++;
72✔
1089
        }
72✔
1090
        catch (std::exception& ae) {
2,659✔
1091
          ostringstream msg;
×
1092
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
×
1093

1094
          if (status != nullptr)
×
1095
            *status += msg.str();
×
1096
          bbd.d_status = msg.str();
×
1097

1098
          g_log << Logger::Warning << d_logprefix << msg.str() << endl;
×
1099
          rejected++;
×
1100
        }
×
1101
        safePutBBDomainInfo(bbd);
2,659✔
1102
      }
2,659✔
1103
      else if (addressesChanged || kindChanged) {
×
1104
        safePutBBDomainInfo(bbd);
×
1105
      }
×
1106
    }
2,659✔
1107
    vector<ZoneName> diff;
278✔
1108

1109
    set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
278✔
1110
    unsigned int remdomains = diff.size();
278✔
1111

1112
    for (const ZoneName& name : diff) {
278!
1113
      safeRemoveBBDomainInfo(name);
×
1114
    }
×
1115

1116
    // count number of entirely new domains
1117
    diff.clear();
278✔
1118
    set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
278✔
1119
    newdomains = diff.size();
278✔
1120

1121
    ostringstream msg;
278✔
1122
    msg << " Done parsing domains, " << rejected << " rejected, " << newdomains << " new, " << remdomains << " removed";
278✔
1123
    if (status != nullptr)
278!
1124
      *status = msg.str();
×
1125

1126
    g_log << Logger::Error << d_logprefix << msg.str() << endl;
278✔
1127
  }
278✔
1128
}
278✔
1129

1130
// NOLINTNEXTLINE(readability-identifier-length)
1131
void Bind2Backend::queueReloadAndStore(domainid_t id)
1132
{
78✔
1133
  BB2DomainInfo bbold;
78✔
1134
  try {
78✔
1135
    if (!safeGetBBDomainInfo(id, &bbold))
78!
1136
      return;
×
1137
    bbold.d_checknow = false;
78✔
1138
    BB2DomainInfo bbnew(bbold);
78✔
1139
    /* make sure that nothing will be able to alter the existing records,
1140
       we will load them from the zone file instead */
1141
    bbnew.d_records = LookButDontTouch<recordstorage_t>();
78✔
1142
    parseZoneFile(&bbnew);
78✔
1143
    bbnew.d_wasRejectedLastReload = false;
78✔
1144
    safePutBBDomainInfo(bbnew);
78✔
1145
    g_log << Logger::Warning << "Zone '" << bbnew.d_name << "' (" << bbnew.d_filename << ") reloaded" << endl;
78✔
1146
  }
78✔
1147
  catch (PDNSException& ae) {
78✔
1148
    ostringstream msg;
×
1149
    msg << " error at " + nowTime() + " parsing '" << bbold.d_name << "' from file '" << bbold.d_filename << "': " << ae.reason;
×
1150
    g_log << Logger::Warning << "Error parsing '" << bbold.d_name << "' from file '" << bbold.d_filename << "': " << ae.reason << endl;
×
1151
    bbold.d_status = msg.str();
×
1152
    bbold.d_lastcheck = time(nullptr);
×
1153
    bbold.d_wasRejectedLastReload = true;
×
1154
    safePutBBDomainInfo(bbold);
×
1155
  }
×
1156
  catch (std::exception& ae) {
78✔
1157
    ostringstream msg;
×
1158
    msg << " error at " + nowTime() + " parsing '" << bbold.d_name << "' from file '" << bbold.d_filename << "': " << ae.what();
×
1159
    g_log << Logger::Warning << "Error parsing '" << bbold.d_name << "' from file '" << bbold.d_filename << "': " << ae.what() << endl;
×
1160
    bbold.d_status = msg.str();
×
1161
    bbold.d_lastcheck = time(nullptr);
×
1162
    bbold.d_wasRejectedLastReload = true;
×
1163
    safePutBBDomainInfo(bbold);
×
1164
  }
×
1165
}
78✔
1166

1167
bool Bind2Backend::findBeforeAndAfterUnhashed(std::shared_ptr<const recordstorage_t>& records, const DNSName& qname, DNSName& /* unhashed */, DNSName& before, DNSName& after)
1168
{
2,710✔
1169
  // for(const auto& record: *records)
1170
  //   cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
1171

1172
  recordstorage_t::const_iterator iterBefore, iterAfter;
2,710✔
1173

1174
  iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
2,710✔
1175

1176
  if (iterBefore != records->begin())
2,710✔
1177
    --iterBefore;
2,709✔
1178
  while ((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
3,239✔
1179
    --iterBefore;
529✔
1180
  before = iterBefore->qname;
2,710✔
1181

1182
  if (iterAfter == records->end()) {
2,710✔
1183
    iterAfter = records->begin();
376✔
1184
  }
376✔
1185
  else {
2,334✔
1186
    while ((!iterAfter->auth && iterAfter->qtype != QType::NS) || !iterAfter->qtype) {
3,498✔
1187
      ++iterAfter;
1,164✔
1188
      if (iterAfter == records->end()) {
1,164!
1189
        iterAfter = records->begin();
×
1190
        break;
×
1191
      }
×
1192
    }
1,164✔
1193
  }
2,334✔
1194
  after = iterAfter->qname;
2,710✔
1195

1196
  return true;
2,710✔
1197
}
2,710✔
1198

1199
// NOLINTNEXTLINE(readability-identifier-length)
1200
bool Bind2Backend::getBeforeAndAfterNamesAbsolute(domainid_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
1201
{
7,040✔
1202
  BB2DomainInfo bbd;
7,040✔
1203
  if (!safeGetBBDomainInfo(id, &bbd))
7,040!
1204
    return false;
×
1205

1206
  shared_ptr<const recordstorage_t> records = bbd.d_records.get();
7,040✔
1207
  if (!bbd.d_nsec3zone) {
7,040✔
1208
    return findBeforeAndAfterUnhashed(records, qname, unhashed, before, after);
2,710✔
1209
  }
2,710✔
1210
  else {
4,330✔
1211
    const auto& hashindex = boost::multi_index::get<NSEC3Tag>(*records);
4,330✔
1212

1213
    // for(auto iter = first; iter != hashindex.end(); iter++)
1214
    //  cerr<<iter->nsec3hash<<endl;
1215

1216
    auto first = hashindex.upper_bound("");
4,330✔
1217
    auto iter = hashindex.upper_bound(qname.toStringNoDot());
4,330✔
1218

1219
    if (iter == hashindex.end()) {
4,330✔
1220
      --iter;
360✔
1221
      before = DNSName(iter->nsec3hash);
360✔
1222
      after = DNSName(first->nsec3hash);
360✔
1223
    }
360✔
1224
    else {
3,970✔
1225
      after = DNSName(iter->nsec3hash);
3,970✔
1226
      if (iter != first)
3,970✔
1227
        --iter;
3,894✔
1228
      else
76✔
1229
        iter = --hashindex.end();
76✔
1230
      before = DNSName(iter->nsec3hash);
3,970✔
1231
    }
3,970✔
1232
    unhashed = iter->qname + bbd.d_name.operator const DNSName&();
4,330✔
1233

1234
    return true;
4,330✔
1235
  }
4,330✔
1236
}
7,040✔
1237

1238
void Bind2Backend::lookup(const QType& qtype, const DNSName& qname, domainid_t zoneId, DNSPacket* /* pkt_p */)
1239
{
4,128✔
1240
  d_handle.reset();
4,128✔
1241

1242
  static bool mustlog = ::arg().mustDo("query-logging");
4,128✔
1243

1244
  bool found = false;
4,128✔
1245
  ZoneName domain;
4,128✔
1246
  BB2DomainInfo bbd;
4,128✔
1247

1248
  if (mustlog)
4,128!
1249
    g_log << Logger::Warning << "Lookup for '" << qtype.toString() << "' of '" << qname << "' within zoneID " << zoneId << endl;
×
1250

1251
  if (zoneId != UnknownDomainID) {
4,128✔
1252
    if ((found = (safeGetBBDomainInfo(zoneId, &bbd) && qname.isPartOf(bbd.d_name)))) {
3,519!
1253
      domain = std::move(bbd.d_name);
3,519✔
1254
    }
3,519✔
1255
  }
3,519✔
1256
  else {
609✔
1257
    domain = ZoneName(qname);
609✔
1258
    do {
612✔
1259
      found = safeGetBBDomainInfo(domain, &bbd);
612✔
1260
    } while (!found && qtype != QType::SOA && domain.chopOff());
612✔
1261
  }
609✔
1262

1263
  if (!found) {
4,128✔
1264
    if (mustlog)
19!
1265
      g_log << Logger::Warning << "Found no authoritative zone for '" << qname << "' and/or id " << zoneId << endl;
×
1266
    d_handle.d_list = false;
19✔
1267
    return;
19✔
1268
  }
19✔
1269

1270
  if (mustlog)
4,109!
1271
    g_log << Logger::Warning << "Found a zone '" << domain << "' (with id " << bbd.d_id << ") that might contain data " << endl;
×
1272

1273
  d_handle.id = bbd.d_id;
4,109✔
1274
  d_handle.qname = qname.makeRelative(domain); // strip domain name
4,109✔
1275
  d_handle.qtype = qtype;
4,109✔
1276
  d_handle.domain = std::move(domain);
4,109✔
1277

1278
  if (!bbd.current()) {
4,109✔
1279
    g_log << Logger::Warning << "Zone '" << d_handle.domain << "' (" << bbd.d_filename << ") needs reloading" << endl;
6✔
1280
    queueReloadAndStore(bbd.d_id);
6✔
1281
    if (!safeGetBBDomainInfo(d_handle.domain, &bbd))
6!
1282
      throw DBException("Zone '" + bbd.d_name.toLogString() + "' (" + bbd.d_filename + ") gone after reload"); // if we don't throw here, we crash for some reason
×
1283
  }
6✔
1284

1285
  if (!bbd.d_loaded) {
4,109✔
1286
    d_handle.reset();
216✔
1287
    throw DBException("Zone for '" + d_handle.domain.toLogString() + "' in '" + bbd.d_filename + "' not loaded (file missing, corrupt or primary dead)"); // fsck
216✔
1288
  }
216✔
1289

1290
  d_handle.d_records = bbd.d_records.get();
3,893✔
1291

1292
  if (d_handle.d_records->empty())
3,893!
1293
    DLOG(g_log << "Query with no results" << endl);
×
1294

1295
  d_handle.mustlog = mustlog;
3,893✔
1296

1297
  const auto& hashedidx = boost::multi_index::get<UnorderedNameTag>(*d_handle.d_records);
3,893✔
1298
  auto range = hashedidx.equal_range(d_handle.qname);
3,893✔
1299

1300
  d_handle.d_list = false;
3,893✔
1301
  d_handle.d_iter = range.first;
3,893✔
1302
  d_handle.d_end_iter = range.second;
3,893✔
1303
}
3,893✔
1304

1305
Bind2Backend::handle::handle()
1306
{
2,825✔
1307
  mustlog = false;
2,825✔
1308
}
2,825✔
1309

1310
bool Bind2Backend::get(DNSResourceRecord& r)
1311
{
197,887✔
1312
  if (!d_handle.d_records) {
197,887✔
1313
    if (d_handle.mustlog)
19!
1314
      g_log << Logger::Warning << "There were no answers" << endl;
×
1315
    return false;
19✔
1316
  }
19✔
1317

1318
  if (!d_handle.get(r)) {
197,868✔
1319
    if (d_handle.mustlog)
4,224!
1320
      g_log << Logger::Warning << "End of answers" << endl;
×
1321

1322
    d_handle.reset();
4,224✔
1323

1324
    return false;
4,224✔
1325
  }
4,224✔
1326
  if (d_handle.mustlog)
193,644!
1327
    g_log << Logger::Warning << "Returning: '" << r.qtype.toString() << "' of '" << r.qname << "', content: '" << r.content << "'" << endl;
×
1328
  return true;
193,644✔
1329
}
197,868✔
1330

1331
bool Bind2Backend::handle::get(DNSResourceRecord& r)
1332
{
197,868✔
1333
  if (d_list)
197,868✔
1334
    return get_list(r);
188,900✔
1335
  else
8,968✔
1336
    return get_normal(r);
8,968✔
1337
}
197,868✔
1338

1339
void Bind2Backend::handle::reset()
1340
{
8,899✔
1341
  d_records.reset();
8,899✔
1342
  qname.clear();
8,899✔
1343
  mustlog = false;
8,899✔
1344
}
8,899✔
1345

1346
//#define DLOG(x) x
1347
bool Bind2Backend::handle::get_normal(DNSResourceRecord& r)
1348
{
8,968✔
1349
  DLOG(g_log << "Bind2Backend get() was called for " << qtype.toString() << " record for '" << qname << "' - " << d_records->size() << " available in total!" << endl);
8,968✔
1350

1351
  if (d_iter == d_end_iter) {
8,968✔
1352
    return false;
3,893✔
1353
  }
3,893✔
1354

1355
  while (d_iter != d_end_iter && !(qtype.getCode() == QType::ANY || (d_iter)->qtype == qtype.getCode())) {
7,808!
1356
    DLOG(g_log << Logger::Warning << "Skipped " << qname << "/" << QType(d_iter->qtype).toString() << ": '" << d_iter->content << "'" << endl);
2,733✔
1357
    d_iter++;
2,733✔
1358
  }
2,733✔
1359
  if (d_iter == d_end_iter) {
5,075!
1360
    return false;
×
1361
  }
×
1362
  DLOG(g_log << "Bind2Backend get() returning a rr with a " << QType(d_iter->qtype).getCode() << endl);
5,075✔
1363

1364
  const DNSName& domainName(domain);
5,075✔
1365
  r.qname = qname.empty() ? domainName : (qname + domainName);
5,075!
1366
  r.domain_id = id;
5,075✔
1367
  r.content = (d_iter)->content;
5,075✔
1368
  //  r.domain_id=(d_iter)->domain_id;
1369
  r.qtype = (d_iter)->qtype;
5,075✔
1370
  r.ttl = (d_iter)->ttl;
5,075✔
1371

1372
  //if(!d_iter->auth && r.qtype.getCode() != QType::A && r.qtype.getCode()!=QType::AAAA && r.qtype.getCode() != QType::NS)
1373
  //  cerr<<"Warning! Unauth response for qtype "<< r.qtype.toString() << " for '"<<r.qname<<"'"<<endl;
1374
  r.auth = d_iter->auth;
5,075✔
1375

1376
  d_iter++;
5,075✔
1377

1378
  return true;
5,075✔
1379
}
5,075✔
1380

1381
bool Bind2Backend::list(const ZoneName& /* target */, domainid_t domainId, bool /* include_disabled */)
1382
{
331✔
1383
  BB2DomainInfo bbd;
331✔
1384

1385
  if (!safeGetBBDomainInfo(domainId, &bbd)) {
331!
1386
    return false;
×
1387
  }
×
1388

1389
  d_handle.reset();
331✔
1390
  DLOG(g_log << "Bind2Backend constructing handle for list of " << domainId << endl);
331✔
1391

1392
  if (!bbd.d_loaded) {
331!
1393
    throw PDNSException("zone was not loaded, perhaps because of: " + bbd.d_status);
×
1394
  }
×
1395

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

1400
  d_handle.id = domainId;
331✔
1401
  d_handle.domain = bbd.d_name;
331✔
1402
  d_handle.d_list = true;
331✔
1403
  return true;
331✔
1404
}
331✔
1405

1406
bool Bind2Backend::handle::get_list(DNSResourceRecord& r)
1407
{
188,900✔
1408
  if (d_qname_iter != d_qname_end) {
188,900✔
1409
    const DNSName& domainName(domain);
188,569✔
1410
    r.qname = d_qname_iter->qname.empty() ? domainName : (d_qname_iter->qname + domainName);
188,569!
1411
    r.domain_id = id;
188,569✔
1412
    r.content = (d_qname_iter)->content;
188,569✔
1413
    r.qtype = (d_qname_iter)->qtype;
188,569✔
1414
    r.ttl = (d_qname_iter)->ttl;
188,569✔
1415
    r.auth = d_qname_iter->auth;
188,569✔
1416
    d_qname_iter++;
188,569✔
1417
    return true;
188,569✔
1418
  }
188,569✔
1419
  return false;
331✔
1420
}
188,900✔
1421

1422
bool Bind2Backend::autoPrimariesList(std::vector<AutoPrimary>& primaries)
1423
{
×
1424
  if (getArg("autoprimary-config").empty())
×
1425
    return false;
×
1426

1427
  ifstream c_if(getArg("autoprimaries"), std::ios::in);
×
1428
  if (!c_if) {
×
1429
    g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl;
×
1430
    return false;
×
1431
  }
×
1432

1433
  string line, sip, saccount;
×
1434
  while (getline(c_if, line)) {
×
1435
    std::istringstream ii(line);
×
1436
    ii >> sip;
×
1437
    if (!sip.empty()) {
×
1438
      ii >> saccount;
×
1439
      primaries.emplace_back(sip, "", saccount);
×
1440
    }
×
1441
  }
×
1442

1443
  c_if.close();
×
1444
  return true;
×
1445
}
×
1446

1447
bool Bind2Backend::autoPrimaryBackend(const string& ipAddress, const ZoneName& /* domain */, const vector<DNSResourceRecord>& /* nsset */, string* /* nameserver */, string* account, DNSBackend** backend)
1448
{
×
1449
  // Check whether we have a configfile available.
1450
  if (getArg("autoprimary-config").empty())
×
1451
    return false;
×
1452

1453
  ifstream c_if(getArg("autoprimaries").c_str(), std::ios::in); // this was nocreate?
×
1454
  if (!c_if) {
×
1455
    g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl;
×
1456
    return false;
×
1457
  }
×
1458

1459
  // Format:
1460
  // <ip> <accountname>
1461
  string line, sip, saccount;
×
1462
  while (getline(c_if, line)) {
×
1463
    std::istringstream ii(line);
×
1464
    ii >> sip;
×
1465
    if (sip == ipAddress) {
×
1466
      ii >> saccount;
×
1467
      break;
×
1468
    }
×
1469
  }
×
1470
  c_if.close();
×
1471

1472
  if (sip != ipAddress) { // ip not found in authorization list - reject
×
1473
    return false;
×
1474
  }
×
1475

1476
  // ip authorized as autoprimary - accept
1477
  *backend = this;
×
1478
  if (saccount.length() > 0)
×
1479
    *account = saccount.c_str();
×
1480

1481
  return true;
×
1482
}
×
1483

1484
BB2DomainInfo Bind2Backend::createDomainEntry(const ZoneName& domain, const string& filename)
1485
{
6✔
1486
  domainid_t newid = 1;
6✔
1487
  { // Find a free zone id nr.
6✔
1488
    auto state = s_state.read_lock();
6✔
1489
    if (!state->empty()) {
6!
1490
      // older (1.53) versions of boost have an expression for s_state.rbegin()
1491
      // that is ambiguous in C++17. So construct it explicitly
1492
      newid = boost::make_reverse_iterator(state->end())->d_id + 1;
6✔
1493
    }
6✔
1494
  }
6✔
1495

1496
  BB2DomainInfo bbd;
6✔
1497
  bbd.d_kind = DomainInfo::Native;
6✔
1498
  bbd.d_id = newid;
6✔
1499
  bbd.d_records = std::make_shared<recordstorage_t>();
6✔
1500
  bbd.d_name = domain;
6✔
1501
  bbd.setCheckInterval(getArgAsNum("check-interval"));
6✔
1502
  bbd.d_filename = filename;
6✔
1503

1504
  return bbd;
6✔
1505
}
6✔
1506

1507
bool Bind2Backend::createSecondaryDomain(const string& ipAddress, const ZoneName& domain, const string& /* nameserver */, const string& account)
1508
{
×
1509
  std::string domainname = domain.toStringNoDot();
×
1510

1511
  // Reject domain name if it embeds quotes; this may happen if 8bit-dns is
1512
  // used, and bind currently does not allow for character escapes in zone
1513
  // names.
1514
  if (domainname.find_first_of("\"") != std::string::npos) {
×
1515
    SLOG(g_log << Logger::Error << d_logprefix
×
1516
               << " Unable to accept autosecondary zone '" << domain
×
1517
               << "' from autoprimary " << ipAddress
×
1518
               << " due to unauthorized characters in domain name for bind configuration file"
×
1519
               << endl,
×
1520
         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)));
×
1521
    throw PDNSException("Unauthorized characters in domain name for bind configuration file");
×
1522
  }
×
1523

1524
  string filename = getArg("autoprimary-destdir") + '/';
×
1525
  if (domainname.empty()) {
×
1526
    filename.append("rootzone.");
×
1527
  }
×
1528
  else {
×
1529
    // Make sure the zone file name does not contain path separators.
1530
    filename.append(boost::replace_all_copy(domainname, "/", "\\047"));
×
1531
  }
×
1532

1533
  g_log << Logger::Warning << d_logprefix
×
1534
        << " Writing bind config zone statement for superslave zone '" << domain
×
1535
        << "' from autoprimary " << ipAddress << endl;
×
1536

1537
  {
×
1538
    auto lock = std::scoped_lock(s_autosecondary_config_lock);
×
1539

1540
    ofstream c_of(getArg("autoprimary-config").c_str(), std::ios::app);
×
1541
    if (!c_of) {
×
1542
      g_log << Logger::Error << "Unable to open autoprimary configfile for append: " << stringerror() << endl;
×
1543
      throw DBException("Unable to open autoprimary configfile for append: " + stringerror());
×
1544
    }
×
1545

1546
    c_of << endl;
×
1547
    c_of << "# AutoSecondary zone '" << domainname << "' (added: " << nowTime() << ") (account: " << account << ')' << endl;
×
1548
    c_of << "zone \"" << domainname << "\" {" << endl;
×
1549
    c_of << "\ttype secondary;" << endl;
×
1550
    c_of << "\tfile \"" << filename << "\";" << endl;
×
1551
    c_of << "\tprimaries { " << ipAddress << "; };" << endl;
×
1552
    c_of << "};" << endl;
×
1553
    c_of.close();
×
1554
  }
×
1555

1556
  BB2DomainInfo bbd = createDomainEntry(domain, filename);
×
1557
  bbd.d_kind = DomainInfo::Secondary;
×
1558
  bbd.d_primaries.emplace_back(ComboAddress(ipAddress, 53));
×
1559
  bbd.setCtime();
×
1560
  safePutBBDomainInfo(bbd);
×
1561

1562
  return true;
×
1563
}
×
1564

1565
bool Bind2Backend::searchRecords(const string& pattern, size_t maxResults, vector<DNSResourceRecord>& result)
1566
{
18✔
1567
  SimpleMatch sm(pattern, true);
18✔
1568
  static bool mustlog = ::arg().mustDo("query-logging");
18✔
1569
  if (mustlog)
18!
1570
    g_log << Logger::Warning << "Search for pattern '" << pattern << "'" << endl;
×
1571

1572
  {
18✔
1573
    auto state = s_state.read_lock();
18✔
1574

1575
    for (const auto& i : *state) {
18!
1576
      BB2DomainInfo h;
×
1577
      if (!safeGetBBDomainInfo(i.d_id, &h)) {
×
1578
        continue;
×
1579
      }
×
1580

1581
      if (!h.d_loaded) {
×
1582
        continue;
×
1583
      }
×
1584

1585
      shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
×
1586

1587
      for (recordstorage_t::const_iterator ri = rhandle->begin(); result.size() < maxResults && ri != rhandle->end(); ri++) {
×
1588
        const DNSName& domainName(i.d_name);
×
1589
        DNSName name = ri->qname.empty() ? domainName : (ri->qname + domainName);
×
1590
        if (sm.match(name) || sm.match(ri->content)) {
×
1591
          DNSResourceRecord r;
×
1592
          r.qname = std::move(name);
×
1593
          r.domain_id = i.d_id;
×
1594
          r.content = ri->content;
×
1595
          r.qtype = ri->qtype;
×
1596
          r.ttl = ri->ttl;
×
1597
          r.auth = ri->auth;
×
1598
          result.push_back(std::move(r));
×
1599
        }
×
1600
      }
×
1601
    }
×
1602
  }
18✔
1603

1604
  return true;
18✔
1605
}
18✔
1606

1607
class Bind2Factory : public BackendFactory
1608
{
1609
public:
1610
  Bind2Factory() :
1611
    BackendFactory("bind") {}
5,776✔
1612

1613
  void declareArguments(const string& suffix = "") override
1614
  {
502✔
1615
    declare(suffix, "ignore-broken-records", "Ignore records that are out-of-bound for the zone.", "no");
502✔
1616
    declare(suffix, "config", "Location of named.conf", "");
502✔
1617
    declare(suffix, "check-interval", "Interval for zonefile changes", "0");
502✔
1618
    declare(suffix, "autoprimary-config", "Location of (part of) named.conf where pdns can write zone-statements to", "");
502✔
1619
    declare(suffix, "autoprimaries", "List of IP-addresses of autoprimaries", "");
502✔
1620
    declare(suffix, "autoprimary-destdir", "Destination directory for newly added secondary zones", ::arg()["config-dir"]);
502✔
1621
    declare(suffix, "dnssec-db", "Filename to store & access our DNSSEC metadatabase, empty for none", "");
502✔
1622
    declare(suffix, "dnssec-db-journal-mode", "SQLite3 journal mode", "WAL");
502✔
1623
    declare(suffix, "hybrid", "Store DNSSEC metadata in other backend", "no");
502✔
1624
  }
502✔
1625

1626
  DNSBackend* make(const string& suffix = "") override
1627
  {
1,972✔
1628
    assertEmptySuffix(suffix);
1,972✔
1629
    return new Bind2Backend(suffix);
1,972✔
1630
  }
1,972✔
1631

1632
  DNSBackend* makeMetadataOnly(const string& suffix = "") override
1633
  {
847✔
1634
    assertEmptySuffix(suffix);
847✔
1635
    return new Bind2Backend(suffix, false);
847✔
1636
  }
847✔
1637

1638
private:
1639
  void assertEmptySuffix(const string& suffix)
1640
  {
2,819✔
1641
    if (!suffix.empty())
2,819!
1642
      throw PDNSException("launch= suffixes are not supported on the bindbackend");
×
1643
  }
2,819✔
1644
};
1645

1646
//! Magic class that is activated when the dynamic library is loaded
1647
class Bind2Loader
1648
{
1649
public:
1650
  Bind2Loader()
1651
  {
5,776✔
1652
    BackendMakers().report(std::make_unique<Bind2Factory>());
5,776✔
1653
    g_log << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
5,776✔
1654
#ifndef REPRODUCIBLE
5,776✔
1655
          << " (" __DATE__ " " __TIME__ ")"
5,776✔
1656
#endif
5,776✔
1657
#ifdef HAVE_SQLITE3
5,776✔
1658
          << " (with bind-dnssec-db support)"
5,776✔
1659
#endif
5,776✔
1660
          << " reporting" << endl;
5,776✔
1661
  }
5,776✔
1662
};
1663
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