fqdn_unittest.cc 42.1 KB
Newer Older
1
// Copyright (C) 2013-2014 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 <asiolink/io_address.h>
#include <dhcp/option4_client_fqdn.h>
18
#include <dhcp/option_int_array.h>
19
#include <dhcp/tests/iface_mgr_test_config.h>
20
#include <dhcp4/tests/dhcp4_test_utils.h>
21
#include <dhcp_ddns/ncr_msg.h>
22
#include <dhcpsrv/cfgmgr.h>
23
24
25
26
27
28
29

#include <gtest/gtest.h>
#include <boost/scoped_ptr.hpp>

using namespace isc;
using namespace isc::asiolink;
using namespace isc::dhcp;
30
using namespace isc::dhcp::test;
31
using namespace isc::dhcp_ddns;
32
33

namespace {
34

35
class NameDhcpv4SrvTest : public Dhcpv4SrvTest {
36
public:
37
38
39
    // Reference to D2ClientMgr singleton
    D2ClientMgr& d2_mgr_;

40
    // Bit Constants for turning on and off DDNS configuration options.
41
42
43
44
    static const uint16_t ALWAYS_INCLUDE_FQDN = 1;
    static const uint16_t OVERRIDE_NO_UPDATE = 2;
    static const uint16_t OVERRIDE_CLIENT_UPDATE = 4;
    static const uint16_t REPLACE_CLIENT_NAME = 8;
45

46
47
    NameDhcpv4SrvTest() : Dhcpv4SrvTest(),
        d2_mgr_(CfgMgr::instance().getD2ClientMgr()) {
48
        srv_ = new NakedDhcpv4Srv(0);
49
50
        // Config DDNS to be enabled, all controls off
        enableD2();
51
    }
52

53
    virtual ~NameDhcpv4SrvTest() {
54
        delete srv_;
55
56
57
        // CfgMgr singleton doesn't get wiped between tests, so  we'll
        // disable D2 explictly between tests.
        disableD2();
58
59
    }

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    /// @brief Sets the server's DDNS configuration to ddns updates disabled.
    void disableD2() {
        // Default constructor creates a config with DHCP-DDNS updates
        // disabled.
        D2ClientConfigPtr cfg(new D2ClientConfig());
        CfgMgr::instance().setD2ClientConfig(cfg);
    }

    /// @brief Enables DHCP-DDNS updates with the given options enabled.
    ///
    /// Replaces the current D2ClientConfiguration with a configuration
    /// which as updates enabled and the control options set based upon
    /// the bit mask of options.
    ///
    /// @param mask Bit mask of configuration options that should be enabled.
    void enableD2(const uint16_t mask = 0) {
        D2ClientConfigPtr cfg;

        ASSERT_NO_THROW(cfg.reset(new D2ClientConfig(true,
79
                                  isc::asiolink::IOAddress("127.0.0.1"), 53001,
80
                                  isc::asiolink::IOAddress("0.0.0.0"), 0, 1024,
81
82
83
84
85
86
                                  dhcp_ddns::NCR_UDP, dhcp_ddns::FMT_JSON,
                                  (mask & ALWAYS_INCLUDE_FQDN),
                                  (mask & OVERRIDE_NO_UPDATE),
                                  (mask & OVERRIDE_CLIENT_UPDATE),
                                  (mask & REPLACE_CLIENT_NAME),
                                  "myhost", "example.com")));
87
88
        ASSERT_NO_THROW(CfgMgr::instance().setD2ClientConfig(cfg));
        ASSERT_NO_THROW(srv_->startD2());
89
90
    }

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    // Create a lease to be used by various tests.
    Lease4Ptr createLease(const isc::asiolink::IOAddress& addr,
                          const std::string& hostname,
                          const bool fqdn_fwd,
                          const bool fqdn_rev) {
        const uint8_t hwaddr[] = { 0, 1, 2, 3, 4, 5, 6 };
        Lease4Ptr lease(new Lease4(addr, hwaddr, sizeof(hwaddr),
                                   &generateClientId()->getData()[0],
                                   generateClientId()->getData().size(),
                                   100, 50, 75, time(NULL), subnet_->getID()));
        // @todo Set this through the Lease4 constructor.
        lease->hostname_ = hostname;
        lease->fqdn_fwd_ = fqdn_fwd;
        lease->fqdn_rev_ = fqdn_rev;

        return (lease);
    }

109
110
111
112
    // Create an instance of the DHCPv4 Client FQDN Option.
    Option4ClientFqdnPtr
    createClientFqdn(const uint8_t flags,
                     const std::string& fqdn_name,
113
                     Option4ClientFqdn::DomainNameType fqdn_type) {
114
115
116
117
118
        return (Option4ClientFqdnPtr(new Option4ClientFqdn(flags,
                                                           Option4ClientFqdn::
                                                           RCODE_CLIENT(),
                                                           fqdn_name,
                                                           fqdn_type)));
119
120
121
   }

