dhcp4_srv.cc 41.2 KB
Newer Older
1
// Copyright (C) 2011-2013 Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

15
#include <asiolink/io_address.h>
16
#include <dhcp/dhcp4.h>
17
#include <dhcp/iface_mgr.h>
18
#include <dhcp/option4_addrlst.h>
19
#include <dhcp/option_int.h>
20
#include <dhcp/option_int_array.h>
21
#include <dhcp/pkt4.h>
22 23
#include <dhcp/duid.h>
#include <dhcp/hwaddr.h>
24 25
#include <dhcp4/dhcp4_log.h>
#include <dhcp4/dhcp4_srv.h>
26 27 28 29 30 31 32
#include <dhcpsrv/utils.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/lease_mgr.h>
#include <dhcpsrv/lease_mgr_factory.h>
#include <dhcpsrv/subnet.h>
#include <dhcpsrv/utils.h>
#include <dhcpsrv/addr_utilities.h>
33 34
#include <hooks/hooks_manager.h>
#include <hooks/callout_handle.h>
35

36 37 38 39 40
#include <boost/algorithm/string/erase.hpp>

#include <iomanip>
#include <fstream>

41 42
using namespace isc;
using namespace isc::asiolink;
43
using namespace isc::dhcp;
44
using namespace isc::hooks;
45 46
using namespace isc::log;
using namespace std;
47

48
/// Structure that holds registered hook indexes
49 50
struct Dhcp4Hooks {
    int hook_index_buffer4_receive_;///< index for "buffer4_receive" hook point
51 52
    int hook_index_pkt4_receive_;   ///< index for "pkt4_receive" hook point
    int hook_index_subnet4_select_; ///< index for "subnet4_select" hook point
53
    int hook_index_lease4_release_; ///< index for "lease4_release" hook point
54
    int hook_index_pkt4_send_;      ///< index for "pkt4_send" hook point
55
    int hook_index_buffer4_send_;   ///< index for "buffer4_send" hook point
56

57 58 59
    /// Constructor that registers hook points for DHCPv4 engine
    Dhcp4Hooks() {
        hook_index_buffer4_receive_= HooksManager::registerHook("buffer4_receive");
60 61 62
        hook_index_pkt4_receive_   = HooksManager::registerHook("pkt4_receive");
        hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
        hook_index_pkt4_send_      = HooksManager::registerHook("pkt4_send");
63 64
        hook_index_lease4_release_ = HooksManager::registerHook("lease4_release");
        hook_index_buffer4_send_   = HooksManager::registerHook("buffer4_send");
65 66 67 68 69 70 71
    }
};

// Declare a Hooks object. As this is outside any function or method, it
// will be instantiated (and the constructor run) when the module is loaded.
// As a result, the hook indexes will be defined before any method in this
// module is called.
72
Dhcp4Hooks Hooks;
73

74 75 76 77 78 79 80 81 82 83 84 85
namespace isc {
namespace dhcp {

/// @brief file name of a server-id file
///
/// Server must store its server identifier in persistent storage that must not
/// change between restarts. This is name of the file that is created in dataDir
/// (see isc::dhcp::CfgMgr::getDataDir()). It is a text file that uses
/// regular IPv4 address, e.g. 192.0.2.1. Server will create it during
/// first run and then use it afterwards.
static const char* SERVER_ID_FILE = "b10-dhcp4-serverid";

86 87 88
// These are hardcoded parameters. Currently this is a skeleton server that only
// grants those options and a single, fixed, hardcoded lease.

89
Dhcpv4Srv::Dhcpv4Srv(uint16_t port, const char* dbconfig, const bool use_bcast,
90
                     const bool direct_response_desired)
91 92
: serverid_(), shutdown_(true), alloc_engine_(), port_(port),
    use_bcast_(use_bcast), hook_index_pkt4_receive_(-1),
93 94
    hook_index_subnet4_select_(-1), hook_index_pkt4_send_(-1) {

95
    LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_OPEN_SOCKET).arg(port);
96
    try {
97
        // First call to instance() will create IfaceMgr (it's a singleton)
98
        // it may throw something if things go wrong.
99
        // The 'true' value of the call to setMatchingPacketFilter imposes
100 101 102 103
        // that IfaceMgr will try to use the mechanism to respond directly
        // to the client which doesn't have address assigned. This capability
        // may be lacking on some OSes, so there is no guarantee that server
        // will be able to respond directly.
104
        IfaceMgr::instance().setMatchingPacketFilter(direct_response_desired);
105

106 107 108
        if (port) {
            // open sockets only if port is non-zero. Port 0 is used
            // for non-socket related testing.
109
            IfaceMgr::instance().openSockets4(port_, use_bcast_);
110
        }
111

112 113 114
        string srvid_file = CfgMgr::instance().getDataDir() + "/" + string(SERVER_ID_FILE);
        if (loadServerID(srvid_file)) {
            LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_SERVERID_LOADED)
115
                .arg(srvidToString(getServerID()))
116 117 118 119 120 121 122 123 124 125 126 127 128
                .arg(srvid_file);
        } else {
            generateServerID();
            LOG_INFO(dhcp4_logger, DHCP4_SERVERID_GENERATED)
                .arg(srvidToString(getServerID()))
                .arg(srvid_file);

            if (!writeServerID(srvid_file)) {
                LOG_WARN(dhcp4_logger, DHCP4_SERVERID_WRITE_FAIL)
                    .arg(srvid_file);
            }

        }
129

130 131 132 133 134 135 136 137 138
        // Instantiate LeaseMgr
        LeaseMgrFactory::create(dbconfig);
        LOG_INFO(dhcp4_logger, DHCP4_DB_BACKEND_STARTED)
            .arg(LeaseMgrFactory::instance().getType())
            .arg(LeaseMgrFactory::instance().getName());

