dhcp_parsers.cc 48.3 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
//
// 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.

15
#include <dhcp/iface_mgr.h>
16 17
#include <dhcp/libdhcp++.h>
#include <dhcpsrv/cfgmgr.h>
18
#include <dhcpsrv/dhcp_parsers.h>
19
#include <hooks/hooks_manager.h>
20 21 22
#include <util/encode/hex.h>
#include <util/strutil.h>

23
#include <boost/algorithm/string.hpp>
24 25 26 27
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>

#include <map>
28 29
#include <string>
#include <vector>
30 31 32

using namespace std;
using namespace isc::data;
33
using namespace isc::hooks;
34 35 36 37

namespace isc {
namespace dhcp {

38
namespace {
39
const char* ALL_IFACES_KEYWORD = "*";
40 41
}

42 43 44
// *********************** ParserContext  *************************

ParserContext::ParserContext(Option::Universe universe):
Mukund Sivaraman's avatar
Mukund Sivaraman committed
45 46 47 48 49
    boolean_values_(new BooleanStorage()),
    uint32_values_(new Uint32Storage()),
    string_values_(new StringStorage()),
    options_(new OptionStorage()),
    option_defs_(new OptionDefStorage()),
50
    hooks_libraries_(),
Mukund Sivaraman's avatar
Mukund Sivaraman committed
51 52 53
    universe_(universe)
{
}
54

55
ParserContext::ParserContext(const ParserContext& rhs):
56 57 58 59 60 61
    boolean_values_(),
    uint32_values_(),
    string_values_(),
    options_(),
    option_defs_(),
    hooks_libraries_(),
Mukund Sivaraman's avatar
Mukund Sivaraman committed
62 63
    universe_(rhs.universe_)
{
64
    copyContext(rhs);
Mukund Sivaraman's avatar
Mukund Sivaraman committed
65
}
66

67
ParserContext&
68 69 70
// The cppcheck version 1.56 doesn't recognize that copyContext
// copies all context fields.
// cppcheck-suppress operatorEqVarError
71
ParserContext::operator=(const ParserContext& rhs) {
Mukund Sivaraman's avatar
Mukund Sivaraman committed
72
    if (this != &rhs) {
73
        copyContext(rhs);
74
    }
75

Mukund Sivaraman's avatar
Mukund Sivaraman committed
76 77
    return (*this);
}
78

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
void
ParserContext::copyContext(const ParserContext& ctx) {
    copyContextPointer(ctx.boolean_values_, boolean_values_);
    copyContextPointer(ctx.uint32_values_, uint32_values_);
    copyContextPointer(ctx.string_values_, string_values_);
    copyContextPointer(ctx.options_, options_);
    copyContextPointer(ctx.option_defs_, option_defs_);
    copyContextPointer(ctx.hooks_libraries_, hooks_libraries_);
    // Copy universe.
    universe_ = ctx.universe_;
}

template<typename T>
void
ParserContext::copyContextPointer(const boost::shared_ptr<T>& source_ptr,
                                  boost::shared_ptr<T>& dest_ptr) {
    if (source_ptr) {
        dest_ptr.reset(new T(*source_ptr));
    } else {
        dest_ptr.reset();
    }
}

102

103 104 105 106 107 108
// **************************** DebugParser *************************

DebugParser::DebugParser(const std::string& param_name)
    :param_name_(param_name) {
}

109
void
110
DebugParser::build(ConstElementPtr new_config) {
111
    value_ = new_config;
112
    std::cout << "Build for token: [" << param_name_ << "] = ["
113
        << value_->str() << "]" << std::endl;
114 115
}

116
void
117
DebugParser::commit() {
118 119 120 121 122 123 124 125
    // Debug message. The whole DebugParser class is used only for parser
    // debugging, and is not used in production code. It is very convenient
    // to keep it around. Please do not turn this cout into logger calls.
    std::cout << "Commit for token: [" << param_name_ << "] = ["
                  << value_->str() << "]" << std::endl;
}

// **************************** BooleanParser  *************************
126

127
template<> void ValueParser<bool>::build(isc::data::ConstElementPtr value) {
128 129
    // The Config Manager checks if user specified a
    // valid value for a boolean parameter: True or False.
130 131 132 133
    // We should have a boolean Element, use value directly
    try {
        value_ = value->boolValue();
    } catch (const isc::data::TypeError &) {
134
        isc_throw(BadValue, " Wrong value type for " << param_name_
135 136
                  << " : build called with a non-boolean element.");
    }
137 138 139 140
}

// **************************** Uin32Parser  *************************

141
template<> void ValueParser<uint32_t>::build(ConstElementPtr value) {
142 143 144 145 146 147 148 149 150 151 152 153 154 155
    int64_t check;
    string x = value->str();
    try {
        check = boost::lexical_cast<int64_t>(x);
    } catch (const boost::bad_lexical_cast &) {
        isc_throw(BadValue, "Failed to parse value " << value->str()
                  << " as unsigned 32-bit integer.");
    }
    if (check > std::numeric_limits<uint32_t>::max()) {
        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."
156
               << " Only 0 or larger are allowed for unsigned 32-bit integer.");
157 158 159 160 161 162 163 164
    }

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

// **************************** StringParser  *************************

165
template <> void ValueParser<std::string>::build(ConstElementPtr value) {
166 167 168 169
    value_ = value->str();
    boost::erase_all(value_, "\"");
}

170
// ******************** InterfaceListConfigParser *************************
171

172 173 174 175 176
InterfaceListConfigParser::
InterfaceListConfigParser(const std::string& param_name)
    : activate_all_(false),
      param_name_(param_name) {
    if (param_name_ != "interfaces") {
177 178 179 180 181
        isc_throw(BadValue, "Internal error. Interface configuration "
            "parser called for the wrong parameter: " << param_name);
    }
}

182
void
183
InterfaceListConfigParser::build(ConstElementPtr value) {
184 185 186
    // First, we iterate over all specified entries and add it to the
    // local container so as we can do some basic validation, e.g. eliminate
    // duplicates.
187
    BOOST_FOREACH(ConstElementPtr iface, value->listValue()) {
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        std::string iface_name = iface->stringValue();
        if (iface_name != ALL_IFACES_KEYWORD) {
            // Let's eliminate duplicates. We could possibly allow duplicates,
            // but if someone specified duplicated interface name it is likely
            // that he mistyped the configuration. Failing here should draw his
            // attention.
            if (isIfaceAdded(iface_name)) {
                isc_throw(isc::dhcp::DhcpConfigError, "duplicate interface"
                          << " name '" << iface_name << "' specified in '"
                          << param_name_ << "' configuration parameter");
            }
            // @todo check that this interface exists in the system!
            // The IfaceMgr exposes mechanisms to check this.

            // Add the interface name if ok.
            interfaces_.push_back(iface_name);

        } else {
            activate_all_ = true;

        }
209 210 211
    }
}

212
void
213
InterfaceListConfigParser::commit() {
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    CfgMgr& cfg_mgr = CfgMgr::instance();
    // Remove active interfaces and clear a flag which marks all interfaces
    // active
    cfg_mgr.deleteActiveIfaces();

    if (activate_all_) {
        // Activate all interfaces. There is not need to add their names
        // explicitly.
        cfg_mgr.activateAllIfaces();

    } else {
        // Explicitly add names of the interfaces which server should listen on.
        BOOST_FOREACH(std::string iface, interfaces_) {
            cfg_mgr.addActiveIface(iface);
        }
    }
}

bool
InterfaceListConfigParser::isIfaceAdded(const std::string& iface) const {
234

235 236 237 238 239 240 241
    for (IfaceListStorage::const_iterator it = interfaces_.begin();
         it != interfaces_.end(); ++it) {
        if (iface == *it) {
            return (true);
        }
    }
    return (false);
242 243
}

Stephen Morris's avatar
Stephen Morris committed
244 245
// ******************** HooksLibrariesParser *************************

246 247 248 249 250
HooksLibrariesParser::HooksLibrariesParser(const std::string& param_name)
    : libraries_(), changed_(false)
{
    // Sanity check on the name.
    if (param_name != "hooks-libraries") {
Stephen Morris's avatar
Stephen Morris committed
251 252 253 254 255
        isc_throw(BadValue, "Internal error. Hooks libraries "
            "parser called for the wrong parameter: " << param_name);
    }
}

Mukund Sivaraman's avatar
Mukund Sivaraman committed
256
void
Stephen Morris's avatar
Stephen Morris committed
257
HooksLibrariesParser::build(ConstElementPtr value) {
258 259 260
    // Initialize.
    libraries_.clear();
    changed_ = false;
Stephen Morris's avatar
Stephen Morris committed
261

262
    // Extract the list of libraries.
Stephen Morris's avatar
Stephen Morris committed
263 264 265
    BOOST_FOREACH(ConstElementPtr iface, value->listValue()) {
        string libname = iface->str();
        boost::erase_all(libname, "\"");
266 267 268 269 270 271 272 273 274 275 276 277 278
        libraries_.push_back(libname);
    }

    // Check if the list of libraries has changed.  If not, nothing is done
    // - the command "DhcpN libreload" is required to reload the same
    // libraries (this prevents needless reloads when anything else in the
    // configuration is changed).
    vector<string> current_libraries = HooksManager::getLibraryNames();
    if (current_libraries == libraries_) {
        return;
    }

    // Library list has changed, validate each of the libraries specified.
279
    vector<string> error_libs = HooksManager::validateLibraries(libraries_);
280
    if (!error_libs.empty()) {
281 282 283 284 285 286

        // Construct the list of libraries in error for the message.
        string error_list = error_libs[0];
        for (int i = 1; i < error_libs.size(); ++i) {
            error_list += (string(", ") + error_libs[i]);
        }
287
        isc_throw(DhcpConfigError, "hooks libraries failed to validate - "
288
                  "library or libraries in error are: " + error_list);
Stephen Morris's avatar
Stephen Morris committed
289
    }
290

291 292 293
    // The library list has changed and the libraries are valid, so flag for
    // update when commit() is called.
    changed_ = true;
Stephen Morris's avatar
Stephen Morris committed
294 295
}

Mukund Sivaraman's avatar
Mukund Sivaraman committed
296
void
Stephen Morris's avatar
Stephen Morris committed
297
HooksLibrariesParser::commit() {
298 299 300
    /// Commits the list of libraries to the configuration manager storage if
    /// the list of libraries has changed.
    if (changed_) {
301 302
        // TODO Delete any stored CalloutHandles before reloading the
        // libraries
303 304 305 306 307 308 309 310 311 312
        HooksManager::loadLibraries(libraries_);
    }
}

// Method for testing
void
HooksLibrariesParser::getLibraries(std::vector<std::string>& libraries,
                                   bool& changed) {
    libraries = libraries_;
    changed = changed_;
Stephen Morris's avatar
Stephen Morris committed
313 314
}

315
// **************************** OptionDataParser *************************
316 317
OptionDataParser::OptionDataParser(const std::string&, OptionStoragePtr options,
                                  ParserContextPtr global_context)
318 319 320
    : boolean_values_(new BooleanStorage()),
    string_values_(new StringStorage()), uint32_values_(new Uint32Storage()),
    options_(options), option_descriptor_(false),
321
    global_context_(global_context) {
322 323 324 325
    if (!options_) {
        isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
             << "options storage may not be NULL");
    }
326 327 328 329 330

