commit e592f8f78ff128ab95f8616ac642e6955dc65de5
Author: Hamish Coleman <hamish@zot.org>
Date:   Tue Jul 1 23:17:47 2008 +1000

    Move the Service Control functions to a separate file - first pass

diff --git a/.gitignore b/.gitignore
index 465d39f..65bb948 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,6 +6,10 @@
 wconsd.exe
 portenum.exe
 
+# Ignore the partial objects
+wconsd.o
+win-scm.o
+
 # Also ignore any binaries from the wine build
 wconsd.exe.so
 wconsd
diff --git a/Makefile b/Makefile
index 8391c6f..48e4f56 100644
--- a/Makefile
+++ b/Makefile
@@ -7,18 +7,20 @@ get:
 put:
 	pscp ./*.exe ./*.c 192.168.1.1:s/src/wconsd/
 
+CFLAGS:=-Wall
+CC:=gcc
 
-wconsd.exe: wconsd.c
-	gcc -Wall -o wconsd.exe wconsd.c -lws2_32
+wconsd.exe: wconsd.o win-scm.o
+	$(CC) -o $@ $^ -lws2_32
 
 portenum.exe: portenum.c
-	gcc -Wall -o portenum.exe portenum.c -lwinspool -lsetupapi
+	$(CC) -o $@ portenum.c -lwinspool -lsetupapi
 
 test: wconsd.exe
 	./wconsd.exe -d
 
 wconsd: wconsd.c
-	winegcc -Wall -mno-cygwin -mwindows -o wconsd wconsd.c -lws2_32
+	winegcc -Wall -mno-cygwin -mwindows -o $@ wconsd.c -lws2_32
 
 wine: wconsd
 	/usr/lib/wine/wine.bin wconsd.exe.so -p 9600
diff --git a/scm.h b/scm.h
new file mode 100644
index 0000000..ffe7a66
--- /dev/null
+++ b/scm.h
@@ -0,0 +1,22 @@
+/*
+ *
+ *
+ *
+ */
+
+struct servicedef {
+	unsigned char *name;
+	unsigned char *desc;
+	int (*init)(int, char **);
+	int (*main)(int);
+	HANDLE stopEvent;
+};
+
+int SCM_Start(struct servicedef *);
+int SCM_Install(struct servicedef *);
+int SCM_Remove(struct servicedef *);
+
+#define SVC_OK		0
+#define	SVC_FAIL	-1
+#define SVC_CONSOLE	1
+
diff --git a/wconsd.c b/wconsd.c
index 9adf61d..f6533f2 100644
--- a/wconsd.c
+++ b/wconsd.c
@@ -30,6 +30,8 @@
 #include <stdio.h>
 #include <stdlib.h>
 
+#include "scm.h"
+
 #define VERSION "0.2.6"
 
 /* Size of buffers for send and receive */
