1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258 |
- // Copyright (C) 2013-2017 Internet Systems Consortium, Inc. ("ISC")
- //
- // This Source Code Form is subject to the terms of the Mozilla Public
- // License, v. 2.0. If a copy of the MPL was not distributed with this
- // file, You can obtain one at http://mozilla.org/MPL/2.0/.
- #include <config.h>
- #include <dhcp/iface_mgr.h>
- #include <dhcp/libdhcp++.h>
- #include <dhcpsrv/cfgmgr.h>
- #include <dhcpsrv/cfg_option.h>
- #include <dhcpsrv/dhcpsrv_log.h>
- #include <dhcpsrv/parsers/dhcp_parsers.h>
- #include <dhcpsrv/parsers/host_reservation_parser.h>
- #include <dhcpsrv/parsers/host_reservations_list_parser.h>
- #include <dhcpsrv/parsers/option_data_parser.h>
- #include <dhcpsrv/cfg_mac_source.h>
- #include <util/encode/hex.h>
- #include <util/strutil.h>
- #include <boost/algorithm/string.hpp>
- #include <boost/foreach.hpp>
- #include <boost/lexical_cast.hpp>
- #include <boost/scoped_ptr.hpp>
- #include <map>
- #include <string>
- #include <vector>
- using namespace std;
- using namespace isc::asiolink;
- using namespace isc::data;
- using namespace isc::util;
- namespace isc {
- namespace dhcp {
- // **************************** DebugParser *************************
- DebugParser::DebugParser(const std::string& param_name)
- :param_name_(param_name) {
- }
- void
- DebugParser::build(ConstElementPtr new_config) {
- value_ = new_config;
- std::cout << "Build for token: [" << param_name_ << "] = ["
- << value_->str() << "]" << std::endl;
- }
- void
- DebugParser::commit() {
- // Debug message. The whole DebugParser class is used only for parser
- // debugging, and is not used in production code. It is very convenient
- // to keep it around. Please do not turn this cout into logger calls.
- std::cout << "Commit for token: [" << param_name_ << "] = ["
- << value_->str() << "]" << std::endl;
- }
- // **************************** BooleanParser *************************
- template<> void ValueParser<bool>::build(isc::data::ConstElementPtr value) {
- // Invoke common code for all specializations of build().
- buildCommon(value);
- // The Config Manager checks if user specified a
- // valid value for a boolean parameter: true or false.
- // We should have a boolean Element, use value directly
- try {
- value_ = value->boolValue();
- } catch (const isc::data::TypeError &) {
- isc_throw(BadValue, " Wrong value type for " << param_name_
- << " : build called with a non-boolean element "
- << "(" << value->getPosition() << ").");
- }
- }
- // **************************** Uin32Parser *************************
- template<> void ValueParser<uint32_t>::build(ConstElementPtr value) {
- // Invoke common code for all specializations of build().
- buildCommon(value);
- int64_t check;
- string x = value->str();
- try {
- check = boost::lexical_cast<int64_t>(x);
- } catch (const boost::bad_lexical_cast &) {
- isc_throw(BadValue, "Failed to parse value " << value->str()
- << " as unsigned 32-bit integer "
- "(" << value->getPosition() << ").");
- }
- if (check > std::numeric_limits<uint32_t>::max()) {
- isc_throw(BadValue, "Value " << value->str() << " is too large"
- " for unsigned 32-bit integer "
- "(" << value->getPosition() << ").");
- }
- if (check < 0) {
- isc_throw(BadValue, "Value " << value->str() << " is negative."
- << " Only 0 or larger are allowed for unsigned 32-bit integer "
- "(" << value->getPosition() << ").");
- }
- // value is small enough to fit
- value_ = static_cast<uint32_t>(check);
- }
- // **************************** StringParser *************************
- template <> void ValueParser<std::string>::build(ConstElementPtr value) {
- // Invoke common code for all specializations of build().
- buildCommon(value);
- // For strings we need to use stringValue() rather than str().
- // str() returns fully escaped special characters, so
- // single backslash would be misrepresented as "\\".
- if (value->getType() == Element::string) {
- value_ = value->stringValue();
- } else {
- value_ = value->str();
- }
- boost::erase_all(value_, "\"");
- }
- // ******************** MACSourcesListConfigParser *************************
- void
- MACSourcesListConfigParser::parse(CfgMACSource& mac_sources, ConstElementPtr value) {
- CfgIface cfg_iface;
- uint32_t source = 0;
- size_t cnt = 0;
- // By default, there's only one source defined: ANY.
- // If user specified anything, we need to get rid of that default.
- mac_sources.clear();
- BOOST_FOREACH(ConstElementPtr source_elem, value->listValue()) {
- std::string source_str = source_elem->stringValue();
- try {
- source = CfgMACSource::MACSourceFromText(source_str);
- mac_sources.add(source);
- ++cnt;
- } catch (const InvalidParameter& ex) {
- isc_throw(DhcpConfigError, "The mac-sources value '" << source_str
- << "' was specified twice (" << value->getPosition() << ")");
- } catch (const std::exception& ex) {
- isc_throw(DhcpConfigError, "Failed to convert '"
- << source_str << "' to any recognized MAC source:"
- << ex.what() << " (" << value->getPosition() << ")");
- }
- }
- if (!cnt) {
- isc_throw(DhcpConfigError, "If specified, MAC Sources cannot be empty");
- }
- }
- // ******************** ControlSocketParser *************************
- void ControlSocketParser::parse(SrvConfig& srv_cfg, isc::data::ConstElementPtr value) {
- if (!value) {
- isc_throw(DhcpConfigError, "Logic error: specified control-socket is null");
- }
- if (value->getType() != Element::map) {
- isc_throw(DhcpConfigError, "Specified control-socket is expected to be a map"
- ", i.e. a structure defined within { }");
- }
- srv_cfg.setControlSocketInfo(value);
- }
- template<typename SearchKey>
- OptionDefinitionPtr
- OptionDataParser::findOptionDefinition(const std::string& option_space,
- const SearchKey& search_key) const {
- OptionDefinitionPtr def = LibDHCP::getOptionDef(option_space, search_key);
- if (!def) {
- // Check if this is a vendor-option. If it is, get vendor-specific
- // definition.
- uint32_t vendor_id = LibDHCP::optionSpaceToVendorId(option_space);
- if (vendor_id) {
- const Option::Universe u = address_family_ == AF_INET ?
- Option::V4 : Option::V6;
- def = LibDHCP::getVendorOptionDef(u, vendor_id, search_key);
- }
- }
- if (!def) {
- // Check if this is an option specified by a user.
- def = CfgMgr::instance().getStagingCfg()->getCfgOptionDef()
- ->get(option_space, search_key);
- }
- return (def);
- }
- // ******************************** OptionDefParser ****************************
- std::pair<isc::dhcp::OptionDefinitionPtr, std::string>
- OptionDefParser::parse(ConstElementPtr option_def) {
- // Get mandatory parameters.
- std::string name = getString(option_def, "name");
- uint32_t code = getInteger(option_def, "code");
- std::string type = getString(option_def, "type");
- // Get optional parameters. Whoever called this parser, should have
- // called SimpleParser::setDefaults first.
- bool array_type = getBoolean(option_def, "array");
- std::string record_types = getString(option_def, "record-types");
- std::string space = getString(option_def, "space");
- std::string encapsulates = getString(option_def, "encapsulate");
- if (!OptionSpace::validateName(space)) {
- isc_throw(DhcpConfigError, "invalid option space name '"
- << space << "' ("
- << getPosition("space", option_def) << ")");
- }
- // Create option definition.
- OptionDefinitionPtr def;
- // We need to check if user has set encapsulated option space
- // name. If so, different constructor will be used.
- if (!encapsulates.empty()) {
- // Arrays can't be used together with sub-options.
- if (array_type) {
- isc_throw(DhcpConfigError, "option '" << space << "."
- << "name" << "', comprising an array of data"
- << " fields may not encapsulate any option space ("
- << option_def->getPosition() << ")");
- } else if (encapsulates == space) {
- isc_throw(DhcpConfigError, "option must not encapsulate"
- << " an option space it belongs to: '"
- << space << "." << name << "' is set to"
- << " encapsulate '" << space << "' ("
- << option_def->getPosition() << ")");
- } else {
- def.reset(new OptionDefinition(name, code, type,
- encapsulates.c_str()));
- }
- } else {
- def.reset(new OptionDefinition(name, code, type, array_type));
- }
- // Split the list of record types into tokens.
- std::vector<std::string> record_tokens =
- isc::util::str::tokens(record_types, ",");
- // Iterate over each token and add a record type into
- // option definition.
- BOOST_FOREACH(std::string record_type, record_tokens) {
- try {
- boost::trim(record_type);
- if (!record_type.empty()) {
- def->addRecordField(record_type);
- }
- } catch (const Exception& ex) {
- isc_throw(DhcpConfigError, "invalid record type values"
- << " specified for the option definition: "
- << ex.what() << " ("
- << getPosition("record-types", option_def) << ")");
- }
- }
- // Validate the definition.
- try {
- def->validate();
- } catch (const std::exception& ex) {
- isc_throw(DhcpConfigError, ex.what()
- << " (" << option_def->getPosition() << ")");
- }
- // Option definition has been created successfully.
- return make_pair(def, space);
- }
- // ******************************** OptionDefListParser ************************
- void
- OptionDefListParser::parse(CfgOptionDefPtr storage, ConstElementPtr option_def_list) {
- if (!option_def_list) {
- isc_throw(DhcpConfigError, "parser error: a pointer to a list of"
- << " option definitions is NULL ("
- << option_def_list->getPosition() << ")");
- }
- OptionDefParser parser;
- BOOST_FOREACH(ConstElementPtr option_def, option_def_list->listValue()) {
- OptionDefinitionTuple def;
- def = parser.parse(option_def);
- try {
- storage->add(def.first, def.second);
- } catch (const std::exception& ex) {
- // Append position if there is a failure.
- isc_throw(DhcpConfigError, ex.what() << " ("
- << option_def->getPosition() << ")");
- }
- }
- // All definitions have been prepared. Put them as runtime options into
- // the libdhcp++.
- LibDHCP::setRuntimeOptionDefs(storage->getContainer());
- }
- //****************************** RelayInfoParser ********************************
- RelayInfoParser::RelayInfoParser(const Option::Universe& family)
- : family_(family) {
- };
- void
- RelayInfoParser::parse(const isc::dhcp::Subnet::RelayInfoPtr& cfg,
- ConstElementPtr relay_info) {
- // There is only one parameter which is mandatory
- IOAddress ip = getAddress(relay_info, "ip-address");
- // Check if the address family matches.
- if ((ip.isV4() && family_ != Option::V4) ||
- (ip.isV6() && family_ != Option::V6) ) {
- isc_throw(DhcpConfigError, "ip-address field " << ip.toText()
- << " does not have IP address of expected family type: "
- << (family_ == Option::V4 ? "IPv4" : "IPv6")
- << " (" << getPosition("ip-address", relay_info) << ")");
- }
- // Ok, we're done with parsing. Let's store the result in the structure
- // we were given as configuration storage.
- *cfg = isc::dhcp::Subnet::RelayInfo(ip);
- }
- //****************************** PoolParser ********************************
- void
- PoolParser::parse(PoolStoragePtr pools,
- ConstElementPtr pool_structure,
- const uint16_t address_family) {
- ConstElementPtr text_pool = pool_structure->get("pool");
- if (!text_pool) {
- isc_throw(DhcpConfigError, "Mandatory 'pool' entry missing in "
- "definition: (" << pool_structure->getPosition() << ")");
- }
- // That should be a single pool representation. It should contain
- // text is form prefix/len or first - last. Note that spaces
- // are allowed
- string txt = text_pool->stringValue();
- // first let's remove any whitespaces
- boost::erase_all(txt, " "); // space
- boost::erase_all(txt, "\t"); // tabulation
- PoolPtr pool;
- // Is this prefix/len notation?
- size_t pos = txt.find("/");
- if (pos != string::npos) {
- isc::asiolink::IOAddress addr("::");
- uint8_t len = 0;
- try {
- addr = isc::asiolink::IOAddress(txt.substr(0, pos));
- // start with the first character after /
- string prefix_len = txt.substr(pos + 1);
- // It is lexical cast to int and then downcast to uint8_t.
- // Direct cast to uint8_t (which is really an unsigned char)
- // will result in interpreting the first digit as output
- // value and throwing exception if length is written on two
- // digits (because there are extra characters left over).
- // No checks for values over 128. Range correctness will
- // be checked in Pool4 constructor, here we only check
- // the representation fits in an uint8_t as this can't
- // be done by a direct lexical cast as explained...
- int val_len = boost::lexical_cast<int>(prefix_len);
- if ((val_len < std::numeric_limits<uint8_t>::min()) ||
- (val_len > std::numeric_limits<uint8_t>::max())) {
- // This exception will be handled 4 line later!
- isc_throw(OutOfRange, "");
- }
- len = static_cast<uint8_t>(val_len);
- } catch (...) {
- isc_throw(DhcpConfigError, "Failed to parse pool "
- "definition: " << txt << " ("
- << text_pool->getPosition() << ")");
- }
- try {
- pool = poolMaker(addr, len);
- pools->push_back(pool);
- } catch (const std::exception& ex) {
- isc_throw(DhcpConfigError, "Failed to create pool defined by: "
- << txt << " (" << text_pool->getPosition() << ")");
- }
- } else {
- isc::asiolink::IOAddress min("::");
- isc::asiolink::IOAddress max("::");
- // Is this min-max notation?
- pos = txt.find("-");
- if (pos != string::npos) {
- // using min-max notation
- try {
- min = isc::asiolink::IOAddress(txt.substr(0, pos));
- max = isc::asiolink::IOAddress(txt.substr(pos + 1));
- } catch (...) {
- isc_throw(DhcpConfigError, "Failed to parse pool "
- "definition: " << txt << " ("
- << text_pool->getPosition() << ")");
- }
- try {
- pool = poolMaker(min, max);
- pools->push_back(pool);
- } catch (const std::exception& ex) {
- isc_throw(DhcpConfigError, "Failed to create pool defined by: "
- << txt << " (" << text_pool->getPosition() << ")");
- }
- }
- }
- if (!pool) {
- isc_throw(DhcpConfigError, "invalid pool definition: "
- << text_pool->stringValue() <<
- ". There are two acceptable formats <min address-max address>"
- " or <prefix/len> ("
- << text_pool->getPosition() << ")");
- }
- // If there's user-context specified, store it.
- ConstElementPtr user_context = pool_structure->get("user-context");
- if (user_context) {
- if (user_context->getType() != Element::map) {
- isc_throw(isc::dhcp::DhcpConfigError, "User context has to be a map ("
- << user_context->getPosition() << ")");
- }
- pool->setContext(user_context);
- }
- // Parser pool specific options.
- ConstElementPtr option_data = pool_structure->get("option-data");
- if (option_data) {
- try {
- CfgOptionPtr cfg = pool->getCfgOption();
- OptionDataListParser option_parser(address_family);
- option_parser.parse(cfg, option_data);
- } catch (const std::exception& ex) {
- isc_throw(isc::dhcp::DhcpConfigError, ex.what()
- << " (" << option_data->getPosition() << ")");
- }
- }
- }
- //****************************** Pool4Parser *************************
- PoolPtr
- Pool4Parser::poolMaker (IOAddress &addr, uint32_t len, int32_t) {
- return (PoolPtr(new Pool4(addr, len)));
- }
- PoolPtr
- Pool4Parser::poolMaker (IOAddress &min, IOAddress &max, int32_t) {
- return (PoolPtr(new Pool4(min, max)));
- }
- //****************************** Pool4ListParser *************************
- void
- Pools4ListParser::parse(PoolStoragePtr pools, ConstElementPtr pools_list) {
- BOOST_FOREACH(ConstElementPtr pool, pools_list->listValue()) {
- Pool4Parser parser;
- parser.parse(pools, pool, AF_INET);
- }
- }
- //****************************** SubnetConfigParser *************************
- SubnetConfigParser::SubnetConfigParser(uint16_t family)
- : pools_(new PoolStorage()),
- address_family_(family),
- options_(new CfgOption()) {
- string addr = family == AF_INET ? "0.0.0.0" : "::";
- relay_info_.reset(new isc::dhcp::Subnet::RelayInfo(IOAddress(addr)));
- }
- SubnetPtr
- SubnetConfigParser::parse(ConstElementPtr subnet) {
- ConstElementPtr options_params = subnet->get("option-data");
- if (options_params) {
- OptionDataListParser opt_parser(address_family_);
- opt_parser.parse(options_, options_params);
- }
- ConstElementPtr relay_params = subnet->get("relay");
- if (relay_params) {
- Option::Universe u = (address_family_ == AF_INET) ? Option::V4 : Option::V6;
- RelayInfoParser parser(u);
- parser.parse(relay_info_, relay_params);
- }
- // Create a subnet.
- try {
- createSubnet(subnet);
- } catch (const std::exception& ex) {
- isc_throw(DhcpConfigError,
- "subnet configuration failed: " << ex.what());
- }
- return (subnet_);
- }
- Subnet::HRMode
- SubnetConfigParser::hrModeFromText(const std::string& txt) {
- if ( (txt.compare("disabled") == 0) ||
- (txt.compare("off") == 0) ) {
- return (Subnet::HR_DISABLED);
- } else if (txt.compare("out-of-pool") == 0) {
- return (Subnet::HR_OUT_OF_POOL);
- } else if (txt.compare("all") == 0) {
- return (Subnet::HR_ALL);
- } else {
- isc_throw(BadValue, "Can't convert '" << txt
- << "' into any valid reservation-mode values");
- }
- }
- void
- SubnetConfigParser::createSubnet(ConstElementPtr params) {
- std::string subnet_txt;
- try {
- subnet_txt = getString(params, "subnet");
- } catch (const DhcpConfigError &) {
- // rethrow with precise error
- isc_throw(DhcpConfigError,
- "mandatory 'subnet' parameter is missing for a subnet being"
- " configured (" << params->getPosition() << ")");
- }
- // Remove any spaces or tabs.
- boost::erase_all(subnet_txt, " ");
- boost::erase_all(subnet_txt, "\t");
- // The subnet format is prefix/len. We are going to extract
- // the prefix portion of a subnet string to create IOAddress
- // object from it. IOAddress will be passed to the Subnet's
- // constructor later on. In order to extract the prefix we
- // need to get all characters preceding "/".
- size_t pos = subnet_txt.find("/");
- if (pos == string::npos) {
- ConstElementPtr elem = params->get("subnet");
- isc_throw(DhcpConfigError,
- "Invalid subnet syntax (prefix/len expected):" << subnet_txt
- << " (" << elem->getPosition() << ")");
- }
- // Try to create the address object. It also validates that
- // the address syntax is ok.
- isc::asiolink::IOAddress addr(subnet_txt.substr(0, pos));
- uint8_t len = boost::lexical_cast<unsigned int>(subnet_txt.substr(pos + 1));
- // Call the subclass's method to instantiate the subnet
- initSubnet(params, addr, len);
- // Add pools to it.
- for (PoolStorage::iterator it = pools_->begin(); it != pools_->end();
- ++it) {
- try {
- subnet_->addPool(*it);
- } catch (const BadValue& ex) {
- // addPool() can throw BadValue if the pool is overlapping or
- // is out of bounds for the subnet.
- isc_throw(DhcpConfigError,
- ex.what() << " (" << params->getPosition() << ")");
- }
- }
- // Now configure parameters that are common for v4 and v6:
- // Get interface name. If it is defined, then the subnet is available
- // directly over specified network interface.
- std::string iface = getString(params, "interface");
- if (!iface.empty()) {
- if (!IfaceMgr::instance().getIface(iface)) {
- ConstElementPtr error = params->get("interface");
- isc_throw(DhcpConfigError, "Specified network interface name " << iface
- << " for subnet " << subnet_->toText()
- << " is not present in the system ("
- << error->getPosition() << ")");
- }
- subnet_->setIface(iface);
- }
- // Let's set host reservation mode. If not specified, the default value of
- // all will be used.
- try {
- std::string hr_mode = getString(params, "reservation-mode");
- subnet_->setHostReservationMode(hrModeFromText(hr_mode));
- } catch (const BadValue& ex) {
- isc_throw(DhcpConfigError, "Failed to process specified value "
- " of reservation-mode parameter: " << ex.what()
- << "(" << getPosition("reservation-mode", params) << ")");
- }
- // Try setting up client class.
- string client_class = getString(params, "client-class");
- if (!client_class.empty()) {
- subnet_->allowClientClass(client_class);
- }
- // If there's user-context specified, store it.
- ConstElementPtr user_context = params->get("user-context");
- if (user_context) {
- if (user_context->getType() != Element::map) {
- isc_throw(isc::dhcp::DhcpConfigError, "User context has to be a map ("
- << user_context->getPosition() << ")");
- }
- subnet_->setContext(user_context);
- }
- // Here globally defined options were merged to the subnet specific
- // options but this is no longer the case (they have a different
- // and not consecutive priority).
- // Copy options to the subnet configuration.
- options_->copyTo(*subnet_->getCfgOption());
- }
- //****************************** Subnet4ConfigParser *************************
- Subnet4ConfigParser::Subnet4ConfigParser()
- :SubnetConfigParser(AF_INET) {
- }
- Subnet4Ptr
- Subnet4ConfigParser::parse(ConstElementPtr subnet) {
- /// Parse Pools first.
- ConstElementPtr pools = subnet->get("pools");
- if (pools) {
- Pools4ListParser parser;
- parser.parse(pools_, pools);
- }
- SubnetPtr generic = SubnetConfigParser::parse(subnet);
- if (!generic) {
- isc_throw(DhcpConfigError,
- "Failed to create an IPv4 subnet (" <<
- subnet->getPosition() << ")");
- }
- Subnet4Ptr sn4ptr = boost::dynamic_pointer_cast<Subnet4>(subnet_);
- if (!sn4ptr) {
- // If we hit this, it is a programming error.
- isc_throw(Unexpected,
- "Invalid Subnet4 cast in Subnet4ConfigParser::parse");
- }
- // Set relay information if it was parsed
- if (relay_info_) {
- sn4ptr->setRelayInfo(*relay_info_);
- }
- // Parse Host Reservations for this subnet if any.
- ConstElementPtr reservations = subnet->get("reservations");
- if (reservations) {
- HostCollection hosts;
- HostReservationsListParser<HostReservationParser4> parser;
- parser.parse(subnet_->getID(), reservations, hosts);
- for (auto h = hosts.begin(); h != hosts.end(); ++h) {
- CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(*h);
- }
- }
- return (sn4ptr);
- }
- void
- Subnet4ConfigParser::initSubnet(data::ConstElementPtr params,
- asiolink::IOAddress addr, uint8_t len) {
- // The renew-timer and rebind-timer are optional. If not set, the
- // option 58 and 59 will not be sent to a client. In this case the
- // client will use default values based on the valid-lifetime.
- Triplet<uint32_t> t1 = getInteger(params, "renew-timer");
- Triplet<uint32_t> t2 = getInteger(params, "rebind-timer");
- // The valid-lifetime is mandatory. It may be specified for a
- // particular subnet. If not, the global value should be present.
- // If there is no global value, exception is thrown.
- Triplet<uint32_t> valid = getInteger(params, "valid-lifetime");
- // Subnet ID is optional. If it is not supplied the value of 0 is used,
- // which means autogenerate. The value was inserted earlier by calling
- // SimpleParser4::setAllDefaults.
- SubnetID subnet_id = static_cast<SubnetID>(getInteger(params, "id"));
- stringstream s;
- s << addr << "/" << static_cast<int>(len) << " with params: ";
- // t1 and t2 are optional may be not specified.
- if (!t1.unspecified()) {
- s << "t1=" << t1 << ", ";
- }
- if (!t2.unspecified()) {
- s << "t2=" << t2 << ", ";
- }
- s <<"valid-lifetime=" << valid;
- LOG_INFO(dhcpsrv_logger, DHCPSRV_CFGMGR_NEW_SUBNET4).arg(s.str());
- Subnet4Ptr subnet4(new Subnet4(addr, len, t1, t2, valid, subnet_id));
- subnet_ = subnet4;
- // Set the match-client-id value for the subnet. It is always present.
- // If not explicitly specified, the default value was filled in when
- // SimpleParser4::setAllDefaults was called.
- bool match_client_id = getBoolean(params, "match-client-id");
- subnet4->setMatchClientId(match_client_id);
- // Set next-server. The default value is 0.0.0.0. Nevertheless, the
- // user could have messed that up by specifying incorrect value.
- // To avoid using 0.0.0.0, user can specify "".
- string next_server;
- try {
- next_server = getString(params, "next-server");
- if (!next_server.empty()) {
- subnet4->setSiaddr(IOAddress(next_server));
- }
- } catch (...) {
- ConstElementPtr next = params->get("next-server");
- string pos;
- if (next) {
- pos = next->getPosition().str();
- } else {
- pos = params->getPosition().str();
- }
- isc_throw(DhcpConfigError, "invalid parameter next-server : "
- << next_server << "(" << pos << ")");
- }
- // 4o6 specific parameter: 4o6-interface. If not explicitly specified,
- // it will have the default value of "".
- string iface4o6 = getString(params, "4o6-interface");
- if (!iface4o6.empty()) {
- subnet4->get4o6().setIface4o6(iface4o6);
- subnet4->get4o6().enabled(true);
- }
- // 4o6 specific parameter: 4o6-subnet. If not explicitly specified, it
- // will have the default value of "".
- string subnet4o6 = getString(params, "4o6-subnet");
- if (!subnet4o6.empty()) {
- size_t slash = subnet4o6.find("/");
- if (slash == std::string::npos) {
- isc_throw(DhcpConfigError, "Missing / in the 4o6-subnet parameter:"
- << subnet4o6 << ", expected format: prefix6/length");
- }
- string prefix = subnet4o6.substr(0, slash);
- string lenstr = subnet4o6.substr(slash + 1);
- uint8_t len = 128;
- try {
- len = boost::lexical_cast<unsigned int>(lenstr.c_str());
- } catch (const boost::bad_lexical_cast &) {
- isc_throw(DhcpConfigError, "Invalid prefix length specified in "
- "4o6-subnet parameter: " << subnet4o6 << ", expected 0..128 value");
- }
- subnet4->get4o6().setSubnet4o6(IOAddress(prefix), len);
- subnet4->get4o6().enabled(true);
- }
- // Try 4o6 specific parameter: 4o6-interface-id
- std::string ifaceid = getString(params, "4o6-interface-id");
- if (!ifaceid.empty()) {
- OptionBuffer tmp(ifaceid.begin(), ifaceid.end());
- OptionPtr opt(new Option(Option::V6, D6O_INTERFACE_ID, tmp));
- subnet4->get4o6().setInterfaceId(opt);
- subnet4->get4o6().enabled(true);
- }
- /// client-class processing is now generic and handled in the common
- /// code (see isc::data::SubnetConfigParser::createSubnet)
- }
- //**************************** Subnets4ListConfigParser **********************
- size_t
- Subnets4ListConfigParser::parse(SrvConfigPtr cfg, ConstElementPtr subnets_list) {
- size_t cnt = 0;
- BOOST_FOREACH(ConstElementPtr subnet_json, subnets_list->listValue()) {
- Subnet4ConfigParser parser;
- Subnet4Ptr subnet = parser.parse(subnet_json);
- if (subnet) {
- // Adding a subnet to the Configuration Manager may fail if the
- // subnet id is invalid (duplicate). Thus, we catch exceptions
- // here to append a position in the configuration string.
- try {
- cfg->getCfgSubnets4()->add(subnet);
- cnt++;
- } catch (const std::exception& ex) {
- isc_throw(DhcpConfigError, ex.what() << " ("
- << subnet_json->getPosition() << ")");
- }
- }
- }
- return (cnt);
- }
- //**************************** Pool6Parser *********************************
- PoolPtr
- Pool6Parser::poolMaker (IOAddress &addr, uint32_t len, int32_t ptype)
- {
- return (PoolPtr(new Pool6(static_cast<isc::dhcp::Lease::Type>
- (ptype), addr, len)));
- }
- PoolPtr
- Pool6Parser::poolMaker (IOAddress &min, IOAddress &max, int32_t ptype)
- {
- return (PoolPtr(new Pool6(static_cast<isc::dhcp::Lease::Type>
- (ptype), min, max)));
- }
- //**************************** Pool6ListParser ***************************
- void
- Pools6ListParser::parse(PoolStoragePtr pools, ConstElementPtr pools_list) {
- BOOST_FOREACH(ConstElementPtr pool, pools_list->listValue()) {
- Pool6Parser parser;
- parser.parse(pools, pool, AF_INET6);
- }
- }
- //**************************** PdPoolParser ******************************
- PdPoolParser::PdPoolParser() : options_(new CfgOption()) {
- }
- void
- PdPoolParser::parse(PoolStoragePtr pools, ConstElementPtr pd_pool_) {
- std::string addr_str = getString(pd_pool_, "prefix");
- uint8_t prefix_len = getUint8(pd_pool_, "prefix-len");
- uint8_t delegated_len = getUint8(pd_pool_, "delegated-len");
- std::string excluded_prefix_str = "::";
- if (pd_pool_->contains("excluded-prefix")) {
- excluded_prefix_str = getString(pd_pool_, "excluded-prefix");
- }
- uint8_t excluded_prefix_len = 0;
- if (pd_pool_->contains("excluded-prefix-len")) {
- excluded_prefix_len = getUint8(pd_pool_, "excluded-prefix-len");
- }
- ConstElementPtr option_data = pd_pool_->get("option-data");
- if (option_data) {
- OptionDataListParser opts_parser(AF_INET6);
- opts_parser.parse(options_, option_data);
- }
-
- ConstElementPtr user_context = pd_pool_->get("user-context");
- if (user_context) {
- user_context_ = user_context;
- }
- // Check the pool parameters. It will throw an exception if any
- // of the required parameters are invalid.
- try {
- // Attempt to construct the local pool.
- pool_.reset(new Pool6(IOAddress(addr_str),
- prefix_len,
- delegated_len,
- IOAddress(excluded_prefix_str),
- excluded_prefix_len));
- // Merge options specified for a pool into pool configuration.
- options_->copyTo(*pool_->getCfgOption());
- } catch (const std::exception& ex) {
- // Some parameters don't exist or are invalid. Since we are not
- // aware whether they don't exist or are invalid, let's append
- // the position of the pool map element.
- isc_throw(isc::dhcp::DhcpConfigError, ex.what()
- << " (" << pd_pool_->getPosition() << ")");
- }
- if (user_context_) {
- pool_->setContext(user_context_);
- }
- // Add the local pool to the external storage ptr.
- pools->push_back(pool_);
- }
- //**************************** PdPoolsListParser ************************
- void
- PdPoolsListParser::parse(PoolStoragePtr pools, ConstElementPtr pd_pool_list) {
- // Loop through the list of pd pools.
- BOOST_FOREACH(ConstElementPtr pd_pool, pd_pool_list->listValue()) {
- PdPoolParser parser;
- parser.parse(pools, pd_pool);
- }
- }
- //**************************** Subnet6ConfigParser ***********************
- Subnet6ConfigParser::Subnet6ConfigParser()
- :SubnetConfigParser(AF_INET6) {
- }
- Subnet6Ptr
- Subnet6ConfigParser::parse(ConstElementPtr subnet) {
- /// Parse all pools first.
- ConstElementPtr pools = subnet->get("pools");
- if (pools) {
- Pools6ListParser parser;
- parser.parse(pools_, pools);
- }
- ConstElementPtr pd_pools = subnet->get("pd-pools");
- if (pd_pools) {
- PdPoolsListParser parser;
- parser.parse(pools_, pd_pools);
- }
- SubnetPtr generic = SubnetConfigParser::parse(subnet);
- if (!generic) {
- isc_throw(DhcpConfigError,
- "Failed to create an IPv6 subnet (" <<
- subnet->getPosition() << ")");
- }
- Subnet6Ptr sn6ptr = boost::dynamic_pointer_cast<Subnet6>(subnet_);
- if (!sn6ptr) {
- // If we hit this, it is a programming error.
- isc_throw(Unexpected,
- "Invalid Subnet6 cast in Subnet6ConfigParser::parse");
- }
- // Set relay information if it was provided
- if (relay_info_) {
- sn6ptr->setRelayInfo(*relay_info_);
- }
- // Parse Host Reservations for this subnet if any.
- ConstElementPtr reservations = subnet->get("reservations");
- if (reservations) {
- HostCollection hosts;
- HostReservationsListParser<HostReservationParser6> parser;
- parser.parse(subnet_->getID(), reservations, hosts);
- for (auto h = hosts.begin(); h != hosts.end(); ++h) {
- CfgMgr::instance().getStagingCfg()->getCfgHosts()->add(*h);
- }
- }
- return (sn6ptr);
- }
- void
- Subnet6ConfigParser::duplicate_option_warning(uint32_t code,
- asiolink::IOAddress& addr) {
- LOG_WARN(dhcpsrv_logger, DHCPSRV_CFGMGR_OPTION_DUPLICATE)
- .arg(code).arg(addr.toText());
- }
- void
- Subnet6ConfigParser::initSubnet(data::ConstElementPtr params,
- asiolink::IOAddress addr, uint8_t len) {
- // Get all 'time' parameters using inheritance.
- // If the subnet-specific value is defined then use it, else
- // use the global value. The global value must always be
- // present. If it is not, it is an internal error and exception
- // is thrown.
- Triplet<uint32_t> t1 = getInteger(params, "renew-timer");
- Triplet<uint32_t> t2 = getInteger(params, "rebind-timer");
- Triplet<uint32_t> pref = getInteger(params, "preferred-lifetime");
- Triplet<uint32_t> valid = getInteger(params, "valid-lifetime");
- // Subnet ID is optional. If it is not supplied the value of 0 is used,
- // which means autogenerate. The value was inserted earlier by calling
- // SimpleParser6::setAllDefaults.
- SubnetID subnet_id = static_cast<SubnetID>(getInteger(params, "id"));
- // We want to log whether rapid-commit is enabled, so we get this
- // before the actual subnet creation.
- bool rapid_commit = getBoolean(params, "rapid-commit");
- std::ostringstream output;
- output << addr << "/" << static_cast<int>(len)
- << " with params t1=" << t1 << ", t2="
- << t2 << ", preferred-lifetime=" << pref
- << ", valid-lifetime=" << valid
- << ", rapid-commit is " << (rapid_commit ? "enabled" : "disabled");
- LOG_INFO(dhcpsrv_logger, DHCPSRV_CFGMGR_NEW_SUBNET4).arg(output.str());
- // Create a new subnet.
- Subnet6* subnet6 = new Subnet6(addr, len, t1, t2, pref, valid,
- subnet_id);
- subnet_.reset(subnet6);
- // Enable or disable Rapid Commit option support for the subnet.
- subnet6->setRapidCommit(rapid_commit);
- // Get interface-id option content. For now we support string
- // representation only
- std::string ifaceid = getString(params, "interface-id");
- std::string iface = getString(params, "interface");
- // Specifying both interface for locally reachable subnets and
- // interface id for relays is mutually exclusive. Need to test for
- // this condition.
- if (!ifaceid.empty() && !iface.empty()) {
- isc_throw(isc::dhcp::DhcpConfigError,
- "parser error: interface (defined for locally reachable "
- "subnets) and interface-id (defined for subnets reachable"
- " via relays) cannot be defined at the same time for "
- "subnet " << addr << "/" << (int)len << "("
- << params->getPosition() << ")");
- }
- // Configure interface-id for remote interfaces, if defined
- if (!ifaceid.empty()) {
- OptionBuffer tmp(ifaceid.begin(), ifaceid.end());
- OptionPtr opt(new Option(Option::V6, D6O_INTERFACE_ID, tmp));
- subnet6->setInterfaceId(opt);
- }
- /// client-class processing is now generic and handled in the common
- /// code (see isc::data::SubnetConfigParser::createSubnet)
- }
- //**************************** Subnet6ListConfigParser ********************
- size_t
- Subnets6ListConfigParser::parse(SrvConfigPtr cfg, ConstElementPtr subnets_list) {
- size_t cnt = 0;
- BOOST_FOREACH(ConstElementPtr subnet_json, subnets_list->listValue()) {
- Subnet6ConfigParser parser;
- Subnet6Ptr subnet = parser.parse(subnet_json);
- // Adding a subnet to the Configuration Manager may fail if the
- // subnet id is invalid (duplicate). Thus, we catch exceptions
- // here to append a position in the configuration string.
- try {
- cfg->getCfgSubnets6()->add(subnet);
- cnt++;
- } catch (const std::exception& ex) {
- isc_throw(DhcpConfigError, ex.what() << " ("
- << subnet_json->getPosition() << ")");
- }
- }
- return (cnt);
- }
- //**************************** D2ClientConfigParser **********************
- dhcp_ddns::NameChangeProtocol
- D2ClientConfigParser::getProtocol(ConstElementPtr scope,
- const std::string& name) {
- return (getAndConvert<dhcp_ddns::NameChangeProtocol,
- dhcp_ddns::stringToNcrProtocol>
- (scope, name, "NameChangeRequest protocol"));
- }
- dhcp_ddns::NameChangeFormat
- D2ClientConfigParser::getFormat(ConstElementPtr scope,
- const std::string& name) {
- return (getAndConvert<dhcp_ddns::NameChangeFormat,
- dhcp_ddns::stringToNcrFormat>
- (scope, name, "NameChangeRequest format"));
- }
- D2ClientConfig::ReplaceClientNameMode
- D2ClientConfigParser::getMode(ConstElementPtr scope,
- const std::string& name) {
- return (getAndConvert<D2ClientConfig::ReplaceClientNameMode,
- D2ClientConfig::stringToReplaceClientNameMode>
- (scope, name, "ReplaceClientName mode"));
- }
- D2ClientConfigPtr
- D2ClientConfigParser::parse(isc::data::ConstElementPtr client_config) {
- D2ClientConfigPtr new_config;
- // Get all parameters that are needed to create the D2ClientConfig.
- bool enable_updates = getBoolean(client_config, "enable-updates");
- IOAddress server_ip = getAddress(client_config, "server-ip");
- uint32_t server_port = getUint32(client_config, "server-port");
- std::string sender_ip_str = getString(client_config, "sender-ip");
- uint32_t sender_port = getUint32(client_config, "sender-port");
- uint32_t max_queue_size = getUint32(client_config, "max-queue-size");
- dhcp_ddns::NameChangeProtocol ncr_protocol =
- getProtocol(client_config, "ncr-protocol");
- dhcp_ddns::NameChangeFormat ncr_format =
- getFormat(client_config, "ncr-format");
- bool always_include_fqdn =
- getBoolean(client_config, "always-include-fqdn");
- bool override_no_update =
- getBoolean(client_config, "override-no-update");
- bool override_client_update =
- getBoolean(client_config, "override-client-update");
- D2ClientConfig::ReplaceClientNameMode replace_client_name_mode =
- getMode(client_config, "replace-client-name");
- std::string generated_prefix =
- getString(client_config, "generated-prefix");
- // qualifying-suffix is the only parameter which has no default
- std::string qualifying_suffix = "";
- bool found_qualifying_suffix = false;
- if (client_config->contains("qualifying-suffix")) {
- qualifying_suffix = getString(client_config, "qualifying-suffix");
- found_qualifying_suffix = true;
- }
- IOAddress sender_ip(0);
- if (sender_ip_str.empty()) {
- // The default sender IP depends on the server IP family
- sender_ip = (server_ip.isV4() ? IOAddress::IPV4_ZERO_ADDRESS() :
- IOAddress::IPV6_ZERO_ADDRESS());
- } else {
- try {
- sender_ip = IOAddress(sender_ip_str);
- } catch (const std::exception& ex) {
- isc_throw(DhcpConfigError, "invalid address (" << sender_ip_str
- << ") specified for parameter 'sender-ip' ("
- << getPosition("sender-ip", client_config) << ")");
- }
- }
- // Qualifying-suffix is required when updates are enabled
- if (enable_updates && !found_qualifying_suffix) {
- isc_throw(DhcpConfigError,
- "parameter 'qualifying-suffix' is required when "
- "updates are enabled ("
- << client_config->getPosition() << ")");
- }
- // Now we check for logical errors. This repeats what is done in
- // D2ClientConfig::validate(), but doing it here permits us to
- // emit meaningful parameter position info in the error.
- if (ncr_format != dhcp_ddns::FMT_JSON) {
- isc_throw(D2ClientError, "D2ClientConfig error: NCR Format: "
- << dhcp_ddns::ncrFormatToString(ncr_format)
- << " is not supported. ("
- << getPosition("ncr-format", client_config) << ")");
- }
- if (ncr_protocol != dhcp_ddns::NCR_UDP) {
- isc_throw(D2ClientError, "D2ClientConfig error: NCR Protocol: "
- << dhcp_ddns::ncrProtocolToString(ncr_protocol)
- << " is not supported. ("
- << getPosition("ncr-protocol", client_config) << ")");
- }
- if (sender_ip.getFamily() != server_ip.getFamily()) {
- isc_throw(D2ClientError,
- "D2ClientConfig error: address family mismatch: "
- << "server-ip: " << server_ip.toText()
- << " is: " << (server_ip.isV4() ? "IPv4" : "IPv6")
- << " while sender-ip: " << sender_ip.toText()
- << " is: " << (sender_ip.isV4() ? "IPv4" : "IPv6")
- << " (" << getPosition("sender-ip", client_config) << ")");
- }
- if (server_ip == sender_ip && server_port == sender_port) {
- isc_throw(D2ClientError,
- "D2ClientConfig error: server and sender cannot"
- " share the exact same IP address/port: "
- << server_ip.toText() << "/" << server_port
- << " (" << getPosition("sender-ip", client_config) << ")");
- }
- try {
- // Attempt to create the new client config.
- new_config.reset(new D2ClientConfig(enable_updates,
- server_ip,
- server_port,
- sender_ip,
- sender_port,
- max_queue_size,
- ncr_protocol,
- ncr_format,
- always_include_fqdn,
- override_no_update,
- override_client_update,
- replace_client_name_mode,
- generated_prefix,
- qualifying_suffix));
- } catch (const std::exception& ex) {
- isc_throw(DhcpConfigError, ex.what() << " ("
- << client_config->getPosition() << ")");
- }
- return(new_config);
- }
- /// @brief This table defines default values for D2 client configuration
- const SimpleDefaults D2ClientConfigParser::D2_CLIENT_CONFIG_DEFAULTS = {
- // enable-updates is unconditionally required
- { "server-ip", Element::string, "127.0.0.1" },
- { "server-port", Element::integer, "53001" },
- // default sender-ip depends on server-ip family, so we leave default blank
- // parser knows to use the appropriate ZERO address based on server-ip
- { "sender-ip", Element::string, "" },
- { "sender-port", Element::integer, "0" },
- { "max-queue-size", Element::integer, "1024" },
- { "ncr-protocol", Element::string, "UDP" },
- { "ncr-format", Element::string, "JSON" },
- { "always-include-fqdn", Element::boolean, "false" },
- { "override-no-update", Element::boolean, "false" },
- { "override-client-update", Element::boolean, "false" },
- { "replace-client-name", Element::string, "never" },
- { "generated-prefix", Element::string, "myhost" }
- // qualifying-suffix has no default
- };
- size_t
- D2ClientConfigParser::setAllDefaults(isc::data::ConstElementPtr d2_config) {
- ElementPtr mutable_d2 = boost::const_pointer_cast<Element>(d2_config);
- return (SimpleParser::setDefaults(mutable_d2, D2_CLIENT_CONFIG_DEFAULTS));
- }
- }; // namespace dhcp
- }; // namespace isc
|