json_config_parser.cc 30.7 KB
Newer Older
1
// Copyright (C) 2012-2016 Internet Systems Consortium, Inc. ("ISC")
2
//
3
4
5
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6

7
8
#include <config.h>

9
#include <cc/command_interpreter.h>
10
#include <dhcp4/dhcp4_log.h>
11
#include <dhcp4/simple_parser4.h>
12
13
#include <dhcp/libdhcp++.h>
#include <dhcp/option_definition.h>
14
#include <dhcpsrv/cfg_option.h>
15
#include <dhcpsrv/cfgmgr.h>
16
#include <dhcpsrv/parsers/client_class_def_parser.h>
17
#include <dhcp4/json_config_parser.h>
18
19
#include <dhcpsrv/parsers/dbaccess_parser.h>
#include <dhcpsrv/parsers/dhcp_parsers.h>
20
#include <dhcpsrv/parsers/expiration_config_parser.h>
21
22
#include <dhcpsrv/parsers/host_reservation_parser.h>
#include <dhcpsrv/parsers/host_reservations_list_parser.h>
23
#include <dhcpsrv/parsers/ifaces_config_parser.h>
24
#include <dhcpsrv/timer_mgr.h>
25
#include <config/command_mgr.h>
26
#include <util/encode/hex.h>
27
#include <util/strutil.h>
28
#include <defaults.h>
29

Tomek Mrugalski's avatar
Tomek Mrugalski committed
30
31
32
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
33

Tomek Mrugalski's avatar
Tomek Mrugalski committed
34
#include <limits>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
35
#include <iostream>
36
#include <netinet/in.h>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
37
38
39
#include <vector>
#include <map>

40
using namespace std;
41
42
using namespace isc;
using namespace isc::dhcp;
43
44
45
using namespace isc::data;
using namespace isc::asiolink;

