From 4dccad3157437d8cda9f48c97970cecb1fcf49ee Mon Sep 17 00:00:00 2001 From: Stefan Schantl Date: Sat, 17 Sep 2022 15:48:27 +0200 Subject: [PATCH] Add function to add addresses or networks to a set. Signed-off-by: Stefan Schantl --- IPSet.xs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ t/IPSet.t | 14 +++++++++++++- 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/IPSet.xs b/IPSet.xs index 0d24ea5..75bbf1e 100644 --- a/IPSet.xs +++ b/IPSet.xs @@ -334,6 +334,56 @@ setname_exists(session, setname) OUTPUT: RETVAL +# +# Functions to add or remove elements to sets. +# +bool +add_address(session, setname, address) + struct ipset_session *session; + const char *setname; + const char *address; + + PREINIT: + enum ipset_cmd cmd = IPSET_CMD_ADD; + const struct ipset_type *type; + + CODE: + // Assign the setname as session data. + int r = ipset_session_data_set(session, IPSET_SETNAME, setname); + if (r < 0) { + goto ERROR; + } + + // Get the set type. + type = ipset_type_get(session, cmd); + if (type == NULL) { + goto ERROR; + } + + // Parse and try to add the given address to the session data. + r = ipset_parse_ip(session, IPSET_OPT_IP, address); + if (r < 0) { + goto ERROR; + } + + r = ipset_cmd(session, cmd, 0); + if (r < 0) { + goto ERROR; + } + + RETVAL = true; + + goto END; + + ERROR: + RETVAL = false; + + // Reset session data. + ipset_data_reset(ipset_session_data(session)); + END: + OUTPUT: + RETVAL + # # Get functions to ask for various data or receive error messages. # diff --git a/t/IPSet.t b/t/IPSet.t index 01778b7..88a61e9 100644 --- a/t/IPSet.t +++ b/t/IPSet.t @@ -8,7 +8,7 @@ use strict; use warnings; -use Test::More tests => 15; +use Test::More tests => 16; BEGIN { use_ok('IPSet') }; ######################### @@ -24,6 +24,9 @@ my %testset = ( "maxelem" => "10", ); +# Array with addresses to be added to the testset. +my @addresses = ("1.1.1.1", "2.2.2.2"); + # Name of the renamed set. my $setname_renamed = "TEST_RENAMED"; @@ -72,5 +75,14 @@ my @sets = &IPSet::get_sets($session); my $sets_count = @sets; ok($sets_count ge 1, "At least one set exists yet!"); +# Add all addresses from array to the testset. +foreach my $address (@addresses) { + &IPSet::add_address($session, $testset{'name'}, $address); +} + +# Grab set data gain. +$data = &IPSet::get_set_data($session, $testset{'name'}); +ok($data->{entries} eq scalar(@addresses), "All addresses added successfully to the set"); + # CLEANUP: Delete the remaining set. &IPSet::delete_set($session, $testset{'name'}); -- 2.47.3