config_parser.cc 58 KB

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