    if (!global_context_) {
        isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
             << "context may may not be NULL");
    }
331 332
}

333
void
334
OptionDataParser::build(ConstElementPtr option_data_entries) {
335 336 337 338
    BOOST_FOREACH(ConfigPair param, option_data_entries->mapValue()) {
        ParserPtr parser;
        if (param.first == "name" || param.first == "data" ||
            param.first == "space") {
339 340
            StringParserPtr name_parser(new StringParser(param.first,
                                        string_values_));
341 342
            parser = name_parser;
        } else if (param.first == "code") {
343 344
            Uint32ParserPtr code_parser(new Uint32Parser(param.first,
                                       uint32_values_));
345 346
            parser = code_parser;
        } else if (param.first == "csv-format") {
347 348
            BooleanParserPtr value_parser(new BooleanParser(param.first,
                                         boolean_values_));
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
            parser = value_parser;
        } else {
            isc_throw(DhcpConfigError,
                      "Parser error: option-data parameter not supported: "
                      << param.first);
        }

        parser->build(param.second);
        // 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();
    }

    // Try to create the option instance.
    createOption();
}

370
void
371
OptionDataParser::commit() {
372
    if (!option_descriptor_.option) {
373
        // Before we can commit the new option should be configured. If it is
374
        // not than somebody must have called commit() before build().
375
        isc_throw(isc::InvalidOperation,
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
            "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::OptionContainerPtr options = options_->getItems(option_space_);
    // The getItems() should never return NULL pointer. If there are no
    // options configured for the particular option space a pointer
    // to an empty container should be returned.
    assert(options);
    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_->addItem(option_descriptor_, option_space_);
}

399
void
400
OptionDataParser::createOption() {
401 402 403
    // 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 uint8_t and is not zero.
404
    uint32_t option_code = uint32_values_->getParam("code");
405 406 407 408 409 410 411 412 413 414 415
    if (option_code == 0) {
        isc_throw(DhcpConfigError, "option code must not be zero."
                << " Option code '0' is reserved in DHCPv4.");
    } else if (option_code > std::numeric_limits<uint8_t>::max()) {
        isc_throw(DhcpConfigError, "invalid option code '" << option_code
                << "', it must not exceed '"
                << std::numeric_limits<uint8_t>::max() << "'");
    }

    // Check that the option name has been specified, is non-empty and does not
    // contain spaces
416
    std::string option_name = string_values_->getParam("name");
417 418 419 420 421 422 423 424
    if (option_name.empty()) {
        isc_throw(DhcpConfigError, "name of the option with code '"
                << option_code << "' is empty");
    } else if (option_name.find(" ") != std::string::npos) {
        isc_throw(DhcpConfigError, "invalid option name '" << option_name
                << "', space character is not allowed");
    }

425
    std::string option_space = string_values_->getParam("space");
426 427 428 429 430 431 432
    if (!OptionSpace::validateName(option_space)) {
        isc_throw(DhcpConfigError, "invalid option space name '"
                << option_space << "' specified for option '"
                << option_name << "' (code '" << option_code
                << "')");
    }

433 434
    const bool csv_format = boolean_values_->getParam("csv-format");

435 436 437 438 439 440 441 442
    // Find the Option Definition for the option by its option code.
    // findOptionDefinition will throw if not found, no need to test.
    OptionDefinitionPtr def;
    if (!(def = findServerSpaceOptionDefinition(option_space, option_code))) {
        // If we are not dealing with a standard option then we
        // need to search for its definition among user-configured
        // options. They are expected to be in the global storage
        // already.
443
        OptionDefContainerPtr defs =
444
            global_context_->option_defs_->getItems(option_space);
445 446 447 448 449 450 451 452 453 454

        // The getItems() should never return the NULL pointer. If there are
        // no option definitions for the particular option space a pointer
        // to an empty container should be returned.
        assert(defs);
        const OptionDefContainerTypeIndex& idx = defs->get<1>();
        OptionDefContainerTypeRange range = idx.equal_range(option_code);
        if (std::distance(range.first, range.second) > 0) {
            def = *range.first;
        }
455 456 457 458

        // It's ok if we don't have option format if the option is
        // specified as hex
        if (!def && csv_format) {
459 460 461 462 463 464 465 466
            isc_throw(DhcpConfigError, "definition for the option '"
                      << option_space << "." << option_name
                      << "' having code '" <<  option_code
                      << "' does not exist");
        }
    }

    // Get option data from the configuration database ('data' field).
467
    const std::string option_data = string_values_->getParam("data");
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

    // Transform string of hexadecimal digits into binary format.
    std::vector<uint8_t> binary;
    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(DhcpConfigError, "option data is not a valid"
                      << " string of hexadecimal digits: " << option_data);
        }
    }

    OptionPtr option;
    if (!def) {
        if (csv_format) {
            isc_throw(DhcpConfigError, "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.");
        }

499 500 501
        // @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
502 503
        // definition does not exist for a particular option code. For now it is
        // ok to create generic option if definition does not exist.
504
        OptionPtr option(new Option(global_context_->universe_,
505
                        static_cast<uint16_t>(option_code), binary));
506 507 508
        // 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
509
        // old option is replaced.
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
        option_descriptor_.option = option;
        option_descriptor_.persistent = false;
    } else {

        // Option name should match the definition. The option name
        // may seem to be redundant but in the future we may want
        // to reference options and definitions using their names
        // and/or option codes so keeping the option name in the
        // definition of option value makes sense.
        if (def->getName() != option_name) {
            isc_throw(DhcpConfigError, "specified option name '"
                      << option_name << "' does not match the "
                      << "option definition: '" << option_space
                      << "." << def->getName() << "'");
        }

        // Option definition has been found so let's use it to create
        // an instance of our option.
        try {
            OptionPtr option = csv_format ?
530
                def->optionFactory(global_context_->universe_,
531
                                  option_code, data_tokens) :
532
                def->optionFactory(global_context_->universe_,
533
                                  option_code, binary);
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
            Subnet::OptionDescriptor desc(option, false);
            option_descriptor_.option = option;
            option_descriptor_.persistent = false;
        } catch (const isc::Exception& ex) {
            isc_throw(DhcpConfigError, "option data does not match"
                      << " option definition (space: " << option_space
                      << ", code: " << option_code << "): "
                      << ex.what());
        }
    }

    // All went good, so we can set the option space name.
    option_space_ = option_space;
}

