source: nscp/service/NSClient++.cpp @ 89838be

0.4.00.4.10.4.2
Last change on this file since 89838be was 89838be, checked in by Michael Medin <michael@…>, 16 months ago
  • Added option to both execute and query item (with a reload in the middle for installing/running unittests)
  • Fixed issue in python unittest framework to handle "unload" (ie. reload)
  • Fixed NRPE certificate path lookup issue
  • Fixed some minor issues here and there
  • Fixed issue in loader to allow loading dummy as dummy (and not only dummy://)
  • Property mode set to 100644
File size: 55.5 KB
Line 
1///////////////////////////////////////////////////////////////////////////
2// NSClient++ Base Service
3//
4// Copyright (c) 2004 MySolutions NORDIC (http://www.medin.name)
5//
6// Date: 2004-03-13
7// Author: Michael Medin (michael@medin.name)
8//
9// Part of this file is based on work by Bruno Vais (bvais@usa.net)
10//
11// This software is provided "AS IS", without a warranty of any kind.
12// You are free to use/modify this code but leave this header intact.
13//
14//////////////////////////////////////////////////////////////////////////
15#include "StdAfx.h"
16#include "NSClient++.h"
17#include <settings/settings_core.hpp>
18#include <charEx.h>
19//#include <Socket.h>
20#include <config.h>
21#ifdef WIN32
22#include <Userenv.h>
23#include <Lmcons.h>
24//#ifdef DEBUG
25#include <crtdbg.h>
26//#endif
27#endif
28//#include <remote_processes.hpp>
29//#include <winsvc.h>
30//#include <Userenv.h>
31//#include <Lmcons.h>
32//#include <remote_processes.hpp>
33#include "core_api.h"
34#include "../helpers/settings_manager/settings_manager_impl.h"
35#include <settings/macros.h>
36#include "simple_client.hpp"
37#include "settings_client.hpp"
38#include "service_manager.hpp"
39#include "settings_logger_impl.hpp"
40#include <nscapi/nscapi_helper.hpp>
41#include <nscapi/functions.hpp>
42
43#include <settings/client/settings_client.hpp>
44#include "cli_parser.hpp"
45#include "../version.hpp"
46
47#include <protobuf/plugin.pb.h>
48
49#ifdef USE_BREAKPAD
50#include <breakpad/exception_handler_win32.hpp>
51// Used for breakpad crash handling
52static ExceptionManager *g_exception_manager = NULL;
53#endif
54
55NSClient mainClient;    // Global core instance.
56
57
58void NSClientT::log_debug(const char* file, const int line, std::wstring message) {
59        std::string s = nsclient::logger_helper::create_debug(file, line, message);
60        mainClient.reportMessage(s);
61}
62void NSClientT::log_error(const char* file, const int line, std::wstring message) {
63        std::string s = nsclient::logger_helper::create_error(file, line, message);
64        mainClient.reportMessage(s);
65}
66void NSClientT::log_error(const char* file, const int line, std::string message) {
67        std::string s = nsclient::logger_helper::create_error(file, line, utf8::cvt<std::wstring>(message));
68        mainClient.reportMessage(s);
69}
70void NSClientT::log_info(const char* file, const int line, std::wstring message) {
71        std::string s = nsclient::logger_helper::create_info(file, line, message);
72        mainClient.reportMessage(s);
73}
74
75#define LOG_CRITICAL_CORE(msg) { std::string s = nsclient::logger_helper::create_error(__FILE__, __LINE__, msg); mainClient.reportMessage(s); }
76#define LOG_CRITICAL_CORE_STD(msg) LOG_CRITICAL_CORE(std::wstring(msg))
77#define LOG_ERROR_CORE(msg) { std::string s = nsclient::logger_helper::create_error(__FILE__, __LINE__, msg); mainClient.reportMessage(s); }
78#define LOG_ERROR_CORE_STD(msg) LOG_ERROR_CORE(std::wstring(msg))
79#define LOG_INFO_CORE(msg) { std::string s = nsclient::logger_helper::create_info(__FILE__, __LINE__, msg); mainClient.reportMessage(s); }
80#define LOG_INFO_CORE_STD(msg) LOG_INFO_CORE(std::wstring(msg))
81#define LOG_DEBUG_CORE(msg) { if (mainClient.logDebug()) { std::string s = nsclient::logger_helper::create_debug(__FILE__, __LINE__, msg); mainClient.reportMessage(s); } }
82#define LOG_DEBUG_CORE_STD(msg) LOG_DEBUG_CORE(std::wstring(msg))
83
84/**
85 * START OF Tray starter MERGE HELPER
86 */
87class tray_starter {
88        struct start_block {
89                std::wstring cmd;
90                std::wstring cmd_line;
91                DWORD sessionId;
92        };
93
94public:
95        static LPVOID init(DWORD dwSessionId, std::wstring exe, std::wstring cmdline) {
96                start_block *sb = new start_block;
97                sb->cmd = exe;
98                sb->cmd_line = cmdline;
99                sb->sessionId = dwSessionId;
100                return sb;
101        }
102        DWORD threadProc(LPVOID lpParameter) {
103#ifdef WIN32
104                start_block* param = static_cast<start_block*>(lpParameter);
105                DWORD dwSessionId = param->sessionId;
106                std::wstring cmd = param->cmd;
107                std::wstring cmdline = param->cmd_line;
108                delete param;
109                for (int i=0;i<10;i++) {
110                        Sleep(1000);
111                        if (startTrayHelper(dwSessionId, cmd, cmdline, false))
112                                break;
113                }
114#endif
115                return 0;
116        }
117
118        static bool start(std::wstring command, unsigned long  dwSessionId) {
119                std::wstring cmdln = _T("\"") + command + _T("\" -channel __") + strEx::itos(dwSessionId) + _T("__");
120                return tray_starter::startTrayHelper(dwSessionId, command, cmdln);
121        }
122
123        static bool startTrayHelper(unsigned long dwSessionId, std::wstring exe, std::wstring cmdline, bool startThread = true) {
124//              HANDLE hToken = NULL;
125//              if (!remote_processes::GetSessionUserToken(dwSessionId, &hToken)) {
126//                      LOG_ERROR_STD(_T("Failed to query user token: ") + error::lookup::last_error());
127//                      return false;
128//              } else {
129//                      STARTUPINFO          StartUPInfo;
130//                      PROCESS_INFORMATION  ProcessInfo;
131//
132//                      ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
133//                      ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
134//                      StartUPInfo.wShowWindow = SW_HIDE;
135//                      StartUPInfo.lpDesktop = L"Winsta0\\Default";
136//                      StartUPInfo.cb = sizeof(STARTUPINFO);
137//
138//                      wchar_t *buffer = new wchar_t[cmdline.size()+10];
139//                      wcscpy(buffer, cmdline.c_str());
140//                      LOG_MESSAGE_STD(_T("Running: ") + exe);
141//                      LOG_MESSAGE_STD(_T("Running: ") + cmdline);
142//
143//                      LPVOID pEnv =NULL;
144//                      DWORD dwCreationFlags = CREATE_NO_WINDOW; //0; //DETACHED_PROCESS
145//
146//                      if(CreateEnvironmentBlock(&pEnv,hToken,TRUE)) {
147//                              dwCreationFlags|=CREATE_UNICODE_ENVIRONMENT;
148//                      } else {
149//                              LOG_ERROR_STD(_T("Failed to create enviornment: ") + error::lookup::last_error());
150//                              pEnv=NULL;
151//                      }
152//                      /*
153//                      LOG_ERROR_STD(_T("Impersonating user: "));
154//                      if (!ImpersonateLoggedOnUser(hToken)) {
155//                              LOG_ERROR_STD(_T("Failed to impersonate the user: ") + error::lookup::last_error());
156//                      }
157//
158//                      wchar_t pszUname[UNLEN + 1];
159//                      ZeroMemory(pszUname,sizeof(pszUname));
160//                      DWORD dwSize = UNLEN;
161//                      if (!GetUserName(pszUname,&dwSize)) {
162//                              DWORD dwErr = GetLastError();
163//                              if (!RevertToSelf())
164//                                      LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
165//                              LOG_ERROR_STD(_T("Failed to get username: ") + error::format::from_system(dwErr));
166//                              return false;
167//                      }
168//                     
169//
170//                      PROFILEINFO info;
171//                      info.dwSize = sizeof(PROFILEINFO);
172//                      info.lpUserName = pszUname;
173//                      if (!LoadUserProfile(hToken, &info)) {
174//                              DWORD dwErr = GetLastError();
175//                              if (!RevertToSelf())
176//                                      LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
177//                              LOG_ERROR_STD(_T("Failed to get username: ") + error::format::from_system(dwErr));
178//                              return false;
179//                      }
180//                      */
181//                      if (!CreateProcessAsUser(hToken, exe.c_str(), buffer, NULL, NULL, FALSE, dwCreationFlags, pEnv, NULL, &StartUPInfo, &ProcessInfo)) {
182//                              DWORD dwErr = GetLastError();
183//                              delete [] buffer;
184//                              /*
185//                              if (!RevertToSelf()) {
186//                                      LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
187//                              }
188//                              */
189//                              if (startThread && dwErr == ERROR_PIPE_NOT_CONNECTED) {
190//                                      LOG_MESSAGE(_T("Failed to start trayhelper: starting a background thread to do it instead..."));
191//                                      Thread<tray_starter> *pThread = new Thread<tray_starter>(_T("tray-starter-thread"));
192//                                      pThread->createThread(tray_starter::init(dwSessionId, exe, cmdline));
193//                                      return false;
194//                              } else if (dwErr == ERROR_PIPE_NOT_CONNECTED) {
195//                                      LOG_ERROR_STD(_T("Thread failed to start trayhelper (will try again): ") + error::format::from_system(dwErr));
196//                                      return false;
197//                              } else {
198//                                      LOG_ERROR_STD(_T("Failed to start trayhelper: ") + error::format::from_system(dwErr));
199//                                      return true;
200//                              }
201//                      } else {
202//                              delete [] buffer;
203//                              /*
204//                              if (!RevertToSelf()) {
205//                                      LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
206//                              }
207//                              */
208//                              LOG_MESSAGE_STD(_T("Started tray in other user session: ") + strEx::itos(dwSessionId));
209//                      }
210//
211//
212//                      CloseHandle(hToken);
213//                      return true;
214//              }
215                return false;
216        }
217};
218
219/**
220 * End of class tray started (MERGE HELP)
221 */
222
223bool is_module(boost::filesystem::wpath file )
224{
225#ifdef WIN32
226        return boost::ends_with(file.string(), _T(".dll"));
227#else
228        return boost::ends_with(file.string(), _T(".so"));
229#endif
230}
231/**
232 * Application startup point
233 *
234 * @param argc Argument count
235 * @param argv[] Argument array
236 * @param envp[] Environment array
237 * @return exit status
238 */
239int nscp_main(int argc, wchar_t* argv[]);
240
241#ifdef WIN32
242int wmain(int argc, wchar_t* argv[], wchar_t* envp[]) { return nscp_main(argc, argv); }
243#else
244int main(int argc, char* argv[]) {
245        wchar_t **wargv = new wchar_t*[argc];
246        for (int i=0;i<argc;i++) {
247                std::wstring s = to_wstring(argv[i]);
248                wargv[i] = new wchar_t[s.length()+10];
249                wcscpy(wargv[i], s.c_str());
250        }
251        int ret = nscp_main(argc, wargv);
252        for (int i=0;i<argc;i++) {
253                delete [] wargv[i];
254        }
255        delete [] wargv;
256}
257#endif
258
259int nscp_main(int argc, wchar_t* argv[])
260{
261        srand( (unsigned)time( NULL ) );
262        cli_parser parser(&mainClient);
263        return parser.parse(argc, argv);
264
265//      int nRetCode = 0;
266//      if ( (argc > 1) && ((*argv[1] == '-') || (*argv[1] == '/')) ) {
267//              if (false) {
268//              } else if ( wcscasecmp( _T("encrypt"), argv[1]+1 ) == 0 ) {
269//                      std::wstring password;
270//                      if (!settings_manager::init_settings()) {
271//                              std::wcout << _T("Could not find settings") << std::endl;;
272//                              return 1;
273//                      }
274//                      std::wcout << _T("Enter password to encrypt (has to be a single word): ");
275//                      std::wcin >> password;
276//                      std::wstring xor_pwd = Encrypt(password);
277//                      std::wcout << _T("obfuscated_password=") << xor_pwd << std::endl;
278//                      std::wstring outPasswd = Decrypt(xor_pwd);
279//                      if (password != outPasswd)
280//                              std::wcout << _T("ERROR: Password did not match: ") << outPasswd<< std::endl;
281//                      settings_manager::destroy_settings();
282//                      return 0;
283//              } else if ( wcscasecmp( _T("about"), argv[1]+1 ) == 0 ) {
284//                      try {
285//                              unsigned int next_plugin_id = 0;
286//                              LOG_INFO_CORE(APPLICATION_NAME _T(" (C) Michael Medin - michael<at>medin<dot>name"));
287//                              LOG_INFO_CORE(_T("Version: ") CURRENT_SERVICE_VERSION);
288//                              LOG_INFO_CORE(_T("Architecture: ") SZARCH);
289//
290//                              boost::filesystem::wpath pluginPath = (boost::filesystem::wpath)mainClient.getBasePath() / _T("modules");
291//                              LOG_INFO_CORE_STD(_T("Looking at plugins in: ") + pluginPath.string());
292//
293//                              boost::filesystem::wdirectory_iterator end_itr; // default construction yields past-the-end
294//                              for ( boost::filesystem::wdirectory_iterator itr( pluginPath ); itr != end_itr; ++itr ) {
295//                                      if ( !is_directory(itr->status()) ) {
296//                                              std::wstring file= itr->leaf();
297//                                              LOG_INFO_CORE_STD(_T("Found: ") + file);
298//                                              if (is_module(pluginPath / file)) {
299//                                                      NSCPlugin *plugin = new NSCPlugin(next_plugin_id++, pluginPath / file, _T(""));
300//                                                      std::wstring name = _T("<unknown>");
301//                                                      std::wstring description = _T("<unknown>");
302//                                                      try {
303//                                                              plugin->load_dll();
304//                                                              name = plugin->getName();
305//                                                              description = plugin->getDescription();
306//                                                      } catch(NSPluginException& e) {
307//                                                              LOG_ERROR_CORE_STD(_T("Exception raised: ") + e.error_ + _T(" in module: ") + e.file_);
308//                                                      } catch (std::exception e) {
309//                                                              LOG_ERROR_CORE_STD(_T("exception loading plugin: ") + strEx::string_to_wstring(e.what()));
310//                                                      } catch (...) {
311//                                                              LOG_ERROR_CORE_STD(_T("Unknown exception loading plugin"));
312//                                                      }
313//                                                      LOG_INFO_CORE_STD(_T("* ") + name + _T(" (") + file + _T(")"));
314//                                                      std::list<std::wstring> list = strEx::splitEx(description, _T("\n"));
315//                                                      for (std::list<std::wstring>::const_iterator cit = list.begin(); cit != list.end(); ++cit) {
316//                                                              LOG_INFO_CORE_STD(_T("    ") + *cit);
317//                                                      }
318//                                              }
319//                                      }
320//                              }
321//                              LOG_INFO_CORE_STD(_T("Done listing plugins from: ") + pluginPath.string());
322//                              return true;
323//                      } catch (std::exception &e) {
324//                              LOG_ERROR_CORE_STD(_T("Exception: ") + to_wstring(e.what()));
325//                      } catch (...) {
326//                              LOG_ERROR_CORE_STD(_T("Unknown Exception: "));
327//                      }
328//                      return false;
329//              } else if ( wcscasecmp( _T("d"), argv[1]+1 ) == 0 ) {
330//                      // Run command from command line (like NRPE) but with debug enabled
331//              } else if ( wcscasecmp( _T("c"), argv[1]+1 ) == 0 ) {
332//                      // Run command from command line (like NRPE)
333//                      mainClient.enableDebug(false);
334//                      mainClient.initCore(true);
335//                      std::wstring command, args, msg, perf;
336//                      if (argc > 2)
337//                              command = argv[2];
338//                      for (int i=3;i<argc;i++) {
339//                              if (i!=3) args += _T(" ");
340//                              args += argv[i];
341//                      }
342//                      nRetCode = mainClient.inject(command, args, msg, perf);
343//                      std::wcout << msg << _T("|") << perf << std::endl;
344//                      mainClient.exitCore(true);
345//                      return nRetCode;
346//              } else {
347//                      std::wcerr << _T("Usage: -version, -about, -install, -uninstall, -start, -stop, -encrypt -settings") << std::endl;
348//                      std::wcerr << _T("Usage: [-noboot] <ModuleName> <commnd> [arguments]") << std::endl;
349//                      return -1;
350//              }
351//              return nRetCode;
352//      return nRetCode;
353}
354
355std::list<std::wstring> NSClientT::list_commands() {
356        return commands_.list();
357}
358
359bool contains_plugin(NSClientT::plugin_alias_list_type &ret, std::wstring alias, std::wstring plugin) {
360        std::pair<std::wstring,std::wstring> v;
361        BOOST_FOREACH(v, ret.equal_range(alias)) {
362                if (v.second == plugin)
363                        return true;
364        }
365        return false;
366}
367NSClientT::plugin_alias_list_type NSClientT::find_all_plugins(bool active) {
368        plugin_alias_list_type ret;
369
370        settings::string_list list = settings_manager::get_settings()->get_keys(MAIN_MODULES_SECTION);
371        BOOST_FOREACH(std::wstring plugin, list) {
372                std::wstring alias;
373                try {
374                        alias = settings_manager::get_settings()->get_string(MAIN_MODULES_SECTION, plugin);
375                } catch (settings::settings_exception e) {
376                        LOG_DEBUG_CORE_STD(_T("Exception looking for module: ") + e.getMessage());
377                }
378                if (plugin == _T("enabled") || plugin == _T("1")) {
379                        plugin = alias;
380                        alias = _T("");
381                } else if (alias == _T("enabled") || alias == _T("1")) {
382                                alias = _T("");
383                } else if ((active && plugin == _T("disabled")) || (active && alias == _T("disabled")))
384                        continue;
385                else if (plugin == _T("disabled")) {
386                        plugin = alias;
387                        alias = _T("");
388                } else if (alias == _T("disabled")) {
389                        alias = _T("");
390                }
391                if (!alias.empty()) {
392                        std::wstring tmp = plugin;
393                        plugin = alias;
394                        alias = tmp;
395                }
396                if (alias.empty()) {
397                        LOG_DEBUG_CORE_STD(_T("Found: ") + plugin);
398                } else {
399                        LOG_DEBUG_CORE_STD(_T("Found: ") + plugin + _T(" as ") + alias);
400                }
401                if (plugin.length() > 4 && plugin.substr(plugin.length()-4) == _T(".dll"))
402                        plugin = plugin.substr(0, plugin.length()-4);
403                ret.insert(plugin_alias_list_type::value_type(alias, plugin));
404        }
405        if (!active) {
406                boost::filesystem::wpath pluginPath = expand_path(_T("${module-path}"));
407                boost::filesystem::wdirectory_iterator end_itr; // default construction yields past-the-end
408                for ( boost::filesystem::wdirectory_iterator itr( pluginPath ); itr != end_itr; ++itr ) {
409                        if ( !is_directory(itr->status()) ) {
410                                boost::filesystem::wpath file= itr->leaf();
411                                if (is_module(pluginPath  / file) && !contains_plugin(ret, _T(""), file.string()))
412                                        ret.insert(plugin_alias_list_type::value_type(_T(""), file.string()));
413                        }
414                }
415        }
416        return ret;
417}
418
419// NSClientT::plugin_info_list NSClientT::get_all_plugins() {
420//      boost::filesystem::wpath pluginPath = expand_path(_T("${module-path}"));
421//      plugin_alias_list_type plugins = find_all_plugins(false);
422//      plugin_info_list ret;
423//      std::pair<std::wstring,std::wstring> v;
424//
425//      BOOST_FOREACH(v, plugins) {
426//              plugin_info_type info;
427//              info.dll = v.second;
428//              try {
429//                      LOG_DEBUG_STD(_T("Attempting to fake load: ") + v.second + _T(" as ") + v.first);
430//                      NSCPlugin plugin(next_plugin_id_++, pluginPath / v.second, v.first);
431//                      plugin.load_dll();
432//                      plugin.load_plugin(NSCAPI::dontStart);
433//                      info.name = plugin.getName();
434//                      info.description = plugin.getDescription();
435//                      plugin.unload();
436//              } catch (NSPluginException e) {
437//                      LOG_CRITICAL_STD(_T("Error loading: ") + e.file_ + _T(" root cause: ") + e.error_);
438//              } catch (...) {
439//                      LOG_CRITICAL_STD(_T("Unknown Error loading: ") + info.dll);
440//              }
441//              ret.push_back(info);
442//      }
443//      return ret;
444// }
445
446
447void NSClientT::load_all_plugins(int mode) {
448        boost::filesystem::wpath pluginPath;
449        {
450                try {
451                        pluginPath = expand_path(_T("${module-path}"));
452                } catch (std::exception &e) {
453                        LOG_CRITICAL_CORE_STD(_T("Failed to load plugins: ") + to_wstring(e.what()) + _T(" for ") + expand_path(_T("${module-path}")));
454                        return;
455                }
456                plugin_alias_list_type plugins = find_all_plugins(false);
457                std::pair<std::wstring,std::wstring> v;
458
459                BOOST_FOREACH(v, plugins) {
460                        try {
461                                addPlugin(pluginPath / v.second, v.first);
462                        } catch (NSPluginException &e) {
463                                LOG_CRITICAL_CORE_STD(_T("Failed to register plugin: ") + e.what());
464                        } catch (...) {
465                                LOG_CRITICAL_CORE_STD(_T("Failed to register plugin key: ") + v.second);
466                        }
467                }
468        }
469
470        try {
471                loadPlugins(mode);
472        } catch (...) {
473                LOG_ERROR_CORE_STD(_T("Unknown exception loading plugins"));
474        }
475
476//              std::wstring desc;
477//              std::wstring name = v.second;
478//              try {
479//                      NSCPlugin plugin(next_plugin_id_++, pluginPath / v.second, v.first);
480//                      name = plugin.getModule();
481//                      plugin.load_dll();
482//                      plugin.load_plugin(mode);
483//                      desc = plugin.getName() + _T(" - ");
484//                      desc += plugin.getDescription();
485//                      plugin.unload();
486//              } catch (NSPluginException e) {
487//                      desc += _T("unknown module");
488//                      LOG_CRITICAL_STD(_T("Error loading: ") + e.file_ + _T(" root cause: ") + e.error_);
489//              } catch (...) {
490//                      desc += _T("unknown module");
491//                      LOG_CRITICAL_STD(_T("Unknown Error loading: ") + name);
492//              }
493//              try {
494//                      if (v.first.empty() && !settings_manager::get_settings()->has_key(MAIN_MODULES_SECTION, v.second))
495//                              settings_manager::get_core()->register_key(MAIN_MODULES_SECTION, name, settings::settings_core::key_string, desc, desc, _T("disabled"), false);
496//              } catch (...) {
497//                      LOG_CRITICAL_STD(_T("Failed to register plugin key: ") + name);
498//              }
499        }
500
501void NSClientT::session_error(std::string file, unsigned int line, std::wstring msg) {
502        std::string s = nsclient::logger_helper::create_error(file.c_str(), line, msg);
503        reportMessage(s);
504}
505
506void NSClientT::session_info(std::string file, unsigned int line, std::wstring msg) {
507        std::string s = nsclient::logger_helper::create_info(file.c_str(), line, msg);
508        reportMessage(s);
509}
510
511
512
513
514//////////////////////////////////////////////////////////////////////////
515// Service functions
516
517
518struct nscp_settings_provider : public settings_manager::provider_interface {
519        virtual std::wstring expand_path(std::wstring file) {
520                return mainClient.expand_path(file);
521        }
522        virtual void log_fatal_error(std::wstring error) {
523                LOG_CRITICAL_CORE_STD(error);
524        }
525        virtual settings::logger_interface* create_logger() {
526                return new settings_logger();
527        }
528        std::wstring get_data(std::wstring key) {
529                // TODO
530                return _T("");
531        }
532};
533
534
535nscp_settings_provider provider;
536
537namespace sh = nscapi::settings_helper;
538
539/**
540 * Initialize the program
541 * @param boot true if we shall boot all plugins
542 * @param attachIfPossible is true we will attach to a running instance.
543 * @return success
544 * @author mickem
545 */
546bool NSClientT::boot_init() {
547        LOG_INFO_CORE(SERVICE_NAME _T(" booting..."));
548
549        if (!settings_manager::init_settings(&provider, context_)) {
550                return false;
551        }
552        LOG_INFO_CORE(_T("Booted settings subsystem..."));
553
554        bool crash_submit = false;
555        bool crash_archive = false;
556        bool crash_restart = false;
557        std::wstring crash_url, crash_folder, crash_target, log_level;
558        try {
559
560                sh::settings_registry settings(settings_manager::get_proxy());
561
562                settings.add_path_to_settings()
563                        (_T("log"),                     _T("LOG SETTINGS"), _T("Section for configuring the log handling."))
564                        (_T("shared session"),  _T("SHRED SESSION"), _T("Section for configuring the shared session."))
565                        (_T("crash"),                   _T("CRASH HANDLER"), _T("Section for configuring the crash handler."))
566                        ;
567
568                settings.add_key_to_settings(_T("log"))
569                        (_T("level"), sh::wstring_key(&log_level, _T("INFO")),
570                        _T("LOG LEVEL"), _T("Log level to use"))
571                        ;
572
573                settings.add_key_to_settings(_T("shared session"))
574                        (_T("enabled"), sh::bool_key(&enable_shared_session_ , false),
575                        _T("LOG LEVEL"), _T("Log level to use"))
576                        ;
577
578                settings.add_key_to_settings(_T("crash"))
579                        (_T("submit"), sh::bool_key(&crash_submit, false),
580                        _T("SUBMIT CRASHREPORTS"), _T("Submit crash reports to nsclient.org (or your configured submission server)"))
581
582                        (_T("archive"), sh::bool_key(&crash_archive, true),
583                        _T("ARCHIVE CRASHREPORTS"), _T("Archive crash reports in the archive folder"))
584
585                        (_T("restart"), sh::bool_key(&crash_restart, true),
586                        _T("RESTART"), _T("Submit crash reports to nsclient.org (or your configured submission server)"))
587
588                        (_T("restart target"), sh::wstring_key(&crash_target, get_service_control().get_service_name()),
589                        _T("RESTART SERVICE NAME"), _T("The url to submit crash reports to"))
590
591                        (_T("submit url"), sh::wstring_key(&crash_url, CRASH_SUBMIT_URL),
592                        _T("SUBMISSION URL"), _T("The url to submit crash reports to"))
593
594                        (_T("archive folder"), sh::wpath_key(&crash_folder, CRASH_ARCHIVE_FOLDER),
595                        CRASH_ARCHIVE_FOLDER_KEY, _T("The folder to archive crash dumps in"))
596                        ;
597
598                settings.register_all();
599                settings.notify();
600
601        } catch (settings::settings_exception e) {
602                LOG_ERROR_CORE_STD(_T("Could not find settings: ") + e.getMessage());
603        }
604
605#ifdef USE_BREAKPAD
606
607        if (!g_exception_manager) {
608                g_exception_manager = new ExceptionManager(false);
609
610                g_exception_manager->setup_app(to_wstring(APPLICATION_NAME), to_wstring(STRPRODUCTVER), to_wstring(STRPRODUCTDATE));
611
612                if (crash_restart) {
613                        LOG_DEBUG_CORE(_T("On crash: restart: ") + crash_target);
614                        g_exception_manager->setup_restart(crash_target);
615                }
616
617                bool crashHandling = false;
618                if (crash_submit) {
619                        g_exception_manager->setup_submit(false, crash_url);
620                        LOG_DEBUG_CORE(_T("Submitting crash dumps to central server: ") + crash_url);
621                        crashHandling = true;
622                }
623                if (crash_archive) {
624                        g_exception_manager->setup_archive(crash_folder);
625                        LOG_DEBUG_CORE(_T("Archiving crash dumps in: ") + crash_folder);
626                        crashHandling = true;
627                }
628                if (!crashHandling) {
629                        LOG_ERROR_CORE(_T("No crash handling configured"));
630                } else {
631                        //g_exception_manager->StartMonitoring();
632                }
633        }
634#else
635        LOG_ERROR_CORE(_T("Warning Not compiled with google breakpad support!"));
636#endif
637
638
639        if (enable_shared_session_) {
640                LOG_INFO_CORE(_T("shared session not ported yet!..."));
641//              if (boot) {
642//                      LOG_INFO_CORE(_T("shared session not ported yet!..."));
643//                      try {
644//                              shared_server_.reset(new nsclient_session::shared_server_session(this));
645//                              if (!shared_server_->session_exists()) {
646//                                      shared_server_->create_new_session();
647//                              } else {
648//                                      LOG_ERROR_STD(_T("Session already exists cant create a new one!"));
649//                              }
650//                              startTrayIcons();
651//                      } catch (nsclient_session::session_exception e) {
652//                              LOG_ERROR_STD(_T("Failed to create new session: ") + e.what());
653//                              shared_server_.reset(NULL);
654//                      } catch (...) {
655//                              LOG_ERROR_STD(_T("Failed to create new session: Unknown exception"));
656//                              shared_server_.reset(NULL);
657//                      }
658//              } else {
659//                      LOG_INFO_CORE(_T("shared session not ported yet!..."));
660//                      try {
661//                              std::wstring id = _T("_attached_") + strEx::itos(GetCurrentProcessId()) + _T("_");
662//                              shared_client_.reset(new nsclient_session::shared_client_session(id, this));
663//                              if (shared_client_->session_exists()) {
664//                                      shared_client_->attach_to_session(id);
665//                              } else {
666//                                      LOG_ERROR_STD(_T("No session was found cant attach!"));
667//                              }
668//                              LOG_ERROR_STD(_T("Session is: ") + shared_client_->get_client_id());
669//                      } catch (nsclient_session::session_exception e) {
670//                              LOG_ERROR_STD(_T("Failed to attach to session: ") + e.what());
671//                              shared_client_.reset(NULL);
672//                      } catch (...) {
673//                              LOG_ERROR_STD(_T("Failed to attach to session: Unknown exception"));
674//                              shared_client_.reset(NULL);
675//                      }
676//              }
677        }
678#ifdef WIN32
679        try {
680                com_helper_.initialize();
681        } catch (com_helper::com_exception e) {
682                LOG_ERROR_CORE_STD(_T("COM exception: ") + e.getMessage());
683                return false;
684        } catch (...) {
685                LOG_ERROR_CORE(_T("Unknown exception iniating COM..."));
686                return false;
687        }
688#endif
689        return true;
690}
691bool NSClientT::boot_load_all_plugins() {
692        LOG_DEBUG_CORE(_T("booting::loading plugins"));
693        try {
694                boost::filesystem::wpath pluginPath = expand_path(_T("${module-path}"));
695                plugin_alias_list_type plugins = find_all_plugins(true);
696                std::pair<std::wstring,std::wstring> v;
697                BOOST_FOREACH(v, plugins) {
698                        std::wstring file = NSCPlugin::get_plugin_file(v.second);
699                        std::wstring alias = v.first;
700                        if (!alias.empty()) {
701                                LOG_DEBUG_CORE_STD(_T("Processing plugin: ") + file + _T(" as ") + alias);
702                        } else {
703                                LOG_DEBUG_CORE_STD(_T("Processing plugin: ") + file);
704                        }
705                        try {
706                                addPlugin(pluginPath / boost::filesystem::wpath(file), alias);
707                        } catch(const NSPluginException& e) {
708                                LOG_ERROR_CORE_STD(_T("Exception raised: '") + e.error_ + _T("' in module: ") + e.file_);
709                        } catch (std::exception e) {
710                                LOG_ERROR_CORE_STD(_T("exception loading plugin: ") + file + strEx::string_to_wstring(e.what()));
711                                return false;
712                        } catch (...) {
713                                LOG_ERROR_CORE_STD(_T("Unknown exception loading plugin: ") + file);
714                                return false;
715                        }
716                }
717        } catch (settings::settings_exception e) {
718                LOG_ERROR_CORE_STD(_T("Settings exception when loading modules: ") + e.getMessage());
719                return false;
720        } catch (...) {
721                LOG_ERROR_CORE_STD(_T("Unknown exception when loading plugins"));
722                return false;
723        }
724        return true;
725}
726
727bool NSClientT::boot_load_plugin(std::wstring plugin) {
728        try {
729                if (plugin.length() > 4 && plugin.substr(plugin.length()-4) == _T(".dll"))
730                        plugin = plugin.substr(0, plugin.length()-4);
731
732                std::wstring plugin_file = NSCPlugin::get_plugin_file(plugin);
733                boost::filesystem::wpath pluginPath = expand_path(_T("${module-path}"));
734                boost::filesystem::wpath file = pluginPath / plugin_file;
735                if (boost::filesystem::is_regular(file)) {
736                        plugin_type plugin = addPlugin(file, _T(""));
737                } else {
738                        LOG_ERROR_CORE_STD(_T("Failed to load: ") + std::wstring(plugin));
739                        return false;
740                }
741        } catch (const NSPluginException &e) {
742                LOG_ERROR_CORE_STD(_T("Module (") + e.file_ + _T(") was not found: ") + e.error_);
743                return false;
744        } catch(const std::exception &e) {
745                LOG_ERROR_CORE_STD(_T("Module (") + plugin + _T(") was not found: ") + utf8::to_unicode(e.what()));
746                return false;
747        } catch(...) {
748                LOG_ERROR_CORE_STD(_T("Module (") + plugin + _T(") was not found..."));
749                return false;
750        }
751        return true;
752}
753bool NSClientT::boot_start_plugins(bool boot) {
754        try {
755                loadPlugins(boot?NSCAPI::normalStart:NSCAPI::dontStart);
756        } catch (...) {
757                LOG_ERROR_CORE_STD(_T("Unknown exception loading plugins"));
758                return false;
759        }
760        LOG_DEBUG_CORE_STD(APPLICATION_NAME _T(" - ") CURRENT_SERVICE_VERSION _T(" Started!"));
761        return true;
762}
763
764void NSClientT::startTrayIcons() {
765//      if (shared_server_.get() == NULL) {
766//              LOG_MESSAGE_STD(_T("No master session so tray icons not started"));
767//              return;
768//      }
769//      remote_processes::PWTS_SESSION_INFO list;
770//      DWORD count;
771//      if (!remote_processes::_WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE , 0, 1, &list, &count)) {
772//              LOG_ERROR_STD(_T("Failed to enumerate sessions:" ) + error::lookup::last_error());
773//      } else {
774//              LOG_DEBUG_STD(_T("Found ") + strEx::itos(count) + _T(" sessions"));
775//              for (DWORD i=0;i<count;i++) {
776//                      LOG_DEBUG_STD(_T("Found session: ") + strEx::itos(list[i].SessionId) + _T(" state: ") + strEx::itos(list[i].State));
777//                      if (list[i].State == remote_processes::_WTS_CONNECTSTATE_CLASS::WTSActive) {
778//                              startTrayIcon(list[i].SessionId);
779//                      }
780//              }
781//      }
782}
783void NSClientT::startTrayIcon(DWORD dwSessionId) {
784//      if (shared_server_.get() == NULL) {
785//              LOG_MESSAGE_STD(_T("No master session so tray icons not started"));
786//              return;
787//      }
788//      if (!shared_server_->re_attach_client(dwSessionId)) {
789//              if (!tray_starter::start(dwSessionId)) {
790//                      LOG_ERROR_STD(_T("Failed to start session (") + strEx::itos(dwSessionId) + _T("): " ) + error::lookup::last_error());
791//              }
792//      }
793}
794
795bool NSClientT::stop_unload_plugins_pre() {
796        LOG_DEBUG_CORE(_T("Attempting to stop all plugins"));
797        try {
798                LOG_DEBUG_CORE(_T("Stopping: NON Message Handling Plugins"));
799                mainClient.unloadPlugins(false);
800        } catch(NSPluginException e) {
801                LOG_ERROR_CORE_STD(_T("Exception raised when unloading non msg plguins: ") + e.error_ + _T(" in module: ") + e.file_);
802        } catch(...) {
803                LOG_ERROR_CORE_STD(_T("Unknown exception raised when unloading non msg plugins"));
804        }
805        return true;
806}
807bool NSClientT::stop_exit_pre() {
808#ifdef WIN32
809        LOG_DEBUG_CORE(_T("Stopping: COM helper"));
810        try {
811                com_helper_.unInitialize();
812        } catch (com_helper::com_exception e) {
813                LOG_ERROR_CORE_STD(_T("COM exception: ") + e.getMessage());
814        } catch (...) {
815                LOG_ERROR_CORE_STD(_T("Unknown exception uniniating COM..."));
816        }
817#endif
818        /*
819        LOG_DEBUG_STD(_T("Stopping: Socket Helpers"));
820        try {
821                simpleSocket::WSACleanup();
822        } catch (simpleSocket::SocketException e) {
823                LOG_ERROR_STD(_T("Socket exception: ") + e.getMessage());
824        } catch (...) {
825                LOG_ERROR_STD(_T("Unknown exception uniniating socket..."));
826        }
827        */
828        LOG_DEBUG_CORE(_T("Stopping: Settings instance"));
829        settings_manager::destroy_settings();
830//      try {
831//              if (shared_client_.get() != NULL) {
832//                      LOG_DEBUG_STD(_T("Stopping: shared client"));
833//                      shared_client_->set_handler(NULL);
834//                      shared_client_->close_session();
835//              }
836//      } catch(nsclient_session::session_exception &e) {
837//              LOG_ERROR_STD(_T("Exception closing shared client session: ") + e.what());
838//      } catch(...) {
839//              LOG_ERROR_STD(_T("Exception closing shared client session: Unknown exception!"));
840//      }
841        try {
842//              if (shared_server_.get() != NULL) {
843//                      LOG_DEBUG_STD(_T("Stopping: shared server"));
844//                      shared_server_->set_handler(NULL);
845//                      shared_server_->close_session();
846//              }
847        } catch(...) {
848                LOG_ERROR_CORE_STD(_T("UNknown exception raised: When closing shared session"));
849        }
850        return true;
851}
852bool NSClientT::stop_unload_plugins_post() {
853        try {
854                LOG_DEBUG_CORE(_T("Stopping: Message handling Plugins"));
855                mainClient.unloadPlugins(true);
856        } catch(NSPluginException e) {
857                LOG_ERROR_CORE_STD(_T("Exception raised when unloading msg plugins: ") + e.error_ + _T(" in module: ") + e.file_);
858        } catch(...) {
859                LOG_ERROR_CORE_STD(_T("UNknown exception raised: When stopping message plguins"));
860        }
861        return true;
862}
863bool NSClientT::stop_exit_post() {
864        try {
865                logger_master_.stop_slave();
866        } catch(...) {
867                LOG_ERROR_CORE_STD(_T("UNknown exception raised: When closing shared session"));
868        }
869        return true;
870}
871
872void NSClientT::service_on_session_changed(unsigned long dwSessionId, bool logon, unsigned long dwEventType) {
873//      if (shared_server_.get() == NULL) {
874//              LOG_DEBUG_STD(_T("No shared session: ignoring change event!"));
875//              return;
876//      }
877//      LOG_DEBUG_CORE_STD(_T("Got session change: ") + strEx::itos(dwSessionId));
878//      if (!logon) {
879//              LOG_DEBUG_CORE_STD(_T("Not a logon event: ") + strEx::itos(dwEventType));
880//              return;
881//      }
882//      tray_starter::start(dwSessionId);
883}
884
885//////////////////////////////////////////////////////////////////////////
886// Member functions
887
888
889
890/**
891 * Unload all plug-ins (in reversed order)
892 */
893void NSClientT::unloadPlugins(bool unloadLoggers) {
894        if (unloadLoggers)
895        {
896                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
897                if (!writeLock.owns_lock()) {
898                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (003)."));
899                        return;
900                }
901                logger_master_.remove_all_plugins();
902        }
903        {
904                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
905                if (!readLock.owns_lock()) {
906                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (004)."));
907                        return;
908                }
909                for (pluginList::reverse_iterator it = plugins_.rbegin(); it != plugins_.rend(); ++it) {
910                        plugin_type p = *it;
911                        if (!p)
912                                continue;
913                        try {
914                                if (unloadLoggers || !p->hasMessageHandler()) {
915                                        LOG_DEBUG_CORE_STD(_T("Unloading plugin: ") + p->getModule() + _T("..."));
916                                        p->unload_plugin();
917                                } else {
918                                        LOG_DEBUG_CORE_STD(_T("Skipping log plugin: ") + p->getModule() + _T("..."));
919                                }
920                        } catch(NSPluginException e) {
921                                LOG_ERROR_CORE_STD(_T("Exception raised when unloading plugin: ") + e.error_ + _T(" in module: ") + e.file_);
922                        } catch(...) {
923                                LOG_ERROR_CORE_STD(_T("Unknown exception raised when unloading plugin"));
924                        }
925                }
926        }
927        {
928                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
929                if (!writeLock.owns_lock()) {
930                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (005)."));
931                        return;
932                }
933                commands_.remove_all();
934                for (pluginList::iterator it = plugins_.begin(); it != plugins_.end();) {
935                        plugin_type p = (*it);
936                        try {
937                                if (!p && (unloadLoggers|| !p->isLoaded())) {
938                                        it = plugins_.erase(it);
939                                        //delete p;
940                                        continue;
941                                }
942                        } catch(NSPluginException e) {
943                                LOG_ERROR_CORE_STD(_T("Exception raised when unloading plugin: ") + e.error_ + _T(" in module: ") + e.file_);
944                        } catch(...) {
945                                LOG_ERROR_CORE(_T("Unknown exception raised when unloading plugin"));
946                        }
947                        it++;
948                }
949        }
950}
951
952NSCAPI::errorReturn NSClientT::reload(const std::wstring module) {
953        if (module == _T("service")) {
954                try {
955                        stop_unload_plugins_pre();
956                        stop_unload_plugins_post();
957
958                        boot_load_all_plugins();
959                        boot_start_plugins(true);
960                        return NSCAPI::isSuccess;
961                } catch(const std::exception &e) {
962                        LOG_ERROR_CORE_STD(_T("Exception raised when reloading: ") + utf8::to_unicode(e.what()));
963                } catch(...) {
964                        LOG_ERROR_CORE_STD(_T("Exception raised when reloading: UNKNOWN"));
965                }
966        } else {
967                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
968                if (!writeLock.owns_lock()) {
969                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (007a)."));
970                        return NSCAPI::hasFailed;
971                }
972
973                BOOST_FOREACH(plugin_type &p, plugins_) {
974                        if (p->get_alias() == module) {
975                                LOG_DEBUG_CORE_STD(_T("Found module: ") + module + _T(", reloading..."));
976                                p->unload_plugin();
977                                p->load_plugin(NSCAPI::normalStart);
978                                return NSCAPI::isSuccess;
979                        }
980                }
981        }
982        return NSCAPI::hasFailed;
983}
984
985void NSClientT::loadPlugins(NSCAPI::moduleLoadMode mode) {
986        bool hasBroken = false;
987        {
988                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
989                if (!readLock.owns_lock()) {
990                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (006)."));
991                        return;
992                }
993                for (pluginList::iterator it=plugins_.begin(); it != plugins_.end();) {
994                        LOG_DEBUG_CORE_STD(_T("Loading plugin: ") + (*it)->get_description());
995                        try {
996                                if (!(*it)->load_plugin(mode)) {
997                                        LOG_ERROR_CORE_STD(_T("Plugin refused to load: ") + (*it)->getModule());
998                                        it = plugins_.erase(it);
999                                } else
1000                                        ++it;
1001                        } catch (NSPluginException e) {
1002                                it = plugins_.erase(it);
1003                                LOG_ERROR_CORE_STD(_T("Could not load plugin: ") + e.file_ + _T(": ") + e.error_);
1004                        } catch (...) {
1005                                it = plugins_.erase(it);
1006                                LOG_ERROR_CORE_STD(_T("Could not load plugin: ") + (*it)->getModule());
1007                        }
1008                }
1009        }
1010        logger_master_.all_plugins_loaded();
1011}
1012/**
1013 * Load and add a plugin to various internal structures
1014 * @param plugin The plug-in instance to load. The pointer is managed by the
1015 */
1016NSClientT::plugin_type NSClientT::addPlugin(boost::filesystem::wpath file, std::wstring alias) {
1017        {
1018                LOG_DEBUG_CORE_STD(_T("addPlugin(") + file.string() + _T(" as ") + alias + _T(")"));
1019                // Check if this is a duplicate plugin (if so return that instance)
1020                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
1021                if (!writeLock.owns_lock()) {
1022                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (007a)."));
1023                        return plugin_type();
1024                }
1025
1026                BOOST_FOREACH(plugin_type plug, plugins_) {
1027                        if (plug->is_duplicate(file, alias)) {
1028                                LOG_DEBUG_CORE_STD(_T("Found duplicate plugin returning old ") + to_wstring(plug->get_id()));
1029                                return plug;
1030                        }
1031                }
1032
1033        }
1034
1035
1036        plugin_type plugin(new NSCPlugin(next_plugin_id_++, file, alias));
1037        plugin->load_dll();
1038        {
1039                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
1040                if (!writeLock.owns_lock()) {
1041                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (007b)."));
1042                        return plugin;
1043                }
1044
1045                plugins_.insert(plugins_.end(), plugin);
1046                if (plugin->hasCommandHandler())
1047                        commands_.add_plugin(plugin);
1048                if (plugin->hasNotificationHandler())
1049                        channels_.add_plugin(plugin);
1050                if (plugin->hasMessageHandler())
1051                        logger_master_.add_plugin(plugin);
1052                if (plugin->has_routing_handler())
1053                        routers_.add_plugin(plugin);
1054                settings_manager::get_core()->register_key(_T("/modules"), plugin->getModule(), settings::settings_core::key_string, plugin->getName(), plugin->getDescription(), _T(""), false);
1055                // TODO add comments elsewhere to the settings store for all loaded modules...
1056        }
1057        return plugin;
1058}
1059
1060
1061std::wstring NSClientT::describeCommand(std::wstring command) {
1062        return commands_.describe(command);
1063}
1064std::list<std::wstring> NSClientT::getAllCommandNames() {
1065        return commands_.list();
1066}
1067void NSClientT::registerCommand(unsigned int id, std::wstring cmd, std::wstring desc) {
1068        return commands_.register_command(id, cmd, desc);
1069}
1070
1071NSCAPI::nagiosReturn NSClientT::inject(std::wstring command, std::wstring arguments, std::wstring &msg, std::wstring & perf) {
1072        /*if (shared_client_.get() != NULL && shared_client_->hasMaster()) {
1073                try {
1074                        return shared_client_->inject(command, arguments, splitter, escape, msg, perf);
1075                } catch (nsclient_session::session_exception &e) {
1076                        LOG_ERROR_STD(_T("Failed to inject remote command: ") + e.what());
1077                        return NSCAPI::returnCRIT;
1078                } catch (...) {
1079                        LOG_ERROR_STD(_T("Failed to inject remote command: Unknown exception"));
1080                        return NSCAPI::returnCRIT;
1081                }
1082        } else */{
1083
1084                std::list<std::wstring> args;
1085                strEx::parse_command(arguments, args);
1086                std::string request, response;
1087                nscapi::functions::create_simple_query_request(command, args, request);
1088                NSCAPI::nagiosReturn ret = injectRAW(command.c_str(), request, response);
1089                if (response.empty()) {
1090                        LOG_ERROR_CORE(_T("No data retutned from command"));
1091                        return NSCAPI::returnUNKNOWN;
1092                }
1093                nscapi::functions::parse_simple_query_response(response, msg, perf);
1094                return ret;
1095        }
1096}
1097
1098/**
1099 * Inject a command into the plug-in stack.
1100 *
1101 * @param command Command to inject
1102 * @param argLen Length of argument buffer
1103 * @param **argument Argument buffer
1104 * @param *returnMessageBuffer Message buffer
1105 * @param returnMessageBufferLen Length of returnMessageBuffer
1106 * @param *returnPerfBuffer Performance data buffer
1107 * @param returnPerfBufferLen Length of returnPerfBuffer
1108 * @return The command status
1109 */
1110NSCAPI::nagiosReturn NSClientT::injectRAW(const wchar_t* raw_command, std::string &request, std::string &response) {
1111        std::wstring cmd = nsclient::commands::make_key(raw_command);
1112        if (logDebug()) {
1113                LOG_DEBUG_CORE_STD(_T("Injecting: ") + cmd + _T("..."));
1114        }
1115        /*if (shared_client_.get() != NULL && shared_client_->hasMaster()) {
1116                try {
1117                        std::wstring msg, perf;
1118                        int returnCode = shared_client_->inject(command, arrayBuffer::arrayBuffer2string(argument, argLen, _T(" ")), L' ', true, msg, perf);
1119                        NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, msg, returnCode);
1120                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, perf, returnCode);
1121                } catch (nsclient_session::session_exception &e) {
1122                        LOG_ERROR_STD(_T("Failed to inject remote command: ") + e.what());
1123                        int returnCode = NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, _T("Failed to inject remote command: ") + e.what(), NSCAPI::returnCRIT);
1124                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, _T(""), returnCode);
1125                } catch (...) {
1126                        LOG_ERROR_STD(_T("Failed to inject remote command: Unknown exception"));
1127                        int returnCode = NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, _T("Failed to inject remote command:  + e.what()"), NSCAPI::returnCRIT);
1128                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, _T(""), returnCode);
1129                }
1130        } else */{
1131                try {
1132                        nsclient::commands::plugin_type plugin = commands_.get(cmd);
1133                        if (!plugin) {
1134                                LOG_ERROR_CORE(_T("No handler for command: ") + cmd + _T(" avalible commands: ") + commands_.to_wstring());
1135                                return NSCAPI::returnIgnored;
1136                        }
1137                        NSCAPI::nagiosReturn c = plugin->handleCommand(cmd.c_str(), request, response);
1138                        LOG_DEBUG_CORE_STD(_T("Result ") + cmd + _T(": ") + nscapi::plugin_helper::translateReturn(c));
1139                        return c;
1140                } catch (nsclient::commands::command_exception &e) {
1141                        LOG_ERROR_CORE(_T("No handler for command: ") + cmd + _T(": ") + to_wstring(e.what()));
1142                        return NSCAPI::returnIgnored;
1143                } catch (...) {
1144                        LOG_ERROR_CORE(_T("Error handling command: ") + cmd);
1145                        return NSCAPI::returnIgnored;
1146                }
1147        }
1148}
1149
1150
1151int NSClientT::load_and_run(std::wstring module, run_function fun, std::list<std::wstring> &errors) {
1152        int ret = -1;
1153        bool found = false;
1154        {
1155                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(5));
1156                if (!readLock.owns_lock()) {
1157                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (001)."));
1158                        return -1;
1159                }
1160                BOOST_FOREACH(plugin_type plugin, plugins_) {
1161                        if (plugin && (module.empty() || plugin->getModule() == module)) {
1162                                LOG_DEBUG_CORE_STD(_T("Found module: ") + plugin->getName() + _T("..."));
1163                                try {
1164                                        ret = fun(plugin);
1165                                        found = true;
1166                                } catch (const NSPluginException &e) {
1167                                        errors.push_back(_T("Could not execute command: ") + e.error_ + _T(" in ") + e.file_);
1168                                        return -1;
1169                                }
1170                        }
1171                }
1172        }
1173        if (!found && !module.empty()) {
1174                try {
1175                        boost::filesystem::wpath file = NSCPlugin::get_filename(getBasePath() / boost::filesystem::wpath(_T("modules")), module);
1176                        if (boost::filesystem::is_regular(file)) {
1177                                plugin_type plugin = addPlugin(file, _T(""));
1178                                if (plugin) {
1179                                        LOG_DEBUG_CORE_STD(_T("Loading plugin: ") + plugin->getName() + _T("..."));
1180                                        plugin->load_plugin(NSCAPI::dontStart);
1181                                        ret = fun(plugin);
1182                                } else {
1183                                        errors.push_back(_T("Failed to load: ") + std::wstring(module));
1184                                        return 1;
1185                                }
1186                        } else {
1187                                errors.push_back(_T("Failed to load: ") + std::wstring(module));
1188                                return 1;
1189                        }
1190                } catch (const NSPluginException &e) {
1191                        errors.push_back(_T("Module (") + e.file_ + _T(") was not found: ") + e.error_);
1192                } catch(const std::exception &e) {
1193                        errors.push_back(_T("Module (") + module + _T(") was not found: ") + utf8::cvt<std::wstring>(e.what()));
1194                        return 1;
1195                } catch(...) {
1196                        errors.push_back(_T("Module (") + module + _T(") was not found..."));
1197                        return 1;
1198                }
1199        }
1200        return ret;
1201}
1202
1203int exec_helper(NSClientT::plugin_type plugin, std::wstring command, std::vector<std::wstring> arguments, std::string request, std::list<std::string> *responses) {
1204        std::string response;
1205        if (!plugin || !plugin->has_command_line_exec())
1206                return -1;
1207        int ret = plugin->commandLineExec(command.c_str(), request, response);
1208        if (ret != NSCAPI::returnIgnored && !response.empty())
1209                responses->push_back(response);
1210        return ret;
1211}
1212
1213int NSClientT::simple_exec(std::wstring module, std::wstring command, std::vector<std::wstring> arguments, std::list<std::wstring> &resp) {
1214        std::string request;
1215        std::list<std::string> responses;
1216        std::list<std::wstring> errors;
1217        nscapi::functions::create_simple_exec_request(command, arguments, request);
1218        int ret = load_and_run(module, boost::bind(&exec_helper, _1, command, arguments, request, &responses), errors);
1219
1220        BOOST_FOREACH(std::string &r, responses) {
1221                try {
1222                        nscapi::functions::parse_simple_exec_result(r, resp);
1223                } catch (std::exception &e) {
1224                        resp.push_back(_T("Failed to extract return message: ") + utf8::cvt<std::wstring>(e.what()));
1225                        LOG_ERROR_CORE_STD(resp.back());
1226                        return NSCAPI::returnUNKNOWN;
1227                }
1228        }
1229        BOOST_FOREACH(const std::wstring &e, errors) {
1230                LOG_ERROR_CORE_STD(e);
1231                resp.push_back(e);
1232        }
1233        return ret;
1234}
1235int query_helper(NSClientT::plugin_type plugin, std::wstring command, std::vector<std::wstring> arguments, std::string request, std::list<std::string> *responses) {
1236        return NSCAPI::returnIgnored;
1237//      std::string response;
1238//      if (!plugin->hasCommandHandler())
1239//              return NSCAPI::returnIgnored;
1240//      int ret = plugin->handleCommand(command.c_str(), request, response);
1241//      if (ret != NSCAPI::returnIgnored && !response.empty())
1242//              responses->push_back(response);
1243//      return ret;
1244}
1245
1246int NSClientT::simple_query(std::wstring module, std::wstring command, std::vector<std::wstring> arguments, std::list<std::wstring> &resp) {
1247        std::string request;
1248        std::list<std::string> responses;
1249        std::list<std::wstring> errors;
1250        nscapi::functions::create_simple_query_request(command, arguments, request);
1251        int ret = load_and_run(module, boost::bind(&query_helper, _1, command, arguments, request, &responses), errors);
1252
1253        nsclient::commands::plugin_type plugin = commands_.get(command);
1254        if (!plugin) {
1255                LOG_ERROR_CORE(_T("No handler for command: ") + command + _T(" avalible commands: ") + commands_.to_wstring());
1256                return NSCAPI::returnUNKNOWN;
1257        }
1258        std::string response;
1259        NSCAPI::nagiosReturn c = plugin->handleCommand(command.c_str(), request, response);
1260        try {
1261                std::wstring msg, perf;
1262                nscapi::functions::parse_simple_query_response(response, msg, perf);
1263                resp.push_back(msg + _T("|") + perf);
1264        } catch (std::exception &e) {
1265                resp.push_back(_T("Failed to extract return message: ") + utf8::cvt<std::wstring>(e.what()));
1266                LOG_ERROR_CORE_STD(resp.back());
1267                return NSCAPI::returnUNKNOWN;
1268        }
1269        BOOST_FOREACH(const std::wstring &e, errors) {
1270                LOG_ERROR_CORE_STD(e);
1271                resp.push_back(e);
1272        }
1273        return ret;
1274}
1275
1276NSCAPI::nagiosReturn NSClientT::exec_command(const wchar_t* raw_target, const wchar_t* raw_command, std::string &request, std::string &response) {
1277        std::wstring target = raw_target;
1278        bool match_any = false;
1279        bool match_all = false;
1280        bool has_match = false;
1281        if (target == _T("any"))
1282                match_any = true;
1283        else if (target == _T("all") || target == _T("*"))
1284                match_all = true;
1285        std::list<std::string> responses;
1286        bool found = false;
1287        {
1288                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(5));
1289                if (!readLock.owns_lock()) {
1290                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (001)."));
1291                        return -1;
1292                }
1293                BOOST_FOREACH(plugin_type p, plugins_) {
1294                        if (p && p->has_command_line_exec()) {
1295                                try {
1296                                        if (match_all || match_any || p->get_alias() == target) {
1297                                                std::string respbuffer;
1298                                                NSCAPI::nagiosReturn r = p->commandLineExec(raw_command, request, respbuffer);
1299                                                if (r != NSCAPI::returnIgnored && !respbuffer.empty()) {
1300                                                        LOG_DEBUG_CORE_STD(_T("Got response from: ") + p->getName());
1301                                                        found = true;
1302                                                        if (match_any) {
1303                                                                response = respbuffer;
1304                                                                return NSCAPI::returnOK;
1305                                                        }
1306                                                        responses.push_back(respbuffer);
1307                                                }
1308                                        }
1309                                } catch (NSPluginException e) {
1310                                        LOG_ERROR_CORE_STD(_T("Could not execute command: ") + e.error_ + _T(" in ") + e.file_);
1311                                }
1312                        }
1313                }
1314        }
1315
1316        Plugin::ExecuteResponseMessage response_message;
1317        nscapi::functions::create_simple_header(response_message.mutable_header());
1318
1319        BOOST_FOREACH(std::string r, responses) {
1320                Plugin::ExecuteResponseMessage tmp;
1321                tmp.ParseFromString(r);
1322                for (int i=0;i<tmp.payload_size();i++) {
1323                        Plugin::ExecuteResponseMessage::Response *r = response_message.add_payload();
1324                        r->CopyFrom(tmp.payload(i));
1325                }
1326        }
1327        response_message.SerializeToString(&response);
1328        if (found)
1329                return NSCAPI::returnOK;
1330        return NSCAPI::returnIgnored;
1331}
1332
1333
1334NSCAPI::errorReturn NSClientT::reroute(std::wstring &channel, std::string &buffer) {
1335        BOOST_FOREACH(nsclient::plugin_type p, routers_.get(channel)) {
1336                wchar_t *new_channel_buffer;
1337                char *new_buffer;
1338                unsigned int new_buffer_len;
1339                int status = p->route_message(channel.c_str(), buffer.c_str(), buffer.size(), &new_channel_buffer, &new_buffer, &new_buffer_len);
1340                if ((status&NSCAPI::message_modified) == NSCAPI::message_modified) {
1341                        buffer = std::string(new_buffer, new_buffer_len);
1342                        p->deleteBuffer(&new_buffer);
1343                }
1344                if ((status&NSCAPI::message_routed) == NSCAPI::message_routed) {
1345                        channel = new_channel_buffer;
1346                        //p->deleteBuffer(new_channel_buffer);
1347                        return NSCAPI::message_routed;
1348                }
1349                if ((status&NSCAPI::message_ignored) == NSCAPI::message_ignored)
1350                        return NSCAPI::message_ignored;
1351                if ((status&NSCAPI::message_digested) == NSCAPI::message_digested)
1352                        return NSCAPI::message_ignored;
1353        }
1354        return NSCAPI::isfalse;
1355}
1356
1357NSCAPI::errorReturn NSClientT::register_submission_listener(unsigned int plugin_id, const wchar_t* channel) {
1358        channels_.register_listener(plugin_id, channel);
1359        return NSCAPI::isSuccess;
1360}
1361NSCAPI::errorReturn NSClientT::register_routing_listener(unsigned int plugin_id, const wchar_t* channel) {
1362        routers_.register_listener(plugin_id, channel);
1363        return NSCAPI::isSuccess;
1364}
1365
1366NSCAPI::errorReturn NSClientT::send_notification(const wchar_t* channel, std::string &request, std::string &response) {
1367        boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
1368        if (!readLock.owns_lock()) {
1369                LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (009)."));
1370                return NSCAPI::hasFailed;
1371        }
1372
1373        std::wstring schannel = channel;
1374        try {
1375                int count = 0;
1376                while (reroute(schannel, request)==NSCAPI::message_routed && count++ <= 10) {
1377                        LOG_DEBUG_CORE_STD(_T("Re-routing message to: ") + schannel);
1378                }
1379                if (count >= 10) {
1380                        LOG_ERROR_CORE(_T("More then 10 routes, discarding message..."));
1381                        return NSCAPI::hasFailed;
1382                }
1383        } catch (nsclient::plugins_list_exception &e) {
1384                LOG_ERROR_CORE(_T("Error routing channel: ") + std::wstring(channel) + _T(": ") + to_wstring(e.what()) + _T("Current channels: ") + channels_.to_wstring());
1385                return NSCAPI::hasFailed;
1386        } catch (...) {
1387                LOG_ERROR_CORE(_T("Error routing channel: ") + std::wstring(channel));
1388                return NSCAPI::hasFailed;
1389        }
1390
1391        try {
1392                //LOG_ERROR_CORE_STD(_T("Notifying: ") + strEx::strip_hex(to_wstring(std::string(result,result_len))));
1393                bool found = false;
1394                BOOST_FOREACH(nsclient::plugin_type p, channels_.get(schannel)) {
1395                        p->handleNotification(schannel.c_str(), request, response);
1396                        found = true;
1397                }
1398                if (!found) {
1399                        LOG_ERROR_CORE_STD(_T("No one listens for events from: ") + schannel + _T(" (") + std::wstring(channel) + _T(")"));
1400                        return NSCAPI::hasFailed;
1401                }
1402                return NSCAPI::isSuccess;
1403        } catch (nsclient::plugins_list_exception &e) {
1404                LOG_ERROR_CORE(_T("No handler for channel: ") + std::wstring(channel) + _T(": ") + to_wstring(e.what()));
1405                return NSCAPI::hasFailed;
1406        } catch (...) {
1407                LOG_ERROR_CORE(_T("Error handling channel: ") + std::wstring(channel));
1408                return NSCAPI::hasFailed;
1409        }
1410}
1411
1412void NSClientT::listPlugins() {
1413        boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
1414        if (!readLock.owns_lock()) {
1415                LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (010)."));
1416                return;
1417        }
1418        for (pluginList::iterator it=plugins_.begin(); it != plugins_.end(); ++it) {
1419                try {
1420                        if ((*it)->isBroken()) {
1421                                std::wcout << (*it)->getModule() << _T(": ") << _T("broken") << std::endl;
1422                        } else {
1423                                std::wcout << (*it)->getModule() << _T(": ") << (*it)->getName() << std::endl;
1424                        }
1425                } catch (NSPluginException e) {
1426                        LOG_ERROR_CORE_STD(_T("Could not load plugin: ") + e.file_ + _T(": ") + e.error_);
1427                }
1428        }
1429
1430}
1431
1432bool NSClientT::logDebug() {
1433        if (debug_ == log_state_unknown) {
1434                debug_ = log_state_looking;
1435                try {
1436                        if (settings_manager::get_settings_no_wait()->get_bool(_T("log"), _T("debug"), false) == 1)
1437                                debug_ = log_state_debug;
1438                        else
1439                                debug_ = log_state_nodebug;
1440                } catch (settings::settings_exception e) {
1441                        debug_ = log_state_unknown;
1442                        return false;
1443                }
1444        } else if (debug_ == log_state_looking)
1445                return false;
1446        return (debug_ == log_state_debug);
1447}
1448
1449/**
1450 * Report a message to all logging enabled modules.
1451 *
1452 * @param msgType Message type
1453 * @param file Filename generally __FILE__
1454 * @param line  Line number, generally __LINE__
1455 * @param message The message as a human readable string.
1456 */
1457void NSClientT::reportMessage(std::string data) {
1458        try {
1459                logger_master_.log(data);
1460        } catch (...) {
1461                logger_master_.log_fatal_error("Caught UNKNOWN Exception when trying to log a message");
1462        }
1463}
1464boost::filesystem::wpath NSClientT::getBasePath(void) {
1465        boost::unique_lock<boost::timed_mutex> lock(internalVariables, boost::get_system_time() + boost::posix_time::seconds(5));
1466        if (!lock.owns_lock()) {
1467                LOG_ERROR_CORE(_T("FATAL ERROR: Could not get mutex."));
1468                return _T("FATAL ERROR");
1469        }
1470        if (!basePath.empty())
1471                return basePath;
1472        unsigned int buf_len = 4096;
1473#ifdef WIN32
1474        wchar_t* buffer = new wchar_t[buf_len+1];
1475        GetModuleFileName(NULL, buffer, buf_len);
1476        std::wstring path = buffer;
1477        std::wstring::size_type pos = path.rfind('\\');
1478        basePath = path.substr(0, pos) + _T("\\");
1479        delete [] buffer;
1480#else
1481        basePath = to_wstring(boost::filesystem::initial_path().string());
1482#endif
1483        try {
1484                settings_manager::get_core()->set_base(basePath);
1485        } catch (settings::settings_exception e) {
1486                LOG_ERROR_CORE_STD(_T("Failed to set settings file: ") + e.getMessage());
1487        } catch (...) {
1488                LOG_ERROR_CORE_STD(_T("Failed to set settings file"));
1489        }
1490        return basePath;
1491}
1492
1493
1494std::wstring Encrypt(std::wstring str, unsigned int algorithm) {
1495        unsigned int len = 0;
1496        NSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
1497        len+=2;
1498        wchar_t *buf = new wchar_t[len+1];
1499        NSCAPI::errorReturn ret = NSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
1500        if (ret == NSCAPI::isSuccess) {
1501                std::wstring ret = buf;
1502                delete [] buf;
1503                return ret;
1504        }
1505        return _T("");
1506}
1507std::wstring Decrypt(std::wstring str, unsigned int algorithm) {
1508        unsigned int len = 0;
1509        NSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
1510        len+=2;
1511        wchar_t *buf = new wchar_t[len+1];
1512        NSCAPI::errorReturn ret = NSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
1513        if (ret == NSCAPI::isSuccess) {
1514                std::wstring ret = buf;
1515                delete [] buf;
1516                return ret;
1517        }
1518        return _T("");
1519}
1520
1521void NSClientT::nsclient_log_error(std::string file, int line, std::wstring error) {
1522        std::string s = nsclient::logger_helper::create_error(file, line, error);
1523        reportMessage(s.c_str());
1524}
1525
1526
1527
1528// Service API
1529NSClient* NSClientT::get_global_instance() {
1530        return &mainClient;
1531}
1532void NSClientT::handle_startup(std::wstring service_name) {
1533        service_name_ = service_name;
1534        boot_init();
1535        boot_load_all_plugins();
1536        boot_start_plugins(true);
1537/*
1538        DWORD dwSessionId = remote_processes::getActiveSessionId();
1539        if (dwSessionId != 0xFFFFFFFF)
1540                tray_starter::start(dwSessionId);
1541        else
1542                LOG_ERROR_STD(_T("Failed to start tray helper:" ) + error::lookup::last_error());
1543                */
1544}
1545void NSClientT::handle_shutdown(std::wstring service_name) {
1546        stop_unload_plugins_pre();
1547        stop_exit_pre();
1548        stop_unload_plugins_post();
1549        stop_exit_post();
1550}
1551
1552NSClientT::service_controller NSClientT::get_service_control() {
1553        return service_controller(service_name_);
1554}
1555
1556void NSClientT::service_controller::stop() {
1557#ifdef WIN32
1558        serviceControll::StopNoWait(get_service_name());
1559#endif
1560}
1561void NSClientT::service_controller::start() {
1562#ifdef WIN32
1563        serviceControll::Start(get_service_name());
1564#endif
1565}
1566bool NSClientT::service_controller::is_started() {
1567#ifdef WIN32
1568        try {
1569                if (serviceControll::isStarted(get_service_name())) {
1570                        return true;
1571                }
1572        } catch (...) {
1573                return false;
1574        }
1575#endif
1576        return false;
1577}
1578
1579std::wstring NSClientT::expand_path(std::wstring file) {
1580        strEx::replace(file, _T("${certificate-path}"), _T("${shared-path}/security"));
1581        strEx::replace(file, _T("${module-path}"), _T("${shared-path}/modules"));
1582       
1583        strEx::replace(file, _T("${base-path}"), getBasePath().string());
1584#ifdef WIN32
1585        strEx::replace(file, _T("${shared-path}"), getBasePath().string());
1586#else
1587        strEx::replace(file, _T("${shared-path}"), getBasePath().string());
1588//      strEx::replace(file, _T("${shared-path}"), _T("/usr/share/nsclient++"));
1589#endif
1590        strEx::replace(file, _T("${exe-path}"), getBasePath().string());
1591        strEx::replace(file, _T("${etc}"), _T("/etc"));
1592        return file;
1593}
1594
1595#ifdef _WIN32
1596void NSClientT::handle_session_change(unsigned long dwSessionId, bool logon) {
1597
1598}
1599#endif
Note: See TracBrowser for help on using the repository browser.