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

PowerDNS / pdns / 20618548088

31 Dec 2025 12:00PM UTC coverage: 72.648% (-0.7%) from 73.336%
20618548088

Pull #16693

github

web-flow
Merge 3f7d9a75b into 65de281db
Pull Request #16693: auth: plumbing for structured logging

39009 of 65430 branches covered (59.62%)

Branch coverage included in aggregate %.

807 of 2400 new or added lines in 58 files covered. (33.63%)

200 existing lines in 39 files now uncovered.

129187 of 166092 relevant lines covered (77.78%)

5266744.49 hits per line

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

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

104
  if (!d_checkinterval)
4,120!
105
    return true;
4,120✔
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,181✔
142
  auto state = s_state.read_lock();
11,181✔
143
  state_t::const_iterator iter = state->find(id);
11,181✔
144
  if (iter == state->end()) {
11,181!
145
    return false;
×
146
  }
×
147
  *bbd = *iter;
11,181✔
148
  return true;
11,181✔
149
}
11,181✔
150

151
bool Bind2Backend::safeGetBBDomainInfo(const ZoneName& name, BB2DomainInfo* bbd)
152
{
4,339✔
153
  auto state = s_state.read_lock();
4,339✔
154
  const auto& nameindex = boost::multi_index::get<NameTag>(*state);
4,339✔
155
  auto iter = nameindex.find(name);
4,339✔
156
  if (iter == nameindex.end()) {
4,339✔
157
    return false;
3,292✔
158
  }
3,292✔
159
  *bbd = *iter;
1,047✔
160
  return true;
1,047✔
161
}
4,339✔
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
static bool ciEqual(const string& lhs, const string& rhs)
291
{
432✔
292
  if (lhs.size() != rhs.size()) {
432✔
293
    return false;
408✔
294
  }
408✔
295

296
  string::size_type pos = 0;
24✔
297
  const string::size_type epos = lhs.size();
24✔
298
  for (; pos < epos; ++pos) {
384✔
299
    if (dns_tolower(lhs[pos]) != dns_tolower(rhs[pos])) {
368✔
300
      return false;
8✔
301
    }
8✔
302
  }
368✔
303
  return true;
16✔
304
}
24✔
305

306
/** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */
307
static bool endsOn(const string& domain, const string& suffix)
308
{
432✔
309
  if (suffix.empty() || ciEqual(domain, suffix)) {
432!
310
    return true;
16✔
311
  }
16✔
312

313
  if (domain.size() <= suffix.size()) {
416✔
314
    return false;
52✔
315
  }
52✔
316

317
  string::size_type dpos = domain.size() - suffix.size() - 1;
364✔
318
  string::size_type spos = 0;
364✔
319

320
  if (domain[dpos++] != '.') {
364✔
321
    return false;
88✔
322
  }
88✔
323

324
  for (; dpos < domain.size(); ++dpos, ++spos) {
3,928✔
325
    if (dns_tolower(domain[dpos]) != dns_tolower(suffix[spos])) {
3,664✔
326
      return false;
12✔
327
    }
12✔
328
  }
3,664✔
329

330
  return true;
264✔
331
}
276✔
332

333
/** strips a domain suffix from a domain, returns true if it stripped */
334
static bool stripDomainSuffix(string* qname, const ZoneName& zonename)
335
{
432✔
336
  std::string domain = zonename.operator const DNSName&().toString();
432✔
337

338
  if (!endsOn(*qname, domain)) {
432✔
339
    return false;
152✔
340
  }
152✔
341

342
  if (toLower(*qname) == toLower(domain)) {
280✔
343
    *qname = "@";
16✔
344
  }
16✔
345
  else {
264✔
346
    if ((*qname)[qname->size() - domain.size() - 1] != '.') {
264!
347
      return false;
×
348
    }
×
349

350
    qname->resize(qname->size() - domain.size() - 1);
264✔
351
  }
264✔
352
  return true;
280✔
353
}
280✔
354

355
bool Bind2Backend::feedRecord(const DNSResourceRecord& rr, const DNSName& /* ordername */, bool /* ordernameIsNSEC3 */)
356
{
202,793✔
357
  if (d_transaction_id == UnknownDomainID) {
202,793!
358
    throw DBException("Bind2Backend::feedRecord() called outside of transaction");
×
359
  }
×
360

361
  string qname;
202,793✔
362
  if (d_transaction_qname.empty()) {
202,793!
363
    qname = rr.qname.toString();
×
364
  }
×
365
  else if (rr.qname.isPartOf(d_transaction_qname)) {
202,793!
366
    if (rr.qname == d_transaction_qname.operator const DNSName&()) {
202,793✔
367
      qname = "@";
633✔
368
    }
633✔
369
    else {
202,160✔
370
      DNSName relName = rr.qname.makeRelative(d_transaction_qname);
202,160✔
371
      qname = relName.toStringNoDot();
202,160✔
372
    }
202,160✔
373
  }
202,793✔
374
  else {
×
375
    throw DBException("out-of-zone data '" + rr.qname.toLogString() + "' during AXFR of zone '" + d_transaction_qname.toLogString() + "'");
×
376
  }
×
377

378
  shared_ptr<DNSRecordContent> drc(DNSRecordContent::make(rr.qtype.getCode(), QClass::IN, rr.content));
202,793✔
379
  string content = drc->getZoneRepresentation();
202,793✔
380

381
  // SOA needs stripping too! XXX FIXME - also, this should not be here I think
382
  switch (rr.qtype.getCode()) {
202,793✔
383
  case QType::MX:
56✔
384
  case QType::SRV:
76✔
385
  case QType::CNAME:
208✔
386
  case QType::DNAME:
212✔
387
  case QType::NS:
432✔
388
    stripDomainSuffix(&content, d_transaction_qname);
432✔
389
    // fallthrough
390
  default:
202,793✔
391
    if (d_of && *d_of) {
202,793!
392
      *d_of << qname << "\t" << rr.ttl << "\t" << rr.qtype.toString() << "\t" << content << endl;
202,793✔
393
    }
202,793✔
394
  }
202,793✔
395
  return true;
202,793✔
396
}
202,793✔
397

