dhcp4_srv_unittest.cc 142 KB
Newer Older
1
// Copyright (C) 2011-2019 Internet Systems Consortium, Inc. ("ISC")
2
//
3 4 5
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 7 8 9

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

10
#include <asiolink/io_address.h>
11
#include <cc/command_interpreter.h>
12
#include <config/command_mgr.h>
13
#include <dhcp4/tests/dhcp4_test_utils.h>
14
#include <dhcp4/tests/dhcp4_client.h>
15
#include <dhcp/tests/pkt_captures.h>
16
#include <dhcp/dhcp4.h>
17
#include <dhcp/iface_mgr.h>
18
#include <dhcp/libdhcp++.h>
19
#include <dhcp/option.h>
20
#include <dhcp/option_int.h>
21
#include <dhcp/option4_addrlst.h>
22
#include <dhcp/option_custom.h>
23
#include <dhcp/option_int_array.h>
24 25
#include <dhcp/pkt_filter.h>
#include <dhcp/pkt_filter_inet.h>
26
#include <dhcp/tests/iface_mgr_test_config.h>
27
#include <dhcp4/dhcp4_srv.h>
Tomek Mrugalski's avatar
Tomek Mrugalski committed
28
#include <dhcp4/dhcp4_log.h>
29
#include <dhcp4/json_config_parser.h>
30 31 32 33
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/lease_mgr.h>
#include <dhcpsrv/lease_mgr_factory.h>
#include <dhcpsrv/utils.h>
34
#include <dhcpsrv/host_mgr.h>
35
#include <stats/stats_mgr.h>
36
#include <testutils/gtest_utils.h>
37
#include <util/encode/hex.h>
38 39
#include <boost/scoped_ptr.hpp>

40 41 42
#include <iostream>

#include <arpa/inet.h>
43 44 45 46

using namespace std;
using namespace isc;
using namespace isc::dhcp;
47
using namespace isc::data;
48
using namespace isc::asiolink;
49
using namespace isc::config;
50
using namespace isc::dhcp::test;
51 52 53

namespace {

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
const char* CONFIGS[] = {
    // Configuration 0:
    // - 1 subnet: 10.254.226.0/25
    // - used for recorded traffic (see PktCaptures::captureRelayedDiscover)
    "{ \"interfaces-config\": {"
        "    \"interfaces\": [ \"*\" ]"
        "},"
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, "
        "\"subnet4\": [ { "
        "    \"pools\": [ { \"pool\": \"10.254.226.0/25\" } ],"
        "    \"subnet\": \"10.254.226.0/24\", "
        "    \"rebind-timer\": 2000, "
        "    \"renew-timer\": 1000, "
        "    \"valid-lifetime\": 4000,"
        "    \"interface\": \"eth0\" "
        " } ],"
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    "\"valid-lifetime\": 4000 }",

    // Configuration 1:
    // - 1 subnet: 192.0.2.0/24
    // - MySQL Host Data Source configured
    "{ \"interfaces-config\": {"
        "    \"interfaces\": [ \"*\" ]"
        "},"
        "\"hosts-database\": {"
        "    \"type\": \"mysql\","
        "    \"name\": \"keatest\","
        "    \"user\": \"keatest\","
        "    \"password\": \"keatest\""
        "},"
        "\"rebind-timer\": 2000, "
        "\"renew-timer\": 1000, "
        "\"subnet4\": [ { "
        "    \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ],"
        "    \"subnet\": \"192.0.2.0/24\", "
        "    \"rebind-timer\": 2000, "
        "    \"renew-timer\": 1000, "
        "    \"valid-lifetime\": 4000,"
        "    \"interface\": \"eth0\" "
        " } ],"
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    "\"valid-lifetime\": 4000 }",

    // Configuration 2:
    // - 1 subnet, 2 global options (one forced with always-send)
    "{"
    "    \"interfaces-config\": {"
    "    \"interfaces\": [ \"*\" ] }, "
    "    \"rebind-timer\": 2000, "
    "    \"renew-timer\": 1000, "
    "    \"valid-lifetime\": 4000, "
    "    \"subnet4\": [ {"
    "        \"pools\": [ { \"pool\": \"192.0.2.1 - 192.0.2.100\" } ], "
    "        \"subnet\": \"192.0.2.0/24\""
    "    } ], "
    "    \"option-data\": ["
    "        {"
    "            \"name\": \"default-ip-ttl\", "
    "            \"data\": \"FF\", "
    "            \"csv-format\": false"
    "        }, "
    "        {"
    "            \"name\": \"ip-forwarding\", "
    "            \"data\": \"false\", "
    "            \"always-send\": true"
    "        }"
    "    ]"
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    "}",

    // Configuration 3:
    // - one subnet, with one pool
    // - user-contexts defined in both subnet and pool
    "{"
        "    \"subnet4\": [ { "
        "    \"pools\": [ { \"pool\": \"10.254.226.0/25\","
        "                   \"user-context\": { \"value\": 42 } } ],"
        "    \"subnet\": \"10.254.226.0/24\", "
        "    \"user-context\": {"
        "        \"secure\": false"
        "    }"
        " } ],"
    "\"valid-lifetime\": 4000 }",
};
137

138 139 140
// 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.
141 142 143 144
TEST_F(Dhcpv4SrvTest, adjustIfaceDataRelay) {
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

145
    // Create the instance of the incoming packet.
146
    boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));
147 148
    // Set the giaddr to non-zero address and hops to non-zero value
    // as if it was relayed.
149
    req->setGiaddr(IOAddress("192.0.1.1"));
150
    req->setHops(2);
151 152
    // Set ciaddr to zero. This simulates the client which applies
    // for the new lease.
153
    req->setCiaddr(IOAddress("0.0.0.0"));
154 155 156
    // Clear broadcast flag.
    req->setFlags(0x0000);

157
    // Set local address, port and interface.
158
    req->setLocalAddr(IOAddress("192.0.2.5"));
159
    req->setLocalPort(1001);
160
    req->setIface("eth1");
161 162
    req->setIndex(1);

163 164 165
    // Set remote port (it will be used in the next test).
    req->setRemotePort(1234);

166
    // Create the exchange using the req.
167
    Dhcpv4Exchange ex = createExchange(req);
168 169

    Pkt4Ptr resp = ex.getResponse();
