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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
// Copyright (C) 2022-2023 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/io_address.h>
#include <cc/data.h>
#include <database/audit_entry.h>
#include <dhcp/pkt4.h>
#include <dhcp/pkt6.h>
#include <dhcpsrv/cfg_option.h>
#include <dhcpsrv/cfg_option_def.h>
#include <dhcpsrv/cfg_subnets4.h>
#include <dhcpsrv/cfg_subnets6.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/srv_config.h>
#include <dhcpsrv/subnet.h>
#include <eval/token.h>
#include <hooks/callout_handle.h>
#include <hooks/hooks_manager.h>
#include <hooks/library_handle.h>
#include <hooks/library_manager_collection.h>
#include <process/daemon.h>
#include <limits/limit_manager.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <testutils/gtest_utils.h>
#include <testutils/lib_load_test_fixture.h>

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

namespace {

using namespace isc::data;
using namespace isc::db;
using namespace isc::dhcp;
using namespace isc::hooks;
using namespace isc::process;

using isc::asiolink::IOAddress;

// Fixture for loading, unloading libraries and for testing callouts. Occasionally uses rate limits
// to test reconfiguration. Lease limits are considered to behave the same way in that regard, and
// for that reason, they are not explicitly tested.
class LimitsLibLoadTest : public isc::test::LibLoadTest {
public:

    // Constructor.
    LimitsLibLoadTest() : LibLoadTest(LIBDHCP_LIMITS_SO) {
    }

