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

PowerDNS / pdns / 30431062990

pending completion
30431062990

Pull #17809

github

web-flow
Merge f1a5e11e2 into b6a44141f
Pull Request #17809: auth: domain transactions

43689 of 82764 branches covered (52.79%)

Branch coverage included in aggregate %.

121 of 248 new or added lines in 13 files covered. (48.79%)

129 existing lines in 21 files now uncovered.

127588 of 172805 relevant lines covered (73.83%)

7120530.07 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

104
  if (!d_checkinterval)
4,167!
105
    return true;
4,167✔
106

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

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

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

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

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

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

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

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

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

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

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

183
// NOLINTNEXTLINE(readability-identifier-length)
184
void Bind2Backend::setNotified(domainid_t id, uint32_t serial)
185
{
×
186
  BB2DomainInfo bbd;
×
NEW
187
  if (!safeGetBBDomainInfo(id, &bbd)) {
×
NEW
188
    return;
×
NEW
189
  }
×
190
  // Ignore pending domains unless we are the backend running the transaction
191
  // in which they are being created. This can't be done in safeGetBBDomainInfo
192
  // because it needs to be a static method.
NEW
193
  if (bbd.d_pending && bbd.d_id != d_transaction_id) {
×
194
    return;
×
NEW
195
  }
×
196
  bbd.d_lastnotified = serial;
×
197
  safePutBBDomainInfo(bbd);
×
198
}
×
199

200
// NOLINTNEXTLINE(readability-identifier-length)
201
void Bind2Backend::setLastCheck(domainid_t domain_id, time_t lastcheck)
202
{
72✔
203
  BB2DomainInfo bbd;
72✔
204
  if (!safeGetBBDomainInfo(domain_id, &bbd)) {
72!
NEW
205
    return;
×
NEW
206
  }
×
207
  // Ignore pending domains unless we are the backend running the transaction
208
  // in which they are being created. This can't be done in safeGetBBDomainInfo
209
  // because it needs to be a static method.
210
  if (bbd.d_pending && bbd.d_id != d_transaction_id) {
72!
NEW
211
    return;
×
UNCOV
212
  }
×
213
  bbd.d_lastcheck = lastcheck;
72✔
214
  safePutBBDomainInfo(bbd);
72✔
215
}
72✔
216

217
void Bind2Backend::setStale(domainid_t domain_id)
218
{
×
NEW
219
  setLastCheck(domain_id, 0);
×
220
}
×
221

222
void Bind2Backend::setFresh(domainid_t domain_id)
223
{
72✔
224
  setLastCheck(domain_id, time(nullptr));
72✔
225
}
72✔
226

227
bool Bind2Backend::startDomainCreationTransactionInternal(BB2DomainInfo& bbd)
228
{
72✔
229
  d_transaction_qname = bbd.d_name;
72✔
230
  d_transaction_id = bbd.d_id;
72✔
231
  d_transaction_tmpname = bbd.main_filename() + "XXXXXX";
72✔
232
  int fd = mkstemp(&d_transaction_tmpname.at(0));
72✔
233
  if (fd == -1) {
72!
NEW
234
    throw DBException("Unable to create a unique temporary zonefile '" + d_transaction_tmpname + "': " + stringerror());
×
NEW
235
  }
×
236

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

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

252
  return true;
72✔
253
}
72✔
254

255
bool Bind2Backend::startDomainCreationTransaction(const ZoneName& /* qname */, domainid_t domainId)
256
{
72✔
257
  d_transaction_tmpname.clear();
72✔
258
  d_transaction_id = UnknownDomainID;
72✔
259

260
  if (domainId == 0) {
72!
261
    throw DBException("domain_id 0 is invalid for this backend.");
×
262
  }
×
263

264
  BB2DomainInfo bbd;
72✔
265
  if (!safeGetBBDomainInfo(domainId, &bbd)) {
72!
NEW
266
    return false;
×
NEW
267
  }
×
268
  // Ignore pending domains since we don't have an active transaction at this
269
  // point, so we can't be the backend currently creating them.
270
  if (bbd.d_pending) {
72!
NEW
271
    return false;
×
NEW
272
  }
×
273
  return startDomainCreationTransactionInternal(bbd);
72✔
274
}
72✔
275

276
bool Bind2Backend::startDomainModificationTransaction(const ZoneName& /* qname */)
277
{
149✔
278
  d_transaction_tmpname.clear();
149✔
279
  d_transaction_id = UnknownDomainID;
149✔
280

281
  // No support for domain contents modification, except as a "delete and
282
  // recreate in its entirety" operation.
283
  return false;
149✔
284
}
149✔
285

286
bool Bind2Backend::commitTransaction()
287
{
221✔
288
  // d_transaction_id is only set to a valid domain id if we are actually
289
  // setting up a replacement zone file with the updated data.
290
  if (d_transaction_id == UnknownDomainID) {
221✔
291
    return false;
149✔
292
  }
149✔
293
  d_of.reset();
72✔
294

295
  BB2DomainInfo bbd;
72✔
296
  if (safeGetBBDomainInfo(d_transaction_id, &bbd)) {
72!
297
    if (rename(d_transaction_tmpname.c_str(), bbd.main_filename().c_str()) < 0) {
72!
298
      throw DBException("Unable to commit (rename to: '" + bbd.main_filename() + "') AXFRed zone: " + stringerror());
×
299
    }
×
300
    // If that domain was part of a transaction, we can finally mark it as
301
    // available to everyone.
302
    if (bbd.d_pending) {
72!
NEW
303
      bbd.d_pending = false;
×
NEW
304
      safePutBBDomainInfo(bbd);
×
NEW
305
    }
×
306
    queueReloadAndStore(bbd.d_id);
72✔
307
  }
72✔
308

309
  d_transaction_id = UnknownDomainID;
72✔
310

311
  return true;
72✔
312
}
72✔
313

314
bool Bind2Backend::abortTransaction()
315
{
×
316
  // d_transaction_id is only set to a valid domain id if we are actually
317
  // setting up a replacement zone file with the updated data.
318
  if (d_transaction_id != UnknownDomainID) {
×
NEW
319
    BB2DomainInfo bbd;
×
NEW
320
    if (safeGetBBDomainInfo(d_transaction_id, &bbd)) {
×
NEW
321
      if (bbd.d_pending) {
×
NEW
322
        safeRemoveBBDomainInfo(bbd.d_name);
×
NEW
323
      }
×
NEW
324
    }
×
325
    unlink(d_transaction_tmpname.c_str());
×
326
    d_of.reset();
×
327
    d_transaction_id = UnknownDomainID;
×
328
  }
×
329

330
  return true;
×
331
}
×
332

333
/** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */
334
static bool endsOn(const string& domain, const string& suffix)
335
{
416✔
336
  if (domain.size() <= suffix.size()) {
416✔
337
    return false;
52✔
338
  }
52✔
339

340
  string::size_type dpos = domain.size() - suffix.size() - 1;
364✔
341
  if (domain[dpos++] != '.') {
364✔
342
    return false;
88✔
343
  }
88✔
344
  // That dot might have been escaped. So we now need to count how many '\'
345
  // characters we can find in a row before it; if their number is odd, the
346
  // dot is escaped and we are not a proper suffix.
347
  size_t slashes{0};
276✔
348
  while (dpos >= 2 + slashes && domain.at(dpos - 2 - slashes) == '\\') {
276!
349
    ++slashes;
×
350
  }
×
351
  if ((slashes % 2) != 0) {
276!
352
    return false;
×
353
  }
×
354

355
  string::size_type spos = 0;
276✔
356
  for (; dpos < domain.size(); ++dpos, ++spos) {
3,928✔
357
    if (!pdns_iequals_ch(domain[dpos], suffix[spos])) {
3,664✔
358
      return false;
12✔
359
    }
12✔
360
  }
3,664✔
361

362
  return true;
264✔
363
}
276✔
364

365
/** strips a domain suffix from a domain */
366
static void stripDomainSuffix(string* qname, const ZoneName& zonename)
367
{
432✔
368
  std::string domain = zonename.operator const DNSName&().toString();
432✔
369

370
  if (domain.empty()) {
432!
371
    return;
×
372
  }
×
373
  if (pdns_iequals(*qname, domain)) {
432✔
374
    *qname = "@";
16✔
375
    return;
16✔
376
  }
16✔
377
  if (endsOn(*qname, domain)) {
416✔
378
    auto prefix = qname->size() - domain.size();
264✔
379
    qname->resize(prefix - 1); // also strip dot
264✔
380
  }
264✔
381
}
416✔
382

383
// Perform adequate escaping of characters which have special meaning in
384
// Bind zone files.
385
// Note that the input is supposed to be a DNSName::toString() - or any of
386
// its variants - so we assume \ and . have been correctly escaped by
387
// DNSName::appendEscapedLabel already.
388
static const std::string bindEscape(const std::string& name)
389
{
202,172✔
390
  std::string ret;
202,172✔
391
  std::array<char, 5> ebuf{};
202,172✔
392

393
  for (char letter : name) {
2,818,960✔
394
    switch (letter) {
2,818,960✔
395
    case '$':
×
396
    case '@':
×
397
    case '"':
×
398
    case ';':
×
399
    case '(':
×
400
    case ')':
×
401
      snprintf(ebuf.data(), ebuf.size(), "\\%03u", static_cast<unsigned char>(letter));
×
402
      ret += ebuf.data();
×
403
      break;
×
404
    default:
2,818,960!
405
      ret += letter;
2,818,960✔
406
      break;
2,818,960✔
407
    }
2,818,960✔
408
  }
2,818,960✔
409
  return ret;
202,172✔
410
}
202,172✔
411

412
bool Bind2Backend::feedRecord(const DNSResourceRecord& rr, const DNSName& /* ordername */, bool /* ordernameIsNSEC3 */)
413
{
202,805✔
414
  if (d_transaction_id == UnknownDomainID) {
202,805!
415
    throw DBException("Bind2Backend::feedRecord() called outside of transaction");
×
416
  }
×
417

418
  string qname;
202,805✔
419
  if (d_transaction_qname.empty()) {
202,805!
420
    qname = bindEscape(rr.qname.toString());
×
421
  }
×
422
  else if (rr.qname.isPartOf(d_transaction_qname)) {
202,805!
423
    if (rr.qname == d_transaction_qname.operator const DNSName&()) {
202,805✔
424
      qname = "@";
633✔
425
    }
633✔
426
    else {
202,172✔
427
      DNSName relName = rr.qname.makeRelative(d_transaction_qname);
202,172✔
428
      qname = bindEscape(relName.toStringNoDot());
202,172✔
429
    }
202,172✔
430
  }
202,805✔
431
  else {
×
432
    throw DBException("out-of-zone data '" + rr.qname.toLogString() + "' during AXFR of zone '" + d_transaction_qname.toLogString() + "'");
×
433
  }
×
434

435
  shared_ptr<DNSRecordContent> drc(DNSRecordContent::make(rr.qtype.getCode(), QClass::IN, rr.content));
202,805✔
436
  string content = drc->getZoneRepresentation();
202,805✔
437

438
  // SOA needs stripping too! XXX FIXME - also, this should not be here I think
439
  switch (rr.qtype.getCode()) {
202,805✔
440
  case QType::MX:
56✔
441
  case QType::SRV:
76✔
442
  case QType::CNAME:
208✔
443
  case QType::DNAME:
212✔
444
  case QType::NS:
432✔
445
    stripDomainSuffix(&content, d_transaction_qname);
432✔
446
    [[fallthrough]];
432✔
447
  default:
202,805✔
448
    if (d_of && *d_of) {
202,805!
449
      *d_of << qname << "\t" << rr.ttl << "\t" << rr.qtype.toString() << "\t" << content << endl;
202,805✔
450
    }
202,805✔
451
  }
202,805✔
452
  return true;
202,805✔
453
}
202,805✔
454

455
void Bind2Backend::getUpdatedPrimaries(vector<DomainInfo>& changedDomains, std::unordered_set<DNSName>& /* catalogs */, CatalogHashMap& /* catalogHashes */)
456
{
×
457
  vector<DomainInfo> consider;
×
458
  {
×
459
    auto state = s_state.read_lock();
×
460

NEW
461
    for (const auto& bbd : *state) {
×
462
      // Ignore pending domains unless we are the backend running the
463
      // transaction in which they are being created.
NEW
464
      if (bbd.d_pending && bbd.d_id != d_transaction_id) {
×
NEW
465
        continue;
×
NEW
466
      }
×
NEW
467
      if (bbd.d_kind != DomainInfo::Primary && this->alsoNotify.empty() && bbd.d_also_notify.empty()) {
×
UNCOV
468
        continue;
×
NEW
469
      }
×
470

NEW
471
      DomainInfo info;
×
NEW
472
      info.id = bbd.d_id;
×
NEW
473
      info.zone = bbd.d_name;
×
NEW
474
      info.last_check = bbd.d_lastcheck;
×
NEW
475
      info.notified_serial = bbd.d_lastnotified;
×
NEW
476
      info.backend = this;
×
NEW
477
      info.kind = DomainInfo::Primary;
×
NEW
478
      consider.push_back(std::move(info));
×
479
    }
×
480
  }
×
481

482
  SOAData soadata;
×
483
  for (DomainInfo& di : consider) {
×
484
    soadata.serial = 0;
×
485
    try {
×
486
      this->getSOA(di.zone, di.id, soadata); // we might not *have* a SOA yet, but this might trigger a load of it
×
487
    }
×
488
    catch (...) {
×
489
      continue;
×
490
    }
×
491
    if (di.notified_serial != soadata.serial) {
×
492
      BB2DomainInfo bbd;
×
493
      // Note that we don't need to filter pending domains here as the loop
494
      // initializing [consider] above has already done that filtering.
495
      if (safeGetBBDomainInfo(di.id, &bbd)) {
×
496
        bbd.d_lastnotified = soadata.serial;
×
497
        safePutBBDomainInfo(bbd);
×
498
      }
×
499
      if (di.notified_serial) { // don't do notification storm on startup
×
500
        di.serial = soadata.serial;
×
501
        changedDomains.push_back(std::move(di));
×
502
      }
×
503
    }
×
504
  }
×
505
}
×
506

507
void Bind2Backend::getAllDomains(vector<DomainInfo>* domains, bool getSerial, bool /* include_disabled */)
508
{
119✔
509
  SOAData soadata;
119✔
510

511
  // prevent deadlock by using getSOA() later on
512
  {
119✔
513
    auto state = s_state.read_lock();
119✔
514
    domains->reserve(state->size());
119✔
515

516
    for (const auto& i : *state) {
279✔
517
      DomainInfo di;
185✔
518
      di.id = i.d_id;
185✔
519
      di.zone = i.d_name;
185✔
520
      di.last_check = i.d_lastcheck;
185✔
521
      di.kind = i.d_kind;
185✔
522
      di.primaries = i.d_primaries;
185✔
523
      di.backend = this;
185✔
524
      domains->push_back(std::move(di));
185✔
525
    };
185✔
526
  }
119✔
527

528
  if (getSerial) {
119✔
529
    for (DomainInfo& di : *domains) {
1,554✔
530
      // do not corrupt di if domain supplied by another backend.
531
      if (di.backend != this)
1,554!
532
        continue;
1,554✔
533
      try {
×
534
        this->getSOA(di.zone, di.id, soadata);
×
535
      }
×
536
      catch (...) {
×
537
        continue;
×
538
      }
×
539
      di.serial = soadata.serial;
×
540
    }
×
541
  }
42✔
542
}
119✔
543

544
void Bind2Backend::getUnfreshSecondaryInfos(vector<DomainInfo>* unfreshDomains)
545
{
8✔
546
  vector<DomainInfo> domains;
8✔
547
  {
8✔
548
    auto state = s_state.read_lock();
8✔
549
    domains.reserve(state->size());
8✔
550
    for (const auto& i : *state) {
72✔
551
      if (i.d_kind != DomainInfo::Secondary)
72!
552
        continue;
×
553
      DomainInfo sd;
72✔
554
      sd.id = i.d_id;
72✔
555
      sd.zone = i.d_name;
72✔
556
      sd.primaries = i.d_primaries;
72✔
557
      sd.last_check = i.d_lastcheck;
72✔
558
      sd.backend = this;
72✔
559
      sd.kind = DomainInfo::Secondary;
72✔
560
      domains.push_back(std::move(sd));
72✔
561
    }
72✔
562
  }
8✔
563
  unfreshDomains->reserve(domains.size());
8✔
564

565
  for (DomainInfo& sd : domains) {
72✔
566
    SOAData soadata;
72✔
567
    soadata.refresh = 0;
72✔
568
    soadata.serial = 0;
72✔
569
    try {
72✔
570
      getSOA(sd.zone, sd.id, soadata); // we might not *have* a SOA yet
72✔
571
    }
72✔
572
    catch (...) {
72✔
573
    }
72✔
574
    sd.serial = soadata.serial;
72✔
575
    if (sd.last_check + soadata.refresh < time(nullptr))
72!
576
      unfreshDomains->push_back(std::move(sd));
72✔
577
  }
72✔
578
}
8✔
579

580
bool Bind2Backend::getDomainInfo(const ZoneName& domain, DomainInfo& info, bool getSerial)
581
{
1,099✔
582
  BB2DomainInfo bbd;
1,099✔
583
  if (!safeGetBBDomainInfo(domain, &bbd))
1,099✔
584
    return false;
648✔
585
  // Ignore pending domains unless we are the backend running the transaction
586
  // in which they are being created. This can't be done in safeGetBBDomainInfo
587
  // because it needs to be a static method.
588
  if (bbd.d_pending && bbd.d_id != d_transaction_id) {
451!
NEW
589
    return false;
×
NEW
590
  }
×
591

592
  info.id = bbd.d_id;
451✔
593
  info.zone = domain;
451✔
594
  info.primaries = bbd.d_primaries;
451✔
595
  info.last_check = bbd.d_lastcheck;
451✔
596
  info.backend = this;
451✔
597
  info.kind = bbd.d_kind;
451✔
598
  info.serial = 0;
451✔
599
  if (getSerial) {
451✔
600
    try {
141✔
601
      SOAData sd;
141✔
602
      sd.serial = 0;
141✔
603

604
      getSOA(bbd.d_name, bbd.d_id, sd); // we might not *have* a SOA yet
141✔
605
      info.serial = sd.serial;
141✔
606
    }
141✔
607
    catch (...) {
141✔
608
    }
72✔
609
  }
141✔
610

611
  return true;
451✔
612
}
451✔
613

614
void Bind2Backend::alsoNotifies(const ZoneName& domain, set<string>* ips)
615
{
4✔
616
  // combine global list with local list
617
  for (const auto& i : this->alsoNotify) {
4!
618
    (*ips).insert(i);
×
619
  }
×
620
  // check metadata too if available
621
  vector<string> meta;
4✔
622
  if (getDomainMetadata(domain, "ALSO-NOTIFY", meta)) {
4!
623
    for (const auto& str : meta) {
×
624
      (*ips).insert(str);
×
625
    }
×
626
  }
×
627
  auto state = s_state.read_lock();
4✔
628
  for (const auto& i : *state) {
4!
629
    if (i.d_name == domain) {
×
630
      for (const auto& it : i.d_also_notify) {
×
631
        (*ips).insert(it);
×
632
      }
×
633
      return;
×
634
    }
×
635
  }
×
636
}
4✔
637

638
// only parses, does NOT add to s_state!
639
void Bind2Backend::parseZoneFile(BB2DomainInfo* bbd)
640
{
2,749✔
641
  NSEC3PARAMRecordContent ns3pr;
2,749✔
642
  bool nsec3zone = false;
2,749✔
643
  if (d_hybrid) {
2,749!
644
    DNSSECKeeper dk(d_slog);
×
645
    nsec3zone = dk.getNSEC3PARAM(bbd->d_name, &ns3pr);
×
646
  }
×
647
  else
2,749✔
648
    nsec3zone = getNSEC3PARAMuncached(bbd->d_name, &ns3pr);
2,749✔
649

650
  auto records = std::make_shared<recordstorage_t>();
2,749✔
651
  ZoneParserTNG zpt(bbd->main_filename(), bbd->d_name, s_binddirectory, d_upgradeContent);
2,749✔
652
  zpt.setMaxGenerateSteps(::arg().asNum("max-generate-steps"));
2,749✔
653
  zpt.setMaxIncludes(::arg().asNum("max-include-depth"));
2,749✔
654
  DNSResourceRecord rr;
2,749✔
655
  string hashed;
2,749✔
656
  while (zpt.get(rr)) {
3,277,668✔
657
    if (rr.qtype.getCode() == QType::NSEC || rr.qtype.getCode() == QType::NSEC3 || rr.qtype.getCode() == QType::NSEC3PARAM)
3,274,919!
658
      continue; // we synthesise NSECs on demand
×
659

660
    insertRecord(records, bbd->d_name, rr.qname, rr.qtype, rr.content, rr.ttl, "");
3,274,919✔
661
  }
3,274,919✔
662
  fixupOrderAndAuth(records, bbd->d_name, nsec3zone, ns3pr);
2,749✔
663
  doEmptyNonTerminals(records, bbd->d_name, nsec3zone, ns3pr);
2,749✔
664
  bbd->d_fileinfo = zpt.getFileset();
2,749✔
665
  bbd->d_loaded = true;
2,749✔
666
  bbd->d_checknow = false;
2,749✔
667
  bbd->d_status = "parsed into memory at " + nowTime();
2,749✔
668
  bbd->d_records = LookButDontTouch<recordstorage_t>(std::move(records));
2,749✔
669
  bbd->d_nsec3zone = nsec3zone;
2,749✔
670
  bbd->d_nsec3param = std::move(ns3pr);
2,749✔
671
}
2,749✔
672

673
/** THIS IS AN INTERNAL FUNCTION! It does moadnsparser prio impedance matching
674
    Much of the complication is due to the efforts to benefit from std::string reference counting copy on write semantics */
675
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)
676
{
3,279,690✔
677
  Bind2DNSRecord bdr;
3,279,690✔
678
  bdr.qname = qname;
3,279,690✔
679

680
  if (zoneName.empty())
3,279,690!
681
    ;
×
682
  else if (bdr.qname.isPartOf(zoneName))
3,279,690✔
683
    bdr.qname.makeUsRelative(zoneName);
3,279,388✔
684
  else {
302✔
685
    string msg = "Trying to insert non-zone data, name='" + bdr.qname.toLogString() + "', qtype=" + qtype.toString() + ", zone='" + zoneName.toLogString() + "'";
302✔
686
    if (s_ignore_broken_records) {
302!
687
      SLOG(g_log << Logger::Warning << msg << " ignored" << endl,
302✔
688
           d_slog->info(Logr::Warning, "Non-zone data record ignored", "zone", Logging::Loggable(zoneName), "name", Logging::Loggable(bdr.qname), "qtype", Logging::Loggable(qtype)));
302✔
689
      return;
302✔
690
    }
302✔
691
    throw PDNSException(std::move(msg));
×
692
  }
302✔
693

694
  //  bdr.qname.swap(bdr.qname);
695

696
  if (!records->empty() && bdr.qname == boost::prior(records->end())->qname)
3,279,388✔
697
    bdr.qname = boost::prior(records->end())->qname;
8,890✔
698

699
  bdr.qname = bdr.qname;
3,279,388✔
700
  bdr.qtype = qtype.getCode();
3,279,388✔
701
  bdr.content = content;
3,279,388✔
702
  bdr.nsec3hash = hashed;
3,279,388✔
703

704
  if (auth != nullptr) // Set auth on empty non-terminals
3,279,388✔
705
    bdr.auth = *auth;
4,771✔
706
  else
3,274,617✔
707
    bdr.auth = true;
3,274,617✔
708

709
  bdr.ttl = ttl;
3,279,388✔
710
  records->insert(std::move(bdr));
3,279,388✔
711
}
3,279,388✔
712

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

717
  for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
718
    BB2DomainInfo bbd;
×
719
    ZoneName zone(*i);
×
720
    if (safeGetBBDomainInfo(zone, &bbd)) {
×
NEW
721
      if (bbd.d_pending) {
×
NEW
722
        ret << *i << ": not commited yet\n";
×
NEW
723
        continue;
×
NEW
724
      }
×
725
      Bind2Backend bb2;
×
726
      bb2.queueReloadAndStore(bbd.d_id);
×
727
      if (!safeGetBBDomainInfo(zone, &bbd)) // Read the *new* domain status
×
728
        ret << *i << ": [missing]\n";
×
729
      else
×
730
        ret << *i << ": " << (bbd.d_wasRejectedLastReload ? "[rejected]" : "") << "\t" << bbd.d_status << "\n";
×
731
      purgeAuthCaches(zone.operator const DNSName&().toString() + "$");
×
732
      DNSSECKeeper::clearMetaCache(zone);
×
733
    }
×
734
    else
×
NEW
735
      ret << *i << ": no such domain\n";
×
736
  }
×
737
  if (ret.str().empty())
×
738
    ret << "no domains reloaded";
×
739
  return ret.str();
×
740
}
×
741

742
string Bind2Backend::DLDomStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
743
{
27✔
744
  ostringstream ret;
27✔
745

746
  if (parts.size() > 1) {
27!
747
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
NEW
748
      ret << *i << ": ";
×
749
      BB2DomainInfo bbd;
×
750
      if (safeGetBBDomainInfo(ZoneName(*i), &bbd)) {
×
NEW
751
        if (bbd.d_pending) {
×
NEW
752
          ret << "not commited yet\n";
×
NEW
753
        }
×
NEW
754
        else {
×
NEW
755
          ret << (bbd.d_loaded ? "" : "[rejected]") << "\t" << bbd.d_status << "\n";
×
NEW
756
        }
×
757
      }
×
758
      else {
×
NEW
759
        ret << "no such domain\n";
×
760
      }
×
761
    }
×
762
  }
×
763
  else {
27✔
764
    auto state = s_state.read_lock();
27✔
765
    for (const auto& bbd : *state) {
235✔
766
      ret << bbd.d_name << ": ";
235✔
767
      if (bbd.d_pending) {
235!
NEW
768
        ret << "not commited yet\n";
×
NEW
769
      }
×
770
      else {
235✔
771
        ret << (bbd.d_loaded ? "" : "[rejected]") << "\t" << bbd.d_status << "\n";
235✔
772
      }
235✔
773
    }
235✔
774
  }
27✔
775

776
  if (ret.str().empty())
27!
777
    ret << "no domains passed";
×
778

779
  return ret.str();
27✔
780
}
27✔
781

782
static void printDomainExtendedStatus(ostringstream& ret, const BB2DomainInfo& info)
783
{
×
784
  ret << info.d_name << ": " << std::endl;
×
785
  ret << "\t Status: " << info.d_status << std::endl;
×
786
  ret << "\t Internal ID: " << info.d_id << std::endl;
×
787
  ret << "\t On-disk file: " << info.main_filename() << " (" << info.d_fileinfo.front().second << ")" << std::endl;
×
788
  ret << "\t Kind: ";
×
789
  switch (info.d_kind) {
×
790
  case DomainInfo::Primary:
×
791
    ret << "Primary";
×
792
    break;
×
793
  case DomainInfo::Secondary:
×
794
    ret << "Secondary";
×
795
    break;
×
796
  default:
×
797
    ret << "Native";
×
798
  }
×
799
  ret << std::endl;
×
800
  ret << "\t Primaries: " << std::endl;
×
801
  for (const auto& primary : info.d_primaries) {
×
802
    ret << "\t\t - " << primary.toStringWithPort() << std::endl;
×
803
  }
×
804
  ret << "\t Also Notify: " << std::endl;
×
805
  for (const auto& also : info.d_also_notify) {
×
806
    ret << "\t\t - " << also << std::endl;
×
807
  }
×
808
  ret << "\t Number of records: " << info.d_records.getEntriesCount() << std::endl;
×
809
  ret << "\t Loaded: " << info.d_loaded << std::endl;
×
810
  ret << "\t Check now: " << info.d_checknow << std::endl;
×
811
  ret << "\t Check interval: " << info.getCheckInterval() << std::endl;
×
812
  ret << "\t Last check: " << info.d_lastcheck << std::endl;
×
813
  ret << "\t Last notified: " << info.d_lastnotified << std::endl;
×
814
}
×
815

816
string Bind2Backend::DLDomExtendedStatusHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
817
{
×
818
  ostringstream ret;
×
819

820
  if (parts.size() > 1) {
×
821
    for (auto i = parts.begin() + 1; i < parts.end(); ++i) {
×
822
      BB2DomainInfo bbd;
×
823
      if (safeGetBBDomainInfo(ZoneName(*i), &bbd)) {
×
NEW
824
        if (bbd.d_pending) {
×
NEW
825
          ret << *i << ": not commited yet\n";
×
NEW
826
          continue;
×
NEW
827
        }
×
828
        printDomainExtendedStatus(ret, bbd);
×
829
      }
×
830
      else {
×
NEW
831
        ret << *i << ": no such domain" << std::endl;
×
832
      }
×
833
    }
×
834
  }
×
835
  else {
×
836
    auto rstate = s_state.read_lock();
×
837
    for (const auto& state : *rstate) {
×
838
      printDomainExtendedStatus(ret, state);
×
839
    }
×
840
  }
×
841

842
  if (ret.str().empty()) {
×
843
    ret << "no domains passed" << std::endl;
×
844
  }
×
845

846
  return ret.str();
×
847
}
×
848

849
string Bind2Backend::DLListRejectsHandler(const vector<string>& /* parts */, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
850
{
×
851
  ostringstream ret;
×
852
  auto rstate = s_state.read_lock();
×
853
  for (const auto& i : *rstate) {
×
854
    if (!i.d_loaded)
×
855
      ret << i.d_name << "\t" << i.d_status << endl;
×
856
  }
×
857
  return ret.str();
×
858
}
×
859

860
string Bind2Backend::DLAddDomainHandler(const vector<string>& parts, Utility::pid_t /* ppid */, Logr::log_t /* slog */)
861
{
12✔
862
  if (parts.size() < 3)
12!
863
    return "ERROR: Domain name and zone filename are required";
×
864

865
  ZoneName domainname(parts[1]);
12✔
866
  const string& filename = parts[2];
12✔
867
  BB2DomainInfo bbd;
12✔
868
  if (safeGetBBDomainInfo(domainname, &bbd)) {
12✔
869
    if (bbd.d_pending) {
6!
NEW
870
      return "Not commited yet";
×
NEW
871
    }
×
872
    return "Already loaded";
6✔
873
  }
6✔
874

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

878
  struct stat buf;
6✔
879
  if (stat(filename.c_str(), &buf) != 0)
6!
880
    return "Unable to load zone " + domainname.toLogString() + " from " + filename + ": " + strerror(errno);
×
881

882
  Bind2Backend bb2; // createdomainentry needs access to our configuration
6✔
883
  bbd = bb2.createDomainEntry(domainname);
6✔
884
  bbd.d_fileinfo.emplace_back(std::make_pair(filename, buf.st_ctime));
6✔
885
  bbd.d_checknow = true;
6✔
886
  bbd.d_loaded = true;
6✔
887
  bbd.d_lastcheck = 0;
6✔
888
  bbd.d_status = "parsing into memory";
6✔
889

890
  safePutBBDomainInfo(bbd);
6✔
891

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

894
  SLOG(g_log << Logger::Warning << "Zone " << domainname << " loaded" << endl,
6!
895
       bb2.d_slog->info(Logr::Info, "Zone loaded", "zone", Logging::Loggable(domainname), "file", Logging::Loggable(filename)));
6✔
896
  return "Loaded zone " + domainname.toLogString() + " from " + filename;
6✔
897
}
6✔
898

899
Bind2Backend::Bind2Backend(const string& suffix, bool loadZones)
900
{
3,511✔
901
  d_getAllDomainMetadataQuery_stmt = nullptr;
3,511✔
902
  d_getDomainMetadataQuery_stmt = nullptr;
3,511✔
903
  d_deleteDomainMetadataQuery_stmt = nullptr;
3,511✔
904
  d_insertDomainMetadataQuery_stmt = nullptr;
3,511✔
905
  d_getDomainKeysQuery_stmt = nullptr;
3,511✔
906
  d_deleteDomainKeyQuery_stmt = nullptr;
3,511✔
907
  d_insertDomainKeyQuery_stmt = nullptr;
3,511✔
908
  d_GetLastInsertedKeyIdQuery_stmt = nullptr;
3,511✔
909
  d_activateDomainKeyQuery_stmt = nullptr;
3,511✔
910
  d_deactivateDomainKeyQuery_stmt = nullptr;
3,511✔
911
  d_getTSIGKeyQuery_stmt = nullptr;
3,511✔
912
  d_setTSIGKeyQuery_stmt = nullptr;
3,511✔
913
  d_deleteTSIGKeyQuery_stmt = nullptr;
3,511✔
914
  d_getTSIGKeysQuery_stmt = nullptr;
3,511✔
915

916
  setArgPrefix("bind" + suffix);
3,511✔
917
  d_logprefix = "[bind" + suffix + "backend]";
3,511✔
918
  if (g_slogStructured) {
3,511✔
919
    d_slog = g_slog->withName("bind" + suffix);
669✔
920
    d_handle.setSLog(d_slog);
669✔
921
  }
669✔
922
  d_hybrid = mustDo("hybrid");
3,511✔
923
  if (d_hybrid && g_zoneCache.isEnabled()) {
3,511!
924
    throw PDNSException("bind-hybrid and the zone cache currently interoperate badly. Please disable the zone cache or stop using bind-hybrid");
×
925
  }
×
926

927
  d_transaction_id = UnknownDomainID;
3,511✔
928
  s_ignore_broken_records = mustDo("ignore-broken-records");
3,511✔
929
  d_upgradeContent = ::arg().mustDo("upgrade-unknown-types");
3,511✔
930

931
  if (!loadZones && d_hybrid)
3,511!
932
    return;
×
933

934
  auto lock = std::scoped_lock(s_startup_lock);
3,511✔
935

936
  setupDNSSEC();
3,511✔
937
  if (s_first == 0) {
3,511✔
938
    return;
2,732✔
939
  }
2,732✔
940

941
  if (loadZones) {
779✔
942
    loadConfig();
317✔
943
    s_first = 0;
317✔
944
  }
317✔
945

946
  DynListener::registerFunc("BIND-ADD-ZONE", &DLAddDomainHandler, "bindbackend: add zone", "<domain> <filename>");
779✔
947
  DynListener::registerFunc("BIND-DOMAIN-EXTENDED-STATUS", &DLDomExtendedStatusHandler, "bindbackend: list the extended status of all domains", "[domains]");
779✔
948
  DynListener::registerFunc("BIND-DOMAIN-STATUS", &DLDomStatusHandler, "bindbackend: list status of all domains", "[domains]");
779✔
949
  DynListener::registerFunc("BIND-LIST-REJECTS", &DLListRejectsHandler, "bindbackend: list rejected domains");
779✔
950
  DynListener::registerFunc("BIND-RELOAD-NOW", &DLReloadNowHandler, "bindbackend: reload domains", "<domains>");
779✔
951
}
779✔
952

953
Bind2Backend::~Bind2Backend()
954
{
3,385✔
955
  freeStatements();
3,385✔
956
} // deallocate statements
3,385✔
957

958
void Bind2Backend::rediscover(string* status)
959
{
×
960
  loadConfig(status);
×
961
}
×
962

963
void Bind2Backend::reload()
964
{
×
965
  auto state = s_state.write_lock();
×
966
  for (const auto& i : *state) {
×
967
    i.d_checknow = true; // being a bit cheeky here, don't index state_t on this (mutable)
×
968
  }
×
969
}
×
970

971
void Bind2Backend::fixupOrderAndAuth(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
972
{
2,677✔
973
  bool skip;
2,677✔
974
  DNSName shorter;
2,677✔
975
  set<DNSName> nssets, dssets;
2,677✔
976

977
  for (const auto& bdr : *records) {
3,274,617✔
978
    if (!bdr.qname.isRoot() && bdr.qtype == QType::NS)
3,274,617✔
979
      nssets.insert(bdr.qname);
3,010✔
980
    else if (bdr.qtype == QType::DS)
3,271,607✔
981
      dssets.insert(bdr.qname);
499✔
982
  }
3,274,617✔
983

984
  for (auto iter = records->begin(); iter != records->end(); iter++) {
3,277,294✔
985
    skip = false;
3,274,617✔
986
    shorter = iter->qname;
3,274,617✔
987

988
    if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
3,274,617!
989
      do {
3,273,507✔
990
        if (nssets.count(shorter) != 0u) {
3,273,507✔
991
          skip = true;
1,359✔
992
          break;
1,359✔
993
        }
1,359✔
994
      } while (shorter.chopOff() && !iter->qname.isRoot());
3,273,507!
995
    }
3,263,450✔
996

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

999
    if (!skip && nsec3zone && iter->qtype != QType::RRSIG && (iter->auth || (iter->qtype == QType::NS && (ns3pr.d_flags == 0u)) || (dssets.count(iter->qname) != 0u))) {
3,274,617✔
1000
      Bind2DNSRecord bdr = *iter;
1,439,658✔
1001
      bdr.nsec3hash = toBase32Hex(hashQNameWithSalt(ns3pr, bdr.qname + zoneName.operator const DNSName&()));
1,439,658✔
1002
      records->replace(iter, bdr);
1,439,658✔
1003
    }
1,439,658✔
1004

1005
    // cerr<<iter->qname<<"\t"<<QType(iter->qtype).toString()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
1006
  }
3,274,617✔
1007
}
2,677✔
1008

1009
void Bind2Backend::doEmptyNonTerminals(std::shared_ptr<recordstorage_t>& records, const ZoneName& zoneName, bool nsec3zone, const NSEC3PARAMRecordContent& ns3pr)
1010
{
2,677✔
1011
  bool auth = false;
2,677✔
1012
  DNSName shorter;
2,677✔
1013
  std::unordered_set<DNSName> qnames;
2,677✔
1014
  std::unordered_map<DNSName, bool> nonterm;
2,677✔
1015

1016
  uint32_t maxent = ::arg().asNum("max-ent-entries");
2,677✔
1017

1018
  for (const auto& bdr : *records)
2,677✔
1019
    qnames.insert(bdr.qname);
3,274,617✔
1020

1021
  for (const auto& bdr : *records) {
3,274,617✔
1022

1023
    if (!bdr.auth && bdr.qtype == QType::NS)
3,274,617✔
1024
      auth = (!nsec3zone || (ns3pr.d_flags == 0u));
3,010✔
1025
    else
3,271,607✔
1026
      auth = bdr.auth;
3,271,607✔
1027

1028
    shorter = bdr.qname;
3,274,617✔
1029
    while (shorter.chopOff()) {
6,549,483✔
1030
      if (qnames.count(shorter) == 0u) {
3,274,866✔
1031
        if (!(maxent)) {
9,891!
1032
          SLOG(g_log << Logger::Error << "Zone '" << zoneName << "' has too many empty non terminals." << endl,
×
1033
               d_slog->info(Logr::Error, "Zone has too many empty non terminals.", "zone", Logging::Loggable(zoneName)));
×
1034
          return;
×
1035
        }
×
1036

1037
        if (nonterm.count(shorter) == 0u) {
9,891✔
1038
          nonterm.emplace(shorter, auth);
4,771✔
1039
          --maxent;
4,771✔
1040
        }
4,771✔
1041
        else if (auth)
5,120✔
1042
          nonterm[shorter] = true;
5,024✔
1043
      }
9,891✔
1044
    }
3,274,866✔
1045
  }
3,274,617✔
1046

1047
  DNSResourceRecord rr;
2,677✔
1048
  rr.qtype = "#0";
2,677✔
1049
  rr.content = "";
2,677✔
1050
  rr.ttl = 0;
2,677✔
1051
  for (auto& nt : nonterm) {
4,784✔
1052
    string hashed;
4,771✔
1053
    rr.qname = nt.first + zoneName.operator const DNSName&();
4,771✔
1054
    if (nsec3zone && nt.second)
4,771✔
1055
      hashed = toBase32Hex(hashQNameWithSalt(ns3pr, rr.qname));
1,853✔
1056
    insertRecord(records, zoneName, rr.qname, rr.qtype, rr.content, rr.ttl, hashed, &nt.second);
4,771✔
1057

1058
    // cerr<<rr.qname<<"\t"<<rr.qtype.toString()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
1059
  }
4,771✔
1060
}
2,677✔
1061

1062
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
1063
{
317✔
1064
  static domainid_t domain_id = 1;
317✔
1065

1066
  if (!getArg("config").empty()) {
317!
1067
    BindParser BP;
317✔
1068
    try {
317✔
1069
      BP.parse(getArg("config"));
317✔
1070
    }
317✔
1071
    catch (PDNSException& ae) {
317✔
1072
      SLOG(g_log << Logger::Error << "Error parsing bind configuration: " << ae.reason << endl,
×
1073
           d_slog->error(Logr::Error, ae.reason, "Error parsing bind configuration"));
×
1074
      throw;
×
1075
    }
×
1076

1077
    vector<BindDomainInfo> domains = BP.getDomains();
317✔
1078
    this->alsoNotify = BP.getAlsoNotify();
317✔
1079

1080
    s_binddirectory = BP.getDirectory();
317✔
1081
    //    ZP.setDirectory(d_binddirectory);
1082

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

1086
    set<ZoneName> oldnames;
317✔
1087
    set<ZoneName> newnames;
317✔
1088
    {
317✔
1089
      auto state = s_state.read_lock();
317✔
1090
      for (const BB2DomainInfo& bbd : *state) {
317!
1091
        oldnames.insert(bbd.d_name);
×
1092
      }
×
1093
    }
317✔
1094
    int rejected = 0;
317✔
1095
    int newdomains = 0;
317✔
1096

1097
    struct stat st;
317✔
1098

1099
    for (auto& domain : domains) {
2,803✔
1100
      if (stat(domain.filename.c_str(), &st) == 0) {
2,671✔
1101
        domain.d_dev = st.st_dev;
2,599✔
1102
        domain.d_ino = st.st_ino;
2,599✔
1103
      }
2,599✔
1104
    }
2,671✔
1105

1106
    sort(domains.begin(), domains.end()); // put stuff in inode order
317✔
1107
    for (const auto& domain : domains) {
2,803✔
1108
      if (!(domain.hadFileDirective)) {
2,671!
1109
        SLOG(g_log << Logger::Warning << d_logprefix << " Zone '" << domain.name << "' has no 'file' directive set in " << getArg("config") << endl,
×
1110
             d_slog->info(Logr::Warning, "Zone has no 'file' directive set", "zone", Logging::Loggable(domain.name), "filename", Logging::Loggable(getArg("config"))));
×
1111
        rejected++;
×
1112
        continue;
×
1113
      }
×
1114

1115
      if (domain.type.empty()) {
2,671!
1116
        SLOG(g_log << Logger::Notice << d_logprefix << " Zone '" << domain.name << "' has no type specified, assuming 'native'" << endl,
×
1117
             d_slog->info(Logr::Notice, "Zone has no type specified, assuming 'native'", "zone", Logging::Loggable(domain.name)));
×
1118
      }
×
1119
      if (domain.type != "primary" && domain.type != "secondary" && domain.type != "native" && !domain.type.empty() && domain.type != "master" && domain.type != "slave") {
2,671!
1120
        SLOG(g_log << Logger::Warning << d_logprefix << " Warning! Skipping zone '" << domain.name << "' because type '" << domain.type << "' is invalid" << endl,
×
1121
             d_slog->info(Logr::Warning, "Skipping zone because type is invalid", "zone", Logging::Loggable(domain.name), "type", Logging::Loggable(domain.type)));
×
1122
        rejected++;
×
1123
        continue;
×
1124
      }
×
1125

1126
      BB2DomainInfo bbd;
2,671✔
1127
      bool isNew = false;
2,671✔
1128

1129
      if (safeGetBBDomainInfo(domain.name, &bbd)) {
2,671!
NEW
1130
        if (bbd.d_pending) {
×
NEW
1131
          SLOG(g_log << Logger::Warning << d_logprefix << " Warning! Skipping zone '" << domain.name << "' because it is not commited yet" << endl,
×
NEW
1132
               d_slog->info(Logr::Warning, "Skipping zone because it is not commited yet", "zone", Logging::Loggable(domain.name)));
×
NEW
1133
          rejected++;
×
NEW
1134
          continue;
×
NEW
1135
        }
×
NEW
1136
      }
×
1137
      else {
2,671✔
1138
        isNew = true;
2,671✔
1139
        bbd.d_id = domain_id++;
2,671✔
1140
        bbd.setCheckInterval(getArgAsNum("check-interval"));
2,671✔
1141
        bbd.d_lastnotified = 0;
2,671✔
1142
        bbd.d_loaded = false;
2,671✔
1143
      }
2,671✔
1144

1145
      // overwrite what we knew about the domain
1146
      bbd.d_name = domain.name;
2,671✔
1147
      bool filenameChanged = bbd.d_fileinfo.empty() || (bbd.main_filename() != domain.filename);
2,671!
1148
      bool addressesChanged = (bbd.d_primaries != domain.primaries || bbd.d_also_notify != domain.alsoNotify);
2,671!
1149
      // Preserve existing fileinfo in case we won't reread anything.
1150
      if (filenameChanged) {
2,671!
1151
        bbd.d_fileinfo.clear();
2,671✔
1152
        bbd.d_fileinfo.emplace_back(std::make_pair(domain.filename, 0));
2,671✔
1153
      }
2,671✔
1154
      bbd.d_primaries = domain.primaries;
2,671✔
1155
      bbd.d_also_notify = domain.alsoNotify;
2,671✔
1156

1157
      DomainInfo::DomainKind kind = DomainInfo::Native;
2,671✔
1158
      if (domain.type == "primary" || domain.type == "master") {
2,671!
1159
        kind = DomainInfo::Primary;
2,599✔
1160
      }
2,599✔
1161
      if (domain.type == "secondary" || domain.type == "slave") {
2,671!
1162
        kind = DomainInfo::Secondary;
72✔
1163
      }
72✔
1164

1165
      bool kindChanged = (bbd.d_kind != kind);
2,671✔
1166
      bbd.d_kind = kind;
2,671✔
1167

1168
      newnames.insert(bbd.d_name);
2,671✔
1169
      if (filenameChanged || !bbd.d_loaded || !bbd.current()) {
2,671!
1170
        SLOG(g_log << Logger::Info << d_logprefix << " parsing '" << domain.name << "' from file '" << domain.filename << "'" << endl,
2,671✔
1171
             d_slog->info(Logr::Info, "Parsing zone from file", "zone", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
2,671✔
1172

1173
        try {
2,671✔
1174
          parseZoneFile(&bbd);
2,671✔
1175
        }
2,671✔
1176
        catch (PDNSException& ae) {
2,671✔
1177
          ostringstream msg;
×
1178
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.reason;
×
1179

1180
          if (status != nullptr)
×
1181
            *status += msg.str();
×
1182
          bbd.d_status = msg.str();
×
1183

1184
          SLOG(g_log << Logger::Warning << d_logprefix << msg.str() << endl,
×
1185
               d_slog->error(Logr::Error, ae.reason, "Error in zone file", "zone", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
×
1186
          rejected++;
×
1187
        }
×
1188
        catch (std::system_error& ae) {
2,671✔
1189
          ostringstream msg;
72✔
1190
          bool missingNewSecondary = ae.code().value() == ENOENT && isNew && kind == DomainInfo::Secondary;
72!
1191
          if (missingNewSecondary) {
72!
1192
            msg << " error at " + nowTime() << " no file found for new secondary domain '" << domain.name << "'. Has not been AXFR'd yet";
72✔
1193
          }
72✔
1194
          else {
×
1195
            msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
×
1196
          }
×
1197

1198
          if (status != nullptr)
72!
1199
            *status += msg.str();
×
1200
          bbd.d_status = msg.str();
72✔
1201
          SLOG(
72!
1202
            g_log << Logger::Warning << d_logprefix << msg.str() << endl,
72✔
1203
            if (missingNewSecondary) {
72✔
1204
              d_slog->error(Logr::Warning, ae.what(), "Secondary domain has not been AXFR'd yet", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename));
72✔
1205
            } else {
72✔
1206
              d_slog->error(Logr::Warning, ae.what(), "Parse error", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename));
72✔
1207
            });
72✔
1208
          rejected++;
72✔
1209
        }
72✔
1210
        catch (std::exception& ae) {
2,671✔
1211
          ostringstream msg;
×
1212
          msg << " error at " + nowTime() + " parsing '" << domain.name << "' from file '" << domain.filename << "': " << ae.what();
×
1213

1214
          if (status != nullptr)
×
1215
            *status += msg.str();
×
1216
          bbd.d_status = msg.str();
×
1217

1218
          SLOG(g_log << Logger::Warning << d_logprefix << msg.str() << endl,
×
1219
               d_slog->error(Logr::Warning, ae.what(), "Parse error", "domain", Logging::Loggable(domain.name), "file", Logging::Loggable(domain.filename)));
×
1220
          rejected++;
×
1221
        }
×
1222
        safePutBBDomainInfo(bbd);
2,671✔
1223
      }
2,671✔
1224
      else if (addressesChanged || kindChanged) {
×
1225
        safePutBBDomainInfo(bbd);
×
1226
      }
×
1227
    }
2,671✔
1228
    vector<ZoneName> diff;
317✔
1229

1230
    set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
317✔
1231
    unsigned int remdomains = diff.size();
317✔
1232

1233
    for (const ZoneName& name : diff) {
317!
1234
      safeRemoveBBDomainInfo(name);
×
1235
    }
×
1236

1237
    // count number of entirely new domains
1238
    diff.clear();
317✔
1239
    set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
317✔
1240
    newdomains = diff.size();
317✔
1241

1242
    ostringstream msg;
317✔
1243
    msg << " Done parsing domains, " << rejected << " rejected, " << newdomains << " new, " << remdomains << " removed";
317✔
1244
    if (status != nullptr)
317!
1245
      *status = msg.str();
×
1246

1247
    SLOG(
317!
1248
      g_log << Logger::Error << d_logprefix << msg.str() << endl,
317✔
1249
      if (rejected == 0) {
317✔
1250
        d_slog->info(Logr::Info, "Done parsing domains", "new", Logging::Loggable(newdomains), "removed", Logging::Loggable(remdomains));
317✔
1251
      } else {
317✔
1252
        d_slog->info(Logr::Error, "Done parsing domains", "new", Logging::Loggable(newdomains), "removed", Logging::Loggable(remdomains), "rejected", Logging::Loggable(rejected));
317✔
1253
      });
317✔
1254
  }
317✔
1255
}
317✔
1256

1257
// NOLINTNEXTLINE(readability-identifier-length)
1258
void Bind2Backend::queueReloadAndStore(domainid_t id)
1259
{
78✔
1260
  BB2DomainInfo bbold;
78✔
1261
  try {
78✔
1262
    if (!safeGetBBDomainInfo(id, &bbold) || bbold.d_pending)
78!
1263
      return;
×
1264
    bbold.d_checknow = false;
78✔
1265
    BB2DomainInfo bbnew(bbold);
78✔
1266
    /* make sure that nothing will be able to alter the existing records,
1267
       we will load them from the zone file instead */
1268
    bbnew.d_records = LookButDontTouch<recordstorage_t>();
78✔
1269
    parseZoneFile(&bbnew);
78✔
1270
    bbnew.d_wasRejectedLastReload = false;
78✔
1271
    safePutBBDomainInfo(bbnew);
78✔
1272
    SLOG(g_log << Logger::Warning << "Zone '" << bbnew.d_name << "' (" << bbnew.main_filename() << ") reloaded" << endl,
78✔
1273
         d_slog->info(Logr::Info, "Zone reloaded", "zone", Logging::Loggable(bbnew.d_name), "file", Logging::Loggable(bbnew.main_filename())));
78✔
1274
  }
78✔
1275
  catch (PDNSException& ae) {
78✔
1276
    ostringstream msg;
×
1277
    msg << " error at " + nowTime() + " parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.reason;
×
1278
    SLOG(g_log << Logger::Warning << "Error parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.reason << endl,
×
1279
         d_slog->error(Logr::Error, ae.reason, "Error reloading zone", "zone", Logging::Loggable(bbold.d_name), "file", Logging::Loggable(bbold.main_filename())));
×
1280
    bbold.d_status = msg.str();
×
1281
    bbold.d_lastcheck = time(nullptr);
×
1282
    bbold.d_wasRejectedLastReload = true;
×
1283
    safePutBBDomainInfo(bbold);
×
1284
  }
×
1285
  catch (std::exception& ae) {
78✔
1286
    ostringstream msg;
×
1287
    msg << " error at " + nowTime() + " parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.what();
×
1288
    SLOG(g_log << Logger::Warning << "Error parsing '" << bbold.d_name << "' from file '" << bbold.main_filename() << "': " << ae.what() << endl,
×
1289
         d_slog->error(Logr::Error, ae.what(), "Error reloading zone", "zone", Logging::Loggable(bbold.d_name), "file", Logging::Loggable(bbold.main_filename())));
×
1290
    bbold.d_status = msg.str();
×
1291
    bbold.d_lastcheck = time(nullptr);
×
1292
    bbold.d_wasRejectedLastReload = true;
×
1293
    safePutBBDomainInfo(bbold);
×
1294
  }
×
1295
}
78✔
1296

1297
bool Bind2Backend::findBeforeAndAfterUnhashed(std::shared_ptr<const recordstorage_t>& records, const DNSName& qname, DNSName& /* unhashed */, DNSName& before, DNSName& after)
1298
{
2,748✔
1299
  // for(const auto& record: *records)
1300
  //   cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
1301

1302
  recordstorage_t::const_iterator iterBefore, iterAfter;
2,748✔
1303

1304
  iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
2,748✔
1305

1306
  if (iterBefore != records->begin())
2,748!
1307
    --iterBefore;
2,748✔
1308
  while ((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
3,277✔
1309
    --iterBefore;
529✔
1310
  before = iterBefore->qname;
2,748✔
1311

1312
  if (iterAfter == records->end()) {
2,748✔
1313
    iterAfter = records->begin();
376✔
1314
  }
376✔
1315
  else {
2,372✔
1316
    while ((!iterAfter->auth && iterAfter->qtype != QType::NS) || !iterAfter->qtype) {
3,581✔
1317
      ++iterAfter;
1,209✔
1318
      if (iterAfter == records->end()) {
1,209!
1319
        iterAfter = records->begin();
×
1320
        break;
×
1321
      }
×
1322
    }
1,209✔
1323
  }
2,372✔
1324
  after = iterAfter->qname;
2,748✔
1325

1326
  return true;
2,748✔
1327
}
2,748✔
1328

1329
// NOLINTNEXTLINE(readability-identifier-length)
1330
bool Bind2Backend::getBeforeAndAfterNamesAbsolute(domainid_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
1331
{
7,112✔
1332
  BB2DomainInfo bbd;
7,112✔
1333
  if (!safeGetBBDomainInfo(id, &bbd))
7,112!
1334
    return false;
×
1335
  // Ignore pending domains unless we are the backend running the transaction
1336
  // in which they are being created. This can't be done in safeGetBBDomainInfo
1337
  // because it needs to be a static method.
1338
  if (bbd.d_pending && bbd.d_id != d_transaction_id) {
7,112!
NEW
1339
    return false;
×
NEW
1340
  }
×
1341

1342
  shared_ptr<const recordstorage_t> records = bbd.d_records.get();
7,112✔
1343
  if (!bbd.d_nsec3zone) {
7,112✔
1344
    return findBeforeAndAfterUnhashed(records, qname, unhashed, before, after);
2,748✔
1345
  }
2,748✔
1346
  else {
4,364✔
1347
    const auto& hashindex = boost::multi_index::get<NSEC3Tag>(*records);
4,364✔
1348

1349
    // for(auto iter = first; iter != hashindex.end(); iter++)
1350
    //  cerr<<iter->nsec3hash<<endl;
1351

1352
    auto first = hashindex.upper_bound("");
4,364✔
1353
    auto iter = hashindex.upper_bound(qname.toStringNoDot());
4,364✔
1354

1355
    if (iter == hashindex.end()) {
4,364✔
1356
      --iter;
358✔
1357
      before = DNSName(iter->nsec3hash);
358✔
1358
      after = DNSName(first->nsec3hash);
358✔
1359
    }
358✔
1360
    else {
4,006✔
1361
      after = DNSName(iter->nsec3hash);
4,006✔
1362
      if (iter != first)
4,006✔
1363
        --iter;
3,932✔
1364
      else
74✔
1365
        iter = --hashindex.end();
74✔
1366
      before = DNSName(iter->nsec3hash);
4,006✔
1367
    }
4,006✔
1368
    unhashed = iter->qname + bbd.d_name.operator const DNSName&();
4,364✔
1369

1370
    return true;
4,364✔
1371
  }
4,364✔
1372
}
7,112✔
1373

1374
void Bind2Backend::lookup(const QType& qtype, const DNSName& qname, domainid_t zoneId, DNSPacket* /* pkt_p */)
1375
{
4,197✔
1376
  d_handle.reset();
4,197✔
1377

1378
  static bool mustlog = ::arg().mustDo("query-logging");
4,197✔
1379

1380
  bool found = false;
4,197✔
1381
  ZoneName domain;
4,197✔
1382
  BB2DomainInfo bbd;
4,197✔
1383

1384
  if (mustlog) {
4,197!
1385
    SLOG(g_log << Logger::Warning << "Lookup for '" << qtype.toString() << "' of '" << qname << "' within zoneID " << zoneId << endl,
×
1386
         d_slog->info(Logr::Warning, "Record lookup", "name", Logging::Loggable(qname), "qtype", Logging::Loggable(qtype), "zone id", Logging::Loggable(zoneId)));
×
1387
  }
×
1388

1389
  if (zoneId != UnknownDomainID) {
4,197✔
1390
    found = safeGetBBDomainInfo(zoneId, &bbd) && qname.isPartOf(bbd.d_name);
3,585!
1391
    // Ignore pending domains unless we are the backend running the transaction
1392
    // in which they are being created. This can't be done in safeGetBBDomainInfo
1393
    // because it needs to be a static method.
1394
    if (found && bbd.d_pending && bbd.d_id != d_transaction_id) {
3,585!
NEW
1395
      found = false;
×
NEW
1396
    }
×
1397
    if (found) {
3,585!
1398
      domain = std::move(bbd.d_name);
3,585✔
1399
    }
3,585✔
1400
  }
3,585✔
1401
  else {
612✔
1402
    domain = ZoneName(qname);
612✔
1403
    do {
615✔
1404
      found = safeGetBBDomainInfo(domain, &bbd);
615✔
1405
      // Ignore pending domains unless we are the backend running the transaction
1406
      // in which they are being created. This can't be done in safeGetBBDomainInfo
1407
      // because it needs to be a static method.
1408
      if (found && bbd.d_pending && bbd.d_id != d_transaction_id) {
615!
NEW
1409
        found = false;
×
NEW
1410
      }
×
1411
    } while (!found && qtype != QType::SOA && domain.chopOff());
615✔
1412
  }
612✔
1413

1414
  if (!found) {
4,197✔
1415
    if (mustlog) {
24!
1416
      SLOG(g_log << Logger::Warning << "Found no authoritative zone for '" << qname << "' and/or id " << zoneId << endl,
×
1417
           d_slog->info(Logr::Warning, "Found no authoritative zone", "name", Logging::Loggable(qname), "zone id", Logging::Loggable(zoneId)));
×
1418
    }
×
1419
    d_handle.d_list = false;
24✔
1420
    return;
24✔
1421
  }
24✔
1422

1423
  if (mustlog) {
4,173!
1424
    SLOG(g_log << Logger::Warning << "Found a zone '" << domain << "' (with id " << bbd.d_id << ") that might contain data " << endl,
×
1425
         d_slog->info(Logr::Warning, "Found authoritative zone", "zone", Logging::Loggable(domain), "zone id", Logging::Loggable(bbd.d_id)));
×
1426
  }
×
1427

1428
  d_handle.id = bbd.d_id;
4,173✔
1429
  d_handle.qname = qname.makeRelative(domain); // strip domain name
4,173✔
1430
  d_handle.qtype = qtype;
4,173✔
1431
  d_handle.domain = std::move(domain);
4,173✔
1432

1433
  if (!bbd.current()) {
4,173✔
1434
    SLOG(g_log << Logger::Warning << "Zone '" << d_handle.domain << "' (" << bbd.main_filename() << ") needs reloading" << endl,
6!
1435
         d_slog->info(Logr::Warning, "Zone needs reloading", "zone", Logging::Loggable(d_handle.domain), "file", Logging::Loggable(bbd.main_filename())));
6✔
1436
    queueReloadAndStore(bbd.d_id);
6✔
1437
    if (!safeGetBBDomainInfo(d_handle.domain, &bbd))
6!
1438
      throw DBException("Zone '" + bbd.d_name.toLogString() + "' (" + bbd.main_filename() + ") gone after reload"); // if we don't throw here, we crash for some reason
×
1439
  }
6✔
1440

1441
  if (!bbd.d_loaded) {
4,173✔
1442
    d_handle.reset();
216✔
1443
    throw DBException("Zone for '" + d_handle.domain.toLogString() + "' in '" + bbd.main_filename() + "' not loaded (file missing, corrupt or primary dead)"); // fsck
216✔
1444
  }
216✔
1445

1446
  d_handle.d_records = bbd.d_records.get();
3,957✔
1447

1448
  if (d_handle.d_records->empty()) {
3,957!
1449
    DLOG(SLOG(g_log << "Query with no results" << endl,
×
1450
              d_slog->info(Logr::Debug, "No results", "name", Logging::Loggable(qname), "qtype", Logging::Loggable(qtype))));
×
1451
  }
×
1452

1453
  d_handle.mustlog = mustlog;
3,957✔
1454

1455
  const auto& hashedidx = boost::multi_index::get<UnorderedNameTag>(*d_handle.d_records);
3,957✔
1456
  auto range = hashedidx.equal_range(d_handle.qname);
3,957✔
1457

1458
  d_handle.d_list = false;
3,957✔
1459
  d_handle.d_iter = range.first;
3,957✔
1460
  d_handle.d_end_iter = range.second;
3,957✔
1461
}
3,957✔
1462

1463
bool Bind2Backend::get(DNSResourceRecord& r)
1464
{
197,984✔
1465
  if (!d_handle.d_records) {
197,984✔
1466
    if (d_handle.mustlog) {
24!
1467
      SLOG(g_log << Logger::Warning << "There were no answers" << endl,
×
1468
           d_slog->info(Logr::Warning, "No answers"));
×
1469
    }
×
1470
    return false;
24✔
1471
  }
24✔
1472

1473
  if (!d_handle.get(r)) {
197,960✔
1474
    if (d_handle.mustlog) {
4,262!
1475
      SLOG(g_log << Logger::Warning << "End of answers" << endl,
×
1476
           d_slog->info(Logr::Warning, "No more answers"));
×
1477
    }
×
1478

1479
    d_handle.reset();
4,262✔
1480

1481
    return false;
4,262✔
1482
  }
4,262✔
1483
  if (d_handle.mustlog) {
193,698!
1484
    SLOG(g_log << Logger::Warning << "Returning: '" << r.qtype.toString() << "' of '" << r.qname << "', content: '" << r.content << "'" << endl,
×
1485
         d_slog->info(Logr::Warning, "Returning record", "name", Logging::Loggable(r.qname), "type", Logging::Loggable(r.qtype), "content", Logging::Loggable(r.content)));
×
1486
  }
×
1487
  return true;
193,698✔
1488
}
197,960✔
1489

1490
void Bind2Backend::lookupEnd()
1491
{
26✔
1492
  d_handle.reset();
26✔
1493
}
26✔
1494

1495
bool Bind2Backend::handle::get(DNSResourceRecord& r)
1496
{
197,960✔
1497
  if (d_list)
197,960✔
1498
    return get_list(r);
188,936✔
1499
  else
9,024✔
1500
    return get_normal(r);
9,024✔
1501
}
197,960✔
1502

1503
void Bind2Backend::handle::reset()
1504
{
9,032✔
1505
  d_records.reset();
9,032✔
1506
  qname.clear();
9,032✔
1507
  mustlog = false;
9,032✔
1508
}
9,032✔
1509

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

1515
  if (d_iter == d_end_iter) {
9,024✔
1516
    return false;
3,931✔
1517
  }
3,931✔
1518

1519
  while (d_iter != d_end_iter && !(qtype.getCode() == QType::ANY || (d_iter)->qtype == qtype.getCode())) {
7,850!
1520
    DLOG(SLOG(g_log << Logger::Warning << "Skipped " << qname << "/" << QType(d_iter->qtype).toString() << ": '" << d_iter->content << "'" << endl,
2,757✔
1521
              d_slog->info(Logr::Debug, "Skipped record", "name", Logging::Loggable(qname), "type", Logging::Loggable(d_iter->qtype), "content", Logging::Loggable(d_iter->content))));
2,757✔
1522
    d_iter++;
2,757✔
1523
  }
2,757✔
1524
  if (d_iter == d_end_iter) {
5,093!
1525
    return false;
×
1526
  }
×
1527
  DLOG(SLOG(g_log << "Bind2Backend get() returning a rr with a " << QType(d_iter->qtype).getCode() << endl,
5,093✔
1528
            d_slog->info(Logr::Debug, "Bind2Backend get() returning a rr", "type", Logging::Loggable(d_iter->qtype))));
5,093✔
1529

1530
  const DNSName& domainName(domain);
5,093✔
1531
  r.qname = qname.empty() ? domainName : (qname + domainName);
5,093!
1532
  r.domain_id = id;
5,093✔
1533
  r.content = (d_iter)->content;
5,093✔
1534
  //  r.domain_id=(d_iter)->domain_id;
1535
  r.qtype = (d_iter)->qtype;
5,093✔
1536
  r.ttl = (d_iter)->ttl;
5,093✔
1537

1538
  //if(!d_iter->auth && r.qtype.getCode() != QType::A && r.qtype.getCode()!=QType::AAAA && r.qtype.getCode() != QType::NS)
1539
  //  cerr<<"Warning! Unauth response for qtype "<< r.qtype.toString() << " for '"<<r.qname<<"'"<<endl;
1540
  r.auth = d_iter->auth;
5,093✔
1541

1542
  d_iter++;
5,093✔
1543

1544
  return true;
5,093✔
1545
}
5,093✔
1546

1547
bool Bind2Backend::list(const ZoneName& /* target */, domainid_t domainId, bool /* include_disabled */)
1548
{
331✔
1549
  BB2DomainInfo bbd;
331✔
1550

1551
  if (!safeGetBBDomainInfo(domainId, &bbd)) {
331!
1552
    return false;
×
1553
  }
×
1554
  // Ignore pending domains unless we are the backend running the transaction
1555
  // in which they are being created. This can't be done in safeGetBBDomainInfo
1556
  // because it needs to be a static method.
1557
  if (bbd.d_pending && bbd.d_id != d_transaction_id) {
331!
NEW
1558
    return false;
×
NEW
1559
  }
×
1560

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

1565
  if (!bbd.d_loaded) {
331!
1566
    throw PDNSException("zone was not loaded, perhaps because of: " + bbd.d_status);
×
1567
  }
×
1568

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

1573
  d_handle.id = domainId;
331✔
1574
  d_handle.domain = bbd.d_name;
331✔
1575
  d_handle.d_list = true;
331✔
1576
  return true;
331✔
1577
}
331✔
1578

1579
bool Bind2Backend::handle::get_list(DNSResourceRecord& r)
1580
{
188,936✔
1581
  if (d_qname_iter != d_qname_end) {
188,936✔
1582
    const DNSName& domainName(domain);
188,605✔
1583
    r.qname = d_qname_iter->qname.empty() ? domainName : (d_qname_iter->qname + domainName);
188,605!
1584
    r.domain_id = id;
188,605✔
1585
    r.content = (d_qname_iter)->content;
188,605✔
1586
    r.qtype = (d_qname_iter)->qtype;
188,605✔
1587
    r.ttl = (d_qname_iter)->ttl;
188,605✔
1588
    r.auth = d_qname_iter->auth;
188,605✔
1589
    d_qname_iter++;
188,605✔
1590
    return true;
188,605✔
1591
  }
188,605✔
1592
  return false;
331✔
1593
}
188,936✔
1594

1595
bool Bind2Backend::autoPrimariesList(std::vector<AutoPrimary>& primaries)
1596
{
×
1597
  if (getArg("autoprimary-config").empty())
×
1598
    return false;
×
1599

1600
  std::string filename(getArg("autoprimaries"));
×
1601
  ifstream c_if(filename, std::ios::in);
×
1602
  if (!c_if) {
×
1603
    SLOG(g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl,
×
1604
         d_slog->error(Logr::Error, errno, "Unable to open autoprimaries file", "file", Logging::Loggable(filename)));
×
1605
    return false;
×
1606
  }
×
1607

1608
  string line, sip, saccount;
×
1609
  while (getline(c_if, line)) {
×
1610
    std::istringstream ii(line);
×
1611
    ii >> sip;
×
1612
    if (!sip.empty()) {
×
1613
      ii >> saccount;
×
1614
      primaries.emplace_back(sip, "", saccount);
×
1615
    }
×
1616
  }
×
1617

1618
  c_if.close();
×
1619
  return true;
×
1620
}
×
1621

1622
bool Bind2Backend::autoPrimaryBackend(const string& ipAddress, const ZoneName& /* domain */, const vector<DNSResourceRecord>& /* nsset */, string* /* nameserver */, string* account, DNSBackend** backend)
1623
{
×
1624
  // Check whether we have a configfile available.
1625
  if (getArg("autoprimary-config").empty())
×
1626
    return false;
×
1627

1628
  std::string filename(getArg("autoprimaries"));
×
1629
  ifstream c_if(filename.c_str(), std::ios::in); // this was nocreate?
×
1630
  if (!c_if) {
×
1631
    SLOG(g_log << Logger::Error << "Unable to open autoprimaries file for read: " << stringerror() << endl,
×
1632
         d_slog->error(Logr::Error, errno, "Unable to open autoprimaries file", "file", Logging::Loggable(filename)));
×
1633
    return false;
×
1634
  }
×
1635

1636
  // Format:
1637
  // <ip> <accountname>
1638
  string line, sip, saccount;
×
1639
  while (getline(c_if, line)) {
×
1640
    std::istringstream ii(line);
×
1641
    ii >> sip;
×
1642
    if (sip == ipAddress) {
×
1643
      ii >> saccount;
×
1644
      break;
×
1645
    }
×
1646
  }
×
1647
  c_if.close();
×
1648

1649
  if (sip != ipAddress) { // ip not found in authorization list - reject
×
1650
    return false;
×
1651
  }
×
1652

1653
  // ip authorized as autoprimary - accept
1654
  *backend = this;
×
1655
  if (saccount.length() > 0)
×
1656
    *account = saccount.c_str();
×
1657

1658
  return true;
×
1659
}
×
1660

1661
BB2DomainInfo Bind2Backend::createDomainEntry(const ZoneName& domain)
1662
{
6✔
1663
  domainid_t newid = 1;
6✔
1664
  { // Find a free zone id nr.
6✔
1665
    auto state = s_state.read_lock();
6✔
1666
    if (!state->empty()) {
6!
1667
      newid = state->rbegin()->d_id + 1;
6✔
1668
    }
6✔
1669
  }
6✔
1670

1671
  BB2DomainInfo bbd;
6✔
1672
  bbd.d_kind = DomainInfo::Native;
6✔
1673
  bbd.d_id = newid;
6✔
1674
  bbd.d_records = std::make_shared<recordstorage_t>();
6✔
1675
  bbd.d_name = domain;
6✔
1676
  bbd.setCheckInterval(getArgAsNum("check-interval"));
6✔
1677

1678
  return bbd;
6✔
1679
}
6✔
1680

1681
bool Bind2Backend::createSecondaryDomain(const string& ipAddress, const ZoneName& domain, const string& /* nameserver */, const string& account, DomainInfo& info, bool startTransaction)
1682
{
×
NEW
1683
  info.backend = this; // to be able to abortTransaction if the operation fails
×
1684

UNCOV
1685
  std::string domainname = domain.toStringNoDot();
×
1686

1687
  // Reject domain name if it embeds quotes; this may happen if 8bit-dns is
1688
  // used, and bind currently does not allow for character escapes in zone
1689
  // names.
1690
  if (domainname.find_first_of("\"") != std::string::npos) {
×
1691
    SLOG(g_log << Logger::Error << d_logprefix
×
1692
               << " Unable to accept autosecondary zone '" << domain
×
1693
               << "' from autoprimary " << ipAddress
×
1694
               << " due to unauthorized characters in domain name for bind configuration file"
×
1695
               << endl,
×
1696
         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)));
×
1697
    throw PDNSException("Unauthorized characters in domain name for bind configuration file");
×
1698
  }
×
1699

1700
  string filename = getArg("autoprimary-destdir") + '/';
×
1701
  if (domainname.empty()) {
×
1702
    filename.append("rootzone.");
×
1703
  }
×
1704
  else {
×
1705
    // Make sure the zone file name does not contain path separators.
1706
    filename.append(boost::replace_all_copy(domainname, "/", "\\047"));
×
1707
  }
×
1708

NEW
1709
  BB2DomainInfo bbd = createDomainEntry(domain);
×
NEW
1710
  bbd.d_kind = DomainInfo::Secondary;
×
NEW
1711
  bbd.d_primaries.emplace_back(ComboAddress(ipAddress, 53));
×
NEW
1712
  bbd.d_fileinfo.emplace_back(std::make_pair(filename, 0));
×
NEW
1713
  bbd.updateCtime();
×
1714

NEW
1715
  if (startTransaction) {
×
1716
    // Remember this domain is pending until the transaction gets commited.
NEW
1717
    bbd.d_pending = true;
×
NEW
1718
    startDomainCreationTransactionInternal(bbd);
×
NEW
1719
  }
×
NEW
1720
  safePutBBDomainInfo(bbd);
×
1721

1722
  SLOG(g_log << Logger::Warning << d_logprefix
×
1723
             << " Writing bind config zone statement for autosecondary zone '" << domain
×
1724
             << "' from autoprimary " << ipAddress << endl,
×
1725
       d_slog->info(Logr::Warning, "Writing bind config zone statement for autosecondary zone", "zone", Logging::Loggable(domain), "autoprimary address", Logging::Loggable(ipAddress)));
×
1726

1727
  {
×
1728
    auto lock = std::scoped_lock(s_autosecondary_config_lock);
×
1729

1730
    std::string configfile(getArg("autoprimary-config"));
×
1731
    ofstream c_of(configfile.c_str(), std::ios::app);
×
1732
    if (!c_of) {
×
1733
      int err = errno;
×
1734
      auto errorMessage = stringerror();
×
1735
      SLOG(g_log << Logger::Error << "Unable to open autoprimary configfile for append: " << errorMessage << endl,
×
1736
           d_slog->error(Logr::Error, err, "Unable to open autoprimary configuration file for append", "file", Logging::Loggable(configfile)));
×
1737
      throw DBException("Unable to open autoprimary configfile for append: " + errorMessage);
×
1738
    }
×
1739

1740
    c_of << endl;
×
1741
    c_of << "# AutoSecondary zone '" << domainname << "' (added: " << nowTime() << ") (account: " << account << ')' << endl;
×
1742
    c_of << "zone \"" << domainname << "\" {" << endl;
×
1743
    c_of << "\ttype secondary;" << endl;
×
1744
    c_of << "\tfile \"" << filename << "\";" << endl;
×
1745
    c_of << "\tprimaries { " << ipAddress << "; };" << endl;
×
1746
    c_of << "};" << endl;
×
1747
    c_of.close();
×
1748
  }
×
1749

NEW
1750
  info.id = bbd.d_id;
×
NEW
1751
  info.zone = domain;
×
NEW
1752
  info.primaries = bbd.d_primaries;
×
NEW
1753
  info.last_check = bbd.d_lastcheck;
×
NEW
1754
  info.backend = this;
×
NEW
1755
  info.kind = bbd.d_kind;
×
NEW
1756
  info.serial = 0;
×
1757
  return true;
×
1758
}
×
1759

1760
bool Bind2Backend::searchRecords(const string& pattern, size_t maxResults, vector<DNSResourceRecord>& result)
1761
{
24✔
1762
  SimpleMatch sm(pattern, true);
24✔
1763
  static bool mustlog = ::arg().mustDo("query-logging");
24✔
1764
  if (mustlog) {
24!
1765
    SLOG(g_log << Logger::Warning << "Search for pattern '" << pattern << "'" << endl,
×
1766
         d_slog->info(Logr::Debug, "Search for pattern", "pattern", Logging::Loggable(pattern)));
×
1767
  }
×
1768

1769
  {
24✔
1770
    auto state = s_state.read_lock();
24✔
1771

1772
    for (const auto& i : *state) {
24!
1773
      BB2DomainInfo h;
×
1774
      if (!safeGetBBDomainInfo(i.d_id, &h)) {
×
1775
        continue;
×
1776
      }
×
1777
      // Ignore pending domains unless we are the backend running the transaction
1778
      // in which they are being created. This can't be done in safeGetBBDomainInfo
1779
      // because it needs to be a static method.
NEW
1780
      if (h.d_pending && h.d_id != d_transaction_id) {
×
NEW
1781
        continue;
×
NEW
1782
      }
×
1783

1784
      if (!h.d_loaded) {
×
1785
        continue;
×
1786
      }
×
1787

1788
      shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
×
1789

1790
      for (recordstorage_t::const_iterator ri = rhandle->begin(); result.size() < maxResults && ri != rhandle->end(); ri++) {
×
1791
        const DNSName& domainName(i.d_name);
×
1792
        DNSName name = ri->qname.empty() ? domainName : (ri->qname + domainName);
×
1793
        if (sm.match(name) || sm.match(ri->content)) {
×
1794
          DNSResourceRecord r;
×
1795
          r.qname = std::move(name);
×
1796
          r.domain_id = i.d_id;
×
1797
          r.content = ri->content;
×
1798
          r.qtype = ri->qtype;
×
1799
          r.ttl = ri->ttl;
×
1800
          r.auth = ri->auth;
×
1801
          result.push_back(std::move(r));
×
1802
        }
×
1803
      }
×
1804
    }
×
1805
  }
24✔
1806

1807
  return true;
24✔
1808
}
24✔
1809

1810
class Bind2Factory : public BackendFactory
1811
{
1812
public:
1813
  Bind2Factory() :
1814
    BackendFactory("bind") {}
6,222✔
1815

1816
  void declareArguments(const string& suffix = "") override
1817
  {
587✔
1818
    declare(suffix, "ignore-broken-records", "Ignore records that are out-of-bound for the zone.", "no");
587✔
1819
    declare(suffix, "config", "Location of named.conf", "");
587✔
1820
    declare(suffix, "check-interval", "Interval for zonefile changes", "0");
587✔
1821
    declare(suffix, "autoprimary-config", "Location of (part of) named.conf where pdns can write zone-statements to", "");
587✔
1822
    declare(suffix, "autoprimaries", "List of IP-addresses of autoprimaries", "");
587✔
1823
    declare(suffix, "autoprimary-destdir", "Destination directory for newly added secondary zones", ::arg()["config-dir"]);
587✔
1824
    declare(suffix, "dnssec-db", "Filename to store & access our DNSSEC metadatabase, empty for none", "");
587✔
1825
    declare(suffix, "dnssec-db-journal-mode", "SQLite3 journal mode", "WAL");
587✔
1826
    declare(suffix, "hybrid", "Store DNSSEC metadata in other backend", "no");
587✔
1827
  }
587✔
1828

1829
  DNSBackend* make(const string& suffix = "") override
1830
  {
2,586✔
1831
    assertEmptySuffix(suffix);
2,586✔
1832
    return new Bind2Backend(suffix);
2,586✔
1833
  }
2,586✔
1834

1835
  DNSBackend* makeMetadataOnly(const string& suffix = "") override
1836
  {
919✔
1837
    assertEmptySuffix(suffix);
919✔
1838
    return new Bind2Backend(suffix, false);
919✔
1839
  }
919✔
1840

1841
private:
1842
  void assertEmptySuffix(const string& suffix)
1843
  {
3,505✔
1844
    if (!suffix.empty())
3,505!
1845
      throw PDNSException("launch= suffixes are not supported on the bindbackend");
×
1846
  }
3,505✔
1847
};
1848

1849
//! Magic class that is activated when the dynamic library is loaded
1850
class Bind2Loader
1851
{
1852
public:
1853
  Bind2Loader()
1854
  {
6,222✔
1855
    BackendMakers().report(std::make_unique<Bind2Factory>());
6,222✔
1856
    // If this module is not loaded dynamically at runtime, this code runs
1857
    // as part of a global constructor, before the structured logger has a
1858
    // chance to be set up, so fallback to simple logging.
1859
    g_log << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
6,222✔
1860
#ifndef REPRODUCIBLE
6,222✔
1861
          << " (" __DATE__ " " __TIME__ ")"
6,222✔
1862
#endif
6,222✔
1863
#ifdef HAVE_SQLITE3
6,222✔
1864
          << " (with bind-dnssec-db support)"
6,222✔
1865
#endif
6,222✔
1866
          << " reporting" << endl;
6,222✔
1867
  }
6,222✔
1868
};
1869
static Bind2Loader bind2loader;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc