dhcp4_srv_unittest.cc 32.6 KB
Newer Older
1
// Copyright (C) 2011-2012  Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//
// 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.

#include <config.h>
#include <sstream>

18
#include <asiolink/io_address.h>
19 20
#include <dhcp/dhcp4.h>
#include <dhcp/option.h>
21
#include <dhcp4/dhcp4_srv.h>
22 23 24 25
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/lease_mgr.h>
#include <dhcpsrv/lease_mgr_factory.h>
#include <dhcpsrv/utils.h>
26 27 28 29 30 31
#include <gtest/gtest.h>

#include <fstream>
#include <iostream>

#include <arpa/inet.h>
32 33 34 35

using namespace std;
using namespace isc;
using namespace isc::dhcp;
36
using namespace isc::asiolink;
37 38

namespace {
39
const char* const INTERFACE_FILE = "interfaces.txt";
40 41

class NakedDhcpv4Srv: public Dhcpv4Srv {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
42
    // "naked" DHCPv4 server, exposes internal fields
43
public:
44 45 46 47 48 49 50 51 52
    NakedDhcpv4Srv(uint16_t port = 0):Dhcpv4Srv(port) { }

    using Dhcpv4Srv::processDiscover;
    using Dhcpv4Srv::processRequest;
    using Dhcpv4Srv::processRelease;
    using Dhcpv4Srv::processDecline;
    using Dhcpv4Srv::processInform;
    using Dhcpv4Srv::getServerID;
    using Dhcpv4Srv::sanityCheck;
53 54 55 56 57
};

class Dhcpv4SrvTest : public ::testing::Test {
public:
    Dhcpv4SrvTest() {
58 59 60 61 62 63 64
        subnet_ = Subnet4Ptr(new Subnet4(IOAddress("192.0.2.0"), 24, 1000,
                                         2000, 3000));
        pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"), IOAddress("192.0.2.110")));
        subnet_->addPool(pool_);

        CfgMgr::instance().deleteSubnets4();
        CfgMgr::instance().addSubnet4(subnet_);
65
    }
66

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    void MessageCheck(const boost::shared_ptr<Pkt4>& q,
                      const boost::shared_ptr<Pkt4>& a) {
        ASSERT_TRUE(q);
        ASSERT_TRUE(a);

        EXPECT_EQ(q->getHops(),   a->getHops());
        EXPECT_EQ(q->getIface(),  a->getIface());
        EXPECT_EQ(q->getIndex(),  a->getIndex());
        EXPECT_EQ(q->getGiaddr(), a->getGiaddr());

        // check that bare minimum of required options are there
        EXPECT_TRUE(a->getOption(DHO_SUBNET_MASK));
        EXPECT_TRUE(a->getOption(DHO_ROUTERS));
        EXPECT_TRUE(a->getOption(DHO_DHCP_SERVER_IDENTIFIER));
        EXPECT_TRUE(a->getOption(DHO_DHCP_LEASE_TIME));
        EXPECT_TRUE(a->getOption(DHO_SUBNET_MASK));
        EXPECT_TRUE(a->getOption(DHO_ROUTERS));
        EXPECT_TRUE(a->getOption(DHO_DOMAIN_NAME));
        EXPECT_TRUE(a->getOption(DHO_DOMAIN_NAME_SERVERS));

        // check that something is offered
        EXPECT_TRUE(a->getYiaddr().toText() != "0.0.0.0");
    }

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    // Generate client-id option
    OptionPtr generateClientId(size_t size = 4) {

        OptionBuffer clnt_id(size);
        for (int i = 0; i < size; i++) {
            clnt_id[i] = 100 + i;
        }

        client_id_ = ClientIdPtr(new ClientId(clnt_id));

        return (OptionPtr(new Option(Option::V4, DHO_DHCP_CLIENT_IDENTIFIER,
                                     clnt_id.begin(),
                                     clnt_id.begin() + size)));
    }