398
void Bind2Backend::getUpdatedPrimaries(vector<DomainInfo>& changedDomains, std::unordered_set<DNSName>& /* catalogs */, CatalogHashMap& /* catalogHashes */)
399
{
×
400
  vector<DomainInfo> consider;
×
401
  {
×
402
    auto state = s_state.read_lock();
×
403

404
    for (const auto& i : *state) {
×
405
      if (i.d_kind != DomainInfo::Primary && this->alsoNotify.empty() && i.d_also_notify.empty())
×
406
        continue;
×
407

408
      DomainInfo di;
×
409
      di.id = i.d_id;
×
410
      di.zone = i.d_name;
×
411
      di.last_check = i.d_lastcheck;
×
412
      di.notified_serial = i.d_lastnotified;
×
413
      di.backend = this;
×
414
      di.kind = DomainInfo::Primary;
×
415
      consider.push_back(std::move(di));
×
416
    }
×
417
  }
×
418

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

442
void Bind2Backend::getAllDomains(vector<DomainInfo>* domains, bool getSerial, bool /* include_disabled */)
443
{
98✔
444
  SOAData soadata;
98✔
445

446
  // prevent deadlock by using getSOA() later on
447
  {
98✔
448
    auto state = s_state.read_lock();
98✔
449
    domains->reserve(state->size());
98✔
450

451
    for (const auto& i : *state) {
258✔
452
      DomainInfo di;
185✔
453
      di.id = i.d_id;
185✔
454
      di.zone = i.d_name;
185✔
455
      di.last_check = i.d_lastcheck;
185✔
456
      di.kind = i.d_kind;
185✔
457
      di.primaries = i.d_primaries;
185✔
458
      di.backend = this;
185✔
459
      domains->push_back(std::move(di));
185✔
460
    };
185✔
461
  }
98✔
462

463
  if (getSerial) {
98✔
464
    for (DomainInfo& di : *domains) {
1,406✔
465
      // do not corrupt di if domain supplied by another backend.
466
      if (di.backend != this)
1,406!
467
        continue;
1,406✔
468
      try {
×
469
        this->getSOA(di.zone, di.id, soadata);
×
470
      }
×
471
      catch (...) {
×
472
        continue;
×
473
      }
×
474
      di.serial = soadata.serial;
×
475
    }
×
476
  }
42✔
477
}
98✔
478

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

500
  for (DomainInfo& sd : domains) {
72✔
501
    SOAData soadata;
72✔
502
    soadata.refresh = 0;
72✔
503
    soadata.serial = 0;
72✔
504
    try {
72✔
505
      getSOA(sd.zone, sd.id, soadata); // we might not *have* a SOA yet
72✔
506
    }
72✔
507
    catch (...) {
72✔
508
    }
72✔
509
    sd.serial = soadata.serial;
72✔
510
    // coverity[store_truncates_time_t]
511
    if (sd.last_check + soadata.refresh < (unsigned int)time(nullptr))
72!
512
      unfreshDomains->push_back(std::move(sd));
72✔
513
  }
72✔
514
}
8✔
515

516
bool Bind2Backend::getDomainInfo(const ZoneName& domain, DomainInfo& info, bool getSerial)
517
{
1,045✔
518
  BB2DomainInfo bbd;
1,045✔
519
  if (!safeGetBBDomainInfo(domain, &bbd))
1,045✔
520
    return false;
600✔
521

522
  info.id = bbd.d_id;
445✔
523
  info.zone = domain;
445✔
524
  info.primaries = bbd.d_primaries;
445✔
525
  info.last_check = bbd.d_lastcheck;
445✔
526
  info.backend = this;
445✔
527
  info.kind = bbd.d_kind;
445✔
528
  info.serial = 0;
445✔
529
  if (getSerial) {
445✔
530
    try {
135✔
531
      SOAData sd;
135✔
532
      sd.serial = 0;
135✔
533

534
      getSOA(bbd.d_name, bbd.d_id, sd); // we might not *have* a SOA yet
135✔
535
      info.serial = sd.serial;
135✔
536
    }
135✔
537
    catch (...) {
135✔
538
    }
72✔
539
  }
135✔
540

541
  return true;
445✔
542
}
445✔
543

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

568
// only parses, does NOT add to s_state!
569
void Bind2Backend::parseZoneFile(BB2DomainInfo* bbd)
570
{
2,737✔
571
  NSEC3PARAMRecordContent ns3pr;
2,737✔
572
  bool nsec3zone = false;
2,737✔
573
  if (d_hybrid) {
2,737!
574
    DNSSECKeeper dk;
×
575
    nsec3zone = dk.getNSEC3PARAM(bbd->d_name, &ns3pr);
×
576
  }
×
577
  else
2,737✔
578
    nsec3zone = getNSEC3PARAMuncached(bbd->d_name, &ns3pr);
2,737✔
579

580
  auto records = std::make_shared<recordstorage_t>();
2,737✔
581
  ZoneParserTNG zpt(bbd->main_filename(), bbd->d_name, s_binddirectory, d_upgradeContent);
2,737✔
582
  zpt.setMaxGenerateSteps(::arg().asNum("max-generate-steps"));
2,737✔
583
  zpt.setMaxIncludes(::arg().asNum("max-include-depth"));
2,737✔
584
  DNSResourceRecord rr;
2,737✔
585
  string hashed;
2,737✔
586
  while (zpt.get(rr)) {
3,277,433✔
587
    if (rr.qtype.getCode() == QType::NSEC || rr.qtype.getCode() == QType::NSEC3 || rr.qtype.getCode() == QType::NSEC3PARAM)
3,274,696!
588
      continue; // we synthesise NSECs on demand
×
589

590
    insertRecord(records, bbd->d_name, rr.qname, rr.qtype, rr.content, rr.ttl, "");
3,274,696✔
591
  }
3,274,696✔
592
  fixupOrderAndAuth(records, bbd->d_name, nsec3zone, ns3pr);
2,737✔
593
  doEmptyNonTerminals(records, bbd->d_name, nsec3zone, ns3pr);
2,737✔
594
  bbd->d_fileinfo = zpt.getFileset();
2,737✔
595
  bbd->d_loaded = true;
2,737✔
596
  bbd->d_checknow = false;
2,737✔
597
  bbd->d_status = "parsed into memory at " + nowTime();
2,737✔
598
  bbd->d_records = LookButDontTouch<recordstorage_t>(std::move(records));
2,737✔
599
  bbd->d_nsec3zone = nsec3zone;
2,737✔
600
  bbd->d_nsec3param = std::move(ns3pr);
2,737✔
601
}
2,737✔
602

603
/** THIS IS AN INTERNAL FUNCTION! It does moadnsparser prio impedance matching
604
    Much of the complication is due to the efforts to benefit from std::string reference counting copy on write semantics */
605
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)
606
{
3,279,312✔
607
  Bind2DNSRecord bdr;
3,279,312✔
608
  bdr.qname = qname;
3,279,312✔
609

610
  if (zoneName.empty())
3,279,312!
611
    ;
×
612
  else if (bdr.qname.isPartOf(zoneName))
3,279,312✔
613
    bdr.qname.makeUsRelative(zoneName);
3,279,010✔
614
  else {
302✔
615
    string msg = "Trying to insert non-zone data, name='" + bdr.qname.toLogString() + "', qtype=" + qtype.toString() + ", zone='" + zoneName.toLogString() + "'";
302✔
616
    if (s_ignore_broken_records) {
302!
617
      SLOG(g_log << Logger::Warning << msg << " ignored" << endl,
302!
618
           d_slog->info(Logr::Warning, "Non-zone data record ignored", "zone", Logging::Loggable(zoneName), "name", Logging::Loggable(bdr.qname), "qtype", Logging::Loggable(qtype)));
302✔
619
      return;
302✔
620
    }
302✔
621
    throw PDNSException(std::move(msg));
×
622
  }
302✔
623

624
  //  bdr.qname.swap(bdr.qname);
625

626
  if (!records->empty() && bdr.qname == boost::prior(records->end())->qname)
3,279,010✔
627
    bdr.qname = boost::prior(records->end())->qname;
8,871✔
628

629
  bdr.qname = bdr.qname;
3,279,010✔
630
  bdr.qtype = qtype.getCode();
3,279,010✔
631
  bdr.content = content;
3,279,010✔
632
  bdr.nsec3hash = hashed;
3,279,010✔
633

634
  if (auth != nullptr) // Set auth on empty non-terminals
3,279,010✔
635
    bdr.auth = *auth;
4,616✔
636
  else
3,274,394✔
637
    bdr.auth = true;
3,274,394✔
638

639
  bdr.ttl = ttl;
3,279,010✔
640
  records->insert(std::move(bdr));
3,279,010✔
641
}
3,279,010✔
642

