config_parser.cc 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491
  1. // Copyright (C) 2012-2013 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 <dhcpsrv/cfgmgr.h>
  21. #include <dhcpsrv/dhcp_config_parser.h>
  22. #include <dhcpsrv/pool.h>
  23. #include <dhcpsrv/subnet.h>
  24. #include <dhcpsrv/triplet.h>
  25. #include <log/logger_support.h>
  26. #include <util/encode/hex.h>
  27. #include <util/strutil.h>
  28. #include <boost/algorithm/string.hpp>
  29. #include <boost/foreach.hpp>
  30. #include <boost/lexical_cast.hpp>
  31. #include <boost/scoped_ptr.hpp>
  32. #include <boost/shared_ptr.hpp>
  33. #include <iostream>
  34. #include <map>
  35. #include <vector>
  36. #include <stdint.h>
  37. using namespace std;
  38. using namespace isc::data;
  39. using namespace isc::dhcp;
  40. using namespace isc::asiolink;
  41. namespace {
  42. /// @brief Auxiliary type used for storing an element name and its parser.
  43. typedef pair<string, ConstElementPtr> ConfigPair;
  44. /// @brief Factory method that will create a parser for a given element name
  45. typedef isc::dhcp::DhcpConfigParser* ParserFactory(const std::string& config_id);
  46. /// @brief Collection of factories that create parsers for specified element names
  47. typedef std::map<std::string, ParserFactory*> FactoryMap;
  48. /// @brief Storage for parsed boolean values.
  49. typedef std::map<string, bool> BooleanStorage;
  50. /// @brief Collection of elements that store uint32 values (e.g. renew-timer = 900).
  51. typedef std::map<string, uint32_t> Uint32Storage;
  52. /// @brief Collection of elements that store string values.
  53. typedef std::map<string, string> StringStorage;
  54. /// @brief Collection of address pools.
  55. ///
  56. /// This type is used as intermediate storage, when pools are parsed, but there is
  57. /// no subnet object created yet to store them.
  58. typedef std::vector<isc::dhcp::Pool6Ptr> PoolStorage;
  59. /// @brief Collection of option descriptors.
  60. ///
  61. /// This container allows to search options using an option code
  62. /// or a persistency flag. This is useful when merging existing
  63. /// options with newly configured options.
  64. typedef isc::dhcp::Subnet::OptionContainer OptionStorage;
  65. /// @brief Global uint32 parameters that will be used as defaults.
  66. Uint32Storage uint32_defaults;
  67. /// @brief global string parameters that will be used as defaults.
  68. StringStorage string_defaults;
  69. /// @brief Global storage for options that will be used as defaults.
  70. OptionStorage option_defaults;
  71. /// @brief a dummy configuration parser
  72. ///
  73. /// This is a debugging parser. It does not configure anything,
  74. /// will accept any configuration and will just print it out
  75. /// on commit. Useful for debugging existing configurations and
  76. /// adding new ones.
  77. class DebugParser : public DhcpConfigParser {
  78. public:
  79. /// @brief Constructor
  80. ///
  81. /// See @ref DhcpConfigParser class for details.
  82. ///
  83. /// @param param_name name of the parsed parameter
  84. DebugParser(const std::string& param_name)
  85. :param_name_(param_name) {
  86. }
  87. /// @brief builds parameter value
  88. ///
  89. /// See @ref DhcpConfigParser class for details.
  90. ///
  91. /// @param new_config pointer to the new configuration
  92. virtual void build(ConstElementPtr new_config) {
  93. std::cout << "Build for token: [" << param_name_ << "] = ["
  94. << value_->str() << "]" << std::endl;
  95. value_ = new_config;
  96. }
  97. /// @brief Pretends to apply the configuration.
  98. ///
  99. /// This is a method required by the base class. It pretends to apply the
  100. /// configuration, but in fact it only prints the parameter out.
  101. ///
  102. /// See @ref DhcpConfigParser class for details.
  103. virtual void commit() {
  104. // Debug message. The whole DebugParser class is used only for parser
  105. // debugging, and is not used in production code. It is very convenient
  106. // to keep it around. Please do not turn this cout into logger calls.
  107. std::cout << "Commit for token: [" << param_name_ << "] = ["
  108. << value_->str() << "]" << std::endl;
  109. }
  110. /// @brief factory that constructs DebugParser objects
  111. ///
  112. /// @param param_name name of the parameter to be parsed
  113. static DhcpConfigParser* factory(const std::string& param_name) {
  114. return (new DebugParser(param_name));
  115. }
  116. private:
  117. /// name of the parsed parameter
  118. std::string param_name_;
  119. /// pointer to the actual value of the parameter
  120. ConstElementPtr value_;
  121. };
  122. /// @brief A boolean value parser.
  123. ///
  124. /// This parser handles configuration values of the boolean type.
  125. /// Parsed values are stored in a provided storage. If no storage
  126. /// is provided then the build function throws an exception.
  127. class BooleanParser : public DhcpConfigParser {
  128. public:
  129. /// @brief Constructor.
  130. ///
  131. /// @param param_name name of the parameter.
  132. BooleanParser(const std::string& param_name)
  133. : storage_(NULL),
  134. param_name_(param_name),
  135. value_(false) {
  136. // Empty parameter name is invalid.
  137. if (param_name_.empty()) {
  138. isc_throw(isc::dhcp::Dhcp6ConfigError, "parser logic error:"
  139. << "empty parameter name provided");
  140. }
  141. }
  142. /// @brief Parse a boolean value.
  143. ///
  144. /// @param value a value to be parsed.
  145. ///
  146. /// @throw isc::InvalidOperation if a storage has not been set
  147. /// prior to calling this function
  148. /// @throw isc::dhcp::Dhcp6ConfigError if a provided parameter's
  149. /// name is empty.
  150. virtual void build(ConstElementPtr value) {
  151. if (storage_ == NULL) {
  152. isc_throw(isc::InvalidOperation, "parser logic error:"
  153. << " storage for the " << param_name_
  154. << " value has not been set");
  155. } else if (param_name_.empty()) {
  156. isc_throw(isc::dhcp::Dhcp6ConfigError, "parser logic error:"
  157. << "empty parameter name provided");
  158. }
  159. // The Config Manager checks if user specified a
  160. // valid value for a boolean parameter: True or False.
  161. // It is then ok to assume that if str() does not return
  162. // 'true' the value is 'false'.
  163. value_ = (value->str() == "true") ? true : false;
  164. }
  165. /// @brief Put a parsed value to the storage.
  166. virtual void commit() {
  167. if (storage_ != NULL && !param_name_.empty()) {
  168. (*storage_)[param_name_] = value_;
  169. }
  170. }
  171. /// @brief Create an instance of the boolean parser.
  172. ///
  173. /// @param param_name name of the parameter for which the
  174. /// parser is created.
  175. static DhcpConfigParser* factory(const std::string& param_name) {
  176. return (new BooleanParser(param_name));
  177. }
  178. /// @brief Set the storage for parsed value.
  179. ///
  180. /// This function must be called prior to calling build.
  181. ///
  182. /// @param storage a pointer to the storage where parsed data
  183. /// is to be stored.
  184. void setStorage(BooleanStorage* storage) {
  185. storage_ = storage;
  186. }
  187. private:
  188. /// Pointer to the storage where parsed value is stored.
  189. BooleanStorage* storage_;
  190. /// Name of the parameter which value is parsed with this parser.
  191. std::string param_name_;
  192. /// Parsed value.
  193. bool value_;
  194. };
  195. /// @brief Configuration parser for uint32 parameters
  196. ///
  197. /// This class is a generic parser that is able to handle any uint32 integer
  198. /// type. By default it stores the value in external global container
  199. /// (uint32_defaults). If used in smaller scopes (e.g. to parse parameters
  200. /// in subnet config), it can be pointed to a different storage, using
  201. /// setStorage() method. This class follows the parser interface, laid out
  202. /// in its base class, @ref DhcpConfigParser.
  203. ///
  204. /// For overview of usability of this generic purpose parser, see
  205. /// @ref dhcpv6ConfigInherit page.
  206. ///
  207. /// @todo this class should be turned into the template class which
  208. /// will handle all uintX_types of data (see ticket #2415).
  209. class Uint32Parser : public DhcpConfigParser {
  210. public:
  211. /// @brief constructor for Uint32Parser
  212. ///
  213. /// @param param_name name of the configuration parameter being parsed
  214. Uint32Parser(const std::string& param_name)
  215. : storage_(&uint32_defaults),
  216. param_name_(param_name) {
  217. // Empty parameter name is invalid.
  218. if (param_name_.empty()) {
  219. isc_throw(Dhcp6ConfigError, "parser logic error:"
  220. << "empty parameter name provided");
  221. }
  222. }
  223. /// @brief Parses configuration configuration parameter as uint32_t.
  224. ///
  225. /// @param value pointer to the content of parsed values
  226. /// @throw isc::dhcp::Dhcp6ConfigError if failed to parse
  227. /// the configuration parameter as uint32_t value.
  228. virtual void build(ConstElementPtr value) {
  229. if (param_name_.empty()) {
  230. isc_throw(isc::dhcp::Dhcp6ConfigError, "parser logic error:"
  231. << "empty parameter name provided");
  232. }
  233. bool parse_error = false;
  234. // Cast the provided value to int64 value to check.
  235. int64_t int64value = 0;
  236. try {
  237. // Parsing the value as a int64 value allows to
  238. // check if the provided value is within the range
  239. // of uint32_t (is not negative or greater than
  240. // maximal uint32_t value).
  241. int64value = boost::lexical_cast<int64_t>(value->str());
  242. } catch (const boost::bad_lexical_cast&) {
  243. parse_error = true;
  244. }
  245. if (!parse_error) {
  246. // Check that the value is not out of bounds.
  247. if ((int64value < 0) ||
  248. (int64value > std::numeric_limits<uint32_t>::max())) {
  249. parse_error = true;
  250. } else {
  251. // A value is not out of bounds so let's cast it to
  252. // the uint32_t type.
  253. value_ = static_cast<uint32_t>(int64value);
  254. }
  255. }
  256. // Invalid value provided.
  257. if (parse_error) {
  258. isc_throw(isc::dhcp::Dhcp6ConfigError, "Failed to parse value " << value->str()
  259. << " as unsigned 32-bit integer.");
  260. }
  261. }
  262. /// @brief Stores the parsed uint32_t value in a storage.
  263. virtual void commit() {
  264. if (storage_ != NULL) {
  265. // If a given parameter already exists in the storage we override
  266. // its value. If it doesn't we insert a new element.
  267. (*storage_)[param_name_] = value_;
  268. }
  269. }
  270. /// @brief Factory that constructs Uint32Parser objects.
  271. ///
  272. /// @param param_name name of the parameter to be parsed.
  273. static DhcpConfigParser* factory(const std::string& param_name) {
  274. return (new Uint32Parser(param_name));
  275. }
  276. /// @brief Sets storage for value of this parameter.
  277. ///
  278. /// See @ref dhcpv6ConfigInherit for details.
  279. ///
  280. /// @param storage pointer to the storage container.
  281. void setStorage(Uint32Storage* storage) {
  282. storage_ = storage;
  283. }
  284. private:
  285. /// pointer to the storage, where parsed value will be stored
  286. Uint32Storage* storage_;
  287. /// name of the parameter to be parsed
  288. std::string param_name_;
  289. /// the actual parsed value
  290. uint32_t value_;
  291. };
  292. /// @brief Configuration parser for string parameters
  293. ///
  294. /// This class is a generic parser that is able to handle any string
  295. /// parameter. By default it stores the value in an external global container
  296. /// (string_defaults). If used in smaller scopes (e.g. to parse parameters
  297. /// in subnet config), it can be pointed to a different storage, using the
  298. /// setStorage() method. This class follows the parser interface, laid out
  299. /// in its base class, @ref DhcpConfigParser.
  300. ///
  301. /// For overview of usability of this generic purpose parser, see
  302. /// @ref dhcpv6ConfigInherit page.
  303. class StringParser : public DhcpConfigParser {
  304. public:
  305. /// @brief constructor for StringParser
  306. ///
  307. /// @param param_name name of the configuration parameter being parsed
  308. StringParser(const std::string& param_name)
  309. : storage_(&string_defaults),
  310. param_name_(param_name) {
  311. // Empty parameter name is invalid.
  312. if (param_name_.empty()) {
  313. isc_throw(Dhcp6ConfigError, "parser logic error:"
  314. << "empty parameter name provided");
  315. }
  316. }
  317. /// @brief parses parameter value
  318. ///
  319. /// Parses configuration parameter's value as string.
  320. ///
  321. /// @param value pointer to the content of parsed values
  322. /// @throws Dhcp6ConfigError if the parsed parameter's name is empty.
  323. virtual void build(ConstElementPtr value) {
  324. if (param_name_.empty()) {
  325. isc_throw(isc::dhcp::Dhcp6ConfigError, "parser logic error:"
  326. << "empty parameter name provided");
  327. }
  328. value_ = value->str();
  329. boost::erase_all(value_, "\"");
  330. }
  331. /// @brief Stores the parsed value in a storage.
  332. virtual void commit() {
  333. if (storage_ != NULL && !param_name_.empty()) {
  334. // If a given parameter already exists in the storage we override
  335. // its value. If it doesn't we insert a new element.
  336. (*storage_)[param_name_] = value_;
  337. }
  338. }
  339. /// @brief Factory that constructs StringParser objects
  340. ///
  341. /// @param param_name name of the parameter to be parsed
  342. static DhcpConfigParser* factory(const std::string& param_name) {
  343. return (new StringParser(param_name));
  344. }
  345. /// @brief Sets storage for value of this parameter.
  346. ///
  347. /// See @ref dhcpv6ConfigInherit for details.
  348. ///
  349. /// @param storage pointer to the storage container
  350. void setStorage(StringStorage* storage) {
  351. storage_ = storage;
  352. }
  353. private:
  354. /// Pointer to the storage, where parsed value will be stored
  355. StringStorage* storage_;
  356. /// Name of the parameter to be parsed
  357. std::string param_name_;
  358. /// The actual parsed value
  359. std::string value_;
  360. };
  361. /// @brief parser for interface list definition
  362. ///
  363. /// This parser handles Dhcp6/interface entry.
  364. /// It contains a list of network interfaces that the server listens on.
  365. /// In particular, it can contain an entry called "all" or "any" that
  366. /// designates all interfaces.
  367. ///
  368. /// It is useful for parsing Dhcp6/interface parameter.
  369. class InterfaceListConfigParser : public DhcpConfigParser {
  370. public:
  371. /// @brief constructor
  372. ///
  373. /// As this is a dedicated parser, it must be used to parse
  374. /// "interface" parameter only. All other types will throw exception.
  375. ///
  376. /// @param param_name name of the configuration parameter being parsed
  377. /// @throw BadValue if supplied parameter name is not "interface"
  378. InterfaceListConfigParser(const std::string& param_name) {
  379. if (param_name != "interface") {
  380. isc_throw(isc::BadValue, "Internal error. Interface configuration "
  381. "parser called for the wrong parameter: " << param_name);
  382. }
  383. }
  384. /// @brief parses parameters value
  385. ///
  386. /// Parses configuration entry (list of parameters) and stores it in
  387. /// storage.
  388. ///
  389. /// @param value pointer to the content of parsed values
  390. virtual void build(ConstElementPtr value) {
  391. BOOST_FOREACH(ConstElementPtr iface, value->listValue()) {
  392. interfaces_.push_back(iface->str());
  393. }
  394. }
  395. /// @brief commits interfaces list configuration
  396. virtual void commit() {
  397. /// @todo: Implement per interface listening. Currently always listening
  398. /// on all interfaces.
  399. }
  400. /// @brief factory that constructs InterfaceListConfigParser objects
  401. ///
  402. /// @param param_name name of the parameter to be parsed
  403. static DhcpConfigParser* factory(const std::string& param_name) {
  404. return (new InterfaceListConfigParser(param_name));
  405. }
  406. private:
  407. /// contains list of network interfaces
  408. vector<string> interfaces_;
  409. };
  410. /// @brief parser for pool definition
  411. ///
  412. /// This parser handles pool definitions, i.e. a list of entries of one
  413. /// of two syntaxes: min-max and prefix/len. Pool6 objects are created
  414. /// and stored in chosen PoolStorage container.
  415. ///
  416. /// As there are no default values for pool, setStorage() must be called
  417. /// before build(). Otherwise an exception will be thrown.
  418. ///
  419. /// It is useful for parsing Dhcp6/subnet6[X]/pool parameters.
  420. class PoolParser : public DhcpConfigParser {
  421. public:
  422. /// @brief constructor.
  423. PoolParser(const std::string& /*param_name*/)
  424. : pools_(NULL) {
  425. // ignore parameter name, it is always Dhcp6/subnet6[X]/pool
  426. }
  427. /// @brief parses the actual list
  428. ///
  429. /// This method parses the actual list of interfaces.
  430. /// No validation is done at this stage, everything is interpreted as
  431. /// interface name.
  432. /// @param pools_list list of pools defined for a subnet
  433. /// @throw isc::InvalidOperation if storage was not specified
  434. /// (setStorage() not called)
  435. void build(ConstElementPtr pools_list) {
  436. // setStorage() should have been called before build
  437. if (!pools_) {
  438. isc_throw(isc::InvalidOperation, "parser logic error: no pool storage set,"
  439. " but pool parser asked to parse pools");
  440. }
  441. BOOST_FOREACH(ConstElementPtr text_pool, pools_list->listValue()) {
  442. // That should be a single pool representation. It should contain
  443. // text in the form prefix/len or first - last. Note that spaces
  444. // are allowed
  445. string txt = text_pool->stringValue();
  446. // first let's remove any whitespaces
  447. boost::erase_all(txt, " "); // space
  448. boost::erase_all(txt, "\t"); // tabulation
  449. // Is this prefix/len notation?
  450. size_t pos = txt.find("/");
  451. if (pos != string::npos) {
  452. IOAddress addr("::");
  453. uint8_t len = 0;
  454. try {
  455. addr = IOAddress(txt.substr(0, pos));
  456. // start with the first character after /
  457. string prefix_len = txt.substr(pos + 1);
  458. // It is lexically cast to int and then downcast to uint8_t.
  459. // Direct cast to uint8_t (which is really an unsigned char)
  460. // will result in interpreting the first digit as output
  461. // value and throwing exception if length is written on two
  462. // digits (because there are extra characters left over).
  463. // No checks for values over 128. Range correctness will
  464. // be checked in Pool6 constructor.
  465. len = boost::lexical_cast<int>(prefix_len);
  466. } catch (...) {
  467. isc_throw(Dhcp6ConfigError, "failed to parse pool "
  468. "definition: " << text_pool->stringValue());
  469. }
  470. Pool6Ptr pool(new Pool6(Pool6::TYPE_IA, addr, len));
  471. local_pools_.push_back(pool);
  472. continue;
  473. }
  474. // Is this min-max notation?
  475. pos = txt.find("-");
  476. if (pos != string::npos) {
  477. // using min-max notation
  478. IOAddress min(txt.substr(0, pos));
  479. IOAddress max(txt.substr(pos + 1));
  480. Pool6Ptr pool(new Pool6(Pool6::TYPE_IA, min, max));
  481. local_pools_.push_back(pool);
  482. continue;
  483. }
  484. isc_throw(Dhcp6ConfigError, "failed to parse pool definition:"
  485. << text_pool->stringValue() <<
  486. ". Does not contain - (for min-max) nor / (prefix/len)");
  487. }
  488. }
  489. /// @brief sets storage for value of this parameter
  490. ///
  491. /// See @ref dhcpv6ConfigInherit for details.
  492. ///
  493. /// @param storage pointer to the storage container
  494. void setStorage(PoolStorage* storage) {
  495. pools_ = storage;
  496. }
  497. /// @brief Stores the parsed values in a storage provided
  498. /// by an upper level parser.
  499. virtual void commit() {
  500. if (pools_) {
  501. // local_pools_ holds the values produced by the build function.
  502. // At this point parsing should have completed successfuly so
  503. // we can append new data to the supplied storage.
  504. pools_->insert(pools_->end(), local_pools_.begin(),
  505. local_pools_.end());
  506. }
  507. }
  508. /// @brief factory that constructs PoolParser objects
  509. ///
  510. /// @param param_name name of the parameter to be parsed
  511. static DhcpConfigParser* factory(const std::string& param_name) {
  512. return (new PoolParser(param_name));
  513. }
  514. private:
  515. /// @brief pointer to the actual Pools storage
  516. ///
  517. /// This is typically a storage somewhere in Subnet parser
  518. /// (an upper level parser).
  519. PoolStorage* pools_;
  520. /// A temporary storage for pools configuration. It is a
  521. /// storage where pools are stored by build function.
  522. PoolStorage local_pools_;
  523. };
  524. /// @brief Parser for option data value.
  525. ///
  526. /// This parser parses configuration entries that specify value of
  527. /// a single option. These entries include option name, option code
  528. /// and data carried by the option. If parsing is successful then an
  529. /// instance of an option is created and added to the storage provided
  530. /// by the calling class.
  531. ///
  532. /// @todo This class parses and validates the option name. However it is
  533. /// not used anywhere until support for option spaces is implemented
  534. /// (see tickets #2319, #2314). When option spaces are implemented
  535. /// there will be a way to reference the particular option using
  536. /// its type (code) or option name.
  537. class OptionDataParser : public DhcpConfigParser {
  538. public:
  539. /// @brief Constructor.
  540. ///
  541. /// Class constructor.
  542. OptionDataParser(const std::string&)
  543. : options_(NULL),
  544. // initialize option to NULL ptr
  545. option_descriptor_(false) { }
  546. /// @brief Parses the single option data.
  547. ///
  548. /// This method parses the data of a single option from the configuration.
  549. /// The option data includes option name, option code and data being
  550. /// carried by this option. Eventually it creates the instance of the
  551. /// option.
  552. ///
  553. /// @warning setStorage must be called with valid storage pointer prior
  554. /// to calling this method.
  555. ///
  556. /// @param option_data_entries collection of entries that define value
  557. /// for a particular option.
  558. /// @throw Dhcp6ConfigError if invalid parameter specified in
  559. /// the configuration.
  560. /// @throw isc::InvalidOperation if failed to set storage prior to
  561. /// calling build.
  562. /// @throw isc::BadValue if option data storage is invalid.
  563. virtual void build(ConstElementPtr option_data_entries) {
  564. if (options_ == NULL) {
  565. isc_throw(isc::InvalidOperation, "Parser logic error: storage must be set before "
  566. "parsing option data.");
  567. }
  568. BOOST_FOREACH(ConfigPair param, option_data_entries->mapValue()) {
  569. ParserPtr parser;
  570. if (param.first == "name") {
  571. boost::shared_ptr<StringParser>
  572. name_parser(dynamic_cast<StringParser*>(StringParser::factory(param.first)));
  573. if (name_parser) {
  574. name_parser->setStorage(&string_values_);
  575. parser = name_parser;
  576. }
  577. } else if (param.first == "code") {
  578. boost::shared_ptr<Uint32Parser>
  579. code_parser(dynamic_cast<Uint32Parser*>(Uint32Parser::factory(param.first)));
  580. if (code_parser) {
  581. code_parser->setStorage(&uint32_values_);
  582. parser = code_parser;
  583. }
  584. } else if (param.first == "data") {
  585. boost::shared_ptr<StringParser>
  586. value_parser(dynamic_cast<StringParser*>(StringParser::factory(param.first)));
  587. if (value_parser) {
  588. value_parser->setStorage(&string_values_);
  589. parser = value_parser;
  590. }
  591. } else if (param.first == "csv-format") {
  592. boost::shared_ptr<BooleanParser>
  593. value_parser(dynamic_cast<BooleanParser*>(BooleanParser::factory(param.first)));
  594. if (value_parser) {
  595. value_parser->setStorage(&boolean_values_);
  596. parser = value_parser;
  597. }
  598. } else {
  599. isc_throw(Dhcp6ConfigError,
  600. "parser error: option-data parameter not supported: "
  601. << param.first);
  602. }
  603. parser->build(param.second);
  604. // Before we can create an option we need to get the data from
  605. // the child parsers. The only way to do it is to invoke commit
  606. // on them so as they store the values in appropriate storages
  607. // that this class provided to them. Note that this will not
  608. // modify values stored in the global storages so the configuration
  609. // will remain consistent even parsing fails somewhere further on.
  610. parser->commit();
  611. }
  612. // Try to create the option instance.
  613. createOption();
  614. }
  615. /// @brief Commits option value.
  616. ///
  617. /// This function adds a new option to the storage or replaces an existing option
  618. /// with the same code.
  619. ///
  620. /// @throw isc::InvalidOperation if failed to set pointer to storage or failed
  621. /// to call build() prior to commit. If that happens data in the storage
  622. /// remain un-modified.
  623. virtual void commit() {
  624. if (options_ == NULL) {
  625. isc_throw(isc::InvalidOperation, "parser logic error: storage must be set before "
  626. "commiting option data.");
  627. } else if (!option_descriptor_.option) {
  628. // Before we can commit the new option should be configured. If it is not
  629. // than somebody must have called commit() before build().
  630. isc_throw(isc::InvalidOperation, "parser logic error: no option has been configured and"
  631. " thus there is nothing to commit. Has build() been called?");
  632. }
  633. uint16_t opt_type = option_descriptor_.option->getType();
  634. isc::dhcp::Subnet::OptionContainerTypeIndex& idx = options_->get<1>();
  635. // Try to find options with the particular option code in the main
  636. // storage. If found, remove these options because they will be
  637. // replaced with new one.
  638. isc::dhcp::Subnet::OptionContainerTypeRange range =
  639. idx.equal_range(opt_type);
  640. if (std::distance(range.first, range.second) > 0) {
  641. idx.erase(range.first, range.second);
  642. }
  643. // Append new option to the main storage.
  644. options_->push_back(option_descriptor_);
  645. }
  646. /// @brief Set storage for the parser.
  647. ///
  648. /// Sets storage for the parser. This storage points to the
  649. /// vector of options and is used by multiple instances of
  650. /// OptionDataParser. Each instance creates exactly one object
  651. /// of dhcp::Option or derived type and appends it to this
  652. /// storage.
  653. ///
  654. /// @param storage pointer to the options storage
  655. void setStorage(OptionStorage* storage) {
  656. options_ = storage;
  657. }
  658. private:
  659. /// @brief Create option instance.
  660. ///
  661. /// Creates an instance of an option and adds it to the provided
  662. /// options storage. If the option data parsed by \ref build function
  663. /// are invalid or insufficient this function emits an exception.
  664. ///
  665. /// @warning this function does not check if options_ storage pointer
  666. /// is intitialized but this check is not needed here because it is done
  667. /// in the \ref build function.
  668. ///
  669. /// @throw Dhcp6ConfigError if parameters provided in the configuration
  670. /// are invalid.
  671. void createOption() {
  672. // Option code is held in the uint32_t storage but is supposed to
  673. // be uint16_t value. We need to check that value in the configuration
  674. // does not exceed range of uint16_t and is not zero.
  675. uint32_t option_code = getUint32Param("code");
  676. if (option_code == 0) {
  677. isc_throw(Dhcp6ConfigError, "Parser error: value of 'code' must not"
  678. << " be equal to zero. Option code '0' is reserved in"
  679. << " DHCPv6.");
  680. } else if (option_code > std::numeric_limits<uint16_t>::max()) {
  681. isc_throw(Dhcp6ConfigError, "Parser error: value of 'code' must not"
  682. << " exceed " << std::numeric_limits<uint16_t>::max());
  683. }
  684. // Check that the option name has been specified, is non-empty and does not
  685. // contain spaces.
  686. // @todo possibly some more restrictions apply here?
  687. std::string option_name = getStringParam("name");
  688. if (option_name.empty()) {
  689. isc_throw(Dhcp6ConfigError, "Parser error: option name must not be"
  690. << " empty");
  691. } else if (option_name.find(" ") != std::string::npos) {
  692. isc_throw(Dhcp6ConfigError, "Parser error: option name must not contain"
  693. << " spaces");
  694. }
  695. // Get option data from the configuration database ('data' field).
  696. const std::string option_data = getStringParam("data");
  697. const bool csv_format = getBooleanParam("csv-format");
  698. std::vector<uint8_t> binary;
  699. std::vector<std::string> data_tokens;
  700. if (csv_format) {
  701. // If the option data is specified as a string of comma
  702. // separated values then we need to split this string into
  703. // individual values - each value will be used to initialize
  704. // one data field of an option.
  705. data_tokens = isc::util::str::tokens(option_data, ",");
  706. } else {
  707. // Otherwise, the option data is specified as a string of
  708. // hexadecimal digits that we have to turn into binary format.
  709. try {
  710. isc::util::encode::decodeHex(option_data, binary);
  711. } catch (...) {
  712. isc_throw(Dhcp6ConfigError, "Parser error: option data is not a valid"
  713. << " string of hexadecimal digits: " << option_data);
  714. }
  715. }
  716. // Get all existing DHCPv6 option definitions. The one that matches
  717. // our option will be picked and used to create it.
  718. OptionDefContainer option_defs = LibDHCP::getOptionDefs(Option::V6);
  719. // Get search index #1. It allows searching for options definitions
  720. // using option type value.
  721. const OptionDefContainerTypeIndex& idx = option_defs.get<1>();
  722. // Get all option definitions matching option code we want to create.
  723. const OptionDefContainerTypeRange& range = idx.equal_range(option_code);
  724. size_t num_defs = std::distance(range.first, range.second);
  725. OptionPtr option;
  726. // Currently we do not allow duplicated definitions and if there are
  727. // any duplicates we issue internal server error.
  728. if (num_defs > 1) {
  729. isc_throw(Dhcp6ConfigError, "Internal error: currently it is not"
  730. << " supported to initialize multiple option definitions"
  731. << " for the same option code. This will be supported once"
  732. << " there option spaces are implemented.");
  733. } else if (num_defs == 0) {
  734. if (csv_format) {
  735. isc_throw(Dhcp6ConfigError, "the CSV option data format can be"
  736. " used to specify values for an option that has a"
  737. " definition. The option with code " << option_code
  738. << " does not have a definition.");
  739. }
  740. // @todo We have a limited set of option definitions intiialized at the moment.
  741. // In the future we want to initialize option definitions for all options.
  742. // Consequently an error will be issued if an option definition does not exist
  743. // for a particular option code. For now it is ok to create generic option
  744. // if definition does not exist.
  745. OptionPtr option(new Option(Option::V6, static_cast<uint16_t>(option_code),
  746. binary));
  747. // The created option is stored in option_descriptor_ class member until the
  748. // commit stage when it is inserted into the main storage. If an option with the
  749. // same code exists in main storage already the old option is replaced.
  750. option_descriptor_.option = option;
  751. option_descriptor_.persistent = false;
  752. } else {
  753. // We have exactly one option definition for the particular option code
  754. // use it to create the option instance.
  755. const OptionDefinitionPtr& def = *(range.first);
  756. try {
  757. OptionPtr option = csv_format ?
  758. def->optionFactory(Option::V6, option_code, data_tokens) :
  759. def->optionFactory(Option::V6, option_code, binary);
  760. Subnet::OptionDescriptor desc(option, false);
  761. option_descriptor_.option = option;
  762. option_descriptor_.persistent = false;
  763. } catch (const isc::Exception& ex) {
  764. isc_throw(Dhcp6ConfigError, "Parser error: option data does not match"
  765. << " option definition (code " << option_code << "): "
  766. << ex.what());
  767. }
  768. }
  769. }
  770. /// @brief Get a parameter from the strings storage.
  771. ///
  772. /// @param param_id parameter identifier.
  773. ///
  774. /// @throw Dhcp6ConfigError if a parameter has not been found.
  775. /// @return a value of the string parameter.
  776. std::string getStringParam(const std::string& param_id) const {
  777. StringStorage::const_iterator param = string_values_.find(param_id);
  778. if (param == string_values_.end()) {
  779. isc_throw(isc::dhcp::Dhcp6ConfigError, "parser error: option-data parameter"
  780. << " '" << param_id << "' not specified");
  781. }
  782. return (param->second);
  783. }
  784. /// @brief Get a parameter from the uint32 values storage.
  785. ///
  786. /// @param param_id parameter identifier.
  787. ///
  788. /// @throw Dhcp6ConfigError if a parameter has not been found.
  789. /// @return a value of the uint32_t parameter.
  790. uint32_t getUint32Param(const std::string& param_id) const {
  791. Uint32Storage::const_iterator param = uint32_values_.find(param_id);
  792. if (param == uint32_values_.end()) {
  793. isc_throw(isc::dhcp::Dhcp6ConfigError, "parser error: option-data parameter"
  794. << " '" << param_id << "' not specified");
  795. }
  796. return (param->second);
  797. }
  798. /// @brief Get a parameter from the boolean values storage.
  799. ///
  800. /// @param param_id parameter identifier.
  801. ///
  802. /// @throw isc::dhcp::Dhcp6ConfigError if a parameter has not been found.
  803. /// @return a value of the boolean parameter.
  804. bool getBooleanParam(const std::string& param_id) const {
  805. BooleanStorage::const_iterator param = boolean_values_.find(param_id);
  806. if (param == boolean_values_.end()) {
  807. isc_throw(isc::dhcp::Dhcp6ConfigError, "parser error: option-data parameter"
  808. << " '" << param_id << "' not specified");
  809. }
  810. return (param->second);
  811. }
  812. /// Storage for uint32 values (e.g. option code).
  813. Uint32Storage uint32_values_;
  814. /// Storage for string values (e.g. option name or data).
  815. StringStorage string_values_;
  816. /// Storage for boolean values.
  817. BooleanStorage boolean_values_;
  818. /// Pointer to options storage. This storage is provided by
  819. /// the calling class and is shared by all OptionDataParser objects.
  820. OptionStorage* options_;
  821. /// Option descriptor holds newly configured option.
  822. isc::dhcp::Subnet::OptionDescriptor option_descriptor_;
  823. };
  824. /// @brief Parser for option data values within a subnet.
  825. ///
  826. /// This parser iterates over all entries that define options
  827. /// data for a particular subnet and creates a collection of options.
  828. /// If parsing is successful, all these options are added to the Subnet
  829. /// object.
  830. class OptionDataListParser : public DhcpConfigParser {
  831. public:
  832. /// @brief Constructor.
  833. ///
  834. /// Unless otherwise specified, parsed options will be stored in
  835. /// a global option container (option_default). That storage location
  836. /// is overriden on a subnet basis.
  837. OptionDataListParser(const std::string&)
  838. : options_(&option_defaults), local_options_() { }
  839. /// @brief Parses entries that define options' data for a subnet.
  840. ///
  841. /// This method iterates over all entries that define option data
  842. /// for options within a single subnet and creates options' instances.
  843. ///
  844. /// @param option_data_list pointer to a list of options' data sets.
  845. /// @throw Dhcp6ConfigError if option parsing failed.
  846. void build(ConstElementPtr option_data_list) {
  847. BOOST_FOREACH(ConstElementPtr option_value, option_data_list->listValue()) {
  848. boost::shared_ptr<OptionDataParser> parser(new OptionDataParser("option-data"));
  849. // options_ member will hold instances of all options thus
  850. // each OptionDataParser takes it as a storage.
  851. parser->setStorage(&local_options_);
  852. // Build the instance of a single option.
  853. parser->build(option_value);
  854. // Store a parser as it will be used to commit.
  855. parsers_.push_back(parser);
  856. }
  857. }
  858. /// @brief Set storage for option instances.
  859. ///
  860. /// @param storage pointer to options storage.
  861. void setStorage(OptionStorage* storage) {
  862. options_ = storage;
  863. }
  864. /// @brief Commit all option values.
  865. ///
  866. /// This function invokes commit for all option values.
  867. void commit() {
  868. BOOST_FOREACH(ParserPtr parser, parsers_) {
  869. parser->commit();
  870. }
  871. // Parsing was successful and we have all configured
  872. // options in local storage. We can now replace old values
  873. // with new values.
  874. std::swap(local_options_, *options_);
  875. }
  876. /// @brief Create DhcpDataListParser object
  877. ///
  878. /// @param param_name param name.
  879. ///
  880. /// @return DhcpConfigParser object.
  881. static DhcpConfigParser* factory(const std::string& param_name) {
  882. return (new OptionDataListParser(param_name));
  883. }
  884. /// Intermediate option storage. This storage is used by
  885. /// lower level parsers to add new options. Values held
  886. /// in this storage are assigned to main storage (options_)
  887. /// if overall parsing was successful.
  888. OptionStorage local_options_;
  889. /// Pointer to options instances storage.
  890. OptionStorage* options_;
  891. /// Collection of parsers;
  892. ParserCollection parsers_;
  893. };
  894. /// @brief this class parses a single subnet
  895. ///
  896. /// This class parses the whole subnet definition. It creates parsers
  897. /// for received configuration parameters as needed.
  898. class Subnet6ConfigParser : public DhcpConfigParser {
  899. public:
  900. /// @brief constructor
  901. Subnet6ConfigParser(const std::string& ) {
  902. // The parameter should always be "subnet", but we don't check
  903. // against that here in case some wants to reuse this parser somewhere.
  904. }
  905. /// @brief parses parameter value
  906. ///
  907. /// @param subnet pointer to the content of subnet definition
  908. ///
  909. /// @throw isc::Dhcp6ConfigError if subnet configuration parsing failed.
  910. void build(ConstElementPtr subnet) {
  911. BOOST_FOREACH(ConfigPair param, subnet->mapValue()) {
  912. ParserPtr parser(createSubnet6ConfigParser(param.first));
  913. // The actual type of the parser is unknown here. We have to discover
  914. // the parser type here to invoke the corresponding setStorage function
  915. // on it. We discover parser type by trying to cast the parser to various
  916. // parser types and checking which one was successful. For this one
  917. // a setStorage and build methods are invoked.
  918. // Try uint32 type parser.
  919. if (!buildParser<Uint32Parser, Uint32Storage >(parser, uint32_values_,
  920. param.second) &&
  921. // Try string type parser.
  922. !buildParser<StringParser, StringStorage >(parser, string_values_,
  923. param.second) &&
  924. // Try pool parser.
  925. !buildParser<PoolParser, PoolStorage >(parser, pools_,
  926. param.second) &&
  927. // Try option data parser.
  928. !buildParser<OptionDataListParser, OptionStorage >(parser, options_,
  929. param.second)) {
  930. // Appropriate parsers are created in the createSubnet6ConfigParser
  931. // and they should be limited to those that we check here for. Thus,
  932. // if we fail to find a matching parser here it is a programming error.
  933. isc_throw(Dhcp6ConfigError, "failed to find suitable parser");
  934. }
  935. }
  936. // In order to create new subnet we need to get the data out
  937. // of the child parsers first. The only way to do it is to
  938. // invoke commit on them because it will make them write
  939. // parsed data into storages we have supplied.
  940. // Note that triggering commits on child parsers does not
  941. // affect global data because we supplied pointers to storages
  942. // local to this object. Thus, even if this method fails
  943. // later on, the configuration remains consistent.
  944. BOOST_FOREACH(ParserPtr parser, parsers_) {
  945. parser->commit();
  946. }
  947. // Create a subnet.
  948. createSubnet();
  949. }
  950. /// @brief Adds the created subnet to a server's configuration.
  951. void commit() {
  952. if (subnet_) {
  953. isc::dhcp::CfgMgr::instance().addSubnet6(subnet_);
  954. }
  955. }
  956. private:
  957. /// @brief Set storage for a parser and invoke build.
  958. ///
  959. /// This helper method casts the provided parser pointer to the specified
  960. /// type. If the cast is successful it sets the corresponding storage for
  961. /// this parser, invokes build on it and saves the parser.
  962. ///
  963. /// @tparam T parser type to which parser argument should be cast.
  964. /// @tparam Y storage type for the specified parser type.
  965. /// @param parser parser on which build must be invoked.
  966. /// @param storage reference to a storage that will be set for a parser.
  967. /// @param subnet subnet element read from the configuration and being parsed.
  968. /// @return true if parser pointer was successfully cast to specialized
  969. /// parser type provided as Y.
  970. template<typename T, typename Y>
  971. bool buildParser(const ParserPtr& parser, Y& storage, const ConstElementPtr& subnet) {
  972. // We need to cast to T in order to set storage for the parser.
  973. boost::shared_ptr<T> cast_parser = boost::dynamic_pointer_cast<T>(parser);
  974. // It is common that this cast is not successful because we try to cast to all
  975. // supported parser types as we don't know the type of a parser in advance.
  976. if (cast_parser) {
  977. // Cast, successful so we go ahead with setting storage and actual parse.
  978. cast_parser->setStorage(&storage);
  979. parser->build(subnet);
  980. parsers_.push_back(parser);
  981. // We indicate that cast was successful so as the calling function
  982. // may skip attempts to cast to other parser types and proceed to
  983. // next element.
  984. return (true);
  985. }
  986. // It was not successful. Indicate that another parser type
  987. // should be tried.
  988. return (false);
  989. }
  990. /// @brief Create a new subnet using a data from child parsers.
  991. ///
  992. /// @throw isc::dhcp::Dhcp6ConfigError if subnet configuration parsing failed.
  993. void createSubnet() {
  994. // Find a subnet string.
  995. StringStorage::const_iterator it = string_values_.find("subnet");
  996. if (it == string_values_.end()) {
  997. isc_throw(Dhcp6ConfigError,
  998. "Mandatory subnet definition in subnet missing");
  999. }
  1000. // Remove any spaces or tabs.
  1001. string subnet_txt = it->second;
  1002. boost::erase_all(subnet_txt, " ");
  1003. boost::erase_all(subnet_txt, "\t");
  1004. // The subnet format is prefix/len. We are going to extract
  1005. // the prefix portion of a subnet string to create IOAddress
  1006. // object from it. IOAddress will be passed to the Subnet's
  1007. // constructor later on. In order to extract the prefix we
  1008. // need to get all characters preceding "/".
  1009. size_t pos = subnet_txt.find("/");
  1010. if (pos == string::npos) {
  1011. isc_throw(Dhcp6ConfigError,
  1012. "Invalid subnet syntax (prefix/len expected):" << it->second);
  1013. }
  1014. // Try to create the address object. It also validates that
  1015. // the address syntax is ok.
  1016. IOAddress addr(subnet_txt.substr(0, pos));
  1017. uint8_t len = boost::lexical_cast<unsigned int>(subnet_txt.substr(pos + 1));
  1018. // Get all 'time' parameters using inheritance.
  1019. // If the subnet-specific value is defined then use it, else
  1020. // use the global value. The global value must always be
  1021. // present. If it is not, it is an internal error and exception
  1022. // is thrown.
  1023. Triplet<uint32_t> t1 = getParam("renew-timer");
  1024. Triplet<uint32_t> t2 = getParam("rebind-timer");
  1025. Triplet<uint32_t> pref = getParam("preferred-lifetime");
  1026. Triplet<uint32_t> valid = getParam("valid-lifetime");
  1027. /// @todo: Convert this to logger once the parser is working reliably
  1028. stringstream tmp;
  1029. tmp << addr.toText() << "/" << (int)len
  1030. << " with params t1=" << t1 << ", t2=" << t2 << ", pref="
  1031. << pref << ", valid=" << valid;
  1032. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_NEW_SUBNET).arg(tmp.str());
  1033. // Create a new subnet.
  1034. subnet_.reset(new Subnet6(addr, len, t1, t2, pref, valid));
  1035. // Add pools to it.
  1036. for (PoolStorage::iterator it = pools_.begin(); it != pools_.end(); ++it) {
  1037. subnet_->addPool(*it);
  1038. }
  1039. Subnet::OptionContainerPtr options = subnet_->getOptionDescriptors("dhcp6");
  1040. const Subnet::OptionContainerTypeIndex& idx = options->get<1>();
  1041. // Add subnet specific options.
  1042. BOOST_FOREACH(Subnet::OptionDescriptor desc, options_) {
  1043. Subnet::OptionContainerTypeRange range = idx.equal_range(desc.option->getType());
  1044. if (std::distance(range.first, range.second) > 0) {
  1045. LOG_WARN(dhcp6_logger, DHCP6_CONFIG_OPTION_DUPLICATE)
  1046. .arg(desc.option->getType()).arg(addr.toText());
  1047. }
  1048. subnet_->addOption(desc.option, false, "dhcp6");
  1049. }
  1050. // Check all global options and add them to the subnet object if
  1051. // they have been configured in the global scope. If they have been
  1052. // configured in the subnet scope we don't add global option because
  1053. // the one configured in the subnet scope always takes precedence.
  1054. BOOST_FOREACH(Subnet::OptionDescriptor desc, option_defaults) {
  1055. // Get all options specified locally in the subnet and having
  1056. // code equal to global option's code.
  1057. Subnet::OptionContainerPtr options = subnet_->getOptionDescriptors("dhcp6");
  1058. const Subnet::OptionContainerTypeIndex& idx = options->get<1>();
  1059. Subnet::OptionContainerTypeRange range = idx.equal_range(desc.option->getType());
  1060. // @todo: In the future we will be searching for options using either
  1061. // an option code or namespace. Currently we have only the option
  1062. // code available so if there is at least one option found with the
  1063. // specific code we don't add the globally configured option.
  1064. // @todo with this code the first globally configured option
  1065. // with the given code will be added to a subnet. We may
  1066. // want to issue a warning about dropping the configuration of
  1067. // a global option if one already exsists.
  1068. if (std::distance(range.first, range.second) == 0) {
  1069. subnet_->addOption(desc.option, false, "dhcp6");
  1070. }
  1071. }
  1072. }
  1073. /// @brief creates parsers for entries in subnet definition
  1074. ///
  1075. /// @param config_id name od the entry
  1076. ///
  1077. /// @return parser object for specified entry name
  1078. /// @throw isc::dhcp::Dhcp6ConfigError if trying to create a parser
  1079. /// for unknown config element
  1080. DhcpConfigParser* createSubnet6ConfigParser(const std::string& config_id) {
  1081. FactoryMap factories;
  1082. factories["preferred-lifetime"] = Uint32Parser::factory;
  1083. factories["valid-lifetime"] = Uint32Parser::factory;
  1084. factories["renew-timer"] = Uint32Parser::factory;
  1085. factories["rebind-timer"] = Uint32Parser::factory;
  1086. factories["subnet"] = StringParser::factory;
  1087. factories["pool"] = PoolParser::factory;
  1088. factories["option-data"] = OptionDataListParser::factory;
  1089. FactoryMap::iterator f = factories.find(config_id);
  1090. if (f == factories.end()) {
  1091. // Used for debugging only.
  1092. // return new DebugParser(config_id);
  1093. isc_throw(isc::dhcp::Dhcp6ConfigError,
  1094. "parser error: subnet6 parameter not supported: "
  1095. << config_id);
  1096. }
  1097. return (f->second(config_id));
  1098. }
  1099. /// @brief Returns value for a given parameter (after using inheritance)
  1100. ///
  1101. /// This method implements inheritance. For a given parameter name, it first
  1102. /// checks if there is a global value for it and overwrites it with specific
  1103. /// value if such value was defined in subnet.
  1104. ///
  1105. /// @param name name of the parameter
  1106. /// @return triplet with the parameter name
  1107. /// @throw Dhcp6ConfigError when requested parameter is not present
  1108. isc::dhcp::Triplet<uint32_t> getParam(const std::string& name) {
  1109. uint32_t value = 0;
  1110. bool found = false;
  1111. Uint32Storage::iterator global = uint32_defaults.find(name);
  1112. if (global != uint32_defaults.end()) {
  1113. value = global->second;
  1114. found = true;
  1115. }
  1116. Uint32Storage::iterator local = uint32_values_.find(name);
  1117. if (local != uint32_values_.end()) {
  1118. value = local->second;
  1119. found = true;
  1120. }
  1121. if (found) {
  1122. return (isc::dhcp::Triplet<uint32_t>(value));
  1123. } else {
  1124. isc_throw(isc::dhcp::Dhcp6ConfigError, "Mandatory parameter " << name
  1125. << " missing (no global default and no subnet-"
  1126. << "specific value)");
  1127. }
  1128. }
  1129. /// storage for subnet-specific uint32 values
  1130. Uint32Storage uint32_values_;
  1131. /// storage for subnet-specific integer values
  1132. StringStorage string_values_;
  1133. /// storage for pools belonging to this subnet
  1134. PoolStorage pools_;
  1135. /// storage for options belonging to this subnet
  1136. OptionStorage options_;
  1137. /// parsers are stored here
  1138. ParserCollection parsers_;
  1139. /// Pointer to the created subnet object.
  1140. isc::dhcp::Subnet6Ptr subnet_;
  1141. };
  1142. /// @brief this class parses a list of subnets
  1143. ///
  1144. /// This is a wrapper parser that handles the whole list of Subnet6
  1145. /// definitions. It iterates over all entries and creates Subnet6ConfigParser
  1146. /// for each entry.
  1147. class Subnets6ListConfigParser : public DhcpConfigParser {
  1148. public:
  1149. /// @brief constructor
  1150. ///
  1151. Subnets6ListConfigParser(const std::string&) {
  1152. /// parameter name is ignored
  1153. }
  1154. /// @brief parses contents of the list
  1155. ///
  1156. /// Iterates over all entries on the list and creates a Subnet6ConfigParser
  1157. /// for each entry.
  1158. ///
  1159. /// @param subnets_list pointer to a list of IPv6 subnets
  1160. void build(ConstElementPtr subnets_list) {
  1161. // No need to define FactoryMap here. There's only one type
  1162. // used: Subnet6ConfigParser
  1163. BOOST_FOREACH(ConstElementPtr subnet, subnets_list->listValue()) {
  1164. ParserPtr parser(new Subnet6ConfigParser("subnet"));
  1165. parser->build(subnet);
  1166. subnets_.push_back(parser);
  1167. }
  1168. }
  1169. /// @brief commits subnets definitions.
  1170. ///
  1171. /// Iterates over all Subnet6 parsers. Each parser contains definitions
  1172. /// of a single subnet and its parameters and commits each subnet separately.
  1173. void commit() {
  1174. // @todo: Implement more subtle reconfiguration than toss
  1175. // the old one and replace with the new one.
  1176. // remove old subnets
  1177. isc::dhcp::CfgMgr::instance().deleteSubnets6();
  1178. BOOST_FOREACH(ParserPtr subnet, subnets_) {
  1179. subnet->commit();
  1180. }
  1181. }
  1182. /// @brief Returns Subnet6ListConfigParser object
  1183. /// @param param_name name of the parameter
  1184. /// @return Subnets6ListConfigParser object
  1185. static DhcpConfigParser* factory(const std::string& param_name) {
  1186. return (new Subnets6ListConfigParser(param_name));
  1187. }
  1188. /// @brief collection of subnet parsers.
  1189. ParserCollection subnets_;
  1190. };
  1191. } // anonymous namespace
  1192. namespace isc {
  1193. namespace dhcp {
  1194. /// @brief creates global parsers
  1195. ///
  1196. /// This method creates global parsers that parse global parameters, i.e.
  1197. /// those that take format of Dhcp6/param1, Dhcp6/param2 and so forth.
  1198. ///
  1199. /// @param config_id pointer to received global configuration entry
  1200. /// @return parser for specified global DHCPv6 parameter
  1201. /// @throw NotImplemented if trying to create a parser for unknown config element
  1202. DhcpConfigParser* createGlobalDhcpConfigParser(const std::string& config_id) {
  1203. FactoryMap factories;
  1204. factories["preferred-lifetime"] = Uint32Parser::factory;
  1205. factories["valid-lifetime"] = Uint32Parser::factory;
  1206. factories["renew-timer"] = Uint32Parser::factory;
  1207. factories["rebind-timer"] = Uint32Parser::factory;
  1208. factories["interface"] = InterfaceListConfigParser::factory;
  1209. factories["subnet6"] = Subnets6ListConfigParser::factory;
  1210. factories["option-data"] = OptionDataListParser::factory;
  1211. factories["version"] = StringParser::factory;
  1212. FactoryMap::iterator f = factories.find(config_id);
  1213. if (f == factories.end()) {
  1214. // Used for debugging only.
  1215. // return new DebugParser(config_id);
  1216. isc_throw(NotImplemented,
  1217. "Parser error: Global configuration parameter not supported: "
  1218. << config_id);
  1219. }
  1220. return (f->second(config_id));
  1221. }
  1222. ConstElementPtr
  1223. configureDhcp6Server(Dhcpv6Srv& , ConstElementPtr config_set) {
  1224. if (!config_set) {
  1225. ConstElementPtr answer = isc::config::createAnswer(1,
  1226. string("Can't parse NULL config"));
  1227. return (answer);
  1228. }
  1229. /// @todo: append most essential info here (like "2 new subnets configured")
  1230. string config_details;
  1231. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_START).arg(config_set->str());
  1232. // Some of the values specified in the configuration depend on
  1233. // other values. Typically, the values in the subnet6 structure
  1234. // depend on the global values. Thus we need to make sure that
  1235. // the global values are processed first and that they can be
  1236. // accessed by the subnet6 parsers. We separate parsers that
  1237. // should process data first (independent_parsers) from those
  1238. // that must process data when the independent data is already
  1239. // processed (dependent_parsers).
  1240. ParserCollection independent_parsers;
  1241. ParserCollection dependent_parsers;
  1242. // The subnet parsers implement data inheritance by directly
  1243. // accessing global storages. For this reason the global data
  1244. // parsers must store the parsed data into global storages
  1245. // immediately. This may cause data inconsistency if the
  1246. // parsing operation fails after the global storage has been
  1247. // modified. We need to preserve the original global data here
  1248. // so as we can rollback changes when an error occurs.
  1249. Uint32Storage uint32_local(uint32_defaults);
  1250. StringStorage string_local(string_defaults);
  1251. OptionStorage option_local(option_defaults);
  1252. // answer will hold the result.
  1253. ConstElementPtr answer;
  1254. // rollback informs whether error occured and original data
  1255. // have to be restored to global storages.
  1256. bool rollback = false;
  1257. try {
  1258. // Iterate over all independent parsers first (all but subnet6)
  1259. // and try to parse the data.
  1260. BOOST_FOREACH(ConfigPair config_pair, config_set->mapValue()) {
  1261. if (config_pair.first != "subnet6") {
  1262. ParserPtr parser(createGlobalDhcpConfigParser(config_pair.first));
  1263. independent_parsers.push_back(parser);
  1264. parser->build(config_pair.second);
  1265. // The commit operation here may modify the global storage
  1266. // but we need it so as the subnet6 parser can access the
  1267. // parsed data.
  1268. parser->commit();
  1269. }
  1270. }
  1271. // Process dependent configuration data.
  1272. BOOST_FOREACH(ConfigPair config_pair, config_set->mapValue()) {
  1273. if (config_pair.first == "subnet6") {
  1274. ParserPtr parser(createGlobalDhcpConfigParser(config_pair.first));
  1275. dependent_parsers.push_back(parser);
  1276. parser->build(config_pair.second);
  1277. }
  1278. }
  1279. } catch (const isc::Exception& ex) {
  1280. answer =
  1281. isc::config::createAnswer(1, string("Configuration parsing failed: ") + ex.what());
  1282. // An error occured, so make sure that we restore original data.
  1283. rollback = true;
  1284. } catch (...) {
  1285. // for things like bad_cast in boost::lexical_cast
  1286. answer =
  1287. isc::config::createAnswer(1, string("Configuration parsing failed"));
  1288. // An error occured, so make sure that we restore original data.
  1289. rollback = true;
  1290. }
  1291. // So far so good, there was no parsing error so let's commit the
  1292. // configuration. This will add created subnets and option values into
  1293. // the server's configuration.
  1294. // This operation should be exception safe but let's make sure.
  1295. if (!rollback) {
  1296. try {
  1297. BOOST_FOREACH(ParserPtr parser, dependent_parsers) {
  1298. parser->commit();
  1299. }
  1300. }
  1301. catch (const isc::Exception& ex) {
  1302. answer =
  1303. isc::config::createAnswer(2, string("Configuration commit failed:")
  1304. + ex.what());
  1305. // An error occured, so make sure to restore the original data.
  1306. rollback = true;
  1307. } catch (...) {
  1308. // for things like bad_cast in boost::lexical_cast
  1309. answer =
  1310. isc::config::createAnswer(2, string("Configuration commit failed"));
  1311. // An error occured, so make sure to restore the original data.
  1312. rollback = true;
  1313. }
  1314. }
  1315. // Rollback changes as the configuration parsing failed.
  1316. if (rollback) {
  1317. std::swap(uint32_defaults, uint32_local);
  1318. std::swap(string_defaults, string_local);
  1319. std::swap(option_defaults, option_local);
  1320. return (answer);
  1321. }
  1322. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_COMPLETE).arg(config_details);
  1323. // Everything was fine. Configuration is successful.
  1324. answer = isc::config::createAnswer(0, "Configuration commited.");
  1325. return (answer);
  1326. }
  1327. }; // end of isc::dhcp namespace
  1328. }; // end of isc namespace