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"
29 static SERVICE_STATUS_HANDLE serviceStatusHandle;
30 static HANDLE hThreadEvent;
31 static HANDLE killServiceEvent;
32 static int serviceCurrentStatus;
34 /** This is used to define ChangeServiceConf2() as we can't link
35 * directly against this symbol (see below where it is used)
37 typedef BOOL (CALLBACK* SETSERVDESC)(SC_HANDLE,DWORD,LPVOID);
39 BOOL UpdateSCMStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint);
40 void terminateService(int code, int wincode);
42 /* A commandline parameter handler for service specific commandline parameters */
43 typedef void (*CommandlineParameterHandler)(void);
45 /* Represents a commandline and its handler */
49 CommandlineParameterHandler Handler;
52 /* A function pointer for dynamic linking tricks */
53 SETSERVDESC ChangeServiceConf;
55 LPCSTR RetrieveLastError()
58 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)err, sizeof(err), 0);
59 SetLastError(ERROR_SUCCESS);
63 /* Returns true if this program is running as a service, false if it is running interactive */
66 USEROBJECTFLAGS uoflags;
67 HWINSTA winstation = GetProcessWindowStation();
68 if (GetUserObjectInformation(winstation, UOI_FLAGS, &uoflags, sizeof(uoflags), NULL))
69 return ((uoflags.dwFlags & WSF_VISIBLE) == 0);
74 /* Kills the service by setting an event which the other thread picks up and exits */
77 SetEvent(hThreadEvent);
79 SetEvent(killServiceEvent);
82 /** The main part of inspircd runs within this thread function. This allows the service part to run
83 * seperately on its own and to be able to kill the worker thread when its time to quit.
85 DWORD WINAPI WorkerThread(LPDWORD param)
87 char modname[MAX_PATH];
88 GetModuleFileNameA(NULL, modname, sizeof(modname));
89 char* argv[] = { modname, "--nofork" };
95 /* This is called when all startup is done */
96 void SetServiceRunning()
101 serviceCurrentStatus = SERVICE_RUNNING;
102 BOOL success = UpdateSCMStatus(SERVICE_RUNNING, NO_ERROR, 0, 0, 0);
105 terminateService(EXIT_STATUS_UPDATESCM_FAILED, GetLastError());
111 /** Starts the worker thread above */
112 void StartServiceThread()
115 CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)WorkerThread,NULL,0,&dwd);
118 /** This function updates the status of the service in the SCM
119 * (service control manager, the services.msc applet)
121 BOOL UpdateSCMStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint)
124 SERVICE_STATUS serviceStatus;
125 serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
126 serviceStatus.dwCurrentState = dwCurrentState;
128 if (dwCurrentState == SERVICE_START_PENDING)
130 serviceStatus.dwControlsAccepted = 0;
134 serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
137 if (dwServiceSpecificExitCode == 0)
139 serviceStatus.dwWin32ExitCode = dwWin32ExitCode;
143 serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
145 serviceStatus.dwServiceSpecificExitCode = dwServiceSpecificExitCode;
146 serviceStatus.dwCheckPoint = dwCheckPoint;
147 serviceStatus.dwWaitHint = dwWaitHint;
149 success = SetServiceStatus (serviceStatusHandle, &serviceStatus);
157 /** This function is called by us when the service is being shut down or when it can't be started */
158 void terminateService(int code, int wincode)
160 UpdateSCMStatus(SERVICE_STOPPED, wincode ? wincode : ERROR_SERVICE_SPECIFIC_ERROR, wincode ? 0 : code, 0, 0);
164 /* In windows we hook this to InspIRCd::Exit() */
165 void SetServiceStopped(int status)
170 /* Are we running as a service? If so, trigger the service specific exit code */
171 terminateService(status, 0);
176 /** This callback is called by windows when the state of the service has been changed */
177 VOID ServiceCtrlHandler(DWORD controlCode)
181 case SERVICE_CONTROL_INTERROGATE:
183 case SERVICE_CONTROL_SHUTDOWN:
184 case SERVICE_CONTROL_STOP:
185 serviceCurrentStatus = SERVICE_STOP_PENDING;
186 UpdateSCMStatus(SERVICE_STOP_PENDING, NO_ERROR, 0, 1, 5000);
188 UpdateSCMStatus(SERVICE_STOPPED, NO_ERROR, 0, 0, 0);
193 UpdateSCMStatus(serviceCurrentStatus, NO_ERROR, 0, 0, 0);
196 /** This callback is called by windows when the service is started */
197 VOID ServiceMain(DWORD argc, LPTSTR *argv)
201 serviceStatusHandle = RegisterServiceCtrlHandler(TEXT("InspIRCd"), (LPHANDLER_FUNCTION)ServiceCtrlHandler);
202 if (!serviceStatusHandle)
204 terminateService(EXIT_STATUS_RSCH_FAILED, GetLastError());
208 success = UpdateSCMStatus(SERVICE_START_PENDING, NO_ERROR, 0, 1, 1000);
211 terminateService(EXIT_STATUS_UPDATESCM_FAILED, GetLastError());
215 killServiceEvent = CreateEvent(NULL, true, false, NULL);
216 hThreadEvent = CreateEvent(NULL, true, false, NULL);
218 if (!killServiceEvent || !hThreadEvent)
220 terminateService(EXIT_STATUS_CREATE_EVENT_FAILED, GetLastError());
224 success = UpdateSCMStatus(SERVICE_START_PENDING, NO_ERROR, 0, 2, 1000);
227 terminateService(EXIT_STATUS_UPDATESCM_FAILED, GetLastError());
231 StartServiceThread();
232 WaitForSingleObject (killServiceEvent, INFINITE);
235 /** Install the windows service. This requires administrator privileges. */
236 void InstallService()
238 SC_HANDLE myService, scm;
239 SERVICE_DESCRIPTION svDesc;
242 TCHAR modname[MAX_PATH];
243 GetModuleFileName(NULL, modname, sizeof(modname));
245 scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
248 std::cout << "Unable to open service control manager: " << RetrieveLastError() << std::endl;
252 myService = CreateService(scm,TEXT("InspIRCd"),TEXT("Inspire IRC Daemon"), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
253 SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, modname, 0, 0, 0, NULL, NULL);
257 std::cout << "Unable to create service: " << RetrieveLastError() << std::endl;
258 CloseServiceHandle(scm);
262 // *** Set service description ***
263 // this is supported from 5.0 (win2k) onwards only, so we can't link to the definition of
264 // this function in advapi32.lib, otherwise the program will not run on windows NT 4. We
265 // must use LoadLibrary and GetProcAddress to export the function name from advapi32.dll
266 advapi32 = LoadLibrary(TEXT("advapi32.dll"));
269 ChangeServiceConf = (SETSERVDESC)GetProcAddress(advapi32,"ChangeServiceConfig2A");
270 if (ChangeServiceConf)
272 TCHAR desc[] = TEXT("The Inspire Internet Relay Chat Daemon hosts IRC channels and conversations.\
273 If this service is stopped, the IRC server will not run.");
274 svDesc.lpDescription = desc;
275 BOOL success = ChangeServiceConf(myService,SERVICE_CONFIG_DESCRIPTION, &svDesc);
278 std::cout << "Unable to set service description: " << RetrieveLastError() << std::endl;
279 CloseServiceHandle(myService);
280 CloseServiceHandle(scm);
284 FreeLibrary(advapi32);
287 std::cout << "Service installed." << std::endl;
288 CloseServiceHandle(myService);
289 CloseServiceHandle(scm);
292 /** Remove the windows service. This requires administrator privileges. */
295 SC_HANDLE myService, scm;
297 scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
300 std::cout << "Unable to open service control manager: " << RetrieveLastError() << std::endl;
304 myService = OpenService(scm,TEXT("InspIRCd"),SERVICE_ALL_ACCESS);
307 std::cout << "Unable to open service: " << RetrieveLastError() << std::endl;
308 CloseServiceHandle(scm);
312 if (!DeleteService(myService))
314 std::cout << "Unable to delete service: " << RetrieveLastError() << std::endl;
315 CloseServiceHandle(myService);
316 CloseServiceHandle(scm);
320 std::cout << "Service removed." << std::endl;
321 CloseServiceHandle(myService);
322 CloseServiceHandle(scm);
325 /* In windows, our main() flows through here, before calling the 'real' main, smain() in inspircd.cpp */
326 int main(int argc, char** argv)
328 /* List of parameters and handlers */
329 Commandline params[] = {
330 { "--installservice", InstallService },
331 { "--removeservice", RemoveService },
335 /* Check for parameters */
338 for (int z = 0; params[z].Switch; ++z)
340 if (!_stricmp(argv[1], params[z].Switch))
348 /* First, check if the service is installed.
349 * if it is not, or we're starting as non-administrator,
350 * just call smain() and start as normal non-service
353 SC_HANDLE myService, scm;
354 scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
357 myService = OpenService(scm,TEXT("InspIRCd"),SERVICE_ALL_ACCESS);
360 /* Service not installed or no permission to modify it */
361 CloseServiceHandle(scm);
362 return smain(argc, argv);
367 /* Not enough privileges to open the SCM */
368 return smain(argc, argv);
371 CloseServiceHandle(myService);
372 CloseServiceHandle(scm);
374 /* Check if the process is running interactively. InspIRCd does not run interactively
375 * as a service so if this is true, we just run the non-service inspircd.
378 return smain(argc, argv);
380 /* If we get here, we know the service is installed so we can start it */
382 SERVICE_TABLE_ENTRY serviceTable[] =
384 {TEXT("InspIRCd"), (LPSERVICE_MAIN_FUNCTION) ServiceMain },
388 StartServiceCtrlDispatcher(serviceTable);