auth_srv.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. // Copyright (C) 2009 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 <config.h>
  15. #include <netinet/in.h>
  16. #include <algorithm>
  17. #include <cassert>
  18. #include <iostream>
  19. #include <vector>
  20. #include <memory>
  21. #include <boost/bind.hpp>
  22. #include <asiolink/asiolink.h>
  23. #include <config/ccsession.h>
  24. #include <cc/data.h>
  25. #include <exceptions/exceptions.h>
  26. #include <util/buffer.h>
  27. #include <dns/edns.h>
  28. #include <dns/exceptions.h>
  29. #include <dns/messagerenderer.h>
  30. #include <dns/name.h>
  31. #include <dns/question.h>
  32. #include <dns/opcode.h>
  33. #include <dns/rcode.h>
  34. #include <dns/rrset.h>
  35. #include <dns/rrttl.h>
  36. #include <dns/message.h>
  37. #include <dns/tsig.h>
  38. #include <datasrc/query.h>
  39. #include <datasrc/data_source.h>
  40. #include <datasrc/memory_datasrc.h>
  41. #include <datasrc/static_datasrc.h>
  42. #include <datasrc/sqlite3_datasrc.h>
  43. #include <xfr/xfrout_client.h>
  44. #include <auth/common.h>
  45. #include <auth/auth_config.h>
  46. #include <auth/auth_srv.h>
  47. #include <auth/query.h>
  48. #include <auth/statistics.h>
  49. #include <auth/auth_log.h>
  50. using namespace std;
  51. using namespace isc;
  52. using namespace isc::cc;
  53. using namespace isc::datasrc;
  54. using namespace isc::dns;
  55. using namespace isc::util;
  56. using namespace isc::auth;
  57. using namespace isc::dns::rdata;
  58. using namespace isc::data;
  59. using namespace isc::config;
  60. using namespace isc::xfr;
  61. using namespace isc::asiolink;
  62. using namespace isc::asiodns;
  63. using namespace isc::server_common::portconfig;
  64. using boost::shared_ptr;
  65. class AuthSrvImpl {
  66. private:
  67. // prohibit copy
  68. AuthSrvImpl(const AuthSrvImpl& source);
  69. AuthSrvImpl& operator=(const AuthSrvImpl& source);
  70. public:
  71. AuthSrvImpl(const bool use_cache, AbstractXfroutClient& xfrout_client);
  72. ~AuthSrvImpl();
  73. isc::data::ConstElementPtr setDbFile(isc::data::ConstElementPtr config);
  74. bool processNormalQuery(const IOMessage& io_message, MessagePtr message,
  75. OutputBufferPtr buffer,
  76. auto_ptr<TSIGContext> tsig_context);
  77. bool processAxfrQuery(const IOMessage& io_message, MessagePtr message,
  78. OutputBufferPtr buffer,
  79. auto_ptr<TSIGContext> tsig_context);
  80. bool processNotify(const IOMessage& io_message, MessagePtr message,
  81. OutputBufferPtr buffer,
  82. auto_ptr<TSIGContext> tsig_context);
  83. IOService io_service_;
  84. /// Currently non-configurable, but will be.
  85. static const uint16_t DEFAULT_LOCAL_UDPSIZE = 4096;
  86. /// These members are public because AuthSrv accesses them directly.
  87. ModuleCCSession* config_session_;
  88. AbstractSession* xfrin_session_;
  89. /// In-memory data source. Currently class IN only for simplicity.
  90. const RRClass memory_client_class_;
  91. AuthSrv::InMemoryClientPtr memory_client_;
  92. /// Hot spot cache
  93. isc::datasrc::HotCache cache_;
  94. /// Interval timer for periodic submission of statistics counters.
  95. IntervalTimer statistics_timer_;
  96. /// Query counters for statistics
  97. AuthCounters counters_;
  98. /// Addresses we listen on
  99. AddressList listen_addresses_;
  100. /// The TSIG keyring
  101. const shared_ptr<TSIGKeyRing>* keyring_;
  102. /// Bind the ModuleSpec object in config_session_ with
  103. /// isc:config::ModuleSpec::validateStatistics.
  104. void registerStatisticsValidator();
  105. private:
  106. std::string db_file_;
  107. MetaDataSrc data_sources_;
  108. /// We keep a pointer to the currently running sqlite datasource
  109. /// so that we can specifically remove that one should the database
  110. /// file change
  111. ConstDataSrcPtr cur_datasrc_;
  112. bool xfrout_connected_;
  113. AbstractXfroutClient& xfrout_client_;
  114. /// Increment query counter
  115. void incCounter(const int protocol);
  116. // validateStatistics
  117. bool validateStatistics(isc::data::ConstElementPtr data) const;
  118. };
  119. AuthSrvImpl::AuthSrvImpl(const bool use_cache,
  120. AbstractXfroutClient& xfrout_client) :
  121. config_session_(NULL),
  122. xfrin_session_(NULL),
  123. memory_client_class_(RRClass::IN()),
  124. statistics_timer_(io_service_),
  125. counters_(),
  126. keyring_(NULL),
  127. xfrout_connected_(false),
  128. xfrout_client_(xfrout_client)
  129. {
  130. // cur_datasrc_ is automatically initialized by the default constructor,
  131. // effectively being an empty (sqlite) data source. once ccsession is up
  132. // the datasource will be set by the configuration setting
  133. // add static data source
  134. data_sources_.addDataSrc(ConstDataSrcPtr(new StaticDataSrc));
  135. // enable or disable the cache
  136. cache_.setEnabled(use_cache);
  137. }
  138. AuthSrvImpl::~AuthSrvImpl() {
  139. if (xfrout_connected_) {
  140. xfrout_client_.disconnect();
  141. xfrout_connected_ = false;
  142. }
  143. }
  144. // This is a derived class of \c DNSLookup, to serve as a
  145. // callback in the asiolink module. It calls
  146. // AuthSrv::processMessage() on a single DNS message.
  147. class MessageLookup : public DNSLookup {
  148. public:
  149. MessageLookup(AuthSrv* srv) : server_(srv) {}
  150. virtual void operator()(const IOMessage& io_message,
  151. MessagePtr message,
  152. MessagePtr answer_message,
  153. OutputBufferPtr buffer,
  154. DNSServer* server) const
  155. {
  156. (void) answer_message;
  157. server_->processMessage(io_message, message, buffer, server);
  158. }
  159. private:
  160. AuthSrv* server_;
  161. };
  162. // This is a derived class of \c DNSAnswer, to serve as a callback in the
  163. // asiolink module. We actually shouldn't do anything in this class because
  164. // we build complete response messages in the process methods; otherwise
  165. // the response message will contain trailing garbage. In future, we should
  166. // probably even drop the reliance on DNSAnswer. We don't need the coroutine
  167. // tricks provided in that framework, and its overhead would be significant
  168. // in terms of performance consideration for the authoritative server
  169. // implementation.
  170. class MessageAnswer : public DNSAnswer {
  171. public:
  172. MessageAnswer(AuthSrv*) {}
  173. virtual void operator()(const IOMessage&, MessagePtr,
  174. MessagePtr, OutputBufferPtr) const
  175. {}
  176. };
  177. // This is a derived class of \c SimpleCallback, to serve
  178. // as a callback in the asiolink module. It checks for queued
  179. // configuration messages, and executes them if found.
  180. class ConfigChecker : public SimpleCallback {
  181. public:
  182. ConfigChecker(AuthSrv* srv) : server_(srv) {}
  183. virtual void operator()(const IOMessage&) const {
  184. if (server_->getConfigSession()->hasQueuedMsgs()) {
  185. server_->getConfigSession()->checkCommand();
  186. }
  187. }
  188. private:
  189. AuthSrv* server_;
  190. };
  191. AuthSrv::AuthSrv(const bool use_cache, AbstractXfroutClient& xfrout_client) :
  192. impl_(new AuthSrvImpl(use_cache, xfrout_client)),
  193. checkin_(new ConfigChecker(this)),
  194. dns_lookup_(new MessageLookup(this)),
  195. dns_answer_(new MessageAnswer(this))
  196. {}
  197. void
  198. AuthSrv::stop() {
  199. impl_->io_service_.stop();
  200. }
  201. AuthSrv::~AuthSrv() {
  202. delete impl_;
  203. delete checkin_;
  204. delete dns_lookup_;
  205. delete dns_answer_;
  206. }
  207. namespace {
  208. class QuestionInserter {
  209. public:
  210. QuestionInserter(MessagePtr message) : message_(message) {}
  211. void operator()(const QuestionPtr question) {
  212. message_->addQuestion(question);
  213. }
  214. MessagePtr message_;
  215. };
  216. void
  217. makeErrorMessage(MessagePtr message, OutputBufferPtr buffer,
  218. const Rcode& rcode,
  219. std::auto_ptr<TSIGContext> tsig_context =
  220. std::auto_ptr<TSIGContext>())
  221. {
  222. // extract the parameters that should be kept.
  223. // XXX: with the current implementation, it's not easy to set EDNS0
  224. // depending on whether the query had it. So we'll simply omit it.
  225. const qid_t qid = message->getQid();
  226. const bool rd = message->getHeaderFlag(Message::HEADERFLAG_RD);
  227. const bool cd = message->getHeaderFlag(Message::HEADERFLAG_CD);
  228. const Opcode& opcode = message->getOpcode();
  229. vector<QuestionPtr> questions;
  230. // If this is an error to a query or notify, we should also copy the
  231. // question section.
  232. if (opcode == Opcode::QUERY() || opcode == Opcode::NOTIFY()) {
  233. questions.assign(message->beginQuestion(), message->endQuestion());
  234. }
  235. message->clear(Message::RENDER);
  236. message->setQid(qid);
  237. message->setOpcode(opcode);
  238. message->setHeaderFlag(Message::HEADERFLAG_QR);
  239. if (rd) {
  240. message->setHeaderFlag(Message::HEADERFLAG_RD);
  241. }
  242. if (cd) {
  243. message->setHeaderFlag(Message::HEADERFLAG_CD);
  244. }
  245. for_each(questions.begin(), questions.end(), QuestionInserter(message));
  246. message->setRcode(rcode);
  247. MessageRenderer renderer(*buffer);
  248. if (tsig_context.get() != NULL) {
  249. message->toWire(renderer, *tsig_context);
  250. } else {
  251. message->toWire(renderer);
  252. }
  253. LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_SEND_ERROR_RESPONSE)
  254. .arg(renderer.getLength()).arg(*message);
  255. }
  256. }
  257. IOService&
  258. AuthSrv::getIOService() {
  259. return (impl_->io_service_);
  260. }
  261. void
  262. AuthSrv::setCacheSlots(const size_t slots) {
  263. impl_->cache_.setSlots(slots);
  264. }
  265. size_t
  266. AuthSrv::getCacheSlots() const {
  267. return (impl_->cache_.getSlots());
  268. }
  269. void
  270. AuthSrv::setXfrinSession(AbstractSession* xfrin_session) {
  271. impl_->xfrin_session_ = xfrin_session;
  272. }
  273. void
  274. AuthSrv::setConfigSession(ModuleCCSession* config_session) {
  275. impl_->config_session_ = config_session;
  276. impl_->registerStatisticsValidator();
  277. }
  278. void
  279. AuthSrv::setStatisticsSession(AbstractSession* statistics_session) {
  280. impl_->counters_.setStatisticsSession(statistics_session);
  281. }
  282. ModuleCCSession*
  283. AuthSrv::getConfigSession() const {
  284. return (impl_->config_session_);
  285. }
  286. AuthSrv::InMemoryClientPtr
  287. AuthSrv::getInMemoryClient(const RRClass& rrclass) {
  288. // XXX: for simplicity, we only support the IN class right now.
  289. if (rrclass != impl_->memory_client_class_) {
  290. isc_throw(InvalidParameter,
  291. "Memory data source is not supported for RR class "
  292. << rrclass);
  293. }
  294. return (impl_->memory_client_);
  295. }
  296. void
  297. AuthSrv::setInMemoryClient(const isc::dns::RRClass& rrclass,
  298. InMemoryClientPtr memory_client)
  299. {
  300. // XXX: see above
  301. if (rrclass != impl_->memory_client_class_) {
  302. isc_throw(InvalidParameter,
  303. "Memory data source is not supported for RR class "
  304. << rrclass);
  305. } else if (!impl_->memory_client_ && memory_client) {
  306. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_MEM_DATASRC_ENABLED)
  307. .arg(rrclass);
  308. } else if (impl_->memory_client_ && !memory_client) {
  309. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_MEM_DATASRC_DISABLED)
  310. .arg(rrclass);
  311. }
  312. impl_->memory_client_ = memory_client;
  313. }
  314. uint32_t
  315. AuthSrv::getStatisticsTimerInterval() const {
  316. return (impl_->statistics_timer_.getInterval() / 1000);
  317. }
  318. void
  319. AuthSrv::setStatisticsTimerInterval(uint32_t interval) {
  320. if (interval == impl_->statistics_timer_.getInterval()) {
  321. return;
  322. }
  323. if (interval > 86400) {
  324. // It can't occur since the value is checked in
  325. // statisticsIntervalConfig::build().
  326. isc_throw(InvalidParameter, "Too long interval: " << interval);
  327. }
  328. if (interval == 0) {
  329. impl_->statistics_timer_.cancel();
  330. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_STATS_TIMER_DISABLED);
  331. } else {
  332. impl_->statistics_timer_.setup(boost::bind(&AuthSrv::submitStatistics,
  333. this),
  334. interval * 1000);
  335. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_STATS_TIMER_SET)
  336. .arg(interval);
  337. }
  338. }
  339. void
  340. AuthSrv::processMessage(const IOMessage& io_message, MessagePtr message,
  341. OutputBufferPtr buffer, DNSServer* server)
  342. {
  343. InputBuffer request_buffer(io_message.getData(), io_message.getDataSize());
  344. // First, check the header part. If we fail even for the base header,
  345. // just drop the message.
  346. try {
  347. message->parseHeader(request_buffer);
  348. // Ignore all responses.
  349. if (message->getHeaderFlag(Message::HEADERFLAG_QR)) {
  350. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RESPONSE_RECEIVED);
  351. server->resume(false);
  352. return;
  353. }
  354. } catch (const Exception& ex) {
  355. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_HEADER_PARSE_FAIL)
  356. .arg(ex.what());
  357. server->resume(false);
  358. return;
  359. }
  360. try {
  361. // Parse the message.
  362. message->fromWire(request_buffer);
  363. } catch (const DNSProtocolError& error) {
  364. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_PACKET_PROTOCOL_ERROR)
  365. .arg(error.getRcode().toText()).arg(error.what());
  366. makeErrorMessage(message, buffer, error.getRcode());
  367. server->resume(true);
  368. return;
  369. } catch (const Exception& ex) {
  370. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_PACKET_PARSE_ERROR)
  371. .arg(ex.what());
  372. makeErrorMessage(message, buffer, Rcode::SERVFAIL());
  373. server->resume(true);
  374. return;
  375. } // other exceptions will be handled at a higher layer.
  376. LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_PACKET_RECEIVED)
  377. .arg(message->toText());
  378. // Perform further protocol-level validation.
  379. // TSIG first
  380. // If this is set to something, we know we need to answer with TSIG as well
  381. std::auto_ptr<TSIGContext> tsig_context;
  382. const TSIGRecord* tsig_record(message->getTSIGRecord());
  383. TSIGError tsig_error(TSIGError::NOERROR());
  384. // Do we do TSIG?
  385. // The keyring can be null if we're in test
  386. if (impl_->keyring_ != NULL && tsig_record != NULL) {
  387. tsig_context.reset(new TSIGContext(tsig_record->getName(),
  388. tsig_record->getRdata().
  389. getAlgorithm(),
  390. **impl_->keyring_));
  391. tsig_error = tsig_context->verify(tsig_record, io_message.getData(),
  392. io_message.getDataSize());
  393. }
  394. bool sendAnswer = true;
  395. if (tsig_error != TSIGError::NOERROR()) {
  396. makeErrorMessage(message, buffer, tsig_error.toRcode(), tsig_context);
  397. } else if (message->getOpcode() == Opcode::NOTIFY()) {
  398. sendAnswer = impl_->processNotify(io_message, message, buffer,
  399. tsig_context);
  400. } else if (message->getOpcode() != Opcode::QUERY()) {
  401. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_UNSUPPORTED_OPCODE)
  402. .arg(message->getOpcode().toText());
  403. makeErrorMessage(message, buffer, Rcode::NOTIMP(), tsig_context);
  404. } else if (message->getRRCount(Message::SECTION_QUESTION) != 1) {
  405. makeErrorMessage(message, buffer, Rcode::FORMERR(), tsig_context);
  406. } else {
  407. ConstQuestionPtr question = *message->beginQuestion();
  408. const RRType &qtype = question->getType();
  409. if (qtype == RRType::AXFR()) {
  410. sendAnswer = impl_->processAxfrQuery(io_message, message, buffer,
  411. tsig_context);
  412. } else if (qtype == RRType::IXFR()) {
  413. makeErrorMessage(message, buffer, Rcode::NOTIMP(), tsig_context);
  414. } else {
  415. sendAnswer = impl_->processNormalQuery(io_message, message, buffer,
  416. tsig_context);
  417. }
  418. }
  419. server->resume(sendAnswer);
  420. }
  421. bool
  422. AuthSrvImpl::processNormalQuery(const IOMessage& io_message, MessagePtr message,
  423. OutputBufferPtr buffer,
  424. auto_ptr<TSIGContext> tsig_context)
  425. {
  426. ConstEDNSPtr remote_edns = message->getEDNS();
  427. const bool dnssec_ok = remote_edns && remote_edns->getDNSSECAwareness();
  428. const uint16_t remote_bufsize = remote_edns ? remote_edns->getUDPSize() :
  429. Message::DEFAULT_MAX_UDPSIZE;
  430. message->makeResponse();
  431. message->setHeaderFlag(Message::HEADERFLAG_AA);
  432. message->setRcode(Rcode::NOERROR());
  433. // Increment query counter.
  434. incCounter(io_message.getSocket().getProtocol());
  435. if (remote_edns) {
  436. EDNSPtr local_edns = EDNSPtr(new EDNS());
  437. local_edns->setDNSSECAwareness(dnssec_ok);
  438. local_edns->setUDPSize(AuthSrvImpl::DEFAULT_LOCAL_UDPSIZE);
  439. message->setEDNS(local_edns);
  440. }
  441. try {
  442. // If a memory data source is configured call the separate
  443. // Query::process()
  444. const ConstQuestionPtr question = *message->beginQuestion();
  445. if (memory_client_ && memory_client_class_ == question->getClass()) {
  446. const RRType& qtype = question->getType();
  447. const Name& qname = question->getName();
  448. auth::Query(*memory_client_, qname, qtype, *message).process();
  449. } else {
  450. datasrc::Query query(*message, cache_, dnssec_ok);
  451. data_sources_.doQuery(query);
  452. }
  453. } catch (const Exception& ex) {
  454. LOG_ERROR(auth_logger, AUTH_PROCESS_FAIL).arg(ex.what());
  455. makeErrorMessage(message, buffer, Rcode::SERVFAIL());
  456. return (true);
  457. }
  458. MessageRenderer renderer(*buffer);
  459. const bool udp_buffer =
  460. (io_message.getSocket().getProtocol() == IPPROTO_UDP);
  461. renderer.setLengthLimit(udp_buffer ? remote_bufsize : 65535);
  462. if (tsig_context.get() != NULL) {
  463. message->toWire(renderer, *tsig_context);
  464. } else {
  465. message->toWire(renderer);
  466. }
  467. LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_SEND_NORMAL_RESPONSE)
  468. .arg(renderer.getLength()).arg(message->toText());
  469. return (true);
  470. }
  471. bool
  472. AuthSrvImpl::processAxfrQuery(const IOMessage& io_message, MessagePtr message,
  473. OutputBufferPtr buffer,
  474. auto_ptr<TSIGContext> tsig_context)
  475. {
  476. // Increment query counter.
  477. incCounter(io_message.getSocket().getProtocol());
  478. if (io_message.getSocket().getProtocol() == IPPROTO_UDP) {
  479. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_AXFR_UDP);
  480. makeErrorMessage(message, buffer, Rcode::FORMERR(), tsig_context);
  481. return (true);
  482. }
  483. try {
  484. if (!xfrout_connected_) {
  485. xfrout_client_.connect();
  486. xfrout_connected_ = true;
  487. }
  488. xfrout_client_.sendXfroutRequestInfo(
  489. io_message.getSocket().getNative(),
  490. io_message.getData(),
  491. io_message.getDataSize());
  492. } catch (const XfroutError& err) {
  493. if (xfrout_connected_) {
  494. // disconnect() may trigger an exception, but since we try it
  495. // only if we've successfully opened it, it shouldn't happen in
  496. // normal condition. Should this occur, we'll propagate it to the
  497. // upper layer.
  498. xfrout_client_.disconnect();
  499. xfrout_connected_ = false;
  500. }
  501. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_AXFR_ERROR)
  502. .arg(err.what());
  503. makeErrorMessage(message, buffer, Rcode::SERVFAIL(), tsig_context);
  504. return (true);
  505. }
  506. return (false);
  507. }
  508. bool
  509. AuthSrvImpl::processNotify(const IOMessage& io_message, MessagePtr message,
  510. OutputBufferPtr buffer,
  511. std::auto_ptr<TSIGContext> tsig_context)
  512. {
  513. // The incoming notify must contain exactly one question for SOA of the
  514. // zone name.
  515. if (message->getRRCount(Message::SECTION_QUESTION) != 1) {
  516. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_NOTIFY_QUESTIONS)
  517. .arg(message->getRRCount(Message::SECTION_QUESTION));
  518. makeErrorMessage(message, buffer, Rcode::FORMERR(), tsig_context);
  519. return (true);
  520. }
  521. ConstQuestionPtr question = *message->beginQuestion();
  522. if (question->getType() != RRType::SOA()) {
  523. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_NOTIFY_RRTYPE)
  524. .arg(question->getType().toText());
  525. makeErrorMessage(message, buffer, Rcode::FORMERR(), tsig_context);
  526. return (true);
  527. }
  528. // According to RFC 1996, rcode should be "no error" and AA bit should be
  529. // on, but we don't check these conditions. This behavior is compatible
  530. // with BIND 9.
  531. // TODO check with the conf-mgr whether current server is the auth of the
  532. // zone
  533. // In the code that follows, we simply ignore the notify if any internal
  534. // error happens rather than returning (e.g.) SERVFAIL. RFC 1996 is
  535. // silent about such cases, but there doesn't seem to be anything we can
  536. // improve at the primary server side by sending an error anyway.
  537. if (xfrin_session_ == NULL) {
  538. LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_NO_XFRIN);
  539. return (false);
  540. }
  541. const string remote_ip_address =
  542. io_message.getRemoteEndpoint().getAddress().toText();
  543. static const string command_template_start =
  544. "{\"command\": [\"notify\", {\"zone_name\" : \"";
  545. static const string command_template_master = "\", \"master\" : \"";
  546. static const string command_template_rrclass = "\", \"zone_class\" : \"";
  547. static const string command_template_end = "\"}]}";
  548. try {
  549. ConstElementPtr notify_command = Element::fromJSON(
  550. command_template_start + question->getName().toText() +
  551. command_template_master + remote_ip_address +
  552. command_template_rrclass + question->getClass().toText() +
  553. command_template_end);
  554. const unsigned int seq =
  555. xfrin_session_->group_sendmsg(notify_command, "Zonemgr",
  556. "*", "*");
  557. ConstElementPtr env, answer, parsed_answer;
  558. xfrin_session_->group_recvmsg(env, answer, false, seq);
  559. int rcode;
  560. parsed_answer = parseAnswer(rcode, answer);
  561. if (rcode != 0) {
  562. LOG_ERROR(auth_logger, AUTH_ZONEMGR_ERROR)
  563. .arg(parsed_answer->str());
  564. return (false);
  565. }
  566. } catch (const Exception& ex) {
  567. LOG_ERROR(auth_logger, AUTH_ZONEMGR_COMMS).arg(ex.what());
  568. return (false);
  569. }
  570. message->makeResponse();
  571. message->setHeaderFlag(Message::HEADERFLAG_AA);
  572. message->setRcode(Rcode::NOERROR());
  573. MessageRenderer renderer(*buffer);
  574. if (tsig_context.get() != NULL) {
  575. message->toWire(renderer, *tsig_context);
  576. } else {
  577. message->toWire(renderer);
  578. }
  579. return (true);
  580. }
  581. void
  582. AuthSrvImpl::incCounter(const int protocol) {
  583. // Increment query counter.
  584. if (protocol == IPPROTO_UDP) {
  585. counters_.inc(AuthCounters::COUNTER_UDP_QUERY);
  586. } else if (protocol == IPPROTO_TCP) {
  587. counters_.inc(AuthCounters::COUNTER_TCP_QUERY);
  588. } else {
  589. // unknown protocol
  590. isc_throw(Unexpected, "Unknown protocol: " << protocol);
  591. }
  592. }
  593. void
  594. AuthSrvImpl::registerStatisticsValidator() {
  595. counters_.registerStatisticsValidator(
  596. boost::bind(&AuthSrvImpl::validateStatistics, this, _1));
  597. }
  598. bool
  599. AuthSrvImpl::validateStatistics(isc::data::ConstElementPtr data) const {
  600. if (config_session_ == NULL) {
  601. return (false);
  602. }
  603. return (
  604. config_session_->getModuleSpec().validateStatistics(
  605. data, true));
  606. }
  607. ConstElementPtr
  608. AuthSrvImpl::setDbFile(ConstElementPtr config) {
  609. ConstElementPtr answer = isc::config::createAnswer();
  610. if (config && config->contains("database_file")) {
  611. db_file_ = config->get("database_file")->stringValue();
  612. } else if (config_session_ != NULL) {
  613. bool is_default;
  614. string item("database_file");
  615. ConstElementPtr value = config_session_->getValue(is_default, item);
  616. ElementPtr final = Element::createMap();
  617. // If the value is the default, and we are running from
  618. // a specific directory ('from build'), we need to use
  619. // a different value than the default (which may not exist)
  620. // (btw, this should not be done here in the end, i think
  621. // the from-source script should have a check for this,
  622. // but for that we need offline access to config, so for
  623. // now this is a decent solution)
  624. if (is_default && getenv("B10_FROM_BUILD")) {
  625. value = Element::create(string(getenv("B10_FROM_BUILD")) +
  626. "/bind10_zones.sqlite3");
  627. }
  628. final->set(item, value);
  629. config = final;
  630. db_file_ = value->stringValue();
  631. } else {
  632. return (answer);
  633. }
  634. LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_DATA_SOURCE).arg(db_file_);
  635. // create SQL data source
  636. // Note: the following step is tricky to be exception-safe and to ensure
  637. // exception guarantee: We first need to perform all operations that can
  638. // fail, while acquiring resources in the RAII manner. We then perform
  639. // delete and swap operations which should not fail.
  640. DataSrcPtr datasrc_ptr(DataSrcPtr(new Sqlite3DataSrc));
  641. datasrc_ptr->init(config);
  642. data_sources_.addDataSrc(datasrc_ptr);
  643. // The following code should be exception free.
  644. if (cur_datasrc_ != NULL) {
  645. data_sources_.removeDataSrc(cur_datasrc_);
  646. }
  647. cur_datasrc_ = datasrc_ptr;
  648. return (answer);
  649. }
  650. ConstElementPtr
  651. AuthSrv::updateConfig(ConstElementPtr new_config) {
  652. try {
  653. // the ModuleCCSession has already checked if we have
  654. // the correct ElementPtr type as specified in our .spec file
  655. if (new_config) {
  656. configureAuthServer(*this, new_config);
  657. }
  658. return (impl_->setDbFile(new_config));
  659. } catch (const isc::Exception& error) {
  660. LOG_ERROR(auth_logger, AUTH_CONFIG_UPDATE_FAIL).arg(error.what());
  661. return (isc::config::createAnswer(1, error.what()));
  662. }
  663. }
  664. bool AuthSrv::submitStatistics() const {
  665. return (impl_->counters_.submitStatistics());
  666. }
  667. uint64_t
  668. AuthSrv::getCounter(const AuthCounters::CounterType type) const {
  669. return (impl_->counters_.getCounter(type));
  670. }
  671. const AddressList&
  672. AuthSrv::getListenAddresses() const {
  673. return (impl_->listen_addresses_);
  674. }
  675. void
  676. AuthSrv::setListenAddresses(const AddressList& addresses) {
  677. installListenAddresses(addresses, impl_->listen_addresses_, *dnss_);
  678. }
  679. void
  680. AuthSrv::setDNSService(isc::asiodns::DNSService& dnss) {
  681. dnss_ = &dnss;
  682. }
  683. void
  684. AuthSrv::setTSIGKeyRing(const shared_ptr<TSIGKeyRing>* keyring) {
  685. impl_->keyring_ = keyring;
  686. }