643
string Bind2Backend::DLReloadNowHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
644
{
×
645
  ostringstream ret;
×
646

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

668
string Bind2Backend::DLDomStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
669
{
29✔
670
  ostringstream ret;
29✔
671

672
  if (parts.size() > 1) {
29!
673
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
674
      BB2DomainInfo bbd;
×
675
      if (safeGetBBDomainInfo(ZoneName(*i), &bbd)) {
×
676
        ret << *i << ": " << (bbd.d_loaded ? "" : "[rejected]") << "\t" << bbd.d_status << "\n";
×
677
      }
×
678
      else {
×
679
        ret << *i << " no such domain\n";
×
680
      }
×
681
    }
×
682
  }
×
683
  else {
29✔
684
    auto state = s_state.read_lock();
29✔
685
    for (const auto& i : *state) {
269✔
686
      ret << i.d_name << ": " << (i.d_loaded ? "" : "[rejected]") << "\t" << i.d_status << "\n";
269✔
687
    }
269✔
688
  }
29✔
689

690
  if (ret.str().empty())
29!
691
    ret << "no domains passed";
×
692

693
  return ret.str();
29✔
694
}
29✔
695

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

730
string Bind2Backend::DLDomExtendedStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
731
{
×
732
  ostringstream ret;
×
733

734
  if (parts.size() > 1) {
×
735
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
736
      BB2DomainInfo bbd;
×
737
      if (safeGetBBDomainInfo(ZoneName(*i), &bbd)) {
×
738
        printDomainExtendedStatus(ret, bbd);
×
739
      }
×
740
      else {
×
741
        ret << *i << " no such domain" << std::endl;
×
742
      }
×
743
    }
×
744
  }
×
745
  else {
×
746
    auto rstate = s_state.read_lock();
×
747
    for (const auto& state : *rstate) {
×
748
      printDomainExtendedStatus(ret, state);
×
749
    }
×
750
  }
×
751

752
  if (ret.str().empty()) {
×
753
    ret << "no domains passed" << std::endl;
×
754
  }
×
755

756
  return ret.str();
×
757
}
×
758

759
string Bind2Backend::DLListRejectsHandler(const vector<string>& /* parts */, Utility::pid_t /* ppid */)
760
{
×
761
  ostringstream ret;
×
762
  auto rstate = s_state.read_lock();
×
763
  for (const auto& i : *rstate) {
×
764
    if (!i.d_loaded)
×
765
      ret << i.d_name << "\t" << i.d_status << endl;
×
766
  }
×
767
  return ret.str();
×
768
}
×
769

770
string Bind2Backend::DLAddDomainHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
771
{
12✔
772
  if (parts.size() < 3)
12!
773
    return "ERROR: Domain name and zone filename are required";
×
774

775
  ZoneName domainname(parts[1]);
12✔
776
  const string& filename = parts[2];
12✔
777
  BB2DomainInfo bbd;
12✔
778
  if (safeGetBBDomainInfo(domainname, &bbd))
12✔
779
    return "Already loaded";
6✔
780

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

784
  struct stat buf;
6✔
785
  if (stat(filename.c_str(), &buf) != 0)
6!
786
    return "Unable to load zone " + domainname.toLogString() + " from " + filename + ": " + strerror(errno);
×
787

788
  Bind2Backend bb2; // createdomainentry needs access to our configuration
6✔
789
  bbd = bb2.createDomainEntry(domainname);
6✔
790
  bbd.d_fileinfo.emplace_back(std::make_pair(filename, buf.st_ctime));
6✔
791
  bbd.d_checknow = true;
6✔
792
  bbd.d_loaded = true;
6✔
793
  bbd.d_lastcheck = 0;
6✔
794
  bbd.d_status = "parsing into memory";
6✔
795

796
  safePutBBDomainInfo(bbd);
6✔
797

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

800
  SLOG(g_log << Logger::Warning << "Zone " << domainname << " loaded" << endl,
6!
801
       bb2.d_slog->info(Logr::Info, "Zone loaded", "zone", Logging::Loggable(domainname), "file", Logging::Loggable(filename)));
6✔
802
  return "Loaded zone " + domainname.toLogString() + " from " + filename;
6✔
803
}
6✔
804

805
Bind2Backend::Bind2Backend(const string& suffix, bool loadZones)
806
{
3,370✔
807
  d_getAllDomainMetadataQuery_stmt = nullptr;
3,370✔
808
  d_getDomainMetadataQuery_stmt = nullptr;
3,370✔
809
  d_deleteDomainMetadataQuery_stmt = nullptr;
3,370✔
810
  d_insertDomainMetadataQuery_stmt = nullptr;
3,370✔
811
  d_getDomainKeysQuery_stmt = nullptr;
3,370✔
812
  d_deleteDomainKeyQuery_stmt = nullptr;
3,370✔
813
  d_insertDomainKeyQuery_stmt = nullptr;
3,370✔
814
  d_GetLastInsertedKeyIdQuery_stmt = nullptr;
3,370✔
815
  d_activateDomainKeyQuery_stmt = nullptr;
3,370✔
816
  d_deactivateDomainKeyQuery_stmt = nullptr;
3,370✔
817
  d_getTSIGKeyQuery_stmt = nullptr;
3,370✔
818
  d_setTSIGKeyQuery_stmt = nullptr;
3,370✔
819
  d_deleteTSIGKeyQuery_stmt = nullptr;
3,370✔
820
  d_getTSIGKeysQuery_stmt = nullptr;
3,370✔
821

822
  setArgPrefix("bind" + suffix);
3,370✔
823
  d_logprefix = "[bind" + suffix + "backend]";
3,370✔
824
  if (g_slogStructured) {
3,370!
NEW
825
    d_slog = g_slog->withName("bind" + suffix);
×
NEW
826
    d_handle.setSLog(d_slog);
×
NEW
827
  }
×
828
  d_hybrid = mustDo("hybrid");
3,370✔
829
  if (d_hybrid && g_zoneCache.isEnabled()) {
3,370!
830
    throw PDNSException("bind-hybrid and the zone cache currently interoperate badly. Please disable the zone cache or stop using bind-hybrid");
×
831
  }
×
832

833
  d_transaction_id = UnknownDomainID;
3,370✔
834
  s_ignore_broken_records = mustDo("ignore-broken-records");
3,370✔
835
  d_upgradeContent = ::arg().mustDo("upgrade-unknown-types");
3,370✔
836

837
  if (!loadZones && d_hybrid)
3,370!
838
    return;
×
839

840
  auto lock = std::scoped_lock(s_startup_lock);
3,370✔
841

842
  setupDNSSEC();
3,370✔
843
  if (s_first == 0) {
3,370✔
844
    return;
2,610✔
845
  }
2,610✔
846

847
  if (loadZones) {
760✔
848
    loadConfig();
311✔
849
    s_first = 0;
311✔
850
  }
311✔
851

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

859
Bind2Backend::~Bind2Backend()
860
{
3,245✔
861
  freeStatements();
3,245✔
862
} // deallocate statements
3,245✔
863

864
void Bind2Backend::rediscover(string* status)
865
{
×
866
  loadConfig(status);
×
867
}
×
868

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

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

883
  for (const auto& bdr : *records) {
3,274,394✔
884
    if (!bdr.qname.isRoot() && bdr.qtype == QType::NS)
3,274,394✔
885
      nssets.insert(bdr.qname);
3,010✔
886
    else if (bdr.qtype == QType::DS)
3,271,384✔
887
      dssets.insert(bdr.qname);
499✔
888
  }
3,274,394✔
889

890
  for (auto iter = records->begin(); iter != records->end(); iter++) {
3,277,059✔
891
    skip = false;
3,274,394✔
892
    shorter = iter->qname;
3,274,394✔
893

894
    if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
3,274,394!
895
      do {
3,273,161✔
896
        if (nssets.count(shorter) != 0u) {
3,273,161✔
897
          skip = true;
1,359✔
898
          break;
1,359✔
899
        }
1,359✔
900
      } while (shorter.chopOff() && !iter->qname.isRoot());
3,273,161!
901
    }
3,263,263✔
902

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

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

911
    // cerr<<iter->qname<<"\t"<<QType(iter->qtype).toString()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
912
  }
