auth_srv.cc 29 KB

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