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