config_parser.cc 62.5 KB
Newer Older
1
// Copyright (C) 2012-2013 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.

#include <config/ccsession.h>
#include <dhcp4/config_parser.h>
#include <dhcp4/dhcp4_log.h>
18 19 20
#include <dhcp/libdhcp++.h>
#include <dhcp/option_definition.h>
#include <dhcpsrv/cfgmgr.h>
21
#include <dhcpsrv/dhcp_config_parser.h>
22
#include <util/encode/hex.h>
23
#include <util/strutil.h>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
24 25 26
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
27
#include <limits>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
28 29 30 31
#include <iostream>
#include <vector>
#include <map>

32
using namespace std;
33 34
using namespace isc;
using namespace isc::dhcp;
35 36 37
using namespace isc::data;
using namespace isc::asiolink;

38 39
namespace {

40 41 42 43
/// @brief auxiliary type used for storing element name and its parser
typedef pair<string, ConstElementPtr> ConfigPair;

/// @brief a factory method that will create a parser for a given element name
44
typedef isc::dhcp::DhcpConfigParser* ParserFactory(const std::string& config_id);
45 46 47 48

/// @brief a collection of factories that creates parsers for specified element names
typedef std::map<std::string, ParserFactory*> FactoryMap;

49 50 51 52 53 54
/// @brief a collection of elements that store uint32 values (e.g. renew-timer = 900)
typedef std::map<std::string, uint32_t> Uint32Storage;

/// @brief a collection of elements that store string values
typedef std::map<std::string, std::string> StringStorage;

55 56 57
/// @brief Storage for parsed boolean values.
typedef std::map<string, bool> BooleanStorage;

58 59 60 61 62 63
/// @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<Pool4Ptr> PoolStorage;

64 65 66 67 68
/// @brief Collection of option descriptors. This container allows searching for
/// options using the option code or persistency flag. This is useful when merging
/// existing options with newly configured options.
typedef Subnet::OptionContainer OptionStorage;

69 70 71 72 73 74
/// @brief Global uint32 parameters that will be used as defaults.
Uint32Storage uint32_defaults;

/// @brief global string parameters that will be used as defaults.
StringStorage string_defaults;

75 76 77
/// @brief Global storage for options that will be used as defaults.
OptionStorage option_defaults;

78 79 80 81 82 83
/// @brief a dummy configuration parser
///
/// 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.
84
class DebugParser : public DhcpConfigParser {
85 86 87 88
public:

    /// @brief Constructor
    ///
89
    /// See @ref DhcpConfigParser class for details.
90 91 92 93 94 95 96 97
    ///
    /// @param param_name name of the parsed parameter
    DebugParser(const std::string& param_name)
        :param_name_(param_name) {
    }

    /// @brief builds parameter value
    ///
98
    /// See @ref DhcpConfigParser class for details.
99 100 101 102 103 104 105 106 107 108 109 110 111
    ///
    /// @param new_config pointer to the new configuration
    virtual void build(ConstElementPtr new_config) {
        std::cout << "Build for token: [" << param_name_ << "] = ["
                  << value_->str() << "]" << std::endl;
        value_ = new_config;
    }

    /// @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.
    ///
112
    /// See @ref DhcpConfigParser class for details.
113 114 115 116 117 118 119 120 121 122 123
    virtual void commit() {
        // Debug message. The whole DebugParser class is used only for parser
        // debugging, and is not used in production code. It is very convenient
        // to keep it around. Please do not turn this cout into logger calls.
        std::cout << "Commit for token: [" << param_name_ << "] = ["
                  << value_->str() << "]" << std::endl;
    }

    /// @brief factory that constructs DebugParser objects
    ///
    /// @param param_name name of the parameter to be parsed
124
    static DhcpConfigParser* Factory(const std::string& param_name) {
125 126 127
        return (new DebugParser(param_name));
    }

Tomek Mrugalski's avatar
Tomek Mrugalski committed
128
private:
129 130 131 132 133 134 135
    /// name of the parsed parameter
    std::string param_name_;

    /// pointer to the actual value of the parameter
    ConstElementPtr value_;
};

136 137 138 139 140
/// @brief A boolean value parser.
///
/// This parser handles configuration values of the boolean type.
/// Parsed values are stored in a provided storage. If no storage
/// is provided then the build function throws an exception.
141
class BooleanParser : public DhcpConfigParser {
142 143 144 145 146 147 148 149
public:
    /// @brief Constructor.
    ///
    /// @param param_name name of the parameter.
    BooleanParser(const std::string& param_name)
        : storage_(NULL),
          param_name_(param_name),
          value_(false) {
150 151 152 153 154
        // Empty parameter name is invalid.
        if (param_name_.empty()) {
            isc_throw(isc::dhcp::Dhcp4ConfigError, "parser logic error:"
                      << "empty parameter name provided");
        }
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    }

    /// @brief Parse a boolean value.
    ///
    /// @param value a value to be parsed.
    ///
    /// @throw isc::InvalidOperation if a storage has not been set
    ///        prior to calling this function
    /// @throw isc::dhcp::Dhcp4ConfigError if a provided parameter's
    ///        name is empty.
    virtual void build(ConstElementPtr value) {
        if (storage_ == NULL) {
            isc_throw(isc::InvalidOperation, "parser logic error:"
                      << " storage for the " << param_name_
                      << " value has not been set");
        } else if (param_name_.empty()) {
            isc_throw(isc::dhcp::Dhcp4ConfigError, "parser logic error:"
                      << "empty parameter name provided");
        }
        // The Config Manager checks if user specified a
        // valid value for a boolean parameter: True or False.
        // It is then ok to assume that if str() does not return
        // 'true' the value is 'false'.
        value_ = (value->str() == "true") ? true : false;
    }

    /// @brief Put a parsed value to the storage.
    virtual void commit() {
        if (storage_ != NULL && !param_name_.empty()) {
            (*storage_)[param_name_] = value_;
        }
    }

    /// @brief Create an instance of the boolean parser.
    ///
    /// @param param_name name of the parameter for which the
    ///        parser is created.
192
    static DhcpConfigParser* factory(const std::string& param_name) {
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        return (new BooleanParser(param_name));
    }