170
    resp->setYiaddr(IOAddress("192.0.1.100"));
171 172
    // Clear the remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));
173 174
    // Set hops value for the response.
    resp->setHops(req->getHops());
175

176
    // This function never throws.
177
    ASSERT_NO_THROW(srv_.adjustIfaceData(ex));
178

179
    // Now the destination address should be relay's address.
180
    EXPECT_EQ("192.0.1.1", resp->getRemoteAddr().toText());
181 182
    // The query has been relayed, so the response must be sent to the port 67.
    EXPECT_EQ(DHCP4_SERVER_PORT, resp->getRemotePort());
183
    // Local address should be the address assigned to interface eth1.
184
    EXPECT_EQ("192.0.2.5", resp->getLocalAddr().toText());
185 186 187 188
    // The local port is always DHCPv4 server port 67.
    EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort());
    // We will send response over the same interface which was used to receive
    // query.
189
    EXPECT_EQ("eth1", resp->getIface());
190
    EXPECT_EQ(1, resp->getIndex());
191 192 193 194

    // 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.
195 196
    req->setGiaddr(IOAddress("192.0.1.50"));
    req->setCiaddr(IOAddress("192.0.1.11"));
197
    req->setFlags(Pkt4::FLAG_BROADCAST_MASK);
198

199
    resp->setYiaddr(IOAddress("192.0.1.100"));
200 201 202
    // Clear remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));

203
    // Set the client and server ports.
204
    srv_.client_port_ = 1234;
205
    srv_.server_port_ = 2345;
206 207

    ASSERT_NO_THROW(srv_.adjustIfaceData(ex));
208 209

    // Response should be sent back to the relay address.
210
    EXPECT_EQ("192.0.1.50", resp->getRemoteAddr().toText());
211 212 213

    // Remote port was enforced to the client port.
    EXPECT_EQ(srv_.client_port_, resp->getRemotePort());
214 215 216

    // Local port was enforced to the server port.
    EXPECT_EQ(srv_.server_port_, resp->getLocalPort());
217 218
}

219 220 221 222 223 224 225 226 227 228 229 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 258 259 260 261 262 263 264 265 266
// This test verifies that the remote port is adjusted when
// the query carries a relay port RAI sub-option.
TEST_F(Dhcpv4SrvTest, adjustIfaceDataRelayPort) {
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

    // Create the instance of the incoming packet.
    boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));
    // Set the giaddr to non-zero address and hops to non-zero value
    // as if it was relayed.
    req->setGiaddr(IOAddress("192.0.1.1"));
    req->setHops(2);
    // Set ciaddr to zero. This simulates the client which applies
    // for the new lease.
    req->setCiaddr(IOAddress("0.0.0.0"));
    // Clear broadcast flag.
    req->setFlags(0x0000);

    // Set local address, port and interface.
    req->setLocalAddr(IOAddress("192.0.2.5"));
    req->setLocalPort(1001);
    req->setIface("eth1");
    req->setIndex(1);

    // Set remote port.
    req->setRemotePort(1234);

    // Add a RAI relay-port sub-option (the only difference with the previous test).
    OptionDefinitionPtr rai_def =
        LibDHCP::getOptionDef(DHCP4_OPTION_SPACE, DHO_DHCP_AGENT_OPTIONS);
    ASSERT_TRUE(rai_def);
    OptionCustomPtr rai(new OptionCustom(*rai_def, Option::V4));
    ASSERT_TRUE(rai);
    req->addOption(rai);
    OptionPtr relay_port(new Option(Option::V4, RAI_OPTION_RELAY_PORT));
    ASSERT_TRUE(relay_port);
    rai->addOption(relay_port);

    // Create the exchange using the req.
    Dhcpv4Exchange ex = createExchange(req);

    Pkt4Ptr resp = ex.getResponse();
    resp->setYiaddr(IOAddress("192.0.1.100"));
    // Clear the remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));
    // Set hops value for the response.
    resp->setHops(req->getHops());

267 268 269
    // Set the remote port to 67 as we know it will be updated.
    resp->setRemotePort(67);

270
    // This function never throws.
271
    ASSERT_NO_THROW(srv_.adjustIfaceData(ex));
272 273 274

    // Now the destination address should be relay's address.
    EXPECT_EQ("192.0.1.1", resp->getRemoteAddr().toText());
275 276
    // The query has been relayed, so the response should be sent to the
    // port 67, but here there is a relay port RAI so another value is used.
277 278 279 280 281 282 283 284 285 286 287
    EXPECT_EQ(1234, resp->getRemotePort());
    // Local address should be the address assigned to interface eth1.
    EXPECT_EQ("192.0.2.5", resp->getLocalAddr().toText());
    // The local port is always DHCPv4 server port 67.
    EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort());
    // We will send response over the same interface which was used to receive
    // query.
    EXPECT_EQ("eth1", resp->getIface());
    EXPECT_EQ(1, resp->getIndex());
}

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
// This test verifies that it is possible to configure the server to use
// routing information to determine the right outbound interface to sent
// responses to a relayed client.
TEST_F(Dhcpv4SrvTest, adjustIfaceDataUseRouting) {
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

    // Create configuration for interfaces. It includes the outbound-interface
    // setting which indicates that the responses aren't neccessarily sent
    // over the same interface via which a request has been received, but routing
    // information is used to determine this interface.
    CfgMgr::instance().clear();
    CfgIfacePtr cfg_iface = CfgMgr::instance().getStagingCfg()->getCfgIface();
    cfg_iface->useSocketType(AF_INET, CfgIface::SOCKET_UDP);
    cfg_iface->use(AF_INET, "eth0");
    cfg_iface->use(AF_INET, "eth1");
    cfg_iface->setOutboundIface(CfgIface::USE_ROUTING);
    CfgMgr::instance().commit();;

    // Create the instance of the incoming packet.
    boost::shared_ptr<Pkt4> req(new Pkt4(DHCPDISCOVER, 1234));
    // Set the giaddr to non-zero address and hops to non-zero value
    // as if it was relayed.
    req->setGiaddr(IOAddress("192.0.1.1"));
    req->setHops(2);
    // Set ciaddr to zero. This simulates the client which applies
    // for the new lease.
    req->setCiaddr(IOAddress("0.0.0.0"));
    // Clear broadcast flag.
    req->setFlags(0x0000);

    // Set local address, port and interface.
    req->setLocalAddr(IOAddress("192.0.2.5"));
    req->setLocalPort(1001);
    req->setIface("eth1");
    req->setIndex(1);

    // Create the exchange using the req.
    Dhcpv4Exchange ex = createExchange(req);

    Pkt4Ptr resp = ex.getResponse();
    resp->setYiaddr(IOAddress("192.0.1.100"));
    // Clear the remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));
    // Set hops value for the response.
    resp->setHops(req->getHops());

    // This function never throws.
336
    ASSERT_NO_THROW(srv_.adjustIfaceData(ex));
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

    // Now the destination address should be relay's address.
    EXPECT_EQ("192.0.1.1", resp->getRemoteAddr().toText());
    // The query has been relayed, so the response must be sent to the port 67.
    EXPECT_EQ(DHCP4_SERVER_PORT, resp->getRemotePort());

    // The local port is always DHCPv4 server port 67.
    EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort());


    // No specific interface is selected as outbound interface and no specific
    // local address is provided. The IfaceMgr will figure out which interface to use.
    EXPECT_TRUE(resp->getLocalAddr().isV4Zero());
    EXPECT_FALSE(resp->indexSet());

