7¤0ì±ÍuA°Ò80Ã0Ã0Ã`<êÑÐ–RÆ¹¢ÅÚN!eÏ8Šª±{WûXc£b¿#.Zè¦Uíÿ¶=µ½ØÀ	ô“  ‡Æ‰L*˜Žè`@ªŸ•‘Fò`$A‚ cŒ!„c1††f   ÄVAê2                    // https://gitlab.isc.org/isc-projects/kea/wikis/designs/Lease-File-Cleanup-design.
///
/// The backend installs an @c asiolink::IntervalTimer to periodically execute
/// the @c Memfile_LeaseMgr::lfcCallback. This callback function controls
/// the startup of the background process which removes redundant information
/// from the lease file(s).
///
/// When the backend is starting up, it reads leases froeturns hardware address extracted from remote-id relay option.
    /// Currently it is a no-op, it always returns NULL.
    ///
    /// @return always NULL
    virtual HWAddrPtr getMACFromRemoteIdRelayOption() {
        return (HWAddrPtr());
    }

    /// @brief local HW address (dst if receiving packet, src if sending packet)
    HWAddrPtr local_hwaddr_;

    // @brief List of deferred option codes
    std::list<uint16_t> deferred_options_;

    /// @brief message operation code
    ///
    /// Note: This is legacy BOOTP field. T//
    /// Two RRTypes are equal iff their type codes are equal.
    ///
    /// This method never throws an exception.
    ///
    /// \param other the \c RRType object to compare against.
    /// \return true if the two RRTypes are equal; otherwise false.
    bool equals(const RRType& other) const {
        return (typecode_ == other.typecode_);
    }
    /// \brief Same as \c equals().
    bool operator==(const RRType& other) const {
        return (equals(other));
    }

    /// \brief Return true iff two RRTypes are not equal.ber of pad characters in a group
    size_t max_pad_;

    /// @brief Indicates whether or not the algorithm's digit set is case-sensitive
    bool case_sensitive_;

    /// @brief Maximum index value of the digit set
    size_t max_bits_to_digit_;

    /// @brief Maximum index value of the algorithm bit table
    size_t max_digit_to_bits_;
};

/// @brief Class for encoding and decoding binary data using Base64
/// as described in RFC 4648.
class Base64Encoder : public BaseNEncoder {
public:
    /// @brief Set of digits used for enelManager::toString() at the
/// time of initial logging
typedef std::pair<std::string, LogEventPtr> LevelAndEvent;

/// Convenience typedef for a vector of LevelAndEvent instances
typedef std::vector<LevelAndEvent> LogEventList;

/// \brief Buffering Logger Appender
///
/// This class can be set as an Appender for log4cplus loggers,
/// and is used to store logging events; it simply keeps any
/// event that is passed to \c append(), and will replay them to the
/// logger that they were originally created for when \c flush() is
///ted:
    unsigned target_;
};

/// @brief Token that represents pop or branch if true.
///
/// Branch to a forward target when the top value is true else pop it.
/// Can be used to implement the left "or" boolean operator.
class TokenPopOrBranchTrue : public TokenBranch {
public:
    /// @brief Constructor
    ///
    /// @param target the label to branch to
    /// @throw EvalParseError when target is 0
    TokenPopOrBranchTrue(const unsigned target);

    /// @brief Looks at the top of stack which must be "false" or "true".
    /ntClass client_class_;
};

/// @brief Token that represents vendor options in DHCPv4 and DHCPv6.
///
/// It covers vendor independent vendor information option (125, DHCPv4)
/// and vendor option (17, DHCPv6). Since both of those options may have
/// suboptions, this class is derived from TokenOption and leverages its
/// ability to operate on sub-options. It also adds additional capabilities.
/// In particular, it allows retrieving enterprise-id.
///
/// It can represent the following expressions:
/// vendor[4491].exists - if vend {}

    /// @brief Compare two values.
    ///
    /// Evaluation does not use packet information, but rather consumes the last
    /// two parameters. It does a simple string comparison and sets the value to
    /// either "true" or "false". It requires at least two parameters to be
    /// present on stack.
    ///
    /// @throw EvalBadStack if there are less than 2 values on stack
    ///
    /// @param pkt (unused)
    /// @param values - stack of values (2 arguments will be popped, 1 result
    ///        will be pushed)
   ted IP address will be pushed here)
    /// @return 0 which means evaluate next token if any.
    virtual unsigned evaluate(Pkt& pkt, ValueStack& values);

protected:
    ///< Constant value (empty string if the IP address cannot be converted)
    std::string value_;
};

/// @brief Token representing an IP address as a string
///
/// This token holds the value of an IP address as a string, for instance
/// 10.0.0.1 is '10.0.0.1'
class TokenIpAddressToText : public Token {
public:
    /// @brief Constructor (does nothing)
    TokenIecific states
    /// when they are defined.
    ///
    /// @param state Numeric value holding lease states.
    /// @return Comma separated list of lease state names.
    static std::string statesToText(const uint32_t state);

    /// @brief Returns a reference to a vector representing a DUID.
    ///
    /// @warning Since the function returns the reference to a vector (not a
    /// copy), the returned object should be used with caution because it will
    /// remain valid only for the period of time when an object which returnre that holds a lease for IPv4 address
///
/// For performance reasons it is a simple structure, not a class. If we chose
/// make it a class, all fields would have to made private and getters/setters
/// would be required. As this is a critical part of the code that will be used
/// extensively, direct access is warranted.
struct Lease4 : public Lease {

    /// @brief Client identifier
    ///
    /// @todo Should this be a pointer to a client ID or the ID itself?
    ///       Compare with the DUID in the Lease6 structure.
    Ce6 extended info for by remote id.
///
/// The lease6 extended info may be accessed using different indexes:
/// - using remote id.
/// - using lease address for deletes.
///
/// The internal layout of remote id is not used. The choice of hash tables
/// was governed by the fact a small number of clients should share the same
/// remote id.
///
/// Indexes can be accessed using the index number (from 0 to 5) or a
/// name tag. It is recommended to use the tags to access indexes as
/// they do not depend on the order of indexes in teRemoteIdRange;

/// @brief DHCPv4 lease storage index by relay-id.
typedef Lease4Storage::index<RelayIdIndexTag>::type Lease4StorageRelayIdIndex;

//@}

/// @name Multi index containers holding DHCPv6 lease extended informations
/// for Bulk Lease Query.
//@{

/// @brief Lease6 extended informations for Bulk Lease Query.
class Lease6ExtendedInfo {
public:
    /// @brief Constructor.
    ///
    /// @param lease_addr Lease address.
    /// @param id Identifier.
    Lease6ExtendedInfo(const isc::asiolink::IOAddress& lease_addr,
    option_definitions_;

};

/// @name Pointers to the @c CfgOptionDef objects.
//@{
/// @brief Non-const pointer.
typedef boost::shared_ptr<CfgOptionDef> CfgOptionDefPtr;

/// @brief Const pointer.
typedef boost::shared_ptr<const CfgOptionDef> ConstCfgOptionDefPtr;

//@}

}
}

#endif // CFG_OPTION_DEF_H
// File created from src/lib/dhcpsrv/alloc_engine_messages.mes

#ifndef ALLOC_ENGINE_MESSAGES_H
#define ALLOC_ENGINE_MESSAGES_H

#include <log/message_types.h>

namespace isc {
namespace dhcp {

extern const isc::log::MessageID ALLOC_return maximal allowed timeout value accepted by @c DNSClient::doUpdate
    static unsigned int getMaxTimeout();

    /// @brief Start asynchronous DNS Update with TSIG.
    ///
    /// This function starts asynchronous DNS Update and returns. The DNS Update
    /// will be executed by the specified IO service. Once the message exchange
    /// with a DNS server is complete, timeout occurs or IO operation is
    /// interrupted, the caller-supplied callback function will be invoked.
    ///
    /// An address and port of the DNS se the @c D2UpdateMessage object, which will
/// encapsulate DNS response, through class constructor. An exception will be
/// thrown if the pointer is not initialized by the caller.
///
/// @todo Ultimately, this class will support both TCP and UDP Transport.
/// Currently only UDP is supported and can be specified as a preferred
/// protocol. @c DNSClient constructor will throw an exception if TCP is
/// specified. Once both protocols are supported, the @c DNSClient logic will
/// try to obey caller's preference. However, it may ushat encapsulates the
    /// output buffer and name compression information.
    void toWire(AbstractMessageRenderer& renderer) const;

    /// \brief Render the <code>Name</code> in the wire format without
    /// compression.
    ///
    /// If resource allocation in rendering process fails, a corresponding
    /// standard exception will be thrown.  This can be avoided by preallocating
    /// a sufficient size of \c buffer.  Specifically, if
    /// <code>buffer.getCapacity() - buffer.getLength() >= Name::MAX_WIRE</code>
    //they at least share the trailing empty label.
    /// So, for example, the relationship between "com." and "net." is
    /// "commonancestor".  The relationship of "NONE" can only happen for
    /// comparison between two label sequences (\c LabelSequence objects);
    /// usually only SUPERDOMAIN, SUBDOMAIN or EQUAL are important relationship
    /// between two names.
    ///
    /// When two \c LabelSequence objects are compared, it's generally expected
    /// they are either both absolute or both non absolute; if one is absoluthe staging buffer, not
        // "length".
        data += 2;
        data_length = cumulative - 2;
    } else {

        // Update total amount of data received.
        cumulative += length;
    }

    // Regardless of anything else, the next read goes into the start of the
    // staging buffer.
    offset = 0;

    // Work out how much data we still have to put in the output buffer. (This
    // could be zero if we have just interpreted the TCP count and that was
    // set to zero.)
    if (expected >= outbuff->getLength()) ndpoint, it
        // does not contain a method for getting at the underlying endpoint
        // type - that is in the derived class and the two classes differ on
        // return type.
        isc_throw_assert(endpoint->getProtocol() == IPPROTO_TCP);
        TCPEndpoint* tcp_endpoint = static_cast<TCPEndpoint*>(endpoint);

        // Write the endpoint details from the communications link.  Ideally
        // we should make IOEndpoint assignable, but this runs in to all sorts
        // of problems concerning the management of re dynamically allocated on first use, and
/// held in the smart pointers which are de-allocated only when all instances
/// of the class are destructed. After the object has been created with the
/// constructor, the \c MessageInitializer::loadDictionary static function is
/// called to populate the messages defined in various instances of the
/// \c MessageInitializer class to the global dictionary.
///
/// When messages are added to the dictionary, the are added via the
/// MessageDictionary::add() method, so any duplicates are / @brief Tag for the index for searching by subnet modification time.
struct SubnetModificationTimeIndexTag { };

/// @brief A simple collection of @c Subnet4 objects
///
/// This container provides a set of indexes which can be used to retrieve
/// subnets by subnet identifier and subnet prefix.
///
/// The random access index is used for direct iteration over the collection.
typedef boost::multi_index_container<
    // Multi index container holds pointers to the subnets.
    Subnet4Ptr,
    // The following holds all indexes.
   nst util::Triplet<uint32_t>& valid_lifetime,
           const SubnetID id);

    /// @brief Returns next subnet within shared network.
    ///
    /// If the current subnet doesn't belong to any shared network or if
    /// the next subnet is the same as first subnet (specified in the
    /// argument) a null pointer is returned.
    ///
    /// @param first_subnet Pointer to the subnet from which iterations have
    /// started.
    ///
    /// @return Pointer to the next subnet or null pointer if the next subnet
    /// is the fi.0.0.0 for Subnet4).
    virtual isc::asiolink::IOAddress default_pool() const = 0;

    /// @brief Returns all pools (const variant).
    ///
    /// The reference is only valid as long as the object that returned it.
    ///
    /// @param type lease type to be set
    /// @return a collection of all pools
    const PoolCollection& getPools(Lease::Type type) const;

    /// @brief Returns the number of possible leases for specified lease type.
    ///
    /// @param type type of the lease
    isc::util::uint128_t getPoolCapacity(  // Look for it.
        auto index = factories_.find(queue_type);

        // Not there so nothing to do.
        if (index == factories_.end()) {
            return (false);
        }

        // If the queue is of the type being unregistered, then remove it. We don't
        // a queue instance outliving its library.
        if ((packet_queue_) && (packet_queue_->getQueueType() == queue_type)) {
            packet_queue_.reset();
        }

        // Remove the factory.
        factories_.erase(index);

        return (true);
rvice.
    void setIOService(const asiolink::IOServicePtr& io_service);

    /// @brief Override default connection timeout.
    ///
    /// @param timeout New connection timeout in milliseconds.
    void setConnectionTimeout(const long timeout);

    /// @brief Use external sockets flag.
    ///
    /// Add sockets as external sockets of the interface manager
    /// so available I/O on them makes a waiting select to return.
    ///
    /// @param use_external True (default) add external sockets.
    void addExternalSockets(bool u@throw calls the syntax error function if the name cannot be resolved
    uint16_t convertOptionName(const std::string& option_name,
                               const isc::eval::location& loc);

    /// @brief Attempts to convert string to unsigned 32bit integer
    ///
    /// For reverse conversion, see @ref fromUint32
    ///
    /// @param number string to be converted
    /// @param loc the location of the token
    /// @return the integer value
    /// @throw EvalParseError if conversion fails or the value is out of range.pair in other is copied
/// into element (the ElementPtr of value is copied, this is not a new object)
/// Unless the value is a NullElement, in which case the key is removed from
/// element, rather than setting the value to the given NullElement.
/// This way, we can remove values from for instance maps with configuration
/// data (which would then result in reverting back to the default).
/// Raises a TypeError if either ElementPtr is not a MapElement
void merge(ElementPtr element, ConstElementPtr other);

/// @brief Function usntPtr that contains the element(s) specified
    /// in the given input stream.
    /// @throw JSONError
    static ElementPtr fromJSON(std::istream& in, const std::string& file_name,
                               bool preproc = false);

    /// Creates an Element from the given input stream, where we keep
    /// track of the location in the stream for error reporting.
    ///
    /// @param in The string to parse the element from.
    /// @param file The input file name.
    /// @param line A reference to the int where the funct
    ///
    /// @param t Element type.
    /// @param pos Structure holding position of the value of the data element.
    /// It comprises the line number and the position within this line. The values
    /// held in this structure are used for error logging purposes.
    Element(types t, const Position& pos = ZERO_POSITION())
        : type_(t), position_(pos) {
    }


public:
    // base class; make dtor virtual
    virtual ~Element() {}

    /// @return the type of this element
    types getType() const { return (type_); }

 changes. Such a log could be made
/// available externally and consumed by another application (e.g., Stork).
///
/// The lease manager can track three types of calls: new lease insertion
/// (add), an existing lease update, and lease deletion. Even though the
/// lease reclamation is similar to deleting a lease because it becomes free,
/// it is a lease update from the lease manager's standpoint. Currently,
/// the lease manager cannot track the deletion of the reclaimed leases
/// (i.e., the leases in the expired-reclaimed state)ct class that should not be used directly, but rather
/// specialized implementations should be used instead.
///
/// This class holds a weak pointer to the subnet owning it because
/// it must not exist without the subnet. Also, it can't hold a shared
/// pointer to the subnet because it would cause a circular dependency
/// between the two.
class Allocator {
public:

    /// @brief Type of preferred PD-pool prefix length selection criteria
    enum PrefixLenMatchType {
        PREFIX_LEN_EQUAL,      // select PD-pools with specifn such that
/// it corresponds to the default level of DEBUG.
///
/// This class comprises nothing more than static methods to aid the conversion
/// of logging levels between log4cplus and Kea, and to register those
/// levels with log4cplus.

class LoggerLevelImpl {
public:

typedef log4cplus::tstring LogLevelString;

    /// \brief Convert Kea level to log4cplus logging level
    ///
    /// Converts the Kea severity level into a log4cplus logging level.
    /// If the severity is DEBUG, the current Kea debug level is taken
    rief Parsing failed.
    static const int HTTP_PARSE_FAILED_ST = SM_DERIVED_STATE_MIN + 1001;

    //@}

    /// @name Events used during HTTP message parsing.
    ///
    //@{

    /// @brief Chunk of data successfully read and parsed.
    static const int DATA_READ_OK_EVT = SM_DERIVED_EVENT_MIN + 1;

    /// @brief Unable to proceed with parsing until new data is provided.
    static const int NEED_MORE_DATA_EVT = SM_DERIVED_EVENT_MIN + 2;

    /// @brief New data provided and parsing should continue.
    static const int MORE_DAToCharString() except it
/// does not include the 1-octet length prefix in the \c result, and the
/// result is not limited to MAX_CHARSTRING_LEN octets.
///
/// \throw InvalidRdataText Upon syntax errors.
///
/// \brief str_region A string that represents a character-string.
/// \brief result A placeholder vector where the resulting data are to be
/// stored.  Expected to be empty, but it's not checked.
void stringToCharStringData(const MasterToken::StringRegion& str_region,
                            CharStringData& result);

//hat these constants are used through a "proxy" function.
/// This is because they may be used to initialize another non-local (e.g.
/// global or namespace-scope) static object as follows:
///
/// \code
/// namespace foo {
/// const RRClass default_class = RRClass::IN();
/// } \endcode
///
/// In order to ensure that the constant RRClass object has been initialized
/// before the initialization for \c default_class, we need help from
/// the proxy function.
///
/// Note to developers: same note as \c RRType applies.
class RRClass {f HttpConnection
/// and stores them in the pool of active connections. The @ref HttpConnection
/// is responsible for managing the next connection received and receiving the
/// HTTP request and sending appropriate response. The listener can handle
/// many HTTP connections simultaneously.
///
/// When the @ref HttpListener::stop is invoked, all active connections are
/// closed and the listener stops accepting new connections.
class HttpListener {
public:

    /// @brief HTTP request timeout value.
    struct RequestTimeout {
    getNative() const { return (-1); }

    /// \brief A dummy derived method of \c IOAsioSocket::getProtocol().
    ///
    /// \return Protocol socket was created with
    virtual int getProtocol() const { return (protocol_); }


    /// \brief Is socket opening synchronous?
    ///
    /// \return true - it is for this class.
    bool isOpenSynchronous() const {
        return true;
    }

    /// \brief Open AsioSocket
    ///
    /// A call that is a no-op on UDP sockets, this opens a connection to the
    /// system identified brapper for the ASIO socket classes such as
/// \c ip::tcp::socket and \c ip::udp::socket.
///
/// This is the basic IOSocket with additional operations - open, send, receive
/// and close.  Depending on how the asiolink code develops, it may be a
/// temporary class: its main use is to add the template parameter needed for
/// the derived classes UDPSocket and TCPSocket but without changing the
/// signature of the more basic IOSocket class.
///
/// We may revisit this decision when we generalize the wrapper and more
/// modules usype of callbacks.
/// @tparam TlsStreamImpl The type of underlying TLS streams.
/// @param service I/O Service object used to manage the stream.
/// @param context Pointer to the TLS context.
/// @note The caller must not provide a null pointer to the TLS context.
template <typename Callback, typename TlsStreamImpl>
TlsStreamBase<Callback, TlsStreamImpl>::
TlsStreamBase(const IOServicePtr& io_service, TlsContextPtr context)
    : StreamService(io_service, context),
      TlsStreamImpl(io_service->getInternalIOService(),
      conteifndef IO_SOCKET_H
#define IO_SOCKET_H 1

// IMPORTANT NOTE: only very few ASIO headers files can be included in
// this file.  In particular, asio.hpp should never be included here.
// See the description of the namespace below.
#include <unistd.h>             // for some network system calls

#include <functional>
#include <string>
#include <boost/asio/socket_base.hpp>

#include <exceptions/exceptions.h>

namespace isc {
namespace asiolink {

/// \brief The \c IOSocket class is an abstract base class to represent
/// various typegr version
    /// @return true if the factory was successfully added to the map, false
    /// if it already exists.
    static bool registerFactory(const std::string& db_type,
                                const Factory& factory,
                                bool no_log = false,
                                DBVersion db_version = DBVersion());

    /// @brief Deregister a lease mgr factory
    ///
    /// Disassociate the factory to a database type in the map.
    /// The no_log is to avoid logging during global object ded by multiple servers.
/// In the latter case, a subnet may be associated with a subset of
/// servers or all servers. An administrator may also add the
/// configuration data into the database and do not associate this data
/// with any particular server.
///
/// When fetching the configuration data from a database or when storing
/// data in the database there is a need to specify which servers this
/// data is associated with. The @c ServerSelector class represents
/// such associations.
///
/// It includes three modes of selecteturn (ret);
    }

    /// @brief Read an unsigned 32-bit integer in network byte order from the buffer, and return it.
    ///
    /// @details If the remaining length of the buffer is smaller than 32-bit,
    /// an exception of class @c isc::OutOfRange will be thrown.
    uint32_t peekUint32() {
        if (current_ + sizeof(uint32_t) > end_) {
            isc_throw(OutOfRange,
                      "InputBuffer::peekUint32 read beyond end of buffer");
        }

        uint32_t ret;
        ret = (static_cast<uint32_t>(currenespace util {

/// @brief The @c InputBuffer class is a buffer abstraction for manipulating read-only data.
///
/// @details The main purpose of this class is to provide a safe placeholder
/// for examining wire-format data received from a network.
///
/// Applications normally use this class only in a limited situation:
/// as an interface between legacy I/O operation (such as receiving
/// data from a BSD socket) and the rest of the Kea DNS library.  One
/// common usage of this class for an application would therefore be
/// somethod and
    /// is used to verify that all the required events are defined.  If the
    /// event set is determined to be invalid this method should throw a
    /// StateModelError.  As with the defineEvents method, each class within
    /// a StateModel derivation hierarchy must supply an implementation
    /// which calls its superclass's implementation as well as verifying any
    /// events added by the derivation.  Validating an event is accomplished
    /// by simply attempting to fetch an event by its value from the event red event or when it has reached its final state.  In the case of
/// the former, the loop may be re-entered upon arrival of the external event.
///
/// This loop is implemented in the runModel method.  This method accepts an
/// event as argument which it "posts" as the next event.  It then retrieves the
/// handler for the current state from the handler map and invokes it. runModel
/// repeats this process until either a NOP_EVT posts or the state changes
/// to END_ST.  In other words each invocation of runModel causes the modelaram len The length of data that should be trimmed.
    void trim(size_t len) {
        buffer_->trim(len);
    }

    /// \brief Clear the internal buffer and other internal resources.
    ///
    /// This method can be used to re-initialize and reuse the renderer
    /// without constructing a new one.
    virtual void clear();

    /// \brief Write an unsigned 8-bit integer into the internal buffer.
    ///
    /// \param data The 8-bit integer to be written into the internal buffer.
    void writeUint8(const uint8_t data) {
   ding this connection.
    TcpConnectionPool& connection_pool_;

    /// @brief External TCP acceptor callback.
    TcpConnectionAcceptorCallback acceptor_callback_;

    /// @brief External callback for filtering connections by IP address.
    TcpConnectionFilterCallback connection_filter_;

    /// @brief Maximum bytes to read in a single socket read.
    size_t read_max_;

    /// @brief Buffer for a single socket read.
    WireData input_buf_;

    /// @brief Remote endpoint.
    boost::asio::ip::tcp::endpoint remote_endpoint_;
d when TLS handshake is performed.
    ///
    /// If the handshake is performed successfully the @ref
    /// TcpConnection::doRead is called.
    ///
    /// @param ec Error code.
    void handshakeCallback(const boost::system::error_code& ec);

    /// @brief Callback invoked when new data is received over the socket.
    ///
    /// This callback supplies the data to the TCP parser and continues
    /// parsing. When the parser signals end of the TCP request the callback
    /// prepares a response and starts asynchronous send dn't include
    /// header fields.
    ///
    /// @return String containing hexadecimal representation of the option.
    virtual std::string toHexString(const bool include_header = false) const;

    /// Returns option type (0-255 for DHCPv4, 0-65535 for DHCPv6)
    ///
    /// @return option type
    uint16_t getType() const {
        return (type_);
    }

    /// Returns length of the complete option (data length + DHCPv4/DHCPv6
    /// option header)
    ///
    /// @return length of the option
    virtual uint16_t len() conut it does not take
    /// the whole vector<uint8_t>, but rather subset of it.
    ///
    /// @todo This can be templated to use different containers, not just
    /// vector. Prototype should look like this:
    /// template<typename InputIterator> Option(Universe u, uint16_t type,
    /// InputIterator first, InputIterator last);
    ///
    /// vector<int8_t> myData;
    /// Example usage: new Option(V4, 123, myData.begin()+1, myData.end()-1)
    /// This will create DHCPv4 option of type 123 that contains data from
    /// trarses list of DHCP4 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.
class Subnets4ListConfigParser : public isc::data::SimpleParser {
public:

    /// @brief constructor
    ///
    /// @param check_iface Check if the specified interface exists in
    /// the system.
    Subnets4ListConfigParser(bool check_iface = true);

    /// @brief Virtual destructor.
    virtual ~Subnets4ListConfigParser() {
    }
can be overridden in the child classes to supply
    /// a custom parser for the pools.
    ///
    /// @return an instance of the @c Pool4Parser.
    virtual boost::shared_ptr<PoolParser> createPoolConfigParser() const;
};

/// @brief parser for additional relay information
///
/// This concrete parser handles RelayInfo structure definitions.
/// So far that structure holds only relay IP (v4 or v6) address, but it
/// is expected that the number of parameters will increase over time.
///
/// It is useful for parsing Dhcp<4/6>/subnttp::HttpRequestPtr& request,
                            const http::HttpStatusCode& status_code) const;

    /// @brief Returns HTTP control socket config.
    HttpCommandConfigPtr getHttpCommandConfig() const {
        return (config_);
    }

private:

    /// @brief Creates un-finalized stock HTTP response.
    ///
    /// The un-finalized response is the response that can't be sent over the
    /// wire until @c finalize() is called, which commits the contents of the
    /// message body.
    ///
    /// @param request Pointe
        void wait() {
            std::unique_lock<std::mutex> lock(mutex_);
            // Wait for any item or for working threads to finish.
            wait_cv_.wait(lock, [&]() {return (working_ == 0 && queue_.empty());});
        }

        /// @brief wait for items to be processed or return after timeout
        ///
        /// Used to block the calling thread until all items in the queue have
        /// been processed or return after timeout
        ///
        /// @param seconds the time in seconds to wait for tasks to f;
/// Pair of iterators to represent the range of options definitions
/// having the same option name. The first element in this pair
/// represents the beginning of the range, the second element
/// represents the end.
typedef std::pair<OptionDefContainerNameIndex::const_iterator,
                  OptionDefContainerNameIndex::const_iterator> OptionDefContainerNameRange;

/// Base type of option definition space container.
typedef OptionSpaceContainer<
    OptionDefContainer, OptionDefinitionPtr, std::string
> BaseOptionDefSpaceCoferConstIter end,
                                             OpaqueDataTuple::LengthFieldType length_field_type);

    /// @brief Factory function to create option with integer value.
    ///
    /// @param u universe (V4 or V6).
    /// @param type option type.
    /// @param encapsulated_space An option space being encapsulated by the
    /// options created by this factory function. The options which belong to
    /// encapsulated option space are sub options of this option.
    /// @param begin iterator pointing to the beginn "record" or even "array of records".
///
/// Array types should be used when the option contains multiple contiguous
/// data values of the same type laid. For example, DHCPv6 option 6 includes
/// multiple fields holding uint16 codes of requested DHCPv6 options (RFC 8415).
/// Such an option can be represented with this class by setting the option
/// type to "uint16" and the array indicator (array_type) to true.  The number
/// of elements in the array is effectively unlimited (although it is actually
/// limited by the maximal ontext.h>

#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/shared_ptr.hpp>
#include <map>
#include <string>

namespace isc {
namespace dhcp {

/// @brief Exception to be thrown when invalid option value has been
/// specified for a particular option definition.
class InvalidOptionValue : public Exception {
public:
    InvalidOptionValue(cons  libraries and returns false. It is a fatal error as there
    ///        is no possible recovery. It is a logic error in the hook
    ///        code too so the solution is to fix it and to restart
    ///        the server with a correct hook library binary.
    ///
    /// @return true if all libraries unloaded successfully, false if they
    ///         are still in memory.
    static bool unloadLibraries();

    /// @brief Prepare the unloading of libraries
    ///
    /// Calls the unload functions when they exist and remove /// Creates the object and calls the callouts on the "context_create"
    /// hook.
    ///
    /// Of the two arguments passed, only the pointer to the callout manager is
    /// actively used.  The second argument, the pointer to the library manager
    /// collection, is used for lifetime control: after use, the callout handle
    /// may contain pointers to memory allocated by the loaded libraries.  The
    /// used of a shared pointer to the collection of library managers means
    /// that the libraries that could have allocbrief Attempts to extract MAC/Hardware address from DOCSIS options.
    ///
    /// The DHCPv6 mechanism extracts that information from DOCSIS option
    /// (vendor-specific info, vendor-id=4491, suboption 1026). Note that
    /// in a DOCSIS capable network, the MAC address information is provided
    /// several times. The first is specified by the modem itself. The second
    /// is added by the CMTS, which acts as a relay agent. This method
    /// attempts to extract the latter. See @ref getMACFromDocsisModem
    /// for a sic std::string makeLabel(const DuidPtr duid, const HWAddrPtr& hwaddr);

    /// @brief Returns text representation of the primary packet identifiers
    ///
    /// This method is intended to be used to provide a consistent way to
    /// identify packets within log statements.  It is an instance-level
    /// wrapper around static makeLabel(). See this method for string
    /// content.
    ///
    /// @note Currently this method doesn't include the HW address in the
    /// returned text.
    ///
    /// @return string with text rostname The lower case hostname.
    /// @param [out] storage Container to which the retrieved objects are
    /// appended.
    /// @tparam One of the @c ConstHostCollection of @c HostCollection.
    template<typename Storage>
    void getAllbyHostnameInternal(const std::string& hostname,
                                  Storage& storage) const;

    /// @brief Return all hosts with a hostname and a DHCPv4 subnet.
    ///
    /// This private method is called by the @c CfgHosts::getAllbyHostname4
    /// method which finds the @cmmunicate with the DHCP server the same IP address
    /// should be assigned. In this case the @c unique value should be set to
    /// false to disable the checks for uniqueness on the backend side.
    ///
    /// @param unique boolean flag indicating if the IP reservations must be
    /// unique or can be non-unique.
    /// @return always true because this data source supports both the case when
    /// the addresses must be unique and when they may be non-unique.
    virtual bool setIPReservationsUnique(const bool unique);

 be empty).
    virtual HostCollection
    getPage4(const SubnetID& subnet_id,
             size_t& source_index,
             uint64_t lower_host_id,
             const HostPageSize& page_size);

    /// @brief Returns range of hosts in a DHCPv6 subnet.
    ///
    /// This method returns a page of @c Host objects which represent
    /// reservations in a specified subnet.
    ///
    /// @param subnet_id Subnet identifier.
    /// @param source_index Index of the source (unused).
    /// @param lower_host_id Host identifier used aHEADER_H
#define CFG_HTTP_HEADER_H

#include <cc/cfg_to_element.h>
#include <cc/data.h>
#include <cc/user_context.h>
#include <http/request.h>
#include <http/response.h>

namespace isc {
namespace http {

/// @brief Config HTTP header.
///
/// Extra headers to include in a message are configured as a list of
/// objects of this class. At the difference of other HTTP header classes
/// there is no numeric value.
class CfgHttpHeader : public isc::data::UserContext, public isc::data::CfgToElement {
public:
    /// @brief Header name.
ffer& result, size_t len);

    /// \brief Calculate the final signature
    ///
    /// len bytes of data from the result will be copied to *result
    /// If len is larger than the output size, only output_size bytes
    /// will be copied. If it is smaller, the output will be truncated
    ///
    /// \exception LibraryError if there was any unexpected exception
    ///                         in the underlying library
    ///
    /// At least len bytes of data must be available for writing at
    /// result
    void sign(void* rtual ConstHostPtr
    get6(const SubnetID& subnet_id, const asiolink::IOAddress& address) const = 0;

    /// @brief Returns all hosts connected to the IPv6 subnet and having
    /// a reservation for a specified address or delegated prefix (lease).
    ///
    /// In most cases it is desired that there is at most one reservation
    /// for a given IPv6 lease within a subnet. In a default configuration,
    /// the backend does not allow for inserting more than one host with
    /// the same IPv6 address or prefix. In that case, ge of hosts in a DHCPv4 subnet.
    ///
    /// This method implements paged browsing of host databases. The
    /// parameters specify a page size, an index in sources and the
    /// starting host id of the range. If not zero this host id is
    /// excluded from the returned range. When a source is exhausted
    /// the index is updated. There is no guarantee about the order
    /// of returned host reservations, only the sources and
    /// reservations from the same source are ordered.
    ///
    /// @param subnet_id Subnet i Host objects using an
/// identifier + identifier type tuple.
typedef HostContainer::nth_index<0>::type HostContainerIndex0;

/// @brief Results range returned using the @c HostContainerIndex0.
typedef std::pair<HostContainerIndex0::iterator,
                  HostContainerIndex0::iterator> HostContainerIndex0Range;

/// @brief Second index type in the @c HostContainer.
///
/// This index allows for searching for @c Host objects using a
/// reserved IPv4 address.
typedef HostContainer::nth_index<1>::type HostContainerIndex1;

/// nction sends a DHCPv6 message through a specified interface and
    /// socket. In general, there may be multiple sockets open on a single
    /// interface as a single interface may have multiple IPv6 addresses.
    ///
    /// @param iface Interface to be used to send packet.
    /// @param sockfd A socket descriptor
    /// @param pkt A packet to be sent.
    ///
    /// @return A result of sending the message. It is 0 if successful.
    virtual int send(const Iface& iface, uint16_t sockfd,
                     const Pkt6Ptr& pks are 4-bit integers that are used in limited
/// places and it's unlikely that new code values will be assigned, we could
/// represent them as simple integers (via constant variables or enums).
/// However, we define a separate class so that we can benefit from C++
/// type safety as much as possible.  For convenience we also provide
/// an enum type for standard OPCDE values, but it is generally advisable
/// to handle OPCODEs through this class.  In fact, public interfaces of
/// this library uses this class to pass or return ODataType data_type);

    /// @brief Read IPv4 or IPv6 address from a buffer.
    ///
    /// @param buf input buffer.
    /// @param family address family: AF_INET or AF_INET6.
    ///
    /// @throw isc::dhcp::BadDataTypeCast when the data being read
    /// is truncated.
    /// @return address being read.
    static asiolink::IOAddress readAddress(const std::vector<uint8_t>& buf,
                                           const short family);

    /// @brief Append IPv4 or IPv6 address to a buffer.
    ///
    /// @param addresThese values are stored by config backend.  Altering any existing
/// values will produce code that is incompatiable with pre-existing data.
/// Futhermore, the order of data types matters: OPT_UNKNOWN_TYPE
/// must always be and OPT_RECORD_TYPE must be at second to last.
/// This is because some functions perform sanity checks on data type
/// values using '>' operators, assuming that all values beyond the
enum OptionDataType : int {
    OPT_EMPTY_TYPE          = 0,
    OPT_BINARY_TYPE         = 1,
    OPT_BOOLEAN_TYPE        = 2, the given @c HttpMessage instance. Once the message
/// is parsed and all required information is stored in the context,
/// the @c create method is called to validate and fetch information
/// from the context into the message. The @c finalize method is called
/// to commit the HTTP message body into the message.
///
/// The outbound message is created locally from the known data, e.g.
/// HTTP version number, URI, method etc. The headers can be then
/// appended to the message via the context. In order to use this message
/// thimum as an Optional.
    util::Optional<uint32_t> getTtlMax() const;

    /// @brief Returns the DDNS config resolution mode for kea-dhcp-ddns
    ///
    /// This value is communicated to D2 via the NCR.
    ///
    /// @return the DDNS conflict resolution mode
    std::string getConflictResolutionMode() const;

    /// @brief Returns the subnet-id of the subnet associated with these parameters
    ///
    /// @return value of subnet-id (or 0 if no subnet is associated)
    SubnetID getSubnetId() const {
        if (subnet_) {
   option. If option hasn't been found, the
    /// descriptor holds null option.
    template<typename Selector>
    OptionDescriptor get(const Selector& key,
                         const uint16_t option_code) const {

        // Check for presence of options.
        OptionContainerPtr options = getAll(key);
        if (!options || options->empty()) {
            return (OptionDescriptor(false, false));
        }

        // Some options present, locate the one we are interested in.
        const OptionContainerTypeIndex& idx = opst::multi_index::ordered_non_unique<
            boost::multi_index::const_mem_fun<
                data::BaseStampedElement,
                boost::posix_time::ptime,
                &data::BaseStampedElement::getModificationTime
            >
        >,

        // Start definition of index #4.
        // Use BaseStampedElement::getId as a key.
        boost::multi_index::hashed_non_unique<
            boost::multi_index::tag<OptionIdIndexTag>,
            boost::multi_index::const_mem_fun<data::BaseStampedElement, uint64_t,
    re is a forward branch to a not found target.
void evaluateRaw(const Expression& expr, Pkt& pkt, ValueStack& values);

/// @brief Evaluate a RPN expression for a v4 or v6 packet and return
///        a true or false decision
///
/// @param expr the RPN expression, i.e., a vector of parsed tokens
/// @param pkt  The v4 or v6 packet
/// @return the boolean decision
/// @throw EvalStackError if there is not exactly one element on the value
///        stack at the end of the evaluation
/// @throw EvalTypeError if the value at the top o/ The file defines the class, ClientClassDef, which houses the
/// information for single client class such as the class name, the
/// logical expression used to identify members of the class, and options
/// that may be attributed to class members.
///
/// In addition it defines a container class, ClientClassDictionary, which
/// is houses class definitions keyed by class name.
///
namespace isc {
namespace dhcp {

/// @brief Error that occurs when an attempt is made to add a duplicate class
/// to a class dictionary.
class Duplicain instance
    DdnsDomainPtr parse(data::ConstElementPtr domain_config,
                        const TSIGKeyInfoMapPtr keys);
};

/// @brief Parser for a list of DdnsDomains
///
/// This class parses a list of "ddns-domain" configuration elements
/// into a map of DdnsDomains.
class DdnsDomainListParser : public data::SimpleParser {
public:
    /// @brief Performs the actual parsing of the given list "ddns-domain"
    /// elements.
    /// Creates a new DdnsDomain map
    /// It iterates over each domain entry in the list:
    / return it as the
    /// match.  If the wild card domain is the only domain in the list, then
    /// it will be returned immediately for any FQDN.
    ///
    /// @param fqdn is the name for which to look.
    /// @param domain receives the matching domain. If no match is found its
    /// contents will be unchanged.
    ///
    /// @return returns true if a match is found, false otherwise.
    /// @todo This is a very basic match method, which expects valid FQDNs
    /// both as input and for the DdnsDomain::getName().  Currentl:ostream&
operator<<(std::ostream& os, const D2Params& config);

/// @brief Defines a pointer for D2Params instances.
typedef boost::shared_ptr<D2Params> D2ParamsPtr;

/// @brief Represents a TSIG Key.
///
/// Acts as both a storage class containing the basic attributes which
/// describe a TSIG Key, as well as owning and providing access to an
/// instance of the actual key (@ref isc::dns::TSIGKey) that can be used
/// by the IO layer for signing and verifying messages.
///
class TSIGKeyInfo : public isc::data::UserContext, public         const AddRRCallback& add_callback,
                 Options options = DEFAULT);

    /// \brief Constructor from a stream
    ///
    /// This is a constructor very similar to the previous one. The only
    /// difference is it doesn't take a filename, but an input stream
    /// to read the data from. It is expected to be mostly used in tests,
    /// but it is public as it may possibly be useful for other currently
    /// unknown purposes.
    MasterLoader(std::istream& input,
                 const Name& zone_origin,
 ///< Last index in yytable_.
      yynnts_ = 22,  ///< Number of nonterminal symbols.
      yyfinal_ = 46 ///< Termination state number.
    };


    // User arguments.
    EvalContext& ctx;

  };

  inline
  EvalParser::symbol_kind_type
  EvalParser::yytranslate_ (int t) YY_NOEXCEPT
  {
    // YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to
    // TOKEN-NUM as returned by yylex.
    static
    const signed char
    translate_table[] =
    {
       0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
       2,st location_type& l)
      {
        return symbol_type (token::TOKEN_INT32TOTEXT, l);
      }
#endif
#if 201103L <= YY_CPLUSPLUS
      static
      symbol_type
      make_UINT8TOTEXT (location_type l)
      {
        return symbol_type (token::TOKEN_UINT8TOTEXT, std::move (l));
      }
#else
      static
      symbol_type
      make_UINT8TOTEXT (const location_type& l)
      {
        return symbol_type (token::TOKEN_UINT8TOTEXT, l);
      }
#endif
#if 201103L <= YY_CPLUSPLUS
      static
      symbol_type
      make_UINT16TOTEXT ng name of the symbol whose (internal) number is
    /// YYSYMBOL.  No bounds checking.
    static std::string symbol_name (symbol_kind_type yysymbol);

    // Implementation of make_symbol for each token kind.
#if 201103L <= YY_CPLUSPLUS
      static
      symbol_type
      make_END (location_type l)
      {
        return symbol_type (token::TOKEN_END, std::move (l));
      }
#else
      static
      symbol_type
      make_END (const location_type& l)
      {
        return symbol_type (token::TOKEN_END, l);
      }
#endif
#if 20
      case symbol_kind::S_enterprise_id: // enterprise_id
        value.move< uint32_t > (std::move (that.value));
        break;

      default:
        break;
    }

      }
#endif

      /// Copy constructor.
      basic_symbol (const basic_symbol& that);

      /// Constructors for typed symbols.
#if 201103L <= YY_CPLUSPLUS
      basic_symbol (typename Base::kind_type t, location_type&& l)
        : Base (t)
        , location (std::move (l))
      {}
#else
      basic_symbol (typename Base::kind_type t, const location_type& l /// self_type::move ().
    template <typename T>
    void
    swap (self_type& that) YY_NOEXCEPT
    {
      EVAL_ASSERT (yytypeid_);
      EVAL_ASSERT (*yytypeid_ == *that.yytypeid_);
      std::swap (as<T> (), that.as<T> ());
    }

    /// Move the content of \a that to this.
    ///
    /// Destroys \a that.
    template <typename T>
    void
    move (self_type& that)
    {
# if 201103L <= YY_CPLUSPLUS
      emplace<T> (std::move (that.as<T> ()));
# else
      emplace<T> ();
      swap<T> (that);
# endif
      that.destroy<Tunified
/// straightforward implementation should suffice for any use cases
/// including performance sensitive ones.
///
/// We may, however, still want to have a customized version of Question
/// for, e.g, highly optimized behavior, and may revisit this design choice
/// as we have more experience with this implementation.
///
/// One disadvantage of defining RRsets and Questions as unrelated classes
/// is that we cannot handle them in a polymorphic way.
/// For example, we might want to iterate over DNS message sections and
//aram db_type database backend type.
    /// @param dbaccess Database access parameters.  These are in the form of
    ///        "keyword=value" pairs, separated by spaces. They are backend-
    ///        -end specific, although must include the "type" keyword which
    ///        gives the backend in use.
    /// @param if_unusable flag which indicates if the host data source should
    ///        be deleted only if it is unusable.
    /// @return false when not removed because it is not found or because it is
    /// still usablation.
    ///
    /// Parse the configuration and check that the various keywords are
    /// consistent.
    ///
    /// @note The supported parameters are:
    /// - syslog parameters:
    ///       - pattern
    ///       - facility
    ///
    /// @param parameters The library parameters.
    /// @param [out] map The parameter map.
    static void parseSyslog(const isc::data::ConstElementPtr& parameters, isc::db::DatabaseConnection::ParameterMap& map);

    /// @brief Parse extra parameters which are not related to backend
   _FAIL;
extern const isc::log::MessageID DHCP_DDNS_CONFIG_SYNTAX_WARNING;
extern const isc::log::MessageID DHCP_DDNS_FAILED;
extern const isc::log::MessageID DHCP_DDNS_FORWARD_ADD_BAD_DNSCLIENT_STATUS;
extern const isc::log::MessageID DHCP_DDNS_FORWARD_ADD_BUILD_FAILURE;
extern const isc::log::MessageID DHCP_DDNS_FORWARD_ADD_IO_ERROR;
extern const isc::log::MessageID DHCP_DDNS_FORWARD_ADD_REJECTED;
extern const isc::log::MessageID DHCP_DDNS_FORWARD_ADD_RESP_CORRUPT;
extern const isc::log::MessageID DHCP_DDNS_FORWARD_ADD_TIMEOUT;
ext the IPv4 case significantly reduces
    /// the amount of memory occupied by the container by removing the overhead
    /// of holding the entire IOAddress instance.
    template<typename AddressType>
    using FreeLeaseQueue = boost::multi_index_container<
        AddressType,
        boost::multi_index::indexed_by<
            boost::multi_index::sequenced<>,
            boost::multi_index::hashed_unique<
                boost::multi_index::identity<AddressType>
            >
        >
    >;

    /// @brief A multi-index contaiports DUID types defined in RFC 8415.
///
/// In most cases DUIDs can be generated automatically, i.e. no manual
/// configuration is required. For example, DUID-LLT is composed of the
/// current time and link layer address and type of one of the network
/// interfaces. Once the DUID is generated it should be stored in the persistent
/// storage and used by a server or client even when the network interface which
/// address had been used to generate the DUID is removed.
///
/// In some cases administrators may elect to use other ame Constructors and Destructor
    ///
    /// Note: The copy constructor and the assignment operator are intentionally
    /// defined as private.  The intended use case wouldn't require copies of
    /// a \c BasicRRset object; once created, it would normally be used
    /// as a \c const object (via references).
    //@{
private:
    BasicRRset(const BasicRRset& source);
    BasicRRset& operator=(const BasicRRset& source);
public:
    /// \brief Constructor from (mostly) fixed parameters of the RRset.
    ///
    /// This const/ This is intentionally defined as \c protected as this base class should
    /// never be instantiated (except as part of a derived class).
    AbstractRRset() {}
public:
    /// The destructor.
    virtual ~AbstractRRset() {}
    //@}

    ///
    /// \name Getter and Setter Methods
    ///
    /// These methods are generally expected to be exception free, but it's
    /// not guaranteed at the interface level;
    /// for example, some performance optimized derived class may manage
    /// the information corresponding to the clef Check if the thread pool is stopped.
    ///
    /// @return True if the thread pool is stopped, false otherwise.
    bool isStopped() {
        return (getState() == State::STOPPED);
    }

    /// @brief Check current thread permissions to transition to the new PAUSED
    /// state.
    ///
    /// This function throws @ref MultiThreadingInvalidOperation if the calling
    /// thread is one of the worker threads. This would prevent a dead-lock if
    /// the calling thread would try to perform a thread pool state transition
  ink/io_service.h>
#include <util/unlock_guard.h>

#include <boost/shared_ptr.hpp>

#include <condition_variable>
#include <list>
#include <mutex>
#include <thread>

namespace isc {
namespace asiolink {

/// @brief Implements a pausable pool of IOService driven threads.
class IoServiceThreadPool {
public:
    /// @brief Describes the possible operational state of the thread pool.
    enum class State {
        STOPPED,    /// Pool is not operational.
        RUNNING,    /// Pool is populated with running threads.
        PAUSED,    n a
    /// given string, excluding quotes. This is useful in cases when specific
    /// identifiers, e.g. circuit-id are manually assigned user friendly values.
    ///
    /// @param identifier Identifier in the textual format. The expected formats
    /// for the hardware address and other identifiers are provided above.
    /// @param identifier_name One of the supported identifiers in the text form as
    /// described for @ref IdentifierType.
    /// @param ipv4_subnet_id Identifier of the IPv4 subnet to which the host
    /      info->set("size", data::Element::create(static_cast<int64_t>(getSize())));
       return (info);
    }

private:

    /// @brief Packet queue
    boost::circular_buffer<PacketTypePtr> queue_;

    /// @brief Mutex for protecting queue accesses.
    boost::scoped_ptr<std::mutex> mutex_;
};


/// @brief DHCPv4 packet queue buffer implementation
///
/// This implementation does not (currently) add any drop
/// or packet skip logic, it operates as a verbatim ring
/// queue for DHCPv4 packets.
///
class PacketQueueRing4 : public Pcations to
    /// handle.
    void process() {
        processInit();
        processEnd();
    }

    /// \brief Run-Time Initialization
    ///
    /// Performs run-time initialization of the logger system, in particular
    /// supplying the root logger name and name of a replacement message file.
    ///
    /// This must be the first logging function called in the program.  If
    /// an attempt is made to log a message before this is function is called,
    /// the results will be dependent on the underlying logging package. as the operation is synchronous.
    virtual void open(const IOEndpoint* endpoint, C& callback);

    /// \brief Send Asynchronously
    ///
    /// Calls the underlying socket's async_send_to() method to send a packet of
    /// data asynchronously to the remote endpoint.  The callback will be called
    /// on completion.
    ///
    /// \param data Data to send
    /// \param length Length of data to send
    /// \param endpoint Target of the send
    /// \param callback Callback object.
    virtual void asyncSend(const void* d  ///
    /// The first call to this function with no arguments will set the default
    /// hooks path to either the value of LOGFILE_DIR or the environment
    /// variable KEA_LOG_FILE_DIR if it is defined. Subsequent calls with no
    /// arguments will simply return this value.
    ///
    /// @param reset recalculate when true, defaults to false.
    /// @param explicit_path set default log path to this value. This is
    /// for testing purposes only.
    ///
    /// @return String containing the default log file path.
    s.

#ifndef DHCPSRV_LOGGING_H
#define DHCPSRV_LOGGING_H

#include <cc/data.h>
#include <process/logging_info.h>
#include <process/config_base.h>
#include <vector>

namespace isc {
namespace process {

/// @brief Configures log4cplus by translating Kea configuration structures
///
/// This parser iterates over provided data elements and translates them
/// into values applicable to log4cplus.
///
/// The data structures converted to JSON format have the following syntax:
/// {
///     "name": "kea",
///     "output-options": [
///   or information as to why the class holds
    /// a reference instead of accessing the singleton within the code.
    ServerHooks& server_hooks_;

    /// Current library index.  When a call is made to any of the callout
    /// registration methods, this variable indicates the index of the user
    /// library that should be associated with the call.
    int current_library_;

    /// Vector of callout vectors.  There is one entry in this outer vector for
    /// each hook. Each element is itself a vector, with one entry for each
 ent(const std::string& command_name) const;

    /// @brief Calls the callouts for a given hook
    ///
    /// Iterates through the library handles and calls the callouts associated
    /// with the given hook index.
    ///
    /// @note This method invalidates the current library index set with
    ///       setLibraryIndex().
    ///
    /// @param hook_index Index of the hook to call.
    /// @param callout_handle Reference to the CalloutHandle object for the
    ///        current object being processed.
    void callCallouts  /// Writes option in wire-format to buffer, returns pointer to first unused
    /// byte after stored option (that is useful for writing options one after
    /// another).
    ///
    /// @param buf pointer to a buffer
    /// @param check flag which indicates if checking the option length is
    /// required (used only in V4)
    ///
    /// @throw InvalidOptionDnrDomainName Thrown when Option's mandatory field ADN is empty.
    /// @throw OutOfRange Thrown when @c check param set to @c true and
    /// @c Option::packHeader(bungth_ field.
    ///
    /// Size is calculated basing on set Service Priority, ADN, IP address(es) and SvcParams.
    /// This should be called after all fields are set.
    /// This is only used for DHCPv4 Encrypted DNS %Option.
    void setDnrInstanceDataLength() {
        dnr_instance_data_length_ = dnrInstanceLen();
    }

    /// @brief Writes the ADN FQDN in the wire format into a buffer.
    ///
    /// The Authentication Domain Name - fully qualified domain name of the encrypted
    /// DNS resolver data is appended at thecation state instance for the pool.
    PoolFreeLeaseQueueAllocationStatePtr getPoolState(const PoolPtr& pool) const;

    /// @brief Returns a pool in the subnet the lease belongs to.
    ///
    /// This function is used in the interface manager callbacks to find
    /// a pool for a lease modified in the database.
    ///
    /// @param lease lease instance for which the pool should be returned.
    /// @return A pool found for a lease or null pointer if such a pool does
    /// not exist.
    PoolPtr getLeasePool(const LeasePtrquality operator.
    ///
    /// This operator compares the string given as an argument to the data
    /// carried in the tuple for inequality.
    ///
    /// @param other String to compare the tuple against.
    /// @return true if the data carried in the tuple is unequal the given
    /// string.
    bool operator!=(const std::string& other);
    //@}

    /// @brief Returns the size of the tuple length field.
    ///
    /// The returned value depends on the @c LengthFieldType set for the tuple.
    int getDataFieldSize() con
/// The Config Backend Managers are typically implemented as singletons
/// which can be accessed from any place within the server code. This
/// includes server configuration, data fetching during normal server
/// operation and data management, including processing of control
/// commands implemented within hooks libraries.
///
/// The @c BaseConfigBackendMgr is a base class for all CBMs implemented
/// for respective Kea servers. It includes mechanisms to register config
/// backend factory functions and to create instances of on type.
    /// @param buf buffer with option data (must not be empty).
    ///
    /// @throw isc::OutOfRange if provided buffer is empty or its length
    /// is not multiple of size of the data type in bytes.
    /// @throw isc::dhcp::InvalidDataType if data field type provided
    /// as template parameter is not a supported integer type.
    OptionIntArray(const Option::Universe u, const uint16_t type,
                   const OptionBuffer& buf)
        : Option(u, type) {
        if (!OptionDataTypeTraits<T>::integer_type) {ter to the @c Pool4 instance.
    static Pool4Ptr create(const isc::asiolink::IOAddress& prefix,
                           uint8_t prefix_len);

    /// @brief Unparse a Pool4 object.
    ///
    /// @return A pointer to unparsed Pool4 configuration.
    virtual data::ElementPtr toElement() const;
};

class Pool6;

/// @brief a pointer an IPv6 Pool
typedef boost::shared_ptr<Pool6> Pool6Ptr;

/// @brief Pool information for IPv6 addresses and prefixes
///
/// It holds information about pool6, i.e. a range of IPv6 address space that    ConstCfgOptionPtr getCfgOption() const {
        return (cfg_option_);
    }

    /// @brief Checks whether this pool supports client that belongs to
    /// specified classes.
    ///
    /// @param client_classes list of all classes the client belongs to
    /// @return true if client can be supported, false otherwise
    bool clientSupported(const ClientClasses& client_classes) const;

    /// @brief Adds class clas_name to the allowed client classes list.
    ///
    /// @param class_name client class to be supported by thi std::map<std::string, OptionSpacePtr> OptionSpaceCollection;

/// @brief DHCP option space.
///
/// This class represents single option space. The option spaces are used
/// to group DHCP options having unique option codes. The special type
/// of the option space is so called "vendor specific option space".
/// It groups sub-options being sent within Vendor Encapsulated Options.
/// For DHCPv4 it is the option with code 43. The option spaces are
/// assigned to option instances represented by isc::dhcp::Option and
/// other classnternal
    /// counter so that the dhcp thread pool can be started according to the
    /// new configuration.
    /// If the internal counter is 0, then start the thread pool.
    ///
    /// Invokes all CriticalSection exit callbacks. Has no effect in
    /// single-threaded mode.
    ///
    /// @note This function swallows exceptions thrown by all exit callbacks
    /// without logging to avoid breaking the CS chain.
    void exitCriticalSection();

    /// @brief Is in critical section flag.
    ///
    /// @return The criticfndef OPTION4_ADDRLST_H
#define OPTION4_ADDRLST_H

#include <asiolink/io_address.h>
#include <dhcp/option.h>
#include <util/buffer.h>

#include <boost/shared_array.hpp>
#include <boost/shared_ptr.hpp>

#include <map>
#include <string>
#include <vector>

namespace isc {
namespace dhcp {

/// Forward declaration to Option4AddrLst class.
class Option4AddrLst;

/// A pointer to the Option4AddrLst object.
typedef boost::shared_ptr<Option4AddrLst> Option4AddrLstPtr;

/// @brief DHCPv4 Option class for handling list of IPv4 addresses.
///onfigured to allow multiple hosts with reservations
    /// for the same IPv4 address in the given subnet, this method can return
    /// more than one host.
    ///
    /// The typical use case when a single IPv4 address is reserved for multiple
    /// hosts is when these hosts represent different interfaces of the same
    /// machine and each interface comes with a different MAC address. In that
    /// case, the same IPv4 address is assigned regardless of which interface is
    /// used by the DHCP client to communicate with tparam identifier_len Identifier length.
    /// @param target The host data source being a target of the operation.
    ///
    /// @return Collection of const @c Host objects.
    ConstHostCollection
    getAll(const Host::IdentifierType& identifier_type,
           const uint8_t* identifier_begin,
           const size_t identifier_len,
           const HostMgrOperationTarget target) const;

    /// @brief The @c HostMgr::getAll compatible with @c BaseHostDataSource
    /// interfaces. Operates on all host sources.
    virtual Colays the queries (calls to the appropriate
/// methods declared in the @c BaseHostDataSource) to the data sources it is
/// connected to. The @c HostMgr is always connected to the server's
/// configuration, accessible through the @c CfgHosts object in the @c CfgMgr.
/// The @c CfgHosts object holds all reservations specified in the DHCP server
/// configuration file. If a particular reservation is not found in the
/// @c CfgHosts object, the @c HostMgr will try to find it using alternate
/// host data storages. An alternate host dbnet or null if no subnet found.
    ConstSubnet4Ptr selectSubnet(const asiolink::IOAddress& address,
                                 const ClientClasses& client_classes
                                 = ClientClasses()) const;

    /// @brief Returns a pointer to a subnet if provided interface name matches.
    ///
    /// This method returns a pointer to the subnet if the interface name passed
    /// in parameter iface matches that of a subnet. This is mainly used for matching
    /// local incoming traffic, even when the addr

        } else {
            auto backends = selectBackends(backend_selector);
            if (!backends.empty()) {
                for (auto const& backend : backends) {
                    properties = ((*backend).*MethodPointer)(server_selector);
                    if (!properties.empty()) {
                        break;
                    }
                }

            } else {
                isc_throw(db::NoSuchDatabase, "no such database found for selector: "
                          << backend_selector.toText());
    /// where @c ConfigBackendDHCPv4::getSubnet4 has the following signature:
    ///
    /// @code
    /// Subnet4Ptr getSubnet4(const ServerSelector&, const SubnetID&) const;
    /// @endcode
    ///
    /// If the backend selector is set to "unspecified", this method will iterate
    /// over the existing backends and call the @c MethodPointer method on each
    /// backend. It will return the first non-null (or non-zero) value returned
    /// by this call. For example: if the first backend returns non-null value,
    /// this va have their own loggers without
/// worrying about the program in which they are used, but:
/// - The origin of the message will be clearly identified.
/// - The same component can have different options (e.g. logging severity)
/// in different programs at the same time.
///
/// \section LoggingApiLoggingMessages Logging Messages
/// Instead of embedding the text of messages within the code, each message
/// is referred to using a symbolic name.  The logging code uses this name as
/// a key in a dictionary from which the message teor<StaticRouteTuple> static_routes_;

    /// @brief Length in octets of all encoded static routes.
    uint16_t data_len_;

    /// @brief Flag stating whether the %Option was constructed with a convenient notation string,
    /// that needs custom parsing, or binary data.
    bool convenient_notation_;

    /// @brief Encodes destination descriptor as per RFC3442.
    ///
    /// @param route static route tuple
    ///
    /// @return Contents of the destination descriptor as a vector
    /// of bytes in network-byte order.
    st,
/// respectively, then it would create a new \c RdataPtr object as follows:
/// \code RdataPtr rdata = createRdata(RRType(type_txt), RRClass(class_txt),
///                              nsname_txt); \endcode
/// On success, \c rdata will point to an object of the \c generic::NS class
/// that internally holds a domain name of "ns.example.com."
///
/// Internally, these functions uses the corresponding
/// \c RRParamRegistry::createRdata methods of the \c RRParamRegistry.
/// See also the description on these methods for related  Triplets describing these parameters will be
/// marked "unspecified". If the server finds that the particular parameter
/// is unspecified it will not include it (e.g. option 58 or 59) in the message
/// to a client.
///
/// There are 3 constructors:
/// - without parameters - marks the parameter "unspecified"
/// - simple (just one value that sets all parameters)
/// - extended (that sets default value and two thresholds)
///
/// It will be used with integer types. It provides necessary operators, so
/// it can be assigned to a  \c name.  The name and address must have been
    /// associated by a prior call to \c setNameAddress().  If no address
    /// associated with the given name is found, it returns NULL.
    ///
    /// Some names are reserved for internal use by this class. If such
    /// a name is passed to this method, an \c isc::InvalidParameter
    /// exception will be thrown. See \c validateName() method for details.
    ///
    /// This method should generally be considered exception free, but there
    /// can be a small chance it throws,c size is correct).
    ///
    /// \throw OutOfRange The passed size doesn't match the allocated memory
    /// size (when identifiable for the implementation).
    /// \throw MemorySegmentError Failure of implementation specific
    /// validation.
    ///
    /// \param ptr Pointer to the block of memory to free/release. This
    /// should be equal to a value returned by <code>allocate()</code>.
    /// \param size The size of the memory to be freed in bytes. This
    /// should be equal to the number of bytes originally alloca  bool operator!=(const ConfigDbInfo& other) const {
        return (!equals(other));
    }

private:
    /// @brief Access string of parameters used to access this database.
    std::string access_str_;

    /// @brief Map of the access parameters and their values.
    db::DatabaseConnection::ParameterMap access_params_;
};

typedef std::vector<ConfigDbInfo> ConfigDbInfoList;

/// @brief Embodies configuration information used during a server's
/// configuration process.
///
/// This is class conveys the configuration control infobuffer An output buffer to store the wire data.
    void
    toWire(util::OutputBuffer& buffer) const {
        for (std::vector<std::vector<uint8_t> >::const_iterator it =
                 string_list_.begin();
             it != string_list_.end();
             ++it)
        {
            buffer.writeData(&(*it)[0], (*it).size());
        }
    }

    /// \brief Render the TXT-like data in the wire format to an
    /// AbstractMessageRenderer object.
    ///
    /// \param renderer An output AbstractMessageRenderer to send the wition space name is invalid this method will return 0, which
    /// is not a valid vendor-id, to signal an error.
    ///
    /// @todo remove this function once when the conversion is dealt by the
    /// appropriate functions returning options by option space names.
    ///
    /// @param option_space Option space name.
    /// @return vendor id.
    static uint32_t optionSpaceToVendorId(const std::string& option_space);

    /// @brief Get definition of DHO_DHCP_REQUESTED_ADDRESS option.
    static const OptionDefinition& DHO_DH          std::list<uint16_t>& deferred,
                                 bool flexible_pad_end = false);

    /// Registers factory method that produces options of specific option types.
    ///
    /// @throw isc::BadValue if provided the type is already registered, has
    ///        too large a value or an invalid universe is specified.
    ///
    /// @param u universe of the option (V4 or V6)
    /// @param type option-type
    /// @param factory function pointer
    static void OptionFactoryRegister(Option::Universe u,
     ifndef LOGGER_SPECIFICATION_H
#define LOGGER_SPECIFICATION_H

#include <stdint.h>
#include <stdlib.h>

#include <log/logger_level.h>
#include <log/output_option.h>

/// \brief Logger Specification
///
/// The logging configuration options are a list of logger specifications, each
/// of which represents a logger and the options for its appenders.
///
/// Unlike OutputOption (which is a struct), this contains a bit more
/// structure and is concealed in a class.

#include <vector>

namespace isc {
namespace log {

class LoggerSpecif boost::posix_time::ptime& modification_time,
                          const uint64_t& modification_id) const;

    /// @brief Retrieves all servers from the particular backend.
    ///
    /// This method returns the list of servers excluding the logical server
    /// 'all'.
    ///
    /// @param backend_selector Backend selector.
    /// @return Collection of servers from the backend.
    virtual db::ServerCollection
    getAllServers6(const db::BackendSelector& backend_selector) const;

    /// @brief Retrieves a server from f the synchronization task. This has to be
    /// identical among the various processes that need to be
    /// synchronized for the same task.
    InterprocessSync(const std::string& task_name) :
        task_name_(task_name), is_locked_(false)
    {}

    /// \brief Destructor
    virtual ~InterprocessSync() {}

protected:
    /// \brief Acquire the lock (blocks if something else has acquired a
    /// lock on the same task name)
    ///
    /// \return Returns true if the lock was acquired, false otherwise.
    virtual bool locdelegated prefix.
    ///
    /// Internal thread-unsafe implementation of the @c pickPrefix.
    ///
    /// @param client_classes list of classes client belongs to.
    /// @param pool the selected pool satisfying all required conditions.
    /// @param duid Client's DUID.
    /// @param prefix_length_match type which indicates the selection criteria
    ///        for the pools relative to the provided hint prefix length
    /// @param hint Client's hint.
    /// @param hint_prefix_length the hint prefix length that the client
 currently selected server.
    DnsServerInfoPtr current_server_;

    /// @brief Next server position in the list.
    ///
    /// This value is always the position of the next selection in the server
    /// list, which may be beyond the end of the list.
    size_t next_server_pos_;

    /// @brief Number of transmit attempts for the current request.
    size_t update_attempts_;

    /// @brief Pointer to the configuration manager.
    D2CfgMgrPtr cfg_mgr_;

    /// @brief Pointer to the TSIG key which should be used (if any).
    state model execution when a DNS update completes is done by a
/// call to StateModel::runStateModel() from within the DNSClient callback,
/// with an event value of IO_COMPLETED_EVT (described below).
///
/// This class defines a set of events and states that are a common to all
/// transactions. Each derivation may add define additional states and events
/// as needed, but it must support the common set.  NameChangeTransaction
/// does not supply any state handlers.  These are the sole responsibility of
/// derivations.
class Na to the created \c Rdata
    /// object.
    rdata::RdataPtr createRdata(const RRType& rrtype, const RRClass& rrclass,
                                const std::string& rdata_string);
    /// \brief Create RDATA of a given pair of RR type and class from
    /// wire-format data.
    ///
    /// This method creates from wire-format binary data an \c Rdata object
    /// of the given pair of RR type and class.
    ///
    /// \param rrtype An \c RRType object specifying the type/class pair.
    /// \param rrclass An \c RRClass objectrue if a new mapping is added to the repository; \c false
    /// if the same mapping is already registered.
    bool addType(const std::string& type_string, uint16_t type_code);

    /// \brief Remove mappings between RR type code and textual representation
    /// for a given type.
    ///
    /// This method can safely be called whether or not the specified mappings
    /// exist in the registry.  If not, this method simply ignores the attempt
    /// and returns \c false.
    ///
    /// This method never throws an exception.
t from the CSV file row.
    ///
    /// @param row CSV file row holding lease information.
    data::ConstElementPtr readContext(const util::CSVRow& row);
    //@}
};

} // namespace isc::dhcp
} // namespace isc

#endif // CSV_LEASE_FILE4_H
// File created from src/lib/config/config_messages.mes

#ifndef CONFIG_MESSAGES_H
#define CONFIG_MESSAGES_H

#include <log/message_types.h>

namespace isc {
namespace config {

extern const isc::log::MessageID COMMAND_ACCEPTOR_START;
extern const isc::log::MessageID COMMAND_DEREGISTERED;
extermespace config {

/// @brief HTTP response creator factory for HTTP control socket.
///
/// @param emulate_agent_response if true results for normal command
/// outcomes are wrapped in Element::list.  This emulates responses
/// generated by kea-ctrl-agent.  The value is passed into the
/// HttpCommandResponseCreator when created. Defaults to true.
///
/// See the documentation of the @ref isc::http::HttpResponseCreatorFactory
/// for the details how the response factory object is used by the
/// @ref isc::http::HttpListener.
///
/< 20: Duplicate TKEY name
        BAD_ALG_CODE = 21,  ///< 21: TKEY algorithm not supported
        BAD_TRUNC_CODE = 22 ///< 22: Bad truncation
    };

    /// \name Constructors
    ///
    /// We use the default versions of destructor, copy constructor,
    /// and assignment operator.
    //@{
    /// Constructor from the code value.
    ///
    /// \exception None
    ///
    /// \param error_code The underlying 16-bit error code value of the \c TSIGError.
    explicit TSIGError(uint16_t error_code) : code_(error_code) {}

    // @brief Sets the lease expiration based on the given Element.
    ///
    /// @param element is string Element containing a date-time string.
    ///
    /// @throw NcrMessageError if the element is not a string
    /// Element, or if the element value is an invalid date-time string.
    void setLeaseExpiresOn(isc::data::ConstElementPtr element);

    /// @brief Fetches the request lease length.
    ///
    /// @return an integer containing the lease length
    uint32_t getLeaseLength() const {
        return (lease_length_);
   mple a string
    /// containing "14A3" converts to a byte array containing:  0x14, 0xA3.
    ///
    /// @throw NcrMessageError if the input data contains non-digits
    /// or there is an odd number of digits.
    void fromStr(const std::string& data);

    /// @brief Sets the DHCID value based on the Client Identifier.
    ///
    /// @param clientid_data Holds the raw bytes representing client identifier.
    /// @param wire_fqdn A on-wire canonical representation of the FQDN.
    void fromClientId(const std::vector<uint8_t>& c invoked when client closes the connection to the server.
    ///
    /// It is passed the native socket handler of the connection's TCP socket.
    typedef std::function<void(const int)> CloseHandler;

    /// @brief Constructor.
    ///
    /// @param io_service IO service to be used by the HTTP client.
    /// @param multi_threading_enabled The flag which indicates if MT is enabled.
    /// @param thread_pool_size maximum number of threads in the thread pool.
    /// A value greater than zero enables multi-threaded mode and setsief Convenience function which closes all open sockets.
    /// It stops the receiver thread too.
    void closeSockets() const;

    /// @brief Compares two @c CfgIface objects for equality.
    ///
    /// @param other An object to be compared with this object.
    ///
    /// @return true if objects are equal, false otherwise.
    bool equals(const CfgIface& other) const;

    /// @brief Tries to open sockets on selected interfaces.
    ///
    /// This function opens sockets bound to link-local address as well as
    /// socketIG_PARSER_H

#include <cc/data.h>
#include <cc/simple_parser.h>
#include <dhcpsrv/cfg_iface.h>
#include <dhcpsrv/parsers/dhcp_parsers.h>

namespace isc {
namespace dhcp {

/// @brief Parser for the configuration of interfaces.
///
/// This parser parses the "interfaces-config" parameter which holds the
/// full configuration of the DHCP server with respect to the use of
/// interfaces, DHCP traffic sockets and alike.
///
/// This parser is used in both DHCPv4 and DHCPv6. Derived parsers
/// are not needed.
class IfacesConfigParser    std::pair<bool, uint32_t> getMaxSampleCount() const;

    /// @brief Resets statistic.
    ///
    /// Sets statistic to a neutral (0, 0.0 or "") value and
    /// clears the underlying storage.
    void reset();

    /// @brief Returns statistic type
    /// @return statistic type
    Type getType() const {
        return (type_);
    }

    /// @brief Returns observed integer sample
    /// @return observed sample (value + timestamp)
    /// @throw InvalidStatType if statistic is not integer
    IntegerSample getInteger() consbrary if the hook library is installed and provides
/// command handlers for the control API.
///
/// The command handlers are registered by a hook library by calling
/// @ref isc::hooks::LibraryHandle::registerCommandCallout. This call
/// creates a hook point for this command (if one doesn't exist) and then
/// registers the specified handler(s). When the @ref HookedCommandMgr
/// receives a command for processing it calls the
/// @ref isc::hooks::HooksManager::commandHandlersPresent to check if there
/// are handlers present for/ @brief Factory function creating an instance of @c AuditEntry.
    ///
    /// This function should be used to create an instance of the audit
    /// entry within a hooks library in cases when the library may be
    /// unloaded before the object is destroyed. This ensures that the
    /// ownership of the object by the Kea process is retained.
    ///
    /// @param object_type name of the table where data was modified.
    /// @param object_id identifier of the modified record in this table.
    /// @param modification_type tyk Transactions
    ///
    /// Rolls back all pending database operations.  On databases that don't
    /// support transactions, this is a no-op.
    virtual void rollback() = 0;

    // -- The following are memfile only, but defined in the base LeaseMgr for convenience. --

    /// @brief Returns the class lease count for a given class and lease type.
    ///
    /// @param client_class client class for which the count is desired
    /// @param ltype type of lease for which the count is desired. Defaults to
    /// Lease::TYPE_V4 beginning of the range.
    /// - Last address of the returned range should be used as a starting
    ///   address for the next page in the subsequent call.
    /// - If the number of leases returned is lower than the page size, it
    ///   indicates that the last page has been retrieved.
    /// - If there are no leases returned it indicates that the previous page
    ///   was the last page.
    ///
    /// @param lower_bound_address IPv4 address used as lower bound for the
    /// returned range.
    /// @param page_size maxi found)
    virtual Lease4Ptr getLease4(const ClientId& clientid,
                                SubnetID subnet_id) const = 0;

    /// @brief Returns all IPv4 leases for the particular subnet identifier.
    ///
    /// @param subnet_id subnet identifier.
    ///
    /// @return Lease collection (may be empty if no IPv4 lease found).
    virtual Lease4Collection getLeases4(SubnetID subnet_id) const = 0;

    /// @brief Returns all IPv4 leases for the particular hostname.
    ///
    /// @param hostname hostname in lower case.
  (15);
    return (c);
}

inline const Rcode&
Rcode::BADVERS() {
    static Rcode c(16);
    return (c);
}

/// \brief Insert the \c Rcode as a string into stream.
///
/// This method convert \c rcode into a string and inserts it into the
/// output stream \c os.
///
/// \param os A \c std::ostream object on which the insertion operation is
/// performed.
/// \param rcode A reference to an \c Rcode object output by the operation.
/// \return A reference to the same \c std::ostream object referenced by
/// parameter \c os after the i_string Input string holding formatted time value.
    /// @return Instance of @ref HttpDateTime.
    /// @throw HttpTimeConversionError if provided timestamp has invalid
    /// format.
    static HttpDateTime fromAsctime(const std::string& time_string);

    /// @brief Creates an instance from a string containing time value
    /// formatted in one of the supported formats.
    ///
    /// This method will detect the format of the time value and parse it.
    /// It tries parsing the value in the following order:
    /// - a form by public @ref setValue() and
    /// @ref addValue() methods.
    /// Should be called in a thread safe context.
    ///
    /// @param stat observation
    void addObservationInternal(const ObservationPtr& stat);

    /// @private

    /// @brief Tries to delete an observation.
    ///
    /// Calls @ref deleteObservationInternal() method in a thread safe context.
    ///
    /// @param name of the statistic to be deleted
    /// @return true if deleted, false if not found
    bool deleteObservation(const std::string& name);

  ());
    ///
    /// @param name name of the observation
    /// @param duration determines maximum age of samples
    /// @return true if successful, false if there's no such statistic
    bool setMaxSampleAge(const std::string& name, const StatsDuration& duration);

    /// @brief Determines how many samples of a given statistic should be kept.
    ///
    /// Specifies that statistic name should be stored not as single value, but
    /// rather as a set of values. In this form, at most max_samples will be kept.
    /// When addifer (option will be stored here)
    /// @param check if set to false, allows options larger than 255 for v4
    void pack(isc::util::OutputBuffer& buf, bool check = true) const;

    /// @brief Parses received buffer
    ///
    /// Parses received buffer and returns offset to the first unused byte after
    /// parsed option.
    ///
    /// @param begin iterator to first byte of option data
    /// @param end iterator to end of option data (first byte after option end)
    virtual void unpack(OptionBufferConstIter begin, OptionBon();

    /// @brief Constructor for the outbound HTTP response.
    ///
    /// @param version HTTP version.
    /// @param status_code HTTP status code.
    /// @param generic_body Indicates if the constructor should call
    /// @c setGenericBody to create a generic content for the given
    /// status code. This should be set to "no" when the constructor is
    /// called by the derived class which provides its own implementation
    /// of the @c setGenericBody method.
    explicit HttpResponseJson(const HttpVersion& version,method must not be called when there is no source pushed for
    /// \c MasterLexer.  This method is otherwise exception free.
    ///
    /// \throw isc::InvalidOperation Called with no pushed source.
    void popSource();

    /// \brief Get number of sources inside the lexer.
    ///
    /// This method never throws.
    size_t getSourceCount() const;

    /// \brief Return the name of the current input source name.
    ///
    /// If it's a file, it will be the C string given at the corresponding
    /// \c pushSource() call, t is supposed to pass a placeholder string object.
    /// This will be more efficient if the caller uses the same
    /// \c MasterLexer repeatedly and needs to get string token in the
    /// form of a string object many times as this version could reuse
    /// the existing internal storage of the passed string.
    ///
    /// Any existing content of the passed string will be removed.
    ///
    /// \throw InvalidOperation Called on a non string-variant types of token.
    /// \throw std::bad_alloc Resource allocation failure iof algorithm requires a string, not a
    /// char value. If we held the separator as a char, we would need to
    /// convert it to string on every call to @c CSVRow::parse.
    std::string separator_;

    /// @brief Internal container holding values that belong to the row.
    std::vector<std::string> values_;

    /// @brief Prefix used to escape special characters.
    static const std::string escape_tag;
};

/// @brief Overrides standard output stream operator for @c CSVRow object.
///
/// The resulting string of characters itring& value);

    /// @brief Appends the value as a new column.
    ///
    /// @param value Value to be written.
    /// @tparam T Type of the value being written.
    template<typename T>
    void append(const T value) {
        try {
            values_.push_back(boost::lexical_cast<std::string>(value));
        } catch (const boost::bad_lexical_cast& ex) {
            isc_throw(CSVFileError, "unable to stringify the value to be "
                      "appended to the CSV file row.");
        }
    }

    /// @brief Replaces his parser handles the list of hooks libraries.  This is an optional list,
/// which may be empty, and is encapsulated into a @ref HooksConfig object.
class HooksLibrariesParser : public isc::data::SimpleParser {
public:

    /// @brief Parses parameters value
    ///
    /// Parses configuration entry (list of parameters) and adds each element
    /// to the hooks libraries list.  The method also checks whether the
    /// list of libraries is the same as that already loaded.  If not, it
    /// checks each of the libraries in theype is used
/// to carry control commands in JSON format. The libkea-http library is
/// meant to be generic and provide means for transferring different types
/// of content, depending on the use case.
///
/// This abstract class specifies a common interface for generating HTTP
/// responses from HTTP requests using specific content type and being
/// used in some specific context. Kea modules providing HTTP services need to
/// implement their specific derivations of the @ref HttpResponseCreator
/// class. These derivations use cst;

private:

    /// Specifies if 4o6 is enabled on this subnet.
    bool enabled_;

    /// Specifies the network interface used as v4 subnet selector.
    util::Optional<std::string> iface4o6_;

    /// Specifies the IPv6 subnet used for v4 subnet selection.
    util::Optional<std::pair<asiolink::IOAddress, uint8_t> > subnet4o6_;

    /// Specifies the v6 interface-id used for v4 subnet selection.
    OptionPtr interface_id_;
};

} // end of isc::dhcp namespace
} // end of isc namespace

#endif
// Copyright (C) 2016-2024 InternNameTag>,
            boost::multi_index::member<SubClassRelation,
                                       ClientClass,
                                       &SubClassRelation::class_def_>
        >
    >
> SubClassRelationContainer;

/// @brief Container for storing client class names
///
/// Both a list to iterate on it in insert order and unordered
/// set of names for existence.
class ClientClasses : public isc::data::CfgToElement {
public:

    /// @brief Type of iterators
    typedef ClientClassContainer::const_iterator const// encapsulates numeric values, but additional specializations are defined
/// as necessary to support other types od data.
///
/// This class includes a boolean flag which indicates if the encapsulated
/// value is specified or unspecified. For example, a configuration parser
/// for the DHCP server may use this class to represent a value of the
/// configuration parameter which may appear in the configuration file, but
/// is not mandatory. The value of the @c Optional may be initialized to
/// "unspecified" initially. When the c of global options or empty collection if no
    /// option found.
    virtual OptionContainer
    getModifiedOptions4(const db::BackendSelector& backend_selector,
                        const db::ServerSelector& server_selector,
                        const boost::posix_time::ptime& modification_time) const;

    /// @brief Retrieves global parameter value.
    ///
    /// @param backend_selector Backend selector.
    /// @param server_selector Server selector.
    /// @param name Name of the global parameter to be retrieved.
   and stored in
/// the appropriate members of the pkt object.
///
/// @warning This function does not check that the provided 'pkt'
/// pointer is valid. Caller must make sure that pointer is
/// allocated.
///
/// @param buf input buffer holding headers to be parsed.
/// @param [out] pkt packet object where IP addresses and ports
/// are stored.
///
/// @throw InvalidPacketHeader if packet header is truncated
/// @throw BadValue if pkt object is NULL.
void decodeIpUdpHeader(util::InputBuffer& buf, Pkt4Ptr& pkt);

/// @brief Writes//
    /// @param mode enum value to convert to label
    ///
    /// @return std:string containing the text label if the value is valid, or
    /// "unknown" if not.
    static std::string replaceClientNameModeToString(const ReplaceClientNameMode& mode);

    /// @brief Unparse a configuration object
    ///
    /// @return a pointer to unparsed configuration
    virtual isc::data::ElementPtr toElement() const;

    /// @brief Validates member values.
    ///
    /// Method is used by the constructor to validate member contents.
 c D2UpdateMessage class API prevents invalid
    /// use of the class. The typical case, when this function may throw an
    /// exception is when this it is called on the object representing
    /// incoming (instead of outgoing) message. In such case, the QR field
    /// will be set to RESPONSE, which is invalid setting when calling this
    /// function.
    ///
    /// @param renderer A renderer object used to generate the message wire
    /// format.
    /// @param tsig_ctx A TSIG context that is to be used for signing the
  st ServerTag& other) const {
        return (tag_ < other.tag_);
    }

private:

    /// @brief Holds server tag as string.
    std::string tag_;
};

/// @brief Insert the @c ServerTag as a string into stream.
///
/// @param os stream to insert server tag into.
/// @param server_tag server tag to be converted to text and
/// inserted into a stream.
/// @return Reference to the stream object with inserted server
/// tag.
std::ostream&
operator<<(std::ostream& os, const ServerTag& server_tag);

} // end of namespace isc::data
} // eween servers.
///

#include <exceptions/exceptions.h>
#include <dhcp/pkt6.h>
#include <boost/noncopyable.hpp>
#include <stdint.h>

namespace isc {
namespace dhcp {

/// @brief Exception thrown when error occurs as a result of use of IPC.
class Dhcp4o6IpcError : public Exception {
public:
    Dhcp4o6IpcError(const char* file, size_t line, const char* what) :
        isc::Exception(file, line, what) { }
};

/// @brief This class implements the communication between the DHCPv4
/// and DHCPv6 servers to allow for transmission of the DH /// Internal state of context
    ///
    /// The constants of this enum type define a specific state of
    /// \c TSIGContext to adjust the behavior.  The definition is public
    /// and the state can be seen via the \c getState() method, but this is
    /// mostly private information.  It's publicly visible mainly for testing
    /// purposes; there is no API for the application to change the state
    /// directly.
    enum State {
        INIT,                   ///< Initial state
        SENT_REQUEST,           ///< Client ternal
/// program bug.
class TSIGContextError : public isc::Exception {
public:
    TSIGContextError(const char* file, size_t line, const char* what) :
        isc::Exception(file, line, what) {}
};

/// TSIG session context.
///
/// The \c TSIGContext class maintains a context of a signed session of
/// DNS transactions by TSIG.  In many cases a TSIG signed session consists
/// of a single set of request (e.g. normal query) and reply (e.g. normal
/// response), where the request is initially signed by the client, and the
/// repl-data.
    // The format defined here includes 32-bit field holding enterprise number.
    // This allows for specifying option-data information where the enterprise-id
    // is represented by a uint32_t value. Previously we represented this option
    // as a binary, but that would imply that enterprise number would have to be
    // represented in binary format in the server configuration. That would be
    // inconvenient and non-intuitive.
    /// @todo We need to extend support for vendor options with ability to specify
    /

// RFC5969 DHCPv6 6RD option.
//
// two 8 bit lengthes, an IPv6 address and one or more IPv4 addresses
RECORD_DECL(OPT_6RD_RECORDS, OPT_UINT8_TYPE, OPT_UINT8_TYPE,
            OPT_IPV6_ADDRESS_TYPE, OPT_IPV4_ADDRESS_TYPE);

/// @brief Definitions of standard DHCPv4 options.
const OptionDefParams STANDARD_V4_OPTION_DEFINITIONS[] = {
    { "subnet-mask", DHO_SUBNET_MASK, DHCP4_OPTION_SPACE,
      OPT_IPV4_ADDRESS_TYPE, false, NO_RECORD_DEF, "" },
    { "time-offset", DHO_TIME_OFFSET, DHCP4_OPTION_SPACE, OPT_INT32_TYPE,
      false,DPCallback* recv_callback);

private:

    /// @brief The IO service used to handle events.
    isc::asiolink::IOServicePtr io_service_;

    /// @brief IP address on which to listen for requests.
    isc::asiolink::IOAddress ip_address_;

    /// @brief Port number on which to listen for requests.
    uint32_t port_;

    /// @brief Wire format of the inbound requests.
    NameChangeFormat format_;

    /// @brief Low level socket underneath the listening socket
    boost::shared_ptr<boost::asio::ip::udp::socket> asio_socket_;

  rom the
        /// buffer.
        size_t bytes_transferred_;

    };

    /// @brief Used as the callback object for UDPSocket services.
    ///
    /// @param buffer is a pointer to the data transfer buffer. This is
    /// the buffer data will be written to on a read, or read from on a
    /// send.
    /// @param buf_size is the capacity of the buffer
    /// @param data_source storage for UDP endpoint which supplied the data
    /// @param handler is a method pointer to the completion handler that
    /// is to be called by t// into the buffer in order to decide where to put the data.  It is up to the
// caller to initialize the data to zero
template <typename C> void
TLSSocket<C>::asyncReceive(void* data, size_t length, size_t offset,
                           IOEndpoint* endpoint, C& callback) {
    if (!socket_.is_open()) {
        isc_throw(SocketNotOpen,
                  "attempt to receive from a TLS socket that is not open");
    }

    // Upconvert to a TCPEndpoint.  We need to do this because although
    // IOEndpoint is the base class of Uopen and the peer has not
    /// closed its connection.
    ///
    /// @return true if the connection is usable.
    bool isUsable() const {
        // If the socket is open it doesn't mean that it is still
        // usable. The connection could have been closed on the other
        // end. We have to check if we can still use this socket.
        if (socket_.is_open()) {
            // Remember the current non blocking setting.
            const bool non_blocking_orig = socket_.non_blocking();

            // Set the socket to  lease file in the
    /// CSV format, creates @c Lease4 or @c Lease6 objects and inserts
    /// them into the storage to which reference is specified as an
    /// argument. If there are multiple entries for the particular lease
    /// in the lease file the entries further in the lease file override
    /// the previous entries.
    ///
    /// If the method finds the entry with the valid lifetime of 0 it
    /// means that the particular lease was released and the method
    /// removes an existing lease from the container.
    normal operations
///
/// An example of the normal operation is a report of a packet being received
/// from the fuzzer.
extern const int FUZZ_DBG_TRACE;

/// @brief Record detailed traces
///
/// Messages logged at this level will log detailed tracing information.
extern const int FUZZ_DBG_TRACE_DETAIL;

///@}

/// @brief Logger for the @c HostMgr and the code it calls.
///
/// Define the logger used to log messages in @c HostMgr and the code it
/// calls to manage host reservations.
extern isc::log::Logger fuzz_logger;

} // namcted label
    /// character including compression pointer, an exception of class
    /// \c BadLabelType will be thrown.  In addition, if resource
    /// allocation for the result string fails, a corresponding standard
    /// exception will be thrown.
    ///
    /// \return a string representation of the <code>LabelSequence</code>.
    std::string toText() const;

    /// \brief Convert the LabelSequence to a string without escape sequences.
    ///
    /// The string returned will contain a single character value for any
    /brief Assignment operator.
    ///
    /// \note The associated data MUST remain in scope during the lifetime
    /// of this LabelSequence, since only the pointers are copied.
    ///
    /// \note No validation is done on the given data upon construction;
    ///       use with care.
    ///
    /// \param other The LabelSequence to assign a LabelSequence from
    LabelSequence& operator=(const LabelSequence& other) {
        if (this != &other) {
            // Not self-assignment.
            data_ = other.data_;
            of and returns 0; otherwise it returns 1, which is the number of RR
    /// rendered.
    ///
    /// In the current implementation the return value is either 0 or 1, but
    /// the return type is <code>unsigned int</code> to be consistent with
    /// \c RRset::toWire().  In any case the caller shouldn't assume these are
    /// only possible return values from this method.
    ///
    /// This method is mostly exception free, but it requires memory
    /// allocation and if it fails a corresponding standard exception will be
    / logically more belongs to CPL process file. Once
    /// Daemon is merged with CPL architecture, it will be a better
    /// fit.
    ///
    /// If cfg is not specified, the current config (as returned by
    /// CfgMgr::instance().getCurrentCfg() will be returned.
    ///
    /// @param config_file name of the file to write the configuration to
    /// @param cfg configuration to write (optional)
    /// @return number of files written
    /// @throw Unexpected if CfgMgr can't retrieve configuration or file cannot
    ///        to be parsed.
    /// @param encapsulate_options a boolean parameter indicating if the
    /// parsed options should be encapsulated with suboptions.
    ///
    /// @return Pointer to an object representing shared network.
    /// @throw DhcpConfigError when shared network configuration is invalid.
    SharedNetwork4Ptr
    parse(const data::ConstElementPtr& shared_network_data,
          bool encapsulate_options = true);

protected:

    /// @brief Returns an instance of the @c OptionDataListParser to
    /// be used in parsing cation times of the configuration objects.
/// This is specifically required by the Kea Configuration Backend
/// feature which stores and fetches configuration from the database.
/// The configuration elements must be accessible by their database
/// identifiers and modification times.
///
/// @note This class is not derived from @c Element and should not
/// be confused with the classes being derived from @c Element class.
/// Those classes are used to represent JSON structures, whereas this
/// class represents data fetched from prefix
    /// delegation pool to which the option belongs.
    /// @param pd_pool_prefix_length Prefix length of the prefix delegation
    /// pool to which the option belongs.
    /// @param option Option to be added or updated.
    virtual void
    createUpdateOption6(const db::ServerSelector& server_selector,
                        const asiolink::IOAddress& pd_pool_prefix,
                        const uint8_t pd_pool_prefix_length,
                        const OptionDescriptorPtr& option) = 0;

    /// @brief Creates or uplude <boost/shared_ptr.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
#include <string>

namespace isc {
namespace dhcp {

/// @brief Interface implemented by DHCPv6 configuration backends.
///
/// All POSIX times specified in the methods belonging to this
/// class must be local times.
///
/// Below, we describe the general rules of using the server selectors
/// when creating, updating, fetching and deleting the configuration
/// elements from the backends. The detailed information can be found
/// in the descriptions of theued for transmission.
    ///
    /// Note that the entry is not removed from the queue.
    /// @param index the index of the entry in the queue to fetch.
    /// Valid values are 0 (front of the queue) to (queue size - 1).
    /// @note This method is for test purposes only.
    ///
    /// @return Pointer reference to the queue entry.
    ///
    /// @throw D2ClientError if sender instance is null. Underlying layer
    /// may throw NCRSenderExceptions exceptions.
    const dhcp_ddns::NameChangeRequestPtr& peekAt(const size_t ir : public dhcp_ddns::NameChangeSender::RequestSendHandler,
                    boost::noncopyable {
public:
    /// @brief Constructor
    ///
    /// Default constructor which constructs an instance which has DHCP-DDNS
    /// updates disabled.
    D2ClientMgr();

    /// @brief Destructor.
    ~D2ClientMgr();

    /// @brief Updates the DHCP-DDNS client configuration to the given value.
    ///
    /// @param new_config pointer to the new client configuration.
    /// @throw D2ClientError if passed an empty pointer.
    void set_selector Server selector.
    /// @param code Code of the option to be deleted.
    /// @param space Option space of the option to be deleted.
    /// @return Number of deleted option definitions.
    virtual uint64_t
    deleteOptionDef4(const db::ServerSelector& server_selector,
                     const uint16_t code,
                     const std::string& space) = 0;

    /// @brief Deletes all option definitions.
    ///
    /// Allowed server selectors: ALL, ONE.
    /// Not allowed server selectors: ANY, UNASSIGNED, MULTINY.
    /// Not allowed server selectors: UNASSIGNED, ALL, ONE, MULTIPLE.
    ///
    /// @param server_selector Server selector.
    /// @param shared_network_name Name of the shared network for which the
    /// retrieved subnets should belongs to.
    /// @return Collection of subnets or empty collection if no subnet found.
    virtual Subnet4Collection
    getSharedNetworkSubnets4(const db::ServerSelector& server_selector,
                             const std::string& shared_network_name) const = 0;

    /// @brief Retrieves \brief The default maximum size of UDP DNS messages we can handle
    static const uint16_t DEFAULT_MAX_EDNS0_UDPSIZE = 4096;
    //@}

private:
    MessageImplPtr impl_;
};

/// \brief Pointer-like type pointing to a \c Message
///
/// This type is expected to be used as an argument in asynchronous
/// callback functions.  The internal reference-counting will ensure that
/// that ongoing state information will not be lost if the object
/// that originated the asynchronous call falls out of scope.
typedef boost::shared_ptr<Message>/ This method is basically exception free, but if
    /// \c flag is not a valid constant of the \c HeaderFlag type,
    /// an exception of class \c InvalidParameter will be thrown.
    ///
    /// \param flag The header flag constant to test.
    /// \return \c true if the specified flag is set; otherwise \c false.
    bool getHeaderFlag(const HeaderFlag flag) const;

    /// \brief Set or clear the specified header flag bit in the header
    /// section.
    ///
    /// The optional parameter \c on indicates the operation mode,
 <util/buffer.h>

#include <dns/edns.h>
#include <dns/question.h>
#include <dns/rrset.h>

namespace isc {
namespace dns {
class TSIGContext;
class TSIGRecord;

///
/// \brief A standard DNS module exception that is thrown if a wire format
/// message parser encounters a short length of data that don't even contain
/// the full header section.
///
class MessageTooShort : public isc::dns::Exception {
public:
    MessageTooShort(const char* file, size_t line, const char* what) :
        isc::dns::Exception(file, line, what) {}
};

///t() {
        LeaseMgrFactory::deregisterFactory("memfile", true);
    }
};

}  // namespace dhcp
}  // namespace isc

#endif // MEMFILE_LEASE_MGR_H
// Copyright (C) 2017-2025 Internet Systems Consortium, Inc. ("ISC")
//
// 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/.

#ifndef HTTP_CONNECTION_H
#define HTTP_CONNECTION_H

#include <asiolink/interval_timer.h>
#include <asiolink/io_se has been successfully moved, it runs
    /// the @c kea-lfc application.
    ///
    /// @param lease_file A pointer to the object representing the Current
    /// %Lease File (DHCPv4 or DHCPv6 lease file).
    ///
    /// @tparam LeaseFileType One of @c CSVLeaseFile4 or @c CSVLeaseFile6.
    template<typename LeaseFileType>
    void lfcExecute(boost::shared_ptr<LeaseFileType>& lease_file);

    /// @brief A pointer to the Lease File Cleanup configuration.
    boost::scoped_ptr<LFCSetup> lfc_setup_;

    /// @brief Parameters stot contains the value of the limit if found
    ///
    /// @return bool true if a limit for the lease type was found, false otherwise.
    bool getLeaseLimit(data::ConstElementPtr parent, Lease::Type ltype, size_t& limit) const;

public:

    /// @brief Return backend type
    ///
    /// Returns the type of the backend.
    ///
    /// @return Type of the backend.
    virtual std::string getType() const override {
        return (std::string("memfile"));
    }

    /// @brief Returns backend name.
    ///
    /// For now, memfile  specified IPv6 leases.
    ///
    /// This rather dangerous method is able to remove all leases from specified
    /// subnet.
    ///
    /// @param subnet_id identifier of the subnet
    ///
    /// @return number of leases removed.
    virtual size_t wipeLeases6(const SubnetID& subnet_id) override;

    /// @brief Checks if the IPv4 lease limits set in the given user context are exceeded.
    /// Memfile implementation.
    ///
    /// @param user_context all or part of the lease's user context which, for the intents and
    / IPv6 address.
    ///
    /// This function returns a copy of the lease. The modification in the
    /// return lease does not affect the instance held in the lease storage.
    ///
    /// @param type specifies lease type: (NA, TA or PD)
    /// @param addr An address of the searched lease.
    ///
    /// @return a pointer to the lease (or NULL if a lease is not found)
    virtual Lease6Ptr getLease6(Lease::Type type,
                                const isc::asiolink::IOAddress& addr) const override;

    /// @brief Returns exss_;
    /// @brief Source address of the message.
    asiolink::IOAddress remote_address_;
    /// @brief Classes that the client belongs to.
    ClientClasses client_classes_;
    /// @brief Name of the interface on which the message was received.
    std::string iface_name_;

    /// @brief Specifies if the packet is DHCP4o6
    bool dhcp4o6_;

    /// @brief Default constru