    /// @brief Set the storage for parsed value.
    ///
    /// This function must be called prior to calling build.
    ///
    /// @param storage a pointer to the storage where parsed data
    ///        is to be stored.
    void setStorage(BooleanStorage* storage) {
        storage_ = storage;
    }

private:
    /// Pointer to the storage where parsed value is stored.
    BooleanStorage* storage_;
    /// Name of the parameter which value is parsed with this parser.
    std::string param_name_;
    /// Parsed value.
    bool value_;
};

215 216 217 218 219 220 221
/// @brief Configuration parser for uint32 parameters
///
/// This class is a generic parser that is able to handle any uint32 integer
/// type. By default it stores the value in external global container
/// (uint32_defaults). If used in smaller scopes (e.g. to parse parameters
/// in subnet config), it can be pointed to a different storage, using
/// setStorage() method. This class follows the parser interface, laid out
222
/// in its base class, @ref DhcpConfigParser.
223 224
///
/// For overview of usability of this generic purpose parser, see
225
/// @ref dhcpv4ConfigInherit page.
226
class Uint32Parser : public DhcpConfigParser {
227 228 229 230 231
public:

    /// @brief constructor for Uint32Parser
    /// @param param_name name of the configuration parameter being parsed
    Uint32Parser(const std::string& param_name)
232 233
        : storage_(&uint32_defaults),
          param_name_(param_name) {
234 235 236 237 238
        // Empty parameter name is invalid.
        if (param_name_.empty()) {
            isc_throw(Dhcp4ConfigError, "parser logic error:"
                      << "empty parameter name provided");
        }
239 240
    }

241
    /// @brief Parses configuration configuration parameter as uint32_t.
242 243
    ///
    /// @param value pointer to the content of parsed values
Tomek Mrugalski's avatar
Tomek Mrugalski committed
244
    /// @throw BadValue if supplied value could not be base to uint32_t
245
    ///        or the parameter name is empty.
246
    virtual void build(ConstElementPtr value) {
247
        if (param_name_.empty()) {
248
            isc_throw(Dhcp4ConfigError, "parser logic error:"
249 250 251
                      << "empty parameter name provided");
        }

Tomek Mrugalski's avatar
Tomek Mrugalski committed
252 253
        int64_t check;
        string x = value->str();
254
        try {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
255
            check = boost::lexical_cast<int64_t>(x);
256 257 258 259
        } catch (const boost::bad_lexical_cast &) {
            isc_throw(BadValue, "Failed to parse value " << value->str()
                      << " as unsigned 32-bit integer.");
        }
Tomek Mrugalski's avatar
Tomek Mrugalski committed
260
        if (check > std::numeric_limits<uint32_t>::max()) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
261 262 263 264 265 266 267 268 269 270
            isc_throw(BadValue, "Value " << value->str() << "is too large"
                      << " for unsigned 32-bit integer.");
        }
        if (check < 0) {
            isc_throw(BadValue, "Value " << value->str() << "is negative."
                      << " Only 0 or larger are allowed for unsigned 32-bit integer.");
        }

        // value is small enough to fit
        value_ = static_cast<uint32_t>(check);
271 272
    }

273
    /// @brief Stores the parsed uint32_t value in a storage.
274
    virtual void commit() {
275 276 277 278 279
        if (storage_ != NULL && !param_name_.empty()) {
            // If a given parameter already exists in the storage we override
            // its value. If it doesn't we insert a new element.
            (*storage_)[param_name_] = value_;
        }
280 281 282 283 284
    }

    /// @brief factory that constructs Uint32Parser objects
    ///
    /// @param param_name name of the parameter to be parsed
285
    static DhcpConfigParser* factory(const std::string& param_name) {
286 287 288 289 290
        return (new Uint32Parser(param_name));
    }

    /// @brief sets storage for value of this parameter
    ///
291
    /// See @ref dhcpv4ConfigInherit for details.
292 293 294 295 296 297
    ///
    /// @param storage pointer to the storage container
    void setStorage(Uint32Storage* storage) {
        storage_ = storage;
    }

Tomek Mrugalski's avatar
Tomek Mrugalski committed
298
private:
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    /// pointer to the storage, where parsed value will be stored
    Uint32Storage* storage_;

    /// name of the parameter to be parsed
    std::string param_name_;

    /// the actual parsed value
    uint32_t value_;
};

/// @brief Configuration parser for string parameters
///
/// This class is a generic parser that is able to handle any string
/// parameter. By default it stores the value in external global container
/// (string_defaults). If used in smaller scopes (e.g. to parse parameters
/// in subnet config), it can be pointed to a different storage, using
/// setStorage() method. This class follows the parser interface, laid out
316
/// in its base class, @ref DhcpConfigParser.
317 318
///
/// For overview of usability of this generic purpose parser, see
319
/// @ref dhcpv4ConfigInherit page.
320
class StringParser : public DhcpConfigParser {
321 322 323 324 325 326
public:

    /// @brief constructor for StringParser
    /// @param param_name name of the configuration parameter being parsed
    StringParser(const std::string& param_name)
        :storage_(&string_defaults), param_name_(param_name) {
327 328 329 330 331
        // Empty parameter name is invalid.
        if (param_name_.empty()) {
            isc_throw(Dhcp4ConfigError, "parser logic error:"
                      << "empty parameter name provided");
        }
332 333 334 335
    }

    /// @brief parses parameter value
    ///
336
    /// Parses configuration entry and stores it in storage. See
337
    /// @ref setStorage() for details.
338 339 340 341 342 343 344
    ///
    /// @param value pointer to the content of parsed values
    virtual void build(ConstElementPtr value) {
        value_ = value->str();
        boost::erase_all(value_, "\"");
    }

345
    /// @brief Stores the parsed value in a storage.
346
    virtual void commit() {
347 348 349 350 351
        if (storage_ != NULL && !param_name_.empty()) {
            // If a given parameter already exists in the storage we override
            // its value. If it doesn't we insert a new element.
            (*storage_)[param_name_] = value_;
        }
352 353 354 355 356
    }

    /// @brief factory that constructs StringParser objects
    ///
    /// @param param_name name of the parameter to be parsed
357
    static DhcpConfigParser* factory(const std::string& param_name) {
358 359 360 361 362
        return (new StringParser(param_name));
    }

