option_definition.h 39.2 KB
Newer Older
1
// Copyright (C) 2012-2019 Internet Systems Consortium, Inc. ("ISC")
2
//
3 4 5
// 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/.
6

7 8
#ifndef OPTION_DEFINITION_H
#define OPTION_DEFINITION_H
9

Marcin Siodelski's avatar
Marcin Siodelski committed
10
#include <dhcp/option.h>
11
#include <dhcp/option_data_types.h>
12
#include <dhcp/option_space_container.h>
13
#include <cc/stamped_element.h>
14
#include <cc/user_context.h>
15

16 17
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
18
#include <boost/multi_index/ordered_index.hpp>
19 20 21
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/shared_ptr.hpp>
22
#include <map>
23
#include <string>
24 25 26 27

namespace isc {
namespace dhcp {

28 29 30 31 32 33 34 35
/// @brief Exception to be thrown when invalid option value has been
/// specified for a particular option definition.
class InvalidOptionValue : public Exception {
public:
    InvalidOptionValue(const char* file, size_t line, const char* what) :
        isc::Exception(file, line, what) { };
};

36 37 38 39 40 41 42
/// @brief Exception to be thrown when option definition is invalid.
class MalformedOptionDefinition : public Exception {
public:
    MalformedOptionDefinition(const char* file, size_t line, const char* what) :
        isc::Exception(file, line, what) { };
};

43 44 45 46 47 48 49 50
/// @brief Exception to be thrown when the particular option definition
/// duplicates existing option definition.
class DuplicateOptionDefinition : public Exception {
public:
    DuplicateOptionDefinition(const char* file, size_t line, const char* what) :
        isc::Exception(file, line, what) { };
};

51 52 53 54 55 56
/// @brief Forward declaration to OptionDefinition.
class OptionDefinition;

/// @brief Pointer to option definition object.
typedef boost::shared_ptr<OptionDefinition> OptionDefinitionPtr;

57
/// @brief Forward declaration to OptionInt.
58
///
59 60 61 62
/// This forward declaration is needed to access the OptionInt class without
/// having to include the option_int.h header file. It is required because
/// this header includes libdhcp++.h, and including option_int.h would cause
/// circular inclusion between libdhcp++.h, option_definition.h and
63 64
/// option6_int.h.
template<typename T>
65
class OptionInt;
66

67
/// @brief Forward declaration to OptionIntArray.
68
///
69 70 71 72 73
/// This forward declaration is needed to access the OptionIntArray class
/// without having to include the option_int_array.h header file. It is
/// required because this header includes libdhcp++.h, and including
/// option_int_array.h would cause circular inclusion between libdhcp++.h,
/// option_definition.h and option_int_array.h.
74
template<typename T>
75
class OptionIntArray;
76

77
/// @brief Base class representing a DHCP option definition.
78
///
79 80
/// This is a base class representing a DHCP option definition, which describes
/// the format of the option. In particular, it defines:
81 82 83 84 85
/// - option name,
/// - option code,
/// - data fields order and their types,
/// - sub options space that the particular option encapsulates.
///
86 87 88 89
/// The option type specifies the data type(s) which an option conveys.  If
/// this is a single value the option type points to the data type of the
/// value. For example, DHCPv6 option 8 comprises a two-byte option code, a
/// two-byte option length and two-byte field that carries a uint16 value
90
/// (RFC 8415 - http://ietf.org/rfc/rfc8415.txt).  In such a case, the option
91 92 93
/// type is defined as "uint16". Length and string tuples are a length
/// on one (DHCPv4) or two (DHCPv6) bytes followed by a string of
/// the given length.
94 95 96 97 98 99
///
/// When the option has a more complex structure, the option type may be
/// defined as "array", "record" or even "array of records".
///
/// Array types should be used when the option contains multiple contiguous
/// data values of the same type laid. For example, DHCPv6 option 6 includes
100
/// multiple fields holding uint16 codes of requested DHCPv6 options (RFC 8415).
101 102 103
/// Such an option can be represented with this class by setting the option
/// type to "uint16" and the array indicator (array_type) to true.  The number
/// of elements in the array is effectively unlimited (although it is actually
104
/// limited by the maximal DHCPv6 option length).
105 106 107
///
/// Should the option comprise data fields of different types, the "record"
/// option type is used. In such cases the data field types within the record
108
/// are specified using \ref OptionDefinition::addRecordField.
109
///
Andrei Pavel's avatar
Andrei Pavel committed
110
/// When the OptionDefinition object has been successfully created, it can be
111 112 113 114
/// queried to return the appropriate option factory function for the specified
/// specified option format. There are a number of "standard" factory functions
/// that cover well known (common) formats.  If the particular format does not
/// match any common format the generic factory function is returned.
115 116
///
/// The following data type strings are supported:
117
/// - "empty" (option does not contain data fields)
118 119 120 121 122 123 124
/// - "boolean"
/// - "int8"
/// - "int16"
/// - "int32"
/// - "uint8"
/// - "uint16"
/// - "uint32"
125
/// - "ipv4-address" (IPv4 Address)
126 127 128
/// - "ipv6-address" (IPv6 Address)
/// - "ipv6-prefix" (IPv6 variable length prefix)
/// - "psid" (PSID length / value)
129
/// - "string"
130
/// - "fqdn" (fully qualified name)
131
/// - "tuple" (length and string)
132
/// - "record" (set of data fields of different types)
133 134 135
///
/// @todo Extend the comment to describe "generic factories".
/// @todo Extend this class to use custom namespaces.
Marcin Siodelski's avatar
Marcin Siodelski committed
136
/// @todo Extend this class with more factory functions.
137
/// @todo Derive from UserContext without breaking the multi index.
138
class OptionDefinition : public data::StampedElement {
139 140 141
public:

    /// List of fields within the record.
142
    typedef std::vector<OptionDataType> RecordFieldsCollection;
143
    /// Const iterator for record data fields.
144
    typedef std::vector<OptionDataType>::const_iterator RecordFieldsConstIter;
145 146 147 148 149 150

    /// @brief Constructor.
    ///
    /// @param name option name.
    /// @param code option code.
    /// @param type option data type as string.
151
    /// @param array_type array indicator, if true it indicates that the
152
    /// option fields are the array.
153 154 155 156
    explicit OptionDefinition(const std::string& name,
                              const uint16_t code,
                              const std::string& type,
                              const bool array_type = false);
157 158 159 160 161 162

    /// @brief Constructor.
    ///
    /// @param name option name.
    /// @param code option code.
    /// @param type option data type.
163
    /// @param array_type array indicator, if true it indicates that the
164
    /// option fields are the array.
165 166 167 168 169 170 171 172 173
    explicit OptionDefinition(const std::string& name,
                              const uint16_t code,
                              const OptionDataType type,
                              const bool array_type = false);

    /// @brief Constructor.
    ///
    /// This constructor sets the name of the option space that is
    /// encapsulated by this option. The encapsulated option space
174
    /// identifies sub-options that are carried within this option.
175 176 177 178 179 180 181 182 183 184 185 186 187 188
    /// This constructor does not allow to set array indicator
    /// because options comprising an array of data fields must
    /// not be used with sub-options.
    ///
    /// @param name option name.
    /// @param code option code.
    /// @param type option data type given as string.
    /// @param encapsulated_space name of the option space being
    /// encapsulated by this option.
    explicit OptionDefinition(const std::string& name,
                              const uint16_t code,
                              const std::string& type,
                              const char* encapsulated_space);

189 190 191 192 193 194 195 196
    /// @brief Constructor.
    ///
    /// This constructor sets the name of the option space that is
    /// encapsulated by this option. The encapsulated option space
    /// identifies sub-options that are carried within this option.
    /// This constructor does not allow to set array indicator
    /// because options comprising an array of data fields must
    /// not be used with sub-options.
197
    ///
198 199 200 201 202 203 204 205 206 207
    /// @param name option name.
    /// @param code option code.
    /// @param type option data type.
    /// @param encapsulated_space name of the option space being
    /// encapsulated by this option.
    explicit OptionDefinition(const std::string& name,
                              const uint16_t code,
                              const OptionDataType type,
                              const char* encapsulated_space);

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    /// @brief Factory function creating an instance of the @c OptionDefinition.
    ///
    /// This function should be used to create an instance of the option
    /// definition within a hooks library in cases when the library may be
    /// unloaded before the object is destroyed. This ensures that the
    /// ownership of the object by the Kea process is retained.
    ///
    /// @param name option name.
    /// @param code option code.
    /// @param type option data type as string.
    /// @param array_type array indicator, if true it indicates that the
    /// option fields are the array.
    ///
    /// @return Pointer to the @c OptionDefinition instance.
    static OptionDefinitionPtr create(const std::string& name,
                                      const uint16_t code,
                                      const std::string& type,
                                      const bool array_type = false);

    /// @brief Factory function creating an instance of the @c OptionDefinition.
    ///
    /// This function should be used to create an instance of the option
    /// definition within a hooks library in cases when the library may be
    /// unloaded before the object is destroyed. This ensures that the
    /// ownership of the object by the Kea process is retained.
    ///
    /// @param name option name.
    /// @param code option code.
    /// @param type option data type.
    /// @param array_type array indicator, if true it indicates that the
    /// option fields are the array.
    ///
    /// @return Pointer to the @c OptionDefinition instance.
    static OptionDefinitionPtr create(const std::string& name,
                                      const uint16_t code,
                                      const OptionDataType type,
                                      const bool array_type = false);

