source: nscp/include/NSCHelper.cpp @ 945c381

0.4.00.4.10.4.2stable
Last change on this file since 945c381 was 945c381, checked in by Michael Medin <michael@…>, 8 years ago
  • Fixed multitasking socket listsner (had a hard-to-find memory leak)
  • Changed ProcessEnumeration? class to one that should work on NT4 New option to set this in the config file. + Added some more options to the config file.
  • Property mode set to 100644
File size: 16.5 KB
Line 
1#include "stdafx.h"
2#include <NSCHelper.h>
3#include <assert.h>
4
5#define BUFF_LEN 4096
6
7
8/**
9* Wrap a return string.
10* This function copies a string to a char buffer making sure the buffer has the correct length.
11*
12* @param *buffer Buffer to copy the string to.
13* @param bufLen Length of the buffer
14* @param str Th string to copy
15* @return NSCAPI::success unless the buffer is to short then it will be NSCAPI::invalidBufferLen
16*/
17#ifdef DEBUG
18NSCAPI::nagiosReturn NSCHelper::wrapReturnString(char *buffer, unsigned int bufLen, std::string str, NSCAPI::nagiosReturn defaultReturnCode /* = NSCAPI::success */) {
19        if (str.length() >= bufLen)
20                return NSCAPI::returnInvalidBufferLen;
21        strncpy(buffer, str.c_str(), bufLen);
22        return defaultReturnCode;
23}
24NSCAPI::errorReturn NSCHelper::wrapReturnString(char *buffer, unsigned int bufLen, std::string str, NSCAPI::errorReturn defaultReturnCode /* = NSCAPI::success */) {
25        if (str.length() >= bufLen)
26                return NSCAPI::isInvalidBufferLen;
27        strncpy(buffer, str.c_str(), bufLen);
28        return defaultReturnCode;
29}
30#else
31int NSCHelper::wrapReturnString(char *buffer, unsigned int bufLen, std::string str, int defaultReturnCode ) {
32        // @todo deprecate this
33        if (str.length() >= bufLen)
34                return -1;
35        strncpy(buffer, str.c_str(), bufLen);
36        return defaultReturnCode;
37}
38#endif
39
40
41/**
42 * Translate a message type into a human readable string.
43 *
44 * @param msgType The message type
45 * @return A string representing the message type
46 */
47std::string NSCHelper::translateMessageType(NSCAPI::messageTypes msgType) {
48        switch (msgType) {
49                case NSCAPI::error:
50                        return "error";
51                case NSCAPI::critical:
52                        return "critical";
53                case NSCAPI::warning:
54                        return "warning";
55                case NSCAPI::log:
56                        return "message";
57                case NSCAPI::debug:
58                        return "debug";
59        }
60        return "unknown";
61}
62std::string NSCHelper::translateReturn(NSCAPI::nagiosReturn returnCode) {
63        if (returnCode == NSCAPI::returnOK)
64                return "OK";
65        else if (returnCode == NSCAPI::returnCRIT)
66                return "CRITICAL";
67        else if (returnCode == NSCAPI::returnWARN)
68                return "WARNING";
69        else
70                return "UNKNOWN";
71}
72
73
74
75namespace NSCModuleHelper {
76        lpNSAPIGetBasePath fNSAPIGetBasePath = NULL;
77        lpNSAPIGetApplicationName fNSAPIGetApplicationName = NULL;
78        lpNSAPIGetApplicationVersionStr fNSAPIGetApplicationVersionStr = NULL;
79        lpNSAPIGetSettingsSection fNSAPIGetSettingsSection = NULL;
80        lpNSAPIGetSettingsString fNSAPIGetSettingsString = NULL;
81        lpNSAPIGetSettingsInt fNSAPIGetSettingsInt = NULL;
82        lpNSAPIMessage fNSAPIMessage = NULL;
83        lpNSAPIStopServer fNSAPIStopServer = NULL;
84        lpNSAPIInject fNSAPIInject = NULL;
85}
86
87//////////////////////////////////////////////////////////////////////////
88// Callbacks into the core
89//////////////////////////////////////////////////////////////////////////
90
91/**
92 * Callback to send a message through to the core
93 *
94 * @param msgType Message type (debug, warning, etc.)
95 * @param file File where message was generated (__FILE__)
96 * @param line Line where message was generated (__LINE__)
97 * @param message Message in human readable format
98 * @throws NSCMHExcpetion When core pointer set is unavailable.
99 */
100void NSCModuleHelper::Message(int msgType, std::string file, int line, std::string message) {
101        if (fNSAPIMessage)
102                return fNSAPIMessage(msgType, file.c_str(), line, message.c_str());
103        else
104                std::cout << "NSCore not loaded..." << std::endl << message << std::endl;
105}
106/**
107 * Inject a request command in the core (this will then be sent to the plug-in stack for processing)
108 * @param command Command to inject (password should not be included.
109 * @return The result (if any) of the command.
110 * @throws NSCMHExcpetion When core pointer set is unavailable or an unknown inject error occurs.
111 */
112NSCAPI::nagiosReturn NSCModuleHelper::InjectCommandRAW(const char* command, const unsigned int argLen, char **argument, char *returnMessageBuffer, unsigned int returnMessageBufferLen, char *returnPerfBuffer, unsigned int returnPerfBufferLen)
113{
114        if (!fNSAPIInject)
115                throw NSCMHExcpetion("NSCore has not been initiated...");
116        return fNSAPIInject(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen);
117}
118NSCAPI::nagiosReturn NSCModuleHelper::InjectCommand(const char* command, const unsigned int argLen, char **argument, std::string & message, std::string & perf)
119{
120        if (!fNSAPIInject)
121                throw NSCMHExcpetion("NSCore has not been initiated...");
122        char *msgBuffer = new char[BUFF_LEN+1];
123        char *perfBuffer = new char[BUFF_LEN+1];
124        msgBuffer[0] = 0;
125        perfBuffer[0] = 0;
126        // @todo message here !
127        NSCAPI::nagiosReturn retC = InjectCommandRAW(command, argLen, argument, msgBuffer, BUFF_LEN, perfBuffer, BUFF_LEN);
128        switch (retC) {
129                case NSCAPI::returnIgnored:
130                        NSC_LOG_MESSAGE("No handler for this message.");
131                        break;
132                case NSCAPI::returnInvalidBufferLen:
133                        NSC_LOG_ERROR("Inject command resulted in an invalid buffer size.");
134                        break;
135                case NSCAPI::returnOK:
136                case NSCAPI::returnCRIT:
137                case NSCAPI::returnWARN:
138                case NSCAPI::returnUNKNOWN:
139                        message = msgBuffer;
140                        perf = perfBuffer;
141                        break;
142                default:
143                        throw NSCMHExcpetion("Unknown inject error.");
144        }
145        delete [] msgBuffer;
146        delete [] perfBuffer;
147        return retC;
148}
149/**
150 * A wrapper around the InjetCommand that is simpler to use.
151 * Parses a string by splitting and makes the array and also manages return buffers and such.
152 * @param command The command to execute
153 * @param buffer The buffer to splitwww.ikea.se
154
155 * @param splitChar The char to use as splitter
156 * @return The result of the command
157 */
158NSCAPI::nagiosReturn NSCModuleHelper::InjectSplitAndCommand(const char* command, char* buffer, char splitChar, std::string & message, std::string & perf)
159{
160        if (!fNSAPIInject)
161                throw NSCMHExcpetion("NSCore has not been initiated...");
162        unsigned int argLen = 0;
163        char ** aBuffer;
164        if (buffer)
165                aBuffer= arrayBuffer::split2arrayBuffer(buffer, splitChar, argLen);
166        else
167                aBuffer= arrayBuffer::createEmptyArrayBuffer(argLen);
168        NSCAPI::nagiosReturn ret = InjectCommand(command, argLen, aBuffer, message, perf);
169        arrayBuffer::destroyArrayBuffer(aBuffer, argLen);
170        return ret;
171}
172NSCAPI::nagiosReturn NSCModuleHelper::InjectSplitAndCommand(const std::string command, const std::string buffer, char splitChar, std::string & message, std::string & perf)
173{
174        if (!fNSAPIInject)
175                throw NSCMHExcpetion("NSCore has not been initiated...");
176        unsigned int argLen = 0;
177        char ** aBuffer;
178        if (buffer.empty())
179                aBuffer= arrayBuffer::createEmptyArrayBuffer(argLen);
180        else
181                aBuffer= arrayBuffer::split2arrayBuffer(buffer, splitChar, argLen);
182        NSCAPI::nagiosReturn ret = InjectCommand(command.c_str(), argLen, aBuffer, message, perf);
183        arrayBuffer::destroyArrayBuffer(aBuffer, argLen);
184        return ret;
185}
186/**
187 * Ask the core to shutdown (only works when run as a service, o/w does nothing ?
188 * @todo Check if this might cause damage if not run as a service.
189 */
190void NSCModuleHelper::StopService(void) {
191        if (fNSAPIStopServer)
192                fNSAPIStopServer();
193}
194/**
195 * Retrieve a string from the settings subsystem (INI-file)
196 * Might possibly be located in the registry in the future.
197 *
198 * @param section Section key (generally module specific, make sure this is "unique")
199 * @param key The key to retrieve
200 * @param defaultValue A default value (if no value is set in the settings file)
201 * @return the current value or defaultValue if no value is set.
202 * @throws NSCMHExcpetion When core pointer set is unavailable or an error occurs.
203 */
204std::string NSCModuleHelper::getSettingsString(std::string section, std::string key, std::string defaultValue) {
205        if (!fNSAPIGetSettingsString)
206                throw NSCMHExcpetion("NSCore has not been initiated...");
207        char *buffer = new char[BUFF_LEN+1];
208        if (fNSAPIGetSettingsString(section.c_str(), key.c_str(), defaultValue.c_str(), buffer, BUFF_LEN) != NSCAPI::isSuccess) {
209                delete [] buffer;
210                throw NSCMHExcpetion("Settings could not be retrieved.");
211        }
212        std::string ret = buffer;
213        delete [] buffer;
214        return ret;
215}
216std::list<std::string> NSCModuleHelper::getSettingsSection(std::string section) {
217        if (!fNSAPIGetSettingsSection)
218                throw NSCMHExcpetion("NSCore has not been initiated...");
219        char ** aBuffer = NULL;
220        unsigned int argLen = 0;
221        if (fNSAPIGetSettingsSection(section.c_str(), &aBuffer, &argLen) != NSCAPI::isSuccess) {
222                throw NSCMHExcpetion("Settings could not be retrieved.");
223        }
224        std::list<std::string> ret = arrayBuffer::arrayBuffer2list(argLen, aBuffer);
225        arrayBuffer::destroyArrayBuffer(aBuffer, argLen);
226        return ret;
227}
228/**
229 * Retrieve an int from the settings subsystem (INI-file)
230 * Might possibly be located in the registry in the future.
231 *
232 * @param section Section key (generally module specific, make sure this is "unique")
233 * @param key The key to retrieve
234 * @param defaultValue A default value (if no value is set in the settings file)
235 * @return the current value or defaultValue if no value is set.
236 * @throws NSCMHExcpetion When core pointer set is unavailable.
237 */
238int NSCModuleHelper::getSettingsInt(std::string section, std::string key, int defaultValue) {
239        if (!fNSAPIGetSettingsInt)
240                throw NSCMHExcpetion("NSCore has not been initiated...");
241        return fNSAPIGetSettingsInt(section.c_str(), key.c_str(), defaultValue);
242}
243
244
245/***************************************************************************
246* max_state(STATE_x, STATE_y)
247* compares STATE_x to  STATE_y and returns result based on the following
248* STATE_UNKNOWN < STATE_OK < STATE_WARNING < STATE_CRITICAL
249*
250* Note that numerically the above does not hold
251****************************************************************************/
252NSCAPI::nagiosReturn NSCHelper::maxState(NSCAPI::nagiosReturn a, NSCAPI::nagiosReturn b)
253{
254        if (a == NSCAPI::returnCRIT || b == NSCAPI::returnCRIT)
255                return NSCAPI::returnCRIT;
256        else if (a == NSCAPI::returnWARN || b == NSCAPI::returnWARN)
257                return NSCAPI::returnWARN;
258        else if (a == NSCAPI::returnOK || b == NSCAPI::returnOK)
259                return NSCAPI::returnOK;
260        else if (a == NSCAPI::returnUNKNOWN || b == NSCAPI::returnUNKNOWN)
261                return NSCAPI::returnUNKNOWN;
262        /*
263        else if (a == STATE_DEPENDENT || b == STATE_DEPENDENT)
264        return STATE_DEPENDENT;
265        */
266        //              else
267        throw "undefined state";
268        //                      return max (a, b);
269}
270
271
272/**
273 * Retrieve the application name (in human readable format) from the core.
274 * @return A string representing the application name.
275 * @throws NSCMHExcpetion When core pointer set is unavailable or an unexpected error occurs.
276 */
277std::string NSCModuleHelper::getApplicationName() {
278        if (!fNSAPIGetApplicationName)
279                throw NSCMHExcpetion("NSCore has not been initiated...");
280        char *buffer = new char[BUFF_LEN+1];
281        if (fNSAPIGetApplicationName(buffer, BUFF_LEN) != NSCAPI::isSuccess) {
282                delete [] buffer;
283                throw NSCMHExcpetion("Application name could not be retrieved");
284        }
285        std::string ret = buffer;
286        delete [] buffer;
287        return ret;
288}
289/**
290 * Retrieve the directory root of the application from the core.
291 * @return A string representing the base path.
292 * @throws NSCMHExcpetion When core pointer set is unavailable or an unexpected error occurs.
293 */
294std::string NSCModuleHelper::getBasePath() {
295        if (!fNSAPIGetBasePath)
296                throw NSCMHExcpetion("NSCore has not been initiated...");
297        char *buffer = new char[BUFF_LEN+1];
298        if (fNSAPIGetBasePath(buffer, BUFF_LEN) != NSCAPI::isSuccess) {
299                delete [] buffer;
300                throw NSCMHExcpetion("Base path could not be retrieved");
301        }
302        std::string ret = buffer;
303        delete [] buffer;
304        return ret;
305}
306/**
307 * Retrieve the application version as a string (in human readable format) from the core.
308 * @return A string representing the application version.
309 * @throws NSCMHExcpetion When core pointer set is unavailable.
310 */
311std::string NSCModuleHelper::getApplicationVersionString() {
312        if (!fNSAPIGetApplicationVersionStr)
313                throw NSCMHExcpetion("NSCore has not been initiated...");
314        char *buffer = new char[BUFF_LEN+1];
315        int x = fNSAPIGetApplicationVersionStr(buffer, BUFF_LEN);
316        std::string ret = buffer;
317        delete [] buffer;
318        return ret;
319}
320
321//////////////////////////////////////////////////////////////////////////
322// Module helper functions
323//////////////////////////////////////////////////////////////////////////
324namespace NSCModuleWrapper {
325        HINSTANCE hModule_ = NULL;
326}
327/**
328 * Used to help store the module handle (and possibly other things in the future)
329 * @param hModule cf. DllMain
330 * @param ul_reason_for_call cf. DllMain
331 * @return TRUE
332 */
333BOOL NSCModuleWrapper::wrapDllMain(HANDLE hModule, DWORD ul_reason_for_call)
334{
335        switch (ul_reason_for_call)
336        {
337        case DLL_PROCESS_ATTACH:
338        case DLL_THREAD_ATTACH:
339                hModule_ = (HINSTANCE)hModule;
340                break;
341        case DLL_THREAD_DETACH:
342        case DLL_PROCESS_DETACH:
343                break;
344        }
345        return TRUE;
346}
347/**
348 * Retrieve the module handle from the DllMain call.
349 * @return Module handle of this DLL
350 */
351HINSTANCE NSCModuleWrapper::getModule() {
352        return hModule_;
353}
354
355/**
356 * Wrapper function around the ModuleHelperInit call.
357 * This wrapper retrieves all pointers and stores them for future use.
358 * @param f A function pointer to a function that can be used to load function from the core.
359 * @return NSCAPI::success or NSCAPI::failure
360 */
361int NSCModuleWrapper::wrapModuleHelperInit(NSCModuleHelper::lpNSAPILoader f) {
362        NSCModuleHelper::fNSAPIGetApplicationName = (NSCModuleHelper::lpNSAPIGetApplicationName)f("NSAPIGetApplicationName");
363        NSCModuleHelper::fNSAPIGetApplicationVersionStr = (NSCModuleHelper::lpNSAPIGetApplicationVersionStr)f("NSAPIGetApplicationVersionStr");
364        NSCModuleHelper::fNSAPIGetSettingsInt = (NSCModuleHelper::lpNSAPIGetSettingsInt)f("NSAPIGetSettingsInt");
365        NSCModuleHelper::fNSAPIGetSettingsString = (NSCModuleHelper::lpNSAPIGetSettingsString)f("NSAPIGetSettingsString");
366        NSCModuleHelper::fNSAPIGetSettingsSection = (NSCModuleHelper::lpNSAPIGetSettingsSection)f("NSAPIGetSettingsSection");
367        NSCModuleHelper::fNSAPIMessage = (NSCModuleHelper::lpNSAPIMessage)f("NSAPIMessage");
368        NSCModuleHelper::fNSAPIStopServer = (NSCModuleHelper::lpNSAPIStopServer)f("NSAPIStopServer");
369        NSCModuleHelper::fNSAPIInject = (NSCModuleHelper::lpNSAPIInject)f("NSAPIInject");
370        NSCModuleHelper::fNSAPIGetBasePath = (NSCModuleHelper::lpNSAPIGetBasePath)f("NSAPIGetBasePath");
371        return NSCAPI::isSuccess;
372}
373/**
374* Wrap the GetModuleName function call
375* @param buf Buffer to store the module name
376* @param bufLen Length of buffer
377* @param str String to store inside the buffer
378* @return buffer copy status
379*/
380NSCAPI::errorReturn NSCModuleWrapper::wrapGetModuleName(char* buf, unsigned int bufLen, std::string str) {
381        return NSCHelper::wrapReturnString(buf, bufLen, str, NSCAPI::isSuccess);
382}
383/**
384 * Wrap the GetModuleVersion function call
385 * @param *major Major version number
386 * @param *minor Minor version number
387 * @param *revision Revision
388 * @param version version as a module_version
389 * @return NSCAPI::success
390 */
391NSCAPI::errorReturn NSCModuleWrapper::wrapGetModuleVersion(int *major, int *minor, int *revision, module_version version) {
392        *major = version.major;
393        *minor = version.minor;
394        *revision = version.revision;
395        return NSCAPI::isSuccess;
396}
397/**
398 * Wrap the HasCommandHandler function call
399 * @param has true if this module has a command handler
400 * @return NSCAPI::istrue or NSCAPI::isfalse
401 */
402NSCAPI::boolReturn NSCModuleWrapper::wrapHasCommandHandler(bool has) {
403        if (has)
404                return NSCAPI::istrue;
405        return NSCAPI::isfalse;
406}
407/**
408 * Wrap the HasMessageHandler function call
409 * @param has true if this module has a message handler
410 * @return NSCAPI::istrue or NSCAPI::isfalse
411 */
412NSCAPI::boolReturn NSCModuleWrapper::wrapHasMessageHandler(bool has) {
413        if (has)
414                return NSCAPI::istrue;
415        return NSCAPI::isfalse;
416}
417/**
418 * Wrap the HandleCommand call
419 * @param retStr The string to return to the core
420 * @param *returnBuffer A buffer to copy the return string to
421 * @param returnBufferLen length of returnBuffer
422 * @return copy status or NSCAPI::isfalse if retStr is empty
423 */
424NSCAPI::nagiosReturn NSCModuleWrapper::wrapHandleCommand(NSCAPI::nagiosReturn retResult, const std::string retMessage, const std::string retPerformance, char *returnBufferMessage, unsigned int returnBufferMessageLen, char *returnBufferPerf, unsigned int returnBufferPerfLen) {
425        if (retMessage.empty())
426                return NSCAPI::returnIgnored;
427        NSCAPI::nagiosReturn ret = NSCHelper::wrapReturnString(returnBufferMessage, returnBufferMessageLen, retMessage, retResult);
428        return NSCHelper::wrapReturnString(returnBufferPerf, returnBufferPerfLen, retPerformance, ret);
429}
430/**
431 * Wrap the NSLoadModule call
432 * @param success true if module load was successfully
433 * @return NSCAPI::success or NSCAPI::failed
434 */
435int NSCModuleWrapper::wrapLoadModule(bool success) {
436        if (success)
437                return NSCAPI::isSuccess;
438        return NSCAPI::hasFailed;
439}
440/**
441 * Wrap the NSUnloadModule call
442 * @param success true if module load was successfully
443 * @return NSCAPI::success or NSCAPI::failed
444 */
445int NSCModuleWrapper::wrapUnloadModule(bool success) {
446        if (success)
447                return NSCAPI::isSuccess;
448        return NSCAPI::hasFailed;
449}
450
451
452
Note: See TracBrowser for help on using the repository browser.