    /// @brief sets storage for value of this parameter
    ///
363
    /// See \ref dhcpv4ConfigInherit for details.
364 365 366 367 368 369
    ///
    /// @param storage pointer to the storage container
    void setStorage(StringStorage* storage) {
        storage_ = storage;
    }

Tomek Mrugalski's avatar
Tomek Mrugalski committed
370
private:
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    /// pointer to the storage, where parsed value will be stored
    StringStorage* storage_;

    /// name of the parameter to be parsed
    std::string param_name_;

    /// the actual parsed value
    std::string value_;
};


/// @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.
390
class InterfaceListConfigParser : public DhcpConfigParser {
391 392 393 394 395 396 397 398
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
Tomek Mrugalski's avatar
Tomek Mrugalski committed
399
    /// @throw BadValue if supplied parameter name is not "interface"
400 401
    InterfaceListConfigParser(const std::string& param_name) {
        if (param_name != "interface") {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
402
            isc_throw(BadValue, "Internal error. Interface configuration "
403 404 405 406 407 408
                      "parser called for the wrong parameter: " << param_name);
        }
    }

    /// @brief parses parameters value
    ///
Tomek Mrugalski's avatar
Tomek Mrugalski committed
409 410
    /// Parses configuration entry (list of parameters) and adds each element
    /// to the interfaces list.
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    ///
    /// @param value pointer to the content of parsed values
    virtual void build(ConstElementPtr value) {
        BOOST_FOREACH(ConstElementPtr iface, value->listValue()) {
            interfaces_.push_back(iface->str());
        }
    }

    /// @brief commits interfaces list configuration
    virtual void commit() {
        /// @todo: Implement per interface listening. Currently always listening
        /// on all interfaces.
    }

    /// @brief factory that constructs InterfaceListConfigParser objects
    ///
    /// @param param_name name of the parameter to be parsed
428
    static DhcpConfigParser* factory(const std::string& param_name) {
429 430 431
        return (new InterfaceListConfigParser(param_name));
    }

Tomek Mrugalski's avatar
Tomek Mrugalski committed
432
private:
433 434 435 436 437 438 439 440 441 442 443 444 445 446
    /// contains list of network interfaces
    vector<string> interfaces_;
};

/// @brief parser for pool definition
///
/// This parser handles pool definitions, i.e. a list of entries of one
/// of two syntaxes: min-max and prefix/len. Pool4 objects are created
/// and stored in chosen PoolStorage container.
///
/// As there are no default values for pool, setStorage() must be called
/// before build(). Otherwise exception will be thrown.
///
/// It is useful for parsing Dhcp4/subnet4[X]/pool parameters.
447
class PoolParser : public DhcpConfigParser {
448 449 450 451 452 453 454 455 456 457 458 459 460
public:

    /// @brief constructor.
    PoolParser(const std::string& /*param_name*/)
        :pools_(NULL) {
        // ignore parameter name, it is always Dhcp4/subnet4[X]/pool
    }

    /// @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.
Tomek Mrugalski's avatar
Tomek Mrugalski committed
461 462 463
    /// @param pools_list list of pools defined for a subnet
    /// @throw InvalidOperation if storage was not specified (setStorage() not called)
    /// @throw Dhcp4ConfigError when pool parsing fails
464 465 466
    void build(ConstElementPtr pools_list) {
        // setStorage() should have been called before build
        if (!pools_) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
467
            isc_throw(InvalidOperation, "Parser logic error. No pool storage set,"
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
                      " but pool parser asked to parse pools");
        }

        BOOST_FOREACH(ConstElementPtr text_pool, pools_list->listValue()) {

            // That should be a single pool representation. It should contain
            // text is form prefix/len or first - last. Note that spaces
            // are allowed
            string txt = text_pool->stringValue();

            // first let's remove any whitespaces
            boost::erase_all(txt, " "); // space
            boost::erase_all(txt, "\t"); // tabulation

            // Is this prefix/len notation?
            size_t pos = txt.find("/");
            if (pos != string::npos) {
                IOAddress addr("::");
                uint8_t len = 0;
                try {
                    addr = IOAddress(txt.substr(0, pos));

                    // start with the first character after /
                    string prefix_len = txt.substr(pos + 1);

                    // It is lexical cast to int and then downcast to uint8_t.
                    // Direct cast to uint8_t (which is really an unsigned char)
                    // will result in interpreting the first digit as output
                    // value and throwing exception if length is written on two
                    // digits (because there are extra characters left over).

                    // No checks for values over 128. Range correctness will
                    // be checked in Pool4 constructor.
                    len = boost::lexical_cast<int>(prefix_len);
                } catch (...)  {
                    isc_throw(Dhcp4ConfigError, "Failed to parse pool "
                              "definition: " << text_pool->stringValue());
                }

                Pool4Ptr pool(new Pool4(addr, len));
508
                local_pools_.push_back(pool);
509 510 511 512 513 514 515
                continue;
            }

            // Is this min-max notation?
            pos = txt.find("-");
            if (pos != string::npos) {
                // using min-max notation
516
                IOAddress min(txt.substr(0,pos));
517 518 519 520
                IOAddress max(txt.substr(pos + 1));

                Pool4Ptr pool(new Pool4(min, max));

521
                local_pools_.push_back(pool);
522 523 524 525 526 527 528 529 530 531 532
                continue;
            }

            isc_throw(Dhcp4ConfigError, "Failed to parse pool definition:"
                      << text_pool->stringValue() <<
                      ". Does not contain - (for min-max) nor / (prefix/len)");
        }
    }

    /// @brief sets storage for value of this parameter
    ///
533
    /// See \ref dhcpv4ConfigInherit for details.
534 535 536 537 538 539
    ///
    /// @param storage pointer to the storage container
    void setStorage(PoolStorage* storage) {
        pools_ = storage;
    }

540 541 542 543 544 545 546 547 548 549 550
    /// @brief Stores the parsed values in a storage provided
    ///        by an upper level parser.
    virtual void commit() {
        if (pools_) {
            // local_pools_ holds the values produced by the build function.
            // At this point parsing should have completed successfuly so
            // we can append new data to the supplied storage.
            pools_->insert(pools_->end(), local_pools_.begin(),
                           local_pools_.end());
        }
    }
551 552 553 554

    /// @brief factory that constructs PoolParser objects
    ///
    /// @param param_name name of the parameter to be parsed
555
    static DhcpConfigParser* factory(const std::string& param_name) {
556 557 558
        return (new PoolParser(param_name));
    }