352 353 354
    // Fixed in #5515 so now the interface name is never empty.
    EXPECT_FALSE(resp->getIface().empty());

355 356 357 358 359 360 361 362 363 364
    // Another test verifies that setting outbound interface to same as inbound will
    // cause the server to set interface and local address as expected.

    cfg_iface = CfgMgr::instance().getStagingCfg()->getCfgIface();
    cfg_iface->useSocketType(AF_INET, CfgIface::SOCKET_UDP);
    cfg_iface->use(AF_INET, "eth0");
    cfg_iface->use(AF_INET, "eth1");
    cfg_iface->setOutboundIface(CfgIface::SAME_AS_INBOUND);
    CfgMgr::instance().commit();

365
    ASSERT_NO_THROW(srv_.adjustIfaceData(ex));
366 367 368 369 370 371

    EXPECT_EQ("192.0.2.5", resp->getLocalAddr().toText());
    EXPECT_EQ("eth1", resp->getIface());
    EXPECT_EQ(1, resp->getIndex());
}

372 373 374 375
// 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.
376 377 378 379
TEST_F(Dhcpv4SrvTest, adjustIfaceDataRenew) {
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

380 381 382 383 384 385 386 387
    // 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).
388
    req->setCiaddr(IOAddress("192.0.1.15"));
389 390 391 392 393 394
    // 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.
395
    req->setFlags(Pkt4::FLAG_BROADCAST_MASK);
396 397 398
    // This is a direct message, so the hops should be cleared.
    req->setHops(0);
    // Set local unicast address as if we are renewing a lease.
399
    req->setLocalAddr(IOAddress("192.0.2.1"));
400 401 402
    // Request is received on the DHCPv4 server port.
    req->setLocalPort(DHCP4_SERVER_PORT);
    // Set the interface. The response should be sent over the same interface.
403
    req->setIface("eth1");
404
    req->setIndex(1);
405

406
    // Create the exchange using the req.
407
    Dhcpv4Exchange ex = createExchange(req);
408 409
    Pkt4Ptr resp = ex.getResponse();

410 411 412 413
    // 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.
414
    resp->setYiaddr(IOAddress("192.0.1.13"));
415 416
    // Clear the remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));
417 418
    // Copy hops value from the query.
    resp->setHops(req->getHops());
419

420
    ASSERT_NO_THROW(srv_.adjustIfaceData(ex));
421 422

    // Check that server responds to ciaddr
423
    EXPECT_EQ("192.0.1.15", resp->getRemoteAddr().toText());
424 425 426 427 428
    // The query was non-relayed, so the response should be sent to a DHCPv4
    // client port 68.
    EXPECT_EQ(DHCP4_CLIENT_PORT, resp->getRemotePort());
    // The response should be sent from the unicast address on which the
    // query has been received.
429
    EXPECT_EQ("192.0.2.1", resp->getLocalAddr().toText());
430 431 432
    // The response should be sent from the DHCPv4 server port.
    EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort());
    // The interface data should match the data in the query.
433
    EXPECT_EQ("eth1", resp->getIface());
434 435
    EXPECT_EQ(1, resp->getIndex());

436 437
}

438 439 440 441 442 443 444
// 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.
445 446 447 448
TEST_F(Dhcpv4SrvTest, adjustIfaceDataSelect) {
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

449 450 451 452 453 454 455 456 457 458 459
    // 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);

460 461 462 463 464 465 466
    // This is a non-relayed message, so let's clear hops count.
    req->setHops(0);
    // The query is sent to the broadcast address in the Select state.
    req->setLocalAddr(IOAddress("255.255.255.255"));
    // The query has been received on the DHCPv4 server port 67.
    req->setLocalPort(DHCP4_SERVER_PORT);
    // Set the interface. The response should be sent via the same interface.
467
    req->setIface("eth1");
468 469
    req->setIndex(1);

470
    // Create the exchange using the req.
471
    Dhcpv4Exchange ex = createExchange(req);
472
    Pkt4Ptr resp = ex.getResponse();
473
    // Assign some new address for this client.
474
    resp->setYiaddr(IOAddress("192.0.1.13"));
475 476
    // Clear the remote address.
    resp->setRemoteAddr(IOAddress("0.0.0.0"));
477 478 479 480 481 482 483 484
    // Copy hops count.
    resp->setHops(req->getHops());

    // We want to test the case, when the server (packet filter) doesn't support
    // ddirect responses to the client which doesn't have an address yet. In
    // case, the server should send its response to the broadcast address.
    // We can control whether the current packet filter returns that its support
    // direct responses or not.
485
    test_config.setDirectResponse(false);
486 487 488 489 490 491 492

    // 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.
493
    ASSERT_NO_THROW(srv_.adjustIfaceData(ex));
494 495 496 497 498

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

499 500 501
    // Although the query has been sent to the broadcast address, the
    // server should select a unicast address on the particular interface
    // as a source address for the response.
502
    EXPECT_EQ("192.0.2.3", resp->getLocalAddr().toText());
503 504 505 506 507 508

    // The response should be sent from the DHCPv4 server port.
    EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort());

    // The response should be sent via the same interface through which
    // query has been received.
