dhcp_parsers.h 41 KB
Newer Older
1
// Copyright (C) 2013-2014 Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#ifndef DHCP_PARSERS_H
#define DHCP_PARSERS_H

18
#include <asiolink/io_address.h>
19 20
#include <cc/data.h>
#include <dhcp/option_definition.h>
21
#include <dhcpsrv/d2_client_cfg.h>
22 23 24 25 26
#include <dhcpsrv/dhcp_config_parser.h>
#include <dhcpsrv/option_space_container.h>
#include <dhcpsrv/subnet.h>
#include <exceptions/exceptions.h>

27 28
#include <boost/shared_ptr.hpp>

29 30 31 32 33 34 35 36 37
#include <stdint.h>
#include <string>
#include <vector>

namespace isc {
namespace dhcp {

/// @brief Storage for option definitions.
typedef OptionSpaceContainer<OptionDefContainer,
38
    OptionDefinitionPtr, std::string> OptionDefStorage;
39
/// @brief Shared pointer to option definitions storage.
40 41
typedef boost::shared_ptr<OptionDefStorage> OptionDefStoragePtr;

42 43 44
/// Collection of containers holding option spaces. Each container within
/// a particular option space holds so-called option descriptors.
typedef OptionSpaceContainer<Subnet::OptionContainer,
45
    Subnet::OptionDescriptor, std::string> OptionStorage;
46
/// @brief Shared pointer to option storage.
47 48
typedef boost::shared_ptr<OptionStorage> OptionStoragePtr;

49 50
/// @brief Shared pointer to collection of hooks libraries.
typedef boost::shared_ptr<std::vector<std::string> > HooksLibsStoragePtr;
Stephen Morris's avatar
Stephen Morris committed
51

52 53
/// @brief A template class that stores named elements of a given data type.
///
54 55 56 57 58 59 60
/// This template class is provides data value storage for configuration
/// parameters of a given data type.  The values are stored by parameter name
/// and as instances of type "ValueType". Each value held in the storage has
/// a corresponding position within a configuration string (file) specified
/// as a: file name, line number and position within the line. The position
/// information is used for logging when the particular configuration value
/// causes a configuration error.
61
///
62
/// @tparam ValueType is the data type of the elements to store.
63 64
template<typename ValueType>
class ValueStorage {
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
public:
    /// @brief  Stores the the parameter, its value and the position in the
    /// store.
    ///
    /// If the parameter does not exist in the store, then it will be added,
    /// otherwise its data value and the position will be updated with the
    /// given values.
    ///
    /// @param name is the name of the paramater to store.
    /// @param value is the data value to store.
    /// @param position is the position of the data element within a
    /// configuration string (file).
    void setParam(const std::string& name, const ValueType& value,
                  const data::Element::Position& position) {
        values_[name] = value;
        positions_[name] = position;
    }
82

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    /// @brief Returns the data value for the given parameter.
    ///
    /// Finds and returns the data value for the given parameter.
    /// @param name is the name of the parameter for which the data
    /// value is desired.
    ///
    /// @return The paramater's data value of type @c ValueType.
    /// @throw DhcpConfigError if the parameter is not found.
    ValueType getParam(const std::string& name) const {
        typename std::map<std::string, ValueType>::const_iterator param
            = values_.find(name);

        if (param == values_.end()) {
            isc_throw(DhcpConfigError, "Missing parameter '"
                      << name << "'");
98 99
        }

100 101
        return (param->second);
    }
102

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    /// @brief Returns position of the data element in the configuration string.
    ///
    /// The returned object comprises file name, line number and the position
    /// within the particular line of the configuration string where the data
    /// element holding a particular value is located.
    ///
    /// @param name is the name of the parameter which position is desired.
    ///
    /// @return Position of the data element or the position holding empty
    /// file name and two zeros if the position hasn't been specified for the
    /// particular value.
    const data::Element::Position& getPosition(const std::string& name) const {
        typename std::map<std::string, data::Element::Position>::const_iterator
            pos = positions_.find(name);
        if (pos == positions_.end()) {
            return (data::Element::ZERO_POSITION());
119 120
        }

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
        return (pos->second);
    }

    /// @brief Returns the data value for an optional parameter.
    ///
    /// Finds and returns the data value for the given parameter or
    /// a supplied default value if it is not found.
    ///
    /// @param name is the name of the parameter for which the data
    /// value is desired.
    /// @param default_value value to use the default
    ///
    /// @return The paramater's data value of type @c ValueType.
    ValueType getOptionalParam(const std::string& name,
                               const ValueType& default_value) const {
        typename std::map<std::string, ValueType>::const_iterator param
            = values_.find(name);

        if (param == values_.end()) {
            return (default_value);
141 142
        }

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
        return (param->second);
    }

    /// @brief  Remove the parameter from the store.
    ///
    /// Deletes the entry for the given parameter from the store if it
    /// exists.
    ///
    /// @param name is the name of the paramater to delete.
    void delParam(const std::string& name) {
        values_.erase(name);
        positions_.erase(name);
    }

    /// @brief Deletes all of the entries from the store.
    ///
    void clear() {
        values_.clear();
        positions_.clear();
    }

private:
    /// @brief An std::map of the data values, keyed by parameter names.
    std::map<std::string, ValueType> values_;

    /// @brief An std::map holding positions of the data elements in the
    /// configuration, which values are held in @c values_.
    ///
    /// The position is used for logging, when the particular value
    /// causes a configuration error.
    std::map<std::string, data::Element::Position> positions_;

175 176 177
};


178
/// @brief a collection of elements that store uint32 values
179 180 181 182 183 184 185 186 187 188
typedef ValueStorage<uint32_t> Uint32Storage;
typedef boost::shared_ptr<Uint32Storage> Uint32StoragePtr;

/// @brief a collection of elements that store string values
typedef ValueStorage<std::string> StringStorage;
typedef boost::shared_ptr<StringStorage> StringStoragePtr;

/// @brief Storage for parsed boolean values.
typedef ValueStorage<bool> BooleanStorage;
typedef boost::shared_ptr<BooleanStorage> BooleanStoragePtr;
189 190

/// @brief Container for the current parsing context. It provides a
191
/// single enclosure for the storage of configuration parameters,
192 193 194 195 196 197
/// options, option definitions, and other context specific information
/// that needs to be accessible throughout the parsing and parsing
/// constructs.
class ParserContext {
public:
    /// @brief Constructor
198
    ///
199
    /// @param universe is the Option::Universe value of this
200
    /// context.
201 202 203
    ParserContext(Option::Universe universe);

    /// @brief Copy constructor
204
    ParserContext(const ParserContext& rhs);
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

    /// @brief Storage for boolean parameters.
    BooleanStoragePtr boolean_values_;

    /// @brief Storage for uint32 parameters.
    Uint32StoragePtr uint32_values_;

    /// @brief Storage for string parameters.
    StringStoragePtr string_values_;

    /// @brief Storage for options.
    OptionStoragePtr options_;

    /// @brief Storage for option definitions.
    OptionDefStoragePtr option_defs_;
220

Stephen Morris's avatar
Stephen Morris committed
221 222 223 224 225 226 227 228 229 230 231 232
    /// @brief Hooks libraries pointer.
    ///
    /// The hooks libraries information is a vector of strings, each containing
    /// the name of a library.  Hooks libraries should only be reloaded if the
    /// list of names has changed, so the list of current DHCP parameters
    /// (in isc::dhcp::CfgMgr) contains an indication as to whether the list has
    /// altered.  This indication is implemented by storing a pointer to the
    /// list of library names which is cleared when the libraries are loaded.
    /// So either the pointer is null (meaning don't reload the libraries and
    /// the list of current names can be obtained from the HooksManager) or it
    /// is non-null (this is the new list of names, reload the libraries when
    /// possible).
233
    HooksLibsStoragePtr hooks_libraries_;
Stephen Morris's avatar
Stephen Morris committed
234

235 236
    /// @brief The parsing universe of this context.
    Option::Universe universe_;
237 238 239

    /// @brief Assignment operator
    ParserContext& operator=(const ParserContext& rhs);
240 241 242 243 244 245 246 247 248 249 250 251 252

    /// @brief Copy the context fields.
    ///
    /// This class method initializes the context data by copying the data
    /// stored in the context instance provided as an argument. Note that
    /// this function will also handle copying the NULL pointers.
    ///
    /// @param ctx context to be copied.
    void copyContext(const ParserContext& ctx);

    template<typename T>
    void copyContextPointer(const boost::shared_ptr<T>& source_ptr,
                            boost::shared_ptr<T>& dest_ptr);
253 254
};

255
/// @brief Pointer to various parser context.
256 257
typedef boost::shared_ptr<ParserContext> ParserContextPtr;

258
/// @brief Simple data-type parser template class
259
///
260
/// This is the template class for simple data-type parsers. It supports
261 262 263
/// parsing a configuration parameter with specific data-type for its
/// possible values. It provides a common constructor, commit, and templated
/// data storage.  The "build" method implementation must be provided by a
264 265 266
/// declaring type.
/// @param ValueType is the data type of the configuration paramater value
/// the parser should handle.
267 268
template<typename ValueType>
class ValueParser : public DhcpConfigParser {
269 270 271 272 273
public:

    /// @brief Constructor.
    ///
    /// @param param_name name of the parameter.
274 275
    /// @param storage is a pointer to the storage container where the parsed
    /// value be stored upon commit.
276 277
    /// @throw isc::dhcp::DhcpConfigError if a provided parameter's
    /// name is empty.
278
    /// @throw isc::dhcp::DhcpConfigError if storage is null.
279
    ValueParser(const std::string& param_name,
280
        boost::shared_ptr<ValueStorage<ValueType> > storage)
281
        : storage_(storage), param_name_(param_name), value_(), pos_() {
282 283 284 285 286 287 288 289 290 291 292 293 294
        // Empty parameter name is invalid.
        if (param_name_.empty()) {
            isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
                << "empty parameter name provided");
        }