Tomek Mrugalski's avatar
Tomek Mrugalski committed
559
private:
560 561 562 563 564
    /// @brief pointer to the actual Pools storage
    ///
    /// That is typically a storage somewhere in Subnet parser
    /// (an upper level parser).
    PoolStorage* pools_;
565 566 567
    /// A temporary storage for pools configuration. It is a
    /// storage where pools are stored by build function.
    PoolStorage local_pools_;
568 569
};

570 571 572 573
/// @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
574
/// and data carried by the option. If parsing is successful then an
575 576 577 578
/// instance of an option is created and added to the storage provided
/// by the calling class.
///
/// @todo This class parses and validates the option name. However it is
579
/// not used anywhere until support for option spaces is implemented
580 581 582
/// (see tickets #2319, #2314). When option spaces are implemented
/// there will be a way to reference the particular option using
/// its type (code) or option name.
583
class OptionDataParser : public DhcpConfigParser {
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
public:

    /// @brief Constructor.
    ///
    /// Class constructor.
    OptionDataParser(const std::string&)
        : options_(NULL),
          // initialize option to NULL ptr
          option_descriptor_(false) { }

    /// @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.
    ///
    /// @warning setStorage must be called with valid storage pointer prior
    /// to calling this method.
    ///
    /// @param option_data_entries collection of entries that define value
    /// for a particular option.
    /// @throw Dhcp4ConfigError if invalid parameter specified in
    /// the configuration.
    /// @throw isc::InvalidOperation if failed to set storage prior to
    /// calling build.
    /// @throw isc::BadValue if option data storage is invalid.
    virtual void build(ConstElementPtr option_data_entries) {
        if (options_ == NULL) {
            isc_throw(isc::InvalidOperation, "Parser logic error: storage must be set before "
                      "parsing option data.");
        }
        BOOST_FOREACH(ConfigPair param, option_data_entries->mapValue()) {
            ParserPtr parser;
            if (param.first == "name") {
                boost::shared_ptr<StringParser>
620
                    name_parser(dynamic_cast<StringParser*>(StringParser::factory(param.first)));
621 622 623 624 625 626
                if (name_parser) {
                    name_parser->setStorage(&string_values_);
                    parser = name_parser;
                }
            } else if (param.first == "code") {
                boost::shared_ptr<Uint32Parser>
627
                    code_parser(dynamic_cast<Uint32Parser*>(Uint32Parser::factory(param.first)));
628 629 630 631 632 633
                if (code_parser) {
                    code_parser->setStorage(&uint32_values_);
                    parser = code_parser;
                }
            } else if (param.first == "data") {
                boost::shared_ptr<StringParser>
634
                    value_parser(dynamic_cast<StringParser*>(StringParser::factory(param.first)));
635 636 637 638
                if (value_parser) {
                    value_parser->setStorage(&string_values_);
                    parser = value_parser;
                }
639 640
            } else if (param.first == "csv-format") {
                boost::shared_ptr<BooleanParser>
641
                    value_parser(dynamic_cast<BooleanParser*>(BooleanParser::factory(param.first)));
642 643 644 645
                if (value_parser) {
                    value_parser->setStorage(&boolean_values_);
                    parser = value_parser;
                }
646 647 648 649 650 651
            } else {
                isc_throw(Dhcp4ConfigError,
                          "Parser error: option-data parameter not supported: "
                          << param.first);
            }
            parser->build(param.second);
652 653 654 655 656 657 658
            // Before we can create an option we need to get the data from
            // the child parsers. The only way to do it is to invoke commit
            // on them so as they store the values in appropriate storages
            // that this class provided to them. Note that this will not
            // modify values stored in the global storages so the configuration
            // will remain consistent even parsing fails somewhere further on.
            parser->commit();
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
        }
        // Try to create the option instance.
        createOption();
    }

    /// @brief Commits option value.
    ///
    /// This function adds a new option to the storage or replaces an existing option
    /// with the same code.
    ///
    /// @throw isc::InvalidOperation if failed to set pointer to storage or failed
    /// to call build() prior to commit. If that happens data in the storage
    /// remain un-modified.
    virtual void commit() {
        if (options_ == NULL) {
            isc_throw(isc::InvalidOperation, "Parser logic error: storage must be set before "
                      "commiting option data.");
        } else  if (!option_descriptor_.option) {
            // Before we can commit the new option should be configured. If it is not
            // than somebody must have called commit() before build().
            isc_throw(isc::InvalidOperation, "Parser logic error: no option has been configured and"
                      " thus there is nothing to commit. Has build() been called?");
        }
        uint16_t opt_type = option_descriptor_.option->getType();
        Subnet::OptionContainerTypeIndex& idx = options_->get<1>();
        // Try to find options with the particular option code in the main
        // storage. If found, remove these options because they will be
        // replaced with new one.
        Subnet::OptionContainerTypeRange range =
            idx.equal_range(opt_type);
        if (std::distance(range.first, range.second) > 0) {
            idx.erase(range.first, range.second);
        }
        // Append new option to the main storage.
        options_->push_back(option_descriptor_);
    }

