]> git.ipfire.org Git - thirdparty/pdns.git/blob - modules/bindbackend/bindbackend2.cc
Merge pull request #8345 from omoerbeek/format-code-script
[thirdparty/pdns.git] / 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 <errno.h>
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
38 #include "pdns/dnsseckeeper.hh"
39 #include "pdns/dnssecinfra.hh"
40 #include "pdns/base32.hh"
41 #include "pdns/namespaces.hh"
42 #include "pdns/dns.hh"
43 #include "pdns/dnsbackend.hh"
44 #include "bindbackend2.hh"
45 #include "pdns/dnspacket.hh"
46 #include "pdns/zoneparser-tng.hh"
47 #include "pdns/bindparserclasses.hh"
48 #include "pdns/logger.hh"
49 #include "pdns/arguments.hh"
50 #include "pdns/qtype.hh"
51 #include "pdns/misc.hh"
52 #include "pdns/dynlistener.hh"
53 #include "pdns/lock.hh"
54 #include "pdns/namespaces.hh"
55
56 /*
57 All instances of this backend share one s_state, which is indexed by zone name and zone id.
58 The s_state is protected by a read/write lock, and the goal it to only interact with it briefly.
59 When a query comes in, we take a read lock and COPY the best zone to answer from s_state (BB2DomainInfo object)
60 All answers are served from this copy.
61
62 To interact with s_state, use safeGetBBDomainInfo (search on name or id), safePutBBDomainInfo (to update)
63 or safeRemoveBBDomainInfo. These all lock as they should.
64
65 Several functions need to traverse s_state to get data for the rest of PowerDNS. When doing so,
66 you need to manually take the s_state_lock (read).
67
68 Parsing zones happens with parseZone(), which fills a BB2DomainInfo object. This can then be stored with safePutBBDomainInfo.
69
70 Finally, the BB2DomainInfo contains all records as a LookButDontTouch object. This makes sure you only look, but don't touch, since
71 the records might be in use in other places.
72 */
73
74 Bind2Backend::state_t Bind2Backend::s_state;
75 int Bind2Backend::s_first=1;
76 bool Bind2Backend::s_ignore_broken_records=false;
77
78 pthread_rwlock_t Bind2Backend::s_state_lock=PTHREAD_RWLOCK_INITIALIZER;
79 pthread_mutex_t Bind2Backend::s_supermaster_config_lock=PTHREAD_MUTEX_INITIALIZER; // protects writes to config file
80 pthread_mutex_t Bind2Backend::s_startup_lock=PTHREAD_MUTEX_INITIALIZER;
81 string Bind2Backend::s_binddirectory;
82
83 template <typename T>
84 std::mutex LookButDontTouch<T>::s_lock;
85
86 BB2DomainInfo::BB2DomainInfo()
87 {
88 d_loaded=false;
89 d_lastcheck=0;
90 d_checknow=false;
91 d_status="Unknown";
92 }
93
94 void BB2DomainInfo::setCheckInterval(time_t seconds)
95 {
96 d_checkinterval=seconds;
97 }
98
99 bool BB2DomainInfo::current()
100 {
101 if(d_checknow) {
102 return false;
103 }
104
105 if(!d_checkinterval)
106 return true;
107
108 if(time(0) - d_lastcheck < d_checkinterval)
109 return true;
110
111 if(d_filename.empty())
112 return true;
113
114 return (getCtime()==d_ctime);
115 }
116
117 time_t BB2DomainInfo::getCtime()
118 {
119 struct stat buf;
120
121 if(d_filename.empty() || stat(d_filename.c_str(),&buf)<0)
122 return 0;
123 d_lastcheck=time(0);
124 return buf.st_ctime;
125 }
126
127 void BB2DomainInfo::setCtime()
128 {
129 struct stat buf;
130 if(stat(d_filename.c_str(),&buf)<0)
131 return;
132 d_ctime=buf.st_ctime;
133 }
134
135 bool Bind2Backend::safeGetBBDomainInfo(int id, BB2DomainInfo* bbd)
136 {
137 ReadLock rl(&s_state_lock);
138 state_t::const_iterator iter = s_state.find(id);
139 if(iter == s_state.end())
140 return false;
141 *bbd=*iter;
142 return true;
143 }
144
145 bool Bind2Backend::safeGetBBDomainInfo(const DNSName& name, BB2DomainInfo* bbd)
146 {
147 ReadLock rl(&s_state_lock);
148 typedef state_t::index<NameTag>::type nameindex_t;
149 nameindex_t& nameindex = boost::multi_index::get<NameTag>(s_state);
150
151 nameindex_t::const_iterator iter = nameindex.find(name);
152 if(iter == nameindex.end())
153 return false;
154 *bbd=*iter;
155 return true;
156 }
157
158 bool Bind2Backend::safeRemoveBBDomainInfo(const DNSName& name)
159 {
160 WriteLock rl(&s_state_lock);
161 typedef state_t::index<NameTag>::type nameindex_t;
162 nameindex_t& nameindex = boost::multi_index::get<NameTag>(s_state);
163
164 nameindex_t::iterator iter = nameindex.find(name);
165 if(iter == nameindex.end())
166 return false;
167 nameindex.erase(iter);
168 return true;
169 }
170
171 void Bind2Backend::safePutBBDomainInfo(const BB2DomainInfo& bbd)
172 {
173 WriteLock rl(&s_state_lock);
174 replacing_insert(s_state, bbd);
175 }
176
177 void Bind2Backend::setNotified(uint32_t id, uint32_t serial)
178 {
179 BB2DomainInfo bbd;
180 if (!safeGetBBDomainInfo(id, &bbd))
181 return;
182 bbd.d_lastnotified = serial;
183 safePutBBDomainInfo(bbd);
184 }
185
186 void Bind2Backend::setFresh(uint32_t domain_id)
187 {
188 BB2DomainInfo bbd;
189 if(safeGetBBDomainInfo(domain_id, &bbd)) {
190 bbd.d_lastcheck=time(0);
191 safePutBBDomainInfo(bbd);
192 }
193 }
194
195 bool Bind2Backend::startTransaction(const DNSName &qname, int id)
196 {
197 if(id < 0) {
198 d_transaction_tmpname.clear();
199 d_transaction_id=id;
200 return false;
201 }
202 if(id == 0) {
203 throw DBException("domain_id 0 is invalid for this backend.");
204 }
205
206 d_transaction_id=id;
207 BB2DomainInfo bbd;
208 if(safeGetBBDomainInfo(id, &bbd)) {
209 d_transaction_tmpname = bbd.d_filename + "XXXXXX";
210 int fd = mkstemp(&d_transaction_tmpname.at(0));
211 if (fd == -1) {
212 throw DBException("Unable to create a unique temporary zonefile '"+d_transaction_tmpname+"': "+stringerror());
213 return false;
214 }
215
216 d_of = std::unique_ptr<ofstream>(new ofstream(d_transaction_tmpname.c_str()));
217 if(!*d_of) {
218 unlink(d_transaction_tmpname.c_str());
219 close(fd);
220 fd = -1;
221 d_of.reset();
222 throw DBException("Unable to open temporary zonefile '"+d_transaction_tmpname+"': "+stringerror());
223 }
224 close(fd);
225 fd = -1;
226
227 *d_of<<"; Written by PowerDNS, don't edit!"<<endl;
228 *d_of<<"; Zone '"<<bbd.d_name<<"' retrieved from master "<<endl<<"; at "<<nowTime()<<endl; // insert master info here again
229
230 return true;
231 }
232 return false;
233 }
234
235 bool Bind2Backend::commitTransaction()
236 {
237 if(d_transaction_id < 0)
238 return false;
239 d_of.reset();
240
241 BB2DomainInfo bbd;
242 if(safeGetBBDomainInfo(d_transaction_id, &bbd)) {
243 if(rename(d_transaction_tmpname.c_str(), bbd.d_filename.c_str())<0)
244 throw DBException("Unable to commit (rename to: '" + bbd.d_filename+"') AXFRed zone: "+stringerror());
245 queueReloadAndStore(bbd.d_id);
246 }
247
248 d_transaction_id=0;
249
250 return true;
251 }
252
253 bool Bind2Backend::abortTransaction()
254 {
255 // -1 = dnssec speciality
256 // 0 = invalid transact
257 // >0 = actual transaction
258 if(d_transaction_id > 0) {
259 unlink(d_transaction_tmpname.c_str());
260 d_of.reset();
261 d_transaction_id=0;
262 }
263
264 return true;
265 }
266
267 bool Bind2Backend::feedRecord(const DNSResourceRecord &rr, const DNSName &ordername, bool ordernameIsNSEC3)
268 {
269 BB2DomainInfo bbd;
270 if (!safeGetBBDomainInfo(d_transaction_id, &bbd))
271 return false;
272
273 string qname;
274 string name = bbd.d_name.toString();
275 if (bbd.d_name.empty()) {
276 qname = rr.qname.toString();
277 }
278 else if (rr.qname.isPartOf(bbd.d_name)) {
279 if (rr.qname == bbd.d_name) {
280 qname = "@";
281 }
282 else {
283 DNSName relName = rr.qname.makeRelative(bbd.d_name);
284 qname = relName.toStringNoDot();
285 }
286 }
287 else {
288 throw DBException("out-of-zone data '"+rr.qname.toLogString()+"' during AXFR of zone '"+bbd.d_name.toLogString()+"'");
289 }
290
291 shared_ptr<DNSRecordContent> drc(DNSRecordContent::mastermake(rr.qtype.getCode(), 1, rr.content));
292 string content = drc->getZoneRepresentation();
293
294 // SOA needs stripping too! XXX FIXME - also, this should not be here I think
295 switch(rr.qtype.getCode()) {
296 case QType::MX:
297 case QType::SRV:
298 case QType::CNAME:
299 case QType::DNAME:
300 case QType::NS:
301 stripDomainSuffix(&content, name);
302 // fallthrough
303 default:
304 if (d_of && *d_of) {
305 *d_of<<qname<<"\t"<<rr.ttl<<"\t"<<rr.qtype.getName()<<"\t"<<content<<endl;
306 }
307 }
308 return true;
309 }
310
311 void Bind2Backend::getUpdatedMasters(vector<DomainInfo> *changedDomains)
312 {
313 vector<DomainInfo> consider;
314 {
315 ReadLock rl(&s_state_lock);
316
317 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
318 if(i->d_kind != DomainInfo::Master && this->alsoNotify.empty() && i->d_also_notify.empty())
319 continue;
320
321 DomainInfo di;
322 di.id=i->d_id;
323 di.zone=i->d_name;
324 di.last_check=i->d_lastcheck;
325 di.notified_serial=i->d_lastnotified;
326 di.backend=this;
327 di.kind=DomainInfo::Master;
328 consider.push_back(di);
329 }
330 }
331
332 SOAData soadata;
333 for(DomainInfo& di : consider) {
334 soadata.serial=0;
335 try {
336 this->getSOA(di.zone, soadata); // we might not *have* a SOA yet, but this might trigger a load of it
337 }
338 catch(...) {
339 continue;
340 }
341 if(di.notified_serial != soadata.serial) {
342 BB2DomainInfo bbd;
343 if(safeGetBBDomainInfo(di.id, &bbd)) {
344 bbd.d_lastnotified=soadata.serial;
345 safePutBBDomainInfo(bbd);
346 }
347 if(di.notified_serial) { // don't do notification storm on startup
348 di.serial=soadata.serial;
349 changedDomains->push_back(di);
350 }
351 }
352 }
353 }
354
355 void Bind2Backend::getAllDomains(vector<DomainInfo> *domains, bool include_disabled)
356 {
357 SOAData soadata;
358
359 // prevent deadlock by using getSOA() later on
360 {
361 ReadLock rl(&s_state_lock);
362
363 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
364 DomainInfo di;
365 di.id=i->d_id;
366 di.zone=i->d_name;
367 di.last_check=i->d_lastcheck;
368 di.kind=i->d_kind;
369 di.masters=i->d_masters;
370 di.backend=this;
371 domains->push_back(di);
372 };
373 }
374
375 for(DomainInfo &di : *domains) {
376 // do not corrupt di if domain supplied by another backend.
377 if (di.backend != this)
378 continue;
379 try {
380 this->getSOA(di.zone, soadata);
381 } catch(...) {
382 continue;
383 }
384 di.serial=soadata.serial;
385 }
386 }
387
388 void Bind2Backend::getUnfreshSlaveInfos(vector<DomainInfo> *unfreshDomains)
389 {
390 vector<DomainInfo> domains;
391 {
392 ReadLock rl(&s_state_lock);
393 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
394 if(i->d_kind != DomainInfo::Slave)
395 continue;
396 DomainInfo sd;
397 sd.id=i->d_id;
398 sd.zone=i->d_name;
399 sd.masters=i->d_masters;
400 sd.last_check=i->d_lastcheck;
401 sd.backend=this;
402 sd.kind=DomainInfo::Slave;
403 domains.push_back(sd);
404 }
405 }
406
407 for(DomainInfo &sd : domains) {
408 SOAData soadata;
409 soadata.refresh=0;
410 soadata.serial=0;
411 try {
412 getSOA(sd.zone,soadata); // we might not *have* a SOA yet
413 }
414 catch(...){}
415 sd.serial=soadata.serial;
416 if(sd.last_check+soadata.refresh < (unsigned int)time(0))
417 unfreshDomains->push_back(sd);
418 }
419 }
420
421 bool Bind2Backend::getDomainInfo(const DNSName& domain, DomainInfo &di, bool getSerial)
422 {
423 BB2DomainInfo bbd;
424 if(!safeGetBBDomainInfo(domain, &bbd))
425 return false;
426
427 di.id=bbd.d_id;
428 di.zone=domain;
429 di.masters=bbd.d_masters;
430 di.last_check=bbd.d_lastcheck;
431 di.backend=this;
432 di.kind=bbd.d_kind;
433 di.serial=0;
434 if(getSerial) {
435 try {
436 SOAData sd;
437 sd.serial=0;
438
439 getSOA(bbd.d_name,sd); // we might not *have* a SOA yet
440 di.serial=sd.serial;
441 }
442 catch(...){}
443 }
444
445 return true;
446 }
447
448 void Bind2Backend::alsoNotifies(const DNSName& domain, set<string> *ips)
449 {
450 // combine global list with local list
451 for(set<string>::iterator i = this->alsoNotify.begin(); i != this->alsoNotify.end(); i++) {
452 (*ips).insert(*i);
453 }
454 // check metadata too if available
455 vector<string> meta;
456 if (getDomainMetadata(domain, "ALSO-NOTIFY", meta)) {
457 for(const auto& str: meta) {
458 (*ips).insert(str);
459 }
460 }
461 ReadLock rl(&s_state_lock);
462 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
463 if(i->d_name == domain) {
464 for(set<string>::iterator it = i->d_also_notify.begin(); it != i->d_also_notify.end(); it++) {
465 (*ips).insert(*it);
466 }
467 return;
468 }
469 }
470 }
471
472 // only parses, does NOT add to s_state!
473 void Bind2Backend::parseZoneFile(BB2DomainInfo *bbd)
474 {
475 NSEC3PARAMRecordContent ns3pr;
476 bool nsec3zone;
477 if (d_hybrid) {
478 DNSSECKeeper dk;
479 nsec3zone=dk.getNSEC3PARAM(bbd->d_name, &ns3pr);
480 } else
481 nsec3zone=getNSEC3PARAM(bbd->d_name, &ns3pr);
482
483 bbd->d_records = shared_ptr<recordstorage_t>(new recordstorage_t());
484 ZoneParserTNG zpt(bbd->d_filename, bbd->d_name, s_binddirectory);
485 zpt.setMaxGenerateSteps(::arg().asNum("max-generate-steps"));
486 DNSResourceRecord rr;
487 string hashed;
488 while(zpt.get(rr)) {
489 if(rr.qtype.getCode() == QType::NSEC || rr.qtype.getCode() == QType::NSEC3 || rr.qtype.getCode() == QType::NSEC3PARAM)
490 continue; // we synthesise NSECs on demand
491
492 insertRecord(*bbd, rr.qname, rr.qtype, rr.content, rr.ttl, "");
493 }
494 fixupOrderAndAuth(*bbd, nsec3zone, ns3pr);
495 doEmptyNonTerminals(*bbd, nsec3zone, ns3pr);
496 bbd->setCtime();
497 bbd->d_loaded=true;
498 bbd->d_checknow=false;
499 bbd->d_status="parsed into memory at "+nowTime();
500 }
501
502 /** THIS IS AN INTERNAL FUNCTION! It does moadnsparser prio impedance matching
503 Much of the complication is due to the efforts to benefit from std::string reference counting copy on write semantics */
504 void Bind2Backend::insertRecord(BB2DomainInfo& bb2, const DNSName &qname, const QType &qtype, const string &content, int ttl, const std::string& hashed, bool *auth)
505 {
506 Bind2DNSRecord bdr;
507 shared_ptr<recordstorage_t> records = bb2.d_records.getWRITABLE();
508 bdr.qname=qname;
509
510 if(bb2.d_name.empty())
511 ;
512 else if(bdr.qname.isPartOf(bb2.d_name))
513 bdr.qname = bdr.qname.makeRelative(bb2.d_name);
514 else {
515 string msg = "Trying to insert non-zone data, name='"+bdr.qname.toLogString()+"', qtype="+qtype.getName()+", zone='"+bb2.d_name.toLogString()+"'";
516 if(s_ignore_broken_records) {
517 g_log<<Logger::Warning<<msg<< " ignored" << endl;
518 return;
519 }
520 else
521 throw PDNSException(msg);
522 }
523
524 // bdr.qname.swap(bdr.qname);
525
526 if(!records->empty() && bdr.qname==boost::prior(records->end())->qname)
527 bdr.qname=boost::prior(records->end())->qname;
528
529 bdr.qname=bdr.qname;
530 bdr.qtype=qtype.getCode();
531 bdr.content=content;
532 bdr.nsec3hash = hashed;
533
534 if (auth) // Set auth on empty non-terminals
535 bdr.auth=*auth;
536 else
537 bdr.auth=true;
538
539 bdr.ttl=ttl;
540 records->insert(bdr);
541 }
542
543 string Bind2Backend::DLReloadNowHandler(const vector<string>&parts, Utility::pid_t ppid)
544 {
545 ostringstream ret;
546
547 for(vector<string>::const_iterator i=parts.begin()+1;i<parts.end();++i) {
548 BB2DomainInfo bbd;
549 DNSName zone(*i);
550 if(safeGetBBDomainInfo(zone, &bbd)) {
551 Bind2Backend bb2;
552 bb2.queueReloadAndStore(bbd.d_id);
553 if (!safeGetBBDomainInfo(zone, &bbd)) // Read the *new* domain status
554 ret << *i << ": [missing]\n";
555 else
556 ret<< *i << ": "<< (bbd.d_wasRejectedLastReload ? "[rejected]": "") <<"\t"<<bbd.d_status<<"\n";
557 }
558 else
559 ret<< *i << " no such domain\n";
560 }
561 if(ret.str().empty())
562 ret<<"no domains reloaded";
563 return ret.str();
564 }
565
566
567 string Bind2Backend::DLDomStatusHandler(const vector<string>&parts, Utility::pid_t ppid)
568 {
569 ostringstream ret;
570
571 if(parts.size() > 1) {
572 for(vector<string>::const_iterator i=parts.begin()+1;i<parts.end();++i) {
573 BB2DomainInfo bbd;
574 if(safeGetBBDomainInfo(DNSName(*i), &bbd)) {
575 ret<< *i << ": "<< (bbd.d_loaded ? "": "[rejected]") <<"\t"<<bbd.d_status<<"\n";
576 }
577 else
578 ret<< *i << " no such domain\n";
579 }
580 }
581 else {
582 ReadLock rl(&s_state_lock);
583 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
584 ret<< i->d_name << ": "<< (i->d_loaded ? "": "[rejected]") <<"\t"<<i->d_status<<"\n";
585 }
586 }
587
588 if(ret.str().empty())
589 ret<<"no domains passed";
590
591 return ret.str();
592 }
593
594 string Bind2Backend::DLListRejectsHandler(const vector<string>&parts, Utility::pid_t ppid)
595 {
596 ostringstream ret;
597 ReadLock rl(&s_state_lock);
598 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
599 if(!i->d_loaded)
600 ret<<i->d_name<<"\t"<<i->d_status<<endl;
601 }
602 return ret.str();
603 }
604
605 string Bind2Backend::DLAddDomainHandler(const vector<string>&parts, Utility::pid_t ppid)
606 {
607 if(parts.size() < 3)
608 return "ERROR: Domain name and zone filename are required";
609
610 DNSName domainname(parts[1]);
611 const string &filename = parts[2];
612 BB2DomainInfo bbd;
613 if(safeGetBBDomainInfo(domainname, &bbd))
614 return "Already loaded";
615
616 if (!boost::starts_with(filename, "/") && ::arg()["chroot"].empty())
617 return "Unable to load zone " + domainname.toLogString() + " from " + filename + " as the filename is not absolute.";
618
619 struct stat buf;
620 if (stat(filename.c_str(), &buf) != 0)
621 return "Unable to load zone " + domainname.toLogString() + " from " + filename + ": " + strerror(errno);
622
623 Bind2Backend bb2; // createdomainentry needs access to our configuration
624 bbd=bb2.createDomainEntry(domainname, filename);
625 bbd.d_filename=filename;
626 bbd.d_checknow=true;
627 bbd.d_loaded=true;
628 bbd.d_lastcheck=0;
629 bbd.d_status="parsing into memory";
630 bbd.setCtime();
631
632 safePutBBDomainInfo(bbd);
633
634 g_log<<Logger::Warning<<"Zone "<<domainname<< " loaded"<<endl;
635 return "Loaded zone " + domainname.toLogString() + " from " + filename;
636 }
637
638 Bind2Backend::Bind2Backend(const string &suffix, bool loadZones)
639 {
640 d_getAllDomainMetadataQuery_stmt = NULL;
641 d_getDomainMetadataQuery_stmt = NULL;
642 d_deleteDomainMetadataQuery_stmt = NULL;
643 d_insertDomainMetadataQuery_stmt = NULL;
644 d_getDomainKeysQuery_stmt = NULL;
645 d_deleteDomainKeyQuery_stmt = NULL;
646 d_insertDomainKeyQuery_stmt = NULL;
647 d_GetLastInsertedKeyIdQuery_stmt = NULL;
648 d_activateDomainKeyQuery_stmt = NULL;
649 d_deactivateDomainKeyQuery_stmt = NULL;
650 d_getTSIGKeyQuery_stmt = NULL;
651 d_setTSIGKeyQuery_stmt = NULL;
652 d_deleteTSIGKeyQuery_stmt = NULL;
653 d_getTSIGKeysQuery_stmt = NULL;
654
655 setArgPrefix("bind"+suffix);
656 d_logprefix="[bind"+suffix+"backend]";
657 d_hybrid=mustDo("hybrid");
658 d_transaction_id=0;
659 s_ignore_broken_records=mustDo("ignore-broken-records");
660
661 if (!loadZones && d_hybrid)
662 return;
663
664 Lock l(&s_startup_lock);
665
666 setupDNSSEC();
667 if(!s_first) {
668 return;
669 }
670
671 if(loadZones) {
672 loadConfig();
673 s_first=0;
674 }
675
676 extern DynListener *dl;
677 dl->registerFunc("BIND-RELOAD-NOW", &DLReloadNowHandler, "bindbackend: reload domains", "<domains>");
678 dl->registerFunc("BIND-DOMAIN-STATUS", &DLDomStatusHandler, "bindbackend: list status of all domains", "[domains]");
679 dl->registerFunc("BIND-LIST-REJECTS", &DLListRejectsHandler, "bindbackend: list rejected domains");
680 dl->registerFunc("BIND-ADD-ZONE", &DLAddDomainHandler, "bindbackend: add zone", "<domain> <filename>");
681 }
682
683 Bind2Backend::~Bind2Backend()
684 { freeStatements(); } // deallocate statements
685
686 void Bind2Backend::rediscover(string *status)
687 {
688 loadConfig(status);
689 }
690
691 void Bind2Backend::reload()
692 {
693 WriteLock rwl(&s_state_lock);
694 for(state_t::iterator i = s_state.begin(); i != s_state.end() ; ++i) {
695 i->d_checknow=true; // being a bit cheeky here, don't index state_t on this (mutable)
696 }
697 }
698
699 void Bind2Backend::fixupOrderAndAuth(BB2DomainInfo& bbd, bool nsec3zone, NSEC3PARAMRecordContent ns3pr)
700 {
701 shared_ptr<recordstorage_t> records = bbd.d_records.getWRITABLE();
702
703 bool skip;
704 DNSName shorter;
705 set<DNSName> nssets, dssets;
706
707 for(const auto& bdr: *records) {
708 if(!bdr.qname.isRoot() && bdr.qtype == QType::NS)
709 nssets.insert(bdr.qname);
710 else if(bdr.qtype == QType::DS)
711 dssets.insert(bdr.qname);
712 }
713
714 for(auto iter = records->begin(); iter != records->end(); iter++) {
715 skip = false;
716 shorter = iter->qname;
717
718 if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
719 do {
720 if(nssets.count(shorter)) {
721 skip = true;
722 break;
723 }
724 } while(shorter.chopOff() && !iter->qname.isRoot());
725 }
726
727 iter->auth = (!skip && (iter->qtype == QType::DS || iter->qtype == QType::RRSIG || !nssets.count(iter->qname)));
728
729 if(!skip && nsec3zone && iter->qtype != QType::RRSIG && (iter->auth || (iter->qtype == QType::NS && !ns3pr.d_flags) || dssets.count(iter->qname))) {
730 Bind2DNSRecord bdr = *iter;
731 bdr.nsec3hash = toBase32Hex(hashQNameWithSalt(ns3pr, bdr.qname+bbd.d_name));
732 records->replace(iter, bdr);
733 }
734
735 // cerr<<iter->qname<<"\t"<<QType(iter->qtype).getName()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
736 }
737 }
738
739 void Bind2Backend::doEmptyNonTerminals(BB2DomainInfo& bbd, bool nsec3zone, NSEC3PARAMRecordContent ns3pr)
740 {
741 shared_ptr<const recordstorage_t> records = bbd.d_records.get();
742
743 bool auth;
744 DNSName shorter;
745 set<DNSName> qnames;
746 map<DNSName, bool> nonterm;
747
748 uint32_t maxent = ::arg().asNum("max-ent-entries");
749
750 for(const auto& bdr : *records)
751 qnames.insert(bdr.qname);
752
753 for(const auto& bdr : *records) {
754
755 if (!bdr.auth && bdr.qtype == QType::NS)
756 auth = (!nsec3zone || !ns3pr.d_flags);
757 else
758 auth = bdr.auth;
759
760 shorter = bdr.qname;
761 while(shorter.chopOff())
762 {
763 if(!qnames.count(shorter))
764 {
765 if(!(maxent))
766 {
767 g_log<<Logger::Error<<"Zone '"<<bbd.d_name<<"' has too many empty non terminals."<<endl;
768 return;
769 }
770
771 if (!nonterm.count(shorter)) {
772 nonterm.insert(pair<DNSName, bool>(shorter, auth));
773 --maxent;
774 } else if (auth)
775 nonterm[shorter] = true;
776 }
777 }
778 }
779
780 DNSResourceRecord rr;
781 rr.qtype = "#0";
782 rr.content = "";
783 rr.ttl = 0;
784 for(auto& nt : nonterm)
785 {
786 string hashed;
787 rr.qname = nt.first + bbd.d_name;
788 if(nsec3zone && nt.second)
789 hashed = toBase32Hex(hashQNameWithSalt(ns3pr, rr.qname));
790 insertRecord(bbd, rr.qname, rr.qtype, rr.content, rr.ttl, hashed, &nt.second);
791
792 // cerr<<rr.qname<<"\t"<<rr.qtype.getName()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
793 }
794 }
795
796 void Bind2Backend::loadConfig(string* status)
797 {
798 static int domain_id=1;
799
800 if(!getArg("config").empty()) {
801 BindParser BP;
802 try {
803 BP.parse(getArg("config"));
804 }
805 catch(PDNSException &ae) {
806 g_log<<Logger::Error<<"Error parsing bind configuration: "<<ae.reason<<endl;
807 throw;
808 }
809
810 vector<BindDomainInfo> domains=BP.getDomains();
811 this->alsoNotify = BP.getAlsoNotify();
812
813 s_binddirectory=BP.getDirectory();
814 // ZP.setDirectory(d_binddirectory);
815
816 g_log<<Logger::Warning<<d_logprefix<<" Parsing "<<domains.size()<<" domain(s), will report when done"<<endl;
817
818 set<DNSName> oldnames, newnames;
819 {
820 ReadLock rl(&s_state_lock);
821 for(const BB2DomainInfo& bbd : s_state) {
822 oldnames.insert(bbd.d_name);
823 }
824 }
825 int rejected=0;
826 int newdomains=0;
827
828 struct stat st;
829
830 for(vector<BindDomainInfo>::iterator i=domains.begin(); i!=domains.end(); ++i)
831 {
832 if(stat(i->filename.c_str(), &st) == 0) {
833 i->d_dev = st.st_dev;
834 i->d_ino = st.st_ino;
835 }
836 }
837
838 sort(domains.begin(), domains.end()); // put stuff in inode order
839 for(vector<BindDomainInfo>::const_iterator i=domains.begin();
840 i!=domains.end();
841 ++i)
842 {
843 if (!(i->hadFileDirective)) {
844 g_log<<Logger::Warning<<d_logprefix<<" Zone '"<<i->name<<"' has no 'file' directive set in "<<getArg("config")<<endl;
845 rejected++;
846 continue;
847 }
848
849 if(i->type == "")
850 g_log<<Logger::Notice<<d_logprefix<<" Zone '"<<i->name<<"' has no type specified, assuming 'native'"<<endl;
851 if(i->type!="master" && i->type!="slave" && i->type != "native" && i->type != "") {
852 g_log<<Logger::Warning<<d_logprefix<<" Warning! Skipping zone '"<<i->name<<"' because type '"<<i->type<<"' is invalid"<<endl;
853 rejected++;
854 continue;
855 }
856
857 BB2DomainInfo bbd;
858 bool isNew = false;
859
860 if(!safeGetBBDomainInfo(i->name, &bbd)) {
861 isNew = true;
862 bbd.d_id=domain_id++;
863 bbd.setCheckInterval(getArgAsNum("check-interval"));
864 bbd.d_lastnotified=0;
865 bbd.d_loaded=false;
866 }
867
868 // overwrite what we knew about the domain
869 bbd.d_name=i->name;
870 bool filenameChanged = (bbd.d_filename!=i->filename);
871 bbd.d_filename=i->filename;
872 bbd.d_masters=i->masters;
873 bbd.d_also_notify=i->alsoNotify;
874
875 bbd.d_kind = DomainInfo::Native;
876 if (i->type == "master")
877 bbd.d_kind = DomainInfo::Master;
878 if (i->type == "slave")
879 bbd.d_kind = DomainInfo::Slave;
880
881 newnames.insert(bbd.d_name);
882 if(filenameChanged || !bbd.d_loaded || !bbd.current()) {
883 g_log<<Logger::Info<<d_logprefix<<" parsing '"<<i->name<<"' from file '"<<i->filename<<"'"<<endl;
884
885 try {
886 parseZoneFile(&bbd);
887 }
888 catch(PDNSException &ae) {
889 ostringstream msg;
890 msg<<" error at "+nowTime()+" parsing '"<<i->name<<"' from file '"<<i->filename<<"': "<<ae.reason;
891
892 if(status)
893 *status+=msg.str();
894 bbd.d_status=msg.str();
895
896 g_log<<Logger::Warning<<d_logprefix<<msg.str()<<endl;
897 rejected++;
898 }
899 catch(std::system_error &ae) {
900 ostringstream msg;
901 if (ae.code().value() == ENOENT && isNew && i->type == "slave")
902 msg<<" error at "+nowTime()<<" no file found for new slave domain '"<<i->name<<"'. Has not been AXFR'd yet";
903 else
904 msg<<" error at "+nowTime()+" parsing '"<<i->name<<"' from file '"<<i->filename<<"': "<<ae.what();
905
906 if(status)
907 *status+=msg.str();
908 bbd.d_status=msg.str();
909 g_log<<Logger::Warning<<d_logprefix<<msg.str()<<endl;
910 rejected++;
911 }
912 catch(std::exception &ae) {
913 ostringstream msg;
914 msg<<" error at "+nowTime()+" parsing '"<<i->name<<"' from file '"<<i->filename<<"': "<<ae.what();
915
916 if(status)
917 *status+=msg.str();
918 bbd.d_status=msg.str();
919
920 g_log<<Logger::Warning<<d_logprefix<<msg.str()<<endl;
921 rejected++;
922 }
923 safePutBBDomainInfo(bbd);
924
925 }
926 }
927 vector<DNSName> diff;
928
929 set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
930 unsigned int remdomains=diff.size();
931
932 for(const DNSName& name: diff) {
933 safeRemoveBBDomainInfo(name);
934 }
935
936 // count number of entirely new domains
937 diff.clear();
938 set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
939 newdomains=diff.size();
940
941 ostringstream msg;
942 msg<<" Done parsing domains, "<<rejected<<" rejected, "<<newdomains<<" new, "<<remdomains<<" removed";
943 if(status)
944 *status=msg.str();
945
946 g_log<<Logger::Error<<d_logprefix<<msg.str()<<endl;
947 }
948 }
949
950 void Bind2Backend::queueReloadAndStore(unsigned int id)
951 {
952 BB2DomainInfo bbold;
953 try {
954 if(!safeGetBBDomainInfo(id, &bbold))
955 return;
956 BB2DomainInfo bbnew(bbold);
957 parseZoneFile(&bbnew);
958 bbnew.d_checknow=false;
959 bbnew.d_wasRejectedLastReload=false;
960 safePutBBDomainInfo(bbnew);
961 g_log<<Logger::Warning<<"Zone '"<<bbnew.d_name<<"' ("<<bbnew.d_filename<<") reloaded"<<endl;
962 }
963 catch(PDNSException &ae) {
964 ostringstream msg;
965 msg<<" error at "+nowTime()+" parsing '"<<bbold.d_name<<"' from file '"<<bbold.d_filename<<"': "<<ae.reason;
966 g_log<<Logger::Warning<<" error parsing '"<<bbold.d_name<<"' from file '"<<bbold.d_filename<<"': "<<ae.reason<<endl;
967 bbold.d_status=msg.str();
968 bbold.d_wasRejectedLastReload=true;
969 safePutBBDomainInfo(bbold);
970 }
971 catch(std::exception &ae) {
972 ostringstream msg;
973 msg<<" error at "+nowTime()+" parsing '"<<bbold.d_name<<"' from file '"<<bbold.d_filename<<"': "<<ae.what();
974 g_log<<Logger::Warning<<" error parsing '"<<bbold.d_name<<"' from file '"<<bbold.d_filename<<"': "<<ae.what()<<endl;
975 bbold.d_status=msg.str();
976 bbold.d_wasRejectedLastReload=true;
977 safePutBBDomainInfo(bbold);
978 }
979 }
980
981 bool Bind2Backend::findBeforeAndAfterUnhashed(BB2DomainInfo& bbd, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
982 {
983 shared_ptr<const recordstorage_t> records = bbd.d_records.get();
984
985 // for(const auto& record: *records)
986 // cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
987
988 recordstorage_t::const_iterator iterBefore, iterAfter;
989
990 iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
991
992 if(iterBefore != records->begin())
993 --iterBefore;
994 while((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
995 --iterBefore;
996 before=iterBefore->qname;
997
998 if(iterAfter == records->end()) {
999 iterAfter = records->begin();
1000 } else {
1001 while((!iterAfter->auth && iterAfter->qtype != QType::NS) || !iterAfter->qtype) {
1002 ++iterAfter;
1003 if(iterAfter == records->end()) {
1004 iterAfter = records->begin();
1005 break;
1006 }
1007 }
1008 }
1009 after = iterAfter->qname;
1010
1011 return true;
1012 }
1013
1014 bool Bind2Backend::getBeforeAndAfterNamesAbsolute(uint32_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
1015 {
1016 BB2DomainInfo bbd;
1017 if (!safeGetBBDomainInfo(id, &bbd))
1018 return false;
1019
1020 NSEC3PARAMRecordContent ns3pr;
1021
1022 bool nsec3zone;
1023 if (d_hybrid) {
1024 DNSSECKeeper dk;
1025 nsec3zone=dk.getNSEC3PARAM(bbd.d_name, &ns3pr);
1026 } else
1027 nsec3zone=getNSEC3PARAM(bbd.d_name, &ns3pr);
1028
1029 if(!nsec3zone) {
1030 return findBeforeAndAfterUnhashed(bbd, qname, unhashed, before, after);
1031 }
1032 else {
1033 auto& hashindex=boost::multi_index::get<NSEC3Tag>(*bbd.d_records.getWRITABLE());
1034
1035 // for(auto iter = first; iter != hashindex.end(); iter++)
1036 // cerr<<iter->nsec3hash<<endl;
1037
1038 auto first = hashindex.upper_bound("");
1039 auto iter = hashindex.upper_bound(qname.toStringNoDot());
1040
1041 if (iter == hashindex.end()) {
1042 --iter;
1043 before = DNSName(iter->nsec3hash);
1044 after = DNSName(first->nsec3hash);
1045 } else {
1046 after = DNSName(iter->nsec3hash);
1047 if (iter != first)
1048 --iter;
1049 else
1050 iter = --hashindex.end();
1051 before = DNSName(iter->nsec3hash);
1052 }
1053 unhashed = iter->qname+bbd.d_name;
1054
1055 return true;
1056 }
1057 }
1058
1059 void Bind2Backend::lookup(const QType &qtype, const DNSName &qname, int zoneId, DNSPacket *pkt_p )
1060 {
1061 d_handle.reset();
1062
1063 static bool mustlog=::arg().mustDo("query-logging");
1064
1065 bool found;
1066 DNSName domain;
1067 BB2DomainInfo bbd;
1068
1069 if(mustlog)
1070 g_log<<Logger::Warning<<"Lookup for '"<<qtype.getName()<<"' of '"<<qname<<"' within zoneID "<<zoneId<<endl;
1071
1072 if (zoneId >= 0) {
1073 if ((found = (safeGetBBDomainInfo(zoneId, &bbd) && qname.isPartOf(bbd.d_name)))) {
1074 domain = bbd.d_name;
1075 }
1076 } else {
1077 domain = qname;
1078 do {
1079 found = safeGetBBDomainInfo(domain, &bbd);
1080 } while (!found && qtype != QType::SOA && domain.chopOff());
1081 }
1082
1083 if(!found) {
1084 if(mustlog)
1085 g_log<<Logger::Warning<<"Found no authoritative zone for '"<<qname<<"' and/or id "<<bbd.d_id<<endl;
1086 d_handle.d_list=false;
1087 return;
1088 }
1089
1090 if(mustlog)
1091 g_log<<Logger::Warning<<"Found a zone '"<<domain<<"' (with id " << bbd.d_id<<") that might contain data "<<endl;
1092
1093 d_handle.id=bbd.d_id;
1094 d_handle.qname=qname.makeRelative(domain); // strip domain name
1095 d_handle.qtype=qtype;
1096 d_handle.domain=domain;
1097
1098 if(!bbd.d_loaded) {
1099 d_handle.reset();
1100 throw DBException("Zone for '"+bbd.d_name.toLogString()+"' in '"+bbd.d_filename+"' temporarily not available (file missing, or master dead)"); // fsck
1101 }
1102
1103 if(!bbd.current()) {
1104 g_log<<Logger::Warning<<"Zone '"<<bbd.d_name<<"' ("<<bbd.d_filename<<") needs reloading"<<endl;
1105 queueReloadAndStore(bbd.d_id);
1106 if (!safeGetBBDomainInfo(domain, &bbd))
1107 throw DBException("Zone '"+bbd.d_name.toLogString()+"' ("+bbd.d_filename+") gone after reload"); // if we don't throw here, we crash for some reason
1108 }
1109
1110 d_handle.d_records = bbd.d_records.get();
1111
1112 if(d_handle.d_records->empty())
1113 DLOG(g_log<<"Query with no results"<<endl);
1114
1115 d_handle.mustlog = mustlog;
1116
1117 auto& hashedidx = boost::multi_index::get<UnorderedNameTag>(*d_handle.d_records);
1118 auto range = hashedidx.equal_range(d_handle.qname);
1119
1120 if(range.first==range.second) {
1121 d_handle.d_list=false;
1122 d_handle.d_iter = d_handle.d_end_iter = range.first;
1123 return;
1124 }
1125 else {
1126 d_handle.d_iter=range.first;
1127 d_handle.d_end_iter=range.second;
1128 }
1129
1130 d_handle.d_list=false;
1131 }
1132
1133 Bind2Backend::handle::handle()
1134 {
1135 mustlog=false;
1136 }
1137
1138 bool Bind2Backend::get(DNSResourceRecord &r)
1139 {
1140 if(!d_handle.d_records) {
1141 if(d_handle.mustlog)
1142 g_log<<Logger::Warning<<"There were no answers"<<endl;
1143 return false;
1144 }
1145
1146 if(!d_handle.get(r)) {
1147 if(d_handle.mustlog)
1148 g_log<<Logger::Warning<<"End of answers"<<endl;
1149
1150 d_handle.reset();
1151
1152 return false;
1153 }
1154 if(d_handle.mustlog)
1155 g_log<<Logger::Warning<<"Returning: '"<<r.qtype.getName()<<"' of '"<<r.qname<<"', content: '"<<r.content<<"'"<<endl;
1156 return true;
1157 }
1158
1159 bool Bind2Backend::handle::get(DNSResourceRecord &r)
1160 {
1161 if(d_list)
1162 return get_list(r);
1163 else
1164 return get_normal(r);
1165 }
1166
1167 void Bind2Backend::handle::reset()
1168 {
1169 d_records.reset();
1170 qname.clear();
1171 mustlog=false;
1172 }
1173
1174 //#define DLOG(x) x
1175 bool Bind2Backend::handle::get_normal(DNSResourceRecord &r)
1176 {
1177 DLOG(g_log << "Bind2Backend get() was called for "<<qtype.getName() << " record for '"<<
1178 qname<<"' - "<<d_records->size()<<" available in total!"<<endl);
1179
1180 if(d_iter==d_end_iter) {
1181 return false;
1182 }
1183
1184 while(d_iter!=d_end_iter && !(qtype.getCode()==QType::ANY || (d_iter)->qtype==qtype.getCode())) {
1185 DLOG(g_log<<Logger::Warning<<"Skipped "<<qname<<"/"<<QType(d_iter->qtype).getName()<<": '"<<d_iter->content<<"'"<<endl);
1186 d_iter++;
1187 }
1188 if(d_iter==d_end_iter) {
1189 return false;
1190 }
1191 DLOG(g_log << "Bind2Backend get() returning a rr with a "<<QType(d_iter->qtype).getCode()<<endl);
1192
1193 r.qname=qname.empty() ? domain : (qname+domain);
1194 r.domain_id=id;
1195 r.content=(d_iter)->content;
1196 // r.domain_id=(d_iter)->domain_id;
1197 r.qtype=(d_iter)->qtype;
1198 r.ttl=(d_iter)->ttl;
1199
1200 //if(!d_iter->auth && r.qtype.getCode() != QType::A && r.qtype.getCode()!=QType::AAAA && r.qtype.getCode() != QType::NS)
1201 // cerr<<"Warning! Unauth response for qtype "<< r.qtype.getName() << " for '"<<r.qname<<"'"<<endl;
1202 r.auth = d_iter->auth;
1203
1204 d_iter++;
1205
1206 return true;
1207 }
1208
1209 bool Bind2Backend::list(const DNSName& target, int id, bool include_disabled)
1210 {
1211 BB2DomainInfo bbd;
1212
1213 if(!safeGetBBDomainInfo(id, &bbd))
1214 return false;
1215
1216 d_handle.reset();
1217 DLOG(g_log<<"Bind2Backend constructing handle for list of "<<id<<endl);
1218
1219 d_handle.d_records=bbd.d_records.get(); // give it a copy, which will stay around
1220 d_handle.d_qname_iter= d_handle.d_records->begin();
1221 d_handle.d_qname_end=d_handle.d_records->end(); // iter now points to a vector of pointers to vector<BBResourceRecords>
1222
1223 d_handle.id=id;
1224 d_handle.domain=bbd.d_name;
1225 d_handle.d_list=true;
1226 return true;
1227 }
1228
1229 bool Bind2Backend::handle::get_list(DNSResourceRecord &r)
1230 {
1231 if(d_qname_iter!=d_qname_end) {
1232 r.qname=d_qname_iter->qname.empty() ? domain : (d_qname_iter->qname+domain);
1233 r.domain_id=id;
1234 r.content=(d_qname_iter)->content;
1235 r.qtype=(d_qname_iter)->qtype;
1236 r.ttl=(d_qname_iter)->ttl;
1237 r.auth = d_qname_iter->auth;
1238 d_qname_iter++;
1239 return true;
1240 }
1241 return false;
1242 }
1243
1244 bool Bind2Backend::superMasterBackend(const string &ip, const DNSName& domain, const vector<DNSResourceRecord>&nsset, string *nameserver, string *account, DNSBackend **db)
1245 {
1246 // Check whether we have a configfile available.
1247 if (getArg("supermaster-config").empty())
1248 return false;
1249
1250 ifstream c_if(getArg("supermasters").c_str(), std::ios::in); // this was nocreate?
1251 if (!c_if) {
1252 g_log << Logger::Error << "Unable to open supermasters file for read: " << stringerror() << endl;
1253 return false;
1254 }
1255
1256 // Format:
1257 // <ip> <accountname>
1258 string line, sip, saccount;
1259 while (getline(c_if, line)) {
1260 std::istringstream ii(line);
1261 ii >> sip;
1262 if (sip == ip) {
1263 ii >> saccount;
1264 break;
1265 }
1266 }
1267 c_if.close();
1268
1269 if (sip != ip) // ip not found in authorization list - reject
1270 return false;
1271
1272 // ip authorized as supermaster - accept
1273 *db = this;
1274 if (saccount.length() > 0)
1275 *account = saccount.c_str();
1276
1277 return true;
1278 }
1279
1280 BB2DomainInfo Bind2Backend::createDomainEntry(const DNSName& domain, const string &filename)
1281 {
1282 int newid=1;
1283 { // Find a free zone id nr.
1284 ReadLock rl(&s_state_lock);
1285 if (!s_state.empty()) {
1286 newid = s_state.rbegin()->d_id+1;
1287 }
1288 }
1289
1290 BB2DomainInfo bbd;
1291 bbd.d_kind = DomainInfo::Native;
1292 bbd.d_id = newid;
1293 bbd.d_records = shared_ptr<recordstorage_t >(new recordstorage_t);
1294 bbd.d_name = domain;
1295 bbd.setCheckInterval(getArgAsNum("check-interval"));
1296 bbd.d_filename = filename;
1297
1298 return bbd;
1299 }
1300
1301 bool Bind2Backend::createSlaveDomain(const string &ip, const DNSName& domain, const string &nameserver, const string &account)
1302 {
1303 string filename = getArg("supermaster-destdir")+'/'+domain.toStringNoDot();
1304
1305 g_log << Logger::Warning << d_logprefix
1306 << " Writing bind config zone statement for superslave zone '" << domain
1307 << "' from supermaster " << ip << endl;
1308
1309 {
1310 Lock l2(&s_supermaster_config_lock);
1311
1312 ofstream c_of(getArg("supermaster-config").c_str(), std::ios::app);
1313 if (!c_of) {
1314 g_log << Logger::Error << "Unable to open supermaster configfile for append: " << stringerror() << endl;
1315 throw DBException("Unable to open supermaster configfile for append: "+stringerror());
1316 }
1317
1318 c_of << endl;
1319 c_of << "# Superslave zone '" << domain.toString() << "' (added: " << nowTime() << ") (account: " << account << ')' << endl;
1320 c_of << "zone \"" << domain.toStringNoDot() << "\" {" << endl;
1321 c_of << "\ttype slave;" << endl;
1322 c_of << "\tfile \"" << filename << "\";" << endl;
1323 c_of << "\tmasters { " << ip << "; };" << endl;
1324 c_of << "};" << endl;
1325 c_of.close();
1326 }
1327
1328 BB2DomainInfo bbd = createDomainEntry(domain, filename);
1329 bbd.d_kind = DomainInfo::Slave;
1330 bbd.d_masters.push_back(ComboAddress(ip, 53));
1331 bbd.setCtime();
1332 safePutBBDomainInfo(bbd);
1333 return true;
1334 }
1335
1336 bool Bind2Backend::searchRecords(const string &pattern, int maxResults, vector<DNSResourceRecord>& result)
1337 {
1338 SimpleMatch sm(pattern,true);
1339 static bool mustlog=::arg().mustDo("query-logging");
1340 if(mustlog)
1341 g_log<<Logger::Warning<<"Search for pattern '"<<pattern<<"'"<<endl;
1342
1343 {
1344 ReadLock rl(&s_state_lock);
1345
1346 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
1347 BB2DomainInfo h;
1348 if (!safeGetBBDomainInfo(i->d_id, &h)) {
1349 continue;
1350 }
1351
1352 shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
1353
1354 for(recordstorage_t::const_iterator ri = rhandle->begin(); result.size() < static_cast<vector<DNSResourceRecord>::size_type>(maxResults) && ri != rhandle->end(); ri++) {
1355 DNSName name = ri->qname.empty() ? i->d_name : (ri->qname+i->d_name);
1356 if (sm.match(name) || sm.match(ri->content)) {
1357 DNSResourceRecord r;
1358 r.qname=name;
1359 r.domain_id=i->d_id;
1360 r.content=ri->content;
1361 r.qtype=ri->qtype;
1362 r.ttl=ri->ttl;
1363 r.auth = ri->auth;
1364 result.push_back(r);
1365 }
1366 }
1367 }
1368 }
1369
1370 return true;
1371 }
1372
1373 class Bind2Factory : public BackendFactory
1374 {
1375 public:
1376 Bind2Factory() : BackendFactory("bind") {}
1377
1378 void declareArguments(const string &suffix="")
1379 {
1380 declare(suffix,"ignore-broken-records","Ignore records that are out-of-bound for the zone.","no");
1381 declare(suffix,"config","Location of named.conf","");
1382 declare(suffix,"check-interval","Interval for zonefile changes","0");
1383 declare(suffix,"supermaster-config","Location of (part of) named.conf where pdns can write zone-statements to","");
1384 declare(suffix,"supermasters","List of IP-addresses of supermasters","");
1385 declare(suffix,"supermaster-destdir","Destination directory for newly added slave zones",::arg()["config-dir"]);
1386 declare(suffix,"dnssec-db","Filename to store & access our DNSSEC metadatabase, empty for none", "");
1387 declare(suffix,"dnssec-db-journal-mode","SQLite3 journal mode", "WAL");
1388 declare(suffix,"hybrid","Store DNSSEC metadata in other backend","no");
1389 }
1390
1391 DNSBackend *make(const string &suffix="")
1392 {
1393 assertEmptySuffix(suffix);
1394 return new Bind2Backend(suffix);
1395 }
1396
1397 DNSBackend *makeMetadataOnly(const string &suffix="")
1398 {
1399 assertEmptySuffix(suffix);
1400 return new Bind2Backend(suffix, false);
1401 }
1402 private:
1403 void assertEmptySuffix(const string &suffix)
1404 {
1405 if(suffix.length())
1406 throw PDNSException("launch= suffixes are not supported on the bindbackend");
1407 }
1408 };
1409
1410 //! Magic class that is activated when the dynamic library is loaded
1411 class Bind2Loader
1412 {
1413 public:
1414 Bind2Loader()
1415 {
1416 BackendMakers().report(new Bind2Factory);
1417 g_log << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
1418 #ifndef REPRODUCIBLE
1419 << " (" __DATE__ " " __TIME__ ")"
1420 #endif
1421 #ifdef HAVE_SQLITE3
1422 << " (with bind-dnssec-db support)"
1423 #endif
1424 << " reporting" << endl;
1425 }
1426 };
1427 static Bind2Loader bind2loader;