source: nscp/NSClient++.cpp @ 99e4d8f

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

2007-11-23 MickeM

  • Converted to unicode (damn sometimes I HATE C++) + Added support for escaping " on the /test syntax so now you can do: CheckWMI MaxCrit=3 "MinWarn=1" "Query:load=Select * from win32_Processor"

2007-11-22 MickeM

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