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

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