json_config_parser.cc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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 <asiolink/io_address.h>
  8. #include <cc/data.h>
  9. #include <cc/command_interpreter.h>
  10. #include <config/command_mgr.h>
  11. #include <dhcp/libdhcp++.h>
  12. #include <dhcp6/json_config_parser.h>
  13. #include <dhcp6/dhcp6_log.h>
  14. #include <dhcp6/simple_parser6.h>
  15. #include <dhcp/iface_mgr.h>
  16. #include <dhcpsrv/cfg_option.h>
  17. #include <dhcpsrv/cfgmgr.h>
  18. #include <dhcpsrv/pool.h>
  19. #include <dhcpsrv/subnet.h>
  20. #include <dhcpsrv/timer_mgr.h>
  21. #include <dhcpsrv/triplet.h>
  22. #include <dhcpsrv/parsers/client_class_def_parser.h>
  23. #include <dhcpsrv/parsers/dbaccess_parser.h>
  24. #include <dhcpsrv/parsers/dhcp_config_parser.h>
  25. #include <dhcpsrv/parsers/dhcp_parsers.h>
  26. #include <dhcpsrv/parsers/duid_config_parser.h>
  27. #include <dhcpsrv/parsers/expiration_config_parser.h>
  28. #include <dhcpsrv/parsers/host_reservation_parser.h>
  29. #include <dhcpsrv/parsers/host_reservations_list_parser.h>
  30. #include <dhcpsrv/parsers/ifaces_config_parser.h>
  31. #include <log/logger_support.h>
  32. #include <util/encode/hex.h>
  33. #include <util/strutil.h>
  34. #include <boost/algorithm/string.hpp>
  35. #include <boost/foreach.hpp>
  36. #include <boost/lexical_cast.hpp>
  37. #include <boost/scoped_ptr.hpp>
  38. #include <boost/shared_ptr.hpp>
  39. #include <iostream>
  40. #include <limits>
  41. #include <map>
  42. #include <netinet/in.h>
  43. #include <vector>
  44. #include <stdint.h>
  45. using namespace std;
  46. using namespace isc;
  47. using namespace isc::data;
  48. using namespace isc::dhcp;
  49. using namespace isc::asiolink;
  50. namespace {
  51. // Pointers to various parser objects.
  52. typedef boost::shared_ptr<BooleanParser> BooleanParserPtr;
  53. typedef boost::shared_ptr<StringParser> StringParserPtr;
  54. typedef boost::shared_ptr<Uint32Parser> Uint32ParserPtr;
  55. /// @brief Parser for IPv6 pool definitions.
  56. ///
  57. /// This is the IPv6 derivation of the PoolParser class and handles pool
  58. /// definitions, i.e. a list of entries of one of two syntaxes: min-max and
  59. /// prefix/len for IPv6 pools. Pool6 objects are created and stored in chosen
  60. /// PoolStorage container.
  61. ///
  62. /// It is useful for parsing Dhcp6/subnet6[X]/pool parameters.
  63. class Pool6Parser : public PoolParser {
  64. protected:
  65. /// @brief Creates a Pool6 object given a IPv6 prefix and the prefix length.
  66. ///
  67. /// @param addr is the IPv6 prefix of the pool.
  68. /// @param len is the prefix length.
  69. /// @param ptype is the type of IPv6 pool (Pool::PoolType). Note this is
  70. /// passed in as an int32_t and cast to PoolType to accommodate a
  71. /// polymorphic interface.
  72. /// @return returns a PoolPtr to the new Pool4 object.
  73. PoolPtr poolMaker (IOAddress &addr, uint32_t len, int32_t ptype)
  74. {
  75. return (PoolPtr(new Pool6(static_cast<isc::dhcp::Lease::Type>
  76. (ptype), addr, len)));
  77. }
  78. /// @brief Creates a Pool6 object given starting and ending IPv6 addresses.
  79. ///
  80. /// @param min is the first IPv6 address in the pool.
  81. /// @param max is the last IPv6 address in the pool.
  82. /// @param ptype is the type of IPv6 pool (Pool::PoolType). Note this is
  83. /// passed in as an int32_t and cast to PoolType to accommodate a
  84. /// polymorphic interface.
  85. /// @return returns a PoolPtr to the new Pool4 object.
  86. PoolPtr poolMaker (IOAddress &min, IOAddress &max, int32_t ptype)
  87. {
  88. return (PoolPtr(new Pool6(static_cast<isc::dhcp::Lease::Type>
  89. (ptype), min, max)));
  90. }
  91. };
  92. /// @brief Specialization of the pool list parser for DHCPv6
  93. class Pools6ListParser : PoolsListParser {
  94. public:
  95. /// @brief parses the actual structure
  96. ///
  97. /// This method parses the actual list of pools.
  98. ///
  99. /// @param pools storage container in which to store the parsed pool.
  100. /// @param pools_list a list of pool structures
  101. /// @throw isc::dhcp::DhcpConfigError when pool parsing fails
  102. void parse(PoolStoragePtr pools,
  103. isc::data::ConstElementPtr pools_list) {
  104. BOOST_FOREACH(ConstElementPtr pool, pools_list->listValue()) {
  105. Pool6Parser parser;
  106. parser.parse(pools, pool, AF_INET6);
  107. }
  108. }
  109. };
  110. /// @brief Parser for IPv6 prefix delegation definitions.
  111. ///
  112. /// This class handles prefix delegation pool definitions for IPv6 subnets
  113. /// Pool6 objects are created and stored in the given PoolStorage container.
  114. ///
  115. /// PdPool definitions currently support three elements: prefix, prefix-len,
  116. /// and delegated-len, as shown in the example JSON text below:
  117. ///
  118. /// @code
  119. ///
  120. /// {
  121. /// "prefix": "2001:db8:1::",
  122. /// "prefix-len": 64,
  123. /// "delegated-len": 128
  124. /// }
  125. /// @endcode
  126. ///
  127. class PdPoolParser : public isc::data::SimpleParser {
  128. public:
  129. /// @brief Constructor.
  130. ///
  131. PdPoolParser() : options_(new CfgOption()) {
  132. }
  133. /// @brief Builds a prefix delegation pool from the given configuration
  134. ///
  135. /// This function parses configuration entries and creates an instance
  136. /// of a dhcp::Pool6 configured for prefix delegation.
  137. ///
  138. /// @param pools storage container in which to store the parsed pool.
  139. /// @param pd_pool_ pointer to an element that holds configuration entries
  140. /// that define a prefix delegation pool.
  141. ///
  142. /// @throw DhcpConfigError if configuration parsing fails.
  143. void parse(PoolStoragePtr pools, ConstElementPtr pd_pool_) {
  144. std::string addr_str = getString(pd_pool_, "prefix");
  145. uint8_t prefix_len = getUint8(pd_pool_, "prefix-len");
  146. uint8_t delegated_len = getUint8(pd_pool_, "delegated-len");
  147. std::string excluded_prefix_str = "::";
  148. if (pd_pool_->contains("excluded-prefix")) {
  149. excluded_prefix_str = getString(pd_pool_, "excluded-prefix");
  150. }
  151. uint8_t excluded_prefix_len = 0;
  152. if (pd_pool_->contains("excluded-prefix-len")) {
  153. excluded_prefix_len = getUint8(pd_pool_, "excluded-prefix-len");
  154. }
  155. ConstElementPtr option_data = pd_pool_->get("option-data");
  156. if (option_data) {
  157. OptionDataListParser opts_parser(AF_INET6);
  158. opts_parser.parse(options_, option_data);
  159. }
  160. ConstElementPtr user_context = pd_pool_->get("user-context");
  161. if (user_context) {
  162. user_context_ = user_context;
  163. }
  164. // Check the pool parameters. It will throw an exception if any
  165. // of the required parameters are invalid.
  166. try {
  167. // Attempt to construct the local pool.
  168. pool_.reset(new Pool6(IOAddress(addr_str),
  169. prefix_len,
  170. delegated_len,
  171. IOAddress(excluded_prefix_str),
  172. excluded_prefix_len));
  173. // Merge options specified for a pool into pool configuration.
  174. options_->copyTo(*pool_->getCfgOption());
  175. } catch (const std::exception& ex) {
  176. // Some parameters don't exist or are invalid. Since we are not
  177. // aware whether they don't exist or are invalid, let's append
  178. // the position of the pool map element.
  179. isc_throw(isc::dhcp::DhcpConfigError, ex.what()
  180. << " (" << pd_pool_->getPosition() << ")");
  181. }
  182. if (user_context_) {
  183. pool_->setUserContext(user_context_);
  184. }
  185. // Add the local pool to the external storage ptr.
  186. pools->push_back(pool_);
  187. }
  188. private:
  189. /// @brief Get an uint8_t value
  190. ///
  191. /// Instantiation of getIntType() to uint8_t
  192. ///
  193. /// @param scope specified parameter will be extracted from this scope
  194. /// @param name name of the parameter
  195. /// @return uint8_t value
  196. /// @throw isc::dhcp::DhcpConfigError when it is not an uint8_t
  197. uint8_t getUint8(ConstElementPtr scope, const std::string& name) {
  198. return (getIntType<uint8_t>(scope, name));
  199. }
  200. /// Pointer to the created pool object.
  201. isc::dhcp::Pool6Ptr pool_;
  202. /// A storage for pool specific option values.
  203. CfgOptionPtr options_;
  204. isc::data::ConstElementPtr user_context_;
  205. };
  206. /// @brief Parser for a list of prefix delegation pools.
  207. ///
  208. /// This parser iterates over a list of prefix delegation pool entries and
  209. /// creates pool instances for each one. If the parsing is successful, the
  210. /// collection of pools is committed to the provided storage.
  211. class PdPoolsListParser : public PoolsListParser {
  212. public:
  213. /// @brief Parse configuration entries.
  214. ///
  215. /// This function parses configuration entries and creates instances
  216. /// of prefix delegation pools .
  217. ///
  218. /// @param storage is the pool storage in which to store the parsed
  219. /// @param pd_pool_list pointer to an element that holds entries
  220. /// that define a prefix delegation pool.
  221. ///
  222. /// @throw DhcpConfigError if configuration parsing fails.
  223. void parse(PoolStoragePtr pools,
  224. isc::data::ConstElementPtr pd_pool_list) {
  225. // Loop through the list of pd pools.
  226. BOOST_FOREACH(ConstElementPtr pd_pool, pd_pool_list->listValue()) {
  227. PdPoolParser parser;
  228. parser.parse(pools, pd_pool);
  229. }
  230. }
  231. };
  232. /// @anchor Subnet6ConfigParser
  233. /// @brief This class parses a single IPv6 subnet.
  234. ///
  235. /// This is the IPv6 derivation of the SubnetConfigParser class and it parses
  236. /// the whole subnet definition. It creates parsersfor received configuration
  237. /// parameters as needed.
  238. class Subnet6ConfigParser : public SubnetConfigParser {
  239. public:
  240. /// @brief Constructor
  241. ///
  242. /// stores global scope parameters, options, option definitions.
  243. Subnet6ConfigParser()
  244. :SubnetConfigParser(AF_INET6) {
  245. }
  246. /// @brief Parses a single IPv6 subnet configuration and adds to the
  247. /// Configuration Manager.
  248. ///
  249. /// @param subnet A new subnet being configured.
  250. /// @return a pointer to created Subnet6 object
  251. Subnet6Ptr parse(ConstElementPtr subnet) {
  252. /// Parse all pools first.
  253. ConstElementPtr pools = subnet->get("pools");
  254. if (pools) {
  255. Pools6ListParser parser;
  256. parser.parse(pools_, pools);
  257. }
  258. ConstElementPtr pd_pools = subnet->get("pd-pools");
  259. if (pd_pools) {
  260. PdPoolsListParser parser;
  261. parser.parse(pools_, pd_pools);
  262. }
  263. SubnetPtr generic = SubnetConfigParser::parse(subnet);
  264. if (!generic) {
  265. isc_throw(DhcpConfigError,
  266. "Failed to create an IPv6 subnet (" <<
  267. subnet->getPosition() << ")");
  268. }
  269. Subnet6Ptr sn6ptr = boost::dynamic_pointer_cast<Subnet6>(subnet_);
  270. if (!sn6ptr) {
  271. // If we hit this, it is a programming error.
  272. isc_throw(Unexpected,
  273. "Invalid Subnet6 cast in Subnet6ConfigParser::parse");
  274. }
  275. // Set relay information if it was provided
  276. if (relay_info_) {
  277. sn6ptr->setRelayInfo(*relay_info_);
  278. }
  279. // Parse Host Reservations for this subnet if any.
  280. ConstElementPtr reservations = subnet->get("reservations");
  281. if (reservations) {
  282. HostReservationsListParser<HostReservationParser6> parser;
  283. parser.parse(subnet_->getID(), reservations);
  284. }
  285. return (sn6ptr);
  286. }
  287. protected:
  288. /// @brief Issues a DHCP6 server specific warning regarding duplicate subnet
  289. /// options.
  290. ///
  291. /// @param code is the numeric option code of the duplicate option
  292. /// @param addr is the subnet address
  293. /// @todo A means to know the correct logger and perhaps a common
  294. /// message would allow this message to be emitted by the base class.
  295. virtual void duplicate_option_warning(uint32_t code,
  296. isc::asiolink::IOAddress& addr) {
  297. LOG_WARN(dhcp6_logger, DHCP6_CONFIG_OPTION_DUPLICATE)
  298. .arg(code).arg(addr.toText());
  299. }
  300. /// @brief Instantiates the IPv6 Subnet based on a given IPv6 address
  301. /// and prefix length.
  302. ///
  303. /// @param addr is IPv6 prefix of the subnet.
  304. /// @param len is the prefix length
  305. void initSubnet(isc::data::ConstElementPtr params,
  306. isc::asiolink::IOAddress addr, uint8_t len) {
  307. // Get all 'time' parameters using inheritance.
  308. // If the subnet-specific value is defined then use it, else
  309. // use the global value. The global value must always be
  310. // present. If it is not, it is an internal error and exception
  311. // is thrown.
  312. Triplet<uint32_t> t1 = getInteger(params, "renew-timer");
  313. Triplet<uint32_t> t2 = getInteger(params, "rebind-timer");
  314. Triplet<uint32_t> pref = getInteger(params, "preferred-lifetime");
  315. Triplet<uint32_t> valid = getInteger(params, "valid-lifetime");
  316. // Subnet ID is optional. If it is not supplied the value of 0 is used,
  317. // which means autogenerate. The value was inserted earlier by calling
  318. // SimpleParser6::setAllDefaults.
  319. SubnetID subnet_id = static_cast<SubnetID>(getInteger(params, "id"));
  320. // We want to log whether rapid-commit is enabled, so we get this
  321. // before the actual subnet creation.
  322. bool rapid_commit = getBoolean(params, "rapid-commit");
  323. std::ostringstream output;
  324. output << addr << "/" << static_cast<int>(len)
  325. << " with params t1=" << t1 << ", t2="
  326. << t2 << ", preferred-lifetime=" << pref
  327. << ", valid-lifetime=" << valid
  328. << ", rapid-commit is " << (rapid_commit ? "enabled" : "disabled");
  329. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_NEW_SUBNET).arg(output.str());
  330. // Create a new subnet.
  331. Subnet6* subnet6 = new Subnet6(addr, len, t1, t2, pref, valid,
  332. subnet_id);
  333. subnet_.reset(subnet6);
  334. // Enable or disable Rapid Commit option support for the subnet.
  335. subnet6->setRapidCommit(rapid_commit);
  336. // Get interface-id option content. For now we support string
  337. // representation only
  338. std::string ifaceid = getString(params, "interface-id");
  339. std::string iface = getString(params, "interface");
  340. // Specifying both interface for locally reachable subnets and
  341. // interface id for relays is mutually exclusive. Need to test for
  342. // this condition.
  343. if (!ifaceid.empty() && !iface.empty()) {
  344. isc_throw(isc::dhcp::DhcpConfigError,
  345. "parser error: interface (defined for locally reachable "
  346. "subnets) and interface-id (defined for subnets reachable"
  347. " via relays) cannot be defined at the same time for "
  348. "subnet " << addr << "/" << (int)len << "("
  349. << params->getPosition() << ")");
  350. }
  351. // Configure interface-id for remote interfaces, if defined
  352. if (!ifaceid.empty()) {
  353. OptionBuffer tmp(ifaceid.begin(), ifaceid.end());
  354. OptionPtr opt(new Option(Option::V6, D6O_INTERFACE_ID, tmp));
  355. subnet6->setInterfaceId(opt);
  356. }
  357. /// client-class processing is now generic and handled in the common
  358. /// code (see @ref isc::data::SubnetConfigParser::createSubnet)
  359. }
  360. };
  361. /// @brief this class parses a list of DHCP6 subnets
  362. ///
  363. /// This is a wrapper parser that handles the whole list of Subnet6
  364. /// definitions. It iterates over all entries and creates Subnet6ConfigParser
  365. /// for each entry.
  366. class Subnets6ListConfigParser : public isc::data::SimpleParser {
  367. public:
  368. /// @brief parses contents of the list
  369. ///
  370. /// Iterates over all entries on the list, parses its content
  371. /// (by instantiating Subnet6ConfigParser) and adds to specified
  372. /// configuration.
  373. ///
  374. /// @param cfg configuration (parsed subnets will be stored here)
  375. /// @param subnets_list pointer to a list of IPv6 subnets
  376. /// @throw DhcpConfigError if CfgMgr rejects the subnet (e.g. subnet-id is a duplicate)
  377. size_t parse(SrvConfigPtr cfg, ConstElementPtr subnets_list) {
  378. size_t cnt = 0;
  379. BOOST_FOREACH(ConstElementPtr subnet_json, subnets_list->listValue()) {
  380. Subnet6ConfigParser parser;
  381. Subnet6Ptr subnet = parser.parse(subnet_json);
  382. // Adding a subnet to the Configuration Manager may fail if the
  383. // subnet id is invalid (duplicate). Thus, we catch exceptions
  384. // here to append a position in the configuration string.
  385. try {
  386. cfg->getCfgSubnets6()->add(subnet);
  387. cnt++;
  388. } catch (const std::exception& ex) {
  389. isc_throw(DhcpConfigError, ex.what() << " ("
  390. << subnet_json->getPosition() << ")");
  391. }
  392. }
  393. return (cnt);
  394. }
  395. };
  396. /// @brief Parser for list of RSOO options
  397. ///
  398. /// This parser handles a Dhcp6/relay-supplied-options entry. It contains a
  399. /// list of RSOO-enabled options which should be sent back to the client.
  400. ///
  401. /// The options on this list can be specified using an option code or option
  402. /// name. Therefore, the values on the list should always be enclosed in
  403. /// "quotes".
  404. class RSOOListConfigParser : public isc::data::SimpleParser {
  405. public:
  406. /// @brief parses parameters value
  407. ///
  408. /// Parses configuration entry (list of sources) and adds each element
  409. /// to the RSOO list.
  410. ///
  411. /// @param value pointer to the content of parsed values
  412. /// @param cfg server configuration (RSOO will be stored here)
  413. void parse(SrvConfigPtr cfg, isc::data::ConstElementPtr value) {
  414. try {
  415. BOOST_FOREACH(ConstElementPtr source_elem, value->listValue()) {
  416. std::string option_str = source_elem->stringValue();
  417. // This option can be either code (integer) or name. Let's try code first
  418. int64_t code = 0;
  419. try {
  420. code = boost::lexical_cast<int64_t>(option_str);
  421. // Protect against the negative value and too high value.
  422. if (code < 0) {
  423. isc_throw(BadValue, "invalid option code value specified '"
  424. << option_str << "', the option code must be a"
  425. " non-negative value");
  426. } else if (code > std::numeric_limits<uint16_t>::max()) {
  427. isc_throw(BadValue, "invalid option code value specified '"
  428. << option_str << "', the option code must not be"
  429. " greater than '" << std::numeric_limits<uint16_t>::max()
  430. << "'");
  431. }
  432. } catch (const boost::bad_lexical_cast &) {
  433. // Oh well, it's not a number
  434. }
  435. if (!code) {
  436. const OptionDefinitionPtr def = LibDHCP::getOptionDef(DHCP6_OPTION_SPACE,
  437. option_str);
  438. if (def) {
  439. code = def->getCode();
  440. } else {
  441. isc_throw(BadValue, "unable to find option code for the "
  442. " specified option name '" << option_str << "'"
  443. " while parsing the list of enabled"
  444. " relay-supplied-options");
  445. }
  446. }
  447. cfg->getCfgRSOO()->enable(code);
  448. }
  449. } catch (const std::exception& ex) {
  450. // Rethrow exception with the appended position of the parsed
  451. // element.
  452. isc_throw(DhcpConfigError, ex.what() << " (" << value->getPosition() << ")");
  453. }
  454. }
  455. };
  456. /// @brief Parser that takes care of global DHCPv6 parameters.
  457. ///
  458. /// See @ref parse method for a list of supported parameters.
  459. class Dhcp6ConfigParser : public isc::data::SimpleParser {
  460. public:
  461. /// @brief Sets global parameters in staging configuration
  462. ///
  463. /// @param global global configuration scope
  464. /// @param cfg Server configuration (parsed parameters will be stored here)
  465. ///
  466. /// Currently this method sets the following global parameters:
  467. ///
  468. /// - decline-probation-period
  469. /// - dhcp4o6-port
  470. ///
  471. /// @throw DhcpConfigError if parameters are missing or
  472. /// or having incorrect values.
  473. void parse(SrvConfigPtr srv_config, ConstElementPtr global) {
  474. // Set the probation period for decline handling.
  475. uint32_t probation_period =
  476. getUint32(global, "decline-probation-period");
  477. srv_config->setDeclinePeriod(probation_period);
  478. // Set the DHCPv4-over-DHCPv6 interserver port.
  479. // @todo Change for uint16_t
  480. uint32_t dhcp4o6_port = getUint32(global, "dhcp4o6-port");
  481. srv_config->setDhcp4o6Port(dhcp4o6_port);
  482. }
  483. private:
  484. /// @brief Returns a value converted to uint32_t
  485. ///
  486. /// Instantiation of getIntType() to uint32_t
  487. ///
  488. /// @param scope specified parameter will be extracted from this scope
  489. /// @param name name of the parameter
  490. /// @return an uint32_t value
  491. uint32_t getUint32(isc::data::ConstElementPtr scope,
  492. const std::string& name) {
  493. return (getIntType<uint32_t>(scope, name));
  494. }
  495. };
  496. } // anonymous namespace
  497. namespace isc {
  498. namespace dhcp {
  499. /// @brief Initialize the command channel based on the staging configuration
  500. ///
  501. /// Only close the current channel, if the new channel configuration is
  502. /// different. This avoids disconnecting a client and hence not sending them
  503. /// a command result, unless they specifically alter the channel configuration.
  504. /// In that case the user simply has to accept they'll be disconnected.
  505. ///
  506. void configureCommandChannel() {
  507. // Get new socket configuration.
  508. ConstElementPtr sock_cfg =
  509. CfgMgr::instance().getStagingCfg()->getControlSocketInfo();
  510. // Get current socket configuration.
  511. ConstElementPtr current_sock_cfg =
  512. CfgMgr::instance().getCurrentCfg()->getControlSocketInfo();
  513. // Determine if the socket configuration has changed. It has if
  514. // both old and new configuration is specified but respective
  515. // data elements are't equal.
  516. bool sock_changed = (sock_cfg && current_sock_cfg &&
  517. !sock_cfg->equals(*current_sock_cfg));
  518. // If the previous or new socket configuration doesn't exist or
  519. // the new configuration differs from the old configuration we
  520. // close the exisitng socket and open a new socket as appropriate.
  521. // Note that closing an existing socket means the clien will not
  522. // receive the configuration result.
  523. if (!sock_cfg || !current_sock_cfg || sock_changed) {
  524. // Close the existing socket (if any).
  525. isc::config::CommandMgr::instance().closeCommandSocket();
  526. if (sock_cfg) {
  527. // This will create a control socket and install the external
  528. // socket in IfaceMgr. That socket will be monitored when
  529. // Dhcp4Srv::receivePacket() calls IfaceMgr::receive4() and
  530. // callback in CommandMgr will be called, if necessary.
  531. isc::config::CommandMgr::instance().openCommandSocket(sock_cfg);
  532. }
  533. }
  534. }
  535. isc::data::ConstElementPtr
  536. configureDhcp6Server(Dhcpv6Srv&, isc::data::ConstElementPtr config_set) {
  537. if (!config_set) {
  538. ConstElementPtr answer = isc::config::createAnswer(1,
  539. string("Can't parse NULL config"));
  540. return (answer);
  541. }
  542. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND,
  543. DHCP6_CONFIG_START).arg(config_set->str());
  544. // Before starting any subnet operations, let's reset the subnet-id counter,
  545. // so newly recreated configuration starts with first subnet-id equal 1.
  546. Subnet::resetSubnetID();
  547. // Remove any existing timers.
  548. TimerMgr::instance()->unregisterTimers();
  549. // Revert any runtime option definitions configured so far and not committed.
  550. LibDHCP::revertRuntimeOptionDefs();
  551. // Let's set empty container in case a user hasn't specified any configuration
  552. // for option definitions. This is equivalent to commiting empty container.
  553. LibDHCP::setRuntimeOptionDefs(OptionDefSpaceContainer());
  554. // Some of the parsers alter state of the system that can't easily
  555. // be undone. (Or alter it in a way such that undoing the change
  556. // has the same risk of failure as doing the change.)
  557. HooksLibrariesParser hooks_parser;
  558. // This is a way to convert ConstElementPtr to ElementPtr.
  559. // We need a config that can be edited, because we will insert
  560. // default values and will insert derived values as well.
  561. ElementPtr mutable_cfg = boost::const_pointer_cast<Element>(config_set);
  562. // answer will hold the result.
  563. ConstElementPtr answer;
  564. // rollback informs whether error occurred and original data
  565. // have to be restored to global storages.
  566. bool rollback = false;
  567. // config_pair holds the details of the current parser when iterating over
  568. // the parsers. It is declared outside the loop so in case of error, the
  569. // name of the failing parser can be retrieved within the "catch" clause.
  570. ConfigPair config_pair;
  571. try {
  572. SrvConfigPtr srv_config = CfgMgr::instance().getStagingCfg();
  573. // Set all default values if not specified by the user.
  574. SimpleParser6::setAllDefaults(mutable_cfg);
  575. // And now derive (inherit) global parameters to subnets, if not specified.
  576. SimpleParser6::deriveParameters(mutable_cfg);
  577. // Make parsers grouping.
  578. const std::map<std::string, ConstElementPtr>& values_map =
  579. mutable_cfg->mapValue();
  580. // We need definitions first
  581. ConstElementPtr option_defs = mutable_cfg->get("option-def");
  582. if (option_defs) {
  583. OptionDefListParser parser;
  584. CfgOptionDefPtr cfg_option_def = srv_config->getCfgOptionDef();
  585. parser.parse(cfg_option_def, option_defs);
  586. }
  587. BOOST_FOREACH(config_pair, values_map) {
  588. // In principle we could have the following code structured as a series
  589. // of long if else if clauses. That would give a marginal performance
  590. // boost, but would make the code less readable. We had serious issues
  591. // with the parser code debugability, so I decided to keep it as a
  592. // series of independent ifs.
  593. if (config_pair.first == "option-def") {
  594. // This is converted to SimpleParser and is handled already above.
  595. continue;
  596. }
  597. if (config_pair.first == "option-data") {
  598. OptionDataListParser parser(AF_INET6);
  599. CfgOptionPtr cfg_option = srv_config->getCfgOption();
  600. parser.parse(cfg_option, config_pair.second);
  601. continue;
  602. }
  603. if (config_pair.first == "mac-sources") {
  604. MACSourcesListConfigParser parser;
  605. CfgMACSource& mac_source = srv_config->getMACSources();
  606. parser.parse(mac_source, config_pair.second);
  607. continue;
  608. }
  609. if (config_pair.first == "control-socket") {
  610. ControlSocketParser parser;
  611. parser.parse(*srv_config, config_pair.second);
  612. continue;
  613. }
  614. if (config_pair.first == "host-reservation-identifiers") {
  615. HostReservationIdsParser6 parser;
  616. parser.parse(config_pair.second);
  617. continue;
  618. }
  619. if (config_pair.first == "server-id") {
  620. DUIDConfigParser parser;
  621. const CfgDUIDPtr& cfg = srv_config->getCfgDUID();
  622. parser.parse(cfg, config_pair.second);
  623. continue;
  624. }
  625. if (config_pair.first == "interfaces-config") {
  626. IfacesConfigParser parser(AF_INET6);
  627. CfgIfacePtr cfg_iface = srv_config->getCfgIface();
  628. parser.parse(cfg_iface, config_pair.second);
  629. continue;
  630. }
  631. if (config_pair.first == "expired-leases-processing") {
  632. ExpirationConfigParser parser;
  633. parser.parse(config_pair.second);
  634. continue;
  635. }
  636. if (config_pair.first == "hooks-libraries") {
  637. hooks_parser.parse(config_pair.second);
  638. hooks_parser.verifyLibraries();
  639. continue;
  640. }
  641. if (config_pair.first == "dhcp-ddns") {
  642. // Apply defaults if not in short cut
  643. if (!D2ClientConfigParser::isShortCutDisabled(config_pair.second)) {
  644. D2ClientConfigParser::setAllDefaults(config_pair.second);
  645. }
  646. D2ClientConfigParser parser;
  647. D2ClientConfigPtr cfg = parser.parse(config_pair.second);
  648. srv_config->setD2ClientConfig(cfg);
  649. continue;
  650. }
  651. if (config_pair.first =="client-classes") {
  652. ClientClassDefListParser parser;
  653. ClientClassDictionaryPtr dictionary =
  654. parser.parse(config_pair.second, AF_INET6);
  655. srv_config->setClientClassDictionary(dictionary);
  656. continue;
  657. }
  658. // Please move at the end when migration will be finished.
  659. if (config_pair.first == "lease-database") {
  660. DbAccessParser parser(DbAccessParser::LEASE_DB);
  661. CfgDbAccessPtr cfg_db_access = srv_config->getCfgDbAccess();
  662. parser.parse(cfg_db_access, config_pair.second);
  663. continue;
  664. }
  665. if (config_pair.first == "hosts-database") {
  666. DbAccessParser parser(DbAccessParser::HOSTS_DB);
  667. CfgDbAccessPtr cfg_db_access = srv_config->getCfgDbAccess();
  668. parser.parse(cfg_db_access, config_pair.second);
  669. continue;
  670. }
  671. if (config_pair.first == "subnet6") {
  672. SrvConfigPtr srv_cfg = CfgMgr::instance().getStagingCfg();
  673. Subnets6ListConfigParser subnets_parser;
  674. // parse() returns number of subnets parsed. We may log it one day.
  675. subnets_parser.parse(srv_cfg, config_pair.second);
  676. continue;
  677. }
  678. // Timers are not used in the global scope. Their values are derived
  679. // to specific subnets (see SimpleParser6::deriveParameters).
  680. // decline-probation-period and dhcp4o6-port are handled in the
  681. // global_parser.parse() which sets global parameters.
  682. if ( (config_pair.first == "renew-timer") ||
  683. (config_pair.first == "rebind-timer") ||
  684. (config_pair.first == "preferred-lifetime") ||
  685. (config_pair.first == "valid-lifetime") ||
  686. (config_pair.first == "decline-probation-period") ||
  687. (config_pair.first == "dhcp4o6-port")) {
  688. continue;
  689. }
  690. if (config_pair.first == "relay-supplied-options") {
  691. RSOOListConfigParser parser;
  692. parser.parse(srv_config, config_pair.second);
  693. continue;
  694. }
  695. // If we got here, no code handled this parameter, so we bail out.
  696. isc_throw(DhcpConfigError,
  697. "unsupported global configuration parameter: " << config_pair.first
  698. << " (" << config_pair.second->getPosition() << ")");
  699. }
  700. // Setup the command channel.
  701. configureCommandChannel();
  702. // Apply global options in the staging config.
  703. Dhcp6ConfigParser global_parser;
  704. global_parser.parse(srv_config, mutable_cfg);
  705. } catch (const isc::Exception& ex) {
  706. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_FAIL)
  707. .arg(config_pair.first).arg(ex.what());
  708. answer = isc::config::createAnswer(1, ex.what());
  709. // An error occurred, so make sure that we restore original data.
  710. rollback = true;
  711. } catch (...) {
  712. // for things like bad_cast in boost::lexical_cast
  713. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_EXCEPTION).arg(config_pair.first);
  714. answer = isc::config::createAnswer(1, "undefined configuration"
  715. " processing error");
  716. // An error occurred, so make sure that we restore original data.
  717. rollback = true;
  718. }
  719. // So far so good, there was no parsing error so let's commit the
  720. // configuration. This will add created subnets and option values into
  721. // the server's configuration.
  722. // This operation should be exception safe but let's make sure.
  723. if (!rollback) {
  724. try {
  725. // No need to commit interface names as this is handled by the
  726. // CfgMgr::commit() function.
  727. // This occurs last as if it succeeds, there is no easy way to
  728. // revert it. As a result, the failure to commit a subsequent
  729. // change causes problems when trying to roll back.
  730. hooks_parser.loadLibraries();
  731. // Apply staged D2ClientConfig, used to be done by parser commit
  732. D2ClientConfigPtr cfg;
  733. cfg = CfgMgr::instance().getStagingCfg()->getD2ClientConfig();
  734. CfgMgr::instance().setD2ClientConfig(cfg);
  735. }
  736. catch (const isc::Exception& ex) {
  737. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(ex.what());
  738. answer = isc::config::createAnswer(2, ex.what());
  739. // An error occurred, so make sure to restore the original data.
  740. rollback = true;
  741. } catch (...) {
  742. // for things like bad_cast in boost::lexical_cast
  743. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_EXCEPTION);
  744. answer = isc::config::createAnswer(2, "undefined configuration"
  745. " parsing error");
  746. // An error occurred, so make sure to restore the original data.
  747. rollback = true;
  748. }
  749. }
  750. // Rollback changes as the configuration parsing failed.
  751. if (rollback) {
  752. // Revert to original configuration of runtime option definitions
  753. // in the libdhcp++.
  754. LibDHCP::revertRuntimeOptionDefs();
  755. return (answer);
  756. }
  757. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_COMPLETE)
  758. .arg(CfgMgr::instance().getStagingCfg()->
  759. getConfigSummary(SrvConfig::CFGSEL_ALL6));
  760. // Everything was fine. Configuration is successful.
  761. answer = isc::config::createAnswer(0, "Configuration successful.");
  762. return (answer);
  763. }
  764. }; // end of isc::dhcp namespace
  765. }; // end of isc namespace