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