// **************************** OptionDataListParser *************************
550
OptionDataListParser::OptionDataListParser(const std::string&,
551 552
    OptionStoragePtr options, ParserContextPtr global_context,
    OptionDataParserFactory* optionDataParserFactory)
553
    : options_(options), local_options_(new OptionStorage()),
554
    global_context_(global_context),
555 556 557 558 559 560
    optionDataParserFactory_(optionDataParserFactory) {
    if (!options_) {
        isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
             << "options storage may not be NULL");
    }

561 562 563 564 565
    if (!options_) {
        isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
             << "context may not be NULL");
    }

566 567 568 569 570 571
    if (!optionDataParserFactory_) {
        isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
             << "option data parser factory may not be NULL");
    }
}

572
void
573
OptionDataListParser::build(ConstElementPtr option_data_list) {
574
    BOOST_FOREACH(ConstElementPtr option_value, option_data_list->listValue()) {
575 576
        boost::shared_ptr<OptionDataParser>
            parser((*optionDataParserFactory_)("option-data",
577
                    local_options_, global_context_));
578 579 580 581 582 583 584 585 586 587

        // options_ member will hold instances of all options thus
        // each OptionDataParser takes it as a storage.
        // 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);
    }
}

588
void
589
OptionDataListParser::commit() {
590 591 592 593 594 595 596
    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.
597
    std::swap(*local_options_, *options_);
598 599 600
}

