dhcp4_srv_unittest.cc 46 KB
Newer Older
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1
// Copyright (C) 2011-2013  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
#include <dhcp/dhcp4.h>
20
#include <dhcp/iface_mgr.h>
21
#include <dhcp/option.h>
22
#include <dhcp/option4_addrlst.h>
23
#include <dhcp/option_custom.h>
24
#include <dhcp/option_int_array.h>
25
#include <dhcp4/dhcp4_srv.h>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
26
#include <dhcp4/dhcp4_log.h>
27 28 29 30
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/lease_mgr.h>
#include <dhcpsrv/lease_mgr_factory.h>
#include <dhcpsrv/utils.h>
31 32
#include <gtest/gtest.h>

33 34
#include <boost/scoped_ptr.hpp>

35 36 37 38
#include <fstream>
#include <iostream>

#include <arpa/inet.h>
39 40 41 42

using namespace std;
using namespace isc;
using namespace isc::dhcp;
43
using namespace isc::asiolink;
44 45 46 47

namespace {

class NakedDhcpv4Srv: public Dhcpv4Srv {
48
    // "Naked" DHCPv4 server, exposes internal fields
49
public:
50 51 52 53 54 55 56 57 58 59

    /// @brief Constructor.
    ///
    /// It disables configuration of broadcast options on
    /// sockets that are opened by the Dhcpv4Srv constructor.
    /// Setting broadcast options requires root privileges
    /// which is not the case when running unit tests.
    NakedDhcpv4Srv(uint16_t port = 0)
        : Dhcpv4Srv(port, "type=memfile", false) {
    }
60 61 62 63 64 65 66

    using Dhcpv4Srv::processDiscover;
    using Dhcpv4Srv::processRequest;
    using Dhcpv4Srv::processRelease;
    using Dhcpv4Srv::processDecline;
    using Dhcpv4Srv::processInform;
    using Dhcpv4Srv::getServerID;
67 68 69
    using Dhcpv4Srv::loadServerID;
    using Dhcpv4Srv::generateServerID;
    using Dhcpv4Srv::writeServerID;
70
    using Dhcpv4Srv::sanityCheck;
71
    using Dhcpv4Srv::srvidToString;
72 73
};

74 75
static const char* SRVID_FILE = "server-id-test.txt";

76 77
class Dhcpv4SrvTest : public ::testing::Test {
public:
78 79 80 81 82

    /// @brief Constructor
    ///
    /// Initializes common objects used in many tests.
    /// Also sets up initial configuration in CfgMgr.
83
    Dhcpv4SrvTest() {
84 85 86 87 88 89 90
        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_);
91

92 93 94 95
        // Add Router option.
        Option4AddrLstPtr opt_routers(new Option4AddrLst(DHO_ROUTERS));
        opt_routers->setAddress(IOAddress("192.0.2.2"));
        subnet_->addOption(opt_routers, false, "dhcp4");
96

97 98
        // it's ok if that fails. There should not be such a file anyway
        unlink(SRVID_FILE);
99
    }
100

101
    /// @brief Add 'Parameter Request List' option to the packet.
102
    ///
103
    /// This function PRL option comprising the following option codes:
104 105 106 107 108 109 110 111 112 113 114 115 116 117
    /// - 5 - Name Server
    /// - 15 - Domain Name
    /// - 7 - Log Server
    /// - 8 - Quotes Server
    /// - 9 - LPR Server
    ///
    /// @param pkt packet to add PRL option to.
    void addPrlOption(Pkt4Ptr& pkt) {

        OptionUint8ArrayPtr option_prl =
            OptionUint8ArrayPtr(new OptionUint8Array(Option::V4,
                                                     DHO_DHCP_PARAMETER_REQUEST_LIST));

        // Let's request options that have been configured for the subnet.
118 119 120 121
        option_prl->addValue(DHO_DOMAIN_NAME_SERVERS);
        option_prl->addValue(DHO_DOMAIN_NAME);
        option_prl->addValue(DHO_LOG_SERVERS);
        option_prl->addValue(DHO_COOKIE_SERVERS);
122 123
        // Let's also request the option that hasn't been configured. In such
        // case server should ignore request for this particular option.
124
        option_prl->addValue(DHO_LPR_SERVERS);
125 126 127 128 129 130
        // And add 'Parameter Request List' option into the DISCOVER packet.
        pkt->addOption(option_prl);
    }