    // Create an instance of the Hostname option.
122
    OptionStringPtr
123
    createHostname(const std::string& hostname) {
124
125
126
        OptionStringPtr opt_hostname(new OptionString(Option::V4,
                                                      DHO_HOST_NAME,
                                                      hostname));
127
        return (opt_hostname);
128
129
    }

130
131
132
133
134
135
136
137
138
139
    /// @brief Convenience method for generating an FQDN from an IP address.
    ///
    /// This is just a wrapper method around the D2ClientMgr's method for
    /// generating domain names from the configured prefix, suffix, and a
    /// given IP address.  This is useful for verifying that fully generated
    /// names are correct.
    ///
    /// @param addr IP address used in the lease.
    ///
    /// @return An std::string contained the generated FQDN.
140
    std::string generatedNameFromAddress(const IOAddress& addr) {
141
        return(CfgMgr::instance().getD2ClientMgr().generateFqdn(addr));
142
143
    }

144
    // Get the Client FQDN Option from the given message.
145
146
147
148
149
    Option4ClientFqdnPtr getClientFqdnOption(const Pkt4Ptr& pkt) {
        return (boost::dynamic_pointer_cast<
                Option4ClientFqdn>(pkt->getOption(DHO_FQDN)));
    }

150
    // get the Hostname option from the given message.
151
    OptionStringPtr getHostnameOption(const Pkt4Ptr& pkt) {
152
        return (boost::dynamic_pointer_cast<
153
                OptionString>(pkt->getOption(DHO_HOST_NAME)));
154
155
    }

156
157
158
159
    // Create a message holding DHCPv4 Client FQDN Option.
    Pkt4Ptr generatePktWithFqdn(const uint8_t msg_type,
                                const uint8_t fqdn_flags,
                                const std::string& fqdn_domain_name,
160
                                Option4ClientFqdn::DomainNameType fqdn_type,
161
162
                                const bool include_prl,
                                const bool include_clientid = true) {
163
164
        Pkt4Ptr pkt = Pkt4Ptr(new Pkt4(msg_type, 1234));
        pkt->setRemoteAddr(IOAddress("192.0.2.3"));
165
        pkt->setIface("eth1");
166
167
168
169
170
        // For DISCOVER we don't include server id, because client broadcasts
        // the message to all servers.
        if (msg_type != DHCPDISCOVER) {
            pkt->addOption(srv_->getServerID());
        }
171
172
173
174

        if (include_clientid) {
            pkt->addOption(generateClientId());
        }
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192

        // Create Client FQDN Option with the specified flags and
        // domain-name.
        pkt->addOption(createClientFqdn(fqdn_flags, fqdn_domain_name,
                                        fqdn_type));

        // Control whether or not to request that server returns the FQDN
        // option. Server may be configured to always return it or return
        // only in case client requested it.
        if (include_prl) {
            OptionUint8ArrayPtr option_prl =
                OptionUint8ArrayPtr(new OptionUint8Array(Option::V4,
                                    DHO_DHCP_PARAMETER_REQUEST_LIST));
            option_prl->addValue(DHO_FQDN);
        }
        return (pkt);
    }

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    // Create a message holding a Hostname option.
    Pkt4Ptr generatePktWithHostname(const uint8_t msg_type,
                                    const std::string& hostname) {

        Pkt4Ptr pkt = Pkt4Ptr(new Pkt4(msg_type, 1234));
        pkt->setRemoteAddr(IOAddress("192.0.2.3"));
        // For DISCOVER we don't include server id, because client broadcasts
        // the message to all servers.
        if (msg_type != DHCPDISCOVER) {
            pkt->addOption(srv_->getServerID());
        }

        pkt->addOption(generateClientId());


        // Create Client FQDN Option with the specified flags and
        // domain-name.
        pkt->addOption(createHostname(hostname));

        return (pkt);

214
    }
215

216
217
218
    // Test that server generates the appropriate FQDN option in response to
    // client's FQDN option.
    void testProcessFqdn(const Pkt4Ptr& query, const uint8_t exp_flags,
219
                         const std::string& exp_domain_name,
220
                         Option4ClientFqdn::DomainNameType
221
                         exp_domain_type = Option4ClientFqdn::FULL) {
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
        ASSERT_TRUE(getClientFqdnOption(query));

        Pkt4Ptr answer;
        if (query->getType() == DHCPDISCOVER) {
            answer.reset(new Pkt4(DHCPOFFER, 1234));

        } else {
            answer.reset(new Pkt4(DHCPACK, 1234));

        }
        ASSERT_NO_THROW(srv_->processClientName(query, answer));

        Option4ClientFqdnPtr fqdn = getClientFqdnOption(answer);
        ASSERT_TRUE(fqdn);

237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        checkFqdnFlags(answer, exp_flags);

        EXPECT_EQ(exp_domain_name, fqdn->getDomainName());
        EXPECT_EQ(exp_domain_type, fqdn->getDomainNameType());

    }

