[PATCH net-next v2 1/3] netfilter: conntrack: add shared port parser for helpers

HACKE-RC
2026-05-01T06:32:16Z

Add nf_ct_helper_parse_port() to the conntrack helper core. This
provides a port parser that does not rely on nul-terminated strings,
taking an explicit length parameter and validating the result fits
in the 1-65535 range.

Modeled after the approach in 8cf6809cddcb ("netfilter:
nf_conntrack_sip: don't use simple_strtoul") but as a shared
function so IRC, Amanda, and other helpers can use it instead of
open-coding simple_strtoul calls with ad-hoc range checks.

Signed-off-by: HACKE-RC <rc@rexion.ai>
---
include/net/netfilter/nf_conntrack_helper.h | 3 +++
net/netfilter/nf_conntrack_helper.c | 28 +++++++++++++++++++++
2 files changed, 31 insertions(+)

diff --git a/include/net/netfilter/nf_conntrack_helper.h b/include/net/netfilter/nf_conntrack_helper.h
index de2f956ab..db19fe25f 100644
--- a/include/net/netfilter/nf_conntrack_helper.h
+++ b/include/net/netfilter/nf_conntrack_helper.h
@@ -160,6 +160,9 @@ nf_ct_helper_expectfn_find_by_name(const char *name);
struct nf_ct_helper_expectfn *
nf_ct_helper_expectfn_find_by_symbol(const void *symbol);

+int nf_ct_helper_parse_port(const char *cp, unsigned int len,
+ u16 *port, char **endp);
+
extern struct hlist_head *nf_ct_helper_hash;
extern unsigned int nf_ct_helper_hsize;

diff --git a/net/netfilter/nf_conntrack_helper.c b/net/netfilter/nf_conntrack_helper.c
index a715304a5..12f51670d 100644
--- a/net/netfilter/nf_conntrack_helper.c
+++ b/net/netfilter/nf_conntrack_helper.c
@@ -499,6 +499,34 @@ void nf_nat_helper_unregister(struct nf_conntrack_nat_helper *nat)
}
EXPORT_SYMBOL_GPL(nf_nat_helper_unregister);

+int nf_ct_helper_parse_port(const char *cp, unsigned int len,
+ u16 *port, char **endp)
+{
+ unsigned long result = 0;
+ const char *start = cp;
+
+ while (len > 0 && *cp >= '0' && *cp <= '9') {
+ result = result * 10 + (*cp - '0');
+ if (result > 65535)
+ return -1;
+ cp++;
+ len--;
+ }
+
+ if (cp == start)
+ return -1;
+
+ if (result == 0)
+ return -1;
+
+ *port = result;
+ if (endp)
+ *endp = (char *)cp;
+
+ return 0;
+}
+EXPORT_SYMBOL_GPL(nf_ct_helper_parse_port);
+
int nf_conntrack_helper_init(void)
{
nf_ct_helper_hsize = 1; /* gets rounded up to use one page */
--
2.54.0