    /// @brief Configures options being requested in the PRL option.
    ///
131
    /// The lpr-servers option is NOT configured here although it is
132 133
    /// added to the 'Parameter Request List' option in the
    /// \ref addPrlOption. When requested option is not configured
134
    /// the server should not return it in its response. The goal
135 136 137 138 139 140 141 142 143 144 145 146
    /// of not configuring the requested option is to verify that
    /// the server will not return it.
    void configureRequestedOptions() {
        // dns-servers
        Option4AddrLstPtr
            option_dns_servers(new Option4AddrLst(DHO_DOMAIN_NAME_SERVERS));
        option_dns_servers->addAddress(IOAddress("192.0.2.1"));
        option_dns_servers->addAddress(IOAddress("192.0.2.100"));
        ASSERT_NO_THROW(subnet_->addOption(option_dns_servers, false, "dhcp4"));

        // domain-name
        OptionDefinition def("domain-name", DHO_DOMAIN_NAME, OPT_FQDN_TYPE);
147
        OptionCustomPtr option_domain_name(new OptionCustom(def, Option::V4));
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
        option_domain_name->writeFqdn("example.com");
        subnet_->addOption(option_domain_name, false, "dhcp4");

        // log-servers
        Option4AddrLstPtr option_log_servers(new Option4AddrLst(DHO_LOG_SERVERS));
        option_log_servers->addAddress(IOAddress("192.0.2.2"));
        option_log_servers->addAddress(IOAddress("192.0.2.10"));
        ASSERT_NO_THROW(subnet_->addOption(option_log_servers, false, "dhcp4"));

        // cookie-servers
        Option4AddrLstPtr option_cookie_servers(new Option4AddrLst(DHO_COOKIE_SERVERS));
        option_cookie_servers->addAddress(IOAddress("192.0.2.1"));
        ASSERT_NO_THROW(subnet_->addOption(option_cookie_servers, false, "dhcp4"));
    }

163 164 165
    /// @brief checks that the response matches request
    /// @param q query (client's message)
    /// @param a answer (server's message)
166
    void messageCheck(const Pkt4Ptr& q, const Pkt4Ptr& a) {
167 168 169 170 171 172 173 174
        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());

175 176 177
        // Check that bare minimum of required options are there.
        // We don't check options requested by a client. Those
        // are checked elsewhere.
178 179 180 181 182
        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));
183 184
        EXPECT_TRUE(a->getOption(DHO_DOMAIN_NAME));
        EXPECT_TRUE(a->getOption(DHO_DOMAIN_NAME_SERVERS));
185

186
        // Check that something is offered
187 188 189
        EXPECT_TRUE(a->getYiaddr().toText() != "0.0.0.0");
    }

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    /// @brief Check that requested options are present.
    ///
    /// @param pkt packet to be checked.
    void optionsCheck(const Pkt4Ptr& pkt) {
        // Check that the requested and configured options are returned
        // in the ACK message.
        EXPECT_TRUE(pkt->getOption(DHO_DOMAIN_NAME))
            << "domain-name not present in the response";
        EXPECT_TRUE(pkt->getOption(DHO_DOMAIN_NAME_SERVERS))
            << "dns-servers not present in the response";
        EXPECT_TRUE(pkt->getOption(DHO_LOG_SERVERS))
            << "log-servers not present in the response";
        EXPECT_TRUE(pkt->getOption(DHO_COOKIE_SERVERS))
            << "cookie-servers not present in the response";
        // Check that the requested but not configured options are not
        // returned in the ACK message.
        EXPECT_FALSE(pkt->getOption(DHO_LPR_SERVERS))
            << "domain-name present in the response but it is"
            << " expected not to be present";
    }

211 212 213 214 215 216 217 218
    /// @brief generates client-id option
    ///
    /// Generate client-id option of specified length
    /// Ids with different lengths are sufficent to generate
    /// unique ids. If more fine grained control is required,
    /// tests generate client-ids on their own.
    /// Sets client_id_ field.
    /// @param size size of the client-id to be generated
219 220 221 222 223 224 225 226 227 228 229 230 231 232
    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)));
    }

233 234 235 236
    /// @brief generate hardware address
    ///
    /// @param size size of the generated MAC address
    /// @param pointer to Hardware Address object
Tomek Mrugalski's avatar
Tomek Mrugalski committed
237
    HWAddrPtr generateHWAddr(size_t size = 6) {
238
        const uint8_t hw_type = 123; // Just a fake number (typically 6=HTYPE_ETHER, see dhcp4.h)
Tomek Mrugalski's avatar
Tomek Mrugalski committed
239 240 241 242 243 244 245
        OptionBuffer mac(size);
        for (int i = 0; i < size; ++i) {
            mac[i] = 50 + i;
        }
        return (HWAddrPtr(new HWAddr(mac, hw_type)));
    }

246 247 248
    /// Check that address was returned from proper range, that its lease
    /// lifetime is correct, that T1 and T2 are returned properly
    /// @param rsp response to be checked
249 250
    /// @param subnet subnet that should be used to verify assigned address
    ///        and options
251 252
    /// @param t1_mandatory is T1 mandatory?
    /// @param t2_mandatory is T2 mandatory?
253
    void checkAddressParams(const Pkt4Ptr& rsp, const SubnetPtr subnet,
254 255
                            bool t1_mandatory = false,
                            bool t2_mandatory = false) {
256 257 258 259 260 261 262

        // 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
263 264
        OptionPtr opt = rsp->getOption(DHO_DHCP_LEASE_TIME);
        if (!opt) {
265 266
            ADD_FAILURE() << "Lease time option missing in response";
        } else {
267
            EXPECT_EQ(opt->getUint32(), subnet->getValid());
268 269 270
        }

        // Check T1 timer
271 272 273
        opt = rsp->getOption(DHO_DHCP_RENEWAL_TIME);
        if (opt) {
            EXPECT_EQ(opt->getUint32(), subnet->getT1());
274 275 276 277 278 279 280
        } else {
            if (t1_mandatory) {
                ADD_FAILURE() << "Required T1 option missing";
            }
        }

        // Check T2 timer
281 282 283
        opt = rsp->getOption(DHO_DHCP_REBINDING_TIME);
        if (opt) {
            EXPECT_EQ(opt->getUint32(), subnet->getT2());
284
        } else {
285
            if (t2_mandatory) {
286 287 288 289 290
                ADD_FAILURE() << "Required T2 option missing";
            }
        }
    }

291 292 293 294 295
    /// @brief Basic checks for generated response (message type and trans-id).
    ///
    /// @param rsp response packet to be validated
    /// @param expected_message_type expected message type
    /// @param expected_transid expected transaction-id
296 297 298 299 300 301 302
    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());
    }

303 304 305 306 307 308
    /// @brief Checks if the lease sent to client is present in the database
    ///
    /// @param rsp response packet to be validated
    /// @param client_id expected client-identifier (or NULL)
    /// @param HWAddr expected hardware address (not used now)
    /// @param expected_addr expected address
309
    Lease4Ptr checkLease(const Pkt4Ptr& rsp, const OptionPtr& client_id,
310
                         const HWAddrPtr&, const IOAddress& expected_addr) {
311 312 313 314 315 316 317 318 319 320 321 322 323 324

        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());
        }

325 326
        EXPECT_EQ(rsp->getYiaddr().toText(), expected_addr.toText());

327 328 329 330 331 332 333 334 335
        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);
    }

336 337 338
    /// @brief Checks if server response (OFFER, ACK, NAK) includes proper server-id
    /// @param rsp response packet to be validated
    /// @param expected_srvid expected value of server-id
339
    void checkServerId(const Pkt4Ptr& rsp, const OptionPtr& expected_srvid) {
340 341 342 343 344 345
        // Check that server included its server-id
        OptionPtr opt = rsp->getOption(DHO_DHCP_SERVER_IDENTIFIER);
        ASSERT_TRUE(opt);
        EXPECT_EQ(opt->getType(), expected_srvid->getType() );
        EXPECT_EQ(opt->len(), expected_srvid->len() );
        EXPECT_TRUE(opt->getData() == expected_srvid->getData());
346 347
    }

348 349 350
    /// @brief Checks if server response (OFFER, ACK, NAK) includes proper client-id
    /// @param rsp response packet to be validated
    /// @param expected_clientid expected value of client-id
351 352
    void checkClientId(const Pkt4Ptr& rsp, const OptionPtr& expected_clientid) {
        // check that server included our own client-id
353 354 355 356 357
        OptionPtr opt = rsp->getOption(DHO_DHCP_CLIENT_IDENTIFIER);
        ASSERT_TRUE(opt);
        EXPECT_EQ(expected_clientid->getType(), opt->getType());
        EXPECT_EQ(expected_clientid->len(), opt->len());
        EXPECT_TRUE(expected_clientid->getData() == opt->getData());
358 359
    }

360 361 362 363 364 365 366 367 368
    /// @brief Tests if Discover or Request message is processed correctly
    ///
    /// @param msg_type DHCPDISCOVER or DHCPREQUEST
    /// @param client_addr client address
    /// @param relay_addr relay address
    void testDiscoverRequest(const uint8_t msg_type,
                             const IOAddress& client_addr,
                             const IOAddress& relay_addr) {

369
        boost::scoped_ptr<NakedDhcpv4Srv> srv(new NakedDhcpv4Srv(0));
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 398 399 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 434 435 436 437 438 439 440 441 442 443 444
        vector<uint8_t> mac(6);
        for (int i = 0; i < 6; i++) {
            mac[i] = i*10;
        }

        boost::shared_ptr<Pkt4> req(new Pkt4(msg_type, 1234));
        boost::shared_ptr<Pkt4> rsp;

        req->setIface("eth0");
        req->setIndex(17);
        req->setHWAddr(1, 6, mac);
        req->setRemoteAddr(IOAddress(client_addr));
        req->setGiaddr(relay_addr);

        // We are going to test that certain options are returned
        // in the response message when requested using 'Parameter
        // Request List' option. Let's configure those options that
        // are returned when requested.
        configureRequestedOptions();

        if (msg_type == DHCPDISCOVER) {
            ASSERT_NO_THROW(
                rsp = srv->processDiscover(req);
            );

            // Should return OFFER
            ASSERT_TRUE(rsp);
            EXPECT_EQ(DHCPOFFER, rsp->getType());

        } else {
            ASSERT_NO_THROW(
                rsp = srv->processRequest(req);
            );

            // Should return ACK
            ASSERT_TRUE(rsp);
            EXPECT_EQ(DHCPACK, rsp->getType());

        }

        if (relay_addr.toText() != "0.0.0.0") {
            // This is relayed message. It should be sent brsp to relay address.
            EXPECT_EQ(req->getGiaddr().toText(),
                      rsp->getRemoteAddr().toText());

        } else if (client_addr.toText() != "0.0.0.0") {
            // This is a message from a client having an IP address.
            EXPECT_EQ(req->getRemoteAddr().toText(),
                      rsp->getRemoteAddr().toText());

        } else {
            // This is a message from a client having no IP address yet.
            // If IfaceMgr supports direct traffic the response should
            // be sent to the new address assigned to the client.
            if (IfaceMgr::instance().isDirectResponseSupported()) {
                EXPECT_EQ(rsp->getYiaddr(),
                          rsp->getRemoteAddr().toText());

            // If direct response to the client having no IP address is
            // not supported, response should go to broadcast.
            } else {
                EXPECT_EQ("255.255.255.255", rsp->getRemoteAddr().toText());

            }

        }

        messageCheck(req, rsp);

        // We did not request any options so these should not be present
        // in the RSP.
        EXPECT_FALSE(rsp->getOption(DHO_LOG_SERVERS));
        EXPECT_FALSE(rsp->getOption(DHO_COOKIE_SERVERS));
        EXPECT_FALSE(rsp->getOption(DHO_LPR_SERVERS));

445
        // Repeat the test but request some options.
446 447 448
        // Add 'Parameter Request List' option.
        addPrlOption(req);

449 450 451 452
        if (msg_type == DHCPDISCOVER) {
            ASSERT_NO_THROW(
                rsp = srv->processDiscover(req);
            );
453

454 455 456
            // Should return non-NULL packet.
            ASSERT_TRUE(rsp);
            EXPECT_EQ(DHCPOFFER, rsp->getType());
457

458 459 460 461 462 463 464 465 466 467
        } else {
            ASSERT_NO_THROW(
                rsp = srv->processRequest(req);
            );

            // Should return non-NULL packet.
            ASSERT_TRUE(rsp);
            EXPECT_EQ(DHCPACK, rsp->getType());

        }
468 469 470

        // Check that the requested options are returned.
        optionsCheck(rsp);
471

472 473
    }