509
    EXPECT_EQ("eth1", resp->getIface());
510 511
    EXPECT_EQ(1, resp->getIndex());

512 513 514
    // 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
515 516 517
    // response based on the capability reported by IfaceMgr. We can
    // control whether the current packet filter returns that it supports
    // direct responses or not.
518
    test_config.setDirectResponse(true);
519 520 521

    // Now we expect that the server will send its response to the
    // address assigned for the client.
522
    ASSERT_NO_THROW(srv_.adjustIfaceData(ex));
523

524
    EXPECT_EQ("192.0.1.13", resp->getRemoteAddr().toText());
525 526
}

527 528 529 530 531
// 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.
532 533 534 535
TEST_F(Dhcpv4SrvTest, adjustIfaceDataBroadcast) {
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

536 537 538 539 540 541 542
    // 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"));
543 544 545 546 547
    // The query is sent to the broadcast address in the Select state.
    req->setLocalAddr(IOAddress("255.255.255.255"));
    // The query has been received on the DHCPv4 server port 67.
    req->setLocalPort(DHCP4_SERVER_PORT);
    // Set the interface. The response should be sent via the same interface.
548
    req->setIface("eth1");
549
    req->setIndex(1);
550 551

    // Let's set the broadcast flag.
552
    req->setFlags(Pkt4::FLAG_BROADCAST_MASK);
553

554
    // Create the exchange using the req.
555
    Dhcpv4Exchange ex = createExchange(req);
556 557
    Pkt4Ptr resp = ex.getResponse();

558
    // Assign some new address for this client.
559
    resp->setYiaddr(IOAddress("192.0.1.13"));
560 561 562 563

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

564
    ASSERT_NO_THROW(srv_.adjustIfaceData(ex));
565

Francis Dupont's avatar
Francis Dupont committed
566
    // Server must respond to broadcast address when client desired that
567 568
    // by setting the broadcast flag in its request.
    EXPECT_EQ("255.255.255.255", resp->getRemoteAddr().toText());
569 570 571 572

    // Although the query has been sent to the broadcast address, the
    // server should select a unicast address on the particular interface
    // as a source address for the response.
573
    EXPECT_EQ("192.0.2.3", resp->getLocalAddr().toText());
574 575 576 577 578 579

    // The response should be sent from the DHCPv4 server port.
    EXPECT_EQ(DHCP4_SERVER_PORT, resp->getLocalPort());

    // The response should be sent via the same interface through which
    // query has been received.
580
    EXPECT_EQ("eth1", resp->getIface());
581 582 583 584
    EXPECT_EQ(1, resp->getIndex());

}

585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
// This test verifies that the mandatory to copy fields and options
// are really copied into the response.
TEST_F(Dhcpv4SrvTest, initResponse) {
    Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234));

    // Set fields which must be copied
    query->setIface("foo");
    query->setIndex(111);
    query->setHops(5);
    const HWAddr& hw = HWAddr::fromText("11:22:33:44:55:66:77:88", 10);
    HWAddrPtr hw_addr(new HWAddr(hw));
    query->setHWAddr(hw_addr);
    query->setGiaddr(IOAddress("10.10.10.10"));
    const HWAddr& src_hw = HWAddr::fromText("e4:ce:8f:12:34:56");
    HWAddrPtr src_hw_addr(new HWAddr(src_hw));
    query->setLocalHWAddr(src_hw_addr);
    const HWAddr& dst_hw = HWAddr::fromText("e8:ab:cd:78:9a:bc");
    HWAddrPtr dst_hw_addr(new HWAddr(dst_hw));
    query->setRemoteHWAddr(dst_hw_addr);
604
    query->setFlags(BOOTP_BROADCAST);
605 606 607 608 609

    // Add options which must be copied
    // client-id echo is optional
    // rai echo is done in relayAgentInfoEcho
    // Do subnet selection option
610
    OptionDefinitionPtr sbnsel_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE,
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
                                                           DHO_SUBNET_SELECTION);
    ASSERT_TRUE(sbnsel_def);
    OptionCustomPtr sbnsel(new OptionCustom(*sbnsel_def, Option::V4));
    ASSERT_TRUE(sbnsel);
    sbnsel->writeAddress(IOAddress("192.0.2.3"));
    query->addOption(sbnsel);

    // Create exchange and get Response
    Dhcpv4Exchange ex = createExchange(query);
    Pkt4Ptr response = ex.getResponse();
    ASSERT_TRUE(response);

    // Check fields
    EXPECT_EQ("foo", response->getIface());
    EXPECT_EQ(111, response->getIndex());
    EXPECT_TRUE(response->getSiaddr().isV4Zero());
    EXPECT_TRUE(response->getCiaddr().isV4Zero());
    EXPECT_EQ(5, response->getHops());
629
    EXPECT_TRUE(hw == *response->getHWAddr());
630
    EXPECT_EQ(IOAddress("10.10.10.10"), response->getGiaddr());
631 632
    EXPECT_TRUE(src_hw == *response->getLocalHWAddr());
    EXPECT_TRUE(dst_hw == *response->getRemoteHWAddr());
633
    EXPECT_TRUE(BOOTP_BROADCAST == response->getFlags());
634 635 636 637 638

    // Check options (i.e., subnet selection option)
    OptionPtr resp_sbnsel = response->getOption(DHO_SUBNET_SELECTION);
    ASSERT_TRUE(resp_sbnsel);
    OptionCustomPtr resp_custom =
639
        boost::dynamic_pointer_cast<OptionCustom>(resp_sbnsel);
640 641 642 643 644 645
    ASSERT_TRUE(resp_custom);
    IOAddress subnet_addr("0.0.0.0");
    ASSERT_NO_THROW(subnet_addr = resp_custom->readAddress());
    EXPECT_EQ(IOAddress("192.0.2.3"), subnet_addr);
}

646 647 648
// This test verifies that the server identifier option is appended to
// a specified DHCPv4 message and the server identifier is correct.
TEST_F(Dhcpv4SrvTest, appendServerID) {
649
    Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 1234));
650
    Dhcpv4Exchange ex = createExchange(query);
651 652
    Pkt4Ptr response = ex.getResponse();

653 654
    // Set a local address. It is required by the function under test
    // to create the Server Identifier option.
