source: nscp/service/NSClient++.cpp @ 441a022

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