auth_srv.cc 27 KB

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