config_parser.cc 33 KB

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