source: nscp/NSClient++.cpp @ 9661f81

0.4.00.4.10.4.2stable
Last change on this file since 9661f81 was 9661f81, checked in by Michael Medin <michael@…>, 3 years ago

2010-05-10 MickeM - 0.3.8 RC2

  • Fixed issue with listpdh and debugpdh (not works again) + Fixed issue and added support for IN ( ... ) and NOT IN ( ... ) operators (CheckEventLog)

2010-05-08 MickeM

+ Added new "script templating" thing to simplify adding scripts:

Two new sections: [Script Wrappings] for adding templates and [Wrapped Scripts] for adding the scripts.

%SCRIPT% is replaced with the script name
%ARGS% is replaced with arguments.

vbs=cscript.exe T:30 NoLogo scripts\wrapper.vbs %SCRIPT% %ARGS%

and

w_vbs=check_test.vbs /arg1:1 /arg2:1 /variable:1

is the same as:

w_vbs=cscript.exe T:30 NoLogo scripts\wrapper.vbs check_test.vbs /arg1:1 /arg2:1 /variable:1

  • Added correct syntax for VB scripts
  • Added correct syntax for powershell scripts
  • Cleaned up scripts folder + Added new "NagiosPlugin? library" from op5 + Added check_no_rdp.vbs (Checks that no RDP connection is online) + Added check_battery.vbs which checks batterys via WMI + Added check_printer.vbs to check printers via WMI
  • Property mode set to 100644