46
47
namespace {

48
/// @brief Parser for IPv4 pool definitions.
49
///
50
51
52
/// This is the IPv4 derivation of the PoolParser class and handles pool
/// definitions, i.e. a list of entries of one of two syntaxes: min-max and
/// prefix/len for IPv4 pools. Pool4 objects are created and stored in chosen
53
/// PoolStorage container.
54
///
55
56
/// It is useful for parsing Dhcp4/subnet4[X]/pool parameters.
class Pool4Parser : public PoolParser {
57
58
public:

59
60
61
62
63
64
65
    /// @brief Constructor.
    ///
    /// @param param_name name of the parameter. Note, it is passed through
    /// but unused, parameter is currently always "Dhcp4/subnet4[X]/pool"
    /// @param pools storage container in which to store the parsed pool
    /// upon "commit"
    Pool4Parser(const std::string& param_name,  PoolStoragePtr pools)
66
        :PoolParser(param_name, pools, AF_INET) {
67
68
    }

69
70
protected:
    /// @brief Creates a Pool4 object given a IPv4 prefix and the prefix length.
71
    ///
72
73
    /// @param addr is the IPv4 prefix of the pool.
    /// @param len is the prefix length.
74
    /// @param ignored dummy parameter to provide symmetry between the
75
    /// PoolParser derivations. The V6 derivation requires a third value.
76
    /// @return returns a PoolPtr to the new Pool4 object.
77
    PoolPtr poolMaker (IOAddress &addr, uint32_t len, int32_t) {
78
79
        return (PoolPtr(new Pool4(addr, len)));
    }
80

81
82
83
84
    /// @brief Creates a Pool4 object given starting and ending IPv4 addresses.
    ///
    /// @param min is the first IPv4 address in the pool.
    /// @param max is the last IPv4 address in the pool.
85
    /// @param ignored dummy parameter to provide symmetry between the
86
    /// PoolParser derivations. The V6 derivation requires a third value.
87
    /// @return returns a PoolPtr to the new Pool4 object.
88
    PoolPtr poolMaker (IOAddress &min, IOAddress &max, int32_t) {
89
        return (PoolPtr(new Pool4(min, max)));
90
    }
91
};
92

93
94
95
96
97
98
99
100
101
102
103
104
class Pools4ListParser : public PoolsListParser {
public:
    Pools4ListParser(const std::string& dummy, PoolStoragePtr pools)
        :PoolsListParser(dummy, pools) {
    }

protected:
    virtual ParserPtr poolParserMaker(PoolStoragePtr storage) {
        return (ParserPtr(new Pool4Parser("pool", storage)));
    }
};

105
/// @anchor Subnet4ConfigParser
106
107
/// @brief This class parses a single IPv4 subnet.
///
108
109
/// This is the IPv4 derivation of the SubnetConfigParser class and it parses
/// the whole subnet definition. It creates parsersfor received configuration
110
111
112
113
/// parameters as needed.
class Subnet4ConfigParser : public SubnetConfigParser {
public:
    /// @brief Constructor
114
    ///
115
    /// @param ignored first parameter
Francis Dupont's avatar
Francis Dupont committed
116
    /// stores global scope parameters, options, option definitions.
117
    Subnet4ConfigParser(const std::string&)
118
        :SubnetConfigParser("", globalContext(), IOAddress("0.0.0.0")) {
119
    }
120

121
122
123
124
125
126
127
    /// @brief Parses a single IPv4 subnet configuration and adds to the
    /// Configuration Manager.
    ///
    /// @param subnet A new subnet being configured.
    void build(ConstElementPtr subnet) {
        SubnetConfigParser::build(subnet);

128
        if (subnet_) {
129
130
131
            Subnet4Ptr sub4ptr = boost::dynamic_pointer_cast<Subnet4>(subnet_);
            if (!sub4ptr) {
                // If we hit this, it is a programming error.
132
                isc_throw(Unexpected,
133
134
135
                          "Invalid cast in Subnet4ConfigParser::commit");
            }

136
137
            // Set relay information if it was parsed
            if (relay_info_) {
138
                sub4ptr->setRelayInfo(*relay_info_);
139
140
            }

141
142
143
144
            // Adding a subnet to the Configuration Manager may fail if the
            // subnet id is invalid (duplicate). Thus, we catch exceptions
            // here to append a position in the configuration string.
            try {
145
                CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(sub4ptr);
146
147
148
149
            } catch (const std::exception& ex) {
                isc_throw(DhcpConfigError, ex.what() << " ("
                          << subnet->getPosition() << ")");
            }
150
        }
151
152
153
154
155
156
157
158

        // Parse Host Reservations for this subnet if any.
        ConstElementPtr reservations = subnet->get("reservations");
        if (reservations) {
            ParserPtr parser(new HostReservationsListParser<
                             HostReservationParser4>(subnet_->getID()));
            parser->build(reservations);
        }
159
160
    }

161
162
163
164
165
166
    /// @brief Commits subnet configuration.
    ///
    /// This function is currently no-op because subnet should already
    /// be added into the Config Manager in the build().
    void commit() { }

167
protected:
168

169
    /// @brief Creates parsers for entries in subnet definition.
170
    ///
171
172
173
174
175
176
177
178
179
180
    /// @param config_id name of the entry
    ///
    /// @return parser object for specified entry name. Note the caller is
    /// responsible for deleting the parser created.
    /// @throw isc::dhcp::DhcpConfigError if trying to create a parser
    /// for unknown config element
    DhcpConfigParser* createSubnetConfigParser(const std::string& config_id) {
        DhcpConfigParser* parser = NULL;
        if ((config_id.compare("valid-lifetime") == 0)  ||
            (config_id.compare("renew-timer") == 0)  ||
181
182
            (config_id.compare("rebind-timer") == 0) ||
            (config_id.compare("id") == 0)) {
183
            parser = new Uint32Parser(config_id, uint32_values_);
184
        } else if ((config_id.compare("subnet") == 0) ||
185
                   (config_id.compare("interface") == 0) ||
186
                   (config_id.compare("client-class") == 0) ||
187
188
                   (config_id.compare("next-server") == 0) ||
                   (config_id.compare("reservation-mode") == 0)) {
189
            parser = new StringParser(config_id, string_values_);
190
191
        } else if (config_id.compare("pools") == 0) {
            parser = new Pools4ListParser(config_id, pools_);
192
        } else if (config_id.compare("relay") == 0) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
193
            parser = new RelayInfoParser(config_id, relay_info_, Option::V4);
194
        // option-data has been converted to SimpleParser already.
195
        } else if (config_id.compare("match-client-id") == 0) {
196
            parser = new BooleanParser(config_id, boolean_values_);
197
198
199
200
        } else if (config_id.compare("4o6-subnet") == 0) {
            parser = new StringParser(config_id, string_values_);
        } else if (config_id.compare("4o6-interface") == 0) {
            parser = new StringParser(config_id, string_values_);
201
202
        } else if (config_id.compare("4o6-interface-id") == 0) {
            parser = new StringParser(config_id, string_values_);
203
        } else {
204
            isc_throw(NotImplemented, "unsupported parameter: " << config_id);
205
206
        }

207
        return (parser);
208
209
    }

210
    /// @brief Issues a DHCP4 server specific warning regarding duplicate subnet
211
212
    /// options.
    ///
213
    /// @param code is the numeric option code of the duplicate option
214
    /// @param addr is the subnet address
215
    /// @todo a means to know the correct logger and perhaps a common
216
    /// message would allow this method to be emitted by the base class.
217
218
219
220
221
    virtual void duplicate_option_warning(uint32_t code,
                                         isc::asiolink::IOAddress& addr) {
        LOG_WARN(dhcp4_logger, DHCP4_CONFIG_OPTION_DUPLICATE)
            .arg(code).arg(addr.toText());
    }
222

223
    /// @brief Instantiates the IPv4 Subnet based on a given IPv4 address
224
225
    /// and prefix length.
    ///
226
    /// @param addr is IPv4 address of the subnet.
227
    /// @param len is the prefix length
228
    void initSubnet(isc::asiolink::IOAddress addr, uint8_t len) {
229
230
231
232
233
234
235
236
        // The renew-timer and rebind-timer are optional. If not set, the
        // option 58 and 59 will not be sent to a client. In this case the
        // client will use default values based on the valid-lifetime.
        Triplet<uint32_t> t1 = getOptionalParam("renew-timer");
        Triplet<uint32_t> t2 = getOptionalParam("rebind-timer");
        // The valid-lifetime is mandatory. It may be specified for a
        // particular subnet. If not, the global value should be present.
        // If there is no global value, exception is thrown.
237
        Triplet<uint32_t> valid = getParam("valid-lifetime");
238
239
240
241
        // Subnet ID is optional. If it is not supplied the value of 0 is used,
        // which means autogenerate.
        SubnetID subnet_id =
            static_cast<SubnetID>(uint32_values_->getOptionalParam("id", 0));
242

243
244
245
246
247
248
249
250
251
252
        stringstream s;
        s << addr << "/" << static_cast<int>(len) << " with params: ";
        // t1 and t2 are optional may be not specified.
        if (!t1.unspecified()) {
            s << "t1=" << t1 << ", ";
        }
        if (!t2.unspecified()) {
            s << "t2=" << t2 << ", ";
        }
        s <<"valid-lifetime=" << valid;
253

254
        LOG_INFO(dhcp4_logger, DHCP4_CONFIG_NEW_SUBNET).arg(s.str());
255

256
        Subnet4Ptr subnet4(new Subnet4(addr, len, t1, t2, valid, subnet_id));
Tomek Mrugalski's avatar
Tomek Mrugalski committed
257
        subnet_ = subnet4;
258

259
260
        // match-client-id
        isc::util::OptionalValue<bool> match_client_id;
261
        try {
262
            match_client_id = boolean_values_->getParam("match-client-id");
263
264
265
266
267
268

        } catch (...) {
            // Ignore because this parameter is optional and it may be specified
            // in the global scope.
        }

269
        // If the match-client-id wasn't specified as a subnet specific parameter
270
        // check if there is global value specified.
271
        if (!match_client_id.isSpecified()) {
272
            // If not specified, use false.
273
274
            match_client_id.specify(globalContext()->boolean_values_->
                                    getOptionalParam("match-client-id", true));
275
276
        }

277
278
        // Set the match-client-id value for the subnet.
        subnet4->setMatchClientId(match_client_id.get());
279
280

        // next-server
281
282
        try {
            string next_server = globalContext()->string_values_->getParam("next-server");
Tomek Mrugalski's avatar
Tomek Mrugalski committed
283
284
285
            if (!next_server.empty()) {
                subnet4->setSiaddr(IOAddress(next_server));
            }
286
        } catch (const DhcpConfigError&) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
287
            // Don't care. next_server is optional. We can live without it
288
289
290
291
        } catch (...) {
            isc_throw(DhcpConfigError, "invalid parameter next-server ("
                      << globalContext()->string_values_->getPosition("next-server")
                      << ")");
292
293
294
295
296
        }

