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

PowerDNS / pdns / 15701660542

17 Jun 2025 08:05AM UTC coverage: 65.092% (-0.4%) from 65.54%
15701660542

Pull #15685

github

web-flow
Merge 62e3fc13e into 297eb9dd5
Pull Request #15685: meson: Pick -lcrypto up from the spot defined by dep_libcrypto

40902 of 91272 branches covered (44.81%)

Branch coverage included in aggregate %.

124841 of 163357 relevant lines covered (76.42%)

6183565.31 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

266
  d_transaction_id = UnknownDomainID;
×
267

268
  return true;
×
269
}
×
270

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

281
  return true;
×
282
}
×
283

284
bool Bind2Backend::feedRecord(const DNSResourceRecord& rr, const DNSName& /* ordername */, bool /* ordernameIsNSEC3 */)
285
{
×
286
  if (d_transaction_id == UnknownDomainID) {
×
287
    throw DBException("Bind2Backend::feedRecord() called outside of transaction");
×
288
  }
×
289

290
  string qname;
×
291
  if (d_transaction_qname.empty()) {
×
292
    qname = rr.qname.toString();
×
293
  }
×
294
  else if (rr.qname.isPartOf(d_transaction_qname)) {
×
295
    if (rr.qname == d_transaction_qname.operator const DNSName&()) {
×
296
      qname = "@";
×
297
    }
×
298
    else {
×
299
      DNSName relName = rr.qname.makeRelative(d_transaction_qname);
×
300
      qname = relName.toStringNoDot();
×
301
    }
×
302
  }
×
303
  else {
×
304
    throw DBException("out-of-zone data '" + rr.qname.toLogString() + "' during AXFR of zone '" + d_transaction_qname.toLogString() + "'");
×
305
  }
×
306

307
  shared_ptr<DNSRecordContent> drc(DNSRecordContent::make(rr.qtype.getCode(), QClass::IN, rr.content));
×
308
  string content = drc->getZoneRepresentation();
×
309

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

327
void Bind2Backend::getUpdatedPrimaries(vector<DomainInfo>& changedDomains, std::unordered_set<DNSName>& /* catalogs */, CatalogHashMap& /* catalogHashes */)
328
{
×
329
  vector<DomainInfo> consider;
×
330
  {
×
331
    auto state = s_state.read_lock();
×
332

333
    for (const auto& i : *state) {
×
334
      if (i.d_kind != DomainInfo::Primary && this->alsoNotify.empty() && i.d_also_notify.empty())
×
335
        continue;
×
336

337
      DomainInfo di;
×
338
      di.id = i.d_id;
×
339
      di.zone = i.d_name;
×
340
      di.last_check = i.d_lastcheck;
×
341
      di.notified_serial = i.d_lastnotified;
×
342
      di.backend = this;
×
343
      di.kind = DomainInfo::Primary;
×
344
      consider.push_back(std::move(di));
×
345
    }
×
346
  }
×
347

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

371
void Bind2Backend::getAllDomains(vector<DomainInfo>* domains, bool getSerial, bool /* include_disabled */)
372
{
70✔
373
  SOAData soadata;
70✔
374

375
  // prevent deadlock by using getSOA() later on
376
  {
70✔
377
    auto state = s_state.read_lock();
70✔
378
    domains->reserve(state->size());
70✔
379

380
    for (const auto& i : *state) {
70✔
381
      DomainInfo di;
5✔
382
      di.id = i.d_id;
5✔
383
      di.zone = i.d_name;
5✔
384
      di.last_check = i.d_lastcheck;
5✔
385
      di.kind = i.d_kind;
5✔
386
      di.primaries = i.d_primaries;
5✔
387
      di.backend = this;
5✔
388
      domains->push_back(std::move(di));
5✔
389
    };
5✔
390
  }
70✔
391

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

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

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

445
bool Bind2Backend::getDomainInfo(const ZoneName& domain, DomainInfo& info, bool getSerial)
446
{
560✔
447
  BB2DomainInfo bbd;
560✔
448
  if (!safeGetBBDomainInfo(domain, &bbd))
560✔
449
    return false;
555✔
450

451
  info.id = bbd.d_id;
5✔
452
  info.zone = domain;
5✔
453
  info.primaries = bbd.d_primaries;
5✔
454
  info.last_check = bbd.d_lastcheck;
5✔
455
  info.backend = this;
5✔
456
  info.kind = bbd.d_kind;
5✔
457
  info.serial = 0;
5✔
458
  if (getSerial) {
5✔
459
    try {
1✔
460
      SOAData sd;
1✔
461
      sd.serial = 0;
1✔
462

463
      getSOA(bbd.d_name, bbd.d_id, sd); // we might not *have* a SOA yet
1✔
464
      info.serial = sd.serial;
1✔
465
    }
1✔
466
    catch (...) {
1✔
467
    }
×
468
  }
1✔
469

470
  return true;
5✔
471
}
5✔
472

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

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

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

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

532
/** THIS IS AN INTERNAL FUNCTION! It does moadnsparser prio impedance matching
533
    Much of the complication is due to the efforts to benefit from std::string reference counting copy on write semantics */
534
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)
535
{
68✔
536
  Bind2DNSRecord bdr;
68✔
537
  bdr.qname = qname;
68✔
538

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

552
  //  bdr.qname.swap(bdr.qname);
553

554
  if (!records->empty() && bdr.qname == boost::prior(records->end())->qname)
68✔
555
    bdr.qname = boost::prior(records->end())->qname;
16✔
556

557
  bdr.qname = bdr.qname;
68✔
558
  bdr.qtype = qtype.getCode();
68✔
559
  bdr.content = content;
68✔
560
  bdr.nsec3hash = hashed;
68✔
561

562
  if (auth != nullptr) // Set auth on empty non-terminals
68✔
563
    bdr.auth = *auth;
6✔
564
  else
62✔
565
    bdr.auth = true;
62✔
566

567
  bdr.ttl = ttl;
68✔
568
  records->insert(std::move(bdr));
68✔
569
}
68✔
570

571
string Bind2Backend::DLReloadNowHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
572
{
×
573
  ostringstream ret;
×
574

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

596
string Bind2Backend::DLDomStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
597
{
4✔
598
  ostringstream ret;
4✔
599

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

618
  if (ret.str().empty())
4!
619
    ret << "no domains passed";
×
620

621
  return ret.str();
4✔
622
}
4✔
623

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

658
string Bind2Backend::DLDomExtendedStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
659
{
×
660
  ostringstream ret;
×
661

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

680
  if (ret.str().empty()) {
×
681
    ret << "no domains passed" << std::endl;
×
682
  }
×
683

684
  return ret.str();
×
685
}
×
686

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

698
string Bind2Backend::DLAddDomainHandler(const vector<string>& parts, Utility::pid_t /* ppid */)
699
{
×
700
  if (parts.size() < 3)
×
701
    return "ERROR: Domain name and zone filename are required";
×
702

703
  ZoneName domainname(parts[1]);
×
704
  const string& filename = parts[2];
×
705
  BB2DomainInfo bbd;
×
706
  if (safeGetBBDomainInfo(domainname, &bbd))
×
707
    return "Already loaded";
×
708

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

712
  struct stat buf;
×
713
  if (stat(filename.c_str(), &buf) != 0)
×
714
    return "Unable to load zone " + domainname.toLogString() + " from " + filename + ": " + strerror(errno);
×
715

716
  Bind2Backend bb2; // createdomainentry needs access to our configuration
×
717
  bbd = bb2.createDomainEntry(domainname, filename);
×
718
  bbd.d_filename = filename;
×
719
  bbd.d_checknow = true;
×
720
  bbd.d_loaded = true;
×
721
  bbd.d_lastcheck = 0;
×
722
  bbd.d_status = "parsing into memory";
×
723
  bbd.setCtime();
×
724

725
  safePutBBDomainInfo(bbd);
×
726

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

729
  g_log << Logger::Warning << "Zone " << domainname << " loaded" << endl;
×
730
  return "Loaded zone " + domainname.toLogString() + " from " + filename;
×
731
}
×
732

733
Bind2Backend::Bind2Backend(const string& suffix, bool loadZones)
734
{
1,855✔
735
  d_getAllDomainMetadataQuery_stmt = nullptr;
1,855✔
736
  d_getDomainMetadataQuery_stmt = nullptr;
1,855✔
737
  d_deleteDomainMetadataQuery_stmt = nullptr;
1,855✔
738
  d_insertDomainMetadataQuery_stmt = nullptr;
1,855✔
739
  d_getDomainKeysQuery_stmt = nullptr;
1,855✔
740
  d_deleteDomainKeyQuery_stmt = nullptr;
1,855✔
741
  d_insertDomainKeyQuery_stmt = nullptr;
1,855✔
742
  d_GetLastInsertedKeyIdQuery_stmt = nullptr;
1,855✔
743
  d_activateDomainKeyQuery_stmt = nullptr;
1,855✔
744
  d_deactivateDomainKeyQuery_stmt = nullptr;
1,855✔
745
  d_getTSIGKeyQuery_stmt = nullptr;
1,855✔
746
  d_setTSIGKeyQuery_stmt = nullptr;
1,855✔
747
  d_deleteTSIGKeyQuery_stmt = nullptr;
1,855✔
748
  d_getTSIGKeysQuery_stmt = nullptr;
1,855✔
749

750
  setArgPrefix("bind" + suffix);
1,855✔
751
  d_logprefix = "[bind" + suffix + "backend]";
1,855✔
752
  d_hybrid = mustDo("hybrid");
1,855✔
753
  if (d_hybrid && g_zoneCache.isEnabled()) {
1,855!
754
    throw PDNSException("bind-hybrid and the zone cache currently interoperate badly. Please disable the zone cache or stop using bind-hybrid");
×
755
  }
×
756

757
  d_transaction_id = UnknownDomainID;
1,855✔
758
  s_ignore_broken_records = mustDo("ignore-broken-records");
1,855✔
759
  d_upgradeContent = ::arg().mustDo("upgrade-unknown-types");
1,855✔
760

761
  if (!loadZones && d_hybrid)
1,855!
762
    return;
×
763

764
  std::lock_guard<std::mutex> l(s_startup_lock);
1,855✔
765

766
  setupDNSSEC();
1,855✔
767
  if (s_first == 0) {
1,855✔
768
    return;
1,476✔
769
  }
1,476✔
770

771
  if (loadZones) {
379✔
772
    loadConfig();
138✔
773
    s_first = 0;
138✔
774
  }
138✔
775

776
  DynListener::registerFunc("BIND-RELOAD-NOW", &DLReloadNowHandler, "bindbackend: reload domains", "<domains>");
379✔
777
  DynListener::registerFunc("BIND-DOMAIN-STATUS", &DLDomStatusHandler, "bindbackend: list status of all domains", "[domains]");
379✔
778
  DynListener::registerFunc("BIND-DOMAIN-EXTENDED-STATUS", &DLDomExtendedStatusHandler, "bindbackend: list the extended status of all domains", "[domains]");
379✔
779
  DynListener::registerFunc("BIND-LIST-REJECTS", &DLListRejectsHandler, "bindbackend: list rejected domains");
379✔
780
  DynListener::registerFunc("BIND-ADD-ZONE", &DLAddDomainHandler, "bindbackend: add zone", "<domain> <filename>");
379✔
781
}
379✔
782

783
Bind2Backend::~Bind2Backend()
784
{
1,819✔
785
  freeStatements();
1,819✔
786
} // deallocate statements
1,819✔
787

788
void Bind2Backend::rediscover(string* status)
789
{
×
790
  loadConfig(status);
×
791
}
×
792

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

801
void Bind2Backend::fixupOrderAndAuth(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
802
{
7✔
803
  bool skip;
7✔
804
  DNSName shorter;
7✔
805
  set<DNSName> nssets, dssets;
7✔
806

807
  for (const auto& bdr : *records) {
62✔
808
    if (!bdr.qname.isRoot() && bdr.qtype == QType::NS)
62✔
809
      nssets.insert(bdr.qname);
2✔
810
    else if (bdr.qtype == QType::DS)
60!
811
      dssets.insert(bdr.qname);
×
812
  }
62✔
813

814
  for (auto iter = records->begin(); iter != records->end(); iter++) {
69✔
815
    skip = false;
62✔
816
    shorter = iter->qname;
62✔
817

818
    if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
62!
819
      do {
57✔
820
        if (nssets.count(shorter) != 0u) {
57!
821
          skip = true;
×
822
          break;
×
823
        }
×
824
      } while (shorter.chopOff() && !iter->qname.isRoot());
57!
825
    }
39✔
826

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

829
    if (!skip && nsec3zone && iter->qtype != QType::RRSIG && (iter->auth || (iter->qtype == QType::NS && (ns3pr.d_flags == 0u)) || (dssets.count(iter->qname) != 0u))) {
62!
830
      Bind2DNSRecord bdr = *iter;
×
831
      bdr.nsec3hash = toBase32Hex(hashQNameWithSalt(ns3pr, bdr.qname + zoneName.operator const DNSName&()));
×
832
      records->replace(iter, bdr);
×
833
    }
×
834

835
    // cerr<<iter->qname<<"\t"<<QType(iter->qtype).toString()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
836
  }
62✔
837
}
7✔
838

839
void Bind2Backend::doEmptyNonTerminals(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
840
{
7✔
841
  bool auth = false;
7✔
842
  DNSName shorter;
7✔
843
  std::unordered_set<DNSName> qnames;
7✔
844
  std::unordered_map<DNSName, bool> nonterm;
7✔
845

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

848
  for (const auto& bdr : *records)
7✔
849
    qnames.insert(bdr.qname);
62✔
850

851
  for (const auto& bdr : *records) {
62✔
852

853
    if (!bdr.auth && bdr.qtype == QType::NS)
62✔
854
      auth = (!nsec3zone || (ns3pr.d_flags == 0u));
2!
855
    else
60✔
856
      auth = bdr.auth;
60✔
857

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

866
        if (nonterm.count(shorter) == 0u) {
17✔
867
          nonterm.emplace(shorter, auth);
6✔
868
          --maxent;
6✔
869
        }
6✔
870
        else if (auth)
11!
871
          nonterm[shorter] = true;
11✔
872
      }
17✔
873
    }
57✔
874
  }
62✔
875

876
  DNSResourceRecord rr;
7✔
877
  rr.qtype = "#0";
7✔
878
  rr.content = "";
7✔
879
  rr.ttl = 0;
7✔
880
  for (auto& nt : nonterm) {
7✔
881
    string hashed;
6✔
882
    rr.qname = nt.first + zoneName.operator const DNSName&();
6✔
883
    if (nsec3zone && nt.second)
6!
884
      hashed = toBase32Hex(hashQNameWithSalt(ns3pr, rr.qname));
×
885
    insertRecord(records, zoneName, rr.qname, rr.qtype, rr.content, rr.ttl, hashed, &nt.second);
6✔
886

887
    // cerr<<rr.qname<<"\t"<<rr.qtype.toString()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
888
  }
6✔
889
}
7✔
890

891
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
892
{
138✔
893
  static domainid_t domain_id = 1;
138✔
894

895
  if (!getArg("config").empty()) {
138!
896
    BindParser BP;
138✔
897
    try {
138✔
898
      BP.parse(getArg("config"));
138✔
899
    }
138✔
900
    catch (PDNSException& ae) {
138✔
901
      g_log << Logger::Error << "Error parsing bind configuration: " << ae.reason << endl;
×
902
      throw;
×
903
    }
×
904

905
    vector<BindDomainInfo> domains = BP.getDomains();
138✔
906
    this->alsoNotify = BP.getAlsoNotify();
138✔
907

908
    s_binddirectory = BP.getDirectory();
138✔
909
    //    ZP.setDirectory(d_binddirectory);
910

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

913
    set<ZoneName> oldnames;
138✔
914
    set<ZoneName> newnames;
138✔
915
    {
138✔
916
      auto state = s_state.read_lock();
138✔
917
      for (const BB2DomainInfo& bbd : *state) {
138!
918
        oldnames.insert(bbd.d_name);
×
919
      }
×
920
    }
138✔
921
    int rejected = 0;
138✔
922
    int newdomains = 0;
138✔
923

924
    struct stat st;
138✔
925

926
    for (auto& domain : domains) {
138✔
927
      if (stat(domain.filename.c_str(), &st) == 0) {
7!
928
        domain.d_dev = st.st_dev;
7✔
929
        domain.d_ino = st.st_ino;
7✔
930
      }
7✔
931
    }
7✔
932

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

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

950
      BB2DomainInfo bbd;
7✔
951
      bool isNew = false;
7✔
952

953
      if (!safeGetBBDomainInfo(domain.name, &bbd)) {
7!
954
        isNew = true;
7✔
955
        bbd.d_id = domain_id++;
7✔
956
        bbd.setCheckInterval(getArgAsNum("check-interval"));
7✔
957
        bbd.d_lastnotified = 0;
7✔
958
        bbd.d_loaded = false;
7✔
959
      }
7✔
960

961
      // overwrite what we knew about the domain
962
      bbd.d_name = domain.name;
7✔
963
      bool filenameChanged = (bbd.d_filename != domain.filename);
7✔
964
      bool addressesChanged = (bbd.d_primaries != domain.primaries || bbd.d_also_notify != domain.alsoNotify);
7!
965
      bbd.d_filename = domain.filename;
7✔
966
      bbd.d_primaries = domain.primaries;
7✔
967
      bbd.d_also_notify = domain.alsoNotify;
7✔
968

969
      DomainInfo::DomainKind kind = DomainInfo::Native;
7✔
970
      if (domain.type == "primary" || domain.type == "master") {
7!
971
        kind = DomainInfo::Primary;
7✔
972
      }
7✔
973
      if (domain.type == "secondary" || domain.type == "slave") {
7!
974
        kind = DomainInfo::Secondary;
×
975
      }
×
976

977
      bool kindChanged = (bbd.d_kind != kind);
7✔
978
      bbd.d_kind = kind;
7✔
979

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

984
        try {
7✔
985
          parseZoneFile(&bbd);
7✔
986
        }
7✔
987
        catch (PDNSException& ae) {
7✔
988
          ostringstream msg;
×
989
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.reason;
×
990

991
          if (status != nullptr)
×
992
            *status += msg.str();
×
993
          bbd.d_status = msg.str();
×
994

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

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

1015
          if (status != nullptr)
×
1016
            *status += msg.str();
×
1017
          bbd.d_status = msg.str();
×
1018

1019
          g_log << Logger::Warning << d_logprefix << msg.str() << endl;
×
1020
          rejected++;
×
1021
        }
×
1022
        safePutBBDomainInfo(bbd);
7✔
1023
      }
7✔
1024
      else if (addressesChanged || kindChanged) {
×
1025
        safePutBBDomainInfo(bbd);
×
1026
      }
×
1027
    }
7✔
1028
    vector<ZoneName> diff;
138✔
1029

1030
    set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
138✔
1031
    unsigned int remdomains = diff.size();
138✔
1032

1033
    for (const ZoneName& name : diff) {
138!
1034
      safeRemoveBBDomainInfo(name);
×
1035
    }
×
1036

1037
    // count number of entirely new domains
1038
    diff.clear();
138✔
1039
    set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
138✔
1040
    newdomains = diff.size();
138✔
1041

1042
    ostringstream msg;
138✔
1043
    msg << " Done parsing domains, " << rejected << " rejected, " << newdomains << " new, " << remdomains << " removed";
138✔
1044
    if (status != nullptr)
138!
1045
      *status = msg.str();
×
1046

1047
    g_log << Logger::Error << d_logprefix << msg.str() << endl;
138✔
1048
  }
138✔
1049
}
138✔
1050

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

