2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
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.
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.
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.
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.
29 #include <sys/types.h>
35 #include <boost/algorithm/string.hpp>
36 #include <system_error>
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"
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.
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.
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).
68 Parsing zones happens with parseZone(), which fills a BB2DomainInfo object. This can then be stored with safePutBBDomainInfo.
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.
74 Bind2Backend::state_t
Bind2Backend::s_state
;
75 int Bind2Backend::s_first
=1;
76 bool Bind2Backend::s_ignore_broken_records
=false;
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
;
83 BB2DomainInfo::BB2DomainInfo()
91 void BB2DomainInfo::setCheckInterval(time_t seconds
)
93 d_checkinterval
=seconds
;
96 bool BB2DomainInfo::current()
105 if(time(0) - d_lastcheck
< d_checkinterval
)
108 if(d_filename
.empty())
111 return (getCtime()==d_ctime
);
114 time_t BB2DomainInfo::getCtime()
118 if(d_filename
.empty() || stat(d_filename
.c_str(),&buf
)<0)
124 void BB2DomainInfo::setCtime()
127 if(stat(d_filename
.c_str(),&buf
)<0)
129 d_ctime
=buf
.st_ctime
;
132 bool Bind2Backend::safeGetBBDomainInfo(int id
, BB2DomainInfo
* bbd
)
134 ReadLock
rl(&s_state_lock
);
135 state_t::const_iterator iter
= s_state
.find(id
);
136 if(iter
== s_state
.end())
142 bool Bind2Backend::safeGetBBDomainInfo(const DNSName
& name
, BB2DomainInfo
* bbd
)
144 ReadLock
rl(&s_state_lock
);
145 typedef state_t::index
<NameTag
>::type nameindex_t
;
146 nameindex_t
& nameindex
= boost::multi_index::get
<NameTag
>(s_state
);
148 nameindex_t::const_iterator iter
= nameindex
.find(name
);
149 if(iter
== nameindex
.end())
155 bool Bind2Backend::safeRemoveBBDomainInfo(const DNSName
& name
)
157 WriteLock
rl(&s_state_lock
);
158 typedef state_t::index
<NameTag
>::type nameindex_t
;
159 nameindex_t
& nameindex
= boost::multi_index::get
<NameTag
>(s_state
);
161 nameindex_t::iterator iter
= nameindex
.find(name
);
162 if(iter
== nameindex
.end())
164 nameindex
.erase(iter
);
168 void Bind2Backend::safePutBBDomainInfo(const BB2DomainInfo
& bbd
)
170 WriteLock
rl(&s_state_lock
);
171 replacing_insert(s_state
, bbd
);
174 void Bind2Backend::setNotified(uint32_t id
, uint32_t serial
)
177 if (!safeGetBBDomainInfo(id
, &bbd
))
179 bbd
.d_lastnotified
= serial
;
180 safePutBBDomainInfo(bbd
);
183 void Bind2Backend::setFresh(uint32_t domain_id
)
186 if(safeGetBBDomainInfo(domain_id
, &bbd
)) {
187 bbd
.d_lastcheck
=time(0);
188 safePutBBDomainInfo(bbd
);
192 bool Bind2Backend::startTransaction(const DNSName
&qname
, int id
)
195 d_transaction_tmpname
.clear();
200 throw DBException("domain_id 0 is invalid for this backend.");
205 if(safeGetBBDomainInfo(id
, &bbd
)) {
206 d_transaction_tmpname
=bbd
.d_filename
+"."+itoa(random());
207 d_of
=std::unique_ptr
<ofstream
>(new ofstream(d_transaction_tmpname
.c_str()));
209 unlink(d_transaction_tmpname
.c_str());
211 throw DBException("Unable to open temporary zonefile '"+d_transaction_tmpname
+"': "+stringerror());
214 *d_of
<<"; Written by PowerDNS, don't edit!"<<endl
;
215 *d_of
<<"; Zone '"<<bbd
.d_name
<<"' retrieved from master "<<endl
<<"; at "<<nowTime()<<endl
; // insert master info here again
222 bool Bind2Backend::commitTransaction()
224 if(d_transaction_id
< 0)
229 if(safeGetBBDomainInfo(d_transaction_id
, &bbd
)) {
230 if(rename(d_transaction_tmpname
.c_str(), bbd
.d_filename
.c_str())<0)
231 throw DBException("Unable to commit (rename to: '" + bbd
.d_filename
+"') AXFRed zone: "+stringerror());
232 queueReloadAndStore(bbd
.d_id
);
240 bool Bind2Backend::abortTransaction()
242 // -1 = dnssec speciality
243 // 0 = invalid transact
244 // >0 = actual transaction
245 if(d_transaction_id
> 0) {
246 unlink(d_transaction_tmpname
.c_str());
254 bool Bind2Backend::feedRecord(const DNSResourceRecord
&rr
, const DNSName
&ordername
)
257 if (!safeGetBBDomainInfo(d_transaction_id
, &bbd
))
261 string name
= bbd
.d_name
.toString();
262 if (bbd
.d_name
.empty()) {
263 qname
= rr
.qname
.toString();
265 else if (rr
.qname
.isPartOf(bbd
.d_name
)) {
266 if (rr
.qname
== bbd
.d_name
) {
270 DNSName relName
= rr
.qname
.makeRelative(bbd
.d_name
);
271 qname
= relName
.toStringNoDot();
275 throw DBException("out-of-zone data '"+rr
.qname
.toLogString()+"' during AXFR of zone '"+bbd
.d_name
.toLogString()+"'");
278 shared_ptr
<DNSRecordContent
> drc(DNSRecordContent::mastermake(rr
.qtype
.getCode(), 1, rr
.content
));
279 string content
= drc
->getZoneRepresentation();
281 // SOA needs stripping too! XXX FIXME - also, this should not be here I think
282 switch(rr
.qtype
.getCode()) {
288 stripDomainSuffix(&content
, name
);
292 *d_of
<<qname
<<"\t"<<rr
.ttl
<<"\t"<<rr
.qtype
.getName()<<"\t"<<content
<<endl
;
298 void Bind2Backend::getUpdatedMasters(vector
<DomainInfo
> *changedDomains
)
300 vector
<DomainInfo
> consider
;
302 ReadLock
rl(&s_state_lock
);
304 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
305 if(i
->d_kind
!= DomainInfo::Master
&& this->alsoNotify
.empty() && i
->d_also_notify
.empty())
311 di
.last_check
=i
->d_lastcheck
;
312 di
.notified_serial
=i
->d_lastnotified
;
314 di
.kind
=DomainInfo::Master
;
315 consider
.push_back(di
);
320 for(DomainInfo
& di
: consider
) {
323 this->getSOA(di
.zone
, soadata
); // we might not *have* a SOA yet, but this might trigger a load of it
328 if(di
.notified_serial
!= soadata
.serial
) {
330 if(safeGetBBDomainInfo(di
.id
, &bbd
)) {
331 bbd
.d_lastnotified
=soadata
.serial
;
332 safePutBBDomainInfo(bbd
);
334 if(di
.notified_serial
) { // don't do notification storm on startup
335 di
.serial
=soadata
.serial
;
336 changedDomains
->push_back(di
);
342 void Bind2Backend::getAllDomains(vector
<DomainInfo
> *domains
, bool include_disabled
)
346 // prevent deadlock by using getSOA() later on
348 ReadLock
rl(&s_state_lock
);
350 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
354 di
.last_check
=i
->d_lastcheck
;
356 di
.masters
=i
->d_masters
;
358 domains
->push_back(di
);
362 for(DomainInfo
&di
: *domains
) {
363 // do not corrupt di if domain supplied by another backend.
364 if (di
.backend
!= this)
366 this->getSOA(di
.zone
, soadata
);
367 di
.serial
=soadata
.serial
;
371 void Bind2Backend::getUnfreshSlaveInfos(vector
<DomainInfo
> *unfreshDomains
)
373 vector
<DomainInfo
> domains
;
375 ReadLock
rl(&s_state_lock
);
376 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
377 if(i
->d_kind
!= DomainInfo::Slave
)
382 sd
.masters
=i
->d_masters
;
383 sd
.last_check
=i
->d_lastcheck
;
385 sd
.kind
=DomainInfo::Slave
;
386 domains
.push_back(sd
);
390 for(DomainInfo
&sd
: domains
) {
395 getSOA(sd
.zone
,soadata
); // we might not *have* a SOA yet
398 sd
.serial
=soadata
.serial
;
399 if(sd
.last_check
+soadata
.refresh
< (unsigned int)time(0))
400 unfreshDomains
->push_back(sd
);
404 bool Bind2Backend::getDomainInfo(const DNSName
& domain
, DomainInfo
&di
)
407 if(!safeGetBBDomainInfo(domain
, &bbd
))
412 di
.masters
=bbd
.d_masters
;
413 di
.last_check
=bbd
.d_lastcheck
;
421 getSOA(bbd
.d_name
,sd
); // we might not *have* a SOA yet
429 void Bind2Backend::alsoNotifies(const DNSName
& domain
, set
<string
> *ips
)
431 // combine global list with local list
432 for(set
<string
>::iterator i
= this->alsoNotify
.begin(); i
!= this->alsoNotify
.end(); i
++) {
435 ReadLock
rl(&s_state_lock
);
436 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
437 if(i
->d_name
== domain
) {
438 for(set
<string
>::iterator it
= i
->d_also_notify
.begin(); it
!= i
->d_also_notify
.end(); it
++) {
446 // only parses, does NOT add to s_state!
447 void Bind2Backend::parseZoneFile(BB2DomainInfo
*bbd
)
449 NSEC3PARAMRecordContent ns3pr
;
453 nsec3zone
=dk
.getNSEC3PARAM(bbd
->d_name
, &ns3pr
);
455 nsec3zone
=getNSEC3PARAM(bbd
->d_name
, &ns3pr
);
457 bbd
->d_records
= shared_ptr
<recordstorage_t
>(new recordstorage_t());
459 ZoneParserTNG
zpt(bbd
->d_filename
, bbd
->d_name
, s_binddirectory
);
460 DNSResourceRecord rr
;
463 if(rr
.qtype
.getCode() == QType::NSEC
|| rr
.qtype
.getCode() == QType::NSEC3
)
464 continue; // we synthesise NSECs on demand
466 insertRecord(*bbd
, rr
.qname
, rr
.qtype
, rr
.content
, rr
.ttl
, "");
468 fixupOrderAndAuth(*bbd
, nsec3zone
, ns3pr
);
469 doEmptyNonTerminals(*bbd
, nsec3zone
, ns3pr
);
472 bbd
->d_checknow
=false;
473 bbd
->d_status
="parsed into memory at "+nowTime();
476 /** THIS IS AN INTERNAL FUNCTION! It does moadnsparser prio impedance matching
477 Much of the complication is due to the efforts to benefit from std::string reference counting copy on write semantics */
478 void Bind2Backend::insertRecord(BB2DomainInfo
& bb2
, const DNSName
&qname
, const QType
&qtype
, const string
&content
, int ttl
, const std::string
& hashed
, bool *auth
)
481 shared_ptr
<recordstorage_t
> records
= bb2
.d_records
.getWRITABLE();
484 if(bb2
.d_name
.empty())
486 else if(bdr
.qname
.isPartOf(bb2
.d_name
))
487 bdr
.qname
= bdr
.qname
.makeRelative(bb2
.d_name
);
489 string msg
= "Trying to insert non-zone data, name='"+bdr
.qname
.toLogString()+"', qtype="+qtype
.getName()+", zone='"+bb2
.d_name
.toLogString()+"'";
490 if(s_ignore_broken_records
) {
491 L
<<Logger::Warning
<<msg
<< " ignored" << endl
;
495 throw PDNSException(msg
);
498 // bdr.qname.swap(bdr.qname);
500 if(!records
->empty() && bdr
.qname
==boost::prior(records
->end())->qname
)
501 bdr
.qname
=boost::prior(records
->end())->qname
;
504 bdr
.qtype
=qtype
.getCode();
506 bdr
.nsec3hash
= hashed
;
508 if (auth
) // Set auth on empty non-terminals
514 records
->insert(bdr
);
517 string
Bind2Backend::DLReloadNowHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
521 for(vector
<string
>::const_iterator i
=parts
.begin()+1;i
<parts
.end();++i
) {
524 if(safeGetBBDomainInfo(zone
, &bbd
)) {
526 bb2
.queueReloadAndStore(bbd
.d_id
);
527 if (!safeGetBBDomainInfo(zone
, &bbd
)) // Read the *new* domain status
528 ret
<< *i
<< ": [missing]\n";
530 ret
<< *i
<< ": "<< (bbd
.d_wasRejectedLastReload
? "[rejected]": "") <<"\t"<<bbd
.d_status
<<"\n";
533 ret
<< *i
<< " no such domain\n";
535 if(ret
.str().empty())
536 ret
<<"no domains reloaded";
541 string
Bind2Backend::DLDomStatusHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
545 if(parts
.size() > 1) {
546 for(vector
<string
>::const_iterator i
=parts
.begin()+1;i
<parts
.end();++i
) {
548 if(safeGetBBDomainInfo(DNSName(*i
), &bbd
)) {
549 ret
<< *i
<< ": "<< (bbd
.d_loaded
? "": "[rejected]") <<"\t"<<bbd
.d_status
<<"\n";
552 ret
<< *i
<< " no such domain\n";
556 ReadLock
rl(&s_state_lock
);
557 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
558 ret
<< i
->d_name
<< ": "<< (i
->d_loaded
? "": "[rejected]") <<"\t"<<i
->d_status
<<"\n";
562 if(ret
.str().empty())
563 ret
<<"no domains passed";
568 string
Bind2Backend::DLListRejectsHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
571 ReadLock
rl(&s_state_lock
);
572 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
574 ret
<<i
->d_name
<<"\t"<<i
->d_status
<<endl
;
579 string
Bind2Backend::DLAddDomainHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
582 return "ERROR: Domain name and zone filename are required";
584 DNSName
domainname(parts
[1]);
585 const string
&filename
= parts
[2];
587 if(safeGetBBDomainInfo(domainname
, &bbd
))
588 return "Already loaded";
590 if (!boost::starts_with(filename
, "/") && ::arg()["chroot"].empty())
591 return "Unable to load zone " + domainname
.toLogString() + " from " + filename
+ " as the filename is not absolute.";
594 if (stat(filename
.c_str(), &buf
) != 0)
595 return "Unable to load zone " + domainname
.toLogString() + " from " + filename
+ ": " + strerror(errno
);
597 Bind2Backend bb2
; // createdomainentry needs access to our configuration
598 bbd
=bb2
.createDomainEntry(domainname
, filename
);
599 bbd
.d_filename
=filename
;
603 bbd
.d_status
="parsing into memory";
605 safePutBBDomainInfo(bbd
);
607 L
<<Logger::Warning
<<"Zone "<<domainname
<< " loaded"<<endl
;
608 return "Loaded zone " + domainname
.toLogString() + " from " + filename
;
611 Bind2Backend::Bind2Backend(const string
&suffix
, bool loadZones
)
613 d_getAllDomainMetadataQuery_stmt
= NULL
;
614 d_getDomainMetadataQuery_stmt
= NULL
;
615 d_deleteDomainMetadataQuery_stmt
= NULL
;
616 d_insertDomainMetadataQuery_stmt
= NULL
;
617 d_getDomainKeysQuery_stmt
= NULL
;
618 d_deleteDomainKeyQuery_stmt
= NULL
;
619 d_insertDomainKeyQuery_stmt
= NULL
;
620 d_GetLastInsertedKeyIdQuery_stmt
= NULL
;
621 d_activateDomainKeyQuery_stmt
= NULL
;
622 d_deactivateDomainKeyQuery_stmt
= NULL
;
623 d_getTSIGKeyQuery_stmt
= NULL
;
624 d_setTSIGKeyQuery_stmt
= NULL
;
625 d_deleteTSIGKeyQuery_stmt
= NULL
;
626 d_getTSIGKeysQuery_stmt
= NULL
;
628 setArgPrefix("bind"+suffix
);
629 d_logprefix
="[bind"+suffix
+"backend]";
630 d_hybrid
=mustDo("hybrid");
631 s_ignore_broken_records
=mustDo("ignore-broken-records");
633 if (!loadZones
&& d_hybrid
)
636 Lock
l(&s_startup_lock
);
649 extern DynListener
*dl
;
650 dl
->registerFunc("BIND-RELOAD-NOW", &DLReloadNowHandler
, "bindbackend: reload domains", "<domains>");
651 dl
->registerFunc("BIND-DOMAIN-STATUS", &DLDomStatusHandler
, "bindbackend: list status of all domains", "[domains]");
652 dl
->registerFunc("BIND-LIST-REJECTS", &DLListRejectsHandler
, "bindbackend: list rejected domains");
653 dl
->registerFunc("BIND-ADD-ZONE", &DLAddDomainHandler
, "bindbackend: add zone", "<domain> <filename>");
656 Bind2Backend::~Bind2Backend()
657 { freeStatements(); } // deallocate statements
659 void Bind2Backend::rediscover(string
*status
)
664 void Bind2Backend::reload()
666 WriteLock
rwl(&s_state_lock
);
667 for(state_t::iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
668 i
->d_checknow
=true; // being a bit cheeky here, don't index state_t on this (mutable)
672 void Bind2Backend::fixupOrderAndAuth(BB2DomainInfo
& bbd
, bool nsec3zone
, NSEC3PARAMRecordContent ns3pr
)
674 shared_ptr
<recordstorage_t
> records
= bbd
.d_records
.getWRITABLE();
678 set
<DNSName
> nssets
, dssets
;
680 for(const auto& bdr
: *records
) {
681 if(!bdr
.qname
.isRoot() && bdr
.qtype
== QType::NS
)
682 nssets
.insert(bdr
.qname
);
683 else if(bdr
.qtype
== QType::DS
)
684 dssets
.insert(bdr
.qname
);
687 for(auto iter
= records
->begin(); iter
!= records
->end(); iter
++) {
689 shorter
= iter
->qname
;
691 if (!iter
->qname
.isRoot() && shorter
.chopOff() && !iter
->qname
.isRoot()) {
693 if(nssets
.count(shorter
)) {
697 } while(shorter
.chopOff() && !iter
->qname
.isRoot());
700 iter
->auth
= (!skip
&& (iter
->qtype
== QType::DS
|| iter
->qtype
== QType::RRSIG
|| !nssets
.count(iter
->qname
)));
702 if(!skip
&& nsec3zone
&& iter
->qtype
!= QType::RRSIG
&& (iter
->auth
|| (iter
->qtype
== QType::NS
&& !ns3pr
.d_flags
) || dssets
.count(iter
->qname
))) {
703 Bind2DNSRecord bdr
= *iter
;
704 bdr
.nsec3hash
= toBase32Hex(hashQNameWithSalt(ns3pr
, bdr
.qname
+bbd
.d_name
));
705 records
->replace(iter
, bdr
);
708 // cerr<<iter->qname<<"\t"<<QType(iter->qtype).getName()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
712 void Bind2Backend::doEmptyNonTerminals(BB2DomainInfo
& bbd
, bool nsec3zone
, NSEC3PARAMRecordContent ns3pr
)
714 shared_ptr
<const recordstorage_t
> records
= bbd
.d_records
.get();
719 map
<DNSName
, bool> nonterm
;
721 uint32_t maxent
= ::arg().asNum("max-ent-entries");
723 for(const auto& bdr
: *records
)
724 qnames
.insert(bdr
.qname
);
726 for(const auto& bdr
: *records
) {
728 if (!bdr
.auth
&& bdr
.qtype
== QType::NS
)
729 auth
= (!nsec3zone
|| !ns3pr
.d_flags
);
734 while(shorter
.chopOff())
736 if(!qnames
.count(shorter
))
740 L
<<Logger::Error
<<"Zone '"<<bbd
.d_name
<<"' has too many empty non terminals."<<endl
;
744 if (!nonterm
.count(shorter
)) {
745 nonterm
.insert(pair
<DNSName
, bool>(shorter
, auth
));
748 nonterm
[shorter
] = true;
753 DNSResourceRecord rr
;
757 for(auto& nt
: nonterm
)
760 rr
.qname
= nt
.first
+ bbd
.d_name
;
761 if(nsec3zone
&& nt
.second
)
762 hashed
= toBase32Hex(hashQNameWithSalt(ns3pr
, rr
.qname
));
763 insertRecord(bbd
, rr
.qname
, rr
.qtype
, rr
.content
, rr
.ttl
, hashed
, &nt
.second
);
765 // cerr<<rr.qname<<"\t"<<rr.qtype.getName()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
769 void Bind2Backend::loadConfig(string
* status
)
771 static int domain_id
=1;
773 if(!getArg("config").empty()) {
776 BP
.parse(getArg("config"));
778 catch(PDNSException
&ae
) {
779 L
<<Logger::Error
<<"Error parsing bind configuration: "<<ae
.reason
<<endl
;
783 vector
<BindDomainInfo
> domains
=BP
.getDomains();
784 this->alsoNotify
= BP
.getAlsoNotify();
786 s_binddirectory
=BP
.getDirectory();
787 // ZP.setDirectory(d_binddirectory);
789 L
<<Logger::Warning
<<d_logprefix
<<" Parsing "<<domains
.size()<<" domain(s), will report when done"<<endl
;
791 set
<DNSName
> oldnames
, newnames
;
793 ReadLock
rl(&s_state_lock
);
794 for(const BB2DomainInfo
& bbd
: s_state
) {
795 oldnames
.insert(bbd
.d_name
);
803 for(vector
<BindDomainInfo
>::iterator i
=domains
.begin(); i
!=domains
.end(); ++i
)
805 if(stat(i
->filename
.c_str(), &st
) == 0) {
806 i
->d_dev
= st
.st_dev
;
807 i
->d_ino
= st
.st_ino
;
811 sort(domains
.begin(), domains
.end()); // put stuff in inode order
812 for(vector
<BindDomainInfo
>::const_iterator i
=domains
.begin();
816 if (!(i
->hadFileDirective
)) {
817 L
<<Logger::Warning
<<d_logprefix
<<" Zone '"<<i
->name
<<"' has no 'file' directive set in "<<getArg("config")<<endl
;
823 L
<<Logger::Notice
<<d_logprefix
<<" Zone '"<<i
->name
<<"' has no type specified, assuming 'native'"<<endl
;
824 if(i
->type
!="master" && i
->type
!="slave" && i
->type
!= "native" && i
->type
!= "") {
825 L
<<Logger::Warning
<<d_logprefix
<<" Warning! Skipping zone '"<<i
->name
<<"' because type '"<<i
->type
<<"' is invalid"<<endl
;
833 if(!safeGetBBDomainInfo(i
->name
, &bbd
)) {
835 bbd
.d_id
=domain_id
++;
836 bbd
.setCheckInterval(getArgAsNum("check-interval"));
837 bbd
.d_lastnotified
=0;
841 // overwrite what we knew about the domain
843 bool filenameChanged
= (bbd
.d_filename
!=i
->filename
);
844 bbd
.d_filename
=i
->filename
;
845 bbd
.d_masters
=i
->masters
;
846 bbd
.d_also_notify
=i
->alsoNotify
;
848 bbd
.d_kind
= DomainInfo::Native
;
849 if (i
->type
== "master")
850 bbd
.d_kind
= DomainInfo::Master
;
851 if (i
->type
== "slave")
852 bbd
.d_kind
= DomainInfo::Slave
;
854 newnames
.insert(bbd
.d_name
);
855 if(filenameChanged
|| !bbd
.d_loaded
|| !bbd
.current()) {
856 L
<<Logger::Info
<<d_logprefix
<<" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"'"<<endl
;
861 catch(PDNSException
&ae
) {
863 msg
<<" error at "+nowTime()+" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"': "<<ae
.reason
;
867 bbd
.d_status
=msg
.str();
869 L
<<Logger::Warning
<<d_logprefix
<<msg
.str()<<endl
;
872 catch(std::system_error
&ae
) {
874 if (ae
.code().value() == ENOENT
&& isNew
&& i
->type
== "slave")
875 msg
<<" error at "+nowTime()<<" no file found for new slave domain '"<<i
->name
<<"'. Has not been AXFR'd yet";
877 msg
<<" error at "+nowTime()+" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"': "<<ae
.what();
881 bbd
.d_status
=msg
.str();
882 L
<<Logger::Warning
<<d_logprefix
<<msg
.str()<<endl
;
885 catch(std::exception
&ae
) {
887 msg
<<" error at "+nowTime()+" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"': "<<ae
.what();
891 bbd
.d_status
=msg
.str();
893 L
<<Logger::Warning
<<d_logprefix
<<msg
.str()<<endl
;
896 safePutBBDomainInfo(bbd
);
900 vector
<DNSName
> diff
;
902 set_difference(oldnames
.begin(), oldnames
.end(), newnames
.begin(), newnames
.end(), back_inserter(diff
));
903 unsigned int remdomains
=diff
.size();
905 for(const DNSName
& name
: diff
) {
906 safeRemoveBBDomainInfo(name
);
909 // count number of entirely new domains
911 set_difference(newnames
.begin(), newnames
.end(), oldnames
.begin(), oldnames
.end(), back_inserter(diff
));
912 newdomains
=diff
.size();
915 msg
<<" Done parsing domains, "<<rejected
<<" rejected, "<<newdomains
<<" new, "<<remdomains
<<" removed";
919 L
<<Logger::Error
<<d_logprefix
<<msg
.str()<<endl
;
923 void Bind2Backend::queueReloadAndStore(unsigned int id
)
927 if(!safeGetBBDomainInfo(id
, &bbold
))
929 BB2DomainInfo
bbnew(bbold
);
930 parseZoneFile(&bbnew
);
931 bbnew
.d_checknow
=false;
932 bbnew
.d_wasRejectedLastReload
=false;
933 safePutBBDomainInfo(bbnew
);
934 L
<<Logger::Warning
<<"Zone '"<<bbnew
.d_name
<<"' ("<<bbnew
.d_filename
<<") reloaded"<<endl
;
936 catch(PDNSException
&ae
) {
938 msg
<<" error at "+nowTime()+" parsing '"<<bbold
.d_name
<<"' from file '"<<bbold
.d_filename
<<"': "<<ae
.reason
;
939 L
<<Logger::Warning
<<" error parsing '"<<bbold
.d_name
<<"' from file '"<<bbold
.d_filename
<<"': "<<ae
.reason
<<endl
;
940 bbold
.d_status
=msg
.str();
941 bbold
.d_wasRejectedLastReload
=true;
942 safePutBBDomainInfo(bbold
);
944 catch(std::exception
&ae
) {
946 msg
<<" error at "+nowTime()+" parsing '"<<bbold
.d_name
<<"' from file '"<<bbold
.d_filename
<<"': "<<ae
.what();
947 L
<<Logger::Warning
<<" error parsing '"<<bbold
.d_name
<<"' from file '"<<bbold
.d_filename
<<"': "<<ae
.what()<<endl
;
948 bbold
.d_status
=msg
.str();
949 bbold
.d_wasRejectedLastReload
=true;
950 safePutBBDomainInfo(bbold
);
954 bool Bind2Backend::findBeforeAndAfterUnhashed(BB2DomainInfo
& bbd
, const DNSName
& qname
, DNSName
& unhashed
, DNSName
& before
, DNSName
& after
)
956 shared_ptr
<const recordstorage_t
> records
= bbd
.d_records
.get();
958 // for(const auto& record: *records)
959 // cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
961 recordstorage_t::const_iterator iterBefore
, iterAfter
;
963 iterBefore
= iterAfter
= records
->upper_bound(qname
.makeLowerCase());
965 if(iterBefore
!= records
->begin())
967 while((!iterBefore
->auth
&& iterBefore
->qtype
!= QType::NS
) || !iterBefore
->qtype
)
969 before
=iterBefore
->qname
;
971 if(iterAfter
== records
->end()) {
972 iterAfter
= records
->begin();
974 while((!iterAfter
->auth
&& iterAfter
->qtype
!= QType::NS
) || !iterAfter
->qtype
) {
976 if(iterAfter
== records
->end()) {
977 iterAfter
= records
->begin();
982 after
= iterAfter
->qname
;
987 bool Bind2Backend::getBeforeAndAfterNamesAbsolute(uint32_t id
, const DNSName
& qname
, DNSName
& unhashed
, DNSName
& before
, DNSName
& after
)
990 if (!safeGetBBDomainInfo(id
, &bbd
))
993 NSEC3PARAMRecordContent ns3pr
;
998 nsec3zone
=dk
.getNSEC3PARAM(bbd
.d_name
, &ns3pr
);
1000 nsec3zone
=getNSEC3PARAM(bbd
.d_name
, &ns3pr
);
1003 return findBeforeAndAfterUnhashed(bbd
, qname
, unhashed
, before
, after
);
1006 auto& hashindex
=boost::multi_index::get
<NSEC3Tag
>(*bbd
.d_records
.getWRITABLE());
1008 // for(auto iter = first; iter != hashindex.end(); iter++)
1009 // cerr<<iter->nsec3hash<<endl;
1011 auto first
= hashindex
.upper_bound("");
1012 auto iter
= hashindex
.upper_bound(qname
.toStringNoDot());
1014 if (iter
== hashindex
.end()) {
1016 before
= DNSName(iter
->nsec3hash
);
1017 after
= DNSName(first
->nsec3hash
);
1019 after
= DNSName(iter
->nsec3hash
);
1023 iter
= --hashindex
.end();
1024 before
= DNSName(iter
->nsec3hash
);
1026 unhashed
= iter
->qname
+bbd
.d_name
;
1032 void Bind2Backend::lookup(const QType
&qtype
, const DNSName
&qname
, DNSPacket
*pkt_p
, int zoneId
)
1035 DNSName
domain(qname
);
1037 static bool mustlog
=::arg().mustDo("query-logging");
1039 L
<<Logger::Warning
<<"Lookup for '"<<qtype
.getName()<<"' of '"<<domain
<<"' within zoneID "<<zoneId
<<endl
;
1044 found
= safeGetBBDomainInfo(domain
, &bbd
);
1045 } while ((!found
|| (zoneId
!= (int)bbd
.d_id
&& zoneId
!= -1)) && domain
.chopOff());
1049 L
<<Logger::Warning
<<"Found no authoritative zone for "<<qname
<<endl
;
1050 d_handle
.d_list
=false;
1055 L
<<Logger::Warning
<<"Found a zone '"<<domain
<<"' (with id " << bbd
.d_id
<<") that might contain data "<<endl
;
1057 d_handle
.id
=bbd
.d_id
;
1059 DLOG(L
<<"Bind2Backend constructing handle for search for "<<qtype
.getName()<<" for "<<
1063 d_handle
.qname
=qname
;
1064 else if(qname
.isPartOf(domain
))
1065 d_handle
.qname
=qname
.makeRelative(domain
); // strip domain name
1067 d_handle
.qtype
=qtype
;
1068 d_handle
.domain
=domain
;
1072 throw DBException("Zone for '"+bbd
.d_name
.toLogString()+"' in '"+bbd
.d_filename
+"' temporarily not available (file missing, or master dead)"); // fsck
1075 if(!bbd
.current()) {
1076 L
<<Logger::Warning
<<"Zone '"<<bbd
.d_name
<<"' ("<<bbd
.d_filename
<<") needs reloading"<<endl
;
1077 queueReloadAndStore(bbd
.d_id
);
1078 if (!safeGetBBDomainInfo(domain
, &bbd
))
1079 throw DBException("Zone '"+bbd
.d_name
.toLogString()+"' ("+bbd
.d_filename
+") gone after reload"); // if we don't throw here, we crash for some reason
1082 d_handle
.d_records
= bbd
.d_records
.get();
1084 if(d_handle
.d_records
->empty())
1085 DLOG(L
<<"Query with no results"<<endl
);
1087 d_handle
.mustlog
= mustlog
;
1089 auto& hashedidx
= boost::multi_index::get
<UnorderedNameTag
>(*d_handle
.d_records
);
1090 auto range
= hashedidx
.equal_range(d_handle
.qname
);
1092 if(range
.first
==range
.second
) {
1093 d_handle
.d_list
=false;
1094 d_handle
.d_iter
= d_handle
.d_end_iter
= range
.first
;
1098 d_handle
.d_iter
=range
.first
;
1099 d_handle
.d_end_iter
=range
.second
;
1102 d_handle
.d_list
=false;
1105 Bind2Backend::handle::handle()
1110 bool Bind2Backend::get(DNSResourceRecord
&r
)
1112 if(!d_handle
.d_records
) {
1113 if(d_handle
.mustlog
)
1114 L
<<Logger::Warning
<<"There were no answers"<<endl
;
1118 if(!d_handle
.get(r
)) {
1119 if(d_handle
.mustlog
)
1120 L
<<Logger::Warning
<<"End of answers"<<endl
;
1126 if(d_handle
.mustlog
)
1127 L
<<Logger::Warning
<<"Returning: '"<<r
.qtype
.getName()<<"' of '"<<r
.qname
<<"', content: '"<<r
.content
<<"'"<<endl
;
1131 bool Bind2Backend::handle::get(DNSResourceRecord
&r
)
1136 return get_normal(r
);
1139 void Bind2Backend::handle::reset()
1147 bool Bind2Backend::handle::get_normal(DNSResourceRecord
&r
)
1149 DLOG(L
<< "Bind2Backend get() was called for "<<qtype
.getName() << " record for '"<<
1150 qname
<<"' - "<<d_records
->size()<<" available in total!"<<endl
);
1152 if(d_iter
==d_end_iter
) {
1156 while(d_iter
!=d_end_iter
&& !(qtype
.getCode()==QType::ANY
|| (d_iter
)->qtype
==qtype
.getCode())) {
1157 DLOG(L
<<Logger::Warning
<<"Skipped "<<qname
<<"/"<<QType(d_iter
->qtype
).getName()<<": '"<<d_iter
->content
<<"'"<<endl
);
1160 if(d_iter
==d_end_iter
) {
1163 DLOG(L
<< "Bind2Backend get() returning a rr with a "<<QType(d_iter
->qtype
).getCode()<<endl
);
1165 r
.qname
=qname
.empty() ? domain
: (qname
+domain
);
1167 r
.content
=(d_iter
)->content
;
1168 // r.domain_id=(d_iter)->domain_id;
1169 r
.qtype
=(d_iter
)->qtype
;
1170 r
.ttl
=(d_iter
)->ttl
;
1172 //if(!d_iter->auth && r.qtype.getCode() != QType::A && r.qtype.getCode()!=QType::AAAA && r.qtype.getCode() != QType::NS)
1173 // cerr<<"Warning! Unauth response for qtype "<< r.qtype.getName() << " for '"<<r.qname<<"'"<<endl;
1174 r
.auth
= d_iter
->auth
;
1181 bool Bind2Backend::list(const DNSName
& target
, int id
, bool include_disabled
)
1185 if(!safeGetBBDomainInfo(id
, &bbd
))
1189 DLOG(L
<<"Bind2Backend constructing handle for list of "<<id
<<endl
);
1191 d_handle
.d_records
=bbd
.d_records
.get(); // give it a copy, which will stay around
1192 d_handle
.d_qname_iter
= d_handle
.d_records
->begin();
1193 d_handle
.d_qname_end
=d_handle
.d_records
->end(); // iter now points to a vector of pointers to vector<BBResourceRecords>
1196 d_handle
.domain
=bbd
.d_name
;
1197 d_handle
.d_list
=true;
1201 bool Bind2Backend::handle::get_list(DNSResourceRecord
&r
)
1203 if(d_qname_iter
!=d_qname_end
) {
1204 r
.qname
=d_qname_iter
->qname
.empty() ? domain
: (d_qname_iter
->qname
+domain
);
1206 r
.content
=(d_qname_iter
)->content
;
1207 r
.qtype
=(d_qname_iter
)->qtype
;
1208 r
.ttl
=(d_qname_iter
)->ttl
;
1209 r
.auth
= d_qname_iter
->auth
;
1216 bool Bind2Backend::isMaster(const DNSName
& name
, const string
&ip
)
1219 if(!safeGetBBDomainInfo(name
, &bbd
))
1222 if(bbd
.d_kind
!= DomainInfo::Slave
)
1225 for(vector
<string
>::const_iterator iter
= bbd
.d_masters
.begin(); iter
!= bbd
.d_masters
.end(); ++iter
)
1232 bool Bind2Backend::superMasterBackend(const string
&ip
, const DNSName
& domain
, const vector
<DNSResourceRecord
>&nsset
, string
*nameserver
, string
*account
, DNSBackend
**db
)
1234 // Check whether we have a configfile available.
1235 if (getArg("supermaster-config").empty())
1238 ifstream
c_if(getArg("supermasters").c_str(), std::ios::in
); // this was nocreate?
1240 L
<< Logger::Error
<< "Unable to open supermasters file for read: " << stringerror() << endl
;
1245 // <ip> <accountname>
1246 string line
, sip
, saccount
;
1247 while (getline(c_if
, line
)) {
1248 std::istringstream
ii(line
);
1257 if (sip
!= ip
) // ip not found in authorization list - reject
1260 // ip authorized as supermaster - accept
1262 if (saccount
.length() > 0)
1263 *account
= saccount
.c_str();
1268 BB2DomainInfo
Bind2Backend::createDomainEntry(const DNSName
& domain
, const string
&filename
)
1271 { // Find a free zone id nr.
1272 ReadLock
rl(&s_state_lock
);
1273 if (!s_state
.empty()) {
1274 newid
= s_state
.rbegin()->d_id
+1;
1280 bbd
.d_records
= shared_ptr
<recordstorage_t
>(new recordstorage_t
);
1281 bbd
.d_name
= domain
;
1282 bbd
.setCheckInterval(getArgAsNum("check-interval"));
1283 bbd
.d_filename
= filename
;
1287 bool Bind2Backend::createSlaveDomain(const string
&ip
, const DNSName
& domain
, const string
&nameserver
, const string
&account
)
1289 string filename
= getArg("supermaster-destdir")+'/'+domain
.toStringNoDot();
1291 L
<< Logger::Warning
<< d_logprefix
1292 << " Writing bind config zone statement for superslave zone '" << domain
1293 << "' from supermaster " << ip
<< endl
;
1296 Lock
l2(&s_supermaster_config_lock
);
1298 ofstream
c_of(getArg("supermaster-config").c_str(), std::ios::app
);
1300 L
<< Logger::Error
<< "Unable to open supermaster configfile for append: " << stringerror() << endl
;
1301 throw DBException("Unable to open supermaster configfile for append: "+stringerror());
1305 c_of
<< "# Superslave zone '" << domain
.toString() << "' (added: " << nowTime() << ") (account: " << account
<< ')' << endl
;
1306 c_of
<< "zone \"" << domain
.toStringNoDot() << "\" {" << endl
;
1307 c_of
<< "\ttype slave;" << endl
;
1308 c_of
<< "\tfile \"" << filename
<< "\";" << endl
;
1309 c_of
<< "\tmasters { " << ip
<< "; };" << endl
;
1310 c_of
<< "};" << endl
;
1314 BB2DomainInfo bbd
= createDomainEntry(domain
, filename
);
1315 bbd
.d_kind
= DomainInfo::Slave
;
1316 bbd
.d_masters
.push_back(ip
);
1317 safePutBBDomainInfo(bbd
);
1321 bool Bind2Backend::searchRecords(const string
&pattern
, int maxResults
, vector
<DNSResourceRecord
>& result
)
1323 SimpleMatch
sm(pattern
,true);
1324 static bool mustlog
=::arg().mustDo("query-logging");
1326 L
<<Logger::Warning
<<"Search for pattern '"<<pattern
<<"'"<<endl
;
1329 ReadLock
rl(&s_state_lock
);
1331 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
1333 safeGetBBDomainInfo(i
->d_id
, &h
);
1334 shared_ptr
<const recordstorage_t
> rhandle
= h
.d_records
.get();
1336 for(recordstorage_t::const_iterator ri
= rhandle
->begin(); result
.size() < static_cast<vector
<DNSResourceRecord
>::size_type
>(maxResults
) && ri
!= rhandle
->end(); ri
++) {
1337 DNSName name
= ri
->qname
.empty() ? i
->d_name
: (ri
->qname
+i
->d_name
);
1338 if (sm
.match(name
) || sm
.match(ri
->content
)) {
1339 DNSResourceRecord r
;
1341 r
.domain_id
=i
->d_id
;
1342 r
.content
=ri
->content
;
1346 result
.push_back(r
);
1355 class Bind2Factory
: public BackendFactory
1358 Bind2Factory() : BackendFactory("bind") {}
1360 void declareArguments(const string
&suffix
="")
1362 declare(suffix
,"ignore-broken-records","Ignore records that are out-of-bound for the zone.","no");
1363 declare(suffix
,"config","Location of named.conf","");
1364 declare(suffix
,"check-interval","Interval for zonefile changes","0");
1365 declare(suffix
,"supermaster-config","Location of (part of) named.conf where pdns can write zone-statements to","");
1366 declare(suffix
,"supermasters","List of IP-addresses of supermasters","");
1367 declare(suffix
,"supermaster-destdir","Destination directory for newly added slave zones",::arg()["config-dir"]);
1368 declare(suffix
,"dnssec-db","Filename to store & access our DNSSEC metadatabase, empty for none", "");
1369 declare(suffix
,"hybrid","Store DNSSEC metadata in other backend","no");
1372 DNSBackend
*make(const string
&suffix
="")
1374 return new Bind2Backend(suffix
);
1377 DNSBackend
*makeMetadataOnly(const string
&suffix
="")
1379 return new Bind2Backend(suffix
, false);
1383 //! Magic class that is activated when the dynamic library is loaded
1389 BackendMakers().report(new Bind2Factory
);
1390 L
<< Logger::Info
<< "[bind2backend] This is the bind backend version " << VERSION
1391 #ifndef REPRODUCIBLE
1392 << " (" __DATE__
" " __TIME__
")"
1394 << " reporting" << endl
;
1397 static Bind2Loader bind2loader
;