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

PowerDNS / pdns / 25191990251

29 Apr 2026 04:54PM UTC coverage: 57.956% (-13.1%) from 71.038%
25191990251

push

github

web-flow
Merge pull request #17257 from omoerbeek/dnsdist-test-signedness

dnsdist: fix a few signed vs unsigned compare warnings in tests

65689 of 176110 branches covered (37.3%)

Branch coverage included in aggregate %.

140865 of 180289 relevant lines covered (78.13%)

5404297.89 hits per line

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

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

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

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

104
  if (!d_checkinterval)
×
105
    return true;
×
106

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

272
  d_transaction_id = UnknownDomainID;
×
273

274
  return true;
275
}
×
276

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

×
287
  return true;
×
288
}
×
289

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

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

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

×
319
  return true;
×
320
}
321

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

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

×
340
bool Bind2Backend::feedRecord(const DNSResourceRecord& rr, const DNSName& /* ordername */, bool /* ordernameIsNSEC3 */)
×
341
{
342
  if (d_transaction_id == UnknownDomainID) {
×
343
    throw DBException("Bind2Backend::feedRecord() called outside of transaction");
×
344
  }
×
345

×
346
  string qname;
×
347
  if (d_transaction_qname.empty()) {
×
348
    qname = rr.qname.toString();
349
  }
350
  else if (rr.qname.isPartOf(d_transaction_qname)) {
×
351
    if (rr.qname == d_transaction_qname.operator const DNSName&()) {
×
352
      qname = "@";
×
353
    }
×
354
    else {
355
      DNSName relName = rr.qname.makeRelative(d_transaction_qname);
×
356
      qname = relName.toStringNoDot();
×
357
    }
×
358
  }
×
359
  else {
×
360
    throw DBException("out-of-zone data '" + rr.qname.toLogString() + "' during AXFR of zone '" + d_transaction_qname.toLogString() + "'");
×
361
  }
×
362

×
363
  shared_ptr<DNSRecordContent> drc(DNSRecordContent::make(rr.qtype.getCode(), QClass::IN, rr.content));
×
364
  string content = drc->getZoneRepresentation();
365

366
  // SOA needs stripping too! XXX FIXME - also, this should not be here I think
48✔
367
  switch (rr.qtype.getCode()) {
48✔
368
  case QType::MX:
369
  case QType::SRV:
370
  case QType::CNAME:
48✔
371
  case QType::DNAME:
48✔
372
  case QType::NS:
48✔
373
    stripDomainSuffix(&content, d_transaction_qname);
374
    [[fallthrough]];
48!
375
  default:
376
    if (d_of && *d_of) {
×
377
      *d_of << qname << "\t" << rr.ttl << "\t" << rr.qtype.toString() << "\t" << content << endl;
×
378
    }
×
379
  }
×
380
  return true;
×
381
}
×
382

×
383
void Bind2Backend::getUpdatedPrimaries(vector<DomainInfo>& changedDomains, std::unordered_set<DNSName>& /* catalogs */, CatalogHashMap& /* catalogHashes */)
384
{
48!
385
  vector<DomainInfo> consider;
×
386
  {
48✔
387
    auto state = s_state.read_lock();
996✔
388

389
    for (const auto& i : *state) {
996!
390
      if (i.d_kind != DomainInfo::Primary && this->alsoNotify.empty() && i.d_also_notify.empty())
996✔
391
        continue;
392

393
      DomainInfo di;
×
394
      di.id = i.d_id;
×
395
      di.zone = i.d_name;
×
396
      di.last_check = i.d_lastcheck;
×
397
      di.notified_serial = i.d_lastnotified;
398
      di.backend = this;
×
399
      di.kind = DomainInfo::Primary;
31!
400
      consider.push_back(std::move(di));
48✔
401
    }
402
  }
403

×
404
  SOAData soadata;
×
405
  for (DomainInfo& di : consider) {
×
406
    soadata.serial = 0;
×
407
    try {
×
408
      this->getSOA(di.zone, di.id, soadata); // we might not *have* a SOA yet, but this might trigger a load of it
×
409
    }
×
410
    catch (...) {
×
411
      continue;
×
412
    }
413
    if (di.notified_serial != soadata.serial) {
×
414
      BB2DomainInfo bbd;
×
415
      if (safeGetBBDomainInfo(di.id, &bbd)) {
×
416
        bbd.d_lastnotified = soadata.serial;
×
417
        safePutBBDomainInfo(bbd);
×
418
      }
×
419
      if (di.notified_serial) { // don't do notification storm on startup
×
420
        di.serial = soadata.serial;
×
421
        changedDomains.push_back(std::move(di));
×
422
      }
×
423
    }
×
424
  }
×
425
}
×
426

×
427
void Bind2Backend::getAllDomains(vector<DomainInfo>* domains, bool getSerial, bool /* include_disabled */)
×
428
{
×
429
  SOAData soadata;
×
430

×
431
  // prevent deadlock by using getSOA() later on
×
432
  {
×
433
    auto state = s_state.read_lock();
434
    domains->reserve(state->size());
×
435

436
    for (const auto& i : *state) {
437
      DomainInfo di;
73✔
438
      di.id = i.d_id;
73✔
439
      di.zone = i.d_name;
440
      di.last_check = i.d_lastcheck;
431✔
441
      di.kind = i.d_kind;
504✔
442
      di.primaries = i.d_primaries;
504!
443
      di.backend = this;
504✔
444
      domains->push_back(std::move(di));
445
    };
73!
446
  }
×
447

×
448
  if (getSerial) {
×
449
    for (DomainInfo& di : *domains) {
×
450
      // do not corrupt di if domain supplied by another backend.
×
451
      if (di.backend != this)
×
452
        continue;
×
453
      try {
×
454
        this->getSOA(di.zone, di.id, soadata);
×
455
      }
73✔
456
      catch (...) {
457
        continue;
73✔
458
      }
1,362✔
459
      di.serial = soadata.serial;
460
    }
1,362!
461
  }
1,362✔
462
}
×
463

464
void Bind2Backend::getUnfreshSecondaryInfos(vector<DomainInfo>* unfreshDomains)
×
465
{
×
466
  vector<DomainInfo> domains;
467
  {
468
    auto state = s_state.read_lock();
3✔
469
    domains.reserve(state->size());
470
    for (const auto& i : *state) {
45!
471
      if (i.d_kind != DomainInfo::Secondary)
73✔
472
        continue;
473
      DomainInfo sd;
474
      sd.id = i.d_id;
3✔
475
      sd.zone = i.d_name;
3!
476
      sd.primaries = i.d_primaries;
×
477
      sd.last_check = i.d_lastcheck;
×
478
      sd.backend = this;
×
479
      sd.kind = DomainInfo::Secondary;
×
480
      domains.push_back(std::move(sd));
3!
481
    }
3!
482
  }
×
483
  unfreshDomains->reserve(domains.size());
×
484

×
485
  for (DomainInfo& sd : domains) {
×
486
    SOAData soadata;
×
487
    soadata.refresh = 0;
×
488
    soadata.serial = 0;
×
489
    try {
3✔
490
      getSOA(sd.zone, sd.id, soadata); // we might not *have* a SOA yet
491
    }
492
    catch (...) {
493
    }
494
    sd.serial = soadata.serial;
×
495
    if (sd.last_check + soadata.refresh < time(nullptr))
×
496
      unfreshDomains->push_back(std::move(sd));
×
497
  }
×
498
}
×
499

×
500
bool Bind2Backend::getDomainInfo(const ZoneName& domain, DomainInfo& info, bool getSerial)
×
501
{
×
502
  BB2DomainInfo bbd;
503
  if (!safeGetBBDomainInfo(domain, &bbd))
×
504
    return false;
505

×
506
  info.id = bbd.d_id;
×
507
  info.zone = domain;
×
508
  info.primaries = bbd.d_primaries;
×
509
  info.last_check = bbd.d_lastcheck;
×
510
  info.backend = this;
×
511
  info.kind = bbd.d_kind;
585✔
512
  info.serial = 0;
585✔
513
  if (getSerial) {
585!
514
    try {
585✔
515
      SOAData sd;
516
      sd.serial = 0;
×
517

×
518
      getSOA(bbd.d_name, bbd.d_id, sd); // we might not *have* a SOA yet
×
519
      info.serial = sd.serial;
×
520
    }
×
521
    catch (...) {
×
522
    }
×
523
  }
×
524

×
525
  return true;
526
}
527

