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