        // Try subnet specific value if it's available
        try {
            string next_server = string_values_->getParam("next-server");
Tomek Mrugalski's avatar
Tomek Mrugalski committed
297
298
299
            if (!next_server.empty()) {
                subnet4->setSiaddr(IOAddress(next_server));
            }
300
        } catch (const DhcpConfigError&) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
301
            // Don't care. next_server is optional. We can live without it
302
303
304
305
        } catch (...) {
            isc_throw(DhcpConfigError, "invalid parameter next-server ("
                      << string_values_->getPosition("next-server")
                      << ")");
306
        }
307

308
        // Try 4o6 specific parameter: 4o6-interface
309
310
        string iface4o6 = string_values_->getOptionalParam("4o6-interface", "");
        if (!iface4o6.empty()) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
311
312
            subnet4->get4o6().setIface4o6(iface4o6);
            subnet4->get4o6().enabled(true);
313
314
315
        }

        // Try 4o6 specific parameter: 4o6-subnet
316
317
        string subnet4o6 = string_values_->getOptionalParam("4o6-subnet", "");
        if (!subnet4o6.empty()) {
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
            size_t slash = subnet4o6.find("/");
            if (slash == std::string::npos) {
                isc_throw(DhcpConfigError, "Missing / in the 4o6-subnet parameter:"
                          + subnet4o6 +", expected format: prefix6/length");
            }
            string prefix = subnet4o6.substr(0, slash);
            string lenstr = subnet4o6.substr(slash + 1);

            uint8_t len = 128;
            try {
                len = boost::lexical_cast<unsigned int>(lenstr.c_str());
            } catch (const boost::bad_lexical_cast &) {
                isc_throw(DhcpConfigError, "Invalid prefix length specified in "
                          "4o6-subnet parameter: " + subnet4o6 + ", expected 0..128 value");
            }
Tomek Mrugalski's avatar
Tomek Mrugalski committed
333
334
            subnet4->get4o6().setSubnet4o6(IOAddress(prefix), len);
            subnet4->get4o6().enabled(true);
335
        }