3,274,394✔
913
}
2,665✔
914

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

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

924
  for (const auto& bdr : *records)
2,665✔
925
    qnames.insert(bdr.qname);
3,274,394✔
926

927
  for (const auto& bdr : *records) {
3,274,394✔
928

929
    if (!bdr.auth && bdr.qtype == QType::NS)
3,274,394✔
930
      auth = (!nsec3zone || (ns3pr.d_flags == 0u));
3,010✔
931
    else
3,271,384✔
932
      auth = bdr.auth;
3,271,384✔
933

934
    shorter = bdr.qname;
3,274,394✔
935
    while (shorter.chopOff()) {
6,548,914✔
936
      if (qnames.count(shorter) == 0u) {
3,274,520✔
937
        if (!(maxent)) {
9,732!
NEW
938
          SLOG(g_log << Logger::Error << "Zone '" << zoneName << "' has too many empty non terminals." << endl,
×
NEW
939
               d_slog->info(Logr::Error, "Zone has too many empty non terminals.", "zone", Logging::Loggable(zoneName)));
×
940
          return;
×
941
        }
×
942

943
        if (nonterm.count(shorter) == 0u) {
9,732✔
944
          nonterm.emplace(shorter, auth);
4,616✔
945
          --maxent;
4,616✔
946
        }
4,616✔
947
        else if (auth)
5,116✔
948
          nonterm[shorter] = true;
5,020✔
949
      }
9,732✔
950
    }
3,274,520✔
951
  }
3,274,394✔
952

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

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