655
    query->setLocalAddr(IOAddress("192.0.3.1"));
656 657

    // Append the Server Identifier.
658
    ASSERT_NO_THROW(NakedDhcpv4Srv::appendServerID(ex));
659 660 661 662 663 664 665 666 667 668 669 670 671 672

    // Make sure that the option has been added.
    OptionPtr opt = response->getOption(DHO_DHCP_SERVER_IDENTIFIER);
    ASSERT_TRUE(opt);
    Option4AddrLstPtr opt_server_id =
        boost::dynamic_pointer_cast<Option4AddrLst>(opt);
    ASSERT_TRUE(opt_server_id);

    // The option is represented as a list of IPv4 addresses but with
    // only one address added.
    Option4AddrLst::AddressContainer addrs = opt_server_id->getAddresses();
    ASSERT_EQ(1, addrs.size());
    // This address should match the local address of the packet.
    EXPECT_EQ("192.0.3.1", addrs[0].toText());
673 674
}

675 676 677 678 679 680
// Sanity check. Verifies that both Dhcpv4Srv and its derived
// class NakedDhcpv4Srv can be instantiated and destroyed.
TEST_F(Dhcpv4SrvTest, basic) {

    // Check that the base class can be instantiated
    boost::scoped_ptr<Dhcpv4Srv> srv;
681 682
    ASSERT_NO_THROW(srv.reset(new Dhcpv4Srv(DHCP4_SERVER_PORT + 10000, false,
                                            false)));
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    srv.reset();
    // 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();

    // Check that the derived class can be instantiated
    boost::scoped_ptr<NakedDhcpv4Srv> naked_srv;
    ASSERT_NO_THROW(
        naked_srv.reset(new NakedDhcpv4Srv(DHCP4_SERVER_PORT + 10000)));
    // Close sockets again for the next test.
    IfaceMgr::instance().closeSockets();

    ASSERT_NO_THROW(naked_srv.reset(new NakedDhcpv4Srv(0)));
}

700
// Verifies that DISCOVER message can be processed correctly,
Tomek Mrugalski's avatar
Tomek Mrugalski committed
701 702 703 704 705 706 707
// 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.
708
TEST_F(Dhcpv4SrvTest, processDiscover) {
709
    testDiscoverRequest(DHCPDISCOVER);
710
}
711

712
// Verifies that REQUEST message can be processed correctly,
713
// that the OFFER message generated in response is valid and
Tomek Mrugalski's avatar
Tomek Mrugalski committed
714 715 716 717
// contains necessary options.
//
// Note: this test focuses on the packet correctness. There
// are other tests that verify correctness of the allocation
718 719
// engine. See DiscoverBasic, DiscoverHint, DiscoverNoClientId
// and DiscoverInvalidHint.
720
TEST_F(Dhcpv4SrvTest, processRequest) {
721
    testDiscoverRequest(DHCPREQUEST);
722 723
}

724 725 726 727 728 729 730 731 732 733 734 735 736
// Verifies that DHCPDISCOVERs are sanity checked correctly.
// 1. They must have either hardware address or client id
// 2. They must not have server id
TEST_F(Dhcpv4SrvTest, sanityCheckDiscover) {
    NakedDhcpv4Srv srv;
    Pkt4Ptr pkt(new Pkt4(DHCPDISCOVER, 1234));

    // Should throw, no hardware address or client id
    ASSERT_THROW_MSG(srv.processDiscover(pkt), RFCViolation,
                     "Missing or useless client-id and no HW address"
                     " provided in message DHCPDISCOVER");

    // Add a hardware address. This should not throw.
737 738
    std::vector<uint8_t> data = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
    HWAddrPtr hwaddr(new HWAddr(data, HTYPE_ETHER));
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
    pkt->setHWAddr(hwaddr);
    ASSERT_NO_THROW(srv.processDiscover(pkt));

    // Now let's make a new pkt with client-id only, it should not throw.
    pkt.reset(new Pkt4(DHCPDISCOVER, 1234));
    pkt->addOption(generateClientId());
    ASSERT_NO_THROW(srv.processDiscover(pkt));

    // Now let's add a server-id. This should throw.
    OptionDefinitionPtr server_id_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE,
                                                              DHO_DHCP_SERVER_IDENTIFIER);
    ASSERT_TRUE(server_id_def);

    OptionCustomPtr server_id(new OptionCustom(*server_id_def, Option::V4));
    server_id->writeAddress(IOAddress("192.0.2.3"));
    pkt->addOption(server_id);
    EXPECT_THROW_MSG(srv.processDiscover(pkt), RFCViolation,
                     "Server-id option was not expected,"
                     " but received in message DHCPDISCOVER");
}

// Verifies that DHCPREQEUSTs are sanity checked correctly.
// 1. They must have either hardware address or client id
// 2. They must have a requested address
// 3. They may or may not have a server id
TEST_F(Dhcpv4SrvTest, sanityCheckRequest) {
    NakedDhcpv4Srv srv;
    Pkt4Ptr pkt(new Pkt4(DHCPREQUEST, 1234));

    // Should throw, no hardware address or client id
    ASSERT_THROW_MSG(srv.processRequest(pkt), RFCViolation,
                     "Missing or useless client-id and no HW address"
                     " provided in message DHCPREQUEST");

    // Add a hardware address. Should not throw.
774 775
    std::vector<uint8_t> data = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
    HWAddrPtr hwaddr(new HWAddr(data, HTYPE_ETHER));
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
    pkt->setHWAddr(hwaddr);
    EXPECT_NO_THROW(srv.processRequest(pkt));

    // Now let's add a requested address. This should not throw.
    OptionDefinitionPtr req_addr_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE,
                                                             DHO_DHCP_REQUESTED_ADDRESS);
    ASSERT_TRUE(req_addr_def);
    OptionCustomPtr req_addr(new OptionCustom(*req_addr_def, Option::V4));
    req_addr->writeAddress(IOAddress("192.0.2.3"));
    pkt->addOption(req_addr);
    ASSERT_NO_THROW(srv.processRequest(pkt));

    // Now let's make a new pkt with client-id only and an address, it should not throw.
    pkt.reset(new Pkt4(DHCPREQUEST, 1234));
    pkt->addOption(generateClientId());
    pkt->addOption(req_addr);
    ASSERT_NO_THROW(srv.processRequest(pkt));

    // Now let's add a server-id. This should not throw.
    OptionDefinitionPtr server_id_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE,
                                                              DHO_DHCP_SERVER_IDENTIFIER);
    ASSERT_TRUE(server_id_def);

    OptionCustomPtr server_id(new OptionCustom(*server_id_def, Option::V4));
    server_id->writeAddress(IOAddress("192.0.2.3"));
    pkt->addOption(server_id);
    EXPECT_NO_THROW(srv.processRequest(pkt));
}

