]> git.ipfire.org Git - thirdparty/nftables.git/commitdiff
libnftables: move init-once guard inside xt_init()
authorThomas Haller <thaller@redhat.com>
Tue, 19 Sep 2023 12:36:17 +0000 (14:36 +0200)
committerPablo Neira Ayuso <pablo@netfilter.org>
Tue, 19 Sep 2023 15:26:27 +0000 (17:26 +0200)
A library should not restrict being used by multiple threads or make
assumptions about how it's being used. Hence a "init_once" pattern
without no locking is racy, a code smell and should be avoided.

Note that libxtables is full of global variables and when linking against
it, libnftables cannot be used from multiple threads either. That is not
easy to fix.

Move the ugliness of "init_once" away from nft_ctx_new(), so that the
problem is concentrated closer to libxtables.

Signed-off-by: Thomas Haller <thaller@redhat.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
src/libnftables.c
src/xt.c

index cedd710bf898d185f98a658526ff4cc5d230d497..1ca5a6f48c4c1b2a12ca94b5d40dcb0ff63b19be 100644 (file)
@@ -191,15 +191,11 @@ void nft_ctx_clear_include_paths(struct nft_ctx *ctx)
 EXPORT_SYMBOL(nft_ctx_new);
 struct nft_ctx *nft_ctx_new(uint32_t flags)
 {
-       static bool init_once;
        struct nft_ctx *ctx;
 
-       if (!init_once) {
-               init_once = true;
 #ifdef HAVE_LIBXTABLES
-               xt_init();
+       xt_init();
 #endif
-       }
 
        ctx = xzalloc(sizeof(struct nft_ctx));
        nft_init(ctx);
index d774e07395a6886bf55f073999a65cded5809575..bb87e86e02af4f9e83c5827e9ceec46d07950152 100644 (file)
--- a/src/xt.c
+++ b/src/xt.c
@@ -361,7 +361,18 @@ static struct xtables_globals xt_nft_globals = {
 
 void xt_init(void)
 {
-       /* Default to IPv4, but this changes in runtime */
-       xtables_init_all(&xt_nft_globals, NFPROTO_IPV4);
+       static bool init_once;
+
+       if (!init_once) {
+               /* libxtables is full of global variables and cannot be used
+                * concurrently by multiple threads. Hence, it's fine that the
+                * "init_once" guard is not thread-safe either.
+                * Don't link against xtables if you want thread safety.
+                */
+               init_once = true;
+
+               /* Default to IPv4, but this changes in runtime */
+               xtables_init_all(&xt_nft_globals, NFPROTO_IPV4);
+       }
 }
 #endif