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

PowerDNS / pdns / 19957761886

05 Dec 2025 08:52AM UTC coverage: 73.063% (-0.07%) from 73.131%
19957761886

push

github

web-flow
Merge pull request #16590 from rgacogne/ddist-coverity-20251204

dnsdist: Fix missed optimizations reported by Coverity in config

38511 of 63422 branches covered (60.72%)

Branch coverage included in aggregate %.

3 of 5 new or added lines in 1 file covered. (60.0%)

13941 existing lines in 122 files now uncovered.

128037 of 164529 relevant lines covered (77.82%)

5473411.95 hits per line

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

61.67
/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()
UNCOV
86
{
15,542✔
UNCOV
87
  d_loaded = false;
15,542✔
UNCOV
88
  d_lastcheck = 0;
15,542✔
UNCOV
89
  d_checknow = false;
15,542✔
UNCOV
90
  d_status = "Unknown";
15,542✔
UNCOV
91
}
15,542✔
92

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

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

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

151
bool Bind2Backend::safeGetBBDomainInfo(const ZoneName& name, BB2DomainInfo* bbd)
UNCOV
152
{
4,315✔
UNCOV
153
  auto state = s_state.read_lock();
4,315✔
UNCOV
154
  const auto& nameindex = boost::multi_index::get<NameTag>(*state);
4,315✔
UNCOV
155
  auto iter = nameindex.find(name);
4,315✔
UNCOV
156
  if (iter == nameindex.end()) {
4,315✔
UNCOV
157
    return false;
3,268✔
UNCOV
158
  }
3,268✔
UNCOV
159
  *bbd = *iter;
1,047✔
UNCOV
160
  return true;
1,047✔
UNCOV
161
}
4,315✔
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)
UNCOV
178
{
2,815✔
UNCOV
179
  auto state = s_state.write_lock();
2,815✔
UNCOV
180
  replacing_insert(*state, bbd);
2,815✔
UNCOV
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)
UNCOV
195
{
72✔
UNCOV
196
  BB2DomainInfo bbd;
72✔
UNCOV
197
  if (safeGetBBDomainInfo(domain_id, &bbd)) {
72!
UNCOV
198
    bbd.d_lastcheck = lastcheck;
72✔
UNCOV
199
    safePutBBDomainInfo(bbd);
72✔
UNCOV
200
  }
72✔
UNCOV
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)
UNCOV
209
{
72✔
UNCOV
210
  Bind2Backend::setLastCheck(domain_id, time(nullptr));
72✔
UNCOV
211
}
72✔
212

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

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

UNCOV
235
    d_of = std::make_unique<ofstream>(d_transaction_tmpname);
72✔
UNCOV
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
    }
×
UNCOV
243
    close(fd);
72✔
UNCOV
244
    fd = -1;
72✔
245

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

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

255
bool Bind2Backend::commitTransaction()
UNCOV
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.
UNCOV
259
  if (d_transaction_id == UnknownDomainID) {
221✔
UNCOV
260
    return false;
149✔
UNCOV
261
  }
149✔
UNCOV
262
  d_of.reset();
72✔
263

UNCOV
264
  BB2DomainInfo bbd;
72✔
UNCOV
265
  if (safeGetBBDomainInfo(d_transaction_id, &bbd)) {
72!
UNCOV
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
    }
×
UNCOV
269
    queueReloadAndStore(bbd.d_id);
72✔
UNCOV
270
  }
72✔
271

UNCOV
272
  d_transaction_id = UnknownDomainID;
72✔
273

UNCOV
274
  return true;
72✔
UNCOV
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)
UNCOV
291
{
432✔
UNCOV
292
  if (lhs.size() != rhs.size()) {
432✔
UNCOV
293
    return false;
408✔
UNCOV
294
  }
408✔
295

UNCOV
296
  string::size_type pos = 0;
24✔
UNCOV
297
  const string::size_type epos = lhs.size();
24✔
UNCOV
298
  for (; pos < epos; ++pos) {
384✔
UNCOV
299
    if (dns_tolower(lhs[pos]) != dns_tolower(rhs[pos])) {
368✔
UNCOV
300
      return false;
8✔
UNCOV
301
    }
8✔
UNCOV
302
  }
368✔
UNCOV
303
  return true;
16✔
UNCOV
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)
UNCOV
308
{
432✔
UNCOV
309
  if (suffix.empty() || ciEqual(domain, suffix)) {
432!
UNCOV
310
    return true;
16✔
UNCOV
311
  }
16✔
312

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

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

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

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

UNCOV
330
  return true;
264✔
UNCOV
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)
UNCOV
335
{
432✔
UNCOV
336
  std::string domain = zonename.operator const DNSName&().toString();
432✔
337

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

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

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

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

UNCOV
361
  string qname;
202,793✔
UNCOV
362
  if (d_transaction_qname.empty()) {
202,793!
363
    qname = rr.qname.toString();
×
364
  }
×
UNCOV
365
  else if (rr.qname.isPartOf(d_transaction_qname)) {
202,793!
UNCOV
366
    if (rr.qname == d_transaction_qname.operator const DNSName&()) {
202,793✔
UNCOV
367
      qname = "@";
633✔
UNCOV
368
    }
633✔
UNCOV
369
    else {
202,160✔
UNCOV
370
      DNSName relName = rr.qname.makeRelative(d_transaction_qname);
202,160✔
UNCOV
371
      qname = relName.toStringNoDot();
202,160✔
UNCOV
372
    }
202,160✔
UNCOV
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

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

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

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

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

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

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

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

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

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

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

UNCOV
541
  return true;
445✔
UNCOV
542
}
445✔
543

544
void Bind2Backend::alsoNotifies(const ZoneName& domain, set<string>* ips)
UNCOV
545
{
4✔
546
  // combine global list with local list
UNCOV
547
  for (const auto& i : this->alsoNotify) {
4!
548
    (*ips).insert(i);
×
549
  }
×
550
  // check metadata too if available
UNCOV
551
  vector<string> meta;
4✔
UNCOV
552
  if (getDomainMetadata(domain, "ALSO-NOTIFY", meta)) {
4!
553
    for (const auto& str : meta) {
×
554
      (*ips).insert(str);
×
555
    }
×
556
  }
×
UNCOV
557
  auto state = s_state.read_lock();
4✔
UNCOV
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
  }
×
UNCOV
566
}
4✔
567

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