        // Instantiate allocation engine
        alloc_engine_.reset(new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));

139 140 141 142 143 144 145
        // Register hook points
        hook_index_pkt4_receive_   = Hooks.hook_index_pkt4_receive_;
        hook_index_subnet4_select_ = Hooks.hook_index_subnet4_select_;
        hook_index_pkt4_send_      = Hooks.hook_index_pkt4_send_;

        /// @todo call loadLibraries() when handling configuration changes

146
    } catch (const std::exception &e) {
147
        LOG_ERROR(dhcp4_logger, DHCP4_SRV_CONSTRUCT_ERROR).arg(e.what());
148 149 150
        shutdown_ = true;
        return;
    }
151

Tomek Mrugalski's avatar
Tomek Mrugalski committed
152
    shutdown_ = false;
153 154 155
}

Dhcpv4Srv::~Dhcpv4Srv() {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
156
    IfaceMgr::instance().closeSockets();
157 158
}

159 160
void
Dhcpv4Srv::shutdown() {
161
    LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC, DHCP4_SHUTDOWN_REQUEST);
162 163 164
    shutdown_ = true;
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
165 166
Pkt4Ptr
Dhcpv4Srv::receivePacket(int timeout) {
167 168 169
    return (IfaceMgr::instance().receive4(timeout));
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
170 171
void
Dhcpv4Srv::sendPacket(const Pkt4Ptr& packet) {
172 173 174
    IfaceMgr::instance().send(packet);
}

175 176
bool
Dhcpv4Srv::run() {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
177
    while (!shutdown_) {
178
        /// @todo: calculate actual timeout once we have lease database
179 180
        //cppcheck-suppress variableScope This is temporary anyway
        const int timeout = 1000;
181

Tomek Mrugalski's avatar
Tomek Mrugalski committed
182
        // client's message and server's response
183
        Pkt4Ptr query;
Tomek Mrugalski's avatar
Tomek Mrugalski committed
184
        Pkt4Ptr rsp;
185

186
        try {
187
            query = receivePacket(timeout);
188 189 190 191
        } catch (const std::exception& e) {
            LOG_ERROR(dhcp4_logger, DHCP4_PACKET_RECEIVE_FAIL).arg(e.what());
        }

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
        // Timeout may be reached or signal received, which breaks select()
        // with no reception ocurred
        if (!query) {
            continue;
        }

        bool skip_unpack = false;

        // The packet has just been received so contains the uninterpreted wire
        // data; execute callouts registered for buffer6_receive.
        if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_buffer4_receive_)) {
            CalloutHandlePtr callout_handle = getCalloutHandle(query);

            // Delete previously set arguments
            callout_handle->deleteAllArguments();

            // Pass incoming packet as argument
            callout_handle->setArgument("query4", query);

            // Call callouts
            HooksManager::callCallouts(Hooks.hook_index_buffer4_receive_, *callout_handle);

            // Callouts decided to skip the next processing step. The next
            // processing step would to parse the packet, so skip at this
            // stage means that callouts did the parsing already, so server
            // should skip parsing.
            if (callout_handle->getSkip()) {
                LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_BUFFER_RCVD_SKIP);
                skip_unpack = true;
            }

            callout_handle->getArgument("query4", query);
        }

        // Unpack the packet information unless the buffer4_receive callouts
        // indicated they did it
        if (!skip_unpack) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
229 230 231
            try {
                query->unpack();
            } catch (const std::exception& e) {
232 233 234
                // Failed to parse the packet.
                LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL,
                          DHCP4_PACKET_PARSE_FAIL).arg(e.what());
235 236
                continue;
            }
237
        }
238

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
        LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_PACKET_RECEIVED)
            .arg(serverReceivedPacketName(query->getType()))
            .arg(query->getType())
            .arg(query->getIface());
        LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_QUERY_DATA)
            .arg(static_cast<int>(query->getType()))
            .arg(query->toText());

        // Let's execute all callouts registered for packet_received
        if (HooksManager::calloutsPresent(hook_index_pkt4_receive_)) {
            CalloutHandlePtr callout_handle = getCalloutHandle(query);

            // Delete previously set arguments
            callout_handle->deleteAllArguments();

            // Pass incoming packet as argument
            callout_handle->setArgument("query4", query);

            // Call callouts
            HooksManager::callCallouts(hook_index_pkt4_receive_,
                                       *callout_handle);

            // Callouts decided to skip the next processing step. The next
            // processing step would to process the packet, so skip at this
            // stage means drop.
            if (callout_handle->getSkip()) {
                LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_PACKET_RCVD_SKIP);
                continue;
            }
268

269 270
            callout_handle->getArgument("query4", query);
        }
