dhcp4_srv_unittest.cc 87.5 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 <config/ccsession.h>
19
#include <dhcp4/tests/dhcp4_test_utils.h>
20
#include <hooks/server_hooks.h>
21
#include <dhcpsrv/utils.h>
22 23
#include <hooks/server_hooks.h>
#include <hooks/hooks_manager.h>
24

25
#include <gtest/gtest.h>
26 27
#include <boost/scoped_ptr.hpp>

28 29 30
#include <fstream>
#include <iostream>

31 32 33
using namespace std;
using namespace isc;
using namespace isc::dhcp;
34
using namespace isc::data;
35
using namespace isc::asiolink;
36
using namespace isc::hooks;
37
using namespace isc::test;
38 39 40

namespace {

Tomek Mrugalski's avatar
Tomek Mrugalski committed
41 42
// Sanity check. Verifies that both Dhcpv4Srv and its derived
// class NakedDhcpv4Srv can be instantiated and destroyed.
43 44
TEST_F(Dhcpv4SrvTest, basic) {

45
    // Check that the base class can be instantiated
46
    boost::scoped_ptr<Dhcpv4Srv> srv;
47 48
    ASSERT_NO_THROW(srv.reset(new Dhcpv4Srv(DHCP4_SERVER_PORT + 10000, "type=memfile",
                                            false, false)));
49
    srv.reset();
50 51 52 53 54
    // We have to close open sockets because further in this test we will
    // call the Dhcpv4Srv constructor again. This constructor will try to
    // set the appropriate packet filter class for IfaceMgr. This requires
    // that all sockets are closed.
    IfaceMgr::instance().closeSockets();
55

56
    // Check that the derived class can be instantiated
57 58
    boost::scoped_ptr<NakedDhcpv4Srv> naked_srv;
    ASSERT_NO_THROW(
59
        naked_srv.reset(new NakedDhcpv4Srv(DHCP4_SERVER_PORT + 10000)));
60
    EXPECT_TRUE(naked_srv->getServerID());
61 62
    // Close sockets again for the next test.
    IfaceMgr::instance().closeSockets();
63

64
    ASSERT_NO_THROW(naked_srv.reset(new NakedDhcpv4Srv(0)));
65
    EXPECT_TRUE(naked_srv->getServerID());
66 67
}

68 69 70
// This test verifies that the destination address of the response
// message is set to giaddr, when giaddr is set to non-zero address
// in the received message.
71 72 73
TEST_F(Dhcpv4SrvTest, adjustRemoteAddressRelay) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv(new NakedDhcpv4Srv(0));

74
    // Create the instance of the incoming packet.
75
    boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));
76
    // Set the giaddr to non-zero address as if it was relayed.
77
    req->setGiaddr(IOAddress("192.0.2.1"));
78 79
    // Set ciaddr to zero. This simulates the client which applies
    // for the new lease.
80
    req->setCiaddr(IOAddress("0.0.0.0"));
81 82 83 84 85 86 87
    // Clear broadcast flag.
    req->setFlags(0x0000);

    // Create a response packet. Assume that the new lease have
    // been created and new address allocated. This address is
    // stored in yiaddr field.
    boost::shared_ptr<Pkt4> resp(new Pkt4(DHCPOFFER, 1234));
88
    resp->setYiaddr(IOAddress("192.0.2.100"));
89 90
    // Clear the remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));
91

92
    // This function never throws.
93 94
    ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));

95
    // Now the destination address should be relay's address.
96
    EXPECT_EQ("192.0.2.1", resp->getRemoteAddr().toText());
97 98 99 100 101 102

    // Let's do another test and set other fields: ciaddr and
    // flags. By doing it, we want to make sure that the relay
    // address will take precedence.
    req->setGiaddr(IOAddress("192.0.2.50"));
    req->setCiaddr(IOAddress("192.0.2.11"));
103
    req->setFlags(Pkt4::FLAG_BROADCAST_MASK);
104 105 106 107 108 109 110 111 112 113 114

    resp->setYiaddr(IOAddress("192.0.2.100"));
    // Clear remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));

    ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));

    // Response should be sent back to the relay address.
    EXPECT_EQ("192.0.2.50", resp->getRemoteAddr().toText());
}

