json_config_parser.cc 38 KB

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