    /// @brief Factory function creating an instance of the @c OptionDefinition.
    ///
    /// This function should be used to create an instance of the option
    /// definition within a hooks library in cases when the library may be
    /// unloaded before the object is destroyed. This ensures that the
    /// ownership of the object by the Kea process is retained.
    ///
    /// @param name option name.
    /// @param code option code.
    /// @param type option data type given as string.
    /// @param encapsulated_space name of the option space being
    /// encapsulated by this option.
    ///
    /// @return Pointer to the @c OptionDefinition instance.
    static OptionDefinitionPtr create(const std::string& name,
                                      const uint16_t code,
                                      const std::string& type,
                                      const char* encapsulated_space);

    /// @brief Factory function creating an instance of the @c OptionDefinition.
    ///
    /// This function should be used to create an instance of the option
    /// definition within a hooks library in cases when the library may be
    /// unloaded before the object is destroyed. This ensures that the
    /// ownership of the object by the Kea process is retained.
    ///
    /// @param name option name.
    /// @param code option code.
    /// @param type option data type.
    /// @param encapsulated_space name of the option space being
    /// encapsulated by this option.
    ///
    /// @return Pointer to the @c OptionDefinition instance.
    static OptionDefinitionPtr create(const std::string& name,
                                      const uint16_t code,
                                      const OptionDataType type,
                                      const char* encapsulated_space);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

    /// @name Comparison functions and operators.
    ///
    //@{
    /// @brief Check if option definition is equal to other.
    ///
    /// @param other Option definition to compare to.
    ///
    /// @return true if two option definitions are equal, false otherwise.
    bool equals(const OptionDefinition& other) const;

    /// @brief Equality operator.
    ///
    /// @param other Option definition to compare to.
    ///
    /// @return true if two option definitions are equal, false otherwise.
    bool operator==(const OptionDefinition& other) const {
        return (equals(other));
    }

    /// @brief Inequality operator.
    ///
    /// @param other Option definition to compare to.
    ///
    /// @return true if option definitions are not equal, false otherwise.
    bool operator!=(const OptionDefinition& other) const {
        return (!equals(other));
    }
    //@}

313 314 315 316 317 318 319 320 321 322 323 324 325 326
    /// @brief Adds data field to the record.
    ///
    /// @param data_type_name name of the data type for the field.
    ///
    /// @throw isc::InvalidOperation if option type is not set to RECORD_TYPE.
    /// @throw isc::BadValue if specified invalid data type.
    void addRecordField(const std::string& data_type_name);

    /// @brief Adds data field to the record.
    ///
    /// @param data_type data type for the field.
    ///
    /// @throw isc::InvalidOperation if option type is not set to RECORD_TYPE.
    /// @throw isc::BadValue if specified invalid data type.
327
    void addRecordField(const OptionDataType data_type);
328 329 330

    /// @brief Return array type indicator.
    ///
331 332
    /// The method returns the bool value to indicate whether the option is a
    /// a single value or an array of values.
333 334 335 336 337 338 339 340 341
    ///
    /// @return true if option comprises an array of values.
    bool getArrayType() const { return (array_type_); }

    /// @brief Return option code.
    ///
    /// @return option code.
    uint16_t getCode() const { return (code_); }

342 343 344
    /// @brief Return name of the encapsulated option space.
    ///
    /// @return name of the encapsulated option space.
345
    std::string getEncapsulatedSpace() const {
346 347 348
        return (encapsulated_space_);
    }

349 350 351
    /// @brief Return option name.
    ///
    /// @return option name.
352
    std::string getName() const { return (name_); }
353 354 355 356

    /// @brief Return list of record fields.
    ///
    /// @return list of record fields.
357 358 359
    const RecordFieldsCollection& getRecordFields() const {
        return (record_fields_);
    }
360 361 362 363

    /// @brief Return option data type.
    ///
    /// @return option data type.
364
    OptionDataType getType() const { return (type_); };
365

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    /// @brief Returns const pointer to the user context
    data::ConstElementPtr getContext() const {
        return (user_context_.getContext());
    }

    /// @brief Sets user context.
    /// @param ctx user context to be stored.
    void setContext(const data::ConstElementPtr& ctx) {
        user_context_.setContext(ctx);
    }