115 116 117 118
// This test verifies that the destination address of the response message
// is set to ciaddr when giaddr is set to zero and the ciaddr is set to
// non-zero address in the received message. This is the case when the
// client is in Renew or Rebind state.
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
TEST_F(Dhcpv4SrvTest, adjustRemoteAddressRenewRebind) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv(new NakedDhcpv4Srv(0));

    // Create instance of the incoming packet.
    boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));

    // Clear giaddr to simulate direct packet.
    req->setGiaddr(IOAddress("0.0.0.0"));
    // Set ciaddr to non-zero address. The response should be sent to this
    // address as the client is in renewing or rebinding state (it is fully
    // configured).
    req->setCiaddr(IOAddress("192.0.2.15"));
    // Let's configure broadcast flag. It should be ignored because
    // we are responding directly to the client having an address
    // and trying to extend his lease. Broadcast flag is only used
    // when new lease is acquired and server must make a decision
    // whether to unicast the response to the acquired address or
    // broadcast it.
137
    req->setFlags(Pkt4::FLAG_BROADCAST_MASK);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

    // Create a response.
    boost::shared_ptr<Pkt4> resp(new Pkt4(DHCPOFFER, 1234));
    // Let's extend the lease for the client in such a way that
    // it will actually get different address. The response
    // should not be sent to this address but rather to ciaddr
    // as client still have ciaddr configured.
    resp->setYiaddr(IOAddress("192.0.2.13"));
    // Clear the remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));

    ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));

    // Check that server responds to ciaddr
    EXPECT_EQ("192.0.2.15", resp->getRemoteAddr().toText());
}

155 156 157 158 159 160 161
// This test verifies that the destination address of the response message
// is set correctly when giaddr and ciaddr is zeroed in the received message
// and the new lease is acquired. The lease address is carried in the
// response message in the yiaddr field. In this case destination address
// of the response should be set to yiaddr if server supports direct responses
// to the client which doesn't have an address yet or broadcast if the server
// doesn't support direct responses.
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 199 200 201 202 203 204 205 206 207 208 209 210 211
TEST_F(Dhcpv4SrvTest, adjustRemoteAddressSelect) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv(new NakedDhcpv4Srv(0));

    // Create instance of the incoming packet.
    boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));

    // Clear giaddr to simulate direct packet.
    req->setGiaddr(IOAddress("0.0.0.0"));
    // Clear client address as it hasn't got any address configured yet.
    req->setCiaddr(IOAddress("0.0.0.0"));

    // Let's clear the broadcast flag.
    req->setFlags(0);

    // Create a response.
    boost::shared_ptr<Pkt4> resp(new Pkt4(DHCPOFFER, 1234));
    // Assign some new address for this client.
    resp->setYiaddr(IOAddress("192.0.2.13"));

    // Clear the remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));

    // When running unit tests, the IfaceMgr is using the default Packet
    // Filtering class, PktFilterInet. This class does not support direct
    // responses to clients without address assigned. When giaddr and ciaddr
    // are zero and client has just got new lease, the assigned address is
    // carried in yiaddr. In order to send this address to the client,
    // server must broadcast its response.
    ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));

    // Check that the response is sent to broadcast address as the
    // server doesn't have capability to respond directly.
    EXPECT_EQ("255.255.255.255", resp->getRemoteAddr().toText());

    // We also want to test the case when the server has capability to
    // respond directly to the client which is not configured. Server
    // makes decision whether it responds directly or broadcast its
    // response based on the capability reported by IfaceMgr. In order
    // to set this capability we have to provide a dummy Packet Filter
    // class which would report the support for direct responses.
    // This class is called PktFilterTest.
    IfaceMgr::instance().setPacketFilter(PktFilterPtr(new PktFilterTest()));

    // Now we expect that the server will send its response to the
    // address assigned for the client.
    ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));

    EXPECT_EQ("192.0.2.13", resp->getRemoteAddr().toText());
}

212 213 214 215 216
// This test verifies that the destination address of the response message
// is set to broadcast address when client set broadcast flag in its
// query. Client sets this flag to indicate that it can't receive direct
// responses from the server when it doesn't have its interface configured.
// Server must respect broadcast flag.
217 218 219 220 221 222 223 224 225 226 227 228
TEST_F(Dhcpv4SrvTest, adjustRemoteAddressBroadcast) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv(new NakedDhcpv4Srv(0));

    // Create instance of the incoming packet.
    boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));

    // Clear giaddr to simulate direct packet.
    req->setGiaddr(IOAddress("0.0.0.0"));
    // Clear client address as it hasn't got any address configured yet.
    req->setCiaddr(IOAddress("0.0.0.0"));

    // Let's set the broadcast flag.
