json_config_parser.cc 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. // Copyright (C) 2012-2016 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <config.h>
  7. #include <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 <defaults.h>
  35. #include <boost/algorithm/string.hpp>
  36. #include <boost/foreach.hpp>
  37. #include <boost/lexical_cast.hpp>
  38. #include <boost/scoped_ptr.hpp>
  39. #include <boost/shared_ptr.hpp>
  40. #include <iostream>
  41. #include <limits>
  42. #include <map>
  43. #include <netinet/in.h>
  44. #include <vector>
  45. #include <stdint.h>
  46. using namespace std;
  47. using namespace isc;
  48. using namespace isc::data;
  49. using namespace isc::dhcp;
  50. using namespace isc::asiolink;
  51. namespace {
  52. // Pointers to various parser objects.
  53. typedef boost::shared_ptr<BooleanParser> BooleanParserPtr;
  54. typedef boost::shared_ptr<StringParser> StringParserPtr;
  55. typedef boost::shared_ptr<Uint32Parser> Uint32ParserPtr;
  56. /// @brief Parser for IPv6 pool definitions.
  57. ///
  58. /// This is the IPv6 derivation of the PoolParser class and handles pool
  59. /// definitions, i.e. a list of entries of one of two syntaxes: min-max and
  60. /// prefix/len for IPv6 pools. Pool6 objects are created and stored in chosen
  61. /// PoolStorage container.
  62. ///
  63. /// It is useful for parsing Dhcp6/subnet6[X]/pool parameters.
  64. class Pool6Parser : public PoolParser {
  65. public:
  66. /// @brief Constructor.
  67. ///
  68. /// @param param_name name of the parameter. Note, it is passed through
  69. /// but unused, parameter is currently always "Dhcp6/subnet6[X]/pool"
  70. /// @param pools storage container in which to store the parsed pool
  71. /// upon "commit"
  72. Pool6Parser(const std::string& param_name, PoolStoragePtr pools)
  73. :PoolParser(param_name, pools, AF_INET6) {
  74. }
  75. protected:
  76. /// @brief Creates a Pool6 object given a IPv6 prefix and the prefix length.
  77. ///
  78. /// @param addr is the IPv6 prefix of the pool.
  79. /// @param len is the prefix length.
  80. /// @param ptype is the type of IPv6 pool (Pool::PoolType). Note this is
  81. /// passed in as an int32_t and cast to PoolType to accommodate a
  82. /// polymorphic interface.
  83. /// @return returns a PoolPtr to the new Pool4 object.
  84. PoolPtr poolMaker (IOAddress &addr, uint32_t len, int32_t ptype)
  85. {
  86. return (PoolPtr(new Pool6(static_cast<isc::dhcp::Lease::Type>
  87. (ptype), addr, len)));
  88. }
  89. /// @brief Creates a Pool6 object given starting and ending IPv6 addresses.
  90. ///
  91. /// @param min is the first IPv6 address in the pool.
  92. /// @param max is the last IPv6 address in the pool.
  93. /// @param ptype is the type of IPv6 pool (Pool::PoolType). Note this is
  94. /// passed in as an int32_t and cast to PoolType to accommodate a
  95. /// polymorphic interface.
  96. /// @return returns a PoolPtr to the new Pool4 object.
  97. PoolPtr poolMaker (IOAddress &min, IOAddress &max, int32_t ptype)
  98. {
  99. return (PoolPtr(new Pool6(static_cast<isc::dhcp::Lease::Type>
  100. (ptype), min, max)));
  101. }
  102. };
  103. class Pools6ListParser : public PoolsListParser {
  104. public:
  105. Pools6ListParser(const std::string& dummy, PoolStoragePtr pools)
  106. :PoolsListParser(dummy, pools) {
  107. }
  108. protected:
  109. virtual ParserPtr poolParserMaker(PoolStoragePtr storage) {
  110. return (ParserPtr(new Pool6Parser("pool", storage)));
  111. }
  112. };
  113. /// @brief Parser for IPv6 prefix delegation definitions.
  114. ///
  115. /// This class handles prefix delegation pool definitions for IPv6 subnets
  116. /// Pool6 objects are created and stored in the given PoolStorage container.
  117. ///
  118. /// PdPool definitions currently support three elements: prefix, prefix-len,
  119. /// and delegated-len, as shown in the example JSON text below:
  120. ///
  121. /// @code
  122. ///
  123. /// {
  124. /// "prefix": "2001:db8:1::",
  125. /// "prefix-len": 64,
  126. /// "delegated-len": 128
  127. /// }
  128. /// @endcode
  129. ///
  130. class PdPoolParser : public DhcpConfigParser {
  131. public:
  132. /// @brief Constructor.
  133. ///
  134. /// @param param_name name of the parameter. Note, it is passed through
  135. /// but unused, parameter is currently always "Dhcp6/subnet6[X]/pool"
  136. /// @param pools storage container in which to store the parsed pool
  137. /// upon "commit"
  138. PdPoolParser(const std::string&, PoolStoragePtr pools)
  139. : uint32_values_(new Uint32Storage()),
  140. string_values_(new StringStorage()), pools_(pools),
  141. options_(new CfgOption()) {
  142. if (!pools_) {
  143. isc_throw(isc::dhcp::DhcpConfigError,
  144. "PdPoolParser context storage may not be NULL");
  145. }
  146. }
  147. /// @brief Builds a prefix delegation pool from the given configuration
  148. ///
  149. /// This function parses configuration entries and creates an instance
  150. /// of a dhcp::Pool6 configured for prefix delegation.
  151. ///
  152. /// @param pd_pool_ pointer to an element that holds configuration entries
  153. /// that define a prefix delegation pool.
  154. ///
  155. /// @throw DhcpConfigError if configuration parsing fails.
  156. virtual void build(ConstElementPtr pd_pool_) {
  157. // Parse the elements that make up the option definition.
  158. BOOST_FOREACH(ConfigPair param, pd_pool_->mapValue()) {
  159. std::string entry(param.first);
  160. ParserPtr parser;
  161. if (entry == "prefix" || entry =="excluded-prefix") {
  162. StringParserPtr str_parser(new StringParser(entry,
  163. string_values_));
  164. parser = str_parser;
  165. } else if (entry == "prefix-len" || entry == "delegated-len" ||
  166. entry == "excluded-prefix-len") {
  167. Uint32ParserPtr code_parser(new Uint32Parser(entry,
  168. uint32_values_));
  169. parser = code_parser;
  170. } else if (entry == "option-data") {
  171. OptionDataListParser opts_parser(AF_INET6);
  172. opts_parser.parse(options_, param.second);
  173. // OptionDataListParser is converted to SimpleParser already,
  174. // no need to go through build/commit phases.
  175. continue;
  176. } else if (entry == "user-context") {
  177. user_context_ = param.second;
  178. continue; // no parser to remember, simply store the value
  179. } else {
  180. isc_throw(DhcpConfigError, "unsupported parameter: " << entry
  181. << " (" << param.second->getPosition() << ")");
  182. }
  183. parser->build(param.second);
  184. parser->commit();
  185. }
  186. // Try to obtain the pool parameters. It will throw an exception if any
  187. // of the required parameters are not present or invalid.
  188. try {
  189. const std::string addr_str = string_values_->getParam("prefix");
  190. const uint32_t prefix_len = uint32_values_->getParam("prefix-len");
  191. const uint32_t delegated_len = uint32_values_->getParam("delegated-len");
  192. const std::string excluded_prefix_str =
  193. string_values_->getOptionalParam("excluded-prefix", "::");
  194. const uint32_t excluded_prefix_len =
  195. uint32_values_->getOptionalParam("excluded-prefix-len", 0);
  196. // Attempt to construct the local pool.
  197. pool_.reset(new Pool6(IOAddress(addr_str), prefix_len,
  198. delegated_len, IOAddress(excluded_prefix_str),
  199. excluded_prefix_len));
  200. // Merge options specified for a pool into pool configuration.
  201. options_->copyTo(*pool_->getCfgOption());
  202. } catch (const std::exception& ex) {
  203. // Some parameters don't exist or are invalid. Since we are not
  204. // aware whether they don't exist or are invalid, let's append
  205. // the position of the pool map element.
  206. isc_throw(isc::dhcp::DhcpConfigError, ex.what()
  207. << " (" << pd_pool_->getPosition() << ")");
  208. }
  209. if (user_context_) {
  210. pool_->setUserContext(user_context_);
  211. }
  212. }
  213. // @brief Commits the constructed local pool to the pool storage.
  214. virtual void commit() {
  215. // Add the local pool to the external storage ptr.
  216. pools_->push_back(pool_);
  217. }
  218. protected:
  219. /// Storage for subnet-specific integer values.
  220. Uint32StoragePtr uint32_values_;
  221. /// Storage for subnet-specific string values.
  222. StringStoragePtr string_values_;
  223. /// Parsers are stored here.
  224. ParserCollection parsers_;
  225. /// Pointer to the created pool object.
  226. isc::dhcp::Pool6Ptr pool_;
  227. /// Pointer to storage to which the local pool is written upon commit.
  228. isc::dhcp::PoolStoragePtr pools_;
  229. /// A storage for pool specific option values.
  230. CfgOptionPtr options_;
  231. isc::data::ConstElementPtr user_context_;
  232. };
  233. /// @brief Parser for a list of prefix delegation pools.
  234. ///
  235. /// This parser iterates over a list of prefix delegation pool entries and
  236. /// creates pool instances for each one. If the parsing is successful, the
  237. /// collection of pools is committed to the provided storage.
  238. class PdPoolListParser : public DhcpConfigParser {
  239. public:
  240. /// @brief Constructor.
  241. ///
  242. /// @param dummy first argument is ignored, all Parser constructors
  243. /// accept string as first argument.
  244. /// @param storage is the pool storage in which to store the parsed
  245. /// pools in this list
  246. /// @throw isc::dhcp::DhcpConfigError if storage is null.
  247. PdPoolListParser(const std::string&, PoolStoragePtr pools)
  248. : local_pools_(new PoolStorage()), pools_(pools) {
  249. if (!pools_) {
  250. isc_throw(isc::dhcp::DhcpConfigError,
  251. "PdPoolListParser pools storage may not be NULL");
  252. }
  253. }
  254. /// @brief Parse configuration entries.
  255. ///
  256. /// This function parses configuration entries and creates instances
  257. /// of prefix delegation pools .
  258. ///
  259. /// @param pd_pool_list pointer to an element that holds entries
  260. /// that define a prefix delegation pool.
  261. ///
  262. /// @throw DhcpConfigError if configuration parsing fails.
  263. void build(isc::data::ConstElementPtr pd_pool_list) {
  264. // Make sure the local list is empty.
  265. local_pools_.reset(new PoolStorage());
  266. // Make sure we have a configuration elements to parse.
  267. if (!pd_pool_list) {
  268. isc_throw(DhcpConfigError,
  269. "PdPoolListParser: list of pool definitions is NULL");
  270. }
  271. // Loop through the list of pd pools.
  272. BOOST_FOREACH(ConstElementPtr pd_pool, pd_pool_list->listValue()) {
  273. boost::shared_ptr<PdPoolParser>
  274. // Create the PdPool parser.
  275. parser(new PdPoolParser("pd-pool", local_pools_));
  276. // Build the pool instance
  277. parser->build(pd_pool);
  278. // Commit the pool to the local list of pools.
  279. parser->commit();
  280. }
  281. }
  282. /// @brief Commits the pools created to the external storage area.
  283. ///
  284. /// Note that this method adds the local list of pools to the storage area
  285. /// rather than replacing its contents. This permits other parsers to
  286. /// contribute to the set of pools.
  287. void commit() {
  288. // local_pools_ holds the values produced by the build function.
  289. // At this point parsing should have completed successfully so
  290. // we can append new data to the supplied storage.
  291. pools_->insert(pools_->end(), local_pools_->begin(),
  292. local_pools_->end());
  293. }
  294. private:
  295. /// @brief storage for local pools
  296. PoolStoragePtr local_pools_;
  297. /// @brief External storage where pools are stored upon list commit.
  298. PoolStoragePtr pools_;
  299. };
  300. /// @anchor Subnet6ConfigParser
  301. /// @brief This class parses a single IPv6 subnet.
  302. ///
  303. /// This is the IPv6 derivation of the SubnetConfigParser class and it parses
  304. /// the whole subnet definition. It creates parsersfor received configuration
  305. /// parameters as needed.
  306. class Subnet6ConfigParser : public SubnetConfigParser {
  307. public:
  308. /// @brief Constructor
  309. ///
  310. /// @param ignored first parameter
  311. /// stores global scope parameters, options, option definitions.
  312. Subnet6ConfigParser(const std::string&)
  313. :SubnetConfigParser("", globalContext(), IOAddress("::")) {
  314. }
  315. /// @brief Parses a single IPv6 subnet configuration and adds to the
  316. /// Configuration Manager.
  317. ///
  318. /// @param subnet A new subnet being configured.
  319. void build(ConstElementPtr subnet) {
  320. SubnetConfigParser::build(subnet);
  321. if (subnet_) {
  322. Subnet6Ptr sub6ptr = boost::dynamic_pointer_cast<Subnet6>(subnet_);
  323. if (!sub6ptr) {
  324. // If we hit this, it is a programming error.
  325. isc_throw(Unexpected,
  326. "Invalid cast in Subnet6ConfigParser::commit");
  327. }
  328. // Set relay information if it was provided
  329. if (relay_info_) {
  330. sub6ptr->setRelayInfo(*relay_info_);
  331. }
  332. // Adding a subnet to the Configuration Manager may fail if the
  333. // subnet id is invalid (duplicate). Thus, we catch exceptions
  334. // here to append a position in the configuration string.
  335. try {
  336. CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->add(sub6ptr);
  337. } catch (const std::exception& ex) {
  338. isc_throw(DhcpConfigError, ex.what() << " ("
  339. << subnet->getPosition() << ")");
  340. }
  341. // Parse Host Reservations for this subnet if any.
  342. ConstElementPtr reservations = subnet->get("reservations");
  343. if (reservations) {
  344. ParserPtr parser(new HostReservationsListParser<
  345. HostReservationParser6>(subnet_->getID()));
  346. parser->build(reservations);
  347. }
  348. }
  349. }
  350. /// @brief Commits subnet configuration.
  351. ///
  352. /// This function is currently no-op because subnet should already
  353. /// be added into the Config Manager in the build().
  354. void commit() { }
  355. protected:
  356. /// @brief creates parsers for entries in subnet definition
  357. ///
  358. /// @param config_id name of the entry
  359. ///
  360. /// @return parser object for specified entry name. Note the caller is
  361. /// responsible for deleting the parser created.
  362. /// @throw isc::dhcp::DhcpConfigError if trying to create a parser
  363. /// for unknown config element
  364. DhcpConfigParser* createSubnetConfigParser(const std::string& config_id) {
  365. DhcpConfigParser* parser = NULL;
  366. if ((config_id.compare("preferred-lifetime") == 0) ||
  367. (config_id.compare("valid-lifetime") == 0) ||
  368. (config_id.compare("renew-timer") == 0) ||
  369. (config_id.compare("rebind-timer") == 0) ||
  370. (config_id.compare("id") == 0)) {
  371. parser = new Uint32Parser(config_id, uint32_values_);
  372. } else if ((config_id.compare("subnet") == 0) ||
  373. (config_id.compare("interface") == 0) ||
  374. (config_id.compare("client-class") == 0) ||
  375. (config_id.compare("interface-id") == 0) ||
  376. (config_id.compare("reservation-mode") == 0)) {
  377. parser = new StringParser(config_id, string_values_);
  378. } else if (config_id.compare("pools") == 0) {
  379. parser = new Pools6ListParser(config_id, pools_);
  380. } else if (config_id.compare("relay") == 0) {
  381. parser = new RelayInfoParser(config_id, relay_info_, Option::V6);
  382. } else if (config_id.compare("pd-pools") == 0) {
  383. parser = new PdPoolListParser(config_id, pools_);
  384. // option-data was here, but it is now converted to SimpleParser
  385. } else if (config_id.compare("rapid-commit") == 0) {
  386. parser = new BooleanParser(config_id, boolean_values_);
  387. } else {
  388. isc_throw(NotImplemented, "unsupported parameter: " << config_id);
  389. }
  390. return (parser);
  391. }
  392. /// @brief Issues a DHCP6 server specific warning regarding duplicate subnet
  393. /// options.
  394. ///
  395. /// @param code is the numeric option code of the duplicate option
  396. /// @param addr is the subnet address
  397. /// @todo A means to know the correct logger and perhaps a common
  398. /// message would allow this message to be emitted by the base class.
  399. virtual void duplicate_option_warning(uint32_t code,
  400. isc::asiolink::IOAddress& addr) {
  401. LOG_WARN(dhcp6_logger, DHCP6_CONFIG_OPTION_DUPLICATE)
  402. .arg(code).arg(addr.toText());
  403. }
  404. /// @brief Instantiates the IPv6 Subnet based on a given IPv6 address
  405. /// and prefix length.
  406. ///
  407. /// @param addr is IPv6 prefix of the subnet.
  408. /// @param len is the prefix length
  409. void initSubnet(isc::asiolink::IOAddress addr, uint8_t len) {
  410. // Get all 'time' parameters using inheritance.
  411. // If the subnet-specific value is defined then use it, else
  412. // use the global value. The global value must always be
  413. // present. If it is not, it is an internal error and exception
  414. // is thrown.
  415. Triplet<uint32_t> t1 = getParam("renew-timer");
  416. Triplet<uint32_t> t2 = getParam("rebind-timer");
  417. Triplet<uint32_t> pref = getParam("preferred-lifetime");
  418. Triplet<uint32_t> valid = getParam("valid-lifetime");
  419. // Subnet ID is optional. If it is not supplied the value of 0 is used,
  420. // which means autogenerate.
  421. SubnetID subnet_id =
  422. static_cast<SubnetID>(uint32_values_->getOptionalParam("id", 0));
  423. // Get interface-id option content. For now we support string
  424. // representation only
  425. std::string ifaceid;
  426. try {
  427. ifaceid = string_values_->getParam("interface-id");
  428. } catch (const DhcpConfigError &) {
  429. // interface-id is not mandatory
  430. }
  431. // Specifying both interface for locally reachable subnets and
  432. // interface id for relays is mutually exclusive. Need to test for
  433. // this condition.
  434. if (!ifaceid.empty()) {
  435. std::string iface;
  436. try {
  437. iface = string_values_->getParam("interface");
  438. } catch (const DhcpConfigError &) {
  439. // iface not mandatory
  440. }
  441. if (!iface.empty()) {
  442. isc_throw(isc::dhcp::DhcpConfigError,
  443. "parser error: interface (defined for locally reachable "
  444. "subnets) and interface-id (defined for subnets reachable"
  445. " via relays) cannot be defined at the same time for "
  446. "subnet " << addr << "/" << (int)len);
  447. }
  448. }
  449. // Gather boolean parameters values.
  450. bool rapid_commit = boolean_values_->getOptionalParam("rapid-commit", false);
  451. std::ostringstream output;
  452. output << addr << "/" << static_cast<int>(len)
  453. << " with params t1=" << t1 << ", t2="
  454. << t2 << ", preferred-lifetime=" << pref
  455. << ", valid-lifetime=" << valid
  456. << ", rapid-commit is " << (rapid_commit ? "enabled" : "disabled");
  457. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_NEW_SUBNET).arg(output.str());
  458. // Create a new subnet.
  459. Subnet6* subnet6 = new Subnet6(addr, len, t1, t2, pref, valid,
  460. subnet_id);
  461. // Configure interface-id for remote interfaces, if defined
  462. if (!ifaceid.empty()) {
  463. OptionBuffer tmp(ifaceid.begin(), ifaceid.end());
  464. OptionPtr opt(new Option(Option::V6, D6O_INTERFACE_ID, tmp));
  465. subnet6->setInterfaceId(opt);
  466. }
  467. // Enable or disable Rapid Commit option support for the subnet.
  468. subnet6->setRapidCommit(rapid_commit);
  469. // Try setting up client class (if specified)
  470. try {
  471. string client_class = string_values_->getParam("client-class");
  472. subnet6->allowClientClass(client_class);
  473. } catch (const DhcpConfigError&) {
  474. // That's ok if it fails. client-class is optional.
  475. }
  476. subnet_.reset(subnet6);
  477. }
  478. };
  479. /// @brief this class parses a list of DHCP6 subnets
  480. ///
  481. /// This is a wrapper parser that handles the whole list of Subnet6
  482. /// definitions. It iterates over all entries and creates Subnet6ConfigParser
  483. /// for each entry.
  484. class Subnets6ListConfigParser : public DhcpConfigParser {
  485. public:
  486. /// @brief constructor
  487. ///
  488. /// @param dummy first argument, always ignored. All parsers accept a
  489. /// string parameter "name" as their first argument.
  490. Subnets6ListConfigParser(const std::string&) {
  491. }
  492. /// @brief parses contents of the list
  493. ///
  494. /// Iterates over all entries on the list and creates a Subnet6ConfigParser
  495. /// for each entry.
  496. ///
  497. /// @param subnets_list pointer to a list of IPv6 subnets
  498. void build(ConstElementPtr subnets_list) {
  499. BOOST_FOREACH(ConstElementPtr subnet, subnets_list->listValue()) {
  500. ParserPtr parser(new Subnet6ConfigParser("subnet"));
  501. parser->build(subnet);
  502. subnets_.push_back(parser);
  503. }
  504. }
  505. /// @brief commits subnets definitions.
  506. ///
  507. /// Iterates over all Subnet6 parsers. Each parser contains definitions of
  508. /// a single subnet and its parameters and commits each subnet separately.
  509. void commit() {
  510. BOOST_FOREACH(ParserPtr subnet, subnets_) {
  511. subnet->commit();
  512. }
  513. }
  514. /// @brief Returns Subnet6ListConfigParser object
  515. /// @param param_name name of the parameter
  516. /// @return Subnets6ListConfigParser object
  517. static DhcpConfigParser* factory(const std::string& param_name) {
  518. return (new Subnets6ListConfigParser(param_name));
  519. }
  520. /// @brief collection of subnet parsers.
  521. ParserCollection subnets_;
  522. };
  523. /// @brief Parser for list of RSOO options
  524. ///
  525. /// This parser handles a Dhcp6/relay-supplied-options entry. It contains a
  526. /// list of RSOO-enabled options which should be sent back to the client.
  527. ///
  528. /// The options on this list can be specified using an option code or option
  529. /// name. Therefore, the values on the list should always be enclosed in
  530. /// "quotes".
  531. class RSOOListConfigParser : public DhcpConfigParser {
  532. public:
  533. /// @brief constructor
  534. ///
  535. /// As this is a dedicated parser, it must be used to parse
  536. /// "relay-supplied-options" parameter only. All other types will throw exception.
  537. ///
  538. /// @param param_name name of the configuration parameter being parsed
  539. /// @throw BadValue if supplied parameter name is not "relay-supplied-options"
  540. RSOOListConfigParser(const std::string& param_name) {
  541. if (param_name != "relay-supplied-options") {
  542. isc_throw(BadValue, "Internal error. RSOO configuration "
  543. "parser called for the wrong parameter: " << param_name);
  544. }
  545. }
  546. /// @brief parses parameters value
  547. ///
  548. /// Parses configuration entry (list of sources) and adds each element
  549. /// to the RSOO list.
  550. ///
  551. /// @param value pointer to the content of parsed values
  552. virtual void build(isc::data::ConstElementPtr value) {
  553. try {
  554. BOOST_FOREACH(ConstElementPtr source_elem, value->listValue()) {
  555. std::string option_str = source_elem->stringValue();
  556. // This option can be either code (integer) or name. Let's try code first
  557. int64_t code = 0;
  558. try {
  559. code = boost::lexical_cast<int64_t>(option_str);
  560. // Protect against the negative value and too high value.
  561. if (code < 0) {
  562. isc_throw(BadValue, "invalid option code value specified '"
  563. << option_str << "', the option code must be a"
  564. " non-negative value");
  565. } else if (code > std::numeric_limits<uint16_t>::max()) {
  566. isc_throw(BadValue, "invalid option code value specified '"
  567. << option_str << "', the option code must not be"
  568. " greater than '" << std::numeric_limits<uint16_t>::max()
  569. << "'");
  570. }
  571. } catch (const boost::bad_lexical_cast &) {
  572. // Oh well, it's not a number
  573. }
  574. if (!code) {
  575. const OptionDefinitionPtr def = LibDHCP::getOptionDef(DHCP6_OPTION_SPACE,
  576. option_str);
  577. if (def) {
  578. code = def->getCode();
  579. } else {
  580. isc_throw(BadValue, "unable to find option code for the "
  581. " specified option name '" << option_str << "'"
  582. " while parsing the list of enabled"
  583. " relay-supplied-options");
  584. }
  585. }
  586. CfgMgr::instance().getStagingCfg()->getCfgRSOO()->enable(code);
  587. }
  588. } catch (const std::exception& ex) {
  589. // Rethrow exception with the appended position of the parsed
  590. // element.
  591. isc_throw(DhcpConfigError, ex.what() << " (" << value->getPosition() << ")");
  592. }
  593. }
  594. /// @brief Does nothing.
  595. virtual void commit() {}
  596. };
  597. } // anonymous namespace
  598. namespace isc {
  599. namespace dhcp {
  600. /// @brief creates global parsers
  601. ///
  602. /// This method creates global parsers that parse global parameters, i.e.
  603. /// those that take format of Dhcp6/param1, Dhcp6/param2 and so forth.
  604. ///
  605. /// @param config_id pointer to received global configuration entry
  606. /// @param element pointer to the element to be parsed
  607. /// @return parser for specified global DHCPv6 parameter
  608. /// @throw NotImplemented if trying to create a parser for unknown config
  609. /// element
  610. DhcpConfigParser* createGlobal6DhcpConfigParser(const std::string& config_id,
  611. ConstElementPtr element) {
  612. DhcpConfigParser* parser = NULL;
  613. if ((config_id.compare("preferred-lifetime") == 0) ||
  614. (config_id.compare("valid-lifetime") == 0) ||
  615. (config_id.compare("renew-timer") == 0) ||
  616. (config_id.compare("rebind-timer") == 0) ||
  617. (config_id.compare("decline-probation-period") == 0) ||
  618. (config_id.compare("dhcp4o6-port") == 0) ) {
  619. parser = new Uint32Parser(config_id,
  620. globalContext()->uint32_values_);
  621. } else if (config_id.compare("interfaces-config") == 0) {
  622. parser = new IfacesConfigParser6();
  623. } else if (config_id.compare("subnet6") == 0) {
  624. parser = new Subnets6ListConfigParser(config_id);
  625. // option-data and option-def are no longer needed here. They're now
  626. // converted to SimpleParser and are handled in configureDhcp6Server
  627. } else if (config_id.compare("version") == 0) {
  628. parser = new StringParser(config_id,
  629. globalContext()->string_values_);
  630. } else if (config_id.compare("lease-database") == 0) {
  631. parser = new DbAccessParser(config_id, DbAccessParser::LEASE_DB);
  632. } else if (config_id.compare("hosts-database") == 0) {
  633. parser = new DbAccessParser(config_id, DbAccessParser::HOSTS_DB);
  634. } else if (config_id.compare("hooks-libraries") == 0) {
  635. parser = new HooksLibrariesParser(config_id);
  636. } else if (config_id.compare("dhcp-ddns") == 0) {
  637. parser = new D2ClientConfigParser(config_id);
  638. } else if (config_id.compare("mac-sources") == 0) {
  639. parser = new MACSourcesListConfigParser(config_id,
  640. globalContext());
  641. } else if (config_id.compare("relay-supplied-options") == 0) {
  642. parser = new RSOOListConfigParser(config_id);
  643. } else if (config_id.compare("control-socket") == 0) {
  644. parser = new ControlSocketParser(config_id);
  645. } else if (config_id.compare("expired-leases-processing") == 0) {
  646. parser = new ExpirationConfigParser();
  647. } else if (config_id.compare("client-classes") == 0) {
  648. parser = new ClientClassDefListParser(config_id, globalContext());
  649. } else if (config_id.compare("server-id") == 0) {
  650. parser = new DUIDConfigParser();
  651. } else if (config_id.compare("host-reservation-identifiers") == 0) {
  652. parser = new HostReservationIdsParser6();
  653. } else {
  654. isc_throw(DhcpConfigError,
  655. "unsupported global configuration parameter: "
  656. << config_id << " (" << element->getPosition() << ")");
  657. }
  658. return (parser);
  659. }
  660. /// @brief Sets global parameters in the staging configuration
  661. ///
  662. /// Currently this method sets the following global parameters:
  663. ///
  664. /// - decline-probation-period
  665. /// - dhcp4o6-port
  666. void setGlobalParameters6() {
  667. // Set the probation period for decline handling.
  668. try {
  669. uint32_t probation_period = globalContext()->uint32_values_
  670. ->getOptionalParam("decline-probation-period",
  671. DEFAULT_DECLINE_PROBATION_PERIOD);
  672. CfgMgr::instance().getStagingCfg()->setDeclinePeriod(probation_period);
  673. } catch (...) {
  674. // That's not really needed.
  675. }
  676. // Set the DHCPv4-over-DHCPv6 interserver port.
  677. try {
  678. uint32_t dhcp4o6_port = globalContext()->uint32_values_
  679. ->getOptionalParam("dhcp4o6-port", 0);
  680. CfgMgr::instance().getStagingCfg()->setDhcp4o6Port(dhcp4o6_port);
  681. } catch (...) {
  682. // Ignore errors. This flag is optional
  683. }
  684. }
  685. isc::data::ConstElementPtr
  686. configureDhcp6Server(Dhcpv6Srv&, isc::data::ConstElementPtr config_set) {
  687. if (!config_set) {
  688. ConstElementPtr answer = isc::config::createAnswer(1,
  689. string("Can't parse NULL config"));
  690. return (answer);
  691. }
  692. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND,
  693. DHCP6_CONFIG_START).arg(config_set->str());
  694. // Reset global context.
  695. globalContext().reset(new ParserContext(Option::V6));
  696. // Before starting any subnet operations, let's reset the subnet-id counter,
  697. // so newly recreated configuration starts with first subnet-id equal 1.
  698. Subnet::resetSubnetID();
  699. // Remove any existing timers.
  700. TimerMgr::instance()->unregisterTimers();
  701. // Revert any runtime option definitions configured so far and not committed.
  702. LibDHCP::revertRuntimeOptionDefs();
  703. // Let's set empty container in case a user hasn't specified any configuration
  704. // for option definitions. This is equivalent to commiting empty container.
  705. LibDHCP::setRuntimeOptionDefs(OptionDefSpaceContainer());
  706. // Some of the values specified in the configuration depend on
  707. // other values. Typically, the values in the subnet6 structure
  708. // depend on the global values. Also, option values configuration
  709. // must be performed after the option definitions configurations.
  710. // Thus we group parsers and will fire them in the right order:
  711. // all parsers other than lease-database, subnet6 and
  712. // option-data parser, then option-data parser, subnet6 parser,
  713. // lease-database parser.
  714. // Please do not change this order!
  715. ParserCollection independent_parsers;
  716. ParserPtr subnet_parser;
  717. ParserPtr iface_parser;
  718. ParserPtr leases_parser;
  719. ParserPtr client_classes_parser;
  720. // Some of the parsers alter state of the system that can't easily
  721. // be undone. (Or alter it in a way such that undoing the change
  722. // has the same risk of failure as doing the change.)
  723. ParserPtr hooks_parser;
  724. // The subnet parsers implement data inheritance by directly
  725. // accessing global storage. For this reason the global data
  726. // parsers must store the parsed data into global storages
  727. // immediately. This may cause data inconsistency if the
  728. // parsing operation fails after the global storage has been
  729. // modified. We need to preserve the original global data here
  730. // so as we can rollback changes when an error occurs.
  731. ParserContext original_context(*globalContext());
  732. // answer will hold the result.
  733. ConstElementPtr answer;
  734. // rollback informs whether error occurred and original data
  735. // have to be restored to global storages.
  736. bool rollback = false;
  737. // config_pair holds ther details of the current parser when iterating over
  738. // the parsers. It is declared outside the loop so in case of error, the
  739. // name of the failing parser can be retrieved within the "catch" clause.
  740. ConfigPair config_pair;
  741. try {
  742. // This is a way to convert ConstElementPtr to ElementPtr.
  743. // We need a config that can be edited, because we will insert
  744. // default values and will insert derived values as well.
  745. ElementPtr mutable_cfg = Element::getMutableMap(config_set);
  746. SimpleParser6::setAllDefaults(mutable_cfg);
  747. // Make parsers grouping.
  748. const std::map<std::string, ConstElementPtr>& values_map =
  749. mutable_cfg->mapValue();
  750. // We need definitions first
  751. ConstElementPtr option_defs = mutable_cfg->get("option-def");
  752. if (option_defs) {
  753. OptionDefListParser parser;
  754. CfgOptionDefPtr cfg_option_def = CfgMgr::instance().getStagingCfg()->getCfgOptionDef();
  755. parser.parse(cfg_option_def, option_defs);
  756. }
  757. BOOST_FOREACH(config_pair, values_map) {
  758. if (config_pair.first == "option-def") {
  759. // This is converted to SimpleParser and is handled already above.
  760. continue;
  761. }
  762. if (config_pair.first == "option-data") {
  763. OptionDataListParser parser(AF_INET6);
  764. CfgOptionPtr cfg_option = CfgMgr::instance().getStagingCfg()->getCfgOption();
  765. parser.parse(cfg_option, config_pair.second);
  766. continue;
  767. }
  768. ParserPtr parser(createGlobal6DhcpConfigParser(config_pair.first,
  769. config_pair.second));
  770. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PARSER_CREATED)
  771. .arg(config_pair.first);
  772. if (config_pair.first == "subnet6") {
  773. subnet_parser = parser;
  774. } else if (config_pair.first == "lease-database") {
  775. leases_parser = parser;
  776. } else if (config_pair.first == "hooks-libraries") {
  777. // Executing the commit will alter currently loaded hooks
  778. // libraries. Check if the supplied libraries are valid,
  779. // but defer the commit until after everything else has
  780. // committed.
  781. hooks_parser = parser;
  782. hooks_parser->build(config_pair.second);
  783. } else if (config_pair.first == "interfaces-config") {
  784. // The interface parser is independent from any other parser and
  785. // can be run here before other parsers.
  786. parser->build(config_pair.second);
  787. iface_parser = parser;
  788. } else if (config_pair.first == "client-classes") {
  789. client_classes_parser = parser;
  790. } else {
  791. // Those parsers should be started before other
  792. // parsers so we can call build straight away.
  793. independent_parsers.push_back(parser);
  794. parser->build(config_pair.second);
  795. // The commit operation here may modify the global storage
  796. // but we need it so as the subnet6 parser can access the
  797. // parsed data.
  798. parser->commit();
  799. }
  800. }
  801. // The class definitions parser is the next one to be run.
  802. std::map<std::string, ConstElementPtr>::const_iterator cc_config =
  803. values_map.find("client-classes");
  804. if (cc_config != values_map.end()) {
  805. config_pair.first = "client-classes";
  806. client_classes_parser->build(cc_config->second);
  807. client_classes_parser->commit();
  808. }
  809. // The subnet parser is the next one to be run.
  810. std::map<std::string, ConstElementPtr>::const_iterator subnet_config =
  811. values_map.find("subnet6");
  812. if (subnet_config != values_map.end()) {
  813. config_pair.first = "subnet6";
  814. subnet_parser->build(subnet_config->second);
  815. }
  816. // Get command socket configuration from the config file.
  817. // This code expects the following structure:
  818. // {
  819. // "socket-type": "unix",
  820. // "socket-name": "/tmp/kea6.sock"
  821. // }
  822. ConstElementPtr sock_cfg =
  823. CfgMgr::instance().getStagingCfg()->getControlSocketInfo();
  824. // Close existing socket (if any).
  825. isc::config::CommandMgr::instance().closeCommandSocket();
  826. if (sock_cfg) {
  827. // This will create a control socket and will install external socket
  828. // in IfaceMgr. That socket will be monitored when Dhcp4Srv::receivePacket()
  829. // calls IfaceMgr::receive4() and callback in CommandMgr will be called,
  830. // if necessary. If there were previously open command socket, it will
  831. // be closed.
  832. isc::config::CommandMgr::instance().openCommandSocket(sock_cfg);
  833. }
  834. // The lease database parser is the last to be run.
  835. std::map<std::string, ConstElementPtr>::const_iterator leases_config =
  836. values_map.find("lease-database");
  837. if (leases_config != values_map.end()) {
  838. config_pair.first = "lease-database";
  839. leases_parser->build(leases_config->second);
  840. leases_parser->commit();
  841. }
  842. } catch (const isc::Exception& ex) {
  843. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_FAIL)
  844. .arg(config_pair.first).arg(ex.what());
  845. answer = isc::config::createAnswer(1, ex.what());
  846. // An error occurred, so make sure that we restore original data.
  847. rollback = true;
  848. } catch (...) {
  849. // for things like bad_cast in boost::lexical_cast
  850. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_EXCEPTION).arg(config_pair.first);
  851. answer = isc::config::createAnswer(1, "undefined configuration"
  852. " processing error");
  853. // An error occurred, so make sure that we restore original data.
  854. rollback = true;
  855. }
  856. // So far so good, there was no parsing error so let's commit the
  857. // configuration. This will add created subnets and option values into
  858. // the server's configuration.
  859. // This operation should be exception safe but let's make sure.
  860. if (!rollback) {
  861. try {
  862. if (subnet_parser) {
  863. subnet_parser->commit();
  864. }
  865. // Apply global options in the staging config.
  866. setGlobalParameters6();
  867. // No need to commit interface names as this is handled by the
  868. // CfgMgr::commit() function.
  869. // This occurs last as if it succeeds, there is no easy way to
  870. // revert it. As a result, the failure to commit a subsequent
  871. // change causes problems when trying to roll back.
  872. if (hooks_parser) {
  873. hooks_parser->commit();
  874. }
  875. }
  876. catch (const isc::Exception& ex) {
  877. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(ex.what());
  878. answer = isc::config::createAnswer(2, ex.what());
  879. // An error occurred, so make sure to restore the original data.
  880. rollback = true;
  881. } catch (...) {
  882. // for things like bad_cast in boost::lexical_cast
  883. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_EXCEPTION);
  884. answer = isc::config::createAnswer(2, "undefined configuration"
  885. " parsing error");
  886. // An error occurred, so make sure to restore the original data.
  887. rollback = true;
  888. }
  889. }
  890. // Rollback changes as the configuration parsing failed.
  891. if (rollback) {
  892. globalContext().reset(new ParserContext(original_context));
  893. // Revert to original configuration of runtime option definitions
  894. // in the libdhcp++.
  895. LibDHCP::revertRuntimeOptionDefs();
  896. return (answer);
  897. }
  898. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_COMPLETE)
  899. .arg(CfgMgr::instance().getStagingCfg()->
  900. getConfigSummary(SrvConfig::CFGSEL_ALL6));
  901. // Everything was fine. Configuration is successful.
  902. answer = isc::config::createAnswer(0, "Configuration successful.");
  903. return (answer);
  904. }
  905. ParserContextPtr& globalContext() {
  906. static ParserContextPtr global_context_ptr(new ParserContext(Option::V6));
  907. return (global_context_ptr);
  908. }
  909. }; // end of isc::dhcp namespace
  910. }; // end of isc namespace