source: nscp/include/NSCHelper.cpp @ 79e734f

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

Re added some more stuff anf fixed *nix compatibility of sockets

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