firewall-util: introduce context structure

for planned nft backend we have three choices:

- open/close a new nfnetlink socket for every operation
- keep a nfnetlink socket open internally
- expose a opaque fw_ctx and stash all internal data here.

Originally I opted for the 2nd option, but during review it was
suggested to avoid static storage duration because of perceived
problems with threaded applications.

This adds fw_ctx and new/free functions, then converts the existing api
and nspawn and networkd to use it.
This commit is contained in:
Florian Westphal
2020-12-16 00:35:56 +01:00
parent f51343d0af
commit 761cf19d7b
11 changed files with 122 additions and 43 deletions
+40 -15
View File
@@ -8,15 +8,6 @@
#include "firewall-util.h"
#include "firewall-util-private.h"
enum FirewallBackend {
FW_BACKEND_NONE,
#if HAVE_LIBIPTC
FW_BACKEND_IPTABLES,
#endif
};
static enum FirewallBackend FirewallBackend;
static enum FirewallBackend firewall_backend_probe(void) {
#if HAVE_LIBIPTC
return FW_BACKEND_IPTABLES;
@@ -25,16 +16,41 @@ static enum FirewallBackend firewall_backend_probe(void) {
#endif
}
int fw_ctx_new(FirewallContext **ret) {
_cleanup_free_ FirewallContext *ctx = NULL;
ctx = new0(FirewallContext, 1);
if (!ctx)
return -ENOMEM;
*ret = TAKE_PTR(ctx);
return 0;
}
FirewallContext *fw_ctx_free(FirewallContext *ctx) {
return mfree(ctx);
}
int fw_add_masquerade(
FirewallContext **fw_ctx,
bool add,
int af,
const union in_addr_union *source,
unsigned source_prefixlen) {
FirewallContext *ctx;
int r;
if (FirewallBackend == FW_BACKEND_NONE)
FirewallBackend = firewall_backend_probe();
if (!*fw_ctx) {
r = fw_ctx_new(fw_ctx);
if (r < 0)
return r;
}
switch (FirewallBackend) {
ctx = *fw_ctx;
if (ctx->firewall_backend == FW_BACKEND_NONE)
ctx->firewall_backend = firewall_backend_probe();
switch (ctx->firewall_backend) {
case FW_BACKEND_NONE:
return -EOPNOTSUPP;
#if HAVE_LIBIPTC
@@ -47,6 +63,7 @@ int fw_add_masquerade(
}
int fw_add_local_dnat(
FirewallContext **fw_ctx,
bool add,
int af,
int protocol,
@@ -54,11 +71,19 @@ int fw_add_local_dnat(
const union in_addr_union *remote,
uint16_t remote_port,
const union in_addr_union *previous_remote) {
FirewallContext *ctx;
if (FirewallBackend == FW_BACKEND_NONE)
FirewallBackend = firewall_backend_probe();
if (!*fw_ctx) {
int ret = fw_ctx_new(fw_ctx);
if (ret < 0)
return ret;
}
switch (FirewallBackend) {
ctx = *fw_ctx;
if (ctx->firewall_backend == FW_BACKEND_NONE)
ctx->firewall_backend = firewall_backend_probe();
switch (ctx->firewall_backend) {
case FW_BACKEND_NONE:
return -EOPNOTSUPP;
#if HAVE_LIBIPTC