database.cc 61 KB

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