474
    ~Dhcpv4SrvTest() {
475
        CfgMgr::instance().deleteSubnets4();
476 477 478

        // Let's clean up if there is such a file.
        unlink(SRVID_FILE);
479
    };
480

481
    /// @brief A subnet used in most tests
482 483
    Subnet4Ptr subnet_;

484
    /// @brief A pool used in most tests
485 486
    Pool4Ptr pool_;

487
    /// @brief A client-id used in most tests
488
    ClientIdPtr client_id_;
489 490
};

Tomek Mrugalski's avatar
Tomek Mrugalski committed
491 492
// Sanity check. Verifies that both Dhcpv4Srv and its derived
// class NakedDhcpv4Srv can be instantiated and destroyed.
493 494
TEST_F(Dhcpv4SrvTest, basic) {

495
    // Check that the base class can be instantiated
496 497 498
    boost::scoped_ptr<Dhcpv4Srv> srv;
    ASSERT_NO_THROW(srv.reset(new Dhcpv4Srv(DHCP4_SERVER_PORT + 10000)));
    srv.reset();
499

500
    // Check that the derived class can be instantiated
501 502 503
    boost::scoped_ptr<NakedDhcpv4Srv> naked_srv;
    ASSERT_NO_THROW(
            naked_srv.reset(new NakedDhcpv4Srv(DHCP4_SERVER_PORT + 10000)));
504 505
    EXPECT_TRUE(naked_srv->getServerID());

506
    ASSERT_NO_THROW(naked_srv.reset(new NakedDhcpv4Srv(0)));
507
    EXPECT_TRUE(naked_srv->getServerID());
508 509
}

510
// Verifies that DISCOVER received via relay can be processed correctly,
Tomek Mrugalski's avatar
Tomek Mrugalski committed
511 512 513 514 515 516 517
// that the OFFER message generated in response is valid and
// contains necessary options.
//
// Note: this test focuses on the packet correctness. There
// are other tests that verify correctness of the allocation
// engine. See DiscoverBasic, DiscoverHint, DiscoverNoClientId
// and DiscoverInvalidHint.
518
TEST_F(Dhcpv4SrvTest, processDiscoverRelay) {
Marcin Siodelski's avatar
Marcin Siodelski committed
519 520 521
    testDiscoverRequest(DHCPDISCOVER,
                        IOAddress("192.0.2.56"),
                        IOAddress("192.0.2.67"));
522
}
523

524 525 526
// Verifies that the non-relayed DISCOVER is processed correctly when
// client source address is specified.
TEST_F(Dhcpv4SrvTest, processDiscoverNoRelay) {
Marcin Siodelski's avatar
Marcin Siodelski committed
527 528 529
    testDiscoverRequest(DHCPDISCOVER,
                        IOAddress("0.0.0.0"),
                        IOAddress("192.0.2.67"));
530
}
531

532 533 534
// Verified that the non-relayed DISCOVER is processed correctly when
// client source address is not specified.
TEST_F(Dhcpv4SrvTest, processDiscoverNoClientAddr) {
Marcin Siodelski's avatar
Marcin Siodelski committed
535 536 537
    testDiscoverRequest(DHCPDISCOVER,
                        IOAddress("0.0.0.0"),
                        IOAddress("0.0.0.0"));
538 539
}

