json_config_parser.cc 44 KB

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