source: nscp/NSClient++.cpp @ df0ab60

0.4.00.4.10.4.2stable
Last change on this file since df0ab60 was df0ab60, checked in by Michael Medin <michael@…>, 6 years ago

2007-11-21 MickeM

  • Fixed process counter so checkProcState now return the *correct* number (previously it was correct-1)
  • Fixed som missing exceptions that were not caught + Added "AliasCol?" option to CheckWMIValue to allow a column to be used as "alias" for a result set:

CheckWMIValue -a "Query=select Caption, ThreadCount? from Win32_Process" MaxWarn=50 MaxCrit=100 Check:threads=ThreadCount AliasCol?=Caption

will give you: "System threads: 98 > warning, svchost.exe threads: 87 > warning"

  • Property mode set to 100644
File size: 25.2 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 <winsvc.h>
17#include "NSClient++.h"
18#include <Settings.h>
19#include <charEx.h>
20#include <Socket.h>
21#include <b64/b64.h>
22#include <config.h>
23#include <msvc_wrappers.h>
24
25
26NSClient mainClient;    // Global core instance.
27bool g_bConsoleLog = false;
28//////////////////////////////////////////////////////////////////////////
29// Startup code
30
31/**
32 * Application startup point
33 *
34 * @param argc Argument count
35 * @param argv[] Argument array
36 * @param envp[] Environment array
37 * @return exit status
38 */
39int main(int argc, TCHAR* argv[], TCHAR* envp[])
40{
41        int nRetCode = 0;
42
43        if ( (argc > 1) && ((*argv[1] == '-') || (*argv[1] == '/')) ) {
44                if ( _stricmp( "install", argv[1]+1 ) == 0 ) {
45                        g_bConsoleLog = true;
46                        try {
47                                serviceControll::Install(SZSERVICENAME, SZSERVICEDISPLAYNAME, SZDEPENDENCIES);
48                        } catch (const serviceControll::SCException& e) {
49                                LOG_MESSAGE_STD("Service installation failed: " + e.error_);
50                                return -1;
51                        }
52                        try {
53                                serviceControll::SetDescription(SZSERVICENAME, SZSERVICEDESCRIPTION);
54                        } catch (const serviceControll::SCException& e) {
55                                LOG_MESSAGE_STD("Couldn't set service description: " + e.error_);
56                        }
57                        LOG_MESSAGE("Service installed!");
58                } else if ( _stricmp( "uninstall", argv[1]+1 ) == 0 ) {
59                        g_bConsoleLog = true;
60                        try {
61                                serviceControll::Uninstall(SZSERVICENAME);
62                        } catch (const serviceControll::SCException& e) {
63                                LOG_MESSAGE_STD("Service deinstallation failed; " + e.error_);
64                                return -1;
65                        }
66                } else if ( _stricmp( "encrypt", argv[1]+1 ) == 0 ) {
67                        g_bConsoleLog = true;
68                        std::string password;
69                        try {
70                                Settings::getInstance()->setFile(mainClient.getBasePath(), "NSC.ini");
71                        } catch (SettingsException e) {
72                                std::cout << "Could not find settings: " << e.getMessage() << std::endl;;
73                                return 1;
74                        }
75                        std::cout << "Enter password to encrypt (has to be a single word): ";
76                        std::cin >> password;
77                        std::string xor_pwd = Encrypt(password);
78                        std::cout << "obfuscated_password=" << xor_pwd << std::endl;
79                        if (password != Decrypt(xor_pwd))
80                                std::cout << "ERROR: Password did not match!" << std::endl;
81                        Settings::destroyInstance();
82                        return 0;
83                } else if ( _stricmp( "start", argv[1]+1 ) == 0 ) {
84                        g_bConsoleLog = true;
85                        try {
86                                serviceControll::Start(SZSERVICENAME);
87                        } catch (const serviceControll::SCException& e) {
88                                LOG_MESSAGE_STD("Service failed to start: " + e.error_);
89                                return -1;
90                        }
91                } else if ( _stricmp( "stop", argv[1]+1 ) == 0 ) {
92                        g_bConsoleLog = true;
93                        try {
94                                serviceControll::Stop(SZSERVICENAME);
95                        } catch (const serviceControll::SCException& e) {
96                                LOG_MESSAGE_STD("Service failed to stop: " + e.error_);
97                                return -1;
98                        }
99                } else if ( _stricmp( "about", argv[1]+1 ) == 0 ) {
100                        g_bConsoleLog = true;
101                        LOG_MESSAGE(SZAPPNAME " (C) Michael Medin");
102                        LOG_MESSAGE("Version " SZVERSION);
103                } else if ( _stricmp( "version", argv[1]+1 ) == 0 ) {
104                        g_bConsoleLog = true;
105                        LOG_MESSAGE(SZAPPNAME " Version: " SZVERSION);
106                } else if ( _stricmp( "noboot", argv[1]+1 ) == 0 ) {
107                        g_bConsoleLog = true;
108                        mainClient.enableDebug(true);
109                        int nRetCode = -1;
110                        if (argc>=4)
111                                nRetCode = mainClient.commandLineExec(argv[2], argv[3], argc-4, &argv[4]);
112                        else if (argc>=3)
113                                nRetCode = mainClient.commandLineExec(argv[2], argv[3], 0, NULL);
114                        return nRetCode;
115                } else if ( _stricmp( "test", argv[1]+1 ) == 0 ) {
116#ifdef _DEBUG
117                        /*
118                        strEx::run_test_getToken();
119                        strEx::run_test_replace();
120                        charEx::run_test_getToken();
121                        arrayBuffer::run_testArrayBuffer();
122                        */
123#endif
124                        g_bConsoleLog = true;
125                        mainClient.enableDebug(true);
126                        if (!mainClient.InitiateService()) {
127                                LOG_ERROR_STD("Service *NOT* started!");
128                                return -1;
129                        }
130                        LOG_MESSAGE_STD("Using settings from: " + Settings::getInstance()->getActiveType());
131                        LOG_MESSAGE("Enter command to inject or exit to terminate...");
132                        std::string s = "";
133                        std::string buff = "";
134                        std::cin >> s;
135                        while (s != "exit") {
136                                if (std::cin.peek() < 15) {
137                                        buff += s;
138                                        strEx::token t = strEx::getToken(buff, ' ');
139                                        std::string msg, perf;
140                                        NSCAPI::nagiosReturn ret = mainClient.inject(t.first, t.second, ' ', msg, perf);
141                                        if (perf.empty())
142                                                std::cout << NSCHelper::translateReturn(ret) << ":" << msg << std::endl;
143                                        else
144                                                std::cout << NSCHelper::translateReturn(ret) << ":" << msg << "|" << perf << std::endl;
145                                        buff = "";
146                                } else {
147                                        buff += s + " ";
148                                }
149                                std::cin >> s;
150                        }
151                        mainClient.TerminateService();
152                        return 0;
153                } else {
154                        LOG_MESSAGE("Usage: -version, -about, -install, -uninstall, -start, -stop, -encrypt");
155                        LOG_MESSAGE("Usage: [-noboot] <ModuleName> <commnd> [arguments]");
156                }
157                return nRetCode;
158        } else if (argc > 2) {
159                g_bConsoleLog = true;
160                mainClient.InitiateService();
161                if (argc>=3)
162                        nRetCode = mainClient.commandLineExec(argv[1], argv[2], argc-3, &argv[3]);
163                else
164                        nRetCode = mainClient.commandLineExec(argv[1], argv[2], 0, NULL);
165                mainClient.TerminateService();
166                return nRetCode;
167        }
168        if (!mainClient.StartServiceCtrlDispatcher()) {
169                LOG_MESSAGE("We failed to start the service");
170        }
171        return nRetCode;
172}
173
174//////////////////////////////////////////////////////////////////////////
175// Service functions
176
177/**
178 * Service control handler startup point.
179 * When the program is started as a service this will be the entry point.
180 */
181bool NSClientT::InitiateService() {
182        try {
183                Settings::getInstance()->setFile(getBasePath(), "NSC.ini");
184                if (debug_) {
185                        Settings::getInstance()->setInt("log", "debug", 1);
186                }
187        } catch (SettingsException e) {
188                LOG_ERROR_STD("Could not find settings: " + e.getMessage());
189                return false;
190        } catch (...) {
191                LOG_ERROR_STD("Unknown exception reading settings...");
192                return false;
193        }
194
195        try {
196                simpleSocket::WSAStartup();
197        } catch (simpleSocket::SocketException e) {
198                LOG_ERROR_STD("Uncaught exception: " + e.getMessage());
199                return false;
200        } catch (...) {
201                LOG_ERROR_STD("Unknown exception iniating socket...");
202                return false;
203        }
204        try {
205                SettingsT::sectionList list = Settings::getInstance()->getSection("modules");
206                for (SettingsT::sectionList::iterator it = list.begin(); it != list.end(); it++) {
207                        try {
208                                loadPlugin(getBasePath() + "modules\\" + (*it));
209                        } catch(const NSPluginException& e) {
210                                LOG_ERROR_STD("Exception raised: " + e.error_ + " in module: " + e.file_);
211                                return false;
212                        } catch (...) {
213                                LOG_ERROR_STD("Unknown exception loading plugin: " + (*it));
214                                return false;
215                        }
216                }
217        } catch (SettingsException e) {
218                NSC_LOG_ERROR_STD("Failed to set settings file" + e.getMessage());
219        }
220        try {
221                loadPlugins();
222        } catch (...) {
223                LOG_ERROR_STD("Unknown exception loading plugins");
224                return false;
225        }
226        return true;
227}
228/**
229 * Service control handler termination point.
230 * When the program is stopped as a service this will be the "exit point".
231 */
232void NSClientT::TerminateService(void) {
233        try {
234                mainClient.unloadPlugins();
235        } catch(NSPluginException *e) {
236                std::cout << "Exception raised: " << e->error_ << " in module: " << e->file_ << std::endl;;
237        }
238        try {
239                simpleSocket::WSACleanup();
240        } catch (simpleSocket::SocketException e) {
241                LOG_ERROR_STD("Uncaught exception: " + e.getMessage());
242        }
243        Settings::destroyInstance();
244}
245
246/**
247 * Forward this to the main service dispatcher helper class
248 * @param dwArgc
249 * @param *lpszArgv
250 */
251void WINAPI NSClientT::service_main_dispatch(DWORD dwArgc, LPTSTR *lpszArgv) {
252        mainClient.service_main(dwArgc, lpszArgv);
253}
254/**
255 * Forward this to the main service dispatcher helper class
256 * @param dwCtrlCode
257 */
258void WINAPI NSClientT::service_ctrl_dispatch(DWORD dwCtrlCode) {
259        mainClient.service_ctrl(dwCtrlCode);
260}
261
262//////////////////////////////////////////////////////////////////////////
263// Member functions
264
265int NSClientT::commandLineExec(const char* module, const char* command, const unsigned int argLen, char** args) {
266        std::string sModule = module;
267        std::string moduleList = "";
268        {
269                ReadLock readLock(&m_mutexRW, true, 10000);
270                if (!readLock.IsLocked()) {
271                        LOG_ERROR("FATAL ERROR: Could not get read-mutex.");
272                        return -1;
273                }
274                for (pluginList::size_type i=0;i<plugins_.size();++i) {
275                        NSCPlugin *p = plugins_[i];
276                        if (!moduleList.empty())
277                                moduleList += ", ";
278                        moduleList += p->getModule();
279                        if (p->getModule() == sModule) {
280                                LOG_DEBUG_STD("Found module: " + p->getName() + "...");
281                                try {
282                                        return p->commandLineExec(command, argLen, args);
283                                } catch (NSPluginException e) {
284                                        LOG_ERROR_STD("Could not execute command: " + e.error_ + " in " + e.file_);
285                                        return -1;
286                                }
287                        }
288                }
289        }
290        LOG_MESSAGE_STD("Module was not loaded, attempt to load it");
291        try {
292                plugin_type plugin = loadPlugin(getBasePath() + "modules\\" + module);
293                LOG_DEBUG_STD("Loading plugin: " + plugin->getName() + "...");
294                plugin->load_plugin();
295                return plugin->commandLineExec(command, argLen, args);
296        } catch (NSPluginException e) {
297                LOG_MESSAGE_STD("Module (" + e.file_ + ") was not found: " + e.error_);
298        }
299        try {
300                plugin_type plugin = loadPlugin(getBasePath() + "modules\\" + module + ".dll");
301                LOG_DEBUG_STD("Loading plugin: " + plugin->getName() + "...");
302                plugin->load_plugin();
303                return plugin->commandLineExec(command, argLen, args);
304        } catch (NSPluginException e) {
305                LOG_MESSAGE_STD("Module (" + e.file_ + ") was not found: " + e.error_);
306        }
307        LOG_ERROR_STD("Module not found: " + module + " available modules are: " + moduleList);
308        return 0;
309}
310
311/**
312 * Load a list of plug-ins
313 * @param plugins A list with plug-ins (DLL files) to load
314 */
315void NSClientT::addPlugins(const std::list<std::string> plugins) {
316        ReadLock readLock(&m_mutexRW, true, 10000);
317        if (!readLock.IsLocked()) {
318                LOG_ERROR("FATAL ERROR: Could not get read-mutex.");
319                return;
320        }
321        std::list<std::string>::const_iterator it;
322        for (it = plugins.begin(); it != plugins.end(); ++it) {
323                loadPlugin(*it);
324        }
325}
326/**
327 * Unload all plug-ins (in reversed order)
328 */
329void NSClientT::unloadPlugins() {
330        {
331                WriteLock writeLock(&m_mutexRW, true, 10000);
332                if (!writeLock.IsLocked()) {
333                        LOG_ERROR("FATAL ERROR: Could not get read-mutex.");
334                        return;
335                }
336                commandHandlers_.clear();
337                messageHandlers_.clear();
338        }
339        {
340                ReadLock readLock(&m_mutexRW, true, 10000);
341                if (!readLock.IsLocked()) {
342                        LOG_ERROR("FATAL ERROR: Could not get read-mutex.");
343                        return;
344                }
345                for (pluginList::size_type i=plugins_.size();i>0;i--) {
346                        NSCPlugin *p = plugins_[i-1];
347                        LOG_DEBUG_STD("Unloading plugin: " + p->getName() + "...");
348                        p->unload();
349                }
350        }
351        {
352                WriteLock writeLock(&m_mutexRW, true, 10000);
353                if (!writeLock.IsLocked()) {
354                        LOG_ERROR("FATAL ERROR: Could not get read-mutex.");
355                        return;
356                }
357                for (pluginList::size_type i=plugins_.size();i>0;i--) {
358                        NSCPlugin *p = plugins_[i-1];
359                        plugins_[i-1] = NULL;
360                        delete p;
361                }
362                plugins_.clear();
363        }
364}
365
366void NSClientT::loadPlugins() {
367        ReadLock readLock(&m_mutexRW, true, 10000);
368        if (!readLock.IsLocked()) {
369                LOG_ERROR("FATAL ERROR: Could not get read-mutex.");
370                return;
371        }
372        for (pluginList::iterator it=plugins_.begin(); it != plugins_.end(); ++it) {
373                LOG_DEBUG_STD("Loading plugin: " + (*it)->getName() + "...");
374                (*it)->load_plugin();
375        }
376}
377/**
378 * Load a single plug-in using a DLL filename
379 * @param file The DLL file
380 */
381NSClientT::plugin_type NSClientT::loadPlugin(const std::string file) {
382        return addPlugin(new NSCPlugin(file));
383}
384/**
385 * Load and add a plugin to various internal structures
386 * @param *plugin The plug-ininstance to load. The pointer is managed by the
387 */
388NSClientT::plugin_type NSClientT::addPlugin(plugin_type plugin) {
389        plugin->load_dll();
390        {
391                WriteLock writeLock(&m_mutexRW, true, 10000);
392                if (!writeLock.IsLocked()) {
393                        LOG_ERROR("FATAL ERROR: Could not get read-mutex.");
394                        return plugin;
395                }
396                plugins_.insert(plugins_.end(), plugin);
397                if (plugin->hasCommandHandler())
398                        commandHandlers_.insert(commandHandlers_.end(), plugin);
399                if (plugin->hasMessageHandler())
400                        messageHandlers_.insert(messageHandlers_.end(), plugin);
401        }
402        return plugin;
403}
404
405NSCAPI::nagiosReturn NSClientT::inject(std::string command, std::string arguments, char splitter, std::string &msg, std::string & perf) {
406        unsigned int aLen = 0;
407        char ** aBuf = arrayBuffer::split2arrayBuffer(arguments, splitter, aLen);
408        char * mBuf = new char[1024];
409        char * pBuf = new char[1024];
410        NSCAPI::nagiosReturn ret = injectRAW(command.c_str(), aLen, aBuf, mBuf, 1023, pBuf, 1023);
411        arrayBuffer::destroyArrayBuffer(aBuf, aLen);
412        if ( (ret == NSCAPI::returnInvalidBufferLen) || (ret == NSCAPI::returnIgnored) ) {
413                delete [] mBuf;
414                delete [] pBuf;
415                return ret;
416        }
417        msg = mBuf;
418        perf = pBuf;
419        delete [] mBuf;
420        delete [] pBuf;
421        return ret;
422}
423
424/**
425 * Inject a command into the plug-in stack.
426 *
427 * @param command Command to inject
428 * @param argLen Length of argument buffer
429 * @param **argument Argument buffer
430 * @param *returnMessageBuffer Message buffer
431 * @param returnMessageBufferLen Length of returnMessageBuffer
432 * @param *returnPerfBuffer Performance data buffer
433 * @param returnPerfBufferLen Length of returnPerfBuffer
434 * @return The command status
435 */
436NSCAPI::nagiosReturn NSClientT::injectRAW(const char* command, const unsigned int argLen, char **argument, char *returnMessageBuffer, unsigned int returnMessageBufferLen, char *returnPerfBuffer, unsigned int returnPerfBufferLen) {
437        if (logDebug()) {
438                LOG_DEBUG_STD("Injecting: " + (std::string) command + ": " + arrayBuffer::arrayBuffer2string(argument, argLen, ", "));
439        }
440        ReadLock readLock(&m_mutexRW, true, 5000);
441        if (!readLock.IsLocked()) {
442                LOG_ERROR("FATAL ERROR: Could not get read-mutex.");
443                return NSCAPI::returnUNKNOWN;
444        }
445        for (pluginList::size_type i = 0; i < commandHandlers_.size(); i++) {
446                try {
447                        NSCAPI::nagiosReturn c = commandHandlers_[i]->handleCommand(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen);
448                        switch (c) {
449                                case NSCAPI::returnInvalidBufferLen:
450                                        LOG_ERROR("UNKNOWN: Return buffer to small to handle this command.");
451                                        return c;
452                                case NSCAPI::returnIgnored:
453                                        break;
454                                case NSCAPI::returnOK:
455                                case NSCAPI::returnWARN:
456                                case NSCAPI::returnCRIT:
457                                case NSCAPI::returnUNKNOWN:
458                                        LOG_DEBUG_STD("Injected Result: " + NSCHelper::translateReturn(c) + "  --  " + (std::string)(returnMessageBuffer));
459                                        LOG_DEBUG_STD("Injected Performance Result: " +(std::string) returnPerfBuffer);
460                                        return c;
461                                default:
462                                        LOG_ERROR_STD("Unknown error from handleCommand: " + strEx::itos(c) + " the injected command was: " + (std::string)command);
463                                        return c;
464                        }
465                } catch(const NSPluginException& e) {
466                        LOG_ERROR_STD("Exception raised: " + e.error_ + " in module: " + e.file_);
467                        return NSCAPI::returnCRIT;
468                }
469        }
470        LOG_MESSAGE_STD("No handler for command: '" + command + "'");
471        return NSCAPI::returnIgnored;
472}
473
474bool NSClientT::logDebug() {
475        typedef enum status {unknown, debug, nodebug };
476        static status d = unknown;
477        if (d == unknown) {
478                try {
479                        if (Settings::getInstance()->getInt("log", "debug", 0) == 1)
480                                d = debug;
481                        else
482                                d = nodebug;
483                } catch (SettingsException e) {
484                        d = debug;
485                }
486        }
487        return (d == debug);
488}
489
490/**
491 * Report a message to all logging enabled modules.
492 *
493 * @param msgType Message type
494 * @param file Filename generally __FILE__
495 * @param line  Line number, generally __LINE__
496 * @param message The message as a human readable string.
497 */
498void NSClientT::reportMessage(int msgType, const char* file, const int line, std::string message) {
499        if ((msgType == NSCAPI::debug)&&(!logDebug())) {
500                return;
501        }
502        std::string file_stl = file;
503        std::string::size_type pos = file_stl.find_last_of("\\");
504        if (pos != std::string::npos)
505                file_stl = file_stl.substr(pos);
506        {
507                ReadLock readLock(&m_mutexRW, true, 5000);
508                if (!readLock.IsLocked()) {
509                        std::cout << "Message was lost as the core was locked..." << std::endl;
510                        return;
511                }
512                MutexLock lock(messageMutex);
513                if (!lock.hasMutex()) {
514                        std::cout << "Message was lost as the core was locked..." << std::endl;
515                        std::cout << message << std::endl;
516                        return;
517                }
518                if (g_bConsoleLog) {
519                        std::string k = "?";
520                        switch (msgType) {
521                        case NSCAPI::critical:
522                                k ="c";
523                                break;
524                        case NSCAPI::warning:
525                                k ="w";
526                                break;
527                        case NSCAPI::error:
528                                k ="e";
529                                break;
530                        case NSCAPI::log:
531                                k ="l";
532                                break;
533                        case NSCAPI::debug:
534                                k ="d";
535                                break;
536                        }
537                        std::cout << k << " " << file_stl << "(" << line << ") " << message << std::endl;
538                }
539                for (pluginList::size_type i = 0; i< messageHandlers_.size(); i++) {
540                        try {
541                                messageHandlers_[i]->handleMessage(msgType, file, line, message.c_str());
542                        } catch(const NSPluginException& e) {
543                                // Here we are pretty much fucked! (as logging this might cause a loop :)
544                                std::cout << "Caught: " << e.error_ << " when trying to log a message..." << std::endl;
545                                std::cout << "This is *really really* bad, now the world is about to end..." << std::endl;
546                        }
547                }
548        }
549}
550std::string NSClientT::getBasePath(void) {
551        MutexLock lock(internalVariables);
552        if (!lock.hasMutex()) {
553                LOG_ERROR("FATAL ERROR: Could not get mutex.");
554                return "FATAL ERROR";
555        }
556        if (!basePath.empty())
557                return basePath;
558        char* buffer = new char[1024];
559        GetModuleFileName(NULL, buffer, 1023);
560        std::string path = buffer;
561        std::string::size_type pos = path.rfind('\\');
562        basePath = path.substr(0, pos) + "\\";
563        delete [] buffer;
564        try {
565                Settings::getInstance()->setFile(basePath, "NSC.ini");
566        } catch (SettingsException e) {
567                NSC_LOG_ERROR_STD("Failed to set settings file" + e.getMessage());
568        }
569        return basePath;
570}
571
572
573NSCAPI::errorReturn NSAPIGetSettingsString(const char* section, const char* key, const char* defaultValue, char* buffer, unsigned int bufLen) {
574        return NSCHelper::wrapReturnString(buffer, bufLen, Settings::getInstance()->getString(section, key, defaultValue), NSCAPI::isSuccess);
575}
576int NSAPIGetSettingsInt(const char* section, const char* key, int defaultValue) {
577        try {
578                return Settings::getInstance()->getInt(section, key, defaultValue);
579        } catch (SettingsException e) {
580                NSC_LOG_ERROR_STD("Failed to set settings file" + e.getMessage());
581        }
582}
583NSCAPI::errorReturn NSAPIGetBasePath(char*buffer, unsigned int bufLen) {
584        return NSCHelper::wrapReturnString(buffer, bufLen, mainClient.getBasePath(), NSCAPI::isSuccess);
585}
586NSCAPI::errorReturn NSAPIGetApplicationName(char*buffer, unsigned int bufLen) {
587        return NSCHelper::wrapReturnString(buffer, bufLen, SZAPPNAME, NSCAPI::isSuccess);
588}
589NSCAPI::errorReturn NSAPIGetApplicationVersionStr(char*buffer, unsigned int bufLen) {
590        return NSCHelper::wrapReturnString(buffer, bufLen, SZVERSION, NSCAPI::isSuccess);
591}
592void NSAPIMessage(int msgType, const char* file, const int line, const char* message) {
593        mainClient.reportMessage(msgType, file, line, message);
594}
595void NSAPIStopServer(void) {
596        serviceControll::Stop(SZSERVICENAME);
597}
598NSCAPI::nagiosReturn NSAPIInject(const char* command, const unsigned int argLen, char **argument, char *returnMessageBuffer, unsigned int returnMessageBufferLen, char *returnPerfBuffer, unsigned int returnPerfBufferLen) {
599        return mainClient.injectRAW(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen);
600}
601NSCAPI::errorReturn NSAPIGetSettingsSection(const char* section, char*** aBuffer, unsigned int * bufLen) {
602        unsigned int len = 0;
603        *aBuffer = arrayBuffer::list2arrayBuffer(Settings::getInstance()->getSection(section), len);
604        *bufLen = len;
605        return NSCAPI::isSuccess;
606}
607NSCAPI::errorReturn NSAPIReleaseSettingsSectionBuffer(char*** aBuffer, unsigned int * bufLen) {
608        arrayBuffer::destroyArrayBuffer(*aBuffer, *bufLen);
609        *bufLen = 0;
610        *aBuffer = NULL;
611        return NSCAPI::isSuccess;
612}
613
614NSCAPI::boolReturn NSAPICheckLogMessages(int messageType) {
615        if (mainClient.logDebug())
616                return NSCAPI::istrue;
617        return NSCAPI::isfalse;
618}
619
620std::string Encrypt(std::string str, unsigned int algorithm) {
621        unsigned int len = 0;
622        NSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
623        len+=2;
624        char *buf = new char[len+1];
625        NSCAPI::errorReturn ret = NSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
626        if (ret == NSCAPI::isSuccess) {
627                std::string ret = buf;
628                delete [] buf;
629                return ret;
630        }
631        return "";
632}
633std::string Decrypt(std::string str, unsigned int algorithm) {
634        unsigned int len = 0;
635        NSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
636        len+=2;
637        char *buf = new char[len+1];
638        NSCAPI::errorReturn ret = NSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
639        if (ret == NSCAPI::isSuccess) {
640                std::string ret = buf;
641                delete [] buf;
642                return ret;
643        }
644        return "";
645}
646
647NSCAPI::errorReturn NSAPIEncrypt(unsigned int algorithm, const char* inBuffer, unsigned int inBufLen, char* outBuf, unsigned int *outBufLen) {
648        if (algorithm != NSCAPI::xor) {
649                LOG_ERROR("Unknown algortihm requested.");
650                return NSCAPI::hasFailed;
651        }
652        std::string s = inBuffer;
653        std::string key = Settings::getInstance()->getString(MAIN_SECTION_TITLE, MAIN_MASTERKEY, MAIN_MASTERKEY_DEFAULT);
654        char *c = new char[inBufLen+1];
655        strncpy_s(c, inBufLen+1, inBuffer, inBufLen);
656        for (unsigned int i=0,j=0;i<inBufLen;i++,j++) {
657                if (j > key.size())
658                        j = 0;
659                c[i] ^= key[j];
660        }
661        size_t len = b64::b64_encode(reinterpret_cast<void*>(c), inBufLen, outBuf, *outBufLen);
662        delete [] c;
663        if (outBuf) {
664                if ((len == 0)||(len >= *outBufLen)) {
665                        LOG_ERROR("Invalid out buffer length.");
666                        return NSCAPI::isInvalidBufferLen;
667                }
668                outBuf[len] = 0;
669                *outBufLen = static_cast<unsigned int>(len);
670        } else {
671                *outBufLen = static_cast<unsigned int>(len);
672        }
673        return NSCAPI::isSuccess;
674}
675
676NSCAPI::errorReturn NSAPIDecrypt(unsigned int algorithm, const char* inBuffer, unsigned int inBufLen, char* outBuf, unsigned int *outBufLen) {
677        if (algorithm != NSCAPI::xor) {
678                LOG_ERROR("Unknown algortihm requested.");
679                return NSCAPI::hasFailed;
680        }
681        size_t len =  b64::b64_decode(inBuffer, inBufLen, reinterpret_cast<void*>(outBuf), *outBufLen);
682        if (outBuf) {
683                if ((len == 0)||(len >= *outBufLen)) {
684                        LOG_ERROR("Invalid out buffer length.");
685                        return NSCAPI::isInvalidBufferLen;
686                }
687                std::string key = Settings::getInstance()->getString(MAIN_SECTION_TITLE, MAIN_MASTERKEY, MAIN_MASTERKEY_DEFAULT);
688                for (unsigned int i=0,j=0;i<len;i++,j++) {
689                        if (j > key.size())
690                                j = 0;
691                        outBuf[i] ^= key[j];
692                }
693                outBuf[len] = 0;
694                *outBufLen = static_cast<unsigned int>(len);
695        } else {
696                *outBufLen = static_cast<unsigned int>(len);
697        }
698        return NSCAPI::isSuccess;
699}
700
701NSCAPI::errorReturn NSAPISetSettingsString(const char* section, const char* key, const char* value) {
702        Settings::getInstance()->setString(section, key, value);
703        return NSCAPI::isSuccess;
704}
705NSCAPI::errorReturn NSAPISetSettingsInt(const char* section, const char* key, int value) {
706        Settings::getInstance()->setInt(section, key, value);
707        return NSCAPI::isSuccess;
708}
709NSCAPI::errorReturn NSAPIWriteSettings(int type) {
710        try {
711                if (type == NSCAPI::settings_registry)
712                        Settings::getInstance()->write(REGSettings::getType());
713                else if (type == NSCAPI::settings_inifile)
714                        Settings::getInstance()->write(INISettings::getType());
715                else
716                        Settings::getInstance()->write();
717        } catch (SettingsException e) {
718                LOG_ERROR_STD(e.getMessage());
719                return NSCAPI::hasFailed;
720        }
721        return NSCAPI::isSuccess;
722}
723NSCAPI::errorReturn NSAPIReadSettings(int type) {
724        try {
725                if (type == NSCAPI::settings_registry)
726                        Settings::getInstance()->read(REGSettings::getType());
727                else if (type == NSCAPI::settings_inifile)
728                        Settings::getInstance()->read(INISettings::getType());
729                else
730                        Settings::getInstance()->read();
731        } catch (SettingsException e) {
732                LOG_ERROR_STD(e.getMessage());
733                return NSCAPI::hasFailed;
734        }
735        return NSCAPI::isSuccess;
736}
737NSCAPI::errorReturn NSAPIRehash(int flag) {
738        return NSCAPI::hasFailed;
739}
740
741
742LPVOID NSAPILoader(char*buffer) {
743        if (_stricmp(buffer, "NSAPIGetApplicationName") == 0)
744                return &NSAPIGetApplicationName;
745        if (_stricmp(buffer, "NSAPIGetApplicationVersionStr") == 0)
746                return &NSAPIGetApplicationVersionStr;
747        if (_stricmp(buffer, "NSAPIGetSettingsString") == 0)
748                return &NSAPIGetSettingsString;
749        if (_stricmp(buffer, "NSAPIGetSettingsSection") == 0)
750                return &NSAPIGetSettingsSection;
751        if (_stricmp(buffer, "NSAPIReleaseSettingsSectionBuffer") == 0)
752                return &NSAPIReleaseSettingsSectionBuffer;
753        if (_stricmp(buffer, "NSAPIGetSettingsInt") == 0)
754                return &NSAPIGetSettingsInt;
755        if (_stricmp(buffer, "NSAPIMessage") == 0)
756                return &NSAPIMessage;
757        if (_stricmp(buffer, "NSAPIStopServer") == 0)
758                return &NSAPIStopServer;
759        if (_stricmp(buffer, "NSAPIInject") == 0)
760                return &NSAPIInject;
761        if (_stricmp(buffer, "NSAPIGetBasePath") == 0)
762                return &NSAPIGetBasePath;
763        if (_stricmp(buffer, "NSAPICheckLogMessages") == 0)
764                return &NSAPICheckLogMessages;
765        if (_stricmp(buffer, "NSAPIEncrypt") == 0)
766                return &NSAPIEncrypt;
767        if (_stricmp(buffer, "NSAPIDecrypt") == 0)
768                return &NSAPIDecrypt;
769        if (_stricmp(buffer, "NSAPISetSettingsString") == 0)
770                return &NSAPISetSettingsString;
771        if (_stricmp(buffer, "NSAPISetSettingsInt") == 0)
772                return &NSAPISetSettingsInt;
773        if (_stricmp(buffer, "NSAPIWriteSettings") == 0)
774                return &NSAPIWriteSettings;
775        if (_stricmp(buffer, "NSAPIReadSettings") == 0)
776                return &NSAPIReadSettings;
777        if (_stricmp(buffer, "NSAPIRehash") == 0)
778                return &NSAPIRehash;
779        return NULL;
780}
Note: See TracBrowser for help on using the repository browser.