540 541
// Verifies that REQUEST received via relay can be processed correctly,
// that the OFFER message generated in response is valid and
Tomek Mrugalski's avatar
Tomek Mrugalski committed
542 543 544 545
// contains necessary options.
//
// Note: this test focuses on the packet correctness. There
// are other tests that verify correctness of the allocation
546 547 548
// engine. See DiscoverBasic, DiscoverHint, DiscoverNoClientId
// and DiscoverInvalidHint.
TEST_F(Dhcpv4SrvTest, processRequestRelay) {
Marcin Siodelski's avatar
Marcin Siodelski committed
549 550 551
    testDiscoverRequest(DHCPREQUEST,
                        IOAddress("192.0.2.56"),
                        IOAddress("192.0.2.67"));
552
}
553

554 555 556
// Verifies that the non-relayed REQUEST is processed correctly when
// client source address is specified.
TEST_F(Dhcpv4SrvTest, processRequestNoRelay) {
Marcin Siodelski's avatar
Marcin Siodelski committed
557 558 559
    testDiscoverRequest(DHCPREQUEST,
                        IOAddress("0.0.0.0"),
                        IOAddress("192.0.2.67"));
560
}
561

562 563 564
// Verified that the non-relayed REQUEST is processed correctly when
// client source address is not specified.
TEST_F(Dhcpv4SrvTest, processRequestNoClientAddr) {
Marcin Siodelski's avatar
Marcin Siodelski committed
565 566 567
    testDiscoverRequest(DHCPREQUEST,
                        IOAddress("0.0.0.0"),
                        IOAddress("0.0.0.0"));
568 569 570
}

TEST_F(Dhcpv4SrvTest, processRelease) {
571
    NakedDhcpv4Srv srv;
572
    Pkt4Ptr pkt(new Pkt4(DHCPRELEASE, 1234));
573

574
    // Should not throw
575
    EXPECT_NO_THROW(srv.processRelease(pkt));
576 577 578
}

TEST_F(Dhcpv4SrvTest, processDecline) {
579
    NakedDhcpv4Srv srv;
580
    Pkt4Ptr pkt(new Pkt4(DHCPDECLINE, 1234));
581

582
    // Should not throw
583
    EXPECT_NO_THROW(srv.processDecline(pkt));
584 585 586
}

TEST_F(Dhcpv4SrvTest, processInform) {
587
    NakedDhcpv4Srv srv;
588
    Pkt4Ptr pkt(new Pkt4(DHCPINFORM, 1234));
589

590
    // Should not throw
591
    EXPECT_NO_THROW(srv.processInform(pkt));
592

593
    // Should return something
594
    EXPECT_TRUE(srv.processInform(pkt));
595

596
    // @todo Implement more reasonable tests before starting
597
    // work on processSomething() method.
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
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));
        }
    }
}

632 633 634 635 636 637 638 639 640 641 642 643 644
// 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;
645
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
646 647 648 649 650 651

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

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

655
    // Check if we get response at all
656 657
    checkResponse(offer, DHCPOFFER, 1234);

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

662
    // Check identifiers
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
    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;
682
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
683 684 685 686 687 688 689 690
    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);

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

694
    // Check if we get response at all
695 696
    checkResponse(offer, DHCPOFFER, 1234);

697
    // Check that address was returned from proper range, that its lease
698 699 700 701 702
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(offer, subnet_);

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

703
    // Check identifiers
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
    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;
722
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
723 724 725 726 727 728
    IOAddress hint("192.0.2.107");

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

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

732
    // Check if we get response at all
733 734
    checkResponse(offer, DHCPOFFER, 1234);

735
    // Check that address was returned from proper range, that its lease
736 737 738 739 740
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(offer, subnet_);

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

741
    // Check identifiers
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
    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;
759
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
760 761 762 763 764 765 766 767
    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);

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

771
    // Check if we get response at all
772 773
    checkResponse(offer, DHCPOFFER, 1234);

774
    // Check that address was returned from proper range, that its lease
775 776 777 778 779
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(offer, subnet_);

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

780
    // Check identifiers
781 782 783 784 785 786 787 788
    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
Tomek Mrugalski's avatar
Tomek Mrugalski committed
789 790
// clients in OFFERs. Please note that OFFER is not a guarantee that such
// an address will be assigned. Had the pool was very small and contained only
791
// 2 addresses, the third client would get the same offer as the first one
792
// and this is a correct behavior. It is REQUEST that will fail for the third
Tomek Mrugalski's avatar
Tomek Mrugalski committed
793
// client. OFFER is basically saying "if you send me a request, you will
794 795 796
// probably get an address like this" (there are no guarantees).
TEST_F(Dhcpv4SrvTest, ManyDiscovers) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
797
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
798 799 800 801 802 803 804 805 806

    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"));