    // At the beginning of each test, simulate a library unload, effectively removing any
    // configuration and any packet counter in the limit manager. There is no way to remove all
    // client classes and all subnets from the configuration so remove them one by one.
    void SetUp() override {
        CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->removeClass("foo");

        if (CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->getBySubnetId(1)) {
            CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->del(1);
        }
        if (CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->getBySubnetId(1)) {
            CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->del(1);
        }

        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->empty())
            << "expected empty client class configuration, found "
            << CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->toElement()->str();
        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->getAll()->empty());
        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->getAll()->empty());
        CfgMgr::instance().commit();
    }

    // Registers v4 hooks in the hook manager.
    void registerV4Hooks() {
        hook_index_cb4_updated_ = HooksManager::registerHook("cb4_updated");
        hook_index_dhcp4_srv_configured_ = HooksManager::registerHook("dhcp4_srv_configured");
        hook_index_pkt4_receive_ = HooksManager::registerHook("pkt4_receive");
        hook_index_subnet4_select_ = HooksManager::registerHook("subnet4_select");
        hook_index_lease4_select_ = HooksManager::registerHook("lease4_select");
        hook_index_lease4_renew_ = HooksManager::registerHook("lease4_renew");
        LeaseMgrFactory::create("type=memfile persist=false universe=4");
    }

    // Registers v6 hooks in the hook manager.
    void registerV6Hooks() {
        hook_index_cb6_updated_ = HooksManager::registerHook("cb6_updated");
        hook_index_dhcp6_srv_configured_ = HooksManager::registerHook("dhcp6_srv_configured");
        hook_index_pkt6_receive_ = HooksManager::registerHook("pkt6_receive");
        hook_index_subnet6_select_ = HooksManager::registerHook("subnet6_select");
        hook_index_lease6_select_ = HooksManager::registerHook("lease6_select");
        hook_index_lease6_renew_ = HooksManager::registerHook("lease6_renew");
        hook_index_lease6_rebind_ = HooksManager::registerHook("lease6_rebind");
        LeaseMgrFactory::create("type=memfile persist=false universe=6");
    }

    // Checks that all v4 callouts are present.
    void calloutsV4Present() {
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_cb4_updated_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_dhcp4_srv_configured_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_pkt4_receive_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_subnet4_select_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_lease4_select_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_lease4_renew_));
    }

    // Checks that all v6 callouts are present.
    void calloutsV6Present() {
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_cb6_updated_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_dhcp6_srv_configured_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_pkt6_receive_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_subnet6_select_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_lease6_select_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_lease6_renew_));
        EXPECT_TRUE(HooksManager::calloutsPresent(hook_index_lease6_rebind_));
    }

    // Call the cb4_updated callout with client class updates or subnet updates.
    void callCb4Updated(CalloutHandlePtr& handle, bool add_client_class = false, bool add_subnet = false) {
        AuditEntryCollectionPtr audit_entries(boost::make_shared<AuditEntryCollection>());

        if (add_client_class) {
            ClientClassDefPtr client_class(boost::make_shared<ClientClassDef>("foo", ExpressionPtr()));
            client_class->setContext(Element::fromJSON(
                R"({ "limits": { "rate-limit": "1 packet per minute" } })"));
            CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->addClass(client_class);

            audit_entries->insert(boost::make_shared<AuditEntry>("dhcp4_client_class",
                                                                 client_class->getId(),
                                                                 AuditEntry::ModificationType::CREATE,
                                                                 client_class->getModificationTime(),
                                                                 1, "added audit entry"));
        }

        if (add_subnet) {
            Subnet4Ptr subnet(
                boost::make_shared<Subnet4>(IOAddress("192.168.0.0"), 24, 900, 1800, 3600, 1));
            subnet->setContext(Element::fromJSON(R"({ "limits": { "rate-limit": "1 packet per minute" } })"));
            CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet);

            audit_entries->insert(boost::make_shared<AuditEntry>("dhcp4_subnet",
                                                                 subnet->getId(),
                                                                 AuditEntry::ModificationType::CREATE,
                                                                 subnet->getModificationTime(),
                                                                 1, "added audit entry"));
        }

        CfgMgr::instance().commit();

        // Add the audit_entries to the callout arguments.
        handle->setArgument("audit_entries", audit_entries);

        // Execute the callout.
        ASSERT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_cb4_updated_, *handle));
        ASSERT_EQ(handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
    }

    // Call the cb6_updated callout with client class updates or subnet updates.
    void callCb6Updated(CalloutHandlePtr& handle, bool add_client_class = false, bool add_subnet = false) {
        AuditEntryCollectionPtr audit_entries(boost::make_shared<AuditEntryCollection>());

        if (add_client_class) {
            ClientClassDefPtr client_class(boost::make_shared<ClientClassDef>("foo", ExpressionPtr()));
            client_class->setContext(Element::fromJSON(
                R"({ "limits": { "rate-limit": "1 packet per minute" } })"));
            CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->addClass(client_class);

            audit_entries->insert(boost::make_shared<AuditEntry>("dhcp6_client_class",
                                                                 client_class->getId(),
                                                                 AuditEntry::ModificationType::CREATE,
                                                                 client_class->getModificationTime(),
                                                                 1, "added audit entry"));
        }

        if (add_subnet) {
            Subnet6Ptr subnet(
                boost::make_shared<Subnet6>(IOAddress("2001:db8::"), 64, 450, 900, 1800, 3600, 1));
            subnet->setContext(Element::fromJSON(R"({ "limits": { "rate-limit": "1 packet per minute" } })"));
            CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->add(subnet);

            audit_entries->insert(boost::make_shared<AuditEntry>("dhcp6_subnet",
                                                                 subnet->getId(),
                                                                 AuditEntry::ModificationType::CREATE,
                                                                 subnet->getModificationTime(),
                                                                 1, "added audit entry"));
        }

        CfgMgr::instance().commit();

        // Add the audit_entries to the callout arguments.
        handle->setArgument("audit_entries", audit_entries);

        // Execute the callout.
        ASSERT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_cb6_updated_, *handle));
        ASSERT_EQ(handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
    }

    // Test that the updates from the cb4_updated callout get propagated to the limit manager.
    void testCb4Updated(bool add_client_class, bool add_subnet) {
        addLibrary(LIBDHCP_LIMITS_SO, ElementPtr());
        registerV4Hooks();

        // Load the library.
        EXPECT_TRUE(loadLibraries());
        calloutsV4Present();

        // In a real environment, configuration is committed after libraries are loaded.
        CfgMgr::instance().commit();

        CalloutHandlePtr cb_handle(HooksManager::createCalloutHandle());
        callCb4Updated(cb_handle, add_client_class, add_subnet);

        // Send four packets. Based on the set limit, there should be two drops and two continues.
        for (unsigned int j = 0; j < 4; ++j) {
            {
                CalloutHandlePtr handle(HooksManager::createCalloutHandle());
                Pkt4Ptr packet(boost::make_shared<Pkt4>(1, 128));
                packet->addClass("foo");
                Subnet4Ptr subnet(
                    boost::make_shared<Subnet4>(IOAddress("192.168.0.0"), 24, 900, 1800, 3600, 1));
                handle->setArgument("query4", packet);
                handle->setArgument("subnet4", subnet);

                EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_pkt4_receive_, *handle));
                EXPECT_EQ(handle->getStatus(), add_client_class ?
                    (j < 1 ? CalloutHandle::NEXT_STEP_CONTINUE : CalloutHandle::NEXT_STEP_DROP) :
                    CalloutHandle::NEXT_STEP_CONTINUE);
            }

            {
                CalloutHandlePtr handle(HooksManager::createCalloutHandle());
                Pkt4Ptr packet(boost::make_shared<Pkt4>(1, 128));
                packet->addClass("foo");
                Subnet4Ptr subnet(
                    boost::make_shared<Subnet4>(IOAddress("192.168.0.0"), 24, 900, 1800, 3600, 1));
                handle->setArgument("query4", packet);
                handle->setArgument("subnet4", subnet);

                EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_subnet4_select_, *handle));
                EXPECT_EQ(handle->getStatus(), add_subnet ?
                    (j < 1 ? CalloutHandle::NEXT_STEP_CONTINUE : CalloutHandle::NEXT_STEP_DROP) :
                    CalloutHandle::NEXT_STEP_CONTINUE);
            }
        }
    }

    // Test that the updates from the cb6_updated callout get propagated to the limit manager.
    void testCb6Updated(bool add_client_class, bool add_subnet) {
        addLibrary(LIBDHCP_LIMITS_SO, ElementPtr());
        registerV6Hooks();

        // Load the library.
        EXPECT_TRUE(loadLibraries());
        calloutsV6Present();
        {
            CalloutHandlePtr srv_configured_handle(HooksManager::createCalloutHandle());
            srv_configured_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
            ASSERT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_dhcp6_srv_configured_,
                                                           *srv_configured_handle));
            ASSERT_EQ(srv_configured_handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
        }

        // In a real environment, configuration is committed after libraries are loaded.
        CfgMgr::instance().commit();

        CalloutHandlePtr cb_handle(HooksManager::createCalloutHandle());
        callCb6Updated(cb_handle, add_client_class, add_subnet);

        // Send four packets. Based on the set limit, there should be two drops and two continues.
        for (unsigned int j = 0; j < 4; ++j) {
            {
                CalloutHandlePtr handle(HooksManager::createCalloutHandle());
                Pkt6Ptr packet(boost::make_shared<Pkt6>(1, 128));
                packet->addClass("foo");
                Subnet6Ptr subnet(
                    boost::make_shared<Subnet6>(IOAddress("2001:db8::"), 64, 450, 900, 1800, 3600, 1));
                handle->setArgument("query6", packet);
                handle->setArgument("subnet6", subnet);

                EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_pkt6_receive_, *handle));
                EXPECT_EQ(handle->getStatus(), add_client_class ?
                    (j < 1 ? CalloutHandle::NEXT_STEP_CONTINUE : CalloutHandle::NEXT_STEP_DROP) :
                    CalloutHandle::NEXT_STEP_CONTINUE);
            }

            {
                CalloutHandlePtr handle(HooksManager::createCalloutHandle());
                Pkt6Ptr packet(boost::make_shared<Pkt6>(1, 128));
                packet->addClass("foo");
                Subnet6Ptr subnet(
                    boost::make_shared<Subnet6>(IOAddress("2001:db8::"), 64, 450, 900, 1800, 3600, 1));
                handle->setArgument("query6", packet);
                handle->setArgument("subnet6", subnet);

                EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_subnet6_select_, *handle));
                EXPECT_EQ(handle->getStatus(), add_subnet ?
                    (j < 1 ? CalloutHandle::NEXT_STEP_CONTINUE : CalloutHandle::NEXT_STEP_DROP) :
                    CalloutHandle::NEXT_STEP_CONTINUE);
            }
        }
    }

    int hook_index_cb4_updated_;
    int hook_index_cb6_updated_;

    int hook_index_dhcp4_srv_configured_;
    int hook_index_dhcp6_srv_configured_;

    int hook_index_pkt4_receive_;
    int hook_index_pkt6_receive_;

    int hook_index_subnet4_select_;
    int hook_index_subnet6_select_;

    int hook_index_lease4_select_;
    int hook_index_lease6_select_;

    int hook_index_lease4_renew_;
    int hook_index_lease6_renew_;

    int hook_index_lease6_rebind_;
};