UNCOV
580
  auto records = std::make_shared<recordstorage_t>();
2,737✔
UNCOV
581
  ZoneParserTNG zpt(bbd->main_filename(), bbd->d_name, s_binddirectory, d_upgradeContent);
2,737✔
UNCOV
582
  zpt.setMaxGenerateSteps(::arg().asNum("max-generate-steps"));
2,737✔
UNCOV
583
  zpt.setMaxIncludes(::arg().asNum("max-include-depth"));
2,737✔
UNCOV
584
  DNSResourceRecord rr;
2,737✔
UNCOV
585
  string hashed;
2,737✔
UNCOV
586
  while (zpt.get(rr)) {
3,277,433✔
UNCOV
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

UNCOV
590
    insertRecord(records, bbd->d_name, rr.qname, rr.qtype, rr.content, rr.ttl, "");
3,274,696✔
UNCOV
591
  }
3,274,696✔
UNCOV
592
  fixupOrderAndAuth(records, bbd->d_name, nsec3zone, ns3pr);
2,737✔
UNCOV
593
  doEmptyNonTerminals(records, bbd->d_name, nsec3zone, ns3pr);
2,737✔
UNCOV
594
  bbd->d_fileinfo = zpt.getFileset();
2,737✔
UNCOV
595
  bbd->d_loaded = true;
2,737✔
UNCOV
596
  bbd->d_checknow = false;
2,737✔
UNCOV
597
  bbd->d_status = "parsed into memory at " + nowTime();
2,737✔
UNCOV
598
  bbd->d_records = LookButDontTouch<recordstorage_t>(std::move(records));
2,737✔
UNCOV
599
  bbd->d_nsec3zone = nsec3zone;
2,737✔
UNCOV
600
  bbd->d_nsec3param = std::move(ns3pr);
2,737✔
UNCOV
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)
UNCOV
606
{
3,279,312✔
UNCOV
607
  Bind2DNSRecord bdr;
3,279,312✔
UNCOV
608
  bdr.qname = qname;
3,279,312✔
609

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
795
  safePutBBDomainInfo(bbd);
6✔
796

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

UNCOV
799
  g_log << Logger::Warning << "Zone " << domainname << " loaded" << endl;
6✔
UNCOV
800
  return "Loaded zone " + domainname.toLogString() + " from " + filename;
6✔
UNCOV
801
}
6✔
802

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

UNCOV
820
  setArgPrefix("bind" + suffix);
3,277✔
UNCOV
821
  d_logprefix = "[bind" + suffix + "backend]";
3,277✔
UNCOV
822
  d_hybrid = mustDo("hybrid");
3,277✔
UNCOV
823
  if (d_hybrid && g_zoneCache.isEnabled()) {
3,277!
824
    throw PDNSException("bind-hybrid and the zone cache currently interoperate badly. Please disable the zone cache or stop using bind-hybrid");
×
825
  }
×
826

UNCOV
827
  d_transaction_id = UnknownDomainID;
3,277✔
UNCOV
828
  s_ignore_broken_records = mustDo("ignore-broken-records");
3,277✔
UNCOV
829
  d_upgradeContent = ::arg().mustDo("upgrade-unknown-types");
3,277✔
830

UNCOV
831
  if (!loadZones && d_hybrid)
3,277!
832
    return;
×
833

UNCOV
834
  auto lock = std::scoped_lock(s_startup_lock);
3,277✔
835

UNCOV
836
  setupDNSSEC();
3,277✔
UNCOV
837
  if (s_first == 0) {
3,277✔
UNCOV
838
    return;
2,517✔
UNCOV
839
  }
2,517✔
840

