config_parser.cc 75 KB

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