2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc>
6 * This file is part of InspIRCd. InspIRCd is free software: you can
7 * redistribute it and/or modify it under the terms of the GNU General Public
8 * License as published by the Free Software Foundation, version 2.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include "inspircd_config.h"
22 #include "exitcodes.h"
28 static SERVICE_STATUS_HANDLE serviceStatusHandle;
29 static HANDLE hThreadEvent;
30 static HANDLE killServiceEvent;
31 static int serviceCurrentStatus;
33 /** This is used to define ChangeServiceConf2() as we can't link
34 * directly against this symbol (see below where it is used)
36 typedef BOOL (CALLBACK* SETSERVDESC)(SC_HANDLE,DWORD,LPVOID);
38 BOOL UpdateSCMStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint);
39 void terminateService(int code, int wincode);
41 /* A commandline parameter handler for service specific commandline parameters */
42 typedef void (*CommandlineParameterHandler)(void);
44 /* Represents a commandline and its handler */
48 CommandlineParameterHandler Handler;
51 /* A function pointer for dynamic linking tricks */
52 SETSERVDESC ChangeServiceConf;
54 LPCSTR RetrieveLastError()
57 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)err, sizeof(err), 0);
58 SetLastError(ERROR_SUCCESS);
62 /* Returns true if this program is running as a service, false if it is running interactive */
65 USEROBJECTFLAGS uoflags;
66 HWINSTA winstation = GetProcessWindowStation();
67 if (GetUserObjectInformation(winstation, UOI_FLAGS, &uoflags, sizeof(uoflags), NULL))
68 return ((uoflags.dwFlags & WSF_VISIBLE) == 0);
73 /* Kills the service by setting an event which the other thread picks up and exits */
76 SetEvent(hThreadEvent);
78 SetEvent(killServiceEvent);
81 /** The main part of inspircd runs within this thread function. This allows the service part to run
82 * seperately on its own and to be able to kill the worker thread when its time to quit.
84 DWORD WINAPI WorkerThread(LPDWORD param)
86 char modname[MAX_PATH];
87 GetModuleFileNameA(NULL, modname, sizeof(modname));
88 char* argv[] = { modname, "--nofork" };
94 /* This is called when all startup is done */
95 void SetServiceRunning()
100 serviceCurrentStatus = SERVICE_RUNNING;
101 BOOL success = UpdateSCMStatus(SERVICE_RUNNING, NO_ERROR, 0, 0, 0);
104 terminateService(EXIT_STATUS_UPDATESCM_FAILED, GetLastError());
110 /** Starts the worker thread above */
111 void StartServiceThread()
114 CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)WorkerThread,NULL,0,&dwd);
117 /** This function updates the status of the service in the SCM
118 * (service control manager, the services.msc applet)
120 BOOL UpdateSCMStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint)
123 SERVICE_STATUS serviceStatus;
124 serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
125 serviceStatus.dwCurrentState = dwCurrentState;
127 if (dwCurrentState == SERVICE_START_PENDING)
129 serviceStatus.dwControlsAccepted = 0;
133 serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
136 if (dwServiceSpecificExitCode == 0)
138 serviceStatus.dwWin32ExitCode = dwWin32ExitCode;
142 serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
144 serviceStatus.dwServiceSpecificExitCode = dwServiceSpecificExitCode;
145 serviceStatus.dwCheckPoint = dwCheckPoint;
146 serviceStatus.dwWaitHint = dwWaitHint;
148 success = SetServiceStatus (serviceStatusHandle, &serviceStatus);
156 /** This function is called by us when the service is being shut down or when it can't be started */
157 void terminateService(int code, int wincode)
159 UpdateSCMStatus(SERVICE_STOPPED, wincode ? wincode : ERROR_SERVICE_SPECIFIC_ERROR, wincode ? 0 : code, 0, 0);
163 /* In windows we hook this to InspIRCd::Exit() */
164 void SetServiceStopped(int status)
169 /* Are we running as a service? If so, trigger the service specific exit code */
170 terminateService(status, 0);
175 /** This callback is called by windows when the state of the service has been changed */
176 VOID ServiceCtrlHandler(DWORD controlCode)
180 case SERVICE_CONTROL_INTERROGATE:
182 case SERVICE_CONTROL_SHUTDOWN:
183 case SERVICE_CONTROL_STOP:
184 serviceCurrentStatus = SERVICE_STOP_PENDING;
185 UpdateSCMStatus(SERVICE_STOP_PENDING, NO_ERROR, 0, 1, 5000);
187 UpdateSCMStatus(SERVICE_STOPPED, NO_ERROR, 0, 0, 0);
192 UpdateSCMStatus(serviceCurrentStatus, NO_ERROR, 0, 0, 0);
195 /** This callback is called by windows when the service is started */
196 VOID ServiceMain(DWORD argc, LPTSTR *argv)
200 serviceStatusHandle = RegisterServiceCtrlHandler(TEXT("InspIRCd"), (LPHANDLER_FUNCTION)ServiceCtrlHandler);
201 if (!serviceStatusHandle)
203 terminateService(EXIT_STATUS_RSCH_FAILED, GetLastError());
207 success = UpdateSCMStatus(SERVICE_START_PENDING, NO_ERROR, 0, 1, 1000);
210 terminateService(EXIT_STATUS_UPDATESCM_FAILED, GetLastError());
214 killServiceEvent = CreateEvent(NULL, true, false, NULL);
215 hThreadEvent = CreateEvent(NULL, true, false, NULL);
217 if (!killServiceEvent || !hThreadEvent)
219 terminateService(EXIT_STATUS_CREATE_EVENT_FAILED, GetLastError());
223 success = UpdateSCMStatus(SERVICE_START_PENDING, NO_ERROR, 0, 2, 1000);
226 terminateService(EXIT_STATUS_UPDATESCM_FAILED, GetLastError());
230 StartServiceThread();
231 WaitForSingleObject (killServiceEvent, INFINITE);
234 /** Install the windows service. This requires administrator privileges. */
235 void InstallService()
237 SC_HANDLE myService, scm;
238 SERVICE_DESCRIPTION svDesc;
241 TCHAR modname[MAX_PATH];
242 GetModuleFileName(NULL, modname, sizeof(modname));
244 scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
247 printf("Unable to open service control manager: %s\n", RetrieveLastError());
251 myService = CreateService(scm,TEXT("InspIRCd"),TEXT("Inspire IRC Daemon"), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
252 SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, modname, 0, 0, 0, NULL, NULL);
256 printf("Unable to create service: %s\n", RetrieveLastError());
257 CloseServiceHandle(scm);
261 // *** Set service description ***
262 // this is supported from 5.0 (win2k) onwards only, so we can't link to the definition of
263 // this function in advapi32.lib, otherwise the program will not run on windows NT 4. We
264 // must use LoadLibrary and GetProcAddress to export the function name from advapi32.dll
265 advapi32 = LoadLibrary(TEXT("advapi32.dll"));
268 ChangeServiceConf = (SETSERVDESC)GetProcAddress(advapi32,"ChangeServiceConfig2A");
269 if (ChangeServiceConf)
271 TCHAR desc[] = TEXT("The Inspire Internet Relay Chat Daemon hosts IRC channels and conversations.\
272 If this service is stopped, the IRC server will not run.");
273 svDesc.lpDescription = desc;
274 BOOL success = ChangeServiceConf(myService,SERVICE_CONFIG_DESCRIPTION, &svDesc);
277 printf("Unable to set service description: %s\n", RetrieveLastError());
278 CloseServiceHandle(myService);
279 CloseServiceHandle(scm);
283 FreeLibrary(advapi32);
286 printf("Service installed.\n");
287 CloseServiceHandle(myService);
288 CloseServiceHandle(scm);
291 /** Remove the windows service. This requires administrator privileges. */
294 SC_HANDLE myService, scm;
296 scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
299 printf("Unable to open service control manager: %s\n", RetrieveLastError());
303 myService = OpenService(scm,TEXT("InspIRCd"),SERVICE_ALL_ACCESS);
306 printf("Unable to open service: %s\n", RetrieveLastError());
307 CloseServiceHandle(scm);
311 if (!DeleteService(myService))
313 printf("Unable to delete service: %s\n", RetrieveLastError());
314 CloseServiceHandle(myService);
315 CloseServiceHandle(scm);
319 printf("Service removed.\n");
320 CloseServiceHandle(myService);
321 CloseServiceHandle(scm);
324 /* In windows, our main() flows through here, before calling the 'real' main, smain() in inspircd.cpp */
325 int main(int argc, char** argv)
327 /* List of parameters and handlers */
328 Commandline params[] = {
329 { "--installservice", InstallService },
330 { "--removeservice", RemoveService },
334 /* Check for parameters */
337 for (int z = 0; params[z].Switch; ++z)
339 if (!_stricmp(argv[1], params[z].Switch))
347 /* First, check if the service is installed.
348 * if it is not, or we're starting as non-administrator,
349 * just call smain() and start as normal non-service
352 SC_HANDLE myService, scm;
353 scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
356 myService = OpenService(scm,TEXT("InspIRCd"),SERVICE_ALL_ACCESS);
359 /* Service not installed or no permission to modify it */
360 CloseServiceHandle(scm);
361 return smain(argc, argv);
366 /* Not enough privileges to open the SCM */
367 return smain(argc, argv);
370 CloseServiceHandle(myService);
371 CloseServiceHandle(scm);
373 /* Check if the process is running interactively. InspIRCd does not run interactively
374 * as a service so if this is true, we just run the non-service inspircd.
377 return smain(argc, argv);
379 /* If we get here, we know the service is installed so we can start it */
381 SERVICE_TABLE_ENTRY serviceTable[] =
383 {TEXT("InspIRCd"), (LPSERVICE_MAIN_FUNCTION) ServiceMain },
387 StartServiceCtrlDispatcher(serviceTable);