// ******************************** OptionDefParser ****************************
601
OptionDefParser::OptionDefParser(const std::string&,
602 603 604
                                OptionDefStoragePtr storage)
    : storage_(storage), boolean_values_(new BooleanStorage()),
    string_values_(new StringStorage()), uint32_values_(new Uint32Storage()) {
605 606 607 608 609 610
    if (!storage_) {
        isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
             << "options storage may not be NULL");
    }
}

611
void
612
OptionDefParser::build(ConstElementPtr option_def) {
613 614 615 616
    // Parse the elements that make up the option definition.
     BOOST_FOREACH(ConfigPair param, option_def->mapValue()) {
        std::string entry(param.first);
        ParserPtr parser;
617
        if (entry == "name" || entry == "type" || entry == "record-types"
618
            || entry == "space" || entry == "encapsulate") {
619
            StringParserPtr str_parser(new StringParser(entry,
620
                                       string_values_));
621 622
            parser = str_parser;
        } else if (entry == "code") {
623
            Uint32ParserPtr code_parser(new Uint32Parser(entry,
624
                                        uint32_values_));
625 626
            parser = code_parser;
        } else if (entry == "array") {
627
            BooleanParserPtr array_parser(new BooleanParser(entry,
628
                                         boolean_values_));
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
            parser = array_parser;
        } else {
            isc_throw(DhcpConfigError, "invalid parameter: " << entry);
        }

        parser->build(param.second);
        parser->commit();
    }

    // Create an instance of option definition.
    createOptionDef();

    // Get all items we collected so far for the particular option space.
    OptionDefContainerPtr defs = storage_->getItems(option_space_name_);

    // Check if there are any items with option code the same as the
    // one specified for the definition we are now creating.
    const OptionDefContainerTypeIndex& idx = defs->get<1>();
    const OptionDefContainerTypeRange& range =
            idx.equal_range(option_definition_->getCode());

    // If there are any items with this option code already we need
    // to issue an error because we don't allow duplicates for
    // option definitions within an option space.
    if (std::distance(range.first, range.second) > 0) {
        isc_throw(DhcpConfigError, "duplicated option definition for"
                << " code '" << option_definition_->getCode() << "'");
    }
}

