1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// Copyright (C) 2023-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Kea Hooks Basic
// Commercial End User License Agreement v2.0. See COPYING file in the premium/
// directory.

#include <config.h>
#include <asiolink/asio_wrapper.h>
#include <asiolink/interval_timer.h>
#include <asiolink/io_service.h>
#include <dhcp/testutils/iface_mgr_test_config.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/lease_mgr_factory.h>
#include <bulk_lease_query.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <bulk_lease_query6.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <lease_query_impl_factory.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <lease_query_listener.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <lease_query_test_client.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <blq6_utils.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <testutils/gtest_utils.h>

#include <gtest/gtest.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

using namespace boost::asio::ip;
using namespace isc::asiolink;
using namespace isc::data;
using namespace isc::tcp;
using namespace isc::lease_query;
using namespace isc::lease_query::test;

namespace ph = std::placeholders;

namespace {

/// @brief IPv6 address to which service is bound.
const std::string SERVER_ADDRESS = "::1";

/// @brief Port number to which service is bound.
const unsigned short SERVER_PORT = 18123;

/// @brief Connection idle timeout used in most of the tests (ms).
const long IDLE_TIMEOUT = 10000;

/// @brief Connection idle timeout used in tests where idle connections
/// are tested (ms).
const long SHORT_IDLE_TIMEOUT = 200;

/// @brief Test timeout (ms).
const long TEST_TIMEOUT = 10000;

/// @brief Simple test fixture for testing XidQueue.
class XidQueue6Test : public ::testing::Test {
public:
    /// @brief Class of test queries..
    class TestQuery {
    public:
        /// @brief Constructor.
        ///
        /// @param xid Xid of the query.
        /// @param xid address ip address used in the query.
        TestQuery(const Xid& xid, const IOAddress& address) :
            xid_(xid), address_(address) {
        }

        /// @brief Destructor.
        virtual ~TestQuery() {
        }

        /// @brief Get xid.
        Xid getXid() const {
            return (xid_);
        }

   private:
        /// The xid.
        Xid xid_;

        /// The address.
        IOAddress address_;
    };

    /// @brief Type of pointers to test queries.
    typedef boost::shared_ptr<TestQuery> TestQueryPtr;
};

// Verifies BulkLeaseQueryList operations.
TEST_F(XidQueue6Test, queue) {<--- syntax error
    // Create some queries.
    TestQueryPtr query1(new TestQuery(78, IOAddress("3001::1")));
    TestQueryPtr query2(new TestQuery(79, IOAddress("3001::2")));
    TestQueryPtr query3(new TestQuery(80, IOAddress("3001::3")));

    // Create an empty list.
    XidQueue<TestQuery> queries;
    ASSERT_EQ(0, queries.size());

    // Add a query to the list.
    ASSERT_NO_THROW(queries.add(query1));
    EXPECT_EQ(1, queries.size());
    TestQueryPtr query;

    // Verify we can find the query.
    ASSERT_NO_THROW(query = queries.find(query1->getXid()));
    ASSERT_TRUE(query);
    EXPECT_EQ(query, query1);

    // Add a second one.
    ASSERT_NO_THROW(queries.add(query2));
    EXPECT_EQ(2, queries.size());

    // Verify we can find it.
    ASSERT_NO_THROW(query = queries.find(query2->getXid()));
    ASSERT_TRUE(query);
    EXPECT_EQ(query, query2);

    // Add another one.
    ASSERT_NO_THROW(queries.add(query3));
    EXPECT_EQ(3, queries.size());

    // Verify we can find the last one.
    ASSERT_NO_THROW(query = queries.find(query3->getXid()));
    ASSERT_TRUE(query);
    EXPECT_EQ(query, query3);

    // Remove one.
    ASSERT_NO_THROW(queries.remove(query2->getXid()));
    EXPECT_EQ(2, queries.size());

    // Verify it's gone.
    ASSERT_NO_THROW(query = queries.find(query2->getXid()));
    EXPECT_FALSE(query);

    // Pop the first.
    ASSERT_NO_THROW(query = queries.pop());
    ASSERT_TRUE(query);
    EXPECT_EQ(query, query1);
    EXPECT_EQ(1, queries.size());

    // Clear the list.
    ASSERT_NO_THROW(queries.clear());
    EXPECT_EQ(0, queries.size());
}

/// @brief Test fixture class for @ref LeaseQueryListener.  It exercises
/// connections and responding to clients.
class LeaseQueryListenerTest6 : public BlqPacketTest6 {
public:
    /// @brief Path name of server's duid file
    static const string duid_file_;