// Verifies that DHCPDECLINEs are sanity checked correctly.
// 1. They must have either hardware address or client id
// 2. They must have a requested address
// 3. They may or may not have a server id
TEST_F(Dhcpv4SrvTest, sanityCheckDecline) {
    NakedDhcpv4Srv srv;
    Pkt4Ptr pkt(new Pkt4(DHCPDECLINE, 1234));

    // Should throw, no hardware address or client id
    ASSERT_THROW_MSG(srv.processDecline(pkt), RFCViolation,
                     "Missing or useless client-id and no HW address"
                     " provided in message DHCPDECLINE");

    // Add a hardware address. Should throw because of missing address.
819 820
    std::vector<uint8_t> data = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
    HWAddrPtr hwaddr(new HWAddr(data, HTYPE_ETHER));
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
    pkt->setHWAddr(hwaddr);
    ASSERT_THROW_MSG(srv.processDecline(pkt), RFCViolation,
                    "Mandatory 'Requested IP address' option missing in DHCPDECLINE"
                    " sent from [hwtype=1 00:fe:fe:fe:fe:fe], cid=[no info], tid=0x4d2");


    // Now let's add a requested address. This should not throw.
    OptionDefinitionPtr req_addr_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE,
                                                             DHO_DHCP_REQUESTED_ADDRESS);
    ASSERT_TRUE(req_addr_def);
    OptionCustomPtr req_addr(new OptionCustom(*req_addr_def, Option::V4));
    req_addr->writeAddress(IOAddress("192.0.2.3"));
    pkt->addOption(req_addr);
    ASSERT_NO_THROW(srv.processDecline(pkt));

    // Now let's make a new pkt with client-id only and an address, it should not throw.
    pkt.reset(new Pkt4(DHCPDECLINE, 1234));
    pkt->addOption(generateClientId());
    pkt->addOption(req_addr);
    ASSERT_NO_THROW(srv.processDecline(pkt));

    // Now let's add a server-id. This should not throw.
    OptionDefinitionPtr server_id_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE,
                                                              DHO_DHCP_SERVER_IDENTIFIER);
    ASSERT_TRUE(server_id_def);

    OptionCustomPtr server_id(new OptionCustom(*server_id_def, Option::V4));
    server_id->writeAddress(IOAddress("192.0.2.3"));
    pkt->addOption(server_id);
    EXPECT_NO_THROW(srv.processDecline(pkt));
}

// Verifies that DHCPRELEASEs are sanity checked correctly.
// 1. They must have either hardware address or client id
// 2. They may or may not have a server id
TEST_F(Dhcpv4SrvTest, sanityCheckRelease) {
857
    NakedDhcpv4Srv srv;
858
    Pkt4Ptr pkt(new Pkt4(DHCPRELEASE, 1234));
859

860 861 862 863 864 865
    // Should throw, no hardware address or client id
    ASSERT_THROW_MSG(srv.processRelease(pkt), RFCViolation,
                     "Missing or useless client-id and no HW address"
                     " provided in message DHCPRELEASE");

    // Add a hardware address. Should not throw.
866 867
    std::vector<uint8_t> data = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
    HWAddrPtr hwaddr(new HWAddr(data, HTYPE_ETHER));
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
    pkt->setHWAddr(hwaddr);
    EXPECT_NO_THROW(srv.processRelease(pkt));

    // Make a new pkt with client-id only.  Should not throw.
    pkt.reset(new Pkt4(DHCPRELEASE, 1234));
    pkt->addOption(generateClientId());
    ASSERT_NO_THROW(srv.processRelease(pkt));

    // Now let's add a server-id. This should not throw.
    OptionDefinitionPtr server_id_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE,
                                                              DHO_DHCP_SERVER_IDENTIFIER);
    ASSERT_TRUE(server_id_def);

    OptionCustomPtr server_id(new OptionCustom(*server_id_def, Option::V4));
    server_id->writeAddress(IOAddress("192.0.2.3"));
    pkt->addOption(server_id);
884
    EXPECT_NO_THROW(srv.processRelease(pkt));
885 886
}

887 888 889 890 891 892 893 894 895 896 897 898 899 900
// Verifies that DHCPINFORMs are sanity checked correctly.
// 1. They must have either hardware address or client id
// 2. They may or may not have requested address
// 3. They may or may not have a server id
TEST_F(Dhcpv4SrvTest, sanityCheckInform) {
    NakedDhcpv4Srv srv;
    Pkt4Ptr pkt(new Pkt4(DHCPINFORM, 1234));

    // Should throw, no hardware address or client id
    ASSERT_THROW_MSG(srv.processInform(pkt), RFCViolation,
                     "Missing or useless client-id and no HW address"
                     " provided in message DHCPINFORM");

    // Add a hardware address. Should not throw.
901 902
    std::vector<uint8_t> data = { 0, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe};
    HWAddrPtr hwaddr(new HWAddr(data, HTYPE_ETHER));
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
    pkt->setHWAddr(hwaddr);
    ASSERT_NO_THROW(srv.processInform(pkt));

    // Now let's add a requested address. This should not throw.
    OptionDefinitionPtr req_addr_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE,
                                                             DHO_DHCP_REQUESTED_ADDRESS);
    ASSERT_TRUE(req_addr_def);
    OptionCustomPtr req_addr(new OptionCustom(*req_addr_def, Option::V4));
    req_addr->writeAddress(IOAddress("192.0.2.3"));
    pkt->addOption(req_addr);
    ASSERT_NO_THROW(srv.processInform(pkt));

    // Now let's make a new pkt with client-id only and an address, it should not throw.
    pkt.reset(new Pkt4(DHCPINFORM, 1234));
    pkt->addOption(generateClientId());
    pkt->addOption(req_addr);
    ASSERT_NO_THROW(srv.processInform(pkt));

    // Now let's add a server-id. This should not throw.
    OptionDefinitionPtr server_id_def = LibDHCP::getOptionDef(DHCP4_OPTION_SPACE,
                                                              DHO_DHCP_SERVER_IDENTIFIER);
    ASSERT_TRUE(server_id_def);

    OptionCustomPtr server_id(new OptionCustom(*server_id_def, Option::V4));
    server_id->writeAddress(IOAddress("192.0.2.3"));
    pkt->addOption(server_id);
    EXPECT_NO_THROW(srv.processInform(pkt));
}