528
void Bind2Backend::alsoNotifies(const ZoneName& domain, set<string>* ips)
529
{
×
530
  // combine global list with local list
×
531
  for (const auto& i : this->alsoNotify) {
×
532
    (*ips).insert(i);
533
  }
×
534
  // check metadata too if available
535
  vector<string> meta;
×
536
  if (getDomainMetadata(domain, "ALSO-NOTIFY", meta)) {
×
537
    for (const auto& str : meta) {
538
      (*ips).insert(str);
539
    }
4!
540
  }
541
  auto state = s_state.read_lock();
4!
542
  for (const auto& i : *state) {
×
543
    if (i.d_name == domain) {
×
544
      for (const auto& it : i.d_also_notify) {
545
        (*ips).insert(it);
4✔
546
      }
4!
547
      return;
×
548
    }
549
  }
×
550
}
×
551

4✔
552
// only parses, does NOT add to s_state!
4!
553
void Bind2Backend::parseZoneFile(BB2DomainInfo* bbd)
×
554
{
×
555
  NSEC3PARAMRecordContent ns3pr;
×
556
  bool nsec3zone = false;
557
  if (d_hybrid) {
×
558
    DNSSECKeeper dk(d_slog);
×
559
    nsec3zone = dk.getNSEC3PARAM(bbd->d_name, &ns3pr);
×
560
  }
4✔
561
  else
562
    nsec3zone = getNSEC3PARAMuncached(bbd->d_name, &ns3pr);
563

564
  auto records = std::make_shared<recordstorage_t>();
×
565
  ZoneParserTNG zpt(bbd->main_filename(), bbd->d_name, s_binddirectory, d_upgradeContent);
566
  zpt.setMaxGenerateSteps(::arg().asNum("max-generate-steps"));
567
  zpt.setMaxIncludes(::arg().asNum("max-include-depth"));
×
568
  DNSResourceRecord rr;
×
569
  string hashed;
570
  while (zpt.get(rr)) {
×
571
    if (rr.qtype.getCode() == QType::NSEC || rr.qtype.getCode() == QType::NSEC3 || rr.qtype.getCode() == QType::NSEC3PARAM)
×
572
      continue; // we synthesise NSECs on demand
×
573

×
574
    insertRecord(records, bbd->d_name, rr.qname, rr.qtype, rr.content, rr.ttl, "");
×
575
  }
×
576
  fixupOrderAndAuth(records, bbd->d_name, nsec3zone, ns3pr);
×
577
  doEmptyNonTerminals(records, bbd->d_name, nsec3zone, ns3pr);
×
578
  bbd->d_fileinfo = zpt.getFileset();
×
579
  bbd->d_loaded = true;
×
580
  bbd->d_checknow = false;
×
581
  bbd->d_status = "parsed into memory at " + nowTime();
×
582
  bbd->d_records = LookButDontTouch<recordstorage_t>(std::move(records));
×
583
  bbd->d_nsec3zone = nsec3zone;
584
  bbd->d_nsec3param = std::move(ns3pr);
×
585
}
×
586

×
587
/** THIS IS AN INTERNAL FUNCTION! It does moadnsparser prio impedance matching
×
588
    Much of the complication is due to the efforts to benefit from std::string reference counting copy on write semantics */
×
589
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)
×
590
{
591
  Bind2DNSRecord bdr;
592
  bdr.qname = qname;
×
593

×
594
  if (zoneName.empty())
595
    ;
×
596
  else if (bdr.qname.isPartOf(zoneName))
×
597
    bdr.qname.makeUsRelative(zoneName);
598
  else {
×
599
    string msg = "Trying to insert non-zone data, name='" + bdr.qname.toLogString() + "', qtype=" + qtype.toString() + ", zone='" + zoneName.toLogString() + "'";
×
600
    if (s_ignore_broken_records) {
×
601
      SLOG(g_log << Logger::Warning << msg << " ignored" << endl,
×
602
           d_slog->info(Logr::Warning, "Non-zone data record ignored", "zone", Logging::Loggable(zoneName), "name", Logging::Loggable(bdr.qname), "qtype", Logging::Loggable(qtype)));
×
603
      return;
604
    }
×
605
    throw PDNSException(std::move(msg));
×
606
  }
×
607

×
608
  //  bdr.qname.swap(bdr.qname);
×
609

×
610
  if (!records->empty() && bdr.qname == boost::prior(records->end())->qname)
×
611
    bdr.qname = boost::prior(records->end())->qname;
×
612

613
  bdr.qname = bdr.qname;
×
614
  bdr.qtype = qtype.getCode();
×
615
  bdr.content = content;
616
  bdr.nsec3hash = hashed;
617

618
  if (auth != nullptr) // Set auth on empty non-terminals
619
    bdr.auth = *auth;
×
620
  else
×
621
    bdr.auth = true;
622

×
623
  bdr.ttl = ttl;
×
624
  records->insert(std::move(bdr));
×
625
}
×
626

627
string Bind2Backend::DLReloadNowHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
×
628
{
×
629
  ostringstream ret;
×
630

×
631
  for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
632
    BB2DomainInfo bbd;
×
633
    ZoneName zone(*i);
×
634
    if (safeGetBBDomainInfo(zone, &bbd)) {
×
635
      Bind2Backend bb2;
636
      bb2.queueReloadAndStore(bbd.d_id);
637
      if (!safeGetBBDomainInfo(zone, &bbd)) // Read the *new* domain status
×
638
        ret << *i << ": [missing]\n";
×
639
      else
640
        ret << *i << ": " << (bbd.d_wasRejectedLastReload ? "[rejected]" : "") << "\t" << bbd.d_status << "\n";
×
641
      purgeAuthCaches(zone.operator const DNSName&().toString() + "$");
×
642
      DNSSECKeeper::clearMetaCache(zone);
×
643
    }
×
644
    else
×
645
      ret << *i << " no such domain\n";
×
646
  }
×
647
  if (ret.str().empty())
×
648
    ret << "no domains reloaded";
×
649
  return ret.str();
×
650
}
×
651

×
652
string Bind2Backend::DLDomStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
653
{
654
  ostringstream ret;
×
655

×
656
  if (parts.size() > 1) {
×
657
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
658
      BB2DomainInfo bbd;
×
659
      if (safeGetBBDomainInfo(ZoneName(*i), &bbd)) {
×
660
        ret << *i << ": " << (bbd.d_loaded ? "" : "[rejected]") << "\t" << bbd.d_status << "\n";
×
661
      }
662
      else {
×
663
        ret << *i << " no such domain\n";
×
664
      }
665
    }
×
666
  }
×
667
  else {
×
668
    auto state = s_state.read_lock();
×
669
    for (const auto& i : *state) {
×
670
      ret << i.d_name << ": " << (i.d_loaded ? "" : "[rejected]") << "\t" << i.d_status << "\n";
×
671
    }
×
672
  }
×
673

×
674
  if (ret.str().empty())
675
    ret << "no domains passed";
×
676

×
677
  return ret.str();
×
678
}
×
679

