json_config_parser.cc 33 KB

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