UNCOV
841
  if (loadZones) {
760✔
UNCOV
842
    loadConfig();
311✔
UNCOV
843
    s_first = 0;
311✔
UNCOV
844
  }
311✔
845

UNCOV
846
  DynListener::registerFunc("BIND-ADD-ZONE", &DLAddDomainHandler, "bindbackend: add zone", "<domain> <filename>");
760✔
UNCOV
847
  DynListener::registerFunc("BIND-DOMAIN-EXTENDED-STATUS", &DLDomExtendedStatusHandler, "bindbackend: list the extended status of all domains", "[domains]");
760✔
UNCOV
848
  DynListener::registerFunc("BIND-DOMAIN-STATUS", &DLDomStatusHandler, "bindbackend: list status of all domains", "[domains]");
760✔
UNCOV
849
  DynListener::registerFunc("BIND-LIST-REJECTS", &DLListRejectsHandler, "bindbackend: list rejected domains");
760✔
UNCOV
850
  DynListener::registerFunc("BIND-RELOAD-NOW", &DLReloadNowHandler, "bindbackend: reload domains", "<domains>");
760✔
UNCOV
851
}
760✔
852

853
Bind2Backend::~Bind2Backend()
UNCOV
854
{
3,153✔
UNCOV
855
  freeStatements();
3,153✔
UNCOV
856
} // deallocate statements
3,153✔
857

858
void Bind2Backend::rediscover(string* status)
859
{
×
860
  loadConfig(status);
×
861
}
×
862

863
void Bind2Backend::reload()
864
{
×
865
  auto state = s_state.write_lock();
×
866
  for (const auto& i : *state) {
×
867
    i.d_checknow = true; // being a bit cheeky here, don't index state_t on this (mutable)
×
868
  }
×
869
}
×
870

871
void Bind2Backend::fixupOrderAndAuth(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
UNCOV
872
{
2,665✔
UNCOV
873
  bool skip;
2,665✔
UNCOV
874
  DNSName shorter;
2,665✔
UNCOV
875
  set<DNSName> nssets, dssets;
2,665✔
876

UNCOV
877
  for (const auto& bdr : *records) {
3,274,394✔
UNCOV
878
    if (!bdr.qname.isRoot() && bdr.qtype == QType::NS)
3,274,394✔
UNCOV
879
      nssets.insert(bdr.qname);
3,010✔
UNCOV
880
    else if (bdr.qtype == QType::DS)
3,271,384✔
UNCOV
881
      dssets.insert(bdr.qname);
499✔
UNCOV
882
  }
3,274,394✔
883

UNCOV
884
  for (auto iter = records->begin(); iter != records->end(); iter++) {
3,277,059✔
UNCOV
885
    skip = false;
3,274,394✔
UNCOV
886
    shorter = iter->qname;
3,274,394✔
887

UNCOV
888
    if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
3,274,394!
UNCOV
889
      do {
3,273,161✔
UNCOV
890
        if (nssets.count(shorter) != 0u) {
3,273,161✔
UNCOV
891
          skip = true;
1,359✔
UNCOV
892
          break;
1,359✔
UNCOV
893
        }
1,359✔
UNCOV
894
      } while (shorter.chopOff() && !iter->qname.isRoot());
3,273,161!
UNCOV
895
    }
3,263,263✔
896

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

UNCOV
899
    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✔
UNCOV
900
      Bind2DNSRecord bdr = *iter;
1,439,587✔
UNCOV
901
      bdr.nsec3hash = toBase32Hex(hashQNameWithSalt(ns3pr, bdr.qname + zoneName.operator const DNSName&()));
1,439,587✔
UNCOV
902
      records->replace(iter, bdr);
1,439,587✔
UNCOV
903
    }
1,439,587✔
904

905
    // cerr<<iter->qname<<"\t"<<QType(iter->qtype).toString()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
UNCOV
906
  }
3,274,394✔
UNCOV
907
}
2,665✔
908

