Skip to contentSkip to conversation

src: avoid re-initing core library when a second context struct is allocated

RFC PATCH In review Florian Westphal 2 participants 3 messages Aug 5, 2019 – Aug 7, 2019 netfilter

lore
Share & tools
lore

Florian Westphal

author maintainer
#0 lore raw

RFC PATCH 1/1 src: avoid re-initing core library when a second context struct is allocated

Calling nft_ctx_new() a second time leaks memory, and calling nft_ctx_free a second time -- on a different context -- causes double-free.

This patch won't work in case we assume libnftables should be thread-safe, in such case we either need a mutex or move all resources under nft_ctx scope.

---
 src/libnftables.c | 8 ++++++++
 1 file changed, 8 insertions(+)
src/libnftables.c +8 -0
index 4a139c58b2b3..880fd4284555 100644
@@ -17,6 +17,8 @@
 #include <stdlib.h>
 #include <string.h>
 
+static unsigned int context_count;
+
 static int nft_netlink(struct nft_ctx *nft,
 		       struct list_head *cmds, struct list_head *msgs,
 		       struct mnl_socket *nf_sock)
@@ -86,6 +88,9 @@ out:
 
 static void nft_init(void)
 {
+	if (context_count++)
+		return;
+
 	mark_table_init();
 	realm_table_rt_init();
 	devgroup_table_init();
@@ -99,6 +104,9 @@ static void nft_init(void)
 
 static void nft_exit(void)
 {
+	if (--context_count)
+		return;
+
 	ct_label_table_exit();
 	realm_table_rt_exit();
 	devgroup_table_exit();
Signature · 1 line
2.21.0
#1 lore raw
Quoted 7 lines · Florian Westphal

Calling nft_ctx_new() a second time leaks memory, and calling nft_ctx_free a second time -- on a different context -- causes double-free.

This patch won't work in case we assume libnftables should be thread-safe, in such case we either need a mutex or move all resources under nft_ctx scope.

These two should avoid the memleak / double free I think:

https://patchwork.ozlabs.org/patch/1143742/
https://patchwork.ozlabs.org/patch/1143743/

Not thread-safe yet, there is a bunch global variables still in place.

author maintainer
#2 lore raw
Quoted 5 lines · Pablo Neira Ayuso
Quoted 4 lines · Florian Westphal

Calling nft_ctx_new() a second time leaks memory, and calling nft_ctx_free a second time -- on a different context -- causes double-free.

Quoted 8 lines
Quoted 3 lines

This patch won't work in case we assume libnftables should be thread-safe, in such case we either need a mutex or move all resources under nft_ctx scope.

These two should avoid the memleak / double free I think:

https://patchwork.ozlabs.org/patch/1143742/
https://patchwork.ozlabs.org/patch/1143743/

Thanks, I will give them a try.

Quoted 1 line

Not thread-safe yet, there is a bunch global variables still in place.

I don't need thread-safety at the moment, I just found this double-free crash when creating another nft_ctx inside nftables (don't ask why, its fugly...)