659
void
660
OptionDefParser::commit() {
661 662 663 664 665 666
    if (storage_ && option_definition_ &&
        OptionSpace::validateName(option_space_name_)) {
            storage_->addItem(option_definition_, option_space_name_);
    }
}

667
void
668
OptionDefParser::createOptionDef() {
669
    // Get the option space name and validate it.
670
    std::string space = string_values_->getParam("space");
671 672 673 674 675 676 677
    if (!OptionSpace::validateName(space)) {
        isc_throw(DhcpConfigError, "invalid option space name '"
                  << space << "'");
    }

    // Get other parameters that are needed to create the
    // option definition.
678 679 680 681 682
    std::string name = string_values_->getParam("name");
    uint32_t code = uint32_values_->getParam("code");
    std::string type = string_values_->getParam("type");
    bool array_type = boolean_values_->getParam("array");
    std::string encapsulates = string_values_->getParam("encapsulate");
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

    // Create option definition.
    OptionDefinitionPtr def;
    // We need to check if user has set encapsulated option space
    // name. If so, different constructor will be used.
    if (!encapsulates.empty()) {
        // Arrays can't be used together with sub-options.
        if (array_type) {
            isc_throw(DhcpConfigError, "option '" << space << "."
                      << "name" << "', comprising an array of data"
                      << " fields may not encapsulate any option space");

        } else if (encapsulates == space) {
            isc_throw(DhcpConfigError, "option must not encapsulate"
                      << " an option space it belongs to: '"
                      << space << "." << name << "' is set to"
                      << " encapsulate '" << space << "'");

        } else {
            def.reset(new OptionDefinition(name, code, type,
                        encapsulates.c_str()));
        }

    } else {
        def.reset(new OptionDefinition(name, code, type, array_type));

    }

    // The record-types field may carry a list of comma separated names
    // of data types that form a record.
713
    std::string record_types = string_values_->getParam("record-types");
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

    // Split the list of record types into tokens.
    std::vector<std::string> record_tokens =
    isc::util::str::tokens(record_types, ",");
    // Iterate over each token and add a record type into
    // option definition.
    BOOST_FOREACH(std::string record_type, record_tokens) {
        try {
            boost::trim(record_type);
            if (!record_type.empty()) {
                    def->addRecordField(record_type);
            }
        } catch (const Exception& ex) {
            isc_throw(DhcpConfigError, "invalid record type values"
                      << " specified for the option definition: "
                      << ex.what());
        }
    }

    // Check the option definition parameters are valid.
    try {
        def->validate();
    } catch (const isc::Exception& ex) {
        isc_throw(DhcpConfigError, "invalid option definition"
                  << " parameters: " << ex.what());
    }

    // Option definition has been created successfully.
    option_space_name_ = space;
    option_definition_ = def;
}

