[PATCH nft 2/2] libnftables: move init-once guard inside xt_init()

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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@xxxxxxxxxx>
---
 src/libnftables.c |  6 +-----
 src/xt.c          | 15 +++++++++++++--
 2 files changed, 14 insertions(+), 7 deletions(-)

diff --git a/src/libnftables.c b/src/libnftables.c
index c34ee43de1fa..ed6b7fb5554c 100644
--- a/src/libnftables.c
+++ b/src/libnftables.c
@@ -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);
diff --git a/src/xt.c b/src/xt.c
index d774e07395a6..bb87e86e02af 100644
--- 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
-- 
2.41.0




[Index of Archives]     [Netfitler Users]     [Berkeley Packet Filter]     [LARTC]     [Bugtraq]     [Yosemite Forum]

  Powered by Linux