        // NUll storage is invalid.
        if (!storage_) {
            isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
                << "storage may not be NULL");
        }
    }

295
    /// @brief Parse a given element into a value of type @c ValueType
296 297 298
    ///
    /// @param value a value to be parsed.
    ///
299
    /// @throw isc::BadValue Typically the implementing type will throw
300
    /// a BadValue exception when given an invalid Element to parse.
301
    void build(isc::data::ConstElementPtr value);
302 303

    /// @brief Put a parsed value to the storage.
304 305 306
    void commit() {
        // If a given parameter already exists in the storage we override
        // its value. If it doesn't we insert a new element.
307
        storage_->setParam(param_name_, value_, pos_);
308
    }
309

310
private:
311 312 313 314 315 316 317 318 319 320 321 322 323

    /// @brief Performs operations common for all specializations of the
    /// @c build function.
    ///
    /// This method should be called by all specializations of the @c build
    /// method.
    ///
    /// @param value a value being parsed.
    void buildCommon(isc::data::ConstElementPtr value) {
        // Remember position of the data element.
        pos_ = value->getPosition();
    }

324
    /// Pointer to the storage where committed value is stored.
325
    boost::shared_ptr<ValueStorage<ValueType> > storage_;
326

327 328
    /// Name of the parameter which value is parsed with this parser.
    std::string param_name_;
329

330
    /// Parsed value.
331
    ValueType value_;
332 333

    data::Element::Position pos_;
334 335
};

336 337 338 339 340 341
/// @brief typedefs for simple data type parsers
typedef ValueParser<bool> BooleanParser;
typedef ValueParser<uint32_t> Uint32Parser;
typedef ValueParser<std::string> StringParser;

/// @brief a dummy configuration parser
342
///
343 344 345 346 347
/// It is a debugging parser. It does not configure anything,
/// will accept any configuration and will just print it out
/// on commit. Useful for debugging existing configurations and
/// adding new ones.
class DebugParser : public DhcpConfigParser {
348 349
public:

350
    /// @brief Constructor
351
    ///
352 353 354 355
    /// See @ref DhcpConfigParser class for details.
    ///
    /// @param param_name name of the parsed parameter
    DebugParser(const std::string& param_name);
356

357
    /// @brief builds parameter value
358
    ///
359
    /// See @ref DhcpConfigParser class for details.
360
    ///
361 362
    /// @param new_config pointer to the new configuration
    virtual void build(isc::data::ConstElementPtr new_config);
363

364 365 366 367 368 369
    /// @brief pretends to apply the configuration
    ///
    /// This is a method required by base class. It pretends to apply the
    /// configuration, but in fact it only prints the parameter out.
    ///
    /// See @ref DhcpConfigParser class for details.
370 371 372
    virtual void commit();

private:
373
    /// name of the parsed parameter
374 375
    std::string param_name_;

376 377 378
    /// pointer to the actual value of the parameter
    isc::data::ConstElementPtr value_;

379 380 381 382 383 384 385 386 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 parser for interface list definition
///
/// This parser handles Dhcp4/interface entry.
/// It contains a list of network interfaces that the server listens on.
/// In particular, it can contain an entry called "all" or "any" that
/// designates all interfaces.
///
/// It is useful for parsing Dhcp4/interface parameter.
class InterfaceListConfigParser : public DhcpConfigParser {
public:

    /// @brief constructor
    ///
    /// As this is a dedicated parser, it must be used to parse
    /// "interface" parameter only. All other types will throw exception.
    ///
    /// @param param_name name of the configuration parameter being parsed
    /// @throw BadValue if supplied parameter name is not "interface"
    InterfaceListConfigParser(const std::string& param_name);

    /// @brief parses parameters value
    ///
    /// Parses configuration entry (list of parameters) and adds each element
    /// to the interfaces list.
    ///
    /// @param value pointer to the content of parsed values
    virtual void build(isc::data::ConstElementPtr value);

    /// @brief commits interfaces list configuration
    virtual void commit();

private:
413 414 415 416 417 418 419 420
    /// @brief Check that specified interface exists in
    /// @c InterfaceListConfigParser::interfaces_.
    ///
    /// @param iface A name of the interface.
    ///
    /// @return true if specified interface name was found.
    bool isIfaceAdded(const std::string& iface) const;

421
    /// contains list of network interfaces
422 423 424 425 426 427 428 429
    typedef std::list<std::string> IfaceListStorage;
    IfaceListStorage interfaces_;

    // Should server listen on all interfaces.
    bool activate_all_;

