database.cc 61 KB

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