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
;
84 std::mutex LookButDontTouch
<T
>::s_lock
;
86 BB2DomainInfo::BB2DomainInfo()
94 void BB2DomainInfo::setCheckInterval(time_t seconds
)
96 d_checkinterval
=seconds
;
99 bool BB2DomainInfo::current()
108 if(time(0) - d_lastcheck
< d_checkinterval
)
111 if(d_filename
.empty())
114 return (getCtime()==d_ctime
);
117 time_t BB2DomainInfo::getCtime()
121 if(d_filename
.empty() || stat(d_filename
.c_str(),&buf
)<0)
127 void BB2DomainInfo::setCtime()
130 if(stat(d_filename
.c_str(),&buf
)<0)
132 d_ctime
=buf
.st_ctime
;
135 bool Bind2Backend::safeGetBBDomainInfo(int id
, BB2DomainInfo
* bbd
)
137 ReadLock
rl(&s_state_lock
);
138 state_t::const_iterator iter
= s_state
.find(id
);
139 if(iter
== s_state
.end())
145 bool Bind2Backend::safeGetBBDomainInfo(const DNSName
& name
, BB2DomainInfo
* bbd
)
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
);
151 nameindex_t::const_iterator iter
= nameindex
.find(name
);
152 if(iter
== nameindex
.end())
158 bool Bind2Backend::safeRemoveBBDomainInfo(const DNSName
& name
)
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
);
164 nameindex_t::iterator iter
= nameindex
.find(name
);
165 if(iter
== nameindex
.end())
167 nameindex
.erase(iter
);
171 void Bind2Backend::safePutBBDomainInfo(const BB2DomainInfo
& bbd
)
173 WriteLock
rl(&s_state_lock
);
174 replacing_insert(s_state
, bbd
);
177 void Bind2Backend::setNotified(uint32_t id
, uint32_t serial
)
180 if (!safeGetBBDomainInfo(id
, &bbd
))
182 bbd
.d_lastnotified
= serial
;
183 safePutBBDomainInfo(bbd
);
186 void Bind2Backend::setFresh(uint32_t domain_id
)
189 if(safeGetBBDomainInfo(domain_id
, &bbd
)) {
190 bbd
.d_lastcheck
=time(0);
191 safePutBBDomainInfo(bbd
);
195 bool Bind2Backend::startTransaction(const DNSName
&qname
, int id
)
198 d_transaction_tmpname
.clear();
203 throw DBException("domain_id 0 is invalid for this backend.");
208 if(safeGetBBDomainInfo(id
, &bbd
)) {
209 d_transaction_tmpname
= bbd
.d_filename
+ "XXXXXX";
210 int fd
= mkstemp(&d_transaction_tmpname
.at(0));
212 throw DBException("Unable to create a unique temporary zonefile '"+d_transaction_tmpname
+"': "+stringerror());
216 d_of
= std::unique_ptr
<ofstream
>(new ofstream(d_transaction_tmpname
.c_str()));
218 unlink(d_transaction_tmpname
.c_str());
222 throw DBException("Unable to open temporary zonefile '"+d_transaction_tmpname
+"': "+stringerror());
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
235 bool Bind2Backend::commitTransaction()
237 if(d_transaction_id
< 0)
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
);
253 bool Bind2Backend::abortTransaction()
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());
267 bool Bind2Backend::feedRecord(const DNSResourceRecord
&rr
, const DNSName
&ordername
, bool ordernameIsNSEC3
)
270 if (!safeGetBBDomainInfo(d_transaction_id
, &bbd
))
274 string name
= bbd
.d_name
.toString();
275 if (bbd
.d_name
.empty()) {
276 qname
= rr
.qname
.toString();
278 else if (rr
.qname
.isPartOf(bbd
.d_name
)) {
279 if (rr
.qname
== bbd
.d_name
) {
283 DNSName relName
= rr
.qname
.makeRelative(bbd
.d_name
);
284 qname
= relName
.toStringNoDot();
288 throw DBException("out-of-zone data '"+rr
.qname
.toLogString()+"' during AXFR of zone '"+bbd
.d_name
.toLogString()+"'");
291 shared_ptr
<DNSRecordContent
> drc(DNSRecordContent::mastermake(rr
.qtype
.getCode(), 1, rr
.content
));
292 string content
= drc
->getZoneRepresentation();
294 // SOA needs stripping too! XXX FIXME - also, this should not be here I think
295 switch(rr
.qtype
.getCode()) {
301 stripDomainSuffix(&content
, name
);
305 *d_of
<<qname
<<"\t"<<rr
.ttl
<<"\t"<<rr
.qtype
.getName()<<"\t"<<content
<<endl
;
311 void Bind2Backend::getUpdatedMasters(vector
<DomainInfo
> *changedDomains
)
313 vector
<DomainInfo
> consider
;
315 ReadLock
rl(&s_state_lock
);
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())
324 di
.last_check
=i
->d_lastcheck
;
325 di
.notified_serial
=i
->d_lastnotified
;
327 di
.kind
=DomainInfo::Master
;
328 consider
.push_back(di
);
333 for(DomainInfo
& di
: consider
) {
336 this->getSOA(di
.zone
, soadata
); // we might not *have* a SOA yet, but this might trigger a load of it
341 if(di
.notified_serial
!= soadata
.serial
) {
343 if(safeGetBBDomainInfo(di
.id
, &bbd
)) {
344 bbd
.d_lastnotified
=soadata
.serial
;
345 safePutBBDomainInfo(bbd
);
347 if(di
.notified_serial
) { // don't do notification storm on startup
348 di
.serial
=soadata
.serial
;
349 changedDomains
->push_back(di
);
355 void Bind2Backend::getAllDomains(vector
<DomainInfo
> *domains
, bool include_disabled
)
359 // prevent deadlock by using getSOA() later on
361 ReadLock
rl(&s_state_lock
);
363 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
367 di
.last_check
=i
->d_lastcheck
;
369 di
.masters
=i
->d_masters
;
371 domains
->push_back(di
);
375 for(DomainInfo
&di
: *domains
) {
376 // do not corrupt di if domain supplied by another backend.
377 if (di
.backend
!= this)
380 this->getSOA(di
.zone
, soadata
);
384 di
.serial
=soadata
.serial
;
388 void Bind2Backend::getUnfreshSlaveInfos(vector
<DomainInfo
> *unfreshDomains
)
390 vector
<DomainInfo
> domains
;
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
)
399 sd
.masters
=i
->d_masters
;
400 sd
.last_check
=i
->d_lastcheck
;
402 sd
.kind
=DomainInfo::Slave
;
403 domains
.push_back(sd
);
407 for(DomainInfo
&sd
: domains
) {
412 getSOA(sd
.zone
,soadata
); // we might not *have* a SOA yet
415 sd
.serial
=soadata
.serial
;
416 if(sd
.last_check
+soadata
.refresh
< (unsigned int)time(0))
417 unfreshDomains
->push_back(sd
);
421 bool Bind2Backend::getDomainInfo(const DNSName
& domain
, DomainInfo
&di
, bool getSerial
)
424 if(!safeGetBBDomainInfo(domain
, &bbd
))
429 di
.masters
=bbd
.d_masters
;
430 di
.last_check
=bbd
.d_lastcheck
;
439 getSOA(bbd
.d_name
,sd
); // we might not *have* a SOA yet
448 void Bind2Backend::alsoNotifies(const DNSName
& domain
, set
<string
> *ips
)
450 // combine global list with local list
451 for(set
<string
>::iterator i
= this->alsoNotify
.begin(); i
!= this->alsoNotify
.end(); i
++) {
454 // check metadata too if available
456 if (getDomainMetadata(domain
, "ALSO-NOTIFY", meta
)) {
457 for(const auto& str
: meta
) {
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
++) {
472 // only parses, does NOT add to s_state!
473 void Bind2Backend::parseZoneFile(BB2DomainInfo
*bbd
)
475 NSEC3PARAMRecordContent ns3pr
;
479 nsec3zone
=dk
.getNSEC3PARAM(bbd
->d_name
, &ns3pr
);
481 nsec3zone
=getNSEC3PARAM(bbd
->d_name
, &ns3pr
);
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
;
489 if(rr
.qtype
.getCode() == QType::NSEC
|| rr
.qtype
.getCode() == QType::NSEC3
|| rr
.qtype
.getCode() == QType::NSEC3PARAM
)
490 continue; // we synthesise NSECs on demand
492 insertRecord(*bbd
, rr
.qname
, rr
.qtype
, rr
.content
, rr
.ttl
, "");
494 fixupOrderAndAuth(*bbd
, nsec3zone
, ns3pr
);
495 doEmptyNonTerminals(*bbd
, nsec3zone
, ns3pr
);
498 bbd
->d_checknow
=false;
499 bbd
->d_status
="parsed into memory at "+nowTime();
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
)
507 shared_ptr
<recordstorage_t
> records
= bb2
.d_records
.getWRITABLE();
510 if(bb2
.d_name
.empty())
512 else if(bdr
.qname
.isPartOf(bb2
.d_name
))
513 bdr
.qname
= bdr
.qname
.makeRelative(bb2
.d_name
);
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
;
521 throw PDNSException(msg
);
524 // bdr.qname.swap(bdr.qname);
526 if(!records
->empty() && bdr
.qname
==boost::prior(records
->end())->qname
)
527 bdr
.qname
=boost::prior(records
->end())->qname
;
530 bdr
.qtype
=qtype
.getCode();
532 bdr
.nsec3hash
= hashed
;
534 if (auth
) // Set auth on empty non-terminals
540 records
->insert(bdr
);
543 string
Bind2Backend::DLReloadNowHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
547 for(vector
<string
>::const_iterator i
=parts
.begin()+1;i
<parts
.end();++i
) {
550 if(safeGetBBDomainInfo(zone
, &bbd
)) {
552 bb2
.queueReloadAndStore(bbd
.d_id
);
553 if (!safeGetBBDomainInfo(zone
, &bbd
)) // Read the *new* domain status
554 ret
<< *i
<< ": [missing]\n";
556 ret
<< *i
<< ": "<< (bbd
.d_wasRejectedLastReload
? "[rejected]": "") <<"\t"<<bbd
.d_status
<<"\n";
559 ret
<< *i
<< " no such domain\n";
561 if(ret
.str().empty())
562 ret
<<"no domains reloaded";
567 string
Bind2Backend::DLDomStatusHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
571 if(parts
.size() > 1) {
572 for(vector
<string
>::const_iterator i
=parts
.begin()+1;i
<parts
.end();++i
) {
574 if(safeGetBBDomainInfo(DNSName(*i
), &bbd
)) {
575 ret
<< *i
<< ": "<< (bbd
.d_loaded
? "": "[rejected]") <<"\t"<<bbd
.d_status
<<"\n";
578 ret
<< *i
<< " no such domain\n";
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";
588 if(ret
.str().empty())
589 ret
<<"no domains passed";
594 string
Bind2Backend::DLListRejectsHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
597 ReadLock
rl(&s_state_lock
);
598 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
600 ret
<<i
->d_name
<<"\t"<<i
->d_status
<<endl
;
605 string
Bind2Backend::DLAddDomainHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
608 return "ERROR: Domain name and zone filename are required";
610 DNSName
domainname(parts
[1]);
611 const string
&filename
= parts
[2];
613 if(safeGetBBDomainInfo(domainname
, &bbd
))
614 return "Already loaded";
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.";
620 if (stat(filename
.c_str(), &buf
) != 0)
621 return "Unable to load zone " + domainname
.toLogString() + " from " + filename
+ ": " + strerror(errno
);
623 Bind2Backend bb2
; // createdomainentry needs access to our configuration
624 bbd
=bb2
.createDomainEntry(domainname
, filename
);
625 bbd
.d_filename
=filename
;
629 bbd
.d_status
="parsing into memory";
632 safePutBBDomainInfo(bbd
);
634 g_log
<<Logger::Warning
<<"Zone "<<domainname
<< " loaded"<<endl
;
635 return "Loaded zone " + domainname
.toLogString() + " from " + filename
;
638 Bind2Backend::Bind2Backend(const string
&suffix
, bool loadZones
)
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
;
655 setArgPrefix("bind"+suffix
);
656 d_logprefix
="[bind"+suffix
+"backend]";
657 d_hybrid
=mustDo("hybrid");
659 s_ignore_broken_records
=mustDo("ignore-broken-records");
661 if (!loadZones
&& d_hybrid
)
664 Lock
l(&s_startup_lock
);
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>");
683 Bind2Backend::~Bind2Backend()
684 { freeStatements(); } // deallocate statements
686 void Bind2Backend::rediscover(string
*status
)
691 void Bind2Backend::reload()
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)
699 void Bind2Backend::fixupOrderAndAuth(BB2DomainInfo
& bbd
, bool nsec3zone
, NSEC3PARAMRecordContent ns3pr
)
701 shared_ptr
<recordstorage_t
> records
= bbd
.d_records
.getWRITABLE();
705 set
<DNSName
> nssets
, dssets
;
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
);
714 for(auto iter
= records
->begin(); iter
!= records
->end(); iter
++) {
716 shorter
= iter
->qname
;
718 if (!iter
->qname
.isRoot() && shorter
.chopOff() && !iter
->qname
.isRoot()) {
720 if(nssets
.count(shorter
)) {
724 } while(shorter
.chopOff() && !iter
->qname
.isRoot());
727 iter
->auth
= (!skip
&& (iter
->qtype
== QType::DS
|| iter
->qtype
== QType::RRSIG
|| !nssets
.count(iter
->qname
)));
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
);
735 // cerr<<iter->qname<<"\t"<<QType(iter->qtype).getName()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
739 void Bind2Backend::doEmptyNonTerminals(BB2DomainInfo
& bbd
, bool nsec3zone
, NSEC3PARAMRecordContent ns3pr
)
741 shared_ptr
<const recordstorage_t
> records
= bbd
.d_records
.get();
746 map
<DNSName
, bool> nonterm
;
748 uint32_t maxent
= ::arg().asNum("max-ent-entries");
750 for(const auto& bdr
: *records
)
751 qnames
.insert(bdr
.qname
);
753 for(const auto& bdr
: *records
) {
755 if (!bdr
.auth
&& bdr
.qtype
== QType::NS
)
756 auth
= (!nsec3zone
|| !ns3pr
.d_flags
);
761 while(shorter
.chopOff())
763 if(!qnames
.count(shorter
))
767 g_log
<<Logger::Error
<<"Zone '"<<bbd
.d_name
<<"' has too many empty non terminals."<<endl
;
771 if (!nonterm
.count(shorter
)) {
772 nonterm
.insert(pair
<DNSName
, bool>(shorter
, auth
));
775 nonterm
[shorter
] = true;
780 DNSResourceRecord rr
;
784 for(auto& nt
: nonterm
)
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
);
792 // cerr<<rr.qname<<"\t"<<rr.qtype.getName()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
796 void Bind2Backend::loadConfig(string
* status
)
798 static int domain_id
=1;
800 if(!getArg("config").empty()) {
803 BP
.parse(getArg("config"));
805 catch(PDNSException
&ae
) {
806 g_log
<<Logger::Error
<<"Error parsing bind configuration: "<<ae
.reason
<<endl
;
810 vector
<BindDomainInfo
> domains
=BP
.getDomains();
811 this->alsoNotify
= BP
.getAlsoNotify();
813 s_binddirectory
=BP
.getDirectory();
814 // ZP.setDirectory(d_binddirectory);
816 g_log
<<Logger::Warning
<<d_logprefix
<<" Parsing "<<domains
.size()<<" domain(s), will report when done"<<endl
;
818 set
<DNSName
> oldnames
, newnames
;
820 ReadLock
rl(&s_state_lock
);
821 for(const BB2DomainInfo
& bbd
: s_state
) {
822 oldnames
.insert(bbd
.d_name
);
830 for(vector
<BindDomainInfo
>::iterator i
=domains
.begin(); i
!=domains
.end(); ++i
)
832 if(stat(i
->filename
.c_str(), &st
) == 0) {
833 i
->d_dev
= st
.st_dev
;
834 i
->d_ino
= st
.st_ino
;
838 sort(domains
.begin(), domains
.end()); // put stuff in inode order
839 for(vector
<BindDomainInfo
>::const_iterator i
=domains
.begin();
843 if (!(i
->hadFileDirective
)) {
844 g_log
<<Logger::Warning
<<d_logprefix
<<" Zone '"<<i
->name
<<"' has no 'file' directive set in "<<getArg("config")<<endl
;
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
;
860 if(!safeGetBBDomainInfo(i
->name
, &bbd
)) {
862 bbd
.d_id
=domain_id
++;
863 bbd
.setCheckInterval(getArgAsNum("check-interval"));
864 bbd
.d_lastnotified
=0;
868 // overwrite what we knew about the domain
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
;
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
;
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
;
888 catch(PDNSException
&ae
) {
890 msg
<<" error at "+nowTime()+" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"': "<<ae
.reason
;
894 bbd
.d_status
=msg
.str();
896 g_log
<<Logger::Warning
<<d_logprefix
<<msg
.str()<<endl
;
899 catch(std::system_error
&ae
) {
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";
904 msg
<<" error at "+nowTime()+" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"': "<<ae
.what();
908 bbd
.d_status
=msg
.str();
909 g_log
<<Logger::Warning
<<d_logprefix
<<msg
.str()<<endl
;
912 catch(std::exception
&ae
) {
914 msg
<<" error at "+nowTime()+" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"': "<<ae
.what();
918 bbd
.d_status
=msg
.str();
920 g_log
<<Logger::Warning
<<d_logprefix
<<msg
.str()<<endl
;
923 safePutBBDomainInfo(bbd
);
927 vector
<DNSName
> diff
;
929 set_difference(oldnames
.begin(), oldnames
.end(), newnames
.begin(), newnames
.end(), back_inserter(diff
));
930 unsigned int remdomains
=diff
.size();
932 for(const DNSName
& name
: diff
) {
933 safeRemoveBBDomainInfo(name
);
936 // count number of entirely new domains
938 set_difference(newnames
.begin(), newnames
.end(), oldnames
.begin(), oldnames
.end(), back_inserter(diff
));
939 newdomains
=diff
.size();
942 msg
<<" Done parsing domains, "<<rejected
<<" rejected, "<<newdomains
<<" new, "<<remdomains
<<" removed";
946 g_log
<<Logger::Error
<<d_logprefix
<<msg
.str()<<endl
;
950 void Bind2Backend::queueReloadAndStore(unsigned int id
)
954 if(!safeGetBBDomainInfo(id
, &bbold
))
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
;
963 catch(PDNSException
&ae
) {
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
);
971 catch(std::exception
&ae
) {
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
);
981 bool Bind2Backend::findBeforeAndAfterUnhashed(BB2DomainInfo
& bbd
, const DNSName
& qname
, DNSName
& unhashed
, DNSName
& before
, DNSName
& after
)
983 shared_ptr
<const recordstorage_t
> records
= bbd
.d_records
.get();
985 // for(const auto& record: *records)
986 // cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
988 recordstorage_t::const_iterator iterBefore
, iterAfter
;
990 iterBefore
= iterAfter
= records
->upper_bound(qname
.makeLowerCase());
992 if(iterBefore
!= records
->begin())
994 while((!iterBefore
->auth
&& iterBefore
->qtype
!= QType::NS
) || !iterBefore
->qtype
)
996 before
=iterBefore
->qname
;
998 if(iterAfter
== records
->end()) {
999 iterAfter
= records
->begin();
1001 while((!iterAfter
->auth
&& iterAfter
->qtype
!= QType::NS
) || !iterAfter
->qtype
) {
1003 if(iterAfter
== records
->end()) {
1004 iterAfter
= records
->begin();
1009 after
= iterAfter
->qname
;
1014 bool Bind2Backend::getBeforeAndAfterNamesAbsolute(uint32_t id
, const DNSName
& qname
, DNSName
& unhashed
, DNSName
& before
, DNSName
& after
)
1017 if (!safeGetBBDomainInfo(id
, &bbd
))
1020 NSEC3PARAMRecordContent ns3pr
;
1025 nsec3zone
=dk
.getNSEC3PARAM(bbd
.d_name
, &ns3pr
);
1027 nsec3zone
=getNSEC3PARAM(bbd
.d_name
, &ns3pr
);
1030 return findBeforeAndAfterUnhashed(bbd
, qname
, unhashed
, before
, after
);
1033 auto& hashindex
=boost::multi_index::get
<NSEC3Tag
>(*bbd
.d_records
.getWRITABLE());
1035 // for(auto iter = first; iter != hashindex.end(); iter++)
1036 // cerr<<iter->nsec3hash<<endl;
1038 auto first
= hashindex
.upper_bound("");
1039 auto iter
= hashindex
.upper_bound(qname
.toStringNoDot());
1041 if (iter
== hashindex
.end()) {
1043 before
= DNSName(iter
->nsec3hash
);
1044 after
= DNSName(first
->nsec3hash
);
1046 after
= DNSName(iter
->nsec3hash
);
1050 iter
= --hashindex
.end();
1051 before
= DNSName(iter
->nsec3hash
);
1053 unhashed
= iter
->qname
+bbd
.d_name
;
1059 void Bind2Backend::lookup(const QType
&qtype
, const DNSName
&qname
, int zoneId
, DNSPacket
*pkt_p
)
1063 static bool mustlog
=::arg().mustDo("query-logging");
1070 g_log
<<Logger::Warning
<<"Lookup for '"<<qtype
.getName()<<"' of '"<<qname
<<"' within zoneID "<<zoneId
<<endl
;
1073 if ((found
= (safeGetBBDomainInfo(zoneId
, &bbd
) && qname
.isPartOf(bbd
.d_name
)))) {
1074 domain
= bbd
.d_name
;
1079 found
= safeGetBBDomainInfo(domain
, &bbd
);
1080 } while (!found
&& qtype
!= QType::SOA
&& domain
.chopOff());
1085 g_log
<<Logger::Warning
<<"Found no authoritative zone for '"<<qname
<<"' and/or id "<<bbd
.d_id
<<endl
;
1086 d_handle
.d_list
=false;
1091 g_log
<<Logger::Warning
<<"Found a zone '"<<domain
<<"' (with id " << bbd
.d_id
<<") that might contain data "<<endl
;
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
;
1100 throw DBException("Zone for '"+bbd
.d_name
.toLogString()+"' in '"+bbd
.d_filename
+"' temporarily not available (file missing, or master dead)"); // fsck
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
1110 d_handle
.d_records
= bbd
.d_records
.get();
1112 if(d_handle
.d_records
->empty())
1113 DLOG(g_log
<<"Query with no results"<<endl
);
1115 d_handle
.mustlog
= mustlog
;
1117 auto& hashedidx
= boost::multi_index::get
<UnorderedNameTag
>(*d_handle
.d_records
);
1118 auto range
= hashedidx
.equal_range(d_handle
.qname
);
1120 if(range
.first
==range
.second
) {
1121 d_handle
.d_list
=false;
1122 d_handle
.d_iter
= d_handle
.d_end_iter
= range
.first
;
1126 d_handle
.d_iter
=range
.first
;
1127 d_handle
.d_end_iter
=range
.second
;
1130 d_handle
.d_list
=false;
1133 Bind2Backend::handle::handle()
1138 bool Bind2Backend::get(DNSResourceRecord
&r
)
1140 if(!d_handle
.d_records
) {
1141 if(d_handle
.mustlog
)
1142 g_log
<<Logger::Warning
<<"There were no answers"<<endl
;
1146 if(!d_handle
.get(r
)) {
1147 if(d_handle
.mustlog
)
1148 g_log
<<Logger::Warning
<<"End of answers"<<endl
;
1154 if(d_handle
.mustlog
)
1155 g_log
<<Logger::Warning
<<"Returning: '"<<r
.qtype
.getName()<<"' of '"<<r
.qname
<<"', content: '"<<r
.content
<<"'"<<endl
;
1159 bool Bind2Backend::handle::get(DNSResourceRecord
&r
)
1164 return get_normal(r
);
1167 void Bind2Backend::handle::reset()
1175 bool Bind2Backend::handle::get_normal(DNSResourceRecord
&r
)
1177 DLOG(g_log
<< "Bind2Backend get() was called for "<<qtype
.getName() << " record for '"<<
1178 qname
<<"' - "<<d_records
->size()<<" available in total!"<<endl
);
1180 if(d_iter
==d_end_iter
) {
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
);
1188 if(d_iter
==d_end_iter
) {
1191 DLOG(g_log
<< "Bind2Backend get() returning a rr with a "<<QType(d_iter
->qtype
).getCode()<<endl
);
1193 r
.qname
=qname
.empty() ? domain
: (qname
+domain
);
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
;
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
;
1209 bool Bind2Backend::list(const DNSName
& target
, int id
, bool include_disabled
)
1213 if(!safeGetBBDomainInfo(id
, &bbd
))
1217 DLOG(g_log
<<"Bind2Backend constructing handle for list of "<<id
<<endl
);
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>
1224 d_handle
.domain
=bbd
.d_name
;
1225 d_handle
.d_list
=true;
1229 bool Bind2Backend::handle::get_list(DNSResourceRecord
&r
)
1231 if(d_qname_iter
!=d_qname_end
) {
1232 r
.qname
=d_qname_iter
->qname
.empty() ? domain
: (d_qname_iter
->qname
+domain
);
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
;
1244 bool Bind2Backend::superMasterBackend(const string
&ip
, const DNSName
& domain
, const vector
<DNSResourceRecord
>&nsset
, string
*nameserver
, string
*account
, DNSBackend
**db
)
1246 // Check whether we have a configfile available.
1247 if (getArg("supermaster-config").empty())
1250 ifstream
c_if(getArg("supermasters").c_str(), std::ios::in
); // this was nocreate?
1252 g_log
<< Logger::Error
<< "Unable to open supermasters file for read: " << stringerror() << endl
;
1257 // <ip> <accountname>
1258 string line
, sip
, saccount
;
1259 while (getline(c_if
, line
)) {
1260 std::istringstream
ii(line
);
1269 if (sip
!= ip
) // ip not found in authorization list - reject
1272 // ip authorized as supermaster - accept
1274 if (saccount
.length() > 0)
1275 *account
= saccount
.c_str();
1280 BB2DomainInfo
Bind2Backend::createDomainEntry(const DNSName
& domain
, const string
&filename
)
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;
1291 bbd
.d_kind
= DomainInfo::Native
;
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
;
1301 bool Bind2Backend::createSlaveDomain(const string
&ip
, const DNSName
& domain
, const string
&nameserver
, const string
&account
)
1303 string filename
= getArg("supermaster-destdir")+'/'+domain
.toStringNoDot();
1305 g_log
<< Logger::Warning
<< d_logprefix
1306 << " Writing bind config zone statement for superslave zone '" << domain
1307 << "' from supermaster " << ip
<< endl
;
1310 Lock
l2(&s_supermaster_config_lock
);
1312 ofstream
c_of(getArg("supermaster-config").c_str(), std::ios::app
);
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());
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
;
1328 BB2DomainInfo bbd
= createDomainEntry(domain
, filename
);
1329 bbd
.d_kind
= DomainInfo::Slave
;
1330 bbd
.d_masters
.push_back(ComboAddress(ip
, 53));
1332 safePutBBDomainInfo(bbd
);
1336 bool Bind2Backend::searchRecords(const string
&pattern
, int maxResults
, vector
<DNSResourceRecord
>& result
)
1338 SimpleMatch
sm(pattern
,true);
1339 static bool mustlog
=::arg().mustDo("query-logging");
1341 g_log
<<Logger::Warning
<<"Search for pattern '"<<pattern
<<"'"<<endl
;
1344 ReadLock
rl(&s_state_lock
);
1346 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
1348 if (!safeGetBBDomainInfo(i
->d_id
, &h
)) {
1352 shared_ptr
<const recordstorage_t
> rhandle
= h
.d_records
.get();
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
;
1359 r
.domain_id
=i
->d_id
;
1360 r
.content
=ri
->content
;
1364 result
.push_back(r
);
1373 class Bind2Factory
: public BackendFactory
1376 Bind2Factory() : BackendFactory("bind") {}
1378 void declareArguments(const string
&suffix
="")
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");
1391 DNSBackend
*make(const string
&suffix
="")
1393 assertEmptySuffix(suffix
);
1394 return new Bind2Backend(suffix
);
1397 DNSBackend
*makeMetadataOnly(const string
&suffix
="")
1399 assertEmptySuffix(suffix
);
1400 return new Bind2Backend(suffix
, false);
1403 void assertEmptySuffix(const string
&suffix
)
1406 throw PDNSException("launch= suffixes are not supported on the bindbackend");
1410 //! Magic class that is activated when the dynamic library is loaded
1416 BackendMakers().report(new Bind2Factory
);
1417 g_log
<< Logger::Info
<< "[bind2backend] This is the bind backend version " << VERSION
1418 #ifndef REPRODUCIBLE
1419 << " (" __DATE__
" " __TIME__
")"
1422 << " (with bind-dnssec-db support)"
1424 << " reporting" << endl
;
1427 static Bind2Loader bind2loader
;