// Copyright (C) 2012, 2014 Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

/**
 @page libdhcpsrv libdhcpsrv - Server DHCP library

This library contains code useful for DHCPv4 and DHCPv6 server operations, like
Lease Manager that stores leases information, configuration manager that stores
configuration etc. The code here is server specific. For generic (useful in
server, client, relay and other tools like perfdhcp) code, please see
\ref libdhcp.

This library contains several crucial elements of the DHCP server operation:

- isc::dhcp::LeaseMgr - Lease Manager is a name for database backend that stores
  leases.
- isc::dhcp::CfgMgr - Configuration Manager that holds DHCP specific
  configuration information (subnets, pools, options, timer values etc.) in
  easy to use format.
- AllocEngine - allocation engine that handles new requestes and allocates new
  leases.

@section leasemgr Lease Manager

LeaseMgr provides a common, unified abstract API for all database backends. All
backends are derived from the base class isc::dhcp::LeaseMgr. Currently the
only available backend is MySQL (see \ref isc::dhcp::MySqlLeaseMgr).

@section cfgmgr Configuration Manager

Configuration Manager (\ref isc::dhcp::CfgMgr) is a singleton object which
holds configuration information necessary for the operation of Kea daemons.
A complete collection of information for the daemon is stored in the
\ref isc::dhcp::SrvConfig object. Internally, the Configuration Manager
holds a list of \ref isc::dhcp::SrvConfig objects, from which one
is marked as "current configuration".

When the server starts up or is being reconfigured a new
\ref isc::dhcp::SrvConfig object, referred to as "staging configuration",
is created. The staging configuration is held at the tip of the list of
configurations. The object can be accessed by calling the
\ref isc::dhcp::CfgMgr::getStagingCfg. This object can be accessed
from different stages of the configuration parsing and modified as needed.
Modifications of the staging configuration do not affect the current
configuration. The staging configuration is unused until the
\ref isc::dhcp::CfgMgr::commit function is called. This exception safe method
marks the staging object as "current configuration". The const pointer to the
current configuration can be accessed by calling a
\ref isc::dhcp::CfgMgr::getCurrentCfg.

The staging configuration can be discarded at any time before it is committed
by calling the \ref isc::dhcp::CfgMgr::rollback. This removes the
\ref isc::dhcp::SrvConfig object from the Configuration Manager. When
the \ref isc::dhcp::CfgMgr::getStagingCfg is called again a fresh/default
\ref isc::dhcp::SrvConfig object is returned.

The Configuration Manager stores previous configurations, i.e. configurations
which occurred prior to the most current configuration. This is currently
unused (except for unit tests) by the deamons, but in the future this
mechanism can be used to trigger a rollover of the server configuration
to a last good configuration that the administrator prefers.

The previous configurations are identified by the value which specifies a
distance between the current configuration and the previous
configuration. For example: the value of 1 identifies an immediate
predecessor of the current configuration, the value of 2 identifies the
one that occurred before it etc.

@todo Currently, only a subset of configuration information is stored in
the \ref isc::dhcp::SrvConfig object. Kea developers are actively working
on migrating the other configuration parameters to it.

@section hostmgr Host Manager

Host Manager implemented by the \ref isc::dhcp::HostMgr is a singleton object
which provides means to retrieve resources statically assigned to the DHCP
clients, such as IP addresses, prefixes or hostnames. The statically assigned
resources are called reservations (or host reservations) and they are
represented in the code by the \ref isc::dhcp::Host class.

The reservations can be specified in the configuration file or in some
other storage (typically in a database). A dedicated object, called
host data source, is needed to retrieve the host reservations from the
database. This object must implement the \ref isc::dhcp::BaseHostDataSource
interface and its implementation is specific to the type of storage
holding the reservations. For example, the host data source managing
host reservations in the MySQL database is required to establish
connection to the MySQL databse and issue specific queries. Once
implemented, the \ref isc::dhcp::HostMgr::create method must be updated
to create an instance of this datasource. Note, that this instance is
created as "alternate host data source" as opposed to the primary data
source which returns host reservations specified in the configuration file.
The primary data source is implemented internally in the
\ref isc::dhcp::HostMgr and uses the configuration data structures held by
the \ref isc::dhcp::CfgMgr to retrieve the reservations. In general, the
\ref isc::dhcp::HostMgr first searches for the reservations using the
primary data source and falls back to the use of alternate data source
when nothing has been found. For those methods which are meant to return
multiple reservations (e.g. find all reservations for the particular
client), the \ref isc::dhcp::HostMgr will use both primary and alternate
data source (if present) and concatenate results.

For more information about the \ref isc::dhcp::HostMgr please refer to its
documentation.

@section optionsConfig Options Configuration Information

The \ref isc::dhcp::CfgOption object holds a collection of options being
sent to the client. Since each subnet comes with a distnict set of
options, every \ref isc::dhcp::Subnet object holds its own copy of the
\ref isc::dhcp::CfgOption object with specific options.

The DHCP server also allows for configuration of "global" options
which are shared by all subnets. The rule here is that if a particular
option appears in the global options set and the subnet specific options
set, the subnet specific option takes precedence. The global options
configuration is held in the dedicated instance of the
\ref isc::dhcp::CfgOption class. This instance is owned by the
\ref isc::dhcp::SrvConfig class.

When the new configuration is parsed, the global options are merged into
the \ref isc::dhcp::CfgOption instances for all subnets. This is
causing some overhead during the reconfiguration of the server but on
the other hand it avoids the lookup of options in two places (among
subnet specific options and global options) during each packet
processing.

One of the benefits of keeping a separate set of global options is
that there may be cases when the server administrator doesn't specify
any subnet configuration and only wants global options to be used.
This is the case, when the DHCP server is used for stateless
configuration, i.e. client's are not allocated an address or prefix,
and only stateless configruation is handed out.

@section allocengine Allocation Engine

Allocation Engine (\ref isc::dhcp::AllocEngine) is what its name say - an engine
that handles allocation of new leases. It takes parameters that the client
provided (client-id, DUID, subnet, a hint if the user provided one, etc.) and
then attempts to allocate a lease.

There is no single best solution to the address assignment problem. Server
is expected to pick an address from its available pools is currently not used.
There are many possible algorithms that can do that, each with its own advantages
and drawbacks. This allocation engine must provide robust operation is radically
different scenarios, so there address selection problem was abstracted into
separate module, called allocator. Its sole purpose is to pick an address from
a pool. Allocation engine will then check if the picked address is free and if
it is not, then will ask allocator to pick again.

At least 3 allocators will be implemented:

- Iterative - it iterates over all resources (addresses or prefixes) in
available pools, one by one. The advantages of this approach are: speed
(typically it only needs to increase address just one), the guarantee to cover
all addresses and predictability.  This allocator behaves reasonably good in
case of nearing depletion. Even when pools are almost completely allocated, it
still will be able to allocate outstanding leases efficiently. Predictability
can also be considered a serious flaw in some environments, as prediction of the
next address is trivial and can be leveraged by an attacker. Another drawback of
this allocator is that it does not attempt to give the same address to returning
clients (clients that released or expired their leases and are requesting a new
lease will likely to get a different lease). This allocator is not suitable for
temporary addresses, which must be randomized. This allocator is implemented
in \ref isc::dhcp::AllocEngine::IterativeAllocator.

- Hashed - ISC-DHCP uses hash of the client-id or DUID to determine, which
address is tried first. If that address is not available, the result is hashed
again. That procedure is repeated until available address is found or there
are no more addresses left. The benefit of that approach is that it provides
a relative lease stability, so returning old clients are likely to get the same
address again. The drawbacks are increased computation cost, as each iteration
requires use of a hashing function. That is especially difficult when the
pools are almost depleted. It also may be difficult to guarantee that the
repeated hashing will iterate over all available addresses in all pools. Flawed
hash algorithm can go into cycles that iterate over only part of the addresses.
It is difficult to detect such issues as only some initial seed (client-id
or DUID) values may trigger short cycles. This allocator is currently not
implemented. This will be the only allocator allowed for temporary addresses.

- Random - Another possible approach to address selection is randomization. This
allocator can pick an address randomly from the configured pool. The benefit
of this approach is that it is easy to implement and makes attacks based on
address prediction more difficult. The drawback of this approach is that
returning clients are almost guaranteed to get a different address. Another
drawback is that with almost depleted pools it is increasingly difficult to
"guess" an address that is free. This allocator is currently not implemented.

@subsection allocEngineTypes Different lease types support

Allocation Engine has been extended to support different types of leases. Four
types are supported: TYPE_V4 (IPv4 addresses), TYPE_NA (normal IPv6 addresses),
TYPE_TA (temporary IPv6 addresses) and TYPE_PD (delegated prefixes). Support for
TYPE_TA is partial. Some routines are able to handle it, while other are
not. The major missing piece is the RandomAllocator, so there is no way to randomly
generate an address. This defeats the purpose of using temporary addresses for now.

@subsection allocEnginePD Prefix Delegation support in AllocEngine

The Allocation Engine supports allocation of the IPv6 addresses and prefixes.
For a prefix pool, the iterative allocator "walks over"
every available pool. It is similar to how it iterates over address pool,
but instead of increasing address by just one, it walks over the whole delegated
prefix length in one step. This is implemented in
isc::dhcp::AllocEngine::IterativeAllocator::increasePrefix(). Functionally the
increaseAddress(addr) call is equivalent to increasePrefix(addr, 128)
(increasing by a /128 prefix, i.e. a single address).  However, both methods are
kept, because increaseAddress() is faster and this is a routine that may be
called many hundred thousands times per second.

@subsection allocEngineDHCPv4HostReservation Host Reservation support

The Allocation Engine supports allocation of statically assigned addresses
to the DHCPv4 clients, a.k.a. Host Reservation.

When the server receives a DHCPDISCOVER or DHCPREQUEST from the client it
calls \ref isc::dhcp::AllocEngine::allocateLease4 to obtain the suitable lease
for the client. If the Allocation Engine determines that the particular client
has a reservation it will try to allocate a reserved address for it. If the
client requested allocation or renewal of a different address, the Allocation
Engine will respond with a NULL lease to indicate that the address
desired by the client could not be assigned. The DHCP server should send
a DHCPNAK to the client and the client should fall back to the DHCP
server discovery. When the client sends DHCPDISCOVER, the Allocation
Engine offers the reserved address and the client should request the
offered address in subsequent DHCPREQUEST messages.

There are cases when the Allocation Engine is unable to assign the
reserved address for the client. This includes the situations when
the address had been previously reserved for another client or the
address had been assigned out of the dynamic address pool. Such address
may still remain in use of the client which obtained it first and the
Allocation Engine must not assign it to the client for which it is
reserved until the client using this address releases or the server
assigns a different address for it.

In order to resolve this conflict the Allocation Engine will refuse to
renew the lease for the client using the addres not reserved for it.
This client should fall back to the 4-way exchange and the Allocation
Engine will assign a different address. As a result, the reserved
address will be freed for the use of the client for which the reservation
was made. The client will be offered/allocated a reserved address
the next time it retries sending a DHCPDISCOVER/DHCPREQUEST message to
the server.

*/