    /// @brief Set storage for the parser.
    ///
    /// Sets storage for the parser. This storage points to the
    /// vector of options and is used by multiple instances of
    /// OptionDataParser. Each instance creates exactly one object
    /// of dhcp::Option or derived type and appends it to this
    /// storage.
    ///
    /// @param storage pointer to the options storage
    void setStorage(OptionStorage* storage) {
        options_ = storage;
    }

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 Dhcp4ConfigError if parameters provided in the configuration
    /// are invalid.
    void createOption() {
        // Option code is held in the uint32_t storage but is supposed to
        // be uint16_t value. We need to check that value in the configuration
        // does not exceed range of uint16_t and is not zero.
        uint32_t option_code = getUint32Param("code");
        if (option_code == 0) {
            isc_throw(Dhcp4ConfigError, "Parser error: value of 'code' must not"
                      << " be equal to zero. Option code '0' is reserved in"
                      << " DHCPv4.");
        } else if (option_code > std::numeric_limits<uint16_t>::max()) {
            isc_throw(Dhcp4ConfigError, "Parser error: value of 'code' must not"
                      << " exceed " << std::numeric_limits<uint16_t>::max());
        }
        // Check that the option name has been specified, is non-empty and does not
        // contain spaces.
        // @todo possibly some more restrictions apply here?
        std::string option_name = getStringParam("name");
        if (option_name.empty()) {
            isc_throw(Dhcp4ConfigError, "Parser error: option name must not be"
                      << " empty");
        } else if (option_name.find(" ") != std::string::npos) {
            isc_throw(Dhcp4ConfigError, "Parser error: option name must not contain"
                      << " spaces");
        }

        // Get option data from the configuration database ('data' field).
749 750
        const std::string option_data = getStringParam("data");
        const bool csv_format = getBooleanParam("csv-format");
751 752
        // Transform string of hexadecimal digits into binary format.
        std::vector<uint8_t> binary;
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
        std::vector<std::string> data_tokens;

        if (csv_format) {
            // If the option data is specified as a string of comma
            // separated values then we need to split this string into
            // individual values - each value will be used to initialize
            // one data field of an option.
            data_tokens = isc::util::str::tokens(option_data, ",");
        } else {
            // Otherwise, the option data is specified as a string of
            // hexadecimal digits that we have to turn into binary format.
            try {
                util::encode::decodeHex(option_data, binary);
            } catch (...) {
                isc_throw(Dhcp4ConfigError, "Parser error: option data is not a valid"
                          << " string of hexadecimal digits: " << option_data);
            }
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
        }
        // Get all existing DHCPv4 option definitions. The one that matches
        // our option will be picked and used to create it.
        OptionDefContainer option_defs = LibDHCP::getOptionDefs(Option::V4);
        // Get search index #1. It allows searching for options definitions
        // using option type value.
        const OptionDefContainerTypeIndex& idx = option_defs.get<1>();
        // Get all option definitions matching option code we want to create.
        const OptionDefContainerTypeRange& range = idx.equal_range(option_code);
        size_t num_defs = std::distance(range.first, range.second);
        OptionPtr option;
        // Currently we do not allow duplicated definitions and if there are
        // any duplicates we issue internal server error.
        if (num_defs > 1) {
            isc_throw(Dhcp4ConfigError, "Internal error: currently it is not"
                      << " supported to initialize multiple option definitions"
                      << " for the same option code. This will be supported once"
                      << " there option spaces are implemented.");
        } else if (num_defs == 0) {
789 790 791 792 793 794 795
            if (csv_format) {
                isc_throw(Dhcp4ConfigError, "the CSV option data format can be"
                          " used to specify values for an option that has a"
                          " definition. The option with code " << option_code
                          << " does not have a definition.");
            }

796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
            // @todo We have a limited set of option definitions intiialized at the moment.
            // In the future we want to initialize option definitions for all options.
            // Consequently an error will be issued if an option definition does not exist
            // for a particular option code. For now it is ok to create generic option
            // if definition does not exist.
            OptionPtr option(new Option(Option::V4, static_cast<uint16_t>(option_code),
                                        binary));
            // The created option is stored in option_descriptor_ class member until the
            // commit stage when it is inserted into the main storage. If an option with the
            // same code exists in main storage already the old option is replaced.
            option_descriptor_.option = option;
            option_descriptor_.persistent = false;
        } else {
            // We have exactly one option definition for the particular option code
            // use it to create the option instance.
            const OptionDefinitionPtr& def = *(range.first);
            try {
813 814 815
                OptionPtr option = csv_format ?
                    def->optionFactory(Option::V4, option_code, data_tokens) :
                    def->optionFactory(Option::V4, option_code, binary);
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
                Subnet::OptionDescriptor desc(option, false);
                option_descriptor_.option = option;
                option_descriptor_.persistent = false;
            } catch (const isc::Exception& ex) {
                isc_throw(Dhcp4ConfigError, "Parser error: option data does not match"
                          << " option definition (code " << option_code << "): "
                          << ex.what());
            }
        }
    }

    /// @brief Get a parameter from the strings storage.
    ///
    /// @param param_id parameter identifier.
    /// @throw Dhcp4ConfigError if parameter has not been found.
    std::string getStringParam(const std::string& param_id) const {
        StringStorage::const_iterator param = string_values_.find(param_id);
        if (param == string_values_.end()) {
            isc_throw(Dhcp4ConfigError, "Parser error: option-data parameter"
                      << " '" << param_id << "' not specified");
        }
        return (param->second);
    }

    /// @brief Get a parameter from the uint32 values storage.
    ///
    /// @param param_id parameter identifier.
    /// @throw Dhcp4ConfigError if parameter has not been found.
    uint32_t getUint32Param(const std::string& param_id) const {
        Uint32Storage::const_iterator param = uint32_values_.find(param_id);
        if (param == uint32_values_.end()) {
            isc_throw(Dhcp4ConfigError, "Parser error: option-data parameter"
                      << " '" << param_id << "' not specified");
        }
        return (param->second);
    }

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
    /// @brief Get a parameter from the boolean values storage.
    ///
    /// @param param_id parameter identifier.
    ///
    /// @throw isc::dhcp::Dhcp6ConfigError if a parameter has not been found.
    /// @return a value of the boolean parameter.
    bool getBooleanParam(const std::string& param_id) const {
        BooleanStorage::const_iterator param = boolean_values_.find(param_id);
        if (param == boolean_values_.end()) {
            isc_throw(isc::dhcp::Dhcp4ConfigError, "parser error: option-data parameter"
                      << " '" << param_id << "' not specified");
        }
        return (param->second);
    }

868 869 870 871
    /// Storage for uint32 values (e.g. option code).
    Uint32Storage uint32_values_;
    /// Storage for string values (e.g. option name or data).
    StringStorage string_values_;
872 873
    /// Storage for boolean values.
    BooleanStorage boolean_values_;
874 875 876 877 878 879 880 881 882 883 884 885 886
    /// Pointer to options storage. This storage is provided by
    /// the calling class and is shared by all OptionDataParser objects.
    OptionStorage* options_;
    /// Option descriptor holds newly configured option.
    Subnet::OptionDescriptor option_descriptor_;
};

/// @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.
887
class OptionDataListParser : public DhcpConfigParser {
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
public:

    /// @brief Constructor.
    ///
    /// Unless otherwise specified, parsed options will be stored in
    /// a global option container (option_default). That storage location
    /// is overriden on a subnet basis.
    OptionDataListParser(const std::string&)
        : options_(&option_defaults), local_options_() { }