// Check that the library can be loaded and unloaded multiple times.
TEST_F(LimitsLibLoadTest, loadUnload) {<--- syntax error
    validDaemonTest("kea-dhcp4", AF_INET);
    validDaemonTest("kea-dhcp6", AF_INET6);
}

// Check that parameters are not allowed not even in the form of an empty map.
TEST_F(LimitsLibLoadTest, parametersNotAllowed) {
    invalidDaemonTest("kea-dhcp4", AF_INET, Element::createMap());
    invalidDaemonTest("kea-dhcp6", AF_INET6, Element::createMap());
}

// Check that a v4 packet gets dropped at the right hook and that the library can be reloaded with
// a different configuration.
TEST_F(LimitsLibLoadTest, v4) {
    CfgMgr::instance().setFamily(AF_INET);
    Daemon::setProcName("kea-dhcp4");
    addLibrary(LIBDHCP_LIMITS_SO, ElementPtr());
    registerV4Hooks();

    // Call everything twice to check subsequent loading and unloading of libraries.
    for (unsigned int i = 0; i < 2; ++i) {
        // Make sure configuration is empty.
        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->empty())
            << "expected empty client class configuration, found "
            << CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->toElement()->str();
        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->getAll()->empty());

        // Add a client class.
        CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->addClass(
            "foo", ExpressionPtr(), "", false, false, CfgOptionPtr(), CfgOptionDefPtr(),
            Element::fromJSON(R"({ "limits": { "rate-limit": "2 packets per year" } })"));

        // Load the library.
        EXPECT_TRUE(loadLibraries());
        calloutsV4Present();
        {
            CalloutHandlePtr srv_configured_handle(HooksManager::createCalloutHandle());
            srv_configured_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
            ASSERT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_dhcp4_srv_configured_,
                                                           *srv_configured_handle));
            ASSERT_EQ(srv_configured_handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
        }

        // In a real environment, configuration is committed after libraries are loaded.
        CfgMgr::instance().commit();

        // Send four packets. Based on the set limit, there should be two drops and two continues.
        for (unsigned int j = 0; j < 4; ++j) {
            CalloutHandlePtr handle(HooksManager::createCalloutHandle());
            Pkt4Ptr packet(boost::make_shared<Pkt4>(1, 128));
            packet->addClass("foo");
            Subnet4Ptr subnet(
                boost::make_shared<Subnet4>(IOAddress("192.168.0.0"), 24, 900, 1800, 3600, 1));
            handle->setArgument("query4", packet);
            handle->setArgument("subnet4", subnet);
            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_pkt4_receive_, *handle));
            // Expect drop after the pkt4_receive hook.
            EXPECT_EQ(handle->getStatus(), j < 2 ? CalloutHandle::NEXT_STEP_CONTINUE :
                                                   CalloutHandle::NEXT_STEP_DROP);
            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_subnet4_select_, *handle));
            EXPECT_EQ(handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
        }

        EXPECT_TRUE(unloadLibraries());
    }

    // Call everything twice to check subsequent loading and unloading of libraries.
    for (unsigned int i = 0; i < 2; ++i) {
        // Make sure configuration is empty.
        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->empty())
            << "expected empty client class configuration, found "
            << CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->toElement()->str();
        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->getAll()->empty());

        // Switch to limiting by subnet ID.
        Subnet4Ptr subnet_for_config(
            boost::make_shared<Subnet4>(IOAddress("192.168.0.0"), 24, 900, 1800, 3600, 1));
        subnet_for_config->setContext(
            Element::fromJSON(R"({ "limits": { "rate-limit": "2 packets per year" } })"));
        CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet_for_config);

        // Load the library.
        EXPECT_TRUE(loadLibraries());
        calloutsV4Present();
        {
            CalloutHandlePtr srv_configured_handle(HooksManager::createCalloutHandle());
            srv_configured_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
            ASSERT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_dhcp4_srv_configured_,
                                                           *srv_configured_handle));
            ASSERT_EQ(srv_configured_handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
        }

        // In a real environment, configuration is committed after libraries are loaded.
        CfgMgr::instance().commit();

        // Send four packets. Based on the set limit, there should be two drops and two continues.
        for (unsigned int j = 0; j < 4; ++j) {
            CalloutHandlePtr handle(HooksManager::createCalloutHandle());
            Pkt4Ptr packet(boost::make_shared<Pkt4>(1, 128));
            packet->addClass("foo");
            Subnet4Ptr subnet(
                boost::make_shared<Subnet4>(IOAddress("192.168.0.0"), 24, 900, 1800, 3600, 1));
            handle->setArgument("query4", packet);
            handle->setArgument("subnet4", subnet);
            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_pkt4_receive_, *handle));
            EXPECT_EQ(handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_subnet4_select_, *handle));
            // Expect drop after the subnet4_select hook.
            EXPECT_EQ(handle->getStatus(), j < 2 ? CalloutHandle::NEXT_STEP_CONTINUE :
                                                   CalloutHandle::NEXT_STEP_DROP);
        }

        EXPECT_TRUE(unloadLibraries());
    }
}

