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