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
, bool ordernameIsNSEC3
)
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
, bool getSerial
)
407 if(!safeGetBBDomainInfo(domain
, &bbd
))
412 di
.masters
=bbd
.d_masters
;
413 di
.last_check
=bbd
.d_lastcheck
;
422 getSOA(bbd
.d_name
,sd
); // we might not *have* a SOA yet
431 void Bind2Backend::alsoNotifies(const DNSName
& domain
, set
<string
> *ips
)
433 // combine global list with local list
434 for(set
<string
>::iterator i
= this->alsoNotify
.begin(); i
!= this->alsoNotify
.end(); i
++) {
437 ReadLock
rl(&s_state_lock
);
438 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
439 if(i
->d_name
== domain
) {
440 for(set
<string
>::iterator it
= i
->d_also_notify
.begin(); it
!= i
->d_also_notify
.end(); it
++) {
448 // only parses, does NOT add to s_state!
449 void Bind2Backend::parseZoneFile(BB2DomainInfo
*bbd
)
451 NSEC3PARAMRecordContent ns3pr
;
455 nsec3zone
=dk
.getNSEC3PARAM(bbd
->d_name
, &ns3pr
);
457 nsec3zone
=getNSEC3PARAM(bbd
->d_name
, &ns3pr
);
459 bbd
->d_records
= shared_ptr
<recordstorage_t
>(new recordstorage_t());
461 ZoneParserTNG
zpt(bbd
->d_filename
, bbd
->d_name
, s_binddirectory
);
462 DNSResourceRecord rr
;
465 if(rr
.qtype
.getCode() == QType::NSEC
|| rr
.qtype
.getCode() == QType::NSEC3
|| rr
.qtype
.getCode() == QType::NSEC3PARAM
)
466 continue; // we synthesise NSECs on demand
468 insertRecord(*bbd
, rr
.qname
, rr
.qtype
, rr
.content
, rr
.ttl
, "");
470 fixupOrderAndAuth(*bbd
, nsec3zone
, ns3pr
);
471 doEmptyNonTerminals(*bbd
, nsec3zone
, ns3pr
);
474 bbd
->d_checknow
=false;
475 bbd
->d_status
="parsed into memory at "+nowTime();
478 /** THIS IS AN INTERNAL FUNCTION! It does moadnsparser prio impedance matching
479 Much of the complication is due to the efforts to benefit from std::string reference counting copy on write semantics */
480 void Bind2Backend::insertRecord(BB2DomainInfo
& bb2
, const DNSName
&qname
, const QType
&qtype
, const string
&content
, int ttl
, const std::string
& hashed
, bool *auth
)
483 shared_ptr
<recordstorage_t
> records
= bb2
.d_records
.getWRITABLE();
486 if(bb2
.d_name
.empty())
488 else if(bdr
.qname
.isPartOf(bb2
.d_name
))
489 bdr
.qname
= bdr
.qname
.makeRelative(bb2
.d_name
);
491 string msg
= "Trying to insert non-zone data, name='"+bdr
.qname
.toLogString()+"', qtype="+qtype
.getName()+", zone='"+bb2
.d_name
.toLogString()+"'";
492 if(s_ignore_broken_records
) {
493 g_log
<<Logger::Warning
<<msg
<< " ignored" << endl
;
497 throw PDNSException(msg
);
500 // bdr.qname.swap(bdr.qname);
502 if(!records
->empty() && bdr
.qname
==boost::prior(records
->end())->qname
)
503 bdr
.qname
=boost::prior(records
->end())->qname
;
506 bdr
.qtype
=qtype
.getCode();
508 bdr
.nsec3hash
= hashed
;
510 if (auth
) // Set auth on empty non-terminals
516 records
->insert(bdr
);
519 string
Bind2Backend::DLReloadNowHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
523 for(vector
<string
>::const_iterator i
=parts
.begin()+1;i
<parts
.end();++i
) {
526 if(safeGetBBDomainInfo(zone
, &bbd
)) {
528 bb2
.queueReloadAndStore(bbd
.d_id
);
529 if (!safeGetBBDomainInfo(zone
, &bbd
)) // Read the *new* domain status
530 ret
<< *i
<< ": [missing]\n";
532 ret
<< *i
<< ": "<< (bbd
.d_wasRejectedLastReload
? "[rejected]": "") <<"\t"<<bbd
.d_status
<<"\n";
535 ret
<< *i
<< " no such domain\n";
537 if(ret
.str().empty())
538 ret
<<"no domains reloaded";
543 string
Bind2Backend::DLDomStatusHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
547 if(parts
.size() > 1) {
548 for(vector
<string
>::const_iterator i
=parts
.begin()+1;i
<parts
.end();++i
) {
550 if(safeGetBBDomainInfo(DNSName(*i
), &bbd
)) {
551 ret
<< *i
<< ": "<< (bbd
.d_loaded
? "": "[rejected]") <<"\t"<<bbd
.d_status
<<"\n";
554 ret
<< *i
<< " no such domain\n";
558 ReadLock
rl(&s_state_lock
);
559 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
560 ret
<< i
->d_name
<< ": "<< (i
->d_loaded
? "": "[rejected]") <<"\t"<<i
->d_status
<<"\n";
564 if(ret
.str().empty())
565 ret
<<"no domains passed";
570 string
Bind2Backend::DLListRejectsHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
573 ReadLock
rl(&s_state_lock
);
574 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
576 ret
<<i
->d_name
<<"\t"<<i
->d_status
<<endl
;
581 string
Bind2Backend::DLAddDomainHandler(const vector
<string
>&parts
, Utility::pid_t ppid
)
584 return "ERROR: Domain name and zone filename are required";
586 DNSName
domainname(parts
[1]);
587 const string
&filename
= parts
[2];
589 if(safeGetBBDomainInfo(domainname
, &bbd
))
590 return "Already loaded";
592 if (!boost::starts_with(filename
, "/") && ::arg()["chroot"].empty())
593 return "Unable to load zone " + domainname
.toLogString() + " from " + filename
+ " as the filename is not absolute.";
596 if (stat(filename
.c_str(), &buf
) != 0)
597 return "Unable to load zone " + domainname
.toLogString() + " from " + filename
+ ": " + strerror(errno
);
599 Bind2Backend bb2
; // createdomainentry needs access to our configuration
600 bbd
=bb2
.createDomainEntry(domainname
, filename
);
601 bbd
.d_filename
=filename
;
605 bbd
.d_status
="parsing into memory";
608 safePutBBDomainInfo(bbd
);
610 g_log
<<Logger::Warning
<<"Zone "<<domainname
<< " loaded"<<endl
;
611 return "Loaded zone " + domainname
.toLogString() + " from " + filename
;
614 Bind2Backend::Bind2Backend(const string
&suffix
, bool loadZones
)
616 d_getAllDomainMetadataQuery_stmt
= NULL
;
617 d_getDomainMetadataQuery_stmt
= NULL
;
618 d_deleteDomainMetadataQuery_stmt
= NULL
;
619 d_insertDomainMetadataQuery_stmt
= NULL
;
620 d_getDomainKeysQuery_stmt
= NULL
;
621 d_deleteDomainKeyQuery_stmt
= NULL
;
622 d_insertDomainKeyQuery_stmt
= NULL
;
623 d_GetLastInsertedKeyIdQuery_stmt
= NULL
;
624 d_activateDomainKeyQuery_stmt
= NULL
;
625 d_deactivateDomainKeyQuery_stmt
= NULL
;
626 d_getTSIGKeyQuery_stmt
= NULL
;
627 d_setTSIGKeyQuery_stmt
= NULL
;
628 d_deleteTSIGKeyQuery_stmt
= NULL
;
629 d_getTSIGKeysQuery_stmt
= NULL
;
631 setArgPrefix("bind"+suffix
);
632 d_logprefix
="[bind"+suffix
+"backend]";
633 d_hybrid
=mustDo("hybrid");
635 s_ignore_broken_records
=mustDo("ignore-broken-records");
637 if (!loadZones
&& d_hybrid
)
640 Lock
l(&s_startup_lock
);
652 extern DynListener
*dl
;
653 dl
->registerFunc("BIND-RELOAD-NOW", &DLReloadNowHandler
, "bindbackend: reload domains", "<domains>");
654 dl
->registerFunc("BIND-DOMAIN-STATUS", &DLDomStatusHandler
, "bindbackend: list status of all domains", "[domains]");
655 dl
->registerFunc("BIND-LIST-REJECTS", &DLListRejectsHandler
, "bindbackend: list rejected domains");
656 dl
->registerFunc("BIND-ADD-ZONE", &DLAddDomainHandler
, "bindbackend: add zone", "<domain> <filename>");
659 Bind2Backend::~Bind2Backend()
660 { freeStatements(); } // deallocate statements
662 void Bind2Backend::rediscover(string
*status
)
667 void Bind2Backend::reload()
669 WriteLock
rwl(&s_state_lock
);
670 for(state_t::iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
671 i
->d_checknow
=true; // being a bit cheeky here, don't index state_t on this (mutable)
675 void Bind2Backend::fixupOrderAndAuth(BB2DomainInfo
& bbd
, bool nsec3zone
, NSEC3PARAMRecordContent ns3pr
)
677 shared_ptr
<recordstorage_t
> records
= bbd
.d_records
.getWRITABLE();
681 set
<DNSName
> nssets
, dssets
;
683 for(const auto& bdr
: *records
) {
684 if(!bdr
.qname
.isRoot() && bdr
.qtype
== QType::NS
)
685 nssets
.insert(bdr
.qname
);
686 else if(bdr
.qtype
== QType::DS
)
687 dssets
.insert(bdr
.qname
);
690 for(auto iter
= records
->begin(); iter
!= records
->end(); iter
++) {
692 shorter
= iter
->qname
;
694 if (!iter
->qname
.isRoot() && shorter
.chopOff() && !iter
->qname
.isRoot()) {
696 if(nssets
.count(shorter
)) {
700 } while(shorter
.chopOff() && !iter
->qname
.isRoot());
703 iter
->auth
= (!skip
&& (iter
->qtype
== QType::DS
|| iter
->qtype
== QType::RRSIG
|| !nssets
.count(iter
->qname
)));
705 if(!skip
&& nsec3zone
&& iter
->qtype
!= QType::RRSIG
&& (iter
->auth
|| (iter
->qtype
== QType::NS
&& !ns3pr
.d_flags
) || dssets
.count(iter
->qname
))) {
706 Bind2DNSRecord bdr
= *iter
;
707 bdr
.nsec3hash
= toBase32Hex(hashQNameWithSalt(ns3pr
, bdr
.qname
+bbd
.d_name
));
708 records
->replace(iter
, bdr
);
711 // cerr<<iter->qname<<"\t"<<QType(iter->qtype).getName()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
715 void Bind2Backend::doEmptyNonTerminals(BB2DomainInfo
& bbd
, bool nsec3zone
, NSEC3PARAMRecordContent ns3pr
)
717 shared_ptr
<const recordstorage_t
> records
= bbd
.d_records
.get();
722 map
<DNSName
, bool> nonterm
;
724 uint32_t maxent
= ::arg().asNum("max-ent-entries");
726 for(const auto& bdr
: *records
)
727 qnames
.insert(bdr
.qname
);
729 for(const auto& bdr
: *records
) {
731 if (!bdr
.auth
&& bdr
.qtype
== QType::NS
)
732 auth
= (!nsec3zone
|| !ns3pr
.d_flags
);
737 while(shorter
.chopOff())
739 if(!qnames
.count(shorter
))
743 g_log
<<Logger::Error
<<"Zone '"<<bbd
.d_name
<<"' has too many empty non terminals."<<endl
;
747 if (!nonterm
.count(shorter
)) {
748 nonterm
.insert(pair
<DNSName
, bool>(shorter
, auth
));
751 nonterm
[shorter
] = true;
756 DNSResourceRecord rr
;
760 for(auto& nt
: nonterm
)
763 rr
.qname
= nt
.first
+ bbd
.d_name
;
764 if(nsec3zone
&& nt
.second
)
765 hashed
= toBase32Hex(hashQNameWithSalt(ns3pr
, rr
.qname
));
766 insertRecord(bbd
, rr
.qname
, rr
.qtype
, rr
.content
, rr
.ttl
, hashed
, &nt
.second
);
768 // cerr<<rr.qname<<"\t"<<rr.qtype.getName()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
772 void Bind2Backend::loadConfig(string
* status
)
774 static int domain_id
=1;
776 if(!getArg("config").empty()) {
779 BP
.parse(getArg("config"));
781 catch(PDNSException
&ae
) {
782 g_log
<<Logger::Error
<<"Error parsing bind configuration: "<<ae
.reason
<<endl
;
786 vector
<BindDomainInfo
> domains
=BP
.getDomains();
787 this->alsoNotify
= BP
.getAlsoNotify();
789 s_binddirectory
=BP
.getDirectory();
790 // ZP.setDirectory(d_binddirectory);
792 g_log
<<Logger::Warning
<<d_logprefix
<<" Parsing "<<domains
.size()<<" domain(s), will report when done"<<endl
;
794 set
<DNSName
> oldnames
, newnames
;
796 ReadLock
rl(&s_state_lock
);
797 for(const BB2DomainInfo
& bbd
: s_state
) {
798 oldnames
.insert(bbd
.d_name
);
806 for(vector
<BindDomainInfo
>::iterator i
=domains
.begin(); i
!=domains
.end(); ++i
)
808 if(stat(i
->filename
.c_str(), &st
) == 0) {
809 i
->d_dev
= st
.st_dev
;
810 i
->d_ino
= st
.st_ino
;
814 sort(domains
.begin(), domains
.end()); // put stuff in inode order
815 for(vector
<BindDomainInfo
>::const_iterator i
=domains
.begin();
819 if (!(i
->hadFileDirective
)) {
820 g_log
<<Logger::Warning
<<d_logprefix
<<" Zone '"<<i
->name
<<"' has no 'file' directive set in "<<getArg("config")<<endl
;
826 g_log
<<Logger::Notice
<<d_logprefix
<<" Zone '"<<i
->name
<<"' has no type specified, assuming 'native'"<<endl
;
827 if(i
->type
!="master" && i
->type
!="slave" && i
->type
!= "native" && i
->type
!= "") {
828 g_log
<<Logger::Warning
<<d_logprefix
<<" Warning! Skipping zone '"<<i
->name
<<"' because type '"<<i
->type
<<"' is invalid"<<endl
;
836 if(!safeGetBBDomainInfo(i
->name
, &bbd
)) {
838 bbd
.d_id
=domain_id
++;
839 bbd
.setCheckInterval(getArgAsNum("check-interval"));
840 bbd
.d_lastnotified
=0;
844 // overwrite what we knew about the domain
846 bool filenameChanged
= (bbd
.d_filename
!=i
->filename
);
847 bbd
.d_filename
=i
->filename
;
848 bbd
.d_masters
=i
->masters
;
849 bbd
.d_also_notify
=i
->alsoNotify
;
851 bbd
.d_kind
= DomainInfo::Native
;
852 if (i
->type
== "master")
853 bbd
.d_kind
= DomainInfo::Master
;
854 if (i
->type
== "slave")
855 bbd
.d_kind
= DomainInfo::Slave
;
857 newnames
.insert(bbd
.d_name
);
858 if(filenameChanged
|| !bbd
.d_loaded
|| !bbd
.current()) {
859 g_log
<<Logger::Info
<<d_logprefix
<<" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"'"<<endl
;
864 catch(PDNSException
&ae
) {
866 msg
<<" error at "+nowTime()+" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"': "<<ae
.reason
;
870 bbd
.d_status
=msg
.str();
872 g_log
<<Logger::Warning
<<d_logprefix
<<msg
.str()<<endl
;
875 catch(std::system_error
&ae
) {
877 if (ae
.code().value() == ENOENT
&& isNew
&& i
->type
== "slave")
878 msg
<<" error at "+nowTime()<<" no file found for new slave domain '"<<i
->name
<<"'. Has not been AXFR'd yet";
880 msg
<<" error at "+nowTime()+" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"': "<<ae
.what();
884 bbd
.d_status
=msg
.str();
885 g_log
<<Logger::Warning
<<d_logprefix
<<msg
.str()<<endl
;
888 catch(std::exception
&ae
) {
890 msg
<<" error at "+nowTime()+" parsing '"<<i
->name
<<"' from file '"<<i
->filename
<<"': "<<ae
.what();
894 bbd
.d_status
=msg
.str();
896 g_log
<<Logger::Warning
<<d_logprefix
<<msg
.str()<<endl
;
899 safePutBBDomainInfo(bbd
);
903 vector
<DNSName
> diff
;
905 set_difference(oldnames
.begin(), oldnames
.end(), newnames
.begin(), newnames
.end(), back_inserter(diff
));
906 unsigned int remdomains
=diff
.size();
908 for(const DNSName
& name
: diff
) {
909 safeRemoveBBDomainInfo(name
);
912 // count number of entirely new domains
914 set_difference(newnames
.begin(), newnames
.end(), oldnames
.begin(), oldnames
.end(), back_inserter(diff
));
915 newdomains
=diff
.size();
918 msg
<<" Done parsing domains, "<<rejected
<<" rejected, "<<newdomains
<<" new, "<<remdomains
<<" removed";
922 g_log
<<Logger::Error
<<d_logprefix
<<msg
.str()<<endl
;
926 void Bind2Backend::queueReloadAndStore(unsigned int id
)
930 if(!safeGetBBDomainInfo(id
, &bbold
))
932 BB2DomainInfo
bbnew(bbold
);
933 parseZoneFile(&bbnew
);
934 bbnew
.d_checknow
=false;
935 bbnew
.d_wasRejectedLastReload
=false;
936 safePutBBDomainInfo(bbnew
);
937 g_log
<<Logger::Warning
<<"Zone '"<<bbnew
.d_name
<<"' ("<<bbnew
.d_filename
<<") reloaded"<<endl
;
939 catch(PDNSException
&ae
) {
941 msg
<<" error at "+nowTime()+" parsing '"<<bbold
.d_name
<<"' from file '"<<bbold
.d_filename
<<"': "<<ae
.reason
;
942 g_log
<<Logger::Warning
<<" error parsing '"<<bbold
.d_name
<<"' from file '"<<bbold
.d_filename
<<"': "<<ae
.reason
<<endl
;
943 bbold
.d_status
=msg
.str();
944 bbold
.d_wasRejectedLastReload
=true;
945 safePutBBDomainInfo(bbold
);
947 catch(std::exception
&ae
) {
949 msg
<<" error at "+nowTime()+" parsing '"<<bbold
.d_name
<<"' from file '"<<bbold
.d_filename
<<"': "<<ae
.what();
950 g_log
<<Logger::Warning
<<" error parsing '"<<bbold
.d_name
<<"' from file '"<<bbold
.d_filename
<<"': "<<ae
.what()<<endl
;
951 bbold
.d_status
=msg
.str();
952 bbold
.d_wasRejectedLastReload
=true;
953 safePutBBDomainInfo(bbold
);
957 bool Bind2Backend::findBeforeAndAfterUnhashed(BB2DomainInfo
& bbd
, const DNSName
& qname
, DNSName
& unhashed
, DNSName
& before
, DNSName
& after
)
959 shared_ptr
<const recordstorage_t
> records
= bbd
.d_records
.get();
961 // for(const auto& record: *records)
962 // cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
964 recordstorage_t::const_iterator iterBefore
, iterAfter
;
966 iterBefore
= iterAfter
= records
->upper_bound(qname
.makeLowerCase());
968 if(iterBefore
!= records
->begin())
970 while((!iterBefore
->auth
&& iterBefore
->qtype
!= QType::NS
) || !iterBefore
->qtype
)
972 before
=iterBefore
->qname
;
974 if(iterAfter
== records
->end()) {
975 iterAfter
= records
->begin();
977 while((!iterAfter
->auth
&& iterAfter
->qtype
!= QType::NS
) || !iterAfter
->qtype
) {
979 if(iterAfter
== records
->end()) {
980 iterAfter
= records
->begin();
985 after
= iterAfter
->qname
;
990 bool Bind2Backend::getBeforeAndAfterNamesAbsolute(uint32_t id
, const DNSName
& qname
, DNSName
& unhashed
, DNSName
& before
, DNSName
& after
)
993 if (!safeGetBBDomainInfo(id
, &bbd
))
996 NSEC3PARAMRecordContent ns3pr
;
1001 nsec3zone
=dk
.getNSEC3PARAM(bbd
.d_name
, &ns3pr
);
1003 nsec3zone
=getNSEC3PARAM(bbd
.d_name
, &ns3pr
);
1006 return findBeforeAndAfterUnhashed(bbd
, qname
, unhashed
, before
, after
);
1009 auto& hashindex
=boost::multi_index::get
<NSEC3Tag
>(*bbd
.d_records
.getWRITABLE());
1011 // for(auto iter = first; iter != hashindex.end(); iter++)
1012 // cerr<<iter->nsec3hash<<endl;
1014 auto first
= hashindex
.upper_bound("");
1015 auto iter
= hashindex
.upper_bound(qname
.toStringNoDot());
1017 if (iter
== hashindex
.end()) {
1019 before
= DNSName(iter
->nsec3hash
);
1020 after
= DNSName(first
->nsec3hash
);
1022 after
= DNSName(iter
->nsec3hash
);
1026 iter
= --hashindex
.end();
1027 before
= DNSName(iter
->nsec3hash
);
1029 unhashed
= iter
->qname
+bbd
.d_name
;
1035 void Bind2Backend::lookup(const QType
&qtype
, const DNSName
&qname
, DNSPacket
*pkt_p
, int zoneId
)
1038 DNSName
domain(qname
);
1040 static bool mustlog
=::arg().mustDo("query-logging");
1042 g_log
<<Logger::Warning
<<"Lookup for '"<<qtype
.getName()<<"' of '"<<domain
<<"' within zoneID "<<zoneId
<<endl
;
1047 found
= safeGetBBDomainInfo(domain
, &bbd
);
1048 } while ((!found
|| (zoneId
!= (int)bbd
.d_id
&& zoneId
!= -1)) && domain
.chopOff());
1052 g_log
<<Logger::Warning
<<"Found no authoritative zone for "<<qname
<<endl
;
1053 d_handle
.d_list
=false;
1058 g_log
<<Logger::Warning
<<"Found a zone '"<<domain
<<"' (with id " << bbd
.d_id
<<") that might contain data "<<endl
;
1060 d_handle
.id
=bbd
.d_id
;
1062 DLOG(g_log
<<"Bind2Backend constructing handle for search for "<<qtype
.getName()<<" for "<<
1066 d_handle
.qname
=qname
;
1067 else if(qname
.isPartOf(domain
))
1068 d_handle
.qname
=qname
.makeRelative(domain
); // strip domain name
1070 d_handle
.qtype
=qtype
;
1071 d_handle
.domain
=domain
;
1075 throw DBException("Zone for '"+bbd
.d_name
.toLogString()+"' in '"+bbd
.d_filename
+"' temporarily not available (file missing, or master dead)"); // fsck
1078 if(!bbd
.current()) {
1079 g_log
<<Logger::Warning
<<"Zone '"<<bbd
.d_name
<<"' ("<<bbd
.d_filename
<<") needs reloading"<<endl
;
1080 queueReloadAndStore(bbd
.d_id
);
1081 if (!safeGetBBDomainInfo(domain
, &bbd
))
1082 throw DBException("Zone '"+bbd
.d_name
.toLogString()+"' ("+bbd
.d_filename
+") gone after reload"); // if we don't throw here, we crash for some reason
1085 d_handle
.d_records
= bbd
.d_records
.get();
1087 if(d_handle
.d_records
->empty())
1088 DLOG(g_log
<<"Query with no results"<<endl
);
1090 d_handle
.mustlog
= mustlog
;
1092 auto& hashedidx
= boost::multi_index::get
<UnorderedNameTag
>(*d_handle
.d_records
);
1093 auto range
= hashedidx
.equal_range(d_handle
.qname
);
1095 if(range
.first
==range
.second
) {
1096 d_handle
.d_list
=false;
1097 d_handle
.d_iter
= d_handle
.d_end_iter
= range
.first
;
1101 d_handle
.d_iter
=range
.first
;
1102 d_handle
.d_end_iter
=range
.second
;
1105 d_handle
.d_list
=false;
1108 Bind2Backend::handle::handle()
1113 bool Bind2Backend::get(DNSResourceRecord
&r
)
1115 if(!d_handle
.d_records
) {
1116 if(d_handle
.mustlog
)
1117 g_log
<<Logger::Warning
<<"There were no answers"<<endl
;
1121 if(!d_handle
.get(r
)) {
1122 if(d_handle
.mustlog
)
1123 g_log
<<Logger::Warning
<<"End of answers"<<endl
;
1129 if(d_handle
.mustlog
)
1130 g_log
<<Logger::Warning
<<"Returning: '"<<r
.qtype
.getName()<<"' of '"<<r
.qname
<<"', content: '"<<r
.content
<<"'"<<endl
;
1134 bool Bind2Backend::handle::get(DNSResourceRecord
&r
)
1139 return get_normal(r
);
1142 void Bind2Backend::handle::reset()
1150 bool Bind2Backend::handle::get_normal(DNSResourceRecord
&r
)
1152 DLOG(g_log
<< "Bind2Backend get() was called for "<<qtype
.getName() << " record for '"<<
1153 qname
<<"' - "<<d_records
->size()<<" available in total!"<<endl
);
1155 if(d_iter
==d_end_iter
) {
1159 while(d_iter
!=d_end_iter
&& !(qtype
.getCode()==QType::ANY
|| (d_iter
)->qtype
==qtype
.getCode())) {
1160 DLOG(g_log
<<Logger::Warning
<<"Skipped "<<qname
<<"/"<<QType(d_iter
->qtype
).getName()<<": '"<<d_iter
->content
<<"'"<<endl
);
1163 if(d_iter
==d_end_iter
) {
1166 DLOG(g_log
<< "Bind2Backend get() returning a rr with a "<<QType(d_iter
->qtype
).getCode()<<endl
);
1168 r
.qname
=qname
.empty() ? domain
: (qname
+domain
);
1170 r
.content
=(d_iter
)->content
;
1171 // r.domain_id=(d_iter)->domain_id;
1172 r
.qtype
=(d_iter
)->qtype
;
1173 r
.ttl
=(d_iter
)->ttl
;
1175 //if(!d_iter->auth && r.qtype.getCode() != QType::A && r.qtype.getCode()!=QType::AAAA && r.qtype.getCode() != QType::NS)
1176 // cerr<<"Warning! Unauth response for qtype "<< r.qtype.getName() << " for '"<<r.qname<<"'"<<endl;
1177 r
.auth
= d_iter
->auth
;
1184 bool Bind2Backend::list(const DNSName
& target
, int id
, bool include_disabled
)
1188 if(!safeGetBBDomainInfo(id
, &bbd
))
1192 DLOG(g_log
<<"Bind2Backend constructing handle for list of "<<id
<<endl
);
1194 d_handle
.d_records
=bbd
.d_records
.get(); // give it a copy, which will stay around
1195 d_handle
.d_qname_iter
= d_handle
.d_records
->begin();
1196 d_handle
.d_qname_end
=d_handle
.d_records
->end(); // iter now points to a vector of pointers to vector<BBResourceRecords>
1199 d_handle
.domain
=bbd
.d_name
;
1200 d_handle
.d_list
=true;
1204 bool Bind2Backend::handle::get_list(DNSResourceRecord
&r
)
1206 if(d_qname_iter
!=d_qname_end
) {
1207 r
.qname
=d_qname_iter
->qname
.empty() ? domain
: (d_qname_iter
->qname
+domain
);
1209 r
.content
=(d_qname_iter
)->content
;
1210 r
.qtype
=(d_qname_iter
)->qtype
;
1211 r
.ttl
=(d_qname_iter
)->ttl
;
1212 r
.auth
= d_qname_iter
->auth
;
1219 bool Bind2Backend::superMasterBackend(const string
&ip
, const DNSName
& domain
, const vector
<DNSResourceRecord
>&nsset
, string
*nameserver
, string
*account
, DNSBackend
**db
)
1221 // Check whether we have a configfile available.
1222 if (getArg("supermaster-config").empty())
1225 ifstream
c_if(getArg("supermasters").c_str(), std::ios::in
); // this was nocreate?
1227 g_log
<< Logger::Error
<< "Unable to open supermasters file for read: " << stringerror() << endl
;
1232 // <ip> <accountname>
1233 string line
, sip
, saccount
;
1234 while (getline(c_if
, line
)) {
1235 std::istringstream
ii(line
);
1244 if (sip
!= ip
) // ip not found in authorization list - reject
1247 // ip authorized as supermaster - accept
1249 if (saccount
.length() > 0)
1250 *account
= saccount
.c_str();
1255 BB2DomainInfo
Bind2Backend::createDomainEntry(const DNSName
& domain
, const string
&filename
)
1258 { // Find a free zone id nr.
1259 ReadLock
rl(&s_state_lock
);
1260 if (!s_state
.empty()) {
1261 newid
= s_state
.rbegin()->d_id
+1;
1266 bbd
.d_kind
= DomainInfo::Native
;
1268 bbd
.d_records
= shared_ptr
<recordstorage_t
>(new recordstorage_t
);
1269 bbd
.d_name
= domain
;
1270 bbd
.setCheckInterval(getArgAsNum("check-interval"));
1271 bbd
.d_filename
= filename
;
1276 bool Bind2Backend::createSlaveDomain(const string
&ip
, const DNSName
& domain
, const string
&nameserver
, const string
&account
)
1278 string filename
= getArg("supermaster-destdir")+'/'+domain
.toStringNoDot();
1280 g_log
<< Logger::Warning
<< d_logprefix
1281 << " Writing bind config zone statement for superslave zone '" << domain
1282 << "' from supermaster " << ip
<< endl
;
1285 Lock
l2(&s_supermaster_config_lock
);
1287 ofstream
c_of(getArg("supermaster-config").c_str(), std::ios::app
);
1289 g_log
<< Logger::Error
<< "Unable to open supermaster configfile for append: " << stringerror() << endl
;
1290 throw DBException("Unable to open supermaster configfile for append: "+stringerror());
1294 c_of
<< "# Superslave zone '" << domain
.toString() << "' (added: " << nowTime() << ") (account: " << account
<< ')' << endl
;
1295 c_of
<< "zone \"" << domain
.toStringNoDot() << "\" {" << endl
;
1296 c_of
<< "\ttype slave;" << endl
;
1297 c_of
<< "\tfile \"" << filename
<< "\";" << endl
;
1298 c_of
<< "\tmasters { " << ip
<< "; };" << endl
;
1299 c_of
<< "};" << endl
;
1303 BB2DomainInfo bbd
= createDomainEntry(domain
, filename
);
1304 bbd
.d_kind
= DomainInfo::Slave
;
1305 bbd
.d_masters
.push_back(ComboAddress(ip
, 53));
1307 safePutBBDomainInfo(bbd
);
1311 bool Bind2Backend::searchRecords(const string
&pattern
, int maxResults
, vector
<DNSResourceRecord
>& result
)
1313 SimpleMatch
sm(pattern
,true);
1314 static bool mustlog
=::arg().mustDo("query-logging");
1316 g_log
<<Logger::Warning
<<"Search for pattern '"<<pattern
<<"'"<<endl
;
1319 ReadLock
rl(&s_state_lock
);
1321 for(state_t::const_iterator i
= s_state
.begin(); i
!= s_state
.end() ; ++i
) {
1323 safeGetBBDomainInfo(i
->d_id
, &h
);
1324 shared_ptr
<const recordstorage_t
> rhandle
= h
.d_records
.get();
1326 for(recordstorage_t::const_iterator ri
= rhandle
->begin(); result
.size() < static_cast<vector
<DNSResourceRecord
>::size_type
>(maxResults
) && ri
!= rhandle
->end(); ri
++) {
1327 DNSName name
= ri
->qname
.empty() ? i
->d_name
: (ri
->qname
+i
->d_name
);
1328 if (sm
.match(name
) || sm
.match(ri
->content
)) {
1329 DNSResourceRecord r
;
1331 r
.domain_id
=i
->d_id
;
1332 r
.content
=ri
->content
;
1336 result
.push_back(r
);
1345 class Bind2Factory
: public BackendFactory
1348 Bind2Factory() : BackendFactory("bind") {}
1350 void declareArguments(const string
&suffix
="")
1352 declare(suffix
,"ignore-broken-records","Ignore records that are out-of-bound for the zone.","no");
1353 declare(suffix
,"config","Location of named.conf","");
1354 declare(suffix
,"check-interval","Interval for zonefile changes","0");
1355 declare(suffix
,"supermaster-config","Location of (part of) named.conf where pdns can write zone-statements to","");
1356 declare(suffix
,"supermasters","List of IP-addresses of supermasters","");
1357 declare(suffix
,"supermaster-destdir","Destination directory for newly added slave zones",::arg()["config-dir"]);
1358 declare(suffix
,"dnssec-db","Filename to store & access our DNSSEC metadatabase, empty for none", "");
1359 declare(suffix
,"hybrid","Store DNSSEC metadata in other backend","no");
1362 DNSBackend
*make(const string
&suffix
="")
1364 assertEmptySuffix(suffix
);
1365 return new Bind2Backend(suffix
);
1368 DNSBackend
*makeMetadataOnly(const string
&suffix
="")
1370 assertEmptySuffix(suffix
);
1371 return new Bind2Backend(suffix
, false);
1374 void assertEmptySuffix(const string
&suffix
)
1377 throw PDNSException("launch= suffixes are not supported on the bindbackend");
1381 //! Magic class that is activated when the dynamic library is loaded
1387 BackendMakers().report(new Bind2Factory
);
1388 g_log
<< Logger::Info
<< "[bind2backend] This is the bind backend version " << VERSION
1389 #ifndef REPRODUCIBLE
1390 << " (" __DATE__
" " __TIME__
")"
1393 << " (with bind-dnssec-db support)"
1395 << " reporting" << endl
;
1398 static Bind2Loader bind2loader
;