1088
bool Bind2Backend::findBeforeAndAfterUnhashed(std::shared_ptr<const recordstorage_t>& records, const DNSName& qname, DNSName& /* unhashed */, DNSName& before, DNSName& after)
1089
{
1✔
1090
  // for(const auto& record: *records)
1091
  //   cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
1092

1093
  recordstorage_t::const_iterator iterBefore, iterAfter;
1✔
1094

1095
  iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
1✔
1096

1097
  if (iterBefore != records->begin())
1!
1098
    --iterBefore;
1✔
1099
  while ((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
1!
1100
    --iterBefore;
×
1101
  before = iterBefore->qname;
1✔
1102

1103
  if (iterAfter == records->end()) {
1!
1104
    iterAfter = records->begin();
1✔
1105
  }
1✔
1106
  else {
×
1107
    while ((!iterAfter->auth && iterAfter->qtype != QType::NS) || !iterAfter->qtype) {
×
1108
      ++iterAfter;
×
1109
      if (iterAfter == records->end()) {
×
1110
        iterAfter = records->begin();
×
1111
        break;
×
1112
      }
×
1113
    }
×
1114
  }
×
1115
  after = iterAfter->qname;
1✔
1116

1117
  return true;
1✔
1118
}
1✔
1119

1120
// NOLINTNEXTLINE(readability-identifier-length)
1121
bool Bind2Backend::getBeforeAndAfterNamesAbsolute(domainid_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
1122
{
1✔
1123
  BB2DomainInfo bbd;
1✔
1124
  if (!safeGetBBDomainInfo(id, &bbd))
1!
1125
    return false;
×
1126

1127
  shared_ptr<const recordstorage_t> records = bbd.d_records.get();
1✔
1128
  if (!bbd.d_nsec3zone) {
1!
1129
    return findBeforeAndAfterUnhashed(records, qname, unhashed, before, after);
1✔
1130
  }
1✔
1131
  else {
×
1132
    const auto& hashindex = boost::multi_index::get<NSEC3Tag>(*records);
×
1133

1134
    // for(auto iter = first; iter != hashindex.end(); iter++)
1135
    //  cerr<<iter->nsec3hash<<endl;
1136

1137
    auto first = hashindex.upper_bound("");
×
1138
    auto iter = hashindex.upper_bound(qname.toStringNoDot());
×
1139

1140
    if (iter == hashindex.end()) {
×
1141
      --iter;
×
1142
      before = DNSName(iter->nsec3hash);
×
1143
      after = DNSName(first->nsec3hash);
×
1144
    }
×
1145
    else {
×
1146
      after = DNSName(iter->nsec3hash);
×
1147
      if (iter != first)
×
1148
        --iter;
×
1149
      else
×
1150
        iter = --hashindex.end();
×
1151
      before = DNSName(iter->nsec3hash);
×
1152
    }
×
1153
    unhashed = iter->qname + bbd.d_name.operator const DNSName&();
×
1154

1155
    return true;
×
1156
  }
×
1157
}
1✔
1158

1159
void Bind2Backend::lookup(const QType& qtype, const DNSName& qname, domainid_t zoneId, DNSPacket* /* pkt_p */)
1160
{
57✔
1161
  d_handle.reset();
57✔
1162

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

1165
  bool found = false;
57✔
1166
  ZoneName domain;
57✔
1167
  BB2DomainInfo bbd;
57✔
1168

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

1172
  if (zoneId != UnknownDomainID) {
57✔
1173
    if ((found = (safeGetBBDomainInfo(zoneId, &bbd) && qname.isPartOf(bbd.d_name)))) {
24!
1174
      domain = std::move(bbd.d_name);
24✔
1175
    }
24✔
1176
  }
24✔
1177
  else {
33✔
1178
    domain = ZoneName(qname);
33✔
1179
    do {
36✔
1180
      found = safeGetBBDomainInfo(domain, &bbd);
36✔
1181
    } while (!found && qtype != QType::SOA && domain.chopOff());
36✔
1182
  }
33✔
1183

1184
  if (!found) {
57✔
1185
    if (mustlog)
24!
1186
      g_log << Logger::Warning << "Found no authoritative zone for '" << qname << "' and/or id " << zoneId << endl;
×
1187
    d_handle.d_list = false;
24✔
1188
    return;
24✔
1189
  }
24✔
1190

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

1194
  d_handle.id = bbd.d_id;
33✔
1195
  d_handle.qname = qname.makeRelative(domain); // strip domain name
33✔
1196
  d_handle.qtype = qtype;
33✔
1197
  d_handle.domain = std::move(domain);
33✔
1198

1199
  if (!bbd.current()) {
33!
1200
    g_log << Logger::Warning << "Zone '" << d_handle.domain << "' (" << bbd.d_filename << ") needs reloading" << endl;
×
1201
    queueReloadAndStore(bbd.d_id);
×
1202
    if (!safeGetBBDomainInfo(d_handle.domain, &bbd))
×
1203
      throw DBException("Zone '" + bbd.d_name.toLogString() + "' (" + bbd.d_filename + ") gone after reload"); // if we don't throw here, we crash for some reason
×
1204
  }
×
1205

1206
  if (!bbd.d_loaded) {
33!
1207
    d_handle.reset();
×
1208
    throw DBException("Zone for '" + d_handle.domain.toLogString() + "' in '" + bbd.d_filename + "' not loaded (file missing, corrupt or primary dead)"); // fsck
×
1209
  }
×
1210

1211
  d_handle.d_records = bbd.d_records.get();
33✔
1212

1213
  if (d_handle.d_records->empty())
33!
1214
    DLOG(g_log << "Query with no results" << endl);
×
1215

1216
  d_handle.mustlog = mustlog;
33✔
1217

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

1221
  d_handle.d_list = false;
33✔
1222
  d_handle.d_iter = range.first;
33✔
1223
  d_handle.d_end_iter = range.second;
33✔
1224
}
33✔
1225

1226
Bind2Backend::handle::handle()
1227
{
1,855✔
1228
  mustlog = false;
1,855✔
1229
}
1,855✔
1230

1231
bool Bind2Backend::get(DNSResourceRecord& r)
1232
{
139✔
1233
  if (!d_handle.d_records) {
139✔
1234
    if (d_handle.mustlog)
24!
1235
      g_log << Logger::Warning << "There were no answers" << endl;
×
1236
    return false;
24✔
1237
  }
24✔
1238

1239
  if (!d_handle.get(r)) {
115✔
1240
    if (d_handle.mustlog)
37!
1241
      g_log << Logger::Warning << "End of answers" << endl;
×
1242

1243
    d_handle.reset();
37✔
1244

1245
    return false;
37✔
1246
  }
37✔
1247
  if (d_handle.mustlog)
78!
1248
    g_log << Logger::Warning << "Returning: '" << r.qtype.toString() << "' of '" << r.qname << "', content: '" << r.content << "'" << endl;
×
1249
  return true;
78✔
1250
}
115✔
1251

1252
bool Bind2Backend::handle::get(DNSResourceRecord& r)
1253
{
115✔
1254
  if (d_list)
115✔
1255
    return get_list(r);
16✔
1256
  else
99✔
1257
    return get_normal(r);
99✔
1258
}
115✔
1259

1260
void Bind2Backend::handle::reset()
1261
{
98✔
1262
  d_records.reset();
98✔
1263
  qname.clear();
98✔
1264
  mustlog = false;
98✔
1265
}
98✔
1266

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

1272
  if (d_iter == d_end_iter) {
99✔
1273
    return false;
33✔
1274
  }
33✔
1275

1276
  while (d_iter != d_end_iter && !(qtype.getCode() == QType::ANY || (d_iter)->qtype == qtype.getCode())) {
86!
1277
    DLOG(g_log << Logger::Warning << "Skipped " << qname << "/" << QType(d_iter->qtype).toString() << ": '" << d_iter->content << "'" << endl);
20✔
1278
    d_iter++;
20✔
1279
  }
20✔
1280
  if (d_iter == d_end_iter) {
66!
1281
    return false;
×
1282
  }
×
1283
  DLOG(g_log << "Bind2Backend get() returning a rr with a " << QType(d_iter->qtype).getCode() << endl);
66✔
1284

1285
  const DNSName& domainName(domain);
66✔
1286
  r.qname = qname.empty() ? domainName : (qname + domainName);
66!
1287
  r.domain_id = id;
66✔
1288
  r.content = (d_iter)->content;
66✔
1289
  //  r.domain_id=(d_iter)->domain_id;
1290
  r.qtype = (d_iter)->qtype;
66✔
1291
  r.ttl = (d_iter)->ttl;
66✔
1292

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

1297
  d_iter++;
66✔
1298

1299
  return true;
66✔
1300
}
66✔
1301

1302
bool Bind2Backend::list(const ZoneName& /* target */, domainid_t domainId, bool /* include_disabled */)
1303
{
4✔
1304
  BB2DomainInfo bbd;
4✔
1305

1306
  if (!safeGetBBDomainInfo(domainId, &bbd)) {
4!
1307
    return false;
×
1308
  }
×
1309

1310
  d_handle.reset();
4✔
1311
  DLOG(g_log << "Bind2Backend constructing handle for list of " << domainId << endl);
4✔
1312

1313
  if (!bbd.d_loaded) {
4!
1314
    throw PDNSException("zone was not loaded, perhaps because of: " + bbd.d_status);
×
1315
  }
×
1316

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

1321
  d_handle.id = domainId;
4✔
1322
  d_handle.domain = bbd.d_name;
4✔
1323
  d_handle.d_list = true;
4✔
1324
  return true;
4✔
1325
}
4✔
1326

1327
bool Bind2Backend::handle::get_list(DNSResourceRecord& r)
1328
{
16✔
1329
  if (d_qname_iter != d_qname_end) {
16✔
1330
    const DNSName& domainName(domain);
12✔
1331
    r.qname = d_qname_iter->qname.empty() ? domainName : (d_qname_iter->qname + domainName);
12!
1332
    r.domain_id = id;
12✔
1333
    r.content = (d_qname_iter)->content;
12✔
1334
    r.qtype = (d_qname_iter)->qtype;
12✔
1335
    r.ttl = (d_qname_iter)->ttl;
12✔
1336
    r.auth = d_qname_iter->auth;
12✔
1337
    d_qname_iter++;
12✔
1338
    return true;
12✔
1339
  }
12✔
1340
  return false;
4✔
1341
}
16✔
1342

1343
bool Bind2Backend::autoPrimariesList(std::vector<AutoPrimary>& primaries)
1344
{
×
1345
  if (getArg("autoprimary-config").empty())
×
1346
    return false;
×
1347

1348
  ifstream c_if(getArg("autoprimaries"), std::ios::in);
×
1349
  if (!c_if) {
×
1350
    g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl;
×
1351
    return false;
×
1352
  }
×
1353

1354
  string line, sip, saccount;
×
1355
  while (getline(c_if, line)) {
×
1356
    std::istringstream ii(line);
×
1357
    ii >> sip;
×
1358
    if (!sip.empty()) {
×
1359
      ii >> saccount;
×
1360
      primaries.emplace_back(sip, "", saccount);
×
1361
    }
×
1362
  }
×
1363

1364
  c_if.close();
×
1365
  return true;
×
1366
}
×
1367

1368
bool Bind2Backend::autoPrimaryBackend(const string& ipAddress, const ZoneName& /* domain */, const vector<DNSResourceRecord>& /* nsset */, string* /* nameserver */, string* account, DNSBackend** backend)
1369
{
×
1370
  // Check whether we have a configfile available.
1371
  if (getArg("autoprimary-config").empty())
×
1372
    return false;
×
1373

1374
  ifstream c_if(getArg("autoprimaries").c_str(), std::ios::in); // this was nocreate?
×
1375
  if (!c_if) {
×
1376
    g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl;
×
1377
    return false;
×
1378
  }
×
1379

1380
  // Format:
1381
  // <ip> <accountname>
1382
  string line, sip, saccount;
×
1383
  while (getline(c_if, line)) {
×
1384
    std::istringstream ii(line);
×
1385
    ii >> sip;
×
1386
    if (sip == ipAddress) {
×
1387
      ii >> saccount;
×
1388
      break;
×
1389
    }
×
1390
  }
×
1391
  c_if.close();
×
1392

1393
  if (sip != ipAddress) { // ip not found in authorization list - reject
×
1394
    return false;
×
1395
  }
×
1396

1397
  // ip authorized as autoprimary - accept
1398
  *backend = this;
×
1399
  if (saccount.length() > 0)
×
1400
    *account = saccount.c_str();
×
1401

1402
  return true;
×
1403
}
×
1404

1405
BB2DomainInfo Bind2Backend::createDomainEntry(const ZoneName& domain, const string& filename)
1406
{
×
1407
  domainid_t newid = 1;
×
1408
  { // Find a free zone id nr.
×
1409
    auto state = s_state.read_lock();
×
1410
    if (!state->empty()) {
×
1411
      // older (1.53) versions of boost have an expression for s_state.rbegin()
1412
      // that is ambiguous in C++17. So construct it explicitly
1413
      newid = boost::make_reverse_iterator(state->end())->d_id + 1;
×
1414
    }
×
1415
  }
×
1416

1417
  BB2DomainInfo bbd;
×
1418
  bbd.d_kind = DomainInfo::Native;
×
1419
  bbd.d_id = newid;
×
1420
  bbd.d_records = std::make_shared<recordstorage_t>();
×
1421
  bbd.d_name = domain;
×
1422
  bbd.setCheckInterval(getArgAsNum("check-interval"));
×
1423
  bbd.d_filename = filename;
×
1424

1425
  return bbd;
×
1426
}
×
1427

1428
bool Bind2Backend::createSecondaryDomain(const string& ipAddress, const ZoneName& domain, const string& /* nameserver */, const string& account)
1429
{
×
1430
  string filename = getArg("autoprimary-destdir") + '/' + domain.toStringNoDot();
×
1431

1432
  g_log << Logger::Warning << d_logprefix
×
1433
        << " Writing bind config zone statement for superslave zone '" << domain
×
1434
        << "' from autoprimary " << ipAddress << endl;
×
1435

1436
  {
×
1437
    std::lock_guard<std::mutex> l2(s_autosecondary_config_lock);
×
1438

1439
    ofstream c_of(getArg("autoprimary-config").c_str(), std::ios::app);
×
1440
    if (!c_of) {
×
1441
      g_log << Logger::Error << "Unable to open autoprimary configfile for append: " << stringerror() << endl;
×
1442
      throw DBException("Unable to open autoprimary configfile for append: " + stringerror());
×
1443
    }
×
1444

1445
    c_of << endl;
×
1446
    c_of << "# AutoSecondary zone '" << domain.toString() << "' (added: " << nowTime() << ") (account: " << account << ')' << endl;
×
1447
    c_of << "zone \"" << domain.toStringNoDot() << "\" {" << endl;
×
1448
    c_of << "\ttype secondary;" << endl;
×
1449
    c_of << "\tfile \"" << filename << "\";" << endl;
×
1450
    c_of << "\tprimaries { " << ipAddress << "; };" << endl;
×
1451
    c_of << "};" << endl;
×
1452
    c_of.close();
×
1453
  }
×
1454

1455
  BB2DomainInfo bbd = createDomainEntry(domain, filename);
×
1456
  bbd.d_kind = DomainInfo::Secondary;
×
1457
  bbd.d_primaries.emplace_back(ComboAddress(ipAddress, 53));
×
1458
  bbd.setCtime();
×
1459
  safePutBBDomainInfo(bbd);
×
1460

1461
  return true;
×
1462
}
×
1463

1464
bool Bind2Backend::searchRecords(const string& pattern, size_t maxResults, vector<DNSResourceRecord>& result)
1465
{
18✔
1466
  SimpleMatch sm(pattern, true);
18✔
1467
  static bool mustlog = ::arg().mustDo("query-logging");
18✔
1468
  if (mustlog)
18!
1469
    g_log << Logger::Warning << "Search for pattern '" << pattern << "'" << endl;
×
1470

1471
  {
18✔
1472
    auto state = s_state.read_lock();
18✔
1473

1474
    for (const auto& i : *state) {
18!
1475
      BB2DomainInfo h;
×
1476
      if (!safeGetBBDomainInfo(i.d_id, &h)) {
×
1477
        continue;
×
1478
      }
×
1479

1480
      if (!h.d_loaded) {
×
1481
        continue;
×
1482
      }
×
1483

1484
      shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
×
1485

1486
      for (recordstorage_t::const_iterator ri = rhandle->begin(); result.size() < maxResults && ri != rhandle->end(); ri++) {
×
1487
        const DNSName& domainName(i.d_name);
×
1488
        DNSName name = ri->qname.empty() ? domainName : (ri->qname + domainName);
×
1489
        if (sm.match(name) || sm.match(ri->content)) {
×
1490
          DNSResourceRecord r;
×
1491
          r.qname = std::move(name);
×
1492
          r.domain_id = i.d_id;
×
1493
          r.content = ri->content;
×
1494
          r.qtype = ri->qtype;
×
1495
          r.ttl = ri->ttl;
×
1496
          r.auth = ri->auth;
×
1497
          result.push_back(std::move(r));
×
1498
        }
×
1499
      }
×
1500
    }
×
1501
  }
18✔
1502

1503
  return true;
18✔
1504
}
18✔
1505

1506
class Bind2Factory : public BackendFactory
1507
{
1508
public:
1509
  Bind2Factory() :
1510
    BackendFactory("bind") {}
5,046✔
1511

1512
  void declareArguments(const string& suffix = "") override
1513
  {
283✔
1514
    declare(suffix, "ignore-broken-records", "Ignore records that are out-of-bound for the zone.", "no");
283✔
1515
    declare(suffix, "config", "Location of named.conf", "");
283✔
1516
    declare(suffix, "check-interval", "Interval for zonefile changes", "0");
283✔
1517
    declare(suffix, "autoprimary-config", "Location of (part of) named.conf where pdns can write zone-statements to", "");
283✔
1518
    declare(suffix, "autoprimaries", "List of IP-addresses of autoprimaries", "");
283✔
1519
    declare(suffix, "autoprimary-destdir", "Destination directory for newly added secondary zones", ::arg()["config-dir"]);
283✔
1520
    declare(suffix, "dnssec-db", "Filename to store & access our DNSSEC metadatabase, empty for none", "");
283✔
1521
    declare(suffix, "dnssec-db-journal-mode", "SQLite3 journal mode", "WAL");
283✔
1522
    declare(suffix, "hybrid", "Store DNSSEC metadata in other backend", "no");
283✔
1523
  }
283✔
1524

1525
  DNSBackend* make(const string& suffix = "") override
1526
  {
1,602✔
1527
    assertEmptySuffix(suffix);
1,602✔
1528
    return new Bind2Backend(suffix);
1,602✔
1529
  }
1,602✔
1530

1531
  DNSBackend* makeMetadataOnly(const string& suffix = "") override
1532
  {
253✔
1533
    assertEmptySuffix(suffix);
253✔
1534
    return new Bind2Backend(suffix, false);
253✔
1535
  }
253✔
1536

1537
private:
1538
  void assertEmptySuffix(const string& suffix)
1539
  {
1,855✔
1540
    if (!suffix.empty())
1,855!
1541
      throw PDNSException("launch= suffixes are not supported on the bindbackend");
×
1542
  }
1,855✔
1543
};
1544

1545
//! Magic class that is activated when the dynamic library is loaded
1546
class Bind2Loader
1547
{
1548
public:
1549
  Bind2Loader()
1550
  {
5,046✔
1551
    BackendMakers().report(std::make_unique<Bind2Factory>());
5,046✔
1552
    g_log << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
5,046✔
1553
#ifndef REPRODUCIBLE
5,046✔
1554
          << " (" __DATE__ " " __TIME__ ")"
5,046✔
1555
#endif
5,046✔
1556
#ifdef HAVE_SQLITE3
5,046✔
1557
          << " (with bind-dnssec-db support)"
5,046✔
1558
#endif
5,046✔
1559
          << " reporting" << endl;
5,046✔
1560
  }
5,046✔
1561
};
1562
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