]> git.ipfire.org Git - thirdparty/pdns.git/blob - modules/bindbackend/bindbackend2.cc
auth: Always initialize the BindBackend's transaction ID
[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, bool ordernameIsNSEC3)
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, bool getSerial)
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 if(getSerial) {
418 try {
419 SOAData sd;
420 sd.serial=0;
421
422 getSOA(bbd.d_name,sd); // we might not *have* a SOA yet
423 di.serial=sd.serial;
424 }
425 catch(...){}
426 }
427
428 return true;
429 }
430
431 void Bind2Backend::alsoNotifies(const DNSName& domain, set<string> *ips)
432 {
433 // combine global list with local list
434 for(set<string>::iterator i = this->alsoNotify.begin(); i != this->alsoNotify.end(); i++) {
435 (*ips).insert(*i);
436 }
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++) {
441 (*ips).insert(*it);
442 }
443 return;
444 }
445 }
446 }
447
448 // only parses, does NOT add to s_state!
449 void Bind2Backend::parseZoneFile(BB2DomainInfo *bbd)
450 {
451 NSEC3PARAMRecordContent ns3pr;
452 bool nsec3zone;
453 if (d_hybrid) {
454 DNSSECKeeper dk;
455 nsec3zone=dk.getNSEC3PARAM(bbd->d_name, &ns3pr);
456 } else
457 nsec3zone=getNSEC3PARAM(bbd->d_name, &ns3pr);
458
459 bbd->d_records = shared_ptr<recordstorage_t>(new recordstorage_t());
460
461 ZoneParserTNG zpt(bbd->d_filename, bbd->d_name, s_binddirectory);
462 DNSResourceRecord rr;
463 string hashed;
464 while(zpt.get(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
467
468 insertRecord(*bbd, rr.qname, rr.qtype, rr.content, rr.ttl, "");
469 }
470 fixupOrderAndAuth(*bbd, nsec3zone, ns3pr);
471 doEmptyNonTerminals(*bbd, nsec3zone, ns3pr);
472 bbd->setCtime();
473 bbd->d_loaded=true;
474 bbd->d_checknow=false;
475 bbd->d_status="parsed into memory at "+nowTime();
476 }
477
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)
481 {
482 Bind2DNSRecord bdr;
483 shared_ptr<recordstorage_t> records = bb2.d_records.getWRITABLE();
484 bdr.qname=qname;
485
486 if(bb2.d_name.empty())
487 ;
488 else if(bdr.qname.isPartOf(bb2.d_name))
489 bdr.qname = bdr.qname.makeRelative(bb2.d_name);
490 else {
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;
494 return;
495 }
496 else
497 throw PDNSException(msg);
498 }
499
500 // bdr.qname.swap(bdr.qname);
501
502 if(!records->empty() && bdr.qname==boost::prior(records->end())->qname)
503 bdr.qname=boost::prior(records->end())->qname;
504
505 bdr.qname=bdr.qname;
506 bdr.qtype=qtype.getCode();
507 bdr.content=content;
508 bdr.nsec3hash = hashed;
509
510 if (auth) // Set auth on empty non-terminals
511 bdr.auth=*auth;
512 else
513 bdr.auth=true;
514
515 bdr.ttl=ttl;
516 records->insert(bdr);
517 }
518
519 string Bind2Backend::DLReloadNowHandler(const vector<string>&parts, Utility::pid_t ppid)
520 {
521 ostringstream ret;
522
523 for(vector<string>::const_iterator i=parts.begin()+1;i<parts.end();++i) {
524 BB2DomainInfo bbd;
525 DNSName zone(*i);
526 if(safeGetBBDomainInfo(zone, &bbd)) {
527 Bind2Backend bb2;
528 bb2.queueReloadAndStore(bbd.d_id);
529 if (!safeGetBBDomainInfo(zone, &bbd)) // Read the *new* domain status
530 ret << *i << ": [missing]\n";
531 else
532 ret<< *i << ": "<< (bbd.d_wasRejectedLastReload ? "[rejected]": "") <<"\t"<<bbd.d_status<<"\n";
533 }
534 else
535 ret<< *i << " no such domain\n";
536 }
537 if(ret.str().empty())
538 ret<<"no domains reloaded";
539 return ret.str();
540 }
541
542
543 string Bind2Backend::DLDomStatusHandler(const vector<string>&parts, Utility::pid_t ppid)
544 {
545 ostringstream ret;
546
547 if(parts.size() > 1) {
548 for(vector<string>::const_iterator i=parts.begin()+1;i<parts.end();++i) {
549 BB2DomainInfo bbd;
550 if(safeGetBBDomainInfo(DNSName(*i), &bbd)) {
551 ret<< *i << ": "<< (bbd.d_loaded ? "": "[rejected]") <<"\t"<<bbd.d_status<<"\n";
552 }
553 else
554 ret<< *i << " no such domain\n";
555 }
556 }
557 else {
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";
561 }
562 }
563
564 if(ret.str().empty())
565 ret<<"no domains passed";
566
567 return ret.str();
568 }
569
570 string Bind2Backend::DLListRejectsHandler(const vector<string>&parts, Utility::pid_t ppid)
571 {
572 ostringstream ret;
573 ReadLock rl(&s_state_lock);
574 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
575 if(!i->d_loaded)
576 ret<<i->d_name<<"\t"<<i->d_status<<endl;
577 }
578 return ret.str();
579 }
580
581 string Bind2Backend::DLAddDomainHandler(const vector<string>&parts, Utility::pid_t ppid)
582 {
583 if(parts.size() < 3)
584 return "ERROR: Domain name and zone filename are required";
585
586 DNSName domainname(parts[1]);
587 const string &filename = parts[2];
588 BB2DomainInfo bbd;
589 if(safeGetBBDomainInfo(domainname, &bbd))
590 return "Already loaded";
591
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.";
594
595 struct stat buf;
596 if (stat(filename.c_str(), &buf) != 0)
597 return "Unable to load zone " + domainname.toLogString() + " from " + filename + ": " + strerror(errno);
598
599 Bind2Backend bb2; // createdomainentry needs access to our configuration
600 bbd=bb2.createDomainEntry(domainname, filename);
601 bbd.d_filename=filename;
602 bbd.d_checknow=true;
603 bbd.d_loaded=true;
604 bbd.d_lastcheck=0;
605 bbd.d_status="parsing into memory";
606 bbd.setCtime();
607
608 safePutBBDomainInfo(bbd);
609
610 g_log<<Logger::Warning<<"Zone "<<domainname<< " loaded"<<endl;
611 return "Loaded zone " + domainname.toLogString() + " from " + filename;
612 }
613
614 Bind2Backend::Bind2Backend(const string &suffix, bool loadZones)
615 {
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;
630
631 setArgPrefix("bind"+suffix);
632 d_logprefix="[bind"+suffix+"backend]";
633 d_hybrid=mustDo("hybrid");
634 d_transaction_id=0;
635 s_ignore_broken_records=mustDo("ignore-broken-records");
636
637 if (!loadZones && d_hybrid)
638 return;
639
640 Lock l(&s_startup_lock);
641
642 setupDNSSEC();
643 if(!s_first) {
644 return;
645 }
646
647 if(loadZones) {
648 loadConfig();
649 s_first=0;
650 }
651
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>");
657 }
658
659 Bind2Backend::~Bind2Backend()
660 { freeStatements(); } // deallocate statements
661
662 void Bind2Backend::rediscover(string *status)
663 {
664 loadConfig(status);
665 }
666
667 void Bind2Backend::reload()
668 {
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)
672 }
673 }
674
675 void Bind2Backend::fixupOrderAndAuth(BB2DomainInfo& bbd, bool nsec3zone, NSEC3PARAMRecordContent ns3pr)
676 {
677 shared_ptr<recordstorage_t> records = bbd.d_records.getWRITABLE();
678
679 bool skip;
680 DNSName shorter;
681 set<DNSName> nssets, dssets;
682
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);
688 }
689
690 for(auto iter = records->begin(); iter != records->end(); iter++) {
691 skip = false;
692 shorter = iter->qname;
693
694 if (!iter->qname.isRoot() && shorter.chopOff() && !iter->qname.isRoot()) {
695 do {
696 if(nssets.count(shorter)) {
697 skip = true;
698 break;
699 }
700 } while(shorter.chopOff() && !iter->qname.isRoot());
701 }
702
703 iter->auth = (!skip && (iter->qtype == QType::DS || iter->qtype == QType::RRSIG || !nssets.count(iter->qname)));
704
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);
709 }
710
711 // cerr<<iter->qname<<"\t"<<QType(iter->qtype).getName()<<"\t"<<iter->nsec3hash<<"\t"<<iter->auth<<endl;
712 }
713 }
714
715 void Bind2Backend::doEmptyNonTerminals(BB2DomainInfo& bbd, bool nsec3zone, NSEC3PARAMRecordContent ns3pr)
716 {
717 shared_ptr<const recordstorage_t> records = bbd.d_records.get();
718
719 bool auth;
720 DNSName shorter;
721 set<DNSName> qnames;
722 map<DNSName, bool> nonterm;
723
724 uint32_t maxent = ::arg().asNum("max-ent-entries");
725
726 for(const auto& bdr : *records)
727 qnames.insert(bdr.qname);
728
729 for(const auto& bdr : *records) {
730
731 if (!bdr.auth && bdr.qtype == QType::NS)
732 auth = (!nsec3zone || !ns3pr.d_flags);
733 else
734 auth = bdr.auth;
735
736 shorter = bdr.qname;
737 while(shorter.chopOff())
738 {
739 if(!qnames.count(shorter))
740 {
741 if(!(maxent))
742 {
743 g_log<<Logger::Error<<"Zone '"<<bbd.d_name<<"' has too many empty non terminals."<<endl;
744 return;
745 }
746
747 if (!nonterm.count(shorter)) {
748 nonterm.insert(pair<DNSName, bool>(shorter, auth));
749 --maxent;
750 } else if (auth)
751 nonterm[shorter] = true;
752 }
753 }
754 }
755
756 DNSResourceRecord rr;
757 rr.qtype = "#0";
758 rr.content = "";
759 rr.ttl = 0;
760 for(auto& nt : nonterm)
761 {
762 string hashed;
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);
767
768 // cerr<<rr.qname<<"\t"<<rr.qtype.getName()<<"\t"<<hashed<<"\t"<<nt.second<<endl;
769 }
770 }
771
772 void Bind2Backend::loadConfig(string* status)
773 {
774 static int domain_id=1;
775
776 if(!getArg("config").empty()) {
777 BindParser BP;
778 try {
779 BP.parse(getArg("config"));
780 }
781 catch(PDNSException &ae) {
782 g_log<<Logger::Error<<"Error parsing bind configuration: "<<ae.reason<<endl;
783 throw;
784 }
785
786 vector<BindDomainInfo> domains=BP.getDomains();
787 this->alsoNotify = BP.getAlsoNotify();
788
789 s_binddirectory=BP.getDirectory();
790 // ZP.setDirectory(d_binddirectory);
791
792 g_log<<Logger::Warning<<d_logprefix<<" Parsing "<<domains.size()<<" domain(s), will report when done"<<endl;
793
794 set<DNSName> oldnames, newnames;
795 {
796 ReadLock rl(&s_state_lock);
797 for(const BB2DomainInfo& bbd : s_state) {
798 oldnames.insert(bbd.d_name);
799 }
800 }
801 int rejected=0;
802 int newdomains=0;
803
804 struct stat st;
805
806 for(vector<BindDomainInfo>::iterator i=domains.begin(); i!=domains.end(); ++i)
807 {
808 if(stat(i->filename.c_str(), &st) == 0) {
809 i->d_dev = st.st_dev;
810 i->d_ino = st.st_ino;
811 }
812 }
813
814 sort(domains.begin(), domains.end()); // put stuff in inode order
815 for(vector<BindDomainInfo>::const_iterator i=domains.begin();
816 i!=domains.end();
817 ++i)
818 {
819 if (!(i->hadFileDirective)) {
820 g_log<<Logger::Warning<<d_logprefix<<" Zone '"<<i->name<<"' has no 'file' directive set in "<<getArg("config")<<endl;
821 rejected++;
822 continue;
823 }
824
825 if(i->type == "")
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;
829 rejected++;
830 continue;
831 }
832
833 BB2DomainInfo bbd;
834 bool isNew = false;
835
836 if(!safeGetBBDomainInfo(i->name, &bbd)) {
837 isNew = true;
838 bbd.d_id=domain_id++;
839 bbd.setCheckInterval(getArgAsNum("check-interval"));
840 bbd.d_lastnotified=0;
841 bbd.d_loaded=false;
842 }
843
844 // overwrite what we knew about the domain
845 bbd.d_name=i->name;
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;
850
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;
856
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;
860
861 try {
862 parseZoneFile(&bbd);
863 }
864 catch(PDNSException &ae) {
865 ostringstream msg;
866 msg<<" error at "+nowTime()+" parsing '"<<i->name<<"' from file '"<<i->filename<<"': "<<ae.reason;
867
868 if(status)
869 *status+=msg.str();
870 bbd.d_status=msg.str();
871
872 g_log<<Logger::Warning<<d_logprefix<<msg.str()<<endl;
873 rejected++;
874 }
875 catch(std::system_error &ae) {
876 ostringstream msg;
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";
879 else
880 msg<<" error at "+nowTime()+" parsing '"<<i->name<<"' from file '"<<i->filename<<"': "<<ae.what();
881
882 if(status)
883 *status+=msg.str();
884 bbd.d_status=msg.str();
885 g_log<<Logger::Warning<<d_logprefix<<msg.str()<<endl;
886 rejected++;
887 }
888 catch(std::exception &ae) {
889 ostringstream msg;
890 msg<<" error at "+nowTime()+" parsing '"<<i->name<<"' from file '"<<i->filename<<"': "<<ae.what();
891
892 if(status)
893 *status+=msg.str();
894 bbd.d_status=msg.str();
895
896 g_log<<Logger::Warning<<d_logprefix<<msg.str()<<endl;
897 rejected++;
898 }
899 safePutBBDomainInfo(bbd);
900
901 }
902 }
903 vector<DNSName> diff;
904
905 set_difference(oldnames.begin(), oldnames.end(), newnames.begin(), newnames.end(), back_inserter(diff));
906 unsigned int remdomains=diff.size();
907
908 for(const DNSName& name: diff) {
909 safeRemoveBBDomainInfo(name);
910 }
911
912 // count number of entirely new domains
913 diff.clear();
914 set_difference(newnames.begin(), newnames.end(), oldnames.begin(), oldnames.end(), back_inserter(diff));
915 newdomains=diff.size();
916
917 ostringstream msg;
918 msg<<" Done parsing domains, "<<rejected<<" rejected, "<<newdomains<<" new, "<<remdomains<<" removed";
919 if(status)
920 *status=msg.str();
921
922 g_log<<Logger::Error<<d_logprefix<<msg.str()<<endl;
923 }
924 }
925
926 void Bind2Backend::queueReloadAndStore(unsigned int id)
927 {
928 BB2DomainInfo bbold;
929 try {
930 if(!safeGetBBDomainInfo(id, &bbold))
931 return;
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;
938 }
939 catch(PDNSException &ae) {
940 ostringstream msg;
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);
946 }
947 catch(std::exception &ae) {
948 ostringstream msg;
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);
954 }
955 }
956
957 bool Bind2Backend::findBeforeAndAfterUnhashed(BB2DomainInfo& bbd, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
958 {
959 shared_ptr<const recordstorage_t> records = bbd.d_records.get();
960
961 // for(const auto& record: *records)
962 // cerr<<record.qname<<"\t"<<makeHexDump(record.qname.toDNSString())<<endl;
963
964 recordstorage_t::const_iterator iterBefore, iterAfter;
965
966 iterBefore = iterAfter = records->upper_bound(qname.makeLowerCase());
967
968 if(iterBefore != records->begin())
969 --iterBefore;
970 while((!iterBefore->auth && iterBefore->qtype != QType::NS) || !iterBefore->qtype)
971 --iterBefore;
972 before=iterBefore->qname;
973
974 if(iterAfter == records->end()) {
975 iterAfter = records->begin();
976 } else {
977 while((!iterAfter->auth && iterAfter->qtype != QType::NS) || !iterAfter->qtype) {
978 ++iterAfter;
979 if(iterAfter == records->end()) {
980 iterAfter = records->begin();
981 break;
982 }
983 }
984 }
985 after = iterAfter->qname;
986
987 return true;
988 }
989
990 bool Bind2Backend::getBeforeAndAfterNamesAbsolute(uint32_t id, const DNSName& qname, DNSName& unhashed, DNSName& before, DNSName& after)
991 {
992 BB2DomainInfo bbd;
993 if (!safeGetBBDomainInfo(id, &bbd))
994 return false;
995
996 NSEC3PARAMRecordContent ns3pr;
997
998 bool nsec3zone;
999 if (d_hybrid) {
1000 DNSSECKeeper dk;
1001 nsec3zone=dk.getNSEC3PARAM(bbd.d_name, &ns3pr);
1002 } else
1003 nsec3zone=getNSEC3PARAM(bbd.d_name, &ns3pr);
1004
1005 if(!nsec3zone) {
1006 return findBeforeAndAfterUnhashed(bbd, qname, unhashed, before, after);
1007 }
1008 else {
1009 auto& hashindex=boost::multi_index::get<NSEC3Tag>(*bbd.d_records.getWRITABLE());
1010
1011 // for(auto iter = first; iter != hashindex.end(); iter++)
1012 // cerr<<iter->nsec3hash<<endl;
1013
1014 auto first = hashindex.upper_bound("");
1015 auto iter = hashindex.upper_bound(qname.toStringNoDot());
1016
1017 if (iter == hashindex.end()) {
1018 --iter;
1019 before = DNSName(iter->nsec3hash);
1020 after = DNSName(first->nsec3hash);
1021 } else {
1022 after = DNSName(iter->nsec3hash);
1023 if (iter != first)
1024 --iter;
1025 else
1026 iter = --hashindex.end();
1027 before = DNSName(iter->nsec3hash);
1028 }
1029 unhashed = iter->qname+bbd.d_name;
1030
1031 return true;
1032 }
1033 }
1034
1035 void Bind2Backend::lookup(const QType &qtype, const DNSName &qname, DNSPacket *pkt_p, int zoneId )
1036 {
1037 d_handle.reset();
1038 DNSName domain(qname);
1039
1040 static bool mustlog=::arg().mustDo("query-logging");
1041 if(mustlog)
1042 g_log<<Logger::Warning<<"Lookup for '"<<qtype.getName()<<"' of '"<<domain<<"' within zoneID "<<zoneId<<endl;
1043 bool found=false;
1044 BB2DomainInfo bbd;
1045
1046 do {
1047 found = safeGetBBDomainInfo(domain, &bbd);
1048 } while ((!found || (zoneId != (int)bbd.d_id && zoneId != -1)) && domain.chopOff());
1049
1050 if(!found) {
1051 if(mustlog)
1052 g_log<<Logger::Warning<<"Found no authoritative zone for "<<qname<<endl;
1053 d_handle.d_list=false;
1054 return;
1055 }
1056
1057 if(mustlog)
1058 g_log<<Logger::Warning<<"Found a zone '"<<domain<<"' (with id " << bbd.d_id<<") that might contain data "<<endl;
1059
1060 d_handle.id=bbd.d_id;
1061
1062 DLOG(g_log<<"Bind2Backend constructing handle for search for "<<qtype.getName()<<" for "<<
1063 qname<<endl);
1064
1065 if(domain.empty())
1066 d_handle.qname=qname;
1067 else if(qname.isPartOf(domain))
1068 d_handle.qname=qname.makeRelative(domain); // strip domain name
1069
1070 d_handle.qtype=qtype;
1071 d_handle.domain=domain;
1072
1073 if(!bbd.d_loaded) {
1074 d_handle.reset();
1075 throw DBException("Zone for '"+bbd.d_name.toLogString()+"' in '"+bbd.d_filename+"' temporarily not available (file missing, or master dead)"); // fsck
1076 }
1077
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
1083 }
1084
1085 d_handle.d_records = bbd.d_records.get();
1086
1087 if(d_handle.d_records->empty())
1088 DLOG(g_log<<"Query with no results"<<endl);
1089
1090 d_handle.mustlog = mustlog;
1091
1092 auto& hashedidx = boost::multi_index::get<UnorderedNameTag>(*d_handle.d_records);
1093 auto range = hashedidx.equal_range(d_handle.qname);
1094
1095 if(range.first==range.second) {
1096 d_handle.d_list=false;
1097 d_handle.d_iter = d_handle.d_end_iter = range.first;
1098 return;
1099 }
1100 else {
1101 d_handle.d_iter=range.first;
1102 d_handle.d_end_iter=range.second;
1103 }
1104
1105 d_handle.d_list=false;
1106 }
1107
1108 Bind2Backend::handle::handle()
1109 {
1110 mustlog=false;
1111 }
1112
1113 bool Bind2Backend::get(DNSResourceRecord &r)
1114 {
1115 if(!d_handle.d_records) {
1116 if(d_handle.mustlog)
1117 g_log<<Logger::Warning<<"There were no answers"<<endl;
1118 return false;
1119 }
1120
1121 if(!d_handle.get(r)) {
1122 if(d_handle.mustlog)
1123 g_log<<Logger::Warning<<"End of answers"<<endl;
1124
1125 d_handle.reset();
1126
1127 return false;
1128 }
1129 if(d_handle.mustlog)
1130 g_log<<Logger::Warning<<"Returning: '"<<r.qtype.getName()<<"' of '"<<r.qname<<"', content: '"<<r.content<<"'"<<endl;
1131 return true;
1132 }
1133
1134 bool Bind2Backend::handle::get(DNSResourceRecord &r)
1135 {
1136 if(d_list)
1137 return get_list(r);
1138 else
1139 return get_normal(r);
1140 }
1141
1142 void Bind2Backend::handle::reset()
1143 {
1144 d_records.reset();
1145 qname.clear();
1146 mustlog=false;
1147 }
1148
1149 //#define DLOG(x) x
1150 bool Bind2Backend::handle::get_normal(DNSResourceRecord &r)
1151 {
1152 DLOG(g_log << "Bind2Backend get() was called for "<<qtype.getName() << " record for '"<<
1153 qname<<"' - "<<d_records->size()<<" available in total!"<<endl);
1154
1155 if(d_iter==d_end_iter) {
1156 return false;
1157 }
1158
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);
1161 d_iter++;
1162 }
1163 if(d_iter==d_end_iter) {
1164 return false;
1165 }
1166 DLOG(g_log << "Bind2Backend get() returning a rr with a "<<QType(d_iter->qtype).getCode()<<endl);
1167
1168 r.qname=qname.empty() ? domain : (qname+domain);
1169 r.domain_id=id;
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;
1174
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;
1178
1179 d_iter++;
1180
1181 return true;
1182 }
1183
1184 bool Bind2Backend::list(const DNSName& target, int id, bool include_disabled)
1185 {
1186 BB2DomainInfo bbd;
1187
1188 if(!safeGetBBDomainInfo(id, &bbd))
1189 return false;
1190
1191 d_handle.reset();
1192 DLOG(g_log<<"Bind2Backend constructing handle for list of "<<id<<endl);
1193
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>
1197
1198 d_handle.id=id;
1199 d_handle.domain=bbd.d_name;
1200 d_handle.d_list=true;
1201 return true;
1202 }
1203
1204 bool Bind2Backend::handle::get_list(DNSResourceRecord &r)
1205 {
1206 if(d_qname_iter!=d_qname_end) {
1207 r.qname=d_qname_iter->qname.empty() ? domain : (d_qname_iter->qname+domain);
1208 r.domain_id=id;
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;
1213 d_qname_iter++;
1214 return true;
1215 }
1216 return false;
1217 }
1218
1219 bool Bind2Backend::superMasterBackend(const string &ip, const DNSName& domain, const vector<DNSResourceRecord>&nsset, string *nameserver, string *account, DNSBackend **db)
1220 {
1221 // Check whether we have a configfile available.
1222 if (getArg("supermaster-config").empty())
1223 return false;
1224
1225 ifstream c_if(getArg("supermasters").c_str(), std::ios::in); // this was nocreate?
1226 if (!c_if) {
1227 g_log << Logger::Error << "Unable to open supermasters file for read: " << stringerror() << endl;
1228 return false;
1229 }
1230
1231 // Format:
1232 // <ip> <accountname>
1233 string line, sip, saccount;
1234 while (getline(c_if, line)) {
1235 std::istringstream ii(line);
1236 ii >> sip;
1237 if (sip == ip) {
1238 ii >> saccount;
1239 break;
1240 }
1241 }
1242 c_if.close();
1243
1244 if (sip != ip) // ip not found in authorization list - reject
1245 return false;
1246
1247 // ip authorized as supermaster - accept
1248 *db = this;
1249 if (saccount.length() > 0)
1250 *account = saccount.c_str();
1251
1252 return true;
1253 }
1254
1255 BB2DomainInfo Bind2Backend::createDomainEntry(const DNSName& domain, const string &filename)
1256 {
1257 int newid=1;
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;
1262 }
1263 }
1264
1265 BB2DomainInfo bbd;
1266 bbd.d_kind = DomainInfo::Native;
1267 bbd.d_id = newid;
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;
1272
1273 return bbd;
1274 }
1275
1276 bool Bind2Backend::createSlaveDomain(const string &ip, const DNSName& domain, const string &nameserver, const string &account)
1277 {
1278 string filename = getArg("supermaster-destdir")+'/'+domain.toStringNoDot();
1279
1280 g_log << Logger::Warning << d_logprefix
1281 << " Writing bind config zone statement for superslave zone '" << domain
1282 << "' from supermaster " << ip << endl;
1283
1284 {
1285 Lock l2(&s_supermaster_config_lock);
1286
1287 ofstream c_of(getArg("supermaster-config").c_str(), std::ios::app);
1288 if (!c_of) {
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());
1291 }
1292
1293 c_of << endl;
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;
1300 c_of.close();
1301 }
1302
1303 BB2DomainInfo bbd = createDomainEntry(domain, filename);
1304 bbd.d_kind = DomainInfo::Slave;
1305 bbd.d_masters.push_back(ComboAddress(ip, 53));
1306 bbd.setCtime();
1307 safePutBBDomainInfo(bbd);
1308 return true;
1309 }
1310
1311 bool Bind2Backend::searchRecords(const string &pattern, int maxResults, vector<DNSResourceRecord>& result)
1312 {
1313 SimpleMatch sm(pattern,true);
1314 static bool mustlog=::arg().mustDo("query-logging");
1315 if(mustlog)
1316 g_log<<Logger::Warning<<"Search for pattern '"<<pattern<<"'"<<endl;
1317
1318 {
1319 ReadLock rl(&s_state_lock);
1320
1321 for(state_t::const_iterator i = s_state.begin(); i != s_state.end() ; ++i) {
1322 BB2DomainInfo h;
1323 safeGetBBDomainInfo(i->d_id, &h);
1324 shared_ptr<const recordstorage_t> rhandle = h.d_records.get();
1325
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;
1330 r.qname=name;
1331 r.domain_id=i->d_id;
1332 r.content=ri->content;
1333 r.qtype=ri->qtype;
1334 r.ttl=ri->ttl;
1335 r.auth = ri->auth;
1336 result.push_back(r);
1337 }
1338 }
1339 }
1340 }
1341
1342 return true;
1343 }
1344
1345 class Bind2Factory : public BackendFactory
1346 {
1347 public:
1348 Bind2Factory() : BackendFactory("bind") {}
1349
1350 void declareArguments(const string &suffix="")
1351 {
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");
1360 }
1361
1362 DNSBackend *make(const string &suffix="")
1363 {
1364 assertEmptySuffix(suffix);
1365 return new Bind2Backend(suffix);
1366 }
1367
1368 DNSBackend *makeMetadataOnly(const string &suffix="")
1369 {
1370 assertEmptySuffix(suffix);
1371 return new Bind2Backend(suffix, false);
1372 }
1373 private:
1374 void assertEmptySuffix(const string &suffix)
1375 {
1376 if(suffix.length())
1377 throw PDNSException("launch= suffixes are not supported on the bindbackend");
1378 }
1379 };
1380
1381 //! Magic class that is activated when the dynamic library is loaded
1382 class Bind2Loader
1383 {
1384 public:
1385 Bind2Loader()
1386 {
1387 BackendMakers().report(new Bind2Factory);
1388 g_log << Logger::Info << "[bind2backend] This is the bind backend version " << VERSION
1389 #ifndef REPRODUCIBLE
1390 << " (" __DATE__ " " __TIME__ ")"
1391 #endif
1392 #ifdef HAVE_SQLITE3
1393 << " (with bind-dnssec-db support)"
1394 #endif
1395 << " reporting" << endl;
1396 }
1397 };
1398 static Bind2Loader bind2loader;