    // Parsed parameter name
    std::string param_name_;
430 431
};

432
/// @brief Parser for hooks library list
Stephen Morris's avatar
Stephen Morris committed
433 434 435
///
/// This parser handles the list of hooks libraries.  This is an optional list,
/// which may be empty.
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
///
/// However, the parser does more than just check the list of library names.
/// It does two other things:
///
/// -# The problem faced with the hooks libraries is that we wish to avoid
/// reloading the libraries if they have not changed.  (This would cause the
/// "unload" and "load" methods to run.  Although libraries should be written
/// to cope with this, it is feasible that such an action may be constly in
/// terms of time and resources, or may cause side effects such as clearning
/// an internal cache.)  To this end, the parser also checks the list against
/// the list of libraries current loaded and notes if there are changes.
/// -# If there are, the parser validates the libraries; it opens them and
/// checks that the "version" function exists and returns the correct value.
///
/// Only if the library list has changed and the libraries are valid will the
/// change be applied.
Stephen Morris's avatar
Stephen Morris committed
452 453 454
class HooksLibrariesParser : public DhcpConfigParser {
public:

455
    /// @brief Constructor
Stephen Morris's avatar
Stephen Morris committed
456 457
    ///
    /// As this is a dedicated parser, it must be used to parse
458
    /// "hooks-libraries" parameter only. All other types will throw exception.
Stephen Morris's avatar
Stephen Morris committed
459 460
    ///
    /// @param param_name name of the configuration parameter being parsed.
461
    ///
462
    /// @throw BadValue if supplied parameter name is not "hooks-libraries"
463
    HooksLibrariesParser(const std::string& param_name);
Stephen Morris's avatar
Stephen Morris committed
464

465
    /// @brief Parses parameters value
Stephen Morris's avatar
Stephen Morris committed
466 467
    ///
    /// Parses configuration entry (list of parameters) and adds each element
468 469 470 471
    /// to the hooks libraries list.  The  method also checks whether the
    /// list of libraries is the same as that already loaded.  If not, it
    /// checks each of the libraries in the list for validity (they exist and
    /// have a "version" function that returns the correct value).
Stephen Morris's avatar
Stephen Morris committed
472 473 474 475
    ///
    /// @param value pointer to the content of parsed values
    virtual void build(isc::data::ConstElementPtr value);

476 477 478 479 480
    /// @brief Commits hooks libraries data
    ///
    /// Providing that the specified libraries are valid and are different
    /// to those already loaded, this method loads the new set of libraries
    /// (and unloads the existing set).
Stephen Morris's avatar
Stephen Morris committed
481 482
    virtual void commit();

483 484 485 486 487 488
    /// @brief Returns list of parsed libraries
    ///
    /// Principally for testing, this returns the list of libraries as well as
    /// an indication as to whether the list is different from the list of
    /// libraries already loaded.
    ///
489
    /// @param [out] libraries List of libraries that were specified in the
490
    ///        new configuration.
491
    /// @param [out] changed true if the list is different from that currently
492 493 494
    ///        loaded.
    void getLibraries(std::vector<std::string>& libraries, bool& changed);

Stephen Morris's avatar
Stephen Morris committed
495
private:
496 497
    /// List of hooks libraries.
    std::vector<std::string> libraries_;
Stephen Morris's avatar
Stephen Morris committed
498

499 500
    /// Indicator flagging that the list of libraries has changed.
    bool changed_;
Stephen Morris's avatar
Stephen Morris committed
501
};
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524

/// @brief Parser for option data value.
///
/// This parser parses configuration entries that specify value of
/// a single option. These entries include option name, option code
/// and data carried by the option. The option data can be specified
/// in one of the two available formats: binary value represented as
/// a string of hexadecimal digits or a list of comma separated values.
/// The format being used is controlled by csv-format configuration
/// parameter. When setting this value to True, the latter format is
/// used. The subsequent values in the CSV format apply to relevant
/// option data fields in the configured option. For example the
/// configuration: "data" : "192.168.2.0, 56, hello world" can be
/// used to set values for the option comprising IPv4 address,
/// integer and string data field. Note that order matters. If the
/// order of values does not match the order of data fields within
/// an option the configuration will not be accepted. If parsing
/// is successful then an instance of an option is created and
/// added to the storage provided by the calling class.
class OptionDataParser : public DhcpConfigParser {
public:
    /// @brief Constructor.
    ///
525 526 527
    /// @param dummy first argument is ignored, all Parser constructors
    /// accept string as first argument.
    /// @param options is the option storage in which to store the parsed option
528 529 530
    /// upon "commit".
    /// @param global_context is a pointer to the global context which
    /// stores global scope parameters, options, option defintions.
531
    /// @throw isc::dhcp::DhcpConfigError if options or global_context are null.
532
    OptionDataParser(const std::string& dummy, OptionStoragePtr options,
533
                    ParserContextPtr global_context);
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551

    /// @brief Parses the single option data.
    ///
    /// This method parses the data of a single option from the configuration.
    /// The option data includes option name, option code and data being
    /// carried by this option. Eventually it creates the instance of the
    /// option.
    ///
    /// @param option_data_entries collection of entries that define value
    /// for a particular option.
    /// @throw DhcpConfigError if invalid parameter specified in
    /// the configuration.
    /// @throw isc::InvalidOperation if failed to set storage prior to
    /// calling build.
    virtual void build(isc::data::ConstElementPtr option_data_entries);