909
void Bind2Backend::doEmptyNonTerminals(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
UNCOV
910
{
2,665✔
UNCOV
911
  bool auth = false;
2,665✔
UNCOV
912
  DNSName shorter;
2,665✔
UNCOV
913
  std::unordered_set<DNSName> qnames;
2,665✔
UNCOV
914
  std::unordered_map<DNSName, bool> nonterm;
2,665✔
915

UNCOV
916
  uint32_t maxent = ::arg().asNum("max-ent-entries");
2,665✔
917

UNCOV
918
  for (const auto& bdr : *records)
2,665✔
UNCOV
919
    qnames.insert(bdr.qname);
3,274,394✔
920

UNCOV
921
  for (const auto& bdr : *records) {
3,274,394✔
922

UNCOV
923
    if (!bdr.auth && bdr.qtype == QType::NS)
3,274,394✔
UNCOV
924
      auth = (!nsec3zone || (ns3pr.d_flags == 0u));
3,010✔
UNCOV
925
    else
3,271,384✔
UNCOV
926
      auth = bdr.auth;
3,271,384✔
927

UNCOV
928
    shorter = bdr.qname;
3,274,394✔
UNCOV
929
    while (shorter.chopOff()) {
6,548,914✔
UNCOV
930
      if (qnames.count(shorter) == 0u) {
3,274,520✔
UNCOV
931
        if (!(maxent)) {
9,732!
932
          g_log << Logger::Error << "Zone '" << zoneName << "' has too many empty non terminals." << endl;
×
933
          return;
×
934
        }
×
935

UNCOV
936
        if (nonterm.count(shorter) == 0u) {
9,732✔
UNCOV
937
          nonterm.emplace(shorter, auth);
4,616✔
UNCOV
938
          --maxent;
4,616✔
UNCOV
939
        }
4,616✔
UNCOV
940
        else if (auth)
5,116✔
UNCOV
941
          nonterm[shorter] = true;
5,020✔
UNCOV
942
      }
9,732✔
UNCOV
943
    }
3,274,520✔
UNCOV
944
  }
3,274,394✔
945

UNCOV
946
  DNSResourceRecord rr;
2,665✔
UNCOV
947
  rr.qtype = "#0";
2,665✔
UNCOV
948
  rr.content = "";
2,665✔
UNCOV
949
  rr.ttl = 0;
2,665✔
UNCOV
950
  for (auto& nt : nonterm) {
4,617✔
UNCOV
951
    string hashed;
4,616✔
UNCOV
952
    rr.qname = nt.first + zoneName.operator const DNSName&();
4,616✔
UNCOV
953
    if (nsec3zone && nt.second)
4,616✔
UNCOV
954
      hashed = toBase32Hex(hashQNameWithSalt(ns3pr, rr.qname));
1,782✔
UNCOV
955
    insertRecord(records, zoneName, rr.qname, rr.qtype, rr.content, rr.ttl, hashed, &nt.second);
4,616✔
956

957
    // cerr<<rr.qname<<"\t"<<rr.qtype.toString()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
UNCOV
958
  }
4,616✔
UNCOV
959
}
2,665✔
960

961
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
UNCOV
962
{
311✔
UNCOV
963
  static domainid_t domain_id = 1;
311✔
964

UNCOV
965
  if (!getArg("config").empty()) {
311!
UNCOV
966
    BindParser BP;
311✔
UNCOV
967
    try {
311✔
UNCOV
968
      BP.parse(getArg("config"));
311✔
UNCOV
969
    }
311✔
UNCOV
970
    catch (PDNSException& ae) {
311✔
971
      g_log << Logger::Error << "Error parsing bind configuration: " << ae.reason << endl;
×
972
      throw;
×
973
    }
×
974

UNCOV
975
    vector<BindDomainInfo> domains = BP.getDomains();
311✔
UNCOV
976
    this->alsoNotify = BP.getAlsoNotify();
311✔
977

UNCOV
978
    s_binddirectory = BP.getDirectory();
311✔
979
    //    ZP.setDirectory(d_binddirectory);
980

UNCOV
981
    g_log << Logger::Warning << d_logprefix << " Parsing " << domains.size() << " domain(s), will report when done" << endl;
311✔
982

UNCOV
983
    set<ZoneName> oldnames;
311✔
UNCOV
984
    set<ZoneName> newnames;
311✔
UNCOV
985
    {
311✔
UNCOV
986
      auto state = s_state.read_lock();
311✔
UNCOV
987
      for (const BB2DomainInfo& bbd : *state) {
311!
988
        oldnames.insert(bbd.d_name);
×
989
      }
×
UNCOV
990
    }
311✔
UNCOV
991
    int rejected = 0;
311✔
UNCOV
992
    int newdomains = 0;
311✔
993

UNCOV
994
    struct stat st;
311✔
995

UNCOV
996
    for (auto& domain : domains) {
2,791✔
UNCOV
997
      if (stat(domain.filename.c_str(), &st) == 0) {
2,659✔
UNCOV
998
        domain.d_dev = st.st_dev;
2,587✔
UNCOV
999
        domain.d_ino = st.st_ino;
2,587✔
UNCOV
1000
      }
2,587✔
UNCOV
1001
    }
2,659✔
1002

UNCOV
1003
    sort(domains.begin(), domains.end()); // put stuff in inode order
311✔
UNCOV
1004
    for (const auto& domain : domains) {
2,791✔
UNCOV
1005
      if (!(domain.hadFileDirective)) {
2,659!
1006
        g_log << Logger::Warning << d_logprefix << " Zone '" << domain.name << "' has no 'file' directive set in " << getArg("config") << endl;
×
1007
        rejected++;
×
1008
        continue;
×
1009
      }
×
1010

UNCOV
1011
      if (domain.type.empty()) {
2,659!
1012
        g_log << Logger::Notice << d_logprefix << " Zone '" << domain.name << "' has no type specified, assuming 'native'" << endl;
×
1013
      }
×
UNCOV
1014
      if (domain.type != "primary" && domain.type != "secondary" && domain.type != "native" && !domain.type.empty() && domain.type != "master" && domain.type != "slave") {
2,659!
1015
        g_log << Logger::Warning << d_logprefix << " Warning! Skipping zone '" << domain.name << "' because type '" << domain.type << "' is invalid" << endl;
×
1016
        rejected++;
×
1017
        continue;
×
1018
      }
×
1019

UNCOV
1020
      BB2DomainInfo bbd;
2,659✔
UNCOV
1021
      bool isNew = false;
2,659✔
1022

UNCOV
1023
      if (!safeGetBBDomainInfo(domain.name, &bbd)) {
2,659!
UNCOV
1024
        isNew = true;
2,659✔
UNCOV
1025
        bbd.d_id = domain_id++;
2,659✔
UNCOV
1026
        bbd.setCheckInterval(getArgAsNum("check-interval"));
2,659✔
UNCOV
1027
        bbd.d_lastnotified = 0;
2,659✔
UNCOV
1028
        bbd.d_loaded = false;
2,659✔
UNCOV
1029
      }
2,659✔
1030

1031
      // overwrite what we knew about the domain
UNCOV
1032
      bbd.d_name = domain.name;
2,659✔
UNCOV
1033
      bool filenameChanged = bbd.d_fileinfo.empty() || (bbd.main_filename() != domain.filename);
2,659!
UNCOV
1034
      bool addressesChanged = (bbd.d_primaries != domain.primaries || bbd.d_also_notify != domain.alsoNotify);
2,659!
1035
      // Preserve existing fileinfo in case we won't reread anything.
UNCOV
1036
      if (filenameChanged) {
2,659!
UNCOV
1037
        bbd.d_fileinfo.clear();
2,659✔
UNCOV
1038
        bbd.d_fileinfo.emplace_back(std::make_pair(domain.filename, 0));
2,659✔
UNCOV
1039
      }
2,659✔
UNCOV
1040
      bbd.d_primaries = domain.primaries;
2,659✔
UNCOV
1041
      bbd.d_also_notify = domain.alsoNotify;
2,659✔
1042

UNCOV
1043
      DomainInfo::DomainKind kind = DomainInfo::Native;
2,659✔
UNCOV
1044
      if (domain.type == "primary" || domain.type == "master") {
2,659!
UNCOV
1045
        kind = DomainInfo::Primary;
2,587✔
UNCOV
1046
      }
2,587✔
UNCOV
1047
      if (domain.type == "secondary" || domain.type == "slave") {
2,659!
UNCOV
1048
        kind = DomainInfo::Secondary;
72✔
UNCOV
1049
      }
72✔
1050

UNCOV
1051
      bool kindChanged = (bbd.d_kind != kind);
2,659✔
UNCOV
1052
      bbd.d_kind = kind;
2,659✔
1053

UNCOV
1054
      newnames.insert(bbd.d_name);
2,659✔
UNCOV
1055
      if (filenameChanged || !bbd.d_loaded || !bbd.current()) {
2,659!
UNCOV
1056
        g_log << Logger::Info << d_logprefix << " parsing '" << domain.name << "' from file '" << domain.filename << "'" << endl;
2,659✔
1057

UNCOV
1058
        try {
2,659✔
UNCOV
1059
          parseZoneFile(&bbd);
2,659✔
UNCOV
1060
        }
2,659✔
UNCOV
1061
        catch (PDNSException& ae) {
2,659✔
1062
          ostringstream msg;
×
1063
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.reason;
×
1064

1065
          if (status != nullptr)
×
1066
            *status += msg.str();
×
1067
          bbd.d_status = msg.str();
×
1068

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

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

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

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

UNCOV
1107
    set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
311✔
UNCOV
1108
    unsigned int remdomains = diff.size();
311✔
1109

UNCOV
1110
    for (const ZoneName& name : diff) {
311!
1111
      safeRemoveBBDomainInfo(name);
×
1112
    }
×
1113

1114
    // count number of entirely new domains
UNCOV
1115
    diff.clear();
311✔
UNCOV
1116
    set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
311✔
UNCOV
1117
    newdomains = diff.size();
311✔
1118

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

UNCOV
1124
    g_log << Logger::Error << d_logprefix << msg.str() << endl;
311✔
UNCOV
1125
  }
311✔
UNCOV
1126
}
311✔
1127

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

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

UNCOV
1170
  recordstorage_t::const_iterator iterBefore, iterAfter;
2,718✔
1171

UNCOV
1172
  iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
2,718✔
1173

UNCOV
1174
  if (iterBefore != records->begin())
2,718!
UNCOV
1175
    --iterBefore;
2,718✔
UNCOV
1176
  while ((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
3,247✔
UNCOV
1177
    --iterBefore;
529✔
UNCOV
1178
  before = iterBefore->qname;
2,718✔
1179

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

UNCOV
1194
  return true;
2,718✔
UNCOV
1195
}
2,718✔
1196

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

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

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

UNCOV
1214
    auto first = hashindex.upper_bound("");
4,339✔
UNCOV
1215
    auto iter = hashindex.upper_bound(qname.toStringNoDot());
4,339✔
1216

UNCOV
1217
    if (iter == hashindex.end()) {
4,339✔
UNCOV
1218
      --iter;
363✔
UNCOV
1219
      before = DNSName(iter->nsec3hash);
363✔
UNCOV
1220
      after = DNSName(first->nsec3hash);
363✔
UNCOV
1221
    }
363✔
UNCOV
1222
    else {
3,976✔
UNCOV
1223
      after = DNSName(iter->nsec3hash);
3,976✔
UNCOV
1224
      if (iter != first)
3,976✔
UNCOV
1225
        --iter;
3,882✔
UNCOV
1226
      else
94✔
UNCOV
1227
        iter = --hashindex.end();
94✔
UNCOV
1228
      before = DNSName(iter->nsec3hash);
3,976✔
UNCOV
1229
    }
3,976✔
UNCOV
1230
    unhashed = iter->qname + bbd.d_name.operator const DNSName&();
4,339✔
1231

UNCOV
1232
    return true;
4,339✔
UNCOV
1233
  }
4,339✔
UNCOV
1234
}
7,057✔
1235

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

UNCOV
1240
  static bool mustlog = ::arg().mustDo("query-logging");
4,162✔
1241

UNCOV
1242
  bool found = false;
4,162✔
UNCOV
1243
  ZoneName domain;
4,162✔
UNCOV
1244
  BB2DomainInfo bbd;
4,162✔
1245

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

UNCOV
1249
  if (zoneId != UnknownDomainID) {
4,162✔
UNCOV
1250
    if ((found = (safeGetBBDomainInfo(zoneId, &bbd) && qname.isPartOf(bbd.d_name)))) {
3,548!
UNCOV
1251
      domain = std::move(bbd.d_name);
3,548✔
UNCOV
1252
    }
3,548✔
UNCOV
1253
  }
3,548✔
UNCOV
1254
  else {
614✔
UNCOV
1255
    domain = ZoneName(qname);
614✔
UNCOV
1256
    do {
617✔
UNCOV
1257
      found = safeGetBBDomainInfo(domain, &bbd);
617✔
UNCOV
1258
    } while (!found && qtype != QType::SOA && domain.chopOff());
617✔
UNCOV
1259
  }
614✔
1260

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

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

UNCOV
1271
  d_handle.id = bbd.d_id;
4,138✔
UNCOV
1272
  d_handle.qname = qname.makeRelative(domain); // strip domain name
4,138✔
UNCOV
1273
  d_handle.qtype = qtype;
4,138✔
UNCOV
1274
  d_handle.domain = std::move(domain);
4,138✔
1275

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

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

UNCOV
1288
  d_handle.d_records = bbd.d_records.get();
3,922✔
1289

UNCOV
1290
  if (d_handle.d_records->empty())
3,922!
1291
    DLOG(g_log << "Query with no results" << endl);
×
1292

UNCOV
1293
  d_handle.mustlog = mustlog;
3,922✔
1294

UNCOV
1295
  const auto& hashedidx = boost::multi_index::get<UnorderedNameTag>(*d_handle.d_records);
3,922✔
UNCOV
1296
  auto range = hashedidx.equal_range(d_handle.qname);
3,922✔
1297

UNCOV
1298
  d_handle.d_list = false;
3,922✔
UNCOV
1299
  d_handle.d_iter = range.first;
3,922✔
UNCOV
1300
  d_handle.d_end_iter = range.second;
3,922✔
UNCOV
1301
}
3,922✔
1302

1303
bool Bind2Backend::get(DNSResourceRecord& r)
UNCOV
1304
{
197,986✔
UNCOV
1305
  if (!d_handle.d_records) {
197,986✔
UNCOV
1306
    if (d_handle.mustlog)
24!
1307
      g_log << Logger::Warning << "There were no answers" << endl;
×
UNCOV
1308
    return false;
24✔
UNCOV
1309
  }
24✔
1310

UNCOV
1311
  if (!d_handle.get(r)) {
197,962✔
UNCOV
1312
    if (d_handle.mustlog)
4,223!
1313
      g_log << Logger::Warning << "End of answers" << endl;
×
1314

UNCOV
1315
    d_handle.reset();
4,223✔
1316

UNCOV
1317
    return false;
4,223✔
UNCOV
1318
  }
4,223✔
UNCOV
1319
  if (d_handle.mustlog)
193,739!
1320
    g_log << Logger::Warning << "Returning: '" << r.qtype.toString() << "' of '" << r.qname << "', content: '" << r.content << "'" << endl;
×
UNCOV
1321
  return true;
193,739✔
UNCOV
1322
}
197,962✔
1323

1324
void Bind2Backend::lookupEnd()
UNCOV
1325
{
30✔
UNCOV
1326
  d_handle.reset();
30✔
UNCOV
1327
}
30✔
1328

1329
bool Bind2Backend::handle::get(DNSResourceRecord& r)
UNCOV
1330
{
197,962✔
UNCOV
1331
  if (d_list)
197,962✔
UNCOV
1332
    return get_list(r);
188,918✔
UNCOV
1333
  else
9,044✔
UNCOV
1334
    return get_normal(r);
9,044✔
UNCOV
1335
}
197,962✔
1336

1337
void Bind2Backend::handle::reset()
UNCOV
1338
{
8,962✔
UNCOV
1339
  d_records.reset();
8,962✔
UNCOV
1340
  qname.clear();
8,962✔
UNCOV
1341
  mustlog = false;
8,962✔
UNCOV
1342
}
8,962✔
1343

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

UNCOV
1349
  if (d_iter == d_end_iter) {
9,044✔
UNCOV
1350
    return false;
3,892✔
UNCOV
1351
  }
3,892✔
1352

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

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

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

UNCOV
1374
  d_iter++;
5,152✔
1375

UNCOV
1376
  return true;
5,152✔
UNCOV
1377
}
5,152✔
1378

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

UNCOV
1383
  if (!safeGetBBDomainInfo(domainId, &bbd)) {
331!
1384
    return false;
×
1385
  }
×
1386

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

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

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

UNCOV
1398
  d_handle.id = domainId;
331✔
UNCOV
1399
  d_handle.domain = bbd.d_name;
331✔
UNCOV
1400
  d_handle.d_list = true;
331✔
UNCOV
1401
  return true;
331✔
UNCOV
1402
}
331✔
1403

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

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

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

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