// ******************************** OptionDefListParser ************************
747
OptionDefListParser::OptionDefListParser(const std::string&,
748
    OptionDefStoragePtr storage) :storage_(storage) {
749 750 751 752 753 754
    if (!storage_) {
        isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
             << "storage may not be NULL");
    }
}

755
void
756
OptionDefListParser::build(ConstElementPtr option_def_list) {
757
    // Clear existing items in the storage.
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
    // We are going to replace all of them.
    storage_->clearItems();

    if (!option_def_list) {
        isc_throw(DhcpConfigError, "parser error: a pointer to a list of"
                  << " option definitions is NULL");
    }

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

774
void
775
OptionDefListParser::commit() {
776 777 778 779
    CfgMgr& cfg_mgr = CfgMgr::instance();
    cfg_mgr.deleteOptionDefs();

    // We need to move option definitions from the temporary
780
    // storage to the storage.
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
    std::list<std::string> space_names =
    storage_->getOptionSpaceNames();

    BOOST_FOREACH(std::string space_name, space_names) {
        BOOST_FOREACH(OptionDefinitionPtr def,
                    *(storage_->getItems(space_name))) {
            // All option definitions should be initialized to non-NULL
            // values. The validation is expected to be made by the
            // OptionDefParser when creating an option definition.
            assert(def);
            cfg_mgr.addOptionDef(def, space_name);
        }
    }
}

796 797 798 799 800 801 802 803 804 805
//****************************** PoolParser ********************************
PoolParser::PoolParser(const std::string&,  PoolStoragePtr pools)
        :pools_(pools) {

    if (!pools_) {
        isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
                  << "storage may not be NULL");
    }
}

806
void
807
PoolParser::build(ConstElementPtr pools_list) {
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    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) {
            isc::asiolink::IOAddress addr("::");
            uint8_t len = 0;
            try {
                addr = isc::asiolink::IOAddress(txt.substr(0, pos));

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

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

835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
                // No checks for values over 128. Range correctness will
                // be checked in Pool4 constructor.
                len = boost::lexical_cast<int>(prefix_len);
            } catch (...)  {
                isc_throw(DhcpConfigError, "Failed to parse pool "
                          "definition: " << text_pool->stringValue());
            }

            PoolPtr pool(poolMaker(addr, len));
            local_pools_.push_back(pool);
            continue;
        }

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

            PoolPtr pool(poolMaker(min, max));
            local_pools_.push_back(pool);
            continue;
        }

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

866
void
867
PoolParser::commit() {
868 869 870 871 872 873 874 875 876 877
    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());
    }
}

//****************************** SubnetConfigParser *************************

878 879 880
SubnetConfigParser::SubnetConfigParser(const std::string&,
                                       ParserContextPtr global_context)
    : uint32_values_(new Uint32Storage()), string_values_(new StringStorage()),
881 882 883 884 885 886 887 888 889 890
    pools_(new PoolStorage()), options_(new OptionStorage()),
    global_context_(global_context) {
    // The first parameter should always be "subnet", but we don't check
    // against that here in case some wants to reuse this parser somewhere.
    if (!global_context_) {
        isc_throw(isc::dhcp::DhcpConfigError, "parser logic error:"
                 << "context storage may not be NULL");
    }
}

891
void
892
SubnetConfigParser::build(ConstElementPtr subnet) {
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
    BOOST_FOREACH(ConfigPair param, subnet->mapValue()) {
        ParserPtr parser(createSubnetConfigParser(param.first));
        parser->build(param.second);
        parsers_.push_back(parser);
    }

    // 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();
}

915 916
void
SubnetConfigParser::appendSubOptions(const std::string& option_space,
917
                                     OptionPtr& option) {
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 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
    // Only non-NULL options are stored in option container.
    // If this option pointer is NULL this is a serious error.
    assert(option);

    OptionDefinitionPtr def;
    if (isServerStdOption(option_space, option->getType())) {
        def = getServerStdOptionDefinition(option->getType());
        // Definitions for some of the standard options hasn't been
        // implemented so it is ok to leave here.
        if (!def) {
            return;
        }
    } else {
        const OptionDefContainerPtr defs =
                global_context_->option_defs_->getItems(option_space);

        const OptionDefContainerTypeIndex& idx = defs->get<1>();
        const OptionDefContainerTypeRange& range =
        idx.equal_range(option->getType());
        // There is no definition so we have to leave.
        if (std::distance(range.first, range.second) == 0) {
            return;
        }

        def = *range.first;

        // If the definition exists, it must be non-NULL.
        // Otherwise it is a programming error.
        assert(def);
    }

    // We need to get option definition for the particular option space
    // and code. This definition holds the information whether our
    // option encapsulates any option space.
    // Get the encapsulated option space name.
    std::string encapsulated_space = def->getEncapsulatedSpace();
    // If option space name is empty it means that our option does not
    // encapsulate any option space (does not include sub-options).
    if (!encapsulated_space.empty()) {
        // Get the sub-options that belong to the encapsulated
        // option space.
        const Subnet::OptionContainerPtr sub_opts =
                global_context_->options_->getItems(encapsulated_space);
        // Append sub-options to the option.
        BOOST_FOREACH(Subnet::OptionDescriptor desc, *sub_opts) {
            if (desc.option) {
                option->addOption(desc.option);
            }
        }
    }
}