@@ -252,7 +254,7 @@ void close_serial_connection(struct connection *conn) {
 
 /* Initialise wconsd: open a listening socket and the COM port, and
  * create lots of event objects. */
-DWORD wconsd_init(DWORD argc, LPSTR *argv, DWORD *specificError)
+DWORD wconsd_init(DWORD argc, LPSTR *argv)
 {
 	struct sockaddr_in sin;
 	WORD wVersionRequested;
@@ -264,7 +266,6 @@ DWORD wconsd_init(DWORD argc, LPSTR *argv, DWORD *specificError)
 	
 	err = WSAStartup( wVersionRequested, &wsaData );
 	if ( err != 0 ) {
-		*specificError=err;
 		/* Tell the user that we could not find a usable */
 		/* WinSock DLL.                                  */
 		return 1;
@@ -289,29 +290,24 @@ DWORD wconsd_init(DWORD argc, LPSTR *argv, DWORD *specificError)
 	// Create the event object used to signal service shutdown
 	stopEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
 	if (stopEvent==NULL) {
-		*specificError=GetLastError();
 		return 3;
 	}
 	// Event objects for overlapped IO
 	readEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
 	if (readEvent==NULL) {
-		*specificError=GetLastError();
 		return 6;
 	}
 	writeEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
 	if (writeEvent==NULL) {
-		*specificError=GetLastError();
 		return 7;
 	}
 	// Create the event object for socket operations
 	listenSocketEvent = WSACreateEvent();
 	if (listenSocketEvent==WSA_INVALID_EVENT) {
-		*specificError=WSAGetLastError();
 		return 8;
 	}
 
 	if (gethostname((char *)hostname,sizeof(hostname))==SOCKET_ERROR) {
-		*specificError=WSAGetLastError();
 		return 1;
 	}
 	dprintf(1,"wconsd: Hostname is %s\n",hostname);
@@ -331,7 +327,6 @@ DWORD wconsd_init(DWORD argc, LPSTR *argv, DWORD *specificError)
 	sin.sin_port=htons(default_tcpport);
 	ls=socket(AF_INET,SOCK_STREAM,0);
 	if (ls==INVALID_SOCKET) {
-		*specificError=WSAGetLastError();
 		return 9;
 	}
 #ifndef MS_WINDOWS
@@ -341,12 +336,10 @@ DWORD wconsd_init(DWORD argc, LPSTR *argv, DWORD *specificError)
 	}
 #endif
 	if (bind(ls,(struct sockaddr *)&sin,sizeof(sin))==SOCKET_ERROR) {
-		*specificError=WSAGetLastError();
 		dprintf(1,"wconsd: wconsd_init: failed to bind socket\n");
 		return 10;
 	}
 	if (listen(ls,1)==SOCKET_ERROR) {
-		*specificError=WSAGetLastError();
 		return 11;
 	}
 	dprintf(1,"wconsd: listening on port %i\n",default_tcpport);
@@ -354,7 +347,6 @@ DWORD wconsd_init(DWORD argc, LPSTR *argv, DWORD *specificError)
 
 	/* Mark the socket as non-blocking */
 	if (WSAEventSelect(ls,listenSocketEvent,FD_ACCEPT)==SOCKET_ERROR) {
-		*specificError=WSAGetLastError();
 		return 12;
 	}
 
@@ -1333,7 +1325,6 @@ VOID WINAPI MyServiceCtrlHandler(DWORD opcode)
 VOID WINAPI ServiceStart(DWORD argc, LPSTR *argv)
 {
 	DWORD status;
-	DWORD specificError;
 
 	wconsd_status.dwServiceType = SERVICE_WIN32;
 	wconsd_status.dwCurrentState = SERVICE_START_PENDING;
@@ -1349,14 +1340,14 @@ VOID WINAPI ServiceStart(DWORD argc, LPSTR *argv)
 		return;
 	}
 
-	status = wconsd_init(argc, argv, &specificError);
+	status = wconsd_init(argc, argv);
 
 	if (status != NO_ERROR) {
 		wconsd_status.dwCurrentState = SERVICE_STOPPED;
 		wconsd_status.dwCheckPoint = 0;
 		wconsd_status.dwWaitHint = 0;
 		wconsd_status.dwWin32ExitCode = status;
-		wconsd_status.dwServiceSpecificExitCode = specificError;
+		wconsd_status.dwServiceSpecificExitCode = 0;
 
 		SetServiceStatus(wconsd_statusHandle, &wconsd_status);
 		return;
@@ -1459,6 +1450,12 @@ int main(int argc, char **argv)
 		{ NULL, NULL }
 	};
 
+	struct servicedef sd = {
+		"wconsd","wconsd - Telnet to Serial server",
+		wconsd_init, wconsd_main,
+		0
+	};
+
 	// debug info for when I test this as a service
 	dprintf(1,"wconsd: started with argc==%i\n",argc);
 
@@ -1467,15 +1464,19 @@ int main(int argc, char **argv)
 		// assume that our messages are going to the debug log
 		debug_mode=0;
 
-		// start by trying to run as a service
-		if (StartServiceCtrlDispatcher(DispatchTable)==0) {
-			err = GetLastError();
-			dprintf(1,"wconsd: StartServiceCtrlDispatcher error = %d\n", err);
-
-			if (err != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
-				// any other error, assume fatal
-				return 1;
-			}
+//		// start by trying to run as a service
+//		if (StartServiceCtrlDispatcher(DispatchTable)==0) {
+//			err = GetLastError();
+//			dprintf(1,"wconsd: StartServiceCtrlDispatcher error = %d\n", err);
+//
+//			if (err != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
+//				// any other error, assume fatal
+//				return 1;
+//			}
+//		}
+		err = SCM_Start(&sd);
+		if (err!=SVC_CONSOLE) {
+			return 0;
 		}
 
 		// fall through and try running as a command-line application
@@ -1497,11 +1498,13 @@ int main(int argc, char **argv)
 				usage();
 				return 1;
 			}
-			RegisterService(argv[2]);
+			// RegisterService(argv[2]);
+			SCM_Install(&sd);
 			return 0;
 		} else if (strcmp(argv[1],"-r")==0) {
 			// request service removal
-			RemoveService();
+			// RemoveService();
+			SCM_Remove(&sd);
 			return 0;
 		} else if (strcmp(argv[1],"-p")==0) {
 			console_application=1;
@@ -1523,9 +1526,9 @@ int main(int argc, char **argv)
 	if (console_application) {
 		int r;
 		dprintf(1,"wconsd: Foreground mode\n");
-		r=wconsd_init(argc,argv,&err);
+		r=wconsd_init(argc,argv);
 		if (r!=0) {
-			dprintf(1,"wconsd: wconsd_init failed, return code %d [%l]\n",r, err);
+			dprintf(1,"wconsd: wconsd_init failed, return code %d\n",r);
 			return 1;
 		}
 		wconsd_main();
diff --git a/win-scm.c b/win-scm.c
new file mode 100644
index 0000000..1feecb1
--- /dev/null
+++ b/win-scm.c
@@ -0,0 +1,187 @@
+/*
+ * win-scm.c - windows service control manager functions
+ *
+ * Copyright (c) 2008 Hamish Coleman <hamish@zot.org>
+ *               2003 Benjamin Schweizer <gopher at h07 dot org>
+ *               1998 Stephen Early <Stephen.Early@cl.cam.ac.uk>
+ *
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#include <windows.h>
+#include <winsvc.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "scm.h"
+
+/* Service status: our current status, and handle on service manager */
+SERVICE_STATUS svcStatus;
+SERVICE_STATUS_HANDLE svcHandle;
+
+/* global pointer to our service definition */
+struct servicedef *global_sd;
+
+VOID WINAPI ServiceCtrlHandler(DWORD opcode) {
+	svcStatus.dwWin32ExitCode = NO_ERROR;
+	if (opcode == SERVICE_CONTROL_STOP) {
+		svcStatus.dwCurrentState = SERVICE_STOP_PENDING;
+		SetServiceStatus( svcHandle, &svcStatus );
+		SetEvent(global_sd->stopEvent);
+		return;
+	}
+	SetServiceStatus( svcHandle, &svcStatus );
+}
+
+VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
+{
+	int err;
+	struct servicedef *sd = global_sd;
+
+	svcHandle = RegisterServiceCtrlHandler(sd->name,ServiceCtrlHandler);
+	if (!svcHandle) {
+		/* FIXME - use SvcReportEvent() */
+		printf("RegisterServiceCtrlHandler failed %u\n", GetLastError());
+		return;
+	}
+
+	svcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
+	svcStatus.dwCurrentState = 0;
+	svcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
+	svcStatus.dwWin32ExitCode = NO_ERROR;
+	svcStatus.dwServiceSpecificExitCode = 0;
+	svcStatus.dwCheckPoint = 0;
+	svcStatus.dwWaitHint = 5000;
+
+	/* Report initial status to the SCM. */
+	svcStatus.dwCurrentState = SERVICE_START_PENDING;
+	SetServiceStatus( svcHandle, &svcStatus );
+
+	/* Create the event object used to signal service shutdown */
+	sd->stopEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
+	if (sd->stopEvent==NULL) {
+		svcStatus.dwCurrentState = SERVICE_STOPPED;
+		SetServiceStatus( svcHandle, &svcStatus );
+		return;
+	}
+
+	if ((err=sd->init(argc,argv))!=0) {
+		svcStatus.dwCurrentState = SERVICE_STOPPED;
+		svcStatus.dwWin32ExitCode = err;
+		SetServiceStatus( svcHandle, &svcStatus );
+		return;
+	}
+
+	svcStatus.dwCurrentState = SERVICE_RUNNING;
+	svcStatus.dwWin32ExitCode = NO_ERROR;
+	SetServiceStatus( svcHandle, &svcStatus );
+
+	/* Loop until we are stopping */
+	while(WaitForSingleObject(sd->stopEvent, 0)==WAIT_TIMEOUT) {
+		err=sd->main(0);
+	}
+
+	svcStatus.dwCurrentState = SERVICE_STOPPED;
+	svcStatus.dwWin32ExitCode = NO_ERROR;
+	SetServiceStatus( svcHandle, &svcStatus );
+	return;
+}
+
+int SCM_Start(struct servicedef *sd) {
+	SERVICE_TABLE_ENTRY ServiceTable[] = {
+		{ "", ServiceMain },
+		{ NULL, NULL }
+	};
+
+	global_sd = sd;
+
+	/* try to run as a service */
+	if (StartServiceCtrlDispatcher(ServiceTable)==0) {
+		int err = GetLastError();
+		printf("StartServiceCtrlDispatcher error = %d\n", err);
+
+		if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
+			/* TODO - could run the console service from here */
+			return SVC_CONSOLE;
+		}
+
+		/* any other error, assume fatal */
+		return SVC_FAIL;
+	}
+	return SVC_OK;
+}
+
+int SCM_Install(struct servicedef *sd) {
+	SC_HANDLE schSCManager, schService;
+
+	char path[MAX_PATH];
+
+	if( !GetModuleFileName( NULL, path, MAX_PATH ) ) {
+		printf("Cannot install service (%u)\n", GetLastError());
+		return -1;
+	}
+
+	schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
+
+	schService = CreateService(
+		schSCManager,
+		sd->name,
+		sd->desc,
+		SERVICE_ALL_ACCESS,
+		SERVICE_WIN32_OWN_PROCESS,
+		SERVICE_AUTO_START,
+		SERVICE_ERROR_NORMAL,
+		path,
+		NULL, NULL, NULL, NULL, NULL);
+
+	if (schService == NULL) {
+		printf("CreateService failed\n");
+		CloseServiceHandle(schService);
+		return -1;
+	} else {
+		printf("Created service '%s', binary path %s\n",sd->name,path);
+		printf("You should now start the service using the service manager.\n");
+		CloseServiceHandle(schService);
+		return 0;
+	}
+}
+
+int SCM_Remove(struct servicedef *sd) {
+	SC_HANDLE schSCManager, schService;
+
+	schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
+	if (schSCManager == NULL) {
+		printf("Couldn't open service manager\n");
+		return -1;
+	}
+
+	schService = OpenService(schSCManager, sd->name, DELETE);
+	if (schService == NULL) {
+		printf("Couldn't open %s service\n",sd->name);
+		return -1;
+	}
+
+	if (!DeleteService(schService)) {
+		printf("Couldn't delete %s service\n",sd->name);
+		return -1;
+	}
+
+	printf("Deleted service '%s'\n",sd->name);
+
+	CloseServiceHandle(schService);
+	return 0;
+}
+