229
    req->setFlags(Pkt4::FLAG_BROADCAST_MASK);
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257

    // Create a response.
    boost::shared_ptr<Pkt4> resp(new Pkt4(DHCPOFFER, 1234));
    // Assign some new address for this client.
    resp->setYiaddr(IOAddress("192.0.2.13"));

    // Clear the remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));

    // When running unit tests, the IfaceMgr is using the default Packet
    // Filtering class, PktFilterInet. This class does not support direct
    // responses to the clients without address assigned. If giaddr and
    // ciaddr are zero and client has just got the new lease, the assigned
    // address is carried in yiaddr. In order to send this address to the
    // client, server must send the response to the broadcast address when
    // direct response is not supported. This conflicts with the purpose
    // of this test which is supposed to verify that responses are sent
    // to broadcast address only, when broadcast flag is set. Therefore,
    // in order to simulate that direct responses are supported we have
    // to replace the default packet filtering class with a dummy class
    // which reports direct response capability.
    IfaceMgr::instance().setPacketFilter(PktFilterPtr(new PktFilterTest()));

    ASSERT_NO_THROW(srv->adjustRemoteAddr(req, resp));

    // Server must repond to broadcast address when client desired that
    // by setting the broadcast flag in its request.
    EXPECT_EQ("255.255.255.255", resp->getRemoteAddr().toText());
258 259
}

260
// Verifies that DISCOVER message can be processed correctly,
Tomek Mrugalski's avatar
Tomek Mrugalski committed
261 262 263 264 265 266 267
// 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.
268 269
TEST_F(Dhcpv4SrvTest, processDiscover) {
    testDiscoverRequest(DHCPDISCOVER);
270
}
271

272
// Verifies that REQUEST message can be processed correctly,
273
// that the OFFER message generated in response is valid and
Tomek Mrugalski's avatar
Tomek Mrugalski committed
274 275 276 277
// contains necessary options.
//
// Note: this test focuses on the packet correctness. There
// are other tests that verify correctness of the allocation
278 279
// engine. See DiscoverBasic, DiscoverHint, DiscoverNoClientId
// and DiscoverInvalidHint.
280 281
TEST_F(Dhcpv4SrvTest, processRequest) {
    testDiscoverRequest(DHCPREQUEST);
282 283 284
}

TEST_F(Dhcpv4SrvTest, processRelease) {
285
    NakedDhcpv4Srv srv;
286
    Pkt4Ptr pkt(new Pkt4(DHCPRELEASE, 1234));
287

288
    // Should not throw
289
    EXPECT_NO_THROW(srv.processRelease(pkt));
290 291 292
}

TEST_F(Dhcpv4SrvTest, processDecline) {
293
    NakedDhcpv4Srv srv;
294
    Pkt4Ptr pkt(new Pkt4(DHCPDECLINE, 1234));
295

296
    // Should not throw
297
    EXPECT_NO_THROW(srv.processDecline(pkt));
298 299 300
}

TEST_F(Dhcpv4SrvTest, processInform) {
301
    NakedDhcpv4Srv srv;
302
    Pkt4Ptr pkt(new Pkt4(DHCPINFORM, 1234));
303

304
    // Should not throw
305
    EXPECT_NO_THROW(srv.processInform(pkt));
306

307
    // Should return something
308
    EXPECT_TRUE(srv.processInform(pkt));
309

310
    // @todo Implement more reasonable tests before starting
311
    // work on processSomething() method.
312 313
}

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
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));
        }
    }
}

346 347 348 349 350 351 352 353 354 355 356 357 358
// 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;
359
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
360 361 362 363 364 365

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

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

369
    // Check if we get response at all
370 371
    checkResponse(offer, DHCPOFFER, 1234);

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

376
    // Check identifiers
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    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;
396
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
397 398 399 400 401 402 403 404
    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);

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

408
    // Check if we get response at all
409 410
    checkResponse(offer, DHCPOFFER, 1234);

411
    // Check that address was returned from proper range, that its lease
412 413 414 415 416
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(offer, subnet_);

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

417
    // Check identifiers
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    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;
436
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
437 438 439 440 441
    IOAddress hint("192.0.2.107");

    Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
    dis->setRemoteAddr(IOAddress("192.0.2.1"));
    dis->setYiaddr(hint);
