config_parser.cc 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  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 <dhcp/iface_mgr.h>
  21. #include <dhcpsrv/cfgmgr.h>
  22. #include <dhcpsrv/dbaccess_parser.h>
  23. #include <dhcpsrv/dhcp_config_parser.h>
  24. #include <dhcpsrv/pool.h>
  25. #include <dhcpsrv/subnet.h>
  26. #include <dhcpsrv/triplet.h>
  27. #include <log/logger_support.h>
  28. #include <util/encode/hex.h>
  29. #include <util/strutil.h>
  30. #include <boost/algorithm/string.hpp>
  31. #include <boost/foreach.hpp>
  32. #include <boost/lexical_cast.hpp>
  33. #include <boost/scoped_ptr.hpp>
  34. #include <boost/shared_ptr.hpp>
  35. #include <iostream>
  36. #include <map>
  37. #include <vector>
  38. #include <stdint.h>
  39. using namespace std;
  40. using namespace isc;
  41. using namespace isc::data;
  42. using namespace isc::dhcp;
  43. using namespace isc::asiolink;
  44. namespace {
  45. // Forward declarations of some of the parser classes.
  46. // They are used to define pointer types for these classes.
  47. class BooleanParser;
  48. class StringParser;
  49. class Uint32Parser;
  50. // Pointers to various parser objects.
  51. typedef boost::shared_ptr<BooleanParser> BooleanParserPtr;
  52. typedef boost::shared_ptr<StringParser> StringParserPtr;
  53. typedef boost::shared_ptr<Uint32Parser> Uint32ParserPtr;
  54. /// @brief Factory method that will create a parser for a given element name
  55. typedef isc::dhcp::DhcpConfigParser* ParserFactory(const std::string& config_id);
  56. /// @brief Collection of factories that create parsers for specified element names
  57. typedef std::map<std::string, ParserFactory*> FactoryMap;
  58. /// @brief Storage for option definitions.
  59. typedef OptionSpaceContainer<OptionDefContainer,
  60. OptionDefinitionPtr> OptionDefStorage;
  61. /// @brief Collection of address pools.
  62. ///
  63. /// This type is used as intermediate storage, when pools are parsed, but there is
  64. /// no subnet object created yet to store them.
  65. typedef std::vector<isc::dhcp::Pool6Ptr> PoolStorage;
  66. /// Collection of containers holding option spaces. Each container within
  67. /// a particular option space holds so-called option descriptors.
  68. typedef OptionSpaceContainer<Subnet::OptionContainer,
  69. Subnet::OptionDescriptor> OptionStorage;
  70. /// @brief Global uint32 parameters that will be used as defaults.
  71. Uint32Storage uint32_defaults;
  72. /// @brief global string parameters that will be used as defaults.
  73. StringStorage string_defaults;
  74. /// @brief Global storage for options that will be used as defaults.
  75. OptionStorage option_defaults;
  76. /// @brief Global storage for option definitions.
  77. OptionDefStorage option_def_intermediate;
  78. /// @brief a dummy configuration parser
  79. ///
  80. /// This is a debugging parser. It does not configure anything,
  81. /// will accept any configuration and will just print it out
  82. /// on commit. Useful for debugging existing configurations and
  83. /// adding new ones.
  84. class DebugParser : public DhcpConfigParser {
  85. public:
  86. /// @brief Constructor
  87. ///
  88. /// See @ref DhcpConfigParser class for details.
  89. ///
  90. /// @param param_name name of the parsed parameter
  91. DebugParser(const std::string& param_name)
  92. :param_name_(param_name) {
  93. }
  94. /// @brief builds parameter value
  95. ///
  96. /// See @ref DhcpConfigParser class for details.
  97. ///
  98. /// @param new_config pointer to the new configuration
  99. virtual void build(ConstElementPtr new_config) {
  100. std::cout << "Build for token: [" << param_name_ << "] = ["
  101. << value_->str() << "]" << std::endl;
  102. value_ = new_config;
  103. }
  104. /// @brief Pretends to apply the configuration.
  105. ///
  106. /// This is a method required by the base class. It pretends to apply the
  107. /// configuration, but in fact it only prints the parameter out.
  108. ///
  109. /// See @ref DhcpConfigParser class for details.
  110. virtual void commit() {
  111. // Debug message. The whole DebugParser class is used only for parser
  112. // debugging, and is not used in production code. It is very convenient
  113. // to keep it around. Please do not turn this cout into logger calls.
  114. std::cout << "Commit for token: [" << param_name_ << "] = ["
  115. << value_->str() << "]" << std::endl;
  116. }
  117. /// @brief factory that constructs DebugParser objects
  118. ///
  119. /// @param param_name name of the parameter to be parsed
  120. static DhcpConfigParser* factory(const std::string& param_name) {
  121. return (new DebugParser(param_name));
  122. }
  123. private:
  124. /// name of the parsed parameter
  125. std::string param_name_;
  126. /// pointer to the actual value of the parameter
  127. ConstElementPtr value_;
  128. };
  129. /// @brief A boolean value parser.
  130. ///
  131. /// This parser handles configuration values of the boolean type.
  132. /// Parsed values are stored in a provided storage. If no storage
  133. /// is provided then the build function throws an exception.
  134. class BooleanParser : public DhcpConfigParser {
  135. public:
  136. /// @brief Constructor.
  137. ///
  138. /// @param param_name name of the parameter.
  139. BooleanParser(const std::string& param_name)
  140. : storage_(NULL),
  141. param_name_(param_name),
  142. value_(false) {
  143. // Empty parameter name is invalid.
  144. if (param_name_.empty()) {
  145. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  146. << "empty parameter name provided");
  147. }
  148. }
  149. /// @brief Parse a boolean value.
  150. ///
  151. /// @param value a value to be parsed.
  152. ///
  153. /// @throw isc::InvalidOperation if a storage has not been set
  154. /// prior to calling this function
  155. /// @throw isc::dhcp::DhcpConfigError if a provided parameter's
  156. /// name is empty.
  157. virtual void build(ConstElementPtr value) {
  158. if (storage_ == NULL) {
  159. isc_throw(isc::InvalidOperation, "parser logic error:"
  160. << " storage for the " << param_name_
  161. << " value has not been set");
  162. } else if (param_name_.empty()) {
  163. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  164. << "empty parameter name provided");
  165. }
  166. // The Config Manager checks if user specified a
  167. // valid value for a boolean parameter: True or False.
  168. // It is then ok to assume that if str() does not return
  169. // 'true' the value is 'false'.
  170. value_ = (value->str() == "true") ? true : false;
  171. }
  172. /// @brief Put a parsed value to the storage.
  173. virtual void commit() {
  174. if (storage_ != NULL && !param_name_.empty()) {
  175. storage_->setParam(param_name_, value_);
  176. }
  177. }
  178. /// @brief Create an instance of the boolean parser.
  179. ///
  180. /// @param param_name name of the parameter for which the
  181. /// parser is created.
  182. static DhcpConfigParser* factory(const std::string& param_name) {
  183. return (new BooleanParser(param_name));
  184. }
  185. /// @brief Set the storage for parsed value.
  186. ///
  187. /// This function must be called prior to calling build.
  188. ///
  189. /// @param storage a pointer to the storage where parsed data
  190. /// is to be stored.
  191. void setStorage(BooleanStorage* storage) {
  192. storage_ = storage;
  193. }
  194. private:
  195. /// Pointer to the storage where parsed value is stored.
  196. BooleanStorage* storage_;
  197. /// Name of the parameter which value is parsed with this parser.
  198. std::string param_name_;
  199. /// Parsed value.
  200. bool value_;
  201. };
  202. /// @brief Configuration parser for uint32 parameters
  203. ///
  204. /// This class is a generic parser that is able to handle any uint32 integer
  205. /// type. By default it stores the value in external global container
  206. /// (uint32_defaults). If used in smaller scopes (e.g. to parse parameters
  207. /// in subnet config), it can be pointed to a different storage, using
  208. /// setStorage() method. This class follows the parser interface, laid out
  209. /// in its base class, @ref DhcpConfigParser.
  210. ///
  211. /// For overview of usability of this generic purpose parser, see
  212. /// @ref dhcpv6ConfigInherit page.
  213. ///
  214. /// @todo this class should be turned into the template class which
  215. /// will handle all uintX_types of data (see ticket #2415).
  216. class Uint32Parser : public DhcpConfigParser {
  217. public:
  218. /// @brief constructor for Uint32Parser
  219. ///
  220. /// @param param_name name of the configuration parameter being parsed
  221. Uint32Parser(const std::string& param_name)
  222. : storage_(&uint32_defaults),
  223. param_name_(param_name) {
  224. // Empty parameter name is invalid.
  225. if (param_name_.empty()) {
  226. isc_throw(DhcpConfigError, "parser logic error:"
  227. << "empty parameter name provided");
  228. }
  229. }
  230. /// @brief Parses configuration configuration parameter as uint32_t.
  231. ///
  232. /// @param value pointer to the content of parsed values
  233. /// @throw isc::dhcp::DhcpConfigError if failed to parse
  234. /// the configuration parameter as uint32_t value.
  235. virtual void build(ConstElementPtr value) {
  236. if (param_name_.empty()) {
  237. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  238. << "empty parameter name provided");
  239. }
  240. bool parse_error = false;
  241. // Cast the provided value to int64 value to check.
  242. int64_t int64value = 0;
  243. try {
  244. // Parsing the value as a int64 value allows to
  245. // check if the provided value is within the range
  246. // of uint32_t (is not negative or greater than
  247. // maximal uint32_t value).
  248. int64value = boost::lexical_cast<int64_t>(value->str());
  249. } catch (const boost::bad_lexical_cast&) {
  250. parse_error = true;
  251. }
  252. if (!parse_error) {
  253. // Check that the value is not out of bounds.
  254. if ((int64value < 0) ||
  255. (int64value > std::numeric_limits<uint32_t>::max())) {
  256. parse_error = true;
  257. } else {
  258. // A value is not out of bounds so let's cast it to
  259. // the uint32_t type.
  260. value_ = static_cast<uint32_t>(int64value);
  261. }
  262. }
  263. // Invalid value provided.
  264. if (parse_error) {
  265. isc_throw(isc::dhcp::DhcpConfigError, "Failed to parse value " << value->str()
  266. << " as unsigned 32-bit integer.");
  267. }
  268. }
  269. /// @brief Stores the parsed uint32_t value in a storage.
  270. virtual void commit() {
  271. if (storage_ != NULL) {
  272. // If a given parameter already exists in the storage we override
  273. // its value. If it doesn't we insert a new element.
  274. storage_->setParam(param_name_, value_);
  275. }
  276. }
  277. /// @brief Factory that constructs Uint32Parser objects.
  278. ///
  279. /// @param param_name name of the parameter to be parsed.
  280. static DhcpConfigParser* factory(const std::string& param_name) {
  281. return (new Uint32Parser(param_name));
  282. }
  283. /// @brief Sets storage for value of this parameter.
  284. ///
  285. /// See @ref dhcpv6ConfigInherit for details.
  286. ///
  287. /// @param storage pointer to the storage container.
  288. void setStorage(Uint32Storage* storage) {
  289. storage_ = storage;
  290. }
  291. private:
  292. /// pointer to the storage, where parsed value will be stored
  293. Uint32Storage* storage_;
  294. /// name of the parameter to be parsed
  295. std::string param_name_;
  296. /// the actual parsed value
  297. uint32_t value_;
  298. };
  299. /// @brief Configuration parser for string parameters
  300. ///
  301. /// This class is a generic parser that is able to handle any string
  302. /// parameter. By default it stores the value in an external global container
  303. /// (string_defaults). If used in smaller scopes (e.g. to parse parameters
  304. /// in subnet config), it can be pointed to a different storage, using the
  305. /// setStorage() method. This class follows the parser interface, laid out
  306. /// in its base class, @ref DhcpConfigParser.
  307. ///
  308. /// For overview of usability of this generic purpose parser, see
  309. /// @ref dhcpv6ConfigInherit page.
  310. class StringParser : public DhcpConfigParser {
  311. public:
  312. /// @brief constructor for StringParser
  313. ///
  314. /// @param param_name name of the configuration parameter being parsed
  315. StringParser(const std::string& param_name)
  316. : storage_(&string_defaults),
  317. param_name_(param_name) {
  318. // Empty parameter name is invalid.
  319. if (param_name_.empty()) {
  320. isc_throw(DhcpConfigError, "parser logic error:"
  321. << "empty parameter name provided");
  322. }
  323. }
  324. /// @brief parses parameter value
  325. ///
  326. /// Parses configuration parameter's value as string.
  327. ///
  328. /// @param value pointer to the content of parsed values
  329. /// @throws DhcpConfigError if the parsed parameter's name is empty.
  330. virtual void build(ConstElementPtr value) {
  331. if (param_name_.empty()) {
  332. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  333. << "empty parameter name provided");
  334. }
  335. value_ = value->str();
  336. boost::erase_all(value_, "\"");
  337. }
  338. /// @brief Stores the parsed value in a storage.
  339. virtual void commit() {
  340. if (storage_ != NULL && !param_name_.empty()) {
  341. // If a given parameter already exists in the storage we override
  342. // its value. If it doesn't we insert a new element.
  343. storage_->setParam(param_name_, value_);
  344. }
  345. }
  346. /// @brief Factory that constructs StringParser objects
  347. ///
  348. /// @param param_name name of the parameter to be parsed
  349. static DhcpConfigParser* factory(const std::string& param_name) {
  350. return (new StringParser(param_name));
  351. }
  352. /// @brief Sets storage for value of this parameter.
  353. ///
  354. /// See @ref dhcpv6ConfigInherit for details.
  355. ///
  356. /// @param storage pointer to the storage container
  357. void setStorage(StringStorage* storage) {
  358. storage_ = storage;
  359. }
  360. private:
  361. /// Pointer to the storage, where parsed value will be stored
  362. StringStorage* storage_;
  363. /// Name of the parameter to be parsed
  364. std::string param_name_;
  365. /// The actual parsed value
  366. std::string value_;
  367. };
  368. /// @brief parser for interface list definition
  369. ///
  370. /// This parser handles Dhcp6/interface entry.
  371. /// It contains a list of network interfaces that the server listens on.
  372. /// In particular, it can contain an entry called "all" or "any" that
  373. /// designates all interfaces.
  374. ///
  375. /// It is useful for parsing Dhcp6/interface parameter.
  376. class InterfaceListConfigParser : public DhcpConfigParser {
  377. public:
  378. /// @brief constructor
  379. ///
  380. /// As this is a dedicated parser, it must be used to parse
  381. /// "interface" parameter only. All other types will throw exception.
  382. ///
  383. /// @param param_name name of the configuration parameter being parsed
  384. /// @throw BadValue if supplied parameter name is not "interface"
  385. InterfaceListConfigParser(const std::string& param_name) {
  386. if (param_name != "interface") {
  387. isc_throw(isc::BadValue, "Internal error. Interface configuration "
  388. "parser called for the wrong parameter: " << param_name);
  389. }
  390. }
  391. /// @brief parses parameters value
  392. ///
  393. /// Parses configuration entry (list of parameters) and stores it in
  394. /// storage.
  395. ///
  396. /// @param value pointer to the content of parsed values
  397. virtual void build(ConstElementPtr value) {
  398. BOOST_FOREACH(ConstElementPtr iface, value->listValue()) {
  399. interfaces_.push_back(iface->str());
  400. }
  401. }
  402. /// @brief commits interfaces list configuration
  403. virtual void commit() {
  404. /// @todo: Implement per interface listening. Currently always listening
  405. /// on all interfaces.
  406. }
  407. /// @brief factory that constructs InterfaceListConfigParser objects
  408. ///
  409. /// @param param_name name of the parameter to be parsed
  410. static DhcpConfigParser* factory(const std::string& param_name) {
  411. return (new InterfaceListConfigParser(param_name));
  412. }
  413. private:
  414. /// contains list of network interfaces
  415. vector<string> interfaces_;
  416. };
  417. /// @brief parser for pool definition
  418. ///
  419. /// This parser handles pool definitions, i.e. a list of entries of one
  420. /// of two syntaxes: min-max and prefix/len. Pool6 objects are created
  421. /// and stored in chosen PoolStorage container.
  422. ///
  423. /// As there are no default values for pool, setStorage() must be called
  424. /// before build(). Otherwise an exception will be thrown.
  425. ///
  426. /// It is useful for parsing Dhcp6/subnet6[X]/pool parameters.
  427. class PoolParser : public DhcpConfigParser {
  428. public:
  429. /// @brief constructor.
  430. PoolParser(const std::string& /*param_name*/)
  431. : pools_(NULL) {
  432. // ignore parameter name, it is always Dhcp6/subnet6[X]/pool
  433. }
  434. /// @brief parses the actual list
  435. ///
  436. /// This method parses the actual list of interfaces.
  437. /// No validation is done at this stage, everything is interpreted as
  438. /// interface name.
  439. /// @param pools_list list of pools defined for a subnet
  440. /// @throw isc::InvalidOperation if storage was not specified
  441. /// (setStorage() not called)
  442. void build(ConstElementPtr pools_list) {
  443. // setStorage() should have been called before build
  444. if (!pools_) {
  445. isc_throw(isc::InvalidOperation, "parser logic error: no pool storage set,"
  446. " but pool parser asked to parse pools");
  447. }
  448. BOOST_FOREACH(ConstElementPtr text_pool, pools_list->listValue()) {
  449. // That should be a single pool representation. It should contain
  450. // text in the form prefix/len or first - last. Note that spaces
  451. // are allowed
  452. string txt = text_pool->stringValue();
  453. // first let's remove any whitespaces
  454. boost::erase_all(txt, " "); // space
  455. boost::erase_all(txt, "\t"); // tabulation
  456. // Is this prefix/len notation?
  457. size_t pos = txt.find("/");
  458. if (pos != string::npos) {
  459. IOAddress addr("::");
  460. uint8_t len = 0;
  461. try {
  462. addr = IOAddress(txt.substr(0, pos));
  463. // start with the first character after /
  464. string prefix_len = txt.substr(pos + 1);
  465. // It is lexically cast to int and then downcast to uint8_t.
  466. // Direct cast to uint8_t (which is really an unsigned char)
  467. // will result in interpreting the first digit as output
  468. // value and throwing exception if length is written on two
  469. // digits (because there are extra characters left over).
  470. // No checks for values over 128. Range correctness will
  471. // be checked in Pool6 constructor.
  472. len = boost::lexical_cast<int>(prefix_len);
  473. } catch (...) {
  474. isc_throw(DhcpConfigError, "failed to parse pool "
  475. "definition: " << text_pool->stringValue());
  476. }
  477. Pool6Ptr pool(new Pool6(Pool6::TYPE_IA, addr, len));
  478. local_pools_.push_back(pool);
  479. continue;
  480. }
  481. // Is this min-max notation?
  482. pos = txt.find("-");
  483. if (pos != string::npos) {
  484. // using min-max notation
  485. IOAddress min(txt.substr(0, pos));
  486. IOAddress max(txt.substr(pos + 1));
  487. Pool6Ptr pool(new Pool6(Pool6::TYPE_IA, min, max));
  488. local_pools_.push_back(pool);
  489. continue;
  490. }
  491. isc_throw(DhcpConfigError, "failed to parse pool definition:"
  492. << text_pool->stringValue() <<
  493. ". Does not contain - (for min-max) nor / (prefix/len)");
  494. }
  495. }
  496. /// @brief sets storage for value of this parameter
  497. ///
  498. /// See @ref dhcpv6ConfigInherit for details.
  499. ///
  500. /// @param storage pointer to the storage container
  501. void setStorage(PoolStorage* storage) {
  502. pools_ = storage;
  503. }
  504. /// @brief Stores the parsed values in a storage provided
  505. /// by an upper level parser.
  506. virtual void commit() {
  507. if (pools_) {
  508. // local_pools_ holds the values produced by the build function.
  509. // At this point parsing should have completed successfuly so
  510. // we can append new data to the supplied storage.
  511. pools_->insert(pools_->end(), local_pools_.begin(),
  512. local_pools_.end());
  513. }
  514. }
  515. /// @brief factory that constructs PoolParser objects
  516. ///
  517. /// @param param_name name of the parameter to be parsed
  518. static DhcpConfigParser* factory(const std::string& param_name) {
  519. return (new PoolParser(param_name));
  520. }
  521. private:
  522. /// @brief pointer to the actual Pools storage
  523. ///
  524. /// This is typically a storage somewhere in Subnet parser
  525. /// (an upper level parser).
  526. PoolStorage* pools_;
  527. /// A temporary storage for pools configuration. It is a
  528. /// storage where pools are stored by build function.
  529. PoolStorage local_pools_;
  530. };
  531. /// @brief Parser for option data value.
  532. ///
  533. /// This parser parses configuration entries that specify value of
  534. /// a single option. These entries include option name, option code
  535. /// and data carried by the option. The option data can be specified
  536. /// in one of the two available formats: binary value represented as
  537. /// a string of hexadecimal digits or a list of comma separated values.
  538. /// The format being used is controlled by csv-format configuration
  539. /// parameter. When setting this value to True, the latter format is
  540. /// used. The subsequent values in the CSV format apply to relevant
  541. /// option data fields in the configured option. For example the
  542. /// configuration: "data" : "192.168.2.0, 56, hello world" can be
  543. /// used to set values for the option comprising IPv4 address,
  544. /// integer and string data field. Note that order matters. If the
  545. /// order of values does not match the order of data fields within
  546. /// an option the configuration will not be accepted. If parsing
  547. /// is successful then an instance of an option is created and
  548. /// added to the storage provided by the calling class.
  549. class OptionDataParser : public DhcpConfigParser {
  550. public:
  551. /// @brief Constructor.
  552. ///
  553. /// Class constructor.
  554. OptionDataParser(const std::string&)
  555. : options_(NULL),
  556. // initialize option to NULL ptr
  557. option_descriptor_(false) { }
  558. /// @brief Parses the single option data.
  559. ///
  560. /// This method parses the data of a single option from the configuration.
  561. /// The option data includes option name, option code and data being
  562. /// carried by this option. Eventually it creates the instance of the
  563. /// option.
  564. ///
  565. /// @warning setStorage must be called with valid storage pointer prior
  566. /// to calling this method.
  567. ///
  568. /// @param option_data_entries collection of entries that define value
  569. /// for a particular option.
  570. /// @throw DhcpConfigError if invalid parameter specified in
  571. /// the configuration.
  572. /// @throw isc::InvalidOperation if failed to set storage prior to
  573. /// calling build.
  574. virtual void build(ConstElementPtr option_data_entries) {
  575. if (options_ == NULL) {
  576. isc_throw(isc::InvalidOperation, "Parser logic error: storage must be set before "
  577. "parsing option data.");
  578. }
  579. BOOST_FOREACH(ConfigPair param, option_data_entries->mapValue()) {
  580. ParserPtr parser;
  581. if (param.first == "name" || param.first == "data" ||
  582. param.first == "space") {
  583. boost::shared_ptr<StringParser>
  584. name_parser(dynamic_cast<StringParser*>(StringParser::factory(param.first)));
  585. if (name_parser) {
  586. name_parser->setStorage(&string_values_);
  587. parser = name_parser;
  588. }
  589. } else if (param.first == "code") {
  590. boost::shared_ptr<Uint32Parser>
  591. code_parser(dynamic_cast<Uint32Parser*>(Uint32Parser::factory(param.first)));
  592. if (code_parser) {
  593. code_parser->setStorage(&uint32_values_);
  594. parser = code_parser;
  595. }
  596. } else if (param.first == "csv-format") {
  597. boost::shared_ptr<BooleanParser>
  598. value_parser(dynamic_cast<BooleanParser*>(BooleanParser::factory(param.first)));
  599. if (value_parser) {
  600. value_parser->setStorage(&boolean_values_);
  601. parser = value_parser;
  602. }
  603. } else {
  604. isc_throw(DhcpConfigError,
  605. "parser error: option-data parameter not supported: "
  606. << param.first);
  607. }
  608. parser->build(param.second);
  609. // Before we can create an option we need to get the data from
  610. // the child parsers. The only way to do it is to invoke commit
  611. // on them so as they store the values in appropriate storages
  612. // that this class provided to them. Note that this will not
  613. // modify values stored in the global storages so the configuration
  614. // will remain consistent even parsing fails somewhere further on.
  615. parser->commit();
  616. }
  617. // Try to create the option instance.
  618. createOption();
  619. }
  620. /// @brief Commits option value.
  621. ///
  622. /// This function adds a new option to the storage or replaces an existing option
  623. /// with the same code.
  624. ///
  625. /// @throw isc::InvalidOperation if failed to set pointer to storage or failed
  626. /// to call build() prior to commit. If that happens data in the storage
  627. /// remain un-modified.
  628. virtual void commit() {
  629. if (options_ == NULL) {
  630. isc_throw(isc::InvalidOperation, "parser logic error: storage must be set before "
  631. "committing option data.");
  632. } else if (!option_descriptor_.option) {
  633. // Before we can commit the new option should be configured. If it is not
  634. // than somebody must have called commit() before build().
  635. isc_throw(isc::InvalidOperation, "parser logic error: no option has been configured and"
  636. " thus there is nothing to commit. Has build() been called?");
  637. }
  638. uint16_t opt_type = option_descriptor_.option->getType();
  639. Subnet::OptionContainerPtr options = options_->getItems(option_space_);
  640. // The getItems() should never return NULL pointer. If there are no
  641. // options configured for the particular option space a pointer
  642. // to an empty container should be returned.
  643. assert(options);
  644. Subnet::OptionContainerTypeIndex& idx = options->get<1>();
  645. // Try to find options with the particular option code in the main
  646. // storage. If found, remove these options because they will be
  647. // replaced with new one.
  648. Subnet::OptionContainerTypeRange range =
  649. idx.equal_range(opt_type);
  650. if (std::distance(range.first, range.second) > 0) {
  651. idx.erase(range.first, range.second);
  652. }
  653. // Append new option to the main storage.
  654. options_->addItem(option_descriptor_, option_space_);
  655. }
  656. /// @brief Set storage for the parser.
  657. ///
  658. /// Sets storage for the parser. This storage points to the
  659. /// vector of options and is used by multiple instances of
  660. /// OptionDataParser. Each instance creates exactly one object
  661. /// of dhcp::Option or derived type and appends it to this
  662. /// storage.
  663. ///
  664. /// @param storage pointer to the options storage
  665. void setStorage(OptionStorage* storage) {
  666. options_ = storage;
  667. }
  668. private:
  669. /// @brief Create option instance.
  670. ///
  671. /// Creates an instance of an option and adds it to the provided
  672. /// options storage. If the option data parsed by \ref build function
  673. /// are invalid or insufficient this function emits an exception.
  674. ///
  675. /// @warning this function does not check if options_ storage pointer
  676. /// is initialized but this check is not needed here because it is done
  677. /// in the \ref build function.
  678. ///
  679. /// @throw DhcpConfigError if parameters provided in the configuration
  680. /// are invalid.
  681. void createOption() {
  682. // Option code is held in the uint32_t storage but is supposed to
  683. // be uint16_t value. We need to check that value in the configuration
  684. // does not exceed range of uint16_t and is not zero.
  685. uint32_t option_code = uint32_values_.getParam("code");
  686. if (option_code == 0) {
  687. isc_throw(DhcpConfigError, "option code must not be zero."
  688. << " Option code '0' is reserved in DHCPv6.");
  689. } else if (option_code > std::numeric_limits<uint16_t>::max()) {
  690. isc_throw(DhcpConfigError, "invalid option code '" << option_code
  691. << "', it must not exceed '"
  692. << std::numeric_limits<uint16_t>::max() << "'");
  693. }
  694. // Check that the option name has been specified, is non-empty and does not
  695. // contain spaces.
  696. std::string option_name = string_values_.getParam("name");
  697. if (option_name.empty()) {
  698. isc_throw(DhcpConfigError, "name of the option with code '"
  699. << option_code << "' is empty");
  700. } else if (option_name.find(" ") != std::string::npos) {
  701. isc_throw(DhcpConfigError, "invalid option name '" << option_name
  702. << "', space character is not allowed");
  703. }
  704. std::string option_space = string_values_.getParam("space");
  705. if (!OptionSpace::validateName(option_space)) {
  706. isc_throw(DhcpConfigError, "invalid option space name '"
  707. << option_space << "' specified for option '"
  708. << option_name << "' (code '" << option_code
  709. << "')");
  710. }
  711. OptionDefinitionPtr def;
  712. if (option_space == "dhcp6" &&
  713. LibDHCP::isStandardOption(Option::V6, option_code)) {
  714. def = LibDHCP::getOptionDef(Option::V6, option_code);
  715. } else if (option_space == "dhcp4") {
  716. isc_throw(DhcpConfigError, "'dhcp4' option space name is reserved"
  717. << " for DHCPv4 server");
  718. } else {
  719. // If we are not dealing with a standard option then we
  720. // need to search for its definition among user-configured
  721. // options. They are expected to be in the global storage
  722. // already.
  723. OptionDefContainerPtr defs = option_def_intermediate.getItems(option_space);
  724. // The getItems() should never return the NULL pointer. If there are
  725. // no option definitions for the particular option space a pointer
  726. // to an empty container should be returned.
  727. assert(defs);
  728. const OptionDefContainerTypeIndex& idx = defs->get<1>();
  729. OptionDefContainerTypeRange range = idx.equal_range(option_code);
  730. if (std::distance(range.first, range.second) > 0) {
  731. def = *range.first;
  732. }
  733. if (!def) {
  734. isc_throw(DhcpConfigError, "definition for the option '"
  735. << option_space << "." << option_name
  736. << "' having code '" << option_code
  737. << "' does not exist");
  738. }
  739. }
  740. // Get option data from the configuration database ('data' field).
  741. const std::string option_data = string_values_.getParam("data");
  742. const bool csv_format = boolean_values_.getParam("csv-format");
  743. // Transform string of hexadecimal digits into binary format.
  744. std::vector<uint8_t> binary;
  745. std::vector<std::string> data_tokens;
  746. if (csv_format) {
  747. // If the option data is specified as a string of comma
  748. // separated values then we need to split this string into
  749. // individual values - each value will be used to initialize
  750. // one data field of an option.
  751. data_tokens = isc::util::str::tokens(option_data, ",");
  752. } else {
  753. // Otherwise, the option data is specified as a string of
  754. // hexadecimal digits that we have to turn into binary format.
  755. try {
  756. util::encode::decodeHex(option_data, binary);
  757. } catch (...) {
  758. isc_throw(DhcpConfigError, "Parser error: option data is not a valid"
  759. << " string of hexadecimal digits: " << option_data);
  760. }
  761. }
  762. OptionPtr option;
  763. if (!def) {
  764. if (csv_format) {
  765. isc_throw(DhcpConfigError, "the CSV option data format can be"
  766. " used to specify values for an option that has a"
  767. " definition. The option with code " << option_code
  768. << " does not have a definition.");
  769. }
  770. // @todo We have a limited set of option definitions initialized at the moment.
  771. // In the future we want to initialize option definitions for all options.
  772. // Consequently an error will be issued if an option definition does not exist
  773. // for a particular option code. For now it is ok to create generic option
  774. // if definition does not exist.
  775. OptionPtr option(new Option(Option::V6, static_cast<uint16_t>(option_code),
  776. binary));
  777. // The created option is stored in option_descriptor_ class member until the
  778. // commit stage when it is inserted into the main storage. If an option with the
  779. // same code exists in main storage already the old option is replaced.
  780. option_descriptor_.option = option;
  781. option_descriptor_.persistent = false;
  782. } else {
  783. // Option name should match the definition. The option name
  784. // may seem to be redundant but in the future we may want
  785. // to reference options and definitions using their names
  786. // and/or option codes so keeping the option name in the
  787. // definition of option value makes sense.
  788. if (def->getName() != option_name) {
  789. isc_throw(DhcpConfigError, "specified option name '"
  790. << option_name << "' does not match the "
  791. << "option definition: '" << option_space
  792. << "." << def->getName() << "'");
  793. }
  794. // Option definition has been found so let's use it to create
  795. // an instance of our option.
  796. try {
  797. OptionPtr option = csv_format ?
  798. def->optionFactory(Option::V6, option_code, data_tokens) :
  799. def->optionFactory(Option::V6, option_code, binary);
  800. Subnet::OptionDescriptor desc(option, false);
  801. option_descriptor_.option = option;
  802. option_descriptor_.persistent = false;
  803. } catch (const isc::Exception& ex) {
  804. isc_throw(DhcpConfigError, "option data does not match"
  805. << " option definition (space: " << option_space
  806. << ", code: " << option_code << "): "
  807. << ex.what());
  808. }
  809. }
  810. // All went good, so we can set the option space name.
  811. option_space_ = option_space;
  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. /// Option space name where the option belongs to.
  825. std::string option_space_;
  826. };
  827. /// @brief Parser for option data values within a subnet.
  828. ///
  829. /// This parser iterates over all entries that define options
  830. /// data for a particular subnet and creates a collection of options.
  831. /// If parsing is successful, all these options are added to the Subnet
  832. /// object.
  833. class OptionDataListParser : public DhcpConfigParser {
  834. public:
  835. /// @brief Constructor.
  836. ///
  837. /// Unless otherwise specified, parsed options will be stored in
  838. /// a global option container (option_default). That storage location
  839. /// is overriden on a subnet basis.
  840. OptionDataListParser(const std::string&)
  841. : options_(&option_defaults), local_options_() { }
  842. /// @brief Parses entries that define options' data for a subnet.
  843. ///
  844. /// This method iterates over all entries that define option data
  845. /// for options within a single subnet and creates options' instances.
  846. ///
  847. /// @param option_data_list pointer to a list of options' data sets.
  848. /// @throw DhcpConfigError if option parsing failed.
  849. void build(ConstElementPtr option_data_list) {
  850. BOOST_FOREACH(ConstElementPtr option_value, option_data_list->listValue()) {
  851. boost::shared_ptr<OptionDataParser> parser(new OptionDataParser("option-data"));
  852. // options_ member will hold instances of all options thus
  853. // each OptionDataParser takes it as a storage.
  854. parser->setStorage(&local_options_);
  855. // Build the instance of a single option.
  856. parser->build(option_value);
  857. // Store a parser as it will be used to commit.
  858. parsers_.push_back(parser);
  859. }
  860. }
  861. /// @brief Set storage for option instances.
  862. ///
  863. /// @param storage pointer to options storage.
  864. void setStorage(OptionStorage* storage) {
  865. options_ = storage;
  866. }
  867. /// @brief Commit all option values.
  868. ///
  869. /// This function invokes commit for all option values.
  870. void commit() {
  871. BOOST_FOREACH(ParserPtr parser, parsers_) {
  872. parser->commit();
  873. }
  874. // Parsing was successful and we have all configured
  875. // options in local storage. We can now replace old values
  876. // with new values.
  877. std::swap(local_options_, *options_);
  878. }
  879. /// @brief Create DhcpDataListParser object
  880. ///
  881. /// @param param_name param name.
  882. ///
  883. /// @return DhcpConfigParser object.
  884. static DhcpConfigParser* factory(const std::string& param_name) {
  885. return (new OptionDataListParser(param_name));
  886. }
  887. /// Pointer to options instances storage.
  888. OptionStorage* options_;
  889. /// Intermediate option storage. This storage is used by
  890. /// lower level parsers to add new options. Values held
  891. /// in this storage are assigned to main storage (options_)
  892. /// if overall parsing was successful.
  893. OptionStorage local_options_;
  894. /// Collection of parsers;
  895. ParserCollection parsers_;
  896. };
  897. /// @brief Parser for a single option definition.
  898. ///
  899. /// This parser creates an instance of a single option definition.
  900. class OptionDefParser: DhcpConfigParser {
  901. public:
  902. /// @brief Constructor.
  903. ///
  904. /// This constructor sets the pointer to the option definitions
  905. /// storage to NULL. It must be set to point to the actual storage
  906. /// before \ref build is called.
  907. OptionDefParser(const std::string&)
  908. : storage_(NULL) {
  909. }
  910. /// @brief Parses an entry that describes single option definition.
  911. ///
  912. /// @param option_def a configuration entry to be parsed.
  913. ///
  914. /// @throw DhcpConfigError if parsing was unsuccessful.
  915. void build(ConstElementPtr option_def) {
  916. if (storage_ == NULL) {
  917. isc_throw(DhcpConfigError, "parser logic error: storage must be set"
  918. " before parsing option definition data");
  919. }
  920. // Parse the elements that make up the option definition.
  921. BOOST_FOREACH(ConfigPair param, option_def->mapValue()) {
  922. std::string entry(param.first);
  923. ParserPtr parser;
  924. if (entry == "name" || entry == "type" || entry == "record-types" ||
  925. entry == "space" || entry == "encapsulate") {
  926. StringParserPtr
  927. str_parser(dynamic_cast<StringParser*>(StringParser::factory(entry)));
  928. if (str_parser) {
  929. str_parser->setStorage(&string_values_);
  930. parser = str_parser;
  931. }
  932. } else if (entry == "code") {
  933. Uint32ParserPtr
  934. code_parser(dynamic_cast<Uint32Parser*>(Uint32Parser::factory(entry)));
  935. if (code_parser) {
  936. code_parser->setStorage(&uint32_values_);
  937. parser = code_parser;
  938. }
  939. } else if (entry == "array") {
  940. BooleanParserPtr
  941. array_parser(dynamic_cast<BooleanParser*>(BooleanParser::factory(entry)));
  942. if (array_parser) {
  943. array_parser->setStorage(&boolean_values_);
  944. parser = array_parser;
  945. }
  946. } else {
  947. isc_throw(DhcpConfigError, "invalid parameter: " << entry);
  948. }
  949. parser->build(param.second);
  950. parser->commit();
  951. }
  952. // Create an instance of option definition.
  953. createOptionDef();
  954. // Get all items we collected so far for the particular option space.
  955. OptionDefContainerPtr defs = storage_->getItems(option_space_name_);
  956. // Check if there are any items with option code the same as the
  957. // one specified for the definition we are now creating.
  958. const OptionDefContainerTypeIndex& idx = defs->get<1>();
  959. const OptionDefContainerTypeRange& range =
  960. idx.equal_range(option_definition_->getCode());
  961. // If there are any items with this option code already we need
  962. // to issue an error because we don't allow duplicates for
  963. // option definitions within an option space.
  964. if (std::distance(range.first, range.second) > 0) {
  965. isc_throw(DhcpConfigError, "duplicated option definition for"
  966. << " code '" << option_definition_->getCode() << "'");
  967. }
  968. }
  969. /// @brief Stores the parsed option definition in the data store.
  970. void commit() {
  971. if (storage_ && option_definition_ &&
  972. OptionSpace::validateName(option_space_name_)) {
  973. storage_->addItem(option_definition_, option_space_name_);
  974. }
  975. }
  976. /// @brief Sets a pointer to the data store.
  977. ///
  978. /// The newly created instance of an option definition will be
  979. /// added to the data store given by the argument.
  980. ///
  981. /// @param storage pointer to the data store where the option definition
  982. /// will be added to.
  983. void setStorage(OptionDefStorage* storage) {
  984. storage_ = storage;
  985. }
  986. private:
  987. /// @brief Create option definition from the parsed parameters.
  988. void createOptionDef() {
  989. // Get the option space name and validate it.
  990. std::string space = string_values_.getParam("space");
  991. if (!OptionSpace::validateName(space)) {
  992. isc_throw(DhcpConfigError, "invalid option space name '"
  993. << space << "'");
  994. }
  995. // Get other parameters that are needed to create the
  996. // option definition.
  997. std::string name = string_values_.getParam("name");
  998. uint32_t code = uint32_values_.getParam("code");
  999. std::string type = string_values_.getParam("type");
  1000. bool array_type = boolean_values_.getParam("array");
  1001. std::string encapsulates = string_values_.getParam("encapsulate");
  1002. // Create option definition.
  1003. OptionDefinitionPtr def;
  1004. // We need to check if user has set encapsulated option space
  1005. // name. If so, different constructor will be used.
  1006. if (!encapsulates.empty()) {
  1007. // Arrays can't be used together with sub-options.
  1008. if (array_type) {
  1009. isc_throw(DhcpConfigError, "option '" << space << "."
  1010. << "name" << "', comprising an array of data"
  1011. << " fields may not encapsulate any option space");
  1012. } else if (encapsulates == space) {
  1013. isc_throw(DhcpConfigError, "option must not encapsulate"
  1014. << " an option space it belongs to: '"
  1015. << space << "." << name << "' is set to"
  1016. << " encapsulate '" << space << "'");
  1017. } else {
  1018. def.reset(new OptionDefinition(name, code, type,
  1019. encapsulates.c_str()));
  1020. }
  1021. } else {
  1022. def.reset(new OptionDefinition(name, code, type, array_type));
  1023. }
  1024. // The record-types field may carry a list of comma separated names
  1025. // of data types that form a record.
  1026. std::string record_types = string_values_.getParam("record-types");
  1027. // Split the list of record types into tokens.
  1028. std::vector<std::string> record_tokens =
  1029. isc::util::str::tokens(record_types, ",");
  1030. // Iterate over each token and add a record type into
  1031. // option definition.
  1032. BOOST_FOREACH(std::string record_type, record_tokens) {
  1033. try {
  1034. boost::trim(record_type);
  1035. if (!record_type.empty()) {
  1036. def->addRecordField(record_type);
  1037. }
  1038. } catch (const Exception& ex) {
  1039. isc_throw(DhcpConfigError, "invalid record type values"
  1040. << " specified for the option definition: "
  1041. << ex.what());
  1042. }
  1043. }
  1044. // Check the option definition parameters are valid.
  1045. try {
  1046. def->validate();
  1047. } catch (const isc::Exception& ex) {
  1048. isc_throw(DhcpConfigError, "invalid option definition"
  1049. << " parameters: " << ex.what());
  1050. }
  1051. // Option definition has been created successfully.
  1052. option_space_name_ = space;
  1053. option_definition_ = def;
  1054. }
  1055. /// Instance of option definition being created by this parser.
  1056. OptionDefinitionPtr option_definition_;
  1057. /// Name of the space the option definition belongs to.
  1058. std::string option_space_name_;
  1059. /// Pointer to a storage where the option definition will be
  1060. /// added when \ref commit is called.
  1061. OptionDefStorage* storage_;
  1062. /// Storage for boolean values.
  1063. BooleanStorage boolean_values_;
  1064. /// Storage for string values.
  1065. StringStorage string_values_;
  1066. /// Storage for uint32 values.
  1067. Uint32Storage uint32_values_;
  1068. };
  1069. /// @brief Parser for a list of option definitions.
  1070. ///
  1071. /// This parser iterates over all configuration entries that define
  1072. /// option definitions and creates instances of these definitions.
  1073. /// If the parsing is successful, the collection of created definitions
  1074. /// is put into the provided storage.
  1075. class OptionDefListParser : DhcpConfigParser {
  1076. public:
  1077. /// @brief Constructor.
  1078. ///
  1079. /// This constructor initializes the pointer to option definitions
  1080. /// storage to NULL value. This pointer has to be set to point to
  1081. /// the actual storage before the \ref build function is called.
  1082. OptionDefListParser(const std::string&) {
  1083. }
  1084. /// @brief Parse configuration entries.
  1085. ///
  1086. /// This function parses configuration entries and creates instances
  1087. /// of option definitions.
  1088. ///
  1089. /// @param option_def_list pointer to an element that holds entries
  1090. /// that define option definitions.
  1091. /// @throw DhcpConfigError if configuration parsing fails.
  1092. void build(ConstElementPtr option_def_list) {
  1093. // Clear existing items in the global storage.
  1094. // We are going to replace all of them.
  1095. option_def_intermediate.clearItems();
  1096. if (!option_def_list) {
  1097. isc_throw(DhcpConfigError, "parser error: a pointer to a list of"
  1098. << " option definitions is NULL");
  1099. }
  1100. BOOST_FOREACH(ConstElementPtr option_def, option_def_list->listValue()) {
  1101. boost::shared_ptr<OptionDefParser>
  1102. parser(new OptionDefParser("single-option-def"));
  1103. parser->setStorage(&option_def_intermediate);
  1104. parser->build(option_def);
  1105. parser->commit();
  1106. }
  1107. }
  1108. /// @brief Stores option definitions in the CfgMgr.
  1109. void commit() {
  1110. CfgMgr& cfg_mgr = CfgMgr::instance();
  1111. cfg_mgr.deleteOptionDefs();
  1112. // We need to move option definitions from the temporary
  1113. // storage to the global storage.
  1114. std::list<std::string> space_names =
  1115. option_def_intermediate.getOptionSpaceNames();
  1116. BOOST_FOREACH(std::string space_name, space_names) {
  1117. BOOST_FOREACH(OptionDefinitionPtr def,
  1118. *option_def_intermediate.getItems(space_name)) {
  1119. // All option definitions should be initialized to non-NULL
  1120. // values. The validation is expected to be made by the
  1121. // OptionDefParser when creating an option definition.
  1122. assert(def);
  1123. cfg_mgr.addOptionDef(def, space_name);
  1124. }
  1125. }
  1126. }
  1127. /// @brief Create an OptionDefListParser object.
  1128. ///
  1129. /// @param param_name configuration entry holding option definitions.
  1130. ///
  1131. /// @return OptionDefListParser object.
  1132. static DhcpConfigParser* factory(const std::string& param_name) {
  1133. return (new OptionDefListParser(param_name));
  1134. }
  1135. };
  1136. /// @brief this class parses a single subnet
  1137. ///
  1138. /// This class parses the whole subnet definition. It creates parsers
  1139. /// for received configuration parameters as needed.
  1140. class Subnet6ConfigParser : public DhcpConfigParser {
  1141. public:
  1142. /// @brief constructor
  1143. Subnet6ConfigParser(const std::string& ) {
  1144. // The parameter should always be "subnet", but we don't check
  1145. // against that here in case some wants to reuse this parser somewhere.
  1146. }
  1147. /// @brief parses parameter value
  1148. ///
  1149. /// @param subnet pointer to the content of subnet definition
  1150. ///
  1151. /// @throw isc::DhcpConfigError if subnet configuration parsing failed.
  1152. void build(ConstElementPtr subnet) {
  1153. BOOST_FOREACH(ConfigPair param, subnet->mapValue()) {
  1154. ParserPtr parser(createSubnet6ConfigParser(param.first));
  1155. // The actual type of the parser is unknown here. We have to discover
  1156. // the parser type here to invoke the corresponding setStorage function
  1157. // on it. We discover parser type by trying to cast the parser to various
  1158. // parser types and checking which one was successful. For this one
  1159. // a setStorage and build methods are invoked.
  1160. // Try uint32 type parser.
  1161. if (!buildParser<Uint32Parser, Uint32Storage >(parser, uint32_values_,
  1162. param.second) &&
  1163. // Try string type parser.
  1164. !buildParser<StringParser, StringStorage >(parser, string_values_,
  1165. param.second) &&
  1166. // Try pool parser.
  1167. !buildParser<PoolParser, PoolStorage >(parser, pools_,
  1168. param.second) &&
  1169. // Try option data parser.
  1170. !buildParser<OptionDataListParser, OptionStorage >(parser, options_,
  1171. param.second)) {
  1172. // Appropriate parsers are created in the createSubnet6ConfigParser
  1173. // and they should be limited to those that we check here for. Thus,
  1174. // if we fail to find a matching parser here it is a programming error.
  1175. isc_throw(DhcpConfigError, "failed to find suitable parser");
  1176. }
  1177. }
  1178. // In order to create new subnet we need to get the data out
  1179. // of the child parsers first. The only way to do it is to
  1180. // invoke commit on them because it will make them write
  1181. // parsed data into storages we have supplied.
  1182. // Note that triggering commits on child parsers does not
  1183. // affect global data because we supplied pointers to storages
  1184. // local to this object. Thus, even if this method fails
  1185. // later on, the configuration remains consistent.
  1186. BOOST_FOREACH(ParserPtr parser, parsers_) {
  1187. parser->commit();
  1188. }
  1189. // Create a subnet.
  1190. createSubnet();
  1191. }
  1192. /// @brief Adds the created subnet to a server's configuration.
  1193. void commit() {
  1194. if (subnet_) {
  1195. isc::dhcp::CfgMgr::instance().addSubnet6(subnet_);
  1196. }
  1197. }
  1198. private:
  1199. /// @brief Set storage for a parser and invoke build.
  1200. ///
  1201. /// This helper method casts the provided parser pointer to the specified
  1202. /// type. If the cast is successful it sets the corresponding storage for
  1203. /// this parser, invokes build on it and saves the parser.
  1204. ///
  1205. /// @tparam T parser type to which parser argument should be cast.
  1206. /// @tparam Y storage type for the specified parser type.
  1207. /// @param parser parser on which build must be invoked.
  1208. /// @param storage reference to a storage that will be set for a parser.
  1209. /// @param subnet subnet element read from the configuration and being parsed.
  1210. /// @return true if parser pointer was successfully cast to specialized
  1211. /// parser type provided as Y.
  1212. template<typename T, typename Y>
  1213. bool buildParser(const ParserPtr& parser, Y& storage, const ConstElementPtr& subnet) {
  1214. // We need to cast to T in order to set storage for the parser.
  1215. boost::shared_ptr<T> cast_parser = boost::dynamic_pointer_cast<T>(parser);
  1216. // It is common that this cast is not successful because we try to cast to all
  1217. // supported parser types as we don't know the type of a parser in advance.
  1218. if (cast_parser) {
  1219. // Cast, successful so we go ahead with setting storage and actual parse.
  1220. cast_parser->setStorage(&storage);
  1221. parser->build(subnet);
  1222. parsers_.push_back(parser);
  1223. // We indicate that cast was successful so as the calling function
  1224. // may skip attempts to cast to other parser types and proceed to
  1225. // next element.
  1226. return (true);
  1227. }
  1228. // It was not successful. Indicate that another parser type
  1229. // should be tried.
  1230. return (false);
  1231. }
  1232. /// @brief Append sub-options to an option.
  1233. ///
  1234. /// @param option_space a name of the encapsulated option space.
  1235. /// @param option option instance to append sub-options to.
  1236. void appendSubOptions(const std::string& option_space, OptionPtr& option) {
  1237. // Only non-NULL options are stored in option container.
  1238. // If this option pointer is NULL this is a serious error.
  1239. assert(option);
  1240. OptionDefinitionPtr def;
  1241. if (option_space == "dhcp6" &&
  1242. LibDHCP::isStandardOption(Option::V6, option->getType())) {
  1243. def = LibDHCP::getOptionDef(Option::V6, option->getType());
  1244. // Definitions for some of the standard options hasn't been
  1245. // implemented so it is ok to leave here.
  1246. if (!def) {
  1247. return;
  1248. }
  1249. } else {
  1250. const OptionDefContainerPtr defs =
  1251. option_def_intermediate.getItems(option_space);
  1252. const OptionDefContainerTypeIndex& idx = defs->get<1>();
  1253. const OptionDefContainerTypeRange& range =
  1254. idx.equal_range(option->getType());
  1255. // There is no definition so we have to leave.
  1256. if (std::distance(range.first, range.second) == 0) {
  1257. return;
  1258. }
  1259. def = *range.first;
  1260. // If the definition exists, it must be non-NULL.
  1261. // Otherwise it is a programming error.
  1262. assert(def);
  1263. }
  1264. // We need to get option definition for the particular option space
  1265. // and code. This definition holds the information whether our
  1266. // option encapsulates any option space.
  1267. // Get the encapsulated option space name.
  1268. std::string encapsulated_space = def->getEncapsulatedSpace();
  1269. // If option space name is empty it means that our option does not
  1270. // encapsulate any option space (does not include sub-options).
  1271. if (!encapsulated_space.empty()) {
  1272. // Get the sub-options that belong to the encapsulated
  1273. // option space.
  1274. const Subnet::OptionContainerPtr sub_opts =
  1275. option_defaults.getItems(encapsulated_space);
  1276. // Append sub-options to the option.
  1277. BOOST_FOREACH(Subnet::OptionDescriptor desc, *sub_opts) {
  1278. if (desc.option) {
  1279. option->addOption(desc.option);
  1280. }
  1281. }
  1282. }
  1283. }
  1284. /// @brief Create a new subnet using a data from child parsers.
  1285. ///
  1286. /// @throw isc::dhcp::DhcpConfigError if subnet configuration parsing failed.
  1287. void createSubnet() {
  1288. std::string subnet_txt;
  1289. try {
  1290. subnet_txt = string_values_.getParam("subnet");
  1291. } catch (DhcpConfigError) {
  1292. // rethrow with precise error
  1293. isc_throw(DhcpConfigError,
  1294. "Mandatory subnet definition in subnet missing");
  1295. }
  1296. // Remove any spaces or tabs.
  1297. boost::erase_all(subnet_txt, " ");
  1298. boost::erase_all(subnet_txt, "\t");
  1299. // The subnet format is prefix/len. We are going to extract
  1300. // the prefix portion of a subnet string to create IOAddress
  1301. // object from it. IOAddress will be passed to the Subnet's
  1302. // constructor later on. In order to extract the prefix we
  1303. // need to get all characters preceding "/".
  1304. size_t pos = subnet_txt.find("/");
  1305. if (pos == string::npos) {
  1306. isc_throw(DhcpConfigError,
  1307. "Invalid subnet syntax (prefix/len expected):" << subnet_txt);
  1308. }
  1309. // Try to create the address object. It also validates that
  1310. // the address syntax is ok.
  1311. IOAddress addr(subnet_txt.substr(0, pos));
  1312. uint8_t len = boost::lexical_cast<unsigned int>(subnet_txt.substr(pos + 1));
  1313. // Get all 'time' parameters using inheritance.
  1314. // If the subnet-specific value is defined then use it, else
  1315. // use the global value. The global value must always be
  1316. // present. If it is not, it is an internal error and exception
  1317. // is thrown.
  1318. Triplet<uint32_t> t1 = getParam("renew-timer");
  1319. Triplet<uint32_t> t2 = getParam("rebind-timer");
  1320. Triplet<uint32_t> pref = getParam("preferred-lifetime");
  1321. Triplet<uint32_t> valid = getParam("valid-lifetime");
  1322. // Get interface name. If it is defined, then the subnet is available
  1323. // directly over specified network interface.
  1324. std::string iface;
  1325. try {
  1326. iface = string_values_.getParam("interface");
  1327. } catch (const DhcpConfigError&) {
  1328. // iface not mandatory so swallow the exception
  1329. }
  1330. // Get interface-id option content. For now we support string
  1331. // represenation only
  1332. std::string ifaceid;
  1333. try {
  1334. ifaceid = string_values_.getParam("interface-id");
  1335. } catch (const DhcpConfigError&) {
  1336. // interface-id is not mandatory
  1337. }
  1338. if (!iface.empty() && !ifaceid.empty()) {
  1339. isc_throw(isc::dhcp::DhcpConfigError,
  1340. "parser error: interface (defined for locally reachable "
  1341. "subnets) and interface-id (defined for subnets reachable"
  1342. " via relays) cannot be defined at the same time for "
  1343. "subnet " << addr.toText() << "/" << (int)len);
  1344. }
  1345. stringstream tmp;
  1346. tmp << addr.toText() << "/" << static_cast<int>(len)
  1347. << " with params t1=" << t1 << ", t2=" << t2 << ", pref="
  1348. << pref << ", valid=" << valid;
  1349. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_NEW_SUBNET).arg(tmp.str());
  1350. // Create a new subnet.
  1351. subnet_.reset(new Subnet6(addr, len, t1, t2, pref, valid));
  1352. // Add pools to it.
  1353. for (PoolStorage::iterator it = pools_.begin(); it != pools_.end(); ++it) {
  1354. subnet_->addPool(*it);
  1355. }
  1356. // Configure interface, if defined
  1357. if (!iface.empty()) {
  1358. if (!IfaceMgr::instance().getIface(iface)) {
  1359. isc_throw(DhcpConfigError, "Specified interface name " << iface
  1360. << " for subnet " << subnet_->toText() << " is not present"
  1361. << " in the system.");
  1362. }
  1363. subnet_->setIface(iface);
  1364. }
  1365. // Configure interface-id for remote interfaces, if defined
  1366. if (!ifaceid.empty()) {
  1367. OptionBuffer tmp(ifaceid.begin(), ifaceid.end());
  1368. OptionPtr opt(new Option(Option::V6, D6O_INTERFACE_ID, tmp));
  1369. subnet_->setInterfaceId(opt);
  1370. }
  1371. // We are going to move configured options to the Subnet object.
  1372. // Configured options reside in the container where options
  1373. // are grouped by space names. Thus we need to get all space names
  1374. // and iterate over all options that belong to them.
  1375. std::list<std::string> space_names = options_.getOptionSpaceNames();
  1376. BOOST_FOREACH(std::string option_space, space_names) {
  1377. // Get all options within a particular option space.
  1378. BOOST_FOREACH(Subnet::OptionDescriptor desc,
  1379. *options_.getItems(option_space)) {
  1380. // The pointer should be non-NULL. The validation is expected
  1381. // to be performed by the OptionDataParser before adding an
  1382. // option descriptor to the container.
  1383. assert(desc.option);
  1384. // We want to check whether an option with the particular
  1385. // option code has been already added. If so, we want
  1386. // to issue a warning.
  1387. Subnet::OptionDescriptor existing_desc =
  1388. subnet_->getOptionDescriptor("option_space",
  1389. desc.option->getType());
  1390. if (existing_desc.option) {
  1391. LOG_WARN(dhcp6_logger, DHCP6_CONFIG_OPTION_DUPLICATE)
  1392. .arg(desc.option->getType()).arg(addr.toText());
  1393. }
  1394. // Add sub-options (if any).
  1395. appendSubOptions(option_space, desc.option);
  1396. // In any case, we add the option to the subnet.
  1397. subnet_->addOption(desc.option, false, option_space);
  1398. }
  1399. }
  1400. // Check all global options and add them to the subnet object if
  1401. // they have been configured in the global scope. If they have been
  1402. // configured in the subnet scope we don't add global option because
  1403. // the one configured in the subnet scope always takes precedence.
  1404. space_names = option_defaults.getOptionSpaceNames();
  1405. BOOST_FOREACH(std::string option_space, space_names) {
  1406. // Get all global options for the particular option space.
  1407. BOOST_FOREACH(Subnet::OptionDescriptor desc,
  1408. *option_defaults.getItems(option_space)) {
  1409. // The pointer should be non-NULL. The validation is expected
  1410. // to be performed by the OptionDataParser before adding an
  1411. // option descriptor to the container.
  1412. assert(desc.option);
  1413. // Check if the particular option has been already added.
  1414. // This would mean that it has been configured in the
  1415. // subnet scope. Since option values configured in the
  1416. // subnet scope take precedence over globally configured
  1417. // values we don't add option from the global storage
  1418. // if there is one already.
  1419. Subnet::OptionDescriptor existing_desc =
  1420. subnet_->getOptionDescriptor(option_space, desc.option->getType());
  1421. if (!existing_desc.option) {
  1422. // Add sub-options (if any).
  1423. appendSubOptions(option_space, desc.option);
  1424. subnet_->addOption(desc.option, false, option_space);
  1425. }
  1426. }
  1427. }
  1428. }
  1429. /// @brief creates parsers for entries in subnet definition
  1430. ///
  1431. /// @param config_id name od the entry
  1432. ///
  1433. /// @return parser object for specified entry name
  1434. /// @throw isc::dhcp::DhcpConfigError if trying to create a parser
  1435. /// for unknown config element
  1436. DhcpConfigParser* createSubnet6ConfigParser(const std::string& config_id) {
  1437. FactoryMap factories;
  1438. factories["preferred-lifetime"] = Uint32Parser::factory;
  1439. factories["valid-lifetime"] = Uint32Parser::factory;
  1440. factories["renew-timer"] = Uint32Parser::factory;
  1441. factories["rebind-timer"] = Uint32Parser::factory;
  1442. factories["subnet"] = StringParser::factory;
  1443. factories["pool"] = PoolParser::factory;
  1444. factories["option-data"] = OptionDataListParser::factory;
  1445. factories["interface"] = StringParser::factory;
  1446. factories["interface-id"] = StringParser::factory;
  1447. FactoryMap::iterator f = factories.find(config_id);
  1448. if (f == factories.end()) {
  1449. // Used for debugging only.
  1450. // return new DebugParser(config_id);
  1451. isc_throw(isc::dhcp::DhcpConfigError,
  1452. "parser error: subnet6 parameter not supported: "
  1453. << config_id);
  1454. }
  1455. return (f->second(config_id));
  1456. }
  1457. /// @brief Returns value for a given parameter (after using inheritance)
  1458. ///
  1459. /// This method implements inheritance. For a given parameter name, it first
  1460. /// checks if there is a global value for it and overwrites it with specific
  1461. /// value if such value was defined in subnet.
  1462. ///
  1463. /// @param name name of the parameter
  1464. /// @return triplet with the parameter name
  1465. /// @throw DhcpConfigError when requested parameter is not present
  1466. isc::dhcp::Triplet<uint32_t> getParam(const std::string& name) {
  1467. uint32_t value = 0;
  1468. try {
  1469. // look for local value
  1470. value = uint32_values_.getParam(name);
  1471. } catch (DhcpConfigError) {
  1472. try {
  1473. // no local, use global value
  1474. value = uint32_defaults.getParam(name);
  1475. } catch (DhcpConfigError) {
  1476. isc_throw(DhcpConfigError, "Mandatory parameter " << name
  1477. << " missing (no global default and no subnet-"
  1478. << "specific value)");
  1479. }
  1480. }
  1481. return (Triplet<uint32_t>(value));
  1482. }
  1483. /// storage for subnet-specific uint32 values
  1484. Uint32Storage uint32_values_;
  1485. /// storage for subnet-specific integer values
  1486. StringStorage string_values_;
  1487. /// storage for pools belonging to this subnet
  1488. PoolStorage pools_;
  1489. /// storage for options belonging to this subnet
  1490. OptionStorage options_;
  1491. /// parsers are stored here
  1492. ParserCollection parsers_;
  1493. /// Pointer to the created subnet object.
  1494. isc::dhcp::Subnet6Ptr subnet_;
  1495. };
  1496. /// @brief this class parses a list of subnets
  1497. ///
  1498. /// This is a wrapper parser that handles the whole list of Subnet6
  1499. /// definitions. It iterates over all entries and creates Subnet6ConfigParser
  1500. /// for each entry.
  1501. class Subnets6ListConfigParser : public DhcpConfigParser {
  1502. public:
  1503. /// @brief constructor
  1504. ///
  1505. Subnets6ListConfigParser(const std::string&) {
  1506. /// parameter name is ignored
  1507. }
  1508. /// @brief parses contents of the list
  1509. ///
  1510. /// Iterates over all entries on the list and creates a Subnet6ConfigParser
  1511. /// for each entry.
  1512. ///
  1513. /// @param subnets_list pointer to a list of IPv6 subnets
  1514. void build(ConstElementPtr subnets_list) {
  1515. // No need to define FactoryMap here. There's only one type
  1516. // used: Subnet6ConfigParser
  1517. BOOST_FOREACH(ConstElementPtr subnet, subnets_list->listValue()) {
  1518. ParserPtr parser(new Subnet6ConfigParser("subnet"));
  1519. parser->build(subnet);
  1520. subnets_.push_back(parser);
  1521. }
  1522. }
  1523. /// @brief commits subnets definitions.
  1524. ///
  1525. /// Iterates over all Subnet6 parsers. Each parser contains definitions
  1526. /// of a single subnet and its parameters and commits each subnet separately.
  1527. void commit() {
  1528. // @todo: Implement more subtle reconfiguration than toss
  1529. // the old one and replace with the new one.
  1530. // remove old subnets
  1531. isc::dhcp::CfgMgr::instance().deleteSubnets6();
  1532. BOOST_FOREACH(ParserPtr subnet, subnets_) {
  1533. subnet->commit();
  1534. }
  1535. }
  1536. /// @brief Returns Subnet6ListConfigParser object
  1537. /// @param param_name name of the parameter
  1538. /// @return Subnets6ListConfigParser object
  1539. static DhcpConfigParser* factory(const std::string& param_name) {
  1540. return (new Subnets6ListConfigParser(param_name));
  1541. }
  1542. /// @brief collection of subnet parsers.
  1543. ParserCollection subnets_;
  1544. };
  1545. } // anonymous namespace
  1546. namespace isc {
  1547. namespace dhcp {
  1548. /// @brief creates global parsers
  1549. ///
  1550. /// This method creates global parsers that parse global parameters, i.e.
  1551. /// those that take format of Dhcp6/param1, Dhcp6/param2 and so forth.
  1552. ///
  1553. /// @param config_id pointer to received global configuration entry
  1554. /// @return parser for specified global DHCPv6 parameter
  1555. /// @throw NotImplemented if trying to create a parser for unknown config element
  1556. DhcpConfigParser* createGlobalDhcpConfigParser(const std::string& config_id) {
  1557. FactoryMap factories;
  1558. factories["preferred-lifetime"] = Uint32Parser::factory;
  1559. factories["valid-lifetime"] = Uint32Parser::factory;
  1560. factories["renew-timer"] = Uint32Parser::factory;
  1561. factories["rebind-timer"] = Uint32Parser::factory;
  1562. factories["interface"] = InterfaceListConfigParser::factory;
  1563. factories["subnet6"] = Subnets6ListConfigParser::factory;
  1564. factories["option-data"] = OptionDataListParser::factory;
  1565. factories["option-def"] = OptionDefListParser::factory;
  1566. factories["version"] = StringParser::factory;
  1567. factories["lease-database"] = DbAccessParser::factory;
  1568. FactoryMap::iterator f = factories.find(config_id);
  1569. if (f == factories.end()) {
  1570. // Used for debugging only.
  1571. // return new DebugParser(config_id);
  1572. isc_throw(NotImplemented,
  1573. "Parser error: Global configuration parameter not supported: "
  1574. << config_id);
  1575. }
  1576. return (f->second(config_id));
  1577. }
  1578. ConstElementPtr
  1579. configureDhcp6Server(Dhcpv6Srv&, ConstElementPtr config_set) {
  1580. if (!config_set) {
  1581. ConstElementPtr answer = isc::config::createAnswer(1,
  1582. string("Can't parse NULL config"));
  1583. return (answer);
  1584. }
  1585. /// @todo: append most essential info here (like "2 new subnets configured")
  1586. string config_details;
  1587. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_START).arg(config_set->str());
  1588. // Some of the values specified in the configuration depend on
  1589. // other values. Typically, the values in the subnet4 structure
  1590. // depend on the global values. Also, option values configuration
  1591. // must be performed after the option definitions configurations.
  1592. // Thus we group parsers and will fire them in the right order:
  1593. // all parsers other than subnet4 and option-data parser,
  1594. // option-data parser, subnet4 parser.
  1595. ParserCollection independent_parsers;
  1596. ParserPtr subnet_parser;
  1597. ParserPtr option_parser;
  1598. // The subnet parsers implement data inheritance by directly
  1599. // accessing global storage. For this reason the global data
  1600. // parsers must store the parsed data into global storages
  1601. // immediately. This may cause data inconsistency if the
  1602. // parsing operation fails after the global storage has been
  1603. // modified. We need to preserve the original global data here
  1604. // so as we can rollback changes when an error occurs.
  1605. Uint32Storage uint32_local(uint32_defaults);
  1606. StringStorage string_local(string_defaults);
  1607. OptionStorage option_local(option_defaults);
  1608. OptionDefStorage option_def_local(option_def_intermediate);
  1609. // answer will hold the result.
  1610. ConstElementPtr answer;
  1611. // rollback informs whether error occured and original data
  1612. // have to be restored to global storages.
  1613. bool rollback = false;
  1614. // config_pair holds ther details of the current parser when iterating over
  1615. // the parsers. It is declared outside the loop so in case of error, the
  1616. // name of the failing parser can be retrieved within the "catch" clause.
  1617. ConfigPair config_pair;
  1618. try {
  1619. // Make parsers grouping.
  1620. const std::map<std::string, ConstElementPtr>& values_map =
  1621. config_set->mapValue();
  1622. BOOST_FOREACH(config_pair, values_map) {
  1623. ParserPtr parser(createGlobalDhcpConfigParser(config_pair.first));
  1624. LOG_DEBUG(dhcp6_logger, DBG_DHCP6_DETAIL, DHCP6_PARSER_CREATED)
  1625. .arg(config_pair.first);
  1626. if (config_pair.first == "subnet6") {
  1627. subnet_parser = parser;
  1628. } else if (config_pair.first == "option-data") {
  1629. option_parser = parser;
  1630. } else {
  1631. // Those parsers should be started before other
  1632. // parsers so we can call build straight away.
  1633. independent_parsers.push_back(parser);
  1634. parser->build(config_pair.second);
  1635. // The commit operation here may modify the global storage
  1636. // but we need it so as the subnet6 parser can access the
  1637. // parsed data.
  1638. parser->commit();
  1639. }
  1640. }
  1641. // The option values parser is the next one to be run.
  1642. std::map<std::string, ConstElementPtr>::const_iterator option_config =
  1643. values_map.find("option-data");
  1644. if (option_config != values_map.end()) {
  1645. option_parser->build(option_config->second);
  1646. option_parser->commit();
  1647. }
  1648. // The subnet parser is the last one to be run.
  1649. std::map<std::string, ConstElementPtr>::const_iterator subnet_config =
  1650. values_map.find("subnet6");
  1651. if (subnet_config != values_map.end()) {
  1652. subnet_parser->build(subnet_config->second);
  1653. }
  1654. } catch (const isc::Exception& ex) {
  1655. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_FAIL)
  1656. .arg(config_pair.first).arg(ex.what());
  1657. answer = isc::config::createAnswer(1,
  1658. string("Configuration parsing failed: ") + ex.what());
  1659. // An error occured, so make sure that we restore original data.
  1660. rollback = true;
  1661. } catch (...) {
  1662. // for things like bad_cast in boost::lexical_cast
  1663. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_EXCEPTION).arg(config_pair.first);
  1664. answer = isc::config::createAnswer(1,
  1665. string("Configuration parsing failed"));
  1666. // An error occured, so make sure that we restore original data.
  1667. rollback = true;
  1668. }
  1669. // So far so good, there was no parsing error so let's commit the
  1670. // configuration. This will add created subnets and option values into
  1671. // the server's configuration.
  1672. // This operation should be exception safe but let's make sure.
  1673. if (!rollback) {
  1674. try {
  1675. if (subnet_parser) {
  1676. subnet_parser->commit();
  1677. }
  1678. }
  1679. catch (const isc::Exception& ex) {
  1680. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(ex.what());
  1681. answer = isc::config::createAnswer(2,
  1682. string("Configuration commit failed:") + ex.what());
  1683. // An error occured, so make sure to restore the original data.
  1684. rollback = true;
  1685. } catch (...) {
  1686. // for things like bad_cast in boost::lexical_cast
  1687. LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_EXCEPTION);
  1688. answer = isc::config::createAnswer(2,
  1689. string("Configuration commit failed"));
  1690. // An error occured, so make sure to restore the original data.
  1691. rollback = true;
  1692. }
  1693. }
  1694. // Rollback changes as the configuration parsing failed.
  1695. if (rollback) {
  1696. std::swap(uint32_defaults, uint32_local);
  1697. std::swap(string_defaults, string_local);
  1698. std::swap(option_defaults, option_local);
  1699. std::swap(option_def_intermediate, option_def_local);
  1700. return (answer);
  1701. }
  1702. LOG_INFO(dhcp6_logger, DHCP6_CONFIG_COMPLETE).arg(config_details);
  1703. // Everything was fine. Configuration is successful.
  1704. answer = isc::config::createAnswer(0, "Configuration committed.");
  1705. return (answer);
  1706. }
  1707. }; // end of isc::dhcp namespace
  1708. }; // end of isc namespace