json_config_parser.cc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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 paramter: 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("interfaces-config") == 0) {
  376. parser = new IfacesConfigParser4();
  377. } else if (config_id.compare("subnet4") == 0) {
  378. parser = new Subnets4ListConfigParser(config_id);
  379. // option-data and option-def have been converted to SimpleParser already.
  380. } else if ((config_id.compare("next-server") == 0)) {
  381. parser = new StringParser(config_id,
  382. globalContext()->string_values_);
  383. } else if (config_id.compare("lease-database") == 0) {
  384. parser = new DbAccessParser(config_id, DbAccessParser::LEASE_DB);
  385. } else if (config_id.compare("hosts-database") == 0) {
  386. parser = new DbAccessParser(config_id, DbAccessParser::HOSTS_DB);
  387. } else if (config_id.compare("hooks-libraries") == 0) {
  388. parser = new HooksLibrariesParser(config_id);
  389. } else if (config_id.compare("echo-client-id") == 0) {
  390. parser = new BooleanParser(config_id, globalContext()->boolean_values_);
  391. } else if (config_id.compare("dhcp-ddns") == 0) {
  392. parser = new D2ClientConfigParser(config_id);
  393. } else if (config_id.compare("match-client-id") == 0) {
  394. parser = new BooleanParser(config_id, globalContext()->boolean_values_);
  395. // control-socket has been converted to SimpleParser already.
  396. } else if (config_id.compare("expired-leases-processing") == 0) {
  397. parser = new ExpirationConfigParser();
  398. } else if (config_id.compare("client-classes") == 0) {
  399. parser = new ClientClassDefListParser(config_id, globalContext());
  400. // host-reservation-identifiers have been converted to SimpleParser already.
  401. } else {
  402. isc_throw(DhcpConfigError,
  403. "unsupported global configuration parameter: "
  404. << config_id << " (" << element->getPosition() << ")");
  405. }
  406. return (parser);
  407. }
  408. /// @brief Sets global parameters in staging configuration
  409. ///
  410. /// Currently this method sets the following global parameters:
  411. ///
  412. /// - echo-client-id
  413. /// - decline-probation-period
  414. /// - dhcp4o6-port
  415. void setGlobalParameters4() {
  416. // Although the function is modest for now, it is certain that the number
  417. // of global switches will increase over time, hence the name.
  418. // Set whether v4 server is supposed to echo back client-id (yes = RFC6842
  419. // compatible, no = backward compatibility)
  420. try {
  421. bool echo_client_id = globalContext()->boolean_values_->getParam("echo-client-id");
  422. CfgMgr::instance().echoClientId(echo_client_id);
  423. } catch (...) {
  424. // Ignore errors. This flag is optional
  425. }
  426. // Set the probation period for decline handling.
  427. try {
  428. uint32_t probation_period = globalContext()->uint32_values_
  429. ->getOptionalParam("decline-probation-period",
  430. DEFAULT_DECLINE_PROBATION_PERIOD);
  431. CfgMgr::instance().getStagingCfg()->setDeclinePeriod(probation_period);
  432. } catch (...) {
  433. // That's not really needed.
  434. }
  435. // Set the DHCPv4-over-DHCPv6 interserver port.
  436. try {
  437. uint32_t dhcp4o6_port = globalContext()->uint32_values_
  438. ->getOptionalParam("dhcp4o6-port", 0);
  439. CfgMgr::instance().getStagingCfg()->setDhcp4o6Port(dhcp4o6_port);
  440. } catch (...) {
  441. // Ignore errors. This flag is optional
  442. }
  443. }
  444. /// @brief Initialize the command channel based on the staging configuration
  445. ///
  446. /// Only close the current channel, if the new channel configuration is
  447. /// different. This avoids disconnecting a client and hence not sending them
  448. /// a command result, unless they specifically alter the channel configuration.
  449. /// In that case the user simply has to accept they'll be disconnected.
  450. ///
  451. void configureCommandChannel() {
  452. // Get new socket configuration.
  453. ConstElementPtr sock_cfg =
  454. CfgMgr::instance().getStagingCfg()->getControlSocketInfo();
  455. // Get current socket configuration.
  456. ConstElementPtr current_sock_cfg =
  457. CfgMgr::instance().getCurrentCfg()->getControlSocketInfo();
  458. // Determine if the socket configuration has changed. It has if
  459. // both old and new configuration is specified but respective
  460. // data elements are't equal.
  461. bool sock_changed = (sock_cfg && current_sock_cfg &&
  462. !sock_cfg->equals(*current_sock_cfg));
  463. // If the previous or new socket configuration doesn't exist or
  464. // the new configuration differs from the old configuration we
  465. // close the exisitng socket and open a new socket as appropriate.
  466. // Note that closing an existing socket means the clien will not
  467. // receive the configuration result.
  468. if (!sock_cfg || !current_sock_cfg || sock_changed) {
  469. // Close the existing socket (if any).
  470. isc::config::CommandMgr::instance().closeCommandSocket();
  471. if (sock_cfg) {
  472. // This will create a control socket and install the external
  473. // socket in IfaceMgr. That socket will be monitored when
  474. // Dhcp4Srv::receivePacket() calls IfaceMgr::receive4() and
  475. // callback in CommandMgr will be called, if necessary.
  476. isc::config::CommandMgr::instance().openCommandSocket(sock_cfg);
  477. }
  478. }
  479. }
  480. isc::data::ConstElementPtr
  481. configureDhcp4Server(Dhcpv4Srv&, isc::data::ConstElementPtr config_set) {
  482. if (!config_set) {
  483. ConstElementPtr answer = isc::config::createAnswer(1,
  484. string("Can't parse NULL config"));
  485. return (answer);
  486. }
  487. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_COMMAND,
  488. DHCP4_CONFIG_START).arg(config_set->str());
  489. // Reset global context.
  490. globalContext().reset(new ParserContext(Option::V4));
  491. // Before starting any subnet operations, let's reset the subnet-id counter,
  492. // so newly recreated configuration starts with first subnet-id equal 1.
  493. Subnet::resetSubnetID();
  494. // Remove any existing timers.
  495. TimerMgr::instance()->unregisterTimers();
  496. // Revert any runtime option definitions configured so far and not committed.
  497. LibDHCP::revertRuntimeOptionDefs();
  498. // Let's set empty container in case a user hasn't specified any configuration
  499. // for option definitions. This is equivalent to commiting empty container.
  500. LibDHCP::setRuntimeOptionDefs(OptionDefSpaceContainer());
  501. // Some of the values specified in the configuration depend on
  502. // other values. Typically, the values in the subnet4 structure
  503. // depend on the global values. Also, option values configuration
  504. // must be performed after the option definitions configurations.
  505. // Thus we group parsers and will fire them in the right order:
  506. // all parsers other than: lease-database, subnet4 and option-data parser,
  507. // then: option-data parser, subnet4 parser, lease-database parser.
  508. // Please do not change this order!
  509. ParserCollection independent_parsers;
  510. ParserPtr subnet_parser;
  511. ParserPtr iface_parser;
  512. ParserPtr leases_parser;
  513. ParserPtr client_classes_parser;
  514. // Some of the parsers alter the state of the system in a way that can't
  515. // easily be undone. (Or alter it in a way such that undoing the change has
  516. // the same risk of failure as doing the change.)
  517. ParserPtr hooks_parser;
  518. // The subnet parsers implement data inheritance by directly
  519. // accessing global storage. For this reason the global data
  520. // parsers must store the parsed data into global storages
  521. // immediately. This may cause data inconsistency if the
  522. // parsing operation fails after the global storage has been
  523. // modified. We need to preserve the original global data here
  524. // so as we can rollback changes when an error occurs.
  525. ParserContext original_context(*globalContext());
  526. // Answer will hold the result.
  527. ConstElementPtr answer;
  528. // Rollback informs whether error occurred and original data
  529. // have to be restored to global storages.
  530. bool rollback = false;
  531. // config_pair holds the details of the current parser when iterating over
  532. // the parsers. It is declared outside the loops so in case of an error,
  533. // the name of the failing parser can be retrieved in the "catch" clause.
  534. ConfigPair config_pair;
  535. try {
  536. // This is a way to convert ConstElementPtr to ElementPtr.
  537. // We need a config that can be edited, because we will insert
  538. // default values and will insert derived values as well.
  539. ElementPtr mutable_cfg = boost::const_pointer_cast<Element>(config_set);
  540. // Set all default values if not specified by the user.
  541. SimpleParser4::setAllDefaults(mutable_cfg);
  542. // We need definitions first
  543. ConstElementPtr option_defs = mutable_cfg->get("option-def");
  544. if (option_defs) {
  545. OptionDefListParser parser;
  546. CfgOptionDefPtr cfg_option_def = CfgMgr::instance().getStagingCfg()->getCfgOptionDef();
  547. parser.parse(cfg_option_def, option_defs);
  548. }
  549. // Make parsers grouping.
  550. const std::map<std::string, ConstElementPtr>& values_map =
  551. mutable_cfg->mapValue();
  552. BOOST_FOREACH(config_pair, values_map) {
  553. if (config_pair.first == "option-def") {
  554. // This is converted to SimpleParser and is handled already above.
  555. continue;
  556. }
  557. if (config_pair.first == "option-data") {
  558. OptionDataListParser parser(AF_INET);
  559. CfgOptionPtr cfg_option = CfgMgr::instance().getStagingCfg()->getCfgOption();
  560. parser.parse(cfg_option, config_pair.second);
  561. continue;
  562. }
  563. if (config_pair.first == "control-socket") {
  564. ControlSocketParser parser;
  565. SrvConfigPtr srv_cfg = CfgMgr::instance().getStagingCfg();
  566. parser.parse(*srv_cfg, config_pair.second);
  567. continue;
  568. }
  569. if (config_pair.first == "host-reservation-identifiers") {
  570. HostReservationIdsParser4 parser;
  571. parser.parse(config_pair.second);
  572. continue;
  573. }
  574. ParserPtr parser(createGlobalDhcp4ConfigParser(config_pair.first,
  575. config_pair.second));
  576. LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_PARSER_CREATED)
  577. .arg(config_pair.first);
  578. if (config_pair.first == "subnet4") {
  579. subnet_parser = parser;
  580. } else if (config_pair.first == "lease-database") {
  581. leases_parser = parser;
  582. } else if (config_pair.first == "interfaces-config") {
  583. // The interface parser is independent from any other
  584. // parser and can be run here before any other parsers.
  585. iface_parser = parser;
  586. parser->build(config_pair.second);
  587. } else if (config_pair.first == "hooks-libraries") {
  588. // Executing commit will alter currently-loaded hooks
  589. // libraries. Check if the supplied libraries are valid,
  590. // but defer the commit until everything else has committed.
  591. hooks_parser = parser;
  592. parser->build(config_pair.second);
  593. } else if (config_pair.first == "client-classes") {
  594. client_classes_parser = parser;
  595. } else {
  596. // Those parsers should be started before other
  597. // parsers so we can call build straight away.
  598. independent_parsers.push_back(parser);
  599. parser->build(config_pair.second);
  600. // The commit operation here may modify the global storage
  601. // but we need it so as the subnet6 parser can access the
  602. // parsed data.
  603. parser->commit();
  604. }
  605. }
  606. // The class definitions parser is the next one to be run.
  607. std::map<std::string, ConstElementPtr>::const_iterator cc_config =
  608. values_map.find("client-classes");
  609. if (cc_config != values_map.end()) {
  610. config_pair.first = "client-classes";
  611. client_classes_parser->build(cc_config->second);
  612. client_classes_parser->commit();
  613. }
  614. // The subnet parser is the next one to be run.
  615. std::map<std::string, ConstElementPtr>::const_iterator subnet_config =
  616. values_map.find("subnet4");
  617. if (subnet_config != values_map.end()) {
  618. config_pair.first = "subnet4";
  619. subnet_parser->build(subnet_config->second);
  620. }
  621. // Setup the command channel.
  622. configureCommandChannel();
  623. // the leases database parser is the last to be run.
  624. std::map<std::string, ConstElementPtr>::const_iterator leases_config =
  625. values_map.find("lease-database");
  626. if (leases_config != values_map.end()) {
  627. config_pair.first = "lease-database";
  628. leases_parser->build(leases_config->second);
  629. leases_parser->commit();
  630. }
  631. } catch (const isc::Exception& ex) {
  632. LOG_ERROR(dhcp4_logger, DHCP4_PARSER_FAIL)
  633. .arg(config_pair.first).arg(ex.what());
  634. answer = isc::config::createAnswer(1, ex.what());
  635. // An error occurred, so make sure that we restore original data.
  636. rollback = true;
  637. } catch (...) {
  638. // For things like bad_cast in boost::lexical_cast
  639. LOG_ERROR(dhcp4_logger, DHCP4_PARSER_EXCEPTION).arg(config_pair.first);
  640. answer = isc::config::createAnswer(1, "undefined configuration"
  641. " processing error");
  642. // An error occurred, so make sure that we restore original data.
  643. rollback = true;
  644. }
  645. // So far so good, there was no parsing error so let's commit the
  646. // configuration. This will add created subnets and option values into
  647. // the server's configuration.
  648. // This operation should be exception safe but let's make sure.
  649. if (!rollback) {
  650. try {
  651. // No need to commit interface names as this is handled by the
  652. // CfgMgr::commit() function.
  653. // Apply global options in the staging config.
  654. setGlobalParameters4();
  655. // This occurs last as if it succeeds, there is no easy way
  656. // revert it. As a result, the failure to commit a subsequent
  657. // change causes problems when trying to roll back.
  658. if (hooks_parser) {
  659. hooks_parser->commit();
  660. }
  661. }
  662. catch (const isc::Exception& ex) {
  663. LOG_ERROR(dhcp4_logger, DHCP4_PARSER_COMMIT_FAIL).arg(ex.what());
  664. answer = isc::config::createAnswer(2, ex.what());
  665. rollback = true;
  666. } catch (...) {
  667. // For things like bad_cast in boost::lexical_cast
  668. LOG_ERROR(dhcp4_logger, DHCP4_PARSER_COMMIT_EXCEPTION);
  669. answer = isc::config::createAnswer(2, "undefined configuration"
  670. " parsing error");
  671. rollback = true;
  672. }
  673. }
  674. // Rollback changes as the configuration parsing failed.
  675. if (rollback) {
  676. globalContext().reset(new ParserContext(original_context));
  677. // Revert to original configuration of runtime option definitions
  678. // in the libdhcp++.
  679. LibDHCP::revertRuntimeOptionDefs();
  680. return (answer);
  681. }
  682. LOG_INFO(dhcp4_logger, DHCP4_CONFIG_COMPLETE)
  683. .arg(CfgMgr::instance().getStagingCfg()->
  684. getConfigSummary(SrvConfig::CFGSEL_ALL4));
  685. // Everything was fine. Configuration is successful.
  686. answer = isc::config::createAnswer(0, "Configuration successful.");
  687. return (answer);
  688. }
  689. ParserContextPtr& globalContext() {
  690. static ParserContextPtr global_context_ptr(new ParserContext(Option::V4));
  691. return (global_context_ptr);
  692. }
  693. }; // end of isc::dhcp namespace
  694. }; // end of isc namespace