    /// @brief Commits option value.
    ///
552
    /// This function adds a new option to the storage or replaces an existing
553
    /// option with the same code.
554
    ///
555
    /// @throw isc::InvalidOperation if failed to set pointer to storage or
556
    /// failed
557 558 559 560
    /// to call build() prior to commit. If that happens data in the storage
    /// remain un-modified.
    virtual void commit();

561
    /// @brief virtual destructor to ensure orderly destruction of derivations.
562 563 564 565
    virtual ~OptionDataParser(){};

protected:
    /// @brief Finds an option definition within the server's option space
566 567
    ///
    /// Given an option space and an option code, find the correpsonding
568 569 570 571
    /// option defintion within the server's option defintion storage. This
    /// method is pure virtual requiring derivations to manage which option
    /// space(s) is valid for search.
    ///
572 573 574
    /// @param option_space name of the parameter option space
    /// @param option_code numeric value of the parameter to find
    /// @return OptionDefintionPtr of the option defintion or an
575
    /// empty OptionDefinitionPtr if not found.
576
    /// @throw DhcpConfigError if the option space requested is not valid
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
    /// for this server.
    virtual OptionDefinitionPtr findServerSpaceOptionDefinition (
            std::string& option_space, uint32_t option_code) = 0;

private:

    /// @brief Create option instance.
    ///
    /// Creates an instance of an option and adds it to the provided
    /// options storage. If the option data parsed by \ref build function
    /// are invalid or insufficient this function emits an exception.
    ///
    /// @warning this function does not check if options_ storage pointer
    /// is intitialized but this check is not needed here because it is done
    /// in the \ref build function.
    ///
    /// @throw DhcpConfigError if parameters provided in the configuration
    /// are invalid.
    void createOption();

    /// Storage for boolean values.
598 599 600 601 602 603 604 605
    BooleanStoragePtr boolean_values_;

    /// Storage for string values (e.g. option name or data).
    StringStoragePtr string_values_;

    /// Storage for uint32 values (e.g. option code).
    Uint32StoragePtr uint32_values_;

606 607
    /// Pointer to options storage. This storage is provided by
    /// the calling class and is shared by all OptionDataParser objects.
608 609
    OptionStoragePtr options_;

610 611
    /// Option descriptor holds newly configured option.
    Subnet::OptionDescriptor option_descriptor_;
612

613 614 615
    /// Option space name where the option belongs to.
    std::string option_space_;

616
    /// Parsing context which contains global values, options and option
617 618
    /// definitions.
    ParserContextPtr global_context_;
619 620 621
};

///@brief Function pointer for OptionDataParser factory methods
622
typedef OptionDataParser *OptionDataParserFactory(const std::string&,
623
                     OptionStoragePtr options, ParserContextPtr global_context);
624 625 626 627 628 629 630 631 632 633 634

/// @brief Parser for option data values within a subnet.
///
/// This parser iterates over all entries that define options
/// data for a particular subnet and creates a collection of options.
/// If parsing is successful, all these options are added to the Subnet
/// object.
class OptionDataListParser : public DhcpConfigParser {
public:
    /// @brief Constructor.
    ///
635
    /// @param dummy nominally would be param name, this is always ignored.
636
    /// @param options parsed option storage for options in this list
637 638 639 640
    /// @param global_context is a pointer to the global context which
    /// stores global scope parameters, options, option defintions.
    /// @param optionDataParserFactory factory method for creating individual
    /// option parsers
641
    /// @throw isc::dhcp::DhcpConfigError if options or global_context are null.
642
    OptionDataListParser(const std::string& dummy, OptionStoragePtr options,
643
                        ParserContextPtr global_context,
644
                        OptionDataParserFactory *optionDataParserFactory);
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661

    /// @brief Parses entries that define options' data for a subnet.
    ///
    /// This method iterates over all entries that define option data
    /// for options within a single subnet and creates options' instances.
    ///
    /// @param option_data_list pointer to a list of options' data sets.
    /// @throw DhcpConfigError if option parsing failed.
    void build(isc::data::ConstElementPtr option_data_list);

    /// @brief Commit all option values.
    ///
    /// This function invokes commit for all option values.
    void commit();

private:
    /// Pointer to options instances storage.
662 663
    OptionStoragePtr options_;

664 665 666 667
    /// Intermediate option storage. This storage is used by
    /// lower level parsers to add new options.  Values held
    /// in this storage are assigned to main storage (options_)
    /// if overall parsing was successful.
668 669
    OptionStoragePtr local_options_;

670 671 672
    /// Collection of parsers;
    ParserCollection parsers_;

673
    /// Parsing context which contains global values, options and option
674 675
    /// definitions.
    ParserContextPtr global_context_;
676 677 678 679 680 681 682 683 684 685 686 687 688

    /// Factory to create server-specific option data parsers
    OptionDataParserFactory *optionDataParserFactory_;
};


/// @brief Parser for a single option definition.
///
/// This parser creates an instance of a single option definition.
class OptionDefParser : public DhcpConfigParser {
public:
    /// @brief Constructor.
    ///
689 690
    /// @param dummy first argument is ignored, all Parser constructors
    /// accept string as first argument.
691 692
    /// @param storage is the definition storage in which to store the parsed
    /// definition upon "commit".
693
    /// @throw isc::dhcp::DhcpConfigError if storage is null.
694
    OptionDefParser(const std::string& dummy, OptionDefStoragePtr storage);
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717

    /// @brief Parses an entry that describes single option definition.
    ///
    /// @param option_def a configuration entry to be parsed.
    ///
    /// @throw DhcpConfigError if parsing was unsuccessful.
    void build(isc::data::ConstElementPtr option_def);

