dhcp_parsers.cc 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. // Copyright (C) 2013 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <dhcp/iface_mgr.h>
  15. #include <dhcp/libdhcp++.h>
  16. #include <dhcpsrv/cfgmgr.h>
  17. #include <dhcpsrv/dhcp_parsers.h>
  18. #include <util/encode/hex.h>
  19. #include <util/strutil.h>
  20. #include <boost/foreach.hpp>
  21. #include <boost/lexical_cast.hpp>
  22. #include <boost/algorithm/string.hpp>
  23. #include <boost/lexical_cast.hpp>
  24. #include <string>
  25. #include <map>
  26. using namespace std;
  27. using namespace isc::data;
  28. namespace isc {
  29. namespace dhcp {
  30. namespace {
  31. const char* ALL_IFACES_KEYWORD = "all";
  32. }
  33. // *********************** ParserContext *************************
  34. ParserContext::ParserContext(Option::Universe universe):
  35. boolean_values_(new BooleanStorage()),
  36. uint32_values_(new Uint32Storage()),
  37. string_values_(new StringStorage()),
  38. options_(new OptionStorage()),
  39. option_defs_(new OptionDefStorage()),
  40. universe_(universe) {
  41. }
  42. ParserContext::ParserContext(const ParserContext& rhs):
  43. boolean_values_(new BooleanStorage(*(rhs.boolean_values_))),
  44. uint32_values_(new Uint32Storage(*(rhs.uint32_values_))),
  45. string_values_(new StringStorage(*(rhs.string_values_))),
  46. options_(new OptionStorage(*(rhs.options_))),
  47. option_defs_(new OptionDefStorage(*(rhs.option_defs_))),
  48. universe_(rhs.universe_) {
  49. }
  50. ParserContext&
  51. ParserContext::operator=(const ParserContext& rhs) {
  52. if (this != &rhs) {
  53. boolean_values_ =
  54. BooleanStoragePtr(new BooleanStorage(*(rhs.boolean_values_)));
  55. uint32_values_ =
  56. Uint32StoragePtr(new Uint32Storage(*(rhs.uint32_values_)));
  57. string_values_ =
  58. StringStoragePtr(new StringStorage(*(rhs.string_values_)));
  59. options_ = OptionStoragePtr(new OptionStorage(*(rhs.options_)));
  60. option_defs_ =
  61. OptionDefStoragePtr(new OptionDefStorage(*(rhs.option_defs_)));
  62. universe_ = rhs.universe_;
  63. }
  64. return (*this);
  65. }
  66. // **************************** DebugParser *************************
  67. DebugParser::DebugParser(const std::string& param_name)
  68. :param_name_(param_name) {
  69. }
  70. void
  71. DebugParser::build(ConstElementPtr new_config) {
  72. value_ = new_config;
  73. std::cout << "Build for token: [" << param_name_ << "] = ["
  74. << value_->str() << "]" << std::endl;
  75. }
  76. void
  77. DebugParser::commit() {
  78. // Debug message. The whole DebugParser class is used only for parser
  79. // debugging, and is not used in production code. It is very convenient
  80. // to keep it around. Please do not turn this cout into logger calls.
  81. std::cout << "Commit for token: [" << param_name_ << "] = ["
  82. << value_->str() << "]" << std::endl;
  83. }
  84. // **************************** BooleanParser *************************
  85. template<> void ValueParser<bool>::build(isc::data::ConstElementPtr value) {
  86. // The Config Manager checks if user specified a
  87. // valid value for a boolean parameter: True or False.
  88. // We should have a boolean Element, use value directly
  89. try {
  90. value_ = value->boolValue();
  91. } catch (const isc::data::TypeError &) {
  92. isc_throw(BadValue, " Wrong value type for " << param_name_
  93. << " : build called with a non-boolean element.");
  94. }
  95. }
  96. // **************************** Uin32Parser *************************
  97. template<> void ValueParser<uint32_t>::build(ConstElementPtr value) {
  98. int64_t check;
  99. string x = value->str();
  100. try {
  101. check = boost::lexical_cast<int64_t>(x);
  102. } catch (const boost::bad_lexical_cast &) {
  103. isc_throw(BadValue, "Failed to parse value " << value->str()
  104. << " as unsigned 32-bit integer.");
  105. }
  106. if (check > std::numeric_limits<uint32_t>::max()) {
  107. isc_throw(BadValue, "Value " << value->str() << "is too large"
  108. << " for unsigned 32-bit integer.");
  109. }
  110. if (check < 0) {
  111. isc_throw(BadValue, "Value " << value->str() << "is negative."
  112. << " Only 0 or larger are allowed for unsigned 32-bit integer.");
  113. }
  114. // value is small enough to fit
  115. value_ = static_cast<uint32_t>(check);
  116. }
  117. // **************************** StringParser *************************
  118. template <> void ValueParser<std::string>::build(ConstElementPtr value) {
  119. value_ = value->str();
  120. boost::erase_all(value_, "\"");
  121. }
  122. // ******************** InterfaceListConfigParser *************************
  123. InterfaceListConfigParser::
  124. InterfaceListConfigParser(const std::string& param_name)
  125. : activate_all_(false),
  126. param_name_(param_name) {
  127. if (param_name_ != "interfaces") {
  128. isc_throw(BadValue, "Internal error. Interface configuration "
  129. "parser called for the wrong parameter: " << param_name);
  130. }
  131. }
  132. void
  133. InterfaceListConfigParser::build(ConstElementPtr value) {
  134. // First, we iterate over all specified entries and add it to the
  135. // local container so as we can do some basic validation, e.g. eliminate
  136. // duplicates.
  137. BOOST_FOREACH(ConstElementPtr iface, value->listValue()) {
  138. std::string iface_name = iface->stringValue();
  139. if (iface_name != ALL_IFACES_KEYWORD) {
  140. // Let's eliminate duplicates. We could possibly allow duplicates,
  141. // but if someone specified duplicated interface name it is likely
  142. // that he mistyped the configuration. Failing here should draw his
  143. // attention.
  144. if (isIfaceAdded(iface_name)) {
  145. isc_throw(isc::dhcp::DhcpConfigError, "duplicate interface"
  146. << " name '" << iface_name << "' specified in '"
  147. << param_name_ << "' configuration parameter");
  148. }
  149. // @todo check that this interface exists in the system!
  150. // The IfaceMgr exposes mechanisms to check this.
  151. // Add the interface name if ok.
  152. interfaces_.push_back(iface_name);
  153. } else {
  154. activate_all_ = true;
  155. }
  156. }
  157. }
  158. void
  159. InterfaceListConfigParser::commit() {
  160. CfgMgr& cfg_mgr = CfgMgr::instance();
  161. // Remove active interfaces and clear a flag which marks all interfaces
  162. // active
  163. cfg_mgr.deleteActiveIfaces();
  164. if (activate_all_) {
  165. // Activate all interfaces. There is not need to add their names
  166. // explicitly.
  167. cfg_mgr.activateAllIfaces();
  168. } else {
  169. // Explicitly add names of the interfaces which server should listen on.
  170. BOOST_FOREACH(std::string iface, interfaces_) {
  171. cfg_mgr.addActiveIface(iface);
  172. }
  173. }
  174. }
  175. bool
  176. InterfaceListConfigParser::isIfaceAdded(const std::string& iface) const {
  177. for (IfaceListStorage::const_iterator it = interfaces_.begin();
  178. it != interfaces_.end(); ++it) {
  179. if (iface == *it) {
  180. return (true);
  181. }
  182. }
  183. return (false);
  184. }
  185. // **************************** OptionDataParser *************************
  186. OptionDataParser::OptionDataParser(const std::string&, OptionStoragePtr options,
  187. ParserContextPtr global_context)
  188. : boolean_values_(new BooleanStorage()),
  189. string_values_(new StringStorage()), uint32_values_(new Uint32Storage()),
  190. options_(options), option_descriptor_(false),
  191. global_context_(global_context) {
  192. if (!options_) {
  193. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  194. << "options storage may not be NULL");
  195. }
  196. if (!global_context_) {
  197. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  198. << "context may may not be NULL");
  199. }
  200. }
  201. void
  202. OptionDataParser::build(ConstElementPtr option_data_entries) {
  203. BOOST_FOREACH(ConfigPair param, option_data_entries->mapValue()) {
  204. ParserPtr parser;
  205. if (param.first == "name" || param.first == "data" ||
  206. param.first == "space") {
  207. StringParserPtr name_parser(new StringParser(param.first,
  208. string_values_));
  209. parser = name_parser;
  210. } else if (param.first == "code") {
  211. Uint32ParserPtr code_parser(new Uint32Parser(param.first,
  212. uint32_values_));
  213. parser = code_parser;
  214. } else if (param.first == "csv-format") {
  215. BooleanParserPtr value_parser(new BooleanParser(param.first,
  216. boolean_values_));
  217. parser = value_parser;
  218. } else {
  219. isc_throw(DhcpConfigError,
  220. "Parser error: option-data parameter not supported: "
  221. << param.first);
  222. }
  223. parser->build(param.second);
  224. // Before we can create an option we need to get the data from
  225. // the child parsers. The only way to do it is to invoke commit
  226. // on them so as they store the values in appropriate storages
  227. // that this class provided to them. Note that this will not
  228. // modify values stored in the global storages so the configuration
  229. // will remain consistent even parsing fails somewhere further on.
  230. parser->commit();
  231. }
  232. // Try to create the option instance.
  233. createOption();
  234. }
  235. void
  236. OptionDataParser::commit() {
  237. if (!option_descriptor_.option) {
  238. // Before we can commit the new option should be configured. If it is
  239. // not than somebody must have called commit() before build().
  240. isc_throw(isc::InvalidOperation,
  241. "parser logic error: no option has been configured and"
  242. " thus there is nothing to commit. Has build() been called?");
  243. }
  244. uint16_t opt_type = option_descriptor_.option->getType();
  245. Subnet::OptionContainerPtr options = options_->getItems(option_space_);
  246. // The getItems() should never return NULL pointer. If there are no
  247. // options configured for the particular option space a pointer
  248. // to an empty container should be returned.
  249. assert(options);
  250. Subnet::OptionContainerTypeIndex& idx = options->get<1>();
  251. // Try to find options with the particular option code in the main
  252. // storage. If found, remove these options because they will be
  253. // replaced with new one.
  254. Subnet::OptionContainerTypeRange range = idx.equal_range(opt_type);
  255. if (std::distance(range.first, range.second) > 0) {
  256. idx.erase(range.first, range.second);
  257. }
  258. // Append new option to the main storage.
  259. options_->addItem(option_descriptor_, option_space_);
  260. }
  261. void
  262. OptionDataParser::createOption() {
  263. // Option code is held in the uint32_t storage but is supposed to
  264. // be uint16_t value. We need to check that value in the configuration
  265. // does not exceed range of uint8_t and is not zero.
  266. uint32_t option_code = uint32_values_->getParam("code");
  267. if (option_code == 0) {
  268. isc_throw(DhcpConfigError, "option code must not be zero."
  269. << " Option code '0' is reserved in DHCPv4.");
  270. } else if (option_code > std::numeric_limits<uint8_t>::max()) {
  271. isc_throw(DhcpConfigError, "invalid option code '" << option_code
  272. << "', it must not exceed '"
  273. << std::numeric_limits<uint8_t>::max() << "'");
  274. }
  275. // Check that the option name has been specified, is non-empty and does not
  276. // contain spaces
  277. std::string option_name = string_values_->getParam("name");
  278. if (option_name.empty()) {
  279. isc_throw(DhcpConfigError, "name of the option with code '"
  280. << option_code << "' is empty");
  281. } else if (option_name.find(" ") != std::string::npos) {
  282. isc_throw(DhcpConfigError, "invalid option name '" << option_name
  283. << "', space character is not allowed");
  284. }
  285. std::string option_space = string_values_->getParam("space");
  286. if (!OptionSpace::validateName(option_space)) {
  287. isc_throw(DhcpConfigError, "invalid option space name '"
  288. << option_space << "' specified for option '"
  289. << option_name << "' (code '" << option_code
  290. << "')");
  291. }
  292. // Find the Option Definition for the option by its option code.
  293. // findOptionDefinition will throw if not found, no need to test.
  294. OptionDefinitionPtr def;
  295. if (!(def = findServerSpaceOptionDefinition(option_space, option_code))) {
  296. // If we are not dealing with a standard option then we
  297. // need to search for its definition among user-configured
  298. // options. They are expected to be in the global storage
  299. // already.
  300. OptionDefContainerPtr defs =
  301. global_context_->option_defs_->getItems(option_space);
  302. // The getItems() should never return the NULL pointer. If there are
  303. // no option definitions for the particular option space a pointer
  304. // to an empty container should be returned.
  305. assert(defs);
  306. const OptionDefContainerTypeIndex& idx = defs->get<1>();
  307. OptionDefContainerTypeRange range = idx.equal_range(option_code);
  308. if (std::distance(range.first, range.second) > 0) {
  309. def = *range.first;
  310. }
  311. if (!def) {
  312. isc_throw(DhcpConfigError, "definition for the option '"
  313. << option_space << "." << option_name
  314. << "' having code '" << option_code
  315. << "' does not exist");
  316. }
  317. }
  318. // Get option data from the configuration database ('data' field).
  319. const std::string option_data = string_values_->getParam("data");
  320. const bool csv_format = boolean_values_->getParam("csv-format");
  321. // Transform string of hexadecimal digits into binary format.
  322. std::vector<uint8_t> binary;
  323. std::vector<std::string> data_tokens;
  324. if (csv_format) {
  325. // If the option data is specified as a string of comma
  326. // separated values then we need to split this string into
  327. // individual values - each value will be used to initialize
  328. // one data field of an option.
  329. data_tokens = isc::util::str::tokens(option_data, ",");
  330. } else {
  331. // Otherwise, the option data is specified as a string of
  332. // hexadecimal digits that we have to turn into binary format.
  333. try {
  334. util::encode::decodeHex(option_data, binary);
  335. } catch (...) {
  336. isc_throw(DhcpConfigError, "option data is not a valid"
  337. << " string of hexadecimal digits: " << option_data);
  338. }
  339. }
  340. OptionPtr option;
  341. if (!def) {
  342. if (csv_format) {
  343. isc_throw(DhcpConfigError, "the CSV option data format can be"
  344. " used to specify values for an option that has a"
  345. " definition. The option with code " << option_code
  346. << " does not have a definition.");
  347. }
  348. // @todo We have a limited set of option definitions intiialized at
  349. // the moment. In the future we want to initialize option definitions
  350. // for all options. Consequently an error will be issued if an option
  351. // definition does not exist for a particular option code. For now it is
  352. // ok to create generic option if definition does not exist.
  353. OptionPtr option(new Option(global_context_->universe_,
  354. static_cast<uint16_t>(option_code), binary));
  355. // The created option is stored in option_descriptor_ class member
  356. // until the commit stage when it is inserted into the main storage.
  357. // If an option with the same code exists in main storage already the
  358. // old option is replaced.
  359. option_descriptor_.option = option;
  360. option_descriptor_.persistent = false;
  361. } else {
  362. // Option name should match the definition. The option name
  363. // may seem to be redundant but in the future we may want
  364. // to reference options and definitions using their names
  365. // and/or option codes so keeping the option name in the
  366. // definition of option value makes sense.
  367. if (def->getName() != option_name) {
  368. isc_throw(DhcpConfigError, "specified option name '"
  369. << option_name << "' does not match the "
  370. << "option definition: '" << option_space
  371. << "." << def->getName() << "'");
  372. }
  373. // Option definition has been found so let's use it to create
  374. // an instance of our option.
  375. try {
  376. OptionPtr option = csv_format ?
  377. def->optionFactory(global_context_->universe_,
  378. option_code, data_tokens) :
  379. def->optionFactory(global_context_->universe_,
  380. option_code, binary);
  381. Subnet::OptionDescriptor desc(option, false);
  382. option_descriptor_.option = option;
  383. option_descriptor_.persistent = false;
  384. } catch (const isc::Exception& ex) {
  385. isc_throw(DhcpConfigError, "option data does not match"
  386. << " option definition (space: " << option_space
  387. << ", code: " << option_code << "): "
  388. << ex.what());
  389. }
  390. }
  391. // All went good, so we can set the option space name.
  392. option_space_ = option_space;
  393. }
  394. // **************************** OptionDataListParser *************************
  395. OptionDataListParser::OptionDataListParser(const std::string&,
  396. OptionStoragePtr options, ParserContextPtr global_context,
  397. OptionDataParserFactory* optionDataParserFactory)
  398. : options_(options), local_options_(new OptionStorage()),
  399. global_context_(global_context),
  400. optionDataParserFactory_(optionDataParserFactory) {
  401. if (!options_) {
  402. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  403. << "options storage may not be NULL");
  404. }
  405. if (!options_) {
  406. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  407. << "context may not be NULL");
  408. }
  409. if (!optionDataParserFactory_) {
  410. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  411. << "option data parser factory may not be NULL");
  412. }
  413. }
  414. void
  415. OptionDataListParser::build(ConstElementPtr option_data_list) {
  416. BOOST_FOREACH(ConstElementPtr option_value, option_data_list->listValue()) {
  417. boost::shared_ptr<OptionDataParser>
  418. parser((*optionDataParserFactory_)("option-data",
  419. local_options_, global_context_));
  420. // options_ member will hold instances of all options thus
  421. // each OptionDataParser takes it as a storage.
  422. // Build the instance of a single option.
  423. parser->build(option_value);
  424. // Store a parser as it will be used to commit.
  425. parsers_.push_back(parser);
  426. }
  427. }
  428. void
  429. OptionDataListParser::commit() {
  430. BOOST_FOREACH(ParserPtr parser, parsers_) {
  431. parser->commit();
  432. }
  433. // Parsing was successful and we have all configured
  434. // options in local storage. We can now replace old values
  435. // with new values.
  436. std::swap(*local_options_, *options_);
  437. }
  438. // ******************************** OptionDefParser ****************************
  439. OptionDefParser::OptionDefParser(const std::string&,
  440. OptionDefStoragePtr storage)
  441. : storage_(storage), boolean_values_(new BooleanStorage()),
  442. string_values_(new StringStorage()), uint32_values_(new Uint32Storage()) {
  443. if (!storage_) {
  444. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  445. << "options storage may not be NULL");
  446. }
  447. }
  448. void
  449. OptionDefParser::build(ConstElementPtr option_def) {
  450. // Parse the elements that make up the option definition.
  451. BOOST_FOREACH(ConfigPair param, option_def->mapValue()) {
  452. std::string entry(param.first);
  453. ParserPtr parser;
  454. if (entry == "name" || entry == "type" || entry == "record-types"
  455. || entry == "space" || entry == "encapsulate") {
  456. StringParserPtr str_parser(new StringParser(entry,
  457. string_values_));
  458. parser = str_parser;
  459. } else if (entry == "code") {
  460. Uint32ParserPtr code_parser(new Uint32Parser(entry,
  461. uint32_values_));
  462. parser = code_parser;
  463. } else if (entry == "array") {
  464. BooleanParserPtr array_parser(new BooleanParser(entry,
  465. boolean_values_));
  466. parser = array_parser;
  467. } else {
  468. isc_throw(DhcpConfigError, "invalid parameter: " << entry);
  469. }
  470. parser->build(param.second);
  471. parser->commit();
  472. }
  473. // Create an instance of option definition.
  474. createOptionDef();
  475. // Get all items we collected so far for the particular option space.
  476. OptionDefContainerPtr defs = storage_->getItems(option_space_name_);
  477. // Check if there are any items with option code the same as the
  478. // one specified for the definition we are now creating.
  479. const OptionDefContainerTypeIndex& idx = defs->get<1>();
  480. const OptionDefContainerTypeRange& range =
  481. idx.equal_range(option_definition_->getCode());
  482. // If there are any items with this option code already we need
  483. // to issue an error because we don't allow duplicates for
  484. // option definitions within an option space.
  485. if (std::distance(range.first, range.second) > 0) {
  486. isc_throw(DhcpConfigError, "duplicated option definition for"
  487. << " code '" << option_definition_->getCode() << "'");
  488. }
  489. }
  490. void
  491. OptionDefParser::commit() {
  492. if (storage_ && option_definition_ &&
  493. OptionSpace::validateName(option_space_name_)) {
  494. storage_->addItem(option_definition_, option_space_name_);
  495. }
  496. }
  497. void
  498. OptionDefParser::createOptionDef() {
  499. // Get the option space name and validate it.
  500. std::string space = string_values_->getParam("space");
  501. if (!OptionSpace::validateName(space)) {
  502. isc_throw(DhcpConfigError, "invalid option space name '"
  503. << space << "'");
  504. }
  505. // Get other parameters that are needed to create the
  506. // option definition.
  507. std::string name = string_values_->getParam("name");
  508. uint32_t code = uint32_values_->getParam("code");
  509. std::string type = string_values_->getParam("type");
  510. bool array_type = boolean_values_->getParam("array");
  511. std::string encapsulates = string_values_->getParam("encapsulate");
  512. // Create option definition.
  513. OptionDefinitionPtr def;
  514. // We need to check if user has set encapsulated option space
  515. // name. If so, different constructor will be used.
  516. if (!encapsulates.empty()) {
  517. // Arrays can't be used together with sub-options.
  518. if (array_type) {
  519. isc_throw(DhcpConfigError, "option '" << space << "."
  520. << "name" << "', comprising an array of data"
  521. << " fields may not encapsulate any option space");
  522. } else if (encapsulates == space) {
  523. isc_throw(DhcpConfigError, "option must not encapsulate"
  524. << " an option space it belongs to: '"
  525. << space << "." << name << "' is set to"
  526. << " encapsulate '" << space << "'");
  527. } else {
  528. def.reset(new OptionDefinition(name, code, type,
  529. encapsulates.c_str()));
  530. }
  531. } else {
  532. def.reset(new OptionDefinition(name, code, type, array_type));
  533. }
  534. // The record-types field may carry a list of comma separated names
  535. // of data types that form a record.
  536. std::string record_types = string_values_->getParam("record-types");
  537. // Split the list of record types into tokens.
  538. std::vector<std::string> record_tokens =
  539. isc::util::str::tokens(record_types, ",");
  540. // Iterate over each token and add a record type into
  541. // option definition.
  542. BOOST_FOREACH(std::string record_type, record_tokens) {
  543. try {
  544. boost::trim(record_type);
  545. if (!record_type.empty()) {
  546. def->addRecordField(record_type);
  547. }
  548. } catch (const Exception& ex) {
  549. isc_throw(DhcpConfigError, "invalid record type values"
  550. << " specified for the option definition: "
  551. << ex.what());
  552. }
  553. }
  554. // Check the option definition parameters are valid.
  555. try {
  556. def->validate();
  557. } catch (const isc::Exception& ex) {
  558. isc_throw(DhcpConfigError, "invalid option definition"
  559. << " parameters: " << ex.what());
  560. }
  561. // Option definition has been created successfully.
  562. option_space_name_ = space;
  563. option_definition_ = def;
  564. }
  565. // ******************************** OptionDefListParser ************************
  566. OptionDefListParser::OptionDefListParser(const std::string&,
  567. OptionDefStoragePtr storage) :storage_(storage) {
  568. if (!storage_) {
  569. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  570. << "storage may not be NULL");
  571. }
  572. }
  573. void
  574. OptionDefListParser::build(ConstElementPtr option_def_list) {
  575. // Clear existing items in the storage.
  576. // We are going to replace all of them.
  577. storage_->clearItems();
  578. if (!option_def_list) {
  579. isc_throw(DhcpConfigError, "parser error: a pointer to a list of"
  580. << " option definitions is NULL");
  581. }
  582. BOOST_FOREACH(ConstElementPtr option_def, option_def_list->listValue()) {
  583. boost::shared_ptr<OptionDefParser>
  584. parser(new OptionDefParser("single-option-def", storage_));
  585. parser->build(option_def);
  586. parser->commit();
  587. }
  588. }
  589. void
  590. OptionDefListParser::commit() {
  591. CfgMgr& cfg_mgr = CfgMgr::instance();
  592. cfg_mgr.deleteOptionDefs();
  593. // We need to move option definitions from the temporary
  594. // storage to the storage.
  595. std::list<std::string> space_names =
  596. storage_->getOptionSpaceNames();
  597. BOOST_FOREACH(std::string space_name, space_names) {
  598. BOOST_FOREACH(OptionDefinitionPtr def,
  599. *(storage_->getItems(space_name))) {
  600. // All option definitions should be initialized to non-NULL
  601. // values. The validation is expected to be made by the
  602. // OptionDefParser when creating an option definition.
  603. assert(def);
  604. cfg_mgr.addOptionDef(def, space_name);
  605. }
  606. }
  607. }
  608. //****************************** PoolParser ********************************
  609. PoolParser::PoolParser(const std::string&, PoolStoragePtr pools)
  610. :pools_(pools) {
  611. if (!pools_) {
  612. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  613. << "storage may not be NULL");
  614. }
  615. }
  616. void
  617. PoolParser::build(ConstElementPtr pools_list) {
  618. BOOST_FOREACH(ConstElementPtr text_pool, pools_list->listValue()) {
  619. // That should be a single pool representation. It should contain
  620. // text is form prefix/len or first - last. Note that spaces
  621. // are allowed
  622. string txt = text_pool->stringValue();
  623. // first let's remove any whitespaces
  624. boost::erase_all(txt, " "); // space
  625. boost::erase_all(txt, "\t"); // tabulation
  626. // Is this prefix/len notation?
  627. size_t pos = txt.find("/");
  628. if (pos != string::npos) {
  629. isc::asiolink::IOAddress addr("::");
  630. uint8_t len = 0;
  631. try {
  632. addr = isc::asiolink::IOAddress(txt.substr(0, pos));
  633. // start with the first character after /
  634. string prefix_len = txt.substr(pos + 1);
  635. // It is lexical cast to int and then downcast to uint8_t.
  636. // Direct cast to uint8_t (which is really an unsigned char)
  637. // will result in interpreting the first digit as output
  638. // value and throwing exception if length is written on two
  639. // digits (because there are extra characters left over).
  640. // No checks for values over 128. Range correctness will
  641. // be checked in Pool4 constructor.
  642. len = boost::lexical_cast<int>(prefix_len);
  643. } catch (...) {
  644. isc_throw(DhcpConfigError, "Failed to parse pool "
  645. "definition: " << text_pool->stringValue());
  646. }
  647. PoolPtr pool(poolMaker(addr, len));
  648. local_pools_.push_back(pool);
  649. continue;
  650. }
  651. // Is this min-max notation?
  652. pos = txt.find("-");
  653. if (pos != string::npos) {
  654. // using min-max notation
  655. isc::asiolink::IOAddress min(txt.substr(0,pos));
  656. isc::asiolink::IOAddress max(txt.substr(pos + 1));
  657. PoolPtr pool(poolMaker(min, max));
  658. local_pools_.push_back(pool);
  659. continue;
  660. }
  661. isc_throw(DhcpConfigError, "Failed to parse pool definition:"
  662. << text_pool->stringValue() <<
  663. ". Does not contain - (for min-max) nor / (prefix/len)");
  664. }
  665. }
  666. void
  667. PoolParser::commit() {
  668. if (pools_) {
  669. // local_pools_ holds the values produced by the build function.
  670. // At this point parsing should have completed successfuly so
  671. // we can append new data to the supplied storage.
  672. pools_->insert(pools_->end(), local_pools_.begin(), local_pools_.end());
  673. }
  674. }
  675. //****************************** SubnetConfigParser *************************
  676. SubnetConfigParser::SubnetConfigParser(const std::string&,
  677. ParserContextPtr global_context)
  678. : uint32_values_(new Uint32Storage()), string_values_(new StringStorage()),
  679. pools_(new PoolStorage()), options_(new OptionStorage()),
  680. global_context_(global_context) {
  681. // The first parameter should always be "subnet", but we don't check
  682. // against that here in case some wants to reuse this parser somewhere.
  683. if (!global_context_) {
  684. isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
  685. << "context storage may not be NULL");
  686. }
  687. }
  688. void
  689. SubnetConfigParser::build(ConstElementPtr subnet) {
  690. BOOST_FOREACH(ConfigPair param, subnet->mapValue()) {
  691. ParserPtr parser(createSubnetConfigParser(param.first));
  692. parser->build(param.second);
  693. parsers_.push_back(parser);
  694. }
  695. // In order to create new subnet we need to get the data out
  696. // of the child parsers first. The only way to do it is to
  697. // invoke commit on them because it will make them write
  698. // parsed data into storages we have supplied.
  699. // Note that triggering commits on child parsers does not
  700. // affect global data because we supplied pointers to storages
  701. // local to this object. Thus, even if this method fails
  702. // later on, the configuration remains consistent.
  703. BOOST_FOREACH(ParserPtr parser, parsers_) {
  704. parser->commit();
  705. }
  706. // Create a subnet.
  707. createSubnet();
  708. }
  709. void
  710. SubnetConfigParser::appendSubOptions(const std::string& option_space,
  711. OptionPtr& option) {
  712. // Only non-NULL options are stored in option container.
  713. // If this option pointer is NULL this is a serious error.
  714. assert(option);
  715. OptionDefinitionPtr def;
  716. if (isServerStdOption(option_space, option->getType())) {
  717. def = getServerStdOptionDefinition(option->getType());
  718. // Definitions for some of the standard options hasn't been
  719. // implemented so it is ok to leave here.
  720. if (!def) {
  721. return;
  722. }
  723. } else {
  724. const OptionDefContainerPtr defs =
  725. global_context_->option_defs_->getItems(option_space);
  726. const OptionDefContainerTypeIndex& idx = defs->get<1>();
  727. const OptionDefContainerTypeRange& range =
  728. idx.equal_range(option->getType());
  729. // There is no definition so we have to leave.
  730. if (std::distance(range.first, range.second) == 0) {
  731. return;
  732. }
  733. def = *range.first;
  734. // If the definition exists, it must be non-NULL.
  735. // Otherwise it is a programming error.
  736. assert(def);
  737. }
  738. // We need to get option definition for the particular option space
  739. // and code. This definition holds the information whether our
  740. // option encapsulates any option space.
  741. // Get the encapsulated option space name.
  742. std::string encapsulated_space = def->getEncapsulatedSpace();
  743. // If option space name is empty it means that our option does not
  744. // encapsulate any option space (does not include sub-options).
  745. if (!encapsulated_space.empty()) {
  746. // Get the sub-options that belong to the encapsulated
  747. // option space.
  748. const Subnet::OptionContainerPtr sub_opts =
  749. global_context_->options_->getItems(encapsulated_space);
  750. // Append sub-options to the option.
  751. BOOST_FOREACH(Subnet::OptionDescriptor desc, *sub_opts) {
  752. if (desc.option) {
  753. option->addOption(desc.option);
  754. }
  755. }
  756. }
  757. }
  758. void
  759. SubnetConfigParser::createSubnet() {
  760. std::string subnet_txt;
  761. try {
  762. subnet_txt = string_values_->getParam("subnet");
  763. } catch (const DhcpConfigError &) {
  764. // rethrow with precise error
  765. isc_throw(DhcpConfigError,
  766. "Mandatory subnet definition in subnet missing");
  767. }
  768. // Remove any spaces or tabs.
  769. boost::erase_all(subnet_txt, " ");
  770. boost::erase_all(subnet_txt, "\t");
  771. // The subnet format is prefix/len. We are going to extract
  772. // the prefix portion of a subnet string to create IOAddress
  773. // object from it. IOAddress will be passed to the Subnet's
  774. // constructor later on. In order to extract the prefix we
  775. // need to get all characters preceding "/".
  776. size_t pos = subnet_txt.find("/");
  777. if (pos == string::npos) {
  778. isc_throw(DhcpConfigError,
  779. "Invalid subnet syntax (prefix/len expected):" << subnet_txt);
  780. }
  781. // Try to create the address object. It also validates that
  782. // the address syntax is ok.
  783. isc::asiolink::IOAddress addr(subnet_txt.substr(0, pos));
  784. uint8_t len = boost::lexical_cast<unsigned int>(subnet_txt.substr(pos + 1));
  785. // Call the subclass's method to instantiate the subnet
  786. initSubnet(addr, len);
  787. // Add pools to it.
  788. for (PoolStorage::iterator it = pools_->begin(); it != pools_->end();
  789. ++it) {
  790. subnet_->addPool(*it);
  791. }
  792. // Configure interface, if defined
  793. // Get interface name. If it is defined, then the subnet is available
  794. // directly over specified network interface.
  795. std::string iface;
  796. try {
  797. iface = string_values_->getParam("interface");
  798. } catch (const DhcpConfigError &) {
  799. // iface not mandatory so swallow the exception
  800. }
  801. if (!iface.empty()) {
  802. if (!IfaceMgr::instance().getIface(iface)) {
  803. isc_throw(DhcpConfigError, "Specified interface name " << iface
  804. << " for subnet " << subnet_->toText()
  805. << " is not present" << " in the system.");
  806. }
  807. subnet_->setIface(iface);
  808. }
  809. // We are going to move configured options to the Subnet object.
  810. // Configured options reside in the container where options
  811. // are grouped by space names. Thus we need to get all space names
  812. // and iterate over all options that belong to them.
  813. std::list<std::string> space_names = options_->getOptionSpaceNames();
  814. BOOST_FOREACH(std::string option_space, space_names) {
  815. // Get all options within a particular option space.
  816. BOOST_FOREACH(Subnet::OptionDescriptor desc,
  817. *options_->getItems(option_space)) {
  818. // The pointer should be non-NULL. The validation is expected
  819. // to be performed by the OptionDataParser before adding an
  820. // option descriptor to the container.
  821. assert(desc.option);
  822. // We want to check whether an option with the particular
  823. // option code has been already added. If so, we want
  824. // to issue a warning.
  825. Subnet::OptionDescriptor existing_desc =
  826. subnet_->getOptionDescriptor("option_space",
  827. desc.option->getType());
  828. if (existing_desc.option) {
  829. duplicate_option_warning(desc.option->getType(), addr);
  830. }
  831. // Add sub-options (if any).
  832. appendSubOptions(option_space, desc.option);
  833. // In any case, we add the option to the subnet.
  834. subnet_->addOption(desc.option, false, option_space);
  835. }
  836. }
  837. // Check all global options and add them to the subnet object if
  838. // they have been configured in the global scope. If they have been
  839. // configured in the subnet scope we don't add global option because
  840. // the one configured in the subnet scope always takes precedence.
  841. space_names = global_context_->options_->getOptionSpaceNames();
  842. BOOST_FOREACH(std::string option_space, space_names) {
  843. // Get all global options for the particular option space.
  844. BOOST_FOREACH(Subnet::OptionDescriptor desc,
  845. *(global_context_->options_->getItems(option_space))) {
  846. // The pointer should be non-NULL. The validation is expected
  847. // to be performed by the OptionDataParser before adding an
  848. // option descriptor to the container.
  849. assert(desc.option);
  850. // Check if the particular option has been already added.
  851. // This would mean that it has been configured in the
  852. // subnet scope. Since option values configured in the
  853. // subnet scope take precedence over globally configured
  854. // values we don't add option from the global storage
  855. // if there is one already.
  856. Subnet::OptionDescriptor existing_desc =
  857. subnet_->getOptionDescriptor(option_space,
  858. desc.option->getType());
  859. if (!existing_desc.option) {
  860. // Add sub-options (if any).
  861. appendSubOptions(option_space, desc.option);
  862. subnet_->addOption(desc.option, false, option_space);
  863. }
  864. }
  865. }
  866. }
  867. isc::dhcp::Triplet<uint32_t>
  868. SubnetConfigParser::getParam(const std::string& name) {
  869. uint32_t value = 0;
  870. try {
  871. // look for local value
  872. value = uint32_values_->getParam(name);
  873. } catch (const DhcpConfigError &) {
  874. try {
  875. // no local, use global value
  876. value = global_context_->uint32_values_->getParam(name);
  877. } catch (const DhcpConfigError &) {
  878. isc_throw(DhcpConfigError, "Mandatory parameter " << name
  879. << " missing (no global default and no subnet-"
  880. << "specific value)");
  881. }
  882. }
  883. return (Triplet<uint32_t>(value));
  884. }
  885. }; // namespace dhcp
  886. }; // namespace isc