database.cc 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. // Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <string>
  15. #include <vector>
  16. #include <datasrc/database.h>
  17. #include <datasrc/data_source.h>
  18. #include <datasrc/iterator.h>
  19. #include <exceptions/exceptions.h>
  20. #include <dns/name.h>
  21. #include <dns/rrclass.h>
  22. #include <dns/rrttl.h>
  23. #include <dns/rrset.h>
  24. #include <dns/rdata.h>
  25. #include <dns/rdataclass.h>
  26. #include <datasrc/data_source.h>
  27. #include <datasrc/logger.h>
  28. #include <boost/foreach.hpp>
  29. using namespace isc::dns;
  30. using namespace std;
  31. using boost::shared_ptr;
  32. using namespace isc::dns::rdata;
  33. namespace isc {
  34. namespace datasrc {
  35. DatabaseClient::DatabaseClient(RRClass rrclass,
  36. boost::shared_ptr<DatabaseAccessor>
  37. accessor) :
  38. rrclass_(rrclass), accessor_(accessor)
  39. {
  40. if (!accessor_) {
  41. isc_throw(isc::InvalidParameter,
  42. "No database provided to DatabaseClient");
  43. }
  44. }
  45. DataSourceClient::FindResult
  46. DatabaseClient::findZone(const Name& name) const {
  47. std::pair<bool, int> zone(accessor_->getZone(name.toText()));
  48. // Try exact first
  49. if (zone.first) {
  50. return (FindResult(result::SUCCESS,
  51. ZoneFinderPtr(new Finder(accessor_,
  52. zone.second, name))));
  53. }
  54. // Then super domains
  55. // Start from 1, as 0 is covered above
  56. for (size_t i(1); i < name.getLabelCount(); ++i) {
  57. isc::dns::Name superdomain(name.split(i));
  58. zone = accessor_->getZone(superdomain.toText());
  59. if (zone.first) {
  60. return (FindResult(result::PARTIALMATCH,
  61. ZoneFinderPtr(new Finder(accessor_,
  62. zone.second,
  63. superdomain))));
  64. }
  65. }
  66. // No, really nothing
  67. return (FindResult(result::NOTFOUND, ZoneFinderPtr()));
  68. }
  69. DatabaseClient::Finder::Finder(boost::shared_ptr<DatabaseAccessor> accessor,
  70. int zone_id, const isc::dns::Name& origin) :
  71. accessor_(accessor),
  72. zone_id_(zone_id),
  73. origin_(origin)
  74. { }
  75. namespace {
  76. // Adds the given Rdata to the given RRset
  77. // If the rrset is an empty pointer, a new one is
  78. // created with the given name, class, type and ttl
  79. // The type is checked if the rrset exists, but the
  80. // name is not.
  81. //
  82. // Then adds the given rdata to the set
  83. //
  84. // Raises a DataSourceError if the type does not
  85. // match, or if the given rdata string does not
  86. // parse correctly for the given type and class
  87. //
  88. // The DatabaseAccessor is passed to print the
  89. // database name in the log message if the TTL is
  90. // modified
  91. void addOrCreate(isc::dns::RRsetPtr& rrset,
  92. const isc::dns::Name& name,
  93. const isc::dns::RRClass& cls,
  94. const isc::dns::RRType& type,
  95. const isc::dns::RRTTL& ttl,
  96. const std::string& rdata_str,
  97. const DatabaseAccessor& db
  98. )
  99. {
  100. if (!rrset) {
  101. rrset.reset(new isc::dns::RRset(name, cls, type, ttl));
  102. } else {
  103. // This is a check to make sure find() is not messing things up
  104. assert(type == rrset->getType());
  105. if (ttl != rrset->getTTL()) {
  106. if (ttl < rrset->getTTL()) {
  107. rrset->setTTL(ttl);
  108. }
  109. logger.warn(DATASRC_DATABASE_FIND_TTL_MISMATCH)
  110. .arg(db.getDBName()).arg(name).arg(cls)
  111. .arg(type).arg(rrset->getTTL());
  112. }
  113. }
  114. try {
  115. rrset->addRdata(isc::dns::rdata::createRdata(type, cls, rdata_str));
  116. } catch (const isc::dns::rdata::InvalidRdataText& ivrt) {
  117. // at this point, rrset may have been initialised for no reason,
  118. // and won't be used. But the caller would drop the shared_ptr
  119. // on such an error anyway, so we don't care.
  120. isc_throw(DataSourceError,
  121. "bad rdata in database for " << name << " "
  122. << type << ": " << ivrt.what());
  123. }
  124. }
  125. // This class keeps a short-lived store of RRSIG records encountered
  126. // during a call to find(). If the backend happens to return signatures
  127. // before the actual data, we might not know which signatures we will need
  128. // So if they may be relevant, we store the in this class.
  129. //
  130. // (If this class seems useful in other places, we might want to move
  131. // it to util. That would also provide an opportunity to add unit tests)
  132. class RRsigStore {
  133. public:
  134. // Adds the given signature Rdata to the store
  135. // The signature rdata MUST be of the RRSIG rdata type
  136. // (the caller must make sure of this).
  137. // NOTE: if we move this class to a public namespace,
  138. // we should add a type_covered argument, so as not
  139. // to have to do this cast here.
  140. void addSig(isc::dns::rdata::RdataPtr sig_rdata) {
  141. const isc::dns::RRType& type_covered =
  142. static_cast<isc::dns::rdata::generic::RRSIG*>(
  143. sig_rdata.get())->typeCovered();
  144. sigs[type_covered].push_back(sig_rdata);
  145. }
  146. // If the store contains signatures for the type of the given
  147. // rrset, they are appended to it.
  148. void appendSignatures(isc::dns::RRsetPtr& rrset) const {
  149. std::map<isc::dns::RRType,
  150. std::vector<isc::dns::rdata::RdataPtr> >::const_iterator
  151. found = sigs.find(rrset->getType());
  152. if (found != sigs.end()) {
  153. BOOST_FOREACH(isc::dns::rdata::RdataPtr sig, found->second) {
  154. rrset->addRRsig(sig);
  155. }
  156. }
  157. }
  158. private:
  159. std::map<isc::dns::RRType, std::vector<isc::dns::rdata::RdataPtr> > sigs;
  160. };
  161. }
  162. DatabaseClient::Finder::FoundRRsets
  163. DatabaseClient::Finder::getRRsets(const string& name, const WantedTypes& types,
  164. bool check_ns, const string* construct_name)
  165. {
  166. RRsigStore sig_store;
  167. bool records_found = false;
  168. std::map<RRType, RRsetPtr> result;
  169. // Request the context
  170. DatabaseAccessor::IteratorContextPtr
  171. context(accessor_->getRecords(name, zone_id_));
  172. // It must not return NULL, that's a bug of the implementation
  173. if (!context) {
  174. isc_throw(isc::Unexpected, "Iterator context null at " + name);
  175. }
  176. std::string columns[DatabaseAccessor::COLUMN_COUNT];
  177. if (construct_name == NULL) {
  178. construct_name = &name;
  179. }
  180. const Name construct_name_object(*construct_name);
  181. bool seen_cname(false);
  182. bool seen_ds(false);
  183. bool seen_other(false);
  184. bool seen_ns(false);
  185. while (context->getNext(columns)) {
  186. // The domain is not empty
  187. records_found = true;
  188. try {
  189. const RRType cur_type(columns[DatabaseAccessor::TYPE_COLUMN]);
  190. if (cur_type == RRType::RRSIG()) {
  191. // If we get signatures before we get the actual data, we
  192. // can't know which ones to keep and which to drop...
  193. // So we keep a separate store of any signature that may be
  194. // relevant and add them to the final RRset when we are
  195. // done.
  196. // A possible optimization here is to not store them for
  197. // types we are certain we don't need
  198. sig_store.addSig(rdata::createRdata(cur_type, getClass(),
  199. columns[DatabaseAccessor::RDATA_COLUMN]));
  200. }
  201. if (types.find(cur_type) != types.end()) {
  202. // This type is requested, so put it into result
  203. const RRTTL cur_ttl(columns[DatabaseAccessor::TTL_COLUMN]);
  204. // Ths sigtype column was an optimization for finding the
  205. // relevant RRSIG RRs for a lookup. Currently this column is
  206. // not used in this revised datasource implementation. We
  207. // should either start using it again, or remove it from use
  208. // completely (i.e. also remove it from the schema and the
  209. // backend implementation).
  210. // Note that because we don't use it now, we also won't notice
  211. // it if the value is wrong (i.e. if the sigtype column
  212. // contains an rrtype that is different from the actual value
  213. // of the 'type covered' field in the RRSIG Rdata).
  214. //cur_sigtype(columns[SIGTYPE_COLUMN]);
  215. addOrCreate(result[cur_type], construct_name_object,
  216. getClass(), cur_type, cur_ttl,
  217. columns[DatabaseAccessor::RDATA_COLUMN],
  218. *accessor_);
  219. }
  220. if (cur_type == RRType::CNAME()) {
  221. seen_cname = true;
  222. } else if (cur_type == RRType::NS()) {
  223. seen_ns = true;
  224. } else if (cur_type == RRType::DS()) {
  225. seen_ds = true;
  226. } else if (cur_type != RRType::RRSIG() &&
  227. cur_type != RRType::NSEC3() &&
  228. cur_type != RRType::NSEC()) {
  229. // NSEC and RRSIG can coexist with anything, otherwise
  230. // we've seen something that can't live together with potential
  231. // CNAME or NS
  232. //
  233. // NSEC3 lives in separate namespace from everything, therefore
  234. // we just ignore it here for these checks as well.
  235. seen_other = true;
  236. }
  237. } catch (const InvalidRRType&) {
  238. isc_throw(DataSourceError, "Invalid RRType in database for " <<
  239. name << ": " << columns[DatabaseAccessor::
  240. TYPE_COLUMN]);
  241. } catch (const InvalidRRTTL&) {
  242. isc_throw(DataSourceError, "Invalid TTL in database for " <<
  243. name << ": " << columns[DatabaseAccessor::
  244. TTL_COLUMN]);
  245. } catch (const rdata::InvalidRdataText&) {
  246. isc_throw(DataSourceError, "Invalid rdata in database for " <<
  247. name << ": " << columns[DatabaseAccessor::
  248. RDATA_COLUMN]);
  249. }
  250. }
  251. if (seen_cname && (seen_other || seen_ns || seen_ds)) {
  252. isc_throw(DataSourceError, "CNAME shares domain " << name <<
  253. " with something else");
  254. }
  255. if (check_ns && seen_ns && seen_other) {
  256. isc_throw(DataSourceError, "NS shares domain " << name <<
  257. " with something else");
  258. }
  259. // Add signatures to all found RRsets
  260. for (std::map<RRType, RRsetPtr>::iterator i(result.begin());
  261. i != result.end(); ++ i) {
  262. sig_store.appendSignatures(i->second);
  263. }
  264. return (FoundRRsets(records_found, result));
  265. }
  266. bool
  267. DatabaseClient::Finder::hasSubdomains(const std::string& name) {
  268. // Request the context
  269. DatabaseAccessor::IteratorContextPtr
  270. context(accessor_->getRecords(name, zone_id_, true));
  271. // It must not return NULL, that's a bug of the implementation
  272. if (!context) {
  273. isc_throw(isc::Unexpected, "Iterator context null at " + name);
  274. }
  275. std::string columns[DatabaseAccessor::COLUMN_COUNT];
  276. return (context->getNext(columns));
  277. }
  278. // Some manipulation with RRType sets
  279. namespace {
  280. // Bunch of functions to construct specific sets of RRTypes we will
  281. // ask from it.
  282. typedef std::set<RRType> WantedTypes;
  283. const WantedTypes&
  284. NSEC_TYPES() {
  285. static bool initialized(false);
  286. static WantedTypes result;
  287. if (!initialized) {
  288. result.insert(RRType::NSEC());
  289. initialized = true;
  290. }
  291. return (result);
  292. }
  293. const WantedTypes&
  294. DELEGATION_TYPES() {
  295. static bool initialized(false);
  296. static WantedTypes result;
  297. if (!initialized) {
  298. result.insert(RRType::DNAME());
  299. result.insert(RRType::NS());
  300. initialized = true;
  301. }
  302. return (result);
  303. }
  304. const WantedTypes&
  305. FINAL_TYPES() {
  306. static bool initialized(false);
  307. static WantedTypes result;
  308. if (!initialized) {
  309. result.insert(RRType::CNAME());
  310. result.insert(RRType::NS());
  311. result.insert(RRType::NSEC());
  312. initialized = true;
  313. }
  314. return (result);
  315. }
  316. }
  317. RRsetPtr
  318. DatabaseClient::Finder::findNSECCover(const Name& name) {
  319. try {
  320. // Which one should contain the NSEC record?
  321. const Name coverName(findPreviousName(name));
  322. // Get the record and copy it out
  323. const FoundRRsets found = getRRsets(coverName.toText(), NSEC_TYPES(),
  324. coverName != getOrigin());
  325. const FoundIterator
  326. nci(found.second.find(RRType::NSEC()));
  327. if (nci != found.second.end()) {
  328. return (nci->second);
  329. } else {
  330. // The previous doesn't contain NSEC.
  331. // Badly signed zone or a bug?
  332. // FIXME: Currently, if the zone is not signed, we could get
  333. // here. In that case we can't really throw, but for now, we can't
  334. // recognize it. So we don't throw at all, enable it once
  335. // we have a is_signed flag or something.
  336. #if 0
  337. isc_throw(DataSourceError, "No NSEC in " +
  338. coverName.toText() + ", but it was "
  339. "returned as previous - "
  340. "accessor error? Badly signed zone?");
  341. #endif
  342. }
  343. }
  344. catch (const isc::NotImplemented&) {
  345. // Well, they want DNSSEC, but there is no available.
  346. // So we don't provide anything.
  347. LOG_INFO(logger, DATASRC_DATABASE_COVER_NSEC_UNSUPPORTED).
  348. arg(accessor_->getDBName()).arg(name);
  349. }
  350. // We didn't find it, return nothing
  351. return (RRsetPtr());
  352. }
  353. ZoneFinder::FindResult
  354. DatabaseClient::Finder::find(const isc::dns::Name& name,
  355. const isc::dns::RRType& type,
  356. isc::dns::RRsetList*,
  357. const FindOptions options)
  358. {
  359. // This variable is used to determine the difference between
  360. // NXDOMAIN and NXRRSET
  361. bool records_found = false;
  362. bool glue_ok((options & FIND_GLUE_OK) != 0);
  363. const bool dnssec_data((options & FIND_DNSSEC) != 0);
  364. bool get_cover(false);
  365. isc::dns::RRsetPtr result_rrset;
  366. ZoneFinder::Result result_status = SUCCESS;
  367. FoundRRsets found;
  368. logger.debug(DBG_TRACE_DETAILED, DATASRC_DATABASE_FIND_RECORDS)
  369. .arg(accessor_->getDBName()).arg(name).arg(type);
  370. // In case we are in GLUE_OK mode and start matching wildcards,
  371. // we can't do it under NS, so we store it here to check
  372. isc::dns::RRsetPtr first_ns;
  373. // First, do we have any kind of delegation (NS/DNAME) here?
  374. const Name origin(getOrigin());
  375. const size_t origin_label_count(origin.getLabelCount());
  376. // Number of labels in the last known non-empty domain
  377. size_t last_known(origin_label_count);
  378. const size_t current_label_count(name.getLabelCount());
  379. // This is how many labels we remove to get origin
  380. const size_t remove_labels(current_label_count - origin_label_count);
  381. // Now go trough all superdomains from origin down
  382. for (int i(remove_labels); i > 0; --i) {
  383. Name superdomain(name.split(i));
  384. // Look if there's NS or DNAME (but ignore the NS in origin)
  385. found = getRRsets(superdomain.toText(), DELEGATION_TYPES(),
  386. i != remove_labels);
  387. if (found.first) {
  388. // It contains some RRs, so it exists.
  389. last_known = superdomain.getLabelCount();
  390. const FoundIterator nsi(found.second.find(RRType::NS()));
  391. const FoundIterator dni(found.second.find(RRType::DNAME()));
  392. // In case we are in GLUE_OK mode, we want to store the
  393. // highest encountered NS (but not apex)
  394. if (glue_ok && !first_ns && i != remove_labels &&
  395. nsi != found.second.end()) {
  396. first_ns = nsi->second;
  397. } else if (!glue_ok && i != remove_labels &&
  398. nsi != found.second.end()) {
  399. // Do a NS delegation, but ignore NS in glue_ok mode. Ignore
  400. // delegation in apex
  401. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  402. DATASRC_DATABASE_FOUND_DELEGATION).
  403. arg(accessor_->getDBName()).arg(superdomain);
  404. result_rrset = nsi->second;
  405. result_status = DELEGATION;
  406. // No need to go lower, found
  407. break;
  408. } else if (dni != found.second.end()) {
  409. // Very similar with DNAME
  410. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  411. DATASRC_DATABASE_FOUND_DNAME).
  412. arg(accessor_->getDBName()).arg(superdomain);
  413. result_rrset = dni->second;
  414. result_status = DNAME;
  415. if (result_rrset->getRdataCount() != 1) {
  416. isc_throw(DataSourceError, "DNAME at " << superdomain <<
  417. " has " << result_rrset->getRdataCount() <<
  418. " rdata, 1 expected");
  419. }
  420. break;
  421. }
  422. }
  423. }
  424. if (!result_rrset) { // Only if we didn't find a redirect already
  425. // Try getting the final result and extract it
  426. // It is special if there's a CNAME or NS, DNAME is ignored here
  427. // And we don't consider the NS in origin
  428. WantedTypes final_types(FINAL_TYPES());
  429. final_types.insert(type);
  430. found = getRRsets(name.toText(), final_types, name != origin);
  431. records_found = found.first;
  432. // NS records, CNAME record and Wanted Type records
  433. const FoundIterator nsi(found.second.find(RRType::NS()));
  434. const FoundIterator cni(found.second.find(RRType::CNAME()));
  435. const FoundIterator wti(found.second.find(type));
  436. if (name != origin && !glue_ok && nsi != found.second.end()) {
  437. // There's a delegation at the exact node.
  438. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  439. DATASRC_DATABASE_FOUND_DELEGATION_EXACT).
  440. arg(accessor_->getDBName()).arg(name);
  441. result_status = DELEGATION;
  442. result_rrset = nsi->second;
  443. } else if (type != isc::dns::RRType::CNAME() &&
  444. cni != found.second.end()) {
  445. // A CNAME here
  446. result_status = CNAME;
  447. result_rrset = cni->second;
  448. if (result_rrset->getRdataCount() != 1) {
  449. isc_throw(DataSourceError, "CNAME with " <<
  450. result_rrset->getRdataCount() <<
  451. " rdata at " << name << ", expected 1");
  452. }
  453. } else if (wti != found.second.end()) {
  454. // Just get the answer
  455. result_rrset = wti->second;
  456. } else if (!records_found) {
  457. // Nothing lives here.
  458. // But check if something lives below this
  459. // domain and if so, pretend something is here as well.
  460. if (hasSubdomains(name.toText())) {
  461. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  462. DATASRC_DATABASE_FOUND_EMPTY_NONTERMINAL).
  463. arg(accessor_->getDBName()).arg(name);
  464. records_found = true;
  465. get_cover = dnssec_data;
  466. } else if ((options & NO_WILDCARD) != 0) {
  467. // If wildcard check is disabled, the search will ultimately
  468. // terminate with NXDOMAIN. If DNSSEC is enabled, flag that
  469. // we need to get the NSEC records to prove this.
  470. if (dnssec_data) {
  471. get_cover = true;
  472. }
  473. } else {
  474. // It's not empty non-terminal. So check for wildcards.
  475. // We remove labels one by one and look for the wildcard there.
  476. // Go up to first non-empty domain.
  477. for (size_t i(1); i <= current_label_count - last_known; ++i) {
  478. // Construct the name with *
  479. const Name superdomain(name.split(i));
  480. const string wildcard("*." + superdomain.toText());
  481. const string construct_name(name.toText());
  482. // TODO What do we do about DNAME here?
  483. // The types are the same as with original query
  484. found = getRRsets(wildcard, final_types, true,
  485. &construct_name);
  486. if (found.first) {
  487. if (first_ns) {
  488. // In case we are under NS, we don't
  489. // wildcard-match, but return delegation
  490. result_rrset = first_ns;
  491. result_status = DELEGATION;
  492. records_found = true;
  493. // We pretend to switch to non-glue_ok mode
  494. glue_ok = false;
  495. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  496. DATASRC_DATABASE_WILDCARD_CANCEL_NS).
  497. arg(accessor_->getDBName()).arg(wildcard).
  498. arg(first_ns->getName());
  499. } else if (!hasSubdomains(name.split(i - 1).toText()))
  500. {
  501. // Nothing we added as part of the * can exist
  502. // directly, as we go up only to first existing
  503. // domain, but it could be empty non-terminal. In
  504. // that case, we need to cancel the match.
  505. records_found = true;
  506. const FoundIterator
  507. cni(found.second.find(RRType::CNAME()));
  508. const FoundIterator
  509. nsi(found.second.find(RRType::NS()));
  510. const FoundIterator
  511. nci(found.second.find(RRType::NSEC()));
  512. const FoundIterator wti(found.second.find(type));
  513. if (cni != found.second.end() &&
  514. type != RRType::CNAME()) {
  515. result_rrset = cni->second;
  516. result_status = WILDCARD_CNAME;
  517. } else if (nsi != found.second.end()) {
  518. result_rrset = nsi->second;
  519. result_status = DELEGATION;
  520. } else if (wti != found.second.end()) {
  521. result_rrset = wti->second;
  522. result_status = WILDCARD;
  523. } else {
  524. // NXRRSET case in the wildcard
  525. result_status = WILDCARD_NXRRSET;
  526. if (dnssec_data &&
  527. nci != found.second.end()) {
  528. // User wants a proof the wildcard doesn't
  529. // contain it
  530. //
  531. // However, we need to get the RRset in the
  532. // name of the wildcard, not the constructed
  533. // one, so we walk it again
  534. found = getRRsets(wildcard, NSEC_TYPES(),
  535. true);
  536. result_rrset =
  537. found.second.find(RRType::NSEC())->
  538. second;
  539. }
  540. }
  541. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  542. DATASRC_DATABASE_WILDCARD).
  543. arg(accessor_->getDBName()).arg(wildcard).
  544. arg(name);
  545. } else {
  546. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  547. DATASRC_DATABASE_WILDCARD_CANCEL_SUB).
  548. arg(accessor_->getDBName()).arg(wildcard).
  549. arg(name).arg(superdomain);
  550. }
  551. break;
  552. } else if (hasSubdomains(wildcard)) {
  553. // Empty non-terminal asterisk
  554. records_found = true;
  555. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  556. DATASRC_DATABASE_WILDCARD_EMPTY).
  557. arg(accessor_->getDBName()).arg(wildcard).
  558. arg(name);
  559. if (dnssec_data) {
  560. result_rrset = findNSECCover(Name(wildcard));
  561. if (result_rrset) {
  562. result_status = WILDCARD_NXRRSET;
  563. }
  564. }
  565. break;
  566. }
  567. }
  568. // This is the NXDOMAIN case (nothing found anywhere). If
  569. // they want DNSSEC data, try getting the NSEC record
  570. if (dnssec_data && !records_found) {
  571. get_cover = true;
  572. }
  573. }
  574. } else if (dnssec_data) {
  575. // This is the "usual" NXRRSET case
  576. // So in case they want DNSSEC, provide the NSEC
  577. // (which should be available already here)
  578. result_status = NXRRSET;
  579. const FoundIterator nci(found.second.find(RRType::NSEC()));
  580. if (nci != found.second.end()) {
  581. result_rrset = nci->second;
  582. }
  583. }
  584. }
  585. if (!result_rrset) {
  586. if (result_status == SUCCESS) {
  587. // Should we look for NSEC covering the name?
  588. if (get_cover) {
  589. result_rrset = findNSECCover(name);
  590. if (result_rrset) {
  591. result_status = NXDOMAIN;
  592. }
  593. }
  594. // Something is not here and we didn't decide yet what
  595. if (records_found) {
  596. logger.debug(DBG_TRACE_DETAILED,
  597. DATASRC_DATABASE_FOUND_NXRRSET)
  598. .arg(accessor_->getDBName()).arg(name)
  599. .arg(getClass()).arg(type);
  600. result_status = NXRRSET;
  601. } else {
  602. logger.debug(DBG_TRACE_DETAILED,
  603. DATASRC_DATABASE_FOUND_NXDOMAIN)
  604. .arg(accessor_->getDBName()).arg(name)
  605. .arg(getClass()).arg(type);
  606. result_status = NXDOMAIN;
  607. }
  608. }
  609. } else {
  610. logger.debug(DBG_TRACE_DETAILED,
  611. DATASRC_DATABASE_FOUND_RRSET)
  612. .arg(accessor_->getDBName()).arg(*result_rrset);
  613. }
  614. return (FindResult(result_status, result_rrset));
  615. }
  616. Name
  617. DatabaseClient::Finder::findPreviousName(const Name& name) const {
  618. const string str(accessor_->findPreviousName(zone_id_,
  619. name.reverse().toText()));
  620. try {
  621. return (Name(str));
  622. }
  623. /*
  624. * To avoid having the same code many times, we just catch all the
  625. * exceptions and handle them in a common code below
  626. */
  627. catch (const isc::dns::EmptyLabel&) {}
  628. catch (const isc::dns::TooLongLabel&) {}
  629. catch (const isc::dns::BadLabelType&) {}
  630. catch (const isc::dns::BadEscape&) {}
  631. catch (const isc::dns::TooLongName&) {}
  632. catch (const isc::dns::IncompleteName&) {}
  633. isc_throw(DataSourceError, "Bad name " + str + " from findPreviousName");
  634. }
  635. Name
  636. DatabaseClient::Finder::getOrigin() const {
  637. return (origin_);
  638. }
  639. isc::dns::RRClass
  640. DatabaseClient::Finder::getClass() const {
  641. // TODO Implement
  642. return isc::dns::RRClass::IN();
  643. }
  644. namespace {
  645. /*
  646. * This needs, beside of converting all data from textual representation, group
  647. * together rdata of the same RRsets. To do this, we hold one row of data ahead
  648. * of iteration. When we get a request to provide data, we create it from this
  649. * data and load a new one. If it is to be put to the same rrset, we add it.
  650. * Otherwise we just return what we have and keep the row as the one ahead
  651. * for next time.
  652. */
  653. class DatabaseIterator : public ZoneIterator {
  654. public:
  655. DatabaseIterator(const DatabaseAccessor::IteratorContextPtr& context,
  656. const RRClass& rrclass, bool adjust_ttl) :
  657. context_(context),
  658. class_(rrclass),
  659. ready_(true),
  660. adjust_ttl_(adjust_ttl)
  661. {
  662. // Prepare data for the next time
  663. getData();
  664. }
  665. virtual isc::dns::ConstRRsetPtr getNextRRset() {
  666. if (!ready_) {
  667. isc_throw(isc::Unexpected, "Iterating past the zone end");
  668. }
  669. if (!data_ready_) {
  670. // At the end of zone
  671. ready_ = false;
  672. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  673. DATASRC_DATABASE_ITERATE_END);
  674. return (ConstRRsetPtr());
  675. }
  676. string name_str(name_), rtype_str(rtype_), ttl(ttl_);
  677. Name name(name_str);
  678. RRType rtype(rtype_str);
  679. RRsetPtr rrset(new RRset(name, class_, rtype, RRTTL(ttl)));
  680. while (data_ready_ && name_ == name_str && rtype_str == rtype_) {
  681. if (adjust_ttl_) {
  682. if (ttl_ != ttl) {
  683. if (ttl < ttl_) {
  684. ttl_ = ttl;
  685. rrset->setTTL(RRTTL(ttl));
  686. }
  687. LOG_WARN(logger, DATASRC_DATABASE_ITERATE_TTL_MISMATCH).
  688. arg(name_).arg(class_).arg(rtype_).arg(rrset->getTTL());
  689. }
  690. } else if (ttl_ != ttl) {
  691. break;
  692. }
  693. rrset->addRdata(rdata::createRdata(rtype, class_, rdata_));
  694. getData();
  695. }
  696. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE_NEXT).
  697. arg(rrset->getName()).arg(rrset->getType());
  698. return (rrset);
  699. }
  700. private:
  701. // Load next row of data
  702. void getData() {
  703. string data[DatabaseAccessor::COLUMN_COUNT];
  704. data_ready_ = context_->getNext(data);
  705. name_ = data[DatabaseAccessor::NAME_COLUMN];
  706. rtype_ = data[DatabaseAccessor::TYPE_COLUMN];
  707. ttl_ = data[DatabaseAccessor::TTL_COLUMN];
  708. rdata_ = data[DatabaseAccessor::RDATA_COLUMN];
  709. }
  710. // The context
  711. const DatabaseAccessor::IteratorContextPtr context_;
  712. // Class of the zone
  713. RRClass class_;
  714. // Status
  715. bool ready_, data_ready_;
  716. // Data of the next row
  717. string name_, rtype_, rdata_, ttl_;
  718. // Whether to modify differing TTL values, or treat a different TTL as
  719. // a different RRset
  720. bool adjust_ttl_;
  721. };
  722. }
  723. ZoneIteratorPtr
  724. DatabaseClient::getIterator(const isc::dns::Name& name,
  725. bool adjust_ttl) const
  726. {
  727. // Get the zone
  728. std::pair<bool, int> zone(accessor_->getZone(name.toText()));
  729. if (!zone.first) {
  730. // No such zone, can't continue
  731. isc_throw(DataSourceError, "Zone " + name.toText() +
  732. " can not be iterated, because it doesn't exist "
  733. "in this data source");
  734. }
  735. // Request the context
  736. DatabaseAccessor::IteratorContextPtr
  737. context(accessor_->getAllRecords(zone.second));
  738. // It must not return NULL, that's a bug of the implementation
  739. if (context == DatabaseAccessor::IteratorContextPtr()) {
  740. isc_throw(isc::Unexpected, "Iterator context null at " +
  741. name.toText());
  742. }
  743. // Create the iterator and return it
  744. // TODO: Once #1062 is merged with this, we need to get the
  745. // actual zone class from the connection, as the DatabaseClient
  746. // doesn't know it and the iterator needs it (so it wouldn't query
  747. // it each time)
  748. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE).
  749. arg(name);
  750. return (ZoneIteratorPtr(new DatabaseIterator(context, RRClass::IN(),
  751. adjust_ttl)));
  752. }
  753. //
  754. // Zone updater using some database system as the underlying data source.
  755. //
  756. class DatabaseUpdater : public ZoneUpdater {
  757. public:
  758. DatabaseUpdater(shared_ptr<DatabaseAccessor> accessor, int zone_id,
  759. const Name& zone_name, const RRClass& zone_class) :
  760. committed_(false), accessor_(accessor), zone_id_(zone_id),
  761. db_name_(accessor->getDBName()), zone_name_(zone_name.toText()),
  762. zone_class_(zone_class),
  763. finder_(new DatabaseClient::Finder(accessor_, zone_id_, zone_name))
  764. {
  765. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_CREATED)
  766. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  767. }
  768. virtual ~DatabaseUpdater() {
  769. if (!committed_) {
  770. try {
  771. accessor_->rollbackUpdateZone();
  772. logger.info(DATASRC_DATABASE_UPDATER_ROLLBACK)
  773. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  774. } catch (const DataSourceError& e) {
  775. // We generally expect that rollback always succeeds, and
  776. // it should in fact succeed in a way we execute it. But
  777. // as the public API allows rollbackUpdateZone() to fail and
  778. // throw, we should expect it. Obviously we cannot re-throw
  779. // it. The best we can do is to log it as a critical error.
  780. logger.error(DATASRC_DATABASE_UPDATER_ROLLBACKFAIL)
  781. .arg(zone_name_).arg(zone_class_).arg(db_name_)
  782. .arg(e.what());
  783. }
  784. }
  785. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_DESTROYED)
  786. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  787. }
  788. virtual ZoneFinder& getFinder() { return (*finder_); }
  789. virtual void addRRset(const RRset& rrset);
  790. virtual void deleteRRset(const RRset& rrset);
  791. virtual void commit();
  792. private:
  793. bool committed_;
  794. shared_ptr<DatabaseAccessor> accessor_;
  795. const int zone_id_;
  796. const string db_name_;
  797. const string zone_name_;
  798. const RRClass zone_class_;
  799. boost::scoped_ptr<DatabaseClient::Finder> finder_;
  800. };
  801. void
  802. DatabaseUpdater::addRRset(const RRset& rrset) {
  803. if (committed_) {
  804. isc_throw(DataSourceError, "Add attempt after commit to zone: "
  805. << zone_name_ << "/" << zone_class_);
  806. }
  807. if (rrset.getClass() != zone_class_) {
  808. isc_throw(DataSourceError, "An RRset of a different class is being "
  809. << "added to " << zone_name_ << "/" << zone_class_ << ": "
  810. << rrset.toText());
  811. }
  812. if (rrset.getRRsig()) {
  813. isc_throw(DataSourceError, "An RRset with RRSIG is being added to "
  814. << zone_name_ << "/" << zone_class_ << ": "
  815. << rrset.toText());
  816. }
  817. RdataIteratorPtr it = rrset.getRdataIterator();
  818. if (it->isLast()) {
  819. isc_throw(DataSourceError, "An empty RRset is being added for "
  820. << rrset.getName() << "/" << zone_class_ << "/"
  821. << rrset.getType());
  822. }
  823. string columns[DatabaseAccessor::ADD_COLUMN_COUNT]; // initialized with ""
  824. columns[DatabaseAccessor::ADD_NAME] = rrset.getName().toText();
  825. columns[DatabaseAccessor::ADD_REV_NAME] =
  826. rrset.getName().reverse().toText();
  827. columns[DatabaseAccessor::ADD_TTL] = rrset.getTTL().toText();
  828. columns[DatabaseAccessor::ADD_TYPE] = rrset.getType().toText();
  829. for (; !it->isLast(); it->next()) {
  830. if (rrset.getType() == RRType::RRSIG()) {
  831. // XXX: the current interface (based on the current sqlite3
  832. // data source schema) requires a separate "sigtype" column,
  833. // even though it won't be used in a newer implementation.
  834. // We should eventually clean up the schema design and simplify
  835. // the interface, but until then we have to conform to the schema.
  836. const generic::RRSIG& rrsig_rdata =
  837. dynamic_cast<const generic::RRSIG&>(it->getCurrent());
  838. columns[DatabaseAccessor::ADD_SIGTYPE] =
  839. rrsig_rdata.typeCovered().toText();
  840. }
  841. columns[DatabaseAccessor::ADD_RDATA] = it->getCurrent().toText();
  842. accessor_->addRecordToZone(columns);
  843. }
  844. }
  845. void
  846. DatabaseUpdater::deleteRRset(const RRset& rrset) {
  847. if (committed_) {
  848. isc_throw(DataSourceError, "Delete attempt after commit on zone: "
  849. << zone_name_ << "/" << zone_class_);
  850. }
  851. if (rrset.getClass() != zone_class_) {
  852. isc_throw(DataSourceError, "An RRset of a different class is being "
  853. << "deleted from " << zone_name_ << "/" << zone_class_
  854. << ": " << rrset.toText());
  855. }
  856. if (rrset.getRRsig()) {
  857. isc_throw(DataSourceError, "An RRset with RRSIG is being deleted from "
  858. << zone_name_ << "/" << zone_class_ << ": "
  859. << rrset.toText());
  860. }
  861. RdataIteratorPtr it = rrset.getRdataIterator();
  862. if (it->isLast()) {
  863. isc_throw(DataSourceError, "An empty RRset is being deleted for "
  864. << rrset.getName() << "/" << zone_class_ << "/"
  865. << rrset.getType());
  866. }
  867. string params[DatabaseAccessor::DEL_PARAM_COUNT]; // initialized with ""
  868. params[DatabaseAccessor::DEL_NAME] = rrset.getName().toText();
  869. params[DatabaseAccessor::DEL_TYPE] = rrset.getType().toText();
  870. for (; !it->isLast(); it->next()) {
  871. params[DatabaseAccessor::DEL_RDATA] = it->getCurrent().toText();
  872. accessor_->deleteRecordInZone(params);
  873. }
  874. }
  875. void
  876. DatabaseUpdater::commit() {
  877. if (committed_) {
  878. isc_throw(DataSourceError, "Duplicate commit attempt for "
  879. << zone_name_ << "/" << zone_class_ << " on "
  880. << db_name_);
  881. }
  882. accessor_->commitUpdateZone();
  883. committed_ = true; // make sure the destructor won't trigger rollback
  884. // We release the accessor immediately after commit is completed so that
  885. // we don't hold the possible internal resource any longer.
  886. accessor_.reset();
  887. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_COMMIT)
  888. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  889. }
  890. // The updater factory
  891. ZoneUpdaterPtr
  892. DatabaseClient::getUpdater(const isc::dns::Name& name, bool replace) const {
  893. shared_ptr<DatabaseAccessor> update_accessor(accessor_->clone());
  894. const std::pair<bool, int> zone(update_accessor->startUpdateZone(
  895. name.toText(), replace));
  896. if (!zone.first) {
  897. return (ZoneUpdaterPtr());
  898. }
  899. return (ZoneUpdaterPtr(new DatabaseUpdater(update_accessor, zone.second,
  900. name, rrclass_)));
  901. }
  902. }
  903. }