config_parser.cc 59 KB

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