source: nscp/service/NSClient++.cpp @ f7a074d

0.4.00.4.10.4.2
Last change on this file since f7a074d was f7a074d, checked in by Michael Medin <michael@…>, 19 months ago
  • Had some "vacation" so no updates for a while
  • A lot of fixes to the NSCA parts (now 100% compatible with old settings file)
  • Added option to read sections (to plugin API)
  • Fixed issues in settings wrapper so child paths are also mapped (not just keys)
  • Many fixes related to NRPE/NSCA/*
  • "RC quality" expect RC within the week (only need to fix default config file somehow)
  • Upgraded all unit test to use the simplified API
  • Fixed a some unicode issues in PythonScript module
  • Improved threading a bit
  • Fixed CheckSystem (service check)
  • Fixed duplicate keys (when replacing) in old settings client
  • Property mode set to 100644
File size: 51.7 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 = settings_manager::get_settings()->get_string(MAIN_MODULES_SECTION, plugin);
373                if (plugin == _T("enabled") || plugin == _T("1")) {
374                        plugin = alias;
375                        alias = _T("");
376                } else if (alias == _T("enabled") || alias == _T("1")) {
377                                alias = _T("");
378                } else if ((active && plugin == _T("disabled")) || (active && alias == _T("disabled")))
379                        continue;
380                else if (plugin == _T("disabled")) {
381                        plugin = alias;
382                        alias = _T("");
383                } else if (alias == _T("disabled")) {
384                        alias = _T("");
385                }
386                if (!alias.empty()) {
387                        std::wstring tmp = plugin;
388                        plugin = alias;
389                        alias = tmp;
390                }
391                if (alias.empty()) {
392                        LOG_DEBUG_CORE_STD(_T("Found: ") + plugin);
393                } else {
394                        LOG_DEBUG_CORE_STD(_T("Found: ") + plugin + _T(" as ") + alias);
395                }
396                if (plugin.length() > 4 && plugin.substr(plugin.length()-4) == _T(".dll"))
397                        plugin = plugin.substr(0, plugin.length()-4);
398                ret.insert(plugin_alias_list_type::value_type(alias, plugin));
399        }
400        if (!active) {
401                boost::filesystem::wpath pluginPath = expand_path(_T("${module-path}"));
402                boost::filesystem::wdirectory_iterator end_itr; // default construction yields past-the-end
403                for ( boost::filesystem::wdirectory_iterator itr( pluginPath ); itr != end_itr; ++itr ) {
404                        if ( !is_directory(itr->status()) ) {
405                                boost::filesystem::wpath file= itr->leaf();
406                                if (is_module(pluginPath  / file) && !contains_plugin(ret, _T(""), file.string()))
407                                        ret.insert(plugin_alias_list_type::value_type(_T(""), file.string()));
408                        }
409                }
410        }
411        return ret;
412}
413
414// NSClientT::plugin_info_list NSClientT::get_all_plugins() {
415//      boost::filesystem::wpath pluginPath = expand_path(_T("${module-path}"));
416//      plugin_alias_list_type plugins = find_all_plugins(false);
417//      plugin_info_list ret;
418//      std::pair<std::wstring,std::wstring> v;
419//
420//      BOOST_FOREACH(v, plugins) {
421//              plugin_info_type info;
422//              info.dll = v.second;
423//              try {
424//                      LOG_DEBUG_STD(_T("Attempting to fake load: ") + v.second + _T(" as ") + v.first);
425//                      NSCPlugin plugin(next_plugin_id_++, pluginPath / v.second, v.first);
426//                      plugin.load_dll();
427//                      plugin.load_plugin(NSCAPI::dontStart);
428//                      info.name = plugin.getName();
429//                      info.description = plugin.getDescription();
430//                      plugin.unload();
431//              } catch (NSPluginException e) {
432//                      LOG_CRITICAL_STD(_T("Error loading: ") + e.file_ + _T(" root cause: ") + e.error_);
433//              } catch (...) {
434//                      LOG_CRITICAL_STD(_T("Unknown Error loading: ") + info.dll);
435//              }
436//              ret.push_back(info);
437//      }
438//      return ret;
439// }
440
441
442void NSClientT::load_all_plugins(int mode) {
443        boost::filesystem::wpath pluginPath;
444        {
445                try {
446                        pluginPath = expand_path(_T("${module-path}"));
447                } catch (std::exception &e) {
448                        LOG_CRITICAL_CORE_STD(_T("Failed to load plugins: ") + to_wstring(e.what()) + _T(" for ") + expand_path(_T("${module-path}")));
449                        return;
450                }
451                plugin_alias_list_type plugins = find_all_plugins(false);
452                std::pair<std::wstring,std::wstring> v;
453
454                BOOST_FOREACH(v, plugins) {
455                        try {
456                                addPlugin(pluginPath / v.second, v.first);
457                        } catch (NSPluginException &e) {
458                                LOG_CRITICAL_CORE_STD(_T("Failed to register plugin: ") + e.what());
459                        } catch (...) {
460                                LOG_CRITICAL_CORE_STD(_T("Failed to register plugin key: ") + v.second);
461                        }
462                }
463        }
464
465        try {
466                loadPlugins(mode);
467        } catch (...) {
468                LOG_ERROR_CORE_STD(_T("Unknown exception loading plugins"));
469        }
470
471//              std::wstring desc;
472//              std::wstring name = v.second;
473//              try {
474//                      NSCPlugin plugin(next_plugin_id_++, pluginPath / v.second, v.first);
475//                      name = plugin.getModule();
476//                      plugin.load_dll();
477//                      plugin.load_plugin(mode);
478//                      desc = plugin.getName() + _T(" - ");
479//                      desc += plugin.getDescription();
480//                      plugin.unload();
481//              } catch (NSPluginException e) {
482//                      desc += _T("unknown module");
483//                      LOG_CRITICAL_STD(_T("Error loading: ") + e.file_ + _T(" root cause: ") + e.error_);
484//              } catch (...) {
485//                      desc += _T("unknown module");
486//                      LOG_CRITICAL_STD(_T("Unknown Error loading: ") + name);
487//              }
488//              try {
489//                      if (v.first.empty() && !settings_manager::get_settings()->has_key(MAIN_MODULES_SECTION, v.second))
490//                              settings_manager::get_core()->register_key(MAIN_MODULES_SECTION, name, settings::settings_core::key_string, desc, desc, _T("disabled"), false);
491//              } catch (...) {
492//                      LOG_CRITICAL_STD(_T("Failed to register plugin key: ") + name);
493//              }
494        }
495
496void NSClientT::session_error(std::string file, unsigned int line, std::wstring msg) {
497        std::string s = nsclient::logger_helper::create_error(file.c_str(), line, msg);
498        reportMessage(s);
499}
500
501void NSClientT::session_info(std::string file, unsigned int line, std::wstring msg) {
502        std::string s = nsclient::logger_helper::create_info(file.c_str(), line, msg);
503        reportMessage(s);
504}
505
506
507
508
509//////////////////////////////////////////////////////////////////////////
510// Service functions
511
512
513struct nscp_settings_provider : public settings_manager::provider_interface {
514        virtual std::wstring expand_path(std::wstring file) {
515                return mainClient.expand_path(file);
516        }
517        virtual void log_fatal_error(std::wstring error) {
518                LOG_CRITICAL_CORE_STD(error);
519        }
520        virtual settings::logger_interface* create_logger() {
521                return new settings_logger();
522        }
523        std::wstring get_data(std::wstring key) {
524                // TODO
525                return _T("");
526        }
527};
528
529
530nscp_settings_provider provider;
531
532namespace sh = nscapi::settings_helper;
533
534/**
535 * Initialize the program
536 * @param boot true if we shall boot all plugins
537 * @param attachIfPossible is true we will attach to a running instance.
538 * @return success
539 * @author mickem
540 */
541bool NSClientT::boot_init() {
542        LOG_INFO_CORE(SERVICE_NAME _T(" booting..."));
543
544        if (!settings_manager::init_settings(&provider, context_)) {
545                return false;
546        }
547        LOG_INFO_CORE(_T("Booted settings subsystem..."));
548
549        bool crash_submit = false;
550        bool crash_archive = false;
551        bool crash_restart = false;
552        std::wstring crash_url, crash_folder, crash_target, log_level;
553        try {
554
555                sh::settings_registry settings(settings_manager::get_proxy());
556
557                settings.add_path_to_settings()
558                        (_T("log"),                     _T("LOG SETTINGS"), _T("Section for configuring the log handling."))
559                        (_T("shared session"),  _T("SHRED SESSION"), _T("Section for configuring the shared session."))
560                        (_T("crash"),                   _T("CRASH HANDLER"), _T("Section for configuring the crash handler."))
561                        ;
562
563                settings.add_key_to_settings(_T("log"))
564                        (_T("level"), sh::wstring_key(&log_level, _T("INFO")),
565                        _T("LOG LEVEL"), _T("Log level to use"))
566                        ;
567
568                settings.add_key_to_settings(_T("shared session"))
569                        (_T("enabled"), sh::bool_key(&enable_shared_session_ , false),
570                        _T("LOG LEVEL"), _T("Log level to use"))
571                        ;
572
573                settings.add_key_to_settings(_T("crash"))
574                        (_T("submit"), sh::bool_key(&crash_submit, false),
575                        _T("SUBMIT CRASHREPORTS"), _T("Submit crash reports to nsclient.org (or your configured submission server)"))
576
577                        (_T("archive"), sh::bool_key(&crash_archive, true),
578                        _T("ARCHIVE CRASHREPORTS"), _T("Archive crash reports in the archive folder"))
579
580                        (_T("restart"), sh::bool_key(&crash_restart, true),
581                        _T("RESTART"), _T("Submit crash reports to nsclient.org (or your configured submission server)"))
582
583                        (_T("restart target"), sh::wstring_key(&crash_target, get_service_control().get_service_name()),
584                        _T("RESTART SERVICE NAME"), _T("The url to submit crash reports to"))
585
586                        (_T("submit url"), sh::wstring_key(&crash_url, CRASH_SUBMIT_URL),
587                        _T("SUBMISSION URL"), _T("The url to submit crash reports to"))
588
589                        (_T("archive folder"), sh::wpath_key(&crash_folder, CRASH_ARCHIVE_FOLDER),
590                        CRASH_ARCHIVE_FOLDER_KEY, _T("The folder to archive crash dumps in"))
591                        ;
592
593                settings.register_all();
594                settings.notify();
595
596        } catch (settings::settings_exception e) {
597                LOG_ERROR_CORE_STD(_T("Could not find settings: ") + e.getMessage());
598        }
599
600#ifdef USE_BREAKPAD
601
602        if (!g_exception_manager) {
603                g_exception_manager = new ExceptionManager(false);
604
605                g_exception_manager->setup_app(to_wstring(APPLICATION_NAME), to_wstring(STRPRODUCTVER), to_wstring(STRPRODUCTDATE));
606
607                if (crash_restart) {
608                        LOG_DEBUG_CORE(_T("On crash: restart: ") + crash_target);
609                        g_exception_manager->setup_restart(crash_target);
610                }
611
612                bool crashHandling = false;
613                if (crash_submit) {
614                        g_exception_manager->setup_submit(false, crash_url);
615                        LOG_DEBUG_CORE(_T("Submitting crash dumps to central server: ") + crash_url);
616                        crashHandling = true;
617                }
618                if (crash_archive) {
619                        g_exception_manager->setup_archive(crash_folder);
620                        LOG_DEBUG_CORE(_T("Archiving crash dumps in: ") + crash_folder);
621                        crashHandling = true;
622                }
623                if (!crashHandling) {
624                        LOG_ERROR_CORE(_T("No crash handling configured"));
625                } else {
626                        //g_exception_manager->StartMonitoring();
627                }
628        }
629#else
630        LOG_ERROR_CORE(_T("Warning Not compiled with google breakpad support!"));
631#endif
632
633
634        if (enable_shared_session_) {
635                LOG_INFO_CORE(_T("shared session not ported yet!..."));
636//              if (boot) {
637//                      LOG_INFO_CORE(_T("shared session not ported yet!..."));
638//                      try {
639//                              shared_server_.reset(new nsclient_session::shared_server_session(this));
640//                              if (!shared_server_->session_exists()) {
641//                                      shared_server_->create_new_session();
642//                              } else {
643//                                      LOG_ERROR_STD(_T("Session already exists cant create a new one!"));
644//                              }
645//                              startTrayIcons();
646//                      } catch (nsclient_session::session_exception e) {
647//                              LOG_ERROR_STD(_T("Failed to create new session: ") + e.what());
648//                              shared_server_.reset(NULL);
649//                      } catch (...) {
650//                              LOG_ERROR_STD(_T("Failed to create new session: Unknown exception"));
651//                              shared_server_.reset(NULL);
652//                      }
653//              } else {
654//                      LOG_INFO_CORE(_T("shared session not ported yet!..."));
655//                      try {
656//                              std::wstring id = _T("_attached_") + strEx::itos(GetCurrentProcessId()) + _T("_");
657//                              shared_client_.reset(new nsclient_session::shared_client_session(id, this));
658//                              if (shared_client_->session_exists()) {
659//                                      shared_client_->attach_to_session(id);
660//                              } else {
661//                                      LOG_ERROR_STD(_T("No session was found cant attach!"));
662//                              }
663//                              LOG_ERROR_STD(_T("Session is: ") + shared_client_->get_client_id());
664//                      } catch (nsclient_session::session_exception e) {
665//                              LOG_ERROR_STD(_T("Failed to attach to session: ") + e.what());
666//                              shared_client_.reset(NULL);
667//                      } catch (...) {
668//                              LOG_ERROR_STD(_T("Failed to attach to session: Unknown exception"));
669//                              shared_client_.reset(NULL);
670//                      }
671//              }
672        }
673#ifdef WIN32
674        try {
675                com_helper_.initialize();
676        } catch (com_helper::com_exception e) {
677                LOG_ERROR_CORE_STD(_T("COM exception: ") + e.getMessage());
678                return false;
679        } catch (...) {
680                LOG_ERROR_CORE(_T("Unknown exception iniating COM..."));
681                return false;
682        }
683#endif
684        return true;
685}
686bool NSClientT::boot_load_plugins(bool boot) {
687        LOG_DEBUG_CORE(_T("booting::loading plugins"));
688        try {
689                boost::filesystem::wpath pluginPath = expand_path(_T("${module-path}"));
690                plugin_alias_list_type plugins = find_all_plugins(true);
691                std::pair<std::wstring,std::wstring> v;
692                BOOST_FOREACH(v, plugins) {
693                        std::wstring file = NSCPlugin::get_plugin_file(v.second);
694                        std::wstring alias = v.first;
695                        if (!alias.empty()) {
696                                LOG_DEBUG_CORE_STD(_T("Processing plugin: ") + file + _T(" as ") + alias);
697                        } else {
698                                LOG_DEBUG_CORE_STD(_T("Processing plugin: ") + file);
699                        }
700                        try {
701                                addPlugin(pluginPath / boost::filesystem::wpath(file), alias);
702                        } catch(const NSPluginException& e) {
703                                LOG_ERROR_CORE_STD(_T("Exception raised: '") + e.error_ + _T("' in module: ") + e.file_);
704                        } catch (std::exception e) {
705                                LOG_ERROR_CORE_STD(_T("exception loading plugin: ") + file + strEx::string_to_wstring(e.what()));
706                                return false;
707                        } catch (...) {
708                                LOG_ERROR_CORE_STD(_T("Unknown exception loading plugin: ") + file);
709                                return false;
710                        }
711                }
712        } catch (settings::settings_exception e) {
713                LOG_ERROR_CORE_STD(_T("Failed to set settings file") + e.getMessage());
714        } catch (...) {
715                LOG_ERROR_CORE_STD(_T("Unknown exception when loading plugins"));
716                return false;
717        }
718        try {
719                loadPlugins(boot?NSCAPI::normalStart:NSCAPI::dontStart);
720        } catch (...) {
721                LOG_ERROR_CORE_STD(_T("Unknown exception loading plugins"));
722                return false;
723        }
724        LOG_DEBUG_CORE_STD(APPLICATION_NAME _T(" - ") CURRENT_SERVICE_VERSION _T(" Started!"));
725        return true;
726}
727
728void NSClientT::startTrayIcons() {
729//      if (shared_server_.get() == NULL) {
730//              LOG_MESSAGE_STD(_T("No master session so tray icons not started"));
731//              return;
732//      }
733//      remote_processes::PWTS_SESSION_INFO list;
734//      DWORD count;
735//      if (!remote_processes::_WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE , 0, 1, &list, &count)) {
736//              LOG_ERROR_STD(_T("Failed to enumerate sessions:" ) + error::lookup::last_error());
737//      } else {
738//              LOG_DEBUG_STD(_T("Found ") + strEx::itos(count) + _T(" sessions"));
739//              for (DWORD i=0;i<count;i++) {
740//                      LOG_DEBUG_STD(_T("Found session: ") + strEx::itos(list[i].SessionId) + _T(" state: ") + strEx::itos(list[i].State));
741//                      if (list[i].State == remote_processes::_WTS_CONNECTSTATE_CLASS::WTSActive) {
742//                              startTrayIcon(list[i].SessionId);
743//                      }
744//              }
745//      }
746}
747void NSClientT::startTrayIcon(DWORD dwSessionId) {
748//      if (shared_server_.get() == NULL) {
749//              LOG_MESSAGE_STD(_T("No master session so tray icons not started"));
750//              return;
751//      }
752//      if (!shared_server_->re_attach_client(dwSessionId)) {
753//              if (!tray_starter::start(dwSessionId)) {
754//                      LOG_ERROR_STD(_T("Failed to start session (") + strEx::itos(dwSessionId) + _T("): " ) + error::lookup::last_error());
755//              }
756//      }
757}
758
759bool NSClientT::exitCore(bool boot) {
760        LOG_DEBUG_CORE(_T("Attempting to stop"));
761        try {
762                LOG_DEBUG_CORE(_T("Stopping: NON Message Handling Plugins"));
763                mainClient.unloadPlugins(false);
764        } catch(NSPluginException e) {
765                LOG_ERROR_CORE_STD(_T("Exception raised when unloading non msg plguins: ") + e.error_ + _T(" in module: ") + e.file_);
766        } catch(...) {
767                LOG_ERROR_CORE_STD(_T("Unknown exception raised when unloading non msg plugins"));
768        }
769#ifdef WIN32
770        LOG_DEBUG_CORE(_T("Stopping: COM helper"));
771        try {
772                com_helper_.unInitialize();
773        } catch (com_helper::com_exception e) {
774                LOG_ERROR_CORE_STD(_T("COM exception: ") + e.getMessage());
775        } catch (...) {
776                LOG_ERROR_CORE_STD(_T("Unknown exception uniniating COM..."));
777        }
778#endif
779        /*
780        LOG_DEBUG_STD(_T("Stopping: Socket Helpers"));
781        try {
782                simpleSocket::WSACleanup();
783        } catch (simpleSocket::SocketException e) {
784                LOG_ERROR_STD(_T("Socket exception: ") + e.getMessage());
785        } catch (...) {
786                LOG_ERROR_STD(_T("Unknown exception uniniating socket..."));
787        }
788        */
789        LOG_DEBUG_CORE(_T("Stopping: Settings instance"));
790        settings_manager::destroy_settings();
791//      try {
792//              if (shared_client_.get() != NULL) {
793//                      LOG_DEBUG_STD(_T("Stopping: shared client"));
794//                      shared_client_->set_handler(NULL);
795//                      shared_client_->close_session();
796//              }
797//      } catch(nsclient_session::session_exception &e) {
798//              LOG_ERROR_STD(_T("Exception closing shared client session: ") + e.what());
799//      } catch(...) {
800//              LOG_ERROR_STD(_T("Exception closing shared client session: Unknown exception!"));
801//      }
802        try {
803//              if (shared_server_.get() != NULL) {
804//                      LOG_DEBUG_STD(_T("Stopping: shared server"));
805//                      shared_server_->set_handler(NULL);
806//                      shared_server_->close_session();
807//              }
808        } catch(...) {
809                LOG_ERROR_CORE_STD(_T("UNknown exception raised: When closing shared session"));
810        }
811        try {
812                LOG_DEBUG_CORE(_T("Stopping: Message handling Plugins"));
813                mainClient.unloadPlugins(true);
814        } catch(NSPluginException e) {
815                LOG_ERROR_CORE_STD(_T("Exception raised when unloading msg plugins: ") + e.error_ + _T(" in module: ") + e.file_);
816        } catch(...) {
817                LOG_ERROR_CORE_STD(_T("UNknown exception raised: When stopping message plguins"));
818        }
819        LOG_INFO_CORE(_T("Stopped succcessfully"));
820        logger_master_.stop_slave();
821        return true;
822}
823void NSClientT::service_on_session_changed(unsigned long dwSessionId, bool logon, unsigned long dwEventType) {
824//      if (shared_server_.get() == NULL) {
825//              LOG_DEBUG_STD(_T("No shared session: ignoring change event!"));
826//              return;
827//      }
828//      LOG_DEBUG_CORE_STD(_T("Got session change: ") + strEx::itos(dwSessionId));
829//      if (!logon) {
830//              LOG_DEBUG_CORE_STD(_T("Not a logon event: ") + strEx::itos(dwEventType));
831//              return;
832//      }
833//      tray_starter::start(dwSessionId);
834}
835
836//////////////////////////////////////////////////////////////////////////
837// Member functions
838
839
840
841/**
842 * Unload all plug-ins (in reversed order)
843 */
844void NSClientT::unloadPlugins(bool unloadLoggers) {
845        {
846                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
847                if (!writeLock.owns_lock()) {
848                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (003)."));
849                        return;
850                }
851                if (unloadLoggers)
852                        logger_master_.remove_all_plugins();
853        }
854        {
855                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
856                if (!readLock.owns_lock()) {
857                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (004)."));
858                        return;
859                }
860                for (pluginList::reverse_iterator it = plugins_.rbegin(); it != plugins_.rend(); ++it) {
861                        plugin_type p = *it;
862                        if (!p)
863                                continue;
864                        try {
865                                if (unloadLoggers || !p->hasMessageHandler()) {
866                                        LOG_DEBUG_CORE_STD(_T("Unloading plugin: ") + p->getModule() + _T("..."));
867                                        p->unload_plugin();
868                                } else {
869                                        LOG_DEBUG_CORE_STD(_T("Skipping log plugin: ") + p->getModule() + _T("..."));
870                                }
871                        } catch(NSPluginException e) {
872                                LOG_ERROR_CORE_STD(_T("Exception raised when unloading plugin: ") + e.error_ + _T(" in module: ") + e.file_);
873                        } catch(...) {
874                                LOG_ERROR_CORE_STD(_T("Unknown exception raised when unloading plugin"));
875                        }
876                }
877        }
878        {
879                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
880                if (!writeLock.owns_lock()) {
881                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (005)."));
882                        return;
883                }
884                commands_.remove_all();
885                for (pluginList::iterator it = plugins_.begin(); it != plugins_.end();) {
886                        plugin_type p = (*it);
887                        try {
888                                if (!p && (unloadLoggers|| !p->isLoaded())) {
889                                        it = plugins_.erase(it);
890                                        //delete p;
891                                        continue;
892                                }
893                        } catch(NSPluginException e) {
894                                LOG_ERROR_CORE_STD(_T("Exception raised when unloading plugin: ") + e.error_ + _T(" in module: ") + e.file_);
895                        } catch(...) {
896                                LOG_ERROR_CORE(_T("Unknown exception raised when unloading plugin"));
897                        }
898                        it++;
899                }
900        }
901}
902
903NSCAPI::errorReturn NSClientT::reload(const wchar_t *module) {
904        {
905                std::wstring m = module;
906                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
907                if (!writeLock.owns_lock()) {
908                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (007a)."));
909                        return NSCAPI::hasFailed;
910                }
911
912                BOOST_FOREACH(plugin_type &p, plugins_) {
913                        if (p->get_alias() == m) {
914                                LOG_DEBUG_CORE_STD(_T("Found module: ") + m + _T(", reloading..."));
915                                p->unload_plugin();
916                                p->load_plugin(NSCAPI::normalStart);
917                                return NSCAPI::isSuccess;
918                        }
919                }
920        }
921        return NSCAPI::hasFailed;
922}
923
924void NSClientT::loadPlugins(NSCAPI::moduleLoadMode mode) {
925        bool hasBroken = false;
926        {
927                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
928                if (!readLock.owns_lock()) {
929                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (006)."));
930                        return;
931                }
932                for (pluginList::iterator it=plugins_.begin(); it != plugins_.end();) {
933                        LOG_DEBUG_CORE_STD(_T("Loading plugin: ") + (*it)->get_description());
934                        try {
935                                if (!(*it)->load_plugin(mode)) {
936                                        LOG_ERROR_CORE_STD(_T("Plugin refused to load: ") + (*it)->getModule());
937                                        it = plugins_.erase(it);
938                                } else
939                                        ++it;
940                        } catch (NSPluginException e) {
941                                it = plugins_.erase(it);
942                                LOG_ERROR_CORE_STD(_T("Could not load plugin: ") + e.file_ + _T(": ") + e.error_);
943                        } catch (...) {
944                                it = plugins_.erase(it);
945                                LOG_ERROR_CORE_STD(_T("Could not load plugin: ") + (*it)->getModule());
946                        }
947                }
948        }
949        logger_master_.all_plugins_loaded();
950}
951/**
952 * Load and add a plugin to various internal structures
953 * @param plugin The plug-in instance to load. The pointer is managed by the
954 */
955NSClientT::plugin_type NSClientT::addPlugin(boost::filesystem::wpath file, std::wstring alias) {
956        {
957                LOG_DEBUG_CORE_STD(_T("addPlugin(") + file.string() + _T(" as ") + alias + _T(")"));
958                // Check if this is a duplicate plugin (if so return that instance)
959                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
960                if (!writeLock.owns_lock()) {
961                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (007a)."));
962                        return plugin_type();
963                }
964
965                BOOST_FOREACH(plugin_type plug, plugins_) {
966                        if (plug->is_duplicate(file, alias)) {
967                                LOG_DEBUG_CORE_STD(_T("Found duplicate plugin returning old ") + to_wstring(plug->get_id()));
968                                return plug;
969                        }
970                }
971
972        }
973
974
975        plugin_type plugin(new NSCPlugin(next_plugin_id_++, file, alias));
976        plugin->load_dll();
977        {
978                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
979                if (!writeLock.owns_lock()) {
980                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (007b)."));
981                        return plugin;
982                }
983
984                plugins_.insert(plugins_.end(), plugin);
985                if (plugin->hasCommandHandler())
986                        commands_.add_plugin(plugin);
987                if (plugin->hasNotificationHandler())
988                        channels_.add_plugin(plugin);
989                if (plugin->hasMessageHandler())
990                        logger_master_.add_plugin(plugin);
991                if (plugin->has_routing_handler())
992                        routers_.add_plugin(plugin);
993                settings_manager::get_core()->register_key(_T("/modules"), plugin->getModule(), settings::settings_core::key_string, plugin->getName(), plugin->getDescription(), _T(""), false);
994                // TODO add comments elsewhere to the settings store for all loaded modules...
995        }
996        return plugin;
997}
998
999
1000std::wstring NSClientT::describeCommand(std::wstring command) {
1001        return commands_.describe(command);
1002}
1003std::list<std::wstring> NSClientT::getAllCommandNames() {
1004        return commands_.list();
1005}
1006void NSClientT::registerCommand(unsigned int id, std::wstring cmd, std::wstring desc) {
1007        return commands_.register_command(id, cmd, desc);
1008}
1009
1010NSCAPI::nagiosReturn NSClientT::inject(std::wstring command, std::wstring arguments, std::wstring &msg, std::wstring & perf) {
1011        /*if (shared_client_.get() != NULL && shared_client_->hasMaster()) {
1012                try {
1013                        return shared_client_->inject(command, arguments, splitter, escape, msg, perf);
1014                } catch (nsclient_session::session_exception &e) {
1015                        LOG_ERROR_STD(_T("Failed to inject remote command: ") + e.what());
1016                        return NSCAPI::returnCRIT;
1017                } catch (...) {
1018                        LOG_ERROR_STD(_T("Failed to inject remote command: Unknown exception"));
1019                        return NSCAPI::returnCRIT;
1020                }
1021        } else */{
1022
1023                std::list<std::wstring> args;
1024                strEx::parse_command(arguments, args);
1025                std::string request, response;
1026                nscapi::functions::create_simple_query_request(command, args, request);
1027                NSCAPI::nagiosReturn ret = injectRAW(command.c_str(), request, response);
1028                if (response.empty()) {
1029                        LOG_ERROR_CORE(_T("No data retutned from command"));
1030                        return NSCAPI::returnUNKNOWN;
1031                }
1032                nscapi::functions::parse_simple_query_response(response, msg, perf);
1033                return ret;
1034        }
1035}
1036
1037/**
1038 * Inject a command into the plug-in stack.
1039 *
1040 * @param command Command to inject
1041 * @param argLen Length of argument buffer
1042 * @param **argument Argument buffer
1043 * @param *returnMessageBuffer Message buffer
1044 * @param returnMessageBufferLen Length of returnMessageBuffer
1045 * @param *returnPerfBuffer Performance data buffer
1046 * @param returnPerfBufferLen Length of returnPerfBuffer
1047 * @return The command status
1048 */
1049NSCAPI::nagiosReturn NSClientT::injectRAW(const wchar_t* raw_command, std::string &request, std::string &response) {
1050        std::wstring cmd = nsclient::commands::make_key(raw_command);
1051        if (logDebug()) {
1052                LOG_DEBUG_CORE_STD(_T("Injecting: ") + cmd + _T("..."));
1053        }
1054        /*if (shared_client_.get() != NULL && shared_client_->hasMaster()) {
1055                try {
1056                        std::wstring msg, perf;
1057                        int returnCode = shared_client_->inject(command, arrayBuffer::arrayBuffer2string(argument, argLen, _T(" ")), L' ', true, msg, perf);
1058                        NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, msg, returnCode);
1059                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, perf, returnCode);
1060                } catch (nsclient_session::session_exception &e) {
1061                        LOG_ERROR_STD(_T("Failed to inject remote command: ") + e.what());
1062                        int returnCode = NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, _T("Failed to inject remote command: ") + e.what(), NSCAPI::returnCRIT);
1063                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, _T(""), returnCode);
1064                } catch (...) {
1065                        LOG_ERROR_STD(_T("Failed to inject remote command: Unknown exception"));
1066                        int returnCode = NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, _T("Failed to inject remote command:  + e.what()"), NSCAPI::returnCRIT);
1067                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, _T(""), returnCode);
1068                }
1069        } else */{
1070                try {
1071                        nsclient::commands::plugin_type plugin = commands_.get(cmd);
1072                        if (!plugin) {
1073                                LOG_ERROR_CORE(_T("No handler for command: ") + cmd + _T(" avalible commands: ") + commands_.to_wstring());
1074                                return NSCAPI::returnIgnored;
1075                        }
1076                        NSCAPI::nagiosReturn c = plugin->handleCommand(cmd.c_str(), request, response);
1077                        LOG_DEBUG_CORE_STD(_T("Result ") + cmd + _T(": ") + nscapi::plugin_helper::translateReturn(c));
1078                        return c;
1079                } catch (nsclient::commands::command_exception &e) {
1080                        LOG_ERROR_CORE(_T("No handler for command: ") + cmd + _T(": ") + to_wstring(e.what()));
1081                        return NSCAPI::returnIgnored;
1082                } catch (...) {
1083                        LOG_ERROR_CORE(_T("Error handling command: ") + cmd);
1084                        return NSCAPI::returnIgnored;
1085                }
1086        }
1087}
1088
1089
1090int NSClientT::simple_exec(std::wstring module, std::wstring command, std::vector<std::wstring> arguments, std::list<std::wstring> &resp) {
1091        bool found = false;
1092        std::string request;
1093        std::list<std::string> responses;
1094        nscapi::functions::create_simple_exec_request(command, arguments, request);
1095        int ret = 0;
1096        {
1097                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(5));
1098                if (!readLock.owns_lock()) {
1099                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (001)."));
1100                        return -1;
1101                }
1102                BOOST_FOREACH(plugin_type p, plugins_) {
1103                        if (p) {
1104                                if ((module.empty() || p->getModule() == module)&&(p->has_command_line_exec())) {
1105                                        LOG_DEBUG_CORE_STD(_T("Found module: ") + p->getName() + _T("..."));
1106                                        try {
1107                                                std::string response;
1108                                                ret = p->commandLineExec(command.c_str(), request, response);
1109                                                found = true;
1110                                                if (ret != NSCAPI::returnIgnored && !response.empty())
1111                                                        responses.push_back(response);
1112                                        } catch (NSPluginException e) {
1113                                                LOG_ERROR_CORE_STD(_T("Could not execute command: ") + e.error_ + _T(" in ") + e.file_);
1114                                                return -1;
1115                                        }
1116                                }
1117                        }
1118                }
1119        }
1120        if (!found && !module.empty()) {
1121                try {
1122                        boost::filesystem::wpath file = NSCPlugin::get_filename(getBasePath() / boost::filesystem::wpath(_T("modules")), module);
1123                        if (boost::filesystem::is_regular(file)) {
1124                                plugin_type plugin = addPlugin(file, _T(""));
1125                                if (plugin) {
1126                                        LOG_DEBUG_CORE_STD(_T("Loading plugin: ") + plugin->getName() + _T("..."));
1127                                        plugin->load_plugin(NSCAPI::dontStart);
1128                                        std::string response;
1129                                        ret = plugin->commandLineExec(command.c_str(), request, response);
1130                                        if (ret != NSCAPI::returnIgnored && !response.empty())
1131                                                responses.push_back(response);
1132                                } else {
1133                                        LOG_ERROR_CORE_STD(_T("Failed to load: ") + std::wstring(module));
1134                                        return 1;
1135                                }
1136                        } else {
1137                                LOG_ERROR_CORE_STD(_T("Failed to load: ") + std::wstring(module));
1138                                return 1;
1139                        }
1140                } catch (const NSPluginException &e) {
1141                        resp.push_back(_T("Module (") + e.file_ + _T(") was not found: ") + e.error_);
1142                        LOG_INFO_CORE_STD(_T("Module (") + e.file_ + _T(") was not found: ") + e.error_);
1143                } catch(const std::exception &e) {
1144                        resp.push_back(_T("Module (") + module + _T(") was not found: ") + utf8::cvt<std::wstring>(e.what()));
1145                        LOG_INFO_CORE_STD(_T("Module (") + module + _T(") was not found: ") + utf8::cvt<std::wstring>(e.what()));
1146                        return 1;
1147                } catch(...) {
1148                        resp.push_back(_T("Module (") + module + _T(") was not found..."));
1149                        LOG_INFO_CORE_STD(_T("Module (") + module + _T(") was not found..."));
1150                        return 1;
1151                }
1152        }
1153        BOOST_FOREACH(std::string &r, responses) {
1154                try {
1155                        nscapi::functions::parse_simple_exec_result(r, resp);
1156                } catch (std::exception &e) {
1157                        resp.push_back(_T("Failed to extract return message: ") + utf8::cvt<std::wstring>(e.what()));
1158                        LOG_ERROR_CORE_STD(resp.back());
1159                        return NSCAPI::returnUNKNOWN;
1160                }
1161        }
1162        return ret;
1163}
1164
1165
1166NSCAPI::nagiosReturn NSClientT::exec_command(const wchar_t* raw_target, const wchar_t* raw_command, std::string &request, std::string &response) {
1167        std::wstring target = raw_target;
1168        bool match_any = false;
1169        bool match_all = false;
1170        bool has_match = false;
1171        if (target == _T("any"))
1172                match_any = true;
1173        else if (target == _T("all") || target == _T("*"))
1174                match_all = true;
1175        std::list<std::string> responses;
1176        bool found = false;
1177        {
1178                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(5));
1179                if (!readLock.owns_lock()) {
1180                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (001)."));
1181                        return -1;
1182                }
1183                BOOST_FOREACH(plugin_type p, plugins_) {
1184                        if (p && p->has_command_line_exec()) {
1185                                try {
1186                                        if (match_all || match_any || p->get_alias() == target) {
1187                                                std::string respbuffer;
1188                                                NSCAPI::nagiosReturn r = p->commandLineExec(raw_command, request, respbuffer);
1189                                                if (r != NSCAPI::returnIgnored && !respbuffer.empty()) {
1190                                                        LOG_DEBUG_CORE_STD(_T("Got response from: ") + p->getName());
1191                                                        found = true;
1192                                                        if (match_any) {
1193                                                                response = respbuffer;
1194                                                                return NSCAPI::returnOK;
1195                                                        }
1196                                                        responses.push_back(respbuffer);
1197                                                }
1198                                        }
1199                                } catch (NSPluginException e) {
1200                                        LOG_ERROR_CORE_STD(_T("Could not execute command: ") + e.error_ + _T(" in ") + e.file_);
1201                                }
1202                        }
1203                }
1204        }
1205
1206        Plugin::ExecuteResponseMessage response_message;
1207        nscapi::functions::create_simple_header(response_message.mutable_header());
1208
1209        BOOST_FOREACH(std::string r, responses) {
1210                Plugin::ExecuteResponseMessage tmp;
1211                tmp.ParseFromString(r);
1212                for (int i=0;i<tmp.payload_size();i++) {
1213                        Plugin::ExecuteResponseMessage::Response *r = response_message.add_payload();
1214                        r->CopyFrom(tmp.payload(i));
1215                }
1216        }
1217        response_message.SerializeToString(&response);
1218        if (found)
1219                return NSCAPI::returnOK;
1220        return NSCAPI::returnIgnored;
1221}
1222
1223
1224NSCAPI::errorReturn NSClientT::reroute(std::wstring &channel, std::string &buffer) {
1225        BOOST_FOREACH(nsclient::plugin_type p, routers_.get(channel)) {
1226                wchar_t *new_channel_buffer;
1227                char *new_buffer;
1228                unsigned int new_buffer_len;
1229                int status = p->route_message(channel.c_str(), buffer.c_str(), buffer.size(), &new_channel_buffer, &new_buffer, &new_buffer_len);
1230                if (status&NSCAPI::message_modified == NSCAPI::message_modified) {
1231                        buffer = std::string(new_buffer, new_buffer_len);
1232                        p->deleteBuffer(&new_buffer);
1233                }
1234                if (status&NSCAPI::message_routed == NSCAPI::message_routed) {
1235                        channel = new_channel_buffer;
1236                        //p->deleteBuffer(new_channel_buffer);
1237                        return NSCAPI::message_routed;
1238                }
1239                if (status&NSCAPI::message_ignored == NSCAPI::message_ignored)
1240                        return NSCAPI::message_ignored;
1241                if (status&NSCAPI::message_digested == NSCAPI::message_digested)
1242                        return NSCAPI::message_ignored;
1243        }
1244        return NSCAPI::isfalse;
1245}
1246
1247NSCAPI::errorReturn NSClientT::register_submission_listener(unsigned int plugin_id, const wchar_t* channel) {
1248        channels_.register_listener(plugin_id, channel);
1249        return NSCAPI::isSuccess;
1250}
1251NSCAPI::errorReturn NSClientT::register_routing_listener(unsigned int plugin_id, const wchar_t* channel) {
1252        routers_.register_listener(plugin_id, channel);
1253        return NSCAPI::isSuccess;
1254}
1255
1256NSCAPI::errorReturn NSClientT::send_notification(const wchar_t* channel, std::string &request, std::string &response) {
1257        boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
1258        if (!readLock.owns_lock()) {
1259                LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (009)."));
1260                return NSCAPI::hasFailed;
1261        }
1262
1263        std::wstring schannel = channel;
1264        try {
1265                int count = 0;
1266                while (reroute(schannel, request)==NSCAPI::message_routed && count++ <= 10) {
1267                        LOG_DEBUG_CORE_STD(_T("Re-routing message to: ") + schannel);
1268                }
1269                if (count >= 10) {
1270                        LOG_ERROR_CORE(_T("More then 10 routes, discarding message..."));
1271                        return NSCAPI::hasFailed;
1272                }
1273        } catch (nsclient::plugins_list_exception &e) {
1274                LOG_ERROR_CORE(_T("Error routing channel: ") + std::wstring(channel) + _T(": ") + to_wstring(e.what()) + _T("Current channels: ") + channels_.to_wstring());
1275                return NSCAPI::hasFailed;
1276        } catch (...) {
1277                LOG_ERROR_CORE(_T("Error routing channel: ") + std::wstring(channel));
1278                return NSCAPI::hasFailed;
1279        }
1280
1281        try {
1282                //LOG_ERROR_CORE_STD(_T("Notifying: ") + strEx::strip_hex(to_wstring(std::string(result,result_len))));
1283                bool found = false;
1284                BOOST_FOREACH(nsclient::plugin_type p, channels_.get(schannel)) {
1285                        p->handleNotification(schannel.c_str(), request, response);
1286                        found = true;
1287                }
1288                if (!found) {
1289                        LOG_ERROR_CORE_STD(_T("No one listens for events from: ") + schannel + _T(" (") + std::wstring(channel) + _T(")"));
1290                        return NSCAPI::hasFailed;
1291                }
1292                return NSCAPI::isSuccess;
1293        } catch (nsclient::plugins_list_exception &e) {
1294                LOG_ERROR_CORE(_T("No handler for channel: ") + std::wstring(channel) + _T(": ") + to_wstring(e.what()));
1295                return NSCAPI::hasFailed;
1296        } catch (...) {
1297                LOG_ERROR_CORE(_T("Error handling channel: ") + std::wstring(channel));
1298                return NSCAPI::hasFailed;
1299        }
1300}
1301
1302void NSClientT::listPlugins() {
1303        boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
1304        if (!readLock.owns_lock()) {
1305                LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (010)."));
1306                return;
1307        }
1308        for (pluginList::iterator it=plugins_.begin(); it != plugins_.end(); ++it) {
1309                try {
1310                        if ((*it)->isBroken()) {
1311                                std::wcout << (*it)->getModule() << _T(": ") << _T("broken") << std::endl;
1312                        } else {
1313                                std::wcout << (*it)->getModule() << _T(": ") << (*it)->getName() << std::endl;
1314                        }
1315                } catch (NSPluginException e) {
1316                        LOG_ERROR_CORE_STD(_T("Could not load plugin: ") + e.file_ + _T(": ") + e.error_);
1317                }
1318        }
1319
1320}
1321
1322bool NSClientT::logDebug() {
1323        if (debug_ == log_state_unknown) {
1324                debug_ = log_state_looking;
1325                try {
1326                        if (settings_manager::get_settings_no_wait()->get_bool(_T("log"), _T("debug"), false) == 1)
1327                                debug_ = log_state_debug;
1328                        else
1329                                debug_ = log_state_nodebug;
1330                } catch (settings::settings_exception e) {
1331                        debug_ = log_state_unknown;
1332                        return false;
1333                }
1334        } else if (debug_ == log_state_looking)
1335                return false;
1336        return (debug_ == log_state_debug);
1337}
1338
1339/**
1340 * Report a message to all logging enabled modules.
1341 *
1342 * @param msgType Message type
1343 * @param file Filename generally __FILE__
1344 * @param line  Line number, generally __LINE__
1345 * @param message The message as a human readable string.
1346 */
1347void NSClientT::reportMessage(std::string data) {
1348        try {
1349                logger_master_.log(data);
1350        } catch (...) {
1351                logger_master_.log_fatal_error("Caught UNKNOWN Exception when trying to log a message");
1352        }
1353}
1354boost::filesystem::wpath NSClientT::getBasePath(void) {
1355        boost::unique_lock<boost::timed_mutex> lock(internalVariables, boost::get_system_time() + boost::posix_time::seconds(5));
1356        if (!lock.owns_lock()) {
1357                LOG_ERROR_CORE(_T("FATAL ERROR: Could not get mutex."));
1358                return _T("FATAL ERROR");
1359        }
1360        if (!basePath.empty())
1361                return basePath;
1362        unsigned int buf_len = 4096;
1363#ifdef WIN32
1364        wchar_t* buffer = new wchar_t[buf_len+1];
1365        GetModuleFileName(NULL, buffer, buf_len);
1366        std::wstring path = buffer;
1367        std::wstring::size_type pos = path.rfind('\\');
1368        basePath = path.substr(0, pos) + _T("\\");
1369        delete [] buffer;
1370#else
1371        basePath = to_wstring(boost::filesystem::initial_path().string());
1372#endif
1373        try {
1374                settings_manager::get_core()->set_base(basePath);
1375        } catch (settings::settings_exception e) {
1376                LOG_ERROR_CORE_STD(_T("Failed to set settings file: ") + e.getMessage());
1377        } catch (...) {
1378                LOG_ERROR_CORE_STD(_T("Failed to set settings file"));
1379        }
1380        return basePath;
1381}
1382
1383
1384std::wstring Encrypt(std::wstring str, unsigned int algorithm) {
1385        unsigned int len = 0;
1386        NSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
1387        len+=2;
1388        wchar_t *buf = new wchar_t[len+1];
1389        NSCAPI::errorReturn ret = NSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
1390        if (ret == NSCAPI::isSuccess) {
1391                std::wstring ret = buf;
1392                delete [] buf;
1393                return ret;
1394        }
1395        return _T("");
1396}
1397std::wstring Decrypt(std::wstring str, unsigned int algorithm) {
1398        unsigned int len = 0;
1399        NSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
1400        len+=2;
1401        wchar_t *buf = new wchar_t[len+1];
1402        NSCAPI::errorReturn ret = NSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
1403        if (ret == NSCAPI::isSuccess) {
1404                std::wstring ret = buf;
1405                delete [] buf;
1406                return ret;
1407        }
1408        return _T("");
1409}
1410
1411void NSClientT::nsclient_log_error(std::string file, int line, std::wstring error) {
1412        std::string s = nsclient::logger_helper::create_error(file, line, error);
1413        reportMessage(s.c_str());
1414}
1415
1416
1417
1418// Service API
1419NSClient* NSClientT::get_global_instance() {
1420        return &mainClient;
1421}
1422void NSClientT::handle_startup(std::wstring service_name) {
1423        service_name_ = service_name;
1424        boot_init();
1425        boot_load_plugins(true);
1426/*
1427        DWORD dwSessionId = remote_processes::getActiveSessionId();
1428        if (dwSessionId != 0xFFFFFFFF)
1429                tray_starter::start(dwSessionId);
1430        else
1431                LOG_ERROR_STD(_T("Failed to start tray helper:" ) + error::lookup::last_error());
1432                */
1433}
1434void NSClientT::handle_shutdown(std::wstring service_name) {
1435        exitCore(true);
1436}
1437
1438NSClientT::service_controller NSClientT::get_service_control() {
1439        return service_controller(service_name_);
1440}
1441
1442void NSClientT::service_controller::stop() {
1443#ifdef WIN32
1444        serviceControll::StopNoWait(get_service_name());
1445#endif
1446}
1447void NSClientT::service_controller::start() {
1448#ifdef WIN32
1449        serviceControll::Start(get_service_name());
1450#endif
1451}
1452bool NSClientT::service_controller::is_started() {
1453#ifdef WIN32
1454        try {
1455                if (serviceControll::isStarted(get_service_name())) {
1456                        return true;
1457                }
1458        } catch (...) {
1459                return false;
1460        }
1461#endif
1462        return false;
1463}
1464
1465std::wstring NSClientT::expand_path(std::wstring file) {
1466        strEx::replace(file, _T("${certificate-path}"), _T("${shared-path}/security"));
1467        strEx::replace(file, _T("${module-path}"), _T("${shared-path}/modules"));
1468       
1469        strEx::replace(file, _T("${base-path}"), getBasePath().string());
1470#ifdef WIN32
1471        strEx::replace(file, _T("${shared-path}"), getBasePath().string());
1472#else
1473        strEx::replace(file, _T("${shared-path}"), getBasePath().string());
1474//      strEx::replace(file, _T("${shared-path}"), _T("/usr/share/nsclient++"));
1475#endif
1476        strEx::replace(file, _T("${exe-path}"), getBasePath().string());
1477        strEx::replace(file, _T("${etc}"), _T("/etc"));
1478        return file;
1479}
1480
1481#ifdef _WIN32
1482void NSClientT::handle_session_change(unsigned long dwSessionId, bool logon) {
1483
1484}
1485#endif
Note: See TracBrowser for help on using the repository browser.