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 DWORD LastError = GetLastError();
59 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, LastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)err, sizeof(err), 0) == 0)
60 snprintf(err, sizeof(err), "Error code: %d", LastError);
61 SetLastError(ERROR_SUCCESS);
65 /* Returns true if this program is running as a service, false if it is running interactive */
68 USEROBJECTFLAGS uoflags;
69 HWINSTA winstation = GetProcessWindowStation();
70 if (GetUserObjectInformation(winstation, UOI_FLAGS, &uoflags, sizeof(uoflags), NULL))
71 return ((uoflags.dwFlags & WSF_VISIBLE) == 0);
76 /* Kills the service by setting an event which the other thread picks up and exits */
79 SetEvent(hThreadEvent);
81 SetEvent(killServiceEvent);
84 /** The main part of inspircd runs within this thread function. This allows the service part to run
85 * seperately on its own and to be able to kill the worker thread when its time to quit.
87 DWORD WINAPI WorkerThread(LPDWORD param)
89 char modname[MAX_PATH];
90 GetModuleFileNameA(NULL, modname, sizeof(modname));
91 char* argv[] = { modname, "--nofork" };
97 /* This is called when all startup is done */
98 void SetServiceRunning()
103 serviceCurrentStatus = SERVICE_RUNNING;
104 BOOL success = UpdateSCMStatus(SERVICE_RUNNING, NO_ERROR, 0, 0, 0);
107 terminateService(EXIT_STATUS_UPDATESCM_FAILED, GetLastError());
113 /** Starts the worker thread above */
114 void StartServiceThread()
117 CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)WorkerThread,NULL,0,&dwd);
120 /** This function updates the status of the service in the SCM
121 * (service control manager, the services.msc applet)
123 BOOL UpdateSCMStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint, DWORD dwWaitHint)
126 SERVICE_STATUS serviceStatus;
127 serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
128 serviceStatus.dwCurrentState = dwCurrentState;
130 if (dwCurrentState == SERVICE_START_PENDING)
132 serviceStatus.dwControlsAccepted = 0;
136 serviceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
139 if (dwServiceSpecificExitCode == 0)
141 serviceStatus.dwWin32ExitCode = dwWin32ExitCode;
145 serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
147 serviceStatus.dwServiceSpecificExitCode = dwServiceSpecificExitCode;
148 serviceStatus.dwCheckPoint = dwCheckPoint;
149 serviceStatus.dwWaitHint = dwWaitHint;
151 success = SetServiceStatus (serviceStatusHandle, &serviceStatus);
159 /** This function is called by us when the service is being shut down or when it can't be started */
160 void terminateService(int code, int wincode)
162 UpdateSCMStatus(SERVICE_STOPPED, wincode ? wincode : ERROR_SERVICE_SPECIFIC_ERROR, wincode ? 0 : code, 0, 0);
166 /* In windows we hook this to InspIRCd::Exit() */
167 void SetServiceStopped(int status)
172 /* Are we running as a service? If so, trigger the service specific exit code */
173 terminateService(status, 0);
178 /** This callback is called by windows when the state of the service has been changed */
179 VOID ServiceCtrlHandler(DWORD controlCode)
183 case SERVICE_CONTROL_INTERROGATE:
185 case SERVICE_CONTROL_SHUTDOWN:
186 case SERVICE_CONTROL_STOP:
187 serviceCurrentStatus = SERVICE_STOP_PENDING;
188 UpdateSCMStatus(SERVICE_STOP_PENDING, NO_ERROR, 0, 1, 5000);
190 UpdateSCMStatus(SERVICE_STOPPED, NO_ERROR, 0, 0, 0);
195 UpdateSCMStatus(serviceCurrentStatus, NO_ERROR, 0, 0, 0);
198 /** This callback is called by windows when the service is started */
199 VOID ServiceMain(DWORD argc, LPTSTR *argv)
203 serviceStatusHandle = RegisterServiceCtrlHandler(TEXT("InspIRCd"), (LPHANDLER_FUNCTION)ServiceCtrlHandler);
204 if (!serviceStatusHandle)
206 terminateService(EXIT_STATUS_RSCH_FAILED, GetLastError());
210 success = UpdateSCMStatus(SERVICE_START_PENDING, NO_ERROR, 0, 1, 1000);
213 terminateService(EXIT_STATUS_UPDATESCM_FAILED, GetLastError());
217 killServiceEvent = CreateEvent(NULL, true, false, NULL);
218 hThreadEvent = CreateEvent(NULL, true, false, NULL);
220 if (!killServiceEvent || !hThreadEvent)
222 terminateService(EXIT_STATUS_CREATE_EVENT_FAILED, GetLastError());
226 success = UpdateSCMStatus(SERVICE_START_PENDING, NO_ERROR, 0, 2, 1000);
229 terminateService(EXIT_STATUS_UPDATESCM_FAILED, GetLastError());
233 StartServiceThread();
234 WaitForSingleObject (killServiceEvent, INFINITE);
237 /** Install the windows service. This requires administrator privileges. */
238 void InstallService()
240 SC_HANDLE myService, scm;
241 SERVICE_DESCRIPTION svDesc;
244 TCHAR modname[MAX_PATH];
245 GetModuleFileName(NULL, modname, sizeof(modname));
247 scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
250 std::cout << "Unable to open service control manager: " << RetrieveLastError() << std::endl;
254 myService = CreateService(scm,TEXT("InspIRCd"),TEXT("Inspire IRC Daemon"), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
255 SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, modname, 0, 0, 0, NULL, NULL);
259 std::cout << "Unable to create service: " << RetrieveLastError() << std::endl;
260 CloseServiceHandle(scm);
264 // *** Set service description ***
265 // this is supported from 5.0 (win2k) onwards only, so we can't link to the definition of
266 // this function in advapi32.lib, otherwise the program will not run on windows NT 4. We
267 // must use LoadLibrary and GetProcAddress to export the function name from advapi32.dll
268 advapi32 = LoadLibrary(TEXT("advapi32.dll"));
271 ChangeServiceConf = (SETSERVDESC)GetProcAddress(advapi32,"ChangeServiceConfig2A");
272 if (ChangeServiceConf)
274 TCHAR desc[] = TEXT("The Inspire Internet Relay Chat Daemon hosts IRC channels and conversations.\
275 If this service is stopped, the IRC server will not run.");
276 svDesc.lpDescription = desc;
277 BOOL success = ChangeServiceConf(myService,SERVICE_CONFIG_DESCRIPTION, &svDesc);
280 std::cout << "Unable to set service description: " << RetrieveLastError() << std::endl;
281 CloseServiceHandle(myService);
282 CloseServiceHandle(scm);
286 FreeLibrary(advapi32);
289 std::cout << "Service installed." << std::endl;
290 CloseServiceHandle(myService);
291 CloseServiceHandle(scm);
294 /** Remove the windows service. This requires administrator privileges. */
297 SC_HANDLE myService, scm;
299 scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
302 std::cout << "Unable to open service control manager: " << RetrieveLastError() << std::endl;
306 myService = OpenService(scm,TEXT("InspIRCd"),SERVICE_ALL_ACCESS);
309 std::cout << "Unable to open service: " << RetrieveLastError() << std::endl;
310 CloseServiceHandle(scm);
314 if (!DeleteService(myService))
316 std::cout << "Unable to delete service: " << RetrieveLastError() << std::endl;
317 CloseServiceHandle(myService);
318 CloseServiceHandle(scm);
322 std::cout << "Service removed." << std::endl;
323 CloseServiceHandle(myService);
324 CloseServiceHandle(scm);
327 /* In windows, our main() flows through here, before calling the 'real' main, smain() in inspircd.cpp */
328 int main(int argc, char** argv)
330 /* List of parameters and handlers */
331 Commandline params[] = {
332 { "--installservice", InstallService },
333 { "--removeservice", RemoveService },
337 /* Check for parameters */
340 for (int z = 0; params[z].Switch; ++z)
342 if (!_stricmp(argv[1], params[z].Switch))
350 /* First, check if the service is installed.
351 * if it is not, or we're starting as non-administrator,
352 * just call smain() and start as normal non-service
355 SC_HANDLE myService, scm;
356 scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
359 myService = OpenService(scm,TEXT("InspIRCd"),SERVICE_ALL_ACCESS);
362 /* Service not installed or no permission to modify it */
363 CloseServiceHandle(scm);
364 return smain(argc, argv);
369 /* Not enough privileges to open the SCM */
370 return smain(argc, argv);
373 CloseServiceHandle(myService);
374 CloseServiceHandle(scm);
376 /* Check if the process is running interactively. InspIRCd does not run interactively
377 * as a service so if this is true, we just run the non-service inspircd.
380 return smain(argc, argv);
382 /* If we get here, we know the service is installed so we can start it */
384 SERVICE_TABLE_ENTRY serviceTable[] =
386 {TEXT("InspIRCd"), (LPSERVICE_MAIN_FUNCTION) ServiceMain },
390 StartServiceCtrlDispatcher(serviceTable);