]> git.ipfire.org Git - thirdparty/pdns.git/blob - modules/bindbackend/bindbackend2.cc
ff645ad750ab12ef15f248985dea26ec3bff08e6
[thirdparty/pdns.git] / modules / bindbackend / bindbackend2.cc
1 /*
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26 #include <errno.h>
27 #include <string>
28 #include <set>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include <fstream>
33 #include <fcntl.h>
34 #include <sstream>
35 #include <boost/algorithm/string.hpp>
36 #include <system_error>
37
38 #include "pdns/dnsseckeeper.hh"
39 #include "pdns/dnssecinfra.hh"
40 #include "pdns/base32.hh"
41 #include "pdns/namespaces.hh"
42 #include "pdns/dns.hh"
43 #include "pdns/dnsbackend.hh"
44 #include "bindbackend2.hh"
45 #include "pdns/dnspacket.hh"
46 #include "pdns/zoneparser-tng.hh"
47 #include "pdns/bindparserclasses.hh"
48 #include "pdns/logger.hh"
49 #include "pdns/arguments.hh"
50 #include "pdns/qtype.hh"
51 #include "pdns/misc.hh"
52 #include "pdns/dynlistener.hh"
53 #include "pdns/lock.hh"
54 #include "pdns/namespaces.hh"
55
56 /*
57 All instances of this backend share one s_state, which is indexed by zone name and zone id.
58 The s_state is protected by a read/write lock, and the goal it to only interact with it briefly.
59 When a query comes in, we take a read lock and COPY the best zone to answer from s_state (BB2DomainInfo object)
60 All answers are served from this copy.
61
62 To interact with s_state, use safeGetBBDomainInfo (search on name or id), safePutBBDomainInfo (to update)
63 or safeRemoveBBDomainInfo. These all lock as they should.
64
65 Several functions need to traverse s_state to get data for the rest of PowerDNS. When doing so,
66 you need to manually take the s_state_lock (read).
67
68 Parsing zones happens with parseZone(), which fills a BB2DomainInfo object. This can then be stored with safePutBBDomainInfo.
69
70 Finally, the BB2DomainInfo contains all records as a LookButDontTouch object. This makes sure you only look, but don't touch, since
71 the records might be in use in other places.
72 */
73
74 Bind2Backend::state_t Bind2Backend::s_state;
75 int Bind2Backend::s_first=1;
76 bool Bind2Backend::s_ignore_broken_records=false;
77
78 pthread_rwlock_t Bind2Backend::s_state_lock=PTHREAD_RWLOCK_INITIALIZER;
79 pthread_mutex_t Bind2Backend::s_supermaster_config_lock=PTHREAD_MUTEX_INITIALIZER; // protects writes to config file
80 pthread_mutex_t Bind2Backend::s_startup_lock=PTHREAD_MUTEX_INITIALIZER;
81 string Bind2Backend::s_binddirectory;
82
83 BB2DomainInfo::BB2DomainInfo()
84 {
85 d_loaded=false;
86 d_lastcheck=0;
87 d_checknow=false;
88 d_status="Unknown";
89 }
90
91 void BB2DomainInfo::setCheckInterval(time_t seconds)
92 {
93 d_checkinterval=seconds;
94 }
95
96 bool BB2DomainInfo::current()
97 {
98 if(d_checknow) {
99 return false;
100 }
101
102 if(!d_checkinterval)
103 return true;
104
105 if(time(0) - d_lastcheck < d_checkinterval)
106 return true;
107
108 if(d_filename.empty())
109 return true;
110
111 return (getCtime()==d_ctime);
112 }
113
114 time_t BB2DomainInfo::getCtime()
115 {
116 struct stat buf;
117
118 if(d_filename.empty() || stat(d_filename.c_str(),&buf)<0)
119 return 0;
120 d_lastcheck=time(0);
121 return buf.st_ctime;
122 }
123
124 void BB2DomainInfo::setCtime()
125 {
126 struct stat buf;
127 if(stat(d_filename.c_str(),&buf)<0)
128 return;
129 d_ctime=buf.st_ctime;
130 }
131
132 bool Bind2Backend::safeGetBBDomainInfo(int id, BB2DomainInfo* bbd)
133 {
134 ReadLock rl(&s_state_lock);
135 state_t::const_iterator iter = s_state.find(id);
136 if(iter == s_state.end())
137 return false;
138 *bbd=*iter;
139 return true;
140 }
141
142 bool Bind2Backend::safeGetBBDomainInfo(const DNSName& name, BB2DomainInfo* bbd)
143 {
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);
147
148 nameindex_t::const_iterator iter = nameindex.find(name);
149 if(iter == nameindex.end())
150 return false;
151 *bbd=*iter;
152 return true;
153 }
154
155 bool Bind2Backend::safeRemoveBBDomainInfo(const DNSName& name)
156 {
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);
160
161 nameindex_t::iterator iter = nameindex.find(name);
162 if(iter == nameindex.end())
163 return false;
164 nameindex.erase(iter);
165 return true;
166 }
167
168 void Bind2Backend::safePutBBDomainInfo(const BB2DomainInfo& bbd)
169 {
170 WriteLock rl(&s_state_lock);
171 replacing_insert(s_state, bbd);
172 }
173
174 void Bind2Backend::setNotified(uint32_t id, uint32_t serial)
175 {
176 BB2DomainInfo bbd;
177 if (!safeGetBBDomainInfo(id, &bbd))
178 return;
179 bbd.d_lastnotified = serial;
180 safePutBBDomainInfo(bbd);
181 }
182
183 void Bind2Backend::setFresh(uint32_t domain_id)
184 {
185 BB2DomainInfo bbd;
186 if(safeGetBBDomainInfo(domain_id, &bbd)) {
187 bbd.d_lastcheck=time(0);
188 safePutBBDomainInfo(bbd);
189 }
190 }
191
192 bool Bind2Backend::startTransaction(const DNSName &qname, int id)
193 {
194 if(id < 0) {
195 d_transaction_tmpname.clear();
196 d_transaction_id=id;
197 return false;
198 }
199 if(id == 0) {
200 throw DBException("domain_id 0 is invalid for this backend.");
201 }
202
203 d_transaction_id=id;
204 BB2DomainInfo bbd;
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()));
208 if(!*d_of) {
209 unlink(d_transaction_tmpname.c_str());
210 d_of.reset();
211 throw DBException("Unable to open temporary zonefile '"+d_transaction_tmpname+"': "+stringerror());
212 }
213
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
216
217 return true;
218 }
219 return false;
220 }
221
222 bool Bind2Backend::commitTransaction()
223 {
224 if(d_transaction_id < 0)
225 return false;
226 d_of.reset();
227
228 BB2DomainInfo bbd;
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);
233 }
234
235 d_transaction_id=0;
236
237 return true;
238 }
239
240 bool Bind2Backend::abortTransaction()
241 {
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());
247 d_of.reset();
248 d_transaction_id=0;
249 }
250
251 return true;
252 }
253
254 bool Bind2Backend::feedRecord(const DNSResourceRecord &rr, const DNSName &ordername)
255 {
256 BB2DomainInfo bbd;
257 if (!safeGetBBDomainInfo(d_transaction_id, &bbd))
258 return false;
259
260 string qname;
261 string name = bbd.d_name.toString();
262 if (bbd.d_name.empty()) {
263 qname = rr.qname.toString();
264 }
265 else if (rr.qname.isPartOf(bbd.d_name)) {
266 if (rr.qname == bbd.d_name) {
267 qname = "@";
268 }
269 else {
270 DNSName relName = rr.qname.makeRelative(bbd.d_name);
271 qname = relName.toStringNoDot();
272 }
273 }
274 else {
275 throw DBException("out-of-zone data '"+rr.qname.toLogString()+"' during AXFR of zone '"+bbd.d_name.toLogString()+"'");
276 }
277
278 shared_ptr<DNSRecordContent> drc(DNSRecordContent::mastermake(rr.qtype.getCode(), 1, rr.content));
279 string content = drc->getZoneRepresentation();
280
281 // SOA needs stripping too! XXX FIXME - also, this should not be here I think
282 switch(rr.qtype.getCode()) {
283 case QType::MX:
284 case QType::SRV:
285 case QType::CNAME:
286 case QType::DNAME:
287 case QType::NS:
288 stripDomainSuffix(&content, name);
289 // fallthrough
290 default:
291 if (d_of && *d_of) {
292 *d_of<<qname<<"\t"<<rr.ttl<<"\t"<<rr.qtype.getName()<<"\t"<<content<<endl;
293 }
294 }
295 return true;
296 }
297
298 void Bind2Backend::getUpdatedMasters(vector<DomainInfo> *changedDomains)
299 {
300 vector<DomainInfo> consider;
301 {
302 ReadLock rl(&s_state_lock);
303
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())
306 continue;
307
308 DomainInfo di;
309 di.id=i->d_id;
310 di.zone=i->d_name;
311 di.last_check=i->d_lastcheck;
312 di.notified_serial=i->d_lastnotified;
313 di.backend=this;
314 di.kind=DomainInfo::Master;
315 consider.push_back(di);
316 }
317 }
318
319 SOAData soadata;
320 for(DomainInfo& di : consider) {
321 soadata.serial=0;
322 try {
323 this->getSOA(di.zone, soadata); // we might not *have* a SOA yet, but this might trigger a load of it
324 }
325 catch(...) {
326 continue;
327 }
328 if(di.notified_serial != soadata.serial) {
329 BB2DomainInfo bbd;
330 if(safeGetBBDomainInfo(di.id, &bbd)) {
331 bbd.d_lastnotified=soadata.serial;
332 safePutBBDomainInfo(bbd);
333 }
334 if(di.notified_serial) { // don't do notification storm on startup
335 di.serial=soadata.serial;
336 changedDomains->push_back(di);
337 }
338 }
339 }
340 }
341
342 void Bind2Backend::getAllDomains(vector<DomainInfo> *domains, bool include_disabled)
343 {
344 SOAData soadata;
345
346 // prevent deadlock by using getSOA() later on
347 {
348 ReadLock rl(&s_state_lock);
349
350 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
351 DomainInfo di;
352 di.id=i->d_id;
353 di.zone=i->d_name;
354 di.last_check=i->d_lastcheck;
355 di.kind=i->d_kind;
356 di.masters=i->d_masters;
357 di.backend=this;
358 domains->push_back(di);
359 };
360 }
361
362 for(DomainInfo &di : *domains) {
363 // do not corrupt di if domain supplied by another backend.
364 if (di.backend != this)
365 continue;
366 this->getSOA(di.zone, soadata);
367 di.serial=soadata.serial;
368 }
369 }
370
371 void Bind2Backend::getUnfreshSlaveInfos(vector<DomainInfo> *unfreshDomains)
372 {
373 vector<DomainInfo> domains;
374 {
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)
378 continue;
379 DomainInfo sd;
380 sd.id=i->d_id;
381 sd.zone=i->d_name;
382 sd.masters=i->d_masters;
383 sd.last_check=i->d_lastcheck;
384 sd.backend=this;
385 sd.kind=DomainInfo::Slave;
386 domains.push_back(sd);
387 }
388 }
389
390 for(DomainInfo &sd : domains) {
391 SOAData soadata;
392 soadata.refresh=0;
393 soadata.serial=0;
394 try {
395 getSOA(sd.zone,soadata); // we might not *have* a SOA yet
396 }
397 catch(...){}
398 sd.serial=soadata.serial;
399 if(sd.last_check+soadata.refresh < (unsigned int)time(0))
400 unfreshDomains->push_back(sd);
401 }
402 }
403
404 bool Bind2Backend::getDomainInfo(const DNSName& domain, DomainInfo &di)
405 {
406 BB2DomainInfo bbd;
407 if(!safeGetBBDomainInfo(domain, &bbd))
408 return false;
409
410 di.id=bbd.d_id;
411 di.zone=domain;
412 di.masters=bbd.d_masters;
413 di.last_check=bbd.d_lastcheck;
414 di.backend=this;
415 di.kind=bbd.d_kind;
416 di.serial=0;
417 try {
418 SOAData sd;
419 sd.serial=0;
420
421 getSOA(bbd.d_name,sd); // we might not *have* a SOA yet
422 di.serial=sd.serial;
423 }
424 catch(...){}
425
426 return true;
427 }
428
429 void Bind2Backend::alsoNotifies(const DNSName& domain, set<string> *ips)
430 {
431 // combine global list with local list
432 for(set<string>::iterator i = this->alsoNotify.begin(); i != this->alsoNotify.end(); i++) {
433 (*ips).insert(*i);
434 }
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++) {
439 (*ips).insert(*it);
440 }
441 return;
442 }
443 }
444 }
445
446 // only parses, does NOT add to s_state!
447 void Bind2Backend::parseZoneFile(BB2DomainInfo *bbd)
448 {
449 NSEC3PARAMRecordContent ns3pr;
450 bool nsec3zone;
451 if (d_hybrid) {
452 DNSSECKeeper dk;
453 nsec3zone=dk.getNSEC3PARAM(bbd->d_name, &ns3pr);
454 } else
455 nsec3zone=getNSEC3PARAM(bbd->d_name, &ns3pr);
456
457 bbd->d_records = shared_ptr<recordstorage_t>(new recordstorage_t());
458
459 ZoneParserTNG zpt(bbd->d_filename, bbd->d_name, s_binddirectory);
460 DNSResourceRecord rr;
461 string hashed;
462 while(zpt.get(rr)) {
463 if(rr.qtype.getCode() == QType::NSEC || rr.qtype.getCode() == QType::NSEC3)
464 continue; // we synthesise NSECs on demand
465
466 insertRecord(*bbd, rr.qname, rr.qtype, rr.content, rr.ttl, "");
467 }
468 fixupOrderAndAuth(*bbd, nsec3zone, ns3pr);
469 doEmptyNonTerminals(*bbd, nsec3zone, ns3pr);
470 bbd->setCtime();
471 bbd->d_loaded=true;
472 bbd->d_checknow=false;
473 bbd->d_status="parsed into memory at "+nowTime();
474 }
475
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)
479 {
480 Bind2DNSRecord bdr;
481 shared_ptr<recordstorage_t> records = bb2.d_records.getWRITABLE();
482 bdr.qname=qname;
483
484 if(bb2.d_name.empty())
485 ;
486 else if(bdr.qname.isPartOf(bb2.d_name))
487 bdr.qname = bdr.qname.makeRelative(bb2.d_name);
488 else {
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;
492 return;
493 }
494 else
495 throw PDNSException(msg);
496 }
497
498 // bdr.qname.swap(bdr.qname);
499
500 if(!records->empty() && bdr.qname==boost::prior(records->end())->qname)
501 bdr.qname=boost::prior(records->end())->qname;
502
503 bdr.qname=bdr.qname;
504 bdr.qtype=qtype.getCode();
505 bdr.content=content;
506 bdr.nsec3hash = hashed;
507
508 if (auth) // Set auth on empty non-terminals
509 bdr.auth=*auth;
510 else
511 bdr.auth=true;
512
513 bdr.ttl=ttl;
514 records->insert(bdr);
515 }
516
517 string Bind2Backend::DLReloadNowHandler(const vector<string>&parts, Utility::pid_t ppid)
518 {
519 ostringstream ret;
520
521 for(vector<string>::const_iterator i=parts.begin()+1;i<parts.end();++i) {
522 BB2DomainInfo bbd;
523 DNSName zone(*i);
524 if(safeGetBBDomainInfo(zone, &bbd)) {
525 Bind2Backend bb2;
526 bb2.queueReloadAndStore(bbd.d_id);
527 if (!safeGetBBDomainInfo(zone, &bbd)) // Read the *new* domain status
528 ret << *i << ": [missing]\n";
529 else
530 ret<< *i << ": "<< (bbd.d_wasRejectedLastReload ? "[rejected]": "") <<"\t"<<bbd.d_status<<"\n";
531 }
532 else
533 ret<< *i << " no such domain\n";
534 }
535 if(ret.str().empty())
536 ret<<"no domains reloaded";
537 return ret.str();
538 }
539
540
541 string Bind2Backend::DLDomStatusHandler(const vector<string>&parts, Utility::pid_t ppid)
542 {
543 ostringstream ret;
544
545 if(parts.size() > 1) {
546 for(vector<string>::const_iterator i=parts.begin()+1;i<parts.end();++i) {
547 BB2DomainInfo bbd;
548 if(safeGetBBDomainInfo(DNSName(*i), &bbd)) {
549 ret<< *i << ": "<< (bbd.d_loaded ? "": "[rejected]") <<"\t"<<bbd.d_status<<"\n";
550 }
551 else
552 ret<< *i << " no such domain\n";
553 }
554 }
555 else {
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";
559 }
560 }
561
562 if(ret.str().empty())
563 ret<<"no domains passed";
564
565 return ret.str();
566 }
567
568 string Bind2Backend::DLListRejectsHandler(const vector<string>&parts, Utility::pid_t ppid)
569 {
570 ostringstream ret;
571 ReadLock rl(&s_state_lock);
572 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
573 if(!i->d_loaded)
574 ret<<i->d_name<<"\t"<<i->d_status<<endl;
575 }
576 return ret.str();
577 }
578
579 string Bind2Backend::DLAddDomainHandler(const vector<string>&parts, Utility::pid_t ppid)
580 {
581 if(parts.size() < 3)
582 return "ERROR: Domain name and zone filename are required";
583
584 DNSName domainname(parts[1]);
585 const string &filename = parts[2];
586 BB2DomainInfo bbd;
587 if(safeGetBBDomainInfo(domainname, &bbd))
588 return "Already loaded";
589
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.";
592
593 struct stat buf;
594 if (stat(filename.c_str(), &buf) != 0)
595 return "Unable to load zone " + domainname.toLogString() + " from " + filename + ": " + strerror(errno);
596
597 Bind2Backend bb2; // createdomainentry needs access to our configuration
598 bbd=bb2.createDomainEntry(domainname, filename);
599 bbd.d_filename=filename;
600 bbd.d_checknow=true;
601 bbd.d_loaded=true;
602 bbd.d_lastcheck=0;
603 bbd.d_status="parsing into memory";
604
605 safePutBBDomainInfo(bbd);
606
607 L<<Logger::Warning<<"Zone "<<domainname<< " loaded"<<endl;
608 return "Loaded zone " + domainname.toLogString() + " from " + filename;
609 }
610
611 Bind2Backend::Bind2Backend(const string &suffix, bool loadZones)
612 {
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;
627
628 setArgPrefix("bind"+suffix);
629 d_logprefix="[bind"+suffix+"backend]";
630 d_hybrid=mustDo("hybrid");
631 s_ignore_broken_records=mustDo("ignore-broken-records");
632
633 if (!loadZones && d_hybrid)
634 return;
635
636 Lock l(&s_startup_lock);
637
638 d_transaction_id=0;
639 setupDNSSEC();
640 if(!s_first) {
641 return;
642 }
643
644 if(loadZones) {
645 loadConfig();
646 s_first=0;
647 }
648
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>");
654 }
655
656 Bind2Backend::~Bind2Backend()
657 { freeStatements(); } // deallocate statements
658
659 void Bind2Backend::rediscover(string *status)
660 {
661 loadConfig(status);
662 }
663
664 void Bind2Backend::reload()
665 {
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)
669 }
670 }
671
672 void Bind2Backend::fixupOrderAndAuth(BB2DomainInfo& bbd, bool nsec3zone, NSEC3PARAMRecordContent ns3pr)
673 {
674 shared_ptr<recordstorage_t> records = bbd.d_records.getWRITABLE();
675
676 bool skip;
677 DNSName shorter;
678 set<DNSName> nssets, dssets;
679
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);
685 }
686
687 for(auto iter = records->begin(); iter != records->end(); iter++) {
688 skip = false;
689 shorter = iter->qname;
690
691 if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
692 do {
693 if(nssets.count(shorter)) {
694 skip = true;
695 break;
696 }
697 } while(shorter.chopOff() && !iter->qname.isRoot());
698 }
699
700 iter->auth = (!skip && (iter->qtype == QType::DS || iter->qtype == QType::RRSIG || !nssets.count(iter->qname)));
701
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);
706 }
707
708 // cerr<<iter->qname<<"\t"<<QType(iter->qtype).getName()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
709 }
710 }
711
712 void Bind2Backend::doEmptyNonTerminals(BB2DomainInfo& bbd, bool nsec3zone, NSEC3PARAMRecordContent ns3pr)
713 {
714 shared_ptr<const recordstorage_t> records = bbd.d_records.get();
715
716 bool auth;
717 DNSName shorter;
718 set<DNSName> qnames;
719 map<DNSName, bool> nonterm;
720
721 uint32_t maxent = ::arg().asNum("max-ent-entries");
722
723 for(const auto& bdr : *records)
724 qnames.insert(bdr.qname);
725
726 for(const auto& bdr : *records) {
727
728 if (!bdr.auth && bdr.qtype == QType::NS)
729 auth = (!nsec3zone || !ns3pr.d_flags);
730 else
731 auth = bdr.auth;
732
733 shorter = bdr.qname;
734 while(shorter.chopOff())
735 {
736 if(!qnames.count(shorter))
737 {
738 if(!(maxent))
739 {
740 L<<Logger::Error<<"Zone '"<<bbd.d_name<<"' has too many empty non terminals."<<endl;
741 return;
742 }
743
744 if (!nonterm.count(shorter)) {
745 nonterm.insert(pair<DNSName, bool>(shorter, auth));
746 --maxent;
747 } else if (auth)
748 nonterm[shorter] = true;
749 }
750 }
751 }
752
753 DNSResourceRecord rr;
754 rr.qtype = "#0";
755 rr.content = "";
756 rr.ttl = 0;
757 for(auto& nt : nonterm)
758 {
759 string hashed;
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);
764
765 // cerr<<rr.qname<<"\t"<<rr.qtype.getName()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
766 }
767 }
768
769 void Bind2Backend::loadConfig(string* status)
770 {
771 static int domain_id=1;
772
773 if(!getArg("config").empty()) {
774 BindParser BP;
775 try {
776 BP.parse(getArg("config"));
777 }
778 catch(PDNSException &ae) {
779 L<<Logger::Error<<"Error parsing bind configuration: "<<ae.reason<<endl;
780 throw;
781 }
782
783 vector<BindDomainInfo> domains=BP.getDomains();
784 this->alsoNotify = BP.getAlsoNotify();
785
786 s_binddirectory=BP.getDirectory();
787 // ZP.setDirectory(d_binddirectory);
788
789 L<<Logger::Warning<<d_logprefix<<" Parsing "<<domains.size()<<" domain(s), will report when done"<<endl;
790
791 set<DNSName> oldnames, newnames;
792 {
793 ReadLock rl(&s_state_lock);
794 for(const BB2DomainInfo& bbd : s_state) {
795 oldnames.insert(bbd.d_name);
796 }
797 }
798 int rejected=0;
799 int newdomains=0;
800
801 struct stat st;
802
803 for(vector<BindDomainInfo>::iterator i=domains.begin(); i!=domains.end(); ++i)
804 {
805 if(stat(i->filename.c_str(), &st) == 0) {
806 i->d_dev = st.st_dev;
807 i->d_ino = st.st_ino;
808 }
809 }
810
811 sort(domains.begin(), domains.end()); // put stuff in inode order
812 for(vector<BindDomainInfo>::const_iterator i=domains.begin();
813 i!=domains.end();
814 ++i)
815 {
816 if (!(i->hadFileDirective)) {
817 L<<Logger::Warning<<d_logprefix<<" Zone '"<<i->name<<"' has no 'file' directive set in "<<getArg("config")<<endl;
818 rejected++;
819 continue;
820 }
821
822 if(i->type == "")
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;
826 rejected++;
827 continue;
828 }
829
830 BB2DomainInfo bbd;
831 bool isNew = false;
832
833 if(!safeGetBBDomainInfo(i->name, &bbd)) {
834 isNew = true;
835 bbd.d_id=domain_id++;
836 bbd.setCheckInterval(getArgAsNum("check-interval"));
837 bbd.d_lastnotified=0;
838 bbd.d_loaded=false;
839 }
840
841 // overwrite what we knew about the domain
842 bbd.d_name=i->name;
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;
847
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;
853
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;
857
858 try {
859 parseZoneFile(&bbd);
860 }
861 catch(PDNSException &ae) {
862 ostringstream msg;
863 msg<<" error at "+nowTime()+" parsing '"<<i->name<<"' from file '"<<i->filename<<"': "<<ae.reason;
864
865 if(status)
866 *status+=msg.str();
867 bbd.d_status=msg.str();
868
869 L<<Logger::Warning<<d_logprefix<<msg.str()<<endl;
870 rejected++;
871 }
872 catch(std::system_error &ae) {
873 ostringstream msg;
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";
876 else
877 msg<<" error at "+nowTime()+" parsing '"<<i->name<<"' from file '"<<i->filename<<"': "<<ae.what();
878
879 if(status)
880 *status+=msg.str();
881 bbd.d_status=msg.str();
882 L<<Logger::Warning<<d_logprefix<<msg.str()<<endl;
883 rejected++;
884 }
885 catch(std::exception &ae) {
886 ostringstream msg;
887 msg<<" error at "+nowTime()+" parsing '"<<i->name<<"' from file '"<<i->filename<<"': "<<ae.what();
888
889 if(status)
890 *status+=msg.str();
891 bbd.d_status=msg.str();
892
893 L<<Logger::Warning<<d_logprefix<<msg.str()<<endl;
894 rejected++;
895 }
896 safePutBBDomainInfo(bbd);
897
898 }
899 }
900 vector<DNSName> diff;
901
902 set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
903 unsigned int remdomains=diff.size();
904
905 for(const DNSName& name: diff) {
906 safeRemoveBBDomainInfo(name);
907 }
908
909 // count number of entirely new domains
910 diff.clear();
911 set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
912 newdomains=diff.size();
913
914 ostringstream msg;
915 msg<<" Done parsing domains, "<<rejected<<" rejected, "<<newdomains<<" new, "<<remdomains<<" removed";
916 if(status)
917 *status=msg.str();
918
919 L<<Logger::Error<<d_logprefix<<msg.str()<<endl;
920 }
921 }
922
923 void Bind2Backend::queueReloadAndStore(unsigned int id)
924 {
925 BB2DomainInfo bbold;
926 try {
927 if(!safeGetBBDomainInfo(id, &bbold))
928 return;
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;
935 }
936 catch(PDNSException &ae) {
937 ostringstream msg;
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);
943 }
944 catch(std::exception &ae) {
945 ostringstream msg;
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);
951 }
952 }
953
954 bool Bind2Backend::findBeforeAndAfterUnhashed(BB2DomainInfo& bbd, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
955 {
956 shared_ptr<const recordstorage_t> records = bbd.d_records.get();
957
958 // for(const auto& record: *records)
959 // cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
960
961 recordstorage_t::const_iterator iterBefore, iterAfter;
962
963 iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
964
965 if(iterBefore != records->begin())
966 --iterBefore;
967 while((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
968 --iterBefore;
969 before=iterBefore->qname;
970
971 if(iterAfter == records->end()) {
972 iterAfter = records->begin();
973 } else {
974 while((!iterAfter->auth && iterAfter->qtype != QType::NS) || !iterAfter->qtype) {
975 ++iterAfter;
976 if(iterAfter == records->end()) {
977 iterAfter = records->begin();
978 break;
979 }
980 }
981 }
982 after = iterAfter->qname;
983
984 return true;
985 }
986
987 bool Bind2Backend::getBeforeAndAfterNamesAbsolute(uint32_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
988 {
989 BB2DomainInfo bbd;
990 if (!safeGetBBDomainInfo(id, &bbd))
991 return false;
992
993 NSEC3PARAMRecordContent ns3pr;
994
995 bool nsec3zone;
996 if (d_hybrid) {
997 DNSSECKeeper dk;
998 nsec3zone=dk.getNSEC3PARAM(bbd.d_name, &ns3pr);
999 } else
1000 nsec3zone=getNSEC3PARAM(bbd.d_name, &ns3pr);
1001
1002 if(!nsec3zone) {
1003 return findBeforeAndAfterUnhashed(bbd, qname, unhashed, before, after);
1004 }
1005 else {
1006 auto& hashindex=boost::multi_index::get<NSEC3Tag>(*bbd.d_records.getWRITABLE());
1007
1008 // for(auto iter = first; iter != hashindex.end(); iter++)
1009 // cerr<<iter->nsec3hash<<endl;
1010
1011 auto first = hashindex.upper_bound("");
1012 auto iter = hashindex.upper_bound(qname.toStringNoDot());
1013
1014 if (iter == hashindex.end()) {
1015 --iter;
1016 before = DNSName(iter->nsec3hash);
1017 after = DNSName(first->nsec3hash);
1018 } else {
1019 after = DNSName(iter->nsec3hash);
1020 if (iter != first)
1021 --iter;
1022 else
1023 iter = --hashindex.end();
1024 before = DNSName(iter->nsec3hash);
1025 }
1026 unhashed = iter->qname+bbd.d_name;
1027
1028 return true;
1029 }
1030 }
1031
1032 void Bind2Backend::lookup(const QType &qtype, const DNSName &qname, DNSPacket *pkt_p, int zoneId )
1033 {
1034 d_handle.reset();
1035 DNSName domain(qname);
1036
1037 static bool mustlog=::arg().mustDo("query-logging");
1038 if(mustlog)
1039 L<<Logger::Warning<<"Lookup for '"<<qtype.getName()<<"' of '"<<domain<<"' within zoneID "<<zoneId<<endl;
1040 bool found=false;
1041 BB2DomainInfo bbd;
1042
1043 do {
1044 found = safeGetBBDomainInfo(domain, &bbd);
1045 } while ((!found || (zoneId != (int)bbd.d_id && zoneId != -1)) && domain.chopOff());
1046
1047 if(!found) {
1048 if(mustlog)
1049 L<<Logger::Warning<<"Found no authoritative zone for "<<qname<<endl;
1050 d_handle.d_list=false;
1051 return;
1052 }
1053
1054 if(mustlog)
1055 L<<Logger::Warning<<"Found a zone '"<<domain<<"' (with id " << bbd.d_id<<") that might contain data "<<endl;
1056
1057 d_handle.id=bbd.d_id;
1058
1059 DLOG(L<<"Bind2Backend constructing handle for search for "<<qtype.getName()<<" for "<<
1060 qname<<endl);
1061
1062 if(domain.empty())
1063 d_handle.qname=qname;
1064 else if(qname.isPartOf(domain))
1065 d_handle.qname=qname.makeRelative(domain); // strip domain name
1066
1067 d_handle.qtype=qtype;
1068 d_handle.domain=domain;
1069
1070 if(!bbd.d_loaded) {
1071 d_handle.reset();
1072 throw DBException("Zone for '"+bbd.d_name.toLogString()+"' in '"+bbd.d_filename+"' temporarily not available (file missing, or master dead)"); // fsck
1073 }
1074
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
1080 }
1081
1082 d_handle.d_records = bbd.d_records.get();
1083
1084 if(d_handle.d_records->empty())
1085 DLOG(L<<"Query with no results"<<endl);
1086
1087 d_handle.mustlog = mustlog;
1088
1089 auto& hashedidx = boost::multi_index::get<UnorderedNameTag>(*d_handle.d_records);
1090 auto range = hashedidx.equal_range(d_handle.qname);
1091
1092 if(range.first==range.second) {
1093 d_handle.d_list=false;
1094 d_handle.d_iter = d_handle.d_end_iter = range.first;
1095 return;
1096 }
1097 else {
1098 d_handle.d_iter=range.first;
1099 d_handle.d_end_iter=range.second;
1100 }
1101
1102 d_handle.d_list=false;
1103 }
1104
1105 Bind2Backend::handle::handle()
1106 {
1107 mustlog=false;
1108 }
1109
1110 bool Bind2Backend::get(DNSResourceRecord &r)
1111 {
1112 if(!d_handle.d_records) {
1113 if(d_handle.mustlog)
1114 L<<Logger::Warning<<"There were no answers"<<endl;
1115 return false;
1116 }
1117
1118 if(!d_handle.get(r)) {
1119 if(d_handle.mustlog)
1120 L<<Logger::Warning<<"End of answers"<<endl;
1121
1122 d_handle.reset();
1123
1124 return false;
1125 }
1126 if(d_handle.mustlog)
1127 L<<Logger::Warning<<"Returning: '"<<r.qtype.getName()<<"' of '"<<r.qname<<"', content: '"<<r.content<<"'"<<endl;
1128 return true;
1129 }
1130
1131 bool Bind2Backend::handle::get(DNSResourceRecord &r)
1132 {
1133 if(d_list)
1134 return get_list(r);
1135 else
1136 return get_normal(r);
1137 }
1138
1139 void Bind2Backend::handle::reset()
1140 {
1141 d_records.reset();
1142 qname.clear();
1143 mustlog=false;
1144 }
1145
1146 //#define DLOG(x) x
1147 bool Bind2Backend::handle::get_normal(DNSResourceRecord &r)
1148 {
1149 DLOG(L << "Bind2Backend get() was called for "<<qtype.getName() << " record for '"<<
1150 qname<<"' - "<<d_records->size()<<" available in total!"<<endl);
1151
1152 if(d_iter==d_end_iter) {
1153 return false;
1154 }
1155
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);
1158 d_iter++;
1159 }
1160 if(d_iter==d_end_iter) {
1161 return false;
1162 }
1163 DLOG(L << "Bind2Backend get() returning a rr with a "<<QType(d_iter->qtype).getCode()<<endl);
1164
1165 r.qname=qname.empty() ? domain : (qname+domain);
1166 r.domain_id=id;
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;
1171
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;
1175
1176 d_iter++;
1177
1178 return true;
1179 }
1180
1181 bool Bind2Backend::list(const DNSName& target, int id, bool include_disabled)
1182 {
1183 BB2DomainInfo bbd;
1184
1185 if(!safeGetBBDomainInfo(id, &bbd))
1186 return false;
1187
1188 d_handle.reset();
1189 DLOG(L<<"Bind2Backend constructing handle for list of "<<id<<endl);
1190
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>
1194
1195 d_handle.id=id;
1196 d_handle.domain=bbd.d_name;
1197 d_handle.d_list=true;
1198 return true;
1199 }
1200
1201 bool Bind2Backend::handle::get_list(DNSResourceRecord &r)
1202 {
1203 if(d_qname_iter!=d_qname_end) {
1204 r.qname=d_qname_iter->qname.empty() ? domain : (d_qname_iter->qname+domain);
1205 r.domain_id=id;
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;
1210 d_qname_iter++;
1211 return true;
1212 }
1213 return false;
1214 }
1215
1216 bool Bind2Backend::isMaster(const DNSName& name, const string &ip)
1217 {
1218 BB2DomainInfo bbd;
1219 if(!safeGetBBDomainInfo(name, &bbd))
1220 return false;
1221
1222 if(bbd.d_kind != DomainInfo::Slave)
1223 return false;
1224
1225 for(vector<string>::const_iterator iter = bbd.d_masters.begin(); iter != bbd.d_masters.end(); ++iter)
1226 if(*iter==ip)
1227 return true;
1228
1229 return false;
1230 }
1231
1232 bool Bind2Backend::superMasterBackend(const string &ip, const DNSName& domain, const vector<DNSResourceRecord>&nsset, string *nameserver, string *account, DNSBackend **db)
1233 {
1234 // Check whether we have a configfile available.
1235 if (getArg("supermaster-config").empty())
1236 return false;
1237
1238 ifstream c_if(getArg("supermasters").c_str(), std::ios::in); // this was nocreate?
1239 if (!c_if) {
1240 L << Logger::Error << "Unable to open supermasters file for read: " << stringerror() << endl;
1241 return false;
1242 }
1243
1244 // Format:
1245 // <ip> <accountname>
1246 string line, sip, saccount;
1247 while (getline(c_if, line)) {
1248 std::istringstream ii(line);
1249 ii >> sip;
1250 if (sip == ip) {
1251 ii >> saccount;
1252 break;
1253 }
1254 }
1255 c_if.close();
1256
1257 if (sip != ip) // ip not found in authorization list - reject
1258 return false;
1259
1260 // ip authorized as supermaster - accept
1261 *db = this;
1262 if (saccount.length() > 0)
1263 *account = saccount.c_str();
1264
1265 return true;
1266 }
1267
1268 BB2DomainInfo Bind2Backend::createDomainEntry(const DNSName& domain, const string &filename)
1269 {
1270 int newid=1;
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;
1275 }
1276 }
1277
1278 BB2DomainInfo bbd;
1279 bbd.d_id = newid;
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;
1284 return bbd;
1285 }
1286
1287 bool Bind2Backend::createSlaveDomain(const string &ip, const DNSName& domain, const string &nameserver, const string &account)
1288 {
1289 string filename = getArg("supermaster-destdir")+'/'+domain.toStringNoDot();
1290
1291 L << Logger::Warning << d_logprefix
1292 << " Writing bind config zone statement for superslave zone '" << domain
1293 << "' from supermaster " << ip << endl;
1294
1295 {
1296 Lock l2(&s_supermaster_config_lock);
1297
1298 ofstream c_of(getArg("supermaster-config").c_str(), std::ios::app);
1299 if (!c_of) {
1300 L << Logger::Error << "Unable to open supermaster configfile for append: " << stringerror() << endl;
1301 throw DBException("Unable to open supermaster configfile for append: "+stringerror());
1302 }
1303
1304 c_of << endl;
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;
1311 c_of.close();
1312 }
1313
1314 BB2DomainInfo bbd = createDomainEntry(domain, filename);
1315 bbd.d_kind = DomainInfo::Slave;
1316 bbd.d_masters.push_back(ip);
1317 safePutBBDomainInfo(bbd);
1318 return true;
1319 }
1320
1321 bool Bind2Backend::searchRecords(const string &pattern, int maxResults, vector<DNSResourceRecord>& result)
1322 {
1323 SimpleMatch sm(pattern,true);
1324 static bool mustlog=::arg().mustDo("query-logging");
1325 if(mustlog)
1326 L<<Logger::Warning<<"Search for pattern '"<<pattern<<"'"<<endl;
1327
1328 {
1329 ReadLock rl(&s_state_lock);
1330
1331 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
1332 BB2DomainInfo h;
1333 safeGetBBDomainInfo(i->d_id, &h);
1334 shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
1335
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;
1340 r.qname=name;
1341 r.domain_id=i->d_id;
1342 r.content=ri->content;
1343 r.qtype=ri->qtype;
1344 r.ttl=ri->ttl;
1345 r.auth = ri->auth;
1346 result.push_back(r);
1347 }
1348 }
1349 }
1350 }
1351
1352 return true;
1353 }
1354
1355 class Bind2Factory : public BackendFactory
1356 {
1357 public:
1358 Bind2Factory() : BackendFactory("bind") {}
1359
1360 void declareArguments(const string &suffix="")
1361 {
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");
1370 }
1371
1372 DNSBackend *make(const string &suffix="")
1373 {
1374 return new Bind2Backend(suffix);
1375 }
1376
1377 DNSBackend *makeMetadataOnly(const string &suffix="")
1378 {
1379 return new Bind2Backend(suffix, false);
1380 }
1381 };
1382
1383 //! Magic class that is activated when the dynamic library is loaded
1384 class Bind2Loader
1385 {
1386 public:
1387 Bind2Loader()
1388 {
1389 BackendMakers().report(new Bind2Factory);
1390 L << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
1391 #ifndef REPRODUCIBLE
1392 << " (" __DATE__ " " __TIME__ ")"
1393 #endif
1394 << " reporting" << endl;
1395 }
1396 };
1397 static Bind2Loader bind2loader;