]> granicus.if.org Git - icinga2/blob - icinga-app/icinga.cpp
Cli: Add blacklist/whitelist commands for agent commands
[icinga2] / icinga-app / icinga.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2014 Icinga Development Team (http://www.icinga.org)    *
4  *                                                                            *
5  * This program is free software; you can redistribute it and/or              *
6  * modify it under the terms of the GNU General Public License                *
7  * as published by the Free Software Foundation; either version 2             *
8  * of the License, or (at your option) any later version.                     *
9  *                                                                            *
10  * This program is distributed in the hope that it will be useful,            *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
13  * GNU General Public License for more details.                               *
14  *                                                                            *
15  * You should have received a copy of the GNU General Public License          *
16  * along with this program; if not, write to the Free Software Foundation     *
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.             *
18  ******************************************************************************/
19
20 #include "cli/clicommand.hpp"
21 #include "config/configcompilercontext.hpp"
22 #include "config/configcompiler.hpp"
23 #include "config/configitembuilder.hpp"
24 #include "base/application.hpp"
25 #include "base/logger.hpp"
26 #include "base/timer.hpp"
27 #include "base/utility.hpp"
28 #include "base/exception.hpp"
29 #include "base/convert.hpp"
30 #include "base/scriptvariable.hpp"
31 #include "base/context.hpp"
32 #include "base/console.hpp"
33 #include "config.h"
34 #include <boost/program_options.hpp>
35 #include <boost/tuple/tuple.hpp>
36 #include <boost/foreach.hpp>
37
38 #ifndef _WIN32
39 #       include <sys/types.h>
40 #       include <pwd.h>
41 #       include <grp.h>
42 #endif /* _WIN32 */
43
44 using namespace icinga;
45 namespace po = boost::program_options;
46
47 #ifdef _WIN32
48 SERVICE_STATUS l_SvcStatus;
49 SERVICE_STATUS_HANDLE l_SvcStatusHandle;
50 #endif /* _WIN32 */
51
52 static std::vector<String> GetLogLevelCompletionSuggestions(const String& arg)
53 {
54         std::vector<String> result;
55         
56         String debugLevel = "debug";
57         if (debugLevel.Find(arg) == 0)
58                 result.push_back(debugLevel);
59
60         String noticeLevel = "notice";
61         if (noticeLevel.Find(arg) == 0)
62                 result.push_back(noticeLevel);
63
64         String informationLevel = "information";
65         if (informationLevel.Find(arg) == 0)
66                 result.push_back(informationLevel);
67
68         String warningLevel = "warning";
69         if (warningLevel.Find(arg) == 0)
70                 result.push_back(warningLevel);
71
72         String criticalLevel = "critical";
73         if (criticalLevel.Find(arg) == 0)
74                 result.push_back(criticalLevel);
75
76         return result;
77 }
78
79 static std::vector<String> GlobalArgumentCompletion(const String& argument, const String& word)
80 {
81         if (argument == "include")
82                 return GetBashCompletionSuggestions("directory", word);
83         else if (argument == "log-level")
84                 return GetLogLevelCompletionSuggestions(word);
85         else
86                 return std::vector<String>();
87 }
88
89 int Main(void)
90 {
91         int argc = Application::GetArgC();
92         char **argv = Application::GetArgV();
93
94         bool autocomplete = false;
95         int autoindex = 0;
96
97         if (argc >= 4 && strcmp(argv[1], "--autocomplete") == 0) {
98                 autocomplete = true;
99                 autoindex = Convert::ToLong(argv[2]);
100                 argc -= 3;
101                 argv += 3;
102         }
103
104         Application::SetStartTime(Utility::GetTime());
105
106         if (!autocomplete)
107                 Application::SetResourceLimits();
108
109         /* Set thread title. */
110         Utility::SetThreadName("Main Thread", false);
111
112         /* Install exception handlers to make debugging easier. */
113         Application::InstallExceptionHandlers();
114
115 #ifdef _WIN32
116         bool builtinPaths = true;
117
118         HKEY hKey;
119         if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Icinga Development Team\\ICINGA2", 0,
120             KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
121                 BYTE pvData[MAX_PATH];
122                 DWORD cbData = sizeof(pvData)-1;
123                 DWORD lType;
124                 if (RegQueryValueEx(hKey, NULL, NULL, &lType, pvData, &cbData) == ERROR_SUCCESS && lType == REG_SZ) {
125                         pvData[cbData] = '\0';
126
127                         String prefix = (char *)pvData;
128                         Application::DeclarePrefixDir(prefix);
129                         Application::DeclareSysconfDir(prefix + "\\etc");
130                         Application::DeclareRunDir(prefix + "\\var\\run");
131                         Application::DeclareLocalStateDir(prefix + "\\var");
132                         Application::DeclarePkgDataDir(prefix + "\\share\\icinga2");
133                         Application::DeclareIncludeConfDir(prefix + "\\share\\icinga2\\include");
134
135                         builtinPaths = false;
136                 }
137
138                 RegCloseKey(hKey);
139         }
140
141         if (builtinPaths) {
142                 Log(LogWarning, "icinga-app", "Registry key could not be read. Falling back to built-in paths.");
143
144 #endif /* _WIN32 */
145                 Application::DeclarePrefixDir(ICINGA_PREFIX);
146                 Application::DeclareSysconfDir(ICINGA_SYSCONFDIR);
147                 Application::DeclareRunDir(ICINGA_RUNDIR);
148                 Application::DeclareLocalStateDir(ICINGA_LOCALSTATEDIR);
149                 Application::DeclarePkgDataDir(ICINGA_PKGDATADIR);
150                 Application::DeclareIncludeConfDir(ICINGA_INCLUDECONFDIR);
151 #ifdef _WIN32
152         }
153 #endif /* _WIN32 */
154
155         Application::DeclareZonesDir(Application::GetSysconfDir() + "/icinga2/zones.d");
156         Application::DeclareApplicationType("icinga/IcingaApplication");
157         Application::DeclareRunAsUser(ICINGA_USER);
158         Application::DeclareRunAsGroup(ICINGA_GROUP);
159
160         LogSeverity logLevel = Logger::GetConsoleLogSeverity();
161         Logger::SetConsoleLogSeverity(LogWarning);
162
163         Utility::LoadExtensionLibrary("cli");
164
165         po::options_description visibleDesc("Global options");
166
167         visibleDesc.add_options()
168                 ("help,h", "show this help message")
169                 ("version,V", "show version information")
170 #ifndef _WIN32
171                 ("color", "use VT100 color codes even when stdout is not a terminal")
172 #endif /* _WIN32 */
173                 ("define,D", po::value<std::vector<std::string> >(), "define a constant")
174                 ("library,l", po::value<std::vector<std::string> >(), "load a library")
175                 ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
176                 ("log-level,x", po::value<std::string>(), "specify the log level for the console log");
177
178         po::options_description hiddenDesc("Hidden options");
179
180         hiddenDesc.add_options()
181 #ifndef _WIN32
182                 ("no-stack-rlimit", "used internally, do not specify manually")
183 #else /* _WIN32 */
184                 ("no-stack-rlimit", "used internally, do not specify manually")
185 #endif /* _WIN32 */
186                 ("arg", po::value<std::vector<std::string> >(), "positional argument");
187
188         po::positional_options_description positionalDesc;
189         positionalDesc.add("arg", -1);
190
191         String cmdname;
192         CLICommand::Ptr command;
193         po::variables_map vm;
194
195         try {
196                 CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
197                     vm, cmdname, command, autocomplete);
198         } catch (const std::exception& ex) {
199                 Log(LogCritical, "icinga-app")
200                     << "Error while parsing command-line options: " << ex.what();
201                 return EXIT_FAILURE;
202         }
203
204         String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";
205
206         if (Utility::PathExists(initconfig)) {
207                 ConfigCompilerContext::GetInstance()->Reset();
208                 ConfigCompiler::CompileFile(initconfig);
209         }
210
211 #ifndef _WIN32
212         if (vm.count("color")) {
213                 Console::SetType(std::cout, Console_VT100);
214                 Console::SetType(std::cerr, Console_VT100);
215         }
216 #endif /* _WIN32 */
217
218         if (vm.count("define")) {
219                 BOOST_FOREACH(const String& define, vm["define"].as<std::vector<std::string> >()) {
220                         String key, value;
221                         size_t pos = define.FindFirstOf('=');
222                         if (pos != String::NPos) {
223                                 key = define.SubStr(0, pos);
224                                 value = define.SubStr(pos + 1);
225                         } else {
226                                 key = define;
227                                 value = "1";
228                         }
229                         ScriptVariable::Set(key, value);
230                 }
231         }
232
233         Application::DeclareStatePath(Application::GetLocalStateDir() + "/lib/icinga2/icinga2.state");
234         Application::DeclareObjectsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.debug");
235         Application::DeclareVarsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.vars");
236         Application::DeclarePidPath(Application::GetRunDir() + "/icinga2/icinga2.pid");
237
238         ConfigCompiler::AddIncludeSearchDir(Application::GetIncludeConfDir());
239
240         if (!autocomplete && vm.count("include")) {
241                 BOOST_FOREACH(const String& includePath, vm["include"].as<std::vector<std::string> >()) {
242                         ConfigCompiler::AddIncludeSearchDir(includePath);
243                 }
244         }
245
246         if (!autocomplete) {
247                 Logger::SetConsoleLogSeverity(logLevel);
248
249                 if (vm.count("log-level")) {
250                         String severity = vm["log-level"].as<std::string>();
251
252                         LogSeverity logLevel = LogInformation;
253                         try {
254                                 logLevel = Logger::StringToSeverity(severity);
255                         } catch (std::exception&) {
256                                 /* use the default */
257                                 Log(LogWarning, "icinga", "Invalid log level set. Using default 'information'.");
258                         }
259
260                         Logger::SetConsoleLogSeverity(logLevel);
261                 }
262
263                 if (vm.count("library")) {
264                         BOOST_FOREACH(const String& libraryName, vm["library"].as<std::vector<std::string> >()) {
265                                 (void)Utility::LoadExtensionLibrary(libraryName);
266                         }
267                 }
268
269                 if (!command || vm.count("help") || vm.count("version")) {
270                         String appName = Utility::BaseName(Application::GetArgV()[0]);
271
272                         if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
273                                 appName = appName.SubStr(3, appName.GetLength() - 3);
274
275                         std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
276                             << Application::GetVersion() << ")" << std::endl << std::endl;
277
278                         if (!command || vm.count("help")) {
279                                 std::cout << "Usage:" << std::endl
280                                     << "  " << argv[0] << " ";
281
282                                 if (cmdname.IsEmpty())
283                                         std::cout << "<command>";
284                                 else
285                                         std::cout << cmdname;
286
287                                 std::cout << " [<arguments>]" << std::endl;
288
289                                 if (command) {
290                                         std::cout << std::endl
291                                                   << command->GetDescription();
292                                 }
293
294                                 std::cout << std::endl;
295                         }
296
297                         if (vm.count("version")) {
298                                 std::cout << "Copyright (c) 2012-2014 Icinga Development Team (http://www.icinga.org)" << std::endl
299                                         << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
300                                         << "This is free software: you are free to change and redistribute it." << std::endl
301                                         << "There is NO WARRANTY, to the extent permitted by law.";
302                         }
303
304                         std::cout << std::endl;
305
306                         if (vm.count("version")) {
307                                 std::cout << std::endl;
308
309                                 Application::DisplayInfoMessage(true);
310
311                                 return EXIT_SUCCESS;
312                         }
313                 }
314
315                 if (!command || vm.count("help")) {
316                         if (!command)
317                                 CLICommand::ShowCommands(argc, argv, NULL);
318
319                         std::cout << visibleDesc << std::endl
320                                 << "Report bugs at <https://dev.icinga.org/>" << std::endl
321                                 << "Icinga home page: <http://www.icinga.org/>" << std::endl;
322                         return EXIT_SUCCESS;
323                 }
324         }
325
326         int rc = 1;
327
328         if (autocomplete) {
329                 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
330                     &GlobalArgumentCompletion, true, autoindex);
331                 rc = 0;
332         } else if (command) {
333 #ifndef _WIN32
334                 if (command->GetImpersonationLevel() == ImpersonateRoot) {
335                         if (getuid() != 0) {
336                                 Log(LogCritical, "cli", "This command must be run as root.");
337                                 return 0;
338                         }
339                 } else if (command && command->GetImpersonationLevel() == ImpersonateIcinga) {
340                         String group = Application::GetRunAsGroup();
341         
342                         errno = 0;
343                         struct group *gr = getgrnam(group.CStr());
344         
345                         if (!gr) {
346                                 if (errno == 0) {
347                                         Log(LogCritical, "cli")
348                                             << "Invalid group specified: " << group;
349                                         return EXIT_FAILURE;
350                                 } else {
351                                         Log(LogCritical, "cli")
352                                             << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
353                                         return EXIT_FAILURE;
354                                 }
355                         }
356         
357                         if (getgid() != gr->gr_gid) {
358                                 if (!vm.count("reload-internal") && setgroups(0, NULL) < 0) {
359                                         Log(LogCritical, "cli")
360                                             << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
361                                         return EXIT_FAILURE;
362                                 }
363         
364                                 if (setgid(gr->gr_gid) < 0) {
365                                         Log(LogCritical, "cli")
366                                             << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
367                                         return EXIT_FAILURE;
368                                 }
369                         }
370         
371                         String user = Application::GetRunAsUser();
372         
373                         errno = 0;
374                         struct passwd *pw = getpwnam(user.CStr());
375         
376                         if (!pw) {
377                                 if (errno == 0) {
378                                         Log(LogCritical, "cli")
379                                             << "Invalid user specified: " << user;
380                                         return EXIT_FAILURE;
381                                 } else {
382                                         Log(LogCritical, "cli")
383                                             << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
384                                         return EXIT_FAILURE;
385                                 }
386                         }
387         
388                         // also activate the additional groups the configured user is member of
389                         if (getuid() != pw->pw_uid) {
390                                 if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
391                                         Log(LogCritical, "cli")
392                                             << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
393                                         return EXIT_FAILURE;
394                                 }
395         
396                                 if (setuid(pw->pw_uid) < 0) {
397                                         Log(LogCritical, "cli")
398                                             << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
399                                         return EXIT_FAILURE;
400                                 }
401                         }
402                 }
403 #endif /* _WIN32 */
404
405                 std::vector<std::string> args;
406                 if (vm.count("arg"))
407                         args = vm["arg"].as<std::vector<std::string> >();
408
409                 if (args.size() < command->GetMinArguments()) {
410                         Log(LogCritical, "cli")
411                             << "Too few arguments. Command needs at least " << command->GetMinArguments()
412                             << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
413                         return EXIT_FAILURE;
414                 }
415
416                 if (command->GetMaxArguments() >= 0 && args.size() > command->GetMaxArguments()) {
417                         Log(LogCritical, "cli")
418                             << "Too many arguments. At most " << command->GetMaxArguments()
419                             << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
420                         return EXIT_FAILURE;
421                 }
422
423                 rc = command->Run(vm, args);
424         }
425
426 #ifndef _DEBUG
427         Application::Exit(rc);
428 #endif /* _DEBUG */
429
430         return rc;
431 }
432
433 #ifdef _WIN32
434 static int SetupService(bool install, int argc, char **argv)
435 {
436         SC_HANDLE schSCManager = OpenSCManager(
437                 NULL,
438                 NULL,
439                 SC_MANAGER_ALL_ACCESS);
440
441         if (NULL == schSCManager) {
442                 printf("OpenSCManager failed (%d)\n", GetLastError());
443                 return 1;
444         }
445
446         TCHAR szPath[MAX_PATH];
447
448         if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
449                 printf("Cannot install service (%d)\n", GetLastError());
450                 return 1;
451         }
452
453         String szArgs;
454         szArgs = Utility::EscapeShellArg(szPath) + " --scm";
455
456         for (int i = 0; i < argc; i++)
457                 szArgs += " " + Utility::EscapeShellArg(argv[i]);
458
459         SC_HANDLE schService = OpenService(schSCManager, "icinga2", DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
460
461         if (schService != NULL) {
462                 SERVICE_STATUS status;
463                 ControlService(schService, SERVICE_CONTROL_STOP, &status);
464
465                 double start = Utility::GetTime();
466                 while (status.dwCurrentState != SERVICE_STOPPED) {
467                         double end = Utility::GetTime();
468
469                         if (end - start > 30) {
470                                 printf("Could not stop the service.\n");
471                                 break;
472                         }
473
474                         Utility::Sleep(5);
475
476                         if (!QueryServiceStatus(schService, &status)) {
477                                 printf("QueryServiceStatus failed (%d)\n", GetLastError());
478                                 return 1;
479                         }
480                 }
481
482                 if (!DeleteService(schService)) {
483                         printf("DeleteService failed (%d)\n", GetLastError());
484                         CloseServiceHandle(schService);
485                         CloseServiceHandle(schSCManager);
486                         return 1;
487                 }
488
489                 if (!install)
490                         printf("Service uninstalled successfully\n");
491
492                 CloseServiceHandle(schService);
493         }
494
495         if (install) {
496                 schService = CreateService(
497                         schSCManager,
498                         "icinga2",
499                         "Icinga 2",
500                         SERVICE_ALL_ACCESS,
501                         SERVICE_WIN32_OWN_PROCESS,
502                         SERVICE_DEMAND_START,
503                         SERVICE_ERROR_NORMAL,
504                         szArgs.CStr(),
505                         NULL,
506                         NULL,
507                         NULL,
508                         "NT AUTHORITY\\NetworkService",
509                         NULL);
510
511                 if (schService == NULL) {
512                         printf("CreateService failed (%d)\n", GetLastError());
513                         CloseServiceHandle(schSCManager);
514                         return 1;
515                 } else
516                         printf("Service installed successfully\n");
517
518                 ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
519                     SERVICE_ERROR_NORMAL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
520
521                 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
522                 ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription);
523
524                 if (!StartService(schService, 0, NULL)) {
525                         printf("StartService failed (%d)\n", GetLastError());
526                         CloseServiceHandle(schService);
527                         CloseServiceHandle(schSCManager);
528                         return 1;
529                 }
530
531                 CloseServiceHandle(schService);
532         }
533
534         CloseServiceHandle(schSCManager);
535
536         return 0;
537 }
538
539 VOID ReportSvcStatus(DWORD dwCurrentState,
540         DWORD dwWin32ExitCode,
541         DWORD dwWaitHint)
542 {
543         static DWORD dwCheckPoint = 1;
544
545         l_SvcStatus.dwCurrentState = dwCurrentState;
546         l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
547         l_SvcStatus.dwWaitHint = dwWaitHint;
548
549         if (dwCurrentState == SERVICE_START_PENDING)
550                 l_SvcStatus.dwControlsAccepted = 0;
551         else
552                 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
553
554         if ((dwCurrentState == SERVICE_RUNNING) ||
555             (dwCurrentState == SERVICE_STOPPED))
556                 l_SvcStatus.dwCheckPoint = 0;
557         else
558                 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
559
560         SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
561 }
562
563 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
564 {
565         if (dwCtrl == SERVICE_CONTROL_STOP) {
566                 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
567                 Application::RequestShutdown();
568         }
569 }
570
571 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
572 {
573         l_SvcStatusHandle = RegisterServiceCtrlHandler(
574                 "icinga2",
575                 ServiceControlHandler);
576
577         l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
578         l_SvcStatus.dwServiceSpecificExitCode = 0;
579
580         ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
581
582         int rc = Main();
583
584         ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, rc);
585 }
586 #endif /* _WIN32 */
587
588 /**
589 * Entry point for the Icinga application.
590 *
591 * @params argc Number of command line arguments.
592 * @params argv Command line arguments.
593 * @returns The application's exit status.
594 */
595 int main(int argc, char **argv)
596 {
597         /* must be called before using any other libbase functions */
598         Application::InitializeBase();
599
600         /* Set command-line arguments. */
601         Application::SetArgC(argc);
602         Application::SetArgV(argv);
603
604 #ifdef _WIN32
605         if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
606                 return SetupService(true, argc - 2, &argv[2]);
607         }
608
609         if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
610                 return SetupService(false, argc - 2, &argv[2]);
611         }
612
613         if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
614                 SERVICE_TABLE_ENTRY dispatchTable[] = {
615                         { "icinga2", ServiceMain },
616                         { NULL, NULL }
617                 };
618
619                 StartServiceCtrlDispatcher(dispatchTable);
620                 Application::Exit(1);
621         }
622 #endif /* _WIN32 */
623
624         int rc = Main();
625
626         Application::Exit(rc);
627 }