json_config_parser.cc 29 KB

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