    // Check that address was returned from proper range, that its lease
    // lifetime is correct, that T1 and T2 are returned properly
    void checkAddressParams(const Pkt4Ptr& rsp, const SubnetPtr subnet,
                            bool t1_mandatory = false, bool t2_mandatory = false) {

        // Technically inPool implies inRange, but let's be on the safe
        // side and check both.
        EXPECT_TRUE(subnet->inRange(rsp->getYiaddr()));
        EXPECT_TRUE(subnet->inPool(rsp->getYiaddr()));

        // Check lease time
        OptionPtr tmp = rsp->getOption(DHO_DHCP_LEASE_TIME);
        if (!tmp) {
            ADD_FAILURE() << "Lease time option missing in response";
        } else {
            EXPECT_EQ(tmp->getUint32(), subnet->getValid());
        }

        // Check T1 timer
        tmp = rsp->getOption(DHO_DHCP_RENEWAL_TIME);
        if (tmp) {
            EXPECT_EQ(tmp->getUint32(), subnet->getT1());
        } else {
            if (t1_mandatory) {
                ADD_FAILURE() << "Required T1 option missing";
            }
        }

        // Check T2 timer
        tmp = rsp->getOption(DHO_DHCP_REBINDING_TIME);
        if (tmp) {
            EXPECT_EQ(tmp->getUint32(), subnet->getT2());
        } else {
            if (t1_mandatory) {
                ADD_FAILURE() << "Required T2 option missing";
            }
        }
    }

    // Basic checks for generated response (message type and transaction-id).
    void checkResponse(const Pkt4Ptr& rsp, uint8_t expected_message_type,
                       uint32_t expected_transid) {
        ASSERT_TRUE(rsp);
        EXPECT_EQ(expected_message_type, rsp->getType());
        EXPECT_EQ(expected_transid, rsp->getTransid());
    }

    // Checks if the lease sent to client is present in the database
    Lease4Ptr checkLease(const Pkt4Ptr& rsp, const OptionPtr& client_id,
                         const HWAddrPtr& hwaddr, const IOAddress& expected_addr) {

        ClientIdPtr id;
        if (client_id) {
            OptionBuffer data = client_id->getData();
            id.reset(new ClientId(data));
        }

        Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(expected_addr);
        if (!lease) {
            cout << "Lease for " << expected_addr.toText()
                 << " not found in the database backend.";
            return (Lease4Ptr());
        }

        EXPECT_EQ(expected_addr.toText(), lease->addr_.toText());
        if (client_id) {
            EXPECT_TRUE(*lease->client_id_ == *id);
        }
        EXPECT_EQ(subnet_->getID(), lease->subnet_id_);

        return (lease);
    }

    // Checks if server response (OFFER, ACK, NAK) includes proper server-id.
    void checkServerId(const Pkt4Ptr& rsp, const OptionPtr& expected_srvid) {
        // check that server included its server-id
        OptionPtr tmp = rsp->getOption(DHO_DHCP_SERVER_IDENTIFIER);
        ASSERT_TRUE(tmp);
        EXPECT_EQ(tmp->getType(), expected_srvid->getType() );
        EXPECT_EQ(tmp->len(), expected_srvid->len() );
        EXPECT_TRUE(tmp->getData() == expected_srvid->getData());
    }

    // Checks if server response (OFFER, ACK, NAK) includes proper client-id.
    void checkClientId(const Pkt4Ptr& rsp, const OptionPtr& expected_clientid) {
        // check that server included our own client-id
        OptionPtr tmp = rsp->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
        ASSERT_TRUE(tmp);
        EXPECT_EQ(expected_clientid->getType(), tmp->getType());
        EXPECT_EQ(expected_clientid->len(), tmp->len());
        EXPECT_TRUE(expected_clientid->getData() == tmp->getData());
    }

199
    ~Dhcpv4SrvTest() {
200
        CfgMgr::instance().deleteSubnets4();
201
    };
202 203 204 205 206 207 208 209 210

    // A subnet used in most tests
    Subnet4Ptr subnet_;

    // A pool used in most tests
    Pool4Ptr pool_;