271

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        try {
            switch (query->getType()) {
            case DHCPDISCOVER:
                rsp = processDiscover(query);
                break;

            case DHCPREQUEST:
                // Note that REQUEST is used for many things in DHCPv4: for
                // requesting new leases, renewing existing ones and even
                // for rebinding.
                rsp = processRequest(query);
                break;

            case DHCPRELEASE:
                processRelease(query);
                break;

            case DHCPDECLINE:
                processDecline(query);
                break;

            case DHCPINFORM:
                processInform(query);
                break;

            default:
                // Only action is to output a message if debug is enabled,
                // and that is covered by the debug statement before the
                // "switch" statement.
                ;
302
            }
303 304 305 306 307 308 309 310 311 312 313 314 315 316
        } catch (const isc::Exception& e) {

            // Catch-all exception (at least for ones based on the isc
            // Exception class, which covers more or less all that
            // are explicitly raised in the BIND 10 code).  Just log
            // the problem and ignore the packet. (The problem is logged
            // as a debug message because debug is disabled by default -
            // it prevents a DDOS attack based on the sending of problem
            // packets.)
            if (dhcp4_logger.isDebugEnabled(DBG_DHCP4_BASIC)) {
                std::string source = "unknown";
                HWAddrPtr hwptr = query->getHWAddr();
                if (hwptr) {
                    source = hwptr->toText();
317
                }
318 319 320
                LOG_DEBUG(dhcp4_logger, DBG_DHCP4_BASIC,
                          DHCP4_PACKET_PROCESS_FAIL)
                    .arg(source).arg(e.what());
321
            }
322
        }
323

324 325 326
        if (!rsp) {
            continue;
        }
327

328
        adjustRemoteAddr(query, rsp);
329

330 331 332 333 334
        if (!rsp->getHops()) {
            rsp->setRemotePort(DHCP4_CLIENT_PORT);
        } else {
            rsp->setRemotePort(DHCP4_SERVER_PORT);
        }
335

336 337 338 339
        rsp->setLocalAddr(query->getLocalAddr());
        rsp->setLocalPort(DHCP4_SERVER_PORT);
        rsp->setIface(query->getIface());
        rsp->setIndex(query->getIndex());
340

341 342
        // Specifies if server should do the packing
        bool skip_pack = false;
343

344 345 346
        // Execute all callouts registered for packet6_send
        if (HooksManager::calloutsPresent(hook_index_pkt4_send_)) {
            CalloutHandlePtr callout_handle = getCalloutHandle(query);
347

348 349
            // Delete all previous arguments
            callout_handle->deleteAllArguments();
350

351 352
            // Clear skip flag if it was set in previous callouts
            callout_handle->setSkip(false);
353

354 355
            // Set our response
            callout_handle->setArgument("response4", rsp);
356

357 358 359
            // Call all installed callouts
            HooksManager::callCallouts(hook_index_pkt4_send_,
                                       *callout_handle);
360

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
            // Callouts decided to skip the next processing step. The next
            // processing step would to send the packet, so skip at this
            // stage means "drop response".
            if (callout_handle->getSkip()) {
                LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_PACKET_SEND_SKIP);
                skip_pack = true;
            }
        }

        if (!skip_pack) {
            try {
                rsp->pack();
            } catch (const std::exception& e) {
                LOG_ERROR(dhcp4_logger, DHCP4_PACKET_SEND_FAIL)
                    .arg(e.what());
            }
        }

        try {
            // Now all fields and options are constructed into output wire buffer.
            // Option objects modification does not make sense anymore. Hooks
            // can only manipulate wire buffer at this stage.
            // Let's execute all callouts registered for buffer6_send
            if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_buffer4_send_)) {
                CalloutHandlePtr callout_handle = getCalloutHandle(query);
386

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
                // Delete previously set arguments
                callout_handle->deleteAllArguments();

                // Pass incoming packet as argument
                callout_handle->setArgument("response4", rsp);

                // Call callouts
                HooksManager::callCallouts(Hooks.hook_index_buffer4_send_, *callout_handle);

                // Callouts decided to skip the next processing step. The next
                // processing step would to parse the packet, so skip at this
                // stage means drop.
                if (callout_handle->getSkip()) {
                    LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_BUFFER_SEND_SKIP);
                    continue;
402
                }
403 404

                callout_handle->getArgument("response4", rsp);
405
            }
406 407 408 409 410 411 412 413 414

            LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA,
                      DHCP4_RESPONSE_DATA)
                .arg(static_cast<int>(rsp->getType())).arg(rsp->toText());

            sendPacket(rsp);
        } catch (const std::exception& e) {
            LOG_ERROR(dhcp4_logger, DHCP4_PACKET_SEND_FAIL)
                .arg(e.what());
415
        }
416 417 418 419 420
    }

    return (true);
}

421 422
bool
Dhcpv4Srv::loadServerID(const std::string& file_name) {
423

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    // load content of the file into a string
    fstream f(file_name.c_str(), ios::in);
    if (!f.is_open()) {
        return (false);
    }

    string hex_string;
    f >> hex_string;
    f.close();

    // remove any spaces
    boost::algorithm::erase_all(hex_string, " ");

    try {
        IOAddress addr(hex_string);

Tomek Mrugalski's avatar
Tomek Mrugalski committed
440
        if (!addr.isV4()) {
441 442 443 444 445 446 447 448 449 450
            return (false);
        }

        // Now create server-id option
        serverid_.reset(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER, addr));

    } catch(...) {
        // any kind of malformed input (empty string, IPv6 address, complete
        // garbate etc.)
        return (false);
451 452 453 454 455
    }

    return (true);
}