    /// @brief Checks the packet's FQDN option flags against a given mask
    ///
    /// @param pkt IPv4 packet whose FQDN flags should be checked.
    /// @param exp_flags Bit mask of flags that are expected to be true.
    void checkFqdnFlags(const Pkt4Ptr& pkt, const uint8_t exp_flags) {
        Option4ClientFqdnPtr fqdn = getClientFqdnOption(pkt);
        ASSERT_TRUE(fqdn);

252
253
254
255
256
257
258
259
260
261
262
        const bool flag_n = (exp_flags & Option4ClientFqdn::FLAG_N) != 0;
        const bool flag_s = (exp_flags & Option4ClientFqdn::FLAG_S) != 0;
        const bool flag_o = (exp_flags & Option4ClientFqdn::FLAG_O) != 0;
        const bool flag_e = (exp_flags & Option4ClientFqdn::FLAG_E) != 0;

        EXPECT_EQ(flag_n, fqdn->getFlag(Option4ClientFqdn::FLAG_N));
        EXPECT_EQ(flag_s, fqdn->getFlag(Option4ClientFqdn::FLAG_S));
        EXPECT_EQ(flag_o, fqdn->getFlag(Option4ClientFqdn::FLAG_O));
        EXPECT_EQ(flag_e, fqdn->getFlag(Option4ClientFqdn::FLAG_E));
    }

263

264
265
266
267
    // Processes the Hostname option in the client's message and returns
    // the hostname option which would be sent to the client. It will
    // throw NULL pointer if the hostname option is not to be included
    // in the response.
268
    OptionStringPtr processHostname(const Pkt4Ptr& query) {
269
270
271
        if (!getHostnameOption(query)) {
            ADD_FAILURE() << "Hostname option not carried in the query";
        }
272
273
274
275
276
277
278
279
280

        Pkt4Ptr answer;
        if (query->getType() == DHCPDISCOVER) {
            answer.reset(new Pkt4(DHCPOFFER, 1234));

        } else {
            answer.reset(new Pkt4(DHCPACK, 1234));

        }
281
        srv_->processClientName(query, answer);
282

283
        OptionStringPtr hostname = getHostnameOption(answer);
284
        return (hostname);
285
286
287

    }

288
289
    // Test that the client message holding an FQDN is processed and
    // that the response packet is as expected.
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
    void testProcessMessageWithFqdn(const uint8_t msg_type,
                            const std::string& hostname) {
        Pkt4Ptr req = generatePktWithFqdn(msg_type, Option4ClientFqdn::FLAG_S |
                                          Option4ClientFqdn::FLAG_E, hostname,
                                          Option4ClientFqdn::FULL, true);
        Pkt4Ptr reply;
        if (msg_type == DHCPDISCOVER) {
            ASSERT_NO_THROW(reply = srv_->processDiscover(req));

        } else if (msg_type == DHCPREQUEST) {
            ASSERT_NO_THROW(reply = srv_->processRequest(req));

        } else if (msg_type == DHCPRELEASE) {
            ASSERT_NO_THROW(srv_->processRelease(req));
            return;

        } else {
            return;
        }

        if (msg_type == DHCPDISCOVER) {
            checkResponse(reply, DHCPOFFER, 1234);

        } else {
            checkResponse(reply, DHCPACK, 1234);
        }

    }

319
320
321
322
    // Verify that NameChangeRequest holds valid values.
    void verifyNameChangeRequest(const isc::dhcp_ddns::NameChangeType type,
                                 const bool reverse, const bool forward,
                                 const std::string& addr,
323
                                 const std::string& fqdn,
324
                                 const std::string& dhcid,
325
326
327
                                 const time_t cltt,
                                 const uint16_t len,
                                 const bool not_strict_expire_check = false) {
328
329
330
331
332
333
334
335
336
        NameChangeRequestPtr ncr;
        ASSERT_NO_THROW(ncr = d2_mgr_.peekAt(0));
        ASSERT_TRUE(ncr);

        EXPECT_EQ(type, ncr->getChangeType());
        EXPECT_EQ(forward, ncr->isForwardChange());
        EXPECT_EQ(reverse, ncr->isReverseChange());
        EXPECT_EQ(addr, ncr->getIpAddress());
        EXPECT_EQ(fqdn, ncr->getFqdn());
337
338
339
        // Compare dhcid if it is not empty. In some cases, the DHCID is
        // not known in advance and can't be compared.
        if (!dhcid.empty()) {
340
            EXPECT_EQ(dhcid, ncr->getDhcid().toStr());
341
        }
342
343
344
345
346
347
        // In some cases, the test doesn't have access to the last transmission
        // time for the particular client. In such cases, the test can use the
        // current time as cltt but the it may not check the lease expiration time
        // for equality but rather check that the lease expiration time is not
        // greater than the current time + lease lifetime.
        if (not_strict_expire_check) {
348
            EXPECT_GE(cltt + len, ncr->getLeaseExpiresOn());
349
        } else {
350
            EXPECT_EQ(cltt + len, ncr->getLeaseExpiresOn());
351
        }
352
353
354
355
356
        EXPECT_EQ(len, ncr->getLeaseLength());
        EXPECT_EQ(isc::dhcp_ddns::ST_NEW, ncr->getStatus());

        // Process the message off the queue
        ASSERT_NO_THROW(d2_mgr_.runReadyIO());
357
358
    }

359
360
361
362
363
364
365
366
367
368
369
370
371
372