// Check that a v6 packet gets dropped at the right hook and that the library can be reloaded with
// a different configuration.
TEST_F(LimitsLibLoadTest, v6) {
    CfgMgr::instance().setFamily(AF_INET6);
    Daemon::setProcName("kea-dhcp6");
    addLibrary(LIBDHCP_LIMITS_SO, ElementPtr());
    registerV6Hooks();

    // Call everything twice to check subsequent loading and unloading of libraries.
    for (unsigned int i = 0; i < 2; ++i) {
        // Make sure configuration is empty.
        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->empty())
            << "expected empty client class configuration, found "
            << CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->toElement()->str();
        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->getAll()->empty());

        // Add a client class.
        CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->addClass(
            "foo", ExpressionPtr(), "", false, false, CfgOptionPtr(), CfgOptionDefPtr(),
            Element::fromJSON(R"({ "limits": { "rate-limit": "2 packets per year" } })"));

        // Load the library.
        EXPECT_TRUE(loadLibraries());
        calloutsV6Present();
        {
            CalloutHandlePtr srv_configured_handle(HooksManager::createCalloutHandle());
            srv_configured_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
            ASSERT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_dhcp6_srv_configured_,
                                                           *srv_configured_handle));
            ASSERT_EQ(srv_configured_handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
        }

        // In a real environment, configuration is committed after libraries are loaded.
        CfgMgr::instance().commit();

        // Send four packets. Based on the set limit, there should be two drops and two continues.
        for (unsigned int j = 0; j < 4; ++j) {
            CalloutHandlePtr handle(HooksManager::createCalloutHandle());
            Pkt6Ptr packet(boost::make_shared<Pkt6>(1, 128));
            packet->addClass("foo");
            Subnet6Ptr subnet(
                boost::make_shared<Subnet6>(IOAddress("2001:db8::"), 64, 450, 900, 1800, 3600, 1));
            handle->setArgument("query6", packet);
            handle->setArgument("subnet6", subnet);
            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_pkt6_receive_, *handle));
            // Expect drop after the pkt6_receive hook.
            EXPECT_EQ(handle->getStatus(), j < 2 ? CalloutHandle::NEXT_STEP_CONTINUE :
                                                   CalloutHandle::NEXT_STEP_DROP);
            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_subnet6_select_, *handle));
            EXPECT_EQ(handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
        }

        EXPECT_TRUE(unloadLibraries());
    }

    // Call everything twice to check subsequent loading and unloading of libraries.
    for (unsigned int i = 0; i < 2; ++i) {
        // Make sure configuration is empty.
        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->empty())
            << "expected empty client class configuration, found "
            << CfgMgr::instance().getStagingCfg()->getClientClassDictionary()->toElement()->str();
        ASSERT_TRUE(CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->getAll()->empty());

        // Switch to limiting by subnet ID.
        Subnet6Ptr subnet_for_config(
            boost::make_shared<Subnet6>(IOAddress("2001:db8::"), 64, 450, 900, 1800, 3600, 1));
        subnet_for_config->setContext(
            Element::fromJSON(R"({ "limits": { "rate-limit": "2 packets per year" } })"));
        CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->add(subnet_for_config);

        // Load the library.
        EXPECT_TRUE(loadLibraries());
        calloutsV6Present();
        {
            CalloutHandlePtr srv_configured_handle(HooksManager::createCalloutHandle());
            srv_configured_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
            ASSERT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_dhcp6_srv_configured_,
                                                           *srv_configured_handle));
            ASSERT_EQ(srv_configured_handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
        }

        // In a real environment, configuration is committed after libraries are loaded.
        CfgMgr::instance().commit();

        // Send four packets. Based on the set limit, there should be two drops and two continues.
        for (unsigned int j = 0; j < 4; ++j) {
            CalloutHandlePtr handle(HooksManager::createCalloutHandle());
            Pkt6Ptr packet(boost::make_shared<Pkt6>(1, 128));
            packet->addClass("foo");
            Subnet6Ptr subnet(
                boost::make_shared<Subnet6>(IOAddress("2001:db8::"), 64, 450, 900, 1800, 3600, 1));
            handle->setArgument("query6", packet);
            handle->setArgument("subnet6", subnet);
            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_pkt6_receive_, *handle));
            EXPECT_EQ(handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_subnet6_select_, *handle));
            // Expect drop after the subnet6_select hook.
            EXPECT_EQ(handle->getStatus(), j < 2 ? CalloutHandle::NEXT_STEP_CONTINUE :
                                                   CalloutHandle::NEXT_STEP_DROP);
        }

        EXPECT_TRUE(unloadLibraries());
    }
}