442
    dis->setHWAddr(generateHWAddr(6));
443

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

447
    // Check if we get response at all
448 449
    checkResponse(offer, DHCPOFFER, 1234);

450
    // Check that address was returned from proper range, that its lease
451 452 453 454 455
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(offer, subnet_);

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

456
    // Check identifiers
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
    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;
474
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
475 476 477 478 479 480 481 482
    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);

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

486
    // Check if we get response at all
487 488
    checkResponse(offer, DHCPOFFER, 1234);

489
    // Check that address was returned from proper range, that its lease
490 491 492 493 494
    // lifetime is correct, that T1 and T2 are returned properly
    checkAddressParams(offer, subnet_);

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

495
    // Check identifiers
496 497 498 499 500 501 502 503
    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
504 505
// 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
506
// 2 addresses, the third client would get the same offer as the first one
507
// and this is a correct behavior. It is REQUEST that will fail for the third
Tomek Mrugalski's avatar
Tomek Mrugalski committed
508
// client. OFFER is basically saying "if you send me a request, you will
509 510 511
// probably get an address like this" (there are no guarantees).
TEST_F(Dhcpv4SrvTest, ManyDiscovers) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
512
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
513 514 515 516 517 518 519 520 521

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

522
    // Different client-id sizes
523 524 525 526 527 528 529 530
    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);

531 532 533 534
    // Pass it to the server and get an offer
    Pkt4Ptr offer1 = srv->processDiscover(dis1);
    Pkt4Ptr offer2 = srv->processDiscover(dis2);
    Pkt4Ptr offer3 = srv->processDiscover(dis3);
535

536 537 538 539
    // Check if we get response at all
    checkResponse(offer1, DHCPOFFER, 1234);
    checkResponse(offer2, DHCPOFFER, 2345);
    checkResponse(offer3, DHCPOFFER, 3456);
540

541 542 543
    IOAddress addr1 = offer1->getYiaddr();
    IOAddress addr2 = offer2->getYiaddr();
    IOAddress addr3 = offer3->getYiaddr();
544 545

    // Check that the assigned address is indeed from the configured pool
546 547 548 549
    checkAddressParams(offer1, subnet_);
    checkAddressParams(offer2, subnet_);
    checkAddressParams(offer3, subnet_);

550
    // Check server-ids
551 552 553 554 555 556
    checkServerId(offer1, srv->getServerID());
    checkServerId(offer2, srv->getServerID());
    checkServerId(offer3, srv->getServerID());
    checkClientId(offer1, clientid1);
    checkClientId(offer2, clientid2);
    checkClientId(offer3, clientid3);
557 558 559 560 561 562 563 564 565 566

    // 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
567 568
// This test verifies that incoming REQUEST can be handled properly, that an
// ACK is generated, that the response has an address and that address
569 570
// really belongs to the configured pool.
//
Tomek Mrugalski's avatar
Tomek Mrugalski committed
571
// constructed a single REQUEST message with:
572
// - client-id option
Tomek Mrugalski's avatar
Tomek Mrugalski committed
573 574
// - hwaddr information
// - requested address (that the client received in DISCOVER/OFFER exchange)
575
//
Tomek Mrugalski's avatar
Tomek Mrugalski committed
576
// expected returned ACK message:
577 578
// - copy of client-id
// - server-id
Tomek Mrugalski's avatar
Tomek Mrugalski committed
579 580 581
// - assigned address
//
// Test verifies that the lease is actually in the database.
582 583
TEST_F(Dhcpv4SrvTest, RequestBasic) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
584
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
585 586 587 588 589 590 591 592 593 594 595

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

596
    // Check if we get response at all
597 598 599
    checkResponse(ack, DHCPACK, 1234);
    EXPECT_EQ(hint.toText(), ack->getYiaddr().toText());

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

604
    // Check identifiers
605 606 607
    checkServerId(ack, srv->getServerID());
    checkClientId(ack, clientid);

608
    // Check that the lease is really in the database
609 610 611 612 613 614
    Lease4Ptr l = checkLease(ack, clientid, req->getHWAddr(), hint);

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

Tomek Mrugalski's avatar
Tomek Mrugalski committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
// 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;
630
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
Tomek Mrugalski's avatar
Tomek Mrugalski committed
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652

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

653
    // Different client-id sizes
Tomek Mrugalski's avatar
Tomek Mrugalski committed
654 655 656 657 658 659 660 661 662 663 664 665 666
    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);