    /// @brief Stores the parsed option definition in a storage.
    void commit();

private:

    /// @brief Create option definition from the parsed parameters.
    void createOptionDef();

    /// Instance of option definition being created by this parser.
    OptionDefinitionPtr option_definition_;
    /// Name of the space the option definition belongs to.
    std::string option_space_name_;

    /// Pointer to a storage where the option definition will be
    /// added when \ref commit is called.
718
    OptionDefStoragePtr storage_;
719 720

    /// Storage for boolean values.
721 722
    BooleanStoragePtr boolean_values_;

723
    /// Storage for string values.
724
    StringStoragePtr string_values_;
725

726 727
    /// Storage for uint32 values.
    Uint32StoragePtr uint32_values_;
728 729 730 731 732 733 734 735 736 737 738 739
};

/// @brief Parser for a list of option definitions.
///
/// This parser iterates over all configuration entries that define
/// option definitions and creates instances of these definitions.
/// If the parsing is successful, the collection of created definitions
/// is put into the provided storage.
class OptionDefListParser : public DhcpConfigParser {
public:
    /// @brief Constructor.
    ///
740 741
    /// @param dummy first argument is ignored, all Parser constructors
    /// accept string as first argument.
742 743
    /// @param storage is the definition storage in which to store the parsed
    /// definitions in this list
744
    /// @throw isc::dhcp::DhcpConfigError if storage is null.
745
    OptionDefListParser(const std::string& dummy, OptionDefStoragePtr storage);
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761

    /// @brief Parse configuration entries.
    ///
    /// This function parses configuration entries and creates instances
    /// of option definitions.
    ///
    /// @param option_def_list pointer to an element that holds entries
    /// that define option definitions.
    /// @throw DhcpConfigError if configuration parsing fails.
    void build(isc::data::ConstElementPtr option_def_list);

    /// @brief Stores option definitions in the CfgMgr.
    void commit();

private:
    /// @brief storage for option definitions.
762
    OptionDefStoragePtr storage_;
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
};

/// @brief a collection of pools
///
/// That type is used as intermediate storage, when pools are parsed, but there is
/// no subnet object created yet to store them.
typedef std::vector<PoolPtr> PoolStorage;
typedef boost::shared_ptr<PoolStorage> PoolStoragePtr;

/// @brief parser for pool definition
///
/// This abstract parser handles pool definitions, i.e. a list of entries of one
/// of two syntaxes: min-max and prefix/len. Pool objects are created
/// and stored in chosen PoolStorage container.
///
/// It is useful for parsing Dhcp<4/6>/subnet<4/6>[X]/pool parameters.
class PoolParser : public DhcpConfigParser {
public:

    /// @brief constructor.
783
    ///
784 785
    /// @param dummy first argument is ignored, all Parser constructors
    /// accept string as first argument.
786 787
    /// @param pools is the storage in which to store the parsed pool
    /// upon "commit".
788
    /// @throw isc::dhcp::DhcpConfigError if storage is null.
789
    PoolParser(const std::string& dummy, PoolStoragePtr pools);
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808

    /// @brief parses the actual list
    ///
    /// This method parses the actual list of interfaces.
    /// No validation is done at this stage, everything is interpreted as
    /// interface name.
    /// @param pools_list list of pools defined for a subnet
    /// @throw isc::dhcp::DhcpConfigError when pool parsing fails
    virtual void build(isc::data::ConstElementPtr pools_list);

    /// @brief Stores the parsed values in a storage provided
    ///        by an upper level parser.
    virtual void commit();

protected:
    /// @brief Creates a Pool object given a IPv4 prefix and the prefix length.
    ///
    /// @param addr is the IP  prefix of the pool.
    /// @param len is the prefix length.
809
    /// @param ptype is the type of pool to create.
810 811
    /// @return returns a PoolPtr to the new Pool object.
    virtual PoolPtr poolMaker(isc::asiolink::IOAddress &addr, uint32_t len,
812 813 814 815 816 817 818 819
                           int32_t ptype=0) = 0;

    /// @brief Creates a Pool object given starting and ending IP addresses.
    ///
    /// @param min is the first IP address in the pool.
    /// @param max is the last IP address in the pool.
    /// @param ptype is the type of pool to create (not used by all derivations)
    /// @return returns a PoolPtr to the new Pool object.
820
    virtual PoolPtr poolMaker(isc::asiolink::IOAddress &min,
821 822 823 824 825 826 827 828 829 830 831 832 833
                           isc::asiolink::IOAddress &max, int32_t ptype=0) = 0;

    /// @brief pointer to the actual Pools storage
    ///
    /// That is typically a storage somewhere in Subnet parser
    /// (an upper level parser).
    PoolStoragePtr pools_;

    /// A temporary storage for pools configuration. It is a
    /// storage where pools are stored by build function.
    PoolStorage local_pools_;
};

834 835 836 837 838 839 840 841 842 843 844
/// @brief parser for additional relay information
///
/// This concrete parser handles RelayInfo structure defintions.
/// So far that structure holds only relay IP (v4 or v6) address, but it
/// is expected that the number of parameters will increase over time.
///
/// It is useful for parsing Dhcp<4/6>/subnet<4/6>[x]/relay parameters.
class RelayInfoParser : public DhcpConfigParser {
public:

    /// @brief constructor
Tomek Mrugalski's avatar
Tomek Mrugalski committed
845
    /// @param unused first argument is ignored, all Parser constructors
846 847
    /// accept string as first argument.
    /// @param relay_info is the storage in which to store the parsed
Tomek Mrugalski's avatar
Tomek Mrugalski committed
848 849
    /// @param family specifies protocol family (IPv4 or IPv6)
    RelayInfoParser(const std::string& unused,
850
                    const isc::dhcp::Subnet::RelayInfoPtr& relay_info,
851
                    const isc::dhcp::Option::Universe& family);
852 853

    /// @brief parses the actual relay parameters
Marcin Siodelski's avatar
Marcin Siodelski committed
854
    /// @param relay_info JSON structure holding relay parameters to parse
855 856 857 858 859 860
    virtual void build(isc::data::ConstElementPtr relay_info);

    /// @brief stores parsed info in relay_info
    virtual void commit();

protected:
Tomek Mrugalski's avatar
Tomek Mrugalski committed
861 862 863 864 865 866 867 868 869 870

    /// @brief Creates a parser for the given "relay" member element id.
    ///
    /// The elements currently supported are:
    /// -# ip-address
    ///
    /// @param config_id is the "item_name" for a specific member element of
    /// the "relay" specification.
    ///
    /// @return returns a pointer to newly created parser.
871 872 873 874 875 876 877 878 879 880 881
    isc::dhcp::ParserPtr
    createConfigParser(const std::string& parser);

    /// Parsed data will be stored there on commit()
    isc::dhcp::Subnet::RelayInfoPtr storage_;

    /// Local storage information (for temporary values)
    isc::dhcp::Subnet::RelayInfo local_;

    /// Storage for subnet-specific string values.
    StringStoragePtr string_values_;
Tomek Mrugalski's avatar
Tomek Mrugalski committed
882 883 884

    /// Protocol family (IPv4 or IPv6)
    Option::Universe family_;
885 886
};

887 888 889 890 891 892 893 894
/// @brief this class parses a single subnet
///
/// This class parses the whole subnet definition. It creates parsers
/// for received configuration parameters as needed.
class SubnetConfigParser : public DhcpConfigParser {
public:

    /// @brief constructor
895 896 897 898 899
    ///
    /// @param global_context
    /// @param default_addr default IP address (0.0.0.0 for IPv4, :: for IPv6)
    SubnetConfigParser(const std::string&, ParserContextPtr global_context,
                       const isc::asiolink::IOAddress& default_addr);
900 901 902 903 904 905

    /// @brief parses parameter value
    ///
    /// @param subnet pointer to the content of subnet definition
    ///
    /// @throw isc::DhcpConfigError if subnet configuration parsing failed.
906
    virtual void build(isc::data::ConstElementPtr subnet);
907 908 909 910

    /// @brief Adds the created subnet to a server's configuration.
    virtual void commit() = 0;

911 912
    /// @brief tries to convert option_space string to numeric vendor_id
    ///
Tomek Mrugalski's avatar
Tomek Mrugalski committed
913 914
    /// This will work if the option_space has format "vendor-X", where
    /// X can be any value between 1 and MAX_UINT32.
915 916 917 918 919
    /// This is used to detect whether a given option-space is a vendor
    /// space or not. Returns 0 if the format is different.
    /// @return numeric vendor-id (or 0 if the format does not match)
    static uint32_t optionSpaceToVendorId(const std::string& option_space);

920 921 922 923 924 925 926 927 928 929 930 931
protected:
    /// @brief creates parsers for entries in subnet definition
    ///
    /// @param config_id name od the entry
    ///
    /// @return parser object for specified entry name
    /// @throw isc::dhcp::DhcpConfigError if trying to create a parser
    ///        for unknown config element
    virtual DhcpConfigParser* createSubnetConfigParser(
                                            const std::string& config_id) = 0;

    /// @brief Determines if the given option space name and code describe
932
    /// a standard option for the  server.
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
    ///
    /// @param option_space is the name of the option space to consider
    /// @param code is the numeric option code to consider
    /// @return returns true if the space and code are part of the server's
    /// standard options.
    virtual bool isServerStdOption(std::string option_space, uint32_t code) = 0;

    /// @brief Returns the option definition for a given option code from
    /// the server's standard set of options.
    /// @param code is the numeric option code of the desired option definition.
    /// @return returns a pointer the option definition
    virtual OptionDefinitionPtr getServerStdOptionDefinition (
                                                             uint32_t code) = 0;