456 457
void
Dhcpv4Srv::generateServerID() {
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474

    const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();

    // Let's find suitable interface.
    for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
         iface != ifaces.end(); ++iface) {

        // Let's don't use loopback.
        if (iface->flag_loopback_) {
            continue;
        }

        // Let's skip downed interfaces. It is better to use working ones.
        if (!iface->flag_up_) {
            continue;
        }

475
        const Iface::AddressCollection addrs = iface->getAddresses();
476

477
        for (Iface::AddressCollection::const_iterator addr = addrs.begin();
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
             addr != addrs.end(); ++addr) {
            if (addr->getFamily() != AF_INET) {
                continue;
            }

            serverid_ = OptionPtr(new Option4AddrLst(DHO_DHCP_SERVER_IDENTIFIER,
                                                     *addr));
            return;
        }


    }

    isc_throw(BadValue, "No suitable interfaces for server-identifier found");
}

494 495
bool
Dhcpv4Srv::writeServerID(const std::string& file_name) {
496 497 498 499 500 501
    fstream f(file_name.c_str(), ios::out | ios::trunc);
    if (!f.good()) {
        return (false);
    }
    f << srvidToString(getServerID());
    f.close();
502
    return (true);
503 504
}

505
string
506
Dhcpv4Srv::srvidToString(const OptionPtr& srvid) {
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    if (!srvid) {
        isc_throw(BadValue, "NULL pointer passed to srvidToString()");
    }
    boost::shared_ptr<Option4AddrLst> generated =
        boost::dynamic_pointer_cast<Option4AddrLst>(srvid);
    if (!srvid) {
        isc_throw(BadValue, "Pointer to invalid option passed to srvidToString()");
    }

    Option4AddrLst::AddressContainer addrs = generated->getAddresses();
    if (addrs.size() != 1) {
        isc_throw(BadValue, "Malformed option passed to srvidToString(). "
                  << "Expected to contain a single IPv4 address.");
    }

    return (addrs[0].toText());
523 524
}

525 526
void
Dhcpv4Srv::copyDefaultFields(const Pkt4Ptr& question, Pkt4Ptr& answer) {
527 528 529
    answer->setIface(question->getIface());
    answer->setIndex(question->getIndex());
    answer->setCiaddr(question->getCiaddr());
530

531
    answer->setSiaddr(IOAddress("0.0.0.0")); // explicitly set this to 0
532
    answer->setHops(question->getHops());
533 534

    // copy MAC address
535
    answer->setHWAddr(question->getHWAddr());
536 537

    // relay address
538 539
    answer->setGiaddr(question->getGiaddr());

540
    // Let's copy client-id to response. See RFC6842.
541 542 543 544
    OptionPtr client_id = question->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
    if (client_id) {
        answer->addOption(client_id);
    }
545 546

    // If src/dest HW addresses are used by the packet filtering class
547 548 549 550 551 552
    // we need to copy them as well. There is a need to check that the
    // address being set is not-NULL because an attempt to set the NULL
    // HW would result in exception. If these values are not set, the
    // the default HW addresses (zeroed) should be generated by the
    // packet filtering class when creating Ethernet header for
    // outgoing packet.
553 554
    HWAddrPtr src_hw_addr = question->getLocalHWAddr();
    if (src_hw_addr) {
555
        answer->setLocalHWAddr(src_hw_addr);
556
    }
557
    HWAddrPtr dst_hw_addr = question->getRemoteHWAddr();
558
    if (dst_hw_addr) {
559
        answer->setRemoteHWAddr(dst_hw_addr);
560
    }
561 562
}

563 564
void
Dhcpv4Srv::appendDefaultOptions(Pkt4Ptr& msg, uint8_t msg_type) {
565
    OptionPtr opt;
566 567

    // add Message Type Option (type 53)
568
    msg->setType(msg_type);
569

Tomek Mrugalski's avatar
Tomek Mrugalski committed
570
    // DHCP Server Identifier (type 54)
571
    msg->addOption(getServerID());
Tomek Mrugalski's avatar
Tomek Mrugalski committed
572

573 574 575
    // more options will be added here later
}

576 577
void
Dhcpv4Srv::appendRequestedOptions(const Pkt4Ptr& question, Pkt4Ptr& msg) {
578 579 580 581 582 583 584 585 586 587 588

    // Get the subnet relevant for the client. We will need it
    // to get the options associated with it.
    Subnet4Ptr subnet = selectSubnet(question);
    // If we can't find the subnet for the client there is no way
    // to get the options to be sent to a client. We don't log an
    // error because it will be logged by the assignLease method
    // anyway.
    if (!subnet) {
        return;
    }
589

590 591 592 593 594 595 596 597 598
    // try to get the 'Parameter Request List' option which holds the
    // codes of requested options.
    OptionUint8ArrayPtr option_prl = boost::dynamic_pointer_cast<
        OptionUint8Array>(question->getOption(DHO_DHCP_PARAMETER_REQUEST_LIST));
    // If there is no PRL option in the message from the client then
    // there is nothing to do.
    if (!option_prl) {
        return;
    }
599

600 601 602 603 604 605 606 607 608 609 610 611
    // Get the codes of requested options.
    const std::vector<uint8_t>& requested_opts = option_prl->getValues();
    // For each requested option code get the instance of the option
    // to be returned to the client.
    for (std::vector<uint8_t>::const_iterator opt = requested_opts.begin();
         opt != requested_opts.end(); ++opt) {
        Subnet::OptionDescriptor desc =
            subnet->getOptionDescriptor("dhcp4", *opt);
        if (desc.option) {
            msg->addOption(desc.option);
        }
    }
Tomek Mrugalski's avatar
Tomek Mrugalski committed
612
}
613

