config_parser.cc 62 KB

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