config_parser.cc 58 KB

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