    /// @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 Dhcp4ConfigError if option parsing failed.
    void build(ConstElementPtr option_data_list) {
        BOOST_FOREACH(ConstElementPtr option_value, option_data_list->listValue()) {
            boost::shared_ptr<OptionDataParser> parser(new OptionDataParser("option-data"));
            // options_ member will hold instances of all options thus
            // each OptionDataParser takes it as a storage.
            parser->setStorage(&local_options_);
            // Build the instance of a single option.
            parser->build(option_value);
            // Store a parser as it will be used to commit.
            parsers_.push_back(parser);
        }
    }

    /// @brief Set storage for option instances.
    ///
    /// @param storage pointer to options storage.
    void setStorage(OptionStorage* storage) {
        options_ = storage;
    }


    /// @brief Commit all option values.
    ///
    /// This function invokes commit for all option values.
    void commit() {
        BOOST_FOREACH(ParserPtr parser, parsers_) {
            parser->commit();
        }
        // Parsing was successful and we have all configured
        // options in local storage. We can now replace old values
        // with new values.
        std::swap(local_options_, *options_);
    }

    /// @brief Create DhcpDataListParser object
    ///
    /// @param param_name param name.
    ///
    /// @return DhcpConfigParser object.
944
    static DhcpConfigParser* factory(const std::string& param_name) {
945 946 947 948 949 950 951 952 953 954 955 956 957 958
        return (new OptionDataListParser(param_name));
    }

    /// 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.
    OptionStorage local_options_;
    /// Pointer to options instances storage.
    OptionStorage* options_;
    /// Collection of parsers;
    ParserCollection parsers_;
};

959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 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
/// @brief Parser for a single option definition.
///
/// This parser creates an instance of a single option definition.
class OptionDefParser: DhcpConfigParser {
public:

    /// @brief Constructor.
    ///
    /// This constructor sets the pointer to the option definitions
    /// storage to NULL. It must be set to point to the actual storage
    /// before \ref build is called.
    OptionDefParser(const std::string&)
        : storage_(NULL) {
    }

    /// @brief Parses an entry that describes single option definition.
    ///
    /// @param option_def a configuration entry to be parsed.
    ///
    /// @throw Dhcp4ConfigError if parsing was unsuccessful.
    void build(ConstElementPtr option_def) {
    }

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

    /// @brief Sets a pointer to a storage.
    ///
    /// The newly created instance of an option definition will be
    /// added to a storage given by the argument.
    ///
    /// @param storage pointer to a storage where the option definition
    /// will be added to.
    void setStorage(OptionDefContainer* storage) {
        storage_ = storage;
    }

private:

    /// Instance of option definition being created by this parser.
    OptionDefinitionPtr option_definition_;

    /// Pointer to a storage where the option definition will be
    /// added when \ref commit is called.
    OptionDefContainer* storage_;
};

/// @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 : DhcpConfigParser {
public:

    /// @brief Constructor.
    ///
    /// This constructor initializes the pointer to option definitions
    /// storage to NULL value. This pointer has to be set to point to
    /// the actual storage before the \ref build function is called.
    OptionDefListParser(const std::string&)
        : option_defs_(NULL) {
    }

    /// @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 Dhcp4ConfigError if configuration parsing fails.
    void build(ConstElementPtr option_def_list) {
        if (!option_def_list) {
            isc_throw(Dhcp4ConfigError, "parser error: a pointer to a list of"
                      << " option definitions is NULL");
        } else if (option_defs_ == NULL) {
            isc_throw(Dhcp4ConfigError, "parser error: the storage for option"
                      << " definitions must be set before parsing option"
                      << " definitions");
        }

        BOOST_FOREACH(ConstElementPtr option_def, option_def_list->listValue()) {
            boost::shared_ptr<OptionDefParser>
                parser(new OptionDefParser("single-option-def"));
            parser->setStorage(&option_defs_local_);
            parser->build(option_def);
        }
    }

    /// @brief Stores option definitions in the provided storage.
    void commit() {
    }

    /// @brief Create an OptionDefListParser object.
    ///
    /// @param param_name configuration entry holding option definitions.
    ///
    /// @return OptionDefListParser object.
    static DhcpConfigParser* factory(const std::string& param_name) {
        return (new OptionDefListParser(param_name));
    }

    /// @brief Set storage for option definition instances.
    ///
    /// @param storage pointer to the option definition storage
    /// where created option instances should be stored.
    void setStorage(OptionDefContainer* storage) {
        option_defs_ = storage;
    }

private:

    /// Pointer to the container where option definitions should
    /// be stored when \ref commit is called.
    OptionDefContainer* option_defs_;

    /// Temporary storage for option definitions. It holds option
    /// definitions before \ref commit is called.
    OptionDefContainer option_defs_local_;
};

1083 1084 1085 1086
/// @brief this class parses a single subnet
///
/// This class parses the whole subnet definition. It creates parsers
/// for received configuration parameters as needed.
1087
class Subnet4ConfigParser : public DhcpConfigParser {
1088 1089 1090 1091 1092
public:

    /// @brief constructor
    Subnet4ConfigParser(const std::string& ) {
        // The parameter should always be "subnet", but we don't check here
1093
        // against it in case someone wants to reuse this parser somewhere.
1094 1095 1096 1097 1098 1099 1100 1101 1102
    }