    /// @brief Merge unparse a user_context object.
    ///
    /// Add user-context to map, but only if defined. Omit if it was not.
    /// Extract comment so it will be pretty-printed first.
    ///
    /// @param map A pointer to map where the user context will be unparsed.
    void contextToElement(data::ElementPtr map) const {
        user_context_.contextToElement(map);
    }

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
    /// @brief Returns option space name.
    ///
    /// Option definitions are associated with option spaces. Typically,
    /// such association is made when the option definition is put into
    /// the @c CfgOptionDef structure. However, in some cases it is also
    /// required to associate option definition with the particular option
    /// space outside of that structure. In particular, when the option
    /// definition is fetched from a database. The database configuration
    /// backend will set option space upon return of the option definition.
    /// In other cases this value won't be set.
    ///
    /// @return Option space name or empty string if option space
    /// name is not set.
    std::string getOptionSpaceName() const {
        return (option_space_name_);
    }

    /// @brief Sets option space name for option definition.
    ///
    /// See @c getOptionSpaceName to learn when option space name is set.
    ///
    /// @param option_space_name New option space name.
    void setOptionSpaceName(const std::string& option_space_name) {
        option_space_name_ = option_space_name;
    }

Marcin Siodelski's avatar
Marcin Siodelski committed
413 414
    /// @brief Check if the option definition is valid.
    ///
415 416 417 418 419 420 421
    /// Note that it is a responsibility of the code that created
    /// the OptionDefinition object to validate that it is valid.
    /// This function will not be called internally anywhere in this
    /// class to verify that the option definition is valid. Using
    /// invalid option definition to create an instance of the
    /// DHCP option leads to undefined behavior.
    ///
422
    /// @throw MalformedOptionDefinition option definition is invalid.
Marcin Siodelski's avatar
Marcin Siodelski committed
423 424
    void validate() const;

425 426 427 428 429 430 431 432 433 434
    /// @brief Check if specified format is IA_NA option format.
    ///
    /// @return true if specified format is IA_NA option format.
    bool haveIA6Format() const;

    /// @brief Check if specified format is IAADDR option format.
    ///
    /// @return true if specified format is IAADDR option format.
    bool haveIAAddr6Format() const;

435 436 437 438 439
    /// @brief Check if specified format is IAPREFIX option format.
    ///
    /// @return true if specified format is IAPREFIX option format.
    bool haveIAPrefix6Format() const;

440 441 442 443 444 445
    /// @brief Check if specified format is OPTION_CLIENT_FQDN option format.
    ///
    /// @return true of specified format is OPTION_CLIENT_FQDN option format,
    /// false otherwise.
    bool haveClientFqdnFormat() const;

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    /// @brief Check if option has format of the DHCPv4 Client FQDN
    /// %Option.
    ///
    /// The encoding of the domain-name carried by the FQDN option is
    /// conditional and is specified in the flags field of the option.
    /// The domain-name can be encoded in the ASCII format or canonical
    /// wire format. The ASCII format is deprecated, therefore canonical
    /// format is selected for the FQDN option definition and this function
    /// returns true if the option definition comprises the domain-name
    /// field encoded in canonical format.
    ///
    /// @return true if option has the format of DHCPv4 Client FQDN
    /// %Option.
    bool haveFqdn4Format() const;

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
    /// @brief Check if the option has format of Vendor-Identifying Vendor
    /// Specific Options.
    ///
    /// @return Always true.
    /// @todo The Vendor-Identifying Vendor-Specific Option has a complex format
    /// which we do not support here. Therefore it is not really possible to
    /// check that the current definition is valid. We may need to add support
    /// for such option format or simply do not check the format for certain
    /// options, e.g. vendor options, IA_NA, IAADDR and always return objects
    /// of the certain type.
    bool haveVendor4Format() const;