1441
  c_if.close();
×
1442
  return true;
×
1443
}
×
1444

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

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

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

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

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

1479
  return true;
×
1480
}
×
1481

1482
BB2DomainInfo Bind2Backend::createDomainEntry(const ZoneName& domain)
UNCOV
1483
{
6✔
UNCOV
1484
  domainid_t newid = 1;
6✔
UNCOV
1485
  { // Find a free zone id nr.
6✔
UNCOV
1486
    auto state = s_state.read_lock();
6✔
UNCOV
1487
    if (!state->empty()) {
6!
UNCOV
1488
      newid = state->rbegin()->d_id + 1;
6✔
UNCOV
1489
    }
6✔
UNCOV
1490
  }
6✔
1491

UNCOV
1492
  BB2DomainInfo bbd;
6✔
UNCOV
1493
  bbd.d_kind = DomainInfo::Native;
6✔
UNCOV
1494
  bbd.d_id = newid;
6✔
UNCOV
1495
  bbd.d_records = std::make_shared<recordstorage_t>();
6✔
UNCOV
1496
  bbd.d_name = domain;
6✔
UNCOV
1497
  bbd.setCheckInterval(getArgAsNum("check-interval"));
6✔
1498

UNCOV
1499
  return bbd;
6✔
UNCOV
1500
}
6✔
1501