807
    // Different client-id sizes
808 809 810 811 812 813 814 815
    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);

816 817 818 819
    // Pass it to the server and get an offer
    Pkt4Ptr offer1 = srv->processDiscover(dis1);
    Pkt4Ptr offer2 = srv->processDiscover(dis2);
    Pkt4Ptr offer3 = srv->processDiscover(dis3);
820

821 822 823 824
    // Check if we get response at all
    checkResponse(offer1, DHCPOFFER, 1234);
    checkResponse(offer2, DHCPOFFER, 2345);
    checkResponse(offer3, DHCPOFFER, 3456);
825

826 827 828
    IOAddress addr1 = offer1->getYiaddr();
    IOAddress addr2 = offer2->getYiaddr();
    IOAddress addr3 = offer3->getYiaddr();
829 830

    // Check that the assigned address is indeed from the configured pool
831 832 833 834
    checkAddressParams(offer1, subnet_);
    checkAddressParams(offer2, subnet_);
    checkAddressParams(offer3, subnet_);

835
    // Check server-ids
836 837 838 839 840 841
    checkServerId(offer1, srv->getServerID());
    checkServerId(offer2, srv->getServerID());
    checkServerId(offer3, srv->getServerID());
    checkClientId(offer1, clientid1);
    checkClientId(offer2, clientid2);
    checkClientId(offer3, clientid3);
842 843 844 845 846 847 848 849 850 851

    // 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;
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
852 853
// This test verifies that incoming REQUEST can be handled properly, that an
// ACK is generated, that the response has an address and that address
854 855
// really belongs to the configured pool.
//
Tomek Mrugalski's avatar
Tomek Mrugalski committed
856
// constructed a single REQUEST message with:
857
// - client-id option
Tomek Mrugalski's avatar
Tomek Mrugalski committed
858 859
// - hwaddr information
// - requested address (that the client received in DISCOVER/OFFER exchange)
860
//
Tomek Mrugalski's avatar
Tomek Mrugalski committed
861
// expected returned ACK message:
862 863
// - copy of client-id
// - server-id
Tomek Mrugalski's avatar
Tomek Mrugalski committed
864 865 866
// - assigned address
//
// Test verifies that the lease is actually in the database.
867 868
TEST_F(Dhcpv4SrvTest, RequestBasic) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
869
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
870 871 872 873 874 875 876 877 878 879 880

    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);

881
    // Check if we get response at all
882 883 884
    checkResponse(ack, DHCPACK, 1234);
    EXPECT_EQ(hint.toText(), ack->getYiaddr().toText());

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

889
    // Check identifiers
890 891 892
    checkServerId(ack, srv->getServerID());
    checkClientId(ack, clientid);

893
    // Check that the lease is really in the database
894 895 896 897 898 899
    Lease4Ptr l = checkLease(ack, clientid, req->getHWAddr(), hint);

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

