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