]> granicus.if.org Git - icinga2/blob - icinga-app/icinga.cpp
DB IDO: Do not deactivate objects during application reload/restart
[icinga2] / icinga-app / icinga.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2018 Icinga Development Team (https://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 "config/expression.hpp"
25 #include "base/application.hpp"
26 #include "base/configuration.hpp"
27 #include "base/logger.hpp"
28 #include "base/timer.hpp"
29 #include "base/utility.hpp"
30 #include "base/loader.hpp"
31 #include "base/exception.hpp"
32 #include "base/convert.hpp"
33 #include "base/scriptglobal.hpp"
34 #include "base/context.hpp"
35 #include "base/console.hpp"
36 #include "base/process.hpp"
37 #include "config.h"
38 #include <boost/program_options.hpp>
39 #include <boost/algorithm/string/split.hpp>
40 #include <thread>
41
42 #ifndef _WIN32
43 #       include <sys/types.h>
44 #       include <pwd.h>
45 #       include <grp.h>
46 #else
47 #       include <windows.h>
48 #       include <Lmcons.h>
49 #       include <Shellapi.h>
50 #       include <tchar.h>
51 #endif /* _WIN32 */
52
53 using namespace icinga;
54 namespace po = boost::program_options;
55
56 #ifdef _WIN32
57 static SERVICE_STATUS l_SvcStatus;
58 static SERVICE_STATUS_HANDLE l_SvcStatusHandle;
59 static HANDLE l_Job;
60 #endif /* _WIN32 */
61
62 static std::vector<String> GetLogLevelCompletionSuggestions(const String& arg)
63 {
64         std::vector<String> result;
65
66         String debugLevel = "debug";
67         if (debugLevel.Find(arg) == 0)
68                 result.push_back(debugLevel);
69
70         String noticeLevel = "notice";
71         if (noticeLevel.Find(arg) == 0)
72                 result.push_back(noticeLevel);
73
74         String informationLevel = "information";
75         if (informationLevel.Find(arg) == 0)
76                 result.push_back(informationLevel);
77
78         String warningLevel = "warning";
79         if (warningLevel.Find(arg) == 0)
80                 result.push_back(warningLevel);
81
82         String criticalLevel = "critical";
83         if (criticalLevel.Find(arg) == 0)
84                 result.push_back(criticalLevel);
85
86         return result;
87 }
88
89 static std::vector<String> GlobalArgumentCompletion(const String& argument, const String& word)
90 {
91         if (argument == "include")
92                 return GetBashCompletionSuggestions("directory", word);
93         else if (argument == "log-level")
94                 return GetLogLevelCompletionSuggestions(word);
95         else
96                 return std::vector<String>();
97 }
98
99 static void HandleLegacyDefines()
100 {
101 #ifdef _WIN32
102         String dataPrefix = Utility::GetIcingaDataPath();
103 #endif /* _WIN32 */
104
105         Value localStateDir = Configuration::LocalStateDir;
106
107         if (!localStateDir.IsEmpty()) {
108                 Log(LogWarning, "icinga-app")
109                         << "Please do not set the deprecated 'LocalStateDir' constant,"
110                         << " use the 'DataDir', 'LogDir', 'CacheDir' and 'SpoolDir' constants instead!"
111                         << " For compatibility reasons, these are now set based on the 'LocalStateDir' constant.";
112
113 #ifdef _WIN32
114                 Configuration::DataDir = localStateDir + "\\lib\\icinga2";
115                 Configuration::LogDir = localStateDir + "\\log\\icinga2";
116                 Configuration::CacheDir = localStateDir + "\\cache\\icinga2";
117                 Configuration::SpoolDir = localStateDir + "\\spool\\icinga2";
118         } else {
119                 Configuration::LocalStateDir = dataPrefix + "\\var";
120 #else /* _WIN32 */
121                 Configuration::DataDir = localStateDir + "/lib/icinga2";
122                 Configuration::LogDir = localStateDir + "/log/icinga2";
123                 Configuration::CacheDir = localStateDir + "/cache/icinga2";
124                 Configuration::SpoolDir = localStateDir + "/spool/icinga2";
125         } else {
126                 Configuration::LocalStateDir = ICINGA_LOCALSTATEDIR;
127 #endif /* _WIN32 */
128         }
129
130         Value sysconfDir = Configuration::SysconfDir;
131         if (!sysconfDir.IsEmpty()) {
132                 Log(LogWarning, "icinga-app")
133                         << "Please do not set the deprecated 'Sysconfdir' constant, use the 'ConfigDir' constant instead! For compatibility reasons, their value is set based on the 'SysconfDir' constant.";
134
135 #ifdef _WIN32
136                 Configuration::ConfigDir = sysconfDir + "\\icinga2";
137         } else {
138                 Configuration::SysconfDir = dataPrefix + "\\etc";
139 #else /* _WIN32 */
140                 Configuration::ConfigDir = sysconfDir + "/icinga2";
141         } else {
142                 Configuration::SysconfDir = ICINGA_SYSCONFDIR;
143 #endif /* _WIN32 */
144         }
145
146         Value runDir = Configuration::RunDir;
147         if (!runDir.IsEmpty()) {
148                 Log(LogWarning, "icinga-app")
149                         << "Please do not set the deprecated 'RunDir' constant, use the 'InitRunDir' constant instead! For compatibility reasons, their value is set based on the 'RunDir' constant.";
150
151 #ifdef _WIN32
152                 Configuration::InitRunDir = runDir + "\\icinga2";
153         } else {
154                 Configuration::RunDir = dataPrefix + "\\var\\run";
155 #else /* _WIN32 */
156                 Configuration::InitRunDir = runDir + "/icinga2";
157         } else {
158                 Configuration::RunDir = ICINGA_RUNDIR;
159 #endif /* _WIN32 */
160         }
161 }
162
163 static int Main()
164 {
165         int argc = Application::GetArgC();
166         char **argv = Application::GetArgV();
167
168         bool autocomplete = false;
169         int autoindex = 0;
170
171         if (argc >= 4 && strcmp(argv[1], "--autocomplete") == 0) {
172                 autocomplete = true;
173
174                 try {
175                         autoindex = Convert::ToLong(argv[2]);
176                 } catch (const std::invalid_argument&) {
177                         Log(LogCritical, "icinga-app")
178                                 << "Invalid index for --autocomplete: " << argv[2];
179                         return EXIT_FAILURE;
180                 }
181
182                 argc -= 3;
183                 argv += 3;
184         }
185
186         Application::SetStartTime(Utility::GetTime());
187
188         /* Set thread title. */
189         Utility::SetThreadName("Main Thread", false);
190
191         /* Install exception handlers to make debugging easier. */
192         Application::InstallExceptionHandlers();
193
194 #ifdef _WIN32
195         bool builtinPaths = true;
196
197         /* Programm install location, C:/Program Files/Icinga2 */
198         String binaryPrefix = Utility::GetIcingaInstallPath();
199         /* Returns the datapath for daemons, %PROGRAMDATA%/icinga2 */
200         String dataPrefix = Utility::GetIcingaDataPath();
201
202         if (!binaryPrefix.IsEmpty() && !dataPrefix.IsEmpty()) {
203                 Configuration::ProgramData = dataPrefix;
204
205                 Configuration::ConfigDir = dataPrefix + "\\etc\\icinga2";
206
207                 Configuration::DataDir =  dataPrefix + "\\var\\lib\\icinga2";
208                 Configuration::LogDir = dataPrefix + "\\var\\log\\icinga2";
209                 Configuration::CacheDir = dataPrefix + "\\var\\cache\\icinga2";
210                 Configuration::SpoolDir = dataPrefix + "\\var\\spool\\icinga2";
211
212                 Configuration::PrefixDir = binaryPrefix;
213
214                 /* Internal constants. */
215                 Configuration::PkgDataDir = binaryPrefix + "\\share\\icinga2";
216                 Configuration::IncludeConfDir = binaryPrefix + "\\share\\icinga2\\include";
217
218                 Configuration::InitRunDir = dataPrefix + "\\var\\run\\icinga2";
219         } else {
220                 Log(LogWarning, "icinga-app", "Registry key could not be read. Falling back to built-in paths.");
221
222 #endif /* _WIN32 */
223                 Configuration::ConfigDir = ICINGA_CONFIGDIR;
224
225                 Configuration::DataDir = ICINGA_DATADIR;
226                 Configuration::LogDir = ICINGA_LOGDIR;
227                 Configuration::CacheDir = ICINGA_CACHEDIR;
228                 Configuration::SpoolDir = ICINGA_SPOOLDIR;
229
230                 Configuration::PrefixDir = ICINGA_PREFIX;
231
232                 /* Internal constants. */
233                 Configuration::PkgDataDir = ICINGA_PKGDATADIR;
234                 Configuration::IncludeConfDir = ICINGA_INCLUDECONFDIR;
235
236                 Configuration::InitRunDir = ICINGA_INITRUNDIR;
237
238 #ifdef _WIN32
239         }
240 #endif /* _WIN32 */
241
242         Configuration::ZonesDir = Configuration::ConfigDir + "/zones.d";
243
244         String icingaUser = Utility::GetFromEnvironment("ICINGA2_USER");
245         if (icingaUser.IsEmpty())
246                 icingaUser = ICINGA_USER;
247
248         String icingaGroup = Utility::GetFromEnvironment("ICINGA2_GROUP");
249         if (icingaGroup.IsEmpty())
250                 icingaGroup = ICINGA_GROUP;
251
252         Configuration::RunAsUser = icingaUser;
253         Configuration::RunAsGroup = icingaGroup;
254
255         if (!autocomplete) {
256 #ifdef RLIMIT_NOFILE
257                 String rLimitFiles = Utility::GetFromEnvironment("ICINGA2_RLIMIT_FILES");
258                 if (rLimitFiles.IsEmpty())
259                         Configuration::RLimitFiles = Application::GetDefaultRLimitFiles();
260                 else {
261                         try {
262                                 Configuration::RLimitFiles = Convert::ToLong(rLimitFiles);
263                         } catch (const std::invalid_argument& ex) {
264                                 std::cout
265                                         << "Error setting \"ICINGA2_RLIMIT_FILES\": " << ex.what() << '\n';
266                                 return EXIT_FAILURE;
267                         }
268                 }
269 #endif /* RLIMIT_NOFILE */
270
271 #ifdef RLIMIT_NPROC
272                 String rLimitProcesses = Utility::GetFromEnvironment("ICINGA2_RLIMIT_PROCESSES");
273                 if (rLimitProcesses.IsEmpty())
274                         Configuration::RLimitProcesses = Application::GetDefaultRLimitProcesses();
275                 else {
276                         try {
277                                 Configuration::RLimitProcesses = Convert::ToLong(rLimitProcesses);
278                         } catch (const std::invalid_argument& ex) {
279                                 std::cout
280                                         << "Error setting \"ICINGA2_RLIMIT_PROCESSES\": " << ex.what() << '\n';
281                                 return EXIT_FAILURE;
282                         }
283                 }
284 #endif /* RLIMIT_NPROC */
285
286 #ifdef RLIMIT_STACK
287                 String rLimitStack = Utility::GetFromEnvironment("ICINGA2_RLIMIT_STACK");
288                 if (rLimitStack.IsEmpty())
289                         Configuration::RLimitStack = Application::GetDefaultRLimitStack();
290                 else {
291                         try {
292                                 Configuration::RLimitStack = Convert::ToLong(rLimitStack);
293                         } catch (const std::invalid_argument& ex) {
294                                 std::cout
295                                         << "Error setting \"ICINGA2_RLIMIT_STACK\": " << ex.what() << '\n';
296                                 return EXIT_FAILURE;
297                         }
298                 }
299 #endif /* RLIMIT_STACK */
300         }
301
302         ScriptGlobal::Set("MaxConcurrentChecks", Application::GetDefaultMaxConcurrentChecks());
303
304         ScriptGlobal::Set("System.PlatformKernel", Utility::GetPlatformKernel(), true);
305         ScriptGlobal::Set("System.PlatformKernelVersion", Utility::GetPlatformKernelVersion(), true);
306         ScriptGlobal::Set("System.PlatformName", Utility::GetPlatformName(), true);
307         ScriptGlobal::Set("System.PlatformVersion", Utility::GetPlatformVersion(), true);
308         ScriptGlobal::Set("System.PlatformArchitecture", Utility::GetPlatformArchitecture(), true);
309
310         ScriptGlobal::Set("System.BuildHostName", ICINGA_BUILD_HOST_NAME, true);
311         ScriptGlobal::Set("System.BuildCompilerName", ICINGA_BUILD_COMPILER_NAME, true);
312         ScriptGlobal::Set("System.BuildCompilerVersion", ICINGA_BUILD_COMPILER_VERSION, true);
313
314         if (!autocomplete)
315                 Application::SetResourceLimits();
316
317         LogSeverity logLevel = Logger::GetConsoleLogSeverity();
318         Logger::SetConsoleLogSeverity(LogWarning);
319
320         po::options_description visibleDesc("Global options");
321
322         visibleDesc.add_options()
323                 ("help,h", "show this help message")
324                 ("version,V", "show version information")
325 #ifndef _WIN32
326                 ("color", "use VT100 color codes even when stdout is not a terminal")
327 #endif /* _WIN32 */
328                 ("define,D", po::value<std::vector<std::string> >(), "define a constant")
329                 ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
330                 ("log-level,x", po::value<std::string>(), "specify the log level for the console log.\n"
331                         "The valid value is either debug, notice, information (default), warning, or critical")
332                 ("script-debugger,X", "whether to enable the script debugger");
333
334         po::options_description hiddenDesc("Hidden options");
335
336         hiddenDesc.add_options()
337                 ("no-stack-rlimit", "used internally, do not specify manually")
338                 ("arg", po::value<std::vector<std::string> >(), "positional argument");
339
340         po::positional_options_description positionalDesc;
341         positionalDesc.add("arg", -1);
342
343         String cmdname;
344         CLICommand::Ptr command;
345         po::variables_map vm;
346
347         try {
348                 CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
349                         vm, cmdname, command, autocomplete);
350         } catch (const std::exception& ex) {
351                 Log(LogCritical, "icinga-app")
352                         << "Error while parsing command-line options: " << ex.what();
353                 return EXIT_FAILURE;
354         }
355
356 #ifdef _WIN32
357         char username[UNLEN + 1];
358         DWORD usernameLen = UNLEN + 1;
359         GetUserName(username, &usernameLen);
360
361         std::ifstream userFile;
362
363         /* The implicit string assignment is needed for Windows builds. */
364         String configDir = Configuration::ConfigDir;
365         userFile.open(configDir + "/user");
366
367         if (userFile && command && !Application::IsProcessElevated()) {
368                 std::string userLine;
369                 if (std::getline(userFile, userLine)) {
370                         userFile.close();
371
372                         std::vector<std::string> strs;
373                         boost::split(strs, userLine, boost::is_any_of("\\"));
374
375                         if (username != strs[1] && command->GetImpersonationLevel() == ImpersonationLevel::ImpersonateIcinga
376                                 || command->GetImpersonationLevel() == ImpersonationLevel::ImpersonateRoot) {
377                                 TCHAR szPath[MAX_PATH];
378
379                                 if (GetModuleFileName(nullptr, szPath, ARRAYSIZE(szPath))) {
380                                         SHELLEXECUTEINFO sei = { sizeof(sei) };
381                                         sei.lpVerb = _T("runas");
382                                         sei.lpFile = "cmd.exe";
383                                         sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI;
384                                         sei.nShow = SW_SHOW;
385
386                                         std::stringstream parameters;
387
388                                         parameters << "/C " << "\"" << szPath << "\"" << " ";
389
390                                         for (int i = 1; i < argc; i++) {
391                                                 if (i != 1)
392                                                         parameters << " ";
393                                                 parameters << argv[i];
394                                         }
395
396                                         parameters << " & SET exitcode=%errorlevel%";
397                                         parameters << " & pause";
398                                         parameters << " & EXIT /B %exitcode%";
399
400                                         std::string str = parameters.str();
401                                         LPCSTR cstr = str.c_str();
402
403                                         sei.lpParameters = cstr;
404
405                                         if (!ShellExecuteEx(&sei)) {
406                                                 DWORD dwError = GetLastError();
407                                                 if (dwError == ERROR_CANCELLED)
408                                                         Application::Exit(0);
409                                         } else {
410                                                 WaitForSingleObject(sei.hProcess, INFINITE);
411
412                                                 DWORD exitCode;
413                                                 GetExitCodeProcess(sei.hProcess, &exitCode);
414
415                                                 CloseHandle(sei.hProcess);
416
417                                                 Application::Exit(exitCode);
418                                         }
419                                 }
420                         }
421                 } else {
422                         userFile.close();
423                 }
424         }
425 #endif /* _WIN32 */
426
427 #ifndef _WIN32
428         if (vm.count("color")) {
429                 Console::SetType(std::cout, Console_VT100);
430                 Console::SetType(std::cerr, Console_VT100);
431         }
432 #endif /* _WIN32 */
433
434         if (vm.count("define")) {
435                 for (const String& define : vm["define"].as<std::vector<std::string> >()) {
436                         String key, value;
437                         size_t pos = define.FindFirstOf('=');
438                         if (pos != String::NPos) {
439                                 key = define.SubStr(0, pos);
440                                 value = define.SubStr(pos + 1);
441                         } else {
442                                 key = define;
443                                 value = "1";
444                         }
445
446                         std::vector<String> keyTokens = key.Split(".");
447
448                         std::unique_ptr<Expression> expr;
449                         std::unique_ptr<VariableExpression> varExpr{new VariableExpression(keyTokens[0], {}, DebugInfo())};
450                         expr = std::move(varExpr);
451
452                         for (size_t i = 1; i < keyTokens.size(); i++) {
453                                 std::unique_ptr<IndexerExpression> indexerExpr{new IndexerExpression(std::move(expr), MakeLiteral(keyTokens[i]))};
454                                 indexerExpr->SetOverrideFrozen();
455                                 expr = std::move(indexerExpr);
456                         }
457
458                         std::unique_ptr<SetExpression> setExpr{new SetExpression(std::move(expr), OpSetLiteral, MakeLiteral(value))};
459                         setExpr->SetOverrideFrozen();
460
461                         ScriptFrame frame(true);
462                         setExpr->Evaluate(frame);
463                 }
464         }
465
466         Configuration::SetReadOnly(true);
467
468         /* Ensure that all defined constants work in the way we expect them. */
469         HandleLegacyDefines();
470
471         if (vm.count("script-debugger"))
472                 Application::SetScriptDebuggerEnabled(true);
473
474         Configuration::StatePath = Configuration::DataDir + "/icinga2.state";
475         Configuration::ModAttrPath = Configuration::DataDir + "/modified-attributes.conf";
476         Configuration::ObjectsPath = Configuration::CacheDir + "/icinga2.debug";
477         Configuration::VarsPath = Configuration::CacheDir + "/icinga2.vars";
478         Configuration::PidPath = Configuration::InitRunDir + "/icinga2.pid";
479
480         ConfigCompiler::AddIncludeSearchDir(Configuration::IncludeConfDir);
481
482         if (!autocomplete && vm.count("include")) {
483                 for (const String& includePath : vm["include"].as<std::vector<std::string> >()) {
484                         ConfigCompiler::AddIncludeSearchDir(includePath);
485                 }
486         }
487
488         if (!autocomplete) {
489                 Logger::SetConsoleLogSeverity(logLevel);
490
491                 if (vm.count("log-level")) {
492                         String severity = vm["log-level"].as<std::string>();
493
494                         LogSeverity logLevel = LogInformation;
495                         try {
496                                 logLevel = Logger::StringToSeverity(severity);
497                         } catch (std::exception&) {
498                                 /* Inform user and exit */
499                                 Log(LogCritical, "icinga-app", "Invalid log level set. Default is 'information'.");
500                                 return EXIT_FAILURE;
501                         }
502
503                         Logger::SetConsoleLogSeverity(logLevel);
504                 }
505
506                 if (!command || vm.count("help") || vm.count("version")) {
507                         String appName;
508
509                         try {
510                                 appName = Utility::BaseName(Application::GetArgV()[0]);
511                         } catch (const std::bad_alloc&) {
512                                 Log(LogCritical, "icinga-app", "Allocation failed.");
513                                 return EXIT_FAILURE;
514                         }
515
516                         if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
517                                 appName = appName.SubStr(3, appName.GetLength() - 3);
518
519                         std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
520                                 << ConsoleColorTag(vm.count("version") ? Console_ForegroundRed : Console_Normal)
521                                 << Application::GetAppVersion()
522 #ifdef I2_DEBUG
523                                 << "; debug"
524 #endif /* I2_DEBUG */
525                                 << ConsoleColorTag(Console_Normal)
526                                 << ")" << std::endl << std::endl;
527
528                         if ((!command || vm.count("help")) && !vm.count("version")) {
529                                 std::cout << "Usage:" << std::endl
530                                         << "  " << Utility::BaseName(argv[0]) << " ";
531
532                                 if (cmdname.IsEmpty())
533                                         std::cout << "<command>";
534                                 else
535                                         std::cout << cmdname;
536
537                                 std::cout << " [<arguments>]" << std::endl;
538
539                                 if (command) {
540                                         std::cout << std::endl
541                                                 << command->GetDescription() << std::endl;
542                                 }
543                         }
544
545                         if (vm.count("version")) {
546                                 std::cout << "Copyright (c) 2012-" << Utility::FormatDateTime("%Y", Utility::GetTime())
547                                         << " Icinga GmbH (https://icinga.com/)" << std::endl
548                                         << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
549                                         << "This is free software: you are free to change and redistribute it." << std::endl
550                                         << "There is NO WARRANTY, to the extent permitted by law.";
551                         }
552
553                         std::cout << std::endl;
554
555                         if (vm.count("version")) {
556                                 std::cout << std::endl;
557
558                                 Application::DisplayInfoMessage(std::cout, true);
559
560                                 return EXIT_SUCCESS;
561                         }
562                 }
563
564                 if (!command || vm.count("help")) {
565                         if (!command)
566                                 CLICommand::ShowCommands(argc, argv, nullptr);
567
568                         std::cout << visibleDesc << std::endl
569                                 << "Report bugs at <https://github.com/Icinga/icinga2>" << std::endl
570                                 << "Get support: <https://icinga.com/support/>" << std::endl
571                                 << "Documentation: <https://icinga.com/docs/>" << std::endl
572                                 << "Icinga home page: <https://icinga.com/>" << std::endl;
573                         return EXIT_SUCCESS;
574                 }
575         }
576
577         int rc = 1;
578
579         if (autocomplete) {
580                 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
581                         &GlobalArgumentCompletion, true, autoindex);
582                 rc = 0;
583         } else if (command) {
584                 Logger::DisableTimestamp();
585 #ifndef _WIN32
586                 if (command->GetImpersonationLevel() == ImpersonateRoot) {
587                         if (getuid() != 0) {
588                                 Log(LogCritical, "cli", "This command must be run as root.");
589                                 return 0;
590                         }
591                 } else if (command && command->GetImpersonationLevel() == ImpersonateIcinga) {
592                         String group = Configuration::RunAsGroup;
593                         String user = Configuration::RunAsUser;
594
595                         errno = 0;
596                         struct group *gr = getgrnam(group.CStr());
597
598                         if (!gr) {
599                                 if (errno == 0) {
600                                         Log(LogCritical, "cli")
601                                                 << "Invalid group specified: " << group;
602                                         return EXIT_FAILURE;
603                                 } else {
604                                         Log(LogCritical, "cli")
605                                                 << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
606                                         return EXIT_FAILURE;
607                                 }
608                         }
609
610                         if (getgid() != gr->gr_gid) {
611                                 if (!vm.count("reload-internal") && setgroups(0, nullptr) < 0) {
612                                         Log(LogCritical, "cli")
613                                                 << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
614                                         Log(LogCritical, "cli")
615                                                 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
616                                         return EXIT_FAILURE;
617                                 }
618
619                                 if (setgid(gr->gr_gid) < 0) {
620                                         Log(LogCritical, "cli")
621                                                 << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
622                                         return EXIT_FAILURE;
623                                 }
624                         }
625
626                         errno = 0;
627                         struct passwd *pw = getpwnam(user.CStr());
628
629                         if (!pw) {
630                                 if (errno == 0) {
631                                         Log(LogCritical, "cli")
632                                                 << "Invalid user specified: " << user;
633                                         return EXIT_FAILURE;
634                                 } else {
635                                         Log(LogCritical, "cli")
636                                                 << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
637                                         return EXIT_FAILURE;
638                                 }
639                         }
640
641                         // also activate the additional groups the configured user is member of
642                         if (getuid() != pw->pw_uid) {
643                                 if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
644                                         Log(LogCritical, "cli")
645                                                 << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
646                                         Log(LogCritical, "cli")
647                                                 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
648                                         return EXIT_FAILURE;
649                                 }
650
651                                 if (setuid(pw->pw_uid) < 0) {
652                                         Log(LogCritical, "cli")
653                                                 << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
654                                         Log(LogCritical, "cli")
655                                                 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
656                                         return EXIT_FAILURE;
657                                 }
658                         }
659                 }
660
661                 Process::InitializeSpawnHelper();
662 #endif /* _WIN32 */
663
664                 std::vector<std::string> args;
665                 if (vm.count("arg"))
666                         args = vm["arg"].as<std::vector<std::string> >();
667
668                 if (static_cast<int>(args.size()) < command->GetMinArguments()) {
669                         Log(LogCritical, "cli")
670                                 << "Too few arguments. Command needs at least " << command->GetMinArguments()
671                                 << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
672                         return EXIT_FAILURE;
673                 }
674
675                 if (command->GetMaxArguments() >= 0 && static_cast<int>(args.size()) > command->GetMaxArguments()) {
676                         Log(LogCritical, "cli")
677                                 << "Too many arguments. At most " << command->GetMaxArguments()
678                                 << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
679                         return EXIT_FAILURE;
680                 }
681
682                 rc = command->Run(vm, args);
683         }
684
685         return rc;
686 }
687
688 #ifdef _WIN32
689 static int SetupService(bool install, int argc, char **argv)
690 {
691         SC_HANDLE schSCManager = OpenSCManager(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
692
693         if (!schSCManager) {
694                 printf("OpenSCManager failed (%d)\n", GetLastError());
695                 return 1;
696         }
697
698         TCHAR szPath[MAX_PATH];
699
700         if (!GetModuleFileName(nullptr, szPath, MAX_PATH)) {
701                 printf("Cannot install service (%d)\n", GetLastError());
702                 return 1;
703         }
704
705         String szArgs;
706         szArgs = Utility::EscapeShellArg(szPath) + " --scm";
707
708         std::string scmUser = "NT AUTHORITY\\NetworkService";
709         std::ifstream initf(Utility::GetIcingaDataPath() + "\\etc\\icinga2\\user");
710         if (initf.good()) {
711                 std::getline(initf, scmUser);
712         }
713         initf.close();
714
715         for (int i = 0; i < argc; i++) {
716                 if (!strcmp(argv[i], "--scm-user") && i + 1 < argc) {
717                         scmUser = argv[i + 1];
718                         i++;
719                 } else
720                         szArgs += " " + Utility::EscapeShellArg(argv[i]);
721         }
722
723         SC_HANDLE schService = OpenService(schSCManager, "icinga2", SERVICE_ALL_ACCESS);
724
725         if (schService) {
726                 SERVICE_STATUS status;
727                 ControlService(schService, SERVICE_CONTROL_STOP, &status);
728
729                 double start = Utility::GetTime();
730                 while (status.dwCurrentState != SERVICE_STOPPED) {
731                         double end = Utility::GetTime();
732
733                         if (end - start > 30) {
734                                 printf("Could not stop the service.\n");
735                                 break;
736                         }
737
738                         Utility::Sleep(5);
739
740                         if (!QueryServiceStatus(schService, &status)) {
741                                 printf("QueryServiceStatus failed (%d)\n", GetLastError());
742                                 return 1;
743                         }
744                 }
745         } else if (install) {
746                 schService = CreateService(
747                         schSCManager,
748                         "icinga2",
749                         "Icinga 2",
750                         SERVICE_ALL_ACCESS,
751                         SERVICE_WIN32_OWN_PROCESS,
752                         SERVICE_DEMAND_START,
753                         SERVICE_ERROR_NORMAL,
754                         szArgs.CStr(),
755                         nullptr,
756                         nullptr,
757                         nullptr,
758                         scmUser.c_str(),
759                         nullptr);
760
761                 if (!schService) {
762                         printf("CreateService failed (%d)\n", GetLastError());
763                         CloseServiceHandle(schSCManager);
764                         return 1;
765                 }
766         } else {
767                 printf("Service isn't installed.\n");
768                 CloseServiceHandle(schSCManager);
769                 return 0;
770         }
771
772         if (!install) {
773                 if (!DeleteService(schService)) {
774                         printf("DeleteService failed (%d)\n", GetLastError());
775                         CloseServiceHandle(schService);
776                         CloseServiceHandle(schSCManager);
777                         return 1;
778                 }
779
780                 printf("Service uninstalled successfully\n");
781         } else {
782                 if (!ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
783                         SERVICE_ERROR_NORMAL, szArgs.CStr(), nullptr, nullptr, nullptr, scmUser.c_str(), nullptr, nullptr)) {
784                         printf("ChangeServiceConfig failed (%d)\n", GetLastError());
785                         CloseServiceHandle(schService);
786                         CloseServiceHandle(schSCManager);
787                         return 1;
788                 }
789
790                 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
791                 if(!ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription)) {
792                         printf("ChangeServiceConfig2 failed (%d)\n", GetLastError());
793                         CloseServiceHandle(schService);
794                         CloseServiceHandle(schSCManager);
795                         return 1;
796                 }
797
798                 if (!StartService(schService, 0, nullptr)) {
799                         printf("StartService failed (%d)\n", GetLastError());
800                         CloseServiceHandle(schService);
801                         CloseServiceHandle(schSCManager);
802                         return 1;
803                 }
804
805                 std::cout << "Service successfully installed for user '" << scmUser << "'\n";
806
807                 String userFilePath = Utility::GetIcingaDataPath() + "\\etc\\icinga2\\user";
808
809                 std::ofstream fuser(userFilePath.CStr(), std::ios::out | std::ios::trunc);
810                 if (fuser)
811                         fuser << scmUser;
812                 else
813                         std::cout << "Could not write user to " << userFilePath << "\n";
814         }
815
816         CloseServiceHandle(schService);
817         CloseServiceHandle(schSCManager);
818
819         return 0;
820 }
821
822 static VOID ReportSvcStatus(DWORD dwCurrentState,
823         DWORD dwWin32ExitCode,
824         DWORD dwWaitHint)
825 {
826         static DWORD dwCheckPoint = 1;
827
828         l_SvcStatus.dwCurrentState = dwCurrentState;
829         l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
830         l_SvcStatus.dwWaitHint = dwWaitHint;
831
832         if (dwCurrentState == SERVICE_START_PENDING)
833                 l_SvcStatus.dwControlsAccepted = 0;
834         else
835                 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
836
837         if ((dwCurrentState == SERVICE_RUNNING) ||
838                 (dwCurrentState == SERVICE_STOPPED))
839                 l_SvcStatus.dwCheckPoint = 0;
840         else
841                 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
842
843         SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
844 }
845
846 static VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
847 {
848         if (dwCtrl == SERVICE_CONTROL_STOP) {
849                 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
850                 TerminateJobObject(l_Job, 0);
851         }
852 }
853
854 static VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
855 {
856         l_SvcStatusHandle = RegisterServiceCtrlHandler(
857                 "icinga2",
858                 ServiceControlHandler);
859
860         l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
861         l_SvcStatus.dwServiceSpecificExitCode = 0;
862
863         ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
864         l_Job = CreateJobObject(nullptr, nullptr);
865
866         for (;;) {
867                 LPSTR arg = argv[0];
868                 String args;
869                 int uargc = Application::GetArgC();
870                 char **uargv = Application::GetArgV();
871
872                 args += Utility::EscapeShellArg(Application::GetExePath(uargv[0]));
873
874                 for (int i = 2; i < uargc && uargv[i]; i++) {
875                         if (args != "")
876                                 args += " ";
877
878                         args += Utility::EscapeShellArg(uargv[i]);
879                 }
880
881                 STARTUPINFO si = { sizeof(si) };
882                 PROCESS_INFORMATION pi;
883
884                 char *uargs = strdup(args.CStr());
885
886                 BOOL res = CreateProcess(nullptr, uargs, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi);
887
888                 free(uargs);
889
890                 if (!res)
891                         break;
892
893                 CloseHandle(pi.hThread);
894
895                 AssignProcessToJobObject(l_Job, pi.hProcess);
896
897                 if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_OBJECT_0)
898                         break;
899
900                 DWORD exitStatus;
901
902                 if (!GetExitCodeProcess(pi.hProcess, &exitStatus))
903                         break;
904
905                 if (exitStatus != 7)
906                         break;
907         }
908
909         TerminateJobObject(l_Job, 0);
910
911         CloseHandle(l_Job);
912
913         ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
914
915         Application::Exit(0);
916 }
917 #endif /* _WIN32 */
918
919 /**
920 * Entry point for the Icinga application.
921 *
922 * @params argc Number of command line arguments.
923 * @params argv Command line arguments.
924 * @returns The application's exit status.
925 */
926 int main(int argc, char **argv)
927 {
928 #ifndef _WIN32
929         if (!getenv("ICINGA2_KEEP_FDS")) {
930                 rlimit rl;
931                 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0) {
932                         rlim_t maxfds = rl.rlim_max;
933
934                         if (maxfds == RLIM_INFINITY)
935                                 maxfds = 65536;
936
937                         for (rlim_t i = 3; i < maxfds; i++) {
938                                 int rc = close(i);
939
940 #ifdef I2_DEBUG
941                                 if (rc >= 0)
942                                         std::cerr << "Closed FD " << i << " which we inherited from our parent process." << std::endl;
943 #endif /* I2_DEBUG */
944                         }
945                 }
946         }
947 #endif /* _WIN32 */
948
949         /* must be called before using any other libbase functions */
950         Application::InitializeBase();
951
952         /* Set command-line arguments. */
953         Application::SetArgC(argc);
954         Application::SetArgV(argv);
955
956 #ifdef _WIN32
957         if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
958                 return SetupService(true, argc - 2, &argv[2]);
959         }
960
961         if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
962                 return SetupService(false, argc - 2, &argv[2]);
963         }
964
965         if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
966                 SERVICE_TABLE_ENTRY dispatchTable[] = {
967                         { "icinga2", ServiceMain },
968                         { nullptr, nullptr }
969                 };
970
971                 StartServiceCtrlDispatcher(dispatchTable);
972                 Application::Exit(EXIT_FAILURE);
973         }
974 #endif /* _WIN32 */
975
976         int rc = Main();
977
978         Application::Exit(rc);
979 }