database.cc 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  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/zone_iterator.h>
  20. #include <datasrc/rrset_collection_base.h>
  21. #include <exceptions/exceptions.h>
  22. #include <dns/name.h>
  23. #include <dns/rrclass.h>
  24. #include <dns/rrttl.h>
  25. #include <dns/rrset.h>
  26. #include <dns/rdata.h>
  27. #include <dns/rdataclass.h>
  28. #include <dns/nsec3hash.h>
  29. #include <datasrc/data_source.h>
  30. #include <datasrc/logger.h>
  31. #include <boost/foreach.hpp>
  32. #include <boost/scoped_ptr.hpp>
  33. using namespace isc::dns;
  34. using namespace std;
  35. using namespace isc::dns::rdata;
  36. using boost::lexical_cast;
  37. using boost::scoped_ptr;
  38. namespace isc {
  39. namespace datasrc {
  40. // RAII-style transaction holder; roll back the transaction unless explicitly
  41. // committed
  42. namespace {
  43. class TransactionHolder {
  44. public:
  45. TransactionHolder(DatabaseAccessor& accessor) : accessor_(accessor),
  46. committed_(false)
  47. {
  48. accessor_.startTransaction();
  49. }
  50. ~TransactionHolder() {
  51. if (!committed_) {
  52. try {
  53. accessor_.rollback();
  54. } catch (const DataSourceError& e) {
  55. // We generally expect that rollback always succeeds, and
  56. // it should in fact succeed in a way we execute it. But
  57. // as the public API allows rollback() to fail and
  58. // throw, we should expect it. Obviously we cannot re-throw
  59. // it. The best we can do is to log it as a critical error.
  60. logger.error(DATASRC_DATABASE_TRANSACTION_ROLLBACKFAIL).
  61. arg(accessor_.getDBName()).
  62. arg(e.what());
  63. }
  64. }
  65. }
  66. void commit() {
  67. accessor_.commit();
  68. committed_ = true;
  69. }
  70. private:
  71. DatabaseAccessor& accessor_;
  72. bool committed_;
  73. };
  74. } // end unnamed namespace
  75. DatabaseClient::DatabaseClient(RRClass rrclass,
  76. boost::shared_ptr<DatabaseAccessor>
  77. accessor) :
  78. rrclass_(rrclass), accessor_(accessor)
  79. {
  80. if (!accessor_) {
  81. isc_throw(isc::InvalidParameter,
  82. "No database provided to DatabaseClient");
  83. }
  84. }
  85. DataSourceClient::FindResult
  86. DatabaseClient::findZone(const Name& name) const {
  87. std::pair<bool, int> zone(accessor_->getZone(name.toText()));
  88. // Try exact first
  89. if (zone.first) {
  90. return (FindResult(result::SUCCESS,
  91. ZoneFinderPtr(new Finder(accessor_,
  92. zone.second, name))));
  93. }
  94. // Then super domains
  95. // Start from 1, as 0 is covered above
  96. for (size_t i(1); i < name.getLabelCount(); ++i) {
  97. isc::dns::Name superdomain(name.split(i));
  98. zone = accessor_->getZone(superdomain.toText());
  99. if (zone.first) {
  100. return (FindResult(result::PARTIALMATCH,
  101. ZoneFinderPtr(new Finder(accessor_,
  102. zone.second,
  103. superdomain))));
  104. }
  105. }
  106. // No, really nothing
  107. return (FindResult(result::NOTFOUND, ZoneFinderPtr()));
  108. }
  109. bool
  110. DatabaseClient::createZone(const Name& zone_name) {
  111. TransactionHolder transaction(*accessor_);
  112. const std::pair<bool, int> zone(accessor_->getZone(zone_name.toText()));
  113. if (zone.first) {
  114. return (false);
  115. }
  116. accessor_->addZone(zone_name.toText());
  117. transaction.commit();
  118. return (true);
  119. }
  120. bool
  121. DatabaseClient::deleteZone(const Name& zone_name) {
  122. TransactionHolder transaction(*accessor_);
  123. const std::pair<bool, int> zinfo(accessor_->getZone(zone_name.toText()));
  124. if (!zinfo.first) { // if it doesn't exist just return false
  125. return (false);
  126. }
  127. accessor_->deleteZone(zinfo.second);
  128. transaction.commit();
  129. return (true);
  130. }
  131. DatabaseClient::Finder::Finder(boost::shared_ptr<DatabaseAccessor> accessor,
  132. int zone_id, const isc::dns::Name& origin) :
  133. accessor_(accessor),
  134. zone_id_(zone_id),
  135. origin_(origin)
  136. { }
  137. namespace {
  138. // Adds the given Rdata to the given RRset
  139. // If the rrset is an empty pointer, a new one is
  140. // created with the given name, class, type and ttl
  141. // The type is checked if the rrset exists, but the
  142. // name is not.
  143. //
  144. // Then adds the given rdata to the set
  145. //
  146. // Raises a DataSourceError if the type does not
  147. // match, or if the given rdata string does not
  148. // parse correctly for the given type and class
  149. //
  150. // The DatabaseAccessor is passed to print the
  151. // database name in the log message if the TTL is
  152. // modified
  153. void addOrCreate(isc::dns::RRsetPtr& rrset,
  154. const isc::dns::Name& name,
  155. const isc::dns::RRClass& cls,
  156. const isc::dns::RRType& type,
  157. const isc::dns::RRTTL& ttl,
  158. const std::string& rdata_str,
  159. const DatabaseAccessor& db
  160. )
  161. {
  162. if (!rrset) {
  163. rrset.reset(new isc::dns::RRset(name, cls, type, ttl));
  164. } else {
  165. // This is a check to make sure find() is not messing things up
  166. assert(type == rrset->getType());
  167. if (ttl != rrset->getTTL()) {
  168. if (ttl < rrset->getTTL()) {
  169. rrset->setTTL(ttl);
  170. }
  171. logger.warn(DATASRC_DATABASE_FIND_TTL_MISMATCH)
  172. .arg(db.getDBName()).arg(name).arg(cls)
  173. .arg(type).arg(rrset->getTTL());
  174. }
  175. }
  176. try {
  177. rrset->addRdata(isc::dns::rdata::createRdata(type, cls, rdata_str));
  178. } catch (const isc::dns::rdata::InvalidRdataText& ivrt) {
  179. // at this point, rrset may have been initialised for no reason,
  180. // and won't be used. But the caller would drop the shared_ptr
  181. // on such an error anyway, so we don't care.
  182. isc_throw(DataSourceError,
  183. "bad rdata in database for " << name << " "
  184. << type << ": " << ivrt.what());
  185. }
  186. }
  187. // This class keeps a short-lived store of RRSIG records encountered
  188. // during a call to find(). If the backend happens to return signatures
  189. // before the actual data, we might not know which signatures we will need
  190. // So if they may be relevant, we store the in this class.
  191. //
  192. // (If this class seems useful in other places, we might want to move
  193. // it to util. That would also provide an opportunity to add unit tests)
  194. class RRsigStore {
  195. public:
  196. // Adds the given signature Rdata to the store
  197. // The signature rdata MUST be of the RRSIG rdata type
  198. // (the caller must make sure of this).
  199. // NOTE: if we move this class to a public namespace,
  200. // we should add a type_covered argument, so as not
  201. // to have to do this cast here.
  202. void addSig(isc::dns::rdata::RdataPtr sig_rdata) {
  203. const isc::dns::RRType& type_covered =
  204. static_cast<isc::dns::rdata::generic::RRSIG*>(
  205. sig_rdata.get())->typeCovered();
  206. sigs_[type_covered].push_back(sig_rdata);
  207. }
  208. // If the store contains signatures for the type of the given
  209. // rrset, they are appended to it.
  210. void appendSignatures(isc::dns::RRsetPtr& rrset) const {
  211. std::map<isc::dns::RRType,
  212. std::vector<isc::dns::rdata::RdataPtr> >::const_iterator
  213. found = sigs_.find(rrset->getType());
  214. if (found != sigs_.end()) {
  215. BOOST_FOREACH(isc::dns::rdata::RdataPtr sig, found->second) {
  216. rrset->addRRsig(sig);
  217. }
  218. }
  219. }
  220. bool empty() const {
  221. return (sigs_.empty());
  222. }
  223. private:
  224. std::map<isc::dns::RRType, std::vector<isc::dns::rdata::RdataPtr> > sigs_;
  225. };
  226. }
  227. DatabaseClient::Finder::FoundRRsets
  228. DatabaseClient::Finder::getRRsets(const string& name, const WantedTypes& types,
  229. bool sigs,
  230. const string* construct_name, bool any,
  231. DatabaseAccessor::IteratorContextPtr context)
  232. {
  233. RRsigStore sig_store;
  234. bool records_found = false;
  235. std::map<RRType, RRsetPtr> result;
  236. // Request the context in case we didn't get one
  237. if (!context) {
  238. context = accessor_->getRecords(name, zone_id_);
  239. }
  240. // It must not return NULL, that's a bug of the implementation
  241. if (!context) {
  242. isc_throw(isc::Unexpected, "Iterator context null at " + name);
  243. }
  244. std::string columns[DatabaseAccessor::COLUMN_COUNT];
  245. if (construct_name == NULL) {
  246. construct_name = &name;
  247. }
  248. const Name construct_name_object(*construct_name);
  249. bool seen_cname(false);
  250. bool seen_other(false);
  251. while (context->getNext(columns)) {
  252. // The domain is not empty
  253. records_found = true;
  254. try {
  255. const RRType cur_type(columns[DatabaseAccessor::TYPE_COLUMN]);
  256. if (sigs && (cur_type == RRType::RRSIG())) {
  257. // If we get signatures before we get the actual data, we
  258. // can't know which ones to keep and which to drop...
  259. // So we keep a separate store of any signature that may be
  260. // relevant and add them to the final RRset when we are
  261. // done.
  262. // A possible optimization here is to not store them for
  263. // types we are certain we don't need
  264. sig_store.addSig(rdata::createRdata(cur_type, getClass(),
  265. columns[DatabaseAccessor::RDATA_COLUMN]));
  266. }
  267. if (types.find(cur_type) != types.end() || any) {
  268. // This type is requested, so put it into result
  269. const RRTTL cur_ttl(columns[DatabaseAccessor::TTL_COLUMN]);
  270. // The sigtype column was an optimization for finding the
  271. // relevant RRSIG RRs for a lookup. Currently this column is
  272. // not used in this revised datasource implementation. We
  273. // should either start using it again, or remove it from use
  274. // completely (i.e. also remove it from the schema and the
  275. // backend implementation).
  276. // Note that because we don't use it now, we also won't notice
  277. // it if the value is wrong (i.e. if the sigtype column
  278. // contains an rrtype that is different from the actual value
  279. // of the 'type covered' field in the RRSIG Rdata).
  280. //cur_sigtype(columns[SIGTYPE_COLUMN]);
  281. addOrCreate(result[cur_type], construct_name_object,
  282. getClass(), cur_type, cur_ttl,
  283. columns[DatabaseAccessor::RDATA_COLUMN],
  284. *accessor_);
  285. }
  286. if (cur_type == RRType::CNAME()) {
  287. seen_cname = true;
  288. } else if (cur_type != RRType::RRSIG() &&
  289. cur_type != RRType::NSEC3() &&
  290. cur_type != RRType::NSEC()) {
  291. // NSEC and RRSIG can coexist with anything, otherwise
  292. // we've seen something that can't live together with potential
  293. // CNAME.
  294. //
  295. // NSEC3 lives in separate namespace from everything, therefore
  296. // we just ignore it here for these checks as well.
  297. seen_other = true;
  298. }
  299. } catch (const InvalidRRType&) {
  300. isc_throw(DataSourceError, "Invalid RRType in database for " <<
  301. name << ": " << columns[DatabaseAccessor::
  302. TYPE_COLUMN]);
  303. } catch (const InvalidRRTTL&) {
  304. isc_throw(DataSourceError, "Invalid TTL in database for " <<
  305. name << ": " << columns[DatabaseAccessor::
  306. TTL_COLUMN]);
  307. } catch (const rdata::InvalidRdataText&) {
  308. isc_throw(DataSourceError, "Invalid rdata in database for " <<
  309. name << ": " << columns[DatabaseAccessor::
  310. RDATA_COLUMN]);
  311. }
  312. }
  313. if (seen_cname && seen_other) {
  314. isc_throw(DataSourceError, "CNAME shares domain " << name <<
  315. " with something else");
  316. }
  317. if (!sig_store.empty()) {
  318. // Add signatures to all found RRsets
  319. for (std::map<RRType, RRsetPtr>::iterator i(result.begin());
  320. i != result.end(); ++ i) {
  321. sig_store.appendSignatures(i->second);
  322. }
  323. }
  324. if (records_found && any) {
  325. result[RRType::ANY()] = RRsetPtr();
  326. // These will be sitting on the other RRsets.
  327. result.erase(RRType::RRSIG());
  328. }
  329. return (FoundRRsets(records_found, result));
  330. }
  331. bool
  332. DatabaseClient::Finder::hasSubdomains(const std::string& name) {
  333. // Request the context
  334. DatabaseAccessor::IteratorContextPtr
  335. context(accessor_->getRecords(name, zone_id_, true));
  336. // It must not return NULL, that's a bug of the implementation
  337. if (!context) {
  338. isc_throw(isc::Unexpected, "Iterator context null at " + name);
  339. }
  340. std::string columns[DatabaseAccessor::COLUMN_COUNT];
  341. return (context->getNext(columns));
  342. }
  343. // Some manipulation with RRType sets
  344. namespace {
  345. // Bunch of functions to construct specific sets of RRTypes we will
  346. // ask from it.
  347. typedef std::set<RRType> WantedTypes;
  348. const WantedTypes&
  349. NSEC3_TYPES() {
  350. static bool initialized(false);
  351. static WantedTypes result;
  352. if (!initialized) {
  353. result.insert(RRType::NSEC3());
  354. initialized = true;
  355. }
  356. return (result);
  357. }
  358. const WantedTypes&
  359. NSEC3PARAM_TYPES() {
  360. static bool initialized(false);
  361. static WantedTypes result;
  362. if (!initialized) {
  363. result.insert(RRType::NSEC3PARAM());
  364. initialized = true;
  365. }
  366. return (result);
  367. }
  368. const WantedTypes&
  369. NSEC_TYPES() {
  370. static bool initialized(false);
  371. static WantedTypes result;
  372. if (!initialized) {
  373. result.insert(RRType::NSEC());
  374. initialized = true;
  375. }
  376. return (result);
  377. }
  378. const WantedTypes&
  379. DELEGATION_TYPES() {
  380. static bool initialized(false);
  381. static WantedTypes result;
  382. if (!initialized) {
  383. result.insert(RRType::DNAME());
  384. result.insert(RRType::NS());
  385. initialized = true;
  386. }
  387. return (result);
  388. }
  389. const WantedTypes&
  390. FINAL_TYPES() {
  391. static bool initialized(false);
  392. static WantedTypes result;
  393. if (!initialized) {
  394. result.insert(RRType::CNAME());
  395. result.insert(RRType::NS());
  396. result.insert(RRType::NSEC());
  397. initialized = true;
  398. }
  399. return (result);
  400. }
  401. }
  402. ZoneFinderContextPtr
  403. DatabaseClient::Finder::findAll(const isc::dns::Name& name,
  404. std::vector<isc::dns::ConstRRsetPtr>& target,
  405. const FindOptions options)
  406. {
  407. return (ZoneFinderContextPtr(new GenericContext(
  408. *this, options,
  409. findInternal(name, RRType::ANY(),
  410. &target, options),
  411. target)));
  412. }
  413. ZoneFinderContextPtr
  414. DatabaseClient::Finder::find(const isc::dns::Name& name,
  415. const isc::dns::RRType& type,
  416. const FindOptions options)
  417. {
  418. if (type == RRType::ANY()) {
  419. isc_throw(isc::Unexpected, "Use findAll to answer ANY");
  420. }
  421. return (ZoneFinderContextPtr(new GenericContext(
  422. *this, options,
  423. findInternal(name, type, NULL,
  424. options))));
  425. }
  426. DatabaseClient::Finder::DelegationSearchResult
  427. DatabaseClient::Finder::findDelegationPoint(const isc::dns::Name& name,
  428. const FindOptions options)
  429. {
  430. // Result of search
  431. isc::dns::ConstRRsetPtr result_rrset;
  432. ZoneFinder::Result result_status = SUCCESS;
  433. // Are we searching for glue?
  434. const bool glue_ok = ((options & FIND_GLUE_OK) != 0);
  435. // This next declaration is an optimisation. When we search the database
  436. // for glue records, we generally ignore delegations. (This allows for
  437. // the case where e.g. the delegation to zone example.com refers to
  438. // nameservers within the zone, e.g. ns1.example.com. When conducting the
  439. // search for ns1.example.com, we have to search past the NS records at
  440. // example.com.)
  441. //
  442. // The one case where this is forbidden is when we search past the zone
  443. // cut but the match we find for the glue is a wildcard match. In that
  444. // case, we return the delegation instead (see RFC 1034, section 4.3.3).
  445. // To save a new search, we record the location of the delegation cut when
  446. // we encounter it here.
  447. isc::dns::ConstRRsetPtr first_ns;
  448. // We want to search from the apex down. We are given the full domain
  449. // name so we have to do some manipulation to ensure that when we start
  450. // checking superdomains, we start from the the domain name of the zone
  451. // (e.g. if the name is b.a.example.com. and we are in the example.com.
  452. // zone, we check example.com., a.example.com. and b.a.example.com. We
  453. // don't need to check com. or .).
  454. //
  455. // Set the number of labels in the origin (i.e. apex of the zone) and in
  456. // the last known non-empty domain (which, at this point, is the origin).
  457. const size_t origin_label_count = getOrigin().getLabelCount();
  458. size_t last_known = origin_label_count;
  459. // Set how many labels we remove to get origin: this is the number of
  460. // labels we have to process in our search.
  461. const size_t remove_labels = name.getLabelCount() - origin_label_count;
  462. // Go through all superdomains from the origin down searching for nodes
  463. // that indicate a delegation (.e. NS or DNAME). Note that we only check
  464. // pure superdomains; delegation on an exact match will be detected later.
  465. for (int i = remove_labels; i > 0; --i) {
  466. const Name superdomain(name.split(i));
  467. // Look if there's NS or DNAME at this point of the tree, but ignore
  468. // the NS RRs at the apex of the zone.
  469. const FoundRRsets found = getRRsets(superdomain.toText(),
  470. DELEGATION_TYPES(),
  471. ((options & FIND_DNSSEC) ==
  472. FIND_DNSSEC));
  473. if (found.first) {
  474. // This node contains either NS or DNAME RRs so it does exist.
  475. const FoundIterator nsi(found.second.find(RRType::NS()));
  476. const FoundIterator dni(found.second.find(RRType::DNAME()));
  477. // Note if this is the origin. (We don't count NS records at the
  478. // origin as a delegation so this controls whether NS RRs are
  479. // included in the results of some searches.)
  480. const bool not_origin = (i != remove_labels);
  481. // An optimisation. We know that there is an exact match for
  482. // something at this point in the tree so remember it. If we have
  483. // to do a wildcard search, as we search upwards through the tree
  484. // we don't need to pass this point, which is an exact match for
  485. // the domain name.
  486. last_known = superdomain.getLabelCount();
  487. if (glue_ok && !first_ns && not_origin &&
  488. nsi != found.second.end()) {
  489. // If we are searching for glue ("glue OK" mode), store the
  490. // highest NS record that we find that is not the apex. This
  491. // is another optimisation for later, where we need the
  492. // information if the domain we are looking for matches through
  493. // a wildcard.
  494. first_ns = nsi->second;
  495. } else if (!glue_ok && not_origin && nsi != found.second.end()) {
  496. // Not searching for glue and we have found an NS RRset that is
  497. // not at the apex. We have found a delegation - return that
  498. // fact, there is no need to search further down the tree.
  499. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  500. DATASRC_DATABASE_FOUND_DELEGATION).
  501. arg(accessor_->getDBName()).arg(superdomain);
  502. result_rrset = nsi->second;
  503. result_status = DELEGATION;
  504. break;
  505. } else if (dni != found.second.end()) {
  506. // We have found a DNAME so again stop searching down the tree
  507. // and return the information.
  508. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  509. DATASRC_DATABASE_FOUND_DNAME).
  510. arg(accessor_->getDBName()).arg(superdomain);
  511. result_rrset = dni->second;
  512. result_status = DNAME;
  513. if (result_rrset->getRdataCount() != 1) {
  514. isc_throw(DataSourceError, "DNAME at " << superdomain <<
  515. " has " << result_rrset->getRdataCount() <<
  516. " rdata, 1 expected");
  517. }
  518. break;
  519. }
  520. }
  521. }
  522. return (DelegationSearchResult(result_status, result_rrset, first_ns,
  523. last_known));
  524. }
  525. // This method is called when we have not found an exact match and when we
  526. // know that the name is not an empty non-terminal. So the only way that
  527. // the name can match something in the zone is through a wildcard match.
  528. //
  529. // During an earlier stage in the search for this name, we made a record of
  530. // the lowest superdomain for which we know an RR exists. (Note the "we
  531. // know" qualification - there may be lower superdomains (ones with more
  532. // labels) that hold an RR, but as we weren't searching for them, we don't
  533. // know about them.)
  534. //
  535. // In the search for a wildcard match (which starts at the given domain
  536. // name and goes up the tree to successive superdomains), this is the level
  537. // at which we can stop - there can't be a wildcard at or beyond that
  538. // point.
  539. //
  540. // At each level that can stop the search, we should consider several cases:
  541. //
  542. // - If we found a wildcard match for a glue record below a
  543. // delegation point, we don't return the match,
  544. // instead we return the delegation. (Note that if we didn't
  545. // a wildcard match at all, we would return NXDOMAIN, not the
  546. // the delegation.)
  547. //
  548. // - If we found a wildcard match and we are sure that the match
  549. // is not an empty non-terminal, return the result taking into account CNAME,
  550. // on a zone cut, and NXRRSET.
  551. // (E.g. searching for a match
  552. // for c.b.a.example.com, we found that b.a.example.com did
  553. // not exist but that *.a.example.com. did. Checking
  554. // b.a.example.com revealed no subdomains, so we can use the
  555. // wilcard match we found.)
  556. //
  557. // - If we found a more specified match, the wildcard search
  558. // is canceled, resulting in NXDOMAIN. (E.g. searching for a match
  559. // for c.b.a.example.com, we found that b.a.example.com did
  560. // not exist but that *.a.example.com. did. Checking
  561. // b.a.example.com found subdomains. So b.example.com is
  562. // an empty non-terminal and so should not be returned in
  563. // the wildcard matching process. In other words,
  564. // b.example.com does exist in the DNS space, it just doesn't
  565. // have any RRs associated with it.)
  566. //
  567. // - If we found a match, but it is an empty non-terminal asterisk (E.g.#
  568. // subdomain.*.example.com. is present, but there is nothing at
  569. // *.example.com.), return an NXRRSET indication;
  570. // the wildcard exists in the DNS space, there's just nothing
  571. // associated with it. If DNSSEC data is required, return the
  572. // covering NSEC record.
  573. //
  574. // If none of the above applies in any level, the search fails with NXDOMAIN.
  575. ZoneFinder::ResultContext
  576. DatabaseClient::Finder::findWildcardMatch(
  577. const Name& name, const RRType& type, const FindOptions options,
  578. const DelegationSearchResult& dresult, vector<ConstRRsetPtr>* target,
  579. FindDNSSECContext& dnssec_ctx)
  580. {
  581. // Note that during the search we are going to search not only for the
  582. // requested type, but also for types that indicate a delegation -
  583. // NS and DNAME.
  584. WantedTypes final_types(FINAL_TYPES());
  585. final_types.insert(type);
  586. const size_t remove_labels = name.getLabelCount() - dresult.last_known;
  587. for (size_t i = 1; i <= remove_labels; ++i) {
  588. // Strip off the left-more label(s) in the name and replace with a "*".
  589. const Name superdomain(name.split(i));
  590. const string wildcard("*." + superdomain.toText());
  591. const string construct_name(name.toText());
  592. // TODO Add a check for DNAME, as DNAME wildcards are discouraged (see
  593. // RFC 4592 section 4.4).
  594. // Search for a match. The types are the same as with original query.
  595. const FoundRRsets found = getRRsets(wildcard, final_types,
  596. ((options & FIND_DNSSEC) ==
  597. FIND_DNSSEC),
  598. &construct_name,
  599. type == RRType::ANY());
  600. if (found.first) {
  601. // Found something - but what?
  602. if (dresult.first_ns) {
  603. // About to use first_ns. The only way this can be set is if
  604. // we are searching for glue, so do a sanity check.
  605. if ((options & FIND_GLUE_OK) == 0) {
  606. isc_throw(Unexpected, "Inconsistent conditions during "
  607. "cancel of wilcard search for " <<
  608. name.toText() << ": find_ns non-null when not "
  609. "processing glue request");
  610. }
  611. // Wildcard match for a glue below a delegation point
  612. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  613. DATASRC_DATABASE_WILDCARD_CANCEL_NS).
  614. arg(accessor_->getDBName()).arg(wildcard).
  615. arg(dresult.first_ns->getName());
  616. return (ResultContext(DELEGATION, dresult.first_ns));
  617. } else if (!hasSubdomains(name.split(i - 1).toText())) {
  618. // The wildcard match is the best one, find the final result
  619. // at it. Note that wildcard should never be the zone origin.
  620. return (findOnNameResult(name, type, options, false, found,
  621. &wildcard, target, dnssec_ctx));
  622. } else {
  623. // more specified match found, cancel wildcard match
  624. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  625. DATASRC_DATABASE_WILDCARD_CANCEL_SUB).
  626. arg(accessor_->getDBName()).arg(wildcard).
  627. arg(name).arg(superdomain);
  628. return (ResultContext(NXDOMAIN, ConstRRsetPtr()));
  629. }
  630. } else if (hasSubdomains(wildcard)) {
  631. // an empty non-terminal asterisk
  632. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  633. DATASRC_DATABASE_WILDCARD_EMPTY).
  634. arg(accessor_->getDBName()).arg(wildcard).arg(name);
  635. const FindResultFlags flags = (RESULT_WILDCARD |
  636. dnssec_ctx.getResultFlags());
  637. return (ResultContext(NXRRSET,
  638. dnssec_ctx.getDNSSECRRset(Name(wildcard),
  639. true), flags));
  640. }
  641. }
  642. // Nothing found at any level.
  643. return (ResultContext(NXDOMAIN, ConstRRsetPtr()));
  644. }
  645. ZoneFinder::ResultContext
  646. DatabaseClient::Finder::logAndCreateResult(
  647. const Name& name, const string* wildname, const RRType& type,
  648. ZoneFinder::Result code, ConstRRsetPtr rrset,
  649. const isc::log::MessageID& log_id, FindResultFlags flags) const
  650. {
  651. if (rrset) {
  652. if (wildname == NULL) {
  653. LOG_DEBUG(logger, DBG_TRACE_DETAILED, log_id).
  654. arg(accessor_->getDBName()).arg(name).arg(type).
  655. arg(getClass()).arg(*rrset);
  656. } else {
  657. LOG_DEBUG(logger, DBG_TRACE_DETAILED, log_id).
  658. arg(accessor_->getDBName()).arg(name).arg(type).
  659. arg(getClass()).arg(*wildname).arg(*rrset);
  660. }
  661. } else {
  662. if (wildname == NULL) {
  663. LOG_DEBUG(logger, DBG_TRACE_DETAILED, log_id).
  664. arg(accessor_->getDBName()).arg(name).arg(type).
  665. arg(getClass());
  666. } else {
  667. LOG_DEBUG(logger, DBG_TRACE_DETAILED, log_id).
  668. arg(accessor_->getDBName()).arg(name).arg(type).
  669. arg(getClass()).arg(*wildname);
  670. }
  671. }
  672. return (ResultContext(code, rrset, flags));
  673. }
  674. DatabaseClient::Finder::FindDNSSECContext::FindDNSSECContext(
  675. DatabaseClient::Finder& finder,
  676. const FindOptions options) :
  677. finder_(finder),
  678. need_dnssec_((options & FIND_DNSSEC) != 0),
  679. is_nsec3_(false),
  680. is_nsec_(false),
  681. probed_(false)
  682. {}
  683. void
  684. DatabaseClient::Finder::FindDNSSECContext::probe() {
  685. if (!probed_) {
  686. probed_ = true;
  687. if (need_dnssec_) {
  688. // If an NSEC3PARAM RR exists at the zone apex, it's quite likely
  689. // that the zone is signed with NSEC3. (If not the zone is more
  690. // or less broken, but it's caller's responsibility how to handle
  691. // such cases).
  692. const string origin = finder_.getOrigin().toText();
  693. const FoundRRsets nsec3_found =
  694. finder_.getRRsets(origin, NSEC3PARAM_TYPES(), true);
  695. const FoundIterator nfi=
  696. nsec3_found.second.find(RRType::NSEC3PARAM());
  697. is_nsec3_ = (nfi != nsec3_found.second.end());
  698. // Likewise for NSEC, depending on the apex has an NSEC RR.
  699. // If we know the zone is NSEC3-signed, however, we don't bother
  700. // to check that. This is aligned with the transition guideline
  701. // described in Section 10.4 of RFC 5155.
  702. if (!is_nsec3_) {
  703. const FoundRRsets nsec_found =
  704. finder_.getRRsets(origin, NSEC_TYPES(), true);
  705. const FoundIterator nfi =
  706. nsec_found.second.find(RRType::NSEC());
  707. is_nsec_ = (nfi != nsec_found.second.end());
  708. }
  709. }
  710. }
  711. }
  712. bool
  713. DatabaseClient::Finder::FindDNSSECContext::isNSEC3() {
  714. if (!probed_) {
  715. probe();
  716. }
  717. return (is_nsec3_);
  718. }
  719. bool
  720. DatabaseClient::Finder::FindDNSSECContext::isNSEC() {
  721. if (!probed_) {
  722. probe();
  723. }
  724. return (is_nsec_);
  725. }
  726. isc::dns::ConstRRsetPtr
  727. DatabaseClient::Finder::FindDNSSECContext::getDNSSECRRset(
  728. const FoundRRsets& found_set)
  729. {
  730. if (!isNSEC()) {
  731. return (ConstRRsetPtr());
  732. }
  733. const FoundIterator nci = found_set.second.find(RRType::NSEC());
  734. if (nci != found_set.second.end()) {
  735. return (nci->second);
  736. } else {
  737. return (ConstRRsetPtr());
  738. }
  739. }
  740. isc::dns::ConstRRsetPtr
  741. DatabaseClient::Finder::FindDNSSECContext::getDNSSECRRset(const Name &name,
  742. bool covering)
  743. {
  744. if (!isNSEC()) {
  745. return (ConstRRsetPtr());
  746. }
  747. try {
  748. const Name& nsec_name =
  749. covering ? finder_.findPreviousName(name) : name;
  750. const FoundRRsets found = finder_.getRRsets(nsec_name.toText(),
  751. NSEC_TYPES(), true);
  752. const FoundIterator nci = found.second.find(RRType::NSEC());
  753. if (nci != found.second.end()) {
  754. return (nci->second);
  755. }
  756. } catch (const isc::NotImplemented&) {
  757. // This happens when the underlying database accessor doesn't support
  758. // findPreviousName() (it probably doesn't support DNSSEC at all) but
  759. // there is somehow an NSEC RR at the zone apex. We log the fact but
  760. // otherwise let the caller decide what to do (so, for example, a
  761. // higher level query processing won't completely fail but can return
  762. // anything it can get).
  763. LOG_INFO(logger, DATASRC_DATABASE_COVER_NSEC_UNSUPPORTED).
  764. arg(finder_.accessor_->getDBName()).arg(name);
  765. }
  766. return (ConstRRsetPtr());
  767. }
  768. ZoneFinder::FindResultFlags
  769. DatabaseClient::Finder::FindDNSSECContext::getResultFlags() {
  770. if (isNSEC3()) {
  771. return (RESULT_NSEC3_SIGNED);
  772. } else if (isNSEC()) {
  773. return (RESULT_NSEC_SIGNED);
  774. }
  775. return (RESULT_DEFAULT);
  776. }
  777. ZoneFinder::ResultContext
  778. DatabaseClient::Finder::findOnNameResult(const Name& name,
  779. const RRType& type,
  780. const FindOptions options,
  781. const bool is_origin,
  782. const FoundRRsets& found,
  783. const string* wildname,
  784. std::vector<isc::dns::ConstRRsetPtr>*
  785. target, FindDNSSECContext& dnssec_ctx)
  786. {
  787. const bool wild = (wildname != NULL);
  788. // For wildcard case with DNSSEC required, the caller would need to
  789. // know whether it's NSEC or NSEC3 signed. getResultFlags returns
  790. // appropriate flag based on the query context and zone status.
  791. const FindResultFlags flags =
  792. wild ? (RESULT_WILDCARD | dnssec_ctx.getResultFlags()) : RESULT_DEFAULT;
  793. // Get iterators for the different types of records we are interested in -
  794. // CNAME, NS and Wanted types.
  795. const FoundIterator nsi(found.second.find(RRType::NS()));
  796. const FoundIterator cni(found.second.find(RRType::CNAME()));
  797. const FoundIterator wti(found.second.find(type));
  798. if (!is_origin && (options & FIND_GLUE_OK) == 0 && type != RRType::DS() &&
  799. nsi != found.second.end()) {
  800. // A NS RRset was found at the domain we were searching for. As it is
  801. // not at the origin of the zone, it is a delegation and indicates that
  802. // this zone is not authoritative for the data. Just return the
  803. // delegation information, except:
  804. // - when we are looking for glue records (FIND_GLUE_OK), or
  805. // - when the query type is DS (which cancels the delegation)
  806. return (logAndCreateResult(name, wildname, type, DELEGATION,
  807. nsi->second,
  808. wild ? DATASRC_DATABASE_WILDCARD_NS :
  809. DATASRC_DATABASE_FOUND_DELEGATION_EXACT,
  810. flags));
  811. } else if (type != RRType::CNAME() && cni != found.second.end()) {
  812. // We are not searching for a CNAME but nevertheless we have found one
  813. // at the name we are searching so we return it. (The caller may
  814. // want to continue the lookup by replacing the query name with the
  815. // canonical name and the original RR type.) First though, do a sanity
  816. // check to ensure that there is only one RR in the CNAME RRset.
  817. if (cni->second->getRdataCount() != 1) {
  818. isc_throw(DataSourceError, "CNAME with " <<
  819. cni->second->getRdataCount() << " rdata at " << name <<
  820. ", expected 1");
  821. }
  822. return (logAndCreateResult(name, wildname, type, CNAME, cni->second,
  823. wild ? DATASRC_DATABASE_WILDCARD_CNAME :
  824. DATASRC_DATABASE_FOUND_CNAME,
  825. flags));
  826. } else if (wti != found.second.end()) {
  827. bool any(type == RRType::ANY());
  828. if (any) {
  829. // An ANY query, copy everything to the target instead of returning
  830. // directly.
  831. for (FoundIterator it(found.second.begin());
  832. it != found.second.end(); ++it) {
  833. if (it->second) {
  834. // Skip over the empty ANY
  835. target->push_back(it->second);
  836. }
  837. }
  838. if (wild) {
  839. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  840. DATASRC_DATABASE_WILDCARD_ANY).
  841. arg(accessor_->getDBName()).arg(name);
  842. } else {
  843. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  844. DATASRC_DATABASE_FOUND_ANY).
  845. arg(accessor_->getDBName()).arg(name);
  846. }
  847. } else {
  848. if (wild) {
  849. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  850. DATASRC_DATABASE_WILDCARD_MATCH).
  851. arg(accessor_->getDBName()).arg(*wildname).
  852. arg(wti->second);
  853. } else {
  854. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  855. DATASRC_DATABASE_FOUND_RRSET).
  856. arg(accessor_->getDBName()).arg(*wti->second);
  857. }
  858. }
  859. // Found an RR matching the query, so return it. (Note that this
  860. // includes the case where we were explicitly querying for a CNAME and
  861. // found it. It also includes the case where we were querying for an
  862. // NS RRset and found it at the apex of the zone.)
  863. return (ResultContext(SUCCESS, wti->second, flags));
  864. }
  865. // If we get here, we have found something at the requested name but not
  866. // one of the RR types we were interested in. This is the NXRRSET case so
  867. // return the appropriate status. If DNSSEC information was requested,
  868. // provide the NSEC records. If it's for wildcard, we need to get the
  869. // NSEC records in the name of the wildcard, not the substituted one,
  870. // so we need to search the tree again.
  871. const ConstRRsetPtr dnssec_rrset =
  872. wild ? dnssec_ctx.getDNSSECRRset(Name(*wildname), false) :
  873. dnssec_ctx.getDNSSECRRset(found);
  874. if (dnssec_rrset) {
  875. // This log message covers both normal and wildcard cases, so we pass
  876. // NULL for 'wildname'.
  877. return (logAndCreateResult(name, NULL, type, NXRRSET, dnssec_rrset,
  878. DATASRC_DATABASE_FOUND_NXRRSET_NSEC,
  879. flags | RESULT_NSEC_SIGNED));
  880. }
  881. return (logAndCreateResult(name, wildname, type, NXRRSET, dnssec_rrset,
  882. wild ? DATASRC_DATABASE_WILDCARD_NXRRSET :
  883. DATASRC_DATABASE_FOUND_NXRRSET,
  884. flags | dnssec_ctx.getResultFlags()));
  885. }
  886. ZoneFinder::ResultContext
  887. DatabaseClient::Finder::findNoNameResult(const Name& name, const RRType& type,
  888. FindOptions options,
  889. const DelegationSearchResult& dresult,
  890. std::vector<isc::dns::ConstRRsetPtr>*
  891. target, FindDNSSECContext& dnssec_ctx)
  892. {
  893. // On entry to this method, we know that the database doesn't have any
  894. // entry for this name. Before returning NXDOMAIN, we need to check
  895. // for special cases.
  896. if (hasSubdomains(name.toText())) {
  897. // Does the domain have a subdomain (i.e. it is an empty non-terminal)?
  898. // If so, return NXRRSET instead of NXDOMAIN (as although the name does
  899. // not exist in the database, it does exist in the DNS tree).
  900. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  901. DATASRC_DATABASE_FOUND_EMPTY_NONTERMINAL).
  902. arg(accessor_->getDBName()).arg(name);
  903. return (ResultContext(NXRRSET, dnssec_ctx.getDNSSECRRset(name, true),
  904. dnssec_ctx.getResultFlags()));
  905. } else if ((options & NO_WILDCARD) == 0) {
  906. // It's not an empty non-terminal and wildcard matching is not
  907. // disabled, so check for wildcards. If there is a wildcard match
  908. // (i.e. all results except NXDOMAIN) return it; otherwise fall
  909. // through to the NXDOMAIN case below.
  910. const ResultContext wcontext =
  911. findWildcardMatch(name, type, options, dresult, target,
  912. dnssec_ctx);
  913. if (wcontext.code != NXDOMAIN) {
  914. return (wcontext);
  915. }
  916. }
  917. // All avenues to find a match are now exhausted, return NXDOMAIN (plus
  918. // NSEC records if requested).
  919. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_NO_MATCH).
  920. arg(accessor_->getDBName()).arg(name).arg(type).arg(getClass());
  921. return (ResultContext(NXDOMAIN, dnssec_ctx.getDNSSECRRset(name, true),
  922. dnssec_ctx.getResultFlags()));
  923. }
  924. ZoneFinder::ResultContext
  925. DatabaseClient::Finder::findInternal(const Name& name, const RRType& type,
  926. std::vector<ConstRRsetPtr>* target,
  927. const FindOptions options)
  928. {
  929. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_FIND_RECORDS)
  930. .arg(accessor_->getDBName()).arg(name).arg(type).arg(getClass());
  931. // find() variants generally expect 'name' to be included in the zone.
  932. // Otherwise the search algorithm below won't work correctly, so we
  933. // reject the unexpected case first.
  934. const NameComparisonResult::NameRelation reln =
  935. name.compare(getOrigin()).getRelation();
  936. if (reln != NameComparisonResult::SUBDOMAIN &&
  937. reln != NameComparisonResult::EQUAL) {
  938. isc_throw(OutOfZone, name.toText() << " not in " << getOrigin());
  939. }
  940. // First, go through all superdomains from the origin down, searching for
  941. // nodes that indicate a delegation (i.e. NS or DNAME, ignoring NS records
  942. // at the apex). If one is found, the search stops there.
  943. //
  944. // (In fact there could be RRs in the database corresponding to subdomains
  945. // of the delegation. The reason we do the search for the delegations
  946. // first is because the delegation means that another zone is authoritative
  947. // for the data and so should be consulted to retrieve it. RRs below
  948. // this delegation point can be found in a search for glue but not
  949. // otherwise; in the latter case they are said to be occluded by the
  950. // presence of the delegation.)
  951. const DelegationSearchResult dresult = findDelegationPoint(name, options);
  952. if (dresult.rrset) {
  953. // In this case no special flags are needed.
  954. return (ResultContext(dresult.code, dresult.rrset));
  955. }
  956. // If there is no delegation, look for the exact match to the request
  957. // name/type/class. However, there are special cases:
  958. // - Requested name has a singleton CNAME record associated with it
  959. // - Requested name is a delegation point (NS only but not at the zone
  960. // apex - DNAME is ignored here as it redirects DNS names subordinate to
  961. // the owner name - the owner name itself is not redirected.)
  962. WantedTypes final_types(FINAL_TYPES());
  963. final_types.insert(type);
  964. const FoundRRsets found = getRRsets(name.toText(), final_types,
  965. ((options & FIND_DNSSEC) ==
  966. FIND_DNSSEC),
  967. NULL, type == RRType::ANY());
  968. FindDNSSECContext dnssec_ctx(*this, options);
  969. if (found.first) {
  970. // Something found at the domain name. Look into it further to get
  971. // the final result.
  972. const bool is_origin = (name == getOrigin());
  973. return (findOnNameResult(name, type, options, is_origin, found, NULL,
  974. target, dnssec_ctx));
  975. } else {
  976. // Did not find anything at all at the domain name, so check for
  977. // subdomains or wildcards.
  978. return (findNoNameResult(name, type, options, dresult, target,
  979. dnssec_ctx));
  980. }
  981. }
  982. // The behaviour is inspired by the one in the in-memory implementation.
  983. ZoneFinder::FindNSEC3Result
  984. DatabaseClient::Finder::findNSEC3(const Name& name, bool recursive) {
  985. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_DATABASE_FINDNSEC3).arg(name).
  986. arg(recursive ? "recursive" : "non-recursive");
  987. // First, validate the input
  988. const NameComparisonResult cmp_result(name.compare(getOrigin()));
  989. if (cmp_result.getRelation() != NameComparisonResult::EQUAL &&
  990. cmp_result.getRelation() != NameComparisonResult::SUBDOMAIN) {
  991. isc_throw(OutOfZone, "findNSEC3 attempt for out-of-zone name: " <<
  992. name << ", zone: " << getOrigin() << "/" << getClass());
  993. }
  994. // Now, we need to get the NSEC3 params from the apex and create the hash
  995. // creator for it.
  996. const FoundRRsets nsec3param(getRRsets(getOrigin().toText(),
  997. NSEC3PARAM_TYPES(),
  998. true));
  999. const FoundIterator param(nsec3param.second.find(RRType::NSEC3PARAM()));
  1000. if (!nsec3param.first || param == nsec3param.second.end()) {
  1001. // No NSEC3 params? :-(
  1002. isc_throw(DataSourceError, "findNSEC3 attempt for non NSEC3 signed " <<
  1003. "zone: " << getOrigin() << "/" << getClass());
  1004. }
  1005. // This takes the RRset received from the find method, takes the first RR
  1006. // in it, casts it to NSEC3PARAM (as it should be that one) and then creates
  1007. // the hash calculator class from it.
  1008. const scoped_ptr<NSEC3Hash> calculator(NSEC3Hash::create(
  1009. dynamic_cast<const generic::NSEC3PARAM&>(
  1010. param->second->getRdataIterator()->getCurrent())));
  1011. // Few shortcut variables
  1012. const unsigned olabels(getOrigin().getLabelCount());
  1013. const unsigned qlabels(name.getLabelCount());
  1014. const string otext(getOrigin().toText());
  1015. // This will be set to the one covering the query name
  1016. ConstRRsetPtr covering_proof;
  1017. // We keep stripping the leftmost label until we find something.
  1018. // In case it is recursive, we'll exit the loop at the first iteration.
  1019. for (unsigned labels(qlabels); labels >= olabels; -- labels) {
  1020. const string hash(calculator->calculate(labels == qlabels ? name :
  1021. name.split(qlabels - labels,
  1022. labels)));
  1023. // Get the exact match for the name.
  1024. LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_DATABASE_FINDNSEC3_TRYHASH).
  1025. arg(name).arg(labels).arg(hash);
  1026. DatabaseAccessor::IteratorContextPtr
  1027. context(accessor_->getNSEC3Records(hash, zone_id_));
  1028. if (!context) {
  1029. isc_throw(Unexpected, "Iterator context null for hash " + hash);
  1030. }
  1031. const FoundRRsets nsec3(getRRsets(hash + "." + otext, NSEC3_TYPES(),
  1032. true,
  1033. NULL, false, context));
  1034. if (nsec3.first) {
  1035. // We found an exact match against the current label.
  1036. const FoundIterator it(nsec3.second.find(RRType::NSEC3()));
  1037. if (it == nsec3.second.end()) {
  1038. isc_throw(DataSourceError, "Hash " + hash +
  1039. "exists, but no NSEC3 there");
  1040. }
  1041. LOG_DEBUG(logger, DBG_TRACE_BASIC,
  1042. DATASRC_DATABASE_FINDNSEC3_MATCH).arg(name).arg(labels).
  1043. arg(*it->second);
  1044. // Yes, we win
  1045. return (FindNSEC3Result(true, labels, it->second, covering_proof));
  1046. } else {
  1047. // There's no exact match. We try a previous one. We must find it
  1048. // (if the zone is properly signed).
  1049. const string prevHash(accessor_->findPreviousNSEC3Hash(zone_id_,
  1050. hash));
  1051. LOG_DEBUG(logger, DBG_TRACE_BASIC,
  1052. DATASRC_DATABASE_FINDNSEC3_TRYHASH_PREV).arg(name).
  1053. arg(labels).arg(prevHash);
  1054. context = accessor_->getNSEC3Records(prevHash, zone_id_);
  1055. const FoundRRsets prev_nsec3(getRRsets(prevHash + "." + otext,
  1056. NSEC3_TYPES(), true,
  1057. NULL, false,
  1058. context));
  1059. if (!prev_nsec3.first) {
  1060. isc_throw(DataSourceError, "Hash " + prevHash + " returned "
  1061. "from findPreviousNSEC3Hash, but it is empty");
  1062. }
  1063. const FoundIterator
  1064. prev_it(prev_nsec3.second.find(RRType::NSEC3()));
  1065. if (prev_it == prev_nsec3.second.end()) {
  1066. isc_throw(DataSourceError, "The previous hash " + prevHash +
  1067. "exists, but does not contain the NSEC3");
  1068. }
  1069. covering_proof = prev_it->second;
  1070. // In case it is recursive, we try to get an exact match a level
  1071. // up. If it is not recursive, the caller is ok with a covering
  1072. // one, so we just return it.
  1073. if (!recursive) {
  1074. LOG_DEBUG(logger, DBG_TRACE_BASIC,
  1075. DATASRC_DATABASE_FINDNSEC3_COVER).arg(name).
  1076. arg(labels).arg(*covering_proof);
  1077. return (FindNSEC3Result(false, labels, covering_proof,
  1078. ConstRRsetPtr()));
  1079. }
  1080. }
  1081. }
  1082. // The zone must contain at least the apex and that one should match
  1083. // exactly. If that doesn't happen, we have a problem.
  1084. isc_throw(DataSourceError, "recursive findNSEC3 mode didn't stop, likely a "
  1085. "broken NSEC3 zone: " << otext << "/" << getClass());
  1086. }
  1087. Name
  1088. DatabaseClient::Finder::findPreviousName(const Name& name) const {
  1089. const string str(accessor_->findPreviousName(zone_id_,
  1090. name.reverse().toText()));
  1091. try {
  1092. return (Name(str));
  1093. } catch (const isc::dns::NameParserException&) {
  1094. isc_throw(DataSourceError, "Bad name " + str +
  1095. " from findPreviousName");
  1096. }
  1097. }
  1098. Name
  1099. DatabaseClient::Finder::getOrigin() const {
  1100. return (origin_);
  1101. }
  1102. isc::dns::RRClass
  1103. DatabaseClient::Finder::getClass() const {
  1104. // TODO Implement
  1105. return isc::dns::RRClass::IN();
  1106. }
  1107. namespace {
  1108. /// This needs, beside of converting all data from textual representation, group
  1109. /// together rdata of the same RRsets. To do this, we hold one row of data ahead
  1110. /// of iteration. When we get a request to provide data, we create it from this
  1111. /// data and load a new one. If it is to be put to the same rrset, we add it.
  1112. /// Otherwise we just return what we have and keep the row as the one ahead
  1113. /// for next time.
  1114. class DatabaseIterator : public ZoneIterator {
  1115. public:
  1116. DatabaseIterator(boost::shared_ptr<DatabaseAccessor> accessor,
  1117. const Name& zone_name,
  1118. const RRClass& rrclass,
  1119. bool separate_rrs) :
  1120. accessor_(accessor),
  1121. class_(rrclass),
  1122. ready_(true),
  1123. separate_rrs_(separate_rrs)
  1124. {
  1125. // Get the zone
  1126. const pair<bool, int> zone(accessor_->getZone(zone_name.toText()));
  1127. if (!zone.first) {
  1128. // No such zone, can't continue
  1129. isc_throw(DataSourceError, "Zone " + zone_name.toText() +
  1130. " can not be iterated, because it doesn't exist "
  1131. "in this data source");
  1132. }
  1133. // Start a separate transaction.
  1134. accessor_->startTransaction();
  1135. // Find the SOA of the zone (may or may not succeed). Note that
  1136. // this must be done before starting the iteration context.
  1137. soa_ = DatabaseClient::Finder(accessor_, zone.second, zone_name).
  1138. find(zone_name, RRType::SOA())->rrset;
  1139. // Request the context
  1140. context_ = accessor_->getAllRecords(zone.second);
  1141. // It must not return NULL, that's a bug of the implementation
  1142. if (!context_) {
  1143. isc_throw(isc::Unexpected, "Iterator context null at " +
  1144. zone_name.toText());
  1145. }
  1146. // Prepare data for the next time
  1147. getData();
  1148. }
  1149. virtual ~DatabaseIterator() {
  1150. if (ready_) {
  1151. accessor_->commit();
  1152. }
  1153. }
  1154. virtual ConstRRsetPtr getSOA() const {
  1155. return (soa_);
  1156. }
  1157. virtual isc::dns::ConstRRsetPtr getNextRRset() {
  1158. if (!ready_) {
  1159. isc_throw(isc::Unexpected, "Iterating past the zone end");
  1160. }
  1161. if (!data_ready_) {
  1162. // At the end of zone
  1163. accessor_->commit();
  1164. ready_ = false;
  1165. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE_END);
  1166. return (ConstRRsetPtr());
  1167. }
  1168. const RRType rtype(rtype_txt_);
  1169. RRsetPtr rrset(new RRset(Name(name_txt_), class_, rtype,
  1170. RRTTL(ttl_txt_)));
  1171. // Remember the first RDATA of the RRset for comparison:
  1172. const ConstRdataPtr rdata_base = rdata_;
  1173. while (true) {
  1174. // Extend the RRset with the new RDATA.
  1175. rrset->addRdata(rdata_);
  1176. // Retrieve the next record from the database. If we reach the
  1177. // end of the zone, done; if we were requested to separate all RRs,
  1178. // just remember this record and return the single RR.
  1179. getData();
  1180. if (separate_rrs_ || !data_ready_) {
  1181. break;
  1182. }
  1183. // Check if the next record belongs to the same RRset. If not,
  1184. // we are done. The next RDATA has been stored in rdata_, which
  1185. // is used within this loop (if it belongs to the same RRset) or
  1186. // in the next call.
  1187. if (Name(name_txt_) != rrset->getName() ||
  1188. !isSameType(rtype, rdata_base, RRType(rtype_txt_), rdata_)) {
  1189. break;
  1190. }
  1191. // Adjust TTL if necessary
  1192. const RRTTL next_ttl(ttl_txt_);
  1193. if (next_ttl != rrset->getTTL()) {
  1194. if (next_ttl < rrset->getTTL()) {
  1195. rrset->setTTL(next_ttl);
  1196. }
  1197. LOG_WARN(logger, DATASRC_DATABASE_ITERATE_TTL_MISMATCH).
  1198. arg(name_txt_).arg(class_).arg(rtype).arg(rrset->getTTL());
  1199. }
  1200. }
  1201. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE_NEXT).
  1202. arg(rrset->getName()).arg(rrset->getType());
  1203. return (rrset);
  1204. }
  1205. private:
  1206. // Check two RDATA types are equivalent. Basically it's a trivial
  1207. // comparison, but if both are of RRSIG, we should also compare the types
  1208. // covered.
  1209. static bool isSameType(RRType type1, ConstRdataPtr rdata1,
  1210. RRType type2, ConstRdataPtr rdata2)
  1211. {
  1212. if (type1 != type2) {
  1213. return (false);
  1214. }
  1215. if (type1 == RRType::RRSIG()) {
  1216. return (dynamic_cast<const generic::RRSIG&>(*rdata1).typeCovered()
  1217. == dynamic_cast<const generic::RRSIG&>(*rdata2).
  1218. typeCovered());
  1219. }
  1220. return (true);
  1221. }
  1222. // Load next row of data
  1223. void getData() {
  1224. string data[DatabaseAccessor::COLUMN_COUNT];
  1225. data_ready_ = context_->getNext(data);
  1226. if (data_ready_) {
  1227. name_txt_ = data[DatabaseAccessor::NAME_COLUMN];
  1228. rtype_txt_ = data[DatabaseAccessor::TYPE_COLUMN];
  1229. ttl_txt_ = data[DatabaseAccessor::TTL_COLUMN];
  1230. rdata_ = rdata::createRdata(RRType(rtype_txt_), class_,
  1231. data[DatabaseAccessor::RDATA_COLUMN]);
  1232. }
  1233. }
  1234. // The dedicated accessor
  1235. boost::shared_ptr<DatabaseAccessor> accessor_;
  1236. // The context
  1237. DatabaseAccessor::IteratorContextPtr context_;
  1238. // Class of the zone
  1239. const RRClass class_;
  1240. // SOA of the zone, if any (it should normally exist)
  1241. ConstRRsetPtr soa_;
  1242. // Status
  1243. bool ready_, data_ready_;
  1244. // Data of the next row
  1245. string name_txt_, rtype_txt_, ttl_txt_;
  1246. // RDATA of the next row
  1247. ConstRdataPtr rdata_;
  1248. // Whether to modify differing TTL values, or treat a different TTL as
  1249. // a different RRset
  1250. const bool separate_rrs_;
  1251. };
  1252. }
  1253. ZoneIteratorPtr
  1254. DatabaseClient::getIterator(const isc::dns::Name& name,
  1255. bool separate_rrs) const
  1256. {
  1257. ZoneIteratorPtr iterator = ZoneIteratorPtr(new DatabaseIterator(
  1258. accessor_->clone(), name,
  1259. rrclass_, separate_rrs));
  1260. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ITERATE).
  1261. arg(name);
  1262. return (iterator);
  1263. }
  1264. /// \brief Database implementation of RRsetCollectionBase.
  1265. class RRsetCollection : public isc::datasrc::RRsetCollectionBase {
  1266. public:
  1267. /// \brief Constructor.
  1268. RRsetCollection(ZoneUpdater& updater, const isc::dns::RRClass& rrclass) :
  1269. isc::datasrc::RRsetCollectionBase(updater, rrclass)
  1270. {}
  1271. /// \brief A wrapper around \c disable() so that it can be used as a
  1272. /// public method. \c disable() is protected.
  1273. void disableWrapper() {
  1274. disable();
  1275. }
  1276. };
  1277. //
  1278. // Zone updater using some database system as the underlying data source.
  1279. //
  1280. class DatabaseUpdater : public ZoneUpdater {
  1281. public:
  1282. DatabaseUpdater(boost::shared_ptr<DatabaseAccessor> accessor, int zone_id,
  1283. const Name& zone_name, const RRClass& zone_class,
  1284. bool journaling) :
  1285. committed_(false), accessor_(accessor), zone_id_(zone_id),
  1286. db_name_(accessor->getDBName()), zone_name_(zone_name.toText()),
  1287. zone_class_(zone_class), journaling_(journaling),
  1288. diff_phase_(NOT_STARTED), serial_(0),
  1289. finder_(new DatabaseClient::Finder(accessor_, zone_id_, zone_name))
  1290. {
  1291. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_CREATED)
  1292. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  1293. }
  1294. virtual ~DatabaseUpdater() {
  1295. if (!committed_) {
  1296. try {
  1297. accessor_->rollback();
  1298. logger.info(DATASRC_DATABASE_UPDATER_ROLLBACK)
  1299. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  1300. } catch (const DataSourceError& e) {
  1301. // See The destructor ~TransactionHolder() for the
  1302. // reason to catch this.
  1303. logger.error(DATASRC_DATABASE_UPDATER_ROLLBACKFAIL)
  1304. .arg(zone_name_).arg(zone_class_).arg(db_name_)
  1305. .arg(e.what());
  1306. }
  1307. }
  1308. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_DESTROYED)
  1309. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  1310. }
  1311. virtual ZoneFinder& getFinder() { return (*finder_); }
  1312. virtual isc::dns::RRsetCollectionBase& getRRsetCollection() {
  1313. if (!rrset_collection_) {
  1314. // This is only assigned the first time and remains for the
  1315. // lifetime of the DatabaseUpdater.
  1316. rrset_collection_.reset(new RRsetCollection(*this, zone_class_));
  1317. }
  1318. return (*rrset_collection_);
  1319. }
  1320. virtual void addRRset(const AbstractRRset& rrset);
  1321. virtual void deleteRRset(const AbstractRRset& rrset);
  1322. virtual void commit();
  1323. private:
  1324. // A short cut typedef only for making the code shorter.
  1325. typedef DatabaseAccessor Accessor;
  1326. bool committed_;
  1327. boost::shared_ptr<DatabaseAccessor> accessor_;
  1328. const int zone_id_;
  1329. const string db_name_;
  1330. const string zone_name_;
  1331. const RRClass zone_class_;
  1332. const bool journaling_;
  1333. // For the journals
  1334. enum DiffPhase {
  1335. NOT_STARTED,
  1336. DELETE,
  1337. ADD
  1338. };
  1339. DiffPhase diff_phase_;
  1340. Serial serial_;
  1341. boost::scoped_ptr<DatabaseClient::Finder> finder_;
  1342. boost::shared_ptr<isc::datasrc::RRsetCollection> rrset_collection_;
  1343. // This is a set of validation checks commonly used for addRRset() and
  1344. // deleteRRset to minimize duplicate code logic and to make the main
  1345. // code concise.
  1346. void validateAddOrDelete(const char* const op_str,
  1347. const AbstractRRset& rrset,
  1348. DiffPhase prev_phase,
  1349. DiffPhase current_phase) const;
  1350. };
  1351. void
  1352. DatabaseUpdater::validateAddOrDelete(const char* const op_str,
  1353. const AbstractRRset& rrset,
  1354. DiffPhase prev_phase,
  1355. DiffPhase current_phase) const
  1356. {
  1357. if (committed_) {
  1358. isc_throw(DataSourceError, op_str << " attempt after commit to zone: "
  1359. << zone_name_ << "/" << zone_class_);
  1360. }
  1361. if (rrset.getRdataCount() == 0) {
  1362. isc_throw(DataSourceError, op_str << " attempt with an empty RRset: "
  1363. << rrset.getName() << "/" << zone_class_ << "/"
  1364. << rrset.getType());
  1365. }
  1366. if (rrset.getClass() != zone_class_) {
  1367. isc_throw(DataSourceError, op_str << " attempt for a different class "
  1368. << zone_name_ << "/" << zone_class_ << ": "
  1369. << rrset.toText());
  1370. }
  1371. if (rrset.getRRsig()) {
  1372. isc_throw(DataSourceError, op_str << " attempt for RRset with RRSIG "
  1373. << zone_name_ << "/" << zone_class_ << ": "
  1374. << rrset.toText());
  1375. }
  1376. if (journaling_) {
  1377. const RRType rrtype(rrset.getType());
  1378. if (rrtype == RRType::SOA() && diff_phase_ != prev_phase) {
  1379. isc_throw(isc::BadValue, op_str << " attempt in an invalid "
  1380. << "diff phase: " << diff_phase_ << ", rrset: " <<
  1381. rrset.toText());
  1382. }
  1383. if (rrtype != RRType::SOA() && diff_phase_ != current_phase) {
  1384. isc_throw(isc::BadValue, "diff state change by non SOA: "
  1385. << rrset.toText());
  1386. }
  1387. }
  1388. }
  1389. // This is a helper class used in adding/deleting RRsets to/from a database.
  1390. // The purpose of this class is to provide conversion interface from various
  1391. // parameters of the RRset to corresponding textual representations that the
  1392. // underlying database interface expects. The necessary parameters and how
  1393. // to convert them depend on several things, such as whether it's NSEC3 related
  1394. // or not, or whether journaling is requested. In order to avoid unnecessary
  1395. // conversion, this class also performs the conversion in a lazy manner.
  1396. // Also, in order to avoid redundant conversion when the conversion is
  1397. // requested for the same parameter multiple times, it remembers the
  1398. // conversion result first time, and reuses it for subsequent requests
  1399. // (this implicitly assumes copying std::string objects is not very expensive;
  1400. // this is often the case in some common implementations that have
  1401. // copy-on-write semantics for the string class).
  1402. class RRParameterConverter {
  1403. public:
  1404. RRParameterConverter(const AbstractRRset& rrset) : rrset_(rrset)
  1405. {}
  1406. const string& getName() {
  1407. if (name_.empty()) {
  1408. name_ = rrset_.getName().toText();
  1409. }
  1410. return (name_);
  1411. }
  1412. const string& getNSEC3Name() {
  1413. if (nsec3_name_.empty()) {
  1414. nsec3_name_ = rrset_.getName().split(0, 1).toText(true);
  1415. }
  1416. return (nsec3_name_);
  1417. }
  1418. const string& getRevName() {
  1419. if (revname_.empty()) {
  1420. revname_ = rrset_.getName().reverse().toText();
  1421. }
  1422. return (revname_);
  1423. }
  1424. const string& getTTL() {
  1425. if (ttl_.empty()) {
  1426. ttl_ = rrset_.getTTL().toText();
  1427. }
  1428. return (ttl_);
  1429. }
  1430. const string& getType() {
  1431. if (type_.empty()) {
  1432. type_ = rrset_.getType().toText();
  1433. }
  1434. return (type_);
  1435. }
  1436. private:
  1437. string name_;
  1438. string nsec3_name_;
  1439. string revname_;
  1440. string ttl_;
  1441. string type_;
  1442. const AbstractRRset& rrset_;
  1443. };
  1444. namespace {
  1445. // A shared shortcut to detect if the given type of RDATA is NSEC3 or
  1446. // RRSIG covering NSEC3. RRSIG for NSEC3 should go to the (conceptual)
  1447. // separate namespace, so we need to check the covered type.
  1448. // Note: in principle the type covered should be the same for
  1449. // all RDATA, but the RRset interface doesn't ensure that condition.
  1450. // So we explicitly check that for every RDATA below.
  1451. bool
  1452. isNSEC3KindType(RRType rrtype, const Rdata& rdata) {
  1453. if (rrtype == RRType::NSEC3()) {
  1454. return (true);
  1455. }
  1456. if (rrtype == RRType::RRSIG() &&
  1457. dynamic_cast<const generic::RRSIG&>(rdata).typeCovered() ==
  1458. RRType::NSEC3())
  1459. {
  1460. return (true);
  1461. }
  1462. return (false);
  1463. }
  1464. }
  1465. void
  1466. DatabaseUpdater::addRRset(const AbstractRRset& rrset) {
  1467. if (rrset_collection_) {
  1468. isc_throw(InvalidOperation,
  1469. "Cannot add RRset after an RRsetCollection has been "
  1470. "requested for ZoneUpdater for "
  1471. << zone_name_ << "/" << zone_class_ << " on "
  1472. << db_name_);
  1473. }
  1474. validateAddOrDelete("add", rrset, DELETE, ADD);
  1475. // It's guaranteed rrset has at least one RDATA at this point.
  1476. RdataIteratorPtr it = rrset.getRdataIterator();
  1477. if (journaling_) {
  1478. diff_phase_ = ADD;
  1479. if (rrset.getType() == RRType::SOA()) {
  1480. serial_ = dynamic_cast<const generic::SOA&>(it->getCurrent()).
  1481. getSerial();
  1482. }
  1483. }
  1484. RRParameterConverter cvtr(rrset);
  1485. for (; !it->isLast(); it->next()) {
  1486. const Rdata& rdata = it->getCurrent();
  1487. const bool nsec3_type = isNSEC3KindType(rrset.getType(), rdata);
  1488. string sigtype;
  1489. if (rrset.getType() == RRType::RRSIG()) {
  1490. // XXX: the current interface (based on the current sqlite3
  1491. // data source schema) requires a separate "sigtype" column,
  1492. // even though it won't be used in a newer implementation.
  1493. // We should eventually clean up the schema design and simplify
  1494. // the interface, but until then we have to conform to the schema.
  1495. sigtype = dynamic_cast<const generic::RRSIG&>(rdata).
  1496. typeCovered().toText();
  1497. }
  1498. const string& rdata_txt = rdata.toText();
  1499. if (journaling_) {
  1500. const string journal[Accessor::DIFF_PARAM_COUNT] =
  1501. { cvtr.getName(), cvtr.getType(), cvtr.getTTL(), rdata_txt };
  1502. accessor_->addRecordDiff(zone_id_, serial_.getValue(),
  1503. Accessor::DIFF_ADD, journal);
  1504. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ADDDIFF).
  1505. arg(cvtr.getName()).arg(cvtr.getType()).arg(rdata_txt);
  1506. }
  1507. if (nsec3_type) {
  1508. const string nsec3_columns[Accessor::ADD_NSEC3_COLUMN_COUNT] =
  1509. { cvtr.getNSEC3Name(), cvtr.getTTL(), cvtr.getType(),
  1510. rdata_txt };
  1511. accessor_->addNSEC3RecordToZone(nsec3_columns);
  1512. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ADDNSEC3).
  1513. arg(cvtr.getNSEC3Name()).arg(rdata_txt);
  1514. } else {
  1515. const string columns[Accessor::ADD_COLUMN_COUNT] =
  1516. { cvtr.getName(), cvtr.getRevName(), cvtr.getTTL(),
  1517. cvtr.getType(), sigtype, rdata_txt };
  1518. accessor_->addRecordToZone(columns);
  1519. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_ADDRR).
  1520. arg(cvtr.getName()).arg(cvtr.getType()).arg(rdata_txt);
  1521. }
  1522. }
  1523. }
  1524. void
  1525. DatabaseUpdater::deleteRRset(const AbstractRRset& rrset) {
  1526. if (rrset_collection_) {
  1527. isc_throw(InvalidOperation,
  1528. "Cannot delete RRset after an RRsetCollection has been "
  1529. "requested for ZoneUpdater for "
  1530. << zone_name_ << "/" << zone_class_ << " on "
  1531. << db_name_);
  1532. }
  1533. // If this is the first operation, pretend we are starting a new delete
  1534. // sequence after adds. This will simplify the validation below.
  1535. if (diff_phase_ == NOT_STARTED) {
  1536. diff_phase_ = ADD;
  1537. }
  1538. validateAddOrDelete("delete", rrset, ADD, DELETE);
  1539. RdataIteratorPtr it = rrset.getRdataIterator();
  1540. if (journaling_) {
  1541. diff_phase_ = DELETE;
  1542. if (rrset.getType() == RRType::SOA()) {
  1543. serial_ =
  1544. dynamic_cast<const generic::SOA&>(it->getCurrent()).
  1545. getSerial();
  1546. }
  1547. }
  1548. RRParameterConverter cvtr(rrset);
  1549. for (; !it->isLast(); it->next()) {
  1550. const Rdata& rdata = it->getCurrent();
  1551. const bool nsec3_type = isNSEC3KindType(rrset.getType(), rdata);
  1552. const string& rdata_txt = it->getCurrent().toText();
  1553. if (journaling_) {
  1554. const string journal[Accessor::DIFF_PARAM_COUNT] =
  1555. { cvtr.getName(), cvtr.getType(), cvtr.getTTL(), rdata_txt };
  1556. accessor_->addRecordDiff(zone_id_, serial_.getValue(),
  1557. Accessor::DIFF_DELETE, journal);
  1558. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_DELETEDIFF).
  1559. arg(cvtr.getName()).arg(cvtr.getType()).arg(rdata_txt);
  1560. }
  1561. if (nsec3_type) {
  1562. const string params[Accessor::DEL_NSEC3_PARAM_COUNT] =
  1563. { cvtr.getNSEC3Name(), cvtr.getType(), rdata_txt };
  1564. accessor_->deleteNSEC3RecordInZone(params);
  1565. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_DELETENSEC3).
  1566. arg(cvtr.getNSEC3Name()).arg(rdata_txt);
  1567. } else {
  1568. const string params[Accessor::DEL_PARAM_COUNT] =
  1569. { cvtr.getName(), cvtr.getType(), rdata_txt,
  1570. cvtr.getRevName() };
  1571. accessor_->deleteRecordInZone(params);
  1572. LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_DATABASE_DELETERR).
  1573. arg(cvtr.getName()).arg(cvtr.getType()).arg(rdata_txt);
  1574. }
  1575. }
  1576. }
  1577. void
  1578. DatabaseUpdater::commit() {
  1579. if (committed_) {
  1580. isc_throw(DataSourceError, "Duplicate commit attempt for "
  1581. << zone_name_ << "/" << zone_class_ << " on "
  1582. << db_name_);
  1583. }
  1584. if (journaling_ && diff_phase_ == DELETE) {
  1585. isc_throw(isc::BadValue, "Update sequence not complete");
  1586. }
  1587. accessor_->commit();
  1588. committed_ = true; // make sure the destructor won't trigger rollback
  1589. // Disable the RRsetCollection if it exists.
  1590. if (rrset_collection_) {
  1591. rrset_collection_->disableWrapper();
  1592. }
  1593. // We release the accessor immediately after commit is completed so that
  1594. // we don't hold the possible internal resource any longer.
  1595. accessor_.reset();
  1596. logger.debug(DBG_TRACE_DATA, DATASRC_DATABASE_UPDATER_COMMIT)
  1597. .arg(zone_name_).arg(zone_class_).arg(db_name_);
  1598. }
  1599. // The updater factory
  1600. ZoneUpdaterPtr
  1601. DatabaseClient::getUpdater(const isc::dns::Name& name, bool replace,
  1602. bool journaling) const
  1603. {
  1604. if (replace && journaling) {
  1605. isc_throw(isc::BadValue, "Can't store journal and replace the whole "
  1606. "zone at the same time");
  1607. }
  1608. boost::shared_ptr<DatabaseAccessor> update_accessor(accessor_->clone());
  1609. const std::pair<bool, int> zone(update_accessor->startUpdateZone(
  1610. name.toText(), replace));
  1611. if (!zone.first) {
  1612. return (ZoneUpdaterPtr());
  1613. }
  1614. return (ZoneUpdaterPtr(new DatabaseUpdater(update_accessor, zone.second,
  1615. name, rrclass_, journaling)));
  1616. }
  1617. //
  1618. // Zone journal reader using some database system as the underlying data
  1619. // source.
  1620. //
  1621. class DatabaseJournalReader : public ZoneJournalReader {
  1622. private:
  1623. // A shortcut typedef to keep the code concise.
  1624. typedef DatabaseAccessor Accessor;
  1625. public:
  1626. DatabaseJournalReader(boost::shared_ptr<Accessor> accessor, const Name& zone,
  1627. int zone_id, const RRClass& rrclass, uint32_t begin,
  1628. uint32_t end) :
  1629. accessor_(accessor), zone_(zone), rrclass_(rrclass),
  1630. begin_(begin), end_(end), finished_(false)
  1631. {
  1632. context_ = accessor_->getDiffs(zone_id, begin, end);
  1633. }
  1634. virtual ~DatabaseJournalReader() {}
  1635. virtual ConstRRsetPtr getNextDiff() {
  1636. if (finished_) {
  1637. isc_throw(InvalidOperation,
  1638. "Diff read attempt past the end of sequence on "
  1639. << accessor_->getDBName());
  1640. }
  1641. string data[Accessor::COLUMN_COUNT];
  1642. if (!context_->getNext(data)) {
  1643. finished_ = true;
  1644. LOG_DEBUG(logger, DBG_TRACE_BASIC,
  1645. DATASRC_DATABASE_JOURNALREADER_END).
  1646. arg(zone_).arg(rrclass_).arg(accessor_->getDBName()).
  1647. arg(begin_).arg(end_);
  1648. return (ConstRRsetPtr());
  1649. }
  1650. try {
  1651. RRsetPtr rrset(new RRset(Name(data[Accessor::NAME_COLUMN]),
  1652. rrclass_,
  1653. RRType(data[Accessor::TYPE_COLUMN]),
  1654. RRTTL(data[Accessor::TTL_COLUMN])));
  1655. rrset->addRdata(rdata::createRdata(rrset->getType(), rrclass_,
  1656. data[Accessor::RDATA_COLUMN]));
  1657. LOG_DEBUG(logger, DBG_TRACE_DETAILED,
  1658. DATASRC_DATABASE_JOURNALREADER_NEXT).
  1659. arg(rrset->getName()).arg(rrset->getType()).
  1660. arg(zone_).arg(rrclass_).arg(accessor_->getDBName());
  1661. return (rrset);
  1662. } catch (const Exception& ex) {
  1663. LOG_ERROR(logger, DATASRC_DATABASE_JOURNALREADER_BADDATA).
  1664. arg(zone_).arg(rrclass_).arg(accessor_->getDBName()).
  1665. arg(begin_).arg(end_).arg(ex.what());
  1666. isc_throw(DataSourceError, "Failed to create RRset from diff on "
  1667. << accessor_->getDBName());
  1668. }
  1669. }
  1670. private:
  1671. boost::shared_ptr<Accessor> accessor_;
  1672. const Name zone_;
  1673. const RRClass rrclass_;
  1674. Accessor::IteratorContextPtr context_;
  1675. const uint32_t begin_;
  1676. const uint32_t end_;
  1677. bool finished_;
  1678. };
  1679. // The JournalReader factory
  1680. pair<ZoneJournalReader::Result, ZoneJournalReaderPtr>
  1681. DatabaseClient::getJournalReader(const isc::dns::Name& zone,
  1682. uint32_t begin_serial,
  1683. uint32_t end_serial) const
  1684. {
  1685. boost::shared_ptr<DatabaseAccessor> jnl_accessor(accessor_->clone());
  1686. const pair<bool, int> zoneinfo(jnl_accessor->getZone(zone.toText()));
  1687. if (!zoneinfo.first) {
  1688. return (pair<ZoneJournalReader::Result, ZoneJournalReaderPtr>(
  1689. ZoneJournalReader::NO_SUCH_ZONE,
  1690. ZoneJournalReaderPtr()));
  1691. }
  1692. try {
  1693. const pair<ZoneJournalReader::Result, ZoneJournalReaderPtr> ret(
  1694. ZoneJournalReader::SUCCESS,
  1695. ZoneJournalReaderPtr(new DatabaseJournalReader(jnl_accessor,
  1696. zone,
  1697. zoneinfo.second,
  1698. rrclass_,
  1699. begin_serial,
  1700. end_serial)));
  1701. LOG_DEBUG(logger, DBG_TRACE_BASIC,
  1702. DATASRC_DATABASE_JOURNALREADER_START).arg(zone).arg(rrclass_).
  1703. arg(jnl_accessor->getDBName()).arg(begin_serial).arg(end_serial);
  1704. return (ret);
  1705. } catch (const NoSuchSerial&) {
  1706. return (pair<ZoneJournalReader::Result, ZoneJournalReaderPtr>(
  1707. ZoneJournalReader::NO_SUCH_VERSION,
  1708. ZoneJournalReaderPtr()));
  1709. }
  1710. }
  1711. }
  1712. }