    // A client-id used in most tests
    ClientIdPtr client_id_;
211 212 213
};

TEST_F(Dhcpv4SrvTest, basic) {
214 215
    // nothing to test. DHCPv4_srv instance is created
    // in test fixture. It is destroyed in destructor
216

217
    Dhcpv4Srv* srv = NULL;
218
    ASSERT_NO_THROW({
Tomek Mrugalski's avatar
Tomek Mrugalski committed
219
        srv = new Dhcpv4Srv(DHCP4_SERVER_PORT + 10000);
220
    });
221 222 223 224 225 226 227 228 229 230 231 232
    delete srv;

    NakedDhcpv4Srv* naked_srv = NULL;
    ASSERT_NO_THROW({
        naked_srv = new NakedDhcpv4Srv(DHCP4_SERVER_PORT + 10000);
    });
    EXPECT_TRUE(naked_srv->getServerID());

    ASSERT_NO_THROW({
        naked_srv = new NakedDhcpv4Srv(0);
    });
    EXPECT_TRUE(naked_srv->getServerID());
233

Tomek Mrugalski's avatar
Tomek Mrugalski committed
234
    delete srv;
235 236 237



238 239 240
}

TEST_F(Dhcpv4SrvTest, processDiscover) {
241
    NakedDhcpv4Srv* srv = new NakedDhcpv4Srv(0);
Tomek Mrugalski's avatar
Tomek Mrugalski committed
242
    vector<uint8_t> mac(6);
243 244 245
    for (int i = 0; i < 6; i++) {
        mac[i] = 255 - i;
    }
246 247

    boost::shared_ptr<Pkt4> pkt(new Pkt4(DHCPDISCOVER, 1234));
248 249 250 251 252 253 254 255 256 257 258
    boost::shared_ptr<Pkt4> offer;

    pkt->setIface("eth0");
    pkt->setIndex(17);
    pkt->setHWAddr(1, 6, mac);
    pkt->setRemoteAddr(IOAddress("192.0.2.56"));
    pkt->setGiaddr(IOAddress("192.0.2.67"));

    // let's make it a relayed message
    pkt->setHops(3);
    pkt->setRemotePort(DHCP4_SERVER_PORT);
259 260 261

    // should not throw
    EXPECT_NO_THROW(
262
        offer = srv->processDiscover(pkt);
263 264 265
    );

    // should return something
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    ASSERT_TRUE(offer);

    EXPECT_EQ(DHCPOFFER, offer->getType());

    // this is relayed message. It should be sent back to relay address.
    EXPECT_EQ(pkt->getGiaddr(), offer->getRemoteAddr());

    MessageCheck(pkt, offer);

    // now repeat the test for directly sent message
    pkt->setHops(0);
    pkt->setGiaddr(IOAddress("0.0.0.0"));
    pkt->setRemotePort(DHCP4_CLIENT_PORT);

    EXPECT_NO_THROW(
        offer = srv->processDiscover(pkt);
    );

    // should return something
    ASSERT_TRUE(offer);

    EXPECT_EQ(DHCPOFFER, offer->getType());

    // this is direct message. It should be sent back to origin, not
    // to relay.
    EXPECT_EQ(pkt->getRemoteAddr(), offer->getRemoteAddr());

    MessageCheck(pkt, offer);
294 295 296 297 298

    delete srv;
}

TEST_F(Dhcpv4SrvTest, processRequest) {
299
    NakedDhcpv4Srv* srv = new NakedDhcpv4Srv(0);
Tomek Mrugalski's avatar
Tomek Mrugalski committed
300
    vector<uint8_t> mac(6);
301 302 303 304 305 306
    for (int i = 0; i < 6; i++) {
        mac[i] = i*10;
    }

    boost::shared_ptr<Pkt4> req(new Pkt4(DHCPREQUEST, 1234));
    boost::shared_ptr<Pkt4> ack;
307

308 309 310 311 312
    req->setIface("eth0");
    req->setIndex(17);
    req->setHWAddr(1, 6, mac);
    req->setRemoteAddr(IOAddress("192.0.2.56"));
    req->setGiaddr(IOAddress("192.0.2.67"));
313 314

    // should not throw
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    ASSERT_NO_THROW(
        ack = srv->processRequest(req);
    );

    // should return something
    ASSERT_TRUE(ack);

    EXPECT_EQ(DHCPACK, ack->getType());

    // this is relayed message. It should be sent back to relay address.
    EXPECT_EQ(req->getGiaddr(), ack->getRemoteAddr());

    MessageCheck(req, ack);

    // now repeat the test for directly sent message
    req->setHops(0);
    req->setGiaddr(IOAddress("0.0.0.0"));
    req->setRemotePort(DHCP4_CLIENT_PORT);

334
    EXPECT_NO_THROW(
335
        ack = srv->processDiscover(req);
336 337 338
    );

    // should return something
339 340 341 342 343 344 345 346 347
    ASSERT_TRUE(ack);

    EXPECT_EQ(DHCPOFFER, ack->getType());

    // this is direct message. It should be sent back to origin, not
    // to relay.
    EXPECT_EQ(ack->getRemoteAddr(), req->getRemoteAddr());

    MessageCheck(req, ack);
348 349 350 351 352 353 354 355 356 357 358 359 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 386 387 388 389 390 391 392 393 394 395 396 397

    delete srv;
}

TEST_F(Dhcpv4SrvTest, processRelease) {
    NakedDhcpv4Srv* srv = new NakedDhcpv4Srv();

    boost::shared_ptr<Pkt4> pkt(new Pkt4(DHCPRELEASE, 1234));

    // should not throw
    EXPECT_NO_THROW(
        srv->processRelease(pkt);
    );

    // TODO: Implement more reasonable tests before starting
    // work on processSomething() method.

    delete srv;
}

TEST_F(Dhcpv4SrvTest, processDecline) {
    NakedDhcpv4Srv* srv = new NakedDhcpv4Srv();

    boost::shared_ptr<Pkt4> pkt(new Pkt4(DHCPDECLINE, 1234));

    // should not throw
    EXPECT_NO_THROW(
        srv->processDecline(pkt);
    );

    // TODO: Implement more reasonable tests before starting
    // work on processSomething() method.
    delete srv;
}

TEST_F(Dhcpv4SrvTest, processInform) {
    NakedDhcpv4Srv* srv = new NakedDhcpv4Srv();

    boost::shared_ptr<Pkt4> pkt(new Pkt4(DHCPINFORM, 1234));

    // should not throw
    EXPECT_NO_THROW(
        srv->processInform(pkt);
    );

    // should return something
    EXPECT_TRUE(srv->processInform(pkt));

    // TODO: Implement more reasonable tests before starting
    // work on processSomething() method.
398

399
    delete srv;
400 401
}

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
TEST_F(Dhcpv4SrvTest, serverReceivedPacketName) {
    // Check all possible packet types
    for (int itype = 0; itype < 256; ++itype) {
        uint8_t type = itype;

        switch (type) {
        case DHCPDECLINE:
            EXPECT_STREQ("DECLINE", Dhcpv4Srv::serverReceivedPacketName(type));
            break;

        case DHCPDISCOVER:
            EXPECT_STREQ("DISCOVER", Dhcpv4Srv::serverReceivedPacketName(type));
            break;

        case DHCPINFORM:
            EXPECT_STREQ("INFORM", Dhcpv4Srv::serverReceivedPacketName(type));
            break;

        case DHCPRELEASE:
            EXPECT_STREQ("RELEASE", Dhcpv4Srv::serverReceivedPacketName(type));
            break;

        case DHCPREQUEST:
            EXPECT_STREQ("REQUEST", Dhcpv4Srv::serverReceivedPacketName(type));
            break;

        default:
            EXPECT_STREQ("UNKNOWN", Dhcpv4Srv::serverReceivedPacketName(type));
        }
    }
}

434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
// This test verifies that incoming DISCOVER can be handled properly, that an
// OFFER is generated, that the response has an address and that address
// really belongs to the configured pool.
//
// constructed very simple DISCOVER message with:
// - client-id option
//
// expected returned OFFER message:
// - copy of client-id
// - server-id
// - offered address
TEST_F(Dhcpv4SrvTest, DiscoverBasic) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW( srv.reset(new NakedDhcpv4Srv(0)) );

    Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
    dis->setRemoteAddr(IOAddress("192.0.2.1"));
    OptionPtr clientid = generateClientId();
    dis->addOption(clientid);