    /// @brief Tests processing a request with the given client flags
    ///
    /// This method creates a request with its FQDN flags set to the given
    /// value and submits it to the server for processing.  It then checks
    /// the following:
    /// 1. Did the server generate an ACK with the correct FQDN flags
    /// 2. If the server should have generated an NCR, did it? and If
    /// so was it correct?
    ///
    /// @param client_flags Mask of client FQDN flags which are true
    /// @param response_flags Mask of expected FQDN flags in the response
    void flagVsConfigScenario(const uint8_t client_flags,
                       const uint8_t response_flags) {
373
374
375
376
        // Create fake interfaces and open fake sockets.
        IfaceMgrTestConfig iface_config(true);
        IfaceMgr::instance().openSockets4();

377
378
379
380
381
382
383
384
385
386
387
388
        Pkt4Ptr req = generatePktWithFqdn(DHCPREQUEST, client_flags,
                                          "myhost.example.com.",
                                          Option4ClientFqdn::FULL, true);

        // Process the request.
        Pkt4Ptr reply;
        ASSERT_NO_THROW(reply = srv_->processRequest(req));

        // Verify the response and flags.
        checkResponse(reply, DHCPACK, 1234);
        checkFqdnFlags(reply, response_flags);

389
390
        // NCRs cannot be sent to the d2_mgr unless updates are enabled.
        if (d2_mgr_.ddnsEnabled()) {
391
392
393
394
            // There should be an NCR if response S flag is 1 or N flag is 0.
            bool exp_fwd = (response_flags & Option4ClientFqdn::FLAG_S);
            bool exp_rev = (!(response_flags & Option4ClientFqdn::FLAG_N));
            if (!exp_fwd && !exp_rev) {
395
396
397
398
                ASSERT_EQ(0, d2_mgr_.getQueueSize());
            } else {
                // Verify that there is one NameChangeRequest as expected.
                ASSERT_EQ(1, d2_mgr_.getQueueSize());
399
400
                verifyNameChangeRequest(isc::dhcp_ddns::CHG_ADD,
                                        exp_rev, exp_fwd,
401
402
403
404
405
406
                                        reply->getYiaddr().toText(),
                                        "myhost.example.com.",
                                        "", // empty DHCID means don't check it
                                        time(NULL) + subnet_->getValid(),
                                        subnet_->getValid(), true);
            }
407
408
409
410
        }
    }


411
412
413
414
    NakedDhcpv4Srv* srv_;

};

415
416
// Test that the exception is thrown if lease pointer specified as the argument
// of computeDhcid function is NULL.
417
TEST_F(NameDhcpv4SrvTest, dhcidNullLease) {
418
419
420
421
422
423
424
    Lease4Ptr lease;
    EXPECT_THROW(srv_->computeDhcid(lease), isc::dhcp::DhcidComputeError);

}

// Test that the appropriate exception is thrown if the lease object used
// to compute DHCID comprises wrong hostname.
425
TEST_F(NameDhcpv4SrvTest, dhcidWrongHostname) {
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
    // First, make sure that the lease with the correct hostname is accepted.
    Lease4Ptr lease = createLease(IOAddress("192.0.2.3"),
                                  "myhost.example.com.", true, true);
    ASSERT_NO_THROW(srv_->computeDhcid(lease));

    // Now, use the wrong hostname. It should result in the exception.
    lease->hostname_ = "myhost...example.com.";
    EXPECT_THROW(srv_->computeDhcid(lease), isc::dhcp::DhcidComputeError);

    // Also, empty hostname is wrong.
    lease->hostname_ = "";
    EXPECT_THROW(srv_->computeDhcid(lease), isc::dhcp::DhcidComputeError);
}

// Test that the DHCID is computed correctly, when the lease holds
// correct hostname and non-NULL client id.
442
TEST_F(NameDhcpv4SrvTest, dhcidComputeFromClientId) {
443
444
445
446
447
448
449
450
451
452
453
454
455
456
    Lease4Ptr lease = createLease(IOAddress("192.0.2.3"),
                                  "myhost.example.com.",
                                  true, true);
    isc::dhcp_ddns::D2Dhcid dhcid;
    ASSERT_NO_THROW(dhcid = srv_->computeDhcid(lease));

    // Make sure that the computed DHCID is valid.
    std::string dhcid_ref = "00010132E91AA355CFBB753C0F0497A5A9404"
        "36965B68B6D438D98E680BF10B09F3BCF";
    EXPECT_EQ(dhcid_ref, dhcid.toStr());
}

// Test that the DHCID is computed correctly, when the lease holds correct
// hostname and NULL client id.
457
TEST_F(NameDhcpv4SrvTest, dhcidComputeFromHWAddr) {
458
459
460
461
462
463
464
465
466
467
468
469
470
471
    Lease4Ptr lease = createLease(IOAddress("192.0.2.3"),
                                  "myhost.example.com.",
                                  true, true);
    lease->client_id_.reset();

    isc::dhcp_ddns::D2Dhcid dhcid;
    ASSERT_NO_THROW(dhcid = srv_->computeDhcid(lease));

    // Make sure that the computed DHCID is valid.
    std::string dhcid_ref = "0000012247F6DC4423C3E8627434A9D6868609"
        "D88948F78018B215EDCAA30C0C135035";
    EXPECT_EQ(dhcid_ref, dhcid.toStr());
}

472
473
474
475
476
477
478
479
480
481
482
483
484
485
// Tests the following scenario:
//  - Updates are enabled
//  - All overrides are off
//  - Client requests forward update  (N = 0, S = 1)
//
//  Server should perform the update:
//  - Reponse flags should N = 0, S = 1, O = 0
//  - Should queue an NCR
TEST_F(NameDhcpv4SrvTest, updatesEnabled) {
    flagVsConfigScenario((Option4ClientFqdn::FLAG_E |
                          Option4ClientFqdn::FLAG_S),
                          (Option4ClientFqdn::FLAG_E |
                           Option4ClientFqdn::FLAG_S));
}
486

487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// Tests the following scenario
//  - Updates are disabled
//  - Client requests forward update  (N = 0, S = 1)
//
//  Server should NOT perform updates:
//   - Response flags should N = 1, S = 0, O = 1
//   - Should not queue any NCRs
TEST_F(NameDhcpv4SrvTest, updatesDisabled) {
    disableD2();
    flagVsConfigScenario((Option4ClientFqdn::FLAG_E |
                          Option4ClientFqdn::FLAG_S),
                          (Option4ClientFqdn::FLAG_E |
                           Option4ClientFqdn::FLAG_N |
                           Option4ClientFqdn::FLAG_O));
}
502

503
504
505
506
507
508
509
510
511
512
513
514
515
516
// Tests the following scenario:
//  - Updates are enabled
//  - All overrides are off.
//  - Client requests no updates  (N = 1, S = 0)
//
//  Server should NOT perform updates:
//  - Response flags should N = 1, S = 0, O = 0
//  - Should not queue any NCRs
TEST_F(NameDhcpv4SrvTest, respectNoUpdate) {
    flagVsConfigScenario((Option4ClientFqdn::FLAG_E |
                          Option4ClientFqdn::FLAG_N),
                          (Option4ClientFqdn::FLAG_E |
                           Option4ClientFqdn::FLAG_N));
}
517

518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// Tests the following scenario:
//  - Updates are enabled
//  - override-no-update is on
//  - Client requests no updates  (N = 1, S = 0)
//
// Server should override "no update" request and perform updates:
// - Response flags should be  N = 0, S = 1, O = 1
// - Should queue an NCR
TEST_F(NameDhcpv4SrvTest, overrideNoUpdate) {
    enableD2(OVERRIDE_NO_UPDATE);
    flagVsConfigScenario((Option4ClientFqdn::FLAG_E |
                          Option4ClientFqdn::FLAG_N),
                          (Option4ClientFqdn::FLAG_E |
                           Option4ClientFqdn::FLAG_S |
                           Option4ClientFqdn::FLAG_O));
}

// Tests the following scenario:
//  - Updates are enabled
//  - All overrides are off.
//  - Client requests delegation  (N = 0, S = 0)
//
// Server should respect client's delegation request and NOT do updates:

542
// - Response flags should be  N = 0, S = 0, O = 0
543
544
545
546
// - Should not queue any NCRs
TEST_F(NameDhcpv4SrvTest, respectClientDelegation) {

    flagVsConfigScenario(Option4ClientFqdn::FLAG_E,
547
                         Option4ClientFqdn::FLAG_E);
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
}

// Tests the following scenario:
//  - Updates are enabled
//  - override-client-update is on.
//  - Client requests delegation  (N = 0, S = 0)
//
// Server should override client's delegation request and do updates:
// - Response flags should be  N = 0, S = 1, O = 1
// - Should queue an NCR
TEST_F(NameDhcpv4SrvTest, overrideClientDelegation) {
    // Turn on override-client-update.
    enableD2(OVERRIDE_CLIENT_UPDATE);

    flagVsConfigScenario(Option4ClientFqdn::FLAG_E,
                         (Option4ClientFqdn::FLAG_E |
                          Option4ClientFqdn::FLAG_S |
                          Option4ClientFqdn::FLAG_O));
566
567
}

568
// Test that server processes the Hostname option sent by a client and
569
570
// responds with the Hostname option to confirm that the server has
// taken responsibility for the update.
571
TEST_F(NameDhcpv4SrvTest, serverUpdateHostname) {
572
573
574
    Pkt4Ptr query;
    ASSERT_NO_THROW(query = generatePktWithHostname(DHCPREQUEST,
                                                    "myhost.example.com."));
575
    OptionStringPtr hostname;
576
577
578
    ASSERT_NO_THROW(hostname = processHostname(query));

    ASSERT_TRUE(hostname);
579
    EXPECT_EQ("myhost.example.com.", hostname->getValue());
580
581
582
583
584
585
586
587

}

// Test that the server skips processing of a wrong Hostname option.
TEST_F(NameDhcpv4SrvTest, serverUpdateWrongHostname) {
    Pkt4Ptr query;
    ASSERT_NO_THROW(query = generatePktWithHostname(DHCPREQUEST,
                                                    "abc..example.com"));
588
    OptionStringPtr hostname;
589
590
    ASSERT_NO_THROW(hostname = processHostname(query));
    EXPECT_FALSE(hostname);
591
592
}

593

594
595
// Test that server generates the fully qualified domain name for the client
// if client supplies the partial name.
596
TEST_F(NameDhcpv4SrvTest, serverUpdateForwardPartialNameFqdn) {
597
598
599
600
601
602
603
604
605
606
607
608
609
    Pkt4Ptr query = generatePktWithFqdn(DHCPREQUEST,
                                        Option4ClientFqdn::FLAG_E |
                                        Option4ClientFqdn::FLAG_S,
                                        "myhost",
                                        Option4ClientFqdn::PARTIAL,
                                        true);

    testProcessFqdn(query,
                    Option4ClientFqdn::FLAG_E | Option4ClientFqdn::FLAG_S,
                    "myhost.example.com.");

}

610
611
612
// Test that server generates the fully qualified domain name for the client
// if client supplies the unqualified name in the Hostname option.
TEST_F(NameDhcpv4SrvTest, serverUpdateUnqualifiedHostname) {
613
614
    Pkt4Ptr query;
    ASSERT_NO_THROW(query = generatePktWithHostname(DHCPREQUEST, "myhost"));
615
    OptionStringPtr hostname;
616
617
618
    ASSERT_NO_THROW(hostname =  processHostname(query));

    ASSERT_TRUE(hostname);
619
    EXPECT_EQ("myhost.example.com.", hostname->getValue());
620

621
622
}

623
624
625
626
// Test that server sets empty domain-name in the FQDN option when client
// supplied no domain-name. The domain-name is supposed to be set after the
// lease is acquired. The domain-name is then generated from the IP address
// assigned to a client.
627
TEST_F(NameDhcpv4SrvTest, serverUpdateForwardNoNameFqdn) {
628
629
630
631
632
633
634
635
636
    Pkt4Ptr query = generatePktWithFqdn(DHCPREQUEST,
                                        Option4ClientFqdn::FLAG_E |
                                        Option4ClientFqdn::FLAG_S,
                                        "",
                                        Option4ClientFqdn::PARTIAL,
                                        true);

    testProcessFqdn(query,
                    Option4ClientFqdn::FLAG_E | Option4ClientFqdn::FLAG_S,
637
                    "", Option4ClientFqdn::PARTIAL);
638
639
640

}

641
642
// Test that exactly one NameChangeRequest is generated when the new lease
// has been acquired (old lease is NULL).
643
TEST_F(NameDhcpv4SrvTest, createNameChangeRequestsNewLease) {
644
645
646
647
648
    Lease4Ptr lease = createLease(IOAddress("192.0.2.3"), "myhost.example.com.",
                                  true, true);
    Lease4Ptr old_lease;

    ASSERT_NO_THROW(srv_->createNameChangeRequests(lease, old_lease));
649
    ASSERT_EQ(1, d2_mgr_.getQueueSize());
650
651

    verifyNameChangeRequest(isc::dhcp_ddns::CHG_ADD, true, true,
652
653
654
                            "192.0.2.3", "myhost.example.com.",
                            "00010132E91AA355CFBB753C0F0497A5A940436965"
                            "B68B6D438D98E680BF10B09F3BCF",
655
                            lease->cltt_, 100);
656
657
658
659
}

// Test that no NameChangeRequest is generated when a lease is renewed and
// the FQDN data hasn't changed.
660
TEST_F(NameDhcpv4SrvTest, createNameChangeRequestsRenewNoChange) {
661
662
663
664
665
666
667
    Lease4Ptr lease = createLease(IOAddress("192.0.2.3"), "myhost.example.com.",
                                  true, true);
    Lease4Ptr old_lease = createLease(IOAddress("192.0.2.3"),
                                      "myhost.example.com.", true, true);
    old_lease->valid_lft_ += 100;

    ASSERT_NO_THROW(srv_->createNameChangeRequests(lease, old_lease));
668
    ASSERT_EQ(0, d2_mgr_.getQueueSize());
669
}
670

671
672
// Test that no NameChangeRequest is generated when forward and reverse
// DNS update flags are not set in the lease.
673
TEST_F(NameDhcpv4SrvTest, createNameChangeRequestsNoUpdate) {
674
675
676
677
678
679
680
    Lease4Ptr lease1 = createLease(IOAddress("192.0.2.3"),
                                   "lease1.example.com.",
                                   true, true);
    Lease4Ptr lease2 = createLease(IOAddress("192.0.2.3"),
                                   "lease2.example.com.",
                                   false, false);
    ASSERT_NO_THROW(srv_->createNameChangeRequests(lease2, lease1));
681
    EXPECT_EQ(1, d2_mgr_.getQueueSize());
682
683
684
685
686

    verifyNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE, true, true,
                            "192.0.2.3", "lease1.example.com.",
                            "0001013A5B311F5B9FB10DDF8E53689B874F25D"
                            "62CC147C2FF237A64C90E5A597C9B7A",
687
                            lease1->cltt_, 100);
688
689
690
691
692