614 615 616 617 618 619 620 621 622
void
Dhcpv4Srv::appendBasicOptions(const Pkt4Ptr& question, Pkt4Ptr& msg) {
    // Identify options that we always want to send to the
    // client (if they are configured).
    static const uint16_t required_options[] = {
        DHO_SUBNET_MASK,
        DHO_ROUTERS,
        DHO_DOMAIN_NAME_SERVERS,
        DHO_DOMAIN_NAME };
623

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    static size_t required_options_size =
        sizeof(required_options) / sizeof(required_options[0]);

    // Get the subnet.
    Subnet4Ptr subnet = selectSubnet(question);
    if (!subnet) {
        return;
    }

    // Try to find all 'required' options in the outgoing
    // message. Those that are not present will be added.
    for (int i = 0; i < required_options_size; ++i) {
        OptionPtr opt = msg->getOption(required_options[i]);
        if (!opt) {
            // Check whether option has been configured.
            Subnet::OptionDescriptor desc =
                subnet->getOptionDescriptor("dhcp4", required_options[i]);
            if (desc.option) {
                msg->addOption(desc.option);
            }
        }
    }
Tomek Mrugalski's avatar
Tomek Mrugalski committed
646
}
647

648 649
void
Dhcpv4Srv::assignLease(const Pkt4Ptr& question, Pkt4Ptr& answer) {
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666

    // We need to select a subnet the client is connected in.
    Subnet4Ptr subnet = selectSubnet(question);
    if (!subnet) {
        // This particular client is out of luck today. We do not have
        // information about the subnet he is connected to. This likely means
        // misconfiguration of the server (or some relays). We will continue to
        // process this message, but our response will be almost useless: no
        // addresses or prefixes, no subnet specific configuration etc. The only
        // thing this client can get is some global information (like DNS
        // servers).

        // perhaps this should be logged on some higher level? This is most likely
        // configuration bug.
        LOG_ERROR(dhcp4_logger, DHCP4_SUBNET_SELECTION_FAILED)
            .arg(question->getRemoteAddr().toText())
            .arg(serverReceivedPacketName(question->getType()));
667
        answer->setType(DHCPNAK);
668 669 670
        answer->setYiaddr(IOAddress("0.0.0.0"));
        return;
    }
671

672 673 674
    LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL_DATA, DHCP4_SUBNET_SELECTED)
        .arg(subnet->toText());

675 676 677 678 679 680 681
    // Get client-id option
    ClientIdPtr client_id;
    OptionPtr opt = question->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
    if (opt) {
        client_id = ClientIdPtr(new ClientId(opt->getData()));
    }
    // client-id is not mandatory in DHCPv4
682

683
    IOAddress hint = question->getYiaddr();
684

685
    HWAddrPtr hwaddr = question->getHWAddr();
686

687 688 689 690 691 692
    // "Fake" allocation is processing of DISCOVER message. We pretend to do an
    // allocation, but we do not put the lease in the database. That is ok,
    // because we do not guarantee that the user will get that exact lease. If
    // the user selects this server to do actual allocation (i.e. sends REQUEST)
    // it should include this hint. That will help us during the actual lease
    // allocation.
693
    bool fake_allocation = (question->getType() == DHCPDISCOVER);
694

695 696
    CalloutHandlePtr callout_handle = getCalloutHandle(question);

697 698 699 700 701
    // Use allocation engine to pick a lease for this client. Allocation engine
    // will try to honour the hint, but it is just a hint - some other address
    // may be used instead. If fake_allocation is set to false, the lease will
    // be inserted into the LeaseMgr as well.
    Lease4Ptr lease = alloc_engine_->allocateAddress4(subnet, client_id, hwaddr,
702 703
                                                      hint, fake_allocation,
                                                      callout_handle);
704 705

    if (lease) {
706 707
        // We have a lease! Let's set it in the packet and send it back to
        // the client.
708 709
        LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, fake_allocation?
                  DHCP4_LEASE_ADVERT:DHCP4_LEASE_ALLOC)
Tomek Mrugalski's avatar
Tomek Mrugalski committed
710
            .arg(lease->addr_.toText())
711
            .arg(client_id?client_id->toText():"(no client-id)")
Tomek Mrugalski's avatar
Tomek Mrugalski committed
712
            .arg(hwaddr?hwaddr->toText():"(no hwaddr info)");
713 714 715 716 717 718 719 720 721

        answer->setYiaddr(lease->addr_);

        // IP Address Lease time (type 51)
        opt = OptionPtr(new Option(Option::V4, DHO_DHCP_LEASE_TIME));
        opt->setUint32(lease->valid_lft_);
        answer->addOption(opt);

        // Router (type 3)
