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