database.cc 36 KB

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