667
    // Check if we get response at all
Tomek Mrugalski's avatar
Tomek Mrugalski committed
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
    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_);

686
    // Check DUIDs
Tomek Mrugalski's avatar
Tomek Mrugalski committed
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    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
711 712 713 714 715 716 717 718 719 720
// 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;
721
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
722 723

    const IOAddress addr("192.0.2.106");
724 725 726 727
    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;
728

729
    // Generate client-id also sets client_id_ member
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
    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
758
    req->setCiaddr(addr); // client's address
759 760 761 762 763 764 765 766 767 768 769

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

770
    // Check that address was returned from proper range, that its lease
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
    // 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));
790
    // Equality or difference by 1 between cltt and expected is ok.
791 792 793 794 795 796 797 798 799 800
    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;
801
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
802 803

    Pkt4Ptr pkt = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
804
    pkt->setHWAddr(generateHWAddr(6));
805

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

809
    // Empty packet, no server-id
810 811 812 813
    EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::MANDATORY), RFCViolation);

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

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

817
    // Server-id is forbidden, but present => exception
818 819
    EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::FORBIDDEN),
                 RFCViolation);
820 821 822 823 824

    // There's no client-id and no HWADDR. Server needs something to
    // identify the client
    pkt->setHWAddr(generateHWAddr(0));
    EXPECT_THROW(srv->sanityCheck(pkt, Dhcpv4Srv::MANDATORY), RFCViolation);
825 826
}

Tomek Mrugalski's avatar
Tomek Mrugalski committed
827 828 829
// 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.
830 831
TEST_F(Dhcpv4SrvTest, ReleaseBasic) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
832
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
833 834 835 836 837 838 839 840 841 842 843 844 845

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

846
    // Let's create a lease and put it in the LeaseMgr
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
    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);
863
    rel->setCiaddr(addr);
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
    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);

881
    // Try to get it by hw/subnet_id combination
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
    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
TEST_F(Dhcpv4SrvTest, ReleaseReject) {
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
905
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
906 907 908 909 910 911 912

    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;

913
    // Let's create a lease and put it in the LeaseMgr
914 915 916 917 918 919 920 921 922 923 924 925 926 927
    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);
928
    rel->setCiaddr(addr);
929 930 931 932 933 934 935 936 937 938 939 940
    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));

Tomek Mrugalski's avatar
Tomek Mrugalski committed
941
    // CASE 2: Lease is known and belongs to this client, but to a different hardware
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
    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);

Tomek Mrugalski's avatar
Tomek Mrugalski committed
978
    // Final sanity check. Verify that with valid hw and client-id release is successful
979 980 981
    rel->delOption(DHO_DHCP_CLIENT_IDENTIFIER);
    rel->addOption(clientid);

Tomek Mrugalski's avatar
Tomek Mrugalski committed
982
    // It should work this time
983 984
    EXPECT_NO_THROW(srv->processRelease(rel));

Tomek Mrugalski's avatar
Tomek Mrugalski committed
985
    // Check that the lease is not there
986 987 988
    l = LeaseMgrFactory::instance().getLease4(addr);
    EXPECT_FALSE(l);
}
989

990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
// This test verifies if the server-id disk operations (read, write) are
// working properly.
TEST_F(Dhcpv4SrvTest, ServerID) {
    NakedDhcpv4Srv srv(0);

    string srvid_text = "192.0.2.100";
    IOAddress srvid(srvid_text);

    fstream file1(SRVID_FILE, ios::out | ios::trunc);
    file1 << srvid_text;
    file1.close();

    // Test reading from a file
    EXPECT_TRUE(srv.loadServerID(SRVID_FILE));
    ASSERT_TRUE(srv.getServerID());
    EXPECT_EQ(srvid_text, srv.srvidToString(srv.getServerID()));

    // Now test writing to a file
    EXPECT_EQ(0, unlink(SRVID_FILE));
    EXPECT_NO_THROW(srv.writeServerID(SRVID_FILE));

    fstream file2(SRVID_FILE, ios::in);
    ASSERT_TRUE(file2.good());
    string text;
    file2 >> text;
    file2.close();

    EXPECT_EQ(srvid_text, text);
}

1020 1021 1022 1023
/// @todo Implement tests for subnetSelect See tests in dhcp6_srv_unittest.cc:
/// selectSubnetAddr, selectSubnetIface, selectSubnetRelayLinkaddr,
/// selectSubnetRelayInterfaceId. Note that the concept of interface-id is not
/// present in the DHCPv4, so not everything is applicable directly.
1024
/// See ticket #3057
1025