×
680
static void printDomainExtendedStatus(ostringstream& ret, const BB2DomainInfo& info)
×
681
{
682
  ret << info.d_name << ": " << std::endl;
683
  ret << "\t Status: " << info.d_status << std::endl;
×
684
  ret << "\t Internal ID: " << info.d_id << std::endl;
×
685
  ret << "\t On-disk file: " << info.main_filename() << " (" << info.d_fileinfo.front().second << ")" << std::endl;
686
  ret << "\t Kind: ";
×
687
  switch (info.d_kind) {
×
688
  case DomainInfo::Primary:
689
    ret << "Primary";
690
    break;
×
691
  case DomainInfo::Secondary:
×
692
    ret << "Secondary";
693
    break;
694
  default:
×
695
    ret << "Native";
×
696
  }
×
697
  ret << std::endl;
×
698
  ret << "\t Primaries: " << std::endl;
×
699
  for (const auto& primary : info.d_primaries) {
×
700
    ret << "\t\t - " << primary.toStringWithPort() << std::endl;
×
701
  }
×
702
  ret << "\t Also Notify: " << std::endl;
×
703
  for (const auto& also : info.d_also_notify) {
×
704
    ret << "\t\t - " << also << std::endl;
×
705
  }
×
706
  ret << "\t Number of records: " << info.d_records.getEntriesCount() << std::endl;
707
  ret << "\t Loaded: " << info.d_loaded << std::endl;
×
708
  ret << "\t Check now: " << info.d_checknow << std::endl;
×
709
  ret << "\t Check interval: " << info.getCheckInterval() << std::endl;
×
710
  ret << "\t Last check: " << info.d_lastcheck << std::endl;
711
  ret << "\t Last notified: " << info.d_lastnotified << std::endl;
×
712
}
×
713

×
714
string Bind2Backend::DLDomExtendedStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
×
715
{
×
716
  ostringstream ret;
×
717

×
718
  if (parts.size() > 1) {
×
719
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
720
      BB2DomainInfo bbd;
×
721
      if (safeGetBBDomainInfo(ZoneName(*i), &bbd)) {
722
        printDomainExtendedStatus(ret, bbd);
723
      }
724
      else {
×
725
        ret << *i << " no such domain" << std::endl;
×
726
      }
727
    }
×
728
  }
×
729
  else {
1,388✔
730
    auto rstate = s_state.read_lock();
1,388!
731
    for (const auto& state : *rstate) {
1,388✔
732
      printDomainExtendedStatus(ret, state);
1,388✔
733
    }
1,388✔
734
  }
1,388✔
735

1,388✔
736
  if (ret.str().empty()) {
1,388✔
737
    ret << "no domains passed" << std::endl;
1,388✔
738
  }
1,388✔
739

1,388✔
740
  return ret.str();
1,388!
741
}
1,388✔
742

