git: 9132c793cb01 - stable/13 - setkey(8): MFC: load ipsec.ko automatically

From: Eugene Grosbein <eugen_at_FreeBSD.org>
Date: Thu, 19 May 2022 06:07:13 UTC
The branch stable/13 has been updated by eugen:

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

commit 9132c793cb014e321c92ed502d20df4426492562
Author:     Eugene Grosbein <eugen@FreeBSD.org>
AuthorDate: 2022-05-05 12:02:29 +0000
Commit:     Eugene Grosbein <eugen@FreeBSD.org>
CommitDate: 2022-05-19 06:05:30 +0000

    setkey(8): MFC: load ipsec.ko automatically
    
    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
    
    (cherry picked from commit 0aef8628458a7d03e3c7e63ae05e228191167eec)
---
 sbin/setkey/setkey.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/sbin/setkey/setkey.c b/sbin/setkey/setkey.c
index 1d66a92e0100..2bc8ec7e5816 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()
 	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(ac, av)
 	int ac;
@@ -167,6 +181,7 @@ main(ac, av)
 		}
 	}
 
+	modload("ipsec");
 	so = pfkey_open();
 	if (so < 0) {
 		perror("pfkey_open");