    // Pass it to the server and get an advertise
    Pkt4Ptr offer = srv->processDiscover(dis);

    // check if we get response at all
    checkResponse(offer, DHCPOFFER, 1234);

    // check that address was returned from proper range, that its lease
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(offer, subnet_);

    // check identifiers
    checkServerId(offer, srv->getServerID());
    checkClientId(offer, clientid);
}


// This test verifies that incoming DISCOVER can be handled properly, that an
// OFFER is generated, that the response has an address and that address
// really belongs to the configured pool.
//
// constructed very simple DISCOVER message with:
// - client-id option
// - address set to specific value as hint
//
// expected returned OFFER message:
// - copy of client-id
// - server-id
// - offered address
TEST_F(Dhcpv4SrvTest, DiscoverHint) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW( srv.reset(new NakedDhcpv4Srv(0)) );
    IOAddress hint("192.0.2.107");

    Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
    dis->setRemoteAddr(IOAddress("192.0.2.1"));
    OptionPtr clientid = generateClientId();
    dis->addOption(clientid);
    dis->setYiaddr(hint);

    // Pass it to the server and get an advertise
    Pkt4Ptr offer = srv->processDiscover(dis);

    // check if we get response at all
    checkResponse(offer, DHCPOFFER, 1234);

    // check that address was returned from proper range, that its lease
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(offer, subnet_);

    EXPECT_EQ(offer->getYiaddr().toText(), hint.toText());

    // check identifiers
    checkServerId(offer, srv->getServerID());
    checkClientId(offer, clientid);
}