    lease2->hostname_ = "";
    lease2->fqdn_rev_ = true;
    lease2->fqdn_fwd_ = true;
    ASSERT_NO_THROW(srv_->createNameChangeRequests(lease2, lease1));
693
    EXPECT_EQ(1, d2_mgr_.getQueueSize());
694
695
696
697
698

}

// Test that two NameChangeRequests are generated when the lease is being
// renewed and the new lease has updated FQDN data.
699
TEST_F(NameDhcpv4SrvTest, createNameChangeRequestsRenew) {
700
701
702
703
704
705
706
    Lease4Ptr lease1 = createLease(IOAddress("192.0.2.3"),
                                   "lease1.example.com.",
                                   true, true);
    Lease4Ptr lease2 = createLease(IOAddress("192.0.2.3"),
                                   "lease2.example.com.",
                                   true, true);
    ASSERT_NO_THROW(srv_->createNameChangeRequests(lease2, lease1));
707
    ASSERT_EQ(2, d2_mgr_.getQueueSize());
708
709
710
711
712

    verifyNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE, true, true,
                            "192.0.2.3", "lease1.example.com.",
                            "0001013A5B311F5B9FB10DDF8E53689B874F25D"
                            "62CC147C2FF237A64C90E5A597C9B7A",
713
                            lease1->cltt_, 100);
