config_parser.cc 68 KB

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