json_config_parser.cc 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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 <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. HostReservationsListParser<HostReservationParser6> parser;
  345. parser.parse(subnet_->getID(), reservations);
  346. }
  347. }
  348. }
  349. /// @brief Commits subnet configuration.
  350. ///
  351. /// This function is currently no-op because subnet should already
  352. /// be added into the Config Manager in the build().
  353. void commit() { }
  354. protected:
  355. /// @brief creates parsers for entries in subnet definition
  356. ///
  357. /// @param config_id name of the entry
  358. ///
  359. /// @return parser object for specified entry name. Note the caller is
  360. /// responsible for deleting the parser created.
  361. /// @throw isc::dhcp::DhcpConfigError if trying to create a parser
  362. /// for unknown config element
  363. DhcpConfigParser* createSubnetConfigParser(const std::string& config_id) {
  364. DhcpConfigParser* parser = NULL;
  365. if ((config_id.compare("preferred-lifetime") == 0) ||
  366. (config_id.compare("valid-lifetime") == 0) ||
  367. (config_id.compare("renew-timer") == 0) ||
  368. (config_id.compare("rebind-timer") == 0) ||
  369. (config_id.compare("id") == 0)) {
  370. parser = new Uint32Parser(config_id, uint32_values_);
  371. } else if ((config_id.compare("subnet") == 0) ||
  372. (config_id.compare("interface") == 0) ||
  373. (config_id.compare("client-class") == 0) ||
  374. (config_id.compare("interface-id") == 0) ||
  375. (config_id.compare("reservation-mode") == 0)) {
  376. parser = new StringParser(config_id, string_values_);
  377. } else if (config_id.compare("pools") == 0) {
  378. parser = new Pools6ListParser(config_id, pools_);
  379. // relay has been converted to SimpleParser.
  380. } else if (config_id.compare("pd-pools") == 0) {
  381. parser = new PdPoolListParser(config_id, pools_);
  382. // option-data was here, but it is now converted to SimpleParser
  383. } else if (config_id.compare("rapid-commit") == 0) {
  384. parser = new BooleanParser(config_id, boolean_values_);
  385. } else {
  386. isc_throw(NotImplemented, "unsupported parameter: " << config_id);
  387. }
  388. return (parser);
  389. }
  390. /// @brief Issues a DHCP6 server specific warning regarding duplicate subnet
  391. /// options.
  392. ///
  393. /// @param code is the numeric option code of the duplicate option
  394. /// @param addr is the subnet address
  395. /// @todo A means to know the correct logger and perhaps a common
  396. /// message would allow this message to be emitted by the base class.
  397. virtual void duplicate_option_warning(uint32_t code,
  398. isc::asiolink::IOAddress& addr) {
  399. LOG_WARN(dhcp6_logger, DHCP6_CONFIG_OPTION_DUPLICATE)
  400. .arg(code).arg(addr.toText());
  401. }
  402. /// @brief Instantiates the IPv6 Subnet based on a given IPv6 address
  403. /// and prefix length.
  404. ///
  405. /// @param addr is IPv6 prefix of the subnet.
  406. /// @param len is the prefix length
  407. void initSubnet(isc::asiolink::IOAddress addr, uint8_t len) {
  408. // Get all 'time' parameters using inheritance.
  409. // If the subnet-specific value is defined then use it, else
  410. // use the global value. The global value must always be
  411. // present. If it is not, it is an internal error and exception
  412. // is thrown.
  413. Triplet<uint32_t> t1 = getParam("renew-timer");
  414. Triplet<uint32_t> t2 = getParam("rebind-timer");
  415. Triplet<uint32_t> pref = getParam("preferred-lifetime");
  416. Triplet<uint32_t> valid = getParam("valid-lifetime");
  417. // Subnet ID is optional. If it is not supplied the value of 0 is used,
  418. // which means autogenerate.
  419. SubnetID subnet_id =
  420. static_cast<SubnetID>(uint32_values_->getOptionalParam("id", 0));
  421. // Get interface-id option content. For now we support string
  422. // representation only
  423. std::string ifaceid;
  424. try {
  425. ifaceid = string_values_->getParam("interface-id");
  426. } catch (const DhcpConfigError &) {
  427. // interface-id is not mandatory
  428. }
  429. // Specifying both interface for locally reachable subnets and
  430. // interface id for relays is mutually exclusive. Need to test for
  431. // this condition.
  432. if (!ifaceid.empty()) {
  433. std::string iface;
  434. try {
  435. iface = string_values_->getParam("interface");
  436. } catch (const DhcpConfigError &) {
  437. // iface not mandatory
  438. }
  439. if (!iface.empty()) {
  440. isc_throw(isc::dhcp::DhcpConfigError,
  441. "parser error: interface (defined for locally reachable "
  442. "subnets) and interface-id (defined for subnets reachable"
  443. " via relays) cannot be defined at the same time for "
  444. "subnet " << addr << "/" << (int)len);
  445. }
  446. }
  447. // Gather boolean parameters values.
  448. bool rapid_commit = boolean_values_->getOptionalParam("rapid-commit", false);
  449. std::ostringstream output;
  450. output << addr << "/" << static_cast<int>(len)
  451. << " with params t1=" << t1 << ", t2="
  452. << t2 << ", preferred-lifetime=" << pref
  453. << ", valid-lifetime=" << valid
  454. << ", rapid-commit is " << (rapid_commit ? "enabled" : "disabled");
  455. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_NEW_SUBNET).arg(output.str());
  456. // Create a new subnet.
  457. Subnet6* subnet6 = new Subnet6(addr, len, t1, t2, pref, valid,
  458. subnet_id);
  459. // Configure interface-id for remote interfaces, if defined
  460. if (!ifaceid.empty()) {
  461. OptionBuffer tmp(ifaceid.begin(), ifaceid.end());
  462. OptionPtr opt(new Option(Option::V6, D6O_INTERFACE_ID, tmp));
  463. subnet6->setInterfaceId(opt);
  464. }
  465. // Enable or disable Rapid Commit option support for the subnet.
  466. subnet6->setRapidCommit(rapid_commit);
  467. // Try setting up client class (if specified)
  468. try {
  469. string client_class = string_values_->getParam("client-class");
  470. subnet6->allowClientClass(client_class);
  471. } catch (const DhcpConfigError&) {
  472. // That's ok if it fails. client-class is optional.
  473. }
  474. subnet_.reset(subnet6);
  475. }
  476. };
  477. /// @brief this class parses a list of DHCP6 subnets
  478. ///
  479. /// This is a wrapper parser that handles the whole list of Subnet6
  480. /// definitions. It iterates over all entries and creates Subnet6ConfigParser
  481. /// for each entry.
  482. class Subnets6ListConfigParser : public DhcpConfigParser {
  483. public:
  484. /// @brief constructor
  485. ///
  486. /// @param dummy first argument, always ignored. All parsers accept a
  487. /// string parameter "name" as their first argument.
  488. Subnets6ListConfigParser(const std::string&) {
  489. }
  490. /// @brief parses contents of the list
  491. ///
  492. /// Iterates over all entries on the list and creates a Subnet6ConfigParser
  493. /// for each entry.
  494. ///
  495. /// @param subnets_list pointer to a list of IPv6 subnets
  496. void build(ConstElementPtr subnets_list) {
  497. BOOST_FOREACH(ConstElementPtr subnet, subnets_list->listValue()) {
  498. ParserPtr parser(new Subnet6ConfigParser("subnet"));
  499. parser->build(subnet);
  500. subnets_.push_back(parser);
  501. }
  502. }
  503. /// @brief commits subnets definitions.
  504. ///
  505. /// Iterates over all Subnet6 parsers. Each parser contains definitions of
  506. /// a single subnet and its parameters and commits each subnet separately.
  507. void commit() {
  508. BOOST_FOREACH(ParserPtr subnet, subnets_) {
  509. subnet->commit();
  510. }
  511. }
  512. /// @brief Returns Subnet6ListConfigParser object
  513. /// @param param_name name of the parameter
  514. /// @return Subnets6ListConfigParser object
  515. static DhcpConfigParser* factory(const std::string& param_name) {
  516. return (new Subnets6ListConfigParser(param_name));
  517. }
  518. /// @brief collection of subnet parsers.
  519. ParserCollection subnets_;
  520. };
  521. /// @brief Parser for list of RSOO options
  522. ///
  523. /// This parser handles a Dhcp6/relay-supplied-options entry. It contains a
  524. /// list of RSOO-enabled options which should be sent back to the client.
  525. ///
  526. /// The options on this list can be specified using an option code or option
  527. /// name. Therefore, the values on the list should always be enclosed in
  528. /// "quotes".
  529. class RSOOListConfigParser : public DhcpConfigParser {
  530. public:
  531. /// @brief constructor
  532. ///
  533. /// As this is a dedicated parser, it must be used to parse
  534. /// "relay-supplied-options" parameter only. All other types will throw exception.
  535. ///
  536. /// @param param_name name of the configuration parameter being parsed
  537. /// @throw BadValue if supplied parameter name is not "relay-supplied-options"
  538. RSOOListConfigParser(const std::string& param_name) {
  539. if (param_name != "relay-supplied-options") {
  540. isc_throw(BadValue, "Internal error. RSOO configuration "
  541. "parser called for the wrong parameter: " << param_name);
  542. }
  543. }
  544. /// @brief parses parameters value
  545. ///
  546. /// Parses configuration entry (list of sources) and adds each element
  547. /// to the RSOO list.
  548. ///
  549. /// @param value pointer to the content of parsed values
  550. virtual void build(isc::data::ConstElementPtr value) {
  551. try {
  552. BOOST_FOREACH(ConstElementPtr source_elem, value->listValue()) {
  553. std::string option_str = source_elem->stringValue();
  554. // This option can be either code (integer) or name. Let's try code first
  555. int64_t code = 0;
  556. try {
  557. code = boost::lexical_cast<int64_t>(option_str);
  558. // Protect against the negative value and too high value.
  559. if (code < 0) {
  560. isc_throw(BadValue, "invalid option code value specified '"
  561. << option_str << "', the option code must be a"
  562. " non-negative value");
  563. } else if (code > std::numeric_limits<uint16_t>::max()) {
  564. isc_throw(BadValue, "invalid option code value specified '"
  565. << option_str << "', the option code must not be"
  566. " greater than '" << std::numeric_limits<uint16_t>::max()
  567. << "'");
  568. }
  569. } catch (const boost::bad_lexical_cast &) {
  570. // Oh well, it's not a number
  571. }
  572. if (!code) {
  573. const OptionDefinitionPtr def = LibDHCP::getOptionDef(DHCP6_OPTION_SPACE,
  574. option_str);
  575. if (def) {
  576. code = def->getCode();
  577. } else {
  578. isc_throw(BadValue, "unable to find option code for the "
  579. " specified option name '" << option_str << "'"
  580. " while parsing the list of enabled"
  581. " relay-supplied-options");
  582. }
  583. }
  584. CfgMgr::instance().getStagingCfg()->getCfgRSOO()->enable(code);
  585. }
  586. } catch (const std::exception& ex) {
  587. // Rethrow exception with the appended position of the parsed
  588. // element.
  589. isc_throw(DhcpConfigError, ex.what() << " (" << value->getPosition() << ")");
  590. }
  591. }
  592. /// @brief Does nothing.
  593. virtual void commit() {}
  594. };
  595. } // anonymous namespace
  596. namespace isc {
  597. namespace dhcp {
  598. /// @brief creates global parsers
  599. ///
  600. /// This method creates global parsers that parse global parameters, i.e.
  601. /// those that take format of Dhcp6/param1, Dhcp6/param2 and so forth.
  602. ///
  603. /// @param config_id pointer to received global configuration entry
  604. /// @param element pointer to the element to be parsed
  605. /// @return parser for specified global DHCPv6 parameter
  606. /// @throw NotImplemented if trying to create a parser for unknown config
  607. /// element
  608. DhcpConfigParser* createGlobal6DhcpConfigParser(const std::string& config_id,
  609. ConstElementPtr element) {
  610. DhcpConfigParser* parser = NULL;
  611. if ((config_id.compare("preferred-lifetime") == 0) ||
  612. (config_id.compare("valid-lifetime") == 0) ||
  613. (config_id.compare("renew-timer") == 0) ||
  614. (config_id.compare("rebind-timer") == 0) ||
  615. (config_id.compare("decline-probation-period") == 0) ||
  616. (config_id.compare("dhcp4o6-port") == 0) ) {
  617. parser = new Uint32Parser(config_id,
  618. globalContext()->uint32_values_);
  619. } else if (config_id.compare("subnet6") == 0) {
  620. parser = new Subnets6ListConfigParser(config_id);
  621. // option-data and option-def are no longer needed here. They're now
  622. // converted to SimpleParser and are handled in configureDhcp6Server.
  623. // interfaces-config has been converted to SimpleParser.
  624. // version was removed - it was a leftover from bindctrl.
  625. } else if (config_id.compare("lease-database") == 0) {
  626. parser = new DbAccessParser(config_id, DbAccessParser::LEASE_DB);
  627. } else if (config_id.compare("hosts-database") == 0) {
  628. parser = new DbAccessParser(config_id, DbAccessParser::HOSTS_DB);
  629. // hooks-libraries is now converted to SimpleParser.
  630. } else if (config_id.compare("dhcp-ddns") == 0) {
  631. parser = new D2ClientConfigParser(config_id);
  632. // mac-source has been converted to SimpleParser.
  633. } else if (config_id.compare("relay-supplied-options") == 0) {
  634. parser = new RSOOListConfigParser(config_id);
  635. // control-socket has been converted to SimpleParser.
  636. // expired-leases-processing has been converted to SimpleParser.
  637. } else if (config_id.compare("client-classes") == 0) {
  638. parser = new ClientClassDefListParser(config_id, globalContext());
  639. // host-reservation-identifiers have been converted to SimpleParser already.
  640. // server-id has been migrated to SimpleParser
  641. } else {
  642. isc_throw(DhcpConfigError,
  643. "unsupported global configuration parameter: "
  644. << config_id << " (" << element->getPosition() << ")");
  645. }
  646. return (parser);
  647. }
  648. /// @brief Sets global parameters in the staging configuration
  649. ///
  650. /// Currently this method sets the following global parameters:
  651. ///
  652. /// - decline-probation-period
  653. /// - dhcp4o6-port
  654. void setGlobalParameters6() {
  655. // Set the probation period for decline handling.
  656. try {
  657. uint32_t probation_period = globalContext()->uint32_values_
  658. ->getOptionalParam("decline-probation-period",
  659. DEFAULT_DECLINE_PROBATION_PERIOD);
  660. CfgMgr::instance().getStagingCfg()->setDeclinePeriod(probation_period);
  661. } catch (...) {
  662. // That's not really needed.
  663. }
  664. // Set the DHCPv4-over-DHCPv6 interserver port.
  665. try {
  666. uint32_t dhcp4o6_port = globalContext()->uint32_values_
  667. ->getOptionalParam("dhcp4o6-port", 0);
  668. CfgMgr::instance().getStagingCfg()->setDhcp4o6Port(dhcp4o6_port);
  669. } catch (...) {
  670. // Ignore errors. This flag is optional
  671. }
  672. }
  673. /// @brief Initialize the command channel based on the staging configuration
  674. ///
  675. /// Only close the current channel, if the new channel configuration is
  676. /// different. This avoids disconnecting a client and hence not sending them
  677. /// a command result, unless they specifically alter the channel configuration.
  678. /// In that case the user simply has to accept they'll be disconnected.
  679. ///
  680. void configureCommandChannel() {
  681. // Get new socket configuration.
  682. ConstElementPtr sock_cfg =
  683. CfgMgr::instance().getStagingCfg()->getControlSocketInfo();
  684. // Get current socket configuration.
  685. ConstElementPtr current_sock_cfg =
  686. CfgMgr::instance().getCurrentCfg()->getControlSocketInfo();
  687. // Determine if the socket configuration has changed. It has if
  688. // both old and new configuration is specified but respective
  689. // data elements are't equal.
  690. bool sock_changed = (sock_cfg && current_sock_cfg &&
  691. !sock_cfg->equals(*current_sock_cfg));
  692. // If the previous or new socket configuration doesn't exist or
  693. // the new configuration differs from the old configuration we
  694. // close the exisitng socket and open a new socket as appropriate.
  695. // Note that closing an existing socket means the clien will not
  696. // receive the configuration result.
  697. if (!sock_cfg || !current_sock_cfg || sock_changed) {
  698. // Close the existing socket (if any).
  699. isc::config::CommandMgr::instance().closeCommandSocket();
  700. if (sock_cfg) {
  701. // This will create a control socket and install the external
  702. // socket in IfaceMgr. That socket will be monitored when
  703. // Dhcp4Srv::receivePacket() calls IfaceMgr::receive4() and
  704. // callback in CommandMgr will be called, if necessary.
  705. isc::config::CommandMgr::instance().openCommandSocket(sock_cfg);
  706. }
  707. }
  708. }
  709. isc::data::ConstElementPtr
  710. configureDhcp6Server(Dhcpv6Srv&, isc::data::ConstElementPtr config_set) {
  711. if (!config_set) {
  712. ConstElementPtr answer = isc::config::createAnswer(1,
  713. string("Can't parse NULL config"));
  714. return (answer);
  715. }
  716. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND,
  717. DHCP6_CONFIG_START).arg(config_set->str());
  718. // Reset global context.
  719. globalContext().reset(new ParserContext(Option::V6));
  720. // Before starting any subnet operations, let's reset the subnet-id counter,
  721. // so newly recreated configuration starts with first subnet-id equal 1.
  722. Subnet::resetSubnetID();
  723. // Remove any existing timers.
  724. TimerMgr::instance()->unregisterTimers();
  725. // Revert any runtime option definitions configured so far and not committed.
  726. LibDHCP::revertRuntimeOptionDefs();
  727. // Let's set empty container in case a user hasn't specified any configuration
  728. // for option definitions. This is equivalent to commiting empty container.
  729. LibDHCP::setRuntimeOptionDefs(OptionDefSpaceContainer());
  730. // Some of the values specified in the configuration depend on
  731. // other values. Typically, the values in the subnet6 structure
  732. // depend on the global values. Also, option values configuration
  733. // must be performed after the option definitions configurations.
  734. // Thus we group parsers and will fire them in the right order:
  735. // all parsers other than lease-database, subnet6 and
  736. // option-data parser, then option-data parser, subnet6 parser,
  737. // lease-database parser.
  738. // Please do not change this order!
  739. ParserCollection independent_parsers;
  740. ParserPtr subnet_parser;
  741. ParserPtr leases_parser;
  742. ParserPtr client_classes_parser;
  743. // Some of the parsers alter state of the system that can't easily
  744. // be undone. (Or alter it in a way such that undoing the change
  745. // has the same risk of failure as doing the change.)
  746. HooksLibrariesParser hooks_parser;
  747. // The subnet parsers implement data inheritance by directly
  748. // accessing global storage. For this reason the global data
  749. // parsers must store the parsed data into global storages
  750. // immediately. This may cause data inconsistency if the
  751. // parsing operation fails after the global storage has been
  752. // modified. We need to preserve the original global data here
  753. // so as we can rollback changes when an error occurs.
  754. ParserContext original_context(*globalContext());
  755. // answer will hold the result.
  756. ConstElementPtr answer;
  757. // rollback informs whether error occurred and original data
  758. // have to be restored to global storages.
  759. bool rollback = false;
  760. // config_pair holds ther details of the current parser when iterating over
  761. // the parsers. It is declared outside the loop so in case of error, the
  762. // name of the failing parser can be retrieved within the "catch" clause.
  763. ConfigPair config_pair;
  764. try {
  765. // This is a way to convert ConstElementPtr to ElementPtr.
  766. // We need a config that can be edited, because we will insert
  767. // default values and will insert derived values as well.
  768. ElementPtr mutable_cfg = boost::const_pointer_cast<Element>(config_set);
  769. SimpleParser6::setAllDefaults(mutable_cfg);
  770. // Make parsers grouping.
  771. const std::map<std::string, ConstElementPtr>& values_map =
  772. mutable_cfg->mapValue();
  773. // We need definitions first
  774. ConstElementPtr option_defs = mutable_cfg->get("option-def");
  775. if (option_defs) {
  776. OptionDefListParser parser;
  777. CfgOptionDefPtr cfg_option_def = CfgMgr::instance().getStagingCfg()->getCfgOptionDef();
  778. parser.parse(cfg_option_def, option_defs);
  779. }
  780. BOOST_FOREACH(config_pair, values_map) {
  781. // In principle we could have the following code structured as a series
  782. // of long if else if clauses. That would give a marginal performance
  783. // boost, but would make the code less readable. We had serious issues
  784. // with the parser code debugability, so I decided to keep it as a
  785. // series of independent ifs.
  786. if (config_pair.first == "option-def") {
  787. // This is converted to SimpleParser and is handled already above.
  788. continue;
  789. }
  790. if (config_pair.first == "option-data") {
  791. OptionDataListParser parser(AF_INET6);
  792. CfgOptionPtr cfg_option = CfgMgr::instance().getStagingCfg()->getCfgOption();
  793. parser.parse(cfg_option, config_pair.second);
  794. continue;
  795. }
  796. if (config_pair.first == "mac-sources") {
  797. MACSourcesListConfigParser parser;
  798. CfgMACSource& mac_source = CfgMgr::instance().getStagingCfg()->getMACSources();
  799. parser.parse(mac_source, config_pair.second);
  800. continue;
  801. }
  802. if (config_pair.first == "control-socket") {
  803. ControlSocketParser parser;
  804. SrvConfigPtr srv_config = CfgMgr::instance().getStagingCfg();
  805. parser.parse(*srv_config, config_pair.second);
  806. continue;
  807. }
  808. if (config_pair.first == "host-reservation-identifiers") {
  809. HostReservationIdsParser6 parser;
  810. parser.parse(config_pair.second);
  811. continue;
  812. }
  813. if (config_pair.first == "server-id") {
  814. DUIDConfigParser parser;
  815. const CfgDUIDPtr& cfg = CfgMgr::instance().getStagingCfg()->getCfgDUID();
  816. parser.parse(cfg, config_pair.second);
  817. continue;
  818. }
  819. if (config_pair.first == "interfaces-config") {
  820. IfacesConfigParser parser(AF_INET6);
  821. CfgIfacePtr cfg_iface = CfgMgr::instance().getStagingCfg()->getCfgIface();
  822. parser.parse(cfg_iface, config_pair.second);
  823. continue;
  824. }
  825. if (config_pair.first == "expired-leases-processing") {
  826. ExpirationConfigParser parser;
  827. parser.parse(config_pair.second);
  828. continue;
  829. }
  830. if (config_pair.first == "hooks-libraries") {
  831. hooks_parser.parse(config_pair.second);
  832. hooks_parser.verifyLibraries();
  833. continue;
  834. }
  835. ParserPtr parser(createGlobal6DhcpConfigParser(config_pair.first,
  836. config_pair.second));
  837. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PARSER_CREATED)
  838. .arg(config_pair.first);
  839. if (config_pair.first == "subnet6") {
  840. subnet_parser = parser;
  841. } else if (config_pair.first == "lease-database") {
  842. leases_parser = parser;
  843. } else if (config_pair.first == "client-classes") {
  844. client_classes_parser = parser;
  845. } else {
  846. // Those parsers should be started before other
  847. // parsers so we can call build straight away.
  848. independent_parsers.push_back(parser);
  849. parser->build(config_pair.second);
  850. // The commit operation here may modify the global storage
  851. // but we need it so as the subnet6 parser can access the
  852. // parsed data.
  853. parser->commit();
  854. }
  855. }
  856. // The class definitions parser is the next one to be run.
  857. std::map<std::string, ConstElementPtr>::const_iterator cc_config =
  858. values_map.find("client-classes");
  859. if (cc_config != values_map.end()) {
  860. config_pair.first = "client-classes";
  861. client_classes_parser->build(cc_config->second);
  862. client_classes_parser->commit();
  863. }
  864. // The subnet parser is the next one to be run.
  865. std::map<std::string, ConstElementPtr>::const_iterator subnet_config =
  866. values_map.find("subnet6");
  867. if (subnet_config != values_map.end()) {
  868. config_pair.first = "subnet6";
  869. subnet_parser->build(subnet_config->second);
  870. }
  871. // Setup the command channel.
  872. configureCommandChannel();
  873. // The lease database parser is the last to be run.
  874. std::map<std::string, ConstElementPtr>::const_iterator leases_config =
  875. values_map.find("lease-database");
  876. if (leases_config != values_map.end()) {
  877. config_pair.first = "lease-database";
  878. leases_parser->build(leases_config->second);
  879. leases_parser->commit();
  880. }
  881. } catch (const isc::Exception& ex) {
  882. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_FAIL)
  883. .arg(config_pair.first).arg(ex.what());
  884. answer = isc::config::createAnswer(1, ex.what());
  885. // An error occurred, so make sure that we restore original data.
  886. rollback = true;
  887. } catch (...) {
  888. // for things like bad_cast in boost::lexical_cast
  889. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_EXCEPTION).arg(config_pair.first);
  890. answer = isc::config::createAnswer(1, "undefined configuration"
  891. " processing error");
  892. // An error occurred, so make sure that we restore original data.
  893. rollback = true;
  894. }
  895. // So far so good, there was no parsing error so let's commit the
  896. // configuration. This will add created subnets and option values into
  897. // the server's configuration.
  898. // This operation should be exception safe but let's make sure.
  899. if (!rollback) {
  900. try {
  901. if (subnet_parser) {
  902. subnet_parser->commit();
  903. }
  904. // Apply global options in the staging config.
  905. setGlobalParameters6();
  906. // No need to commit interface names as this is handled by the
  907. // CfgMgr::commit() function.
  908. // This occurs last as if it succeeds, there is no easy way to
  909. // revert it. As a result, the failure to commit a subsequent
  910. // change causes problems when trying to roll back.
  911. hooks_parser.loadLibraries();
  912. }
  913. catch (const isc::Exception& ex) {
  914. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(ex.what());
  915. answer = isc::config::createAnswer(2, ex.what());
  916. // An error occurred, so make sure to restore the original data.
  917. rollback = true;
  918. } catch (...) {
  919. // for things like bad_cast in boost::lexical_cast
  920. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_EXCEPTION);
  921. answer = isc::config::createAnswer(2, "undefined configuration"
  922. " parsing error");
  923. // An error occurred, so make sure to restore the original data.
  924. rollback = true;
  925. }
  926. }
  927. // Rollback changes as the configuration parsing failed.
  928. if (rollback) {
  929. globalContext().reset(new ParserContext(original_context));
  930. // Revert to original configuration of runtime option definitions
  931. // in the libdhcp++.
  932. LibDHCP::revertRuntimeOptionDefs();
  933. return (answer);
  934. }
  935. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_COMPLETE)
  936. .arg(CfgMgr::instance().getStagingCfg()->
  937. getConfigSummary(SrvConfig::CFGSEL_ALL6));
  938. // Everything was fine. Configuration is successful.
  939. answer = isc::config::createAnswer(0, "Configuration successful.");
  940. return (answer);
  941. }
  942. ParserContextPtr& globalContext() {
  943. static ParserContextPtr global_context_ptr(new ParserContext(Option::V6));
  944. return (global_context_ptr);
  945. }
  946. }; // end of isc::dhcp namespace
  947. }; // end of isc namespace