    /// @brief Constructor.
    ///
    /// Starts test timer which detects timeouts.
    LeaseQueryListenerTest6()
        : io_service_(new IOService()), test_timer_(io_service_),
          run_io_service_timer_(io_service_),
          clients_(), clients_done_(0) {
          test_timer_.setup(std::bind(&LeaseQueryListenerTest6::timeoutHandler,
                                      this, true),
                            TEST_TIMEOUT,
                            IntervalTimer::ONE_SHOT);
        CfgMgr::instance().clear();
    }

    virtual void SetUp() {
        BlqPacketTest6::SetUp();
        LeaseMgrFactory::destroy();
        LeaseMgrFactory::create("type=memfile persist=false universe=6 "
                                "extended-info-tables=true");
        // Configure a server id
        CfgMgr& cfg_mgr = CfgMgr::instance();
        server_id_ = cfg_mgr.getStagingCfg()->getCfgDUID()->create(duid_file_);

        // Commit the config.
        cfg_mgr.commit();

        // Create an implementation.
        const std::string json = "{ \"requesters\" : [ \"2001:db8:3::1\" ] }";
        ConstElementPtr config;
        ASSERT_NO_THROW_LOG(config = Element::fromJSON(json));
        LeaseQueryImpl::terminated_ = false;
        ASSERT_NO_THROW_LOG(LeaseQueryImplFactory::createImpl(AF_INET6, config));
    }

    /// @brief Destructor.
    ///
    /// Removes active clients.
    virtual ~LeaseQueryListenerTest6() {
        for (auto const& client : clients_) {
            client->close();
        }

        LeaseQueryImplFactory::destroyImpl();
        LeaseMgrFactory::destroy();
        CfgMgr::instance().clear();
        static_cast<void>(remove(duid_file_.c_str()));
        test_timer_.cancel();
        io_service_->stop();
        io_service_->restart();
        try {
            io_service_->poll();
        } catch (...) {
        }
    }

    /// @brief Create a new listener.
    virtual LeaseQueryListenerPtr
    makeListener(const TlsContextPtr& tls_context,
                 const TcpListener::IdleTimeout& idle_timeout,
                 const TcpConnectionFilterCallback& filter_callback = 0) {
        LeaseQueryListenerPtr listener(
            new LeaseQueryListener(io_service_,
                                   IOAddress(SERVER_ADDRESS),
                                   SERVER_PORT,
                                   tls_context,
                                   idle_timeout,
                                   filter_callback,
                                   AF_INET6));
        return (listener);
    }

    /// @brief Create client.
    ///
    /// This method creates LeaseQueryTestClient instance and retains it
    /// in the clients_ list.
    LeaseQueryTestClientPtr createClient() {
        LeaseQueryTestClientPtr client(new LeaseQueryTestClient(io_service_,
                                       std::bind(&LeaseQueryListenerTest6::clientDone, this),
                                       AF_INET6, SERVER_ADDRESS));
        clients_.push_back(client);
        return (client);
    }

    /// @brief Connect to the endpoint.
    ///
    /// This method creates LeaseQueryTestClient instance and retains it
    /// in the clients_ list.
    void connectClient() {
        LeaseQueryTestClientPtr client = createClient();
        if (!client) {
            isc_throw(isc::Unexpected, "failed to create a client");
        }
        client->connect();
    }

    /// @brief Connect to the endpoint and send a request.
    ///
    /// This method creates a LeaseQueryTestClient instance and initiates a
    /// request.
    ///
    /// @param request String containing the request to be sent.
    void startRequest(BlqQueryPtr query) {
        LeaseQueryTestClientPtr client = createClient();
        client->startRequest(query);
    }