1,388✔
743
string Bind2Backend::DLListRejectsHandler(const vector<string>& /* parts */, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
1,388✔
744
{
745
  ostringstream ret;
1,388!
746
  auto rstate = s_state.read_lock();
1,388✔
747
  for (const auto& i : *rstate) {
1,388✔
748
    if (!i.d_loaded)
1,388!
749
      ret << i.d_name << "\t" << i.d_status << endl;
×
750
  }
×
751
  return ret.str();
752
}
1,388✔
753

1,388✔
754
string Bind2Backend::DLAddDomainHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
1,388✔
755
{
756
  if (parts.size() < 3)
1,388!
757
    return "ERROR: Domain name and zone filename are required";
×
758

759
  ZoneName domainname(parts[1]);
1,388✔
760
  const string& filename = parts[2];
761
  BB2DomainInfo bbd;
1,388✔
762
  if (safeGetBBDomainInfo(domainname, &bbd))
1,388✔
763
    return "Already loaded";
1,117✔
764

1,117✔
765
  if (!boost::starts_with(filename, "/") && ::arg()["chroot"].empty())
×
766
    return "Unable to load zone " + domainname.toLogString() + " from " + filename + " as the filename is not absolute.";
271✔
767

98✔
768
  struct stat buf;
98✔
769
  if (stat(filename.c_str(), &buf) != 0)
98✔
770
    return "Unable to load zone " + domainname.toLogString() + " from " + filename + ": " + strerror(errno);
771

271!
772
  Bind2Backend bb2; // createdomainentry needs access to our configuration
271✔
773
  bbd = bb2.createDomainEntry(domainname);
271✔
774
  bbd.d_fileinfo.emplace_back(std::make_pair(filename, buf.st_ctime));
271!
775
  bbd.d_checknow = true;
271✔
776
  bbd.d_loaded = true;
271✔
777
  bbd.d_lastcheck = 0;
778
  bbd.d_status = "parsing into memory";
×
779

1,376✔
780
  safePutBBDomainInfo(bbd);
1,376✔
781

1,376✔
782
  g_zoneCache.add(domainname, bbd.d_id); // make new zone visible
783

784
  SLOG(g_log << Logger::Warning << "Zone " << domainname << " loaded" << endl,
×
785
       bb2.d_slog->info(Logr::Info, "Zone loaded", "zone", Logging::Loggable(domainname), "file", Logging::Loggable(filename)));
×
786
  return "Loaded zone " + domainname.toLogString() + " from " + filename;
×
787
}
788

789
Bind2Backend::Bind2Backend(const string& suffix, bool loadZones)
790
{
×
791
  d_getAllDomainMetadataQuery_stmt = nullptr;
×
792
  d_getDomainMetadataQuery_stmt = nullptr;
×
793
  d_deleteDomainMetadataQuery_stmt = nullptr;
794
  d_insertDomainMetadataQuery_stmt = nullptr;
×
795
  d_getDomainKeysQuery_stmt = nullptr;
796
  d_deleteDomainKeyQuery_stmt = nullptr;
797
  d_insertDomainKeyQuery_stmt = nullptr;
798
  d_GetLastInsertedKeyIdQuery_stmt = nullptr;
799
  d_activateDomainKeyQuery_stmt = nullptr;
1,960✔
800
  d_deactivateDomainKeyQuery_stmt = nullptr;
1,960✔
801
  d_getTSIGKeyQuery_stmt = nullptr;
1,960✔
802
  d_setTSIGKeyQuery_stmt = nullptr;
1,960!
803
  d_deleteTSIGKeyQuery_stmt = nullptr;
1,960!
804
  d_getTSIGKeysQuery_stmt = nullptr;
1,960✔
805

1,960!
806
  setArgPrefix("bind" + suffix);
1,960✔
807
  d_logprefix = "[bind" + suffix + "backend]";
1,960✔
808
  if (g_slogStructured) {
1,960✔
809
    d_slog = g_slog->withName("bind" + suffix);
1,960!
810
    d_handle.setSLog(d_slog);
1,960✔
811
  }
1,960✔
812
  d_hybrid = mustDo("hybrid");
1,960✔
813
  if (d_hybrid && g_zoneCache.isEnabled()) {
1,960!
814
    throw PDNSException("bind-hybrid and the zone cache currently interoperate badly. Please disable the zone cache or stop using bind-hybrid");
815
  }
1,960!
816

1,960✔
817
  d_transaction_id = UnknownDomainID;
1,960✔
818
  s_ignore_broken_records = mustDo("ignore-broken-records");
1,960!
819
  d_upgradeContent = ::arg().mustDo("upgrade-unknown-types");
×
820

×
821
  if (!loadZones && d_hybrid)
822
    return;
1,960!
823

1,960✔
824
  auto lock = std::scoped_lock(s_startup_lock);
1,960!
825

826
  setupDNSSEC();
1,960!
827
  if (s_first == 0) {
×
828
    return;
829
  }
1,960✔
830

831
  if (loadZones) {
1,960✔
832
    loadConfig();
1,960✔
833
    s_first = 0;
1,608✔
834
  }
1,608✔
835

836
  DynListener::registerFunc("BIND-ADD-ZONE", &DLAddDomainHandler, "bindbackend: add zone", "<domain> <filename>");
352✔
837
  DynListener::registerFunc("BIND-DOMAIN-EXTENDED-STATUS", &DLDomExtendedStatusHandler, "bindbackend: list the extended status of all domains", "[domains]");
132✔
838
  DynListener::registerFunc("BIND-DOMAIN-STATUS", &DLDomStatusHandler, "bindbackend: list status of all domains", "[domains]");
132✔
839
  DynListener::registerFunc("BIND-LIST-REJECTS", &DLListRejectsHandler, "bindbackend: list rejected domains");
132✔
840
  DynListener::registerFunc("BIND-RELOAD-NOW", &DLReloadNowHandler, "bindbackend: reload domains", "<domains>");
841
}
352✔
842

352✔
843
Bind2Backend::~Bind2Backend()
352!
844
{
352✔
845
  freeStatements();
352✔
846
} // deallocate statements
352!
847

848
void Bind2Backend::rediscover(string* status)
×
849
{
1,944!
850
  loadConfig(status);
1,944✔
851
}
1,944✔
852

853
void Bind2Backend::reload()
854
{
×
855
  auto state = s_state.write_lock();
×
856
  for (const auto& i : *state) {
×
857
    i.d_checknow = true; // being a bit cheeky here, don't index state_t on this (mutable)
858
  }
859
}
×
860

861
void Bind2Backend::fixupOrderAndAuth(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
×
862
{
×
863
  bool skip;
×
864
  DNSName shorter;
×
865
  set<DNSName> nssets, dssets;
×
866

867
  for (const auto& bdr : *records) {
×
868
    if (!bdr.qname.isRoot() && bdr.qtype == QType::NS)
×
869
      nssets.insert(bdr.qname);
×
870
    else if (bdr.qtype == QType::DS)
871
      dssets.insert(bdr.qname);
872
  }
×
873

×
874
  for (auto iter = records->begin(); iter != records->end(); iter++) {
×
875
    skip = false;
×
876
    shorter = iter->qname;
×
877

×
878
    if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
×
879
      do {
×
880
        if (nssets.count(shorter) != 0u) {
×
881
          skip = true;
882
          break;
883
        }
×
884
      } while (shorter.chopOff() && !iter->qname.isRoot());
×
885
    }
×
886

887
    iter->auth = (!skip && (iter->qtype == QType::DS || iter->qtype == QType::RRSIG || (nssets.count(iter->qname) == 0u)));
98✔
888

98✔
889
    if (!skip && nsec3zone && iter->qtype != QType::RRSIG && (iter->auth || (iter->qtype == QType::NS && (ns3pr.d_flags == 0u)) || (dssets.count(iter->qname) != 0u))) {
×
890
      Bind2DNSRecord bdr = *iter;
98!
891
      bdr.nsec3hash = toBase32Hex(hashQNameWithSalt(ns3pr, bdr.qname + zoneName.operator const DNSName&()));
98✔
892
      records->replace(iter, bdr);
98!
893
    }
98✔
894

98!
895
    // cerr<<iter->qname<<"\t"<<QType(iter->qtype).toString()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
98✔
896
  }
×
897
}
×
898

×
899
void Bind2Backend::doEmptyNonTerminals(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
900
{
98✔
901
  bool auth = false;
98✔
902
  DNSName shorter;
903
  std::unordered_set<DNSName> qnames;
98✔
904
  std::unordered_map<DNSName, bool> nonterm;
905

906
  uint32_t maxent = ::arg().asNum("max-ent-entries");
98✔
907

908
  for (const auto& bdr : *records)
98✔
909
    qnames.insert(bdr.qname);
98✔
910

98✔
911
  for (const auto& bdr : *records) {
98!
912

913
    if (!bdr.auth && bdr.qtype == QType::NS)
×
914
      auth = (!nsec3zone || (ns3pr.d_flags == 0u));
98✔
915
    else
98✔
916
      auth = bdr.auth;
98!
917

918
    shorter = bdr.qname;
98!
919
    while (shorter.chopOff()) {
×
920
      if (qnames.count(shorter) == 0u) {
98!
921
        if (!(maxent)) {
×
922
          SLOG(g_log << Logger::Error << "Zone '" << zoneName << "' has too many empty non terminals." << endl,
923
               d_slog->info(Logr::Error, "Zone has too many empty non terminals.", "zone", Logging::Loggable(zoneName)));
×
924
          return;
×
925
        }
×
926

×
927
        if (nonterm.count(shorter) == 0u) {
98✔
928
          nonterm.emplace(shorter, auth);
98!
929
          --maxent;
×
930
        }
931
        else if (auth)
×
932
          nonterm[shorter] = true;
×
933
      }
×
934
    }
935
  }
×
936

×
937
  DNSResourceRecord rr;
×
938
  rr.qtype = "#0";
×
939
  rr.content = "";
×
940
  rr.ttl = 0;
941
  for (auto& nt : nonterm) {
×
942
    string hashed;
×
943
    rr.qname = nt.first + zoneName.operator const DNSName&();
944
    if (nsec3zone && nt.second)
×
945
      hashed = toBase32Hex(hashQNameWithSalt(ns3pr, rr.qname));
×
946
    insertRecord(records, zoneName, rr.qname, rr.qtype, rr.content, rr.ttl, hashed, &nt.second);
947

×
948
    // cerr<<rr.qname<<"\t"<<rr.qtype.toString()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
×
949
  }
×
950
}
×
951

952
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
953
{
×
954
  static domainid_t domain_id = 1;
955

956
  if (!getArg("config").empty()) {
957
    BindParser BP;
132✔
958
    try {
132!
959
      BP.parse(getArg("config"));
960
    }
132!
961
    catch (PDNSException& ae) {
132✔
962
      SLOG(g_log << Logger::Error << "Error parsing bind configuration: " << ae.reason << endl,
132✔
963
           d_slog->error(Logr::Error, ae.reason, "Error parsing bind configuration"));
132✔
964
      throw;
132!
965
    }
132✔
966

×
967
    vector<BindDomainInfo> domains = BP.getDomains();
×
968
    this->alsoNotify = BP.getAlsoNotify();
×
969

970
    s_binddirectory = BP.getDirectory();
132✔
971
    //    ZP.setDirectory(d_binddirectory);
132✔
972

973
    SLOG(g_log << Logger::Warning << d_logprefix << " Parsing " << domains.size() << " domain(s), will report when done" << endl,
132✔
974
         d_slog->info(Logr::Info, "Parsing " + std::to_string(domains.size()) + " domain(s), will report when done"));
975

×
976
    set<ZoneName> oldnames;
132✔
977
    set<ZoneName> newnames;
978
    {
132✔
979
      auto state = s_state.read_lock();
132✔
980
      for (const BB2DomainInfo& bbd : *state) {
132✔
981
        oldnames.insert(bbd.d_name);
132✔
982
      }
132!
983
    }
×
984
    int rejected = 0;
985
    int newdomains = 0;
132!
986

132✔
987
    struct stat st;
132✔
988

989
    for (auto& domain : domains) {
132✔
990
      if (stat(domain.filename.c_str(), &st) == 0) {
991
        domain.d_dev = st.st_dev;
132!
992
        domain.d_ino = st.st_ino;
×
993
      }
×
994
    }
×
995

×
996
    sort(domains.begin(), domains.end()); // put stuff in inode order
×
997
    for (const auto& domain : domains) {
998
      if (!(domain.hadFileDirective)) {
132✔
999
        SLOG(g_log << Logger::Warning << d_logprefix << " Zone '" << domain.name << "' has no 'file' directive set in " << getArg("config") << endl,
132!
1000
             d_slog->info(Logr::Warning, "Zone has no 'file' directive set", "zone", Logging::Loggable(domain.name), "filename", Logging::Loggable(getArg("config"))));
×
1001
        rejected++;
×
1002
        continue;
×
1003
      }
×
1004

×
1005
      if (domain.type.empty()) {
1006
        SLOG(g_log << Logger::Notice << d_logprefix << " Zone '" << domain.name << "' has no type specified, assuming 'native'" << endl,
×
1007
             d_slog->info(Logr::Notice, "Zone has no type specified, assuming 'native'", "zone", Logging::Loggable(domain.name)));
×
1008
      }
1009
      if (domain.type != "primary" && domain.type != "secondary" && domain.type != "native" && !domain.type.empty() && domain.type != "master" && domain.type != "slave") {
×
1010
        SLOG(g_log << Logger::Warning << d_logprefix << " Warning! Skipping zone '" << domain.name << "' because type '" << domain.type << "' is invalid" << endl,
×
1011
             d_slog->info(Logr::Warning, "Skipping zone because type is invalid", "zone", Logging::Loggable(domain.name), "type", Logging::Loggable(domain.type)));
×
1012
        rejected++;
1013
        continue;
×
1014
      }
1015

×
1016
      BB2DomainInfo bbd;
×
1017
      bool isNew = false;
1018

×
1019
      if (!safeGetBBDomainInfo(domain.name, &bbd)) {
×
1020
        isNew = true;
×
1021
        bbd.d_id = domain_id++;
×
1022
        bbd.setCheckInterval(getArgAsNum("check-interval"));
98✔
1023
        bbd.d_lastnotified = 0;
1024
        bbd.d_loaded = false;
98✔
1025
      }
98✔
1026

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

98!
1039
      DomainInfo::DomainKind kind = DomainInfo::Native;
×
1040
      if (domain.type == "primary" || domain.type == "master") {
1041
        kind = DomainInfo::Primary;
98✔
1042
      }
98✔
1043
      if (domain.type == "secondary" || domain.type == "slave") {
98✔
1044
        kind = DomainInfo::Secondary;
1045
      }
1046

×
1047
      bool kindChanged = (bbd.d_kind != kind);
×
1048
      bbd.d_kind = kind;
1049

×
1050
      newnames.insert(bbd.d_name);
×
1051
      if (filenameChanged || !bbd.d_loaded || !bbd.current()) {
×
1052
        SLOG(g_log << Logger::Info << d_logprefix << " parsing '" << domain.name << "' from file '" << domain.filename << "'" << endl,
×
1053
             d_slog->info(Logr::Info, "Parsing zone from file", "zone", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
1054

1055
        try {
1056
          parseZoneFile(&bbd);
×
1057
        }
×
1058
        catch (PDNSException& ae) {
×
1059
          ostringstream msg;
1060
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.reason;
×
1061

×
1062
          if (status != nullptr)
×
1063
            *status += msg.str();
×
1064
          bbd.d_status = msg.str();
×
1065

×
1066
          SLOG(g_log << Logger::Warning << d_logprefix << msg.str() << endl,
×
1067
               d_slog->error(Logr::Error, ae.reason, "Error in zone file", "zone", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
×
1068
          rejected++;
×
1069
        }
1070
        catch (std::system_error& ae) {
×
1071
          ostringstream msg;
×
1072
          bool missingNewSecondary = ae.code().value() == ENOENT && isNew && kind == DomainInfo::Secondary;
×
1073
          if (missingNewSecondary) {
×
1074
            msg << " error at " + nowTime() << " no file found for new secondary domain '" << domain.name << "'. Has not been AXFR'd yet";
×
1075
          }
×
1076
          else {
×
1077
            msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
×
1078
          }
×
1079

1080
          if (status != nullptr)
×
1081
            *status += msg.str();
1082
          bbd.d_status = msg.str();
×
1083
          SLOG(
1084
            g_log << Logger::Warning << d_logprefix << msg.str() << endl,
1085
            if (missingNewSecondary) {
1086
              d_slog->error(Logr::Warning, ae.what(), "Secondary domain has not been AXFR'd yet", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename));
×
1087
            } else {
1088
              d_slog->error(Logr::Warning, ae.what(), "Parse error", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename));
×
1089
            });
×
1090
          rejected++;
×
1091
        }
×
1092
        catch (std::exception& ae) {
×
1093
          ostringstream msg;
132✔
1094
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
1095

132✔
1096
          if (status != nullptr)
132!
1097
            *status += msg.str();
1098
          bbd.d_status = msg.str();
132!
1099

×
1100
          SLOG(g_log << Logger::Warning << d_logprefix << msg.str() << endl,
×
1101
               d_slog->error(Logr::Warning, ae.what(), "Parse error", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
1102
          rejected++;
×
1103
        }
132✔
1104
        safePutBBDomainInfo(bbd);
132✔
1105
      }
132✔
1106
      else if (addressesChanged || kindChanged) {
1107
        safePutBBDomainInfo(bbd);
132✔
1108
      }
132✔
1109
    }
132!
1110
    vector<ZoneName> diff;
×
1111

1112
    set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
132✔
1113
    unsigned int remdomains = diff.size();
132✔
1114

132✔
1115
    for (const ZoneName& name : diff) {
1116
      safeRemoveBBDomainInfo(name);
×
1117
    }
1118

1119
    // count number of entirely new domains
×
1120
    diff.clear();
×
1121
    set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
×
1122
    newdomains = diff.size();
×
1123

×
1124
    ostringstream msg;
×
1125
    msg << " Done parsing domains, " << rejected << " rejected, " << newdomains << " new, " << remdomains << " removed";
1126
    if (status != nullptr)
1127
      *status = msg.str();
1128

1129
    SLOG(
×
1130
      g_log << Logger::Error << d_logprefix << msg.str() << endl,
×
1131
      if (rejected == 0) {
1132
        d_slog->info(Logr::Info, "Done parsing domains", "new", Logging::Loggable(newdomains), "removed", Logging::Loggable(remdomains));
×
1133
      } else {
×
1134
        d_slog->info(Logr::Error, "Done parsing domains", "new", Logging::Loggable(newdomains), "removed", Logging::Loggable(remdomains), "rejected", Logging::Loggable(rejected));
×
1135
      });
×
1136
  }
×
1137
}
×
1138

×
1139
// NOLINTNEXTLINE(readability-identifier-length)
×
1140
void Bind2Backend::queueReloadAndStore(domainid_t id)
×
1141
{
×
1142
  BB2DomainInfo bbold;
×
1143
  try {
×
1144
    if (!safeGetBBDomainInfo(id, &bbold))
×
1145
      return;
×
1146
    bbold.d_checknow = false;
1147
    BB2DomainInfo bbnew(bbold);
×
1148
    /* make sure that nothing will be able to alter the existing records,
×
1149
       we will load them from the zone file instead */
×
1150
    bbnew.d_records = LookButDontTouch<recordstorage_t>();
1151
    parseZoneFile(&bbnew);
1152
    bbnew.d_wasRejectedLastReload = false;
15✔
1153
    safePutBBDomainInfo(bbnew);
15✔
1154
    SLOG(g_log << Logger::Warning << "Zone '" << bbnew.d_name << "' (" << bbnew.main_filename() << ") reloaded" << endl,
1155
         d_slog->info(Logr::Info, "Zone reloaded", "zone", Logging::Loggable(bbnew.d_name), "file", Logging::Loggable(bbnew.main_filename())));
15✔
1156
  }
1157
  catch (PDNSException& ae) {
15✔
1158
    ostringstream msg;
15✔
1159
    msg << " error at " + nowTime() + " parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.reason;
15✔
1160
    SLOG(g_log << Logger::Warning << "Error parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.reason << endl,
1161
         d_slog->error(Logr::Error, ae.reason, "Error reloading zone", "zone", Logging::Loggable(bbold.d_name), "file", Logging::Loggable(bbold.main_filename())));
15!
1162
    bbold.d_status = msg.str();
×
1163
    bbold.d_lastcheck = time(nullptr);
1164
    bbold.d_wasRejectedLastReload = true;
15!
1165
    safePutBBDomainInfo(bbold);
×
1166
  }
×
1167
  catch (std::exception& ae) {
1168
    ostringstream msg;
×
1169
    msg << " error at " + nowTime() + " parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.what();
15✔
1170
    SLOG(g_log << Logger::Warning << "Error parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.what() << endl,
15✔
1171
         d_slog->error(Logr::Error, ae.what(), "Error reloading zone", "zone", Logging::Loggable(bbold.d_name), "file", Logging::Loggable(bbold.main_filename())));
15✔
1172
    bbold.d_status = msg.str();
15!
1173
    bbold.d_lastcheck = time(nullptr);
15!
1174
    bbold.d_wasRejectedLastReload = true;
15!
1175
    safePutBBDomainInfo(bbold);
1176
  }
15!
1177
}
15!
1178

×
1179
bool Bind2Backend::findBeforeAndAfterUnhashed(std::shared_ptr<const recordstorage_t>& records, const DNSName& qname, DNSName& /* unhashed */, DNSName& before, DNSName& after)
15✔
1180
{
15✔
1181
  // for(const auto& record: *records)
15✔
1182
  //   cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
1183

×
1184
  recordstorage_t::const_iterator iterBefore, iterAfter;
1185

1186
  iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
1187

×
1188
  if (iterBefore != records->begin())
×
1189
    --iterBefore;
×
1190
  while ((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
1191
    --iterBefore;
×
1192
  before = iterBefore->qname;
×
1193

×
1194
  if (iterAfter == records->end()) {
×
1195
    iterAfter = records->begin();
×
1196
  }
×
1197
  else {
1198
    while ((!iterAfter->auth && iterAfter->qtype != QType::NS) || !iterAfter->qtype) {
×
1199
      ++iterAfter;
1200
      if (iterAfter == records->end()) {
1201
        iterAfter = records->begin();
1202
        break;
1203
      }
×
1204
    }
1205
  }
×
1206
  after = iterAfter->qname;
×
1207

1208
  return true;
×
1209
}
1210

×
1211
// NOLINTNEXTLINE(readability-identifier-length)
×
1212
bool Bind2Backend::getBeforeAndAfterNamesAbsolute(domainid_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
×
1213
{
×
1214
  BB2DomainInfo bbd;
×
1215
  if (!safeGetBBDomainInfo(id, &bbd))
×
1216
    return false;
×
1217

1218
  shared_ptr<const recordstorage_t> records = bbd.d_records.get();
1219
  if (!bbd.d_nsec3zone) {
1,388✔
1220
    return findBeforeAndAfterUnhashed(records, qname, unhashed, before, after);
1,388✔
1221
  }
1,388✔
1222
  else {
1223
    const auto& hashindex = boost::multi_index::get<NSEC3Tag>(*records);
1224

15✔
1225
    // for(auto iter = first; iter != hashindex.end(); iter++)
35!
1226
    //  cerr<<iter->nsec3hash<<endl;
35!
1227

1228
    auto first = hashindex.upper_bound("");
35✔
1229
    auto iter = hashindex.upper_bound(qname.toStringNoDot());
15✔
1230

20✔
1231
    if (iter == hashindex.end()) {
20!
1232
      --iter;
20!
1233
      before = DNSName(iter->nsec3hash);
1234
      after = DNSName(first->nsec3hash);
20!
1235
    }
×
1236
    else {
1237
      after = DNSName(iter->nsec3hash);
20!
1238
      if (iter != first)
×
1239
        --iter;
×
1240
      else
×
1241
        iter = --hashindex.end();
×
1242
      before = DNSName(iter->nsec3hash);
20✔
1243
    }
20✔
1244
    unhashed = iter->qname + bbd.d_name.operator const DNSName&();
20✔
1245

20✔
1246
    return true;
20!
1247
  }
20✔
1248
}
1249

20!
1250
void Bind2Backend::lookup(const QType& qtype, const DNSName& qname, domainid_t zoneId, DNSPacket* /* pkt_p */)
20!
1251
{
1252
  d_handle.reset();
20✔
1253

35✔
1254
  static bool mustlog = ::arg().mustDo("query-logging");
35✔
1255

15✔
1256
  bool found = false;
15!
1257
  ZoneName domain;
15✔
1258
  BB2DomainInfo bbd;
1259

1260
  if (mustlog) {
1261
    SLOG(g_log << Logger::Warning << "Lookup for '" << qtype.toString() << "' of '" << qname << "' within zoneID " << zoneId << endl,
×
1262
         d_slog->info(Logr::Warning, "Record lookup", "name", Logging::Loggable(qname), "qtype", Logging::Loggable(qtype), "zone id", Logging::Loggable(zoneId)));
×
1263
  }
1264

×
1265
  if (zoneId != UnknownDomainID) {
×
1266
    if ((found = (safeGetBBDomainInfo(zoneId, &bbd) && qname.isPartOf(bbd.d_name)))) {
×
1267
      domain = std::move(bbd.d_name);
×
1268
    }
×
1269
  }
×
1270
  else {
1271
    domain = ZoneName(qname);
×
1272
    do {
×
1273
      found = safeGetBBDomainInfo(domain, &bbd);
×
1274
    } while (!found && qtype != QType::SOA && domain.chopOff());
×
1275
  }
1276

1277
  if (!found) {
×
1278
    if (mustlog) {
×
1279
      SLOG(g_log << Logger::Warning << "Found no authoritative zone for '" << qname << "' and/or id " << zoneId << endl,
×
1280
           d_slog->info(Logr::Warning, "Found no authoritative zone", "name", Logging::Loggable(qname), "zone id", Logging::Loggable(zoneId)));
1281
    }
×
1282
    d_handle.d_list = false;
1283
    return;
1284
  }
1285

1286
  if (mustlog) {
×
1287
    SLOG(g_log << Logger::Warning << "Found a zone '" << domain << "' (with id " << bbd.d_id << ") that might contain data " << endl,
1288
         d_slog->info(Logr::Warning, "Found authoritative zone", "zone", Logging::Loggable(domain), "zone id", Logging::Loggable(bbd.d_id)));
×
1289
  }
1290

1291
  d_handle.id = bbd.d_id;
1292
  d_handle.qname = qname.makeRelative(domain); // strip domain name
1,960✔
1293
  d_handle.qtype = qtype;
1,960✔
1294
  d_handle.domain = std::move(domain);
1,960✔
1295

1296
  if (!bbd.current()) {
1297
    SLOG(g_log << Logger::Warning << "Zone '" << d_handle.domain << "' (" << bbd.main_filename() << ") needs reloading" << endl,
20!
1298
         d_slog->info(Logr::Warning, "Zone needs reloading", "zone", Logging::Loggable(d_handle.domain), "file", Logging::Loggable(bbd.main_filename())));
20!
1299
    queueReloadAndStore(bbd.d_id);
20!
1300
    if (!safeGetBBDomainInfo(d_handle.domain, &bbd))
×
1301
      throw DBException("Zone '" + bbd.d_name.toLogString() + "' (" + bbd.main_filename() + ") gone after reload"); // if we don't throw here, we crash for some reason
20✔
1302
  }
20✔
1303

×
1304
  if (!bbd.d_loaded) {
×
1305
    d_handle.reset();
×
1306
    throw DBException("Zone for '" + d_handle.domain.toLogString() + "' in '" + bbd.main_filename() + "' not loaded (file missing, corrupt or primary dead)"); // fsck
1307
  }
1308

×
1309
  d_handle.d_records = bbd.d_records.get();
1310

1311
  if (d_handle.d_records->empty()) {
×
1312
    DLOG(SLOG(g_log << "Query with no results" << endl,
×
1313
              d_slog->info(Logr::Debug, "No results", "name", Logging::Loggable(qname), "qtype", Logging::Loggable(qtype))));
×
1314
  }
×
1315

×
1316
  d_handle.mustlog = mustlog;
1317

1318
  const auto& hashedidx = boost::multi_index::get<UnorderedNameTag>(*d_handle.d_records);
×
1319
  auto range = hashedidx.equal_range(d_handle.qname);
×
1320

×
1321
  d_handle.d_list = false;
×
1322
  d_handle.d_iter = range.first;
×
1323
  d_handle.d_end_iter = range.second;
×
1324
}
1325

1326
bool Bind2Backend::get(DNSResourceRecord& r)
20✔
1327
{
20✔
1328
  if (!d_handle.d_records) {
20✔
1329
    if (d_handle.mustlog) {
20✔
1330
      SLOG(g_log << Logger::Warning << "There were no answers" << endl,
20✔
1331
           d_slog->info(Logr::Warning, "No answers"));
1332
    }
1333
    return false;
1334
  }
×
1335

×
1336
  if (!d_handle.get(r)) {
1337
    if (d_handle.mustlog) {
×
1338
      SLOG(g_log << Logger::Warning << "End of answers" << endl,
×
1339
           d_slog->info(Logr::Warning, "No more answers"));
×
1340
    }
1341

×
1342
    d_handle.reset();
1343

×
1344
    return false;
×
1345
  }
×
1346
  if (d_handle.mustlog) {
×
1347
    SLOG(g_log << Logger::Warning << "Returning: '" << r.qtype.toString() << "' of '" << r.qname << "', content: '" << r.content << "'" << endl,
×
1348
         d_slog->info(Logr::Warning, "Returning record", "name", Logging::Loggable(r.qname), "type", Logging::Loggable(r.qtype), "content", Logging::Loggable(r.content)));
×
1349
  }
1350
  return true;
×
1351
}
×
1352

1353
void Bind2Backend::lookupEnd()
×
1354
{
1355
  d_handle.reset();
×
1356
}
1357

1358
bool Bind2Backend::handle::get(DNSResourceRecord& r)
1359
{
1360
  if (d_list)
×
1361
    return get_list(r);
1362
  else
1363
    return get_normal(r);
1364
}
×
1365

×
1366
void Bind2Backend::handle::reset()
1367
{
1368
  d_records.reset();
1369
  qname.clear();
1370
  mustlog = false;
1371
}
×
1372

×
1373
bool Bind2Backend::handle::get_normal(DNSResourceRecord& r)
×
1374
{
1375
  DLOG(SLOG(g_log << "Bind2Backend get() was called for " << qtype.toString() << " record for '" << qname << "' - " << d_records->size() << " available in total!" << endl,
×
1376
            d_slog->info(Logr::Debug, "Bind2Backend get() invoked", "name", Logging::Loggable(qname), "type", Logging::Loggable(qtype), "results", Logging::Loggable(d_records->size()))));
×
1377

1378
  if (d_iter == d_end_iter) {
×
1379
    return false;
×
1380
  }
×
1381

1382
  while (d_iter != d_end_iter && !(qtype.getCode() == QType::ANY || (d_iter)->qtype == qtype.getCode())) {
×
1383
    DLOG(SLOG(g_log << Logger::Warning << "Skipped " << qname << "/" << QType(d_iter->qtype).toString() << ": '" << d_iter->content << "'" << endl,
×
1384
              d_slog->info(Logr::Debug, "Skipped record", "name", Logging::Loggable(qname), "type", Logging::Loggable(d_iter->qtype), "content", Logging::Loggable(d_iter->content))));
1385
    d_iter++;
1386
  }
×
1387
  if (d_iter == d_end_iter) {
×
1388
    return false;
×
1389
  }
1390
  DLOG(SLOG(g_log << "Bind2Backend get() returning a rr with a " << QType(d_iter->qtype).getCode() << endl,
×
1391
            d_slog->info(Logr::Debug, "Bind2Backend get() returning a rr", "type", Logging::Loggable(d_iter->qtype))));
1392

1393
  const DNSName& domainName(domain);
1394
  r.qname = qname.empty() ? domainName : (qname + domainName);
×
1395
  r.domain_id = id;
×
1396
  r.content = (d_iter)->content;
×
1397
  //  r.domain_id=(d_iter)->domain_id;
×
1398
  r.qtype = (d_iter)->qtype;
×
1399
  r.ttl = (d_iter)->ttl;
1400

1401
  //if(!d_iter->auth && r.qtype.getCode() != QType::A && r.qtype.getCode()!=QType::AAAA && r.qtype.getCode() != QType::NS)
×
1402
  //  cerr<<"Warning! Unauth response for qtype "<< r.qtype.toString() << " for '"<<r.qname<<"'"<<endl;
×
1403
  r.auth = d_iter->auth;
×
1404

1405
  d_iter++;
×
1406

×
1407
  return true;
1408
}
1409

×
1410
bool Bind2Backend::list(const ZoneName& /* target */, domainid_t domainId, bool /* include_disabled */)
×
1411
{
×
1412
  BB2DomainInfo bbd;
1413

×
1414
  if (!safeGetBBDomainInfo(domainId, &bbd)) {
×
1415
    return false;
1416
  }
1417

×
1418
  d_handle.reset();
1419
  DLOG(SLOG(g_log << "Bind2Backend constructing handle for list of " << domainId << endl,
1420
            d_slog->info(Logr::Debug, "Bind2Backend constructing handle for zone list", "zone id", Logging::Loggable(domainId))));
×
1421

1422
  if (!bbd.d_loaded) {
1423
    throw PDNSException("zone was not loaded, perhaps because of: " + bbd.d_status);
×
1424
  }
×
1425

×
1426
  d_handle.d_records = bbd.d_records.get(); // give it a copy, which will stay around
×
1427
  d_handle.d_qname_iter = d_handle.d_records->begin();
×
1428
  d_handle.d_qname_end = d_handle.d_records->end(); // iter now points to a vector of pointers to vector<BBResourceRecords>
1429

×
1430
  d_handle.id = domainId;
×
1431
  d_handle.domain = bbd.d_name;
×
1432
  d_handle.d_list = true;
1433
  return true;
1434
}
×
1435

1436
bool Bind2Backend::handle::get_list(DNSResourceRecord& r)
×
1437
{
×
1438
  if (d_qname_iter != d_qname_end) {
1439
    const DNSName& domainName(domain);
×
1440
    r.qname = d_qname_iter->qname.empty() ? domainName : (d_qname_iter->qname + domainName);
×
1441
    r.domain_id = id;
1442
    r.content = (d_qname_iter)->content;
×
1443
    r.qtype = (d_qname_iter)->qtype;
×
1444
    r.ttl = (d_qname_iter)->ttl;
1445
    r.auth = d_qname_iter->auth;
1446
    d_qname_iter++;
1447
    return true;
×
1448
  }
×
1449
  return false;
×
1450
}
×
1451

×
1452
bool Bind2Backend::autoPrimariesList(std::vector<AutoPrimary>& primaries)
×
1453
{
×
1454
  if (getArg("autoprimary-config").empty())
1455
    return false;
×
1456

×
1457
  std::string filename(getArg("autoprimaries"));
1458
  ifstream c_if(filename, std::ios::in);
×
1459
  if (!c_if) {
×
1460
    SLOG(g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl,
×
1461
         d_slog->error(Logr::Error, errno, "Unable to open autoprimaries file", "file", Logging::Loggable(filename)));
1462
    return false;
1463
  }
×
1464

×
1465
  string line, sip, saccount;
×
1466
  while (getline(c_if, line)) {
1467
    std::istringstream ii(line);
×
1468
    ii >> sip;
×
1469
    if (!sip.empty()) {
1470
      ii >> saccount;
1471
      primaries.emplace_back(sip, "", saccount);
×
1472
    }
×
1473
  }
1474

1475
  c_if.close();
12!
1476
  return true;
12✔
1477
}
12✔
1478

12!
1479
bool Bind2Backend::autoPrimaryBackend(const string& ipAddress, const ZoneName& /* domain */, const vector<DNSResourceRecord>& /* nsset */, string* /* nameserver */, string* account, DNSBackend** backend)
×
1480
{
1481
  // Check whether we have a configfile available.
12✔
1482
  if (getArg("autoprimary-config").empty())
12✔
1483
    return false;
1484

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

1493
  // Format:
1494
  // <ip> <accountname>
×
1495
  string line, sip, saccount;
1496
  while (getline(c_if, line)) {
×
1497
    std::istringstream ii(line);
×
1498
    ii >> sip;
×
1499
    if (sip == ipAddress) {
1500
      ii >> saccount;
×
1501
      break;
×
1502
    }
×
1503
  }
×
1504
  c_if.close();
×
1505

×
1506
  if (sip != ipAddress) { // ip not found in authorization list - reject
×
1507
    return false;
×
1508
  }
×
1509

1510
  // ip authorized as autoprimary - accept
12✔
1511
  *backend = this;
×
1512
  if (saccount.length() > 0)
12✔
1513
    *account = saccount.c_str();
12✔
1514

1515
  return true;
1516
}
1517

1518
BB2DomainInfo Bind2Backend::createDomainEntry(const ZoneName& domain)
1519
{
206✔
1520
  domainid_t newid = 1;
1521
  { // Find a free zone id nr.
1522
    auto state = s_state.read_lock();
176✔
1523
    if (!state->empty()) {
176✔
1524
      newid = state->rbegin()->d_id + 1;
176✔
1525
    }
176✔
1526
  }
176✔
1527

176!
1528
  BB2DomainInfo bbd;
176✔
1529
  bbd.d_kind = DomainInfo::Native;
176✔
1530
  bbd.d_id = newid;
176✔
1531
  bbd.d_records = std::make_shared<recordstorage_t>();
176✔
1532
  bbd.d_name = domain;
176✔
1533
  bbd.setCheckInterval(getArgAsNum("check-interval"));
1534

1535
  return bbd;
1,215✔
1536
}
1,215✔
1537

1,215✔
1538
bool Bind2Backend::createSecondaryDomain(const string& ipAddress, const ZoneName& domain, const string& /* nameserver */, const string& account)
1,215✔
1539
{
1540
  std::string domainname = domain.toStringNoDot();
1541

173✔
1542
  // Reject domain name if it embeds quotes; this may happen if 8bit-dns is
173✔
1543
  // used, and bind currently does not allow for character escapes in zone
173✔
1544
  // names.
173✔
1545
  if (domainname.find_first_of("\"") != std::string::npos) {
1546
    SLOG(g_log << Logger::Error << d_logprefix
1547
               << " Unable to accept autosecondary zone '" << domain
1548
               << "' from autoprimary " << ipAddress
1,388✔
1549
               << " due to unauthorized characters in domain name for bind configuration file"
1,388!
1550
               << endl,
1551
         d_slog->error(Logr::Error, "unauthorized characters in domain name for bind configuration file", "Unable to accept autosecondary zone", "zone", Logging::Loggable(domain), "autoprimary address", Logging::Loggable(ipAddress)));
1,388✔
1552
    throw PDNSException("Unauthorized characters in domain name for bind configuration file");
23✔
1553
  }
23✔
1554

23✔
1555
  string filename = getArg("autoprimary-destdir") + '/';
23!
1556
  if (domainname.empty()) {
1557
    filename.append("rootzone.");
1558
  }
23✔
1559
  else {
229✔
1560
    // Make sure the zone file name does not contain path separators.
206✔
1561
    filename.append(boost::replace_all_copy(domainname, "/", "\\047"));
229!
1562
  }
206✔
1563

206!
1564
  SLOG(g_log << Logger::Warning << d_logprefix
206✔
1565
             << " Writing bind config zone statement for autosecondary zone '" << domain
206✔
1566
             << "' from autoprimary " << ipAddress << endl,
206✔
1567
       d_slog->info(Logr::Warning, "Writing bind config zone statement for autosecondary zone", "zone", Logging::Loggable(domain), "autoprimary address", Logging::Loggable(ipAddress)));
206!
1568

206✔
1569
  {
206✔
1570
    auto lock = std::scoped_lock(s_autosecondary_config_lock);
1571

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

1582
    c_of << endl;
1583
    c_of << "# AutoSecondary zone '" << domainname << "' (added: " << nowTime() << ") (account: " << account << ')' << endl;
1584
    c_of << "zone \"" << domainname << "\" {" << endl;
1585
    c_of << "\ttype secondary;" << endl;
1586
    c_of << "\tfile \"" << filename << "\";" << endl;
1587
    c_of << "\tprimaries { " << ipAddress << "; };" << endl;
1588
    c_of << "};" << endl;
23✔
1589
    c_of.close();
1590
  }
23✔
1591

23✔
1592
  BB2DomainInfo bbd = createDomainEntry(domain);
1593
  bbd.d_kind = DomainInfo::Secondary;
1594
  bbd.d_primaries.emplace_back(ComboAddress(ipAddress, 53));
1595
  bbd.d_fileinfo.emplace_back(std::make_pair(filename, 0));
1596
  bbd.updateCtime();
1597
  safePutBBDomainInfo(bbd);
280✔
1598

1599
  return true;
1600
}
236✔
1601

236✔
1602
bool Bind2Backend::searchRecords(const string& pattern, size_t maxResults, vector<DNSResourceRecord>& result)
236✔
1603
{
236✔
1604
  SimpleMatch sm(pattern, true);
236✔
1605
  static bool mustlog = ::arg().mustDo("query-logging");
236✔
1606
  if (mustlog) {
236✔
1607
    SLOG(g_log << Logger::Warning << "Search for pattern '" << pattern << "'" << endl,
236✔
1608
         d_slog->info(Logr::Debug, "Search for pattern", "pattern", Logging::Loggable(pattern)));
236✔
1609
  }
236✔
1610

236✔
1611
  {
1612
    auto state = s_state.read_lock();
1613

1,740✔
1614
    for (const auto& i : *state) {
1,740✔
1615
      BB2DomainInfo h;
1,740✔
1616
      if (!safeGetBBDomainInfo(i.d_id, &h)) {
1,740✔
1617
        continue;
1618
      }
1619

220✔
1620
      if (!h.d_loaded) {
220✔
1621
        continue;
220✔
1622
      }
220✔
1623

1624
      shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
1625

1626
      for (recordstorage_t::const_iterator ri = rhandle->begin(); result.size() < maxResults && ri != rhandle->end(); ri++) {
1,960✔
1627
        const DNSName& domainName(i.d_name);
1,960!
1628
        DNSName name = ri->qname.empty() ? domainName : (ri->qname + domainName);
1629
        if (sm.match(name) || sm.match(ri->content)) {
1,960✔
1630
          DNSResourceRecord r;
1631
          r.qname = std::move(name);
1632
          r.domain_id = i.d_id;
1633
          r.content = ri->content;
1634
          r.qtype = ri->qtype;
1635
          r.ttl = ri->ttl;
1636
          r.auth = ri->auth;
1637
          result.push_back(std::move(r));
280✔
1638
        }
280✔
1639
      }
280✔
1640
    }
280✔
1641
  }
280✔
1642

280✔
1643
  return true;
280✔
1644
}
280✔
1645

280✔
1646
class Bind2Factory : public BackendFactory
280✔
1647
{
280✔
1648
public:
1649
  Bind2Factory() :
1650
    BackendFactory("bind") {}
1651

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

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

1671
  DNSBackend* makeMetadataOnly(const string& suffix = "") override
1672
  {
1673
    assertEmptySuffix(suffix);
1674
    return new Bind2Backend(suffix, false);
1675
  }
1676

1677
private:
1678
  void assertEmptySuffix(const string& suffix)
1679
  {
1680
    if (!suffix.empty())
1681
      throw PDNSException("launch= suffixes are not supported on the bindbackend");
1682
  }
1683
};
1684

1685
//! Magic class that is activated when the dynamic library is loaded
1686
class Bind2Loader
1687
{
1688
public:
1689
  Bind2Loader()
1690
  {
1691
    BackendMakers().report(std::make_unique<Bind2Factory>());
1692
    // If this module is not loaded dynamically at runtime, this code runs
1693
    // as part of a global constructor, before the structured logger has a
1694
    // chance to be set up, so fallback to simple logging.
1695
    g_log << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
1696
#ifndef REPRODUCIBLE
1697
          << " (" __DATE__ " " __TIME__ ")"
1698
#endif
1699
#ifdef HAVE_SQLITE3
1700
          << " (with bind-dnssec-db support)"
1701
#endif
1702
          << " reporting" << endl;
1703
  }
1704
};
1705
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