// ---- The following tests check that CB updates for client classes and subnets are propagated to
// the limits hook library. ----

TEST_F(LimitsLibLoadTest, cb4UpdatedPlain) {
    testCb4Updated(false, false);
}

TEST_F(LimitsLibLoadTest, cb4UpdatedClientClassOnly) {
    testCb4Updated(true, false);
}

TEST_F(LimitsLibLoadTest, cb4UpdatedSubnetOnly) {
    testCb4Updated(false, true);
}

TEST_F(LimitsLibLoadTest, cb4UpdatedClientClassAndSubnet) {
    testCb4Updated(true, true);
}

TEST_F(LimitsLibLoadTest, cb6UpdatedPlain) {
    testCb6Updated(false, false);
}

TEST_F(LimitsLibLoadTest, cb6UpdatedClientClassOnly) {
    testCb6Updated(true, false);
}

TEST_F(LimitsLibLoadTest, cb6UpdatedSubnetOnly) {
    testCb6Updated(false, true);
}

TEST_F(LimitsLibLoadTest, cb6UpdatedClientClassAndSubnet) {
    testCb6Updated(true, true);
}

// ---- The following tests check that subnet_cmds updates for client classes and subnets are
// propagated to the limits hook library. ----

TEST_F(LimitsLibLoadTest, subnetCmdsV4) {
    CfgMgr::instance().setFamily(AF_INET);
    Daemon::setProcName("kea-dhcp4");
    addLibrary(LIBDHCP_LIMITS_SO, ElementPtr());
    registerV4Hooks();

    // Load the library.
    EXPECT_TRUE(loadLibraries());
    calloutsV4Present();
    {
        CalloutHandlePtr srv_configured_handle(HooksManager::createCalloutHandle());
        srv_configured_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
        ASSERT_NO_THROW_LOG(
            HooksManager::callCallouts(hook_index_dhcp4_srv_configured_, *srv_configured_handle));
        ASSERT_EQ(srv_configured_handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
    }

    // In a real environment, configuration is committed after libraries are loaded.
    CfgMgr::instance().commit();

    // Simulate a subnet addition through subnet_cmds.
    Subnet4Ptr subnet_for_config(
        boost::make_shared<Subnet4>(IOAddress("192.168.0.0"), 24, 900, 1800, 3600, 1));
    subnet_for_config->setContext(
        Element::fromJSON(R"({ "limits": { "rate-limit": "2 packets per minute" } })"));
    CfgMgr::instance().getStagingCfg()->getCfgSubnets4()->add(subnet_for_config);
    CfgMgr::instance().commit();

    // Send four packets. Based on the set limit, there should be two drops and two continues.
    for (unsigned int j = 0; j < 4; ++j) {
        {
            CalloutHandlePtr handle(HooksManager::createCalloutHandle());
            Pkt4Ptr packet(boost::make_shared<Pkt4>(1, 128));
            Subnet4Ptr subnet(
                boost::make_shared<Subnet4>(IOAddress("192.168.0.0"), 24, 900, 1800, 3600, 1));
            handle->setArgument("query4", packet);
            handle->setArgument("subnet4", subnet);

            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_pkt4_receive_, *handle));
            EXPECT_EQ(handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
        }

        {
            CalloutHandlePtr handle(HooksManager::createCalloutHandle());
            Pkt4Ptr packet(boost::make_shared<Pkt4>(1, 128));
            Subnet4Ptr subnet(
                boost::make_shared<Subnet4>(IOAddress("192.168.0.0"), 24, 900, 1800, 3600, 1));
            handle->setArgument("query4", packet);
            handle->setArgument("subnet4", subnet);

            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_subnet4_select_, *handle));
            EXPECT_EQ(handle->getStatus(),
                      j < 2 ? CalloutHandle::NEXT_STEP_CONTINUE : CalloutHandle::NEXT_STEP_DROP);
        }
    }

    EXPECT_TRUE(unloadLibraries());
}

