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