From be187435911cde6cc3cef6982a508261074f1e56 Mon Sep 17 00:00:00 2001
From: Matt Jolly <Matt.Jolly@footclan.ninja>
Date: Thu, 2 Feb 2023 21:05:40 +1100
Subject: [PATCH] systemd: Add optional support for systemd `sd_notify`

This is a rebase of Dennis Lamm's <expeditioneer@gentoo.org>
patch based on Jakub Jelen's <jjelen@redhat.com> original patch

Upstream-Status: Submitted [https://github.com/openssh/openssh-portable/pull/375/commits/be187435911cde6cc3cef6982a508261074f1e56]

Signed-off-by: Xiangyu Chen <xiangyu.chen@windriver.com>
---
 configure.ac | 24 ++++++++++++++++++++++++
 sshd.c       | 13 +++++++++++++
 2 files changed, 37 insertions(+)

diff --git a/configure.ac b/configure.ac
index 22fee70f..486c189f 100644
--- a/configure.ac
+++ b/configure.ac
@@ -4835,6 +4835,29 @@ AC_SUBST([GSSLIBS])
 AC_SUBST([K5LIBS])
 AC_SUBST([CHANNELLIBS])
 
+# Check whether user wants systemd support
+SYSTEMD_MSG="no"
+AC_ARG_WITH(systemd,
+	[  --with-systemd          Enable systemd support],
+	[ if test "x$withval" != "xno" ; then
+		AC_PATH_TOOL([PKGCONFIG], [pkg-config], [no])
+		if test "$PKGCONFIG" != "no"; then
+			AC_MSG_CHECKING([for libsystemd])
+			if $PKGCONFIG --exists libsystemd; then
+				SYSTEMD_CFLAGS=`$PKGCONFIG --cflags libsystemd`
+				SYSTEMD_LIBS=`$PKGCONFIG --libs libsystemd`
+				CPPFLAGS="$CPPFLAGS $SYSTEMD_CFLAGS"
+				SSHDLIBS="$SSHDLIBS $SYSTEMD_LIBS"
+				AC_MSG_RESULT([yes])
+				AC_DEFINE(HAVE_SYSTEMD, 1, [Define if you want systemd support.])
+				SYSTEMD_MSG="yes"
+			else
+				AC_MSG_RESULT([no])
+			fi
+		fi
+	fi ]
+)
+
 # Looking for programs, paths and files
 
 PRIVSEP_PATH=/var/empty
@@ -5634,6 +5657,7 @@ echo "                   libldns support: $LDNS_MSG"
 echo "  Solaris process contract support: $SPC_MSG"
 echo "           Solaris project support: $SP_MSG"
 echo "         Solaris privilege support: $SPP_MSG"
+echo "                   systemd support: $SYSTEMD_MSG"
 echo "       IP address in \$DISPLAY hack: $DISPLAY_HACK_MSG"
 echo "           Translate v4 in v6 hack: $IPV4_IN6_HACK_MSG"
 echo "                  BSD Auth support: $BSD_AUTH_MSG"
diff --git a/sshd.c b/sshd.c
index 6321936c..859d6a0b 100644
--- a/sshd.c
+++ b/sshd.c
@@ -88,6 +88,10 @@
 #include <prot.h>
 #endif
 
+#ifdef HAVE_SYSTEMD
+#include <systemd/sd-daemon.h>
+#endif
+
 #include "xmalloc.h"
 #include "ssh.h"
 #include "ssh2.h"
@@ -310,6 +314,10 @@ static void
 sighup_restart(void)
 {
 	logit("Received SIGHUP; restarting.");
+#ifdef HAVE_SYSTEMD
+	/* Signal systemd that we are reloading */
+	sd_notify(0, "RELOADING=1");
+#endif
 	if (options.pid_file != NULL)
 		unlink(options.pid_file);
 	platform_pre_restart();
@@ -2086,6 +2094,11 @@ main(int ac, char **av)
 			}
 		}
 
+#ifdef HAVE_SYSTEMD
+		/* Signal systemd that we are ready to accept connections */
+		sd_notify(0, "READY=1");
+#endif
+
 		/* Accept a connection and return in a forked child */
 		server_accept_loop(&sock_in, &sock_out,
 		    &newsock, config_s);
-- 
2.25.1