932 933 934 935 936 937 938 939 940 941 942
// 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
943 944 945 946
TEST_F(Dhcpv4SrvTest, DiscoverBasic) {
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

947
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
948
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
949 950 951 952 953

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

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

959
    // Check if we get response at all
960 961
    checkResponse(offer, DHCPOFFER, 1234);

962
    // Check that address was returned from proper range, that its lease
963
    // lifetime is correct, that T1 and T2 are returned properly
964
    checkAddressParams(offer, subnet_, true, true);
965

966
    // Check identifiers
967 968 969 970
    checkServerId(offer, srv->getServerID());
    checkClientId(offer, clientid);
}

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 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 1043 1044 1045 1046
// This test verifies that OFFERs return expected valid lifetimes.
TEST_F(Dhcpv4SrvTest, DiscoverValidLifetime) {
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));

    // Recreate subnet
    Triplet<uint32_t> unspecified;
    Triplet<uint32_t> valid_lft(500, 1000, 1500);
    subnet_.reset(new Subnet4(IOAddress("192.0.2.0"), 24,
                              unspecified,
                              unspecified,
                              valid_lft));

    pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"),
                               IOAddress("192.0.2.110")));
    subnet_->addPool(pool_);
    CfgMgr::instance().clear();
    CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet_);
    CfgMgr::instance().commit();

    // Struct for describing an individual lifetime test scenario
    struct LifetimeTest {
        // logged test description
        std::string description_;
        // lifetime hint (0 means not send dhcp-lease-time option)
        uint32_t hint;
        // expected returned value
        uint32_t expected;
    };

    // Test scenarios
    std::vector<LifetimeTest> tests = {
        { "default valid lifetime", 0, 1000 },
        { "specified valid lifetime", 1001, 1001 },
        { "too small valid lifetime", 100, 500 },
        { "too large valid lifetime", 2000, 1500 }
    };

    // Iterate over the test scenarios.
    for (auto test : tests) {
        SCOPED_TRACE(test.description_);

        // Create a discover packet to use
        Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
        dis->setRemoteAddr(IOAddress("192.0.2.1"));
        OptionPtr clientid = generateClientId();
        dis->addOption(clientid);
        dis->setIface("eth1");

        // Add dhcp-lease-time option.
        if (test.hint) {
            OptionUint32Ptr opt(new OptionUint32(Option::V4,
                                                 DHO_DHCP_LEASE_TIME,
                                                 test.hint));
            dis->addOption(opt);
        }

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

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

        // Check that address was returned from proper range, that its lease
        // lifetime is correct and has the expected value.
        checkAddressParams(offer, subnet_, false, false, test.expected);

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

1047
// Check that option 58 and 59 are only included if they were specified
1048 1049
// (and calculate-tee-times = false) and the values are sane:
//  T2 is less than valid lft;  T1 is less than T2 (if given) or valid
1050 1051
// lft if T2 is not given.
TEST_F(Dhcpv4SrvTest, DiscoverTimers) {
1052 1053 1054 1055 1056 1057
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));

1058 1059 1060
    // Recreate subnet
    Triplet<uint32_t> unspecified;
    Triplet<uint32_t> valid_lft(1000);
1061
    subnet_.reset(new Subnet4(IOAddress("192.0.2.0"), 24,
1062 1063 1064 1065
                              unspecified,
                              unspecified,
                              valid_lft));

1066 1067 1068
    pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"),
                               IOAddress("192.0.2.110")));
    subnet_->addPool(pool_);
1069 1070 1071
    CfgMgr::instance().clear();
    CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet_);
    CfgMgr::instance().commit();
1072

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    // Struct for describing an individual timer test scenario
    struct TimerTest {
        // logged test description
        std::string description_;
        // configured value for subnet's T1
        Triplet<uint32_t> cfg_t1_;
        // configured value for subnet's T1
        Triplet<uint32_t> cfg_t2_;
        // True if Offer should contain Subnet's T1 value
        bool exp_t1_;
        // True if Offer should contain Subnet's T2 value
        bool exp_t2_;
    };
1086

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 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 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    // Convenience constants
    bool T1 = true;
    bool T2 = true;

    // Test scenarios
    std::vector<TimerTest> tests = {
    {
        "T1:unspecified, T2:unspecified",
        unspecified, unspecified,
        // Client should neither.
        !T1, !T2
    },
    {
        "T1 unspecified, T2 < VALID",
        unspecified, valid_lft - 1,
        // Client should only get T2.
        !T1, T2
    },
    {
        "T1:unspecified, T2 = VALID",
        unspecified, valid_lft,
        // Client should get neither.
        !T1, !T2
    },
    {
        "T1:unspecified, T2 > VALID",
        unspecified, valid_lft + 1,
        // Client should get neither.
        !T1, !T2
    },

    {
        "T1 < VALID, T2:unspecified",
        valid_lft - 1, unspecified,
        // Client should only get T1.
        T1, !T2
    },
    {
        "T1 = VALID, T2:unspecified",
        valid_lft, unspecified,
        // Client should get neither.
        !T1, !T2
    },
    {
        "T1 > VALID, T2:unspecified",
        valid_lft + 1, unspecified,
        // Client should get neither.
        !T1, !T2
    },
    {
        "T1 < T2 < VALID",
        valid_lft - 2, valid_lft - 1,
        // Client should get both.
        T1, T2
    },
    {
        "T1 = T2 < VALID",
        valid_lft - 1, valid_lft - 1,
        // Client should only get T2.
        !T1, T2
    },
    {
        "T1 > T2 < VALID",
        valid_lft - 1, valid_lft - 2,
        // Client should only get T2.
        !T1, T2
    },
    {
       "T1 = T2 = VALID",
        valid_lft, valid_lft,
        // Client should get neither.
        !T1, !T2
    },
    {
       "T1 > VALID < T2, T2 > VALID",
        valid_lft + 1, valid_lft + 2,
        // Client should get neither.
        !T1, !T2
    }
    };
