json_config_parser.cc 32 KB

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