970
void
971
SubnetConfigParser::createSubnet() {
972 973 974
    std::string subnet_txt;
    try {
        subnet_txt = string_values_->getParam("subnet");
975
    } catch (const DhcpConfigError &) {
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
        // rethrow with precise error
        isc_throw(DhcpConfigError,
                 "Mandatory subnet definition in subnet missing");
    }

    // Remove any spaces or tabs.
    boost::erase_all(subnet_txt, " ");
    boost::erase_all(subnet_txt, "\t");

    // The subnet format is prefix/len. We are going to extract
    // the prefix portion of a subnet string to create IOAddress
    // object from it. IOAddress will be passed to the Subnet's
    // constructor later on. In order to extract the prefix we
    // need to get all characters preceding "/".
    size_t pos = subnet_txt.find("/");
    if (pos == string::npos) {
        isc_throw(DhcpConfigError,
                  "Invalid subnet syntax (prefix/len expected):" << subnet_txt);
    }

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

1001
    // Call the subclass's method to instantiate the subnet
1002 1003 1004
    initSubnet(addr, len);

    // Add pools to it.
1005
    for (PoolStorage::iterator it = pools_->begin(); it != pools_->end();
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
         ++it) {
        subnet_->addPool(*it);
    }

    // Configure interface, if defined

    // Get interface name. If it is defined, then the subnet is available
    // directly over specified network interface.
    std::string iface;
    try {
        iface = string_values_->getParam("interface");
1017
    } catch (const DhcpConfigError &) {
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
        // iface not mandatory so swallow the exception
    }

    if (!iface.empty()) {
        if (!IfaceMgr::instance().getIface(iface)) {
            isc_throw(DhcpConfigError, "Specified interface name " << iface
                     << " for subnet " << subnet_->toText()
                     << " is not present" << " in the system.");
        }

        subnet_->setIface(iface);
    }

    // We are going to move configured options to the Subnet object.
    // Configured options reside in the container where options
    // are grouped by space names. Thus we need to get all space names
    // and iterate over all options that belong to them.
    std::list<std::string> space_names = options_->getOptionSpaceNames();
    BOOST_FOREACH(std::string option_space, space_names) {
        // Get all options within a particular option space.
        BOOST_FOREACH(Subnet::OptionDescriptor desc,
                      *options_->getItems(option_space)) {
            // The pointer should be non-NULL. The validation is expected
            // to be performed by the OptionDataParser before adding an
            // option descriptor to the container.
            assert(desc.option);
            // We want to check whether an option with the particular
            // option code has been already added. If so, we want
            // to issue a warning.
            Subnet::OptionDescriptor existing_desc =
                            subnet_->getOptionDescriptor("option_space",
                                                 desc.option->getType());
            if (existing_desc.option) {
                duplicate_option_warning(desc.option->getType(), addr);
            }
            // Add sub-options (if any).
            appendSubOptions(option_space, desc.option);
1055

Tomek Mrugalski's avatar
Tomek Mrugalski committed
1056
            // Check if the option space defines a vendor-option
1057 1058 1059 1060 1061 1062 1063 1064
            uint32_t vendor_id = optionSpaceToVendorId(option_space);
            if (vendor_id) {
                // This is a vendor option
                subnet_->addVendorOption(desc.option, false, vendor_id);
            } else {
                // This is a normal option
                subnet_->addOption(desc.option, false, option_space);
            }
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
        }
    }

    // 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.
    space_names = global_context_->options_->getOptionSpaceNames();
    BOOST_FOREACH(std::string option_space, space_names) {
        // Get all global options for the particular option space.
        BOOST_FOREACH(Subnet::OptionDescriptor desc,
                *(global_context_->options_->getItems(option_space))) {
            // The pointer should be non-NULL. The validation is expected
            // to be performed by the OptionDataParser before adding an
            // option descriptor to the container.
            assert(desc.option);
            // Check if the particular option has been already added.
            // This would mean that it has been configured in the
            // subnet scope. Since option values configured in the
            // subnet scope take precedence over globally configured
            // values we don't add option from the global storage
            // if there is one already.
            Subnet::OptionDescriptor existing_desc =
1088
                    subnet_->getOptionDescriptor(option_space,
1089 1090 1091 1092
                                                desc.option->getType());
            if (!existing_desc.option) {
                // Add sub-options (if any).
                appendSubOptions(option_space, desc.option);
1093 1094 1095 1096 1097 1098 1099 1100 1101

                uint32_t vendor_id = optionSpaceToVendorId(option_space);
                if (vendor_id) {
                    // This is a vendor option
                    subnet_->addVendorOption(desc.option, false, vendor_id);
                } else {
                    // This is a normal option
                    subnet_->addOption(desc.option, false, option_space);
                }
1102 1103 1104 1105 1106
            }
        }
    }
}

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
uint32_t
SubnetConfigParser::optionSpaceToVendorId(const std::string& option_space) {
    if (option_space.size() < 8) {
        // 8 is a minimal length of "vendor-X" format
        return (0);
    }
    if (option_space.substr(0,7) != "vendor-") {
        return (0);
    }

    // text after "vendor-", supposedly numbers only
    string x = option_space.substr(7);

    int64_t check;
    try {
        check = boost::lexical_cast<int64_t>(x);
    } catch (const boost::bad_lexical_cast &) {
        /// @todo: Should we throw here?
        // isc_throw(BadValue, "Failed to parse vendor-X value (" << x
        //           << ") as unsigned 32-bit integer.");
        return (0);
    }
    if (check > std::numeric_limits<uint32_t>::max()) {
        /// @todo: Should we throw here?
        //isc_throw(BadValue, "Value " << x << "is too large"
        //          << " for unsigned 32-bit integer.");
        return (0);
    }
    if (check < 0) {
        /// @todo: Should we throw here?
        // isc_throw(BadValue, "Value " << x << "is negative."
        //       << " Only 0 or larger are allowed for unsigned 32-bit integer.");
        return (0);
    }

    // value is small enough to fit
    return (static_cast<uint32_t>(check));
}