1167

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    // Create a discover packet to use
    Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
    dis->setRemoteAddr(IOAddress("192.0.2.1"));
    OptionPtr clientid = generateClientId();
    dis->addOption(clientid);
    dis->setIface("eth1");

    // Iterate over the test scenarios.
    for (auto test = tests.begin(); test != tests.end(); ++test) {
        {
            SCOPED_TRACE((*test).description_);
            // Configure sunbet's timer values
            subnet_->setT1((*test).cfg_t1_);
            subnet_->setT2((*test).cfg_t2_);

            // Discover/Offer exchange with the server
            Pkt4Ptr offer = srv->processDiscover(dis);

            // Verify we have an offer
            checkResponse(offer, DHCPOFFER, 1234);

            // Verify the timers are as expected.
            checkAddressParams(offer, subnet_,
                               (*test).exp_t1_, (*test).exp_t2_);
        }
    }
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 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
// Check that option 58 and 59 are included when calculate-tee-times
// is enabled, but only when they are not explicitly specified via
// renew-timer and rebinding-timer.  This test does not check whether
// the subnet's for t1-percent and t2-percent are valid, as this is
// enforced by parsing and tested elsewhere.
TEST_F(Dhcpv4SrvTest, calculateTeeTimers) {
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

    boost::scoped_ptr<NakedDhcpv4Srv> srv;
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));

    // Recreate subnet
    Triplet<uint32_t> unspecified;
    Triplet<uint32_t> valid_lft(1000);
    subnet_.reset(new Subnet4(IOAddress("192.0.2.0"), 24,
                              unspecified,
                              unspecified,
                              valid_lft));

    pool_ = Pool4Ptr(new Pool4(IOAddress("192.0.2.100"),
                               IOAddress("192.0.2.110")));
    subnet_->addPool(pool_);
    CfgMgr::instance().clear();
    CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet_);
    CfgMgr::instance().commit();

    // Struct for describing an individual timer test scenario
    struct TimerTest {
        // logged test description
        std::string description_;
        // configured value for subnet's T1
        Triplet<uint32_t> cfg_t1_;
        // configured value for subnet's T1
        Triplet<uint32_t> cfg_t2_;
        // configured value for sunbet's t1_percent.
        double t1_percent_;
        // configured value for sunbet's t2_percent.
        double t2_percent_;
        // expected value for T1 in server response.
        // A value of 0 means server should not have sent T1.
        uint32_t t1_exp_value_;
        // expected value for T2 in server response.
        // A value of 0 means server should not have sent T2.
        uint32_t t2_exp_value_;
    };

    // Convenience constant
    uint32_t not_expected = 0;

    // Test scenarios
    std::vector<TimerTest> tests = {
    {
        "T1 and T2 calculated",
        unspecified, unspecified,
        0.4, 0.8,
        400, 800
    },
    {
        "T1 and T2 specified insane",
        valid_lft + 1,  valid_lft + 2,
        0.4, 0.8,
        not_expected, not_expected
    },
    {
        "T1 should be calculated, T2 specified",
        unspecified, valid_lft - 1,
        0.4, 0.8,
        400, valid_lft - 1
    },
    {
        "T1 specified, T2 should be calculated",
        299, unspecified,
        0.4, 0.8,
        299, 800
    },
    {
        "T1 specified > T2, T2 should be calculated",
        valid_lft - 1, unspecified,
        0.4, 0.8,
        not_expected, 800
    }
    };

    // Calculation is enabled for all the scenarios.
    subnet_->setCalculateTeeTimes(true);

    // Create a discover packet to use
    Pkt4Ptr dis = Pkt4Ptr(new Pkt4(DHCPDISCOVER, 1234));
    dis->setRemoteAddr(IOAddress("192.0.2.1"));
    OptionPtr clientid = generateClientId();
    dis->addOption(clientid);
    dis->setIface("eth1");

    // Iterate over the test scenarios.
    for (auto test = tests.begin(); test != tests.end(); ++test) {
        {
            SCOPED_TRACE((*test).description_);
            // Configure sunbet's timer values
            subnet_->setT1((*test).cfg_t1_);
            subnet_->setT2((*test).cfg_t2_);

            subnet_->setT1Percent((*test).t1_percent_);
            subnet_->setT2Percent((*test).t2_percent_);

            // Discover/Offer exchange with the server
            Pkt4Ptr offer = srv->processDiscover(dis);

            // Verify we have an offer
            checkResponse(offer, DHCPOFFER, 1234);

            // Check T1 timer
            OptionUint32Ptr opt = boost::dynamic_pointer_cast
                                  <OptionUint32> (offer->getOption(DHO_DHCP_RENEWAL_TIME));

            if ((*test).t1_exp_value_ == not_expected) {
                EXPECT_FALSE(opt) << "T1 present and shouldn't be";
            } else {
                ASSERT_TRUE(opt) << "Required T1 option missing or it has"
                                    " an unexpected type";
                EXPECT_EQ(opt->getValue(), (*test).t1_exp_value_);
            }

            // Check T2 timer
             opt = boost::dynamic_pointer_cast
                   <OptionUint32>(offer->getOption(DHO_DHCP_REBINDING_TIME));

            if ((*test).t2_exp_value_ == not_expected) {
                EXPECT_FALSE(opt) << "T2 present and shouldn't be";
            } else {
                ASSERT_TRUE(opt) << "Required T2 option missing or it has"
                                    " an unexpected type";
                EXPECT_EQ(opt->getValue(), (*test).t2_exp_value_);
            }
        }
    }
}

1335

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
// 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)
1348 1349 1350 1351
TEST_F(Dhcpv4SrvTest, DiscoverInvalidHint) {
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

1352
    boost::scoped_ptr<NakedDhcpv4Srv> srv;
1353
    ASSERT_NO_THROW(srv.reset(new NakedDhcpv4Srv(0)));
1354 1355 1356 1357 1358 1359 1360
    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);
1361
    dis->setIface("eth1");
1362

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

1366
    // Check if we get response at all
1367 1368
    checkResponse(offer, DHCPOFFER, 1234);