// This test verifies that incoming DISCOVER can be handled properly, that an
// OFFER is generated, that the response has an address and that address
// really belongs to the configured pool.
//
// constructed very simple DISCOVER message with:
// - address set to specific value as hint
//
// expected returned OFFER message:
// - copy of client-id
// - server-id
// - offered address
TEST_F(Dhcpv4SrvTest, DiscoverNoClientId) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW( srv.reset(new NakedDhcpv4Srv(0)) );
    IOAddress hint("192.0.2.107");

    Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
    dis->setRemoteAddr(IOAddress("192.0.2.1"));
    dis->setYiaddr(hint);

    // Pass it to the server and get an advertise
    Pkt4Ptr offer = srv->processDiscover(dis);

    // check if we get response at all
    checkResponse(offer, DHCPOFFER, 1234);

    // check that address was returned from proper range, that its lease
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(offer, subnet_);

    EXPECT_EQ(offer->getYiaddr().toText(), hint.toText());

    // check identifiers
    checkServerId(offer, srv->getServerID());
}

// This test verifies that incoming DISCOVER can be handled properly, that an
// OFFER is generated, that the response has an address and that address
// really belongs to the configured pool.
//
// constructed very simple DISCOVER message with:
// - client-id option
// - address set to specific value as hint, but that hint is invalid
//
// expected returned OFFER message:
// - copy of client-id
// - server-id
// - offered address (!= hint)
TEST_F(Dhcpv4SrvTest, DiscoverInvalidHint) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW( srv.reset(new NakedDhcpv4Srv(0)) );
    IOAddress hint("10.1.2.3");

    Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
    dis->setRemoteAddr(IOAddress("192.0.2.107"));
    OptionPtr clientid = generateClientId();
    dis->addOption(clientid);
    dis->setYiaddr(hint);

    // Pass it to the server and get an advertise
    Pkt4Ptr offer = srv->processDiscover(dis);

    // check if we get response at all
    checkResponse(offer, DHCPOFFER, 1234);

    // check that address was returned from proper range, that its lease
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(offer, subnet_);

    EXPECT_NE(offer->getYiaddr().toText(), hint.toText());

    // check identifiers
    checkServerId(offer, srv->getServerID());
    checkClientId(offer, clientid);
}

/// @todo: Add a test that client sends hint that is in pool, but currently
/// being used by a different client.

// This test checks that the server is offering different addresses to different
// clients in ADVERTISEs. Please note that ADVERTISE is not a guarantee that such
// and address will be assigned. Had the pool was very small and contained only
// 2 addresses, the third client would get the same advertise as the first one
// and this is a correct behavior. It is REQUEST that will fail for the third
// client. ADVERTISE is basically saying "if you send me a request, you will
// probably get an address like this" (there are no guarantees).
TEST_F(Dhcpv4SrvTest, ManyDiscovers) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW( srv.reset(new NakedDhcpv4Srv(0)) );

    Pkt4Ptr dis1 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
    Pkt4Ptr dis2 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 2345));
    Pkt4Ptr dis3 = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 3456));

    dis1->setRemoteAddr(IOAddress("192.0.2.1"));
    dis2->setRemoteAddr(IOAddress("192.0.2.2"));
    dis3->setRemoteAddr(IOAddress("192.0.2.3"));

    // different client-id sizes
    OptionPtr clientid1 = generateClientId(4); // length 4
    OptionPtr clientid2 = generateClientId(5); // length 5
    OptionPtr clientid3 = generateClientId(6); // length 6

    dis1->addOption(clientid1);
    dis2->addOption(clientid2);
    dis3->addOption(clientid3);

    // Pass it to the server and get an advertise
    Pkt4Ptr reply1 = srv->processDiscover(dis1);
    Pkt4Ptr reply2 = srv->processDiscover(dis2);
    Pkt4Ptr reply3 = srv->processDiscover(dis3);

    // check if we get response at all
    checkResponse(reply1, DHCPOFFER, 1234);
    checkResponse(reply2, DHCPOFFER, 2345);
    checkResponse(reply3, DHCPOFFER, 3456);

    IOAddress addr1 = reply1->getYiaddr();
    IOAddress addr2 = reply2->getYiaddr();
    IOAddress addr3 = reply3->getYiaddr();

    // Check that the assigned address is indeed from the configured pool
    checkAddressParams(reply1, subnet_);
    checkAddressParams(reply2, subnet_);
    checkAddressParams(reply3, subnet_);

    // check DUIDs
    checkServerId(reply1, srv->getServerID());
    checkServerId(reply2, srv->getServerID());
    checkServerId(reply3, srv->getServerID());
    checkClientId(reply1, clientid1);
    checkClientId(reply2, clientid2);
    checkClientId(reply3, clientid3);

    // Finally check that the addresses offered are different
    EXPECT_NE(addr1.toText(), addr2.toText());
    EXPECT_NE(addr2.toText(), addr3.toText());
    EXPECT_NE(addr3.toText(), addr1.toText());
    cout << "Offered address to client1=" << addr1.toText() << endl;
    cout << "Offered address to client2=" << addr2.toText() << endl;
    cout << "Offered address to client3=" << addr3.toText() << endl;
}