    /// @brief parses parameter value
    ///
    /// @param subnet pointer to the content of subnet definition
    void build(ConstElementPtr subnet) {

        BOOST_FOREACH(ConfigPair param, subnet->mapValue()) {
            ParserPtr parser(createSubnet4ConfigParser(param.first));
1103 1104 1105 1106 1107 1108 1109
            // The actual type of the parser is unknown here. We have to discover
            // the parser type here to invoke the corresponding setStorage function
            // on it.  We discover parser type by trying to cast the parser to various
            // parser types and checking which one was successful. For this one
            // a setStorage and build methods are invoked.

            // Try uint32 type parser.
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
            if (!buildParser<Uint32Parser, Uint32Storage >(parser, uint32_values_,
                                                          param.second) &&
                // Try string type parser.
                !buildParser<StringParser, StringStorage >(parser, string_values_,
                                                           param.second) &&
                // Try pool parser.
                !buildParser<PoolParser, PoolStorage >(parser, pools_,
                                                       param.second) &&
                // Try option data parser.
                !buildParser<OptionDataListParser, OptionStorage >(parser, options_,
                                                                   param.second)) {
                // Appropriate parsers are created in the createSubnet6ConfigParser
                // and they should be limited to those that we check here for. Thus,
                // if we fail to find a matching parser here it is a programming error.
                isc_throw(Dhcp4ConfigError, "failed to find suitable parser");
1125 1126
            }
        }
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
        // In order to create new subnet we need to get the data out
        // of the child parsers first. The only way to do it is to
        // invoke commit on them because it will make them write
        // parsed data into storages we have supplied.
        // Note that triggering commits on child parsers does not
        // affect global data because we supplied pointers to storages
        // local to this object. Thus, even if this method fails
        // later on, the configuration remains consistent.
        BOOST_FOREACH(ParserPtr parser, parsers_) {
            parser->commit();
        }

        // Create a subnet.
        createSubnet();
1141 1142 1143 1144 1145 1146 1147 1148
    }

    /// @brief commits received configuration.
    ///
    /// This method does most of the configuration. Many other parsers are just
    /// storing the values that are actually consumed here. Pool definitions
    /// created in other parsers are used here and added to newly created Subnet4
    /// objects. Subnet4 are then added to DHCP CfgMgr.
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1149
    /// @throw Dhcp4ConfigError if there are any issues encountered during commit
1150
    void commit() {
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
        if (subnet_) {
            CfgMgr::instance().addSubnet4(subnet_);
        }
    }

private:

    /// @brief Set storage for a parser and invoke build.
    ///
    /// This helper method casts the provided parser pointer to the specified
    /// type. If the cast is successful it sets the corresponding storage for
    /// this parser, invokes build on it and saves the parser.
    ///
    /// @tparam T parser type to which parser argument should be cast.
    /// @tparam Y storage type for the specified parser type.
    /// @param parser parser on which build must be invoked.
    /// @param storage reference to a storage that will be set for a parser.
    /// @param subnet subnet element read from the configuration and being parsed.
    /// @return true if parser pointer was successfully cast to specialized
    /// parser type provided as Y.
    template<typename T, typename Y>
    bool buildParser(const ParserPtr& parser, Y& storage, const ConstElementPtr& subnet) {
        // We need to cast to T in order to set storage for the parser.
        boost::shared_ptr<T> cast_parser = boost::dynamic_pointer_cast<T>(parser);
        // It is common that this cast is not successful because we try to cast to all
        // supported parser types as we don't know the type of a parser in advance.
        if (cast_parser) {
            // Cast, successful so we go ahead with setting storage and actual parse.
            cast_parser->setStorage(&storage);
            parser->build(subnet);
            parsers_.push_back(parser);
            // We indicate that cast was successful so as the calling function
            // may skip attempts to cast to other parser types and proceed to
            // next element.
            return (true);
1186
        }
1187 1188 1189 1190
        // It was not successful. Indicate that another parser type
        // should be tried.
        return (false);
    }
1191

1192 1193 1194 1195
    /// @brief Create a new subnet using a data from child parsers.
    ///
    /// @throw isc::dhcp::Dhcp4ConfigError if subnet configuration parsing failed.
    void createSubnet() {
1196 1197 1198 1199 1200
        StringStorage::const_iterator it = string_values_.find("subnet");
        if (it == string_values_.end()) {
            isc_throw(Dhcp4ConfigError,
                      "Mandatory subnet definition in subnet missing");
        }
1201
        // Remove any spaces or tabs.
1202 1203 1204 1205
        string subnet_txt = it->second;
        boost::erase_all(subnet_txt, " ");
        boost::erase_all(subnet_txt, "\t");

1206 1207 1208 1209 1210
        // The subnet format is prefix/len. We are going to extract
        // the prefix portion of a subnet string to create IOAddress
        // object from it. IOAddress will be passed to the Subnet's
        // constructor later on. In order to extract the prefix we
        // need to get all characters preceding "/".
1211 1212 1213 1214 1215
        size_t pos = subnet_txt.find("/");
        if (pos == string::npos) {
            isc_throw(Dhcp4ConfigError,
                      "Invalid subnet syntax (prefix/len expected):" << it->second);
        }
1216 1217 1218

        // Try to create the address object. It also validates that
        // the address syntax is ok.
1219 1220 1221
        IOAddress addr(subnet_txt.substr(0, pos));
        uint8_t len = boost::lexical_cast<unsigned int>(subnet_txt.substr(pos + 1));

1222 1223 1224 1225 1226
        // Get all 'time' parameters using inheritance.
        // If the subnet-specific value is defined then use it, else
        // use the global value. The global value must always be
        // present. If it is not, it is an internal error and exception
        // is thrown.
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
        Triplet<uint32_t> t1 = getParam("renew-timer");
        Triplet<uint32_t> t2 = getParam("rebind-timer");
        Triplet<uint32_t> valid = getParam("valid-lifetime");

        /// @todo: Convert this to logger once the parser is working reliably
        stringstream tmp;
        tmp << addr.toText() << "/" << (int)len
            << " with params t1=" << t1 << ", t2=" << t2 << ", valid=" << valid;

        LOG_INFO(dhcp4_logger, DHCP4_CONFIG_NEW_SUBNET).arg(tmp.str());

1238
        subnet_.reset(new Subnet4(addr, len, t1, t2, valid));
1239 1240

        for (PoolStorage::iterator it = pools_.begin(); it != pools_.end(); ++it) {
1241
            subnet_->addPool4(*it);
1242 1243
        }

1244
        Subnet::OptionContainerPtr options = subnet_->getOptionDescriptors("dhcp4");
1245
        const Subnet::OptionContainerTypeIndex& idx = options->get<1>();
1246 1247 1248 1249 1250 1251 1252 1253

        // Add subnet specific options.
        BOOST_FOREACH(Subnet::OptionDescriptor desc, options_) {
            Subnet::OptionContainerTypeRange range = idx.equal_range(desc.option->getType());
            if (std::distance(range.first, range.second) > 0) {
                LOG_WARN(dhcp4_logger, DHCP4_CONFIG_OPTION_DUPLICATE)
                    .arg(desc.option->getType()).arg(addr.toText());
            }
1254
            subnet_->addOption(desc.option, false, "dhcp4");
1255 1256
        }

1257 1258 1259 1260 1261 1262 1263
        // Check all global options and add them to the subnet object if
        // they have been configured in the global scope. If they have been
        // configured in the subnet scope we don't add global option because
        // the one configured in the subnet scope always takes precedence.
        BOOST_FOREACH(Subnet::OptionDescriptor desc, option_defaults) {
            // Get all options specified locally in the subnet and having
            // code equal to global option's code.
1264
            Subnet::OptionContainerPtr options = subnet_->getOptionDescriptors("dhcp4");
1265
            const Subnet::OptionContainerTypeIndex& idx = options->get<1>();
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
            Subnet::OptionContainerTypeRange range = idx.equal_range(desc.option->getType());
            // @todo: In the future we will be searching for options using either
            // an option code or namespace. Currently we have only the option
            // code available so if there is at least one option found with the
            // specific code we don't add the globally configured option.
            // @todo with this code the first globally configured option
            // with the given code will be added to a subnet. We may
            // want to issue a warning about dropping the configuration of
            // a global option if one already exsists.
            if (std::distance(range.first, range.second) == 0) {
1276
                subnet_->addOption(desc.option, false, "dhcp4");
1277 1278
            }
        }
1279 1280
    }

1281 1282 1283 1284 1285 1286
    /// @brief creates parsers for entries in subnet definition
    ///
    /// @todo Add subnet-specific things here (e.g. subnet-specific options)
    ///
    /// @param config_id name od the entry
    /// @return parser object for specified entry name
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1287
    /// @throw NotImplemented if trying to create a parser for unknown config element
1288
    DhcpConfigParser* createSubnet4ConfigParser(const std::string& config_id) {
1289 1290
        FactoryMap factories;

1291 1292 1293 1294 1295 1296
        factories["valid-lifetime"] = Uint32Parser::factory;
        factories["renew-timer"] = Uint32Parser::factory;
        factories["rebind-timer"] = Uint32Parser::factory;
        factories["subnet"] = StringParser::factory;
        factories["pool"] = PoolParser::factory;
        factories["option-data"] = OptionDataListParser::factory;
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317

        FactoryMap::iterator f = factories.find(config_id);
        if (f == factories.end()) {
            // Used for debugging only.
            // return new DebugParser(config_id);

            isc_throw(NotImplemented,
                      "Parser error: Subnet4 parameter not supported: "
                      << config_id);
        }
        return (f->second(config_id));
    }