336

337
        // Try 4o6 specific paramter: 4o6-interface-id
338
339
        std::string ifaceid = string_values_->getOptionalParam("4o6-interface-id", "");
        if (!ifaceid.empty()) {
340
341
            OptionBuffer tmp(ifaceid.begin(), ifaceid.end());
            OptionPtr opt(new Option(Option::V6, D6O_INTERFACE_ID, tmp));
Tomek Mrugalski's avatar
Tomek Mrugalski committed
342
343
            subnet4->get4o6().setInterfaceId(opt);
            subnet4->get4o6().enabled(true);
344
345
        }

346
347
348
349
350
351
352
        // Try setting up client class (if specified)
        try {
            string client_class = string_values_->getParam("client-class");
            subnet4->allowClientClass(client_class);
        } catch (const DhcpConfigError&) {
            // That's ok if it fails. client-class is optional.
        }
353
354
355
    }
};

356
/// @brief this class parses list of DHCP4 subnets
357
358
359
360
///
/// This is a wrapper parser that handles the whole list of Subnet4
/// definitions. It iterates over all entries and creates Subnet4ConfigParser
/// for each entry.
361
class Subnets4ListConfigParser : public DhcpConfigParser {
362
363
364
365
public:

    /// @brief constructor
    ///
366
    /// @param dummy first argument, always ignored. All parsers accept a
367
    /// string parameter "name" as their first argument.
368
369
370
371
372
373
374
375
376
377
378
    Subnets4ListConfigParser(const std::string&) {
    }