// This test verifies that incoming DISCOVER can be handled properly, that an
// OFFER is generated, that the response has an address and that address
// really belongs to the configured pool.
//
// constructed very simple DISCOVER message with:
// - client-id option
//
// expected returned OFFER message:
// - copy of client-id
// - server-id
// - offered address
TEST_F(Dhcpv4SrvTest, RequestBasic) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW( srv.reset(new NakedDhcpv4Srv(0)) );

    IOAddress hint("192.0.2.107");
    Pkt4Ptr req = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234));
    req->setRemoteAddr(IOAddress("192.0.2.1"));
    OptionPtr clientid = generateClientId();
    req->addOption(clientid);
    req->setYiaddr(hint);

    // Pass it to the server and get an advertise
    Pkt4Ptr ack = srv->processRequest(req);

    // check if we get response at all
    checkResponse(ack, DHCPACK, 1234);
    EXPECT_EQ(hint.toText(), ack->getYiaddr().toText());

    // check that address was returned from proper range, that its lease
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(ack, subnet_);

    // check identifiers
    checkServerId(ack, srv->getServerID());
    checkClientId(ack, clientid);

    // check that the lease is really in the database
    Lease4Ptr l = checkLease(ack, clientid, req->getHWAddr(), hint);

    ASSERT_TRUE(l);
    LeaseMgrFactory::instance().deleteLease(l->addr_);
}

// This test verifies that incoming (positive) RENEW can be handled properly, that a
// REPLY is generated, that the response has an address and that address
// really belongs to the configured pool and that lease is actually renewed.
//
// expected:
// - returned REPLY message has copy of client-id
// - returned REPLY message has server-id
// - returned REPLY message has IA that includes IAADDR
// - lease is actually renewed in LeaseMgr
TEST_F(Dhcpv4SrvTest, RenewBasic) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW( srv.reset(new NakedDhcpv4Srv(0)) );

    const IOAddress addr("192.0.2.106");
712 713 714 715
    const uint32_t temp_t1 = 50;
    const uint32_t temp_t2 = 75;
    const uint32_t temp_valid = 100;
    const time_t temp_timestamp = time(NULL) - 10;
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 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 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812

    // Generate client-id also duid_
    OptionPtr clientid = generateClientId();

    // Check that the address we are about to use is indeed in pool
    ASSERT_TRUE(subnet_->inPool(addr));

    // let's create a lease and put it in the LeaseMgr
    uint8_t hwaddr2[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
    uint8_t clientid2[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
    Lease4Ptr used(new Lease4(IOAddress("192.0.2.106"), hwaddr2, sizeof(hwaddr2),
                              &client_id_->getDuid()[0], client_id_->getDuid().size(),
                              temp_valid, temp_t1, temp_t2, temp_timestamp,
                              subnet_->getID()));
    ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));

    // Check that the lease is really in the database
    Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
    ASSERT_TRUE(l);

    // Check that T1, T2, preferred, valid and cltt really set.
    // Constructed lease looks as if it was assigned 10 seconds ago
    // EXPECT_EQ(l->t1_, temp_t1);
    // EXPECT_EQ(l->t2_, temp_t2);
    EXPECT_EQ(l->valid_lft_, temp_valid);
    EXPECT_EQ(l->cltt_, temp_timestamp);

    // Let's create a RENEW
    Pkt4Ptr req = Pkt4Ptr(new Pkt4(DHCPREQUEST, 1234));
    req->setRemoteAddr(IOAddress(addr));
    req->setYiaddr(addr);

    req->addOption(clientid);
    req->addOption(srv->getServerID());

    // Pass it to the server and hope for a REPLY
    Pkt4Ptr ack = srv->processRequest(req);

    // Check if we get response at all
    checkResponse(ack, DHCPACK, 1234);
    EXPECT_EQ(addr.toText(), ack->getYiaddr().toText());

    // check that address was returned from proper range, that its lease
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(ack, subnet_);

    // Check identifiers
    checkServerId(ack, srv->getServerID());
    checkClientId(ack, clientid);

    // Check that the lease is really in the database
    l = checkLease(ack, clientid, req->getHWAddr(), addr);
    ASSERT_TRUE(l);

    // Check that T1, T2, preferred, valid and cltt were really updated
    EXPECT_EQ(l->t1_, subnet_->getT1());
    EXPECT_EQ(l->t2_, subnet_->getT2());
    EXPECT_EQ(l->valid_lft_, subnet_->getValid());

    // Checking for CLTT is a bit tricky if we want to avoid off by 1 errors
    int32_t cltt = static_cast<int32_t>(l->cltt_);
    int32_t expected = static_cast<int32_t>(time(NULL));
    // equality or difference by 1 between cltt and expected is ok.
    EXPECT_GE(1, abs(cltt - expected));

    EXPECT_TRUE(LeaseMgrFactory::instance().deleteLease(addr));
}