File size: 54.8 KB
Line 
1///////////////////////////////////////////////////////////////////////////
2// NSClient++ Base Service
3//
4// Copyright (c) 2004 MySolutions NORDIC (http://www.medin.name)
5//
6// Date: 2004-03-13
7// Author: Michael Medin (michael@medin.name)
8//
9// Part of this file is based on work by Bruno Vais (bvais@usa.net)
10//
11// This software is provided "AS IS", without a warranty of any kind.
12// You are free to use/modify this code but leave this header intact.
13//
14//////////////////////////////////////////////////////////////////////////
15#include "stdafx.h"
16#include <winsvc.h>
17#include "NSClient++.h"
18#include <Settings.h>
19#include <charEx.h>
20#include <Socket.h>
21#include <b64/b64.h>
22#include <config.h>
23#include <msvc_wrappers.h>
24#include <Userenv.h>
25#include <remote_processes.hpp>
26#include <Lmcons.h>
27//#ifdef DEBUG
28#include <crtdbg.h>
29//#endif
30
31NSClient mainClient(SZSERVICENAME);     // Global core instance.
32bool g_bConsoleLog = false;
33
34
35class tray_starter {
36        struct start_block {
37                std::wstring cmd;
38                std::wstring cmd_line;
39                DWORD sessionId;
40        };
41
42public:
43        static LPVOID init(DWORD dwSessionId, std::wstring exe, std::wstring cmdline) {
44                start_block *sb = new start_block;
45                sb->cmd = exe;
46                sb->cmd_line = cmdline;
47                sb->sessionId = dwSessionId;
48                return sb;
49        }
50        DWORD threadProc(LPVOID lpParameter) {
51                start_block* param = static_cast<start_block*>(lpParameter);
52                DWORD dwSessionId = param->sessionId;
53                std::wstring cmd = param->cmd;
54                std::wstring cmdline = param->cmd_line;
55                delete param;
56                for (int i=0;i<10;i++) {
57                        Sleep(1000);
58                        if (startTrayHelper(dwSessionId, cmd, cmdline, false))
59                                break;
60                }
61                return 0;
62        }
63
64        static bool start(DWORD dwSessionId) {
65                std::wstring program = mainClient.getBasePath() +  _T("\\") + Settings::getInstance()->getString(NSCLIENT_SECTION_TITLE, NSCLIENT_SETTINGS_SYSTRAY_EXE, NSCLIENT_SETTINGS_SYSTRAY_EXE_DEFAULT);
66                std::wstring cmdln = _T("\"") + program + _T("\" -channel __") + strEx::itos(dwSessionId) + _T("__");
67                return tray_starter::startTrayHelper(dwSessionId, program, cmdln);
68        }
69
70        static bool startTrayHelper(DWORD dwSessionId, std::wstring exe, std::wstring cmdline, bool startThread = true) {
71                HANDLE hToken = NULL;
72                if (!remote_processes::GetSessionUserToken(dwSessionId, &hToken)) {
73                        LOG_ERROR_STD(_T("Failed to query user token: ") + error::lookup::last_error());
74                        return false;
75                } else {
76                        STARTUPINFO          StartUPInfo;
77                        PROCESS_INFORMATION  ProcessInfo;
78
79                        ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
80                        ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
81                        StartUPInfo.wShowWindow = SW_HIDE;
82                        StartUPInfo.lpDesktop = L"Winsta0\\Default";
83                        StartUPInfo.cb = sizeof(STARTUPINFO);
84
85                        wchar_t *buffer = new wchar_t[cmdline.size()+10];
86                        wcscpy(buffer, cmdline.c_str());
87                        LOG_MESSAGE_STD(_T("Running: ") + exe);
88                        LOG_MESSAGE_STD(_T("Running: ") + cmdline);
89
90                        LPVOID pEnv =NULL;
91                        DWORD dwCreationFlags = CREATE_NO_WINDOW; //0; //DETACHED_PROCESS
92
93                        if(CreateEnvironmentBlock(&pEnv,hToken,TRUE)) {
94                                dwCreationFlags|=CREATE_UNICODE_ENVIRONMENT;
95                        } else {
96                                LOG_ERROR_STD(_T("Failed to create enviornment: ") + error::lookup::last_error());
97                                pEnv=NULL;
98                        }
99                        /*
100                        LOG_ERROR_STD(_T("Impersonating user: "));
101                        if (!ImpersonateLoggedOnUser(hToken)) {
102                                LOG_ERROR_STD(_T("Failed to impersonate the user: ") + error::lookup::last_error());
103                        }
104
105                        wchar_t pszUname[UNLEN + 1];
106                        ZeroMemory(pszUname,sizeof(pszUname));
107                        DWORD dwSize = UNLEN;
108                        if (!GetUserName(pszUname,&dwSize)) {
109                                DWORD dwErr = GetLastError();
110                                if (!RevertToSelf())
111                                        LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
112                                LOG_ERROR_STD(_T("Failed to get username: ") + error::format::from_system(dwErr));
113                                return false;
114                        }
115                       
116
117                        PROFILEINFO info;
118                        info.dwSize = sizeof(PROFILEINFO);
119                        info.lpUserName = pszUname;
120                        if (!LoadUserProfile(hToken, &info)) {
121                                DWORD dwErr = GetLastError();
122                                if (!RevertToSelf())
123                                        LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
124                                LOG_ERROR_STD(_T("Failed to get username: ") + error::format::from_system(dwErr));
125                                return false;
126                        }
127                        */
128                        if (!CreateProcessAsUser(hToken, exe.c_str(), buffer, NULL, NULL, FALSE, dwCreationFlags, pEnv, NULL, &StartUPInfo, &ProcessInfo)) {
129                                DWORD dwErr = GetLastError();
130                                delete [] buffer;
131                                /*
132                                if (!RevertToSelf()) {
133                                        LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
134                                }
135                                */
136                                if (startThread && dwErr == ERROR_PIPE_NOT_CONNECTED) {
137                                        LOG_MESSAGE(_T("Failed to start trayhelper: starting a background thread to do it instead..."));
138                                        Thread<tray_starter> *pThread = new Thread<tray_starter>(_T("tray-starter-thread"));
139                                        pThread->createThread(tray_starter::init(dwSessionId, exe, cmdline));
140                                        return false;
141                                } else if (dwErr == ERROR_PIPE_NOT_CONNECTED) {
142                                        LOG_ERROR_STD(_T("Thread failed to start trayhelper (will try again): ") + error::format::from_system(dwErr));
143                                        return false;
144                                } else {
145                                        LOG_ERROR_STD(_T("Failed to start trayhelper: ") + error::format::from_system(dwErr));
146                                        return true;
147                                }
148                        } else {
149                                delete [] buffer;
150                                /*
151                                if (!RevertToSelf()) {
152                                        LOG_ERROR_STD(_T("Failed to revert to self: ") + error::lookup::last_error());
153                                }
154                                */
155                                LOG_MESSAGE_STD(_T("Started tray in other user session: ") + strEx::itos(dwSessionId));
156                        }
157
158
159                        CloseHandle(hToken);
160                        return true;
161                }
162        }
163};
164
165
166
167void display(std::wstring title, std::wstring message) {
168        ::MessageBox(NULL, message.c_str(), title.c_str(), MB_OK|MB_ICONERROR);
169}
170
171/**
172 * Application startup point
173 *
174 * @param argc Argument count
175 * @param argv[] Argument array
176 * @param envp[] Environment array
177 * @return exit status
178 */
179int wmain(int argc, TCHAR* argv[], TCHAR* envp[])
180{
181        srand( (unsigned)time( NULL ) );
182        int nRetCode = 0;
183        if ( (argc > 1) && ((*argv[1] == '-') || (*argv[1] == '/')) ) {
184                if ( _wcsicmp( _T("install"), argv[1]+1 ) == 0 ) {
185                        bool bGui = false;
186                        bool bStart = false;
187                        std::wstring service_name, service_description;
188                        for (int i=2;i<argc;i++) {
189                                if (_wcsicmp( _T("gui"), argv[i]) == 0) {
190                                        bGui = true;
191                                } else if (_wcsicmp( _T("start"), argv[i]) == 0) {
192                                        bStart = true;
193                                } else {
194                                        if (service_name.empty())
195                                                service_name = argv[i];
196                                        else {
197                                                if (!service_description.empty())
198                                                        service_description += _T(" ");
199                                                service_description += argv[i];
200                                        }
201                                }
202                        }
203                        if (service_name.empty())
204                                service_name = SZSERVICENAME;
205                        if (service_description.empty())
206                                service_description = SZSERVICEDISPLAYNAME;
207                        g_bConsoleLog = true;
208                        try {
209                                serviceControll::Install(service_name.c_str(), service_description.c_str(), SZDEPENDENCIES);
210                                if (bStart)
211                                        serviceControll::Start(service_name);
212                        } catch (const serviceControll::SCException& e) {
213                                if (bGui)
214                                        display(_T("Error installing"), _T("Service installation failed; ") + e.error_);
215                                LOG_ERROR_STD(_T("Service installation failed: ") + e.error_);
216                                return -1;
217                        }
218                        try {
219                                serviceControll::SetDescription(service_name, service_description);
220                        } catch (const serviceControll::SCException& e) {
221                                if (bGui)
222                                        display(_T("Error installing"), _T("Service installation failed; ") + e.error_);
223                                LOG_MESSAGE_STD(_T("Couldn't set service description: ") + e.error_);
224                        }
225                        if (bGui)
226                                display(_T("Service installed"), _T("Service installed successfully!"));
227                        LOG_MESSAGE(_T("Service installed!"));
228                        return 0;
229                } else if ( _wcsicmp( _T("uninstall"), argv[1]+1 ) == 0 ) {
230                        bool bGui = false;
231                        bool bStop = false;
232                        std::wstring service_name;
233                        for (int i=2;i<argc;i++) {
234                                if (_wcsicmp( _T("gui"), argv[i]) == 0) {
235                                        bGui = true;
236                                } else if (_wcsicmp( _T("stop"), argv[i]) == 0) {
237                                        bStop = true;
238                                } else {
239                                        service_name = argv[i];
240                                }
241                        }
242                        if (service_name.empty())
243                                service_name = SZSERVICENAME;
244                        g_bConsoleLog = true;
245                        try {
246                                if (bStop)
247                                        serviceControll::Stop(service_name);
248                        } catch (const serviceControll::SCException& e) {
249                                LOG_MESSAGE_STD(_T("Failed to stop service (") + service_name + _T(") failed; ") + e.error_);
250                        }
251                        try {
252                                serviceControll::Uninstall(service_name);
253                        } catch (const serviceControll::SCException& e) {
254                                if (bGui)
255                                        display(_T("Error uninstalling"), _T("Service de-installation (") + service_name + _T(") failed; ") + e.error_ + _T("\nMaybe the service was not previously installed properly?"));
256                                LOG_ERROR_STD(_T("Service deinstallation failed; ") + e.error_);
257                                return 0;
258                        }
259                        if (bGui)
260                                display(_T("Service uninstalled"), _T("Service uninstalled successfully!"));
261                        LOG_MESSAGE(_T("Service uninstalled!"));
262                        return 0;
263                } else if ( _wcsicmp( _T("encrypt"), argv[1]+1 ) == 0 ) {
264                        g_bConsoleLog = true;
265                        std::wstring password;
266                        try {
267                                Settings::getInstance()->setFile(mainClient.getBasePath(), _T("NSC.ini"));
268                        } catch (SettingsException e) {
269                                std::wcout << _T("Could not find settings: ") << e.getMessage() << std::endl;;
270                                return 1;
271                        }
272                        std::wcout << _T("Enter password to encrypt (has to be a single word): ");
273                        std::wcin >> password;
274                        std::wstring xor_pwd = Encrypt(password);
275                        std::wcout << _T("obfuscated_password=") << xor_pwd << std::endl;
276                        std::wstring outPasswd = Decrypt(xor_pwd);
277                        if (password != outPasswd)
278                                std::wcout << _T("ERROR: Password did not match: ") << outPasswd<< std::endl;
279                        Settings::destroyInstance();
280                        return 0;
281                } else if ( _wcsicmp( _T("start"), argv[1]+1 ) == 0 ) {
282                        g_bConsoleLog = true;
283                        bool bGui = false;
284                        std::wstring service_name;
285                        for (int i=2;i<argc;i++) {
286                                if (_wcsicmp( _T("gui"), argv[i]) == 0) {
287                                        bGui = true;
288                                } else {
289                                        service_name = argv[i];
290                                }
291                        }
292                        if (service_name.empty())
293                                service_name = SZSERVICENAME;
294                        try {
295                                serviceControll::Start(service_name.c_str());
296                        } catch (const serviceControll::SCException& e) {
297                                if (bGui)
298                                        display(_T("Service failed to start"), e.error_);
299                                LOG_MESSAGE_STD(_T("Service failed to start: ") + e.error_);
300                                return -1;
301                        }
302                } else if ( _wcsicmp( _T("stop"), argv[1]+1 ) == 0 ) {
303                        g_bConsoleLog = true;
304                        bool bGui = false;
305                        std::wstring service_name;
306                        for (int i=2;i<argc;i++) {
307                                if (_wcsicmp( _T("gui"), argv[i]) == 0) {
308                                        bGui = true;
309                                } else {
310                                        service_name = argv[i];
311                                }
312                        }
313                        if (service_name.empty())
314                                service_name = SZSERVICENAME;
315                        try {
316                                serviceControll::Stop(service_name.c_str());
317                        } catch (const serviceControll::SCException& e) {
318                                if (bGui)
319                                        display(_T("Service failed to stop"), e.error_);
320                                LOG_MESSAGE_STD(_T("Service failed to stop: ") + e.error_);
321                                return -1;
322                        }
323                } else if ( _wcsicmp( _T("about"), argv[1]+1 ) == 0 ) {
324                        g_bConsoleLog = true;
325                        LOG_MESSAGE(SZAPPNAME _T(" (C) Michael Medin - michael<at>medin<dot>name"));
326                        LOG_MESSAGE(_T("Version: ") SZVERSION);
327                        LOG_MESSAGE(_T("Architecture: ") SZARCH);
328
329                        std::wstring pluginPath = mainClient.getBasePath() + _T("modules\\");
330                        LOG_MESSAGE_STD(_T("Looking at plugins in: ") + pluginPath);
331
332                        WIN32_FIND_DATA wfd;
333                        HANDLE hFind = FindFirstFile((pluginPath + _T("*.dll")).c_str(), &wfd);
334                        if (hFind != INVALID_HANDLE_VALUE) {
335                                do {
336                                        std::wstring file = wfd.cFileName;
337                                        NSCPlugin *plugin = new NSCPlugin(pluginPath + _T("\\") + file);
338                                        std::wstring name = _T("<unknown>");
339                                        std::wstring description = _T("<unknown>");
340                                        try {
341                                                plugin->load_dll();
342                                                name = plugin->getName();
343                                                description = plugin->getDescription();
344                                        } catch(const NSPluginException& e) {
345                                                LOG_ERROR_STD(_T("Exception raised: ") + e.error_ + _T(" in module: ") + e.file_);
346                                        } catch (std::exception e) {
347                                                LOG_ERROR_STD(_T("exception loading plugin: ") + strEx::string_to_wstring(e.what()));
348                                        } catch (...) {
349                                                LOG_ERROR_STD(_T("Unknown exception loading plugin"));
350                                        }
351                                        LOG_MESSAGE_STD(_T("* ") + name + _T(" (") + file + _T(")"));
352                                        std::list<std::wstring> list = strEx::splitEx(description, _T("\n"));
353                                        for (std::list<std::wstring>::const_iterator cit = list.begin(); cit != list.end(); ++cit) {
354                                                LOG_MESSAGE_STD(_T("    ") + *cit);
355                                        }
356                                } while (FindNextFile(hFind, &wfd));
357                        } else {
358                                LOG_CRITICAL(_T("No plugin was found!"));
359                        }
360                        FindClose(hFind);
361                } else if ( _wcsicmp( _T("version"), argv[1]+1 ) == 0 ) {
362                        g_bConsoleLog = true;
363                        LOG_MESSAGE(SZAPPNAME _T(" Version: ") SZVERSION _T(", Plattform: ") SZARCH);
364                } else if ( _wcsicmp( _T("d"), argv[1]+1 ) == 0 ) {
365                        // Run command from command line (like NRPE) but with debug enabled
366                        g_bConsoleLog = true;
367                        mainClient.enableDebug(true);
368                        mainClient.initCore(true);
369                        std::wstring command, args, msg, perf;
370                        if (argc > 2)
371                                command = argv[2];
372                        for (int i=3;i<argc;i++) {
373                                if (i!=3) args += _T(" ");
374                                args += argv[i];
375                        }
376                        nRetCode = mainClient.inject(command, args, L' ', true, msg, perf);
377                        std::wcout << msg << _T("|") << perf << std::endl;
378                        mainClient.exitCore(true);
379                        return nRetCode;
380                } else if ( (_wcsicmp( _T("c"), argv[1]+1 ) == 0) || (_wcsicmp( _T("m"), argv[1]+1 ) == 0)) {
381                        std::wstring module, command, args, msg, perf;
382                        int arg_start;
383                        if ( _wcsicmp( _T("m"), argv[1]+1 ) == 0) {
384                                if ((argc < 4) || (_wcsicmp( _T("c"), argv[3]+1) != 0)) {
385                                        std::wcout << _T("missing argument");
386                                        return -1;
387                                }
388                                module = argv[2];
389                                command = argv[4];
390                                arg_start = 5;
391                        } else {
392                                if (argc > 2)
393                                        command = argv[2];
394                                arg_start = 3;
395                        }
396                        // Run command from command line (like NRPE)
397                        g_bConsoleLog = true;
398                        mainClient.enableDebug(false);
399                        mainClient.initCore(true, module);
400                        for (int i=arg_start;i<argc;i++) {
401                                if (i!=arg_start) args += _T(" ");
402                                args += argv[i];
403                        }
404                        nRetCode = mainClient.inject(command, args, L' ', true, msg, perf);
405                        std::wcout << msg << _T("|") << perf << std::endl;
406                        mainClient.exitCore(true);
407                        return nRetCode;
408                } else if ( _wcsicmp( _T("noboot"), argv[1]+1 ) == 0 ) {
409                        g_bConsoleLog = true;
410                        try {
411                                mainClient.enableDebug(false);
412                                mainClient.initCore(false);
413                                int nRetCode = -1;
414                                if (argc>=4)
415                                        nRetCode = mainClient.commandLineExec(argv[2], argv[3], argc-4, &argv[4]);
416                                else if (argc>=3)
417                                        nRetCode = mainClient.commandLineExec(argv[2], argv[3], 0, NULL);
418                                else
419                                        std::wcerr << _T("No arguments specified...") << std::endl;
420                                mainClient.exitCore(false);
421                        } catch (...) {
422                                std::wcerr << _T("Unknown error...") << std::endl;
423                        }
424                        return nRetCode;
425                } else if ( _wcsicmp( _T("svc"), argv[1]+1 ) == 0 ) {
426                        g_bConsoleLog = true;
427                        try {
428                                std::wstring exe = serviceControll::get_exe_path(SZSERVICENAME);
429                                LOG_MESSAGE_STD(_T("The Service uses: ") + exe);
430                        } catch (const serviceControll::SCException& e) {
431                                LOG_ERROR_STD(_T("Failed to find service: ") + e.error_);
432                        }
433                } else if ( _wcsicmp( _T("test"), argv[1]+1 ) == 0 ) {
434                        bool server = false;
435                        if (argc > 2 && _wcsicmp( _T("server"), argv[2] ) == 0 ) {
436                                server = true;
437                        }
438                        std::wcout << "Launching test mode - " << (server?_T("server mode"):_T("client mode")) << std::endl;
439                        LOG_MESSAGE_STD(_T("Booting: " SZSERVICEDISPLAYNAME ));
440                        try {
441                                if (serviceControll::isStarted(SZSERVICENAME)) {
442                                        std::wcerr << "Service seems to be started, this is probably not a good idea..." << std::endl;
443                                }
444                        } catch (const serviceControll::SCException& e) {
445                                e;// Empty by design
446                        }
447                        g_bConsoleLog = true;
448                        mainClient.enableDebug(true);
449                        if (!mainClient.initCore(true)) {
450                                LOG_ERROR_STD(_T("Service *NOT* started!"));
451                                return -1;
452                        }
453//                      if (server)
454//                              mainClient.startTrayIcon(0);
455                        LOG_MESSAGE_STD(_T("Using settings from: ") + Settings::getInstance()->getActiveType());
456                        LOG_MESSAGE(_T("Enter command to inject or exit to terminate..."));
457
458                        std::wstring s = _T("");
459                        std::wstring buff = _T("");
460                        while (true) {
461                                std::wcin >> s;
462                                if (s == _T("exit")) {
463                                        std::wcout << _T("Exiting...") << std::endl;
464                                        break;
465                                } else if (s == _T("off") && buff == _T("debug ")) {
466                                        std::wcout << _T("Setting debug log off...") << std::endl;
467                                        mainClient.enableDebug(false);
468                                } else if (s == _T("on") && buff == _T("debug ")) {
469                                        std::wcout << _T("Setting debug log on...") << std::endl;
470                                        mainClient.enableDebug(true);
471                                } else if (s == _T("reattach")) {
472                                        std::wcout << _T("Reattaching to session 0") << std::endl;
473                                        mainClient.startTrayIcon(0);
474//#ifdef DEBUG
475                                } else if (s == _T("assert")) {
476                                        throw "test";
477//#endif
478                                } else if (std::cin.peek() < 15) {
479                                        buff += s;
480                                        strEx::token t = strEx::getToken(buff, ' ');
481                                        std::wstring msg, perf;
482                                        NSCAPI::nagiosReturn ret = mainClient.inject(t.first, t.second, ' ', true, msg, perf);
483                                        if (ret == NSCAPI::returnIgnored) {
484                                                std::wcout << _T("No handler for command: ") << t.first << std::endl;
485                                        } else {
486                                                std::wcout << NSCHelper::translateReturn(ret) << _T(":");
487                                                std::cout << strEx::wstring_to_string(msg);
488                                                if (!perf.empty())
489                                                        std::cout << "|" << strEx::wstring_to_string(perf);
490                                                std::wcout << std::endl;
491                                        }
492                                        buff = _T("");
493                                } else {
494                                        buff += s + _T(" ");
495                                }
496                        }
497                        mainClient.exitCore(true);
498                        return 0;
499                } else {
500                        std::wcerr << _T("Usage: -version, -about, -install, -uninstall, -start, -stop, -encrypt") << std::endl;
501                        std::wcerr << _T("Usage: [-noboot] <ModuleName> <commnd> [arguments]") << std::endl;
502                        return -1;
503                }
504                return nRetCode;
505        } else if (argc > 2) {
506                g_bConsoleLog = true;
507                mainClient.initCore(true);
508                if (argc>=3)
509                        nRetCode = mainClient.commandLineExec(argv[1], argv[2], argc-3, &argv[3]);
510                else
511                        nRetCode = mainClient.commandLineExec(argv[1], argv[2], 0, NULL);
512                mainClient.exitCore(true);
513                return nRetCode;
514        } else if (argc > 1) {
515                g_bConsoleLog = true;
516                mainClient.enableDebug(true);
517                std::wcerr << _T("Invalid command line argument: ") << argv[1] << std::endl;
518                std::wcerr << _T("Usage: -version, -about, -install, -uninstall, -start, -stop, -encrypt") << std::endl;
519                std::wcerr << _T("Usage: [-noboot] <ModuleName> <commnd> [arguments]") << std::endl;
520                return -1;
521        }
522        std::wcout << _T("Running as service...") << std::endl;
523        if (!mainClient.StartServiceCtrlDispatcher()) {
524                LOG_MESSAGE(_T("We failed to start the service"));
525        }
526        return nRetCode;
527}
528
529void NSClientT::session_error(std::wstring file, unsigned int line, std::wstring msg) {
530        NSAPIMessage(NSCAPI::error, file.c_str(), line, msg.c_str());
531}
532
533void NSClientT::session_info(std::wstring file, unsigned int line, std::wstring msg) {
534        NSAPIMessage(NSCAPI::log, file.c_str(), line, msg.c_str());
535}
536
537
538
539
540//////////////////////////////////////////////////////////////////////////
541// Service functions
542
543/**
544 * Initialize the program
545 * @param boot true if we shall boot all plugins
546 * @param attachIfPossible is true we will attach to a running instance.
547 * @return success
548 * @author mickem
549 */
550bool NSClientT::initCore(bool boot, std::wstring module) {
551        LOG_DEBUG(_T("Attempting to start NSCLient++ - " SZVERSION));
552        try {
553                Settings::getInstance()->setFile(getBasePath(), _T("NSC.ini"));
554                if (debug_ == log_debug) {
555                        Settings::getInstance()->setInt(_T("log"), _T("debug"), 1);
556                }
557                if (enable_shared_session_)
558                        Settings::getInstance()->setInt(MAIN_SECTION_TITLE, MAIN_SHARED_SESSION, 1);
559                enable_shared_session_ = Settings::getInstance()->getInt(MAIN_SECTION_TITLE, MAIN_SHARED_SESSION, MAIN_SHARED_SESSION_DEFAULT)==1;
560        } catch (SettingsException e) {
561                LOG_ERROR_STD(_T("Could not find settings: ") + e.getMessage());
562                return false;
563        } catch (...) {
564                LOG_ERROR_STD(_T("Unknown exception reading settings..."));
565                return false;
566        }
567
568        if (enable_shared_session_) {
569                LOG_MESSAGE_STD(_T("Enabling shared session..."));
570                if (boot) {
571                        LOG_MESSAGE_STD(_T("Starting shared session..."));
572                        try {
573                                shared_server_.reset(new nsclient_session::shared_server_session(this));
574                                if (!shared_server_->session_exists()) {
575                                        shared_server_->create_new_session();
576                                } else {
577                                        LOG_ERROR_STD(_T("Session already exists cant create a new one!"));
578                                }
579                                startTrayIcons();
580                        } catch (nsclient_session::session_exception e) {
581                                LOG_ERROR_STD(_T("Failed to create new session: ") + e.what());
582                                shared_server_.reset(NULL);
583                        } catch (...) {
584                                LOG_ERROR_STD(_T("Failed to create new session: Unknown exception"));
585                                shared_server_.reset(NULL);
586                        }
587                } else {
588                        LOG_MESSAGE_STD(_T("Attaching to shared session..."));
589                        try {
590                                std::wstring id = _T("_attached_") + strEx::itos(GetCurrentProcessId()) + _T("_");
591                                shared_client_.reset(new nsclient_session::shared_client_session(id, this));
592                                if (shared_client_->session_exists()) {
593                                        shared_client_->attach_to_session(id);
594                                } else {
595                                        LOG_ERROR_STD(_T("No session was found cant attach!"));
596                                }
597                                LOG_ERROR_STD(_T("Session is: ") + shared_client_->get_client_id());
598                        } catch (nsclient_session::session_exception e) {
599                                LOG_ERROR_STD(_T("Failed to attach to session: ") + e.what());
600                                shared_client_.reset(NULL);
601                        } catch (...) {
602                                LOG_ERROR_STD(_T("Failed to attach to session: Unknown exception"));
603                                shared_client_.reset(NULL);
604                        }
605                }
606        }
607
608        try {
609                simpleSocket::WSAStartup();
610        } catch (simpleSocket::SocketException e) {
611                LOG_ERROR_STD(_T("Socket exception: ") + e.getMessage());
612                return false;
613        } catch (...) {
614                LOG_ERROR_STD(_T("Unknown exception iniating socket..."));
615                return false;
616        }
617
618        try {
619                com_helper_.initialize();
620        } catch (com_helper::com_exception e) {
621                LOG_ERROR_STD(_T("COM exception: ") + e.getMessage());
622                return false;
623        } catch (...) {
624                LOG_ERROR_STD(_T("Unknown exception iniating COM..."));
625                return false;
626        }
627        if (boot) {
628                try {
629                        if (module.empty()) {
630                                settings_base::sectionList list = Settings::getInstance()->getSection(_T("modules"));
631                                for (settings_base::sectionList::iterator it = list.begin(); it != list.end(); it++) {
632                                        try {
633                                                loadPlugin(getBasePath() + _T("modules\\") + (*it));
634                                        } catch(const NSPluginException& e) {
635                                                LOG_ERROR_STD(_T("Exception raised: ") + e.error_ + _T(" in module: ") + e.file_);
636                                                //return false;
637                                        } catch (std::exception e) {
638                                                LOG_ERROR_STD(_T("exception loading plugin: ") + (*it) + strEx::string_to_wstring(e.what()));
639                                                return false;
640                                        } catch (...) {
641                                                LOG_ERROR_STD(_T("Unknown exception loading plugin: ") + (*it));
642                                                return false;
643                                        }
644                                }
645                        } else {
646                                try {
647                                        loadPlugin(getBasePath() + _T("modules\\") + module);
648                                } catch(const NSPluginException& e) {
649                                        LOG_ERROR_STD(_T("Exception raised: ") + e.error_ + _T(" in module: ") + e.file_);
650                                        //return false;
651                                } catch (std::exception e) {
652                                        LOG_ERROR_STD(_T("exception loading plugin: ") + module + strEx::string_to_wstring(e.what()));
653                                        return false;
654                                } catch (...) {
655                                        LOG_ERROR_STD(_T("Unknown exception loading plugin: ") + module);
656                                        return false;
657                                }
658                        }
659                } catch (SettingsException e) {
660                        LOG_ERROR_STD(_T("Failed to set settings file") + e.getMessage());
661                } catch (...) {
662                        LOG_ERROR_STD(_T("Unknown exception when loading settings"));
663                        return false;
664                }
665                try {
666                        loadPlugins();
667                } catch (...) {
668                        LOG_ERROR_STD(_T("Unknown exception loading plugins"));
669                        return false;
670                }
671                LOG_DEBUG_STD(_T("NSCLient++ - " SZVERSION) + _T(" Started!"));
672        }
673        return true;
674}
675
676/**
677 * Service control handler startup point.
678 * When the program is started as a service this will be the entry point.
679 */
680bool NSClientT::InitiateService() {
681        if (!initCore(true))
682                return false;
683/*
684        DWORD dwSessionId = remote_processes::getActiveSessionId();
685        if (dwSessionId != 0xFFFFFFFF)
686                tray_starter::start(dwSessionId);
687        else
688                LOG_ERROR_STD(_T("Failed to start tray helper:" ) + error::lookup::last_error());
689                */
690        return true;
691}
692
693void NSClientT::startTrayIcons() {
694        if (shared_server_.get() == NULL) {
695                LOG_MESSAGE_STD(_T("No master session so tray icons not started"));
696                return;
697        }
698        remote_processes::PWTS_SESSION_INFO list;
699        DWORD count;
700        if (!remote_processes::_WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE , 0, 1, &list, &count)) {
701                LOG_ERROR_STD(_T("Failed to enumerate sessions:" ) + error::lookup::last_error());
702        } else {
703                LOG_DEBUG_STD(_T("Found ") + strEx::itos(count) + _T(" sessions"));
704                for (DWORD i=0;i<count;i++) {
705                        LOG_DEBUG_STD(_T("Found session: ") + strEx::itos(list[i].SessionId) + _T(" state: ") + strEx::itos(list[i].State));
706                        if (list[i].State == remote_processes::_WTS_CONNECTSTATE_CLASS::WTSActive) {
707                                startTrayIcon(list[i].SessionId);
708                        }
709                }
710        }
711}
712void NSClientT::startTrayIcon(DWORD dwSessionId) {
713        if (shared_server_.get() == NULL) {
714                LOG_MESSAGE_STD(_T("No master session so tray icons not started"));
715                return;
716        }
717        if (!shared_server_->re_attach_client(dwSessionId)) {
718                if (!tray_starter::start(dwSessionId)) {
719                        LOG_ERROR_STD(_T("Failed to start session (") + strEx::itos(dwSessionId) + _T("): " ) + error::lookup::last_error());
720                }
721        }
722}
723
724bool NSClientT::exitCore(bool boot) {
725        plugins_loaded_ = false;
726        LOG_DEBUG(_T("Attempting to stop NSCLient++ - " SZVERSION));
727        if (boot) {
728                try {
729                        LOG_DEBUG_STD(_T("Stopping: NON Message Handling Plugins"));
730                        mainClient.unloadPlugins(false);
731                } catch(NSPluginException e) {
732                        LOG_ERROR_STD(_T("Exception raised when unloading non msg plguins: ") + e.error_ + _T(" in module: ") + e.file_);
733                } catch(...) {
734                        LOG_ERROR_STD(_T("Unknown exception raised when unloading non msg plugins"));
735                }
736        }
737        LOG_DEBUG_STD(_T("Stopping: COM helper"));
738        try {
739                com_helper_.unInitialize();
740        } catch (com_helper::com_exception e) {
741                LOG_ERROR_STD(_T("COM exception: ") + e.getMessage());
742        } catch (...) {
743                LOG_ERROR_STD(_T("Unknown exception uniniating COM..."));
744        }
745        LOG_DEBUG_STD(_T("Stopping: Socket Helpers"));
746        try {
747                simpleSocket::WSACleanup();
748        } catch (simpleSocket::SocketException e) {
749                LOG_ERROR_STD(_T("Socket exception: ") + e.getMessage());
750        } catch (...) {
751                LOG_ERROR_STD(_T("Unknown exception uniniating socket..."));
752        }
753        LOG_DEBUG_STD(_T("Stopping: Settings instance"));
754        Settings::destroyInstance();
755        try {
756                if (shared_client_.get() != NULL) {
757                        LOG_DEBUG_STD(_T("Stopping: shared client"));
758                        shared_client_->set_handler(NULL);
759                        shared_client_->close_session();
760                }
761        } catch(nsclient_session::session_exception &e) {
762                LOG_ERROR_STD(_T("Exception closing shared client session: ") + e.what());
763        } catch(...) {
764                LOG_ERROR_STD(_T("Exception closing shared client session: Unknown exception!"));
765        }
766        try {
767                if (shared_server_.get() != NULL) {
768                        LOG_DEBUG_STD(_T("Stopping: shared server"));
769                        shared_server_->set_handler(NULL);
770                        shared_server_->close_session();
771                }
772        } catch(...) {
773                LOG_ERROR_STD(_T("UNknown exception raised: When closing shared session"));
774        }
775        if (boot) {
776                try {
777                        LOG_DEBUG_STD(_T("Stopping: Message handling Plugins"));
778                        mainClient.unloadPlugins(true);
779                } catch(NSPluginException e) {
780                        LOG_ERROR_STD(_T("Exception raised when unloading msg plugins: ") + e.error_ + _T(" in module: ") + e.file_);
781                } catch(...) {
782                        LOG_ERROR_STD(_T("UNknown exception raised: When stopping message plguins"));
783                }
784                LOG_DEBUG_STD(_T("NSCLient++ - " SZVERSION) + _T(" Stopped succcessfully"));
785        }
786        return true;
787}
788/**
789 * Service control handler termination point.
790 * When the program is stopped as a service this will be the "exit point".
791 */
792void NSClientT::TerminateService(void) {
793        exitCore(true);
794}
795
796/**
797 * Forward this to the main service dispatcher helper class
798 * @param dwArgc
799 * @param *lpszArgv
800 */
801void WINAPI NSClientT::service_main_dispatch(DWORD dwArgc, LPTSTR *lpszArgv) {
802        try {
803                mainClient.service_main(dwArgc, lpszArgv);
804        } catch (service_helper::service_exception e) {
805                LOG_ERROR_STD(_T("Unknown service error: ") + e.what());
806        } catch (...) {
807                LOG_ERROR_STD(_T("Unknown service error!"));
808        }
809}
810DWORD WINAPI NSClientT::service_ctrl_dispatch_ex(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext) {
811        return mainClient.service_ctrl_ex(dwControl, dwEventType, lpEventData, lpContext);
812}
813
814/**
815 * Forward this to the main service dispatcher helper class
816 * @param dwCtrlCode
817 */
818void WINAPI NSClientT::service_ctrl_dispatch(DWORD dwCtrlCode) {
819        mainClient.service_ctrl_ex(dwCtrlCode, NULL, NULL, NULL);
820}
821
822
823void NSClientT::service_on_session_changed(DWORD dwSessionId, bool logon, DWORD dwEventType) {
824        if (shared_server_.get() == NULL) {
825                LOG_DEBUG_STD(_T("No shared session: ignoring change event!"));
826                return;
827        }
828        LOG_DEBUG_STD(_T("Got session change: ") + strEx::itos(dwSessionId));
829        if (!logon) {
830                LOG_DEBUG_STD(_T("Not a logon event: ") + strEx::itos(dwEventType));
831                return;
832        }
833        tray_starter::start(dwSessionId);
834}
835
836
837//////////////////////////////////////////////////////////////////////////
838// Member functions
839
840int NSClientT::commandLineExec(const TCHAR* module, const TCHAR* command, const unsigned int argLen, TCHAR** args) {
841        std::wstring sModule = module;
842        std::wstring moduleList = _T("");
843        {
844                ReadLock readLock(&m_mutexRW, true, 10000);
845                if (!readLock.IsLocked()) {
846                        LOG_ERROR(_T("FATAL ERROR: Could not get read-mutex."));
847                        return -1;
848                }
849                for (pluginList::size_type i=0;i<plugins_.size();++i) {
850                        NSCPlugin *p = plugins_[i];
851                        if (!moduleList.empty())
852                                moduleList += _T(", ");
853                        moduleList += p->getModule();
854                        if (p->getModule() == sModule) {
855                                LOG_DEBUG_STD(_T("Found module: ") + p->getName() + _T("..."));
856                                try {
857                                        return p->commandLineExec(command, argLen, args);
858                                } catch (NSPluginException e) {
859                                        LOG_ERROR_STD(_T("Could not execute command: ") + e.error_ + _T(" in ") + e.file_);
860                                        return -1;
861                                }
862                        }
863                }
864        }
865        try {
866                plugin_type plugin = loadPlugin(getBasePath() + _T("modules\\") + module);
867                LOG_DEBUG_STD(_T("Loading plugin: ") + plugin->getName() + _T("..."));
868                plugin->load_plugin();
869                return plugin->commandLineExec(command, argLen, args);
870        } catch (NSPluginException e) {
871                LOG_MESSAGE_STD(_T("Module (") + e.file_ + _T(") was not found: ") + e.error_);
872        }
873        try {
874                plugin_type plugin = loadPlugin(getBasePath() + _T("modules\\") + module + _T(".dll"));
875                LOG_DEBUG_STD(_T("Loading plugin: ") + plugin->getName() + _T("..."));
876                plugin->load_plugin();
877                return plugin->commandLineExec(command, argLen, args);
878        } catch (NSPluginException e) {
879                LOG_MESSAGE_STD(_T("Module (") + e.file_ + _T(") was not found: ") + e.error_);
880        }
881        LOG_ERROR_STD(_T("Module not found: ") + module + _T(" available modules are: ") + moduleList);
882        return 0;
883}
884
885/**
886 * Load a list of plug-ins
887 * @param plugins A list with plug-ins (DLL files) to load
888 */
889void NSClientT::addPlugins(const std::list<std::wstring> plugins) {
890        ReadLock readLock(&m_mutexRW, true, 10000);
891        if (!readLock.IsLocked()) {
892                LOG_ERROR(_T("FATAL ERROR: Could not get read-mutex."));
893                return;
894        }
895        std::list<std::wstring>::const_iterator it;
896        for (it = plugins.begin(); it != plugins.end(); ++it) {
897                loadPlugin(*it);
898        }
899}
900/**
901 * Unload all plug-ins (in reversed order)
902 */
903void NSClientT::unloadPlugins(bool unloadLoggers) {
904        {
905                WriteLock writeLock(&m_mutexRW, true, 10000);
906                if (!writeLock.IsLocked()) {
907                        LOG_ERROR(_T("FATAL ERROR: Could not get read-mutex."));
908                        return;
909                }
910                commandHandlers_.clear();
911                if (unloadLoggers)
912                        messageHandlers_.clear();
913        }
914        {
915                ReadLock readLock(&m_mutexRW, true, 10000);
916                if (!readLock.IsLocked()) {
917                        LOG_ERROR(_T("FATAL ERROR: Could not get read-mutex."));
918                        return;
919                }
920                for (pluginList::reverse_iterator it = plugins_.rbegin(); it != plugins_.rend(); ++it) {
921                        NSCPlugin *p = *it;
922                        if (p == NULL)
923                                continue;
924                        try {
925                                if (unloadLoggers || !p->hasMessageHandler()) {
926                                        LOG_DEBUG_STD(_T("Unloading plugin: ") + p->getModule() + _T("..."));
927                                        p->unload();
928                                } else {
929                                        LOG_DEBUG_STD(_T("Skipping log plugin: ") + p->getModule() + _T("..."));
930                                }
931                        } catch(NSPluginException e) {
932                                LOG_ERROR_STD(_T("Exception raised when unloading plugin: ") + e.error_ + _T(" in module: ") + e.file_);
933                        } catch(...) {
934                                LOG_ERROR_STD(_T("Unknown exception raised when unloading plugin"));
935                        }
936                }
937        }
938        {
939                WriteLock writeLock(&m_mutexRW, true, 10000);
940                if (!writeLock.IsLocked()) {
941                        LOG_ERROR(_T("FATAL ERROR: Could not get read-mutex."));
942                        return;
943                }
944                for (pluginList::iterator it = plugins_.begin(); it != plugins_.end();) {
945                        NSCPlugin *p = (*it);
946                        try {
947                                if (p != NULL && (unloadLoggers|| !p->isLoaded())) {
948                                        it = plugins_.erase(it);
949                                        delete p;
950                                        continue;
951                                }
952                        } catch(NSPluginException e) {
953                                LOG_ERROR_STD(_T("Exception raised when unloading plugin: ") + e.error_ + _T(" in module: ") + e.file_);
954                        } catch(...) {
955                                LOG_ERROR_STD(_T("Unknown exception raised when unloading plugin"));
956                        }
957                        it++;
958                }
959        }
960}
961
962void NSClientT::loadPlugins() {
963        ReadLock readLock(&m_mutexRW, true, 10000);
964        if (!readLock.IsLocked()) {
965                LOG_ERROR(_T("FATAL ERROR: Could not get read-mutex."));
966                return;
967        }
968        for (pluginList::iterator it=plugins_.begin(); it != plugins_.end();) {
969                LOG_DEBUG_STD(_T("Loading plugin: ") + (*it)->getName() + _T("..."));
970                try {
971                        (*it)->load_plugin();
972                        ++it;
973                } catch(NSPluginException e) {
974                        it = plugins_.erase(it);
975                        LOG_ERROR_STD(_T("Exception raised when loading plugin: ") + e.error_ + _T(" in module: ") + e.file_ + _T(" plugin has been removed."));
976                } catch(...) {
977                        it = plugins_.erase(it);
978                        LOG_ERROR_STD(_T("Unknown exception raised when unloading plugin plugin has been removed"));
979                }
980        }
981        plugins_loaded_ = true;
982}
983/**
984 * Load a single plug-in using a DLL filename
985 * @param file The DLL file
986 */
987NSClientT::plugin_type NSClientT::loadPlugin(const std::wstring file) {
988        return addPlugin(new NSCPlugin(file));
989}
990/**
991 * Load and add a plugin to various internal structures
992 * @param *plugin The plug-ininstance to load. The pointer is managed by the
993 */
994NSClientT::plugin_type NSClientT::addPlugin(plugin_type plugin) {
995        plugin->load_dll();
996        {
997                WriteLock writeLock(&m_mutexRW, true, 10000);
998                if (!writeLock.IsLocked()) {
999                        LOG_ERROR(_T("FATAL ERROR: Could not get read-mutex."));
1000                        return plugin;
1001                }
1002                plugins_.insert(plugins_.end(), plugin);
1003                if (plugin->hasCommandHandler())
1004                        commandHandlers_.insert(commandHandlers_.end(), plugin);
1005                if (plugin->hasMessageHandler())
1006                        messageHandlers_.insert(messageHandlers_.end(), plugin);
1007        }
1008        return plugin;
1009}
1010
1011
1012std::wstring NSClientT::describeCommand(std::wstring command) {
1013        ReadLock readLock(&m_mutexRWcmdDescriptions, true, 5000);
1014        if (!readLock.IsLocked()) {
1015                LOG_ERROR(_T("FATAL ERROR: Could not get read-mutex when trying to get command list."));
1016                return _T("Failed to get mutex when describing command: ") + command;
1017        }
1018        cmdMap::const_iterator cit = cmdDescriptions_.find(command);
1019        if (cit == cmdDescriptions_.end())
1020                return _T("Command not found: ") + command + _T(", maybe it has not been register?");
1021        return (*cit).second;
1022}
1023std::list<std::wstring> NSClientT::getAllCommandNames() {
1024        std::list<std::wstring> lst;
1025        ReadLock readLock(&m_mutexRWcmdDescriptions, true, 5000);
1026        if (!readLock.IsLocked()) {
1027                LOG_ERROR(_T("FATAL ERROR: Could not get read-mutex when trying to get command list."));
1028                return lst;
1029        }
1030        for (cmdMap::const_iterator cit = cmdDescriptions_.begin(); cit != cmdDescriptions_.end(); ++cit) {
1031                lst.push_back((*cit).first);
1032        }
1033        return lst;
1034}
1035void NSClientT::registerCommand(std::wstring cmd, std::wstring desc) {
1036        WriteLock writeLock(&m_mutexRWcmdDescriptions, true, 10000);
1037        if (!writeLock.IsLocked()) {
1038                LOG_ERROR_STD(_T("FATAL ERROR: Failed to describe command:") + cmd);
1039                return;
1040        }
1041        cmdDescriptions_[cmd] = desc;
1042}
1043
1044unsigned int NSClientT::getBufferLength() {
1045        static unsigned int len = 0;
1046        if (len == 0) {
1047                try {
1048                        len = Settings::getInstance()->getInt(MAIN_SECTION_TITLE, MAIN_STRING_LENGTH, MAIN_STRING_LENGTH_DEFAULT);
1049                } catch (SettingsException &e) {
1050                        LOG_DEBUG_STD(_T("Failed to get length: ") + e.getMessage());
1051                        return MAIN_STRING_LENGTH_DEFAULT;
1052                } catch (...) {
1053                        LOG_ERROR(_T("Failed to get length: :("));
1054                        return MAIN_STRING_LENGTH_DEFAULT;
1055                }
1056        }
1057        return len;
1058}
1059
1060NSCAPI::nagiosReturn NSClientT::inject(std::wstring command, std::wstring arguments, TCHAR splitter, bool escape, std::wstring &msg, std::wstring & perf) {
1061        if (shared_client_.get() != NULL && shared_client_->hasMaster()) {
1062                try {
1063                        return shared_client_->inject(command, arguments, splitter, escape, msg, perf);
1064                } catch (nsclient_session::session_exception &e) {
1065                        LOG_ERROR_STD(_T("Failed to inject remote command: ") + e.what());
1066                        return NSCAPI::returnCRIT;
1067                } catch (...) {
1068                        LOG_ERROR_STD(_T("Failed to inject remote command: Unknown exception"));
1069                        return NSCAPI::returnCRIT;
1070                }
1071        } else {
1072                unsigned int aLen = 0;
1073                TCHAR ** aBuf = arrayBuffer::split2arrayBuffer(arguments, splitter, aLen, escape);
1074                unsigned int buf_len = getBufferLength();
1075                TCHAR * mBuf = new TCHAR[buf_len+1]; mBuf[0] = '\0';
1076                TCHAR * pBuf = new TCHAR[buf_len+1]; pBuf[0] = '\0';
1077                NSCAPI::nagiosReturn ret = injectRAW(command.c_str(), aLen, aBuf, mBuf, buf_len, pBuf, buf_len);
1078                arrayBuffer::destroyArrayBuffer(aBuf, aLen);
1079                if ( (ret == NSCAPI::returnInvalidBufferLen) || (ret == NSCAPI::returnIgnored) ) {
1080                        delete [] mBuf;
1081                        delete [] pBuf;
1082                        return ret;
1083                }
1084                msg = mBuf;
1085                perf = pBuf;
1086                delete [] mBuf;
1087                delete [] pBuf;
1088                return ret;
1089        }
1090}
1091
1092/**
1093 * Inject a command into the plug-in stack.
1094 *
1095 * @param command Command to inject
1096 * @param argLen Length of argument buffer
1097 * @param **argument Argument buffer
1098 * @param *returnMessageBuffer Message buffer
1099 * @param returnMessageBufferLen Length of returnMessageBuffer
1100 * @param *returnPerfBuffer Performance data buffer
1101 * @param returnPerfBufferLen Length of returnPerfBuffer
1102 * @return The command status
1103 */
1104NSCAPI::nagiosReturn NSClientT::injectRAW(const TCHAR* command, const unsigned int argLen, TCHAR **argument, TCHAR *returnMessageBuffer, unsigned int returnMessageBufferLen, TCHAR *returnPerfBuffer, unsigned int returnPerfBufferLen) {
1105        if (logDebug()) {
1106                LOG_DEBUG_STD(_T("Injecting: ") + (std::wstring) command + _T(": ") + arrayBuffer::arrayBuffer2string(argument, argLen, _T(", ")));
1107        }
1108        if (shared_client_.get() != NULL && shared_client_->hasMaster()) {
1109                try {
1110                        std::wstring msg, perf;
1111                        int returnCode = shared_client_->inject(command, arrayBuffer::arrayBuffer2string(argument, argLen, _T(" ")), L' ', true, msg, perf);
1112                        NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, msg, returnCode);
1113                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, perf, returnCode);
1114                } catch (nsclient_session::session_exception &e) {
1115                        LOG_ERROR_STD(_T("Failed to inject remote command: ") + e.what());
1116                        int returnCode = NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, _T("Failed to inject remote command: ") + e.what(), NSCAPI::returnCRIT);
1117                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, _T(""), returnCode);
1118                } catch (...) {
1119                        LOG_ERROR_STD(_T("Failed to inject remote command: Unknown exception"));
1120                        int returnCode = NSCHelper::wrapReturnString(returnMessageBuffer, returnMessageBufferLen, _T("Failed to inject remote command:  + e.what()"), NSCAPI::returnCRIT);
1121                        return NSCHelper::wrapReturnString(returnPerfBuffer, returnPerfBufferLen, _T(""), returnCode);
1122                }
1123        } else {
1124                ReadLock readLock(&m_mutexRW, true, 5000);
1125                if (!readLock.IsLocked()) {
1126                        LOG_ERROR(_T("FATAL ERROR: Could not get read-mutex."));
1127                        return NSCAPI::returnUNKNOWN;
1128                }
1129                for (pluginList::size_type i = 0; i < commandHandlers_.size(); i++) {
1130                        try {
1131                                NSCAPI::nagiosReturn c = commandHandlers_[i]->handleCommand(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen);
1132                                switch (c) {
1133                                        case NSCAPI::returnInvalidBufferLen:
1134                                                LOG_ERROR(_T("UNKNOWN: Return buffer to small to handle this command."));
1135                                                return c;
1136                                        case NSCAPI::returnIgnored:
1137                                                break;
1138                                        case NSCAPI::returnOK:
1139                                        case NSCAPI::returnWARN:
1140                                        case NSCAPI::returnCRIT:
1141                                        case NSCAPI::returnUNKNOWN:
1142                                                LOG_DEBUG_STD(_T("Injected Result: ") + NSCHelper::translateReturn(c) + _T(" '") + (std::wstring)(returnMessageBuffer) + _T("'"));
1143                                                LOG_DEBUG_STD(_T("Injected Performance Result: '") +(std::wstring)(returnPerfBuffer) + _T("'"));
1144                                                return c;
1145                                        default:
1146                                                LOG_ERROR_STD(_T("Unknown error from handleCommand: ") + strEx::itos(c) + _T(" the injected command was: ") + (std::wstring)command);
1147                                                return c;
1148                                }
1149                        } catch(const NSPluginException& e) {
1150                                LOG_ERROR_STD(_T("Exception raised: ") + e.error_ + _T(" in module: ") + e.file_);
1151                                return NSCAPI::returnCRIT;
1152                        } catch(...) {
1153                                LOG_ERROR_STD(_T("Unknown exception raised in module"));
1154                                return NSCAPI::returnCRIT;
1155                        }
1156                }
1157                LOG_MESSAGE_STD(_T("No handler for command: '") + command + _T("'"));
1158                return NSCAPI::returnIgnored;
1159        }
1160}
1161
1162bool NSClientT::logDebug() {
1163        if (debug_ == log_unknown) {
1164                try {
1165                        if (Settings::getInstance()->getInt(_T("log"), _T("debug"), 0) == 1)
1166                                debug_ = log_debug;
1167                        else
1168                                debug_ = log_nodebug;
1169                } catch (SettingsException e) {
1170                        return true;
1171                }
1172        }
1173        return (debug_ == log_debug);
1174}
1175void NSClientT::enableDebug(bool debug) {
1176        if (debug) {
1177                debug_ = log_debug;
1178                LOG_DEBUG(_T("Enabling debug mode..."));
1179        }
1180        else
1181                debug_ = log_nodebug;
1182}
1183
1184
1185void log_broken_message(std::wstring msg) {
1186        OutputDebugString(msg.c_str());
1187        std::wcout << msg << std::endl;
1188}
1189/**
1190 * Report a message to all logging enabled modules.
1191 *
1192 * @param msgType Message type
1193 * @param file Filename generally __FILE__
1194 * @param line  Line number, generally __LINE__
1195 * @param message The message as a human readable string.
1196 */
1197void NSClientT::reportMessage(int msgType, const TCHAR* file, const int line, std::wstring message) {
1198        if ((msgType == NSCAPI::debug)&&(!logDebug())) {
1199                return;
1200        }
1201        if (shared_server_.get() != NULL && shared_server_->hasClients()) {
1202                try {
1203                        shared_server_->sendLogMessageToClients(msgType, file, line, message);
1204                } catch (nsclient_session::session_exception e) {
1205                        log_broken_message(_T("Failed to send message to clients: ") + e.what());
1206                }
1207        }
1208        std::wstring file_stl = file;
1209        std::wstring::size_type pos = file_stl.find_last_of(_T("\\"));
1210        if (pos != std::wstring::npos)
1211                file_stl = file_stl.substr(pos);
1212        {
1213                ReadLock readLock(&m_mutexRW, true, 5000);
1214                if (!readLock.IsLocked()) {
1215                        log_broken_message(_T("Message was lost as the (mutexRW) core was locked: ") + message);
1216                        return;
1217                }
1218                MutexLock lock(messageMutex);
1219                if (!lock.hasMutex()) {
1220                        log_broken_message(_T("Message was lost as the core was locked: ") + message);
1221                        return;
1222                }
1223                if (g_bConsoleLog) {
1224                        std::string k = "?";
1225                        switch (msgType) {
1226                        case NSCAPI::critical:
1227                                k ="c";
1228                                break;
1229                        case NSCAPI::warning:
1230                                k ="w";
1231                                break;
1232                        case NSCAPI::error:
1233                                k ="e";
1234                                break;
1235                        case NSCAPI::log:
1236                                k ="l";
1237                                break;
1238                        case NSCAPI::debug:
1239                                k ="d";
1240                                break;
1241                        }       
1242                        std::cout << k << " " << strEx::wstring_to_string(file_stl) << "(" << line << ") " << strEx::wstring_to_string(message) << std::endl;
1243                }
1244                if (!plugins_loaded_) {
1245                        OutputDebugString(message.c_str());
1246                        log_cache_.push_back(cached_log_entry(msgType, file, line, message));
1247                } else {
1248                        if (log_cache_.size() > 0) {
1249                                for (log_cache_type::const_iterator cit=log_cache_.begin();cit!=log_cache_.end();++cit) {
1250                                        for (pluginList::size_type i = 0; i< messageHandlers_.size(); i++) {
1251                                                try {
1252                                                        messageHandlers_[i]->handleMessage((*cit).msgType, (_T("CACHE") + (*cit).file).c_str(), (*cit).line, (*cit).message.c_str());
1253                                                } catch(const NSPluginException& e) {
1254                                                        log_broken_message(_T("Caught: ") + e.error_ + _T(" when trying to log a message..."));
1255                                                        return;
1256                                                } catch(...) {
1257                                                        log_broken_message(_T("Caught: Unknown Exception when trying to log a message..."));
1258                                                        return;
1259                                                }
1260                                        }
1261                                }
1262                                log_cache_.clear();
1263                        }
1264                        for (pluginList::size_type i = 0; i< messageHandlers_.size(); i++) {
1265                                try {
1266                                        messageHandlers_[i]->handleMessage(msgType, file, line, message.c_str());
1267                                } catch(const NSPluginException& e) {
1268                                        log_broken_message(_T("Caught: ") + e.error_ + _T(" when trying to log a message..."));
1269                                        return;
1270                                } catch(...) {
1271                                        log_broken_message(_T("Caught: Unknown Exception when trying to log a message..."));
1272                                        return;
1273                                }
1274                        }
1275                }
1276        }
1277}
1278std::wstring NSClientT::getBasePath(void) {
1279        MutexLock lock(internalVariables);
1280        if (!lock.hasMutex()) {
1281                LOG_ERROR(_T("FATAL ERROR: Could not get mutex."));
1282                return _T("FATAL ERROR");
1283        }
1284        if (!basePath.empty())
1285                return basePath;
1286        unsigned int buf_len = 4096;
1287        TCHAR* buffer = new TCHAR[buf_len+1];
1288        GetModuleFileName(NULL, buffer, buf_len);
1289        std::wstring path = buffer;
1290        std::wstring::size_type pos = path.rfind('\\');
1291        basePath = path.substr(0, pos) + _T("\\");
1292        delete [] buffer;
1293        try {
1294                Settings::getInstance()->setFile(basePath, _T("NSC.ini"));
1295        } catch (SettingsException e) {
1296                LOG_ERROR_STD(_T("Failed to set settings file") + e.getMessage());
1297        }
1298        return basePath;
1299}
1300
1301
1302NSCAPI::errorReturn NSAPIGetSettingsString(const TCHAR* section, const TCHAR* key, const TCHAR* defaultValue, TCHAR* buffer, unsigned int bufLen) {
1303        try {
1304                return NSCHelper::wrapReturnString(buffer, bufLen, Settings::getInstance()->getString(section, key, defaultValue), NSCAPI::isSuccess);
1305        } catch (...) {
1306                LOG_ERROR_STD(_T("Failed to getString: ") + key);
1307                return NSCAPI::hasFailed;
1308        }
1309}
1310int NSAPIGetSettingsInt(const TCHAR* section, const TCHAR* key, int defaultValue) {
1311        try {
1312                return Settings::getInstance()->getInt(section, key, defaultValue);
1313        } catch (SettingsException e) {
1314                LOG_ERROR_STD(_T("Failed to set settings file") + e.getMessage());
1315                return defaultValue;
1316        }
1317}
1318NSCAPI::errorReturn NSAPIGetBasePath(TCHAR*buffer, unsigned int bufLen) {
1319        return NSCHelper::wrapReturnString(buffer, bufLen, mainClient.getBasePath(), NSCAPI::isSuccess);
1320}
1321NSCAPI::errorReturn NSAPIGetApplicationName(TCHAR*buffer, unsigned int bufLen) {
1322        return NSCHelper::wrapReturnString(buffer, bufLen, SZAPPNAME, NSCAPI::isSuccess);
1323}
1324NSCAPI::errorReturn NSAPIGetApplicationVersionStr(TCHAR*buffer, unsigned int bufLen) {
1325        return NSCHelper::wrapReturnString(buffer, bufLen, SZVERSION, NSCAPI::isSuccess);
1326}
1327void NSAPIMessage(int msgType, const TCHAR* file, const int line, const TCHAR* message) {
1328        mainClient.reportMessage(msgType, file, line, message);
1329}
1330void NSAPIStopServer(void) {
1331        serviceControll::StopNoWait(SZSERVICENAME);
1332}
1333NSCAPI::nagiosReturn NSAPIInject(const TCHAR* command, const unsigned int argLen, TCHAR **argument, TCHAR *returnMessageBuffer, unsigned int returnMessageBufferLen, TCHAR *returnPerfBuffer, unsigned int returnPerfBufferLen) {
1334        return mainClient.injectRAW(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen);
1335}
1336NSCAPI::errorReturn NSAPIGetSettingsSection(const TCHAR* section, TCHAR*** aBuffer, unsigned int * bufLen) {
1337        try {
1338                unsigned int len = 0;
1339                *aBuffer = arrayBuffer::list2arrayBuffer(Settings::getInstance()->getSection(section), len);
1340                *bufLen = len;
1341                return NSCAPI::isSuccess;
1342        } catch (...) {
1343                LOG_ERROR_STD(_T("Failed to getSection: ") + section);
1344                return NSCAPI::hasFailed;
1345        }
1346}
1347NSCAPI::errorReturn NSAPIReleaseSettingsSectionBuffer(TCHAR*** aBuffer, unsigned int * bufLen) {
1348        arrayBuffer::destroyArrayBuffer(*aBuffer, *bufLen);
1349        *bufLen = 0;
1350        *aBuffer = NULL;
1351        return NSCAPI::isSuccess;
1352}
1353
1354NSCAPI::boolReturn NSAPICheckLogMessages(int messageType) {
1355        if (mainClient.logDebug())
1356                return NSCAPI::istrue;
1357        return NSCAPI::isfalse;
1358}
1359
1360std::wstring Encrypt(std::wstring str, unsigned int algorithm) {
1361        unsigned int len = 0;
1362        NSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
1363        len+=2;
1364        TCHAR *buf = new TCHAR[len+1];
1365        NSCAPI::errorReturn ret = NSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
1366        if (ret == NSCAPI::isSuccess) {
1367                std::wstring ret = buf;
1368                delete [] buf;
1369                return ret;
1370        }
1371        return _T("");
1372}
1373std::wstring Decrypt(std::wstring str, unsigned int algorithm) {
1374        unsigned int len = 0;
1375        NSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len);
1376        len+=2;
1377        TCHAR *buf = new TCHAR[len+1];
1378        NSCAPI::errorReturn ret = NSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len);
1379        if (ret == NSCAPI::isSuccess) {
1380                std::wstring ret = buf;
1381                delete [] buf;
1382                return ret;
1383        }
1384        return _T("");
1385}
1386
1387NSCAPI::errorReturn NSAPIEncrypt(unsigned int algorithm, const TCHAR* inBuffer, unsigned int inBufLen, TCHAR* outBuf, unsigned int *outBufLen) {
1388        if (algorithm != NSCAPI::xor) {
1389                LOG_ERROR(_T("Unknown algortihm requested."));
1390                return NSCAPI::hasFailed;
1391        }
1392        std::wstring key = Settings::getInstance()->getString(MAIN_SECTION_TITLE, MAIN_MASTERKEY, MAIN_MASTERKEY_DEFAULT);
1393        int tcharInBufLen = 0;
1394        char *c = charEx::tchar_to_char(inBuffer, inBufLen, tcharInBufLen);
1395        std::wstring::size_type j=0;
1396        for (int i=0;i<tcharInBufLen;i++,j++) {
1397                if (j > key.size())
1398                        j = 0;
1399                c[i] ^= key[j];
1400        }
1401        size_t cOutBufLen = b64::b64_encode(reinterpret_cast<void*>(c), tcharInBufLen, NULL, NULL);
1402        if (!outBuf) {
1403                *outBufLen = static_cast<unsigned int>(cOutBufLen*2); // TODO: Guessing wildly here but no proper way to tell without a lot of extra work
1404                return NSCAPI::isSuccess;
1405        }
1406        char *cOutBuf = new char[cOutBufLen+1];
1407        size_t len = b64::b64_encode(reinterpret_cast<void*>(c), tcharInBufLen, cOutBuf, cOutBufLen);
1408        delete [] c;
1409        if (len == 0) {
1410                LOG_ERROR(_T("Invalid out buffer length."));
1411                return NSCAPI::isInvalidBufferLen;
1412        }
1413        int realOutLen;
1414        TCHAR *realOut = charEx::char_to_tchar(cOutBuf, cOutBufLen, realOutLen);
1415        if (static_cast<unsigned int>(realOutLen) >= *outBufLen) {
1416                LOG_ERROR_STD(_T("Invalid out buffer length: ") + strEx::itos(realOutLen) + _T(" was needed but only ") + strEx::itos(*outBufLen) + _T(" was allocated."));
1417                return NSCAPI::isInvalidBufferLen;
1418        }
1419        wcsncpy_s(outBuf, *outBufLen, realOut, realOutLen);
1420        delete [] realOut;
1421        outBuf[realOutLen] = 0;
1422        *outBufLen = static_cast<unsigned int>(realOutLen);
1423        return NSCAPI::isSuccess;
1424}
1425
1426NSCAPI::errorReturn NSAPIDecrypt(unsigned int algorithm, const TCHAR* inBuffer, unsigned int inBufLen, TCHAR* outBuf, unsigned int *outBufLen) {
1427        if (algorithm != NSCAPI::xor) {
1428                LOG_ERROR(_T("Unknown algortihm requested."));
1429                return NSCAPI::hasFailed;
1430        }
1431        int inBufLenC = 0;
1432        char *inBufferC = charEx::tchar_to_char(inBuffer, inBufLen, inBufLenC);
1433        size_t cOutLen =  b64::b64_decode(inBufferC, inBufLenC, NULL, NULL);
1434        if (!outBuf) {
1435                *outBufLen = static_cast<unsigned int>(cOutLen*2); // TODO: Guessing wildly here but no proper way to tell without a lot of extra work
1436                return NSCAPI::isSuccess;
1437        }
1438        char *cOutBuf = new char[cOutLen+1];
1439        size_t len = b64::b64_decode(inBufferC, inBufLenC, reinterpret_cast<void*>(cOutBuf), cOutLen);
1440        delete [] inBufferC;
1441        if (len == 0) {
1442                LOG_ERROR(_T("Invalid out buffer length."));
1443                return NSCAPI::isInvalidBufferLen;
1444        }
1445        int realOutLen;
1446
1447        std::wstring key = Settings::getInstance()->getString(MAIN_SECTION_TITLE, MAIN_MASTERKEY, MAIN_MASTERKEY_DEFAULT);
1448        std::wstring::size_type j=0;
1449        for (int i=0;i<cOutLen;i++,j++) {
1450                if (j > key.size())
1451                        j = 0;
1452                cOutBuf[i] ^= key[j];
1453        }
1454
1455        TCHAR *realOut = charEx::char_to_tchar(cOutBuf, cOutLen, realOutLen);
1456        if (static_cast<unsigned int>(realOutLen) >= *outBufLen) {
1457                LOG_ERROR_STD(_T("Invalid out buffer length: ") + strEx::itos(realOutLen) + _T(" was needed but only ") + strEx::itos(*outBufLen) + _T(" was allocated."));
1458                return NSCAPI::isInvalidBufferLen;
1459        }
1460        wcsncpy_s(outBuf, *outBufLen, realOut, realOutLen);
1461        delete [] realOut;
1462        outBuf[realOutLen] = 0;
1463        *outBufLen = static_cast<unsigned int>(realOutLen);
1464        return NSCAPI::isSuccess;
1465}
1466
1467NSCAPI::errorReturn NSAPISetSettingsString(const TCHAR* section, const TCHAR* key, const TCHAR* value) {
1468        try {
1469                Settings::getInstance()->setString(section, key, value);
1470        } catch (...) {
1471                LOG_ERROR_STD(_T("Failed to setString: ") + key);
1472                return NSCAPI::hasFailed;
1473        }
1474        return NSCAPI::isSuccess;
1475}
1476NSCAPI::errorReturn NSAPISetSettingsInt(const TCHAR* section, const TCHAR* key, int value) {
1477        try {
1478                Settings::getInstance()->setInt(section, key, value);
1479        } catch (...) {
1480                LOG_ERROR_STD(_T("Failed to setInt: ") + key);
1481                return NSCAPI::hasFailed;
1482        }
1483        return NSCAPI::isSuccess;
1484}
1485NSCAPI::errorReturn NSAPIWriteSettings(int type) {
1486        try {
1487                if (type == NSCAPI::settings_registry)
1488                        Settings::getInstance()->write(REGSettings::getType());
1489                else if (type == NSCAPI::settings_inifile)
1490                        Settings::getInstance()->write(INISettings::getType());
1491                else
1492                        Settings::getInstance()->write();
1493        } catch (SettingsException e) {
1494                LOG_ERROR_STD(_T("Failed to write settings: ") + e.getMessage());
1495                return NSCAPI::hasFailed;
1496        } catch (...) {
1497                LOG_ERROR_STD(_T("Failed to write settings"));
1498                return NSCAPI::hasFailed;
1499        }
1500        return NSCAPI::isSuccess;
1501}
1502NSCAPI::errorReturn NSAPIReadSettings(int type) {
1503        try {
1504                if (type == NSCAPI::settings_registry)
1505                        Settings::getInstance()->read(REGSettings::getType());
1506                else if (type == NSCAPI::settings_inifile)
1507                        Settings::getInstance()->read(INISettings::getType());
1508                else
1509                        Settings::getInstance()->read();
1510        } catch (SettingsException e) {
1511                LOG_ERROR_STD(_T("Failed to read settings: ") + e.getMessage());
1512                return NSCAPI::hasFailed;
1513        } catch (...) {
1514                LOG_ERROR_STD(_T("Failed to read settings"));
1515                return NSCAPI::hasFailed;
1516        }
1517        return NSCAPI::isSuccess;
1518}
1519NSCAPI::errorReturn NSAPIRehash(int flag) {
1520        return NSCAPI::hasFailed;
1521}
1522NSCAPI::errorReturn NSAPIDescribeCommand(const TCHAR* command, TCHAR* buffer, unsigned int bufLen) {
1523        return NSCHelper::wrapReturnString(buffer, bufLen, mainClient.describeCommand(command), NSCAPI::isSuccess);
1524}
1525NSCAPI::errorReturn NSAPIGetAllCommandNames(arrayBuffer::arrayBuffer* aBuffer, unsigned int *bufLen) {
1526        unsigned int len = 0;
1527        *aBuffer = arrayBuffer::list2arrayBuffer(mainClient.getAllCommandNames(), len);
1528        *bufLen = len;
1529        return NSCAPI::isSuccess;
1530}
1531NSCAPI::errorReturn NSAPIReleaseAllCommandNamessBuffer(TCHAR*** aBuffer, unsigned int * bufLen) {
1532        arrayBuffer::destroyArrayBuffer(*aBuffer, *bufLen);
1533        *bufLen = 0;
1534        *aBuffer = NULL;
1535        return NSCAPI::isSuccess;
1536}
1537NSCAPI::errorReturn NSAPIRegisterCommand(const TCHAR* cmd,const TCHAR* desc) {
1538        mainClient.registerCommand(cmd, desc);
1539        return NSCAPI::isSuccess;
1540}
1541
1542
1543LPVOID NSAPILoader(TCHAR*buffer) {
1544        if (_wcsicmp(buffer, _T("NSAPIGetApplicationName")) == 0)
1545                return &NSAPIGetApplicationName;
1546        if (_wcsicmp(buffer, _T("NSAPIGetApplicationVersionStr")) == 0)
1547                return &NSAPIGetApplicationVersionStr;
1548        if (_wcsicmp(buffer, _T("NSAPIGetSettingsString")) == 0)
1549                return &NSAPIGetSettingsString;
1550        if (_wcsicmp(buffer, _T("NSAPIGetSettingsSection")) == 0)
1551                return &NSAPIGetSettingsSection;
1552        if (_wcsicmp(buffer, _T("NSAPIReleaseSettingsSectionBuffer")) == 0)
1553                return &NSAPIReleaseSettingsSectionBuffer;
1554        if (_wcsicmp(buffer, _T("NSAPIGetSettingsInt")) == 0)
1555                return &NSAPIGetSettingsInt;
1556        if (_wcsicmp(buffer, _T("NSAPIMessage")) == 0)
1557                return &NSAPIMessage;
1558        if (_wcsicmp(buffer, _T("NSAPIStopServer")) == 0)
1559                return &NSAPIStopServer;
1560        if (_wcsicmp(buffer, _T("NSAPIInject")) == 0)
1561                return &NSAPIInject;
1562        if (_wcsicmp(buffer, _T("NSAPIGetBasePath")) == 0)
1563                return &NSAPIGetBasePath;
1564        if (_wcsicmp(buffer, _T("NSAPICheckLogMessages")) == 0)
1565                return &NSAPICheckLogMessages;
1566        if (_wcsicmp(buffer, _T("NSAPIEncrypt")) == 0)
1567                return &NSAPIEncrypt;
1568        if (_wcsicmp(buffer, _T("NSAPIDecrypt")) == 0)
1569                return &NSAPIDecrypt;
1570        if (_wcsicmp(buffer, _T("NSAPISetSettingsString")) == 0)
1571                return &NSAPISetSettingsString;
1572        if (_wcsicmp(buffer, _T("NSAPISetSettingsInt")) == 0)
1573                return &NSAPISetSettingsInt;
1574        if (_wcsicmp(buffer, _T("NSAPIWriteSettings")) == 0)
1575                return &NSAPIWriteSettings;
1576        if (_wcsicmp(buffer, _T("NSAPIReadSettings")) == 0)
1577                return &NSAPIReadSettings;
1578        if (_wcsicmp(buffer, _T("NSAPIRehash")) == 0)
1579                return &NSAPIRehash;
1580        if (_wcsicmp(buffer, _T("NSAPIDescribeCommand")) == 0)
1581                return &NSAPIDescribeCommand;
1582        if (_wcsicmp(buffer, _T("NSAPIGetAllCommandNames")) == 0)
1583                return &NSAPIGetAllCommandNames;
1584        if (_wcsicmp(buffer, _T("NSAPIReleaseAllCommandNamessBuffer")) == 0)
1585                return &NSAPIReleaseAllCommandNamessBuffer;
1586        if (_wcsicmp(buffer, _T("NSAPIRegisterCommand")) == 0)
1587                return &NSAPIRegisterCommand;
1588
1589        return NULL;
1590}
Note: See TracBrowser for help on using the repository browser.