From cc7bb66c8b650a8a007bf2ef320cde71a3ca23fb Mon Sep 17 00:00:00 2001 From: Stefan Schantl Date: Sat, 17 Sep 2022 15:59:21 +0200 Subject: [PATCH] Add function to remove addresses or networks from a set. Signed-off-by: Stefan Schantl --- IPSet.xs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ t/IPSet.t | 11 ++++++++++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/IPSet.xs b/IPSet.xs index 75bbf1e..160bfa9 100644 --- a/IPSet.xs +++ b/IPSet.xs @@ -383,6 +383,53 @@ add_address(session, setname, address) END: OUTPUT: RETVAL + +bool +remove_address(session, setname, address) + struct ipset_session *session; + const char *setname; + const char *address; + + PREINIT: + enum ipset_cmd cmd = IPSET_CMD_DEL; + const struct ipset_type *type; + + CODE: + // Assign 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 88a61e9..76bd249 100644 --- a/t/IPSet.t +++ b/t/IPSet.t @@ -8,7 +8,7 @@ use strict; use warnings; -use Test::More tests => 16; +use Test::More tests => 19; BEGIN { use_ok('IPSet') }; ######################### @@ -84,5 +84,14 @@ foreach my $address (@addresses) { $data = &IPSet::get_set_data($session, $testset{'name'}); ok($data->{entries} eq scalar(@addresses), "All addresses added successfully to the set"); +# Remove the first address from array from the set. +my $remove = &IPSet::remove_address($session, $testset{'name'}, $addresses[0]); +ok($remove, "Successfully removed $addresses[0] from testset"); + +# Update set data. +$data = &IPSet::get_set_data($session, $testset{'name'}); +ok($data->{entries} lt scalar(@addresses), "Less entries in the set than at the addresses array"); +ok($data->{entries} gt 0, "At least one entry on the testset"); + # CLEANUP: Delete the remaining set. &IPSet::delete_set($session, $testset{'name'}); -- 2.47.2