Kea 2.5.8
option_data_parser.cc
Go to the documentation of this file.
1// Copyright (C) 2017-2024 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#include <config.h>
8
10#include <dhcp/dhcp4.h>
11#include <dhcp/libdhcp++.h>
13#include <dhcp/option_space.h>
14#include <dhcpsrv/cfgmgr.h>
18#include <util/encode/encode.h>
19#include <util/str.h>
20#include <boost/make_shared.hpp>
21#include <limits>
22#include <vector>
23
24using namespace isc::data;
25using namespace isc::util;
26
27namespace isc {
28namespace dhcp {
29
30// **************************** OptionDataParser *************************
31
32OptionDataParser::OptionDataParser(const uint16_t address_family,
33 CfgOptionDefPtr cfg_option_def)
34 : address_family_(address_family), cfg_option_def_(cfg_option_def) {
35}
36
37std::pair<OptionDescriptor, std::string>
39
40 // Check parameters.
41 if (address_family_ == AF_INET) {
43 } else {
45 }
46
47 // Try to create the option instance.
48 std::pair<OptionDescriptor, std::string> opt = createOption(single_option);
49
50 if (!opt.first.option_) {
51 // Should never happen (@todo: update message)
53 "parser logic error: no option has been configured and"
54 " thus there is nothing to commit. Has build() been called?");
55 }
56
57 return (opt);
58}
59
62 uint32_t code;
63 try {
64 code = getInteger(parent, "code");
65
66 } catch (const std::exception&) {
67 // The code parameter was not found. Return an unspecified
68 // value.
69 return (Optional<uint32_t>());
70 }
71
72 if (address_family_ == AF_INET &&
73 code > std::numeric_limits<uint8_t>::max()) {
74 isc_throw(DhcpConfigError, "invalid option code '" << code
75 << "', it must not be greater than '"
76 << static_cast<int>(std::numeric_limits<uint8_t>::max())
77 << "' (" << getPosition("code", parent)
78 << ")");
79
80 } else if (address_family_ == AF_INET6 &&
81 code > std::numeric_limits<uint16_t>::max()) {
82 isc_throw(DhcpConfigError, "invalid option code '" << code
83 << "', it must not exceed '"
84 << std::numeric_limits<uint16_t>::max()
85 << "' (" << getPosition("code", parent)
86 << ")");
87
88 }
89
90 return (Optional<uint32_t>(code));
91}
92
95 std::string name;
96 try {
97 name = getString(parent, "name");
98
99 } catch (...) {
100 return (Optional<std::string>());
101 }
102
103 if (name.find(" ") != std::string::npos) {
104 isc_throw(DhcpConfigError, "invalid option name '" << name
105 << "', space character is not allowed ("
106 << getPosition("name", parent) << ")");
107 }
108
109 return (Optional<std::string>(name));
110}
111
114 std::string data;
115 try {
116 data = getString(parent, "data");
117
118 } catch (...) {
119 // The "data" parameter was not found. Return an empty value.
120 return (Optional<std::string>());
121 }
122
123 return (Optional<std::string>(data));
124}
125
128 bool csv_format = true;
129 try {
130 csv_format = getBoolean(parent, "csv-format");
131
132 } catch (...) {
133 return (Optional<bool>());
134 }
135
136 return (Optional<bool>(csv_format));
137}
138
139std::string
141 std::string space = address_family_ == AF_INET ?
143 try {
144 space = getString(parent, "space");
145
146 } catch (...) {
147 return (space);
148 }
149
150 try {
151 if (!OptionSpace::validateName(space)) {
152 isc_throw(DhcpConfigError, "invalid option space name '"
153 << space << "'");
154 }
155
156 if ((space == DHCP4_OPTION_SPACE) && (address_family_ == AF_INET6)) {
158 << "' option space name is reserved for DHCPv4 server");
159
160 } else if ((space == DHCP6_OPTION_SPACE) &&
161 (address_family_ == AF_INET)) {
163 << "' option space name is reserved for DHCPv6 server");
164 }
165
166 } catch (const std::exception& ex) {
167 // Append position of the option space parameter.
168 isc_throw(DhcpConfigError, ex.what() << " ("
169 << getPosition("space", parent) << ")");
170 }
171
172 return (space);
173}
174
177 bool persist = false;
178 try {
179 persist = getBoolean(parent, "always-send");
180
181 } catch (...) {
182 return (Optional<bool>());
183 }
184
185 return (Optional<bool>(persist));
186}
187
190 bool cancel = false;
191 try {
192 cancel = getBoolean(parent, "never-send");
193
194 } catch (...) {
195 return (Optional<bool>());
196 }
197
198 return (Optional<bool>(cancel));
199}
200
202OptionDataParser::findOptionDefinition(const std::string& option_space,
203 const Optional<uint32_t>& option_code,
204 const Optional<std::string>& option_name) const {
206 if (cfg_option_def_) {
207 // Check if the definition was given in the constructor
208 if (option_code.unspecified()) {
209 def = cfg_option_def_->get(option_space, option_name);
210 } else {
211 def = cfg_option_def_->get(option_space, option_code);
212 }
213 }
214
215 if (!def) {
216 // Check if this is a standard option.
217 if (option_code.unspecified()) {
218 def = LibDHCP::getOptionDef(option_space, option_name);
219 } else {
220 def = LibDHCP::getOptionDef(option_space, option_code);
221 }
222 }
223
224 if (!def) {
225 // Check if this is a vendor-option. If it is, get vendor-specific
226 // definition.
227 uint32_t vendor_id = LibDHCP::optionSpaceToVendorId(option_space);
228 if (vendor_id) {
229 const Option::Universe u = address_family_ == AF_INET ?
231 if (option_code.unspecified()) {
232 def = LibDHCP::getVendorOptionDef(u, vendor_id, option_name);
233 } else {
234 def = LibDHCP::getVendorOptionDef(u, vendor_id, option_code);
235 }
236 }
237 }
238
239 if (!def) {
240 // Check if this is an option specified by a user. We used to
241 // check that in the staging configuration, but when the configuration
242 // changes are caused by a command the staging configuration doesn't
243 // exist. What is always available is the container holding runtime
244 // option definitions in LibDHCP. It holds option definitions from
245 // the staging configuration in case of the full reconfiguration or
246 // the definitions from the current configuration in case there is
247 // no staging configuration (after configuration commit). In other
248 // words, runtime options are always the ones that we need here.
249 if (option_code.unspecified()) {
250 def = LibDHCP::getRuntimeOptionDef(option_space, option_name);
251 } else {
252 def = LibDHCP::getRuntimeOptionDef(option_space, option_code);
253 }
254 }
255
256 if (!def) {
257 // Finish by last resort definitions.
258 if (option_code.unspecified()) {
259 def = LibDHCP::getLastResortOptionDef(option_space, option_name);
260 } else {
261 def = LibDHCP::getLastResortOptionDef(option_space, option_code);
262 }
263 }
264
265 return (def);
266}
267
268std::pair<OptionDescriptor, std::string>
270 const Option::Universe universe = address_family_ == AF_INET ?
272
273 Optional<uint32_t> code_param = extractCode(option_data);
274 Optional<std::string> name_param = extractName(option_data);
275 Optional<bool> csv_format_param = extractCSVFormat(option_data);
276 Optional<bool> persist_param = extractPersistent(option_data);
277 Optional<bool> cancel_param = extractCancelled(option_data);
278 Optional<std::string> data_param = extractData(option_data);
279 std::string space_param = extractSpace(option_data);
280 ConstElementPtr user_context = option_data->get("user-context");
281
282 // Require that option code or option name is specified.
283 if (code_param.unspecified() && name_param.unspecified()) {
284 isc_throw(DhcpConfigError, "option data configuration requires one of"
285 " 'code' or 'name' parameters to be specified"
286 << " (" << option_data->getPosition() << ")");
287 }
288
289 // Try to find a corresponding option definition using option code or
290 // option name.
291 OptionDefinitionPtr def = findOptionDefinition(space_param, code_param, name_param);
292
293 // If there is no definition, the user must not explicitly enable the
294 // use of csv-format.
295 if (!def) {
296 // If explicitly requested that the CSV format is to be used,
297 // the option definition is a must.
298 if (!csv_format_param.unspecified() && csv_format_param) {
299 isc_throw(DhcpConfigError, "definition for the option '"
300 << space_param << "." << name_param
301 << "' having code '" << code_param
302 << "' does not exist ("
303 << getPosition("name", option_data)
304 << ")");
305
306 // If there is no option definition and the option code is not specified
307 // we have no means to find the option code.
308 } else if (!name_param.unspecified() && code_param.unspecified()) {
309 isc_throw(DhcpConfigError, "definition for the option '"
310 << space_param << "." << name_param
311 << "' does not exist ("
312 << getPosition("name", option_data)
313 << ")");
314 }
315 } else {
316 // Option name is specified it should match the name in the definition.
317 if (!name_param.unspecified() && (def->getName() != name_param.get())) {
318 isc_throw(DhcpConfigError, "specified option name '"
319 << name_param << "' does not match the "
320 << "option definition: '" << space_param
321 << "." << def->getName() << "' ("
322 << getPosition("name", option_data)
323 << ")");
324 }
325 }
326
327 // No data and cancelled is a supported special case.
328 if (!cancel_param.unspecified() && cancel_param &&
329 data_param.unspecified()) {
330 uint16_t code;
331 if (def) {
332 code = def->getCode();
333 } else {
334 code = static_cast<uint16_t>(code_param);
335 }
336 OptionPtr option(new Option(universe, code));
337 bool persistent = !persist_param.unspecified() && persist_param;
338 OptionDescriptor desc(option, persistent, true, "", user_context);
339 return (make_pair(desc, space_param));
340 }
341
342 // Transform string of hexadecimal digits into binary format.
343 std::vector<uint8_t> binary;
344 std::vector<std::string> data_tokens;
345
346 // If the definition is available and csv-format hasn't been explicitly
347 // disabled, we will parse the data as comma separated values.
348 if (def && (csv_format_param.unspecified() || csv_format_param)) {
349 // If the option data is specified as a string of comma
350 // separated values then we need to split this string into
351 // individual values - each value will be used to initialize
352 // one data field of an option.
353 // It is the only usage of the escape option: this allows
354 // to embed commas in individual values and to return
355 // for instance a string value with embedded commas.
356 data_tokens = isc::util::str::tokens(data_param, ",", true);
357
358 } else {
359 // Try to convert the values in quotes into a vector of ASCII codes.
360 // If the identifier lacks opening and closing quote, this will return
361 // an empty value, in which case we'll try to decode it as a string of
362 // hexadecimal digits.
363 try {
364 binary = util::str::quotedStringToBinary(data_param);
365 if (binary.empty()) {
366 util::str::decodeFormattedHexString(data_param, binary);
367 }
368 } catch (...) {
369 isc_throw(DhcpConfigError, "option data is not a valid"
370 << " string of hexadecimal digits: " << data_param
371 << " ("
372 << getPosition("data", option_data)
373 << ")");
374 }
375 }
376
377 OptionDescriptor desc(false, false);
378
379 if (!def) {
380 // @todo We have a limited set of option definitions initialized at
381 // the moment. In the future we want to initialize option definitions
382 // for all options. Consequently an error will be issued if an option
383 // definition does not exist for a particular option code. For now it is
384 // ok to create generic option if definition does not exist.
385 OptionPtr option(new Option(universe, static_cast<uint16_t>(code_param),
386 binary));
387
388 desc.option_ = option;
389 desc.persistent_ = !persist_param.unspecified() && persist_param;
390 desc.cancelled_ = !cancel_param.unspecified() && cancel_param;
391 } else {
392 // Option definition has been found so let's use it to create
393 // an instance of our option.
394 try {
395 bool use_csv = csv_format_param.unspecified() || csv_format_param;
396 OptionPtr option = use_csv ?
397 def->optionFactory(universe, def->getCode(), data_tokens) :
398 def->optionFactory(universe, def->getCode(), binary);
399 desc.option_ = option;
400 desc.persistent_ = !persist_param.unspecified() && persist_param;
401 desc.cancelled_ = !cancel_param.unspecified() && cancel_param;
402 if (use_csv) {
403 desc.formatted_value_ = data_param;
404 }
405 } catch (const isc::Exception& ex) {
406 isc_throw(DhcpConfigError, "option data does not match"
407 << " option definition (space: " << space_param
408 << ", code: " << def->getCode() << "): "
409 << ex.what() << " ("
410 << getPosition("data", option_data)
411 << ")");
412 }
413 }
414
415 // Check PAD and END in (and only in) dhcp4 space.
416 if (space_param == DHCP4_OPTION_SPACE) {
417 if (desc.option_->getType() == DHO_PAD) {
418 isc_throw(DhcpConfigError, "invalid option code '0': "
419 << "reserved for PAD ("
420 << option_data->getPosition() << ")");
421 } else if (desc.option_->getType() == DHO_END) {
422 isc_throw(DhcpConfigError, "invalid option code '255': "
423 << "reserved for END ("
424 << option_data->getPosition() << ")");
425 }
426 }
427
428 // For dhcp6 space the value 0 is reserved.
429 if (space_param == DHCP6_OPTION_SPACE) {
430 if (desc.option_->getType() == 0) {
431 isc_throw(DhcpConfigError, "invalid option code '0': "
432 << "reserved value ("
433 << option_data->getPosition() << ")");
434 }
435 }
436
437
438 // Add user context
439 if (user_context) {
440 desc.setContext(user_context);
441 }
442
443 // All went good, so we can set the option space name.
444 return (make_pair(desc, space_param));
445}
446
447// **************************** OptionDataListParser *************************
449 //const CfgOptionPtr& cfg,
450 const uint16_t address_family,
451 CfgOptionDefPtr cfg_option_def)
452 : address_family_(address_family), cfg_option_def_(cfg_option_def) {
453}
454
455
457 isc::data::ConstElementPtr option_data_list,
458 bool encapsulate) {
459 auto option_parser = createOptionDataParser();
460 for (auto const& data : option_data_list->listValue()) {
461 std::pair<OptionDescriptor, std::string> option =
462 option_parser->parse(data);
463 // Use the option description to keep the formatted value
464 cfg->add(option.first, option.second);
465 if (encapsulate) {
466 cfg->encapsulate();
467 }
468 }
469}
470
471boost::shared_ptr<OptionDataParser>
473 auto parser = boost::make_shared<OptionDataParser>(address_family_, cfg_option_def_);
474 return (parser);
475}
476
477} // end of namespace isc::dhcp
478} // end of namespace isc
This is a base class for exceptions thrown from the DNS library module.
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
A generic exception that is thrown if a function is called in a prohibited way.
static void checkKeywords(const SimpleKeywords &keywords, isc::data::ConstElementPtr scope)
Checks acceptable keywords with their expected type.
static const data::Element::Position & getPosition(const std::string &name, const data::ConstElementPtr parent)
Utility method that returns position of an element.
static std::string getString(isc::data::ConstElementPtr scope, const std::string &name)
Returns a string parameter from a scope.
static bool getBoolean(isc::data::ConstElementPtr scope, const std::string &name)
Returns a boolean parameter from a scope.
static int64_t getInteger(isc::data::ConstElementPtr scope, const std::string &name)
Returns an integer parameter from a scope.
To be removed. Please use ConfigError instead.
static OptionDefinitionPtr getOptionDef(const std::string &space, const uint16_t code)
Return the first option definition matching a particular option code.
Definition: libdhcp++.cc:126
static OptionDefinitionPtr getVendorOptionDef(const Option::Universe u, const uint32_t vendor_id, const uint16_t code)
Returns vendor option definition for a given vendor-id and code.
Definition: libdhcp++.cc:168
static uint32_t optionSpaceToVendorId(const std::string &option_space)
Converts option space name to vendor id.
Definition: libdhcp++.cc:1298
static OptionDefinitionPtr getRuntimeOptionDef(const std::string &space, const uint16_t code)
Returns runtime (non-standard) option definition by space and option code.
Definition: libdhcp++.cc:189
static OptionDefinitionPtr getLastResortOptionDef(const std::string &space, const uint16_t code)
Returns last resort option definition by space and option code.
Definition: libdhcp++.cc:247
CfgOptionDefPtr cfg_option_def_
Config option definitions.
virtual boost::shared_ptr< OptionDataParser > createOptionDataParser() const
Returns an instance of the OptionDataListParser to be used in parsing options.
void parse(const CfgOptionPtr &cfg, isc::data::ConstElementPtr option_data_list, bool encapsulate=true)
Parses a list of options, instantiates them and stores in cfg.
OptionDataListParser(const uint16_t address_family, CfgOptionDefPtr cfg_option_def=CfgOptionDefPtr())
Constructor.
uint16_t address_family_
Address family: AF_INET or AF_INET6.
util::Optional< std::string > extractData(data::ConstElementPtr parent) const
Retrieves option data as a string.
std::pair< OptionDescriptor, std::string > parse(isc::data::ConstElementPtr single_option)
Parses ElementPtr containing option definition.
uint16_t address_family_
Address family: AF_INET or AF_INET6.
std::string extractSpace(data::ConstElementPtr parent) const
Retrieves option space name.
util::Optional< bool > extractPersistent(data::ConstElementPtr parent) const
Retrieves persistent/always-send parameter as an optional value.
std::pair< OptionDescriptor, std::string > createOption(isc::data::ConstElementPtr option_data)
Create option instance.
util::Optional< bool > extractCSVFormat(data::ConstElementPtr parent) const
Retrieves csv-format parameter as an optional value.
util::Optional< uint32_t > extractCode(data::ConstElementPtr parent) const
Retrieves parsed option code as an optional value.
virtual OptionDefinitionPtr findOptionDefinition(const std::string &option_space, const util::Optional< uint32_t > &option_code, const util::Optional< std::string > &option_name) const
Finds an option definition within an option space.
CfgOptionDefPtr cfg_option_def_
Config option definitions.
util::Optional< std::string > extractName(data::ConstElementPtr parent) const
Retrieves parsed option name as an optional value.
util::Optional< bool > extractCancelled(data::ConstElementPtr parent) const
Retrieves cancelled/never-send parameter as an optional value.
OptionDataParser(const uint16_t address_family, CfgOptionDefPtr cfg_option_def=CfgOptionDefPtr())
Constructor.
Option descriptor.
Definition: cfg_option.h:47
OptionPtr option_
Option instance.
Definition: cfg_option.h:50
bool cancelled_
Cancelled flag.
Definition: cfg_option.h:64
std::string formatted_value_
Option value in textual (CSV) format.
Definition: cfg_option.h:79
bool persistent_
Persistence flag.
Definition: cfg_option.h:56
static bool validateName(const std::string &name)
Checks that the provided option space name is valid.
Definition: option_space.cc:26
Universe
defines option universe DHCPv4 or DHCPv6
Definition: option.h:83
static const isc::data::SimpleKeywords OPTION4_PARAMETERS
This table defines all option parameters.
static const isc::data::SimpleKeywords OPTION6_PARAMETERS
This table defines all option parameters.
A template representing an optional value.
Definition: optional.h:36
T get() const
Retrieves the encapsulated value.
Definition: optional.h:114
void unspecified(bool unspecified)
Modifies the flag that indicates whether the value is specified or unspecified.
Definition: optional.h:136
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
boost::shared_ptr< const Element > ConstElementPtr
Definition: data.h:29
boost::shared_ptr< CfgOption > CfgOptionPtr
Non-const pointer.
Definition: cfg_option.h:803
@ DHO_END
Definition: dhcp4.h:230
@ DHO_PAD
Definition: dhcp4.h:69
boost::shared_ptr< CfgOptionDef > CfgOptionDefPtr
Non-const pointer.
boost::shared_ptr< OptionDefinition > OptionDefinitionPtr
Pointer to option definition object.
boost::shared_ptr< Option > OptionPtr
Definition: option.h:37
void decodeFormattedHexString(const string &hex_string, vector< uint8_t > &binary)
Converts a formatted string of hexadecimal digits into a vector.
Definition: str.cc:212
vector< string > tokens(const string &text, const string &delim, bool escape)
Split string into tokens.
Definition: str.cc:52
vector< uint8_t > quotedStringToBinary(const string &quoted_string)
Converts a string in quotes into vector.
Definition: str.cc:139
Defines the logger used by the top-level component of kea-lfc.
#define DHCP4_OPTION_SPACE
global std option spaces
#define DHCP6_OPTION_SPACE
void setContext(const data::ConstElementPtr &ctx)
Sets user context.
Definition: user_context.h:30