config_parser.cc 60 KB

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