json_config_parser.cc 39 KB

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