722 723 724 725 726
        Subnet::OptionDescriptor opt_routers =
            subnet->getOptionDescriptor("dhcp4", DHO_ROUTERS);
        if (opt_routers.option) {
            answer->addOption(opt_routers.option);
        }
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

        // Subnet mask (type 1)
        answer->addOption(getNetmaskOption(subnet));

        // @todo: send renew timer option (T1, option 58)
        // @todo: send rebind timer option (T2, option 59)

    } else {
        // Allocation engine did not allocate a lease. The engine logged
        // cause of that failure. The only thing left is to insert
        // status code to pass the sad news to the client.

        LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, fake_allocation?
                  DHCP4_LEASE_ADVERT_FAIL:DHCP4_LEASE_ALLOC_FAIL)
            .arg(client_id?client_id->toText():"(no client-id)")
            .arg(hwaddr?hwaddr->toText():"(no hwaddr info)")
            .arg(hint.toText());

745
        answer->setType(DHCPNAK);
746 747 748 749
        answer->setYiaddr(IOAddress("0.0.0.0"));
    }
}

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
void
Dhcpv4Srv::adjustRemoteAddr(const Pkt4Ptr& question, Pkt4Ptr& msg) {
    // Let's create static objects representing zeroed and broadcast
    // addresses. We will use them further in this function to test
    // other addresses against them. Since they are static, they will
    // be created only once.
    static const IOAddress zero_addr("0.0.0.0");
    static const IOAddress bcast_addr("255.255.255.255");

    // If received relayed message, server responds to the relay address.
    if (question->getGiaddr() != zero_addr) {
        msg->setRemoteAddr(question->getGiaddr());

    // If giaddr is 0 but client set ciaddr, server should unicast the
    // response to ciaddr.
    } else if (question->getCiaddr() != zero_addr) {
        msg->setRemoteAddr(question->getCiaddr());

    // We can't unicast the response to the client when sending NAK,
    // because we haven't allocated address for him. Therefore,
    // NAK is broadcast.
    } else if (msg->getType() == DHCPNAK) {
        msg->setRemoteAddr(bcast_addr);

    // If yiaddr is set it means that we have created a lease for a client.
775
    } else if (msg->getYiaddr() != zero_addr) {
776 777 778 779 780 781
        // If the broadcast bit is set in the flags field, we have to
        // send the response to broadcast address. Client may have requested it
        // because it doesn't support reception of messages on the interface
        // which doesn't have an address assigned. The other case when response
        // must be broadcasted is when our server does not support responding
        // directly to a client without address assigned.
782
        const bool bcast_flag = ((question->getFlags() & Pkt4::FLAG_BROADCAST_MASK) != 0);
783 784 785 786 787 788 789
        if (!IfaceMgr::instance().isDirectResponseSupported() || bcast_flag) {
            msg->setRemoteAddr(bcast_addr);

        // Client cleared the broadcast bit and we support direct responses
        // so we should unicast the response to a newly allocated address -
        // yiaddr.
        } else {
790
            msg->setRemoteAddr(msg->getYiaddr());
791 792 793 794 795 796 797 798 799 800 801 802 803

        }

    // In most cases, we should have the remote address found already. If we
    // found ourselves at this point, the rational thing to do is to respond
    // to the address we got the query from.
    } else {
        msg->setRemoteAddr(question->getRemoteAddr());

    }
}


804 805
OptionPtr
Dhcpv4Srv::getNetmaskOption(const Subnet4Ptr& subnet) {
806 807 808 809 810 811 812 813
    uint32_t netmask = getNetmask4(subnet->get().second);

    OptionPtr opt(new OptionInt<uint32_t>(Option::V4,
                  DHO_SUBNET_MASK, netmask));

    return (opt);
}

814 815
Pkt4Ptr
Dhcpv4Srv::processDiscover(Pkt4Ptr& discover) {
816 817 818

    sanityCheck(discover, FORBIDDEN);

819
    Pkt4Ptr offer = Pkt4Ptr
Tomek Mrugalski's avatar
Tomek Mrugalski committed
820
        (new Pkt4(DHCPOFFER, discover->getTransid()));
821

Tomek Mrugalski's avatar
Tomek Mrugalski committed
822 823
    copyDefaultFields(discover, offer);
    appendDefaultOptions(offer, DHCPOFFER);
824
    appendRequestedOptions(discover, offer);
Tomek Mrugalski's avatar
Tomek Mrugalski committed
825

826
    assignLease(discover, offer);
827

828 829 830 831 832
    // There are a few basic options that we always want to
    // include in the response. If client did not request
    // them we append them for him.
    appendBasicOptions(discover, offer);

833
    return (offer);
834 835
}

836 837
Pkt4Ptr
Dhcpv4Srv::processRequest(Pkt4Ptr& request) {
838
    Pkt4Ptr ack = Pkt4Ptr
839 840 841 842
        (new Pkt4(DHCPACK, request->getTransid()));

    copyDefaultFields(request, ack);
    appendDefaultOptions(ack, DHCPACK);
843
    appendRequestedOptions(request, ack);
844

845 846 847
    // Note that we treat REQUEST message uniformly, regardless if this is a
    // first request (requesting for new address), renewing existing address
    // or even rebinding.
848
    assignLease(request, ack);
849

850 851 852 853 854
    // There are a few basic options that we always want to
    // include in the response. If client did not request
    // them we append them for him.
    appendBasicOptions(request, ack);

855
    return (ack);
856 857
}