714
715
716
717
718

    verifyNameChangeRequest(isc::dhcp_ddns::CHG_ADD, true, true,
                            "192.0.2.3", "lease2.example.com.",
                            "000101F906D2BB752E1B2EECC5FF2BF434C0B2D"
                            "D6D7F7BD873F4F280165DB8C9DBA7CB",
719
                            lease2->cltt_, 100);
720
721
722
723
724
725

}

// This test verifies that exception is thrown when leases passed to the
// createNameChangeRequests function do not match, i.e. they comprise
// different IP addresses, client ids etc.
726
TEST_F(NameDhcpv4SrvTest, createNameChangeRequestsLeaseMismatch) {
727
728
729
730
731
732
733
734
735
    Lease4Ptr lease1 = createLease(IOAddress("192.0.2.3"),
                                   "lease1.example.com.",
                                   true, true);
    Lease4Ptr lease2 = createLease(IOAddress("192.0.2.4"),
                                   "lease2.example.com.",
                                   true, true);
    EXPECT_THROW(srv_->createNameChangeRequests(lease2, lease1),
                 isc::Unexpected);
}
736

737
738
// Test that the OFFER message generated as a result of the DISCOVER message
// processing will not result in generation of the NameChangeRequests.
739
TEST_F(NameDhcpv4SrvTest, processDiscover) {
740
741
742
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

743
744
745
746
747
748
749
750
751
    Pkt4Ptr req = generatePktWithFqdn(DHCPDISCOVER, Option4ClientFqdn::FLAG_S |
                                      Option4ClientFqdn::FLAG_E,
                                      "myhost.example.com.",
                                      Option4ClientFqdn::FULL, true);

    Pkt4Ptr reply;
    ASSERT_NO_THROW(reply = srv_->processDiscover(req));
    checkResponse(reply, DHCPOFFER, 1234);

752
    EXPECT_EQ(0, d2_mgr_.getQueueSize());
753
754
}

755
756
757
// Test that server generates client's hostname from the IP address assigned
// to it when DHCPv4 Client FQDN option specifies an empty domain-name.
TEST_F(NameDhcpv4SrvTest, processRequestFqdnEmptyDomainName) {
758
759
760
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

761
762
763
764
765
766
767
768
769
770
    Pkt4Ptr req = generatePktWithFqdn(DHCPREQUEST, Option4ClientFqdn::FLAG_S |
                                      Option4ClientFqdn::FLAG_E,
                                      "", Option4ClientFqdn::PARTIAL, true);

    Pkt4Ptr reply;
    ASSERT_NO_THROW(reply = srv_->processRequest(req));

    checkResponse(reply, DHCPACK, 1234);

    // Verify that there is one NameChangeRequest generated.
771
    ASSERT_EQ(1, d2_mgr_.getQueueSize());
772

773
    // The hostname is generated from the IP address acquired (yiaddr).
774
775
    std::string hostname = generatedNameFromAddress(reply->getYiaddr());

776
    verifyNameChangeRequest(isc::dhcp_ddns::CHG_ADD, true, true,
777
                            reply->getYiaddr().toText(), hostname,
778
                            "", // empty DHCID forces that it is not checked
779
780
                            time(NULL) + subnet_->getValid(),
                            subnet_->getValid(), true);
781
782
}

