From 9c7127cd811d8453c2aa4dd3ec9a1e30421086f3 Mon Sep 17 00:00:00 2001
From: Mark Valence <mrv@openldap.org>
Date: Thu, 15 Jun 2000 02:21:01 +0000
Subject: [PATCH] Check if process is installed/running as service on NT beofre
 trying t o start it as a service (gets around an annoying pause when starting
 u p as a non-service).

---
 libraries/liblutil/ntservice.c | 51 ++++++++++++++++++++++++++++++++++
 servers/slapd/nt_svc.c         |  6 +++-
 2 files changed, 56 insertions(+), 1 deletion(-)

diff --git a/libraries/liblutil/ntservice.c b/libraries/liblutil/ntservice.c
index 657974ae7c..bc4ae422dc 100644
--- a/libraries/liblutil/ntservice.c
+++ b/libraries/liblutil/ntservice.c
@@ -150,6 +150,57 @@ int srv_remove(LPCTSTR lpszServiceName, LPCTSTR lpszBinaryPathName)
 }
 
 
+DWORD
+svc_installed (LPTSTR lpszServiceName, LPTSTR lpszBinaryPathName)
+{
+	char buf[256];
+	HKEY key;
+	DWORD rc;
+	DWORD type;
+	long len;
+
+	strcpy(buf, TEXT("SYSTEM\\CurrentControlSet\\Services\\"));
+	strcat(buf, lpszServiceName);
+	if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, buf, 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
+		return(-1);
+
+	rc = 0;
+	if (lpszBinaryPathName) {
+		len = sizeof(buf);
+		if (RegQueryValueEx(key, "ImagePath", NULL, &type, buf, &len) == ERROR_SUCCESS) {
+			if (strcmp(lpszBinaryPathName, buf))
+				rc = -1;
+		}
+	}
+	RegCloseKey(key);
+	return(rc);
+}
+
+
+DWORD
+svc_running (LPTSTR lpszServiceName)
+{
+	SC_HANDLE service;
+	SC_HANDLE scm;
+	DWORD rc;
+	SERVICE_STATUS ss;
+
+	if (!(scm = OpenSCManager(NULL, NULL, GENERIC_READ)))
+		return(GetLastError());
+
+	rc = 1;
+	service = OpenService(scm, lpszServiceName, SERVICE_QUERY_STATUS);
+	if (service) {
+		if (!QueryServiceStatus(service, &ss))
+			rc = GetLastError();
+		else if (ss.dwCurrentState != SERVICE_STOPPED)
+			rc = 0;
+		CloseServiceHandle(service);
+	}
+	CloseServiceHandle(scm);
+	return(rc);
+}
+
 
 static void *start_status_routine( void *ptr )
 {
diff --git a/servers/slapd/nt_svc.c b/servers/slapd/nt_svc.c
index 5bd46f9636..d81bc68a47 100644
--- a/servers/slapd/nt_svc.c
+++ b/servers/slapd/nt_svc.c
@@ -18,6 +18,8 @@ void WINAPI ServiceMain( DWORD argc, LPTSTR *argv );
 int srv_install( char* service, char * displayName, char* filename,
 		 BOOL auto_start );
 int srv_remove ( char* service, char* filename );
+DWORD svc_installed (LPTSTR lpszServiceName, LPTSTR lpszBinaryPathName);
+DWORD svc_running (LPTSTR lpszServiceName);
 
 int main( int argc, LPTSTR *argv )
 {
@@ -99,7 +101,9 @@ int main( int argc, LPTSTR *argv )
 	}
 
 	puts( "starting slapd..." );
-	if ( !StartServiceCtrlDispatcher(DispatchTable) )
+	if (svc_installed(SERVICE_NAME, NULL) != 0
+		|| svc_running(SERVICE_NAME) == 1
+		|| StartServiceCtrlDispatcher(DispatchTable) != 0 )
 	{
 		is_NT_Service = 0;
 		ServiceMain( argc, argv );
-- 
GitLab