    /// @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
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1318
    /// @throw Dhcp4ConfigError when requested parameter is not present
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
    Triplet<uint32_t> getParam(const std::string& name) {
        uint32_t value = 0;
        bool found = false;
        Uint32Storage::iterator global = uint32_defaults.find(name);
        if (global != uint32_defaults.end()) {
            value = global->second;
            found = true;
        }

        Uint32Storage::iterator local = uint32_values_.find(name);
        if (local != uint32_values_.end()) {
            value = local->second;
            found = true;
        }

        if (found) {
            return (Triplet<uint32_t>(value));
        } else {
            isc_throw(Dhcp4ConfigError, "Mandatory parameter " << name
                      << " missing (no global default and no subnet-"
                      << "specific value)");
        }
    }

    /// storage for subnet-specific uint32 values
    Uint32Storage uint32_values_;

    /// storage for subnet-specific integer values
    StringStorage string_values_;

    /// storage for pools belonging to this subnet
    PoolStorage pools_;

1352 1353 1354
    /// storage for options belonging to this subnet
    OptionStorage options_;

1355 1356
    /// parsers are stored here
    ParserCollection parsers_;
1357 1358 1359

    /// @brief Pointer to the created subnet object.
    isc::dhcp::Subnet4Ptr subnet_;
1360 1361 1362 1363 1364 1365 1366
};

/// @brief this class parses list of subnets
///
/// This is a wrapper parser that handles the whole list of Subnet4
/// definitions. It iterates over all entries and creates Subnet4ConfigParser
/// for each entry.
1367
class Subnets4ListConfigParser : public DhcpConfigParser {
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
public:

    /// @brief constructor
    ///
    Subnets4ListConfigParser(const std::string&) {
        /// parameter name is ignored
    }

    /// @brief parses contents of the list
    ///
    /// Iterates over all entries on the list and creates Subnet4ConfigParser
    /// for each entry.
    ///
    /// @param subnets_list pointer to a list of IPv4 subnets
    void build(ConstElementPtr subnets_list) {

        // No need to define FactoryMap here. There's only one type
        // used: Subnet4ConfigParser

        BOOST_FOREACH(ConstElementPtr subnet, subnets_list->listValue()) {
            ParserPtr parser(new Subnet4ConfigParser("subnet"));
            parser->build(subnet);
            subnets_.push_back(parser);
        }

    }

    /// @brief commits subnets definitions.
    ///
    /// Iterates over all Subnet4 parsers. Each parser contains definitions
    /// of a single subnet and its parameters and commits each subnet separately.
    void commit() {
        // @todo: Implement more subtle reconfiguration than toss
        // the old one and replace with the new one.

        // remove old subnets
        CfgMgr::instance().deleteSubnets4();

        BOOST_FOREACH(ParserPtr subnet, subnets_) {
            subnet->commit();
        }

    }

    /// @brief Returns Subnet4ListConfigParser object
    /// @param param_name name of the parameter
    /// @return Subnets4ListConfigParser object
1415
    static DhcpConfigParser* factory(const std::string& param_name) {
1416 1417 1418 1419 1420
        return (new Subnets4ListConfigParser(param_name));
    }

    /// @brief collection of subnet parsers.
    ParserCollection subnets_;
1421

1422 1423
};

1424 1425 1426 1427 1428
} // anonymous namespace

namespace isc {
namespace dhcp {

1429 1430 1431 1432 1433 1434 1435
/// @brief creates global parsers
///
/// This method creates global parsers that parse global parameters, i.e.
/// those that take format of Dhcp4/param1, Dhcp4/param2 and so forth.
///
/// @param config_id pointer to received global configuration entry
/// @return parser for specified global DHCPv4 parameter
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1436
/// @throw NotImplemented if trying to create a parser for unknown config element
1437
DhcpConfigParser* createGlobalDhcp4ConfigParser(const std::string& config_id) {
1438 1439
    FactoryMap factories;