1 /******************************************************************************
3 * Copyright (C) 2012-2017 Icinga Development Team (https://www.icinga.com/) *
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License *
7 * as published by the Free Software Foundation; either version 2 *
8 * of the License, or (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the Free Software Foundation *
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
18 ******************************************************************************/
20 #include "cli/clicommand.hpp"
21 #include "config/configcompilercontext.hpp"
22 #include "config/configcompiler.hpp"
23 #include "config/configitembuilder.hpp"
24 #include "base/application.hpp"
25 #include "base/logger.hpp"
26 #include "base/timer.hpp"
27 #include "base/utility.hpp"
28 #include "base/loader.hpp"
29 #include "base/exception.hpp"
30 #include "base/convert.hpp"
31 #include "base/scriptglobal.hpp"
32 #include "base/context.hpp"
33 #include "base/console.hpp"
34 #include "base/process.hpp"
36 #include <boost/program_options.hpp>
37 #include <boost/tuple/tuple.hpp>
40 # include <sys/types.h>
46 # include <Shellapi.h>
50 using namespace icinga;
51 namespace po = boost::program_options;
54 static SERVICE_STATUS l_SvcStatus;
55 static SERVICE_STATUS_HANDLE l_SvcStatusHandle;
59 static std::vector<String> GetLogLevelCompletionSuggestions(const String& arg)
61 std::vector<String> result;
63 String debugLevel = "debug";
64 if (debugLevel.Find(arg) == 0)
65 result.push_back(debugLevel);
67 String noticeLevel = "notice";
68 if (noticeLevel.Find(arg) == 0)
69 result.push_back(noticeLevel);
71 String informationLevel = "information";
72 if (informationLevel.Find(arg) == 0)
73 result.push_back(informationLevel);
75 String warningLevel = "warning";
76 if (warningLevel.Find(arg) == 0)
77 result.push_back(warningLevel);
79 String criticalLevel = "critical";
80 if (criticalLevel.Find(arg) == 0)
81 result.push_back(criticalLevel);
86 static std::vector<String> GlobalArgumentCompletion(const String& argument, const String& word)
88 if (argument == "include")
89 return GetBashCompletionSuggestions("directory", word);
90 else if (argument == "log-level")
91 return GetLogLevelCompletionSuggestions(word);
93 return std::vector<String>();
98 int argc = Application::GetArgC();
99 char **argv = Application::GetArgV();
101 bool autocomplete = false;
104 if (argc >= 4 && strcmp(argv[1], "--autocomplete") == 0) {
108 autoindex = Convert::ToLong(argv[2]);
109 } catch (const std::invalid_argument& ex) {
110 Log(LogCritical, "icinga-app")
111 << "Invalid index for --autocomplete: " << argv[2];
119 Application::SetStartTime(Utility::GetTime());
121 /* Set thread title. */
122 Utility::SetThreadName("Main Thread", false);
124 /* Install exception handlers to make debugging easier. */
125 Application::InstallExceptionHandlers();
128 bool builtinPaths = true;
130 String binaryPrefix = Utility::GetIcingaInstallPath();
131 String dataPrefix = Utility::GetIcingaDataPath();
133 if (!binaryPrefix.IsEmpty() && !dataPrefix.IsEmpty()) {
134 Application::DeclarePrefixDir(binaryPrefix);
135 Application::DeclareSysconfDir(dataPrefix + "\\etc");
136 Application::DeclareRunDir(dataPrefix + "\\var\\run");
137 Application::DeclareLocalStateDir(dataPrefix + "\\var");
138 Application::DeclarePkgDataDir(binaryPrefix + "\\share\\icinga2");
139 Application::DeclareIncludeConfDir(binaryPrefix + "\\share\\icinga2\\include");
141 Log(LogWarning, "icinga-app", "Registry key could not be read. Falling back to built-in paths.");
144 Application::DeclarePrefixDir(ICINGA_PREFIX);
145 Application::DeclareSysconfDir(ICINGA_SYSCONFDIR);
146 Application::DeclareRunDir(ICINGA_RUNDIR);
147 Application::DeclareLocalStateDir(ICINGA_LOCALSTATEDIR);
148 Application::DeclarePkgDataDir(ICINGA_PKGDATADIR);
149 Application::DeclareIncludeConfDir(ICINGA_INCLUDECONFDIR);
154 Application::DeclareZonesDir(Application::GetSysconfDir() + "/icinga2/zones.d");
155 Application::DeclareRunAsUser(ICINGA_USER);
156 Application::DeclareRunAsGroup(ICINGA_GROUP);
158 Application::DeclareRLimitFiles(Application::GetDefaultRLimitFiles());
159 Application::DeclareRLimitProcesses(Application::GetDefaultRLimitProcesses());
160 Application::DeclareRLimitStack(Application::GetDefaultRLimitStack());
161 #endif /* __linux__ */
162 Application::DeclareConcurrency(boost::thread::hardware_concurrency());
164 ScriptGlobal::Set("AttachDebugger", false);
166 ScriptGlobal::Set("PlatformKernel", Utility::GetPlatformKernel());
167 ScriptGlobal::Set("PlatformKernelVersion", Utility::GetPlatformKernelVersion());
168 ScriptGlobal::Set("PlatformName", Utility::GetPlatformName());
169 ScriptGlobal::Set("PlatformVersion", Utility::GetPlatformVersion());
170 ScriptGlobal::Set("PlatformArchitecture", Utility::GetPlatformArchitecture());
172 ScriptGlobal::Set("BuildHostName", ICINGA_BUILD_HOST_NAME);
173 ScriptGlobal::Set("BuildCompilerName", ICINGA_BUILD_COMPILER_NAME);
174 ScriptGlobal::Set("BuildCompilerVersion", ICINGA_BUILD_COMPILER_VERSION);
176 String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";
178 if (Utility::PathExists(initconfig)) {
179 Expression *expression;
181 expression = ConfigCompiler::CompileFile(initconfig);
184 expression->Evaluate(frame);
185 } catch (const std::exception& ex) {
188 Log(LogCritical, "config", DiagnosticInformation(ex));
196 Application::SetResourceLimits();
198 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
199 Logger::SetConsoleLogSeverity(LogWarning);
201 Loader::LoadExtensionLibrary("cli");
203 po::options_description visibleDesc("Global options");
205 visibleDesc.add_options()
206 ("help,h", "show this help message")
207 ("version,V", "show version information")
209 ("color", "use VT100 color codes even when stdout is not a terminal")
211 ("define,D", po::value<std::vector<std::string> >(), "define a constant")
212 ("app,a", po::value<std::string>(), "application library name (default: icinga)")
213 ("library,l", po::value<std::vector<std::string> >(), "load a library")
214 ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
215 ("log-level,x", po::value<std::string>(), "specify the log level for the console log.\n"
216 "The valid value is either debug, notice, information (default), warning, or critical")
217 ("script-debugger,X", "whether to enable the script debugger");
219 po::options_description hiddenDesc("Hidden options");
221 hiddenDesc.add_options()
222 ("no-stack-rlimit", "used internally, do not specify manually")
223 ("arg", po::value<std::vector<std::string> >(), "positional argument");
225 po::positional_options_description positionalDesc;
226 positionalDesc.add("arg", -1);
229 CLICommand::Ptr command;
230 po::variables_map vm;
233 CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
234 vm, cmdname, command, autocomplete);
235 } catch (const std::exception& ex) {
236 Log(LogCritical, "icinga-app")
237 << "Error while parsing command-line options: " << ex.what();
242 char username[UNLEN + 1];
243 DWORD usernameLen = UNLEN + 1;
244 GetUserName(username, &usernameLen);
246 std::ifstream userFile;
247 userFile.open(Application::GetSysconfDir() + "/icinga2/user");
249 if (userFile && command && !Application::IsProcessElevated()) {
250 std::string userLine;
251 if (std::getline(userFile, userLine)) {
254 std::vector<std::string> strs;
255 boost::split(strs, userLine, boost::is_any_of("\\"));
257 if (username != strs[1] && command->GetImpersonationLevel() == ImpersonationLevel::ImpersonateIcinga
258 || command->GetImpersonationLevel() == ImpersonationLevel::ImpersonateRoot) {
259 TCHAR szPath[MAX_PATH];
261 if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath))) {
262 SHELLEXECUTEINFO sei = { sizeof(sei) };
263 sei.lpVerb = _T("runas");
264 sei.lpFile = "cmd.exe";
265 sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI;
268 std::stringstream parameters;
270 parameters << "/C " << "\"" << szPath << "\"" << " ";
272 for (int i = 1; i < argc; i++) {
275 parameters << argv[i];
278 parameters << " & SET exitcode=%errorlevel%";
279 parameters << " & pause";
280 parameters << " & EXIT /B %exitcode%";
282 std::string str = parameters.str();
283 LPCSTR cstr = str.c_str();
285 sei.lpParameters = cstr;
287 if (!ShellExecuteEx(&sei)) {
288 DWORD dwError = GetLastError();
289 if (dwError == ERROR_CANCELLED)
290 Application::Exit(0);
292 WaitForSingleObject(sei.hProcess, INFINITE);
295 GetExitCodeProcess(sei.hProcess, &exitCode);
297 CloseHandle(sei.hProcess);
299 Application::Exit(exitCode);
310 if (vm.count("color")) {
311 Console::SetType(std::cout, Console_VT100);
312 Console::SetType(std::cerr, Console_VT100);
316 if (vm.count("define")) {
317 for (const String& define : vm["define"].as<std::vector<std::string> >()) {
319 size_t pos = define.FindFirstOf('=');
320 if (pos != String::NPos) {
321 key = define.SubStr(0, pos);
322 value = define.SubStr(pos + 1);
327 ScriptGlobal::Set(key, value);
331 if (vm.count("script-debugger"))
332 Application::SetScriptDebuggerEnabled(true);
334 Application::DeclareStatePath(Application::GetLocalStateDir() + "/lib/icinga2/icinga2.state");
335 Application::DeclareModAttrPath(Application::GetLocalStateDir() + "/lib/icinga2/modified-attributes.conf");
336 Application::DeclareObjectsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.debug");
337 Application::DeclareVarsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.vars");
338 Application::DeclarePidPath(Application::GetRunDir() + "/icinga2/icinga2.pid");
340 ConfigCompiler::AddIncludeSearchDir(Application::GetIncludeConfDir());
342 if (!autocomplete && vm.count("include")) {
343 for (const String& includePath : vm["include"].as<std::vector<std::string> >()) {
344 ConfigCompiler::AddIncludeSearchDir(includePath);
349 Logger::SetConsoleLogSeverity(logLevel);
351 if (vm.count("log-level")) {
352 String severity = vm["log-level"].as<std::string>();
354 LogSeverity logLevel = LogInformation;
356 logLevel = Logger::StringToSeverity(severity);
357 } catch (std::exception&) {
358 /* Inform user and exit */
359 Log(LogCritical, "icinga-app", "Invalid log level set. Default is 'information'.");
363 Logger::SetConsoleLogSeverity(logLevel);
366 if (vm.count("library")) {
367 for (const String& libraryName : vm["library"].as<std::vector<std::string> >()) {
369 (void) Loader::LoadExtensionLibrary(libraryName);
370 } catch (const std::exception& ex) {
371 Log(LogCritical, "icinga-app")
372 << "Could not load library \"" << libraryName << "\": " << DiagnosticInformation(ex);
378 if (!command || vm.count("help") || vm.count("version")) {
382 appName = Utility::BaseName(Application::GetArgV()[0]);
383 } catch (const std::bad_alloc&) {
384 Log(LogCritical, "icinga-app", "Allocation failed.");
388 if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
389 appName = appName.SubStr(3, appName.GetLength() - 3);
391 std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
392 << ConsoleColorTag(vm.count("version") ? Console_ForegroundRed : Console_Normal)
393 << Application::GetAppVersion()
396 #endif /* I2_DEBUG */
397 << ConsoleColorTag(Console_Normal)
398 << ")" << std::endl << std::endl;
400 if ((!command || vm.count("help")) && !vm.count("version")) {
401 std::cout << "Usage:" << std::endl
402 << " " << Utility::BaseName(argv[0]) << " ";
404 if (cmdname.IsEmpty())
405 std::cout << "<command>";
407 std::cout << cmdname;
409 std::cout << " [<arguments>]" << std::endl;
412 std::cout << std::endl
413 << command->GetDescription() << std::endl;
417 if (vm.count("version")) {
418 std::cout << "Copyright (c) 2012-2017 Icinga Development Team (https://www.icinga.com/)" << std::endl
419 << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
420 << "This is free software: you are free to change and redistribute it." << std::endl
421 << "There is NO WARRANTY, to the extent permitted by law.";
424 std::cout << std::endl;
426 if (vm.count("version")) {
427 std::cout << std::endl;
429 Application::DisplayInfoMessage(std::cout, true);
435 if (!command || vm.count("help")) {
437 CLICommand::ShowCommands(argc, argv, NULL);
439 std::cout << visibleDesc << std::endl
440 << "Report bugs at <https://github.com/Icinga/icinga2>" << std::endl
441 << "Icinga home page: <https://www.icinga.com/>" << std::endl;
449 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
450 &GlobalArgumentCompletion, true, autoindex);
452 } else if (command) {
453 Logger::DisableTimestamp(true);
455 if (command->GetImpersonationLevel() == ImpersonateRoot) {
457 Log(LogCritical, "cli", "This command must be run as root.");
460 } else if (command && command->GetImpersonationLevel() == ImpersonateIcinga) {
461 String group = Application::GetRunAsGroup();
462 String user = Application::GetRunAsUser();
465 struct group *gr = getgrnam(group.CStr());
469 Log(LogCritical, "cli")
470 << "Invalid group specified: " << group;
473 Log(LogCritical, "cli")
474 << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
479 if (getgid() != gr->gr_gid) {
480 if (!vm.count("reload-internal") && setgroups(0, NULL) < 0) {
481 Log(LogCritical, "cli")
482 << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
483 Log(LogCritical, "cli")
484 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
488 if (setgid(gr->gr_gid) < 0) {
489 Log(LogCritical, "cli")
490 << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
496 struct passwd *pw = getpwnam(user.CStr());
500 Log(LogCritical, "cli")
501 << "Invalid user specified: " << user;
504 Log(LogCritical, "cli")
505 << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
510 // also activate the additional groups the configured user is member of
511 if (getuid() != pw->pw_uid) {
512 if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
513 Log(LogCritical, "cli")
514 << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
515 Log(LogCritical, "cli")
516 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
520 if (setuid(pw->pw_uid) < 0) {
521 Log(LogCritical, "cli")
522 << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
523 Log(LogCritical, "cli")
524 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
530 Process::InitializeSpawnHelper();
533 std::vector<std::string> args;
535 args = vm["arg"].as<std::vector<std::string> >();
537 if (static_cast<int>(args.size()) < command->GetMinArguments()) {
538 Log(LogCritical, "cli")
539 << "Too few arguments. Command needs at least " << command->GetMinArguments()
540 << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
544 if (command->GetMaxArguments() >= 0 && static_cast<int>(args.size()) > command->GetMaxArguments()) {
545 Log(LogCritical, "cli")
546 << "Too many arguments. At most " << command->GetMaxArguments()
547 << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
551 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
552 Logger::SetConsoleLogSeverity(LogWarning);
555 Loader::LoadExtensionLibrary(vm["app"].as<std::string>());
557 Loader::LoadExtensionLibrary("icinga");
559 Logger::SetConsoleLogSeverity(logLevel);
561 rc = command->Run(vm, args);
568 static int SetupService(bool install, int argc, char **argv)
570 SC_HANDLE schSCManager = OpenSCManager(
573 SC_MANAGER_ALL_ACCESS);
575 if (NULL == schSCManager) {
576 printf("OpenSCManager failed (%d)\n", GetLastError());
580 TCHAR szPath[MAX_PATH];
582 if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
583 printf("Cannot install service (%d)\n", GetLastError());
588 szArgs = Utility::EscapeShellArg(szPath) + " --scm";
590 std::string scmUser = "NT AUTHORITY\\NetworkService";
591 std::ifstream initf(Utility::GetIcingaDataPath() + "\\etc\\icinga2\\user");
593 std::getline(initf, scmUser);
597 for (int i = 0; i < argc; i++) {
598 if (!strcmp(argv[i], "--scm-user") && i + 1 < argc) {
599 scmUser = argv[i + 1];
602 szArgs += " " + Utility::EscapeShellArg(argv[i]);
605 SC_HANDLE schService = OpenService(schSCManager, "icinga2", SERVICE_ALL_ACCESS);
607 if (schService != NULL) {
608 SERVICE_STATUS status;
609 ControlService(schService, SERVICE_CONTROL_STOP, &status);
611 double start = Utility::GetTime();
612 while (status.dwCurrentState != SERVICE_STOPPED) {
613 double end = Utility::GetTime();
615 if (end - start > 30) {
616 printf("Could not stop the service.\n");
622 if (!QueryServiceStatus(schService, &status)) {
623 printf("QueryServiceStatus failed (%d)\n", GetLastError());
627 } else if (install) {
628 schService = CreateService(
633 SERVICE_WIN32_OWN_PROCESS,
634 SERVICE_DEMAND_START,
635 SERVICE_ERROR_NORMAL,
643 if (schService == NULL) {
644 printf("CreateService failed (%d)\n", GetLastError());
645 CloseServiceHandle(schSCManager);
649 printf("Service isn't installed.\n");
650 CloseServiceHandle(schSCManager);
655 if (!DeleteService(schService)) {
656 printf("DeleteService failed (%d)\n", GetLastError());
657 CloseServiceHandle(schService);
658 CloseServiceHandle(schSCManager);
662 printf("Service uninstalled successfully\n");
664 if (!ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
665 SERVICE_ERROR_NORMAL, szArgs.CStr(), NULL, NULL, NULL, scmUser.c_str(), NULL, NULL)) {
666 printf("ChangeServiceConfig failed (%d)\n", GetLastError());
667 CloseServiceHandle(schService);
668 CloseServiceHandle(schSCManager);
672 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
673 if(!ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription)) {
674 printf("ChangeServiceConfig2 failed (%d)\n", GetLastError());
675 CloseServiceHandle(schService);
676 CloseServiceHandle(schSCManager);
680 if (!StartService(schService, 0, NULL)) {
681 printf("StartService failed (%d)\n", GetLastError());
682 CloseServiceHandle(schService);
683 CloseServiceHandle(schSCManager);
687 printf("Service successfully installed for user '%s'\n", scmUser);
689 std::ofstream fuser(Utility::GetIcingaDataPath() + "\\etc\\icinga2\\user", std::ios::out | std::ios::trunc);
693 printf("Could not write user to %s\\etc\\icinga2\\user", Utility::GetIcingaDataPath());
697 CloseServiceHandle(schService);
698 CloseServiceHandle(schSCManager);
703 VOID ReportSvcStatus(DWORD dwCurrentState,
704 DWORD dwWin32ExitCode,
707 static DWORD dwCheckPoint = 1;
709 l_SvcStatus.dwCurrentState = dwCurrentState;
710 l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
711 l_SvcStatus.dwWaitHint = dwWaitHint;
713 if (dwCurrentState == SERVICE_START_PENDING)
714 l_SvcStatus.dwControlsAccepted = 0;
716 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
718 if ((dwCurrentState == SERVICE_RUNNING) ||
719 (dwCurrentState == SERVICE_STOPPED))
720 l_SvcStatus.dwCheckPoint = 0;
722 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
724 SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
727 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
729 if (dwCtrl == SERVICE_CONTROL_STOP) {
730 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
731 TerminateJobObject(l_Job, 0);
735 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
737 l_SvcStatusHandle = RegisterServiceCtrlHandler(
739 ServiceControlHandler);
741 l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
742 l_SvcStatus.dwServiceSpecificExitCode = 0;
744 ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
745 l_Job = CreateJobObject(NULL, NULL);
750 int uargc = Application::GetArgC();
751 char **uargv = Application::GetArgV();
753 args += Utility::EscapeShellArg(Application::GetExePath(uargv[0]));
755 for (int i = 2; i < uargc && uargv[i]; i++) {
759 args += Utility::EscapeShellArg(uargv[i]);
762 STARTUPINFO si = { sizeof(si) };
763 PROCESS_INFORMATION pi;
765 char *uargs = strdup(args.CStr());
767 BOOL res = CreateProcess(NULL, uargs, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
774 CloseHandle(pi.hThread);
776 AssignProcessToJobObject(l_Job, pi.hProcess);
778 if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_OBJECT_0)
783 if (!GetExitCodeProcess(pi.hProcess, &exitStatus))
790 TerminateJobObject(l_Job, 0);
794 ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
796 Application::Exit(0);
801 * Entry point for the Icinga application.
803 * @params argc Number of command line arguments.
804 * @params argv Command line arguments.
805 * @returns The application's exit status.
807 int main(int argc, char **argv)
810 if (!getenv("ICINGA2_KEEP_FDS")) {
812 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0) {
813 rlim_t maxfds = rl.rlim_max;
815 if (maxfds == RLIM_INFINITY)
818 for (rlim_t i = 3; i < maxfds; i++) {
823 std::cerr << "Closed FD " << i << " which we inherited from our parent process." << std::endl;
824 #endif /* I2_DEBUG */
830 /* must be called before using any other libbase functions */
831 Application::InitializeBase();
833 /* Set command-line arguments. */
834 Application::SetArgC(argc);
835 Application::SetArgV(argv);
838 if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
839 return SetupService(true, argc - 2, &argv[2]);
842 if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
843 return SetupService(false, argc - 2, &argv[2]);
846 if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
847 SERVICE_TABLE_ENTRY dispatchTable[] = {
848 { "icinga2", ServiceMain },
852 StartServiceCtrlDispatcher(dispatchTable);
853 Application::Exit(EXIT_FAILURE);
859 Application::Exit(rc);