    /// @brief Connect to the endpoint and send a list of requests.
    ///
    /// This method creates a LeaseQueryTestClient instance and initiates a
    /// series of requests.
    ///
    /// @param request String containing the request to be sent.
    void startRequests(const std::list<BlqQueryPtr>& requests) {
        LeaseQueryTestClientPtr client = createClient();
        client->startRequests(requests);
    }

    /// @brief Callback function invoke upon test timeout.
    ///
    /// It stops the IO service and reports test timeout.
    ///
    /// @param fail_on_timeout Specifies if test failure should be reported.
    void timeoutHandler(const bool fail_on_timeout) {
        if (fail_on_timeout) {
            ADD_FAILURE() << "Timeout occurred while running the test!";
        }
        io_service_->stop();
    }

    /// @brief Callback function each client invokes when done.
    ///
    /// It stops the IO service when all clients are done.
    ///
    /// @param fail_on_timeout Specifies if test failure should be reported.
    void clientDone() {
        ++clients_done_;
        if (clients_done_ >= clients_.size()) {
            // They're all done or dead. Stop the service.
            io_service_->stop();
        }
    }

    /// @brief Runs IO service with optional timeout.
    ///
    /// @param timeout Optional value specifying for how long the io service
    /// should be ran.
    void runIOService(long timeout = 0) {
        io_service_->stop();
        io_service_->restart();

        if (timeout > 0) {
            run_io_service_timer_.setup(std::bind(&LeaseQueryListenerTest6::timeoutHandler,
                                                  this, false),
                                        timeout,
                                        IntervalTimer::ONE_SHOT);
        }
        io_service_->run();
        io_service_->stop();
        io_service_->restart();
        io_service_->poll();
    }

    /// @brief Filter that denies every other connection.
    ///
    /// @param remote_endpoint_address ip address of the remote end of
    /// a connection.
    bool connectionFilter(const boost::asio::ip::tcp::endpoint& remote_endpoint) {
        static size_t count = 0;
        // If the address doesn't match, something hinky is going on, so
        // we'll reject them all.  If it does match, then cool, it works
        // as expected.
        if ((count++ % 2) ||
            (remote_endpoint.address().to_string() != SERVER_ADDRESS)) {
            // Reject every other connection.
            return (false);
        }

        return (true);
    }

    /// @brief Constructs a DHCPv6 bulk query by IP address.
    ///
    /// @param qr_iaaddr Address to query for.
    /// @return An BlqQuery containing the query packet.
    BlqQueryPtr makeBlqQueryByIpAddress(const IOAddress& qry_iaaddr) {
        Pkt6Ptr lq = makeQueryByIpAddress6(qry_iaaddr);
        return (BlqQueryPtr(new BlqQuery(lq)));
    }

    /// @brief IO service used in the tests.
    IOServicePtr io_service_;

    /// @brief Asynchronous timer service to detect timeouts.
    IntervalTimer test_timer_;

    /// @brief Asynchronous timer for running IO service for a specified amount
    /// of time.
    IntervalTimer run_io_service_timer_;

    /// @brief List of client connections.
    std::list<LeaseQueryTestClientPtr> clients_;

    /// @brief Counts the number of clients that have reported as done.
    size_t clients_done_;