1502
bool Bind2Backend::createSecondaryDomain(const string& ipAddress, const ZoneName& domain, const string& /* nameserver */, const string& account)
1503
{
×
1504
  string filename = getArg("autoprimary-destdir") + '/' + domain.toStringNoDot();
×
1505

1506
  g_log << Logger::Warning << d_logprefix
×
1507
        << " Writing bind config zone statement for superslave zone '" << domain
×
1508
        << "' from autoprimary " << ipAddress << endl;
×
1509

1510
  {
×
1511
    auto lock = std::scoped_lock(s_autosecondary_config_lock);
×
1512

1513
    ofstream c_of(getArg("autoprimary-config").c_str(), std::ios::app);
×
1514
    if (!c_of) {
×
1515
      g_log << Logger::Error << "Unable to open autoprimary configfile for append: " << stringerror() << endl;
×
1516
      throw DBException("Unable to open autoprimary configfile for append: " + stringerror());
×
1517
    }
×
1518

1519
    c_of << endl;
×
1520
    c_of << "# AutoSecondary zone '" << domain.toString() << "' (added: " << nowTime() << ") (account: " << account << ')' << endl;
×
1521
    c_of << "zone \"" << domain.toStringNoDot() << "\" {" << endl;
×
1522
    c_of << "\ttype secondary;" << endl;
×
1523
    c_of << "\tfile \"" << filename << "\";" << endl;
×
1524
    c_of << "\tprimaries { " << ipAddress << "; };" << endl;
×
1525
    c_of << "};" << endl;
×
1526
    c_of.close();
×
1527
  }
×
1528

1529
  BB2DomainInfo bbd = createDomainEntry(domain);
×
1530
  bbd.d_kind = DomainInfo::Secondary;
×
1531
  bbd.d_primaries.emplace_back(ComboAddress(ipAddress, 53));
×
1532
  bbd.d_fileinfo.emplace_back(std::make_pair(filename, 0));
×
1533
  bbd.updateCtime();
×
1534
  safePutBBDomainInfo(bbd);
×
1535

1536
  return true;
×
1537
}
×
1538