783
784
785
786
// Test that server generates client's hostname from the IP address assigned
// to it when DHCPv4 Client FQDN option specifies an empty domain-name  AND
// ddns updates are disabled.
TEST_F(NameDhcpv4SrvTest, processRequestEmptyDomainNameDisabled) {
787
788
789
790
    // Create fake interfaces and open fake sockets.
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
    disableD2();
    Pkt4Ptr req = generatePktWithFqdn(DHCPREQUEST, Option4ClientFqdn::FLAG_S |
                                      Option4ClientFqdn::FLAG_E,
                                      "", Option4ClientFqdn::PARTIAL, true);
    Pkt4Ptr reply;
    ASSERT_NO_THROW(reply = srv_->processRequest(req));

    checkResponse(reply, DHCPACK, 1234);

    Option4ClientFqdnPtr fqdn = getClientFqdnOption(reply);
    ASSERT_TRUE(fqdn);

    // The hostname is generated from the IP address acquired (yiaddr).
    std::string hostname = generatedNameFromAddress(reply->getYiaddr());

    EXPECT_EQ(hostname, fqdn->getDomainName());
    EXPECT_EQ(Option4ClientFqdn::FULL, fqdn->getDomainNameType());
}


811
812
// Test that server generates client's hostname from the IP address assigned
// to it when Hostname option carries the top level domain-name.
813
TEST_F(NameDhcpv4SrvTest, processRequestTopLevelHostname) {
814
815
816
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

817
    Pkt4Ptr req = generatePktWithHostname(DHCPREQUEST, ".");
818
819
    // Set interface for the incoming packet. The server requires it to
    // generate client id.
820
    req->setIface("eth1");
821
822
823
824
825
826
827

    Pkt4Ptr reply;
    ASSERT_NO_THROW(reply = srv_->processRequest(req));

    checkResponse(reply, DHCPACK, 1234);

    // Verify that there is one NameChangeRequest generated.
828
    ASSERT_EQ(1, d2_mgr_.getQueueSize());
829

830
    // The hostname is generated from the IP address acquired (yiaddr).
831
832
    std::string hostname = generatedNameFromAddress(reply->getYiaddr());

833
    verifyNameChangeRequest(isc::dhcp_ddns::CHG_ADD, true, true,
834
                            reply->getYiaddr().toText(), hostname,
835
                            "", // empty DHCID forces that it is not checked
836
                            time(NULL), subnet_->getValid(), true);
837
838
}

839
840
841
842
// Test that client may send two requests, each carrying FQDN option with
// a different domain-name. Server should use existing lease for the second
// request but modify the DNS entries for the lease according to the contents
// of the FQDN sent in the second request.
843
TEST_F(NameDhcpv4SrvTest, processTwoRequestsFqdn) {
844
845
846
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

847
848
849
850
851
852
853
854
855
856
857
    Pkt4Ptr req1 = generatePktWithFqdn(DHCPREQUEST, Option4ClientFqdn::FLAG_S |
                                       Option4ClientFqdn::FLAG_E,
                                       "myhost.example.com.",
                                       Option4ClientFqdn::FULL, true);

    Pkt4Ptr reply;
    ASSERT_NO_THROW(reply = srv_->processRequest(req1));

    checkResponse(reply, DHCPACK, 1234);

    // Verify that there is one NameChangeRequest generated.
858
    ASSERT_EQ(1, d2_mgr_.getQueueSize());
859
860
861
862
    verifyNameChangeRequest(isc::dhcp_ddns::CHG_ADD, true, true,
                            reply->getYiaddr().toText(), "myhost.example.com.",
                            "00010132E91AA355CFBB753C0F0497A5A940436"
                            "965B68B6D438D98E680BF10B09F3BCF",
863
                            time(NULL), subnet_->getValid(), true);
864
865
866
867
868
869
870
871
872
873
874
875
876

    // Create another Request message but with a different FQDN. Server
    // should generate two NameChangeRequests: one to remove existing entry,
    // another one to add new entry with updated domain-name.
    Pkt4Ptr req2 = generatePktWithFqdn(DHCPREQUEST, Option4ClientFqdn::FLAG_S |
                                       Option4ClientFqdn::FLAG_E,
                                       "otherhost.example.com.",
                                       Option4ClientFqdn::FULL, true);

    ASSERT_NO_THROW(reply = srv_->processRequest(req2));

    checkResponse(reply, DHCPACK, 1234);

877
    // There should be two NameChangeRequests. Verify that they are valid.
878
    ASSERT_EQ(2, d2_mgr_.getQueueSize());
879
880
881
882
883
    verifyNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE, true, true,
                            reply->getYiaddr().toText(),
                            "myhost.example.com.",
                            "00010132E91AA355CFBB753C0F0497A5A940436"
                            "965B68B6D438D98E680BF10B09F3BCF",
884
                            time(NULL), subnet_->getValid(), true);
885
886
887
888
889
890

    verifyNameChangeRequest(isc::dhcp_ddns::CHG_ADD, true, true,
                            reply->getYiaddr().toText(),
                            "otherhost.example.com.",
                            "000101A5AEEA7498BD5AD9D3BF600E49FF39A7E3"
                            "AFDCE8C3D0E53F35CC584DD63C89CA",
891
                            time(NULL), subnet_->getValid(), true);
892
893
894
895
896
897
898
}

