source: nscp/include/NSCHelper.cpp @ 8223547

0.4.00.4.10.4.2stable
Last change on this file since 8223547 was 8223547, checked in by Michael Medin <michael@…>, 8 years ago
  • Improved thread safety in Core + Added exception handling and logging in PDH code
  • Various fixes all over the place + New module for check size of files/directories
  • Changed build to Dynamic link
  • Added regular expression support for EventLog? checker
  • Property mode set to 100644
File size: 12.9 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 */
17int NSCHelper::wrapReturnString(char *buffer, unsigned int bufLen, std::string str, int defaultReturnCode /* = NSCAPI::success */) {
18        if (str.length() >= bufLen)
19                return NSCAPI::invalidBufferLen;
20        strncpy(buffer, str.c_str(), bufLen);
21        return defaultReturnCode;
22}
23/**
24 * Make a list out of a array of char arrays (arguments type)
25 * @param argLen Length of argument array
26 * @param *argument[] Argument array
27 * @return Argument wrapped as a list
28 */
29std::list<std::string> NSCHelper::arrayBuffer2list(const unsigned int argLen, char *argument[]) {
30        std::list<std::string> ret;
31        int i=0;
32        for (unsigned int i=0;i<argLen;i++) {
33                std::string s = argument[i];
34                ret.push_back(s);
35        }
36        return ret;
37}
38/**
39 * Create an arrayBuffer from a list.
40 * This is the reverse of arrayBuffer2list.
41 * <b>Notice</b> it is up to the caller to free the memory allocated in the returned buffer.
42 *
43 * @param lst A list to convert.
44 * @param &argLen Write the length to this argument.
45 * @return A pointer that is managed by the caller.
46 */
47char ** NSCHelper::list2arrayBuffer(const std::list<std::string> lst, unsigned int &argLen) {
48        std::string ret;
49        argLen = static_cast<unsigned int>(lst.size());
50        char **arrayBuffer = new char*[argLen];
51        std::list<std::string>::const_iterator it = lst.begin();
52        for (int i=0;it!=lst.end();++it,i++) {
53                std::string::size_type alen = (*it).size();
54                arrayBuffer[i] = new char[alen+2];
55                strncpy(arrayBuffer[i], (*it).c_str(), alen+1);
56        }
57        assert(i == argLen);
58        return arrayBuffer;
59}
60/**
61 * Destroy an arrayBuffer.
62 * The buffer should have been created with list2arrayBuffer.
63 *
64 * @param **argument
65 * @param argLen
66 */
67void NSCHelper::destroyArrayBuffer(char **argument, const unsigned int argLen) {
68        for (unsigned int i=0;i<argLen;i++) {
69                delete [] argument[i];
70        }
71        delete [] argument;
72}
73
74
75/**
76 * Translate a message type into a human readable string.
77 *
78 * @param msgType The message type
79 * @return A string representing the message type
80 */
81std::string NSCHelper::translateMessageType(NSCAPI::messageTypes msgType) {
82        switch (msgType) {
83                case NSCAPI::error:
84                        return "error";
85                case NSCAPI::critical:
86                        return "critical";
87                case NSCAPI::warning:
88                        return "warning";
89                case NSCAPI::log:
90                        return "message";
91                case NSCAPI::debug:
92                        return "debug";
93        }
94        return "unknown";
95}
96std::string NSCHelper::translateReturn(NSCAPI::returnCodes returnCode) {
97        if (returnCode == NSCAPI::returnOK)
98                return "OK";
99        else if (returnCode == NSCAPI::returnCRIT)
100                return "CRITICAL";
101        else if (returnCode == NSCAPI::returnWARN)
102                return "WARNING";
103        else
104                return "UNKNOWN";
105}
106
107
108
109namespace NSCModuleHelper {
110        lpNSAPIGetBasePath fNSAPIGetBasePath = NULL;
111        lpNSAPIGetApplicationName fNSAPIGetApplicationName = NULL;
112        lpNSAPIGetApplicationVersionStr fNSAPIGetApplicationVersionStr = NULL;
113        lpNSAPIGetSettingsString fNSAPIGetSettingsString = NULL;
114        lpNSAPIGetSettingsInt fNSAPIGetSettingsInt = NULL;
115        lpNSAPIMessage fNSAPIMessage = NULL;
116        lpNSAPIStopServer fNSAPIStopServer = NULL;
117        lpNSAPIInject fNSAPIInject = NULL;
118}
119
120//////////////////////////////////////////////////////////////////////////
121// Callbacks into the core
122//////////////////////////////////////////////////////////////////////////
123
124/**
125 * Callback to send a message through to the core
126 *
127 * @param msgType Message type (debug, warning, etc.)
128 * @param file File where message was generated (__FILE__)
129 * @param line Line where message was generated (__LINE__)
130 * @param message Message in human readable format
131 * @throws NSCMHExcpetion When core pointer set is unavailable.
132 */
133void NSCModuleHelper::Message(int msgType, std::string file, int line, std::string message) {
134        if (!fNSAPIMessage)
135                throw NSCMHExcpetion("NSCore has not been initiated...");
136        return fNSAPIMessage(msgType, file.c_str(), line, message.c_str());
137}
138/**
139 * Inject a request command in the core (this will then be sent to the plug-in stack for processing)
140 * @param command Command to inject (password should not be included.
141 * @return The result (if any) of the command.
142 * @throws NSCMHExcpetion When core pointer set is unavailable or an unknown inject error occures.
143 */
144std::string NSCModuleHelper::InjectCommand(std::string command) {
145        if (!fNSAPIInject)
146                throw NSCMHExcpetion("NSCore has not been initiated...");
147        char *buffer = new char[BUFF_LEN+1];
148        std::string ret;
149        int err;
150        if ((err = fNSAPIInject(command.c_str(), buffer, BUFF_LEN)) != NSCAPI::success) {
151                if (err == NSCAPI::invalidBufferLen)
152                        NSC_LOG_ERROR("Inject command resulted in an invalid buffer size.");
153                else
154                        throw NSCMHExcpetion("Unknown inject error.");
155        } else {
156                ret = buffer;
157        }
158        delete [] buffer;
159        return ret;
160}
161/**
162 * Ask the core to shutdown (only works when run as a service, o/w does nothing ?
163 * @todo Check if this might cause damage if not run as a service.
164 */
165void NSCModuleHelper::StopService(void) {
166        if (fNSAPIStopServer)
167                fNSAPIStopServer();
168}
169/**
170 * Retrieve a string from the settings subsystem (INI-file)
171 * Might possibly be located in the registry in the future.
172 *
173 * @param section Section key (generally module specific, make sure this is "unique")
174 * @param key The key to retrieve
175 * @param defaultValue A default value (if no value is set in the settings file)
176 * @return the current value or defaultValue if no value is set.
177 * @throws NSCMHExcpetion When core pointer set is unavailable or an error occurs.
178 */
179std::string NSCModuleHelper::getSettingsString(std::string section, std::string key, std::string defaultValue) {
180        if (!fNSAPIGetSettingsString)
181                throw NSCMHExcpetion("NSCore has not been initiated...");
182        char *buffer = new char[BUFF_LEN+1];
183        if (fNSAPIGetSettingsString(section.c_str(), key.c_str(), defaultValue.c_str(), buffer, BUFF_LEN) != NSCAPI::success) {
184                delete [] buffer;
185                throw NSCMHExcpetion("Settings could not be retrieved.");
186        }
187        std::string ret = buffer;
188        delete [] buffer;
189        return ret;
190}
191/**
192 * Retrieve an int from the settings subsystem (INI-file)
193 * Might possibly be located in the registry in the future.
194 *
195 * @param section Section key (generally module specific, make sure this is "unique")
196 * @param key The key to retrieve
197 * @param defaultValue A default value (if no value is set in the settings file)
198 * @return the current value or defaultValue if no value is set.
199 * @throws NSCMHExcpetion When core pointer set is unavailable.
200 */
201int NSCModuleHelper::getSettingsInt(std::string section, std::string key, int defaultValue) {
202        if (!fNSAPIGetSettingsInt)
203                throw NSCMHExcpetion("NSCore has not been initiated...");
204        return fNSAPIGetSettingsInt(section.c_str(), key.c_str(), defaultValue);
205}
206/**
207 * Retrieve the application name (in human readable format) from the core.
208 * @return A string representing the application name.
209 * @throws NSCMHExcpetion When core pointer set is unavailable or an unexpected error occurs.
210 */
211std::string NSCModuleHelper::getApplicationName() {
212        if (!fNSAPIGetApplicationName)
213                throw NSCMHExcpetion("NSCore has not been initiated...");
214        char *buffer = new char[BUFF_LEN+1];
215        if (fNSAPIGetApplicationName(buffer, BUFF_LEN) != NSCAPI::success) {
216                delete [] buffer;
217                throw NSCMHExcpetion("Application name could not be retrieved");
218        }
219        std::string ret = buffer;
220        delete [] buffer;
221        return ret;
222}
223/**
224 * Retrieve the directory root of the application from the core.
225 * @return A string representing the base path.
226 * @throws NSCMHExcpetion When core pointer set is unavailable or an unexpected error occurs.
227 */
228std::string NSCModuleHelper::getBasePath() {
229        if (!fNSAPIGetBasePath)
230                throw NSCMHExcpetion("NSCore has not been initiated...");
231        char *buffer = new char[BUFF_LEN+1];
232        if (fNSAPIGetBasePath(buffer, BUFF_LEN) != NSCAPI::success) {
233                delete [] buffer;
234                throw NSCMHExcpetion("Base path could not be retrieved");
235        }
236        std::string ret = buffer;
237        delete [] buffer;
238        return ret;
239}
240/**
241 * Retrieve the application version as a string (in human readable format) from the core.
242 * @return A string representing the application version.
243 * @throws NSCMHExcpetion When core pointer set is unavailable.
244 */
245std::string NSCModuleHelper::getApplicationVersionString() {
246        if (!fNSAPIGetApplicationVersionStr)
247                throw NSCMHExcpetion("NSCore has not been initiated...");
248        char *buffer = new char[BUFF_LEN+1];
249        int x = fNSAPIGetApplicationVersionStr(buffer, BUFF_LEN);
250        std::string ret = buffer;
251        delete [] buffer;
252        return ret;
253}
254
255//////////////////////////////////////////////////////////////////////////
256// Module helper functions
257//////////////////////////////////////////////////////////////////////////
258namespace NSCModuleWrapper {
259        HINSTANCE hModule_ = NULL;
260}
261/**
262 * Used to help store the module handle (and possibly other things in the future)
263 * @param hModule cf. DllMain
264 * @param ul_reason_for_call cf. DllMain
265 * @return TRUE
266 */
267BOOL NSCModuleWrapper::wrapDllMain(HANDLE hModule, DWORD ul_reason_for_call)
268{
269        switch (ul_reason_for_call)
270        {
271        case DLL_PROCESS_ATTACH:
272        case DLL_THREAD_ATTACH:
273                hModule_ = (HINSTANCE)hModule;
274                break;
275        case DLL_THREAD_DETACH:
276        case DLL_PROCESS_DETACH:
277                break;
278        }
279        return TRUE;
280}
281/**
282 * Retrieve the module handle from the DllMain call.
283 * @return Module handle of this DLL
284 */
285HINSTANCE NSCModuleWrapper::getModule() {
286        return hModule_;
287}
288
289/**
290 * Wrapper function around the ModuleHelperInit call.
291 * This wrapper retrieves all pointers and stores them for future use.
292 * @param f A function pointer to a function that can be used to load function from the core.
293 * @return NSCAPI::success or NSCAPI::failure
294 */
295int NSCModuleWrapper::wrapModuleHelperInit(NSCModuleHelper::lpNSAPILoader f) {
296        NSCModuleHelper::fNSAPIGetApplicationName = (NSCModuleHelper::lpNSAPIGetApplicationName)f("NSAPIGetApplicationName");
297        NSCModuleHelper::fNSAPIGetApplicationVersionStr = (NSCModuleHelper::lpNSAPIGetApplicationVersionStr)f("NSAPIGetApplicationVersionStr");
298        NSCModuleHelper::fNSAPIGetSettingsInt = (NSCModuleHelper::lpNSAPIGetSettingsInt)f("NSAPIGetSettingsInt");
299        NSCModuleHelper::fNSAPIGetSettingsString = (NSCModuleHelper::lpNSAPIGetSettingsString)f("NSAPIGetSettingsString");
300        NSCModuleHelper::fNSAPIMessage = (NSCModuleHelper::lpNSAPIMessage)f("NSAPIMessage");
301        NSCModuleHelper::fNSAPIStopServer = (NSCModuleHelper::lpNSAPIStopServer)f("NSAPIStopServer");
302        NSCModuleHelper::fNSAPIInject = (NSCModuleHelper::lpNSAPIInject)f("NSAPIInject");
303        NSCModuleHelper::fNSAPIGetBasePath = (NSCModuleHelper::lpNSAPIGetBasePath)f("NSAPIGetBasePath");
304        return NSCAPI::success;
305}
306/**
307* Wrap the GetModuleName function call
308* @param buf Buffer to store the module name
309* @param bufLen Length of buffer
310* @param str String to store inside the buffer
311* @return buffer copy status
312*/
313int NSCModuleWrapper::wrapGetModuleName(char* buf, unsigned int bufLen, std::string str) {
314        return NSCHelper::wrapReturnString(buf, bufLen, str);
315}
316/**
317 * Wrap the GetModuleVersion function call
318 * @param *major Major version number
319 * @param *minor Minor version number
320 * @param *revision Revision
321 * @param version version as a module_version
322 * @return NSCAPI::success
323 */
324int NSCModuleWrapper::wrapGetModuleVersion(int *major, int *minor, int *revision, module_version version) {
325        *major = version.major;
326        *minor = version.minor;
327        *revision = version.revision;
328        return NSCAPI::success;
329}
330/**
331 * Wrap the HasCommandHandler function call
332 * @param has true if this module has a command handler
333 * @return NSCAPI::istrue or NSCAPI::isfalse
334 */
335int NSCModuleWrapper::wrapHasCommandHandler(bool has) {
336        if (has)
337                return NSCAPI::istrue;
338        return NSCAPI::isfalse;
339}
340/**
341 * Wrap the HasMessageHandler function call
342 * @param has true if this module has a message handler
343 * @return NSCAPI::istrue or NSCAPI::isfalse
344 */
345int NSCModuleWrapper::wrapHasMessageHandler(bool has) {
346        if (has)
347                return NSCAPI::istrue;
348        return NSCAPI::isfalse;
349}
350/**
351 * Wrap the HandleCommand call
352 * @param retStr The string to return to the core
353 * @param *returnBuffer A buffer to copy the return string to
354 * @param returnBufferLen length of returnBuffer
355 * @return copy status or NSCAPI::isfalse if retStr is empty
356 */
357int NSCModuleWrapper::wrapHandleCommand(const std::string retStr, char *returnBuffer, unsigned int returnBufferLen) {
358        if (retStr.empty())
359                return NSCAPI::isfalse;
360        return NSCHelper::wrapReturnString(returnBuffer, returnBufferLen, retStr, NSCAPI::handled);
361}
362/**
363 * Wrap the NSLoadModule call
364 * @param success true if module load was successfully
365 * @return NSCAPI::success or NSCAPI::failed
366 */
367int NSCModuleWrapper::wrapLoadModule(bool success) {
368        if (success)
369                return NSCAPI::success;
370        return NSCAPI::failed;
371}
372/**
373 * Wrap the NSUnloadModule call
374 * @param success true if module load was successfully
375 * @return NSCAPI::success or NSCAPI::failed
376 */
377int NSCModuleWrapper::wrapUnloadModule(bool success) {
378        if (success)
379                return NSCAPI::success;
380        return NSCAPI::failed;
381}
382
383
384
Note: See TracBrowser for help on using the repository browser.