1026 1027 1028 1029 1030
// Checks if hooks are registered properly.
TEST_F(Dhcpv4SrvTest, Hooks) {
    NakedDhcpv4Srv srv(0);

    // check if appropriate hooks are registered
1031 1032 1033 1034 1035 1036
    int hook_index_buffer4_receive = -1;
    int hook_index_pkt4_receive    = -1;
    int hook_index_select_subnet   = -1;
    int hook_index_lease4_release  = -1;
    int hook_index_pkt4_send       = -1;
    int hook_index_buffer4_send    = -1;
1037 1038

    // check if appropriate indexes are set
1039 1040 1041
    EXPECT_NO_THROW(hook_index_buffer4_receive = ServerHooks::getServerHooks()
                    .getIndex("buffer4_receive"));
    EXPECT_NO_THROW(hook_index_pkt4_receive = ServerHooks::getServerHooks()
1042 1043 1044
                    .getIndex("pkt4_receive"));
    EXPECT_NO_THROW(hook_index_select_subnet = ServerHooks::getServerHooks()
                    .getIndex("subnet4_select"));
1045 1046 1047
    EXPECT_NO_THROW(hook_index_lease4_release = ServerHooks::getServerHooks()
                    .getIndex("lease4_release"));
    EXPECT_NO_THROW(hook_index_pkt4_send = ServerHooks::getServerHooks()
1048
                    .getIndex("pkt4_send"));
1049 1050
    EXPECT_NO_THROW(hook_index_buffer4_send = ServerHooks::getServerHooks()
                    .getIndex("buffer4_send"));
1051

1052 1053
    EXPECT_TRUE(hook_index_buffer4_receive > 0);
    EXPECT_TRUE(hook_index_pkt4_receive > 0);
1054
    EXPECT_TRUE(hook_index_select_subnet > 0);
1055
    EXPECT_TRUE(hook_index_lease4_release > 0);
1056
    EXPECT_TRUE(hook_index_pkt4_send > 0);
1057
    EXPECT_TRUE(hook_index_buffer4_send > 0);
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
}

    // a dummy MAC address
    const uint8_t dummyMacAddr[] = {0, 1, 2, 3, 4, 5};

    // A dummy MAC address, padded with 0s
    const uint8_t dummyChaddr[16] = {0, 1, 2, 3, 4, 5, 0, 0,
                                     0, 0, 0, 0, 0, 0, 0, 0 };

    // Let's use some creative test content here (128 chars + \0)
    const uint8_t dummyFile[] = "Lorem ipsum dolor sit amet, consectetur "
        "adipiscing elit. Proin mollis placerat metus, at "
        "lacinia orci ornare vitae. Mauris amet.";

    // Yet another type of test content (64 chars + \0)
    const uint8_t dummySname[] = "Lorem ipsum dolor sit amet, consectetur "
        "adipiscing elit posuere.";

/// @brief a class dedicated to Hooks testing in DHCPv4 server
///
/// This class has a number of static members, because each non-static
/// method has implicit 'this' parameter, so it does not match callout
/// signature and couldn't be registered. Furthermore, static methods
/// can't modify non-static members (for obvious reasons), so many
/// fields are declared static. It is still better to keep them as
/// one class rather than unrelated collection of global objects.
class HooksDhcpv4SrvTest : public Dhcpv4SrvTest {

public:

    /// @brief creates Dhcpv4Srv and prepares buffers for callouts
    HooksDhcpv4SrvTest() {

        // Allocate new DHCPv6 Server
        srv_ = new NakedDhcpv4Srv(0);

        // clear static buffers
        resetCalloutBuffers();
    }

    /// @brief destructor (deletes Dhcpv4Srv)
    virtual ~HooksDhcpv4SrvTest() {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1100

1101 1102
        HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("buffer4_receive");
        HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("buffer4_send");
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1103 1104 1105
        HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("pkt4_receive");
        HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("pkt4_send");
        HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("subnet4_select");
1106
        HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("lease4_renew");
1107
        HooksManager::preCalloutsLibraryHandle().deregisterAllCallouts("lease4_release");
Tomek Mrugalski's avatar
Tomek Mrugalski committed
1108

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 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
        delete srv_;
    }