858 859
void
Dhcpv4Srv::processRelease(Pkt4Ptr& release) {
860 861

    // Try to find client-id
862 863 864 865 866 867
    ClientIdPtr client_id;
    OptionPtr opt = release->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
    if (opt) {
        client_id = ClientIdPtr(new ClientId(opt->getData()));
    }

868 869 870 871 872 873 874 875 876 877 878 879
    try {
        // Do we have a lease for that particular address?
        Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(release->getYiaddr());

        if (!lease) {
            // No such lease - bogus release
            LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_NO_LEASE)
                .arg(release->getYiaddr().toText())
                .arg(release->getHWAddr()->toText())
                .arg(client_id ? client_id->toText() : "(no client-id)");
            return;
        }
880

881 882 883 884 885 886 887 888 889 890
        // Does the hardware address match? We don't want one client releasing
        // second client's leases.
        if (lease->hwaddr_ != release->getHWAddr()->hwaddr_) {
            // @todo: Print hwaddr from lease as part of ticket #2589
            LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_HWADDR)
                .arg(release->getYiaddr().toText())
                .arg(client_id ? client_id->toText() : "(no client-id)")
                .arg(release->getHWAddr()->toText());
            return;
        }
891

892 893 894 895 896 897 898 899 900
        // Does the lease have client-id info? If it has, then check it with what
        // the client sent us.
        if (lease->client_id_ && client_id && *lease->client_id_ != *client_id) {
            LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE_FAIL_WRONG_CLIENT_ID)
                .arg(release->getYiaddr().toText())
                .arg(client_id->toText())
                .arg(lease->client_id_->toText());
            return;
        }
901

902
        bool skip = false;
903

904 905 906 907 908 909
        // Execute all callouts registered for packet6_send
        if (HooksManager::getHooksManager().calloutsPresent(Hooks.hook_index_lease4_release_)) {
            CalloutHandlePtr callout_handle = getCalloutHandle(release);

            // Delete all previous arguments
            callout_handle->deleteAllArguments();
910

911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
            // Pass the original packet
            callout_handle->setArgument("query4", release);

            // Pass the lease to be updated
            callout_handle->setArgument("lease4", lease);

            // Call all installed callouts
            HooksManager::callCallouts(Hooks.hook_index_lease4_release_, *callout_handle);

            // Callouts decided to skip the next processing step. The next
            // processing step would to send the packet, so skip at this
            // stage means "drop response".
            if (callout_handle->getSkip()) {
                skip = true;
                LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_LEASE4_RELEASE_SKIP);
            }
        }

        // Ok, we've passed all checks. Let's release this address.
        bool success = false; // was the removal operation succeessful?

        // Ok, hw and client-id match - let's release the lease.
        if (!skip) {
            success = LeaseMgrFactory::instance().deleteLease(lease->addr_);

            if (success) {
                // Release successful - we're done here
                LOG_DEBUG(dhcp4_logger, DBG_DHCP4_DETAIL, DHCP4_RELEASE)
                    .arg(lease->addr_.toText())
                    .arg(client_id ? client_id->toText() : "(no client-id)")
                    .arg(release->getHWAddr()->toText());
            } else {
                // Release failed -
                LOG_ERROR(dhcp4_logger, DHCP4_RELEASE_FAIL)
                    .arg(lease->addr_.toText())
946
                .arg(client_id ? client_id->toText() : "(no client-id)")
947 948
                    .arg(release->getHWAddr()->toText());
            }
949 950 951 952 953 954
        }
    } catch (const isc::Exception& ex) {
        // Rethrow the exception with a bit more data.
        LOG_ERROR(dhcp4_logger, DHCP4_RELEASE_EXCEPTION)
            .arg(ex.what())
            .arg(release->getYiaddr());
955 956
    }

957
}
958

959
void
960
Dhcpv4Srv::processDecline(Pkt4Ptr& /* decline */) {
961 962 963
    /// TODO: Implement this.
}

964 965
Pkt4Ptr
Dhcpv4Srv::processInform(Pkt4Ptr& inform) {
966
    /// TODO: Currently implemented echo mode. Implement this for real
967 968
    return (inform);
}
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999

const char*
Dhcpv4Srv::serverReceivedPacketName(uint8_t type) {
    static const char* DISCOVER = "DISCOVER";
    static const char* REQUEST = "REQUEST";
    static const char* RELEASE = "RELEASE";
    static const char* DECLINE = "DECLINE";
    static const char* INFORM = "INFORM";
    static const char* UNKNOWN = "UNKNOWN";

    switch (type) {
    case DHCPDISCOVER:
        return (DISCOVER);

    case DHCPREQUEST:
        return (REQUEST);

    case DHCPRELEASE:
        return (RELEASE);

    case DHCPDECLINE:
        return (DECLINE);

    case DHCPINFORM:
        return (INFORM);

    default:
        ;
    }
    return (UNKNOWN);
}
1000