1146
isc::dhcp::Triplet<uint32_t>
1147
SubnetConfigParser::getParam(const std::string& name) {
1148 1149
    uint32_t value = 0;
    try {
1150
        // look for local value
1151
        value = uint32_values_->getParam(name);
1152
    } catch (const DhcpConfigError &) {
1153
        try {
1154
            // no local, use global value
1155
            value = global_context_->uint32_values_->getParam(name);
1156
        } catch (const DhcpConfigError &) {
1157 1158 1159 1160 1161 1162 1163 1164 1165
            isc_throw(DhcpConfigError, "Mandatory parameter " << name
                      << " missing (no global default and no subnet-"
                      << "specific value)");
        }
    }

    return (Triplet<uint32_t>(value));
}

1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
//**************************** D2ClientConfigParser **********************
D2ClientConfigParser::D2ClientConfigParser(const std::string& entry_name)
    : entry_name_(entry_name), boolean_values_(new BooleanStorage()),
      uint32_values_(new Uint32Storage()), string_values_(new StringStorage()),
      local_client_config_() {
}

D2ClientConfigParser::~D2ClientConfigParser() {
}

void
D2ClientConfigParser::build(isc::data::ConstElementPtr client_config) {
    BOOST_FOREACH(ConfigPair param, client_config->mapValue()) {
        ParserPtr parser(createConfigParser(param.first));
        parser->build(param.second);
        parser->commit();
    }

    bool enable_updates = boolean_values_->getParam("enable-updates");
1185 1186 1187 1188 1189
    if (!enable_updates && (client_config->mapValue().size() == 1)) {
        // If enable-updates is the only parameter and it is false then
        // we're done.  This allows for an abbreviated configuration entry
        // that only contains that flag.  Use the default D2ClientConfig
        // constructor to a create a disabled instance.
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
        local_client_config_.reset(new D2ClientConfig());
        return;
    }

    // Get all parameters that are needed to create the D2ClientConfig.
    asiolink::IOAddress server_ip(string_values_->getParam("server-ip"));

    uint32_t server_port = uint32_values_->getParam("server-port");

    dhcp_ddns::NameChangeProtocol
    ncr_protocol = dhcp_ddns:: stringToNcrProtocol(string_values_->
                                                   getParam("ncr-protocol"));

    dhcp_ddns::NameChangeFormat
    ncr_format = dhcp_ddns::stringToNcrFormat(string_values_->
                                              getParam("ncr-format"));

    std::string generated_prefix = string_values_->getParam("generated-prefix");
    std::string qualifying_suffix = string_values_->
                                    getParam("qualifying-suffix");

    bool remove_on_renew = boolean_values_->getParam("remove-on-renew");
    bool always_include_fqdn = boolean_values_->getParam("always-include-fqdn");
    bool override_no_update = boolean_values_->getParam("override-no-update");
    bool override_client_update = boolean_values_->
                                  getParam("override-client-update");
    bool replace_client_name = boolean_values_->getParam("replace-client-name");

    // Attempt to create the new client config.
    local_client_config_.reset(new D2ClientConfig(enable_updates, server_ip,
                                                  server_port, ncr_protocol,
                                                  ncr_format, remove_on_renew,
                                                  always_include_fqdn,