]> granicus.if.org Git - icinga2/blob - icinga-app/icinga.cpp
Make order for deferred initializers deterministic
[icinga2] / icinga-app / icinga.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org)    *
4  *                                                                            *
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.                     *
9  *                                                                            *
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.                               *
14  *                                                                            *
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  ******************************************************************************/
19
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 "config.h"
35 #include <boost/program_options.hpp>
36 #include <boost/tuple/tuple.hpp>
37 #include <boost/foreach.hpp>
38
39 #ifndef _WIN32
40 #       include <sys/types.h>
41 #       include <pwd.h>
42 #       include <grp.h>
43 #endif /* _WIN32 */
44
45 using namespace icinga;
46 namespace po = boost::program_options;
47
48 #ifdef _WIN32
49 SERVICE_STATUS l_SvcStatus;
50 SERVICE_STATUS_HANDLE l_SvcStatusHandle;
51 #endif /* _WIN32 */
52
53 static std::vector<String> GetLogLevelCompletionSuggestions(const String& arg)
54 {
55         std::vector<String> result;
56         
57         String debugLevel = "debug";
58         if (debugLevel.Find(arg) == 0)
59                 result.push_back(debugLevel);
60
61         String noticeLevel = "notice";
62         if (noticeLevel.Find(arg) == 0)
63                 result.push_back(noticeLevel);
64
65         String informationLevel = "information";
66         if (informationLevel.Find(arg) == 0)
67                 result.push_back(informationLevel);
68
69         String warningLevel = "warning";
70         if (warningLevel.Find(arg) == 0)
71                 result.push_back(warningLevel);
72
73         String criticalLevel = "critical";
74         if (criticalLevel.Find(arg) == 0)
75                 result.push_back(criticalLevel);
76
77         return result;
78 }
79
80 static std::vector<String> GlobalArgumentCompletion(const String& argument, const String& word)
81 {
82         if (argument == "include")
83                 return GetBashCompletionSuggestions("directory", word);
84         else if (argument == "log-level")
85                 return GetLogLevelCompletionSuggestions(word);
86         else
87                 return std::vector<String>();
88 }
89
90 int Main(void)
91 {
92         int argc = Application::GetArgC();
93         char **argv = Application::GetArgV();
94
95         bool autocomplete = false;
96         int autoindex = 0;
97
98         if (argc >= 4 && strcmp(argv[1], "--autocomplete") == 0) {
99                 autocomplete = true;
100
101                 try {
102                         autoindex = Convert::ToLong(argv[2]);
103                 } catch (const std::invalid_argument& ex) {
104                         Log(LogCritical, "icinga-app")
105                             << "Invalid index for --autocomplete: " << argv[2];
106                         return EXIT_FAILURE;
107                 }
108
109                 argc -= 3;
110                 argv += 3;
111         }
112
113         Application::SetStartTime(Utility::GetTime());
114
115         if (!autocomplete)
116                 Application::SetResourceLimits();
117
118         /* Set thread title. */
119         Utility::SetThreadName("Main Thread", false);
120
121         /* Install exception handlers to make debugging easier. */
122         Application::InstallExceptionHandlers();
123
124 #ifdef _WIN32
125         bool builtinPaths = true;
126
127         HKEY hKey;
128         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Icinga Development Team\\ICINGA2", 0,
129             KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
130                 BYTE pvData[MAX_PATH];
131                 DWORD cbData = sizeof(pvData)-1;
132                 DWORD lType;
133                 if (RegQueryValueEx(hKey, NULL, NULL, &lType, pvData, &cbData) == ERROR_SUCCESS && lType == REG_SZ) {
134                         pvData[cbData] = '\0';
135
136                         String prefix = (char *)pvData;
137                         Application::DeclarePrefixDir(prefix);
138                         Application::DeclareSysconfDir(prefix + "\\etc");
139                         Application::DeclareRunDir(prefix + "\\var\\run");
140                         Application::DeclareLocalStateDir(prefix + "\\var");
141                         Application::DeclarePkgDataDir(prefix + "\\share\\icinga2");
142                         Application::DeclareIncludeConfDir(prefix + "\\share\\icinga2\\include");
143
144                         builtinPaths = false;
145                 }
146
147                 RegCloseKey(hKey);
148         }
149
150         if (builtinPaths) {
151                 Log(LogWarning, "icinga-app", "Registry key could not be read. Falling back to built-in paths.");
152
153 #endif /* _WIN32 */
154                 Application::DeclarePrefixDir(ICINGA_PREFIX);
155                 Application::DeclareSysconfDir(ICINGA_SYSCONFDIR);
156                 Application::DeclareRunDir(ICINGA_RUNDIR);
157                 Application::DeclareLocalStateDir(ICINGA_LOCALSTATEDIR);
158                 Application::DeclarePkgDataDir(ICINGA_PKGDATADIR);
159                 Application::DeclareIncludeConfDir(ICINGA_INCLUDECONFDIR);
160 #ifdef _WIN32
161         }
162 #endif /* _WIN32 */
163
164         Application::DeclareZonesDir(Application::GetSysconfDir() + "/icinga2/zones.d");
165         Application::DeclareRunAsUser(ICINGA_USER);
166         Application::DeclareRunAsGroup(ICINGA_GROUP);
167         Application::DeclareConcurrency(boost::thread::hardware_concurrency());
168
169         if (!ScriptGlobal::Exists("UseVfork"))
170 #ifdef __APPLE__
171                 ScriptGlobal::Set("UseVfork", false);
172 #else /* __APPLE__ */
173                 ScriptGlobal::Set("UseVfork", true);
174 #endif /* __APPLE__ */
175
176         LogSeverity logLevel = Logger::GetConsoleLogSeverity();
177         Logger::SetConsoleLogSeverity(LogWarning);
178
179         Loader::LoadExtensionLibrary("cli");
180
181         po::options_description visibleDesc("Global options");
182
183         visibleDesc.add_options()
184                 ("help,h", "show this help message")
185                 ("version,V", "show version information")
186 #ifndef _WIN32
187                 ("color", "use VT100 color codes even when stdout is not a terminal")
188 #endif /* _WIN32 */
189                 ("define,D", po::value<std::vector<std::string> >(), "define a constant")
190                 ("app,a", po::value<std::string>(), "application library name (default: icinga)")
191                 ("library,l", po::value<std::vector<std::string> >(), "load a library")
192                 ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
193                 ("log-level,x", po::value<std::string>(), "specify the log level for the console log");
194
195         po::options_description hiddenDesc("Hidden options");
196
197         hiddenDesc.add_options()
198 #ifndef _WIN32
199                 ("no-stack-rlimit", "used internally, do not specify manually")
200 #else /* _WIN32 */
201                 ("no-stack-rlimit", "used internally, do not specify manually")
202 #endif /* _WIN32 */
203                 ("arg", po::value<std::vector<std::string> >(), "positional argument");
204
205         po::positional_options_description positionalDesc;
206         positionalDesc.add("arg", -1);
207
208         String cmdname;
209         CLICommand::Ptr command;
210         po::variables_map vm;
211
212         try {
213                 CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
214                     vm, cmdname, command, autocomplete);
215         } catch (const std::exception& ex) {
216                 Log(LogCritical, "icinga-app")
217                     << "Error while parsing command-line options: " << ex.what();
218                 return EXIT_FAILURE;
219         }
220
221         String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";
222
223         if (Utility::PathExists(initconfig)) {
224                 Expression *expression;
225                 try {
226                         expression = ConfigCompiler::CompileFile(initconfig);
227
228                         ScriptFrame frame;
229                         expression->Evaluate(frame);
230                 } catch (const std::exception& ex) {
231                         delete expression;
232
233                         Log(LogCritical, "config", DiagnosticInformation(ex));
234                         return EXIT_FAILURE;
235                 }
236
237                 delete expression;
238         }
239
240 #ifndef _WIN32
241         if (vm.count("color")) {
242                 Console::SetType(std::cout, Console_VT100);
243                 Console::SetType(std::cerr, Console_VT100);
244         }
245 #endif /* _WIN32 */
246
247         if (vm.count("define")) {
248                 BOOST_FOREACH(const String& define, vm["define"].as<std::vector<std::string> >()) {
249                         String key, value;
250                         size_t pos = define.FindFirstOf('=');
251                         if (pos != String::NPos) {
252                                 key = define.SubStr(0, pos);
253                                 value = define.SubStr(pos + 1);
254                         } else {
255                                 key = define;
256                                 value = "1";
257                         }
258                         ScriptGlobal::Set(key, value);
259                 }
260         }
261
262         Application::DeclareStatePath(Application::GetLocalStateDir() + "/lib/icinga2/icinga2.state");
263         Application::DeclareObjectsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.debug");
264         Application::DeclareVarsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.vars");
265         Application::DeclarePidPath(Application::GetRunDir() + "/icinga2/icinga2.pid");
266
267         ConfigCompiler::AddIncludeSearchDir(Application::GetIncludeConfDir());
268
269         if (!autocomplete && vm.count("include")) {
270                 BOOST_FOREACH(const String& includePath, vm["include"].as<std::vector<std::string> >()) {
271                         ConfigCompiler::AddIncludeSearchDir(includePath);
272                 }
273         }
274
275         if (!autocomplete) {
276                 Logger::SetConsoleLogSeverity(logLevel);
277
278                 if (vm.count("log-level")) {
279                         String severity = vm["log-level"].as<std::string>();
280
281                         LogSeverity logLevel = LogInformation;
282                         try {
283                                 logLevel = Logger::StringToSeverity(severity);
284                         } catch (std::exception&) {
285                                 /* Inform user and exit */
286                                 Log(LogCritical, "icinga-app", "Invalid log level set. Default is 'information'.");
287                                 return EXIT_FAILURE;
288                         }
289
290                         Logger::SetConsoleLogSeverity(logLevel);
291                 }
292
293                 if (vm.count("library")) {
294                         BOOST_FOREACH(const String& libraryName, vm["library"].as<std::vector<std::string> >()) {
295                                 try {
296                                         (void) Loader::LoadExtensionLibrary(libraryName);
297                                 } catch (const std::exception& ex) {
298                                         Log(LogCritical, "icinga-app")
299                                             <<  "Could not load library \"" << libraryName << "\": " << DiagnosticInformation(ex);
300                                         return EXIT_FAILURE;
301                                 }
302                         }
303                 } 
304
305                 if (!command || vm.count("help") || vm.count("version")) {
306                         String appName;
307
308                         try {
309                                 appName = Utility::BaseName(Application::GetArgV()[0]);
310                         } catch (const std::bad_alloc&) {
311                                 Log(LogCritical, "icinga-app", "Allocation failed.");
312                                 return EXIT_FAILURE;
313                         }
314
315                         if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
316                                 appName = appName.SubStr(3, appName.GetLength() - 3);
317
318                         std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
319                             << ConsoleColorTag(vm.count("version") ? Console_ForegroundRed : Console_Normal)
320                             << Application::GetVersion()
321 #ifdef I2_DEBUG
322                             << "; debug"
323 #endif /* I2_DEBUG */
324                             << ConsoleColorTag(Console_Normal)
325                             << ")" << std::endl << std::endl;
326
327                         if ((!command || vm.count("help")) && !vm.count("version")) {
328                                 std::cout << "Usage:" << std::endl
329                                     << "  " << argv[0] << " ";
330
331                                 if (cmdname.IsEmpty())
332                                         std::cout << "<command>";
333                                 else
334                                         std::cout << cmdname;
335
336                                 std::cout << " [<arguments>]" << std::endl;
337
338                                 if (command) {
339                                         std::cout << std::endl
340                                                   << command->GetDescription() << std::endl;
341                                 }
342                         }
343
344                         if (vm.count("version")) {
345                                 std::cout << "Copyright (c) 2012-2015 Icinga Development Team (https://www.icinga.org)" << std::endl
346                                         << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
347                                         << "This is free software: you are free to change and redistribute it." << std::endl
348                                         << "There is NO WARRANTY, to the extent permitted by law.";
349                         }
350
351                         std::cout << std::endl;
352
353                         if (vm.count("version")) {
354                                 std::cout << std::endl;
355
356                                 Application::DisplayInfoMessage(std::cout, true);
357
358                                 return EXIT_SUCCESS;
359                         }
360                 }
361
362                 if (!command || vm.count("help")) {
363                         if (!command)
364                                 CLICommand::ShowCommands(argc, argv, NULL);
365
366                         std::cout << visibleDesc << std::endl
367                                 << "Report bugs at <https://dev.icinga.org/>" << std::endl
368                                 << "Icinga home page: <https://www.icinga.org/>" << std::endl;
369                         return EXIT_SUCCESS;
370                 }
371         }
372
373         int rc = 1;
374
375         if (autocomplete) {
376                 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
377                     &GlobalArgumentCompletion, true, autoindex);
378                 rc = 0;
379         } else if (command) {
380                 Logger::DisableTimestamp(true);
381 #ifndef _WIN32
382                 if (command->GetImpersonationLevel() == ImpersonateRoot) {
383                         if (getuid() != 0) {
384                                 Log(LogCritical, "cli", "This command must be run as root.");
385                                 return 0;
386                         }
387                 } else if (command && command->GetImpersonationLevel() == ImpersonateIcinga) {
388                         String group = Application::GetRunAsGroup();
389                         String user = Application::GetRunAsUser();
390         
391                         errno = 0;
392                         struct group *gr = getgrnam(group.CStr());
393         
394                         if (!gr) {
395                                 if (errno == 0) {
396                                         Log(LogCritical, "cli")
397                                             << "Invalid group specified: " << group;
398                                         return EXIT_FAILURE;
399                                 } else {
400                                         Log(LogCritical, "cli")
401                                             << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
402                                         return EXIT_FAILURE;
403                                 }
404                         }
405         
406                         if (getgid() != gr->gr_gid) {
407                                 if (!vm.count("reload-internal") && setgroups(0, NULL) < 0) {
408                                         Log(LogCritical, "cli")
409                                             << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
410                                         Log(LogCritical, "cli")
411                                             << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
412                                         return EXIT_FAILURE;
413                                 }
414         
415                                 if (setgid(gr->gr_gid) < 0) {
416                                         Log(LogCritical, "cli")
417                                             << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
418                                         return EXIT_FAILURE;
419                                 }
420                         }
421         
422                         errno = 0;
423                         struct passwd *pw = getpwnam(user.CStr());
424         
425                         if (!pw) {
426                                 if (errno == 0) {
427                                         Log(LogCritical, "cli")
428                                             << "Invalid user specified: " << user;
429                                         return EXIT_FAILURE;
430                                 } else {
431                                         Log(LogCritical, "cli")
432                                             << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
433                                         return EXIT_FAILURE;
434                                 }
435                         }
436         
437                         // also activate the additional groups the configured user is member of
438                         if (getuid() != pw->pw_uid) {
439                                 if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
440                                         Log(LogCritical, "cli")
441                                             << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
442                                         Log(LogCritical, "cli")
443                                             << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
444                                         return EXIT_FAILURE;
445                                 }
446         
447                                 if (setuid(pw->pw_uid) < 0) {
448                                         Log(LogCritical, "cli")
449                                             << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
450                                         Log(LogCritical, "cli")
451                                             << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
452                                         return EXIT_FAILURE;
453                                 }
454                         }
455                 }
456 #endif /* _WIN32 */
457
458                 std::vector<std::string> args;
459                 if (vm.count("arg"))
460                         args = vm["arg"].as<std::vector<std::string> >();
461
462                 if (args.size() < command->GetMinArguments()) {
463                         Log(LogCritical, "cli")
464                             << "Too few arguments. Command needs at least " << command->GetMinArguments()
465                             << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
466                         return EXIT_FAILURE;
467                 }
468
469                 if (command->GetMaxArguments() >= 0 && args.size() > command->GetMaxArguments()) {
470                         Log(LogCritical, "cli")
471                             << "Too many arguments. At most " << command->GetMaxArguments()
472                             << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
473                         return EXIT_FAILURE;
474                 }
475
476                 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
477                 Logger::SetConsoleLogSeverity(LogWarning);
478
479                 if (vm.count("app"))
480                         Loader::LoadExtensionLibrary(vm["app"].as<std::string>());
481                 else
482                         Loader::LoadExtensionLibrary("icinga");
483
484                 Logger::SetConsoleLogSeverity(logLevel);
485
486                 rc = command->Run(vm, args);
487         }
488
489         return rc;
490 }
491
492 #ifdef _WIN32
493 static int SetupService(bool install, int argc, char **argv)
494 {
495         SC_HANDLE schSCManager = OpenSCManager(
496                 NULL,
497                 NULL,
498                 SC_MANAGER_ALL_ACCESS);
499
500         if (NULL == schSCManager) {
501                 printf("OpenSCManager failed (%d)\n", GetLastError());
502                 return 1;
503         }
504
505         TCHAR szPath[MAX_PATH];
506
507         if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
508                 printf("Cannot install service (%d)\n", GetLastError());
509                 return 1;
510         }
511
512         String szArgs;
513         szArgs = Utility::EscapeShellArg(szPath) + " --scm";
514
515         for (int i = 0; i < argc; i++)
516                 szArgs += " " + Utility::EscapeShellArg(argv[i]);
517
518         SC_HANDLE schService = OpenService(schSCManager, "icinga2", DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
519
520         if (schService != NULL) {
521                 SERVICE_STATUS status;
522                 ControlService(schService, SERVICE_CONTROL_STOP, &status);
523
524                 double start = Utility::GetTime();
525                 while (status.dwCurrentState != SERVICE_STOPPED) {
526                         double end = Utility::GetTime();
527
528                         if (end - start > 30) {
529                                 printf("Could not stop the service.\n");
530                                 break;
531                         }
532
533                         Utility::Sleep(5);
534
535                         if (!QueryServiceStatus(schService, &status)) {
536                                 printf("QueryServiceStatus failed (%d)\n", GetLastError());
537                                 return 1;
538                         }
539                 }
540
541                 if (!DeleteService(schService)) {
542                         printf("DeleteService failed (%d)\n", GetLastError());
543                         CloseServiceHandle(schService);
544                         CloseServiceHandle(schSCManager);
545                         return 1;
546                 }
547
548                 if (!install)
549                         printf("Service uninstalled successfully\n");
550
551                 CloseServiceHandle(schService);
552         }
553
554         if (install) {
555                 schService = CreateService(
556                         schSCManager,
557                         "icinga2",
558                         "Icinga 2",
559                         SERVICE_ALL_ACCESS,
560                         SERVICE_WIN32_OWN_PROCESS,
561                         SERVICE_DEMAND_START,
562                         SERVICE_ERROR_NORMAL,
563                         szArgs.CStr(),
564                         NULL,
565                         NULL,
566                         NULL,
567                         "NT AUTHORITY\\NetworkService",
568                         NULL);
569
570                 if (schService == NULL) {
571                         printf("CreateService failed (%d)\n", GetLastError());
572                         CloseServiceHandle(schSCManager);
573                         return 1;
574                 } else
575                         printf("Service installed successfully\n");
576
577                 ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
578                     SERVICE_ERROR_NORMAL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
579
580                 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
581                 ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription);
582
583                 if (!StartService(schService, 0, NULL)) {
584                         printf("StartService failed (%d)\n", GetLastError());
585                         CloseServiceHandle(schService);
586                         CloseServiceHandle(schSCManager);
587                         return 1;
588                 }
589
590                 CloseServiceHandle(schService);
591         }
592
593         CloseServiceHandle(schSCManager);
594
595         return 0;
596 }
597
598 VOID ReportSvcStatus(DWORD dwCurrentState,
599         DWORD dwWin32ExitCode,
600         DWORD dwWaitHint)
601 {
602         static DWORD dwCheckPoint = 1;
603
604         l_SvcStatus.dwCurrentState = dwCurrentState;
605         l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
606         l_SvcStatus.dwWaitHint = dwWaitHint;
607
608         if (dwCurrentState == SERVICE_START_PENDING)
609                 l_SvcStatus.dwControlsAccepted = 0;
610         else
611                 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
612
613         if ((dwCurrentState == SERVICE_RUNNING) ||
614             (dwCurrentState == SERVICE_STOPPED))
615                 l_SvcStatus.dwCheckPoint = 0;
616         else
617                 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
618
619         SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
620 }
621
622 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
623 {
624         if (dwCtrl == SERVICE_CONTROL_STOP) {
625                 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
626                 Application::RequestShutdown();
627         }
628 }
629
630 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
631 {
632         l_SvcStatusHandle = RegisterServiceCtrlHandler(
633                 "icinga2",
634                 ServiceControlHandler);
635
636         l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
637         l_SvcStatus.dwServiceSpecificExitCode = 0;
638
639         ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
640
641         int rc = Main();
642
643         ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, rc);
644
645         Application::Exit(rc);
646 }
647 #endif /* _WIN32 */
648
649 /**
650 * Entry point for the Icinga application.
651 *
652 * @params argc Number of command line arguments.
653 * @params argv Command line arguments.
654 * @returns The application's exit status.
655 */
656 int main(int argc, char **argv)
657 {
658 #ifndef _WIN32
659         rlimit rl;
660         if (getrlimit(RLIMIT_NOFILE, &rl) >= 0) {
661                 rlim_t maxfds = rl.rlim_max;
662
663                 if (maxfds == RLIM_INFINITY)
664                         maxfds = 65536;
665
666                 for (rlim_t i = 3; i < maxfds; i++) {
667                         int rc = close(i);
668
669 #ifdef I2_DEBUG
670                         if (rc >= 0)
671                                 std::cerr << "Closed FD " << i << " which we inherited from our parent process." << std::endl;
672 #endif /* I2_DEBUG */
673                 }
674         }
675 #endif /* _WIN32 */
676
677         /* must be called before using any other libbase functions */
678         Application::InitializeBase();
679
680         /* Set command-line arguments. */
681         Application::SetArgC(argc);
682         Application::SetArgV(argv);
683
684 #ifdef _WIN32
685         if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
686                 return SetupService(true, argc - 2, &argv[2]);
687         }
688
689         if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
690                 return SetupService(false, argc - 2, &argv[2]);
691         }
692
693         if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
694                 SERVICE_TABLE_ENTRY dispatchTable[] = {
695                         { "icinga2", ServiceMain },
696                         { NULL, NULL }
697                 };
698
699                 StartServiceCtrlDispatcher(dispatchTable);
700                 Application::Exit(EXIT_FAILURE);
701         }
702 #endif /* _WIN32 */
703
704         int rc = Main();
705
706         Application::Exit(rc);
707 }