database.cc 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  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 <utility>
  16. #include <vector>
  17. #include <datasrc/database.h>
  18. #include <datasrc/data_source.h>
  19. #include <datasrc/iterator.h>
  20. #include <exceptions/exceptions.h>
  21. #include <dns/name.h>
  22. #include <dns/rrclass.h>
  23. #include <dns/rrttl.h>
  24. #include <dns/rrset.h>
  25. #include <dns/rdata.h>
  26. #include <dns/rdataclass.h>
  27. #include <datasrc/data_source.h>
  28. #include <datasrc/logger.h>
  29. #include <boost/foreach.hpp>
  30. using namespace isc::dns;
  31. using namespace std;
  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. bool any)
  166. {
  167. RRsigStore sig_store;
  168. bool records_found = false;
  169. std::map<RRType, RRsetPtr> result;
  170. // Request the context
  171. DatabaseAccessor::IteratorContextPtr
  172. context(accessor_->getRecords(name, zone_id_));
  173. // It must not return NULL, that's a bug of the implementation
  174. if (!context) {
  175. isc_throw(isc::Unexpected, "Iterator context null at " + name);
  176. }
  177. std::string columns[DatabaseAccessor::COLUMN_COUNT];
  178. if (construct_name == NULL) {
  179. construct_name = &name;
  180. }
  181. const Name construct_name_object(*construct_name);
  182. bool seen_cname(false);
  183. bool seen_ds(false);
  184. bool seen_other(false);
  185. bool seen_ns(false);
  186. while (context->getNext(columns)) {
  187. // The domain is not empty
  188. records_found = true;
  189. try {
  190. const RRType cur_type(columns[DatabaseAccessor::TYPE_COLUMN]);
  191. if (cur_type == RRType::RRSIG()) {
  192. // If we get signatures before we get the actual data, we
  193. // can't know which ones to keep and which to drop...
  194. // So we keep a separate store of any signature that may be
  195. // relevant and add them to the final RRset when we are
  196. // done.
  197. // A possible optimization here is to not store them for
  198. // types we are certain we don't need
  199. sig_store.addSig(rdata::createRdata(cur_type, getClass(),
  200. columns[DatabaseAccessor::RDATA_COLUMN]));
  201. }
  202. if (types.find(cur_type) != types.end() || any) {
  203. // This type is requested, so put it into result
  204. const RRTTL cur_ttl(columns[DatabaseAccessor::TTL_COLUMN]);
  205. // Ths sigtype column was an optimization for finding the
  206. // relevant RRSIG RRs for a lookup. Currently this column is
  207. // not used in this revised datasource implementation. We
  208. // should either start using it again, or remove it from use
  209. // completely (i.e. also remove it from the schema and the
  210. // backend implementation).
  211. // Note that because we don't use it now, we also won't notice
  212. // it if the value is wrong (i.e. if the sigtype column
  213. // contains an rrtype that is different from the actual value
  214. // of the 'type covered' field in the RRSIG Rdata).
  215. //cur_sigtype(columns[SIGTYPE_COLUMN]);
  216. addOrCreate(result[cur_type], construct_name_object,
  217. getClass(), cur_type, cur_ttl,
  218. columns[DatabaseAccessor::RDATA_COLUMN],
  219. *accessor_);
  220. }
  221. if (cur_type == RRType::CNAME()) {
  222. seen_cname = true;
  223. } else if (cur_type == RRType::NS()) {
  224. seen_ns = true;
  225. } else if (cur_type == RRType::DS()) {
  226. seen_ds = true;
  227. } else if (cur_type != RRType::RRSIG() &&
  228. cur_type != RRType::NSEC3() &&
  229. cur_type != RRType::NSEC()) {
  230. // NSEC and RRSIG can coexist with anything, otherwise
  231. // we've seen something that can't live together with potential
  232. // CNAME or NS
  233. //
  234. // NSEC3 lives in separate namespace from everything, therefore
  235. // we just ignore it here for these checks as well.
  236. seen_other = true;
  237. }
  238. } catch (const InvalidRRType&) {
  239. isc_throw(DataSourceError, "Invalid RRType in database for " <<
  240. name << ": " << columns[DatabaseAccessor::
  241. TYPE_COLUMN]);
  242. } catch (const InvalidRRTTL&) {
  243. isc_throw(DataSourceError, "Invalid TTL in database for " <<
  244. name << ": " << columns[DatabaseAccessor::
  245. TTL_COLUMN]);
  246. } catch (const rdata::InvalidRdataText&) {
  247. isc_throw(DataSourceError, "Invalid rdata in database for " <<
  248. name << ": " << columns[DatabaseAccessor::
  249. RDATA_COLUMN]);
  250. }
  251. }
  252. if (seen_cname && (seen_other || seen_ns || seen_ds)) {
  253. isc_throw(DataSourceError, "CNAME shares domain " << name <<
  254. " with something else");
  255. }
  256. if (check_ns && seen_ns && seen_other) {
  257. isc_throw(DataSourceError, "NS shares domain " << name <<
  258. " with something else");
  259. }
  260. // Add signatures to all found RRsets
  261. for (std::map<RRType, RRsetPtr>::iterator i(result.begin());
  262. i != result.end(); ++ i) {
  263. sig_store.appendSignatures(i->second);
  264. }
  265. if (records_found && any) {
  266. result[RRType::ANY()] = RRsetPtr();
  267. // These will be sitting on the other RRsets.
  268. result.erase(RRType::RRSIG());
  269. }
  270. return (FoundRRsets(records_found, result));
  271. }
  272. bool
  273. DatabaseClient::Finder::hasSubdomains(const std::string& name) {
  274. // Request the context
  275. DatabaseAccessor::IteratorContextPtr
  276. context(accessor_->getRecords(name, zone_id_, true));
  277. // It must not return NULL, that's a bug of the implementation
  278. if (!context) {
  279. isc_throw(isc::Unexpected, "Iterator context null at " + name);
  280. }
  281. std::string columns[DatabaseAccessor::COLUMN_COUNT];
  282. return (context->getNext(columns));
  283. }
  284. // Some manipulation with RRType sets
  285. namespace {
  286. // Bunch of functions to construct specific sets of RRTypes we will
  287. // ask from it.
  288. typedef std::set<RRType> WantedTypes;
  289. const WantedTypes&
  290. NSEC_TYPES() {
  291. static bool initialized(false);
  292. static WantedTypes result;
  293. if (!initialized) {
  294. result.insert(RRType::NSEC());
  295. initialized = true;
  296. }
  297. return (result);
  298. }
  299. const WantedTypes&
  300. DELEGATION_TYPES() {
  301. static bool initialized(false);
  302. static WantedTypes result;
  303. if (!initialized) {
  304. result.insert(RRType::DNAME());
  305. result.insert(RRType::NS());
  306. initialized = true;
  307. }
  308. return (result);
  309. }
  310. const WantedTypes&
  311. FINAL_TYPES() {
  312. static bool initialized(false);
  313. static WantedTypes result;
  314. if (!initialized) {
  315. result.insert(RRType::CNAME());
  316. result.insert(RRType::NS());
  317. result.insert(RRType::NSEC());
  318. initialized = true;
  319. }
  320. return (result);
  321. }
  322. }
  323. ConstRRsetPtr
  324. DatabaseClient::Finder::findNSECCover(const Name& name) {
  325. try {
  326. // Which one should contain the NSEC record?
  327. const Name coverName(findPreviousName(name));
  328. // Get the record and copy it out
  329. const FoundRRsets found = getRRsets(coverName.toText(), NSEC_TYPES(),
  330. coverName != getOrigin());
  331. const FoundIterator
  332. nci(found.second.find(RRType::NSEC()));
  333. if (nci != found.second.end()) {
  334. return (nci->second);
  335. } else {
  336. // The previous doesn't contain NSEC.
  337. // Badly signed zone or a bug?
  338. // FIXME: Currently, if the zone is not signed, we could get
  339. // here. In that case we can't really throw, but for now, we can't
  340. // recognize it. So we don't throw at all, enable it once
  341. // we have a is_signed flag or something.
  342. #if 0
  343. isc_throw(DataSourceError, "No NSEC in " +
  344. coverName.toText() + ", but it was "
  345. "returned as previous - "
  346. "accessor error? Badly signed zone?");
  347. #endif
  348. }
  349. }
  350. catch (const isc::NotImplemented&) {
  351. // Well, they want DNSSEC, but there is no available.
  352. // So we don't provide anything.
  353. LOG_INFO(logger, DATASRC_DATABASE_COVER_NSEC_UNSUPPORTED).
  354. arg(accessor_->getDBName()).arg(name);
  355. }
  356. // We didn't find it, return nothing
  357. return (ConstRRsetPtr());
  358. }
  359. ZoneFinder::FindResult
  360. DatabaseClient::Finder::findAll(const isc::dns::Name& name,
  361. std::vector<isc::dns::ConstRRsetPtr>& target,
  362. const FindOptions options)
  363. {
  364. return (findInternal(name, RRType::ANY(), &target, options));
  365. }
  366. ZoneFinder::FindResult
  367. DatabaseClient::Finder::find(const isc::dns::Name& name,
  368. const isc::dns::RRType& type,
  369. const FindOptions options)
  370. {
  371. if (type == RRType::ANY()) {
  372. isc_throw(isc::Unexpected, "Use findAll to answer ANY");
  373. }
  374. return (findInternal(name, type, NULL, options));
  375. }
  376. DatabaseClient::Finder::DelegationSearchResult
  377. DatabaseClient::Finder::findDelegationPoint(const isc::dns::Name& name,
  378. const FindOptions options)
  379. {
  380. // Result of search
  381. isc::dns::ConstRRsetPtr result_rrset;
  382. ZoneFinder::Result result_status = SUCCESS;
  383. // Are we searching for glue?
  384. const bool glue_ok = ((options & FIND_GLUE_OK) != 0);
  385. // This next declaration is an optimisation. When we search the database
  386. // for glue records, we generally ignore delegations. (This allows for
  387. // the case where e.g. the delegation to zone example.com refers to
  388. // nameservers within the zone, e.g. ns1.example.com. When conducting the
  389. // search for ns1.example.com, we have to search past the NS records at
  390. // example.com.)
  391. //
  392. // The one case where this is forbidden is when we search past the zone
  393. // cut but the match we find for the glue is a wildcard match. In that
  394. // case, we return the delegation instead (see RFC 1034, section 4.3.3).
  395. // To save a new search, we record the location of the delegation cut when
  396. // we encounter it here.
  397. isc::dns::ConstRRsetPtr first_ns;
  398. // We want to search from the apex down. We are given the full domain
  399. // name so we have to do some manipulation to ensure that when we start
  400. // checking superdomains, we start from the the domain name of the zone
  401. // (e.g. if the name is b.a.example.com. and we are in the example.com.
  402. // zone, we check example.com., a.example.com. and b.a.example.com. We
  403. // don't need to check com. or .).
  404. //
  405. // Set the number of labels in the origin (i.e. apex of the zone) and in
  406. // the last known non-empty domain (which, at this point, is the origin).
  407. const size_t origin_label_count = getOrigin().getLabelCount();
  408. size_t last_known = origin_label_count;
  409. // Set how many labels we remove to get origin: this is the number of
  410. // labels we have to process in our search.
  411. const size_t remove_labels = name.getLabelCount() - origin_label_count;
  412. // Go through all superdomains from the origin down searching for nodes
  413. // that indicate a delegation (.e. NS or DNAME).
  414. for (int i = remove_labels; i > 0; --i) {
  415. const Name superdomain(name.split(i));
  416. // Note if this is the origin. (We don't count NS records at the origin
  417. // as a delegation so this controls whether NS RRs are included in
  418. // the results of some searches.)
  419. const bool not_origin = (i != remove_labels);
  420. // Look if there's NS or DNAME at this point of the tree, but ignore
  421. // the NS RRs at the apex of the zone.
  422. const FoundRRsets found = getRRsets(superdomain.toText(),
  423. DELEGATION_TYPES(), not_origin);
  424. if (found.first) {
  425. // This node contains either NS or DNAME RRs so it does exist.
  426. const FoundIterator nsi(found.second.find(RRType::NS()));
  427. const FoundIterator dni(found.second.find(RRType::DNAME()));
  428. // An optimisation. We know that there is an exact match for
  429. // something at this point in the tree so remember it. If we have
  430. // to do a wildcard search, as we search upwards through the tree
  431. // we don't need to pass this point, which is an exact match for
  432. // the domain name.
  433. last_known = superdomain.getLabelCount();
  434. if (glue_ok && !first_ns && not_origin &&
  435. nsi != found.second.end()) {
  436. // If we are searching for glue ("glue OK" mode), store the
  437. // highest NS record that we find that is not the apex. This
  438. // is another optimisation for later, where we need the
  439. // information if the domain we are looking for matches through
  440. // a wildcard.
  441. first_ns = nsi->second;
  442. } else if (!glue_ok && not_origin && nsi != found.second.end()) {
  443. // Not searching for glue and we have found an NS RRset that is
  444. // not at the apex. We have found a delegation - return that
  445. // fact, there is no need to search further down the tree.
  446. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  447. DATASRC_DATABASE_FOUND_DELEGATION).
  448. arg(accessor_->getDBName()).arg(superdomain);
  449. result_rrset = nsi->second;
  450. result_status = DELEGATION;
  451. break;
  452. } else if (dni != found.second.end()) {
  453. // We have found a DNAME so again stop searching down the tree
  454. // and return the information.
  455. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  456. DATASRC_DATABASE_FOUND_DNAME).
  457. arg(accessor_->getDBName()).arg(superdomain);
  458. result_rrset = dni->second;
  459. result_status = DNAME;
  460. if (result_rrset->getRdataCount() != 1) {
  461. isc_throw(DataSourceError, "DNAME at " << superdomain <<
  462. " has " << result_rrset->getRdataCount() <<
  463. " rdata, 1 expected");
  464. }
  465. break;
  466. }
  467. }
  468. }
  469. return (DelegationSearchResult(result_status, result_rrset, first_ns,
  470. last_known));
  471. }
  472. // This method is called when we have not found an exact match and when we
  473. // know that the name is not an empty non-terminal. So the only way that
  474. // the name can match something in the zone is through a wildcard match.
  475. //
  476. // During an earlier stage in the search for this name, we made a record of
  477. // the lowest superdomain for which we know an RR exists. (Note the "we
  478. // know" qualification - there may be lower superdomains (ones with more
  479. // labels) that hold an RR, but as we weren't searching for them, we don't
  480. // know about them.)
  481. //
  482. // In the search for a wildcard match (which starts at the given domain
  483. // name and goes up the tree to successive superdomains), this is the level
  484. // at which we can stop - there can't be a wildcard at or beyond that
  485. // point.
  486. //
  487. // At each level that can stop the search, we should consider several cases:
  488. //
  489. // - If we found a wildcard match for a glue record below a
  490. // delegation point, we don't return the match,
  491. // instead we return the delegation. (Note that if we didn't
  492. // a wildcard match at all, we would return NXDOMAIN, not the
  493. // the delegation.)
  494. //
  495. // - If we found a wildcard match and we are sure that the match
  496. // is not an empty non-terminal, return the result taking into account CNAME,
  497. // on a zone cut, and NXRRSET.
  498. // (E.g. searching for a match
  499. // for c.b.a.example.com, we found that b.a.example.com did
  500. // not exist but that *.a.example.com. did. Checking
  501. // b.a.example.com revealed no subdomains, so we can use the
  502. // wilcard match we found.)
  503. //
  504. // - If we found a more specified match, the wildcard search
  505. // is canceled, resulting in NXDOMAIN. (E.g. searching for a match
  506. // for c.b.a.example.com, we found that b.a.example.com did
  507. // not exist but that *.a.example.com. did. Checking
  508. // b.a.example.com found subdomains. So b.example.com is
  509. // an empty non-terminal and so should not be returned in
  510. // the wildcard matching process. In other words,
  511. // b.example.com does exist in the DNS space, it just doesn't
  512. // have any RRs associated with it.)
  513. //
  514. // - If we found a match, but it is an empty non-terminal asterisk (E.g.#
  515. // subdomain.*.example.com. is present, but there is nothing at
  516. // *.example.com.), return an NXRRSET indication;
  517. // the wildcard exists in the DNS space, there's just nothing
  518. // associated with it. If DNSSEC data is required, return the
  519. // covering NSEC record.
  520. //
  521. // If none of the above applies in any level, the search fails with NXDOMAIN.
  522. ZoneFinder::FindResult
  523. DatabaseClient::Finder::findWildcardMatch(
  524. const isc::dns::Name& name, const isc::dns::RRType& type,
  525. const FindOptions options, const DelegationSearchResult& dresult,
  526. std::vector<isc::dns::ConstRRsetPtr>* target)
  527. {
  528. // Note that during the search we are going to search not only for the
  529. // requested type, but also for types that indicate a delegation -
  530. // NS and DNAME.
  531. WantedTypes final_types(FINAL_TYPES());
  532. final_types.insert(type);
  533. const size_t remove_labels = name.getLabelCount() - dresult.last_known;
  534. for (size_t i = 1; i <= remove_labels; ++i) {
  535. // Strip off the left-more label(s) in the name and replace with a "*".
  536. const Name superdomain(name.split(i));
  537. const string wildcard("*." + superdomain.toText());
  538. const string construct_name(name.toText());
  539. // TODO Add a check for DNAME, as DNAME wildcards are discouraged (see
  540. // RFC 4592 section 4.4).
  541. // Search for a match. The types are the same as with original query.
  542. FoundRRsets found = getRRsets(wildcard, final_types, true,
  543. &construct_name, type == RRType::ANY());
  544. if (found.first) {
  545. // Found something - but what?
  546. if (dresult.first_ns) {
  547. // About to use first_ns. The only way this can be set is if
  548. // we are searching for glue, so do a sanity check.
  549. if ((options & FIND_GLUE_OK) == 0) {
  550. isc_throw(Unexpected, "Inconsistent conditions during "
  551. "cancel of wilcard search for " <<
  552. name.toText() << ": find_ns non-null when not "
  553. "processing glue request");
  554. }
  555. // Wildcard match for a glue below a delegation point
  556. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  557. DATASRC_DATABASE_WILDCARD_CANCEL_NS).
  558. arg(accessor_->getDBName()).arg(wildcard).
  559. arg(dresult.first_ns->getName());
  560. return (FindResult(DELEGATION, dresult.first_ns));
  561. } else if (!hasSubdomains(name.split(i - 1).toText())) {
  562. // The wildcard match is the best one, find the final result
  563. // at it. Note that wildcard should never be the zone origin.
  564. return (findOnNameResult(name, type, options, false,
  565. found, &wildcard, target));
  566. } else {
  567. // more specified match found, cancel wildcard match
  568. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  569. DATASRC_DATABASE_WILDCARD_CANCEL_SUB).
  570. arg(accessor_->getDBName()).arg(wildcard).
  571. arg(name).arg(superdomain);
  572. return (FindResult(NXDOMAIN, ConstRRsetPtr()));
  573. }
  574. } else if (hasSubdomains(wildcard)) {
  575. // an empty non-terminal asterisk
  576. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  577. DATASRC_DATABASE_WILDCARD_EMPTY).
  578. arg(accessor_->getDBName()).arg(wildcard).arg(name);
  579. if ((options & FIND_DNSSEC) != 0) {
  580. ConstRRsetPtr nsec = findNSECCover(Name(wildcard));
  581. if (nsec) {
  582. return (FindResult(NXRRSET, nsec,
  583. RESULT_WILDCARD | RESULT_NSEC_SIGNED));
  584. }
  585. }
  586. return (FindResult(NXRRSET, ConstRRsetPtr(), RESULT_WILDCARD));
  587. }
  588. }
  589. // Nothing found at any level.
  590. return (FindResult(NXDOMAIN, ConstRRsetPtr()));
  591. }
  592. ZoneFinder::FindResult
  593. DatabaseClient::Finder::logAndCreateResult(
  594. const Name& name, const string* wildname, const RRType& type,
  595. ZoneFinder::Result code, ConstRRsetPtr rrset,
  596. const isc::log::MessageID& log_id, FindResultFlags flags) const
  597. {
  598. if (rrset) {
  599. if (wildname == NULL) {
  600. LOG_DEBUG(logger, DBG_TRACE_DETAILED, log_id).
  601. arg(accessor_->getDBName()).arg(name).arg(type).
  602. arg(getClass()).arg(*rrset);
  603. } else {
  604. LOG_DEBUG(logger, DBG_TRACE_DETAILED, log_id).
  605. arg(accessor_->getDBName()).arg(name).arg(type).
  606. arg(getClass()).arg(*wildname).arg(*rrset);
  607. }
  608. } else {
  609. if (wildname == NULL) {
  610. LOG_DEBUG(logger, DBG_TRACE_DETAILED, log_id).
  611. arg(accessor_->getDBName()).arg(name).arg(type).
  612. arg(getClass());
  613. } else {
  614. LOG_DEBUG(logger, DBG_TRACE_DETAILED, log_id).
  615. arg(accessor_->getDBName()).arg(name).arg(type).
  616. arg(getClass()).arg(*wildname);
  617. }
  618. }
  619. return (ZoneFinder::FindResult(code, rrset, flags));
  620. }
  621. ZoneFinder::FindResult
  622. DatabaseClient::Finder::findOnNameResult(const Name& name,
  623. const RRType& type,
  624. const FindOptions options,
  625. const bool is_origin,
  626. const FoundRRsets& found,
  627. const string* wildname,
  628. std::vector<isc::dns::ConstRRsetPtr>*
  629. target)
  630. {
  631. const bool wild = (wildname != NULL);
  632. FindResultFlags flags = wild ? RESULT_WILDCARD : RESULT_DEFAULT;
  633. // Get iterators for the different types of records we are interested in -
  634. // CNAME, NS and Wanted types.
  635. const FoundIterator nsi(found.second.find(RRType::NS()));
  636. const FoundIterator cni(found.second.find(RRType::CNAME()));
  637. const FoundIterator wti(found.second.find(type));
  638. // For wildcard case with DNSSEC required, the caller would need to know
  639. // whether it's NSEC or NSEC3 signed. So we need to do an additional
  640. // search here, even though the NSEC RR may not be returned.
  641. // TODO: this part should be revised when we support NSEC3; ideally we
  642. // should use more effective and efficient way to identify (whether and)
  643. // in which way the zone is signed.
  644. if (wild && (options & FIND_DNSSEC) != 0 &&
  645. found.second.find(RRType::NSEC()) != found.second.end()) {
  646. flags = flags | RESULT_NSEC_SIGNED;
  647. }
  648. if (!is_origin && ((options & FIND_GLUE_OK) == 0) &&
  649. nsi != found.second.end()) {
  650. // A NS RRset was found at the domain we were searching for. As it is
  651. // not at the origin of the zone, it is a delegation and indicates that
  652. // this zone is not authoritative for the data. Just return the
  653. // delegation information.
  654. return (logAndCreateResult(name, wildname, type, DELEGATION,
  655. nsi->second,
  656. wild ? DATASRC_DATABASE_WILDCARD_NS :
  657. DATASRC_DATABASE_FOUND_DELEGATION_EXACT,
  658. flags));
  659. } else if (type != RRType::CNAME() && cni != found.second.end()) {
  660. // We are not searching for a CNAME but nevertheless we have found one
  661. // at the name we are searching so we return it. (The caller may
  662. // want to continue the lookup by replacing the query name with the
  663. // canonical name and the original RR type.) First though, do a sanity
  664. // check to ensure that there is only one RR in the CNAME RRset.
  665. if (cni->second->getRdataCount() != 1) {
  666. isc_throw(DataSourceError, "CNAME with " <<
  667. cni->second->getRdataCount() << " rdata at " << name <<
  668. ", expected 1");
  669. }
  670. return (logAndCreateResult(name, wildname, type, CNAME, cni->second,
  671. wild ? DATASRC_DATABASE_WILDCARD_CNAME :
  672. DATASRC_DATABASE_FOUND_CNAME,
  673. flags));
  674. } else if (wti != found.second.end()) {
  675. bool any(type == RRType::ANY());
  676. isc::log::MessageID lid(wild ? DATASRC_DATABASE_WILDCARD_MATCH :
  677. DATASRC_DATABASE_FOUND_RRSET);
  678. if (any) {
  679. // An ANY query, copy everything to the target instead of returning
  680. // directly.
  681. for (FoundIterator it(found.second.begin());
  682. it != found.second.end(); ++it) {
  683. if (it->second) {
  684. // Skip over the empty ANY
  685. target->push_back(it->second);
  686. }
  687. }
  688. lid = wild ? DATASRC_DATABASE_WILDCARD_ANY :
  689. DATASRC_DATABASE_FOUND_ANY;
  690. }
  691. // Found an RR matching the query, so return it. (Note that this
  692. // includes the case where we were explicitly querying for a CNAME and
  693. // found it. It also includes the case where we were querying for an
  694. // NS RRset and found it at the apex of the zone.)
  695. return (logAndCreateResult(name, wildname, type, SUCCESS,
  696. wti->second, lid, flags));
  697. }
  698. // If we get here, we have found something at the requested name but not
  699. // one of the RR types we were interested in. This is the NXRRSET case so
  700. // return the appropriate status. If DNSSEC information was requested,
  701. // provide the NSEC records. If it's for wildcard, we need to get the
  702. // NSEC records in the name of the wildcard, not the substituted one,
  703. // so we need to search the tree again.
  704. ConstRRsetPtr nsec_rrset; // possibly used with DNSSEC, otherwise NULL
  705. if ((options & FIND_DNSSEC) != 0) {
  706. if (wild) {
  707. const FoundRRsets wfound = getRRsets(*wildname, NSEC_TYPES(),
  708. true);
  709. const FoundIterator nci = wfound.second.find(RRType::NSEC());
  710. if (nci != wfound.second.end()) {
  711. nsec_rrset = nci->second;
  712. }
  713. } else {
  714. const FoundIterator nci = found.second.find(RRType::NSEC());
  715. if (nci != found.second.end()) {
  716. nsec_rrset = nci->second;
  717. }
  718. }
  719. }
  720. if (nsec_rrset) {
  721. // This log message covers both normal and wildcard cases, so we pass
  722. // NULL for 'wildname'.
  723. return (logAndCreateResult(name, NULL, type, NXRRSET, nsec_rrset,
  724. DATASRC_DATABASE_FOUND_NXRRSET_NSEC,
  725. flags | RESULT_NSEC_SIGNED));
  726. }
  727. return (logAndCreateResult(name, wildname, type, NXRRSET, nsec_rrset,
  728. wild ? DATASRC_DATABASE_WILDCARD_NXRRSET :
  729. DATASRC_DATABASE_FOUND_NXRRSET, flags));
  730. }
  731. ZoneFinder::FindResult
  732. DatabaseClient::Finder::findNoNameResult(const Name& name, const RRType& type,
  733. FindOptions options,
  734. const DelegationSearchResult& dresult,
  735. std::vector<isc::dns::ConstRRsetPtr>*
  736. target)
  737. {
  738. const bool dnssec_data = ((options & FIND_DNSSEC) != 0);
  739. // On entry to this method, we know that the database doesn't have any
  740. // entry for this name. Before returning NXDOMAIN, we need to check
  741. // for special cases.
  742. if (hasSubdomains(name.toText())) {
  743. // Does the domain have a subdomain (i.e. it is an empty non-terminal)?
  744. // If so, return NXRRSET instead of NXDOMAIN (as although the name does
  745. // not exist in the database, it does exist in the DNS tree).
  746. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  747. DATASRC_DATABASE_FOUND_EMPTY_NONTERMINAL).
  748. arg(accessor_->getDBName()).arg(name);
  749. const ConstRRsetPtr nsec = dnssec_data ? findNSECCover(name) :
  750. ConstRRsetPtr();
  751. return (FindResult(NXRRSET, nsec,
  752. nsec ? RESULT_NSEC_SIGNED : RESULT_DEFAULT));
  753. } else if ((options & NO_WILDCARD) == 0) {
  754. // It's not an empty non-terminal and wildcard matching is not
  755. // disabled, so check for wildcards. If there is a wildcard match
  756. // (i.e. all results except NXDOMAIN) return it; otherwise fall
  757. // through to the NXDOMAIN case below.
  758. const ZoneFinder::FindResult wresult =
  759. findWildcardMatch(name, type, options, dresult, target);
  760. if (wresult.code != NXDOMAIN) {
  761. return (wresult);
  762. }
  763. }
  764. // All avenues to find a match are now exhausted, return NXDOMAIN (plus
  765. // NSEC records if requested).
  766. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_NO_MATCH).
  767. arg(accessor_->getDBName()).arg(name).arg(type).arg(getClass());
  768. const ConstRRsetPtr nsec = dnssec_data ? findNSECCover(name) :
  769. ConstRRsetPtr();
  770. return (FindResult(NXDOMAIN, nsec,
  771. nsec ? RESULT_NSEC_SIGNED : RESULT_DEFAULT));
  772. }
  773. ZoneFinder::FindResult
  774. DatabaseClient::Finder::findInternal(const Name& name, const RRType& type,
  775. std::vector<ConstRRsetPtr>* target,
  776. const FindOptions options)
  777. {
  778. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_FIND_RECORDS)
  779. .arg(accessor_->getDBName()).arg(name).arg(type).arg(getClass());
  780. // find() variants generally expect 'name' to be included in the zone.
  781. // Otherwise the search algorithm below won't work correctly, so we
  782. // reject the unexpected case first.
  783. const NameComparisonResult::NameRelation reln =
  784. name.compare(getOrigin()).getRelation();
  785. if (reln != NameComparisonResult::SUBDOMAIN &&
  786. reln != NameComparisonResult::EQUAL) {
  787. return (FindResult(NXDOMAIN, ConstRRsetPtr()));
  788. }
  789. // First, go through all superdomains from the origin down, searching for
  790. // nodes that indicate a delegation (i.e. NS or DNAME, ignoring NS records
  791. // at the apex). If one is found, the search stops there.
  792. //
  793. // (In fact there could be RRs in the database corresponding to subdomains
  794. // of the delegation. The reason we do the search for the delegations
  795. // first is because the delegation means that another zone is authoritative
  796. // for the data and so should be consulted to retrieve it. RRs below
  797. // this delegation point can be found in a search for glue but not
  798. // otherwise; in the latter case they are said to be occluded by the
  799. // presence of the delegation.)
  800. const DelegationSearchResult dresult = findDelegationPoint(name, options);
  801. if (dresult.rrset) {
  802. // In this case no special flags are needed.
  803. return (FindResult(dresult.code, dresult.rrset));
  804. }
  805. // If there is no delegation, look for the exact match to the request
  806. // name/type/class. However, there are special cases:
  807. // - Requested name has a singleton CNAME record associated with it
  808. // - Requested name is a delegation point (NS only but not at the zone
  809. // apex - DNAME is ignored here as it redirects DNS names subordinate to
  810. // the owner name - the owner name itself is not redirected.)
  811. const bool is_origin = (name == getOrigin());
  812. WantedTypes final_types(FINAL_TYPES());
  813. final_types.insert(type);
  814. const FoundRRsets found = getRRsets(name.toText(), final_types,
  815. !is_origin, NULL,
  816. type == RRType::ANY());
  817. if (found.first) {
  818. // Something found at the domain name. Look into it further to get
  819. // the final result.
  820. return (findOnNameResult(name, type, options, is_origin, found, NULL,
  821. target));
  822. } else {
  823. // Did not find anything at all at the domain name, so check for
  824. // subdomains or wildcards.
  825. return (findNoNameResult(name, type, options, dresult, target));
  826. }
  827. }
  828. ZoneFinder::FindNSEC3Result
  829. DatabaseClient::Finder::findNSEC3(const Name&, bool) {
  830. isc_throw(NotImplemented, "findNSEC3 is not yet implemented for database "
  831. "data source");
  832. }
  833. Name
  834. DatabaseClient::Finder::findPreviousName(const Name& name) const {
  835. const string str(accessor_->findPreviousName(zone_id_,
  836. name.reverse().toText()));
  837. try {
  838. return (Name(str));
  839. }
  840. // To avoid having the same code many times, we just catch all the
  841. // exceptions and handle them in a common code below
  842. catch (const isc::dns::EmptyLabel&) {}
  843. catch (const isc::dns::TooLongLabel&) {}
  844. catch (const isc::dns::BadLabelType&) {}
  845. catch (const isc::dns::BadEscape&) {}
  846. catch (const isc::dns::TooLongName&) {}
  847. catch (const isc::dns::IncompleteName&) {}
  848. isc_throw(DataSourceError, "Bad name " + str + " from findPreviousName");
  849. }
  850. Name
  851. DatabaseClient::Finder::getOrigin() const {
  852. return (origin_);
  853. }
  854. isc::dns::RRClass
  855. DatabaseClient::Finder::getClass() const {
  856. // TODO Implement
  857. return isc::dns::RRClass::IN();
  858. }
  859. namespace {
  860. /// This needs, beside of converting all data from textual representation, group
  861. /// together rdata of the same RRsets. To do this, we hold one row of data ahead
  862. /// of iteration. When we get a request to provide data, we create it from this
  863. /// data and load a new one. If it is to be put to the same rrset, we add it.
  864. /// Otherwise we just return what we have and keep the row as the one ahead
  865. /// for next time.
  866. class DatabaseIterator : public ZoneIterator {
  867. public:
  868. DatabaseIterator(boost::shared_ptr<DatabaseAccessor> accessor,
  869. const Name& zone_name,
  870. const RRClass& rrclass,
  871. bool separate_rrs) :
  872. accessor_(accessor),
  873. class_(rrclass),
  874. ready_(true),
  875. separate_rrs_(separate_rrs)
  876. {
  877. // Get the zone
  878. const pair<bool, int> zone(accessor_->getZone(zone_name.toText()));
  879. if (!zone.first) {
  880. // No such zone, can't continue
  881. isc_throw(DataSourceError, "Zone " + zone_name.toText() +
  882. " can not be iterated, because it doesn't exist "
  883. "in this data source");
  884. }
  885. // Start a separate transaction.
  886. accessor_->startTransaction();
  887. // Find the SOA of the zone (may or may not succeed). Note that
  888. // this must be done before starting the iteration context.
  889. soa_ = DatabaseClient::Finder(accessor_, zone.second, zone_name).
  890. find(zone_name, RRType::SOA()).rrset;
  891. // Request the context
  892. context_ = accessor_->getAllRecords(zone.second);
  893. // It must not return NULL, that's a bug of the implementation
  894. if (!context_) {
  895. isc_throw(isc::Unexpected, "Iterator context null at " +
  896. zone_name.toText());
  897. }
  898. // Prepare data for the next time
  899. getData();
  900. }
  901. virtual ~DatabaseIterator() {
  902. if (ready_) {
  903. accessor_->commit();
  904. }
  905. }
  906. virtual ConstRRsetPtr getSOA() const {
  907. return (soa_);
  908. }
  909. virtual isc::dns::ConstRRsetPtr getNextRRset() {
  910. if (!ready_) {
  911. isc_throw(isc::Unexpected, "Iterating past the zone end");
  912. }
  913. if (!data_ready_) {
  914. // At the end of zone
  915. accessor_->commit();
  916. ready_ = false;
  917. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  918. DATASRC_DATABASE_ITERATE_END);
  919. return (ConstRRsetPtr());
  920. }
  921. const string name_str(name_), rtype_str(rtype_), ttl(ttl_);
  922. const Name name(name_str);
  923. const RRType rtype(rtype_str);
  924. RRsetPtr rrset(new RRset(name, class_, rtype, RRTTL(ttl)));
  925. while (data_ready_ && name_ == name_str && rtype_str == rtype_) {
  926. if (ttl_ != ttl) {
  927. if (ttl < ttl_) {
  928. ttl_ = ttl;
  929. rrset->setTTL(RRTTL(ttl));
  930. }
  931. LOG_WARN(logger, DATASRC_DATABASE_ITERATE_TTL_MISMATCH).
  932. arg(name_).arg(class_).arg(rtype_).arg(rrset->getTTL());
  933. }
  934. rrset->addRdata(rdata::createRdata(rtype, class_, rdata_));
  935. getData();
  936. if (separate_rrs_) {
  937. break;
  938. }
  939. }
  940. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE_NEXT).
  941. arg(rrset->getName()).arg(rrset->getType());
  942. return (rrset);
  943. }
  944. private:
  945. // Load next row of data
  946. void getData() {
  947. string data[DatabaseAccessor::COLUMN_COUNT];
  948. data_ready_ = context_->getNext(data);
  949. name_ = data[DatabaseAccessor::NAME_COLUMN];
  950. rtype_ = data[DatabaseAccessor::TYPE_COLUMN];
  951. ttl_ = data[DatabaseAccessor::TTL_COLUMN];
  952. rdata_ = data[DatabaseAccessor::RDATA_COLUMN];
  953. }
  954. // The dedicated accessor
  955. boost::shared_ptr<DatabaseAccessor> accessor_;
  956. // The context
  957. DatabaseAccessor::IteratorContextPtr context_;
  958. // Class of the zone
  959. const RRClass class_;
  960. // SOA of the zone, if any (it should normally exist)
  961. ConstRRsetPtr soa_;
  962. // Status
  963. bool ready_, data_ready_;
  964. // Data of the next row
  965. string name_, rtype_, rdata_, ttl_;
  966. // Whether to modify differing TTL values, or treat a different TTL as
  967. // a different RRset
  968. bool separate_rrs_;
  969. };
  970. }
  971. ZoneIteratorPtr
  972. DatabaseClient::getIterator(const isc::dns::Name& name,
  973. bool separate_rrs) const
  974. {
  975. ZoneIteratorPtr iterator = ZoneIteratorPtr(new DatabaseIterator(
  976. accessor_->clone(), name,
  977. rrclass_, separate_rrs));
  978. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE).
  979. arg(name);
  980. return (iterator);
  981. }
  982. //
  983. // Zone updater using some database system as the underlying data source.
  984. //
  985. class DatabaseUpdater : public ZoneUpdater {
  986. public:
  987. DatabaseUpdater(boost::shared_ptr<DatabaseAccessor> accessor, int zone_id,
  988. const Name& zone_name, const RRClass& zone_class,
  989. bool journaling) :
  990. committed_(false), accessor_(accessor), zone_id_(zone_id),
  991. db_name_(accessor->getDBName()), zone_name_(zone_name.toText()),
  992. zone_class_(zone_class), journaling_(journaling),
  993. diff_phase_(NOT_STARTED), serial_(0),
  994. finder_(new DatabaseClient::Finder(accessor_, zone_id_, zone_name))
  995. {
  996. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_CREATED)
  997. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  998. }
  999. virtual ~DatabaseUpdater() {
  1000. if (!committed_) {
  1001. try {
  1002. accessor_->rollback();
  1003. logger.info(DATASRC_DATABASE_UPDATER_ROLLBACK)
  1004. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  1005. } catch (const DataSourceError& e) {
  1006. // We generally expect that rollback always succeeds, and
  1007. // it should in fact succeed in a way we execute it. But
  1008. // as the public API allows rollback() to fail and
  1009. // throw, we should expect it. Obviously we cannot re-throw
  1010. // it. The best we can do is to log it as a critical error.
  1011. logger.error(DATASRC_DATABASE_UPDATER_ROLLBACKFAIL)
  1012. .arg(zone_name_).arg(zone_class_).arg(db_name_)
  1013. .arg(e.what());
  1014. }
  1015. }
  1016. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_DESTROYED)
  1017. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  1018. }
  1019. virtual ZoneFinder& getFinder() { return (*finder_); }
  1020. virtual void addRRset(const RRset& rrset);
  1021. virtual void deleteRRset(const RRset& rrset);
  1022. virtual void commit();
  1023. private:
  1024. // A short cut typedef only for making the code shorter.
  1025. typedef DatabaseAccessor Accessor;
  1026. bool committed_;
  1027. boost::shared_ptr<DatabaseAccessor> accessor_;
  1028. const int zone_id_;
  1029. const string db_name_;
  1030. const string zone_name_;
  1031. const RRClass zone_class_;
  1032. const bool journaling_;
  1033. // For the journals
  1034. enum DiffPhase {
  1035. NOT_STARTED,
  1036. DELETE,
  1037. ADD
  1038. };
  1039. DiffPhase diff_phase_;
  1040. Serial serial_;
  1041. boost::scoped_ptr<DatabaseClient::Finder> finder_;
  1042. // This is a set of validation checks commonly used for addRRset() and
  1043. // deleteRRset to minimize duplicate code logic and to make the main
  1044. // code concise.
  1045. void validateAddOrDelete(const char* const op_str, const RRset& rrset,
  1046. DiffPhase prev_phase,
  1047. DiffPhase current_phase) const;
  1048. };
  1049. void
  1050. DatabaseUpdater::validateAddOrDelete(const char* const op_str,
  1051. const RRset& rrset,
  1052. DiffPhase prev_phase,
  1053. DiffPhase current_phase) const
  1054. {
  1055. if (committed_) {
  1056. isc_throw(DataSourceError, op_str << " attempt after commit to zone: "
  1057. << zone_name_ << "/" << zone_class_);
  1058. }
  1059. if (rrset.getRdataCount() == 0) {
  1060. isc_throw(DataSourceError, op_str << " attempt with an empty RRset: "
  1061. << rrset.getName() << "/" << zone_class_ << "/"
  1062. << rrset.getType());
  1063. }
  1064. if (rrset.getClass() != zone_class_) {
  1065. isc_throw(DataSourceError, op_str << " attempt for a different class "
  1066. << zone_name_ << "/" << zone_class_ << ": "
  1067. << rrset.toText());
  1068. }
  1069. if (rrset.getRRsig()) {
  1070. isc_throw(DataSourceError, op_str << " attempt for RRset with RRSIG "
  1071. << zone_name_ << "/" << zone_class_ << ": "
  1072. << rrset.toText());
  1073. }
  1074. if (journaling_) {
  1075. const RRType rrtype(rrset.getType());
  1076. if (rrtype == RRType::SOA() && diff_phase_ != prev_phase) {
  1077. isc_throw(isc::BadValue, op_str << " attempt in an invalid "
  1078. << "diff phase: " << diff_phase_ << ", rrset: " <<
  1079. rrset.toText());
  1080. }
  1081. if (rrtype != RRType::SOA() && diff_phase_ != current_phase) {
  1082. isc_throw(isc::BadValue, "diff state change by non SOA: "
  1083. << rrset.toText());
  1084. }
  1085. }
  1086. }
  1087. void
  1088. DatabaseUpdater::addRRset(const RRset& rrset) {
  1089. validateAddOrDelete("add", rrset, DELETE, ADD);
  1090. // It's guaranteed rrset has at least one RDATA at this point.
  1091. RdataIteratorPtr it = rrset.getRdataIterator();
  1092. string columns[Accessor::ADD_COLUMN_COUNT]; // initialized with ""
  1093. columns[Accessor::ADD_NAME] = rrset.getName().toText();
  1094. columns[Accessor::ADD_REV_NAME] = rrset.getName().reverse().toText();
  1095. columns[Accessor::ADD_TTL] = rrset.getTTL().toText();
  1096. columns[Accessor::ADD_TYPE] = rrset.getType().toText();
  1097. string journal[Accessor::DIFF_PARAM_COUNT];
  1098. if (journaling_) {
  1099. journal[Accessor::DIFF_NAME] = columns[Accessor::ADD_NAME];
  1100. journal[Accessor::DIFF_TYPE] = columns[Accessor::ADD_TYPE];
  1101. journal[Accessor::DIFF_TTL] = columns[Accessor::ADD_TTL];
  1102. diff_phase_ = ADD;
  1103. if (rrset.getType() == RRType::SOA()) {
  1104. serial_ =
  1105. dynamic_cast<const generic::SOA&>(it->getCurrent()).
  1106. getSerial();
  1107. }
  1108. }
  1109. for (; !it->isLast(); it->next()) {
  1110. if (rrset.getType() == RRType::RRSIG()) {
  1111. // XXX: the current interface (based on the current sqlite3
  1112. // data source schema) requires a separate "sigtype" column,
  1113. // even though it won't be used in a newer implementation.
  1114. // We should eventually clean up the schema design and simplify
  1115. // the interface, but until then we have to conform to the schema.
  1116. const generic::RRSIG& rrsig_rdata =
  1117. dynamic_cast<const generic::RRSIG&>(it->getCurrent());
  1118. columns[Accessor::ADD_SIGTYPE] =
  1119. rrsig_rdata.typeCovered().toText();
  1120. }
  1121. columns[Accessor::ADD_RDATA] = it->getCurrent().toText();
  1122. if (journaling_) {
  1123. journal[Accessor::DIFF_RDATA] = columns[Accessor::ADD_RDATA];
  1124. accessor_->addRecordDiff(zone_id_, serial_.getValue(),
  1125. Accessor::DIFF_ADD, journal);
  1126. }
  1127. accessor_->addRecordToZone(columns);
  1128. }
  1129. }
  1130. void
  1131. DatabaseUpdater::deleteRRset(const RRset& rrset) {
  1132. // If this is the first operation, pretend we are starting a new delete
  1133. // sequence after adds. This will simplify the validation below.
  1134. if (diff_phase_ == NOT_STARTED) {
  1135. diff_phase_ = ADD;
  1136. }
  1137. validateAddOrDelete("delete", rrset, ADD, DELETE);
  1138. RdataIteratorPtr it = rrset.getRdataIterator();
  1139. string params[Accessor::DEL_PARAM_COUNT]; // initialized with ""
  1140. params[Accessor::DEL_NAME] = rrset.getName().toText();
  1141. params[Accessor::DEL_TYPE] = rrset.getType().toText();
  1142. string journal[Accessor::DIFF_PARAM_COUNT];
  1143. if (journaling_) {
  1144. journal[Accessor::DIFF_NAME] = params[Accessor::DEL_NAME];
  1145. journal[Accessor::DIFF_TYPE] = params[Accessor::DEL_TYPE];
  1146. journal[Accessor::DIFF_TTL] = rrset.getTTL().toText();
  1147. diff_phase_ = DELETE;
  1148. if (rrset.getType() == RRType::SOA()) {
  1149. serial_ =
  1150. dynamic_cast<const generic::SOA&>(it->getCurrent()).
  1151. getSerial();
  1152. }
  1153. }
  1154. for (; !it->isLast(); it->next()) {
  1155. params[Accessor::DEL_RDATA] = it->getCurrent().toText();
  1156. if (journaling_) {
  1157. journal[Accessor::DIFF_RDATA] = params[Accessor::DEL_RDATA];
  1158. accessor_->addRecordDiff(zone_id_, serial_.getValue(),
  1159. Accessor::DIFF_DELETE, journal);
  1160. }
  1161. accessor_->deleteRecordInZone(params);
  1162. }
  1163. }
  1164. void
  1165. DatabaseUpdater::commit() {
  1166. if (committed_) {
  1167. isc_throw(DataSourceError, "Duplicate commit attempt for "
  1168. << zone_name_ << "/" << zone_class_ << " on "
  1169. << db_name_);
  1170. }
  1171. if (journaling_ && diff_phase_ == DELETE) {
  1172. isc_throw(isc::BadValue, "Update sequence not complete");
  1173. }
  1174. accessor_->commit();
  1175. committed_ = true; // make sure the destructor won't trigger rollback
  1176. // We release the accessor immediately after commit is completed so that
  1177. // we don't hold the possible internal resource any longer.
  1178. accessor_.reset();
  1179. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_COMMIT)
  1180. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  1181. }
  1182. // The updater factory
  1183. ZoneUpdaterPtr
  1184. DatabaseClient::getUpdater(const isc::dns::Name& name, bool replace,
  1185. bool journaling) const
  1186. {
  1187. if (replace && journaling) {
  1188. isc_throw(isc::BadValue, "Can't store journal and replace the whole "
  1189. "zone at the same time");
  1190. }
  1191. boost::shared_ptr<DatabaseAccessor> update_accessor(accessor_->clone());
  1192. const std::pair<bool, int> zone(update_accessor->startUpdateZone(
  1193. name.toText(), replace));
  1194. if (!zone.first) {
  1195. return (ZoneUpdaterPtr());
  1196. }
  1197. return (ZoneUpdaterPtr(new DatabaseUpdater(update_accessor, zone.second,
  1198. name, rrclass_, journaling)));
  1199. }
  1200. //
  1201. // Zone journal reader using some database system as the underlying data
  1202. // source.
  1203. //
  1204. class DatabaseJournalReader : public ZoneJournalReader {
  1205. private:
  1206. // A shortcut typedef to keep the code concise.
  1207. typedef DatabaseAccessor Accessor;
  1208. public:
  1209. DatabaseJournalReader(boost::shared_ptr<Accessor> accessor, const Name& zone,
  1210. int zone_id, const RRClass& rrclass, uint32_t begin,
  1211. uint32_t end) :
  1212. accessor_(accessor), zone_(zone), rrclass_(rrclass),
  1213. begin_(begin), end_(end), finished_(false)
  1214. {
  1215. context_ = accessor_->getDiffs(zone_id, begin, end);
  1216. }
  1217. virtual ~DatabaseJournalReader() {}
  1218. virtual ConstRRsetPtr getNextDiff() {
  1219. if (finished_) {
  1220. isc_throw(InvalidOperation,
  1221. "Diff read attempt past the end of sequence on "
  1222. << accessor_->getDBName());
  1223. }
  1224. string data[Accessor::COLUMN_COUNT];
  1225. if (!context_->getNext(data)) {
  1226. finished_ = true;
  1227. LOG_DEBUG(logger, DBG_TRACE_BASIC,
  1228. DATASRC_DATABASE_JOURNALREADER_END).
  1229. arg(zone_).arg(rrclass_).arg(accessor_->getDBName()).
  1230. arg(begin_).arg(end_);
  1231. return (ConstRRsetPtr());
  1232. }
  1233. try {
  1234. RRsetPtr rrset(new RRset(Name(data[Accessor::NAME_COLUMN]),
  1235. rrclass_,
  1236. RRType(data[Accessor::TYPE_COLUMN]),
  1237. RRTTL(data[Accessor::TTL_COLUMN])));
  1238. rrset->addRdata(rdata::createRdata(rrset->getType(), rrclass_,
  1239. data[Accessor::RDATA_COLUMN]));
  1240. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  1241. DATASRC_DATABASE_JOURNALREADER_NEXT).
  1242. arg(rrset->getName()).arg(rrset->getType()).
  1243. arg(zone_).arg(rrclass_).arg(accessor_->getDBName());
  1244. return (rrset);
  1245. } catch (const Exception& ex) {
  1246. LOG_ERROR(logger, DATASRC_DATABASE_JOURNALREADR_BADDATA).
  1247. arg(zone_).arg(rrclass_).arg(accessor_->getDBName()).
  1248. arg(begin_).arg(end_).arg(ex.what());
  1249. isc_throw(DataSourceError, "Failed to create RRset from diff on "
  1250. << accessor_->getDBName());
  1251. }
  1252. }
  1253. private:
  1254. boost::shared_ptr<Accessor> accessor_;
  1255. const Name zone_;
  1256. const RRClass rrclass_;
  1257. Accessor::IteratorContextPtr context_;
  1258. const uint32_t begin_;
  1259. const uint32_t end_;
  1260. bool finished_;
  1261. };
  1262. // The JournalReader factory
  1263. pair<ZoneJournalReader::Result, ZoneJournalReaderPtr>
  1264. DatabaseClient::getJournalReader(const isc::dns::Name& zone,
  1265. uint32_t begin_serial,
  1266. uint32_t end_serial) const
  1267. {
  1268. boost::shared_ptr<DatabaseAccessor> jnl_accessor(accessor_->clone());
  1269. const pair<bool, int> zoneinfo(jnl_accessor->getZone(zone.toText()));
  1270. if (!zoneinfo.first) {
  1271. return (pair<ZoneJournalReader::Result, ZoneJournalReaderPtr>(
  1272. ZoneJournalReader::NO_SUCH_ZONE,
  1273. ZoneJournalReaderPtr()));
  1274. }
  1275. try {
  1276. const pair<ZoneJournalReader::Result, ZoneJournalReaderPtr> ret(
  1277. ZoneJournalReader::SUCCESS,
  1278. ZoneJournalReaderPtr(new DatabaseJournalReader(jnl_accessor,
  1279. zone,
  1280. zoneinfo.second,
  1281. rrclass_,
  1282. begin_serial,
  1283. end_serial)));
  1284. LOG_DEBUG(logger, DBG_TRACE_BASIC,
  1285. DATASRC_DATABASE_JOURNALREADER_START).arg(zone).arg(rrclass_).
  1286. arg(jnl_accessor->getDBName()).arg(begin_serial).arg(end_serial);
  1287. return (ret);
  1288. } catch (const NoSuchSerial&) {
  1289. return (pair<ZoneJournalReader::Result, ZoneJournalReaderPtr>(
  1290. ZoneJournalReader::NO_SUCH_VERSION,
  1291. ZoneJournalReaderPtr()));
  1292. }
  1293. }
  1294. }
  1295. }