git: 0aef8628458a - main - If setkey(8) is used without ipsec.ko loaded beforehand, its attempt to install SA/SPD into the kernel results in cryptic EINVAL error code.

From: Eugene Grosbein <eugen_at_FreeBSD.org>
Date: Thu, 05 May 2022 12:06:43 UTC
The branch main has been updated by eugen:

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

commit 0aef8628458a7d03e3c7e63ae05e228191167eec
Author:     Eugene Grosbein <eugen@FreeBSD.org>
AuthorDate: 2022-05-05 12:02:29 +0000
Commit:     Eugene Grosbein <eugen@FreeBSD.org>
CommitDate: 2022-05-05 12:02:29 +0000

    If setkey(8) is used without ipsec.ko loaded beforehand,
    its attempt to install SA/SPD into the kernel results in cryptic
    EINVAL error code.
    
    Let it be a bit more user-friendly and try to load ipsec.ko
    automatically if it is not loaded, just like ifconfig(8) does it
    for modules it needs.
    
    PR:             263379
    MFC after:      2 weeks
---
 sbin/setkey/setkey.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/sbin/setkey/setkey.c b/sbin/setkey/setkey.c
index d556a842f048..faf6373b312e 100644
--- a/sbin/setkey/setkey.c
+++ b/sbin/setkey/setkey.c
@@ -34,6 +34,8 @@
 
 #include <sys/types.h>
 #include <sys/param.h>
+#include <sys/linker.h>
+#include <sys/module.h>
 #include <sys/socket.h>
 #include <sys/time.h>
 #include <err.h>
@@ -67,6 +69,7 @@ void shortdump_hdr(void);
 void shortdump(struct sadb_msg *);
 static void printdate(void);
 static int32_t gmt2local(time_t);
+static int modload(const char *name);
 
 #define MODE_SCRIPT	1
 #define MODE_CMDDUMP	2
@@ -102,6 +105,17 @@ usage(void)
 	exit(1);
 }
 
+static int
+modload(const char *name)
+{
+	if (modfind(name) < 0)
+		if (kldload(name) < 0 || modfind(name) < 0) {
+			warn("%s: module not found", name);
+			return 0;
+	}
+	return 1;
+}
+
 int
 main(int ac, char **av)
 {
@@ -165,6 +179,7 @@ main(int ac, char **av)
 		}
 	}
 
+	modload("ipsec");
 	so = pfkey_open();
 	if (so < 0) {
 		perror("pfkey_open");