// @todo: Implement tests for rejecting renewals

// This test verifies if the sanityCheck() really checks options presence.
TEST_F(Dhcpv4SrvTest, sanityCheck) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW( srv.reset(new NakedDhcpv4Srv(0)) );

    Pkt4Ptr pkt = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));

    // check that the packets originating from local addresses can be
    pkt->setRemoteAddr(IOAddress("192.0.2.1"));

    // client-id is optional for information-request, so
    EXPECT_NO_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::OPTIONAL));

    // empty packet, no server-id
    EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::MANDATORY), RFCViolation);

    pkt->addOption(srv->getServerID());

    // server-id is mandatory and present = no exception
    EXPECT_NO_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::MANDATORY));

    // server-id is forbidden, but present => exception
    EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::FORBIDDEN),
                 RFCViolation);
}

// @todo: write tests for RELEASE
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 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 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
// This test verifies that incoming (positive) RELEASE can be handled properly,
// that a REPLY is generated, that the response has status code and that the
// lease is indeed removed from the database.
//
// expected:
// - returned REPLY message has copy of client-id
// - returned REPLY message has server-id
// - returned REPLY message has IA that does not include an IAADDR
// - lease is actually removed from LeaseMgr
TEST_F(Dhcpv4SrvTest, ReleaseBasic) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW( srv.reset(new NakedDhcpv4Srv(0)) );

    const IOAddress addr("192.0.2.106");
    const uint32_t temp_t1 = 50;
    const uint32_t temp_t2 = 75;
    const uint32_t temp_valid = 100;
    const time_t temp_timestamp = time(NULL) - 10;

    // Generate client-id also duid_
    OptionPtr clientid = generateClientId();

    // Check that the address we are about to use is indeed in pool
    ASSERT_TRUE(subnet_->inPool(addr));

    // let's create a lease and put it in the LeaseMgr
    uint8_t mac_addr[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
    HWAddrPtr hw(new HWAddr(mac_addr, sizeof(mac_addr), HTYPE_ETHER));
    Lease4Ptr used(new Lease4(addr, mac_addr, sizeof(mac_addr),
                              &client_id_->getDuid()[0], client_id_->getDuid().size(),
                              temp_valid, temp_t1, temp_t2, temp_timestamp,
                              subnet_->getID()));
    ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));

    // Check that the lease is really in the database
    Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
    ASSERT_TRUE(l);

    // Let's create a RELEASE
    // Generate client-id also duid_
    Pkt4Ptr rel = Pkt4Ptr(new Pkt4(DHCPRELEASE, 1234));
    rel->setRemoteAddr(addr);
    rel->setYiaddr(addr);
    rel->addOption(clientid);
    rel->addOption(srv->getServerID());
    rel->setHWAddr(hw);

    // Pass it to the server and hope for a REPLY
    // Note: this is no response to RELEASE in DHCPv4
    EXPECT_NO_THROW(srv->processRelease(rel));

    // The lease should be gone from LeaseMgr
    l = LeaseMgrFactory::instance().getLease4(addr);
    EXPECT_FALSE(l);

    // Try to get the lease by hardware address
    // @todo: Uncomment this once trac2592 is implemented
    // Lease4Collection leases = LeaseMgrFactory::instance().getLease4(hw->hwaddr_);
    // EXPECT_EQ(leases.size(), 0);

    // Try to get it by hw/subnet_id compination
    l = LeaseMgrFactory::instance().getLease4(hw->hwaddr_, subnet_->getID());
    EXPECT_FALSE(l);

    // Try by client-id
    // @todo: Uncomment this once trac2592 is implemented
    //Lease4Collection leases = LeaseMgrFactory::instance().getLease4(*client_id_);
    //EXPECT_EQ(leases.size(), 0);

    // Try by client-id/subnet-id
    l = LeaseMgrFactory::instance().getLease4(*client_id_, subnet_->getID());
    EXPECT_FALSE(l);

    // Ok, the lease is *really* not there.
}