    /// @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) {
        BOOST_FOREACH(ConstElementPtr subnet, subnets_list->listValue()) {
379
            ParserPtr parser(new Subnet4ConfigParser("subnet"));
380
381
382
383
384
385
            parser->build(subnet);
        }
    }

    /// @brief commits subnets definitions.
    ///
386
    /// Does nothing.
387
388
389
390
391
392
    void commit() {
    }

    /// @brief Returns Subnet4ListConfigParser object
    /// @param param_name name of the parameter
    /// @return Subnets4ListConfigParser object
393
    static DhcpConfigParser* factory(const std::string& param_name) {
394
395
396
397
        return (new Subnets4ListConfigParser(param_name));
    }
};

398
399
400
401
402
} // anonymous namespace

namespace isc {
namespace dhcp {

403
404
405
406
407
408
/// @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
409
/// @param element pointer to the element to be parsed
410
/// @return parser for specified global DHCPv4 parameter
411
/// @throw NotImplemented if trying to create a parser for unknown
412
/// config element
Francis Dupont's avatar
Francis Dupont committed
413
414
DhcpConfigParser* createGlobalDhcp4ConfigParser(const std::string& config_id,
                                                ConstElementPtr element) {
415
    DhcpConfigParser* parser = NULL;
416
417
    if ((config_id.compare("valid-lifetime") == 0)  ||
        (config_id.compare("renew-timer") == 0)  ||
418
        (config_id.compare("rebind-timer") == 0) ||
419
420
        (config_id.compare("decline-probation-period") == 0) ||
        (config_id.compare("dhcp4o6-port") == 0) )  {
421
        parser = new Uint32Parser(config_id,
422
                                  globalContext()->uint32_values_);
423
    } else if (config_id.compare("interfaces-config") == 0) {
424
        parser = new IfacesConfigParser4();
425
    } else if (config_id.compare("subnet4") == 0) {
426
        parser = new Subnets4ListConfigParser(config_id);
427
    // option-data and option-def have been converted to SimpleParser already.
428
    } else if ((config_id.compare("next-server") == 0)) {
429
        parser  = new StringParser(config_id,
430
                                    globalContext()->string_values_);
431
    } else if (config_id.compare("lease-database") == 0) {
432
        parser = new DbAccessParser(config_id, DbAccessParser::LEASE_DB);
433
    } else if (config_id.compare("hosts-database") == 0) {
434
        parser = new DbAccessParser(config_id, DbAccessParser::HOSTS_DB);
435
436
    } else if (config_id.compare("hooks-libraries") == 0) {
        parser = new HooksLibrariesParser(config_id);
437
438
    } else if (config_id.compare("echo-client-id") == 0) {
        parser = new BooleanParser(config_id, globalContext()->boolean_values_);
439
440
    } else if (config_id.compare("dhcp-ddns") == 0) {
        parser = new D2ClientConfigParser(config_id);
441
    } else if (config_id.compare("match-client-id") == 0) {
442
        parser = new BooleanParser(config_id, globalContext()->boolean_values_);
443
444
    } else if (config_id.compare("control-socket") == 0) {
        parser = new ControlSocketParser(config_id);
445
446
    } else if (config_id.compare("expired-leases-processing") == 0) {
        parser = new ExpirationConfigParser();
447
448
    } else if (config_id.compare("client-classes") == 0) {
        parser = new ClientClassDefListParser(config_id, globalContext());
449
450
    } else if (config_id.compare("host-reservation-identifiers") == 0) {
        parser = new HostReservationIdsParser4();
451
    } else {
452
453
454
        isc_throw(DhcpConfigError,
                "unsupported global configuration parameter: "
                  << config_id << " (" << element->getPosition() << ")");
455
    }
456
457

    return (parser);
458
459
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
460
/// @brief Sets global parameters in staging configuration
461
462
463
464
465
///
/// Currently this method sets the following global parameters:
///
/// - echo-client-id
/// - decline-probation-period
466
/// - dhcp4o6-port
Tomek Mrugalski's avatar
Tomek Mrugalski committed
467
void setGlobalParameters4() {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
468
469
    // Although the function is modest for now, it is certain that the number
    // of global switches will increase over time, hence the name.
470
471
472
473
474
475
476
477
478

    // Set whether v4 server is supposed to echo back client-id (yes = RFC6842
    // compatible, no = backward compatibility)
    try {
        bool echo_client_id = globalContext()->boolean_values_->getParam("echo-client-id");
        CfgMgr::instance().echoClientId(echo_client_id);
    } catch (...) {
        // Ignore errors. This flag is optional
    }
479
480
481
482
483
484
485
486
487
488

    // Set the probation period for decline handling.
    try {
        uint32_t probation_period = globalContext()->uint32_values_
            ->getOptionalParam("decline-probation-period",
                               DEFAULT_DECLINE_PROBATION_PERIOD);
        CfgMgr::instance().getStagingCfg()->setDeclinePeriod(probation_period);
    } catch (...) {
        // That's not really needed.
    }
489
490
491
492
493
494
495
496
497

    // Set the DHCPv4-over-DHCPv6 interserver port.
    try {
        uint32_t dhcp4o6_port = globalContext()->uint32_values_
            ->getOptionalParam("dhcp4o6-port", 0);
        CfgMgr::instance().getStagingCfg()->setDhcp4o6Port(dhcp4o6_port);
    } catch (...) {
        // Ignore errors. This flag is optional
    }
498
499
}

500
isc::data::ConstElementPtr
501
configureDhcp4Server(Dhcpv4Srv&, isc::data::ConstElementPtr config_set) {
502
    if (!config_set) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
503
504
505
        ConstElementPtr answer = isc::config::createAnswer(1,
                                 string("Can't parse NULL config"));
        return (answer);
506
507
    }

508
    LOG_DEBUG(dhcp4_logger, DBG_DHCP4_COMMAND,
509
              DHCP4_CONFIG_START).arg(config_set->str());
510

511
512
513
    // Reset global context.
    globalContext().reset(new ParserContext(Option::V4));

514
515
516
517
    // Before starting any subnet operations, let's reset the subnet-id counter,
    // so newly recreated configuration starts with first subnet-id equal 1.
    Subnet::resetSubnetID();

518
519
520
    // Remove any existing timers.
    TimerMgr::instance()->unregisterTimers();

521
522
    // Revert any runtime option definitions configured so far and not committed.
    LibDHCP::revertRuntimeOptionDefs();
523
524
525
    // Let's set empty container in case a user hasn't specified any configuration
    // for option definitions. This is equivalent to commiting empty container.
    LibDHCP::setRuntimeOptionDefs(OptionDefSpaceContainer());
526

527
    // Some of the values specified in the configuration depend on
528
529
530
    // other values. Typically, the values in the subnet4 structure
    // depend on the global values. Also, option values configuration
    // must be performed after the option definitions configurations.
531
    // Thus we group parsers and will fire them in the right order:
532
533
    // all parsers other than: lease-database, subnet4 and option-data parser,
    // then: option-data parser, subnet4 parser, lease-database parser.
534
    // Please do not change this order!
535
    ParserCollection independent_parsers;
536
    ParserPtr subnet_parser;
537
    ParserPtr iface_parser;
538
    ParserPtr leases_parser;
539
    ParserPtr client_classes_parser;
540

541
542
    // Some of the parsers alter the state of the system in a way that can't
    // easily be undone. (Or alter it in a way such that undoing the change has
543
    // the same risk of failure as doing the change.)
544
    ParserPtr hooks_parser;
545

546
    // The subnet parsers implement data inheritance by directly
547
    // accessing global storage. For this reason the global data
548
    // parsers must store the parsed data into global storages
549
550
551
552
    // immediately. This may cause data inconsistency if the
    // parsing operation fails after the global storage has been
    // modified. We need to preserve the original global data here
    // so as we can rollback changes when an error occurs.
553
    ParserContext original_context(*globalContext());
554

555
    // Answer will hold the result.
556
    ConstElementPtr answer;
Francis Dupont's avatar
Francis Dupont committed
557
    // Rollback informs whether error occurred and original data
558
559
    // have to be restored to global storages.
    bool rollback = false;
560
    // config_pair holds the details of the current parser when iterating over
561
562
    // the parsers.  It is declared outside the loops so in case of an error,
    // the name of the failing parser can be retrieved in the "catch" clause.
563
    ConfigPair config_pair;
564
    try {
565
566
567
568

        // This is a way to convert ConstElementPtr to ElementPtr.
        // We need a config that can be edited, because we will insert
        // default values and will insert derived values as well.
569
        ElementPtr mutable_cfg = boost::const_pointer_cast<Element>(config_set);
570
571

        // Set all default values if not specified by the user.
572
        SimpleParser4::setAllDefaults(mutable_cfg);
573
574
575
576

        // We need definitions first
        ConstElementPtr option_defs = mutable_cfg->get("option-def");
        if (option_defs) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
577
            OptionDefListParser parser;
578
579
580
581
            CfgOptionDefPtr cfg_option_def = CfgMgr::instance().getStagingCfg()->getCfgOptionDef();
            parser.parse(cfg_option_def, option_defs);
        }

582
        // Make parsers grouping.
583
        const std::map<std::string, ConstElementPtr>& values_map =
584
                                                        mutable_cfg->mapValue();
585
        BOOST_FOREACH(config_pair, values_map) {
586
587
588
589
590
591
592
593
594
595
596
597
598

            if (config_pair.first == "option-def") {
                // This is converted to SimpleParser and is handled already above.
                continue;
            }

            if (config_pair.first == "option-data") {
                OptionDataListParser parser(AF_INET);
                CfgOptionPtr cfg_option = CfgMgr::instance().getStagingCfg()->getCfgOption();
                parser.parse(cfg_option, config_pair.second);
                continue;
            }

599
600
            ParserPtr parser(createGlobalDhcp4ConfigParser(config_pair.first,
                                                           config_pair.second));
601
602
            LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_PARSER_CREATED)
                      .arg(config_pair.first);
603
604
            if (config_pair.first == "subnet4") {
                subnet_parser = parser;
605
606
            } else if (config_pair.first == "lease-database") {
                leases_parser = parser;
607
            } else if (config_pair.first == "interfaces-config") {
608
609
610
611
                // The interface parser is independent from any other
                // parser and can be run here before any other parsers.
                iface_parser = parser;
                parser->build(config_pair.second);
612
613
614
615
            } else if (config_pair.first == "hooks-libraries") {
                // Executing commit will alter currently-loaded hooks
                // libraries.  Check if the supplied libraries are valid,
                // but defer the commit until everything else has committed.
616
                hooks_parser = parser;
617
                parser->build(config_pair.second);
618
619
            } else if (config_pair.first == "client-classes") {
                client_classes_parser = parser;
620
            } else {
621
622
                // Those parsers should be started before other
                // parsers so we can call build straight away.
623
624
625
626
627
628
629
630
                independent_parsers.push_back(parser);
                parser->build(config_pair.second);
                // The commit operation here may modify the global storage
                // but we need it so as the subnet6 parser can access the
                // parsed data.
                parser->commit();
            }
        }
631

632
633
634
635
636
637
638
639
640
        // The class definitions parser is the next one to be run.
        std::map<std::string, ConstElementPtr>::const_iterator cc_config =
            values_map.find("client-classes");
        if (cc_config != values_map.end()) {
            config_pair.first = "client-classes";
            client_classes_parser->build(cc_config->second);
            client_classes_parser->commit();
        }

641
        // The subnet parser is the next one to be run.
642
643
644
        std::map<std::string, ConstElementPtr>::const_iterator subnet_config =
            values_map.find("subnet4");
        if (subnet_config != values_map.end()) {
645
            config_pair.first = "subnet4";
646
            subnet_parser->build(subnet_config->second);
647
        }
648

649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
        // Get command socket configuration from the config file.
        // This code expects the following structure:
        // {
        //     "socket-type": "unix",
        //     "socket-name": "/tmp/kea4.sock"
        // }
        ConstElementPtr sock_cfg =
            CfgMgr::instance().getStagingCfg()->getControlSocketInfo();

