json_config_parser.cc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. // Copyright (C) 2012-2016 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <config.h>
  7. #include <cc/command_interpreter.h>
  8. #include <dhcp4/dhcp4_log.h>
  9. #include <dhcp/libdhcp++.h>
  10. #include <dhcp/option_definition.h>
  11. #include <dhcpsrv/cfg_option.h>
  12. #include <dhcpsrv/cfgmgr.h>
  13. #include <dhcpsrv/parsers/client_class_def_parser.h>
  14. #include <dhcp4/json_config_parser.h>
  15. #include <dhcpsrv/parsers/dbaccess_parser.h>
  16. #include <dhcpsrv/parsers/dhcp_parsers.h>
  17. #include <dhcpsrv/parsers/expiration_config_parser.h>
  18. #include <dhcpsrv/parsers/host_reservation_parser.h>
  19. #include <dhcpsrv/parsers/host_reservations_list_parser.h>
  20. #include <dhcpsrv/parsers/ifaces_config_parser.h>
  21. #include <dhcpsrv/timer_mgr.h>
  22. #include <config/command_mgr.h>
  23. #include <util/encode/hex.h>
  24. #include <util/strutil.h>
  25. #include <defaults.h>
  26. #include <boost/foreach.hpp>
  27. #include <boost/lexical_cast.hpp>
  28. #include <boost/algorithm/string.hpp>
  29. #include <limits>
  30. #include <iostream>
  31. #include <netinet/in.h>
  32. #include <vector>
  33. #include <map>
  34. using namespace std;
  35. using namespace isc;
  36. using namespace isc::dhcp;
  37. using namespace isc::data;
  38. using namespace isc::asiolink;
  39. namespace {
  40. /// @brief Parser for IPv4 pool definitions.
  41. ///
  42. /// This is the IPv4 derivation of the PoolParser class and handles pool
  43. /// definitions, i.e. a list of entries of one of two syntaxes: min-max and
  44. /// prefix/len for IPv4 pools. Pool4 objects are created and stored in chosen
  45. /// PoolStorage container.
  46. ///
  47. /// It is useful for parsing Dhcp4/subnet4[X]/pool parameters.
  48. class Pool4Parser : public PoolParser {
  49. public:
  50. /// @brief Constructor.
  51. ///
  52. /// @param param_name name of the parameter. Note, it is passed through
  53. /// but unused, parameter is currently always "Dhcp4/subnet4[X]/pool"
  54. /// @param pools storage container in which to store the parsed pool
  55. /// upon "commit"
  56. Pool4Parser(const std::string& param_name, PoolStoragePtr pools)
  57. :PoolParser(param_name, pools, AF_INET) {
  58. }
  59. protected:
  60. /// @brief Creates a Pool4 object given a IPv4 prefix and the prefix length.
  61. ///
  62. /// @param addr is the IPv4 prefix of the pool.
  63. /// @param len is the prefix length.
  64. /// @param ignored dummy parameter to provide symmetry between the
  65. /// PoolParser derivations. The V6 derivation requires a third value.
  66. /// @return returns a PoolPtr to the new Pool4 object.
  67. PoolPtr poolMaker (IOAddress &addr, uint32_t len, int32_t) {
  68. return (PoolPtr(new Pool4(addr, len)));
  69. }
  70. /// @brief Creates a Pool4 object given starting and ending IPv4 addresses.
  71. ///
  72. /// @param min is the first IPv4 address in the pool.
  73. /// @param max is the last IPv4 address in the pool.
  74. /// @param ignored dummy parameter to provide symmetry between the
  75. /// PoolParser derivations. The V6 derivation requires a third value.
  76. /// @return returns a PoolPtr to the new Pool4 object.
  77. PoolPtr poolMaker (IOAddress &min, IOAddress &max, int32_t) {
  78. return (PoolPtr(new Pool4(min, max)));
  79. }
  80. };
  81. class Pools4ListParser : public PoolsListParser {
  82. public:
  83. Pools4ListParser(const std::string& dummy, PoolStoragePtr pools)
  84. :PoolsListParser(dummy, pools) {
  85. }
  86. protected:
  87. virtual ParserPtr poolParserMaker(PoolStoragePtr storage) {
  88. return (ParserPtr(new Pool4Parser("pool", storage)));
  89. }
  90. };
  91. /// @anchor Subnet4ConfigParser
  92. /// @brief This class parses a single IPv4 subnet.
  93. ///
  94. /// This is the IPv4 derivation of the SubnetConfigParser class and it parses
  95. /// the whole subnet definition. It creates parsersfor received configuration
  96. /// parameters as needed.
  97. class Subnet4ConfigParser : public SubnetConfigParser {
  98. public:
  99. /// @brief Constructor
  100. ///
  101. /// @param ignored first parameter
  102. /// stores global scope parameters, options, option definitions.
  103. Subnet4ConfigParser(const std::string&)
  104. :SubnetConfigParser("", globalContext(), IOAddress("0.0.0.0")) {
  105. }
  106. /// @brief Parses a single IPv4 subnet configuration and adds to the
  107. /// Configuration Manager.
  108. ///
  109. /// @param subnet A new subnet being configured.
  110. void build(ConstElementPtr subnet) {
  111. SubnetConfigParser::build(subnet);
  112. if (subnet_) {
  113. Subnet4Ptr sub4ptr = boost::dynamic_pointer_cast<Subnet4>(subnet_);
  114. if (!sub4ptr) {
  115. // If we hit this, it is a programming error.
  116. isc_throw(Unexpected,
  117. "Invalid cast in Subnet4ConfigParser::commit");
  118. }
  119. // Set relay information if it was parsed
  120. if (relay_info_) {
  121. sub4ptr->setRelayInfo(*relay_info_);
  122. }
  123. // Adding a subnet to the Configuration Manager may fail if the
  124. // subnet id is invalid (duplicate). Thus, we catch exceptions
  125. // here to append a position in the configuration string.
  126. try {
  127. CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(sub4ptr);
  128. } catch (const std::exception& ex) {
  129. isc_throw(DhcpConfigError, ex.what() << " ("
  130. << subnet->getPosition() << ")");
  131. }
  132. }
  133. // Parse Host Reservations for this subnet if any.
  134. ConstElementPtr reservations = subnet->get("reservations");
  135. if (reservations) {
  136. ParserPtr parser(new HostReservationsListParser<
  137. HostReservationParser4>(subnet_->getID()));
  138. parser->build(reservations);
  139. }
  140. }
  141. /// @brief Commits subnet configuration.
  142. ///
  143. /// This function is currently no-op because subnet should already
  144. /// be added into the Config Manager in the build().
  145. void commit() { }
  146. protected:
  147. /// @brief Creates parsers for entries in subnet definition.
  148. ///
  149. /// @param config_id name of the entry
  150. ///
  151. /// @return parser object for specified entry name. Note the caller is
  152. /// responsible for deleting the parser created.
  153. /// @throw isc::dhcp::DhcpConfigError if trying to create a parser
  154. /// for unknown config element
  155. DhcpConfigParser* createSubnetConfigParser(const std::string& config_id) {
  156. DhcpConfigParser* parser = NULL;
  157. if ((config_id.compare("valid-lifetime") == 0) ||
  158. (config_id.compare("renew-timer") == 0) ||
  159. (config_id.compare("rebind-timer") == 0) ||
  160. (config_id.compare("id") == 0)) {
  161. parser = new Uint32Parser(config_id, uint32_values_);
  162. } else if ((config_id.compare("subnet") == 0) ||
  163. (config_id.compare("interface") == 0) ||
  164. (config_id.compare("client-class") == 0) ||
  165. (config_id.compare("next-server") == 0) ||
  166. (config_id.compare("reservation-mode") == 0)) {
  167. parser = new StringParser(config_id, string_values_);
  168. } else if (config_id.compare("pools") == 0) {
  169. parser = new Pools4ListParser(config_id, pools_);
  170. } else if (config_id.compare("relay") == 0) {
  171. parser = new RelayInfoParser(config_id, relay_info_, Option::V4);
  172. } else if (config_id.compare("option-data") == 0) {
  173. parser = new OptionDataListParser(config_id, options_, AF_INET);
  174. } else if (config_id.compare("match-client-id") == 0) {
  175. parser = new BooleanParser(config_id, boolean_values_);
  176. } else if (config_id.compare("4o6-subnet") == 0) {
  177. parser = new StringParser(config_id, string_values_);
  178. } else if (config_id.compare("4o6-interface") == 0) {
  179. parser = new StringParser(config_id, string_values_);
  180. } else if (config_id.compare("4o6-interface-id") == 0) {
  181. parser = new StringParser(config_id, string_values_);
  182. } else {
  183. isc_throw(NotImplemented, "unsupported parameter: " << config_id);
  184. }
  185. return (parser);
  186. }
  187. /// @brief Issues a DHCP4 server specific warning regarding duplicate subnet
  188. /// options.
  189. ///
  190. /// @param code is the numeric option code of the duplicate option
  191. /// @param addr is the subnet address
  192. /// @todo a means to know the correct logger and perhaps a common
  193. /// message would allow this method to be emitted by the base class.
  194. virtual void duplicate_option_warning(uint32_t code,
  195. isc::asiolink::IOAddress& addr) {
  196. LOG_WARN(dhcp4_logger, DHCP4_CONFIG_OPTION_DUPLICATE)
  197. .arg(code).arg(addr.toText());
  198. }
  199. /// @brief Instantiates the IPv4 Subnet based on a given IPv4 address
  200. /// and prefix length.
  201. ///
  202. /// @param addr is IPv4 address of the subnet.
  203. /// @param len is the prefix length
  204. void initSubnet(isc::asiolink::IOAddress addr, uint8_t len) {
  205. // The renew-timer and rebind-timer are optional. If not set, the
  206. // option 58 and 59 will not be sent to a client. In this case the
  207. // client will use default values based on the valid-lifetime.
  208. Triplet<uint32_t> t1 = getOptionalParam("renew-timer");
  209. Triplet<uint32_t> t2 = getOptionalParam("rebind-timer");
  210. // The valid-lifetime is mandatory. It may be specified for a
  211. // particular subnet. If not, the global value should be present.
  212. // If there is no global value, exception is thrown.
  213. Triplet<uint32_t> valid = getParam("valid-lifetime");
  214. // Subnet ID is optional. If it is not supplied the value of 0 is used,
  215. // which means autogenerate.
  216. SubnetID subnet_id =
  217. static_cast<SubnetID>(uint32_values_->getOptionalParam("id", 0));
  218. stringstream s;
  219. s << addr << "/" << static_cast<int>(len) << " with params: ";
  220. // t1 and t2 are optional may be not specified.
  221. if (!t1.unspecified()) {
  222. s << "t1=" << t1 << ", ";
  223. }
  224. if (!t2.unspecified()) {
  225. s << "t2=" << t2 << ", ";
  226. }
  227. s <<"valid-lifetime=" << valid;
  228. LOG_INFO(dhcp4_logger, DHCP4_CONFIG_NEW_SUBNET).arg(s.str());
  229. Subnet4Ptr subnet4(new Subnet4(addr, len, t1, t2, valid, subnet_id));
  230. subnet_ = subnet4;
  231. // match-client-id
  232. isc::util::OptionalValue<bool> match_client_id;
  233. try {
  234. match_client_id = boolean_values_->getParam("match-client-id");
  235. } catch (...) {
  236. // Ignore because this parameter is optional and it may be specified
  237. // in the global scope.
  238. }
  239. // If the match-client-id wasn't specified as a subnet specific parameter
  240. // check if there is global value specified.
  241. if (!match_client_id.isSpecified()) {
  242. // If not specified, use false.
  243. match_client_id.specify(globalContext()->boolean_values_->
  244. getOptionalParam("match-client-id", true));
  245. }
  246. // Set the match-client-id value for the subnet.
  247. subnet4->setMatchClientId(match_client_id.get());
  248. // next-server
  249. try {
  250. string next_server = globalContext()->string_values_->getParam("next-server");
  251. if (!next_server.empty()) {
  252. subnet4->setSiaddr(IOAddress(next_server));
  253. }
  254. } catch (const DhcpConfigError&) {
  255. // Don't care. next_server is optional. We can live without it
  256. } catch (...) {
  257. isc_throw(DhcpConfigError, "invalid parameter next-server ("
  258. << globalContext()->string_values_->getPosition("next-server")
  259. << ")");
  260. }
  261. // Try subnet specific value if it's available
  262. try {
  263. string next_server = string_values_->getParam("next-server");
  264. if (!next_server.empty()) {
  265. subnet4->setSiaddr(IOAddress(next_server));
  266. }
  267. } catch (const DhcpConfigError&) {
  268. // Don't care. next_server is optional. We can live without it
  269. } catch (...) {
  270. isc_throw(DhcpConfigError, "invalid parameter next-server ("
  271. << string_values_->getPosition("next-server")
  272. << ")");
  273. }
  274. // Try 4o6 specific parameter: 4o6-interface
  275. string iface4o6 = string_values_->getOptionalParam("4o6-interface", "");
  276. if (!iface4o6.empty()) {
  277. subnet4->get4o6().setIface4o6(iface4o6);
  278. subnet4->get4o6().enabled(true);
  279. }
  280. // Try 4o6 specific parameter: 4o6-subnet
  281. string subnet4o6 = string_values_->getOptionalParam("4o6-subnet", "");
  282. if (!subnet4o6.empty()) {
  283. size_t slash = subnet4o6.find("/");
  284. if (slash == std::string::npos) {
  285. isc_throw(DhcpConfigError, "Missing / in the 4o6-subnet parameter:"
  286. + subnet4o6 +", expected format: prefix6/length");
  287. }
  288. string prefix = subnet4o6.substr(0, slash);
  289. string lenstr = subnet4o6.substr(slash + 1);
  290. uint8_t len = 128;
  291. try {
  292. len = boost::lexical_cast<unsigned int>(lenstr.c_str());
  293. } catch (const boost::bad_lexical_cast &) {
  294. isc_throw(DhcpConfigError, "Invalid prefix length specified in "
  295. "4o6-subnet parameter: " + subnet4o6 + ", expected 0..128 value");
  296. }
  297. subnet4->get4o6().setSubnet4o6(IOAddress(prefix), len);
  298. subnet4->get4o6().enabled(true);
  299. }
  300. // Try 4o6 specific paramter: 4o6-interface-id
  301. std::string ifaceid = string_values_->getOptionalParam("4o6-interface-id", "");
  302. if (!ifaceid.empty()) {
  303. OptionBuffer tmp(ifaceid.begin(), ifaceid.end());
  304. OptionPtr opt(new Option(Option::V6, D6O_INTERFACE_ID, tmp));
  305. subnet4->get4o6().setInterfaceId(opt);
  306. subnet4->get4o6().enabled(true);
  307. }
  308. // Try setting up client class (if specified)
  309. try {
  310. string client_class = string_values_->getParam("client-class");
  311. subnet4->allowClientClass(client_class);
  312. } catch (const DhcpConfigError&) {
  313. // That's ok if it fails. client-class is optional.
  314. }
  315. }
  316. };
  317. /// @brief this class parses list of DHCP4 subnets
  318. ///
  319. /// This is a wrapper parser that handles the whole list of Subnet4
  320. /// definitions. It iterates over all entries and creates Subnet4ConfigParser
  321. /// for each entry.
  322. class Subnets4ListConfigParser : public DhcpConfigParser {
  323. public:
  324. /// @brief constructor
  325. ///
  326. /// @param dummy first argument, always ignored. All parsers accept a
  327. /// string parameter "name" as their first argument.
  328. Subnets4ListConfigParser(const std::string&) {
  329. }
  330. /// @brief parses contents of the list
  331. ///
  332. /// Iterates over all entries on the list and creates Subnet4ConfigParser
  333. /// for each entry.
  334. ///
  335. /// @param subnets_list pointer to a list of IPv4 subnets
  336. void build(ConstElementPtr subnets_list) {
  337. BOOST_FOREACH(ConstElementPtr subnet, subnets_list->listValue()) {
  338. ParserPtr parser(new Subnet4ConfigParser("subnet"));
  339. parser->build(subnet);
  340. }
  341. }
  342. /// @brief commits subnets definitions.
  343. ///
  344. /// Does nothing.
  345. void commit() {
  346. }
  347. /// @brief Returns Subnet4ListConfigParser object
  348. /// @param param_name name of the parameter
  349. /// @return Subnets4ListConfigParser object
  350. static DhcpConfigParser* factory(const std::string& param_name) {
  351. return (new Subnets4ListConfigParser(param_name));
  352. }
  353. };
  354. } // anonymous namespace
  355. namespace isc {
  356. namespace dhcp {
  357. /// @brief creates global parsers
  358. ///
  359. /// This method creates global parsers that parse global parameters, i.e.
  360. /// those that take format of Dhcp4/param1, Dhcp4/param2 and so forth.
  361. ///
  362. /// @param config_id pointer to received global configuration entry
  363. /// @param element pointer to the element to be parsed
  364. /// @return parser for specified global DHCPv4 parameter
  365. /// @throw NotImplemented if trying to create a parser for unknown
  366. /// config element
  367. DhcpConfigParser* createGlobalDhcp4ConfigParser(const std::string& config_id,
  368. ConstElementPtr element) {
  369. DhcpConfigParser* parser = NULL;
  370. if ((config_id.compare("valid-lifetime") == 0) ||
  371. (config_id.compare("renew-timer") == 0) ||
  372. (config_id.compare("rebind-timer") == 0) ||
  373. (config_id.compare("decline-probation-period") == 0) ||
  374. (config_id.compare("dhcp4o6-port") == 0) ) {
  375. parser = new Uint32Parser(config_id,
  376. globalContext()->uint32_values_);
  377. } else if (config_id.compare("interfaces-config") == 0) {
  378. parser = new IfacesConfigParser4();
  379. } else if (config_id.compare("subnet4") == 0) {
  380. parser = new Subnets4ListConfigParser(config_id);
  381. } else if (config_id.compare("option-data") == 0) {
  382. parser = new OptionDataListParser(config_id, CfgOptionPtr(), AF_INET);
  383. } else if (config_id.compare("option-def") == 0) {
  384. parser = new OptionDefListParser(config_id, globalContext());
  385. } else if ((config_id.compare("version") == 0) ||
  386. (config_id.compare("next-server") == 0)) {
  387. parser = new StringParser(config_id,
  388. globalContext()->string_values_);
  389. } else if (config_id.compare("lease-database") == 0) {
  390. parser = new DbAccessParser(config_id, DbAccessParser::LEASE_DB);
  391. } else if (config_id.compare("hosts-database") == 0) {
  392. parser = new DbAccessParser(config_id, DbAccessParser::HOSTS_DB);
  393. } else if (config_id.compare("hooks-libraries") == 0) {
  394. parser = new HooksLibrariesParser(config_id);
  395. } else if (config_id.compare("echo-client-id") == 0) {
  396. parser = new BooleanParser(config_id, globalContext()->boolean_values_);
  397. } else if (config_id.compare("dhcp-ddns") == 0) {
  398. parser = new D2ClientConfigParser(config_id);
  399. } else if (config_id.compare("match-client-id") == 0) {
  400. parser = new BooleanParser(config_id, globalContext()->boolean_values_);
  401. } else if (config_id.compare("control-socket") == 0) {
  402. parser = new ControlSocketParser(config_id);
  403. } else if (config_id.compare("expired-leases-processing") == 0) {
  404. parser = new ExpirationConfigParser();
  405. } else if (config_id.compare("client-classes") == 0) {
  406. parser = new ClientClassDefListParser(config_id, globalContext());
  407. } else if (config_id.compare("host-reservation-identifiers") == 0) {
  408. parser = new HostReservationIdsParser4();
  409. } else {
  410. isc_throw(DhcpConfigError,
  411. "unsupported global configuration parameter: "
  412. << config_id << " (" << element->getPosition() << ")");
  413. }
  414. return (parser);
  415. }
  416. /// @brief Sets global parameters in staging configuration
  417. ///
  418. /// Currently this method sets the following global parameters:
  419. ///
  420. /// - echo-client-id
  421. /// - decline-probation-period
  422. /// - dhcp4o6-port
  423. void setGlobalParameters4() {
  424. // Although the function is modest for now, it is certain that the number
  425. // of global switches will increase over time, hence the name.
  426. // Set whether v4 server is supposed to echo back client-id (yes = RFC6842
  427. // compatible, no = backward compatibility)
  428. try {
  429. bool echo_client_id = globalContext()->boolean_values_->getParam("echo-client-id");
  430. CfgMgr::instance().echoClientId(echo_client_id);
  431. } catch (...) {
  432. // Ignore errors. This flag is optional
  433. }
  434. // Set the probation period for decline handling.
  435. try {
  436. uint32_t probation_period = globalContext()->uint32_values_
  437. ->getOptionalParam("decline-probation-period",
  438. DEFAULT_DECLINE_PROBATION_PERIOD);
  439. CfgMgr::instance().getStagingCfg()->setDeclinePeriod(probation_period);
  440. } catch (...) {
  441. // That's not really needed.
  442. }
  443. // Set the DHCPv4-over-DHCPv6 interserver port.
  444. try {
  445. uint32_t dhcp4o6_port = globalContext()->uint32_values_
  446. ->getOptionalParam("dhcp4o6-port", 0);
  447. CfgMgr::instance().getStagingCfg()->setDhcp4o6Port(dhcp4o6_port);
  448. } catch (...) {
  449. // Ignore errors. This flag is optional
  450. }
  451. }
  452. isc::data::ConstElementPtr
  453. configureDhcp4Server(Dhcpv4Srv&, isc::data::ConstElementPtr config_set) {
  454. if (!config_set) {
  455. ConstElementPtr answer = isc::config::createAnswer(1,
  456. string("Can't parse NULL config"));
  457. return (answer);
  458. }
  459. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_COMMAND,
  460. DHCP4_CONFIG_START).arg(config_set->str());
  461. // Reset global context.
  462. globalContext().reset(new ParserContext(Option::V4));
  463. // Before starting any subnet operations, let's reset the subnet-id counter,
  464. // so newly recreated configuration starts with first subnet-id equal 1.
  465. Subnet::resetSubnetID();
  466. // Remove any existing timers.
  467. TimerMgr::instance()->unregisterTimers();
  468. // Revert any runtime option definitions configured so far and not committed.
  469. LibDHCP::revertRuntimeOptionDefs();
  470. // Let's set empty container in case a user hasn't specified any configuration
  471. // for option definitions. This is equivalent to commiting empty container.
  472. LibDHCP::setRuntimeOptionDefs(OptionDefSpaceContainer());
  473. // Some of the values specified in the configuration depend on
  474. // other values. Typically, the values in the subnet4 structure
  475. // depend on the global values. Also, option values configuration
  476. // must be performed after the option definitions configurations.
  477. // Thus we group parsers and will fire them in the right order:
  478. // all parsers other than: lease-database, subnet4 and option-data parser,
  479. // then: option-data parser, subnet4 parser, lease-database parser.
  480. // Please do not change this order!
  481. ParserCollection independent_parsers;
  482. ParserPtr subnet_parser;
  483. ParserPtr option_parser;
  484. ParserPtr iface_parser;
  485. ParserPtr leases_parser;
  486. ParserPtr client_classes_parser;
  487. // Some of the parsers alter the state of the system in a way that can't
  488. // easily be undone. (Or alter it in a way such that undoing the change has
  489. // the same risk of failure as doing the change.)
  490. ParserPtr hooks_parser;
  491. // The subnet parsers implement data inheritance by directly
  492. // accessing global storage. For this reason the global data
  493. // parsers must store the parsed data into global storages
  494. // immediately. This may cause data inconsistency if the
  495. // parsing operation fails after the global storage has been
  496. // modified. We need to preserve the original global data here
  497. // so as we can rollback changes when an error occurs.
  498. ParserContext original_context(*globalContext());
  499. // Answer will hold the result.
  500. ConstElementPtr answer;
  501. // Rollback informs whether error occurred and original data
  502. // have to be restored to global storages.
  503. bool rollback = false;
  504. // config_pair holds the details of the current parser when iterating over
  505. // the parsers. It is declared outside the loops so in case of an error,
  506. // the name of the failing parser can be retrieved in the "catch" clause.
  507. ConfigPair config_pair;
  508. try {
  509. // Make parsers grouping.
  510. const std::map<std::string, ConstElementPtr>& values_map =
  511. config_set->mapValue();
  512. BOOST_FOREACH(config_pair, values_map) {
  513. ParserPtr parser(createGlobalDhcp4ConfigParser(config_pair.first,
  514. config_pair.second));
  515. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_PARSER_CREATED)
  516. .arg(config_pair.first);
  517. if (config_pair.first == "subnet4") {
  518. subnet_parser = parser;
  519. } else if (config_pair.first == "lease-database") {
  520. leases_parser = parser;
  521. } else if (config_pair.first == "option-data") {
  522. option_parser = parser;
  523. } else if (config_pair.first == "interfaces-config") {
  524. // The interface parser is independent from any other
  525. // parser and can be run here before any other parsers.
  526. iface_parser = parser;
  527. parser->build(config_pair.second);
  528. } else if (config_pair.first == "hooks-libraries") {
  529. // Executing commit will alter currently-loaded hooks
  530. // libraries. Check if the supplied libraries are valid,
  531. // but defer the commit until everything else has committed.
  532. hooks_parser = parser;
  533. parser->build(config_pair.second);
  534. } else if (config_pair.first == "client-classes") {
  535. client_classes_parser = parser;
  536. } else {
  537. // Those parsers should be started before other
  538. // parsers so we can call build straight away.
  539. independent_parsers.push_back(parser);
  540. parser->build(config_pair.second);
  541. // The commit operation here may modify the global storage
  542. // but we need it so as the subnet6 parser can access the
  543. // parsed data.
  544. parser->commit();
  545. }
  546. }
  547. // The option values parser is the next one to be run.
  548. std::map<std::string, ConstElementPtr>::const_iterator option_config =
  549. values_map.find("option-data");
  550. if (option_config != values_map.end()) {
  551. config_pair.first = "option-data";
  552. option_parser->build(option_config->second);
  553. option_parser->commit();
  554. }
  555. // The class definitions parser is the next one to be run.
  556. std::map<std::string, ConstElementPtr>::const_iterator cc_config =
  557. values_map.find("client-classes");
  558. if (cc_config != values_map.end()) {
  559. config_pair.first = "client-classes";
  560. client_classes_parser->build(cc_config->second);
  561. client_classes_parser->commit();
  562. }
  563. // The subnet parser is the next one to be run.
  564. std::map<std::string, ConstElementPtr>::const_iterator subnet_config =
  565. values_map.find("subnet4");
  566. if (subnet_config != values_map.end()) {
  567. config_pair.first = "subnet4";
  568. subnet_parser->build(subnet_config->second);
  569. }
  570. // Get command socket configuration from the config file.
  571. // This code expects the following structure:
  572. // {
  573. // "socket-type": "unix",
  574. // "socket-name": "/tmp/kea4.sock"
  575. // }
  576. ConstElementPtr sock_cfg =
  577. CfgMgr::instance().getStagingCfg()->getControlSocketInfo();
  578. // Close existing socket (if any).
  579. isc::config::CommandMgr::instance().closeCommandSocket();
  580. if (sock_cfg) {
  581. // This will create a control socket and will install external socket
  582. // in IfaceMgr. That socket will be monitored when Dhcp4Srv::receivePacket()
  583. // calls IfaceMgr::receive4() and callback in CommandMgr will be called,
  584. // if necessary. If there were previously open command socket, it will
  585. // be closed.
  586. isc::config::CommandMgr::instance().openCommandSocket(sock_cfg);
  587. }
  588. // the leases database parser is the last to be run.
  589. std::map<std::string, ConstElementPtr>::const_iterator leases_config =
  590. values_map.find("lease-database");
  591. if (leases_config != values_map.end()) {
  592. config_pair.first = "lease-database";
  593. leases_parser->build(leases_config->second);
  594. leases_parser->commit();
  595. }
  596. } catch (const isc::Exception& ex) {
  597. LOG_ERROR(dhcp4_logger, DHCP4_PARSER_FAIL)
  598. .arg(config_pair.first).arg(ex.what());
  599. answer = isc::config::createAnswer(1, ex.what());
  600. // An error occurred, so make sure that we restore original data.
  601. rollback = true;
  602. } catch (...) {
  603. // For things like bad_cast in boost::lexical_cast
  604. LOG_ERROR(dhcp4_logger, DHCP4_PARSER_EXCEPTION).arg(config_pair.first);
  605. answer = isc::config::createAnswer(1, "undefined configuration"
  606. " processing error");
  607. // An error occurred, so make sure that we restore original data.
  608. rollback = true;
  609. }
  610. // So far so good, there was no parsing error so let's commit the
  611. // configuration. This will add created subnets and option values into
  612. // the server's configuration.
  613. // This operation should be exception safe but let's make sure.
  614. if (!rollback) {
  615. try {
  616. // No need to commit interface names as this is handled by the
  617. // CfgMgr::commit() function.
  618. // Apply global options in the staging config.
  619. setGlobalParameters4();
  620. // This occurs last as if it succeeds, there is no easy way
  621. // revert it. As a result, the failure to commit a subsequent
  622. // change causes problems when trying to roll back.
  623. if (hooks_parser) {
  624. hooks_parser->commit();
  625. }
  626. }
  627. catch (const isc::Exception& ex) {
  628. LOG_ERROR(dhcp4_logger, DHCP4_PARSER_COMMIT_FAIL).arg(ex.what());
  629. answer = isc::config::createAnswer(2, ex.what());
  630. rollback = true;
  631. } catch (...) {
  632. // For things like bad_cast in boost::lexical_cast
  633. LOG_ERROR(dhcp4_logger, DHCP4_PARSER_COMMIT_EXCEPTION);
  634. answer = isc::config::createAnswer(2, "undefined configuration"
  635. " parsing error");
  636. rollback = true;
  637. }
  638. }
  639. // Rollback changes as the configuration parsing failed.
  640. if (rollback) {
  641. globalContext().reset(new ParserContext(original_context));
  642. // Revert to original configuration of runtime option definitions
  643. // in the libdhcp++.
  644. LibDHCP::revertRuntimeOptionDefs();
  645. return (answer);
  646. }
  647. LOG_INFO(dhcp4_logger, DHCP4_CONFIG_COMPLETE)
  648. .arg(CfgMgr::instance().getStagingCfg()->
  649. getConfigSummary(SrvConfig::CFGSEL_ALL4));
  650. // Everything was fine. Configuration is successful.
  651. answer = isc::config::createAnswer(0, "Configuration successful.");
  652. return (answer);
  653. }
  654. ParserContextPtr& globalContext() {
  655. static ParserContextPtr global_context_ptr(new ParserContext(Option::V4));
  656. return (global_context_ptr);
  657. }
  658. }; // end of isc::dhcp namespace
  659. }; // end of isc namespace