config_parser.cc 70 KB

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