968
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
969
{
311✔
970
  static domainid_t domain_id = 1;
311✔
971

972
  if (!getArg("config").empty()) {
311!
973
    BindParser BP;
311✔
974
    try {
311✔
975
      BP.parse(getArg("config"));
311✔
976
    }
311✔
977
    catch (PDNSException& ae) {
311✔
NEW
978
      SLOG(g_log << Logger::Error << "Error parsing bind configuration: " << ae.reason << endl,
×
NEW
979
           d_slog->error(Logr::Error, ae.reason, "Error parsing bind configuration"));
×
980
      throw;
×
981
    }
×
982

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

986
    s_binddirectory = BP.getDirectory();
311✔
987
    //    ZP.setDirectory(d_binddirectory);
988

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

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

1003
    struct stat st;
311✔
1004

1005
    for (auto& domain : domains) {
2,791✔
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
311✔
1013
    for (const auto& domain : domains) {
2,791✔
1014
      if (!(domain.hadFileDirective)) {
2,659!
NEW
1015
        SLOG(g_log << Logger::Warning << d_logprefix << " Zone '" << domain.name << "' has no 'file' directive set in " << getArg("config") << endl,
×
NEW
1016
             d_slog->info(Logr::Warning, "Zone has no 'file' directive set", "zone", Logging::Loggable(domain.name), "filename", Logging::Loggable(getArg("config"))));
×
1017
        rejected++;
×
1018
        continue;
×
1019
      }
×
1020

1021
      if (domain.type.empty()) {
2,659!
NEW
1022
        SLOG(g_log << Logger::Notice << d_logprefix << " Zone '" << domain.name << "' has no type specified, assuming 'native'" << endl,
×
NEW
1023
             d_slog->info(Logr::Notice, "Zone has no type specified, assuming 'native'", "zone", Logging::Loggable(domain.name)));
×
UNCOV
1024
      }
×
1025
      if (domain.type != "primary" && domain.type != "secondary" && domain.type != "native" && !domain.type.empty() && domain.type != "master" && domain.type != "slave") {
2,659!
NEW
1026
        SLOG(g_log << Logger::Warning << d_logprefix << " Warning! Skipping zone '" << domain.name << "' because type '" << domain.type << "' is invalid" << endl,
×
NEW
1027
             d_slog->info(Logr::Warning, "Skipping zone because type is invalid", "zone", Logging::Loggable(domain.name), "type", Logging::Loggable(domain.type)));
×
1028
        rejected++;
×
1029
        continue;
×
1030
      }
×
1031

1032
      BB2DomainInfo bbd;
2,659✔
1033
      bool isNew = false;
2,659✔
1034

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

1043
      // overwrite what we knew about the domain
1044
      bbd.d_name = domain.name;
2,659✔
1045
      bool filenameChanged = bbd.d_fileinfo.empty() || (bbd.main_filename() != domain.filename);
2,659!
1046
      bool addressesChanged = (bbd.d_primaries != domain.primaries || bbd.d_also_notify != domain.alsoNotify);
2,659!
1047
      // Preserve existing fileinfo in case we won't reread anything.
1048
      if (filenameChanged) {
2,659!
1049
        bbd.d_fileinfo.clear();
2,659✔
1050
        bbd.d_fileinfo.emplace_back(std::make_pair(domain.filename, 0));
2,659✔
1051
      }
2,659✔
1052
      bbd.d_primaries = domain.primaries;
2,659✔
1053
      bbd.d_also_notify = domain.alsoNotify;
2,659✔
1054

1055
      DomainInfo::DomainKind kind = DomainInfo::Native;
2,659✔
1056
      if (domain.type == "primary" || domain.type == "master") {
2,659!
1057
        kind = DomainInfo::Primary;
2,587✔
1058
      }
2,587✔
1059
      if (domain.type == "secondary" || domain.type == "slave") {
2,659!
1060
        kind = DomainInfo::Secondary;
72✔
1061
      }
72✔
1062

1063
      bool kindChanged = (bbd.d_kind != kind);
2,659✔
1064
      bbd.d_kind = kind;
2,659✔
1065

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

1071
        try {
2,659✔
1072
          parseZoneFile(&bbd);
2,659✔
1073
        }
2,659✔
1074
        catch (PDNSException& ae) {
2,659✔
1075
          ostringstream msg;
×
1076
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.reason;
×
1077

1078
          if (status != nullptr)
×
1079
            *status += msg.str();
×
1080
          bbd.d_status = msg.str();
×
1081

NEW
1082
          SLOG(g_log << Logger::Warning << d_logprefix << msg.str() << endl,
×
NEW
1083
               d_slog->error(Logr::Error, ae.reason, "Error in zone file", "zone", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
×
1084
          rejected++;
×
1085
        }
×
1086
        catch (std::system_error& ae) {
2,659✔
1087
          ostringstream msg;
72✔
1088
          bool missingNewSecondary = ae.code().value() == ENOENT && isNew && kind == DomainInfo::Secondary;
72!
1089
          if (missingNewSecondary) {
72!
1090
            msg << " error at " + nowTime() << " no file found for new secondary domain '" << domain.name << "'. Has not been AXFR'd yet";
72✔
1091
          }
72✔
1092
          else {
×
1093
            msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
×
1094
          }
×
1095

1096
          if (status != nullptr)
72!
1097
            *status += msg.str();
×
1098
          bbd.d_status = msg.str();
72✔
1099
          SLOG(
72!
1100
            g_log << Logger::Warning << d_logprefix << msg.str() << endl,
72✔
1101
            if (missingNewSecondary) {
72✔
1102
              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✔
1103
            } else {
72✔
1104
              d_slog->error(Logr::Warning, ae.what(), "Parse error", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename));
72✔
1105
            });
72✔
1106
          rejected++;
72✔
1107
        }
72✔
1108
        catch (std::exception& ae) {
2,659✔
1109
          ostringstream msg;
×
1110
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
×
1111

1112
          if (status != nullptr)
×
1113
            *status += msg.str();
×
1114
          bbd.d_status = msg.str();
×
1115

NEW
1116
          SLOG(g_log << Logger::Warning << d_logprefix << msg.str() << endl,
×
NEW
1117
               d_slog->error(Logr::Warning, ae.what(), "Parse error", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
×
1118
          rejected++;
×
1119
        }
×
1120
        safePutBBDomainInfo(bbd);
2,659✔
1121
      }
2,659✔
1122
      else if (addressesChanged || kindChanged) {
×
1123
        safePutBBDomainInfo(bbd);
×
1124
      }
×
1125
    }
2,659✔
1126
    vector<ZoneName> diff;
311✔
1127

1128
    set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
311✔
1129
    unsigned int remdomains = diff.size();
311✔
1130

1131
    for (const ZoneName& name : diff) {
311!
1132
      safeRemoveBBDomainInfo(name);
×
1133
    }
×
1134

1135
    // count number of entirely new domains
1136
    diff.clear();
311✔
1137
    set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
311✔
1138
    newdomains = diff.size();
311✔
1139

1140
    ostringstream msg;
311✔
1141
    msg << " Done parsing domains, " << rejected << " rejected, " << newdomains << " new, " << remdomains << " removed";
311✔
1142
    if (status != nullptr)
311!
1143
      *status = msg.str();
×
1144

1145
    SLOG(
311!
1146
      g_log << Logger::Error << d_logprefix << msg.str() << endl,
311✔
1147
      if (rejected == 0) {
311✔
1148
        d_slog->info(Logr::Info, "Done parsing domains", "new", Logging::Loggable(newdomains), "removed", Logging::Loggable(remdomains));
311✔
1149
      } else {
311✔
1150
        d_slog->error(Logr::Error, "Done parsing domains", "new", Logging::Loggable(newdomains), "removed", Logging::Loggable(remdomains), "rejected", Logging::Loggable(rejected));
311✔
1151
      });
311✔
1152
  }
311✔
1153
}
311✔
1154

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

1195
bool Bind2Backend::findBeforeAndAfterUnhashed(std::shared_ptr<const recordstorage_t>& records, const DNSName& qname, DNSName& /* unhashed */, DNSName& before, DNSName& after)
1196
{
2,714✔
1197
  // for(const auto& record: *records)
1198
  //   cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
1199

1200
  recordstorage_t::const_iterator iterBefore, iterAfter;
2,714✔
1201

1202
  iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
2,714✔
1203

1204
  if (iterBefore != records->begin())
2,714!
1205
    --iterBefore;
2,714✔
1206
  while ((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
3,243✔
1207
    --iterBefore;
529✔
1208
  before = iterBefore->qname;
2,714✔
1209

1210
  if (iterAfter == records->end()) {
2,714✔
1211
    iterAfter = records->begin();
376✔
1212
  }
376✔
1213
  else {
2,338✔
1214
    while ((!iterAfter->auth && iterAfter->qtype != QType::NS) || !iterAfter->qtype) {
3,502✔
1215
      ++iterAfter;
1,164✔
1216
      if (iterAfter == records->end()) {
1,164!
1217
        iterAfter = records->begin();
×
1218
        break;
×
1219
      }
×
1220
    }
1,164✔
1221
  }
2,338✔
1222
  after = iterAfter->qname;
2,714✔
1223

1224
  return true;
2,714✔
1225
}
2,714✔
1226

1227
// NOLINTNEXTLINE(readability-identifier-length)
1228
bool Bind2Backend::getBeforeAndAfterNamesAbsolute(domainid_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
1229
{
7,020✔
1230
  BB2DomainInfo bbd;
7,020✔
1231
  if (!safeGetBBDomainInfo(id, &bbd))
7,020!
1232
    return false;
×
1233

1234
  shared_ptr<const recordstorage_t> records = bbd.d_records.get();
7,020✔
1235
  if (!bbd.d_nsec3zone) {
7,020✔
1236
    return findBeforeAndAfterUnhashed(records, qname, unhashed, before, after);
2,714✔
1237
  }
2,714✔
1238
  else {
4,306✔
1239
    const auto& hashindex = boost::multi_index::get<NSEC3Tag>(*records);
4,306✔
1240

1241
    // for(auto iter = first; iter != hashindex.end(); iter++)
1242
    //  cerr<<iter->nsec3hash<<endl;
1243

1244
    auto first = hashindex.upper_bound("");
4,306✔
1245
    auto iter = hashindex.upper_bound(qname.toStringNoDot());
4,306✔
1246

1247
    if (iter == hashindex.end()) {
4,306✔
1248
      --iter;
338✔
1249
      before = DNSName(iter->nsec3hash);
338✔
1250
      after = DNSName(first->nsec3hash);
338✔
1251
    }
338✔
1252
    else {
3,968✔
1253
      after = DNSName(iter->nsec3hash);
3,968✔
1254
      if (iter != first)
3,968✔
1255
        --iter;
3,900✔
1256
      else
68✔
1257
        iter = --hashindex.end();
68✔
1258
      before = DNSName(iter->nsec3hash);
3,968✔
1259
    }
3,968✔
1260
    unhashed = iter->qname + bbd.d_name.operator const DNSName&();
4,306✔
1261

1262
    return true;
4,306✔
1263
  }
4,306✔
1264
}
7,020✔
1265

1266
void Bind2Backend::lookup(const QType& qtype, const DNSName& qname, domainid_t zoneId, DNSPacket* /* pkt_p */)
1267
{
4,150✔
1268
  d_handle.reset();
4,150✔
1269

1270
  static bool mustlog = ::arg().mustDo("query-logging");
4,150✔
1271

1272
  bool found = false;
4,150✔
1273
  ZoneName domain;
4,150✔
1274
  BB2DomainInfo bbd;
4,150✔
1275

1276
  if (mustlog) {
4,150!
NEW
1277
    SLOG(g_log << Logger::Warning << "Lookup for '" << qtype.toString() << "' of '" << qname << "' within zoneID " << zoneId << endl,
×
NEW
1278
         d_slog->info(Logr::Warning, "Record lookup", "name", Logging::Loggable(qname), "qtype", Logging::Loggable(qtype), "zone id", Logging::Loggable(zoneId)));
×
NEW
1279
  }
×
1280

1281
  if (zoneId != UnknownDomainID) {
4,150✔
1282
    if ((found = (safeGetBBDomainInfo(zoneId, &bbd) && qname.isPartOf(bbd.d_name)))) {
3,536!
1283
      domain = std::move(bbd.d_name);
3,536✔
1284
    }
3,536✔
1285
  }
3,536✔
1286
  else {
614✔
1287
    domain = ZoneName(qname);
614✔
1288
    do {
617✔
1289
      found = safeGetBBDomainInfo(domain, &bbd);
617✔
1290
    } while (!found && qtype != QType::SOA && domain.chopOff());
617✔
1291
  }
614✔
1292

1293
  if (!found) {
4,150✔
1294
    if (mustlog) {
24!
NEW
1295
      SLOG(g_log << Logger::Warning << "Found no authoritative zone for '" << qname << "' and/or id " << zoneId << endl,
×
NEW
1296
           d_slog->info(Logr::Warning, "Found no authoritative zone", "name", Logging::Loggable(qname), "zone id", Logging::Loggable(zoneId)));
×
NEW
1297
    }
×
1298
    d_handle.d_list = false;
24✔
1299
    return;
24✔
1300
  }
24✔
1301

1302
  if (mustlog) {
4,126!
NEW
1303
    SLOG(g_log << Logger::Warning << "Found a zone '" << domain << "' (with id " << bbd.d_id << ") that might contain data " << endl,
×
NEW
1304
         d_slog->info(Logr::Warning, "Found authoritative zone", "zone", Logging::Loggable(domain), "zone id", Logging::Loggable(bbd.d_id)));
×
NEW
1305
  }
×
1306

1307
  d_handle.id = bbd.d_id;
4,126✔
1308
  d_handle.qname = qname.makeRelative(domain); // strip domain name
4,126✔
1309
  d_handle.qtype = qtype;
4,126✔
1310
  d_handle.domain = std::move(domain);
4,126✔
1311

1312
  if (!bbd.current()) {
4,126✔
1313
    SLOG(g_log << Logger::Warning << "Zone '" << d_handle.domain << "' (" << bbd.main_filename() << ") needs reloading" << endl,
6!
1314
         d_slog->info(Logr::Warning, "Zone needs reloading", "zone", Logging::Loggable(d_handle.domain), "file", Logging::Loggable(bbd.main_filename())));
6✔
1315
    queueReloadAndStore(bbd.d_id);
6✔
1316
    if (!safeGetBBDomainInfo(d_handle.domain, &bbd))
6!
1317
      throw DBException("Zone '" + bbd.d_name.toLogString() + "' (" + bbd.main_filename() + ") gone after reload"); // if we don't throw here, we crash for some reason
×
1318
  }
6✔
1319

1320
  if (!bbd.d_loaded) {
4,126✔
1321
    d_handle.reset();
216✔
1322
    throw DBException("Zone for '" + d_handle.domain.toLogString() + "' in '" + bbd.main_filename() + "' not loaded (file missing, corrupt or primary dead)"); // fsck
216✔
1323
  }
216✔
1324

1325
  d_handle.d_records = bbd.d_records.get();
3,910✔
1326

1327
  if (d_handle.d_records->empty()) {
3,910!
NEW
1328
    DLOG(SLOG(g_log << "Query with no results" << endl,
×
NEW
1329
              d_slog->info(Logr::Debug, "No results", "name", Logging::Loggable(qname), "qtype", Logging::Loggable(qtype))));
×
NEW
1330
  }
×
1331

1332
  d_handle.mustlog = mustlog;
3,910✔
1333

1334
  const auto& hashedidx = boost::multi_index::get<UnorderedNameTag>(*d_handle.d_records);
3,910✔
1335
  auto range = hashedidx.equal_range(d_handle.qname);
3,910✔
1336

1337
  d_handle.d_list = false;
3,910✔
1338
  d_handle.d_iter = range.first;
3,910✔
1339
  d_handle.d_end_iter = range.second;
3,910✔
1340
}
3,910✔
1341

1342
bool Bind2Backend::get(DNSResourceRecord& r)
1343
{
197,970✔
1344
  if (!d_handle.d_records) {
197,970✔
1345
    if (d_handle.mustlog) {
24!
NEW
1346
      SLOG(g_log << Logger::Warning << "There were no answers" << endl,
×
NEW
1347
           d_slog->info(Logr::Warning, "No answers"));
×
NEW
1348
    }
×
1349
    return false;
24✔
1350
  }
24✔
1351

1352
  if (!d_handle.get(r)) {
197,946✔
1353
    if (d_handle.mustlog) {
4,215!
NEW
1354
      SLOG(g_log << Logger::Warning << "End of answers" << endl,
×
NEW
1355
           d_slog->info(Logr::Warning, "No more answers"));
×
NEW
1356
    }
×
1357

1358
    d_handle.reset();
4,215✔
1359

1360
    return false;
4,215✔
1361
  }
4,215✔
1362
  if (d_handle.mustlog) {
193,731!
NEW
1363
    SLOG(g_log << Logger::Warning << "Returning: '" << r.qtype.toString() << "' of '" << r.qname << "', content: '" << r.content << "'" << endl,
×
NEW
1364
         d_slog->info(Logr::Warning, "Returning record", "name", Logging::Loggable(r.qname), "type", Logging::Loggable(r.qtype), "content", Logging::Loggable(r.content)));
×
NEW
1365
  }
×
1366
  return true;
193,731✔
1367
}
197,946✔
1368

1369
void Bind2Backend::lookupEnd()
1370
{
26✔
1371
  d_handle.reset();
26✔
1372
}
26✔
1373

1374
bool Bind2Backend::handle::get(DNSResourceRecord& r)
1375
{
197,946✔
1376
  if (d_list)
197,946✔
1377
    return get_list(r);
188,918✔
1378
  else
9,028✔
1379
    return get_normal(r);
9,028✔
1380
}
197,946✔
1381

1382
void Bind2Backend::handle::reset()
1383
{
8,938✔
1384
  d_records.reset();
8,938✔
1385
  qname.clear();
8,938✔
1386
  mustlog = false;
8,938✔
1387
}
8,938✔
1388

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

1394
  if (d_iter == d_end_iter) {
9,028✔
1395
    return false;
3,884✔
1396
  }
3,884✔
1397

1398
  while (d_iter != d_end_iter && !(qtype.getCode() == QType::ANY || (d_iter)->qtype == qtype.getCode())) {
7,877!
1399
    DLOG(SLOG(g_log << Logger::Warning << "Skipped " << qname << "/" << QType(d_iter->qtype).toString() << ": '" << d_iter->content << "'" << endl,
2,733✔
1400
              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✔
1401
    d_iter++;
2,733✔
1402
  }
2,733✔
1403
  if (d_iter == d_end_iter) {
5,144!
1404
    return false;
×
1405
  }
×
1406
  DLOG(SLOG(g_log << "Bind2Backend get() returning a rr with a " << QType(d_iter->qtype).getCode() << endl,
5,144✔
1407
            d_slog->info(Logr::Debug, "Bind2Backend get() returning a rr", "type", Logging::Loggable(d_iter->qtype))));
5,144✔
1408

1409
  const DNSName& domainName(domain);
5,144✔
1410
  r.qname = qname.empty() ? domainName : (qname + domainName);
5,144!
1411
  r.domain_id = id;
5,144✔
1412
  r.content = (d_iter)->content;
5,144✔
1413
  //  r.domain_id=(d_iter)->domain_id;
1414
  r.qtype = (d_iter)->qtype;
5,144✔
1415
  r.ttl = (d_iter)->ttl;
5,144✔
1416

1417
  //if(!d_iter->auth && r.qtype.getCode() != QType::A && r.qtype.getCode()!=QType::AAAA && r.qtype.getCode() != QType::NS)
1418
  //  cerr<<"Warning! Unauth response for qtype "<< r.qtype.toString() << " for '"<<r.qname<<"'"<<endl;
1419
  r.auth = d_iter->auth;
5,144✔
1420

1421
  d_iter++;
5,144✔
1422

1423
  return true;
5,144✔
1424
}
5,144✔
1425

1426
bool Bind2Backend::list(const ZoneName& /* target */, domainid_t domainId, bool /* include_disabled */)
1427
{
331✔
1428
  BB2DomainInfo bbd;
331✔
1429

1430
  if (!safeGetBBDomainInfo(domainId, &bbd)) {
331!
1431
    return false;
×
1432
  }
×
1433

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

1438
  if (!bbd.d_loaded) {
331!
1439
    throw PDNSException("zone was not loaded, perhaps because of: " + bbd.d_status);
×
1440
  }
×
1441

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

1446
  d_handle.id = domainId;
331✔
1447
  d_handle.domain = bbd.d_name;
331✔
1448
  d_handle.d_list = true;
331✔
1449
  return true;
331✔
1450
}
331✔
1451

1452
bool Bind2Backend::handle::get_list(DNSResourceRecord& r)
1453
{
188,918✔
1454
  if (d_qname_iter != d_qname_end) {
188,918✔
1455
    const DNSName& domainName(domain);
188,587✔
1456
    r.qname = d_qname_iter->qname.empty() ? domainName : (d_qname_iter->qname + domainName);
188,587!
1457
    r.domain_id = id;
188,587✔
1458
    r.content = (d_qname_iter)->content;
188,587✔
1459
    r.qtype = (d_qname_iter)->qtype;
188,587✔
1460
    r.ttl = (d_qname_iter)->ttl;
188,587✔
1461
    r.auth = d_qname_iter->auth;
188,587✔
1462
    d_qname_iter++;
188,587✔
1463
    return true;
188,587✔
1464
  }
188,587✔
1465
  return false;
331✔
1466
}
188,918✔
1467

1468
bool Bind2Backend::autoPrimariesList(std::vector<AutoPrimary>& primaries)
1469
{
×
1470
  if (getArg("autoprimary-config").empty())
×
1471
    return false;
×
1472

NEW
1473
  std::string filename(getArg("autoprimaries"));
×
NEW
1474
  ifstream c_if(filename, std::ios::in);
×
1475
  if (!c_if) {
×
NEW
1476
    SLOG(g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl,
×
NEW
1477
         d_slog->error(Logr::Error, errno, "Unable to open autoprimaries file", "file", Logging::Loggable(filename)));
×
1478
    return false;
×
1479
  }
×
1480

1481
  string line, sip, saccount;
×
1482
  while (getline(c_if, line)) {
×
1483
    std::istringstream ii(line);
×
1484
    ii >> sip;
×
1485
    if (!sip.empty()) {
×
1486
      ii >> saccount;
×
1487
      primaries.emplace_back(sip, "", saccount);
×
1488
    }
×
1489
  }
×
1490

1491
  c_if.close();
×
1492
  return true;
×
1493
}
×
1494

1495
bool Bind2Backend::autoPrimaryBackend(const string& ipAddress, const ZoneName& /* domain */, const vector<DNSResourceRecord>& /* nsset */, string* /* nameserver */, string* account, DNSBackend** backend)
1496
{
×
1497
  // Check whether we have a configfile available.
1498
  if (getArg("autoprimary-config").empty())
×
1499
    return false;
×
1500

NEW
1501
  std::string filename(getArg("autoprimaries"));
×
NEW
1502
  ifstream c_if(filename.c_str(), std::ios::in); // this was nocreate?
×
1503
  if (!c_if) {
×
NEW
1504
    SLOG(g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl,
×
NEW
1505
         d_slog->error(Logr::Error, errno, "Unable to open autoprimaries file", "file", Logging::Loggable(filename)));
×
1506
    return false;
×
1507
  }
×
1508

1509
  // Format:
1510
  // <ip> <accountname>
1511
  string line, sip, saccount;
×
1512
  while (getline(c_if, line)) {
×
1513
    std::istringstream ii(line);
×
1514
    ii >> sip;
×
1515
    if (sip == ipAddress) {
×
1516
      ii >> saccount;
×
1517
      break;
×
1518
    }
×
1519
  }
×
1520
  c_if.close();
×
1521

1522
  if (sip != ipAddress) { // ip not found in authorization list - reject
×
1523
    return false;
×
1524
  }
×
1525

1526
  // ip authorized as autoprimary - accept
1527
  *backend = this;
×
1528
  if (saccount.length() > 0)
×
1529
    *account = saccount.c_str();
×
1530

1531
  return true;
×
1532
}
×
1533

1534
BB2DomainInfo Bind2Backend::createDomainEntry(const ZoneName& domain)
1535
{
6✔
1536
  domainid_t newid = 1;
6✔
1537
  { // Find a free zone id nr.
6✔
1538
    auto state = s_state.read_lock();
6✔
1539
    if (!state->empty()) {
6!
1540
      newid = state->rbegin()->d_id + 1;
6✔
1541
    }
6✔
1542
  }
6✔
1543

1544
  BB2DomainInfo bbd;
6✔
1545
  bbd.d_kind = DomainInfo::Native;
6✔
1546
  bbd.d_id = newid;
6✔
1547
  bbd.d_records = std::make_shared<recordstorage_t>();
6✔
1548
  bbd.d_name = domain;
6✔
1549
  bbd.setCheckInterval(getArgAsNum("check-interval"));
6✔
1550

1551
  return bbd;
6✔
1552
}
6✔
1553

1554
bool Bind2Backend::createSecondaryDomain(const string& ipAddress, const ZoneName& domain, const string& /* nameserver */, const string& account)
1555
{
×
1556
  string filename = getArg("autoprimary-destdir") + '/' + domain.toStringNoDot();
×
1557

NEW
1558
  SLOG(g_log << Logger::Warning << d_logprefix
×
NEW
1559
             << " Writing bind config zone statement for autosecondary zone '" << domain
×
NEW
1560
             << "' from autoprimary " << ipAddress << endl,
×
NEW
1561
       d_slog->info(Logr::Warning, "Writing bind config zone statement for autosecondary zone", "zone", Logging::Loggable(domain), "autoprimary address", Logging::Loggable(ipAddress)));
×
1562

1563
  {
×
1564
    auto lock = std::scoped_lock(s_autosecondary_config_lock);
×
1565

NEW
1566
    std::string configfile(getArg("autoprimary-config"));
×
NEW
1567
    ofstream c_of(configfile.c_str(), std::ios::app);
×
1568
    if (!c_of) {
×
NEW
1569
      int err = errno;
×
NEW
1570
      auto errorMessage = stringerror();
×
NEW
1571
      SLOG(g_log << Logger::Error << "Unable to open autoprimary configfile for append: " << errorMessage << endl,
×
NEW
1572
           d_slog->error(Logr::Error, err, "Unable to open autoprimary configuration file for append", "file", Logging::Loggable(configfile)));
×
NEW
1573
      throw DBException("Unable to open autoprimary configfile for append: " + errorMessage);
×
UNCOV
1574
    }
×
1575

1576
    c_of << endl;
×
1577
    c_of << "# AutoSecondary zone '" << domain.toString() << "' (added: " << nowTime() << ") (account: " << account << ')' << endl;
×
1578
    c_of << "zone \"" << domain.toStringNoDot() << "\" {" << endl;
×
1579
    c_of << "\ttype secondary;" << endl;
×
1580
    c_of << "\tfile \"" << filename << "\";" << endl;
×
1581
    c_of << "\tprimaries { " << ipAddress << "; };" << endl;
×
1582
    c_of << "};" << endl;
×
1583
    c_of.close();
×
1584
  }
×
1585

1586
  BB2DomainInfo bbd = createDomainEntry(domain);
×
1587
  bbd.d_kind = DomainInfo::Secondary;
×
1588
  bbd.d_primaries.emplace_back(ComboAddress(ipAddress, 53));
×
1589
  bbd.d_fileinfo.emplace_back(std::make_pair(filename, 0));
×
1590
  bbd.updateCtime();
×
1591
  safePutBBDomainInfo(bbd);
×
1592

1593
  return true;
×
1594
}
×
1595

1596
bool Bind2Backend::searchRecords(const string& pattern, size_t maxResults, vector<DNSResourceRecord>& result)
1597
{
23✔
1598
  SimpleMatch sm(pattern, true);
23✔
1599
  static bool mustlog = ::arg().mustDo("query-logging");
23✔
1600
  if (mustlog) {
23!
NEW
1601
    SLOG(g_log << Logger::Warning << "Search for pattern '" << pattern << "'" << endl,
×
NEW
1602
         d_slog->info(Logr::Debug, "Search for pattern", "pattern", Logging::Loggable(pattern)));
×
NEW
1603
  }
×
1604

1605
  {
23✔
1606
    auto state = s_state.read_lock();
23✔
1607

1608
    for (const auto& i : *state) {
23!
1609
      BB2DomainInfo h;
×
1610
      if (!safeGetBBDomainInfo(i.d_id, &h)) {
×
1611
        continue;
×
1612
      }
×
1613

1614
      if (!h.d_loaded) {
×
1615
        continue;
×
1616
      }
×
1617

1618
      shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
×
1619

1620
      for (recordstorage_t::const_iterator ri = rhandle->begin(); result.size() < maxResults && ri != rhandle->end(); ri++) {
×
1621
        const DNSName& domainName(i.d_name);
×
1622
        DNSName name = ri->qname.empty() ? domainName : (ri->qname + domainName);
×
1623
        if (sm.match(name) || sm.match(ri->content)) {
×
1624
          DNSResourceRecord r;
×
1625
          r.qname = std::move(name);
×
1626
          r.domain_id = i.d_id;
×
1627
          r.content = ri->content;
×
1628
          r.qtype = ri->qtype;
×
1629
          r.ttl = ri->ttl;
×
1630
          r.auth = ri->auth;
×
1631
          result.push_back(std::move(r));
×
1632
        }
×
1633
      }
×
1634
    }
×
1635
  }
23✔
1636

1637
  return true;
23✔
1638
}
23✔
1639

1640
class Bind2Factory : public BackendFactory
1641
{
1642
public:
1643
  Bind2Factory() :
1644
    BackendFactory("bind") {}
5,904✔
1645

1646
  void declareArguments(const string& suffix = "") override
1647
  {
569✔
1648
    declare(suffix, "ignore-broken-records", "Ignore records that are out-of-bound for the zone.", "no");
569✔
1649
    declare(suffix, "config", "Location of named.conf", "");
569✔
1650
    declare(suffix, "check-interval", "Interval for zonefile changes", "0");
569✔
1651
    declare(suffix, "autoprimary-config", "Location of (part of) named.conf where pdns can write zone-statements to", "");
569✔
1652
    declare(suffix, "autoprimaries", "List of IP-addresses of autoprimaries", "");
569✔
1653
    declare(suffix, "autoprimary-destdir", "Destination directory for newly added secondary zones", ::arg()["config-dir"]);
569✔
1654
    declare(suffix, "dnssec-db", "Filename to store & access our DNSSEC metadatabase, empty for none", "");
569✔
1655
    declare(suffix, "dnssec-db-journal-mode", "SQLite3 journal mode", "WAL");
569✔
1656
    declare(suffix, "hybrid", "Store DNSSEC metadata in other backend", "no");
569✔
1657
  }
569✔
1658

1659
  DNSBackend* make(const string& suffix = "") override
1660
  {
2,458✔
1661
    assertEmptySuffix(suffix);
2,458✔
1662
    return new Bind2Backend(suffix);
2,458✔
1663
  }
2,458✔
1664

1665
  DNSBackend* makeMetadataOnly(const string& suffix = "") override
1666
  {
906✔
1667
    assertEmptySuffix(suffix);
906✔
1668
    return new Bind2Backend(suffix, false);
906✔
1669
  }
906✔
1670

1671
private:
1672
  void assertEmptySuffix(const string& suffix)
1673
  {
3,364✔
1674
    if (!suffix.empty())
3,364!
1675
      throw PDNSException("launch= suffixes are not supported on the bindbackend");
×
1676
  }
3,364✔
1677
};
1678

1679
//! Magic class that is activated when the dynamic library is loaded
1680
class Bind2Loader
1681
{
1682
public:
1683
  Bind2Loader()
1684
  {
5,904✔
1685
    BackendMakers().report(std::make_unique<Bind2Factory>());
5,904✔
1686
    // If this module is not loaded dynamically at runtime, this code runs
1687
    // as part of a global constructor, before the structured logger has a
1688
    // chance to be set up, so fallback to simple logging in this case.
1689
    if (!g_slogStructured || !g_slog) {
5,904!
1690
      g_log << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
5,904✔
1691
#ifndef REPRODUCIBLE
5,904✔
1692
            << " (" __DATE__ " " __TIME__ ")"
5,904✔
1693
#endif
5,904✔
1694
#ifdef HAVE_SQLITE3
5,904✔
1695
            << " (with bind-dnssec-db support)"
5,904✔
1696
#endif
5,904✔
1697
            << " reporting" << endl;
5,904✔
1698
    }
5,904✔
NEW
1699
    else {
×
NEW
1700
      g_slog->withName("bind2backend")->info(Logr::Info, "Bind backend starting", "version", Logging::Loggable(VERSION),
×
UNCOV
1701
#ifndef REPRODUCIBLE
×
NEW
1702
                                             "build date", Logging::Loggable(__DATE__ " " __TIME__),
×
UNCOV
1703
#endif
×
NEW
1704
                                             "options",
×
UNCOV
1705
#ifdef HAVE_SQLITE3
×
NEW
1706
                                             Logging::Loggable("bind-dnssec-db")
×
1707
#else
1708
                                             Logging::Loggable("")
1709
#endif
NEW
1710
      );
×
NEW
1711
    }
×
1712
  }
5,904✔
1713
};
1714
static Bind2Loader bind2loader;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc