File: tinydnsbackend.cc

package info (click to toggle)
pdns 5.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,824 kB
  • sloc: cpp: 101,240; sh: 5,616; makefile: 2,318; sql: 860; ansic: 675; python: 635; yacc: 245; perl: 161; lex: 131
file content (455 lines) | stat: -rw-r--r-- 14,217 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "tinydnsbackend.hh"
#include "pdns/misc.hh"
#include "pdns/dnsrecords.hh"
#include <utility>

static string backendname = "[TinyDNSBackend] ";
domainid_t TinyDNSBackend::s_lastId;
LockGuarded<TinyDNSBackend::TDI_suffix_t> TinyDNSBackend::s_domainInfo;

vector<string> TinyDNSBackend::getLocations()
{
  vector<string> ret;

  if (!d_dnspacket) {
    return ret;
  }

  //TODO: We do not have IPv6 support.
  Netmask remote = d_dnspacket->getRealRemote();
  if (remote.getBits() != 32) {
    return ret;
  }

  unsigned long addr = remote.getNetwork().sin4.sin_addr.s_addr;

  char key[6];
  key[0] = '\000';
  key[1] = '\045';
  key[2] = (addr) & 0xff;
  key[3] = (addr >> 8) & 0xff;
  key[4] = (addr >> 16) & 0xff;
  key[5] = (addr >> 24) & 0xff;

  for (int i = 4; i >= 0; i--) {
    string searchkey(key, i + 2);
    try {
      auto reader = std::make_unique<CDB>(getArg("dbfile"));
      ret = reader->findall(searchkey);
    }
    catch (const std::exception& e) {
      g_log << Logger::Error << e.what() << endl;
      throw PDNSException(e.what());
    }

    //Biggest item wins, so when we find something, we can jump out.
    if (ret.size() > 0) {
      break;
    }
  }

  return ret;
}

TinyDNSBackend::TinyDNSBackend(const string& suffix)
{
  setArgPrefix("tinydns" + suffix);
  d_suffix = suffix;
  d_locations = mustDo("locations");
  d_ignorebogus = mustDo("ignore-bogus-records");
  d_taiepoch = 4611686018427387904ULL + getArgAsNum("tai-adjust");
  d_dnspacket = NULL;
  d_cdbReader = NULL;
  d_isAxfr = false;
  d_isWildcardQuery = false;
}

TinyDNSBackend::TDI_t::iterator TinyDNSBackend::updateState(DomainInfo& domain, TDI_t* state)
{
  TDIByZone_t& zone_index = state->get<tag_zone>();
  TDIByZone_t::iterator itByZone = zone_index.find(domain.zone);
  if (itByZone != zone_index.end()) {
    return itByZone;
  }

  TinyDomainInfo tmp;
  s_lastId++;
  tmp.zone = domain.zone;
  tmp.id = s_lastId;
  tmp.notified_serial = domain.serial;
  return state->insert(tmp).first;
}

void TinyDNSBackend::getUpdatedPrimaries(vector<DomainInfo>& retDomains, std::unordered_set<DNSName>& /* catalogs */, CatalogHashMap& /* catalogHashes */)
{
  bool alwaysNotify{false};
  auto domainInfo = s_domainInfo.lock(); //TODO: We could actually lock less if we do it per suffix.
  if (domainInfo->count(d_suffix) == 0) {
    // If we don't have any state yet, this is startup, check whether we need
    // to always notify.
    alwaysNotify = mustDo("notify-on-startup");
    TDI_t tmp;
    domainInfo->emplace(d_suffix, tmp);
  }

  TDI_t* state = &(*domainInfo)[d_suffix];

  vector<DomainInfo> allDomains;
  getAllDomains_locked(&allDomains, true);

  for (auto& domain : allDomains) {
    auto iter = updateState(domain, state);
    // Keep domain id in sync with our current state.
    domain.id = iter->id;
    if (alwaysNotify || iter->notified_serial < domain.serial) {
      retDomains.push_back(domain);
    }
  }
}

// NOLINTNEXTLINE(readability-identifier-length)
void TinyDNSBackend::setNotified(domainid_t id, uint32_t serial)
{
  auto domainInfo = s_domainInfo.lock();
  if (!domainInfo->count(d_suffix)) {
    throw PDNSException("Can't get list of domains to set the serial.");
  }
  TDI_t* state = &(*domainInfo)[d_suffix];
  TDIById_t& domain_index = state->get<tag_domainid>();
  TDIById_t::iterator itById = domain_index.find(id);
  if (itById == domain_index.end()) {
    g_log << Logger::Error << backendname << "Received updated serial(" << serial << "), but domain ID (" << id << ") is not known in this backend." << endl;
  }
  else {
    DLOG(g_log << Logger::Debug << backendname << "Setting serial for " << itById->zone << " to " << serial << endl);
    domain_index.modify(itById, TDI_SerialModifier(serial));
  }
  (*domainInfo)[d_suffix] = *state;
}

void TinyDNSBackend::getAllDomains_locked(vector<DomainInfo>* domains, bool getSerial)
{
  d_isAxfr = true;
  d_isGetDomains = true;
  d_dnspacket = NULL;

  try {
    d_cdbReader = std::make_unique<CDB>(getArg("dbfile"));
    d_currentDomain = UnknownDomainID;
  }
  catch (const std::exception& e) {
    g_log << Logger::Error << e.what() << endl;
    throw PDNSException(e.what());
  }

  d_cdbReader->searchAll();
  DNSResourceRecord rr;
  std::unordered_set<DNSName> dupcheck;

  while (get(rr)) {
    if (rr.qtype.getCode() == QType::SOA && dupcheck.insert(rr.qname).second) {
      DomainInfo di;
      di.id = d_currentDomain; // Will be overridden by caller
      di.backend = this;
      di.zone = ZoneName(rr.qname);
      di.kind = DomainInfo::Primary;
      di.last_check = time(0);

      if (getSerial) {
        SOAData sd;
        try {
          fillSOAData(rr.content, sd);
          di.serial = sd.serial;
        }
        catch (...) {
          di.serial = 0;
        }
      }

      di.notified_serial = di.serial;
      domains->push_back(di);
    }
  }
}

void TinyDNSBackend::getAllDomains(vector<DomainInfo>* domains, bool getSerial, bool /* include_disabled */)
{
  auto domainInfo = s_domainInfo.lock(); //TODO: We could actually lock less if we do it per suffix.
  if (domainInfo->count(d_suffix) == 0) {
    TDI_t tmp;
    domainInfo->emplace(d_suffix, tmp);
  }

  TDI_t* state = &(*domainInfo)[d_suffix];

  getAllDomains_locked(domains, getSerial);

  for (auto& domain : *domains) {
    auto iter = updateState(domain, state);
    // Keep domain id in sync with our current state.
    domain.id = iter->id;
  }
}

//NOLINTNEXTLINE(readability-identifier-length)
bool TinyDNSBackend::getDomainInfo(const ZoneName& domain, DomainInfo& di, bool getSerial)
{
  auto domainInfo = s_domainInfo.lock(); //TODO: We could actually lock less if we do it per suffix.
  if (domainInfo->count(d_suffix) == 0) {
    TDI_t tmp;
    domainInfo->emplace(d_suffix, tmp);
  }

  TDI_t* state = &(*domainInfo)[d_suffix];

  vector<DomainInfo> allDomains;
  getAllDomains_locked(&allDomains, getSerial);

  bool found{false};
  for (auto& oneDomain : allDomains) {
    auto iter = updateState(oneDomain, state);
    if (oneDomain.zone == domain) {
      // Keep domain id in sync with our current state.
      oneDomain.id = iter->id;
      di = oneDomain;
      found = true;
    }
  }
  return found;
}

bool TinyDNSBackend::list(const ZoneName& target, domainid_t domain_id, bool /* include_disabled */)
{
  d_isAxfr = true;
  d_isGetDomains = false;
  string key = target.operator const DNSName&().toDNSStringLC();
  try {
    d_cdbReader = std::make_unique<CDB>(getArg("dbfile"));
    d_currentDomain = domain_id;
  }
  catch (const std::exception& e) {
    g_log << Logger::Error << e.what() << endl;
    throw PDNSException(e.what());
  }

  return d_cdbReader->searchSuffix(key);
}

void TinyDNSBackend::lookup(const QType& qtype, const DNSName& qdomain, domainid_t zoneId, DNSPacket* pkt_p)
{
  d_isAxfr = false;
  d_isGetDomains = false;
  string queryDomain = toLowerCanonic(qdomain.toString());

  string key = simpleCompress(queryDomain);

  DLOG(g_log << Logger::Debug << backendname << "[lookup] query for qtype [" << qtype.toString() << "] qdomain [" << qdomain << "]" << endl);
  DLOG(g_log << Logger::Debug << "[lookup] key [" << makeHexDump(key) << "]" << endl);

  d_isWildcardQuery = false;
  if (key[0] == '\001' && key[1] == '\052') {
    d_isWildcardQuery = true;
    key.erase(0, 2);
  }

  d_qtype = qtype;

  try {
    d_cdbReader = std::make_unique<CDB>(getArg("dbfile"));
    d_currentDomain = zoneId;
  }
  catch (const std::exception& e) {
    g_log << Logger::Error << e.what() << endl;
    throw PDNSException(e.what());
  }

  d_cdbReader->searchKey(key);
  d_dnspacket = pkt_p;
}

bool TinyDNSBackend::get(DNSResourceRecord& rr)
{
  pair<string, string> record;

  while (d_cdbReader->readNext(record)) {
    string val = record.second;
    string key = record.first;

    //DLOG(g_log<<Logger::Debug<<"[GET] Key: "<<makeHexDump(key)<<endl);
    //DLOG(g_log<<Logger::Debug<<"[GET] Val: "<<makeHexDump(val)<<endl);
    if (key[0] == '\000' && key[1] == '\045') { // skip locations
      continue;
    }

    if (!d_isAxfr) {
      // If we have a wildcard query, but the record we got is not a wildcard, we skip.
      if (d_isWildcardQuery && val[2] != '\052' && val[2] != '\053') {
        continue;
      }

      // If it is NOT a wildcard query, but we do find a wildcard record, we skip it.
      if (!d_isWildcardQuery && (val[2] == '\052' || val[2] == '\053')) {
        continue;
      }
    }

    PacketReader pr(val, 0);
    rr.qtype = QType(pr.get16BitInt());

    if (d_isGetDomains && rr.qtype != QType::SOA) {
      continue;
    }

    if (d_isAxfr || d_qtype.getCode() == QType::ANY || rr.qtype == d_qtype) {
      char locwild = pr.get8BitInt();
      if (locwild != '\075' && (locwild == '\076' || locwild == '\053')) {
        if (d_isAxfr && d_locations) { // We skip records with a location in AXFR, unless we disable locations.
          continue;
        }
        char recloc[2];
        recloc[0] = pr.get8BitInt();
        recloc[1] = pr.get8BitInt();

        if (d_locations) {
          bool foundLocation = false;
          vector<string> locations = getLocations();
          while (locations.size() > 0) {
            string locId = locations.back();
            locations.pop_back();

            if (recloc[0] == locId[0] && recloc[1] == locId[1]) {
              foundLocation = true;
              break;
            }
          }
          if (!foundLocation) {
            continue;
          }
        }
      }

      if (d_isAxfr && (val[2] == '\052' || val[2] == '\053')) { // Keys are not stored with wildcard character, with AXFR we need to add that.
        key.insert(0, 1, '\052');
        key.insert(0, 1, '\001');
      }
      // rr.qname.clear();
      rr.qname = DNSName(key.c_str(), key.size(), 0, false);
      rr.domain_id = d_currentDomain;
      // 11:13.21 <@ahu> IT IS ALWAYS AUTH --- well not really because we are just a backend :-)
      // We could actually do NSEC3-NARROW DNSSEC according to Habbie, if we do, we need to change something here.
      rr.auth = true;

      rr.ttl = pr.get32BitInt();
      uint64_t timestamp = pr.get32BitInt();
      timestamp <<= 32;
      timestamp += pr.get32BitInt();
      if (timestamp) {
        uint64_t now = d_taiepoch + time(NULL);
        if (rr.ttl == 0) {
          if (timestamp < now) {
            continue;
          }
          rr.ttl = timestamp - now;
          if (rr.ttl <= 2)
            rr.ttl = 2;
          if (rr.ttl >= 3600)
            rr.ttl = 3600;
        }
        else if (now <= timestamp) {
          continue;
        }
      }
      try {
        DNSRecord dr;
        dr.d_class = 1;
        dr.d_type = rr.qtype.getCode();
        dr.d_clen = val.size() - pr.getPosition();

        auto drc = DNSRecordContent::make(dr, pr);
        rr.content = drc->getZoneRepresentation();
        DLOG(cerr << "CONTENT: " << rr.content << endl);
      }
      catch (...) {
        g_log << Logger::Error << backendname << "Failed to parse record content for " << rr.qname << " with type " << rr.qtype.toString();
        if (d_ignorebogus || d_isGetDomains) {
          g_log << ". Ignoring!" << endl;
          continue;
        }
        else {
          g_log << ". Erroring out!" << endl;
          throw;
        }
      }
      //      DLOG(g_log<<Logger::Debug<<backendname<<"Returning ["<<rr.content<<"] for ["<<rr.qname<<"] of RecordType ["<<rr.qtype.toString()<<"]"<<endl;);
      return true;
    }
  } // end of while
  DLOG(g_log << Logger::Debug << backendname << "No more records to return." << endl);

  d_cdbReader = nullptr;
  d_currentDomain = UnknownDomainID;
  return false;
}

// boilerplate
class TinyDNSFactory : public BackendFactory
{
public:
  TinyDNSFactory() :
    BackendFactory("tinydns") {}

  void declareArguments(const string& suffix = "") override
  {
    declare(suffix, "notify-on-startup", "Tell the TinyDNSBackend to notify all the secondary nameservers on startup. Default is no.", "no");
    declare(suffix, "dbfile", "Location of the cdb data file", "data.cdb");
    declare(suffix, "tai-adjust", "This adjusts the TAI value if timestamps are used. These seconds will be added to the start point (1970) and will allow you to adjust for leap seconds. The default is 11.", "11");
    declare(suffix, "locations", "Enable or Disable location support in the backend. Changing the value to 'no' will make the backend ignore the locations. This then returns all records!", "yes");
    declare(suffix, "ignore-bogus-records", "The data.cdb file might have some incorrect record data, this causes PowerDNS to fail, where tinydns would send out truncated data. This option makes powerdns ignore that data!", "no");
  }

  DNSBackend* make(const string& suffix = "") override
  {
    return new TinyDNSBackend(suffix);
  }
};

// boilerplate
class TinyDNSLoader
{
public:
  TinyDNSLoader()
  {
    BackendMakers().report(std::make_unique<TinyDNSFactory>());
    g_log << Logger::Info << "[tinydnsbackend] This is the tinydns backend version " VERSION
#ifndef REPRODUCIBLE
          << " (" __DATE__ " " __TIME__ ")"
#endif
          << " reporting" << endl;
  }
};

static TinyDNSLoader tinydnsloader;