    /// @brief Issues a server specific warning regarding duplicate subnet
948 949
    /// options.
    ///
950
    /// @param code is the numeric option code of the duplicate option
951
    /// @param addr is the subnet address
952 953
    /// @todo a means to know the correct logger and perhaps a common
    /// message would allow this method to be emitted by the base class.
954
    virtual void duplicate_option_warning(uint32_t code,
955 956
        isc::asiolink::IOAddress& addr) = 0;

957 958 959
    /// @brief Instantiates the subnet based on a given IP prefix and prefix
    /// length.
    ///
960
    /// @param addr is the IP prefix of the subnet.
961
    /// @param len is the prefix length
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    virtual void initSubnet(isc::asiolink::IOAddress addr, uint8_t len) = 0;

    /// @brief Returns value for a given parameter (after using inheritance)
    ///
    /// This method implements inheritance. For a given parameter name, it first
    /// checks if there is a global value for it and overwrites it with specific
    /// value if such value was defined in subnet.
    ///
    /// @param name name of the parameter
    /// @return triplet with the parameter name
    /// @throw DhcpConfigError when requested parameter is not present
    isc::dhcp::Triplet<uint32_t> getParam(const std::string& name);

private:

    /// @brief Append sub-options to an option.
    ///
    /// @param option_space a name of the encapsulated option space.
    /// @param option option instance to append sub-options to.
    void appendSubOptions(const std::string& option_space, OptionPtr& option);

    /// @brief Create a new subnet using a data from child parsers.
    ///
985
    /// @throw isc::dhcp::DhcpConfigError if subnet configuration parsing
986 987 988 989 990 991 992
    /// failed.
    void createSubnet();

protected:

    /// Storage for subnet-specific integer values.
    Uint32StoragePtr uint32_values_;
993

994 995
    /// Storage for subnet-specific string values.
    StringStoragePtr string_values_;
996

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    /// Storage for pools belonging to this subnet.
    PoolStoragePtr pools_;

    /// Storage for options belonging to this subnet.
    OptionStoragePtr options_;

    /// Parsers are stored here.
    ParserCollection parsers_;

    /// Pointer to the created subnet object.
    isc::dhcp::SubnetPtr subnet_;

1009
    /// Parsing context which contains global values, options and option
1010 1011
    /// definitions.
    ParserContextPtr global_context_;
1012 1013 1014

    /// Pointer to relay information
    isc::dhcp::Subnet::RelayInfoPtr relay_info_;
1015 1016
};

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
/// @brief Parser for  D2ClientConfig
///
/// This class parses the configuration element "dhcp-ddns" common to the
/// spec files for both dhcp4 and dhcp6. It creates an instance of a
/// D2ClientConfig.
class D2ClientConfigParser : public  isc::dhcp::DhcpConfigParser {
public:
    /// @brief Constructor
    ///
    /// @param entry_name is an arbitrary label assigned to this configuration
    /// definition.
    D2ClientConfigParser(const std::string& entry_name);

    /// @brief Destructor
    virtual ~D2ClientConfigParser();

    /// @brief Performs the parsing of the given dhcp-ddns element.
    ///
    /// The results of the parsing are retained internally for use during
    /// commit.
1037 1038 1039
    /// @todo This parser supplies hard-coded default values for all
    /// optional parameters.  This should be changed once a new plan
    /// for configuration is determined.
1040 1041 1042 1043 1044 1045
    ///
    /// @param client_config is the "dhcp-ddns" configuration to parse
    virtual void build(isc::data::ConstElementPtr client_config);

    /// @brief Creates a parser for the given "dhcp-ddns" member element id.
    ///
1046 1047
    /// The elements currently supported are (see isc::dhcp::D2ClientConfig
    /// for details on each):
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    /// -# enable-updates
    /// -# server-ip
    /// -# server-port
    /// -# ncr-protocol
    /// -# ncr-format
    /// -# remove-on-renew
    /// -# always-include-fqdn
    /// -# allow-client-update
    /// -# override-no-update
    /// -# override-client-update
    /// -# replace-client-name
    /// -# generated-prefix
    /// -# qualifying-suffix
    ///
    /// @param config_id is the "item_name" for a specific member element of
    /// the "dns_server" specification.
    ///
    /// @return returns a pointer to newly created parser.
    virtual isc::dhcp::ParserPtr createConfigParser(const std::string&
                                                    config_id);

    /// @brief Instantiates a D2ClientConfig from internal data values
    /// passes to CfgMgr singleton.
    virtual void commit();

private:
    /// @brief Arbitrary label assigned to this parser instance.
    /// Primarily used for diagnostics.
    std::string entry_name_;

    /// Storage for subnet-specific boolean values.
    BooleanStoragePtr boolean_values_;

    /// Storage for subnet-specific integer values.
    Uint32StoragePtr uint32_values_;

    /// Storage for subnet-specific string values.
    StringStoragePtr string_values_;

    /// @brief Pointer to temporary local instance created during build.
    D2ClientConfigPtr local_client_config_ ;
};

1091 1092 1093 1094 1095
// Pointers to various parser objects.
typedef boost::shared_ptr<BooleanParser> BooleanParserPtr;
typedef boost::shared_ptr<StringParser> StringParserPtr;
typedef boost::shared_ptr<Uint32Parser> Uint32ParserPtr;

1096 1097 1098 1099 1100
}; // end of isc::dhcp namespace
}; // end of isc namespace

#endif // DHCP_PARSERS_H