git: e4e0f497429c - main - in: add in_mask2len()

From: Kristof Provost <kp_at_FreeBSD.org>
Date: Tue, 17 Dec 2024 10:07:41 UTC
The branch main has been updated by kp:

URL: https://cgit.FreeBSD.org/src/commit/?id=e4e0f497429c635a02897d86c4eb5ec649cc2df8

commit e4e0f497429c635a02897d86c4eb5ec649cc2df8
Author:     Kristof Provost <kp@FreeBSD.org>
AuthorDate: 2024-10-22 08:45:06 +0000
Commit:     Kristof Provost <kp@FreeBSD.org>
CommitDate: 2024-12-17 10:07:12 +0000

    in: add in_mask2len()
    
    Similar to the existing in6_mask2len() function, but for IPv4. This will be used
    by pf's nat64 code.
    
    Obtained from:  OpenBSD
    Sponsored by:   Rubicon Communications, LLC ("Netgate")
    Differential Revision:  https://reviews.freebsd.org/D47785
---
 sys/netinet/in.c     | 21 +++++++++++++++++++++
 sys/netinet/in_var.h |  1 +
 2 files changed, 22 insertions(+)

diff --git a/sys/netinet/in.c b/sys/netinet/in.c
index c78f0f5758f7..a6f212e9d3ef 100644
--- a/sys/netinet/in.c
+++ b/sys/netinet/in.c
@@ -441,6 +441,27 @@ in_control_ioctl(u_long cmd, void *data, struct ifnet *ifp,
 	return (error);
 }
 
+int
+in_mask2len(struct in_addr *mask)
+{
+	int x, y;
+	u_char *p;
+
+	p = (u_char *)mask;
+	for (x = 0; x < sizeof(*mask); x++) {
+		if (p[x] != 0xff)
+			break;
+	}
+	y = 0;
+	if (x < sizeof(*mask)) {
+		for (y = 0; y < 8; y++) {
+			if ((p[x] & (0x80 >> y)) == 0)
+				break;
+		}
+	}
+	return (x * 8 + y);
+}
+
 int
 in_control(struct socket *so, u_long cmd, void *data, struct ifnet *ifp,
     struct thread *td)
diff --git a/sys/netinet/in_var.h b/sys/netinet/in_var.h
index b4bdb2a65fc8..1f6f6edb9219 100644
--- a/sys/netinet/in_var.h
+++ b/sys/netinet/in_var.h
@@ -459,6 +459,7 @@ int	in_joingroup_locked(struct ifnet *, const struct in_addr *,
 int	in_leavegroup(struct in_multi *, /*const*/ struct in_mfilter *);
 int	in_leavegroup_locked(struct in_multi *,
 	    /*const*/ struct in_mfilter *);
+int	in_mask2len(struct in_addr *);
 int	in_control(struct socket *, u_long, void *, struct ifnet *,
 	    struct thread *);
 int	in_control_ioctl(u_long, void *, struct ifnet *,