database.cc 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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 Name& name, const WantedTypes& types,
  164. bool check_ns, const Name* 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.toText(), 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 " +
  175. name.toText());
  176. }
  177. std::string columns[DatabaseAccessor::COLUMN_COUNT];
  178. if (construct_name == NULL) {
  179. construct_name = &name;
  180. }
  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, getClass(),
  216. 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. seen_other = true;
  233. }
  234. } catch (const InvalidRRType&) {
  235. isc_throw(DataSourceError, "Invalid RRType in database for " <<
  236. name << ": " << columns[DatabaseAccessor::
  237. TYPE_COLUMN]);
  238. } catch (const InvalidRRTTL&) {
  239. isc_throw(DataSourceError, "Invalid TTL in database for " <<
  240. name << ": " << columns[DatabaseAccessor::
  241. TTL_COLUMN]);
  242. } catch (const rdata::InvalidRdataText&) {
  243. isc_throw(DataSourceError, "Invalid rdata in database for " <<
  244. name << ": " << columns[DatabaseAccessor::
  245. RDATA_COLUMN]);
  246. }
  247. }
  248. if (seen_cname && (seen_other || seen_ns || seen_ds)) {
  249. isc_throw(DataSourceError, "CNAME shares domain " << name <<
  250. " with something else");
  251. }
  252. if (check_ns && seen_ns && seen_other) {
  253. isc_throw(DataSourceError, "NS shares domain " << name <<
  254. " with something else");
  255. }
  256. // Add signatures to all found RRsets
  257. for (std::map<RRType, RRsetPtr>::iterator i(result.begin());
  258. i != result.end(); ++ i) {
  259. sig_store.appendSignatures(i->second);
  260. }
  261. return (FoundRRsets(records_found, result));
  262. }
  263. bool
  264. DatabaseClient::Finder::hasSubdomains(const std::string& name) {
  265. // Request the context
  266. DatabaseAccessor::IteratorContextPtr
  267. context(accessor_->getRecords(name, zone_id_, true));
  268. // It must not return NULL, that's a bug of the implementation
  269. if (!context) {
  270. isc_throw(isc::Unexpected, "Iterator context null at " + name);
  271. }
  272. std::string columns[DatabaseAccessor::COLUMN_COUNT];
  273. return (context->getNext(columns));
  274. }
  275. // Some manipulation with RRType sets
  276. namespace {
  277. // To conveniently put the RRTypes into the sets. This is not really clean
  278. // design, but it is hidden inside this file and makes the calls much more
  279. // convenient.
  280. std::set<RRType> operator +(std::set<RRType> set, const RRType& type) {
  281. set.insert(type);
  282. return (set);
  283. }
  284. }
  285. ZoneFinder::FindResult
  286. DatabaseClient::Finder::find(const isc::dns::Name& name,
  287. const isc::dns::RRType& type,
  288. isc::dns::RRsetList*,
  289. const FindOptions options)
  290. {
  291. // This variable is used to determine the difference between
  292. // NXDOMAIN and NXRRSET
  293. bool records_found = false;
  294. bool glue_ok((options & FIND_GLUE_OK) != 0);
  295. const bool dnssec_data((options & FIND_DNSSEC) != 0);
  296. bool get_cover(false);
  297. isc::dns::RRsetPtr result_rrset;
  298. ZoneFinder::Result result_status = SUCCESS;
  299. FoundRRsets found;
  300. logger.debug(DBG_TRACE_DETAILED, DATASRC_DATABASE_FIND_RECORDS)
  301. .arg(accessor_->getDBName()).arg(name).arg(type);
  302. // In case we are in GLUE_OK mode and start matching wildcards,
  303. // we can't do it under NS, so we store it here to check
  304. isc::dns::RRsetPtr first_ns;
  305. // This is used at multiple places
  306. static const WantedTypes nsec_types(WantedTypes() + RRType::NSEC());
  307. // First, do we have any kind of delegation (NS/DNAME) here?
  308. const Name origin(getOrigin());
  309. const size_t origin_label_count(origin.getLabelCount());
  310. // Number of labels in the last known non-empty domain
  311. size_t last_known(origin_label_count);
  312. const size_t current_label_count(name.getLabelCount());
  313. // This is how many labels we remove to get origin
  314. size_t remove_labels(current_label_count - origin_label_count);
  315. // Type shortcut, used a lot here
  316. typedef std::map<RRType, RRsetPtr>::const_iterator FoundIterator;
  317. // Now go trough all superdomains from origin down
  318. for (int i(remove_labels); i > 0; --i) {
  319. Name superdomain(name.split(i));
  320. // Look if there's NS or DNAME (but ignore the NS in origin)
  321. static const WantedTypes delegation_types(WantedTypes() +
  322. RRType::DNAME() +
  323. RRType::NS());
  324. found = getRRsets(superdomain, delegation_types, i != remove_labels);
  325. if (found.first) {
  326. // It contains some RRs, so it exists.
  327. last_known = superdomain.getLabelCount();
  328. const FoundIterator nsi(found.second.find(RRType::NS()));
  329. const FoundIterator dni(found.second.find(RRType::DNAME()));
  330. // In case we are in GLUE_OK mode, we want to store the
  331. // highest encountered NS (but not apex)
  332. if (glue_ok && !first_ns && i != remove_labels &&
  333. nsi != found.second.end()) {
  334. first_ns = nsi->second;
  335. } else if (!glue_ok && i != remove_labels &&
  336. nsi != found.second.end()) {
  337. // Do a NS delegation, but ignore NS in glue_ok mode. Ignore
  338. // delegation in apex
  339. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  340. DATASRC_DATABASE_FOUND_DELEGATION).
  341. arg(accessor_->getDBName()).arg(superdomain);
  342. result_rrset = nsi->second;
  343. result_status = DELEGATION;
  344. // No need to go lower, found
  345. break;
  346. } else if (dni != found.second.end()) {
  347. // Very similar with DNAME
  348. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  349. DATASRC_DATABASE_FOUND_DNAME).
  350. arg(accessor_->getDBName()).arg(superdomain);
  351. result_rrset = dni->second;
  352. result_status = DNAME;
  353. if (result_rrset->getRdataCount() != 1) {
  354. isc_throw(DataSourceError, "DNAME at " << superdomain <<
  355. " has " << result_rrset->getRdataCount() <<
  356. " rdata, 1 expected");
  357. }
  358. break;
  359. }
  360. }
  361. }
  362. if (!result_rrset) { // Only if we didn't find a redirect already
  363. // Try getting the final result and extract it
  364. // It is special if there's a CNAME or NS, DNAME is ignored here
  365. // And we don't consider the NS in origin
  366. static const WantedTypes final_types(WantedTypes() + RRType::CNAME() +
  367. RRType::NS() + RRType::NSEC());
  368. found = getRRsets(name, final_types + type, name != origin);
  369. records_found = found.first;
  370. // NS records, CNAME record and Wanted Type records
  371. const FoundIterator nsi(found.second.find(RRType::NS()));
  372. const FoundIterator cni(found.second.find(RRType::CNAME()));
  373. const FoundIterator wti(found.second.find(type));
  374. if (name != origin && !glue_ok && nsi != found.second.end()) {
  375. // There's a delegation at the exact node.
  376. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  377. DATASRC_DATABASE_FOUND_DELEGATION_EXACT).
  378. arg(accessor_->getDBName()).arg(name);
  379. result_status = DELEGATION;
  380. result_rrset = nsi->second;
  381. } else if (type != isc::dns::RRType::CNAME() &&
  382. cni != found.second.end()) {
  383. // A CNAME here
  384. result_status = CNAME;
  385. result_rrset = cni->second;
  386. if (result_rrset->getRdataCount() != 1) {
  387. isc_throw(DataSourceError, "CNAME with " <<
  388. result_rrset->getRdataCount() <<
  389. " rdata at " << name << ", expected 1");
  390. }
  391. } else if (wti != found.second.end()) {
  392. // Just get the answer
  393. result_rrset = wti->second;
  394. } else if (!records_found) {
  395. // Nothing lives here.
  396. // But check if something lives below this
  397. // domain and if so, pretend something is here as well.
  398. if (hasSubdomains(name.toText())) {
  399. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  400. DATASRC_DATABASE_FOUND_EMPTY_NONTERMINAL).
  401. arg(accessor_->getDBName()).arg(name);
  402. records_found = true;
  403. get_cover = dnssec_data;
  404. } else {
  405. // It's not empty non-terminal. So check for wildcards.
  406. // We remove labels one by one and look for the wildcard there.
  407. // Go up to first non-empty domain.
  408. remove_labels = current_label_count - last_known;
  409. const Name star("*");
  410. for (size_t i(1); i <= remove_labels; ++ i) {
  411. // Construct the name with *
  412. // TODO: Once the underlying DatabaseAccessor takes
  413. // string, do the concatenation on strings, not
  414. // Names
  415. const Name superdomain(name.split(i));
  416. const Name wildcard(star.concatenate(superdomain));
  417. // TODO What do we do about DNAME here?
  418. static const WantedTypes wildcard_types(WantedTypes() +
  419. RRType::CNAME() +
  420. RRType::NS() +
  421. RRType::NSEC());
  422. found = getRRsets(wildcard, wildcard_types + type, true,
  423. &name);
  424. if (found.first) {
  425. if (first_ns) {
  426. // In case we are under NS, we don't
  427. // wildcard-match, but return delegation
  428. result_rrset = first_ns;
  429. result_status = DELEGATION;
  430. records_found = true;
  431. // We pretend to switch to non-glue_ok mode
  432. glue_ok = false;
  433. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  434. DATASRC_DATABASE_WILDCARD_CANCEL_NS).
  435. arg(accessor_->getDBName()).arg(wildcard).
  436. arg(first_ns->getName());
  437. } else if (!hasSubdomains(name.split(i - 1).toText()))
  438. {
  439. // Nothing we added as part of the * can exist
  440. // directly, as we go up only to first existing
  441. // domain, but it could be empty non-terminal. In
  442. // that case, we need to cancel the match.
  443. records_found = true;
  444. const FoundIterator
  445. cni(found.second.find(RRType::CNAME()));
  446. const FoundIterator
  447. nsi(found.second.find(RRType::NS()));
  448. const FoundIterator
  449. nci(found.second.find(RRType::NSEC()));
  450. const FoundIterator wti(found.second.find(type));
  451. if (cni != found.second.end() &&
  452. type != RRType::CNAME()) {
  453. result_rrset = cni->second;
  454. result_status = CNAME;
  455. } else if (nsi != found.second.end()) {
  456. result_rrset = nsi->second;
  457. result_status = DELEGATION;
  458. } else if (wti != found.second.end()) {
  459. result_rrset = wti->second;
  460. result_status = WILDCARD;
  461. } else {
  462. // NXRRSET case in the wildcard
  463. result_status = WILDCARD_NXRRSET;
  464. if (dnssec_data &&
  465. nci != found.second.end()) {
  466. // User wants a proof the wildcard doesn't
  467. // contain it
  468. //
  469. // However, we need to get the RRset in the
  470. // name of the wildcard, not the constructed
  471. // one, so we walk it again
  472. found = getRRsets(wildcard, nsec_types,
  473. true);
  474. result_rrset =
  475. found.second.find(RRType::NSEC())->
  476. second;
  477. }
  478. }
  479. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  480. DATASRC_DATABASE_WILDCARD).
  481. arg(accessor_->getDBName()).arg(wildcard).
  482. arg(name);
  483. } else {
  484. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  485. DATASRC_DATABASE_WILDCARD_CANCEL_SUB).
  486. arg(accessor_->getDBName()).arg(wildcard).
  487. arg(name).arg(superdomain);
  488. }
  489. break;
  490. } else if (hasSubdomains(wildcard.toText())) {
  491. // Empty non-terminal asterisk
  492. records_found = true;
  493. get_cover = dnssec_data;
  494. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  495. DATASRC_DATABASE_WILDCARD_EMPTY).
  496. arg(accessor_->getDBName()).arg(wildcard).
  497. arg(name);
  498. break;
  499. }
  500. }
  501. // This is the NXDOMAIN case (nothing found anywhere). If
  502. // they want DNSSEC data, try getting the NSEC record
  503. if (dnssec_data && !records_found) {
  504. get_cover = true;
  505. }
  506. }
  507. } else if (dnssec_data) {
  508. // This is the "usual" NXRRSET case
  509. // So in case they want DNSSEC, provide the NSEC
  510. // (which should be available already here)
  511. result_status = NXRRSET;
  512. const FoundIterator nci(found.second.find(RRType::NSEC()));
  513. if (nci != found.second.end()) {
  514. result_rrset = nci->second;
  515. }
  516. }
  517. }
  518. if (!result_rrset) {
  519. if (result_status == SUCCESS) {
  520. // Should we look for NSEC covering the name?
  521. if (get_cover) {
  522. try {
  523. // Which one should contain the NSEC record?
  524. const Name coverName(findPreviousName(name));
  525. // Get the record and copy it out
  526. found = getRRsets(coverName, nsec_types, true);
  527. const FoundIterator
  528. nci(found.second.find(RRType::NSEC()));
  529. if (nci != found.second.end()) {
  530. result_status = NXDOMAIN;
  531. result_rrset = nci->second;
  532. } else {
  533. // The previous doesn't contain NSEC, bug?
  534. isc_throw(DataSourceError, "No NSEC in " +
  535. coverName.toText() + ", but it was "
  536. "returned as previous - "
  537. "accessor error?");
  538. }
  539. }
  540. catch (const isc::NotImplemented&) {
  541. // Well, they want DNSSEC, but there is no available.
  542. // So we don't provide anything.
  543. }
  544. }
  545. // Something is not here and we didn't decide yet what
  546. if (records_found) {
  547. logger.debug(DBG_TRACE_DETAILED,
  548. DATASRC_DATABASE_FOUND_NXRRSET)
  549. .arg(accessor_->getDBName()).arg(name)
  550. .arg(getClass()).arg(type);
  551. result_status = NXRRSET;
  552. } else {
  553. logger.debug(DBG_TRACE_DETAILED,
  554. DATASRC_DATABASE_FOUND_NXDOMAIN)
  555. .arg(accessor_->getDBName()).arg(name)
  556. .arg(getClass()).arg(type);
  557. result_status = NXDOMAIN;
  558. }
  559. }
  560. } else {
  561. logger.debug(DBG_TRACE_DETAILED,
  562. DATASRC_DATABASE_FOUND_RRSET)
  563. .arg(accessor_->getDBName()).arg(*result_rrset);
  564. }
  565. return (FindResult(result_status, result_rrset));
  566. }
  567. Name
  568. DatabaseClient::Finder::findPreviousName(const Name& name) const {
  569. return (Name(accessor_->findPreviousName(zone_id_,
  570. name.reverse().toText())));
  571. }
  572. Name
  573. DatabaseClient::Finder::getOrigin() const {
  574. return (origin_);
  575. }
  576. isc::dns::RRClass
  577. DatabaseClient::Finder::getClass() const {
  578. // TODO Implement
  579. return isc::dns::RRClass::IN();
  580. }
  581. namespace {
  582. /*
  583. * This needs, beside of converting all data from textual representation, group
  584. * together rdata of the same RRsets. To do this, we hold one row of data ahead
  585. * of iteration. When we get a request to provide data, we create it from this
  586. * data and load a new one. If it is to be put to the same rrset, we add it.
  587. * Otherwise we just return what we have and keep the row as the one ahead
  588. * for next time.
  589. */
  590. class DatabaseIterator : public ZoneIterator {
  591. public:
  592. DatabaseIterator(const DatabaseAccessor::IteratorContextPtr& context,
  593. const RRClass& rrclass) :
  594. context_(context),
  595. class_(rrclass),
  596. ready_(true)
  597. {
  598. // Prepare data for the next time
  599. getData();
  600. }
  601. virtual isc::dns::ConstRRsetPtr getNextRRset() {
  602. if (!ready_) {
  603. isc_throw(isc::Unexpected, "Iterating past the zone end");
  604. }
  605. if (!data_ready_) {
  606. // At the end of zone
  607. ready_ = false;
  608. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  609. DATASRC_DATABASE_ITERATE_END);
  610. return (ConstRRsetPtr());
  611. }
  612. string name_str(name_), rtype_str(rtype_), ttl(ttl_);
  613. Name name(name_str);
  614. RRType rtype(rtype_str);
  615. RRsetPtr rrset(new RRset(name, class_, rtype, RRTTL(ttl)));
  616. while (data_ready_ && name_ == name_str && rtype_str == rtype_) {
  617. if (ttl_ != ttl) {
  618. if (ttl < ttl_) {
  619. ttl_ = ttl;
  620. rrset->setTTL(RRTTL(ttl));
  621. }
  622. LOG_WARN(logger, DATASRC_DATABASE_ITERATE_TTL_MISMATCH).
  623. arg(name_).arg(class_).arg(rtype_).arg(rrset->getTTL());
  624. }
  625. rrset->addRdata(rdata::createRdata(rtype, class_, rdata_));
  626. getData();
  627. }
  628. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE_NEXT).
  629. arg(rrset->getName()).arg(rrset->getType());
  630. return (rrset);
  631. }
  632. private:
  633. // Load next row of data
  634. void getData() {
  635. string data[DatabaseAccessor::COLUMN_COUNT];
  636. data_ready_ = context_->getNext(data);
  637. name_ = data[DatabaseAccessor::NAME_COLUMN];
  638. rtype_ = data[DatabaseAccessor::TYPE_COLUMN];
  639. ttl_ = data[DatabaseAccessor::TTL_COLUMN];
  640. rdata_ = data[DatabaseAccessor::RDATA_COLUMN];
  641. }
  642. // The context
  643. const DatabaseAccessor::IteratorContextPtr context_;
  644. // Class of the zone
  645. RRClass class_;
  646. // Status
  647. bool ready_, data_ready_;
  648. // Data of the next row
  649. string name_, rtype_, rdata_, ttl_;
  650. };
  651. }
  652. ZoneIteratorPtr
  653. DatabaseClient::getIterator(const isc::dns::Name& name) const {
  654. // Get the zone
  655. std::pair<bool, int> zone(accessor_->getZone(name.toText()));
  656. if (!zone.first) {
  657. // No such zone, can't continue
  658. isc_throw(DataSourceError, "Zone " + name.toText() +
  659. " can not be iterated, because it doesn't exist "
  660. "in this data source");
  661. }
  662. // Request the context
  663. DatabaseAccessor::IteratorContextPtr
  664. context(accessor_->getAllRecords(zone.second));
  665. // It must not return NULL, that's a bug of the implementation
  666. if (context == DatabaseAccessor::IteratorContextPtr()) {
  667. isc_throw(isc::Unexpected, "Iterator context null at " +
  668. name.toText());
  669. }
  670. // Create the iterator and return it
  671. // TODO: Once #1062 is merged with this, we need to get the
  672. // actual zone class from the connection, as the DatabaseClient
  673. // doesn't know it and the iterator needs it (so it wouldn't query
  674. // it each time)
  675. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE).
  676. arg(name);
  677. return (ZoneIteratorPtr(new DatabaseIterator(context, RRClass::IN())));
  678. }
  679. //
  680. // Zone updater using some database system as the underlying data source.
  681. //
  682. class DatabaseUpdater : public ZoneUpdater {
  683. public:
  684. DatabaseUpdater(shared_ptr<DatabaseAccessor> accessor, int zone_id,
  685. const Name& zone_name, const RRClass& zone_class) :
  686. committed_(false), accessor_(accessor), zone_id_(zone_id),
  687. db_name_(accessor->getDBName()), zone_name_(zone_name.toText()),
  688. zone_class_(zone_class),
  689. finder_(new DatabaseClient::Finder(accessor_, zone_id_, zone_name))
  690. {
  691. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_CREATED)
  692. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  693. }
  694. virtual ~DatabaseUpdater() {
  695. if (!committed_) {
  696. try {
  697. accessor_->rollbackUpdateZone();
  698. logger.info(DATASRC_DATABASE_UPDATER_ROLLBACK)
  699. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  700. } catch (const DataSourceError& e) {
  701. // We generally expect that rollback always succeeds, and
  702. // it should in fact succeed in a way we execute it. But
  703. // as the public API allows rollbackUpdateZone() to fail and
  704. // throw, we should expect it. Obviously we cannot re-throw
  705. // it. The best we can do is to log it as a critical error.
  706. logger.error(DATASRC_DATABASE_UPDATER_ROLLBACKFAIL)
  707. .arg(zone_name_).arg(zone_class_).arg(db_name_)
  708. .arg(e.what());
  709. }
  710. }
  711. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_DESTROYED)
  712. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  713. }
  714. virtual ZoneFinder& getFinder() { return (*finder_); }
  715. virtual void addRRset(const RRset& rrset);
  716. virtual void deleteRRset(const RRset& rrset);
  717. virtual void commit();
  718. private:
  719. bool committed_;
  720. shared_ptr<DatabaseAccessor> accessor_;
  721. const int zone_id_;
  722. const string db_name_;
  723. const string zone_name_;
  724. const RRClass zone_class_;
  725. boost::scoped_ptr<DatabaseClient::Finder> finder_;
  726. };
  727. void
  728. DatabaseUpdater::addRRset(const RRset& rrset) {
  729. if (committed_) {
  730. isc_throw(DataSourceError, "Add attempt after commit to zone: "
  731. << zone_name_ << "/" << zone_class_);
  732. }
  733. if (rrset.getClass() != zone_class_) {
  734. isc_throw(DataSourceError, "An RRset of a different class is being "
  735. << "added to " << zone_name_ << "/" << zone_class_ << ": "
  736. << rrset.toText());
  737. }
  738. if (rrset.getRRsig()) {
  739. isc_throw(DataSourceError, "An RRset with RRSIG is being added to "
  740. << zone_name_ << "/" << zone_class_ << ": "
  741. << rrset.toText());
  742. }
  743. RdataIteratorPtr it = rrset.getRdataIterator();
  744. if (it->isLast()) {
  745. isc_throw(DataSourceError, "An empty RRset is being added for "
  746. << rrset.getName() << "/" << zone_class_ << "/"
  747. << rrset.getType());
  748. }
  749. string columns[DatabaseAccessor::ADD_COLUMN_COUNT]; // initialized with ""
  750. columns[DatabaseAccessor::ADD_NAME] = rrset.getName().toText();
  751. columns[DatabaseAccessor::ADD_REV_NAME] =
  752. rrset.getName().reverse().toText();
  753. columns[DatabaseAccessor::ADD_TTL] = rrset.getTTL().toText();
  754. columns[DatabaseAccessor::ADD_TYPE] = rrset.getType().toText();
  755. for (; !it->isLast(); it->next()) {
  756. if (rrset.getType() == RRType::RRSIG()) {
  757. // XXX: the current interface (based on the current sqlite3
  758. // data source schema) requires a separate "sigtype" column,
  759. // even though it won't be used in a newer implementation.
  760. // We should eventually clean up the schema design and simplify
  761. // the interface, but until then we have to conform to the schema.
  762. const generic::RRSIG& rrsig_rdata =
  763. dynamic_cast<const generic::RRSIG&>(it->getCurrent());
  764. columns[DatabaseAccessor::ADD_SIGTYPE] =
  765. rrsig_rdata.typeCovered().toText();
  766. }
  767. columns[DatabaseAccessor::ADD_RDATA] = it->getCurrent().toText();
  768. accessor_->addRecordToZone(columns);
  769. }
  770. }
  771. void
  772. DatabaseUpdater::deleteRRset(const RRset& rrset) {
  773. if (committed_) {
  774. isc_throw(DataSourceError, "Delete attempt after commit on zone: "
  775. << zone_name_ << "/" << zone_class_);
  776. }
  777. if (rrset.getClass() != zone_class_) {
  778. isc_throw(DataSourceError, "An RRset of a different class is being "
  779. << "deleted from " << zone_name_ << "/" << zone_class_
  780. << ": " << rrset.toText());
  781. }
  782. if (rrset.getRRsig()) {
  783. isc_throw(DataSourceError, "An RRset with RRSIG is being deleted from "
  784. << zone_name_ << "/" << zone_class_ << ": "
  785. << rrset.toText());
  786. }
  787. RdataIteratorPtr it = rrset.getRdataIterator();
  788. if (it->isLast()) {
  789. isc_throw(DataSourceError, "An empty RRset is being deleted for "
  790. << rrset.getName() << "/" << zone_class_ << "/"
  791. << rrset.getType());
  792. }
  793. string params[DatabaseAccessor::DEL_PARAM_COUNT]; // initialized with ""
  794. params[DatabaseAccessor::DEL_NAME] = rrset.getName().toText();
  795. params[DatabaseAccessor::DEL_TYPE] = rrset.getType().toText();
  796. for (; !it->isLast(); it->next()) {
  797. params[DatabaseAccessor::DEL_RDATA] = it->getCurrent().toText();
  798. accessor_->deleteRecordInZone(params);
  799. }
  800. }
  801. void
  802. DatabaseUpdater::commit() {
  803. if (committed_) {
  804. isc_throw(DataSourceError, "Duplicate commit attempt for "
  805. << zone_name_ << "/" << zone_class_ << " on "
  806. << db_name_);
  807. }
  808. accessor_->commitUpdateZone();
  809. committed_ = true; // make sure the destructor won't trigger rollback
  810. // We release the accessor immediately after commit is completed so that
  811. // we don't hold the possible internal resource any longer.
  812. accessor_.reset();
  813. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_COMMIT)
  814. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  815. }
  816. // The updater factory
  817. ZoneUpdaterPtr
  818. DatabaseClient::getUpdater(const isc::dns::Name& name, bool replace) const {
  819. shared_ptr<DatabaseAccessor> update_accessor(accessor_->clone());
  820. const std::pair<bool, int> zone(update_accessor->startUpdateZone(
  821. name.toText(), replace));
  822. if (!zone.first) {
  823. return (ZoneUpdaterPtr());
  824. }
  825. return (ZoneUpdaterPtr(new DatabaseUpdater(update_accessor, zone.second,
  826. name, rrclass_)));
  827. }
  828. }
  829. }