// This test verifies that incoming (invalid) RELEASE can be handled properly.
//
// This test checks 3 scenarios:
// 1. there is no such lease at all
// 2. there is such a lease, but it is assigned to a different IAID
// 3. there is such a lease, but it belongs to a different client
//
// expected:
// - returned REPLY message has copy of client-id
// - returned REPLY message has server-id
// - returned REPLY message has IA that includes STATUS-CODE
// - No lease in LeaseMgr
TEST_F(Dhcpv4SrvTest, ReleaseReject) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW( srv.reset(new NakedDhcpv4Srv(0)) );

    const IOAddress addr("192.0.2.106");
    const uint32_t t1 = 50;
    const uint32_t t2 = 75;
    const uint32_t valid = 100;
    const time_t timestamp = time(NULL) - 10;

    // let's create a lease and put it in the LeaseMgr
    uint8_t bogus_mac_addr[] = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
    HWAddrPtr bogus_hw(new HWAddr(bogus_mac_addr, sizeof(bogus_mac_addr), HTYPE_ETHER));
    OptionPtr bogus_clientid = generateClientId(7); // different length

    // Generate client-id also duid_
    OptionPtr clientid = generateClientId();

    // Check that the address we are about to use is indeed in pool
    ASSERT_TRUE(subnet_->inPool(addr));

    // Let's create a RELEASE
    // Generate client-id also duid_
    Pkt4Ptr rel = Pkt4Ptr(new Pkt4(DHCPRELEASE, 1234));
    rel->setRemoteAddr(addr);
    rel->setYiaddr(addr);
    rel->addOption(clientid);
    rel->addOption(srv->getServerID());
    rel->setHWAddr(bogus_hw);

    // Case 1: No lease known to server
    SCOPED_TRACE("CASE 1: Lease is not known to the server");

    // There is nothing to check here. The lease is not there and server does
    // not send anything back. This case is enumerated here just for keeping
    // parity with similar test in DHCPv6.
    EXPECT_NO_THROW(srv->processRelease(rel));

    // CASE 2: Lease is known and belongs to this client, but to a different client-id
    SCOPED_TRACE("CASE 2: Lease is known and belongs to this client, but uses different HW addr");

    // Let's create a lease and put it in the LeaseMgr
    uint8_t mac_addr[] = { 0, 0x1, 0x2, 0x3, 0x4, 0x5};
    HWAddrPtr hw(new HWAddr(mac_addr, sizeof(mac_addr), HTYPE_ETHER));
    Lease4Ptr used(new Lease4(addr, mac_addr, sizeof(mac_addr),
                              &client_id_->getDuid()[0], client_id_->getDuid().size(),
                              valid, t1, t2, timestamp, subnet_->getID()));
    ASSERT_TRUE(LeaseMgrFactory::instance().addLease(used));
    // Check that the lease is really in the database
    Lease4Ptr l = LeaseMgrFactory::instance().getLease4(addr);
    ASSERT_TRUE(l);

    rel->setHWAddr(bogus_hw);

    EXPECT_NO_THROW(srv->processRelease(rel));

    // Check that the lease was not removed (due to hardware address mis-match)
    l = LeaseMgrFactory::instance().getLease4(addr);
    ASSERT_TRUE(l);

    // CASE 3: Lease belongs to a client with different client-id
    SCOPED_TRACE("CASE 3: Lease belongs to a client with different client-id");

    rel->setHWAddr(hw); // proper HW address this time
    rel->delOption(DHO_DHCP_CLIENT_IDENTIFIER);
    rel->addOption(bogus_clientid); // but invalid client-id

    OptionPtr x = rel->getOption(DHO_DHCP_CLIENT_IDENTIFIER);

    EXPECT_NO_THROW(srv->processRelease(rel));

    // Check that the lease is still there
    l = LeaseMgrFactory::instance().getLease4(addr);
    ASSERT_TRUE(l);

    // Final sanity check. Verify that with valid hw and client-id release is working
    rel->delOption(DHO_DHCP_CLIENT_IDENTIFIER);
    rel->addOption(clientid);

    EXPECT_NO_THROW(srv->processRelease(rel));

    l = LeaseMgrFactory::instance().getLease4(addr);
    EXPECT_FALSE(l);

}
986

987
} // end of anonymous namespace