        // Close existing socket (if any).
        isc::config::CommandMgr::instance().closeCommandSocket();
        if (sock_cfg) {
            // This will create a control socket and will install external socket
            // in IfaceMgr. That socket will be monitored when Dhcp4Srv::receivePacket()
            // calls IfaceMgr::receive4() and callback in CommandMgr will be called,
            // if necessary. If there were previously open command socket, it will
            // be closed.
            isc::config::CommandMgr::instance().openCommandSocket(sock_cfg);
        }

669
670
671
672
673
674
675
676
677
        // the leases database parser is the last to be run.
        std::map<std::string, ConstElementPtr>::const_iterator leases_config =
            values_map.find("lease-database");
        if (leases_config != values_map.end()) {
            config_pair.first = "lease-database";
            leases_parser->build(leases_config->second);
            leases_parser->commit();
        }

678
    } catch (const isc::Exception& ex) {
679
        LOG_ERROR(dhcp4_logger, DHCP4_PARSER_FAIL)
680
                  .arg(config_pair.first).arg(ex.what());
681
        answer = isc::config::createAnswer(1, ex.what());
682

Francis Dupont's avatar
Francis Dupont committed
683
        // An error occurred, so make sure that we restore original data.
684
685
        rollback = true;

686
    } catch (...) {
687
        // For things like bad_cast in boost::lexical_cast
688
        LOG_ERROR(dhcp4_logger, DHCP4_PARSER_EXCEPTION).arg(config_pair.first);
689
690
        answer = isc::config::createAnswer(1, "undefined configuration"
                                           " processing error");
691

Francis Dupont's avatar
Francis Dupont committed
692
        // An error occurred, so make sure that we restore original data.
693
        rollback = true;
694
695
    }

696
697
698
699
700
701
    // So far so good, there was no parsing error so let's commit the
    // configuration. This will add created subnets and option values into
    // the server's configuration.
    // This operation should be exception safe but let's make sure.
    if (!rollback) {
        try {
702
703
            // No need to commit interface names as this is handled by the
            // CfgMgr::commit() function.
704

Tomek Mrugalski's avatar
Tomek Mrugalski committed
705
706
            // Apply global options in the staging config.
            setGlobalParameters4();
707

708
709
710
            // This occurs last as if it succeeds, there is no easy way
            // revert it.  As a result, the failure to commit a subsequent
            // change causes problems when trying to roll back.
711
712
            if (hooks_parser) {
                hooks_parser->commit();
713
            }
714
715
        }
        catch (const isc::Exception& ex) {
716
            LOG_ERROR(dhcp4_logger, DHCP4_PARSER_COMMIT_FAIL).arg(ex.what());
717
            answer = isc::config::createAnswer(2, ex.what());
718
719
            rollback = true;
        } catch (...) {
720
            // For things like bad_cast in boost::lexical_cast
721
            LOG_ERROR(dhcp4_logger, DHCP4_PARSER_COMMIT_EXCEPTION);
722
723
            answer = isc::config::createAnswer(2, "undefined configuration"
                                               " parsing error");
724
            rollback = true;
725
726
        }
    }
727
728
729

    // Rollback changes as the configuration parsing failed.
    if (rollback) {
730
        globalContext().reset(new ParserContext(original_context));
731
732
733
        // Revert to original configuration of runtime option definitions
        // in the libdhcp++.
        LibDHCP::revertRuntimeOptionDefs();
734
735
736
        return (answer);
    }

737
    LOG_INFO(dhcp4_logger, DHCP4_CONFIG_COMPLETE)
738
        .arg(CfgMgr::instance().getStagingCfg()->
739
             getConfigSummary(SrvConfig::CFGSEL_ALL4));
740

741
    // Everything was fine. Configuration is successful.
742
    answer = isc::config::createAnswer(0, "Configuration successful.");
743
744
745
    return (answer);
}

746
ParserContextPtr& globalContext() {
747
748
    static ParserContextPtr global_context_ptr(new ParserContext(Option::V4));
    return (global_context_ptr);
749
750
}

751
752


753
754
}; // end of isc::dhcp namespace
}; // end of isc namespace