1001 1002
Subnet4Ptr
Dhcpv4Srv::selectSubnet(const Pkt4Ptr& question) {
1003

1004
    Subnet4Ptr subnet;
1005 1006
    // Is this relayed message?
    IOAddress relay = question->getGiaddr();
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1007
    static const IOAddress notset("0.0.0.0");
1008

Tomek Mrugalski's avatar
Tomek Mrugalski committed
1009
    if (relay != notset) {
1010
        // Yes: Use relay address to select subnet
1011
        subnet = CfgMgr::instance().getSubnet4(relay);
1012 1013 1014
    } else {

        // No: Use client's address to select subnet
1015
        subnet = CfgMgr::instance().getSubnet4(question->getRemoteAddr());
1016
    }
1017

1018 1019
    /// @todo Implement getSubnet4(interface-name)

1020
    // Let's execute all callouts registered for packet_received
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1021
    if (HooksManager::calloutsPresent(hook_index_subnet4_select_)) {
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
        CalloutHandlePtr callout_handle = getCalloutHandle(question);

        // We're reusing callout_handle from previous calls
        callout_handle->deleteAllArguments();

        // Set new arguments
        callout_handle->setArgument("query4", question);
        callout_handle->setArgument("subnet4", subnet);
        callout_handle->setArgument("subnet4collection", CfgMgr::instance().getSubnets4());

        // Call user (and server-side) callouts
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1033
        HooksManager::callCallouts(hook_index_subnet4_select_, *callout_handle);
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

        // Callouts decided to skip this step. This means that no subnet will be
        // selected. Packet processing will continue, but it will be severly limited
        // (i.e. only global options will be assigned)
        if (callout_handle->getSkip()) {
            LOG_DEBUG(dhcp4_logger, DBG_DHCP4_HOOKS, DHCP4_HOOK_SUBNET4_SELECT_SKIP);
            return (Subnet4Ptr());
        }

        // Use whatever subnet was specified by the callout
        callout_handle->getArgument("subnet4", subnet);
1045
    }
1046 1047

    return (subnet);
1048 1049
}

1050 1051
void
Dhcpv4Srv::sanityCheck(const Pkt4Ptr& pkt, RequirementLevel serverid) {
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    OptionPtr server_id = pkt->getOption(DHO_DHCP_SERVER_IDENTIFIER);
    switch (serverid) {
    case FORBIDDEN:
        if (server_id) {
            isc_throw(RFCViolation, "Server-id option was not expected, but "
                      << "received in " << serverReceivedPacketName(pkt->getType()));
        }
        break;

    case MANDATORY:
        if (!server_id) {
            isc_throw(RFCViolation, "Server-id option was expected, but not "
                      " received in message "
                      << serverReceivedPacketName(pkt->getType()));
        }
        break;

    case OPTIONAL:
        // do nothing here
        ;
    }
1073 1074

    // If there is HWAddress set and it is non-empty, then we're good
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1075
    if (pkt->getHWAddr() && !pkt->getHWAddr()->hwaddr_.empty()) {
1076
        return;
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1077
    }
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

    // There has to be something to uniquely identify the client:
    // either non-zero MAC address or client-id option present (or both)
    OptionPtr client_id = pkt->getOption(DHO_DHCP_CLIENT_IDENTIFIER);

    // If there's no client-id (or a useless one is provided, i.e. 0 length)
    if (!client_id || client_id->len() == client_id->getHeaderLen()) {
        isc_throw(RFCViolation, "Missing or useless client-id and no HW address "
                  " provided in message "
                  << serverReceivedPacketName(pkt->getType()));
    }
1089
}
1090

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
isc::hooks::CalloutHandlePtr Dhcpv4Srv::getCalloutHandle(const Pkt4Ptr& pkt) {
    // This method returns a CalloutHandle for a given packet. It is guaranteed
    // to return the same callout_handle (so user library contexts are
    // preserved). This method works well if the server processes one packet
    // at a time. Once the server architecture is extended to cover parallel
    // packets processing (e.g. delayed-ack, some form of buffering etc.), this
    // method has to be extended (e.g. store callouts in a map and use pkt as
    // a key). Additional code would be required to release the callout handle
    // once the server finished processing.

    CalloutHandlePtr callout_handle;
    static Pkt4Ptr old_pointer;

    if (!callout_handle ||
        old_pointer != pkt) {
        // This is the first packet or a different packet than previously
        // passed to getCalloutHandle()

        // Remember the pointer to this packet
        old_pointer = pkt;

Tomek Mrugalski's avatar
Tomek Mrugalski committed
1112
        callout_handle = HooksManager::createCalloutHandle();
1113 1114 1115
    }

    return (callout_handle);
1116
}
1117

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
void
Dhcpv4Srv::openActiveSockets(const uint16_t port,
                             const bool use_bcast) {
    IfaceMgr::instance().closeSockets();

    // Get the reference to the collection of interfaces. This reference should
    // be valid as long as the program is run because IfaceMgr is a singleton.
    // Therefore we can safely iterate over instances of all interfaces and
    // modify their flags. Here we modify flags which indicate whether socket
    // should be open for a particular interface or not.
    const IfaceMgr::IfaceCollection& ifaces = IfaceMgr::instance().getIfaces();
    for (IfaceMgr::IfaceCollection::const_iterator iface = ifaces.begin();
         iface != ifaces.end(); ++iface) {
        Iface* iface_ptr = IfaceMgr::instance().getIface(iface->getName());
1132 1133 1134 1135 1136
        if (iface_ptr == NULL) {
            isc_throw(isc::Unexpected, "Interface Manager returned NULL"
                      << " instance of the interface when DHCPv4 server was"
                      << " trying to reopen sockets after reconfiguration");
        }