    /// @brief Convenience values.
    DuidPtr server_id_;
};

/// @brief Path name for server-id generation
const string LeaseQueryListenerTest6::duid_file_
    = string(TEST_DATA_BUILDDIR) + string("/lq6-duid");

// This test verifies that A TCP connection can be established and used to
// transmit a V6 LeaseQuery query and receive a LeaseQuery response.
TEST_F(LeaseQueryListenerTest6, listen) {
    LeaseQueryListenerPtr listener =
        makeListener(TlsContextPtr(),
                     TcpListener::IdleTimeout(IDLE_TIMEOUT),
                     TcpConnectionFilterCallback(0));
    ASSERT_TRUE(listener);

    ASSERT_NO_THROW(listener->start());
    ASSERT_EQ(SERVER_ADDRESS, listener->getLocalAddress().toText());
    ASSERT_EQ(SERVER_PORT, listener->getLocalPort());

    BlqQueryPtr request = makeBlqQueryByIpAddress(IOAddress("2001:db8::1"));
    ASSERT_NO_THROW(startRequest(request));

    ASSERT_NO_THROW(runIOService());
    ASSERT_EQ(1, clients_.size());
    LeaseQueryTestClientPtr client = *clients_.begin();
    ASSERT_TRUE(client);
    EXPECT_TRUE(client->receiveDone());
    EXPECT_FALSE(client->expectedEof());
    client->checkResponses();

    listener->stop();
    io_service_->poll();
}

// This test verifies that A TCP connection will be timed out and closed if
// it remains idle for longer than the idle timeout.
TEST_F(LeaseQueryListenerTest6, idleTimeoutTest) {
    LeaseQueryListenerPtr listener =
        makeListener(TlsContextPtr(),
                     TcpListener::IdleTimeout(SHORT_IDLE_TIMEOUT),
                     TcpConnectionFilterCallback(0));
    ASSERT_TRUE(listener);

    ASSERT_NO_THROW(listener->start());
    ASSERT_EQ(SERVER_ADDRESS, listener->getLocalAddress().toText());
    ASSERT_EQ(SERVER_PORT, listener->getLocalPort());
    ASSERT_NO_THROW(connectClient());
    ASSERT_EQ(1, clients_.size());
    LeaseQueryTestClientPtr client = *clients_.begin();
    ASSERT_TRUE(client);

    // Tell the client expecting reading to fail with an EOF.
    ASSERT_NO_THROW(client->waitForEof());

    // Run until idle timer expires.
    ASSERT_NO_THROW(runIOService());
    EXPECT_FALSE(client->receiveDone());
    EXPECT_TRUE(client->expectedEof());

    listener->stop();
    io_service_->poll();
}

// This test verifies that a client connection can submit and receive
// responses to multiple queries.
TEST_F(LeaseQueryListenerTest6, multipleQueries) {
    LeaseQueryListenerPtr listener =
        makeListener(TlsContextPtr(),
                     TcpListener::IdleTimeout(IDLE_TIMEOUT),
                     TcpConnectionFilterCallback(0));
    ASSERT_TRUE(listener);


    ASSERT_NO_THROW(listener->start());
    ASSERT_EQ(SERVER_ADDRESS, listener->getLocalAddress().toText());
    ASSERT_EQ(SERVER_PORT, listener->getLocalPort());
    size_t num_requests = 4;
    std::list<BlqQueryPtr> requests;
    for (auto i = 0; i < num_requests; ++i) {
        BlqQueryPtr request =
            makeBlqQueryByIpAddress(IOAddress("2001:db8::1"));
        requests.push_back(request);
    }

    ASSERT_NO_THROW(startRequests(requests));
    ASSERT_NO_THROW(runIOService());

    ASSERT_EQ(1, clients_.size());
    LeaseQueryTestClientPtr client = *clients_.begin();
    ASSERT_TRUE(client);
    EXPECT_TRUE(client->receiveDone());
    EXPECT_FALSE(client->expectedEof());
    client->checkResponses();

    listener->stop();
    io_service_->poll();
}

// This test verifies that the listener can support multiple, concurrent client
// connections.
TEST_F(LeaseQueryListenerTest6, multipleClientsListen) {
    LeaseQueryListenerPtr listener =
        makeListener(TlsContextPtr(),
                     TcpListener::IdleTimeout(IDLE_TIMEOUT),
                     TcpConnectionFilterCallback(0));
    ASSERT_TRUE(listener);

    ASSERT_NO_THROW(listener->start());
    ASSERT_EQ(SERVER_ADDRESS, listener->getLocalAddress().toText());
    ASSERT_EQ(SERVER_PORT, listener->getLocalPort());
    size_t num_clients = 5;
    std::list<BlqQueryPtr> requests;
    for (auto i = 0; i < num_clients; ++i) {
        BlqQueryPtr request =
            makeBlqQueryByIpAddress(IOAddress("2001:db8::1"));
        ASSERT_NO_THROW(startRequest(request));
        requests.push_back(request);
    }

    ASSERT_NO_THROW(runIOService());
    ASSERT_EQ(num_clients, clients_.size());

    for (auto const& client : clients_) {
        EXPECT_TRUE(client->receiveDone());
        EXPECT_FALSE(client->expectedEof());
        client->checkResponses();
    }

    listener->stop();
    io_service_->poll();
}

// This test verifies that the listener handles multiple requests from multiple
// clients.
TEST_F(LeaseQueryListenerTest6, multipleRequetsPerClients) {
    LeaseQueryListenerPtr listener =
        makeListener(TlsContextPtr(),
                     TcpListener::IdleTimeout(IDLE_TIMEOUT),
                     TcpConnectionFilterCallback(0));
    ASSERT_TRUE(listener);

    ASSERT_NO_THROW(listener->start());
    ASSERT_EQ(SERVER_ADDRESS, listener->getLocalAddress().toText());
    ASSERT_EQ(SERVER_PORT, listener->getLocalPort());
    size_t num_clients = 5;
    size_t num_requests = 4;
    for (auto i = 0; i < num_clients; ++i) {
        std::list<BlqQueryPtr> requests;
        for (auto j = 0; j < num_requests; ++j) {
            BlqQueryPtr request =
                makeBlqQueryByIpAddress(IOAddress("2001:db8::1"));
            requests.push_back(request);
        }

        ASSERT_NO_THROW(startRequests(requests));
    }

    ASSERT_NO_THROW(runIOService());
    ASSERT_EQ(num_clients, clients_.size());

    for (auto const& client : clients_) {
        EXPECT_TRUE(client->receiveDone());
        EXPECT_FALSE(client->expectedEof());
        EXPECT_EQ(num_requests, client->getResponses().size());
        client->checkResponses();
    }

    listener->stop();
    io_service_->poll();
}

// This test verifies that connection filtering can eliminate specific connections.
TEST_F(LeaseQueryListenerTest6, filterClientsTest) {
    LeaseQueryListenerPtr listener
        = makeListener(TlsContextPtr(),
                       TcpListener::IdleTimeout(IDLE_TIMEOUT),
                       std::bind(&LeaseQueryListenerTest6::connectionFilter, this, ph::_1));

    ASSERT_NO_THROW(listener->start());
    ASSERT_EQ(SERVER_ADDRESS, listener->getLocalAddress().toText());
    ASSERT_EQ(SERVER_PORT, listener->getLocalPort());
    size_t num_clients = 5;
    std::list<BlqQueryPtr> requests;
    for (auto i = 0; i < num_clients; ++i) {
        // Every other client sends nothing (i.e. waits for EOF) as
        // we expect the filter to reject them.
        if (i % 2 == 0) {
            BlqQueryPtr request =
                makeBlqQueryByIpAddress(IOAddress("2001:db8::1"));
            requests.push_back(request);
            ASSERT_NO_THROW(startRequest(request));
        } else {
            ASSERT_NO_THROW(startRequest(BlqQueryPtr()));
        }
    }

    ASSERT_NO_THROW(runIOService());
    ASSERT_EQ(num_clients, clients_.size());

    size_t i = 0;
    for (auto const& client : clients_) {
        if (i % 2 == 0) {
            // These clients should have been accepted and received responses.
            EXPECT_TRUE(client->receiveDone());
            EXPECT_FALSE(client->expectedEof());
            EXPECT_EQ(1, client->getResponses().size());
            client->checkResponses();
        } else {
            // These clients should have been rejected and gotten EOF'd.
            EXPECT_FALSE(client->receiveDone());
            EXPECT_TRUE(client->expectedEof());
            EXPECT_EQ(0, client->getResponses().size());
        }

        ++i;
    }

    listener->stop();
    io_service_->poll();
}

}