1539
bool Bind2Backend::searchRecords(const string& pattern, size_t maxResults, vector<DNSResourceRecord>& result)
UNCOV
1540
{
23✔
UNCOV
1541
  SimpleMatch sm(pattern, true);
23✔
UNCOV
1542
  static bool mustlog = ::arg().mustDo("query-logging");
23✔
UNCOV
1543
  if (mustlog)
23!
1544
    g_log << Logger::Warning << "Search for pattern '" << pattern << "'" << endl;
×
1545

UNCOV
1546
  {
23✔
UNCOV
1547
    auto state = s_state.read_lock();
23✔
1548

UNCOV
1549
    for (const auto& i : *state) {
23!
1550
      BB2DomainInfo h;
×
1551
      if (!safeGetBBDomainInfo(i.d_id, &h)) {
×
1552
        continue;
×
1553
      }
×
1554

1555
      if (!h.d_loaded) {
×
1556
        continue;
×
1557
      }
×
1558

1559
      shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
×
1560

1561
      for (recordstorage_t::const_iterator ri = rhandle->begin(); result.size() < maxResults && ri != rhandle->end(); ri++) {
×
1562
        const DNSName& domainName(i.d_name);
×
1563
        DNSName name = ri->qname.empty() ? domainName : (ri->qname + domainName);
×
1564
        if (sm.match(name) || sm.match(ri->content)) {
×
1565
          DNSResourceRecord r;
×
1566
          r.qname = std::move(name);
×
1567
          r.domain_id = i.d_id;
×
1568
          r.content = ri->content;
×
1569
          r.qtype = ri->qtype;
×
1570
          r.ttl = ri->ttl;
×
1571
          r.auth = ri->auth;
×
1572
          result.push_back(std::move(r));
×
1573
        }
×
1574
      }
×
1575
    }
×
UNCOV
1576
  }
23✔
1577

UNCOV
1578
  return true;
23✔
UNCOV
1579
}
23✔
1580