TEST_F(LimitsLibLoadTest, subnetCmdsV6) {
    CfgMgr::instance().setFamily(AF_INET6);
    Daemon::setProcName("kea-dhcp6");
    addLibrary(LIBDHCP_LIMITS_SO, ElementPtr());
    registerV6Hooks();

    // Load the library.
    EXPECT_TRUE(loadLibraries());
    calloutsV6Present();
    {
        CalloutHandlePtr srv_configured_handle(HooksManager::createCalloutHandle());
        srv_configured_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
        ASSERT_NO_THROW_LOG(
            HooksManager::callCallouts(hook_index_dhcp6_srv_configured_, *srv_configured_handle));
        ASSERT_EQ(srv_configured_handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
    }

    // In a real environment, configuration is committed after libraries are loaded.
    CfgMgr::instance().commit();

    // Simulate a subnet addition through subnet_cmds.
    Subnet6Ptr subnet_for_config(
        boost::make_shared<Subnet6>(IOAddress("2001:db8::"), 64, 450, 900, 1800, 3600, 1));
    subnet_for_config->setContext(
        Element::fromJSON(R"({ "limits": { "rate-limit": "2 packets per minute" } })"));
    CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->add(subnet_for_config);
    CfgMgr::instance().commit();

    // Send four packets. Based on the set limit, there should be two drops and two continues.
    for (unsigned int j = 0; j < 4; ++j) {
        {
            CalloutHandlePtr handle(HooksManager::createCalloutHandle());
            Pkt6Ptr packet(boost::make_shared<Pkt6>(1, 128));
            Subnet6Ptr subnet(
                boost::make_shared<Subnet6>(IOAddress("2001:db8::"), 64, 450, 900, 1800, 3600, 1));
            handle->setArgument("query6", packet);
            handle->setArgument("subnet6", subnet);

            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_pkt6_receive_, *handle));
            EXPECT_EQ(handle->getStatus(), CalloutHandle::NEXT_STEP_CONTINUE);
        }

        {
            CalloutHandlePtr handle(HooksManager::createCalloutHandle());
            Pkt6Ptr packet(boost::make_shared<Pkt6>(1, 128));
            Subnet6Ptr subnet(
                boost::make_shared<Subnet6>(IOAddress("2001:db8::"), 64, 450, 900, 1800, 3600, 1));
            handle->setArgument("query6", packet);
            handle->setArgument("subnet6", subnet);

            EXPECT_NO_THROW_LOG(HooksManager::callCallouts(hook_index_subnet6_select_, *handle));
            EXPECT_EQ(handle->getStatus(),
                      j < 2 ? CalloutHandle::NEXT_STEP_CONTINUE : CalloutHandle::NEXT_STEP_DROP);
        }
    }

    EXPECT_TRUE(unloadLibraries());
}

// ----

// Simple test that checks the library cannot by loaded by invalid daemons.
TEST_F(LimitsLibLoadTest, invalidDaemonLoad) {
    // V4 is invalid when family is AF_INET6
    invalidDaemonTest("kea-dhcp4", AF_INET6);

    // V6 is invalid when family is AF_INET
    invalidDaemonTest("kea-dhcp6", AF_INET);

    invalidDaemonTest("kea-ctrl-agent", AF_INET);
    invalidDaemonTest("kea-dhcp-ddns", AF_INET);
    invalidDaemonTest("bogus", AF_INET);
}

}  // namespace