    /// @brief Check if option has a format of the Vendor-Specific Information
    /// %Option.
    ///
    /// The Vendor-Specific Information %Option comprises 32-bit enterprise id
    /// and the suboptions.
    ///
    /// @return true if option definition conforms to the format of the
    /// Vendor-Specific Information %Option.
    bool haveVendor6Format() const;

483 484 485 486 487
    /// @brief Check if the option has format of DHCPv4 V-I Vendor Class option.
    ///
    /// @return true if the option has the format of DHCPv4 Vendor Class option.
    bool haveVendorClass4Format() const;

488 489 490 491 492
    /// @brief Check if the option has format of DHCPv6 Vendor Class option.
    ///
    /// @return true if option has the format of DHCPv6 Vendor Class option.
    bool haveVendorClass6Format() const;

493 494 495 496 497 498 499 500 501
    /// @brief Check if option has format of the SLP Service Scope
    /// %Option.
    ///
    /// The scope list in the SLP Service Scope option is optional
    /// (i.e., as the error message in the DHCPv6 Status code option).
    ///
    /// @return true if option has the format of SLP Service Scope %Option.
    bool haveServiceScopeFormat() const;

502 503 504 505 506
    /// @brief Check if the option has format of DHCPv6 Status Code option.
    ///
    /// @return true if option has the format of DHCPv6 Status code option.
    bool haveStatusCodeFormat() const;

Shawn Routhier's avatar
Shawn Routhier committed
507 508 509 510 511
    /// @brief Check if the option has format of OpaqueDataTuples type options.
    ///
    /// @return true if option has the format of OpaqueDataTuples type options.
    bool haveOpaqueDataTuplesFormat() const;

512 513 514
    /// @brief Check if the option has format of CompressedFqdnList options.
    bool haveCompressedFqdnListFormat() const;

515 516 517 518 519 520
    /// @brief Option factory.
    ///
    /// This function creates an instance of DHCP option using
    /// provided chunk of buffer. This function may be used to
    /// create option which is to be sent in the outgoing packet.
    ///
521 522 523 524
    /// @warning calling this function on invalid option definition
    /// yields undefined behavior. Use \ref validate to test that
    /// the option definition is valid.
    ///
525
    /// @param u option universe (V4 or V6).
526 527 528 529 530
    /// @param type option type.
    /// @param begin beginning of the option buffer.
    /// @param end end of the option buffer.
    ///
    /// @return instance of the DHCP option.
531
    /// @throw InvalidOptionValue if data for the option is invalid.
532 533
    OptionPtr optionFactory(Option::Universe u, uint16_t type,
                            OptionBufferConstIter begin,
534
                            OptionBufferConstIter end) const;
535 536 537 538 539 540 541

    /// @brief Option factory.
    ///
    /// This function creates an instance of DHCP option using
    /// whole provided buffer. This function may be used to
    /// create option which is to be sent in the outgoing packet.
    ///
542 543 544 545
    /// @warning calling this function on invalid option definition
    /// yields undefined behavior. Use \ref validate to test that
    /// the option definition is valid.
    ///
546
    /// @param u option universe (V4 or V6).
547 548 549 550
    /// @param type option type.
    /// @param buf option buffer.
    ///
    /// @return instance of the DHCP option.
551
    /// @throw InvalidOptionValue if data for the option is invalid.
552
    OptionPtr optionFactory(Option::Universe u, uint16_t type,
553
                            const OptionBuffer& buf = OptionBuffer()) const;
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568

    /// @brief Option factory.
    ///
    /// This function creates an instance of DHCP option using the vector
    /// of strings which carry data values for option data fields.
    /// The order of values in the vector corresponds to the order of data
    /// fields in the option. The supplied string values are cast to
    /// their actual data types which are determined based on the
    /// option definition. If cast fails due to type mismatch, an exception
    /// is thrown. This factory function can be used to create option
    /// instance when user specified option value in the <b>comma separated
    /// values</b> format in the configuration database. Provided string
    /// must be tokenized into the vector of string values and this vector
    /// can be supplied to this function.
    ///
569 570 571 572
    /// @warning calling this function on invalid option definition
    /// yields undefined behavior. Use \ref validate to test that
    /// the option definition is valid.
    ///
573
    /// @param u option universe (V4 or V6).
574 575 576 577
    /// @param type option type.
    /// @param values a vector of values to be used to set data for an option.
    ///
    /// @return instance of the DHCP option.
578
    /// @throw InvalidOptionValue if data for the option is invalid.
579 580
    OptionPtr optionFactory(Option::Universe u, uint16_t type,
                            const std::vector<std::string>& values) const;
581

582 583 584
    /// @brief Factory to create option with address list.
    ///
    /// @param type option type.
585 586 587 588
    /// @param begin iterator pointing to the beginning of the buffer
    /// with a list of IPv4 addresses.
    /// @param end iterator pointing to the end of the buffer with
    /// a list of IPv4 addresses.
Marcin Siodelski's avatar
Marcin Siodelski committed
589 590 591
    ///
    /// @throw isc::OutOfRange if length of the provided option buffer
    /// is not multiple of IPV4 address length.
592
    static OptionPtr factoryAddrList4(uint16_t type,
593 594
                                      OptionBufferConstIter begin,
                                      OptionBufferConstIter end);
595 596 597 598

    /// @brief Factory to create option with address list.
    ///
    /// @param type option type.
599 600 601 602
    /// @param begin iterator pointing to the beginning of the buffer
    /// with a list of IPv6 addresses.
    /// @param end iterator pointing to the end of the buffer with
    /// a list of IPv6 addresses.
Marcin Siodelski's avatar
Marcin Siodelski committed
603 604 605
    ///
    /// @throw isc::OutOfaRange if length of provided option buffer
    /// is not multiple of IPV6 address length.
606
    static OptionPtr factoryAddrList6(uint16_t type,
607 608
                                      OptionBufferConstIter begin,
                                      OptionBufferConstIter end);
609 610 611 612 613

    /// @brief Empty option factory.
    ///
    /// @param u universe (V6 or V4).
    /// @param type option type.
614
    static OptionPtr factoryEmpty(Option::Universe u, uint16_t type);
615

Marcin Siodelski's avatar
Marcin Siodelski committed
616
    /// @brief Factory to create generic option.
617 618 619
    ///
    /// @param u universe (V6 or V4).
    /// @param type option type.
620 621
    /// @param begin iterator pointing to the beginning of the buffer.
    /// @param end iterator pointing to the end of the buffer.
622
    static OptionPtr factoryGeneric(Option::Universe u, uint16_t type,
623 624
                                    OptionBufferConstIter begin,
                                    OptionBufferConstIter end);
625

626 627 628
    /// @brief Factory for IA-type of option.
    ///
    /// @param type option type.
629 630
    /// @param begin iterator pointing to the beginning of the buffer.
    /// @param end iterator pointing to the end of the buffer.
631 632 633
    ///
    /// @throw isc::OutOfRange if provided option buffer is too short or
    /// too long. Expected size is 12 bytes.
634
    static OptionPtr factoryIA6(uint16_t type,
635 636
                                OptionBufferConstIter begin,
                                OptionBufferConstIter end);
637 638 639 640

    /// @brief Factory for IAADDR-type of option.
    ///
    /// @param type option type.
641 642
    /// @param begin iterator pointing to the beginning of the buffer.
    /// @param end iterator pointing to the end of the buffer.
643 644 645
    ///
    /// @throw isc::OutOfRange if provided option buffer is too short or
    /// too long. Expected size is 24 bytes.
646
    static OptionPtr factoryIAAddr6(uint16_t type,
647 648
                                    OptionBufferConstIter begin,
                                    OptionBufferConstIter end);
649

650 651 652 653 654 655
    /// @brief Factory for IAPREFIX-type of option.
    ///
    /// @param type option type.
    /// @param begin iterator pointing to the beginning of the buffer.
    /// @param end iterator pointing to the end of the buffer.
    ///
Tomek Mrugalski's avatar
Tomek Mrugalski committed
656 657
    /// @throw isc::OutOfRange if provided option buffer is too short.
    /// Expected minimum size is 25 bytes.
658 659 660 661
    static OptionPtr factoryIAPrefix6(uint16_t type,
                                      OptionBufferConstIter begin,
                                      OptionBufferConstIter end);

662 663 664
    /// @brief Factory to create option with tuple list.
    ///
    /// @param u option universe (V4 or V6).
665
    /// @param type option type.
666 667 668 669 670 671 672 673 674 675 676
    /// @param begin iterator pointing to the beginning of the buffer
    /// with a list of tuples.
    /// @param end iterator pointing to the end of the buffer with
    /// a list of tuples.
    ///
    /// @return instance of the DHCP option.
    static OptionPtr factoryOpaqueDataTuples(Option::Universe u,
                                             uint16_t type,
                                             OptionBufferConstIter begin,
                                             OptionBufferConstIter end);

677 678
    /// @brief Factory function to create option with integer value.
    ///
679
    /// @param u universe (V4 or V6).
680
    /// @param type option type.
681 682 683
    /// @param encapsulated_space An option space being encapsulated by the
    /// options created by this factory function. The options which belong to
    /// encapsulated option space are sub options of this option.
684 685
    /// @param begin iterator pointing to the beginning of the buffer.
    /// @param end iterator pointing to the end of the buffer.
Marcin Siodelski's avatar
Marcin Siodelski committed
686 687 688
    /// @tparam T type of the data field (must be one of the uintX_t or intX_t).
    ///
    /// @throw isc::OutOfRange if provided option buffer length is invalid.
689
    template<typename T>
690
    static OptionPtr factoryInteger(Option::Universe u, uint16_t type,
691
                                    const std::string& encapsulated_space,
692
                                    OptionBufferConstIter begin,
693
                                    OptionBufferConstIter end) {
694 695 696
        OptionPtr option(new OptionInt<T>(u, type, 0));
        option->setEncapsulatedSpace(encapsulated_space);
        option->unpack(begin, end);
697 698 699 700 701
        return (option);
    }

    /// @brief Factory function to create option with array of integer values.
    ///
702
    /// @param u universe (V4 or V6).
703
    /// @param type option type.
704 705
    /// @param begin iterator pointing to the beginning of the buffer.
    /// @param end iterator pointing to the end of the buffer.
Marcin Siodelski's avatar
Marcin Siodelski committed
706 707 708
    /// @tparam T type of the data field (must be one of the uintX_t or intX_t).
    ///
    /// @throw isc::OutOfRange if provided option buffer length is invalid.
709
    template<typename T>
710 711
    static OptionPtr factoryIntegerArray(Option::Universe u,
                                         uint16_t type,
712 713
                                         OptionBufferConstIter begin,
                                         OptionBufferConstIter end) {
714
        OptionPtr option(new OptionIntArray<T>(u, type, begin, end));
715 716 717 718 719
        return (option);
    }

private:

720 721 722 723 724 725 726 727 728 729 730 731 732
    /// @brief Factory function to create option with a compressed FQDN list.
    ///
    /// @param u universe (V4 or V6).
    /// @param type option type.
    /// @param begin iterator pointing to the beginning of the buffer.
    /// @param end iterator pointing to the end of the buffer.
    ///
    /// @return instance of the DHCP option where FQDNs are uncompressed.
    /// @throw InvalidOptionValue if data for the option is invalid.
    OptionPtr factoryFqdnList(Option::Universe u,
                              OptionBufferConstIter begin,
                              OptionBufferConstIter end) const;

733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    /// @brief Creates an instance of an option having special format.
    ///
    /// The option with special formats are encapsulated by the dedicated
    /// classes derived from @c Option class. In particular these are:
    /// - IA_NA
    /// - IAADDR
    /// - FQDN
    /// - VIVSO.
    ///
    /// @param u A universe (V4 or V6).
    /// @param begin beginning of the option buffer.
    /// @param end end of the option buffer.
    ///
    /// @return An instance of the option having special format or NULL if
    /// such an option can't be created because an option with the given
    /// option code hasn't got the special format.
    OptionPtr factorySpecialFormatOption(Option::Universe u,
                                         OptionBufferConstIter begin,
751
                                         OptionBufferConstIter end) const;
752

753 754 755 756 757 758 759 760 761
    /// @brief Check if specified option format is a record with 3 fields
    /// where first one is custom, and two others are uint32.
    ///
    /// This is a helper function for functions that detect IA_NA and IAAddr
    /// option formats.
    ///
    /// @param first_type type of the first data field.
    ///
    /// @return true if actual option format matches expected format.
762
    bool haveIAx6Format(const OptionDataType first_type) const;
763

764 765 766
    /// @brief Check if specified type matches option definition type.
    ///
    /// @return true if specified type matches option definition type.
767
    inline bool haveType(const OptionDataType type) const {
768 769 770
        return (type == type_);
    }

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
    /// @brief Converts a string value to a boolean value.
    ///
    /// This function converts the value represented as string to a boolean
    /// value. The following conversions are acceptable:
    /// - "true" => true
    /// - "false" => false
    /// - "1" => true
    /// - "0" => false
    /// The first two conversions are case insensitive, so as conversions from
    /// strings such as "TRUE", "trUE" etc. will be accepted. Note that the
    /// only acceptable integer values, carried as strings are: "0" and "1".
    /// For other values, e.g. "2", "3" etc. an exception will be thrown
    /// during conversion.
    ///
    /// @param value_str Input value.
    ///
    /// @return boolean representation of the string specified as the parameter.
    /// @throw isc::dhcp::BadDataTypeCast if failed to perform the conversion.
    bool convertToBool(const std::string& value_str) const;

791 792 793
    /// @brief Perform lexical cast of the value and validate its range.
    ///
    /// This function performs lexical cast of a string value to integer
794 795
    /// value and checks if the resulting value is within a range of a
    /// target type. The target type should be one of the supported
796
    /// integer types. Hexadecimal input is supported.
797 798
    ///
    /// @param value_str input value given as string.
799
    /// @tparam T target integer type for lexical cast.
800
    ///
801 802
    /// @return Integer value after conversion from the string.
    /// @throw isc::dhcp::BadDataTypeCast if conversion was not successful.
803 804 805 806 807 808 809 810 811 812 813 814 815
    template<typename T>
    T lexicalCastWithRangeCheck(const std::string& value_str) const;

    /// @brief Write the string value into the provided buffer.
    ///
    /// This method writes the given value to the specified buffer.
    /// The provided string value may represent data of different types.
    /// The actual data type is specified with the second argument.
    /// Based on a value of this argument, this function will first
    /// try to cast the string value to the particular data type and
    /// if it is successful it will store the data in the buffer
    /// in a binary format.
    ///
816
    /// @param u option universe (V4 or V6).
817 818 819 820 821
    /// @param value string representation of the value to be written.
    /// @param type the actual data type to be stored.
    /// @param [in, out] buf buffer where the value is to be stored.
    ///
    /// @throw BadDataTypeCast if data write was unsuccessful.
822 823
    void writeToBuffer(Option::Universe u, const std::string& value,
                       const OptionDataType type, OptionBuffer& buf) const;
824

825 826 827 828 829
    /// Option name.
    std::string name_;
    /// Option code.
    uint16_t code_;
    /// Option data type.
830
    OptionDataType type_;
Josh Soref's avatar
Josh Soref committed
831
    /// Indicates whether option is a single value or array.
832
    bool array_type_;
833 834
    /// Name of the space being encapsulated by this option.
    std::string encapsulated_space_;
835 836
    /// Collection of data fields within the record.
    RecordFieldsCollection record_fields_;
837
    /// User context
838
    data::UserContext user_context_;
839 840
    /// Option space name
    std::string option_space_name_;
841 842 843
};


844 845 846 847
/// @brief Multi index container for DHCP option definitions.
///
/// This container allows to search for DHCP option definition
/// using two indexes:
848
/// - sequenced: used to access elements in the order they have
849
/// been added to the container
850
/// - option code: used to search definitions of options
851
/// with a specified option code (aka option type).
852 853
/// Note that this container can hold multiple options with the
/// same code. For this reason, the latter index can be used to
854
/// obtain a range of options for a particular option code.
855
///
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
/// @todo: need an index to search options using option space name
/// once option spaces are implemented.
typedef boost::multi_index_container<
    // Container comprises elements of OptionDefinition type.
    OptionDefinitionPtr,
    // Here we start enumerating various indexes.
    boost::multi_index::indexed_by<
        // Sequenced index allows accessing elements in the same way
        // as elements in std::list. Sequenced is an index #0.
        boost::multi_index::sequenced<>,
        // Start definition of index #1.
        boost::multi_index::hashed_non_unique<
            // Use option type as the index key. The type is held
            // in OptionDefinition object so we have to call
            // OptionDefinition::getCode to retrieve this key
871 872 873
            // for each element. The option code is non-unique so
            // multiple elements with the same option code can
            // be returned by this index.
874 875 876 877 878
            boost::multi_index::const_mem_fun<
                OptionDefinition,
                uint16_t,
                &OptionDefinition::getCode
            >
879 880 881 882 883 884 885 886 887 888 889
        >,
        // Start definition of index #2
        boost::multi_index::hashed_non_unique<
            // Use option name as the index key. This value is
            // returned by the @c OptionDefinition::getName
            // method.
            boost::multi_index::const_mem_fun<
                OptionDefinition,
                std::string,
                &OptionDefinition::getName
            >
890 891 892 893
        >,
        // Start definition of index #3
        boost::multi_index::ordered_non_unique<
            // Use option definition modification time as the index key.
894
            // This value is returned by the BaseStampedElement::getModificationTime
895
            boost::multi_index::const_mem_fun<
896
                data::BaseStampedElement,
897 898 899
                boost::posix_time::ptime,
                &data::StampedElement::getModificationTime
            >
900 901 902 903 904
        >,
        // Start definition of index #4.
        // Use StampedElement::getId as a key.
        boost::multi_index::hashed_non_unique<
            boost::multi_index::tag<OptionIdIndexTag>,
905 906
            boost::multi_index::const_mem_fun<data::BaseStampedElement, uint64_t,
                                              &data::BaseStampedElement::getId>
907 908 909 910
        >
    >
> OptionDefContainer;

911 912 913
/// Pointer to an option definition container.
typedef boost::shared_ptr<OptionDefContainer> OptionDefContainerPtr;

914 915 916
/// Container that holds option definitions for various option spaces.
typedef std::map<std::string, OptionDefContainerPtr> OptionDefContainers;

917
/// Container that holds various vendor option containers
918
typedef std::map<uint32_t, OptionDefContainerPtr> VendorOptionDefContainers;
919

920 921 922 923
/// Type of the index #1 - option type.
typedef OptionDefContainer::nth_index<1>::type OptionDefContainerTypeIndex;
/// Pair of iterators to represent the range of options definitions
///  having the same option type value. The first element in this pair
924
///  represents the beginning of the range, the second element
925 926 927 928
///  represents the end.
typedef std::pair<OptionDefContainerTypeIndex::const_iterator,
                  OptionDefContainerTypeIndex::const_iterator> OptionDefContainerTypeRange;

929 930 931 932 933 934 935 936 937
/// Type of the index #2 - option name.
typedef OptionDefContainer::nth_index<2>::type OptionDefContainerNameIndex;
/// Pair of iterators to represent the range of options definitions
/// having the same option name. The first element in this pair
/// represents the beginning of the range, the second element
/// represents the end.
typedef std::pair<OptionDefContainerNameIndex::const_iterator,
                  OptionDefContainerNameIndex::const_iterator> OptionDefContainerNameRange;

938 939 940 941
typedef OptionSpaceContainer<
    OptionDefContainer, OptionDefinitionPtr, std::string
> OptionDefSpaceContainer;

942

943 944 945
} // namespace isc::dhcp
} // namespace isc

946
#endif // OPTION_DEFINITION_H