1581
class Bind2Factory : public BackendFactory
1582
{
1583
public:
1584
  Bind2Factory() :
1585
    BackendFactory("bind") {}
5,904✔
1586

1587
  void declareArguments(const string& suffix = "") override
UNCOV
1588
  {
569✔
UNCOV
1589
    declare(suffix, "ignore-broken-records", "Ignore records that are out-of-bound for the zone.", "no");
569✔
UNCOV
1590
    declare(suffix, "config", "Location of named.conf", "");
569✔
UNCOV
1591
    declare(suffix, "check-interval", "Interval for zonefile changes", "0");
569✔
UNCOV
1592
    declare(suffix, "autoprimary-config", "Location of (part of) named.conf where pdns can write zone-statements to", "");
569✔
UNCOV
1593
    declare(suffix, "autoprimaries", "List of IP-addresses of autoprimaries", "");
569✔
UNCOV
1594
    declare(suffix, "autoprimary-destdir", "Destination directory for newly added secondary zones", ::arg()["config-dir"]);
569✔
UNCOV
1595
    declare(suffix, "dnssec-db", "Filename to store & access our DNSSEC metadatabase, empty for none", "");
569✔
UNCOV
1596
    declare(suffix, "dnssec-db-journal-mode", "SQLite3 journal mode", "WAL");
569✔
UNCOV
1597
    declare(suffix, "hybrid", "Store DNSSEC metadata in other backend", "no");
569✔
UNCOV
1598
  }
569✔
1599

1600
  DNSBackend* make(const string& suffix = "") override
UNCOV
1601
  {
2,365✔
UNCOV
1602
    assertEmptySuffix(suffix);
2,365✔
UNCOV
1603
    return new Bind2Backend(suffix);
2,365✔
UNCOV
1604
  }
2,365✔
1605

1606
  DNSBackend* makeMetadataOnly(const string& suffix = "") override
UNCOV
1607
  {
906✔
UNCOV
1608
    assertEmptySuffix(suffix);
906✔
UNCOV
1609
    return new Bind2Backend(suffix, false);
906✔
UNCOV
1610
  }
906✔
1611

1612
private:
1613
  void assertEmptySuffix(const string& suffix)
UNCOV
1614
  {
3,271✔
UNCOV
1615
    if (!suffix.empty())
3,271!
1616
      throw PDNSException("launch= suffixes are not supported on the bindbackend");
×
UNCOV
1617
  }
3,271✔
1618
};
1619

1620
//! Magic class that is activated when the dynamic library is loaded
1621
class Bind2Loader
1622
{
1623
public:
1624
  Bind2Loader()
1625
  {
5,904✔
1626
    BackendMakers().report(std::make_unique<Bind2Factory>());
5,904✔
1627
    g_log << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
5,904✔
1628
#ifndef REPRODUCIBLE
5,904✔
1629
          << " (" __DATE__ " " __TIME__ ")"
5,904✔
1630
#endif
5,904✔
1631
#ifdef HAVE_SQLITE3
5,904✔
1632
          << " (with bind-dnssec-db support)"
5,904✔
1633
#endif
5,904✔
1634
          << " reporting" << endl;
5,904✔
1635
  }
5,904✔
1636
};
1637
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