source: nscp/service/NSClient++.cpp @ 920626f

0.4.00.4.10.4.2
Last change on this file since 920626f was 920626f, checked in by Michael Medin <michael@…>, 3 years ago

Made some changes to facilitate building protocol buffer files from cmake

  • Property mode set to 100644
File size: 47.6 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.h>
18#include <charEx.h>
19//#include <Socket.h>
20#include <config.h>
21#include <msvc_wrappers.h>
22#ifdef WIN32
23#include <Userenv.h>
24#include <Lmcons.h>
25//#ifdef DEBUG
26#include <crtdbg.h>
27//#endif
28#endif
29//#include <remote_processes.hpp>
30//#include <winsvc.h>
31//#include <Userenv.h>
32//#include <Lmcons.h>
33//#include <remote_processes.hpp>
34#include "core_api.h"
35#include "settings_manager_impl.h"
36#include <settings/macros.h>
37#include <NSCHelper.h>
38#include "simple_client.hpp"
39#include "settings_client.hpp"
40#include "service_manager.hpp"
41
42#include "../proto/plugin.proto.h"
43
44NSClient mainClient(SZSERVICENAME);     // Global core instance.
45bool g_bConsoleLog = false;
46
47
48//////////////////////////////////////////////////////////////////////////
49// Log macros to simplify logging
50// Generally names are of the form LOG_<severity>[_STD]
51// Where _STD indicates that strings are force wrapped inside a std::wstring
52//
53#define LOG_ERROR_STD(msg) LOG_ERROR(((std::wstring)msg).c_str())
54#define LOG_ERROR(msg) \
55        NSAPIMessage(NSCAPI::error, __FILEW__, __LINE__, msg)
56
57#define LOG_CRITICAL_STD(msg) LOG_CRITICAL(((std::wstring)msg).c_str())
58#define LOG_CRITICAL(msg) \
59        NSAPIMessage(NSCAPI::critical, __FILEW__, __LINE__, msg)
60#define LOG_MESSAGE_STD(msg) LOG_MESSAGE(((std::wstring)msg).c_str())
61#define LOG_MESSAGE(msg) \
62        NSAPIMessage(NSCAPI::log, __FILEW__, __LINE__, msg)
63
64#define LOG_DEBUG_STD(msg) LOG_DEBUG(((std::wstring)msg).c_str())
65#define LOG_DEBUG(msg) \
66        NSAPIMessage(NSCAPI::debug, __FILEW__, __LINE__, msg)
67
68#define LOG_ERROR_CORE(msg) reportMessage(NSCAPI::error, __FILEW__, __LINE__, msg)
69#define LOG_ERROR_CORE_STD(msg) LOG_ERROR_CORE(std::wstring(msg))
70
71
72#define SETTINGS_GET_BOOL_CORE(key) \
73        settings_manager::get_settings()->get_bool(setting_keys::key ## _PATH, setting_keys::key, setting_keys::key ## _DEFAULT)
74
75#define SETTINGS_GET_STRING_CORE(key) \
76        settings_manager::get_settings()->get_string(setting_keys::key ## _PATH, setting_keys::key, setting_keys::key ## _DEFAULT)
77/*
78#define SETTINGS_SET_STRING_CORE(key, value) \
79        Settings::get_settings()->set_string(setting_keys::key ## _PATH, setting_keys::key, value);
80*/
81/**
82 * START OF Tray starter MERGE HELPER
83 */
84class tray_starter {
85        struct start_block {
86                std::wstring cmd;
87                std::wstring cmd_line;
88                DWORD sessionId;
89        };
90
91public:
92        static LPVOID init(DWORD dwSessionId, std::wstring exe, std::wstring cmdline) {
93                start_block *sb = new start_block;
94                sb->cmd = exe;
95                sb->cmd_line = cmdline;
96                sb->sessionId = dwSessionId;
97                return sb;
98        }
99        DWORD threadProc(LPVOID lpParameter) {
100#ifdef WIN32
101                start_block* param = static_cast<start_block*>(lpParameter);
102                DWORD dwSessionId = param->sessionId;
103                std::wstring cmd = param->cmd;
104                std::wstring cmdline = param->cmd_line;
105                delete param;
106                for (int i=0;i<10;i++) {
107                        Sleep(1000);
108                        if (startTrayHelper(dwSessionId, cmd, cmdline, false))
109                                break;
110                }
111#endif
112                return 0;
113        }
114
115        static bool start(unsigned long  dwSessionId) {
116                boost::filesystem::wpath program = mainClient.getBasePath() / SETTINGS_GET_STRING_CORE(settings_def::SYSTRAY_EXE);
117                std::wstring cmdln = _T("\"") + program.string() + _T("\" -channel __") + strEx::itos(dwSessionId) + _T("__");
118                return tray_starter::startTrayHelper(dwSessionId, program.string(), cmdln);
119        }
120
121        static bool startTrayHelper(unsigned long dwSessionId, std::wstring exe, std::wstring cmdline, bool startThread = true) {
122//              HANDLE hToken = NULL;
123//              if (!remote_processes::GetSessionUserToken(dwSessionId, &hToken)) {
124//                      LOG_ERROR_STD(_T("Failed to query user token: ") + error::lookup::last_error());
125//                      return false;
126//              } else {
127//                      STARTUPINFO          StartUPInfo;
128//                      PROCESS_INFORMATION  ProcessInfo;
129//
130//                      ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
131//                      ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
132//                      StartUPInfo.wShowWindow = SW_HIDE;
133//                      StartUPInfo.lpDesktop = L"Winsta0\\Default";
134//                      StartUPInfo.cb = sizeof(STARTUPINFO);
135//
136//                      wchar_t *buffer = new wchar_t[cmdline.size()+10];
137//                      wcscpy(buffer, cmdline.c_str());
138//                      LOG_MESSAGE_STD(_T("Running: ") + exe);
139//                      LOG_MESSAGE_STD(_T("Running: ") + cmdline);
140//
141//                      LPVOID pEnv =NULL;
142//                      DWORD dwCreationFlags = CREATE_NO_WINDOW; //0; //DETACHED_PROCESS
143//
144//                      if(CreateEnvironmentBlock(&pEnv,hToken,TRUE)) {
145//                              dwCreationFlags|=CREATE_UNICODE_ENVIRONMENT;
146//                      } else {
147//                              LOG_ERROR_STD(_T("Failed to create enviornment: ") + error::lookup::last_error());
148//                              pEnv=NULL;
149//                      }
150//                      /*
151//                      LOG_ERROR_STD(_T("Impersonating user: "));
152//                      if (!ImpersonateLoggedOnUser(hToken)) {
153//                              LOG_ERROR_STD(_T("Failed to impersonate the user: ") + error::lookup::last_error());
154//                      }
155//
156//                      wchar_t pszUname[UNLEN + 1];
157//                      ZeroMemory(pszUname,sizeof(pszUname));
158//                      DWORD dwSize = UNLEN;
159//                      if (!GetUserName(pszUname,&dwSize)) {
160//                              DWORD dwErr = GetLastError();
161//                              if (!RevertToSelf())
162//                                      LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
163//                              LOG_ERROR_STD(_T("Failed to get username: ") + error::format::from_system(dwErr));
164//                              return false;
165//                      }
166//                     
167//
168//                      PROFILEINFO info;
169//                      info.dwSize = sizeof(PROFILEINFO);
170//                      info.lpUserName = pszUname;
171//                      if (!LoadUserProfile(hToken, &info)) {
172//                              DWORD dwErr = GetLastError();
173//                              if (!RevertToSelf())
174//                                      LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
175//                              LOG_ERROR_STD(_T("Failed to get username: ") + error::format::from_system(dwErr));
176//                              return false;
177//                      }
178//                      */
179//                      if (!CreateProcessAsUser(hToken, exe.c_str(), buffer, NULL, NULL, FALSE, dwCreationFlags, pEnv, NULL, &StartUPInfo, &ProcessInfo)) {
180//                              DWORD dwErr = GetLastError();
181//                              delete [] buffer;
182//                              /*
183//                              if (!RevertToSelf()) {
184//                                      LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
185//                              }
186//                              */
187//                              if (startThread && dwErr == ERROR_PIPE_NOT_CONNECTED) {
188//                                      LOG_MESSAGE(_T("Failed to start trayhelper: starting a background thread to do it instead..."));
189//                                      Thread<tray_starter> *pThread = new Thread<tray_starter>(_T("tray-starter-thread"));
190//                                      pThread->createThread(tray_starter::init(dwSessionId, exe, cmdline));
191//                                      return false;
192//                              } else if (dwErr == ERROR_PIPE_NOT_CONNECTED) {
193//                                      LOG_ERROR_STD(_T("Thread failed to start trayhelper (will try again): ") + error::format::from_system(dwErr));
194//                                      return false;
195//                              } else {
196//                                      LOG_ERROR_STD(_T("Failed to start trayhelper: ") + error::format::from_system(dwErr));
197//                                      return true;
198//                              }
199//                      } else {
200//                              delete [] buffer;
201//                              /*
202//                              if (!RevertToSelf()) {
203//                                      LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
204//                              }
205//                              */
206//                              LOG_MESSAGE_STD(_T("Started tray in other user session: ") + strEx::itos(dwSessionId));
207//                      }
208//
209//
210//                      CloseHandle(hToken);
211//                      return true;
212//              }
213                return false;
214        }
215};
216
217/**
218 * End of class tray started (MERGE HELP)
219 */
220
221#define XNSC_DEFINE_SETTING_KEY(name, tag) \
222        name ## _SECTION \
223       
224 /**
225 * RANDOM JUNK (MERGE HELP)
226 */
227
228void display(std::wstring title, std::wstring message) {
229#ifdef WIN32
230        ::MessageBox(NULL, message.c_str(), title.c_str(), MB_OK|MB_ICONERROR);
231#endif
232        std::wcout << title << std::endl << message << std::endl;
233}
234
235
236bool is_module(boost::filesystem::wpath file )
237{
238        return boost::ends_with(file.string(), _T(".dll")) || boost::ends_with(file.string(), _T(".so"));
239}
240/**
241 * Application startup point
242 *
243 * @param argc Argument count
244 * @param argv[] Argument array
245 * @param envp[] Environment array
246 * @return exit status
247 */
248int nscp_main(int argc, wchar_t* argv[]);
249
250#ifdef WIN32
251int wmain(int argc, wchar_t* argv[], wchar_t* envp[]) { return nscp_main(argc, argv); }
252#else
253int main(int argc, char* argv[]) {
254        wchar_t **wargv = new wchar_t*[argc];
255        for (int i=0;i<argc;i++) {
256                std::wstring s = to_wstring(argv[i]);
257                wargv[i] = new wchar_t[s.length()+10];
258                wcscpy(wargv[i], s.c_str());
259        }
260        int ret = nscp_main(argc, wargv);
261        for (int i=0;i<argc;i++) {
262                delete [] wargv[i];
263        }
264        delete [] wargv;
265}
266#endif
267int nscp_main(int argc, wchar_t* argv[])
268{
269        srand( (unsigned)time( NULL ) );
270        int nRetCode = 0;
271        if ( (argc > 1) && ((*argv[1] == '-') || (*argv[1] == '/')) ) {
272                if (false) {
273                } if ( wcscasecmp( _T("install"), argv[1]+1 ) == 0 ) {
274                        nsclient::client::service_manager mgr(argc-1,&argv[1]);
275                        return mgr.install();
276                } else if ( wcscasecmp( _T("uninstall"), argv[1]+1 ) == 0 ) {
277                        nsclient::client::service_manager mgr(argc-1,&argv[1]);
278                        return mgr.uninstall();
279                } else if ( wcscasecmp( _T("start"), argv[1]+1 ) == 0 ) {
280                        nsclient::client::service_manager mgr(argc-1,&argv[1]);
281                        return mgr.start();
282                } else if ( wcscasecmp( _T("stop"), argv[1]+1 ) == 0 ) {
283                        nsclient::client::service_manager mgr(argc-1,&argv[1]);
284                        return mgr.stop();
285                } else if ( wcscasecmp( _T("svc"), argv[1]+1 ) == 0 ) {
286                        nsclient::client::service_manager mgr(argc-1,&argv[1]);
287                        return mgr.print_command();
288                } else if ( wcscasecmp( _T("encrypt"), argv[1]+1 ) == 0 ) {
289                        g_bConsoleLog = true;
290                        std::wstring password;
291                        if (!settings_manager::init_settings(mainClient.getBasePath())) {
292                                std::wcout << _T("Could not find settings") << std::endl;;
293                                return 1;
294                        }
295                        std::wcout << _T("Enter password to encrypt (has to be a single word): ");
296                        std::wcin >> password;
297                        std::wstring xor_pwd = Encrypt(password);
298                        std::wcout << _T("obfuscated_password=") << xor_pwd << std::endl;
299                        std::wstring outPasswd = Decrypt(xor_pwd);
300                        if (password != outPasswd)
301                                std::wcout << _T("ERROR: Password did not match: ") << outPasswd<< std::endl;
302                        settings_manager::destroy_settings();
303                        return 0;
304                } else if ( wcscasecmp( _T("about"), argv[1]+1 ) == 0 ) {
305                        try {
306                                g_bConsoleLog = true;
307                                LOG_MESSAGE(SZAPPNAME _T(" (C) Michael Medin - michael<at>medin<dot>name"));
308                                LOG_MESSAGE(_T("Version: ") SZVERSION);
309                                LOG_MESSAGE(_T("Architecture: ") SZARCH);
310
311                                boost::filesystem::wpath pluginPath = (boost::filesystem::wpath)mainClient.getBasePath() / _T("modules");
312                                LOG_MESSAGE_STD(_T("Looking at plugins in: ") + pluginPath.string());
313
314                                boost::filesystem::wdirectory_iterator end_itr; // default construction yields past-the-end
315                                for ( boost::filesystem::wdirectory_iterator itr( pluginPath ); itr != end_itr; ++itr ) {
316                                        if ( !is_directory(itr->status()) ) {
317                                                std::wstring file= itr->leaf();
318                                                LOG_MESSAGE_STD(_T("Found: ") + file);
319                                                if (is_module(pluginPath / file)) {
320                                                        NSCPlugin *plugin = new NSCPlugin(pluginPath / file);
321                                                        std::wstring name = _T("<unknown>");
322                                                        std::wstring description = _T("<unknown>");
323                                                        try {
324                                                                plugin->load_dll();
325                                                                name = plugin->getName();
326                                                                description = plugin->getDescription();
327                                                        } catch(const NSPluginException& e) {
328                                                                LOG_ERROR_STD(_T("Exception raised: ") + e.error_ + _T(" in module: ") + e.file_);
329                                                        } catch (std::exception e) {
330                                                                LOG_ERROR_STD(_T("exception loading plugin: ") + strEx::string_to_wstring(e.what()));
331                                                        } catch (...) {
332                                                                LOG_ERROR_STD(_T("Unknown exception loading plugin"));
333                                                        }
334                                                        LOG_MESSAGE_STD(_T("* ") + name + _T(" (") + file + _T(")"));
335                                                        std::list<std::wstring> list = strEx::splitEx(description, _T("\n"));
336                                                        for (std::list<std::wstring>::const_iterator cit = list.begin(); cit != list.end(); ++cit) {
337                                                                LOG_MESSAGE_STD(_T("    ") + *cit);
338                                                        }
339                                                }
340                                        }
341                                }
342                                LOG_MESSAGE_STD(_T("Done listing plugins from: ") + pluginPath.string());
343                                return true;
344                        } catch (std::exception &e) {
345                                LOG_ERROR_STD(_T("Exception: ") + to_wstring(e.what()));
346                        } catch (...) {
347                                LOG_ERROR_STD(_T("Unknown Exception: "));
348                        }
349                        return false;
350                } else if ( wcscasecmp( _T("version"), argv[1]+1 ) == 0 ) {
351                        g_bConsoleLog = true;
352                        LOG_MESSAGE(SZAPPNAME _T(" Version: ") SZVERSION _T(", Plattform: ") SZARCH);
353                } else if ( wcscasecmp( _T("d"), argv[1]+1 ) == 0 ) {
354                        // Run command from command line (like NRPE) but with debug enabled
355                } else if ( wcscasecmp( _T("noboot"), argv[1]+1 ) == 0 ) {
356                        g_bConsoleLog = true;
357                        mainClient.enableDebug(false);
358                        mainClient.initCore(false);
359                        if (argc>=3)
360                                nRetCode = mainClient.commandLineExec(argv[2], argc-3, &argv[3]);
361                        else
362                                nRetCode = mainClient.commandLineExec(argv[2], 0, NULL);
363                        mainClient.exitCore(true);
364                        return nRetCode;
365                } else if ( wcscasecmp( _T("c"), argv[1]+1 ) == 0 ) {
366                        // Run command from command line (like NRPE)
367                        g_bConsoleLog = true;
368                        mainClient.enableDebug(false);
369                        mainClient.initCore(true);
370                        std::wstring command, args, msg, perf;
371                        if (argc > 2)
372                                command = argv[2];
373                        for (int i=3;i<argc;i++) {
374                                if (i!=3) args += _T(" ");
375                                args += argv[i];
376                        }
377                        nRetCode = mainClient.inject(command, args, msg, perf);
378                        std::wcout << msg << _T("|") << perf << std::endl;
379                        mainClient.exitCore(true);
380                        return nRetCode;
381                } else if ( wcscasecmp( _T("test"), argv[1]+1 ) == 0 ) {
382                        g_bConsoleLog = true;
383                        bool server = false;
384                        if (argc > 2 && wcscasecmp( _T("server"), argv[2] ) == 0 ) {
385                                server = true;
386                        }
387                        std::wcout << "Launching test mode - " << (server?_T("server mode"):_T("client mode")) << std::endl;
388                        LOG_MESSAGE_STD(_T("Booting: ") SZSERVICEDISPLAYNAME );
389#ifdef WIN32
390                        try {
391                                if (serviceControll::isStarted(SZSERVICENAME)) {
392                                        std::wcerr << "Service seems to be started, this is probably not a good idea..." << std::endl;
393                                }
394                        } catch (...) {
395                                // Empty by design
396                        }
397#endif
398                        nsclient::simple_client client(&mainClient);
399                        client.start();
400                        return 0;
401                } else if ( wcscasecmp( _T("settings"), argv[1]+1 ) == 0 ) {
402                        nsclient::settings_client client(&mainClient);
403                        g_bConsoleLog = true;
404                        if (argc > 2)
405                                client.parse(argv[2], argc-3, argv+3);
406                        else
407                                client.help();
408                        return 0;
409                } else {
410                        std::wcerr << _T("Usage: -version, -about, -install, -uninstall, -start, -stop, -encrypt -settings") << std::endl;
411                        std::wcerr << _T("Usage: [-noboot] <ModuleName> <commnd> [arguments]") << std::endl;
412                        return -1;
413                }
414                return nRetCode;
415        } else if (argc > 2) {
416                g_bConsoleLog = true;
417                std::wcout << _T(" * * * * * * * ") << std::endl;
418                mainClient.initCore(true);
419                if (argc>=3)
420                        nRetCode = mainClient.commandLineExec(argv[1], argc-2, &argv[2]);
421                else
422                        nRetCode = mainClient.commandLineExec(argv[1], 0, NULL);
423                mainClient.exitCore(true);
424                return nRetCode;
425        } else if (argc > 1) {
426                g_bConsoleLog = true;
427                mainClient.enableDebug(true);
428                std::wcerr << _T("Invalid command line argument: ") << argv[1] << std::endl;
429                std::wcerr << _T("Usage: -version, -about, -install, -uninstall, -start, -stop, -encrypt") << std::endl;
430                std::wcerr << _T("Usage: [-noboot] <ModuleName> <commnd> [arguments]") << std::endl;
431                return -1;
432        }
433        try {
434                std::wcout << _T("Running as service...") << std::endl;
435                mainClient.enableDebug(true);
436                mainClient.start_and_wait();
437        } catch (...) {
438                std::wcerr << _T("Unknown exception in service") << std::endl;
439        }
440        return nRetCode;
441}
442
443void migrate() {}
444
445std::list<std::wstring> NSClientT::list_commands() {
446        return commands_.list();
447}
448
449NSClientT::plugin_info_list NSClientT::get_all_plugins() {
450        plugin_info_list ret;
451        boost::filesystem::wpath pluginPath = getBasePath() / boost::filesystem::wpath(_T("modules"));
452        boost::filesystem::wdirectory_iterator end_itr; // default construction yields past-the-end
453        for ( boost::filesystem::wdirectory_iterator itr( pluginPath ); itr != end_itr; ++itr ) {
454                if ( !is_directory(itr->status()) ) {
455                        boost::filesystem::wpath file= itr->leaf();
456                        if (is_module(pluginPath  / file)) {
457                                plugin_info_type info;
458                                info.dll = itr->leaf();
459                                try {
460                                        LOG_DEBUG_STD(_T("Attempting to fake load: ") + file.string());
461                                        NSCPlugin plugin(pluginPath / file);
462                                        plugin.load_dll();
463                                        plugin.load_plugin(NSCAPI::dontStart);
464                                        info.name = plugin.getName();
465                                        info.description = plugin.getDescription();
466                                        plugin.unload();
467                                } catch (NSPluginException e) {
468                                        LOG_CRITICAL_STD(_T("Error loading: ") + e.file_ + _T(" root cause: ") + e.error_);
469                                } catch (...) {
470                                        LOG_CRITICAL_STD(_T("Unknown Error loading: ") + file.string());
471                                }
472                                ret.push_back(info);
473                        }
474                }
475        }
476        return ret;
477}
478
479
480void NSClientT::load_all_plugins(int mode) {
481        boost::filesystem::wpath modPath = getBasePath() / boost::filesystem::wpath(_T("modules"));
482
483        boost::filesystem::wdirectory_iterator end_itr; // default construction yields past-the-end
484        for ( boost::filesystem::wdirectory_iterator itr( modPath ); itr != end_itr; ++itr ) {
485                if ( !is_directory(itr->status()) ) {
486                        boost::filesystem::wpath file= itr->leaf();
487                        if (is_module(modPath / file)) {
488                                if (settings_manager::get_settings()->has_key(MAIN_MODULES_SECTION, file.string())) {
489                                        if (settings_manager::get_settings()->get_string(MAIN_MODULES_SECTION, file.string()) == _T("disabled")) {
490                                                try {
491                                                        LOG_DEBUG_STD(_T("Attempting to fake load: ") + file.string());
492                                                        NSCPlugin plugin(modPath / file);
493                                                        plugin.load_dll();
494                                                        plugin.load_plugin(mode);
495                                                        plugin.unload();
496                                                } catch (NSPluginException e) {
497                                                        LOG_CRITICAL_STD(_T("Error loading: ") + e.file_ + _T(" root cause: ") + e.error_);
498                                                } catch (...) {
499                                                        LOG_CRITICAL_STD(_T("Unknown Error loading: ") + file.string());
500                                                }
501                                        }
502                                } else {
503                                        std::wstring desc;
504                                        std::wstring name = file.string();
505                                        try {
506                                                NSCPlugin plugin(modPath / file);
507                                                name = plugin.getModule();
508                                                plugin.load_dll();
509                                                plugin.load_plugin(mode);
510                                                desc = plugin.getName() + _T(" - ");
511                                                desc += plugin.getDescription();
512                                                plugin.unload();
513                                        } catch (NSPluginException e) {
514                                                desc += _T("unknown module");
515                                                LOG_CRITICAL_STD(_T("Error loading: ") + e.file_ + _T(" root cause: ") + e.error_);
516                                        } catch (...) {
517                                                desc += _T("unknown module");
518                                                LOG_CRITICAL_STD(_T("Unknown Error loading: ") + file.string());
519                                        }
520                                        settings_manager::get_core()->register_key(MAIN_MODULES_SECTION, name, Settings::SettingsCore::key_string, desc, desc, _T("disabled"), false);
521                                }
522                        }
523                }
524        }
525}
526
527void NSClientT::session_error(std::wstring file, unsigned int line, std::wstring msg) {
528        NSAPIMessage(NSCAPI::error, file.c_str(), line, msg.c_str());
529}
530
531void NSClientT::session_info(std::wstring file, unsigned int line, std::wstring msg) {
532        NSAPIMessage(NSCAPI::log, file.c_str(), line, msg.c_str());
533}
534
535
536
537
538//////////////////////////////////////////////////////////////////////////
539// Service functions
540
541/**
542 * Initialize the program
543 * @param boot true if we shall boot all plugins
544 * @param attachIfPossible is true we will attach to a running instance.
545 * @return success
546 * @author mickem
547 */
548bool NSClientT::initCore(bool boot) {
549        LOG_MESSAGE(_T("Attempting to start NSCLient++ - ") SZVERSION);
550        if (!settings_manager::init_settings(getBasePath())) {
551                return false;
552        }
553        LOG_MESSAGE(_T("Got settings subsystem..."));
554        try {
555                if (debug_)
556                        settings_manager::get_settings()->set_int(_T("log"), _T("debug"), 1);
557                        settings_manager::get_settings()->set_int(_T("Settings"), _T("shared_Session"), 1);
558                enable_shared_session_ = SETTINGS_GET_BOOL_CORE(settings_def::SHARED_SESSION);
559        } catch (SettingsException e) {
560                LOG_ERROR_CORE_STD(_T("Could not find settings: ") + e.getMessage());
561        }
562
563        if (enable_shared_session_) {
564                LOG_DEBUG_STD(_T("Enabling shared session..."));
565                if (boot) {
566                        LOG_MESSAGE_STD(_T("shared session not ported yet!..."));
567//                      try {
568//                              shared_server_.reset(new nsclient_session::shared_server_session(this));
569//                              if (!shared_server_->session_exists()) {
570//                                      shared_server_->create_new_session();
571//                              } else {
572//                                      LOG_ERROR_STD(_T("Session already exists cant create a new one!"));
573//                              }
574//                              startTrayIcons();
575//                      } catch (nsclient_session::session_exception e) {
576//                              LOG_ERROR_STD(_T("Failed to create new session: ") + e.what());
577//                              shared_server_.reset(NULL);
578//                      } catch (...) {
579//                              LOG_ERROR_STD(_T("Failed to create new session: Unknown exception"));
580//                              shared_server_.reset(NULL);
581//                      }
582                } else {
583                        LOG_MESSAGE_STD(_T("shared session not ported yet!..."));
584//                      try {
585//                              std::wstring id = _T("_attached_") + strEx::itos(GetCurrentProcessId()) + _T("_");
586//                              shared_client_.reset(new nsclient_session::shared_client_session(id, this));
587//                              if (shared_client_->session_exists()) {
588//                                      shared_client_->attach_to_session(id);
589//                              } else {
590//                                      LOG_ERROR_STD(_T("No session was found cant attach!"));
591//                              }
592//                              LOG_ERROR_STD(_T("Session is: ") + shared_client_->get_client_id());
593//                      } catch (nsclient_session::session_exception e) {
594//                              LOG_ERROR_STD(_T("Failed to attach to session: ") + e.what());
595//                              shared_client_.reset(NULL);
596//                      } catch (...) {
597//                              LOG_ERROR_STD(_T("Failed to attach to session: Unknown exception"));
598//                              shared_client_.reset(NULL);
599//                      }
600                }
601        }
602/*
603        try {
604                simpleSocket::WSAStartup();
605        } catch (simpleSocket::SocketException e) {
606                LOG_ERROR_STD(_T("Socket exception: ") + e.getMessage());
607                return false;
608        } catch (...) {
609                LOG_ERROR_STD(_T("Unknown exception iniating socket..."));
610                return false;
611        }
612*/
613#ifdef WIN32
614        try {
615                com_helper_.initialize();
616        } catch (com_helper::com_exception e) {
617                LOG_ERROR_CORE_STD(_T("COM exception: ") + e.getMessage());
618                return false;
619        } catch (...) {
620                LOG_ERROR_CORE(_T("Unknown exception iniating COM..."));
621                return false;
622        }
623#endif
624        if (boot) {
625                try {
626                        Settings::string_list list = settings_manager::get_settings()->get_keys(MAIN_MODULES_SECTION);
627                        for (Settings::string_list::const_iterator cit = list.begin(); cit != list.end(); ++cit) {
628                                LOG_DEBUG_STD(_T("Processing plugin: " + *cit));
629                                try {
630                                        if (settings_manager::get_settings()->get_string(MAIN_MODULES_SECTION, *cit) == _T("disabled")) {
631                                                LOG_DEBUG_STD(_T("Not booting: ") + *cit + _T(" since it is disabled."));
632                                                continue;
633                                        }
634                                } catch (...) {
635                                        // If we except we load the plugin in as-is
636                                }
637                                try {
638                                        loadPlugin(getBasePath() / boost::filesystem::wpath(_T("modules")) / boost::filesystem::wpath(*cit));
639                                } catch(const NSPluginException& e) {
640                                        LOG_ERROR_CORE_STD(_T("Exception raised: '") + e.error_ + _T("' in module: ") + e.file_);
641                                        //return false;
642                                } catch (std::exception e) {
643                                        LOG_ERROR_CORE_STD(_T("exception loading plugin: ") + (*cit) + strEx::string_to_wstring(e.what()));
644                                        return false;
645                                } catch (...) {
646                                        LOG_ERROR_CORE_STD(_T("Unknown exception loading plugin: ") + (*cit));
647                                        return false;
648                                }
649                        }
650                } catch (SettingsException e) {
651                        LOG_ERROR_CORE_STD(_T("Failed to set settings file") + e.getMessage());
652                } catch (...) {
653                        LOG_ERROR_CORE_STD(_T("Unknown exception when loading plugins"));
654                        return false;
655                }
656                try {
657                        loadPlugins(boot?NSCAPI::normalStart:NSCAPI::dontStart);
658                } catch (...) {
659                        LOG_ERROR_CORE_STD(_T("Unknown exception loading plugins"));
660                        return false;
661                }
662                LOG_DEBUG_STD(_T("NSCLient++ - ") SZVERSION _T(" Started!"));
663        }
664        LOG_MESSAGE_STD(_T("NSCLient++ - ") SZVERSION _T(" Started!"));
665        return true;
666}
667
668void NSClientT::startTrayIcons() {
669//      if (shared_server_.get() == NULL) {
670//              LOG_MESSAGE_STD(_T("No master session so tray icons not started"));
671//              return;
672//      }
673//      remote_processes::PWTS_SESSION_INFO list;
674//      DWORD count;
675//      if (!remote_processes::_WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE , 0, 1, &list, &count)) {
676//              LOG_ERROR_STD(_T("Failed to enumerate sessions:" ) + error::lookup::last_error());
677//      } else {
678//              LOG_DEBUG_STD(_T("Found ") + strEx::itos(count) + _T(" sessions"));
679//              for (DWORD i=0;i<count;i++) {
680//                      LOG_DEBUG_STD(_T("Found session: ") + strEx::itos(list[i].SessionId) + _T(" state: ") + strEx::itos(list[i].State));
681//                      if (list[i].State == remote_processes::_WTS_CONNECTSTATE_CLASS::WTSActive) {
682//                              startTrayIcon(list[i].SessionId);
683//                      }
684//              }
685//      }
686}
687void NSClientT::startTrayIcon(DWORD dwSessionId) {
688//      if (shared_server_.get() == NULL) {
689//              LOG_MESSAGE_STD(_T("No master session so tray icons not started"));
690//              return;
691//      }
692//      if (!shared_server_->re_attach_client(dwSessionId)) {
693//              if (!tray_starter::start(dwSessionId)) {
694//                      LOG_ERROR_STD(_T("Failed to start session (") + strEx::itos(dwSessionId) + _T("): " ) + error::lookup::last_error());
695//              }
696//      }
697}
698
699bool NSClientT::exitCore(bool boot) {
700        plugins_loaded_ = false;
701        LOG_DEBUG(_T("Attempting to stop NSCLient++ - ") SZVERSION);
702        if (boot) {
703                try {
704                        LOG_DEBUG_STD(_T("Stopping: NON Message Handling Plugins"));
705                        mainClient.unloadPlugins(false);
706                } catch(NSPluginException e) {
707                        LOG_ERROR_CORE_STD(_T("Exception raised when unloading non msg plguins: ") + e.error_ + _T(" in module: ") + e.file_);
708                } catch(...) {
709                        LOG_ERROR_CORE_STD(_T("Unknown exception raised when unloading non msg plugins"));
710                }
711        }
712#ifdef WIN32
713        LOG_DEBUG_STD(_T("Stopping: COM helper"));
714        try {
715                com_helper_.unInitialize();
716        } catch (com_helper::com_exception e) {
717                LOG_ERROR_CORE_STD(_T("COM exception: ") + e.getMessage());
718        } catch (...) {
719                LOG_ERROR_CORE_STD(_T("Unknown exception uniniating COM..."));
720        }
721#endif
722        /*
723        LOG_DEBUG_STD(_T("Stopping: Socket Helpers"));
724        try {
725                simpleSocket::WSACleanup();
726        } catch (simpleSocket::SocketException e) {
727                LOG_ERROR_STD(_T("Socket exception: ") + e.getMessage());
728        } catch (...) {
729                LOG_ERROR_STD(_T("Unknown exception uniniating socket..."));
730        }
731        */
732        LOG_DEBUG_STD(_T("Stopping: Settings instance"));
733        settings_manager::destroy_settings();
734//      try {
735//              if (shared_client_.get() != NULL) {
736//                      LOG_DEBUG_STD(_T("Stopping: shared client"));
737//                      shared_client_->set_handler(NULL);
738//                      shared_client_->close_session();
739//              }
740//      } catch(nsclient_session::session_exception &e) {
741//              LOG_ERROR_STD(_T("Exception closing shared client session: ") + e.what());
742//      } catch(...) {
743//              LOG_ERROR_STD(_T("Exception closing shared client session: Unknown exception!"));
744//      }
745        try {
746//              if (shared_server_.get() != NULL) {
747//                      LOG_DEBUG_STD(_T("Stopping: shared server"));
748//                      shared_server_->set_handler(NULL);
749//                      shared_server_->close_session();
750//              }
751        } catch(...) {
752                LOG_ERROR_CORE_STD(_T("UNknown exception raised: When closing shared session"));
753        }
754        if (boot) {
755                try {
756                        LOG_DEBUG_STD(_T("Stopping: Message handling Plugins"));
757                        mainClient.unloadPlugins(true);
758                } catch(NSPluginException e) {
759                        LOG_ERROR_CORE_STD(_T("Exception raised when unloading msg plugins: ") + e.error_ + _T(" in module: ") + e.file_);
760                } catch(...) {
761                        LOG_ERROR_CORE_STD(_T("UNknown exception raised: When stopping message plguins"));
762                }
763        }
764        LOG_MESSAGE_STD(_T("NSCLient++ - ") SZVERSION _T(" Stopped succcessfully"));
765        return true;
766}
767#ifdef WIN32x
768/**
769 * Forward this to the main service dispatcher helper class
770 * @param dwArgc
771 * @param *lpszArgv
772 */
773void WINAPI NSClientT::service_main_dispatch(DWORD dwArgc, LPTSTR *lpszArgv) {
774        try {
775                //WTF!!! mainClient.service_main(dwArgc, lpszArgv);
776        } catch (service_helper::service_exception e) {
777                LOG_ERROR_STD(_T("Unknown service error: ") + e.what());
778        } catch (...) {
779                LOG_ERROR_STD(_T("Unknown service error!"));
780        }
781}
782DWORD WINAPI NSClientT::service_ctrl_dispatch_ex(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext) {
783        return mainClient.service_ctrl_ex(dwControl, dwEventType, lpEventData, lpContext);
784}
785/**
786 * Forward this to the main service dispatcher helper class
787 * @param dwCtrlCode
788 */
789void WINAPI NSClientT::service_ctrl_dispatch(unsigned long dwCtrlCode) {
790        mainClient.service_ctrl_ex(dwCtrlCode, NULL, NULL, NULL);
791}
792#endif
793
794void NSClientT::service_on_session_changed(unsigned long dwSessionId, bool logon, unsigned long dwEventType) {
795//      if (shared_server_.get() == NULL) {
796//              LOG_DEBUG_STD(_T("No shared session: ignoring change event!"));
797//              return;
798//      }
799        LOG_DEBUG_STD(_T("Got session change: ") + strEx::itos(dwSessionId));
800        if (!logon) {
801                LOG_DEBUG_STD(_T("Not a logon event: ") + strEx::itos(dwEventType));
802                return;
803        }
804        tray_starter::start(dwSessionId);
805}
806
807//////////////////////////////////////////////////////////////////////////
808// Member functions
809
810int NSClientT::commandLineExec(const wchar_t* module, const unsigned int argLen, wchar_t** args) {
811        std::wstring sModule = module;
812        std::wstring moduleList = _T("");
813        {
814                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(5));
815                if (!readLock.owns_lock()) {
816                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex."));
817                        return -1;
818                }
819                for (pluginList::size_type i=0;i<plugins_.size();++i) {
820                        plugin_type p = plugins_[i];
821                        if (!moduleList.empty())
822                                moduleList += _T(", ");
823                        if (p) {
824                                moduleList += p->getModule();
825                                if (p->getModule() == sModule) {
826                                        LOG_DEBUG_STD(_T("Found module: ") + p->getName() + _T("..."));
827                                        try {
828                                                return p->commandLineExec(argLen, args);
829                                        } catch (NSPluginException e) {
830                                                LOG_ERROR_CORE_STD(_T("Could not execute command: ") + e.error_ + _T(" in ") + e.file_);
831                                                return -1;
832                                        }
833                                }
834                        }
835                }
836        }
837        try {
838                plugin_type plugin = loadPlugin(getBasePath() / boost::filesystem::wpath(_T("modules")) / boost::filesystem::wpath(module));
839                LOG_DEBUG_STD(_T("Loading plugin: ") + plugin->getName() + _T("..."));
840                plugin->load_plugin(NSCAPI::dontStart);
841                return plugin->commandLineExec(argLen, args);
842        } catch (NSPluginException e) {
843                LOG_MESSAGE_STD(_T("Module (") + e.file_ + _T(") was not found: ") + e.error_);
844        }
845        LOG_ERROR_CORE_STD(_T("Module not found: ") + std::wstring(module) + _T(" available modules are: ") + moduleList);
846        return 0;
847}
848
849/**
850 * Load a list of plug-ins
851 * @param plugins A list with plug-ins (DLL files) to load
852 */
853void NSClientT::addPlugins(const std::list<std::wstring> plugins) {
854        boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
855        if (!readLock.owns_lock()) {
856                LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex."));
857                return;
858        }
859        std::list<std::wstring>::const_iterator it;
860        for (it = plugins.begin(); it != plugins.end(); ++it) {
861                loadPlugin(*it);
862        }
863}
864/**
865 * Unload all plug-ins (in reversed order)
866 */
867void NSClientT::unloadPlugins(bool unloadLoggers) {
868        {
869                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
870                if (!writeLock.owns_lock()) {
871                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex."));
872                        return;
873                }
874                commandHandlers_.clear();
875                if (unloadLoggers)
876                        messageHandlers_.clear();
877        }
878        {
879                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
880                if (!readLock.owns_lock()) {
881                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex."));
882                        return;
883                }
884                for (pluginList::reverse_iterator it = plugins_.rbegin(); it != plugins_.rend(); ++it) {
885                        plugin_type p = *it;
886                        if (!p)
887                                continue;
888                        try {
889                                if (unloadLoggers || !p->hasMessageHandler()) {
890                                        LOG_DEBUG_STD(_T("Unloading plugin: ") + p->getModule() + _T("..."));
891                                        p->unload();
892                                } else {
893                                        LOG_DEBUG_STD(_T("Skipping log plugin: ") + p->getModule() + _T("..."));
894                                }
895                        } catch(NSPluginException e) {
896                                LOG_ERROR_CORE_STD(_T("Exception raised when unloading plugin: ") + e.error_ + _T(" in module: ") + e.file_);
897                        } catch(...) {
898                                LOG_ERROR_CORE_STD(_T("Unknown exception raised when unloading plugin"));
899                        }
900                }
901        }
902        {
903                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
904                if (!writeLock.owns_lock()) {
905                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex."));
906                        return;
907                }
908                commands_.remove_all();
909                for (pluginList::iterator it = plugins_.begin(); it != plugins_.end();) {
910                        plugin_type p = (*it);
911                        try {
912                                if (!p && (unloadLoggers|| !p->isLoaded())) {
913                                        it = plugins_.erase(it);
914                                        //delete p;
915                                        continue;
916                                }
917                        } catch(NSPluginException e) {
918                                LOG_ERROR_CORE_STD(_T("Exception raised when unloading plugin: ") + e.error_ + _T(" in module: ") + e.file_);
919                        } catch(...) {
920                                LOG_ERROR_CORE(_T("Unknown exception raised when unloading plugin"));
921                        }
922                        it++;
923                }
924        }
925}
926
927void NSClientT::loadPlugins(NSCAPI::moduleLoadMode mode) {
928        bool hasBroken = false;
929        {
930                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
931                if (!readLock.owns_lock()) {
932                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex."));
933                        return;
934                }
935                for (pluginList::iterator it=plugins_.begin(); it != plugins_.end();) {
936                        LOG_DEBUG_STD(_T("Loading plugin: ") + (*it)->getName() + _T("..."));
937                        try {
938                                if (!(*it)->load_plugin(NSCAPI::normalStart)) {
939                                        LOG_ERROR_CORE_STD(_T("Plugin refused to load: ") + (*it)->getModule());
940                                        it = plugins_.erase(it);
941                                } else
942                                        ++it;
943                        } catch (NSPluginException e) {
944                                it = plugins_.erase(it);
945                                LOG_ERROR_CORE_STD(_T("Could not load plugin: ") + e.file_ + _T(": ") + e.error_);
946                        } catch (...) {
947                                it = plugins_.erase(it);
948                                LOG_ERROR_CORE_STD(_T("Could not load plugin: ") + (*it)->getModule());
949                        }
950                }
951        }
952        /*
953        for (pluginList::iterator it=plugins_.begin(); it != plugins_.end();) {
954                LOG_DEBUG_STD(_T("Loading plugin: ") + (*it)->getName() + _T("..."));
955                try {
956                        (*it)->load_plugin(mode);
957                        ++it;
958                } catch(NSPluginException e) {
959                        it = plugins_.erase(it);
960                        LOG_ERROR_CORE_STD(_T("Exception raised when loading plugin: ") + e.error_ + _T(" in module: ") + e.file_ + _T(" plugin has been removed."));
961                } catch(...) {
962                        it = plugins_.erase(it);
963                        LOG_ERROR_CORE(_T("Unknown exception raised when unloading plugin plugin has been removed"));
964                }
965        }
966        */
967        plugins_loaded_ = true;
968}
969/**
970 * Load a single plug-in using a DLL filename
971 * @param file The DLL file
972 */
973NSClientT::plugin_type NSClientT::loadPlugin(const boost::filesystem::wpath file) {
974        plugin_type plugin(new NSCPlugin(file));
975        return addPlugin(plugin);
976}
977/**
978 * Load and add a plugin to various internal structures
979 * @param plugin The plug-in instance to load. The pointer is managed by the
980 */
981NSClientT::plugin_type NSClientT::addPlugin(plugin_type plugin) {
982        plugin->load_dll();
983        {
984                boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10));
985                if (!writeLock.owns_lock()) {
986                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex."));
987                        return plugin;
988                }
989                plugins_.insert(plugins_.end(), plugin);
990                if (plugin->hasCommandHandler())
991                        commandHandlers_.insert(commandHandlers_.end(), plugin);
992                if (plugin->hasMessageHandler())
993                        messageHandlers_.insert(messageHandlers_.end(), plugin);
994                settings_manager::get_core()->register_key(_T("/modules"), plugin->getModule(), Settings::SettingsCore::key_string, plugin->getName(), plugin->getDescription(), _T(""), false);
995        }
996        return plugin;
997}
998
999
1000std::wstring NSClientT::describeCommand(std::wstring command) {
1001        return commands_.describe(command);
1002}
1003std::list<std::wstring> NSClientT::getAllCommandNames() {
1004        return commands_.list();
1005}
1006void NSClientT::registerCommand(unsigned int id, std::wstring cmd, std::wstring desc) {
1007        return commands_.register_command(id, cmd, desc);
1008}
1009
1010unsigned int NSClientT::getBufferLength() {
1011        static unsigned int len = 0;
1012        if (len == 0) {
1013                try {
1014                        len = settings_manager::get_settings()->get_int(SETTINGS_KEY(settings_def::PAYLOAD_LEN));
1015                } catch (SettingsException &e) {
1016                        LOG_DEBUG_STD(_T("Failed to get length: ") + e.getMessage());
1017                        return setting_keys::settings_def::PAYLOAD_LEN_DEFAULT;
1018                } catch (...) {
1019                        LOG_ERROR_CORE(_T("Failed to get length: :("));
1020                        return setting_keys::settings_def::PAYLOAD_LEN_DEFAULT;
1021                }
1022        }
1023        return len;
1024}
1025
1026NSCAPI::nagiosReturn NSClientT::inject(std::wstring command, std::wstring arguments, std::wstring &msg, std::wstring & perf) {
1027        /*if (shared_client_.get() != NULL && shared_client_->hasMaster()) {
1028                try {
1029                        return shared_client_->inject(command, arguments, splitter, escape, msg, perf);
1030                } catch (nsclient_session::session_exception &e) {
1031                        LOG_ERROR_STD(_T("Failed to inject remote command: ") + e.what());
1032                        return NSCAPI::returnCRIT;
1033                } catch (...) {
1034                        LOG_ERROR_STD(_T("Failed to inject remote command: Unknown exception"));
1035                        return NSCAPI::returnCRIT;
1036                }
1037        } else */{
1038                PluginCommand::RequestMessage message;
1039                PluginCommand::Header *hdr = message.mutable_header();
1040                hdr->set_type(PluginCommand::Header_Type_REQUEST);
1041                hdr->set_version(PluginCommand::Header_Version_VERSION_1);
1042
1043                PluginCommand::Request *req = message.add_payload();
1044                req->set_command(to_string(command));
1045                req->set_version(PluginCommand::Request_Version_VERSION_1);
1046
1047                std::string args = to_string(arguments);
1048                boost::tokenizer<boost::escaped_list_separator<char> > tok(args, boost::escaped_list_separator<char>('\\', ' ', '\"'));
1049                BOOST_FOREACH(string s, tok)
1050                        req->add_arguments(s);
1051
1052                std::string request, response;
1053                message.SerializeToString(&request);
1054
1055
1056
1057                NSCAPI::nagiosReturn ret = injectRAW(command.c_str(), request, response);
1058                if (response.empty()) {
1059                        LOG_ERROR(_T("No data retutned from command"));
1060                        return NSCAPI::returnUNKNOWN;
1061                }
1062
1063                PluginCommand::ResponseMessage rsp_msg;
1064                rsp_msg.ParseFromString(response);
1065                if (rsp_msg.payload_size() != 1) {
1066                        LOG_ERROR_STD(_T("Failed to extract return message not 1 payload: ") + strEx::itos(rsp_msg.payload_size()));
1067                        return NSCAPI::returnUNKNOWN;
1068                }
1069                msg = to_wstring(rsp_msg.payload(0).message());
1070                if ( (ret == NSCAPI::returnInvalidBufferLen) || (ret == NSCAPI::returnIgnored) ) {
1071                        return ret;
1072                }
1073                return ret;
1074        }
1075}
1076
1077/**
1078 * Inject a command into the plug-in stack.
1079 *
1080 * @param command Command to inject
1081 * @param argLen Length of argument buffer
1082 * @param **argument Argument buffer
1083 * @param *returnMessageBuffer Message buffer
1084 * @param returnMessageBufferLen Length of returnMessageBuffer
1085 * @param *returnPerfBuffer Performance data buffer
1086 * @param returnPerfBufferLen Length of returnPerfBuffer
1087 * @return The command status
1088 */
1089NSCAPI::nagiosReturn NSClientT::injectRAW(const wchar_t* command, std::string &request, std::string &response) {
1090        if (logDebug()) {
1091                LOG_DEBUG_STD(_T("Injecting: ") + std::wstring(command) + _T(": {{{") + strEx::strip_hex(to_wstring(request)) + _T("}}}"));
1092        }
1093        /*if (shared_client_.get() != NULL && shared_client_->hasMaster()) {
1094                try {
1095                        std::wstring msg, perf;
1096                        int returnCode = shared_client_->inject(command, arrayBuffer::arrayBuffer2string(argument, argLen, _T(" ")), L' ', true, msg, perf);
1097                        NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, msg, returnCode);
1098                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, perf, returnCode);
1099                } catch (nsclient_session::session_exception &e) {
1100                        LOG_ERROR_STD(_T("Failed to inject remote command: ") + e.what());
1101                        int returnCode = NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, _T("Failed to inject remote command: ") + e.what(), NSCAPI::returnCRIT);
1102                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, _T(""), returnCode);
1103                } catch (...) {
1104                        LOG_ERROR_STD(_T("Failed to inject remote command: Unknown exception"));
1105                        int returnCode = NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, _T("Failed to inject remote command:  + e.what()"), NSCAPI::returnCRIT);
1106                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, _T(""), returnCode);
1107                }
1108        } else */{
1109                boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
1110                if (!readLock.owns_lock()) {
1111                        LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex."));
1112                        return NSCAPI::returnUNKNOWN;
1113                }
1114                for (pluginList::size_type i = 0; i < commandHandlers_.size(); i++) {
1115                        try {
1116                                NSCAPI::nagiosReturn c = commandHandlers_[i]->handleCommand(command, request, response);
1117                                switch (c) {
1118                                        case NSCAPI::returnInvalidBufferLen:
1119                                                LOG_ERROR_CORE(_T("UNKNOWN: Return buffer to small to handle this command."));
1120                                                return c;
1121                                        case NSCAPI::returnIgnored:
1122                                                break;
1123                                        case NSCAPI::returnOK:
1124                                        case NSCAPI::returnWARN:
1125                                        case NSCAPI::returnCRIT:
1126                                        case NSCAPI::returnUNKNOWN:
1127                                                LOG_DEBUG_STD(_T("Result ") + std::wstring(command) + _T(": ") + NSCHelper::translateReturn(c) + _T(" {{{") + strEx::strip_hex(to_wstring(response)) + _T("}}}"));
1128                                                return c;
1129                                        default:
1130                                                LOG_ERROR_CORE_STD(_T("Unknown error from handleCommand: ") + strEx::itos(c) + _T(" the injected command was: ") + (std::wstring)command);
1131                                                return c;
1132                                }
1133                        } catch(const NSPluginException& e) {
1134                                LOG_ERROR_CORE_STD(_T("Exception raised: ") + e.error_ + _T(" in module: ") + e.file_);
1135                                return NSCAPI::returnCRIT;
1136                        } catch(...) {
1137                                LOG_ERROR_CORE(_T("Unknown exception raised in module"));
1138                                return NSCAPI::returnCRIT;
1139                        }
1140                }
1141                LOG_MESSAGE_STD(_T("No handler for command: '") + command + _T("'"));
1142                return NSCAPI::returnIgnored;
1143        }
1144}
1145
1146void NSClientT::listPlugins() {
1147        boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
1148        if (!readLock.owns_lock()) {
1149                LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex."));
1150                return;
1151        }
1152        for (pluginList::iterator it=plugins_.begin(); it != plugins_.end(); ++it) {
1153                try {
1154                        if ((*it)->isBroken()) {
1155                                std::wcout << (*it)->getModule() << _T(": ") << _T("broken") << std::endl;
1156                        } else {
1157                                std::wcout << (*it)->getModule() << _T(": ") << (*it)->getName() << std::endl;
1158                        }
1159                } catch (NSPluginException e) {
1160                        LOG_ERROR_CORE_STD(_T("Could not load plugin: ") + e.file_ + _T(": ") + e.error_);
1161                }
1162        }
1163
1164}
1165
1166bool NSClientT::logDebug() {
1167        if (debug_ == log_unknown) {
1168                debug_ = log_looking;
1169                try {
1170                        if (settings_manager::get_settings()->get_int(_T("log"), _T("debug"), 0) == 1)
1171                                debug_ = log_debug;
1172                        else
1173                                debug_ = log_nodebug;
1174                } catch (SettingsException e) {
1175                        return true;
1176                }
1177        } else if (debug_ == log_looking)
1178                return true;
1179        return (debug_ == log_debug);
1180}
1181
1182void log_broken_message(std::wstring msg) {
1183#ifdef WIN32
1184        OutputDebugString(msg.c_str());
1185#else
1186        std::wcout << _T("--BROKEN MESSAGE: ") << msg << _T("--") << std::endl;
1187#endif
1188}
1189/**
1190 * Report a message to all logging enabled modules.
1191 *
1192 * @param msgType Message type
1193 * @param file Filename generally __FILE__
1194 * @param line  Line number, generally __LINE__
1195 * @param message The message as a human readable string.
1196 */
1197void NSClientT::reportMessage(int msgType, const wchar_t* file, const int line, std::wstring message) {
1198        try {
1199                strEx::replace(message, _T("\n"), _T(" "));
1200                strEx::replace(message, _T("\r"), _T(" "));
1201                if ((msgType == NSCAPI::debug)&&(!logDebug())) {
1202                        return;
1203                }
1204//              if (shared_server_.get() != NULL && shared_server_->hasClients()) {
1205//                      try {
1206//                              shared_server_->sendLogMessageToClients(msgType, file, line, message);
1207//                      } catch (nsclient_session::session_exception e) {
1208//                              log_broken_message(_T("Failed to send message to clients: ") + e.what());
1209//                      }
1210//              }
1211                std::wstring file_stl = file;
1212                std::wstring::size_type pos = file_stl.find_last_of(_T("\\"));
1213                if (pos != std::wstring::npos)
1214                        file_stl = file_stl.substr(pos);
1215                {
1216                        boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000));
1217                        if (!readLock.owns_lock()) {
1218                                log_broken_message(_T("Message was lost as the (mutexRW) core was locked: ") + message);
1219                                return;
1220                        }
1221                        boost::unique_lock<boost::timed_mutex> lock(messageMutex, boost::get_system_time() + boost::posix_time::seconds(5));
1222                        if (!lock.owns_lock()) {
1223                                log_broken_message(_T("Message was lost as the core was locked: ") + message);
1224                                return;
1225                        }
1226                        if (g_bConsoleLog) {
1227                                std::wstring k = _T("?");
1228                                switch (msgType) {
1229                                case NSCAPI::critical:
1230                                        k =_T("c");
1231                                        break;
1232                                case NSCAPI::warning:
1233                                        k =_T("w");
1234                                        break;
1235                                case NSCAPI::error:
1236                                        k =_T("e");
1237                                        break;
1238                                case NSCAPI::log:
1239                                        k =_T("l");
1240                                        break;
1241                                case NSCAPI::debug:
1242                                        k =_T("d");
1243                                        break;
1244                                default:
1245                                        k =_T("?");
1246                                }
1247                                std::wcout << k << _T(" ") << file_stl << _T("(") << line << _T(") ") << message << std::endl;
1248                        }
1249                        if (!plugins_loaded_) {
1250                                log_broken_message(message);
1251                                cached_log_entry entry(msgType, file, line, message);
1252                                log_cache_.push_back(entry);
1253                        } else {
1254                                if (log_cache_.size() > 0) {
1255                                        for (log_cache_type::const_iterator cit=log_cache_.begin();cit!=log_cache_.end();++cit) {
1256                                                for (pluginList::size_type i = 0; i< messageHandlers_.size(); i++) {
1257                                                        try {
1258                                                                messageHandlers_[i]->handleMessage((*cit).msgType, (_T("CACHE") + (*cit).file).c_str(), (*cit).line, (*cit).message.c_str());
1259                                                        } catch(const NSPluginException& e) {
1260                                                                log_broken_message(_T("Caught: ") + e.error_ + _T(" when trying to log a message..."));
1261                                                                return;
1262                                                        } catch(...) {
1263                                                                log_broken_message(_T("Caught: Unknown Exception when trying to log a message..."));
1264                                                                return;
1265                                                        }
1266                                                }
1267                                        }
1268                                        log_cache_.clear();
1269                                }
1270                                for (pluginList::size_type i = 0; i< messageHandlers_.size(); i++) {
1271                                        try {
1272                                                messageHandlers_[i]->handleMessage(msgType, file, line, message.c_str());
1273                                        } catch(const NSPluginException& e) {
1274                                                log_broken_message(_T("Caught: ") + e.error_ + _T(" when trying to log a message..."));
1275                                                return;
1276                                        } catch(...) {
1277                                                log_broken_message(_T("Caught: Unknown Exception when trying to log a message..."));
1278                                                return;
1279                                        }
1280                                }
1281                        }
1282                }
1283        } catch (...) {
1284                log_broken_message(_T("Caught UNKNOWN Exception when trying to log a message: ") + message);
1285        }
1286}
1287boost::filesystem::wpath NSClientT::getBasePath(void) {
1288        boost::unique_lock<boost::timed_mutex> lock(internalVariables, boost::get_system_time() + boost::posix_time::seconds(5));
1289        if (!lock.owns_lock()) {
1290                LOG_ERROR_CORE(_T("FATAL ERROR: Could not get mutex."));
1291                return _T("FATAL ERROR");
1292        }
1293        if (!basePath.empty())
1294                return basePath;
1295        unsigned int buf_len = 4096;
1296#ifdef WIN32
1297        wchar_t* buffer = new wchar_t[buf_len+1];
1298        GetModuleFileName(NULL, buffer, buf_len);
1299        std::wstring path = buffer;
1300        std::wstring::size_type pos = path.rfind('\\');
1301        basePath = path.substr(0, pos) + _T("\\");
1302        delete [] buffer;
1303#else
1304        basePath = to_wstring(boost::filesystem::initial_path().string());
1305#endif
1306        try {
1307                settings_manager::get_core()->set_base(basePath);
1308        } catch (SettingsException e) {
1309                LOG_ERROR_CORE_STD(_T("Failed to set settings file: ") + e.getMessage());
1310        } catch (...) {
1311                LOG_ERROR_CORE_STD(_T("Failed to set settings file"));
1312        }
1313        return basePath;
1314}
1315
1316
1317std::wstring Encrypt(std::wstring str, unsigned int algorithm) {
1318        unsigned int len = 0;
1319        NSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
1320        len+=2;
1321        wchar_t *buf = new wchar_t[len+1];
1322        NSCAPI::errorReturn ret = NSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
1323        if (ret == NSCAPI::isSuccess) {
1324                std::wstring ret = buf;
1325                delete [] buf;
1326                return ret;
1327        }
1328        return _T("");
1329}
1330std::wstring Decrypt(std::wstring str, unsigned int algorithm) {
1331        unsigned int len = 0;
1332        NSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
1333        len+=2;
1334        wchar_t *buf = new wchar_t[len+1];
1335        NSCAPI::errorReturn ret = NSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
1336        if (ret == NSCAPI::isSuccess) {
1337                std::wstring ret = buf;
1338                delete [] buf;
1339                return ret;
1340        }
1341        return _T("");
1342}
1343
1344void NSClientT::nsclient_log_error(std::wstring file, int line, std::wstring error) {
1345        reportMessage(NSCAPI::error, file.c_str(), line, error);
1346}
1347
1348
1349
1350// Service API
1351NSClient* NSClientT::get_global_instance() {
1352        return &mainClient;
1353}
1354void NSClientT::handle_startup() {
1355        initCore(true);
1356/*
1357        DWORD dwSessionId = remote_processes::getActiveSessionId();
1358        if (dwSessionId != 0xFFFFFFFF)
1359                tray_starter::start(dwSessionId);
1360        else
1361                LOG_ERROR_STD(_T("Failed to start tray helper:" ) + error::lookup::last_error());
1362                */
1363}
1364void NSClientT::handle_shutdown() {
1365        exitCore(true);
1366}
1367#ifdef _WIN32
1368void NSClientT::handle_session_change(unsigned long dwSessionId, bool logon) {
1369
1370}
1371#endif
Note: See TracBrowser for help on using the repository browser.