    /// @brief creates an option with specified option code
    ///
    /// This method is static, because it is used from callouts
    /// that do not have a pointer to HooksDhcpv4SSrvTest object
    ///
    /// @param option_code code of option to be created
    ///
    /// @return pointer to create option object
    static OptionPtr createOption(uint16_t option_code) {

        char payload[] = {
            0xa, 0xb, 0xc, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14
        };

        OptionBuffer tmp(payload, payload + sizeof(payload));
        return OptionPtr(new Option(Option::V4, option_code, tmp));
    }

    /// @brief Generates test packet.
    ///
    /// Allocates and generates on-wire buffer that represents test packet, with all
    /// fixed fields set to non-zero values.  Content is not always reasonable.
    ///
    /// See generateTestPacket1() function that returns exactly the same packet as
    /// Pkt4 object.
    ///
    /// @return pointer to allocated Pkt4 object
    // Returns a vector containing a DHCPv4 packet header.
    Pkt4Ptr
    generateSimpleDiscover() {

        // That is only part of the header. It contains all "short" fields,
        // larger fields are constructed separately.
        uint8_t hdr[] = {
            1, 6, 6, 13,            // op, htype, hlen, hops,
            0x12, 0x34, 0x56, 0x78, // transaction-id
            0, 42, 0x80, 0x00,      // 42 secs, BROADCAST flags
            192, 0, 2, 1,           // ciaddr
            1, 2, 3, 4,             // yiaddr
            192, 0, 2, 255,         // siaddr
            255, 255, 255, 255,     // giaddr
        };
1154

1155 1156
        // Initialize the vector with the header fields defined above.
        vector<uint8_t> buf(hdr, hdr + sizeof(hdr));
1157

1158 1159 1160 1161
        // Append the large header fields.
        copy(dummyChaddr, dummyChaddr + Pkt4::MAX_CHADDR_LEN, back_inserter(buf));
        copy(dummySname, dummySname + Pkt4::MAX_SNAME_LEN, back_inserter(buf));
        copy(dummyFile, dummyFile + Pkt4::MAX_FILE_LEN, back_inserter(buf));
1162

1163 1164 1165 1166 1167
        // Should now have all the header, so check.  The "static_cast" is used
        // to get round an odd bug whereby the linker appears not to find the
        // definition of DHCPV4_PKT_HDR_LEN if it appears within an EXPECT_EQ().
        EXPECT_EQ(static_cast<size_t>(Pkt4::DHCPV4_PKT_HDR_LEN), buf.size());

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
        // Add magic cookie
        buf.push_back(0x63);
        buf.push_back(0x82);
        buf.push_back(0x53);
        buf.push_back(0x63);

        // Add message type DISCOVER
        buf.push_back(static_cast<uint8_t>(DHO_DHCP_MESSAGE_TYPE));
        buf.push_back(1); // length (just one byte)
        buf.push_back(static_cast<uint8_t>(DHCPDISCOVER));

        return (Pkt4Ptr(new Pkt4(&buf[0], buf.size())));
1180 1181
    }

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
    /// Test callback that stores received callout name and pkt4 value
    /// @param callout_handle handle passed by the hooks framework
    /// @return always 0
    static int
    buffer4_receive_callout(CalloutHandle& callout_handle) {
        callback_name_ = string("buffer4_receive");

        callout_handle.getArgument("query4", callback_pkt4_);

        callback_argument_names_ = callout_handle.getArgumentNames();
        return (0);
    }

    /// Test callback that changes hwaddr value
    /// @param callout_handle handle passed by the hooks framework
    /// @return always 0
    static int
    buffer4_receive_change_hwaddr(CalloutHandle& callout_handle) {

        Pkt4Ptr pkt;
        callout_handle.getArgument("query4", pkt);

        // If there is at least one option with data
        if (pkt->data_.size() >= Pkt4::DHCPV4_PKT_HDR_LEN) {
            // Offset of the first byte of the CHWADDR field. Let's the first
            // byte to some new value that we could later check
            pkt->data_[28] = 0xff;
        }

        // Carry on as usual
        return buffer4_receive_callout(callout_handle);
    }

    /// Test callback that deletes MAC address
    /// @param callout_handle handle passed by the hooks framework
    /// @return always 0
    static int
    buffer4_receive_delete_hwaddr(CalloutHandle& callout_handle) {

        Pkt4Ptr pkt;
        callout_handle.getArgument("query4", pkt);

        pkt->data_[