Tomek Mrugalski's avatar
Tomek Mrugalski committed
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
// This test verifies that incoming REQUEST can be handled properly, that an
// ACK is generated, that the response has an address and that address
// really belongs to the configured pool.
//
// constructed 3 REQUEST messages with:
// - client-id option (differs between messages)
// - hwaddr information (differs between messages)
//
// expected returned ACK message:
// - copy of client-id
// - server-id
// - assigned address (different for each client)
TEST_F(Dhcpv4SrvTest, ManyRequests) {

    boost::scoped_ptr<NakedDhcpv4Srv> srv;
915
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
Tomek Mrugalski's avatar
Tomek Mrugalski committed
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937

    const IOAddress req_addr1("192.0.2.105");
    const IOAddress req_addr2("192.0.2.101");
    const IOAddress req_addr3("192.0.2.109");
    const IOAddress relay("192.0.2.1");

    Pkt4Ptr req1 = Pkt4Ptr(new Pkt4(DHCPOFFER, 1234));
    Pkt4Ptr req2 = Pkt4Ptr(new Pkt4(DHCPOFFER, 2345));
    Pkt4Ptr req3 = Pkt4Ptr(new Pkt4(DHCPOFFER, 3456));

    req1->setRemoteAddr(relay);
    req2->setRemoteAddr(relay);
    req3->setRemoteAddr(relay);

    req1->setYiaddr(req_addr1);
    req2->setYiaddr(req_addr2);
    req3->setYiaddr(req_addr3);

    req1->setHWAddr(generateHWAddr(6));
    req2->setHWAddr(generateHWAddr(7));
    req3->setHWAddr(generateHWAddr(8));

938
    // Different client-id sizes
Tomek Mrugalski's avatar
Tomek Mrugalski committed
939 940 941 942 943 944 945 946 947 948 949 950 951
    OptionPtr clientid1 = generateClientId(4); // length 4
    OptionPtr clientid2 = generateClientId(5); // length 5
    OptionPtr clientid3 = generateClientId(6); // length 6

    req1->addOption(clientid1);
    req2->addOption(clientid2);
    req3->addOption(clientid3);

    // Pass it to the server and get an advertise
    Pkt4Ptr ack1 = srv->processRequest(req1);
    Pkt4Ptr ack2 = srv->processRequest(req2);
    Pkt4Ptr ack3 = srv->processRequest(req3);

952
    // Check if we get response at all
Tomek Mrugalski's avatar
Tomek Mrugalski committed
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
    checkResponse(ack1, DHCPACK, 1234);
    checkResponse(ack2, DHCPACK, 2345);
    checkResponse(ack3, DHCPACK, 3456);

    IOAddress addr1 = ack1->getYiaddr();
    IOAddress addr2 = ack2->getYiaddr();
    IOAddress addr3 = ack3->getYiaddr();

    // Check that every client received the address it requested
    EXPECT_EQ(req_addr1.toText(), addr1.toText());
    EXPECT_EQ(req_addr2.toText(), addr2.toText());
    EXPECT_EQ(req_addr3.toText(), addr3.toText());

    // Check that the assigned address is indeed from the configured pool
    checkAddressParams(ack1, subnet_);
    checkAddressParams(ack2, subnet_);
    checkAddressParams(ack3, subnet_);

971
    // Check DUIDs
Tomek Mrugalski's avatar
Tomek Mrugalski committed
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
    checkServerId(ack1, srv->getServerID());
    checkServerId(ack2, srv->getServerID());
    checkServerId(ack3, srv->getServerID());
    checkClientId(ack1, clientid1);
    checkClientId(ack2, clientid2);
    checkClientId(ack3, clientid3);

    // Check that leases are in the database
    Lease4Ptr l = checkLease(ack1, clientid1, req1->getHWAddr(), addr1);
    EXPECT_TRUE(l);
    l = checkLease(ack2, clientid2, req2->getHWAddr(), addr2);
    l = checkLease(ack3, clientid3, req3->getHWAddr(), addr3);

    // 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 (positive) REQUEST/Renewing can be handled properly, that a
996 997 998 999 1000 1001 1002 1003 1004 1005
// 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;
1006
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
1007 1008

    const IOAddress addr("192.0.2.106");
1009 1010 1011 1012
    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;
1013

1014
    // Generate client-id also sets client_id_ member
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    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};
    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);
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1043
    req->setCiaddr(addr); // client's address
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054

    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());

1055
    // Check that address was returned from proper range, that its lease
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
    // 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));
1075
    // Equality or difference by 1 between cltt and expected is ok.
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    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;
1086
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
1087 1088 1089

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

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

1093
    // Empty packet, no server-id
1094 1095 1096 1097
    EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::MANDATORY), RFCViolation);

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

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

1101
    // Server-id is forbidden, but present => exception
1102 1103 1104 1105
    EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::FORBIDDEN),
                 RFCViolation);
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
1106 1107 1108
// This test verifies that incoming (positive) RELEASE can be handled properly.
// As there is no REPLY in DHCPv4, the only thing to verify here is that
// the lease is indeed removed from the database.
1109 1110
TEST_F(Dhcpv4SrvTest, ReleaseBasic) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
1111
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124

    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));

1125
    // Let's create a lease and put it in the LeaseMgr
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    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