source: nscp/include/NSCHelper.cpp @ 7f9c823

0.4.00.4.10.4.2
Last change on this file since 7f9c823 was 7f9c823, checked in by Michael Medin <michael@…>, 4 years ago

First attempt at serious boostification.
NOTICE! This is NOT a complete edition, it build and runs but many features are disabled and/or broken.
But we have working, sockets and mutexes and conversion functions from boost inside now and more to come...
Also started to build with CMake since it works better then boost.build

  • Property mode set to 100644
File size: 33.0 KB
Line 
1/**************************************************************************
2*   Copyright (C) 2004-2007 by Michael Medin <michael@medin.name>         *
3*                                                                         *
4*   This code is part of NSClient++ - http://trac.nakednuns.org/nscp      *
5*                                                                         *
6*   This program is free software; you can redistribute it and/or modify  *
7*   it under the terms of the GNU General Public License as published by  *
8*   the Free Software Foundation; either version 2 of the License, or     *
9*   (at your option) any later version.                                   *
10*                                                                         *
11*   This program is distributed in the hope that it will be useful,       *
12*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14*   GNU General Public License for more details.                          *
15*                                                                         *
16*   You should have received a copy of the GNU General Public License     *
17*   along with this program; if not, write to the                         *
18*   Free Software Foundation, Inc.,                                       *
19*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
20***************************************************************************/
21
22#include <NSCHelper.h>
23#include <nsc_module_wrapper.hpp>
24#include <msvc_wrappers.h>
25#include <settings/macros.h>
26#include <arrayBuffer.h>
27//#include <config.h>
28#include <strEx.h>
29
30#ifdef DEBUG
31/**
32* Wrap a return string.
33* This function copies a string to a char buffer making sure the buffer has the correct length.
34*
35* @param *buffer Buffer to copy the string to.
36* @param bufLen Length of the buffer
37* @param str Th string to copy
38* @return NSCAPI::success unless the buffer is to short then it will be NSCAPI::invalidBufferLen
39*/
40NSCAPI::nagiosReturn NSCHelper::wrapReturnString(char *buffer, unsigned int bufLen, std::wstring str, NSCAPI::nagiosReturn defaultReturnCode /* = NSCAPI::success */) {
41        if (str.length() >= bufLen)
42                return NSCAPI::returnInvalidBufferLen;
43        strncpy(buffer, str.c_str(), bufLen);
44        return defaultReturnCode;
45}
46/**
47* Wrap a return string.
48* This function copies a string to a char buffer making sure the buffer has the correct length.
49*
50* @param *buffer Buffer to copy the string to.
51* @param bufLen Length of the buffer
52* @param str Th string to copy
53* @return NSCAPI::success unless the buffer is to short then it will be NSCAPI::invalidBufferLen
54*/
55NSCAPI::errorReturn NSCHelper::wrapReturnString(char *buffer, unsigned int bufLen, std::wstring str, NSCAPI::errorReturn defaultReturnCode /* = NSCAPI::success */) {
56        if (str.length() >= bufLen)
57                return NSCAPI::isInvalidBufferLen;
58        strncpy(buffer, str.c_str(), bufLen);
59        return defaultReturnCode;
60}
61#else
62/**
63* Wrap a return string.
64* This function copies a string to a char buffer making sure the buffer has the correct length.
65*
66* @param *buffer Buffer to copy the string to.
67* @param bufLen Length of the buffer
68* @param str Th string to copy
69* @param defaultReturnCode The default return code
70* @return NSCAPI::success unless the buffer is to short then it will be NSCAPI::invalidBufferLen
71*/
72int NSCHelper::wrapReturnString(wchar_t *buffer, unsigned int bufLen, std::wstring str, int defaultReturnCode ) {
73        // @todo deprecate this
74        if (str.length() >= bufLen) {
75                std::wstring sstr = str.substr(0, min(10, str.length()));
76                NSC_DEBUG_MSG_STD(_T("String (") + strEx::itos(str.length()) + _T(") to long to fit inside buffer(") + strEx::itos(bufLen) + _T(") : ") + sstr);
77                return NSCAPI::isInvalidBufferLen;
78        }
79        wcsncpy_s(buffer, bufLen, str.c_str(), bufLen);
80        return defaultReturnCode;
81}
82#endif
83
84
85/**
86 * Translate a message type into a human readable string.
87 *
88 * @param msgType The message type
89 * @return A string representing the message type
90 */
91std::wstring NSCHelper::translateMessageType(NSCAPI::messageTypes msgType) {
92        switch (msgType) {
93                case NSCAPI::error:
94                        return _T("error");
95                case NSCAPI::critical:
96                        return _T("critical");
97                case NSCAPI::warning:
98                        return _T("warning");
99                case NSCAPI::log:
100                        return _T("message");
101                case NSCAPI::debug:
102                        return _T("debug");
103        }
104        return _T("unknown");
105}
106/**
107 * Translate a return code into the corresponding string
108 * @param returnCode
109 * @return
110 */
111std::wstring NSCHelper::translateReturn(NSCAPI::nagiosReturn returnCode) {
112        if (returnCode == NSCAPI::returnOK)
113                return _T("OK");
114        else if (returnCode == NSCAPI::returnCRIT)
115                return _T("CRITICAL");
116        else if (returnCode == NSCAPI::returnWARN)
117                return _T("WARNING");
118        else if (returnCode == NSCAPI::returnUNKNOWN)
119                return _T("WARNING");
120        else
121                return _T("BAD_CODE");
122}
123/**
124* Translate a string into the corresponding return code
125* @param returnCode
126* @return
127*/
128NSCAPI::nagiosReturn NSCHelper::translateReturn(std::wstring str) {
129        if (str == _T("OK"))
130                return NSCAPI::returnOK;
131        else if (str == _T("CRITICAL"))
132                return NSCAPI::returnCRIT;
133        else if (str == _T("WARNING"))
134                return NSCAPI::returnWARN;
135        else
136                return NSCAPI::returnUNKNOWN;
137}
138
139
140
141namespace NSCModuleHelper {
142        lpNSAPIGetBasePath fNSAPIGetBasePath = NULL;
143        lpNSAPIGetApplicationName fNSAPIGetApplicationName = NULL;
144        lpNSAPIGetApplicationVersionStr fNSAPIGetApplicationVersionStr = NULL;
145        lpNSAPIGetSettingsSection fNSAPIGetSettingsSection = NULL;
146        lpNSAPIReleaseSettingsSectionBuffer fNSAPIReleaseSettingsSectionBuffer = NULL;
147        lpNSAPIGetSettingsString fNSAPIGetSettingsString = NULL;
148        lpNSAPIGetSettingsInt fNSAPIGetSettingsInt = NULL;
149        lpNSAPIMessage fNSAPIMessage = NULL;
150        lpNSAPIStopServer fNSAPIStopServer = NULL;
151        lpNSAPIExit fNSAPIExit = NULL;
152        lpNSAPIInject fNSAPIInject = NULL;
153        lpNSAPICheckLogMessages fNSAPICheckLogMessages = NULL;
154        lpNSAPIEncrypt fNSAPIEncrypt = NULL;
155        lpNSAPIDecrypt fNSAPIDecrypt = NULL;
156        lpNSAPISetSettingsString fNSAPISetSettingsString = NULL;
157        lpNSAPISetSettingsInt fNSAPISetSettingsInt = NULL;
158        lpNSAPIWriteSettings fNSAPIWriteSettings = NULL;
159        lpNSAPIReadSettings fNSAPIReadSettings = NULL;
160        lpNSAPIRehash fNSAPIRehash = NULL;
161        lpNSAPIDescribeCommand fNSAPIDescribeCommand= NULL;
162        lpNSAPIGetAllCommandNames fNSAPIGetAllCommandNames= NULL;
163        lpNSAPIReleaseAllCommandNamessBuffer fNSAPIReleaseAllCommandNamessBuffer= NULL;
164        lpNSAPIRegisterCommand fNSAPIRegisterCommand= NULL;
165        lpNSAPISettingsRegKey fNSAPISettingsRegKey = NULL;
166        lpNSAPISettingsRegPath fNSAPISettingsRegPath = NULL;
167        lpNSAPIGetPluginList fNSAPIGetPluginList = NULL;
168        lpNSAPIReleasePluginList fNSAPIReleasePluginList = NULL;
169        lpNSAPISettingsSave fNSAPISettingsSave = NULL;
170
171        unsigned int buffer_length;
172
173}
174
175//////////////////////////////////////////////////////////////////////////
176// Callbacks into the core
177//////////////////////////////////////////////////////////////////////////
178
179/**
180 * Callback to send a message through to the core
181 *
182 * @param msgType Message type (debug, warning, etc.)
183 * @param file File where message was generated (__FILE__)
184 * @param line Line where message was generated (__LINE__)
185 * @param message Message in human readable format
186 * @throws NSCMHExcpetion When core pointer set is unavailable.
187 */
188void NSCModuleHelper::Message(int msgType, std::wstring file, int line, std::wstring message) {
189        if (fNSAPIMessage) {
190                if ((msgType == NSCAPI::debug) && (!logDebug()))
191                        return;
192                /*
193                std::wstring::size_type pos = file.find_last_of("\\");
194                if (pos != std::wstring::npos)
195                        file = file.substr(pos);
196                        */
197                return fNSAPIMessage(msgType, file.c_str(), line, message.c_str());
198        }
199        else
200                std::wcout << _T("*** *** *** NSCore not loaded, dumping log: ") << file << _T(":") << line << _T(": ") << std::endl << message << std::endl;
201}
202/**
203 * Inject a request command in the core (this will then be sent to the plug-in stack for processing)
204 * @param command Command to inject (password should not be included.
205 * @return The result (if any) of the command.
206 * @throws NSCMHExcpetion When core pointer set is unavailable or an unknown inject error occurs.
207 */
208
209/**
210 * Inject a request command in the core (this will then be sent to the plug-in stack for processing)
211 * @param command Command to inject
212 * @param argLen The length of the argument buffer
213 * @param **argument The argument buffer
214 * @param *returnMessageBuffer Buffer to hold the returned message
215 * @param returnMessageBufferLen Length of returnMessageBuffer
216 * @param *returnPerfBuffer Buffer to hold the returned performance data
217 * @param returnPerfBufferLen returnPerfBuffer
218 * @return The returned status of the command
219 */
220NSCAPI::nagiosReturn NSCModuleHelper::InjectCommandRAW(const wchar_t* command, const unsigned int argLen, TCHAR **argument, TCHAR *returnMessageBuffer, unsigned int returnMessageBufferLen, TCHAR *returnPerfBuffer, unsigned int returnPerfBufferLen)
221{
222        if (!fNSAPIInject)
223                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
224        return fNSAPIInject(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen);
225}
226/**
227 * Inject a request command in the core (this will then be sent to the plug-in stack for processing)
228 * @param command Command to inject (password should not be included.
229 * @param argLen The length of the argument buffer
230 * @param **argument The argument buffer
231 * @param message The return message buffer
232 * @param perf The return performance data buffer
233 * @return The return of the command
234 */
235NSCAPI::nagiosReturn NSCModuleHelper::InjectCommand(const TCHAR* command, const unsigned int argLen, TCHAR **argument, std::wstring & message, std::wstring & perf)
236{
237        if (!fNSAPIInject)
238                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
239        unsigned int buf_len = getBufferLength();
240        TCHAR *msgBuffer = new TCHAR[buf_len+1];
241        TCHAR *perfBuffer = new TCHAR[buf_len+1];
242        msgBuffer[0] = 0;
243        perfBuffer[0] = 0;
244        NSCAPI::nagiosReturn retC = InjectCommandRAW(command, argLen, argument, msgBuffer, buf_len, perfBuffer, buf_len);
245        switch (retC) {
246                case NSCAPI::returnIgnored:
247                        NSC_LOG_MESSAGE_STD(_T("No handler for command '") + command + _T("'."));
248                        break;
249                case NSCAPI::returnInvalidBufferLen:
250                        NSC_LOG_ERROR(_T("Inject buffer to small, increase the value of: string_length."));
251                        break;
252                case NSCAPI::returnOK:
253                case NSCAPI::returnCRIT:
254                case NSCAPI::returnWARN:
255                case NSCAPI::returnUNKNOWN:
256                        message = msgBuffer;
257                        perf = perfBuffer;
258                        break;
259                default:
260                        delete [] msgBuffer;
261                        delete [] perfBuffer;
262                        throw NSCMHExcpetion(_T("Unknown return code when injecting: ") + std::wstring(command));
263        }
264        delete [] msgBuffer;
265        delete [] perfBuffer;
266        return retC;
267}
268
269/**
270* Inject a request command in the core (this will then be sent to the plug-in stack for processing)
271* @param command Command to inject (password should not be included.
272* @param argLen The length of the argument buffer
273* @param **argument The argument buffer
274* @param message The return message buffer
275* @param perf The return performance data buffer
276* @return The return of the command
277*/
278NSCAPI::nagiosReturn NSCModuleHelper::InjectCommand(const TCHAR* command, std::list<std::wstring> argument, std::wstring & message, std::wstring & perf)
279{
280        if (!fNSAPIInject)
281                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
282        unsigned int buf_len = getBufferLength();
283
284
285        unsigned int argLen;
286        TCHAR ** aBuffer = arrayBuffer::list2arrayBuffer(argument, argLen);
287        TCHAR *msgBuffer = new TCHAR[buf_len+1];
288        TCHAR *perfBuffer = new TCHAR[buf_len+1];
289        msgBuffer[0] = 0;
290        perfBuffer[0] = 0;
291        NSCAPI::nagiosReturn retC = InjectCommandRAW(command, argLen, aBuffer, msgBuffer, buf_len, perfBuffer, buf_len);
292        arrayBuffer::destroyArrayBuffer(aBuffer, argLen);
293        switch (retC) {
294                case NSCAPI::returnIgnored:
295                        NSC_LOG_MESSAGE_STD(_T("No handler for command '") + command + _T("'."));
296                        break;
297                case NSCAPI::returnInvalidBufferLen:
298                        NSC_LOG_ERROR(_T("Inject buffer to small, increase the value of: string_length."));
299                        break;
300                case NSCAPI::returnOK:
301                case NSCAPI::returnCRIT:
302                case NSCAPI::returnWARN:
303                case NSCAPI::returnUNKNOWN:
304                        message = msgBuffer;
305                        perf = perfBuffer;
306                        break;
307                default:
308                        delete [] msgBuffer;
309                        delete [] perfBuffer;
310                        throw NSCMHExcpetion(_T("Unknown return code when injecting: ") + std::wstring(command));
311        }
312        delete [] msgBuffer;
313        delete [] perfBuffer;
314        return retC;
315}
316
317/**
318 * A wrapper around the InjetCommand that is simpler to use.
319 * Parses a string by splitting and makes the array and also manages return buffers and such.
320 * @param command The command to execute
321 * @param buffer The buffer to split
322 * @param splitChar The char to use as splitter
323 * @param message The return message buffer
324 * @param perf The return performance data buffer
325 * @return The result of the command
326 */
327NSCAPI::nagiosReturn NSCModuleHelper::InjectSplitAndCommand(const TCHAR* command, TCHAR* buffer, TCHAR splitChar, std::wstring & message, std::wstring & perf)
328{
329        if (!fNSAPIInject)
330                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
331        unsigned int argLen = 0;
332        TCHAR ** aBuffer;
333        if (buffer)
334                aBuffer= arrayBuffer::split2arrayBuffer(buffer, splitChar, argLen);
335        else
336                aBuffer= arrayBuffer::createEmptyArrayBuffer(argLen);
337        NSCAPI::nagiosReturn ret = InjectCommand(command, argLen, aBuffer, message, perf);
338        arrayBuffer::destroyArrayBuffer(aBuffer, argLen);
339        return ret;
340}
341/**
342 * A wrapper around the InjetCommand that is simpler to use.
343 * @param command The command to execute
344 * @param buffer The buffer to split
345 * @param splitChar The char to use as splitter
346 * @param message The return message buffer
347 * @param perf The return performance data buffer
348 * @return The result of the command
349 */
350NSCAPI::nagiosReturn NSCModuleHelper::InjectSplitAndCommand(const std::wstring command, const std::wstring buffer, TCHAR splitChar, std::wstring & message, std::wstring & perf, bool escape)
351{
352        if (!fNSAPIInject)
353                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
354        unsigned int argLen = 0;
355        TCHAR ** aBuffer;
356        if (buffer.empty())
357                aBuffer= arrayBuffer::createEmptyArrayBuffer(argLen);
358        else
359                aBuffer= arrayBuffer::split2arrayBuffer(buffer, splitChar, argLen, escape);
360        NSCAPI::nagiosReturn ret = InjectCommand(command.c_str(), argLen, aBuffer, message, perf);
361        arrayBuffer::destroyArrayBuffer(aBuffer, argLen);
362        return ret;
363}
364/**
365 * Ask the core to shutdown (only works when run as a service, o/w does nothing ?
366 * @todo Check if this might cause damage if not run as a service.
367 */
368void NSCModuleHelper::StopService(void) {
369        if (fNSAPIStopServer)
370                fNSAPIStopServer();
371}
372/**
373 * Close the program (usefull for tray/testmode) without stopping the service (unless this is the service).
374 * @author mickem
375 */
376void NSCModuleHelper::Exit(void) {
377        if (fNSAPIExit)
378                fNSAPIExit();
379}
380/**
381 * Retrieve a string from the settings subsystem (INI-file)
382 * Might possibly be located in the registry in the future.
383 *
384 * @param section Section key (generally module specific, make sure this is "unique")
385 * @param key The key to retrieve
386 * @param defaultValue A default value (if no value is set in the settings file)
387 * @return the current value or defaultValue if no value is set.
388 * @throws NSCMHExcpetion When core pointer set is unavailable or an error occurs.
389 */
390std::wstring NSCModuleHelper::getSettingsString(std::wstring section, std::wstring key, std::wstring defaultValue) {
391        if (!fNSAPIGetSettingsString)
392                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
393        unsigned int buf_len = getBufferLength();
394        TCHAR *buffer = new TCHAR[buf_len+1];
395        if (fNSAPIGetSettingsString(section.c_str(), key.c_str(), defaultValue.c_str(), buffer, buf_len) != NSCAPI::isSuccess) {
396                delete [] buffer;
397                throw NSCMHExcpetion(_T("Settings could not be retrieved."));
398        }
399        std::wstring ret = buffer;
400        delete [] buffer;
401        return ret;
402}
403/**
404 * Get a section of settings strings
405 * @param section The section to retrieve
406 * @return The keys in the section
407 */
408std::list<std::wstring> NSCModuleHelper::getSettingsSection(std::wstring section) {
409        if (!fNSAPIGetSettingsSection)
410                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
411        arrayBuffer::arrayBuffer aBuffer = NULL;
412        unsigned int argLen = 0;
413        if (fNSAPIGetSettingsSection(section.c_str(), &aBuffer, &argLen) != NSCAPI::isSuccess) {
414                throw NSCMHExcpetion(_T("Settings could not be retrieved."));
415        }
416        std::list<std::wstring> ret = arrayBuffer::arrayBuffer2list(argLen, aBuffer);
417        if (fNSAPIReleaseSettingsSectionBuffer(&aBuffer, &argLen) != NSCAPI::isSuccess) {
418                throw NSCMHExcpetion(_T("Settings could not be destroyed."));
419        }
420        if (aBuffer != NULL)
421                throw NSCMHExcpetion(_T("buffer is not null?."));
422        return ret;
423}
424/**
425 * Retrieve an int from the settings subsystem (INI-file)
426 * Might possibly be located in the registry in the future.
427 *
428 * @param section Section key (generally module specific, make sure this is "unique")
429 * @param key The key to retrieve
430 * @param defaultValue A default value (if no value is set in the settings file)
431 * @return the current value or defaultValue if no value is set.
432 * @throws NSCMHExcpetion When core pointer set is unavailable.
433 */
434int NSCModuleHelper::getSettingsInt(std::wstring section, std::wstring key, int defaultValue) {
435        if (!fNSAPIGetSettingsInt)
436                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
437        return fNSAPIGetSettingsInt(section.c_str(), key.c_str(), defaultValue);
438}
439
440void NSCModuleHelper::settings_register_key(std::wstring path, std::wstring key, NSCAPI::settings_type type, std::wstring title, std::wstring description, std::wstring defaultValue, bool advanced) {
441        if (!fNSAPISettingsRegKey)
442                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
443        fNSAPISettingsRegKey(path.c_str(), key.c_str(), type, title.c_str(), description.c_str(), defaultValue.c_str(), advanced);
444}
445void NSCModuleHelper::settings_register_path(std::wstring path, std::wstring title, std::wstring description, bool advanced) {
446        if (!fNSAPISettingsRegPath)
447                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
448        fNSAPISettingsRegPath(path.c_str(), title.c_str(), description.c_str(), advanced);
449}
450
451
452void NSCModuleHelper::settings_save() {
453        if (!fNSAPISettingsSave)
454                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
455        fNSAPISettingsSave();
456}
457
458
459
460/**
461 * Returns the biggest of the two states
462 * STATE_UNKNOWN < STATE_OK < STATE_WARNING < STATE_CRITICAL
463 * @param a
464 * @param b
465 * @return
466 */
467NSCAPI::nagiosReturn NSCHelper::maxState(NSCAPI::nagiosReturn a, NSCAPI::nagiosReturn b)
468{
469        if (a == NSCAPI::returnCRIT || b == NSCAPI::returnCRIT)
470                return NSCAPI::returnCRIT;
471        else if (a == NSCAPI::returnWARN || b == NSCAPI::returnWARN)
472                return NSCAPI::returnWARN;
473        else if (a == NSCAPI::returnOK || b == NSCAPI::returnOK)
474                return NSCAPI::returnOK;
475        else if (a == NSCAPI::returnUNKNOWN || b == NSCAPI::returnUNKNOWN)
476                return NSCAPI::returnUNKNOWN;
477        return NSCAPI::returnUNKNOWN;
478}
479/**
480 * Retrieve the application name (in human readable format) from the core.
481 * @return A string representing the application name.
482 * @throws NSCMHExcpetion When core pointer set is unavailable or an unexpected error occurs.
483 */
484std::wstring NSCModuleHelper::getApplicationName() {
485        if (!fNSAPIGetApplicationName)
486                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
487        unsigned int buf_len = getBufferLength();
488        TCHAR *buffer = new TCHAR[buf_len+1];
489        if (fNSAPIGetApplicationName(buffer, buf_len) != NSCAPI::isSuccess) {
490                delete [] buffer;
491                throw NSCMHExcpetion(_T("Application name could not be retrieved"));
492        }
493        std::wstring ret = buffer;
494        delete [] buffer;
495        return ret;
496}
497/**
498 * Retrieve the directory root of the application from the core.
499 * @return A string representing the base path.
500 * @throws NSCMHExcpetion When core pointer set is unavailable or an unexpected error occurs.
501 */
502std::wstring NSCModuleHelper::getBasePath() {
503        if (!fNSAPIGetBasePath)
504                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
505        unsigned int buf_len = getBufferLength();
506        TCHAR *buffer = new TCHAR[buf_len+1];
507        if (fNSAPIGetBasePath(buffer, buf_len) != NSCAPI::isSuccess) {
508                delete [] buffer;
509                throw NSCMHExcpetion(_T("Base path could not be retrieved"));
510        }
511        std::wstring ret = buffer;
512        delete [] buffer;
513        return ret;
514}
515
516unsigned int NSCModuleHelper::getBufferLength() {
517        static unsigned int len = 0;
518        if (len == 0) {
519                len = SETTINGS_GET_INT(settings_def::PAYLOAD_LEN);
520        }
521        return len;
522}
523
524
525bool NSCModuleHelper::logDebug() {
526        typedef enum status {unknown, debug, nodebug };
527        static status d = unknown;
528        if (d == unknown) {
529                if (checkLogMessages(debug)== NSCAPI::istrue)
530                        d = debug;
531                else
532                        d = nodebug;
533        }
534        return (d == debug);
535}
536
537std::wstring NSCModuleHelper::Encrypt(std::wstring str, unsigned int algorithm) {
538        if (!fNSAPIEncrypt)
539                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
540        unsigned int len = 0;
541        // @todo investigate potential problems with static_cast<unsigned int>
542        fNSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
543        len+=2;
544        TCHAR *buf = new TCHAR[len+1];
545        NSCAPI::errorReturn ret = fNSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
546        if (ret == NSCAPI::isSuccess) {
547                std::wstring ret = buf;
548                delete [] buf;
549                return ret;
550        }
551        return _T("");
552}
553std::wstring NSCModuleHelper::Decrypt(std::wstring str, unsigned int algorithm) {
554        if (!fNSAPIDecrypt)
555                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
556        unsigned int len = 0;
557        // @todo investigate potential problems with: static_cast<unsigned int>(str.size())
558        fNSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
559        len+=2;
560        TCHAR *buf = new TCHAR[len+1];
561        NSCAPI::errorReturn ret = fNSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
562        if (ret == NSCAPI::isSuccess) {
563                std::wstring ret = buf;
564                delete [] buf;
565                return ret;
566        }
567        return _T("");
568}
569NSCAPI::errorReturn NSCModuleHelper::SetSettingsString(std::wstring section, std::wstring key, std::wstring value) {
570        if (!fNSAPISetSettingsString)
571                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
572        return fNSAPISetSettingsString(section.c_str(), key.c_str(), value.c_str());
573}
574NSCAPI::errorReturn NSCModuleHelper::SetSettingsInt(std::wstring section, std::wstring key, int value) {
575        if (!fNSAPISetSettingsInt)
576                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
577        return fNSAPISetSettingsInt(section.c_str(), key.c_str(), value);
578}
579NSCAPI::errorReturn NSCModuleHelper::WriteSettings(int type) {
580        if (!fNSAPIWriteSettings)
581                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
582        return fNSAPIWriteSettings(type);
583}
584NSCAPI::errorReturn NSCModuleHelper::ReadSettings(int type) {
585        if (!fNSAPIReadSettings)
586                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
587        return fNSAPIReadSettings(type);
588}
589NSCAPI::errorReturn NSCModuleHelper::Rehash(int flag) {
590        if (!fNSAPIRehash)
591                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
592        return fNSAPIRehash(flag);
593}
594NSCModuleHelper::plugin_info_list NSCModuleHelper::getPluginList() {
595        if (!fNSAPIGetPluginList || !fNSAPIReleasePluginList)
596                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
597        plugin_info_list ret;
598       
599       
600        int len = 0;
601        //NSCAPI::plugin_info_list **list2;
602        //NSCAPI::plugin_info_list *list[1];
603        NSCAPI::plugin_info *list[1];
604        //typedef NSCAPI::errorReturn (*lpNSAPIGetPluginList)(int *len, NSAPI_plugin_info** list);
605        //typedef NSCAPI::errorReturn (*lpNSAPIReleasePluginList)(int len, NSAPI_plugin_info** list);
606        NSCAPI::errorReturn err = fNSAPIGetPluginList(&len, list);
607        if (err != NSCAPI::isSuccess)
608                return ret;
609        for (int i=0;i<len;i++) {
610                plugin_info_type info;
611                info.description = (*list)[i].description;
612                info.name = (*list)[i].name;
613                info.dll = (*list)[i].dll;
614                ret.push_back(info);
615        }
616        fNSAPIReleasePluginList(len, list);
617        return ret;
618}
619
620std::list<std::wstring> NSCModuleHelper::getAllCommandNames() {
621        if (!fNSAPIGetAllCommandNames || !fNSAPIReleaseAllCommandNamessBuffer )
622                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
623        arrayBuffer::arrayBuffer aBuffer = NULL;
624        unsigned int argLen = 0;
625        if (fNSAPIGetAllCommandNames(&aBuffer, &argLen) != NSCAPI::isSuccess) {
626                throw NSCMHExcpetion(_T("Commands could not be retrieved."));
627        }
628        std::list<std::wstring> ret = arrayBuffer::arrayBuffer2list(argLen, aBuffer);
629        if (fNSAPIReleaseAllCommandNamessBuffer(&aBuffer, &argLen) != NSCAPI::isSuccess) {
630                throw NSCMHExcpetion(_T("Commands could not be destroyed."));
631        }
632        if (aBuffer != NULL)
633                throw NSCMHExcpetion(_T("buffer is not null?."));
634        return ret;
635}
636std::wstring NSCModuleHelper::describeCommand(std::wstring command) {
637        if (!fNSAPIDescribeCommand)
638                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
639        unsigned int buf_len = getBufferLength();
640        TCHAR *buffer = new TCHAR[buf_len+1];
641        if (fNSAPIDescribeCommand(command.c_str(), buffer, buf_len) != NSCAPI::isSuccess) {
642                delete [] buffer;
643                throw NSCMHExcpetion(_T("Base path could not be retrieved"));
644        }
645        std::wstring ret = buffer;
646        delete [] buffer;
647        return ret;
648}
649void NSCModuleHelper::registerCommand(std::wstring command, std::wstring description) {
650        if (!fNSAPIRegisterCommand)
651                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
652        fNSAPIRegisterCommand(command.c_str(), description.c_str());
653}
654
655
656bool NSCModuleHelper::checkLogMessages(int type) {
657        if (!fNSAPICheckLogMessages)
658                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
659        return fNSAPICheckLogMessages(type) == NSCAPI::istrue;
660}
661/**
662 * Retrieve the application version as a string (in human readable format) from the core.
663 * @return A string representing the application version.
664 * @throws NSCMHExcpetion When core pointer set is unavailable.
665 */
666std::wstring NSCModuleHelper::getApplicationVersionString() {
667        if (!fNSAPIGetApplicationVersionStr)
668                throw NSCMHExcpetion(_T("NSCore has not been initiated..."));
669        unsigned int buf_len = getBufferLength();
670        TCHAR *buffer = new TCHAR[buf_len+1];
671        if (fNSAPIGetApplicationVersionStr(buffer, buf_len) != NSCAPI::isSuccess) {
672                delete [] buffer;
673                return _T("");
674        }
675        std::wstring ret = buffer;
676        delete [] buffer;
677        return ret;
678}
679
680namespace NSCModuleWrapper {
681        HINSTANCE hModule_ = NULL;
682}
683/**
684 * Used to help store the module handle (and possibly other things in the future)
685 * @param hModule cf. DllMain
686 * @param ul_reason_for_call cf. DllMain
687 * @return TRUE
688 */
689BOOL NSCModuleWrapper::wrapDllMain(HANDLE hModule, DWORD ul_reason_for_call)
690{
691        switch (ul_reason_for_call)
692        {
693        case DLL_PROCESS_ATTACH:
694        case DLL_THREAD_ATTACH:
695                hModule_ = (HINSTANCE)hModule;
696                break;
697        case DLL_THREAD_DETACH:
698        case DLL_PROCESS_DETACH:
699                break;
700        }
701        return TRUE;
702}
703/**
704 * Retrieve the module handle from the DllMain call.
705 * @return Module handle of this DLL
706 */
707HINSTANCE NSCModuleWrapper::getModule() {
708        return hModule_;
709}
710
711/**
712 * Wrapper function around the ModuleHelperInit call.
713 * This wrapper retrieves all pointers and stores them for future use.
714 * @param f A function pointer to a function that can be used to load function from the core.
715 * @return NSCAPI::success or NSCAPI::failure
716 */
717int NSCModuleWrapper::wrapModuleHelperInit(NSCModuleHelper::lpNSAPILoader f) {
718        NSCModuleHelper::fNSAPIGetApplicationName = (NSCModuleHelper::lpNSAPIGetApplicationName)f(_T("NSAPIGetApplicationName"));
719        NSCModuleHelper::fNSAPIGetApplicationVersionStr = (NSCModuleHelper::lpNSAPIGetApplicationVersionStr)f(_T("NSAPIGetApplicationVersionStr"));
720        NSCModuleHelper::fNSAPIGetSettingsInt = (NSCModuleHelper::lpNSAPIGetSettingsInt)f(_T("NSAPIGetSettingsInt"));
721        NSCModuleHelper::fNSAPIGetSettingsString = (NSCModuleHelper::lpNSAPIGetSettingsString)f(_T("NSAPIGetSettingsString"));
722        NSCModuleHelper::fNSAPIGetSettingsSection = (NSCModuleHelper::lpNSAPIGetSettingsSection)f(_T("NSAPIGetSettingsSection"));
723        NSCModuleHelper::fNSAPIReleaseSettingsSectionBuffer = (NSCModuleHelper::lpNSAPIReleaseSettingsSectionBuffer)f(_T("NSAPIReleaseSettingsSectionBuffer"));
724        NSCModuleHelper::fNSAPIMessage = (NSCModuleHelper::lpNSAPIMessage)f(_T("NSAPIMessage"));
725        NSCModuleHelper::fNSAPIStopServer = (NSCModuleHelper::lpNSAPIStopServer)f(_T("NSAPIStopServer"));
726        NSCModuleHelper::fNSAPIExit = (NSCModuleHelper::lpNSAPIExit)f(_T("NSAPIExit"));
727        NSCModuleHelper::fNSAPIInject = (NSCModuleHelper::lpNSAPIInject)f(_T("NSAPIInject"));
728        NSCModuleHelper::fNSAPIGetBasePath = (NSCModuleHelper::lpNSAPIGetBasePath)f(_T("NSAPIGetBasePath"));
729        NSCModuleHelper::fNSAPICheckLogMessages = (NSCModuleHelper::lpNSAPICheckLogMessages)f(_T("NSAPICheckLogMessages"));
730        NSCModuleHelper::fNSAPIDecrypt = (NSCModuleHelper::lpNSAPIDecrypt)f(_T("NSAPIDecrypt"));
731        NSCModuleHelper::fNSAPIEncrypt = (NSCModuleHelper::lpNSAPIEncrypt)f(_T("NSAPIEncrypt"));
732        NSCModuleHelper::fNSAPISetSettingsString = (NSCModuleHelper::lpNSAPISetSettingsString)f(_T("NSAPISetSettingsString"));
733        NSCModuleHelper::fNSAPISetSettingsInt = (NSCModuleHelper::lpNSAPISetSettingsInt)f(_T("NSAPISetSettingsInt"));
734        NSCModuleHelper::fNSAPIWriteSettings = (NSCModuleHelper::lpNSAPIWriteSettings)f(_T("NSAPIWriteSettings"));
735        NSCModuleHelper::fNSAPIReadSettings = (NSCModuleHelper::lpNSAPIReadSettings)f(_T("NSAPIReadSettings"));
736        NSCModuleHelper::fNSAPIRehash = (NSCModuleHelper::lpNSAPIRehash)f(_T("NSAPIRehash"));
737
738        NSCModuleHelper::fNSAPIDescribeCommand = (NSCModuleHelper::lpNSAPIDescribeCommand)f(_T("NSAPIDescribeCommand"));
739        NSCModuleHelper::fNSAPIGetAllCommandNames = (NSCModuleHelper::lpNSAPIGetAllCommandNames)f(_T("NSAPIGetAllCommandNames"));
740        NSCModuleHelper::fNSAPIReleaseAllCommandNamessBuffer = (NSCModuleHelper::lpNSAPIReleaseAllCommandNamessBuffer)f(_T("NSAPIReleaseAllCommandNamessBuffer"));
741        NSCModuleHelper::fNSAPIRegisterCommand = (NSCModuleHelper::lpNSAPIRegisterCommand)f(_T("NSAPIRegisterCommand"));
742
743        NSCModuleHelper::fNSAPISettingsRegKey = (NSCModuleHelper::lpNSAPISettingsRegKey)f(_T("NSAPISettingsRegKey"));
744        NSCModuleHelper::fNSAPISettingsRegPath = (NSCModuleHelper::lpNSAPISettingsRegPath)f(_T("NSAPISettingsRegPath"));
745
746        NSCModuleHelper::fNSAPIGetPluginList = (NSCModuleHelper::lpNSAPIGetPluginList)f(_T("NSAPIGetPluginList"));
747        NSCModuleHelper::fNSAPIReleasePluginList = (NSCModuleHelper::lpNSAPIReleasePluginList)f(_T("NSAPIReleasePluginList"));
748
749        NSCModuleHelper::fNSAPISettingsSave = (NSCModuleHelper::lpNSAPISettingsSave)f(_T("NSAPISettingsSave"));
750               
751
752        return NSCAPI::isSuccess;
753}
754/**
755* Wrap the GetModuleName function call
756* @param buf Buffer to store the module name
757* @param bufLen Length of buffer
758* @param str String to store inside the buffer
759* @      copy status
760*/
761NSCAPI::errorReturn NSCModuleWrapper::wrapGetModuleName(TCHAR* buf, unsigned int bufLen, std::wstring str) {
762        return NSCHelper::wrapReturnString(buf, bufLen, str, NSCAPI::isSuccess);
763}
764
765NSCAPI::errorReturn NSCModuleWrapper::wrapGetConfigurationMeta(TCHAR* buf, unsigned int bufLen, std::wstring str) {
766        return NSCHelper::wrapReturnString(buf, bufLen, str, NSCAPI::isSuccess);
767}
768/**
769 * Wrap the GetModuleVersion function call
770 * @param *major Major version number
771 * @param *minor Minor version number
772 * @param *revision Revision
773 * @param version version as a module_version
774 * @return NSCAPI::success
775 */
776NSCAPI::errorReturn NSCModuleWrapper::wrapGetModuleVersion(int *major, int *minor, int *revision, module_version version) {
777        *major = version.major;
778        *minor = version.minor;
779        *revision = version.revision;
780        return NSCAPI::isSuccess;
781}
782/**
783 * Wrap the HasCommandHandler function call
784 * @param has true if this module has a command handler
785 * @return NSCAPI::istrue or NSCAPI::isfalse
786 */
787NSCAPI::boolReturn NSCModuleWrapper::wrapHasCommandHandler(bool has) {
788        if (has)
789                return NSCAPI::istrue;
790        return NSCAPI::isfalse;
791}
792/**
793 * Wrap the HasMessageHandler function call
794 * @param has true if this module has a message handler
795 * @return NSCAPI::istrue or NSCAPI::isfalse
796 */
797NSCAPI::boolReturn NSCModuleWrapper::wrapHasMessageHandler(bool has) {
798        if (has)
799                return NSCAPI::istrue;
800        return NSCAPI::isfalse;
801}
802/**
803 * Wrap the HandleCommand call
804 * @param retResult The returned result
805 * @param retMessage The returned message
806 * @param retPerformance The returned performance data
807 * @param *returnBufferMessage The return message buffer
808 * @param returnBufferMessageLen The return message buffer length
809 * @param *returnBufferPerf The return performance data buffer
810 * @param returnBufferPerfLen The return performance data buffer length
811 * @return the return code
812 */
813NSCAPI::nagiosReturn NSCModuleWrapper::wrapHandleCommand(NSCAPI::nagiosReturn retResult, const std::wstring retMessage, const std::wstring retPerformance, TCHAR *returnBufferMessage, unsigned int returnBufferMessageLen, TCHAR *returnBufferPerf, unsigned int returnBufferPerfLen) {
814        if (retMessage.empty())
815                return NSCAPI::returnIgnored;
816        NSCAPI::nagiosReturn ret = NSCHelper::wrapReturnString(returnBufferMessage, returnBufferMessageLen, retMessage, retResult);
817        if (!NSCHelper::isMyNagiosReturn(ret)) {
818                NSC_LOG_ERROR(_T("A module returned an invalid return code"));
819        }
820        return NSCHelper::wrapReturnString(returnBufferPerf, returnBufferPerfLen, retPerformance, ret);
821}
822
823/**
824 * Wrap the NSLoadModule call
825 * @param success true if module load was successfully
826 * @return NSCAPI::success or NSCAPI::failed
827 */
828int NSCModuleWrapper::wrapLoadModule(bool success) {
829        if (success)
830                return NSCAPI::isSuccess;
831        return NSCAPI::hasFailed;
832}
833/**
834 * Wrap the NSUnloadModule call
835 * @param success true if module load was successfully
836 * @return NSCAPI::success or NSCAPI::failed
837 */
838int NSCModuleWrapper::wrapUnloadModule(bool success) {
839        if (success)
840                return NSCAPI::isSuccess;
841        return NSCAPI::hasFailed;
842}
843
844
845
Note: See TracBrowser for help on using the repository browser.