// Test that client may send two requests, each carrying Hostname option with
// a different name. Server should use existing lease for the second request
// but modify the DNS entries for the lease according to the contents of the
// Hostname sent in the second request.
TEST_F(NameDhcpv4SrvTest, processTwoRequestsHostname) {
899
900
901
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

902
903
    Pkt4Ptr req1 = generatePktWithHostname(DHCPREQUEST, "myhost.example.com.");

904
905
    // Set interface for the incoming packet. The server requires it to
    // generate client id.
906
    req1->setIface("eth1");
907
908


909
910
911
912
913
914
    Pkt4Ptr reply;
    ASSERT_NO_THROW(reply = srv_->processRequest(req1));

    checkResponse(reply, DHCPACK, 1234);

    // Verify that there is one NameChangeRequest generated.
915
    ASSERT_EQ(1, d2_mgr_.getQueueSize());
916
917
918
919
    verifyNameChangeRequest(isc::dhcp_ddns::CHG_ADD, true, true,
                            reply->getYiaddr().toText(), "myhost.example.com.",
                            "00010132E91AA355CFBB753C0F0497A5A940436"
                            "965B68B6D438D98E680BF10B09F3BCF",
920
                            time(NULL), subnet_->getValid(), true);
921
922
923
924
925
926

    // Create another Request message but with a different Hostname. Server
    // should generate two NameChangeRequests: one to remove existing entry,
    // another one to add new entry with updated domain-name.
    Pkt4Ptr req2 = generatePktWithHostname(DHCPREQUEST, "otherhost");

927
928
    // Set interface for the incoming packet. The server requires it to
    // generate client id.
929
    req2->setIface("eth1");
930

931
932
933
934
    ASSERT_NO_THROW(reply = srv_->processRequest(req2));

    checkResponse(reply, DHCPACK, 1234);

935
    // There should be two NameChangeRequests. Verify that they are valid.
936
    ASSERT_EQ(2, d2_mgr_.getQueueSize());
937
938
939
940
941
    verifyNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE, true, true,
                            reply->getYiaddr().toText(),
                            "myhost.example.com.",
                            "00010132E91AA355CFBB753C0F0497A5A940436"
                            "965B68B6D438D98E680BF10B09F3BCF",
942
                            time(NULL), subnet_->getValid(), true);
943
944
945
946
947
948

    verifyNameChangeRequest(isc::dhcp_ddns::CHG_ADD, true, true,
                            reply->getYiaddr().toText(),
                            "otherhost.example.com.",
                            "000101A5AEEA7498BD5AD9D3BF600E49FF39A7E3"
                            "AFDCE8C3D0E53F35CC584DD63C89CA",
949
                            time(NULL), subnet_->getValid(), true);
950
951
}

952
// Test that when a release message is sent for a previously acquired lease,
953
954
955
// DDNS updates are enabled that the server genenerates a NameChangeRequest
// to remove entries corresponding to the released lease.
TEST_F(NameDhcpv4SrvTest, processRequestRelease) {
956
957
958
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

959
    // Verify the updates are enabled.
960
961
962
    ASSERT_TRUE(CfgMgr::instance().ddnsEnabled());

    // Create and process a lease request so we have a lease to release.
963
964
965
966
967
968
969
970
    Pkt4Ptr req = generatePktWithFqdn(DHCPREQUEST, Option4ClientFqdn::FLAG_S |
                                      Option4ClientFqdn::FLAG_E,
                                      "myhost.example.com.",
                                      Option4ClientFqdn::FULL, true);
    Pkt4Ptr reply;
    ASSERT_NO_THROW(reply = srv_->processRequest(req));
    checkResponse(reply, DHCPACK, 1234);

971
    // Verify that there is one NameChangeRequest generated for lease.
972
    ASSERT_EQ(1, d2_mgr_.getQueueSize());
973
974
975
976
    verifyNameChangeRequest(isc::dhcp_ddns::CHG_ADD, true, true,
                            reply->getYiaddr().toText(), "myhost.example.com.",
                            "00010132E91AA355CFBB753C0F0497A5A940436"
                            "965B68B6D438D98E680BF10B09F3BCF",
977
                            time(NULL), subnet_->getValid(), true);
978

979
    // Create and process the Release message.
980
981
982
983
984
985
986
987
988
    Pkt4Ptr rel = Pkt4Ptr(new Pkt4(DHCPRELEASE, 1234));
    rel->setCiaddr(reply->getYiaddr());
    rel->setRemoteAddr(IOAddress("192.0.2.3"));
    rel->addOption(generateClientId());
    rel->addOption(srv_->getServerID());
    ASSERT_NO_THROW(srv_->processRelease(rel));

    // The lease has been removed, so there should be a NameChangeRequest to
    // remove corresponding DNS entries.
989
    ASSERT_EQ(1, d2_mgr_.getQueueSize());
990
991
992
993
994
    verifyNameChangeRequest(isc::dhcp_ddns::CHG_REMOVE, true, true,
                            reply->getYiaddr().toText(), "myhost.example.com.",
                            "00010132E91AA355CFBB753C0F0497A5A940436"
                            "965B68B6D438D98E680BF10B09F3BCF",
                            time(NULL), subnet_->getValid(), true);
995
996
}

997
998
999
// Test that when the Release message is sent for a previously acquired lease
// and DDNS updates are disabled that server does NOT generate a
// NameChangeRequest to remove entries corresponding to the released lease.
1000
1001
1002
// Queue size is not available when updates are not enabled, however,
// attempting to send a NCR when updates disabled will result in a throw.
// If no throws are experienced then no attempt was made to send a NCR.
1003
TEST_F(NameDhcpv4SrvTest, processRequestReleaseUpdatesDisabled) {
1004
1005
1006
1007
    // Create fake interfaces and open fake sockets.
    IfaceMgrTestConfig test_config(true);
    IfaceMgr::instance().openSockets4();

1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
    // Disable DDNS.
    disableD2();
    ASSERT_FALSE(CfgMgr::instance().ddnsEnabled());

    // Create and process a lease request so we have a lease to release.
    Pkt4Ptr req = generatePktWithFqdn(DHCPREQUEST, Option4ClientFqdn::FLAG_S |
                                      Option4ClientFqdn::FLAG_E,
                                      "myhost.example.com.",
                                      Option4ClientFqdn::FULL, true);
    Pkt4Ptr reply;
    ASSERT_NO_THROW(reply = srv_->processRequest(req));
    checkResponse(reply, DHCPACK, 1234);

    // Create and process the Release message.
    Pkt4Ptr rel = Pkt4Ptr(new Pkt4(DHCPRELEASE, 1234));
    rel->setCiaddr(reply->getYiaddr());
    rel->setRemoteAddr(IOAddress("192.0.2.3"));
    rel->addOption(generateClientId());
    rel->addOption(srv_->getServerID());
    ASSERT_NO_THROW(srv_->processRelease(rel));
}


1031
} // end of anonymous namespace