json_config_parser.cc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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 <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 <dhcpsrv/parsers/ifaces_config_parser.h>
  32. #include <log/logger_support.h>
  33. #include <util/encode/hex.h>
  34. #include <util/strutil.h>
  35. #include <boost/algorithm/string.hpp>
  36. #include <boost/foreach.hpp>
  37. #include <boost/lexical_cast.hpp>
  38. #include <boost/scoped_ptr.hpp>
  39. #include <boost/shared_ptr.hpp>
  40. #include <iostream>
  41. #include <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 defintions 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. std::string addr_str;
  176. uint32_t prefix_len;
  177. uint32_t delegated_len;
  178. try {
  179. addr_str = string_values_->getParam("prefix");
  180. prefix_len = uint32_values_->getParam("prefix-len");
  181. delegated_len = uint32_values_->getParam("delegated-len");
  182. // Attempt to construct the local pool.
  183. pool_.reset(new Pool6(Lease::TYPE_PD, IOAddress(addr_str),
  184. prefix_len, delegated_len));
  185. } catch (const std::exception& ex) {
  186. // Some parameters don't exist or are invalid. Since we are not
  187. // aware whether they don't exist or are invalid, let's append
  188. // the position of the pool map element.
  189. isc_throw(isc::dhcp::DhcpConfigError, ex.what()
  190. << " (" << pd_pool_->getPosition() << ")");
  191. }
  192. }
  193. // @brief Commits the constructed local pool to the pool storage.
  194. virtual void commit() {
  195. // Add the local pool to the external storage ptr.
  196. pools_->push_back(pool_);
  197. }
  198. protected:
  199. /// Storage for subnet-specific integer values.
  200. Uint32StoragePtr uint32_values_;
  201. /// Storage for subnet-specific string values.
  202. StringStoragePtr string_values_;
  203. /// Parsers are stored here.
  204. ParserCollection parsers_;
  205. /// Pointer to the created pool object.
  206. isc::dhcp::Pool6Ptr pool_;
  207. /// Pointer to storage to which the local pool is written upon commit.
  208. isc::dhcp::PoolStoragePtr pools_;
  209. };
  210. /// @brief Parser for a list of prefix delegation pools.
  211. ///
  212. /// This parser iterates over a list of prefix delegation pool entries and
  213. /// creates pool instances for each one. If the parsing is successful, the
  214. /// collection of pools is committed to the provided storage.
  215. class PdPoolListParser : public DhcpConfigParser {
  216. public:
  217. /// @brief Constructor.
  218. ///
  219. /// @param dummy first argument is ignored, all Parser constructors
  220. /// accept string as first argument.
  221. /// @param storage is the pool storage in which to store the parsed
  222. /// pools in this list
  223. /// @throw isc::dhcp::DhcpConfigError if storage is null.
  224. PdPoolListParser(const std::string&, PoolStoragePtr pools)
  225. : local_pools_(new PoolStorage()), pools_(pools) {
  226. if (!pools_) {
  227. isc_throw(isc::dhcp::DhcpConfigError,
  228. "PdPoolListParser pools storage may not be NULL");
  229. }
  230. }
  231. /// @brief Parse configuration entries.
  232. ///
  233. /// This function parses configuration entries and creates instances
  234. /// of prefix delegation pools .
  235. ///
  236. /// @param pd_pool_list pointer to an element that holds entries
  237. /// that define a prefix delegation pool.
  238. ///
  239. /// @throw DhcpConfigError if configuration parsing fails.
  240. void build(isc::data::ConstElementPtr pd_pool_list) {
  241. // Make sure the local list is empty.
  242. local_pools_.reset(new PoolStorage());
  243. // Make sure we have a configuration elements to parse.
  244. if (!pd_pool_list) {
  245. isc_throw(DhcpConfigError,
  246. "PdPoolListParser: list of pool definitions is NULL");
  247. }
  248. // Loop through the list of pd pools.
  249. BOOST_FOREACH(ConstElementPtr pd_pool, pd_pool_list->listValue()) {
  250. boost::shared_ptr<PdPoolParser>
  251. // Create the PdPool parser.
  252. parser(new PdPoolParser("pd-pool", local_pools_));
  253. // Build the pool instance
  254. parser->build(pd_pool);
  255. // Commit the pool to the local list of pools.
  256. parser->commit();
  257. }
  258. }
  259. /// @brief Commits the pools created to the external storage area.
  260. ///
  261. /// Note that this method adds the local list of pools to the storage area
  262. /// rather than replacing its contents. This permits other parsers to
  263. /// contribute to the set of pools.
  264. void commit() {
  265. // local_pools_ holds the values produced by the build function.
  266. // At this point parsing should have completed successfully so
  267. // we can append new data to the supplied storage.
  268. pools_->insert(pools_->end(), local_pools_->begin(),
  269. local_pools_->end());
  270. }
  271. private:
  272. /// @brief storage for local pools
  273. PoolStoragePtr local_pools_;
  274. /// @brief External storage where pools are stored upon list commit.
  275. PoolStoragePtr pools_;
  276. };
  277. /// @brief This class parses a single IPv6 subnet.
  278. ///
  279. /// This is the IPv6 derivation of the SubnetConfigParser class and it parses
  280. /// the whole subnet definition. It creates parsersfor received configuration
  281. /// parameters as needed.
  282. class Subnet6ConfigParser : public SubnetConfigParser {
  283. public:
  284. /// @brief Constructor
  285. ///
  286. /// @param ignored first parameter
  287. /// stores global scope parameters, options, option defintions.
  288. Subnet6ConfigParser(const std::string&)
  289. :SubnetConfigParser("", globalContext(), IOAddress("::")) {
  290. }
  291. /// @brief Parses a single IPv6 subnet configuration and adds to the
  292. /// Configuration Manager.
  293. ///
  294. /// @param subnet A new subnet being configured.
  295. void build(ConstElementPtr subnet) {
  296. SubnetConfigParser::build(subnet);
  297. if (subnet_) {
  298. Subnet6Ptr sub6ptr = boost::dynamic_pointer_cast<Subnet6>(subnet_);
  299. if (!sub6ptr) {
  300. // If we hit this, it is a programming error.
  301. isc_throw(Unexpected,
  302. "Invalid cast in Subnet6ConfigParser::commit");
  303. }
  304. // Set relay infomation if it was provided
  305. if (relay_info_) {
  306. sub6ptr->setRelayInfo(*relay_info_);
  307. }
  308. // Adding a subnet to the Configuration Manager may fail if the
  309. // subnet id is invalid (duplicate). Thus, we catch exceptions
  310. // here to append a position in the configuration string.
  311. try {
  312. CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->add(sub6ptr);
  313. } catch (const std::exception& ex) {
  314. isc_throw(DhcpConfigError, ex.what() << " ("
  315. << subnet->getPosition() << ")");
  316. }
  317. // Parse Host Reservations for this subnet if any.
  318. ConstElementPtr reservations = subnet->get("reservations");
  319. if (reservations) {
  320. ParserPtr parser(new HostReservationsListParser<
  321. HostReservationParser6>(subnet_->getID()));
  322. parser->build(reservations);
  323. }
  324. }
  325. }
  326. /// @brief Commits subnet configuration.
  327. ///
  328. /// This function is currently no-op because subnet should already
  329. /// be added into the Config Manager in the build().
  330. void commit() { }
  331. protected:
  332. /// @brief creates parsers for entries in subnet definition
  333. ///
  334. /// @param config_id name of the entry
  335. ///
  336. /// @return parser object for specified entry name. Note the caller is
  337. /// responsible for deleting the parser created.
  338. /// @throw isc::dhcp::DhcpConfigError if trying to create a parser
  339. /// for unknown config element
  340. DhcpConfigParser* createSubnetConfigParser(const std::string& config_id) {
  341. DhcpConfigParser* parser = NULL;
  342. if ((config_id.compare("preferred-lifetime") == 0) ||
  343. (config_id.compare("valid-lifetime") == 0) ||
  344. (config_id.compare("renew-timer") == 0) ||
  345. (config_id.compare("rebind-timer") == 0) ||
  346. (config_id.compare("id") == 0)) {
  347. parser = new Uint32Parser(config_id, uint32_values_);
  348. } else if ((config_id.compare("subnet") == 0) ||
  349. (config_id.compare("interface") == 0) ||
  350. (config_id.compare("client-class") == 0) ||
  351. (config_id.compare("interface-id") == 0) ||
  352. (config_id.compare("reservation-mode") == 0)) {
  353. parser = new StringParser(config_id, string_values_);
  354. } else if (config_id.compare("pools") == 0) {
  355. parser = new Pools6ListParser(config_id, pools_);
  356. } else if (config_id.compare("relay") == 0) {
  357. parser = new RelayInfoParser(config_id, relay_info_, Option::V6);
  358. } else if (config_id.compare("pd-pools") == 0) {
  359. parser = new PdPoolListParser(config_id, pools_);
  360. } else if (config_id.compare("option-data") == 0) {
  361. parser = new OptionDataListParser(config_id, options_, AF_INET6);
  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. // represenation 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. stringstream tmp;
  425. tmp << addr << "/" << static_cast<int>(len)
  426. << " with params t1=" << t1 << ", t2=" << t2 << ", pref="
  427. << pref << ", valid=" << valid;
  428. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_NEW_SUBNET).arg(tmp.str());
  429. // Create a new subnet.
  430. Subnet6* subnet6 = new Subnet6(addr, len, t1, t2, pref, valid,
  431. subnet_id);
  432. // Configure interface-id for remote interfaces, if defined
  433. if (!ifaceid.empty()) {
  434. OptionBuffer tmp(ifaceid.begin(), ifaceid.end());
  435. OptionPtr opt(new Option(Option::V6, D6O_INTERFACE_ID, tmp));
  436. subnet6->setInterfaceId(opt);
  437. }
  438. // Try setting up client class (if specified)
  439. try {
  440. string client_class = string_values_->getParam("client-class");
  441. subnet6->allowClientClass(client_class);
  442. } catch (const DhcpConfigError&) {
  443. // That's ok if it fails. client-class is optional.
  444. }
  445. subnet_.reset(subnet6);
  446. }
  447. };
  448. /// @brief this class parses a list of DHCP6 subnets
  449. ///
  450. /// This is a wrapper parser that handles the whole list of Subnet6
  451. /// definitions. It iterates over all entries and creates Subnet6ConfigParser
  452. /// for each entry.
  453. class Subnets6ListConfigParser : public DhcpConfigParser {
  454. public:
  455. /// @brief constructor
  456. ///
  457. /// @param dummy first argument, always ignored. All parsers accept a
  458. /// string parameter "name" as their first argument.
  459. Subnets6ListConfigParser(const std::string&) {
  460. }
  461. /// @brief parses contents of the list
  462. ///
  463. /// Iterates over all entries on the list and creates a Subnet6ConfigParser
  464. /// for each entry.
  465. ///
  466. /// @param subnets_list pointer to a list of IPv6 subnets
  467. void build(ConstElementPtr subnets_list) {
  468. BOOST_FOREACH(ConstElementPtr subnet, subnets_list->listValue()) {
  469. ParserPtr parser(new Subnet6ConfigParser("subnet"));
  470. parser->build(subnet);
  471. subnets_.push_back(parser);
  472. }
  473. }
  474. /// @brief commits subnets definitions.
  475. ///
  476. /// Iterates over all Subnet6 parsers. Each parser contains definitions of
  477. /// a single subnet and its parameters and commits each subnet separately.
  478. void commit() {
  479. BOOST_FOREACH(ParserPtr subnet, subnets_) {
  480. subnet->commit();
  481. }
  482. }
  483. /// @brief Returns Subnet6ListConfigParser object
  484. /// @param param_name name of the parameter
  485. /// @return Subnets6ListConfigParser object
  486. static DhcpConfigParser* factory(const std::string& param_name) {
  487. return (new Subnets6ListConfigParser(param_name));
  488. }
  489. /// @brief collection of subnet parsers.
  490. ParserCollection subnets_;
  491. };
  492. } // anonymous namespace
  493. namespace isc {
  494. namespace dhcp {
  495. /// @brief creates global parsers
  496. ///
  497. /// This method creates global parsers that parse global parameters, i.e.
  498. /// those that take format of Dhcp6/param1, Dhcp6/param2 and so forth.
  499. ///
  500. /// @param config_id pointer to received global configuration entry
  501. /// @return parser for specified global DHCPv6 parameter
  502. /// @throw NotImplemented if trying to create a parser for unknown config
  503. /// element
  504. DhcpConfigParser* createGlobal6DhcpConfigParser(const std::string& config_id,
  505. ConstElementPtr element) {
  506. DhcpConfigParser* parser = NULL;
  507. if ((config_id.compare("preferred-lifetime") == 0) ||
  508. (config_id.compare("valid-lifetime") == 0) ||
  509. (config_id.compare("renew-timer") == 0) ||
  510. (config_id.compare("rebind-timer") == 0)) {
  511. parser = new Uint32Parser(config_id,
  512. globalContext()->uint32_values_);
  513. } else if (config_id.compare("interfaces-config") == 0) {
  514. parser = new IfacesConfigParser6();
  515. } else if (config_id.compare("subnet6") == 0) {
  516. parser = new Subnets6ListConfigParser(config_id);
  517. } else if (config_id.compare("option-data") == 0) {
  518. parser = new OptionDataListParser(config_id, CfgOptionPtr(), AF_INET6);
  519. } else if (config_id.compare("option-def") == 0) {
  520. parser = new OptionDefListParser(config_id, globalContext());
  521. } else if (config_id.compare("version") == 0) {
  522. parser = new StringParser(config_id,
  523. globalContext()->string_values_);
  524. } else if (config_id.compare("lease-database") == 0) {
  525. parser = new DbAccessParser(config_id, *globalContext());
  526. } else if (config_id.compare("hooks-libraries") == 0) {
  527. parser = new HooksLibrariesParser(config_id);
  528. } else if (config_id.compare("dhcp-ddns") == 0) {
  529. parser = new D2ClientConfigParser(config_id);
  530. } else if (config_id.compare("mac-sources") == 0) {
  531. parser = new MACSourcesListConfigParser(config_id,
  532. globalContext());
  533. } else {
  534. isc_throw(DhcpConfigError,
  535. "unsupported global configuration parameter: "
  536. << config_id << " (" << element->getPosition() << ")");
  537. }
  538. return (parser);
  539. }
  540. isc::data::ConstElementPtr
  541. configureDhcp6Server(Dhcpv6Srv&, isc::data::ConstElementPtr config_set) {
  542. if (!config_set) {
  543. ConstElementPtr answer = isc::config::createAnswer(1,
  544. string("Can't parse NULL config"));
  545. return (answer);
  546. }
  547. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND,
  548. DHCP6_CONFIG_START).arg(config_set->str());
  549. // Before starting any subnet operations, let's reset the subnet-id counter,
  550. // so newly recreated configuration starts with first subnet-id equal 1.
  551. Subnet::resetSubnetID();
  552. // Some of the values specified in the configuration depend on
  553. // other values. Typically, the values in the subnet6 structure
  554. // depend on the global values. Also, option values configuration
  555. // must be performed after the option definitions configurations.
  556. // Thus we group parsers and will fire them in the right order:
  557. // all parsers other than lease-database, subnet6 and
  558. // option-data parser, then option-data parser, subnet6 parser,
  559. // lease-database parser.
  560. // Please do not change this order!
  561. ParserCollection independent_parsers;
  562. ParserPtr subnet_parser;
  563. ParserPtr option_parser;
  564. ParserPtr iface_parser;
  565. ParserPtr leases_parser;
  566. // Some of the parsers alter state of the system that can't easily
  567. // be undone. (Or alter it in a way such that undoing the change
  568. // has the same risk of failure as doing the change.)
  569. ParserPtr hooks_parser;
  570. // The subnet parsers implement data inheritance by directly
  571. // accessing global storage. For this reason the global data
  572. // parsers must store the parsed data into global storages
  573. // immediately. This may cause data inconsistency if the
  574. // parsing operation fails after the global storage has been
  575. // modified. We need to preserve the original global data here
  576. // so as we can rollback changes when an error occurs.
  577. ParserContext original_context(*globalContext());
  578. // answer will hold the result.
  579. ConstElementPtr answer;
  580. // rollback informs whether error occured and original data
  581. // have to be restored to global storages.
  582. bool rollback = false;
  583. // config_pair holds ther details of the current parser when iterating over
  584. // the parsers. It is declared outside the loop so in case of error, the
  585. // name of the failing parser can be retrieved within the "catch" clause.
  586. ConfigPair config_pair;
  587. try {
  588. // Make parsers grouping.
  589. const std::map<std::string, ConstElementPtr>& values_map =
  590. config_set->mapValue();
  591. BOOST_FOREACH(config_pair, values_map) {
  592. ParserPtr parser(createGlobal6DhcpConfigParser(config_pair.first,
  593. config_pair.second));
  594. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PARSER_CREATED)
  595. .arg(config_pair.first);
  596. if (config_pair.first == "subnet6") {
  597. subnet_parser = parser;
  598. } else if (config_pair.first == "lease-database") {
  599. leases_parser = parser;
  600. } else if (config_pair.first == "option-data") {
  601. option_parser = parser;
  602. } else if (config_pair.first == "hooks-libraries") {
  603. // Executing the commit will alter currently loaded hooks
  604. // libraries. Check if the supplied libraries are valid,
  605. // but defer the commit until after everything else has
  606. // committed.
  607. hooks_parser = parser;
  608. hooks_parser->build(config_pair.second);
  609. } else if (config_pair.first == "interfaces-config") {
  610. // The interface parser is independent from any other parser and
  611. // can be run here before other parsers.
  612. parser->build(config_pair.second);
  613. iface_parser = parser;
  614. } else {
  615. // Those parsers should be started before other
  616. // parsers so we can call build straight away.
  617. independent_parsers.push_back(parser);
  618. parser->build(config_pair.second);
  619. // The commit operation here may modify the global storage
  620. // but we need it so as the subnet6 parser can access the
  621. // parsed data.
  622. parser->commit();
  623. }
  624. }
  625. // The option values parser is the next one to be run.
  626. std::map<std::string, ConstElementPtr>::const_iterator option_config =
  627. values_map.find("option-data");
  628. if (option_config != values_map.end()) {
  629. config_pair.first = "option-data";
  630. option_parser->build(option_config->second);
  631. option_parser->commit();
  632. }
  633. // The subnet parser is the next one to be run.
  634. std::map<std::string, ConstElementPtr>::const_iterator subnet_config =
  635. values_map.find("subnet6");
  636. if (subnet_config != values_map.end()) {
  637. config_pair.first = "subnet6";
  638. subnet_parser->build(subnet_config->second);
  639. }
  640. // The lease database parser is the last to be run.
  641. std::map<std::string, ConstElementPtr>::const_iterator leases_config =
  642. values_map.find("lease-database");
  643. if (leases_config != values_map.end()) {
  644. config_pair.first = "lease-database";
  645. leases_parser->build(leases_config->second);
  646. leases_parser->commit();
  647. }
  648. } catch (const isc::Exception& ex) {
  649. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_FAIL)
  650. .arg(config_pair.first).arg(ex.what());
  651. answer = isc::config::createAnswer(1, ex.what());
  652. // An error occured, so make sure that we restore original data.
  653. rollback = true;
  654. } catch (...) {
  655. // for things like bad_cast in boost::lexical_cast
  656. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_EXCEPTION).arg(config_pair.first);
  657. answer = isc::config::createAnswer(1, "undefined configuration"
  658. " processing error");
  659. // An error occured, so make sure that we restore original data.
  660. rollback = true;
  661. }
  662. // So far so good, there was no parsing error so let's commit the
  663. // configuration. This will add created subnets and option values into
  664. // the server's configuration.
  665. // This operation should be exception safe but let's make sure.
  666. if (!rollback) {
  667. try {
  668. if (subnet_parser) {
  669. subnet_parser->commit();
  670. }
  671. // No need to commit interface names as this is handled by the
  672. // CfgMgr::commit() function.
  673. // This occurs last as if it succeeds, there is no easy way to
  674. // revert it. As a result, the failure to commit a subsequent
  675. // change causes problems when trying to roll back.
  676. if (hooks_parser) {
  677. hooks_parser->commit();
  678. }
  679. }
  680. catch (const isc::Exception& ex) {
  681. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(ex.what());
  682. answer = isc::config::createAnswer(2, ex.what());
  683. // An error occured, so make sure to restore the original data.
  684. rollback = true;
  685. } catch (...) {
  686. // for things like bad_cast in boost::lexical_cast
  687. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_EXCEPTION);
  688. answer = isc::config::createAnswer(2, "undefined configuration"
  689. " parsing error");
  690. // An error occured, so make sure to restore the original data.
  691. rollback = true;
  692. }
  693. }
  694. // Rollback changes as the configuration parsing failed.
  695. if (rollback) {
  696. globalContext().reset(new ParserContext(original_context));
  697. return (answer);
  698. }
  699. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_COMPLETE)
  700. .arg(CfgMgr::instance().getCurrentCfg()->
  701. getConfigSummary(SrvConfig::CFGSEL_ALL6));
  702. // Everything was fine. Configuration is successful.
  703. answer = isc::config::createAnswer(0, "Configuration successful.");
  704. return (answer);
  705. }
  706. ParserContextPtr& globalContext() {
  707. static ParserContextPtr global_context_ptr(new ParserContext(Option::V6));
  708. return (global_context_ptr);
  709. }
  710. }; // end of isc::dhcp namespace
  711. }; // end of isc namespace