Changeset 5d8e0b5 in nscp


Ignore:
Timestamp:
04/19/05 00:50:16 (8 years ago)
Author:
Michael Medin <michael@…>
Children:
ae192e3
Parents:
ce6eabf
Message:

MAJOR CHANGES
2004-04-19 MickeM

+ Added SSL support
+ Added alot of new options
+ Added documentation

  • Renamed and restructured NSCLientCompat to CheckSystem
  • *ALOT* of fixes all over : We are now starting to get to something that is "stable" : This means that soon you might actually be able to use this.
Location:
trunk
Files:
15 added
33 edited

Legend:

Unmodified
Added
Removed
  • trunk/NSCPlugin.cpp

    rc515660 r5d8e0b5  
    1010NSCPlugin::NSCPlugin(const std::string file) 
    1111  : file_(file) 
     12  ,hModule_(NULL) 
    1213  ,fLoadModule(NULL) 
    1314  ,fGetName(NULL) 
     
    1819  ,bLoaded_(false) 
    1920{ 
     21} 
     22 
     23NSCPlugin::NSCPlugin(NSCPlugin &other) 
     24  :hModule_(NULL) 
     25  ,fLoadModule(NULL) 
     26  ,fGetName(NULL) 
     27  ,fHasCommandHandler(NULL) 
     28  ,fUnLoadModule(NULL) 
     29  ,fHasMessageHandler(NULL) 
     30  ,fHandleMessage(NULL) 
     31  ,bLoaded_(false) 
     32{ 
     33  if (other.bLoaded_) { 
     34    file_ = other.file_; 
     35    hModule_ = LoadLibrary(file_.c_str()); 
     36    if (!hModule_) 
     37      throw NSPluginException(file_, "Could not load library: ", GetLastError()); 
     38    loadRemoteProcs_(); 
     39    if (!fLoadModule) 
     40      throw NSPluginException(file_, "Critical error (fLoadModule)"); 
     41    bLoaded_ = other.bLoaded_; 
     42  } 
    2043} 
    2144 
  • trunk/NSCPlugin.h

    rc515660 r5d8e0b5  
    8888  std::string file_;    // Name of the DLL file 
    8989 
    90   typedef int (*lpModuleHelperInit)(NSCModuleHelper::lpNSAPILoader f); 
    91   typedef int (*lpLoadModule)(); 
     90  typedef INT (*lpModuleHelperInit)(NSCModuleHelper::lpNSAPILoader f); 
     91  typedef INT (*lpLoadModule)(); 
    9292  typedef INT (*lpGetName)(char*,unsigned int); 
    9393  typedef INT (*lpHasCommandHandler)(); 
     
    9595  typedef NSCAPI::nagiosReturn (*lpHandleCommand)(const char*,const unsigned int, char**,char*,unsigned int,char *,unsigned int); 
    9696  typedef INT (*lpHandleMessage)(int,const char*,const int,const char*); 
    97   typedef int (*lpUnLoadModule)(); 
     97  typedef INT (*lpUnLoadModule)(); 
    9898 
    9999  lpModuleHelperInit fModuleHelperInit; 
     
    108108public: 
    109109  NSCPlugin(const std::string file); 
     110  NSCPlugin(NSCPlugin &other); 
    110111  virtual ~NSCPlugin(void); 
    111112 
  • trunk/NSClient++.cpp

    rebcb766 r5d8e0b5  
    8282      std::cin >> s; 
    8383      while (s != "exit") { 
    84 //        mainClient.inject(s); 
     84        strEx::token t = strEx::getToken(s, ','); 
     85        std::string msg, perf; 
     86        NSCAPI::nagiosReturn ret = mainClient.inject(t.first, t.second, ',', msg, perf); 
     87        if (perf.empty()) 
     88          std::cout << NSCHelper::translateReturn(ret) << ":" << msg << std::endl; 
     89        else 
     90          std::cout << NSCHelper::translateReturn(ret) << ":" << msg << "|" << perf << std::endl; 
    8591        std::cin >> s; 
    8692      } 
     
    109115 
    110116  try { 
    111     simpleSocket::Socket::WSAStartup(); 
     117    simpleSocket::WSAStartup(); 
    112118  } catch (simpleSocket::SocketException e) { 
    113119    LOG_ERROR_STD("Uncaught exception: " + e.getMessage()); 
     
    136142  } 
    137143  try { 
    138     simpleSocket::Socket::WSACleanup(); 
     144    simpleSocket::WSACleanup(); 
    139145  } catch (simpleSocket::SocketException e) { 
    140146    LOG_ERROR_STD("Uncaught exception: " + e.getMessage()); 
     
    187193    return; 
    188194  } 
    189   pluginList::reverse_iterator it; 
    190   for (it = plugins_.rbegin(); it != plugins_.rend(); ++it) { 
    191     LOG_DEBUG_STD("Unloading plugin: " + (*it)->getName() + "..."); 
    192     (*it)->unload(); 
    193   } 
     195  commandHandlers_.clear(); 
    194196  { 
    195197    MutexLock lock2(messageMutex,20000); 
     
    200202    } 
    201203  } 
    202   commandHandlers_.clear(); 
    203   for (it = plugins_.rbegin(); it != plugins_.rend(); ++it) { 
    204     delete (*it); 
     204  for (pluginList::size_type i=plugins_.size();i>0;i--) { 
     205    NSCPlugin *p = plugins_[i-1]; 
     206    LOG_DEBUG_STD("Unloading plugin: " + p->getName() + "..."); 
     207    p->unload(); 
     208  } 
     209 
     210  for (unsigned int i=plugins_.size();i>0;i--) { 
     211    NSCPlugin *p = plugins_[i-1]; 
     212    plugins_[i-1] = NULL; 
     213    delete p; 
    205214  } 
    206215  plugins_.clear(); 
     
    226235  LOG_DEBUG_STD("Loading: " + plugin->getName()); 
    227236  // @todo Catch here and unload if we fail perhaps ? 
    228   plugins_.push_back(plugin); 
     237  plugins_.insert(plugins_.end(), plugin); 
    229238  if (plugin->hasCommandHandler()) 
    230     commandHandlers_.push_back(plugin); 
     239    commandHandlers_.insert(commandHandlers_.end(), plugin); 
    231240  if (plugin->hasMessageHandler()) 
    232     messageHandlers_.push_back(plugin); 
    233 } 
     241    messageHandlers_.insert(messageHandlers_.end(), plugin); 
     242} 
     243 
     244NSCAPI::nagiosReturn NSClientT::inject(std::string command, std::string arguments, char splitter, std::string &msg, std::string & perf) { 
     245  unsigned int aLen = 0; 
     246  char ** aBuf = arrayBuffer::split2arrayBuffer(arguments, splitter, aLen); 
     247  char * mBuf = new char[1024]; 
     248  char * pBuf = new char[1024]; 
     249  NSCAPI::nagiosReturn ret = injectRAW(command.c_str(), aLen, aBuf, mBuf, 1023, pBuf, 1023); 
     250  arrayBuffer::destroyArrayBuffer(aBuf, aLen); 
     251  if ( (ret == NSCAPI::returnInvalidBufferLen) || (ret == NSCAPI::returnIgnored) ) 
     252    return ret; 
     253  msg = mBuf; 
     254  perf = pBuf; 
     255  delete [] mBuf; 
     256  delete [] pBuf; 
     257  return ret; 
     258} 
     259 
    234260/** 
    235261 * Inject a command into the plug-in stack. 
     
    240266NSCAPI::nagiosReturn NSClientT::injectRAW(const char* command, const unsigned int argLen, char **argument, char *returnMessageBuffer, unsigned int returnMessageBufferLen, char *returnPerfBuffer, unsigned int returnPerfBufferLen) { 
    241267  MutexLock lock(pluginMutex); 
    242  
    243   pluginList::const_iterator plit; 
    244   for (plit = commandHandlers_.begin(); plit != commandHandlers_.end(); ++plit) { 
     268  if (!lock.hasMutex()) { 
     269    LOG_ERROR("Failed to get mutex, command ignored..."); 
     270  } 
     271 
     272  for (pluginList::size_type i = 0; i < commandHandlers_.size(); i++) { 
    245273    try { 
    246       NSCAPI::nagiosReturn c = (*plit)->handleCommand(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen); 
     274      NSCAPI::nagiosReturn c = commandHandlers_[i]->handleCommand(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen); 
    247275      switch (c) { 
    248276        case NSCAPI::returnInvalidBufferLen: 
     
    287315  } 
    288316  if (g_bConsoleLog) { 
    289     std::cout << NSCHelper::translateMessageType(msgType) << " " << file << "(" << line << ") " << message << std::endl; 
     317    std::string k = "?"; 
     318    switch (msgType) { 
     319      case NSCAPI::critical: 
     320        k ="c"; 
     321        break; 
     322      case NSCAPI::warning: 
     323        k ="w"; 
     324        break; 
     325      case NSCAPI::error: 
     326        k ="e"; 
     327        break; 
     328      case NSCAPI::log: 
     329        k ="l"; 
     330        break; 
     331      case NSCAPI::debug: 
     332        k ="d"; 
     333        break; 
     334    } 
     335    std::cout << k << " " << file << "(" << line << ") " << message << std::endl; 
    290336  } 
    291337  if (msgType == NSCAPI::debug) { 
     
    301347      return; 
    302348  } 
    303   pluginList::const_iterator plit; 
    304   for (plit = messageHandlers_.begin(); plit != messageHandlers_.end(); ++plit) { 
     349  for (pluginList::size_type i = 0; i< messageHandlers_.size(); i++) { 
    305350    try { 
    306       (*plit)->handleMessage(msgType, file, line, message.c_str()); 
     351      messageHandlers_[i]->handleMessage(msgType, file, line, message.c_str()); 
    307352    } catch(const NSPluginException& e) { 
    308353      // Here we are pretty much fucked! (as logging this might cause a loop :) 
  • trunk/NSClient++.h

    rebcb766 r5d8e0b5  
    3737private: 
    3838  typedef NSCPlugin* plugin_type; 
    39   typedef std::list<plugin_type> pluginList; 
     39  typedef std::vector<plugin_type> pluginList; 
    4040  pluginList plugins_; 
    4141  pluginList commandHandlers_; 
     
    5959  std::string getBasePath(void); 
    6060  NSCAPI::nagiosReturn injectRAW(const char* command, const unsigned int argLen, char **argument, char *returnMessageBuffer, unsigned int returnMessageBufferLen, char *returnPerfBuffer, unsigned int returnPerfBufferLen); 
     61  NSCAPI::nagiosReturn NSClientT::inject(std::string command, std::string arguments, char splitter, std::string &msg, std::string & perf); 
    6162//  std::string inject(const std::string buffer); 
    6263  std::string execute(std::string password, std::string cmd, std::list<std::string> args); 
     
    105106#define LOG_MESSAGE(msg) \ 
    106107  NSAPIMessage(NSCAPI::log, __FILE__, __LINE__, msg) 
     108 
    107109#define LOG_DEBUG_STD(msg) LOG_DEBUG(((std::string)msg).c_str()) 
    108110#define LOG_DEBUG(msg) \ 
    109111  NSAPIMessage(NSCAPI::debug, __FILE__, __LINE__, msg) 
     112/* 
     113#define LOG_DEBUG_STD(msg) 
     114#define LOG_DEBUG(msg) 
     115*/ 
  • trunk/NSClient++.sln

    rebcb766 r5d8e0b5  
    55    {BBFF8362-C626-4838-B0A2-F695D638AD24} = {BBFF8362-C626-4838-B0A2-F695D638AD24} 
    66    {08D6246D-1B4A-47A3-965D-296DCC54A4E8} = {08D6246D-1B4A-47A3-965D-296DCC54A4E8} 
    7     {79F1F571-78A6-4B20-8BD5-0F65CD60012C} = {79F1F571-78A6-4B20-8BD5-0F65CD60012C} 
    87    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45} = {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45} 
    98    {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F} = {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F} 
     
    1211EndProject 
    1312Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SysTray", "modules\SysTray\SysTray.vcproj", "{BBFF8362-C626-4838-B0A2-F695D638AD24}" 
    14   ProjectSection(ProjectDependencies) = postProject 
    15   EndProjectSection 
    16 EndProject 
    17 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NSClientCompat", "modules\NSClientCompat\NSClientCompat.vcproj", "{79F1F571-78A6-4B20-8BD5-0F65CD60012C}" 
    1813  ProjectSection(ProjectDependencies) = postProject 
    1914  EndProjectSection 
     
    3631EndProject 
    3732Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NSClientListener", "modules\NSClientListener\NSClientListener.vcproj", "{08D6246D-1B4A-47A3-965D-296DCC54A4E8}" 
     33  ProjectSection(ProjectDependencies) = postProject 
     34  EndProjectSection 
     35EndProject 
     36Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CheckSystem", "modules\CheckSystem\CheckSystem.vcproj", "{2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}" 
    3837  ProjectSection(ProjectDependencies) = postProject 
    3938  EndProjectSection 
     
    6160    {BBFF8362-C626-4838-B0A2-F695D638AD24}.Release.ActiveCfg = Release|Win32 
    6261    {BBFF8362-C626-4838-B0A2-F695D638AD24}.Release.Build.0 = Release|Win32 
    63     {79F1F571-78A6-4B20-8BD5-0F65CD60012C}.Debug.ActiveCfg = Debug|Win32 
    64     {79F1F571-78A6-4B20-8BD5-0F65CD60012C}.Debug.Build.0 = Debug|Win32 
    65     {79F1F571-78A6-4B20-8BD5-0F65CD60012C}.Distribution.ActiveCfg = Distribution|Win32 
    66     {79F1F571-78A6-4B20-8BD5-0F65CD60012C}.Distribution.Build.0 = Distribution|Win32 
    67     {79F1F571-78A6-4B20-8BD5-0F65CD60012C}.Release.ActiveCfg = Release|Win32 
    68     {79F1F571-78A6-4B20-8BD5-0F65CD60012C}.Release.Build.0 = Release|Win32 
    6962    {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F}.Debug.ActiveCfg = Debug|Win32 
    7063    {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F}.Debug.Build.0 = Debug|Win32 
     
    7972    {BA246C01-063A-4548-8957-32D5CC76171B}.Release.ActiveCfg = Release|Win32 
    8073    {BA246C01-063A-4548-8957-32D5CC76171B}.Release.Build.0 = Release|Win32 
    81     {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.ActiveCfg = Debug Dynamic Linkage|Win32 
    82     {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.Build.0 = Debug Dynamic Linkage|Win32 
     74    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.ActiveCfg = Debug|Win32 
     75    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.Build.0 = Debug|Win32 
    8376    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Distribution.ActiveCfg = Distribution|Win32 
    8477    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Distribution.Build.0 = Distribution|Win32 
    85     {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.ActiveCfg = Dynamic Linkage|Win32 
    86     {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.Build.0 = Dynamic Linkage|Win32 
     78    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.ActiveCfg = Release|Win32 
     79    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.Build.0 = Release|Win32 
    8780    {2FF60AF6-09AA-49AB-B414-2E8FD01655C6}.Debug.ActiveCfg = Debug|Win32 
    8881    {2FF60AF6-09AA-49AB-B414-2E8FD01655C6}.Debug.Build.0 = Debug|Win32 
     
    9790    {08D6246D-1B4A-47A3-965D-296DCC54A4E8}.Release.ActiveCfg = Release|Win32 
    9891    {08D6246D-1B4A-47A3-965D-296DCC54A4E8}.Release.Build.0 = Release|Win32 
     92    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Debug.ActiveCfg = Debug|Win32 
     93    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Debug.Build.0 = Debug|Win32 
     94    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Distribution.ActiveCfg = Distribution|Win32 
     95    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Distribution.Build.0 = Distribution|Win32 
     96    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Release.ActiveCfg = Release|Win32 
     97    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Release.Build.0 = Release|Win32 
    9998  EndGlobalSection 
    10099  GlobalSection(ExtensibilityGlobals) = postSolution 
  • trunk/NSClient++.vcproj

    rebcb766 r5d8e0b5  
    4242        Name="VCCustomBuildTool" 
    4343        CommandLine="echo Copying dependency DLLs 
    44 cmd /c &quot;copy $(InputDir)\dist_dll\*.* $(InputDir)\$(OutDir)\&quot;" 
     44cmd /c &quot;copy $(InputDir)\dist_dll\*.* $(InputDir)\$(OutDir)\&quot; 
     45" 
    4546        Outputs="$(InputDir)\$(OutDir)\msvcp71.dll"/> 
    4647      <Tool 
     
    173174      <Tool 
    174175        Name="VCCustomBuildTool" 
    175         CommandLine="echo Copying dependency DLLs 
     176        CommandLine="echo Copying documentation 
     177cmd /c &quot;copy $(InputDir)\*.html $(InputDir)\Dist\&quot; 
     178echo Copying dependency DLLs 
    176179cmd /c &quot;copy $(InputDir)\dist_dll\*.dll $(InputDir)\Dist\&quot; 
    177180echo Removing old archive 
    178181cmd /c &quot;del $(InputDir)\Dist\$(InputName).zip&quot; 
    179182echo Making archive 
    180 7z.exe a -r -tzip -bd $(InputDir)\Dist\$(InputName).zip $(InputDir)\Dist\*" 
     1837z.exe a -r -tzip -bd $(InputDir)\Dist\$(InputName).zip $(InputDir)\Dist\* 
     184" 
    181185        Outputs="$(InputDir)\Dist\$(ProjectName).zip"/> 
    182186      <Tool 
     
    245249      </File> 
    246250      <File 
     251        RelativePath=".\include\Socket.cpp"> 
     252      </File> 
     253      <File 
    247254        RelativePath="StdAfx.cpp"> 
    248255        <FileConfiguration 
     
    327334            Name="VCCustomBuildTool" 
    328335            CommandLine="echo Copying $(InputFileName)... 
    329 cmd /c &quot;copy $(InputDir)\$(InputName) $(InputDir)\Dist\&quot;" 
     336cmd /c &quot;copy $(InputDir)\$(InputName) $(InputDir)\Dist\&quot; 
     337" 
    330338            Outputs="$(InputDir)\Dist\$(InputFileName)"/> 
    331339        </FileConfiguration> 
     
    389397            Name="VCCustomBuildTool" 
    390398            CommandLine="echo Copying $(InputFileName)... 
    391 cmd /c &quot;copy $(InputDir)\$(InputFileName) $(InputDir)\Dist\&quot;" 
     399cmd /c &quot;copy $(InputDir)\$(InputFileName) $(InputDir)\Dist\&quot; 
     400" 
    392401            AdditionalDependencies="" 
    393402            Outputs="$(InputDir)\Dist\$(InputFileName)"/> 
     
    415424            Name="VCCustomBuildTool" 
    416425            CommandLine="echo Copying $(InputFileName)... 
    417 cmd /c &quot;copy $(InputDir)\$(InputFileName) $(InputDir)\Dist\&quot;" 
     426cmd /c &quot;copy $(InputDir)\$(InputFileName) $(InputDir)\Dist\&quot; 
     427" 
    418428            Outputs="$(InputDir)\Dist\$(InputFileName)"/> 
    419429        </FileConfiguration> 
  • trunk/StdAfx.h

    rebcb766 r5d8e0b5  
    2121#include <list> 
    2222#include <sstream> 
     23#include <vector> 
    2324 
    2425#include "config.h" 
  • trunk/changelog

    rebcb766 r5d8e0b5  
     12004-04-19 MickeM 
     2 + Added SSL support 
     3 + Added alot of new options 
     4 + Added documentation 
     5 * Renamed and restructured NSCLientCompat to CheckSystem 
     6 * *ALOT* of fixes all over 
     7 : We are now starting to get to something that is "stable" 
     8 : This means that soon you might actually be able to use this. 
     9  
    1102005-03-28 MickeM 
    211 * Changed the Thread class a bit (mutex -> signal, and CreatThread does not return the instance) 
  • trunk/dist_dll/placeholder.txt

    rebcb766 r5d8e0b5  
    22I have the following in my directory: 
    33 
    4 boost_regex-vc71-mt-p-1_32.dll  - Only needed if you want to compile the CheckEventLog module 
     4boost_regex-vc71-mt-p-1_32.dll  - Only needed if you want to use the CheckEventLog module 
    55msvcp71.dll     - Regular MS VC++ 7.1 runtimes 
    66msvcr71.dll     - Regular MS VC++ 7.1 runtimes 
    77stlport_vc7146.dll    - STL port runtimes 
     8libeay32.dll      - SSL 
     9ssleay32.dll      - SSL 
  • trunk/include/NSCHelper.h

    rf705d34 r5d8e0b5  
    1919  std::string translateReturn(NSCAPI::nagiosReturn returnCode); 
    2020  NSCAPI::nagiosReturn maxState(NSCAPI::nagiosReturn a, NSCAPI::nagiosReturn b); 
     21 
     22  inline bool isNagiosReturnCode(NSCAPI::nagiosReturn code) { 
     23    if ( (code == NSCAPI::returnOK) || (code == NSCAPI::returnWARN) || (code == NSCAPI::returnCRIT) || (code == NSCAPI::returnUNKNOWN) ) 
     24      return true; 
     25    return false; 
     26  } 
    2127 
    2228#ifdef DEBUG 
     
    159165  NSCModuleHelper::Message(NSCAPI::debug, __FILE__, __LINE__, msg) 
    160166 
     167/* 
     168#define NSC_DEBUG_MSG_STD(msg) 
     169#define NSC_DEBUG_MSG(msg) 
     170*/ 
    161171////////////////////////////////////////////////////////////////////////// 
    162172// Message wrappers below this point 
  • trunk/include/PDHCollectors.h

    re0705d4 r5d8e0b5  
    2626    unsigned int current; 
    2727  public: 
     28    RoundINTPDHBufferListener() : buffer(NULL), length(0), current(0) {} 
    2829    RoundINTPDHBufferListener(int length_) : length(length_), current(0) { 
    2930      buffer = new int[length]; 
     
    3435      delete [] buffer; 
    3536    } 
     37     
     38    /** 
     39     * Resize the buffer to a new length 
     40     * 
     41     * @todo Make this copy the old buffer if there is one. 
     42     * 
     43     * @param newLength The new length 
     44     */ 
     45    void resize(int newLength) { 
     46      delete [] buffer; 
     47 
     48      current = 0; 
     49      length = newLength; 
     50 
     51      buffer = new int[length]; 
     52      for (unsigned int i=0; i<length;i++) 
     53        buffer[i] = 0; 
     54         
     55    } 
    3656    virtual void collect(const PDH::PDHCounter &counter) { 
    3757      pushValue(static_cast<int>(counter.getInt64Value())); 
     
    4060    void detach(const PDH::PDHCounter &counter){} 
    4161    void pushValue(int value) { 
     62      if (buffer == NULL) 
     63        return; 
     64      if (current >= length) 
     65        return; 
    4266      buffer[current++] = value; 
    4367      if (current >= length) 
     
    6185      return static_cast<int>(ret/backItems); 
    6286    } 
     87    inline unsigned int getLength() const { 
     88      return length; 
     89    } 
    6390  }; 
    6491 
  • trunk/include/Socket.cpp

    rebcb766 r5d8e0b5  
    11#include "stdafx.h" 
    22#include <Socket.h> 
    3  
    4  
    5 simpleSocket::Listener::~Listener() { 
    6   // @todo: Force cleanup here 
    7 } 
     3#include <NSCHelper.h> 
    84 
    95 
     
    1410* @todo This needs to be reworked, possibly completely redone ? 
    1511*/ 
    16 DWORD simpleSocket::Listener::ListenerThread::threadProc(LPVOID lpParameter) 
    17 { 
    18   unsigned long NoBlock = 1; 
    19   Listener *core = reinterpret_cast<Listener*>(lpParameter); 
    2012 
    21   hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
    22   if (!hStopEvent) { 
    23     NSC_LOG_ERROR_STD("Create StopEvent failed: " + strEx::itos(GetLastError())); 
    24     return 0; 
    25   } 
    2613 
    27   try { 
    28     core->socket(AF_INET,SOCK_STREAM,0); 
    29     core->setAddr(AF_INET, INADDR_ANY, htons(core->port_)); 
    30     core->bind(); 
    31     core->listen(10); 
    32     core->ioctlsocket(FIONBIO, &NoBlock); 
    33     while (!(WaitForSingleObject(hStopEvent, 100) == WAIT_OBJECT_0)) { 
    34       Socket client; 
    35       if (core->accept(client)) 
    36         core->onAccept(client); 
    37     } 
    38   } catch (SocketException e) { 
    39     NSC_LOG_ERROR_STD(e.getMessage()); 
    40   } 
    41   HANDLE hTmp = hStopEvent; 
    42   hStopEvent = NULL; 
    43   BOOL b = CloseHandle(hTmp); 
    44   assert(b); 
    45   return 0; 
     14void simpleSocket::Socket::printError(std::string error) { 
     15  NSC_LOG_ERROR_STD(error); 
    4616} 
    4717 
    48 /** 
    49 * Exit thread callback proc.  
    50 * This is called by the thread manager when the thread should initiate a shutdown procedure. 
    51 * The thread manager is responsible for waiting for the actual termination of the thread. 
    52 */ 
    53 void simpleSocket::Listener::ListenerThread::exitThread(void) { 
    54   assert(hStopEvent); 
    55   if (!SetEvent(hStopEvent)) { 
    56     NSC_LOG_ERROR_STD("SetStopEvent failed"); 
    57   } 
    58 } 
    5918 
    6019void simpleSocket::Socket::readAll(DataBuffer &buffer, unsigned int tmpBufferLength /* = 1024*/) { 
     
    6322  char *tmpBuffer = new char[tmpBufferLength+1]; 
    6423  int n=recv(socket_,tmpBuffer,tmpBufferLength,0); 
    65   while ((n!=SOCKET_ERROR )||(n!=0)) { 
     24  while ((n!=SOCKET_ERROR )&&(n!=0)) { 
    6625    if (n == tmpBufferLength) { 
    6726      // We filled the buffer (There is more to get) 
     
    7837} 
    7938 
    80 void simpleSocket::Listener::StartListen(int port) { 
    81   port_ = port; 
    82   threadManager_.createThread(this); 
     39 
     40WSADATA simpleSocket::WSAStartup(WORD wVersionRequested /* = 0x202 */) { 
     41  WSADATA wsaData; 
     42  int wsaret=::WSAStartup(wVersionRequested,&wsaData); 
     43  if(wsaret != 0) 
     44    throw SocketException("WSAStartup failed: " + strEx::itos(wsaret)); 
     45  return wsaData; 
    8346} 
    84 void simpleSocket::Listener::close() { 
    85   if (threadManager_.hasActiveThread()) 
    86     if (!threadManager_.exitThread()) 
    87       throw new SocketException("Could not terminate thread."); 
    88   Socket::close(); 
     47void simpleSocket::WSACleanup() { 
     48  if (::WSACleanup() != 0) 
     49    throw SocketException("WSACleanup failed: ", ::WSAGetLastError()); 
    8950} 
    90  
    91  
    92  
    93  
  • trunk/include/Socket.h

    rebcb766 r5d8e0b5  
    4949      return length_; 
    5050    } 
     51    void copyFrom(const char* buffer, const unsigned int length) { 
     52      delete [] buffer_; 
     53      buffer_ = new char[length+1]; 
     54      memcpy(buffer_, buffer, length); 
     55    } 
    5156  }; 
    5257 
    5358  class Socket { 
    54   private: 
     59  protected: 
    5560    SOCKET socket_; 
    5661    sockaddr_in from_; 
    5762 
    5863  public: 
    59     Socket() : socket_(NULL) { 
    60     } 
    61     Socket(SOCKET socket) : socket_(socket) { 
    62     } 
     64    Socket() : socket_(NULL) {} 
     65    Socket(SOCKET socket) : socket_(socket) {} 
    6366    Socket(Socket &other) { 
    6467      socket_ = other.socket_; 
     
    7174      socket_ = NULL; 
    7275    } 
    73     SOCKET getSocket() const { 
    74       return socket_; 
    75     } 
     76    virtual SOCKET detach() { 
     77      SOCKET s = socket_; 
     78      socket_ = NULL; 
     79      return s; 
     80    } 
     81    virtual void attach(SOCKET s) { 
     82      assert(socket_ == NULL); 
     83      socket_ = s; 
     84    } 
     85    virtual void shutdown(int how = SD_BOTH) { 
     86      if (socket_) 
     87        ::shutdown(socket_, how); 
     88    } 
     89 
    7690    virtual void close() { 
    7791      if (socket_) 
     
    7993      socket_ = NULL; 
    8094    } 
    81     void readAll(DataBuffer &buffer, unsigned int tmpBufferLength = 1024); 
    82  
    83     void socket(int af, int type, int protocol ) { 
     95    virtual void setNonBlock() { 
     96      unsigned long NoBlock = 1; 
     97      this->ioctlsocket(FIONBIO, &NoBlock); 
     98    } 
     99    virtual void readAll(DataBuffer &buffer, unsigned int tmpBufferLength = 1024); 
     100 
     101    virtual void socket(int af, int type, int protocol ) { 
    84102      socket_ = ::socket(af, type, protocol); 
    85103      assert(socket_ != INVALID_SOCKET); 
    86104    } 
    87     void bind() { 
     105    virtual void bind() { 
     106      assert(socket_); 
    88107      int fromlen=sizeof(from_); 
    89108      if (::bind(socket_, (sockaddr*)&from_, fromlen) == SOCKET_ERROR) 
    90109        throw SocketException("bind failed: ", ::WSAGetLastError()); 
    91110    } 
    92     void listen(int backlog = 0) { 
     111    virtual void listen(int backlog = 0) { 
     112      assert(socket_); 
    93113      if (::listen(socket_, backlog) == SOCKET_ERROR) 
    94114        throw SocketException("listen failed: ", ::WSAGetLastError()); 
    95115    } 
    96     bool accept(Socket &client) { 
     116    virtual bool accept(Socket &client) { 
    97117      int fromlen=sizeof(client.from_); 
    98       client.socket_ = ::accept(socket_, (sockaddr*)&client.from_, &fromlen); 
    99       if(client.socket_ == INVALID_SOCKET) { 
     118      SOCKET s = ::accept(socket_, (sockaddr*)&client.from_, &fromlen); 
     119      if(s == INVALID_SOCKET) { 
    100120        int err = ::WSAGetLastError(); 
    101121        if (err == WSAEWOULDBLOCK) 
     
    103123        throw SocketException("accept failed: ", ::WSAGetLastError()); 
    104124      } 
     125      client.attach(s); 
    105126      return true; 
    106127    } 
    107     void setAddr(short family, u_long addr, u_short port) { 
     128    virtual void setAddr(short family, u_long addr, u_short port) { 
    108129      from_.sin_family=family; 
    109130      from_.sin_addr.s_addr=addr; 
    110131      from_.sin_port=port; 
    111132    } 
    112     int send(const char * buf, unsigned int len, int flags ) { 
     133    virtual int send(const char * buf, unsigned int len, int flags = 0) { 
     134      assert(socket_); 
    113135      return ::send(socket_, buf, len, flags); 
    114136    } 
    115     void ioctlsocket(long cmd, u_long *argp) { 
     137    int inline send(DataBuffer &buffer, int flags = 0) { 
     138      return send(buffer.getBuffer(), buffer.getLength(), flags); 
     139    } 
     140    virtual void ioctlsocket(long cmd, u_long *argp) { 
     141      assert(socket_); 
    116142      if (::ioctlsocket(socket_, cmd, argp) == SOCKET_ERROR) 
    117143        throw SocketException("ioctlsocket failed: ", ::WSAGetLastError()); 
    118144    } 
    119     std::string getAddrString() { 
     145    virtual std::string getAddrString() { 
    120146      return inet_ntoa(from_.sin_addr); 
    121147    } 
    122  
    123     static WSADATA WSAStartup(WORD wVersionRequested = 0x202) { 
    124       WSADATA wsaData; 
    125       int wsaret=::WSAStartup(wVersionRequested,&wsaData); 
    126       if(wsaret != 0) 
    127         throw SocketException("WSAStartup failed: " + strEx::itos(wsaret)); 
    128       return wsaData; 
    129     } 
    130     static void WSACleanup() { 
    131       if (::WSACleanup() != 0) 
    132         throw SocketException("WSACleanup failed: ", ::WSAGetLastError()); 
    133     } 
    134  
    135  
    136  
     148    virtual void printError(std::string error); 
     149  }; 
     150 
     151  class ListenerHandler { 
     152  public: 
     153    virtual void onAccept(Socket &client) = 0; 
     154    virtual void onClose() = 0; 
    137155  }; 
    138156 
     
    162180   * 
    163181   */ 
    164   class Listener : public Socket { 
     182  template <class TListenerType = simpleSocket::Socket, class TSocketType = TListenerType> 
     183  class Listener : public TListenerType { 
     184  public: 
     185    typedef TListenerType tListener; 
     186    typedef TSocketType tSocket; 
     187  private: 
     188    typedef TListenerType tBase; 
     189    class ListenerThread; 
     190    typedef Thread<ListenerThread> listenThreadManager; 
     191 
     192    u_short port_; 
     193    listenThreadManager threadManager_; 
     194 
    165195  public: 
    166196    class ListenerThread { 
    167197    private: 
    168       HANDLE hStopEvent; 
     198      typedef TListenerType tParentBase; 
     199      typedef TSocketType tSocket; 
     200 
     201      HANDLE hStopEvent_; 
    169202    public: 
    170       ListenerThread() : hStopEvent(NULL) { 
     203      ListenerThread() : hStopEvent_(NULL) {} 
     204      DWORD threadProc(LPVOID lpParameter); 
     205      void exitThread(void) { 
     206        assert(hStopEvent_ != NULL); 
     207        if (!SetEvent(hStopEvent_)) 
     208          throw new SocketException("SetEvent failed."); 
    171209      } 
    172       DWORD threadProc(LPVOID lpParameter); 
    173       void exitThread(void); 
    174210    }; 
    175  
    176   private: 
    177     MutexHandler mutexHandler; 
    178     u_short port_; 
    179     typedef Thread<ListenerThread> listenThreadManager; 
    180     listenThreadManager threadManager_; 
    181  
    182   public: 
    183     Listener() {}; 
    184     virtual ~Listener(); 
    185  
    186     void StartListen(int port); 
    187     virtual void close(); 
    188  
    189   private: 
    190     virtual void onAccept(Socket client) = 0; 
    191  
    192   }; 
     211  private: 
     212    ListenerHandler *pHandler_; 
     213 
     214  public: 
     215    Listener() : pHandler_(NULL) {}; 
     216    virtual ~Listener() {}; 
     217 
     218    virtual void StartListener(int port) { 
     219      port_ = port; 
     220      threadManager_.createThread(this); 
     221    } 
     222    virtual void StopListener() { 
     223      if (threadManager_.hasActiveThread()) 
     224        if (!threadManager_.exitThread()) 
     225          throw new SocketException("Could not terminate thread."); 
     226      tBase::close(); 
     227    } 
     228    void setHandler(ListenerHandler* pHandler) { 
     229      pHandler_ = pHandler; 
     230    } 
     231    void removeHandler(ListenerHandler* pHandler) { 
     232      if (pHandler != pHandler_) 
     233        throw SocketException("Not a registered handler!"); 
     234      pHandler_ = NULL; 
     235    } 
     236 
     237 
     238  private: 
     239    void onAccept(tSocket &client) { 
     240      if (pHandler_) 
     241        pHandler_->onAccept(client); 
     242    } 
     243    void onClose() { 
     244      if (pHandler_) 
     245        pHandler_->onClose(); 
     246    } 
     247    virtual bool accept(tSocket &client) { 
     248      return tBase::accept(client); 
     249    } 
     250  }; 
     251 
     252  WSADATA WSAStartup(WORD wVersionRequested = 0x202); 
     253  void WSACleanup(); 
     254 
    193255} 
    194256 
     257template <class TListenerType, class TSocketType> 
     258DWORD simpleSocket::Listener<TListenerType, TSocketType>::ListenerThread::threadProc(LPVOID lpParameter) 
     259{ 
     260  Listener *core = reinterpret_cast<Listener*>(lpParameter); 
     261 
     262  hStopEvent_ = CreateEvent(NULL, TRUE, FALSE, NULL); 
     263  if (!hStopEvent_) { 
     264    core->printError("Create StopEvent failed: " + strEx::itos(GetLastError())); 
     265    return 0; 
     266  } 
     267 
     268  try { 
     269    core->socket(AF_INET,SOCK_STREAM,0); 
     270    core->setAddr(AF_INET, INADDR_ANY, htons(core->port_)); 
     271    core->bind(); 
     272    core->listen(10); 
     273    core->setNonBlock(); 
     274    while (!(WaitForSingleObject(hStopEvent_, 100) == WAIT_OBJECT_0)) { 
     275      try { 
     276        tSocket client; 
     277        if (core->accept(client)) 
     278          core->onAccept(client); 
     279      } catch (SocketException e) { 
     280        core->printError(e.getMessage() + ", attempting to resume..."); 
     281      } 
     282    } 
     283  } catch (SocketException e) { 
     284    core->printError(e.getMessage()); 
     285  } 
     286  core->shutdown(SD_BOTH); 
     287  core->close(); 
     288  core->onClose(); 
     289  HANDLE hTmp = hStopEvent_; 
     290  hStopEvent_ = NULL; 
     291  if (!CloseHandle(hTmp)) { 
     292    core->printError("CloseHandle StopEvent failed: " + strEx::itos(GetLastError())); 
     293  } 
     294  return 0; 
     295} 
  • trunk/include/config.h

    rce6eabf r5d8e0b5  
    1  
    2  
    31#pragma once 
    42 
     
    75 
    86// Version 
    9 #define SZVERSION "0.0.2 alfa 2005-03-27" 
     7#define SZVERSION "0.0.9 rc1 2005-04-19" 
    108 
    119// internal name of the service 
     
    2119#define RECV_BUFFER_LEN   1024 
    2220 
    23 // The default NRPE port (used by NSRPListener plugin) 
    24 #define DEFAULT_NRPE_PORT 5666 
     21#define NASTY_METACHARS         "|`&><'\"\\[]{}"        /* This may need to be modified for windows directory seperator */ 
    2522 
    26 // The default NSClient port (used by NSClientListener plugin) 
    27 #define DEFAULT_NSCLIENT_PORT 12489 
     23 
     24// Default Argumentstring (for consistency) 
     25#define SHOW_ALL "ShowAll" 
     26#define SHOW_FAIL "ShowFail" 
     27#define NSCLIENT "nsclient" 
     28 
     29// NSClient Setting headlines 
     30#define NSCLIENT_SECTION_TITLE "NSClient" 
     31#define NSCLIENT_SETTINGS_PORT "port" 
     32#define NSCLIENT_SETTINGS_PORT_DEFAULT 12489 
     33#define NSCLIENT_SETTINGS_ALLOWED "allowed_hosts" 
     34#define NSCLIENT_SETTINGS_ALLOWED_DEFAULT "" 
     35#define NSCLIENT_SETTINGS_PWD "password" 
     36#define NSCLIENT_SETTINGS_PWD_DEFAULT "" 
    2837 
    2938// NRPE Settings headlines 
     
    3140#define NRPE_HANDLER_SECTION_TITLE "NRPE Handlers" 
    3241#define NRPE_SETTINGS_TIMEOUT "command_timeout" 
     42#define NRPE_SETTINGS_TIMEOUT_DEFAULT 60 
    3343#define NRPE_SETTINGS_ALLOWED "allowed_hosts" 
     44#define NRPE_SETTINGS_ALLOWED_DEFAULT "" 
    3445#define NRPE_SETTINGS_PORT "port" 
     46#define NRPE_SETTINGS_PORT_DEFAULT 5666 
    3547#define NRPE_SETTINGS_ALLOW_ARGUMENTS "allow_arguments" 
     48#define NRPE_SETTINGS_ALLOW_ARGUMENTS_DEFAULT 0 
    3649#define NRPE_SETTINGS_ALLOW_NASTY_META "allow_nasty_meta_chars" 
     50#define NRPE_SETTINGS_ALLOW_NASTY_META_DEFAULT 0 
     51#define NRPE_SETTINGS_USE_SSL "use_ssl" 
     52#define NRPE_SETTINGS_USE_SSL_DEFAULT 1 
    3753 
     54// Check System Settings 
     55#define C_SYSTEM_SECTION_TITLE "Check System" 
     56#define C_SYSTEM_CPU_BUFFER_TIME "CPUBufferSize"  
     57#define C_SYSTEM_CPU_BUFFER_TIME_DEFAULT "1h" 
     58#define C_SYSTEM_CHECK_RESOLUTION "CheckResolution" 
     59#define C_SYSTEM_CHECK_RESOLUTION_DEFAULT 10 /* unit: second/10 */ 
     60#define C_SYSTEM_MEM_PAGE_LIMIT "CounterPageLimit" 
     61#define C_SYSTEM_MEM_PAGE_LIMIT_DEFAULT "\\\\.\\Memory\\Commit Limit" 
     62#define C_SYSTEM_MEM_PAGE "CounterPage" 
     63#define C_SYSTEM_MEM_PAGE_DEFAULT "\\\\.\\Memory\\Committed Bytes" 
     64#define C_SYSTEM_UPTIME "CounterUptime" 
     65#define C_SYSTEM_UPTIME_DEFAULT "\\\\.\\System\\System Up Time" 
     66#define C_SYSTEM_CPU "CounterCPU" 
     67#define C_SYSTEM_MEM_CPU_DEFAULT "\\\\.\\Processor(_total)\\% Processor Time" 
    3868 
     69// Log to File Settings 
     70#define LOG_SECTION_TITLE "log" 
     71#define LOG_FILENAME "file"  
     72#define LOG_FILENAME_DEFAULT "nsclient.log"  
     73 
  • trunk/include/strEx.h

    rebcb766 r5d8e0b5  
    44#include <string> 
    55#include <utility> 
     6#include <list> 
     7#ifdef _DEBUG 
     8#include <iostream> 
     9#endif 
    610 
    711namespace strEx { 
     
    2529    return ss.str(); 
    2630  } 
     31  inline std::string itos(unsigned long long i) { 
     32    std::stringstream ss; 
     33    ss << i; 
     34    return ss.str(); 
     35  } 
    2736  inline std::string itos(__int64 i) { 
    2837    std::stringstream ss; 
     
    3039    return ss.str(); 
    3140  } 
    32   inline std::string itos(DWORD i) { 
     41  inline std::string itos(unsigned long i) { 
    3342    std::stringstream ss; 
    3443    ss << i; 
     
    3847    return atoi(s.c_str()); 
    3948  } 
     49  inline long long stoi64(std::string s) { 
     50    return _atoi64(s.c_str()); 
     51  } 
     52  inline unsigned stoui_as_time(std::string time, unsigned int smallest_unit = 1000) { 
     53    std::string::size_type p = time.find_first_of("sSmMhHdDwW"); 
     54    unsigned int value = atoi(time.c_str()); 
     55    if (p == std::string::npos) 
     56      return value * smallest_unit; 
     57    else if ( (time[p] == 's') || (time[p] == 'S') ) 
     58      return value * 1000; 
     59    else if ( (time[p] == 'm') || (time[p] == 'M') ) 
     60      return value * 60 * 1000; 
     61    else if ( (time[p] == 'h') || (time[p] == 'H') ) 
     62      return value * 60 * 60 * 1000; 
     63    else if ( (time[p] == 'd') || (time[p] == 'D') ) 
     64      return value * 24 * 60 * 60 * 1000; 
     65    else if ( (time[p] == 'w') || (time[p] == 'W') ) 
     66      return value * 7 * 24 * 60 * 60 * 1000; 
     67    return value * smallest_unit; 
     68  } 
     69  inline unsigned long long stoi64_as_time(std::string time, unsigned int smallest_unit = 1000) { 
     70    std::string::size_type p = time.find_first_of("sSmMhHdDwW"); 
     71    unsigned long long value = _atoi64(time.c_str()); 
     72    if (p == std::string::npos) 
     73      return value * smallest_unit; 
     74    else if ( (time[p] == 's') || (time[p] == 'S') ) 
     75      return value * 1000; 
     76    else if ( (time[p] == 'm') || (time[p] == 'M') ) 
     77      return value * 60 * 1000; 
     78    else if ( (time[p] == 'h') || (time[p] == 'H') ) 
     79      return value * 60 * 60 * 1000; 
     80    else if ( (time[p] == 'd') || (time[p] == 'D') ) 
     81      return value * 24 * 60 * 60 * 1000; 
     82    else if ( (time[p] == 'w') || (time[p] == 'W') ) 
     83      return value * 7 * 24 * 60 * 60 * 1000; 
     84    return value * smallest_unit; 
     85  } 
     86  inline std::string itos_as_time(unsigned long long time) { 
     87    if (time > 7 * 24 * 60 * 60 * 1000) 
     88      return itos(static_cast<unsigned int>(time/(7 * 24 * 60 * 60 * 1000))) + "w"; 
     89    else if (time > 24 * 60 * 60 * 1000) 
     90      return itos(static_cast<unsigned int>(time/(24 * 60 * 60 * 1000))) + "d"; 
     91    else if (time > 60 * 60 * 1000) 
     92      return itos(static_cast<unsigned int>(time/(60 * 60 * 1000))) + "h"; 
     93    else if (time > 60 * 1000) 
     94      return itos(static_cast<unsigned int>(time/(60 * 1000))) + "m"; 
     95    else if (time > 1000) 
     96      return itos(static_cast<unsigned int>(time/(1000))) + "s"; 
     97    return itos(static_cast<unsigned int>(time)); 
     98  } 
     99 
    40100  inline long long stoi64_as_BKMG(std::string s) { 
    41101    std::string::size_type p = s.find_first_of("BMKG"); 
  • trunk/include/thread.h

    rebcb766 r5d8e0b5  
    11#pragma once 
     2 
     3#include <process.h> 
     4#include <Mutex.h> 
     5 
     6class ThreadException { 
     7public: 
     8  std::string e_; 
     9  ThreadException(std::string e) : e_(e) {} 
     10}; 
    211 
    312/** 
     
    2837private: 
    2938  HANDLE hThread_;    // Thread handle 
    30   DWORD dwThreadID_;    // Thread ID 
    3139  T* pObject_;      // Wrapped object 
    3240  HANDLE hStopEvent_;   // Event to signal that the thread has stopped 
     41  HANDLE hMutex_;     // Mutex to protect internal data 
     42 
    3343 
    3444  typedef struct thread_param { 
    35     Thread* manager;  // The thread manager 
     45    HANDLE hStopEvent;  // The stop event to signal when thread dies 
    3646    T *instance;    // The thread instance object 
    3747    LPVOID lpParam;   // The optional argument to the thread 
     48    Thread *pCore; 
    3849  } thread_param; 
    3950 
     
    4354   * Sets up default values 
    4455   */ 
    45   Thread() : hThread_(NULL), dwThreadID_(0), pObject_(NULL), hStopEvent_(NULL) {} 
     56  Thread() : hThread_(NULL), pObject_(NULL), hStopEvent_(NULL) { 
     57    hMutex_ = CreateMutex(NULL, FALSE, NULL); 
     58    assert(hMutex_ != NULL); 
     59  } 
    4660  /** 
    4761   * Default d-tor. 
     
    5064   */ 
    5165  virtual ~Thread() { 
    52     if (hThread_) 
    53       CloseHandle(hThread_); 
    54     if (hStopEvent_) 
    55       CloseHandle(hStopEvent_); 
     66    { 
     67      MutexLock mutex(hMutex_, 5000L); 
     68      if (!mutex.hasMutex()) { 
     69        throw ThreadException("Could not retrieve mutex when killing thread, we are fucked..."); 
     70      } 
     71      if (hThread_) 
     72        CloseHandle(hThread_); 
     73      hThread_ = NULL; 
     74      if (hStopEvent_) 
     75        CloseHandle(hStopEvent_); 
     76      hStopEvent_ = NULL; 
     77      delete pObject_; 
     78      pObject_ = NULL; 
     79    } 
     80    if (hMutex_) 
     81      CloseHandle(hMutex_); 
     82    hMutex_ = NULL; 
    5683  } 
    5784 
     
    6491   * @return exit status 
    6592   */ 
    66   static DWORD WINAPI threadProc(LPVOID lpParameter) { 
     93  static void threadProc(LPVOID lpParameter) { 
    6794    thread_param* param = static_cast<thread_param*>(lpParameter); 
    6895    T* instance = param->instance; 
    69     Thread *manager = param->manager; 
     96    HANDLE hStopEvent = param->hStopEvent; 
    7097    LPVOID lpParam = param->lpParam; 
     98    Thread *pCore = param->pCore; 
    7199    delete param; 
    72100 
    73     assert(manager->hStopEvent_); 
    74     DWORD ret = instance->threadProc(lpParam); 
    75     BOOL b = SetEvent(manager->hStopEvent_); 
    76     assert(b); 
    77     return ret; 
     101    if (hStopEvent != NULL) { 
     102      instance->threadProc(lpParam); 
     103      SetEvent(hStopEvent); 
     104    } 
     105    pCore->terminate(); 
     106    _endthread(); 
    78107  } 
    79108 
     
    89118   */ 
    90119  void createThread(LPVOID lpParam = NULL) { 
    91     assert(pObject_ == NULL); 
    92     assert(hStopEvent_ == NULL); 
    93     pObject_ = new T; 
    94     thread_param* param = new thread_param; 
    95     param->instance = pObject_; 
    96     param->manager = this; 
    97     param->lpParam = lpParam; 
    98     hStopEvent_ = CreateEvent(NULL, TRUE, FALSE, NULL); 
    99     hThread_ = ::CreateThread(NULL,0,threadProc,reinterpret_cast<VOID*>(param),0,&dwThreadID_); 
     120    thread_param* param = NULL; 
     121    { 
     122      MutexLock mutex(hMutex_, 5000L); 
     123      if (!mutex.hasMutex()) { 
     124        throw ThreadException("Could not retrieve mutex, thread not started..."); 
     125      } 
     126      if (pObject_) { 
     127        throw ThreadException("Thread already started, thread not started..."); 
     128      } 
     129      assert(hStopEvent_ == NULL); 
     130      param = new thread_param; 
     131      param->instance = pObject_ = new T; 
     132      param->hStopEvent = hStopEvent_ = CreateEvent(NULL, TRUE, FALSE, NULL); 
     133      param->lpParam = lpParam; 
     134      param->pCore = this; 
     135    } 
     136    hThread_ = reinterpret_cast<HANDLE>(::_beginthread(threadProc, 0, reinterpret_cast<VOID*>(param))); 
     137    assert(hThread_ != NULL); 
    100138  } 
    101139  /** 
     
    105143   */ 
    106144  bool exitThread(const unsigned int delay = 5000L) { 
    107     assert(pObject_ != NULL); 
    108     assert(hStopEvent_ != NULL); 
    109     pObject_->exitThread(); 
    110  
    111     DWORD dwWaitResult = WaitForSingleObject(hStopEvent_, delay); 
     145    DWORD dwWaitResult = -1; 
     146    { 
     147      MutexLock mutex(hMutex_, 5000L); 
     148      if (!mutex.hasMutex()) { 
     149        throw ThreadException("Could not retrieve mutex, thread not stopped..."); 
     150      } 
     151      if (!pObject_) 
     152        return true; 
     153      assert(hStopEvent_ != NULL); 
     154      pObject_->exitThread(); 
     155      dwWaitResult = WaitForSingleObject(hStopEvent_, delay); 
     156    } 
    112157    switch (dwWaitResult) { 
    113158      // The thread got mutex ownership. 
    114159      case WAIT_OBJECT_0: 
    115         { 
    116           // @todo pObject should be protected! 
    117           HANDLE hTmp = hStopEvent_; 
    118           T* pTmp = pObject_; 
    119           pObject_ = NULL; 
    120           delete pTmp; 
    121           hStopEvent_ = NULL; 
    122           CloseHandle(hTmp); 
    123         } 
    124160        return true; 
    125161        // Did not get a signal due to time-out. 
    126162      case WAIT_TIMEOUT:  
    127163        return false;  
    128  
    129164        // Never got a signal. 
    130165      case WAIT_ABANDONED:  
     
    134169  } 
    135170  bool hasActiveThread() const { 
    136     // @todo pObject should be protected! 
     171    MutexLock mutex(hMutex_, 5000L); 
     172    if (!mutex.hasMutex()) { 
     173      throw ThreadException("Could not retrieve mutex, thread not stopped..."); 
     174    } 
    137175    return pObject_ != NULL; 
    138176  } 
    139177  const T* getThreadConst() const { 
    140     // @todo pObject should be protected! 
     178    MutexLock mutex(hMutex_, 5000L); 
     179    if (!mutex.hasMutex()) { 
     180      throw ThreadException("Could not retrieve mutex, thread not stopped..."); 
     181    } 
    141182    return pObject_; 
    142183  } 
    143184  T* getThread() const { 
    144     // @todo pObject should be protected! 
     185    MutexLock mutex(hMutex_, 5000L); 
     186    if (!mutex.hasMutex()) { 
     187      throw ThreadException("Could not retrieve mutex, thread not stopped..."); 
     188    } 
    145189    return pObject_; 
    146190  } 
     191private: 
     192  void terminate() { 
     193    MutexLock mutex(hMutex_, 5000L); 
     194    if (!mutex.hasMutex()) { 
     195      throw ThreadException("Could not retrieve mutex, thread not stopped..."); 
     196    } 
     197    delete pObject_; 
     198    pObject_ = NULL; 
     199    CloseHandle(hStopEvent_); 
     200    hStopEvent_ = NULL; 
     201    hThread_ = NULL; 
     202  } 
    147203}; 
    148204 
  • trunk/modules/CheckDisk/CheckDisk.cpp

    rf705d34 r5d8e0b5  
    66#include <strEx.h> 
    77#include <time.h> 
     8#include <utils.h> 
    89 
    910CheckDisk gCheckDisk; 
     
    8283} 
    8384 
    84 NSCAPI::nagiosReturn CheckDisk::CheckFileSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
     85NSCAPI::nagiosReturn CheckDisk::CheckDriveSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
    8586  // CheckFileSize 
    86   // request: CheckFileSize&<option>&<option>... 
     87  // request: CheckFileSize <option> <option>... 
    8788  // <option>     MaxWarn=<size gmkb> 
    8889  //          MaxCrit=<size gmkb> 
     
    100101  // Examples: 
    101102  // <return string>  <directory> <size gmkb> ... |<shortname>=<size>:<warn>:<crit> 
    102   // test: CheckFileSize&ShowAll&MaxWarn=1024M&MaxCrit=4096M&File:WIN=c:\WINDOWS\*.* 
     103  // test: CheckFileSize ShowAll MaxWarn=1024M MaxCrit=4096M File:WIN=c:\WINDOWS\*.* 
     104  //       CheckFileSize 
     105  // 
     106  // check_nscp -H <ip> -p <port> -s <passwd> -c <commandstring> 
     107  // 
     108  // ./check_nscp -H 192.168.0.167 -p 1234 -s pwd -c 'CheckFileSize&ShowAll&MaxWarn=1024M&MaxCrit=4096M&File:WIN=c:\WINDOWS\*.*' 
     109  // WIN: 1G (2110962363B)|WIN:2110962363:1073741824:4294967296 
     110  NSC_DEBUG_MSG("CheckDriveSize"); 
     111  NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK; 
     112  std::list<std::string> args = arrayBuffer::arrayBuffer2list(argLen, char_args); 
     113  if (args.empty()) { 
     114    message = "Missing argument(s)."; 
     115    return NSCAPI::returnCRIT; 
     116  } 
     117 
     118  checkHolders::SizeMaxMin warn; 
     119  checkHolders::SizeMaxMin crit; 
     120  bool bShowAll = false; 
     121  bool bNSClient = false; 
     122  std::list<std::string> drives; 
     123 
     124  std::list<std::string>::const_iterator cit; 
     125  for (cit=args.begin();cit!=args.end();++cit) { 
     126    std::string arg = *cit; 
     127    std::pair<std::string,std::string> p = strEx::split(arg,"="); 
     128    if (p.first == "Drive") { 
     129      drives.push_back(p.second); 
     130    } else if (p.first == "MaxWarn") { 
     131      warn.max.set(p.second); 
     132    } else if (p.first == "MinWarn") { 
     133      warn.min.set(p.second); 
     134    } else if (p.first == "MaxCrit") { 
     135      crit.max.set(p.second); 
     136    } else if (p.first == "MinCrit") { 
     137      crit.min.set(p.second); 
     138    } else if (p.first == "ShowAll") { 
     139      bShowAll = true; 
     140    } else if (p.first == "nsclient") { 
     141      bNSClient = true; 
     142    } else { 
     143      drives.push_back(p.first); 
     144    } 
     145  } 
     146 
     147  NSC_DEBUG_MSG_STD("Bounds: critical " + crit.min.toString() + " > size > " + crit.max.toString()); 
     148  NSC_DEBUG_MSG_STD("Bounds: warning " + warn.min.toString() + " > size > " + warn.max.toString()); 
     149  NSC_DEBUG_MSG_STD("Showall: " + ((bShowAll)?"yeap":"noop")); 
     150  NSC_DEBUG_MSG_STD("nsclient: " + ((bNSClient)?"yeap":"noop")); 
     151 
     152  for (std::list<std::string>::iterator it = drives.begin();it!=drives.end();it++) { 
     153    std::string drive = (*it); 
     154    if (drive.length() == 1) 
     155      drive += ":"; 
     156    if (GetDriveType(drive.c_str()) != DRIVE_FIXED){ 
     157      message = "ERROR: Drive is not a fixed drive: " + drive; 
     158      return NSCAPI::returnUNKNOWN; 
     159    } 
     160    ULARGE_INTEGER freeBytesAvailableToCaller; 
     161    ULARGE_INTEGER totalNumberOfBytes; 
     162    ULARGE_INTEGER totalNumberOfFreeBytes; 
     163    if (!GetDiskFreeSpaceEx(drive.c_str(), &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes)) { 
     164      message = "ERROR: Could not get free space for" + drive; 
     165      return NSCAPI::returnUNKNOWN; 
     166    } 
     167 
     168    if (bNSClient) { 
     169      message += strEx::itos(totalNumberOfFreeBytes.QuadPart) + "&"; 
     170      message += strEx::itos(totalNumberOfBytes.QuadPart) + "&"; 
     171    } else { 
     172      std::string tStr; 
     173      long long usedSpace = totalNumberOfBytes.QuadPart-totalNumberOfFreeBytes.QuadPart; 
     174      long long totalSpace = totalNumberOfBytes.QuadPart; 
     175      if (crit.max.hasBounds() && crit.max.checkMAX(usedSpace, totalSpace)) { 
     176        message += crit.max.prettyPrint(drive, usedSpace, totalSpace); 
     177        NSCHelper::escalteReturnCodeToCRIT(returnCode); 
     178      } else if (crit.min.hasBounds() && crit.min.checkMIN(usedSpace, totalSpace)) { 
     179        tStr = crit.min.prettyPrint(drive, usedSpace, totalSpace); 
     180        NSCHelper::escalteReturnCodeToCRIT(returnCode); 
     181      } else if (warn.max.hasBounds() && warn.max.checkMAX(usedSpace, totalSpace)) { 
     182        tStr = warn.max.prettyPrint(drive, usedSpace, totalSpace); 
     183        NSCHelper::escalteReturnCodeToWARN(returnCode); 
     184      } else if (warn.min.hasBounds() && warn.min.checkMIN(usedSpace, totalSpace)) { 
     185        tStr = warn.min.prettyPrint(drive, usedSpace, totalSpace); 
     186        NSCHelper::escalteReturnCodeToWARN(returnCode); 
     187      } else if (bShowAll) { 
     188        tStr = drive + ": " + strEx::itos_as_BKMG(usedSpace); 
     189      } 
     190      perf += checkHolders::SizeMaxMin::printPerf(drive, usedSpace, totalSpace, warn, crit); 
     191      if (!message.empty() && !tStr.empty()) 
     192        message += ", "; 
     193      if (!tStr.empty()) 
     194        message += tStr; 
     195    } 
     196  } 
     197  if (message.empty()) 
     198    message = "All drive sizes are within bounds."; 
     199  return returnCode; 
     200} 
     201 
     202NSCAPI::nagiosReturn CheckDisk::CheckFileSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
     203  // CheckFileSize 
     204  // request: CheckFileSize <option> <option>... 
     205  // <option>     MaxWarn=<size gmkb> 
     206  //          MaxCrit=<size gmkb> 
     207  //          MinWarn=<size gmkb> 
     208  //          MinCrit=<size gmkb> 
     209  //          ShowAll 
     210  //          File=<path> 
     211  //          File:<shortname>=<path> 
     212  // 
     213  // Return: <return state>&<return string>... 
     214  // <return state> 0 - No errors 
     215  //          1 - Unknown 
     216  //          2 - Errors 
     217  // <size gmkb> is a size with a possible modifier letter (such as G for gigabyte, M for Megabyte, K for kilobyte etc) 
     218  // Examples: 
     219  // <return string>  <directory> <size gmkb> ... |<shortname>=<size>:<warn>:<crit> 
     220  // test: CheckFileSize ShowAll MaxWarn=1024M MaxCrit=4096M File:WIN=c:\WINDOWS\*.* 
    103221  //       CheckFileSize 
    104222  // 
     
    196314  if (command == "CheckFileSize") { 
    197315    return CheckFileSize(argLen, char_args, msg, perf); 
     316  } else if (command == "CheckDriveSize") { 
     317    return CheckDriveSize(argLen, char_args, msg, perf); 
     318 
    198319//  } else if (command == "CheckFileDate") { 
    199320  }  
  • trunk/modules/CheckDisk/CheckDisk.h

    rc515660 r5d8e0b5  
    1818  // Check commands 
    1919  NSCAPI::nagiosReturn CheckFileSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
     20  NSCAPI::nagiosReturn CheckDriveSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
    2021}; 
  • trunk/modules/CheckDisk/CheckDisk.vcproj

    rebcb766 r5d8e0b5  
    2121        Optimization="0" 
    2222        AdditionalIncludeDirectories="../include;../../include" 
    23         PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_STLP_USE_STATIC_LIB;_STLP_USE_NEWALLOC" 
     23        PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_STLP_USE_NEWALLOC;_STLP_DEBUG=1" 
    2424        MinimalRebuild="TRUE" 
    2525        BasicRuntimeChecks="3" 
    26         RuntimeLibrary="1" 
     26        RuntimeLibrary="3" 
    2727        UsePrecompiledHeader="3" 
    2828        WarningLevel="3" 
     
    7171        Name="VCCLCompilerTool" 
    7272        AdditionalIncludeDirectories="../include;../../include" 
    73         PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_STLP_USE_STATIC_LIB;SYSTRAY_EXPORTS" 
    74         RuntimeLibrary="0" 
     73        PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS" 
     74        RuntimeLibrary="2" 
    7575        UsePrecompiledHeader="3" 
    7676        WarningLevel="3" 
     
    112112    </Configuration> 
    113113    <Configuration 
    114       Name="Dynamic Linkage|Win32" 
    115       OutputDirectory="$(ConfigurationName)" 
    116       IntermediateDirectory="$(ConfigurationName)" 
    117       ConfigurationType="2" 
    118       CharacterSet="2"> 
    119       <Tool 
    120         Name="VCCLCompilerTool" 
    121         AdditionalIncludeDirectories="../include;../../include" 
    122         PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS" 
    123         RuntimeLibrary="2" 
    124         UsePrecompiledHeader="3" 
    125         WarningLevel="3" 
    126         Detect64BitPortabilityProblems="TRUE" 
    127         DebugInformationFormat="3"/> 
    128       <Tool 
    129         Name="VCCustomBuildTool"/> 
    130       <Tool 
    131         Name="VCLinkerTool" 
    132         OutputFile="../../Release/modules/$(ProjectName).dll" 
    133         LinkIncremental="1" 
    134         ModuleDefinitionFile="CheckDisk.def" 
    135         GenerateDebugInformation="TRUE" 
    136         SubSystem="2" 
    137         OptimizeReferences="2" 
    138         EnableCOMDATFolding="2" 
    139         ImportLibrary="$(OutDir)/CheckDisk.lib" 
    140         TargetMachine="1"/> 
    141       <Tool 
    142         Name="VCMIDLTool"/> 
    143       <Tool 
    144         Name="VCPostBuildEventTool"/> 
    145       <Tool 
    146         Name="VCPreBuildEventTool"/> 
    147       <Tool 
    148         Name="VCPreLinkEventTool"/> 
    149       <Tool 
    150         Name="VCResourceCompilerTool"/> 
    151       <Tool 
    152         Name="VCWebServiceProxyGeneratorTool"/> 
    153       <Tool 
    154         Name="VCXMLDataGeneratorTool"/> 
    155       <Tool 
    156         Name="VCWebDeploymentTool"/> 
    157       <Tool 
    158         Name="VCManagedWrapperGeneratorTool"/> 
    159       <Tool 
    160         Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
    161     </Configuration> 
    162     <Configuration 
    163       Name="Debug Dynamic Linkage|Win32" 
    164       OutputDirectory="$(ConfigurationName)" 
    165       IntermediateDirectory="$(ConfigurationName)" 
    166       ConfigurationType="2" 
    167       CharacterSet="2"> 
    168       <Tool 
    169         Name="VCCLCompilerTool" 
    170         Optimization="0" 
    171         AdditionalIncludeDirectories="../include;../../include" 
    172         PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_STLP_USE_NEWALLOC;_STLP_DEBUG=1" 
    173         MinimalRebuild="TRUE" 
    174         BasicRuntimeChecks="3" 
    175         RuntimeLibrary="3" 
    176         UsePrecompiledHeader="3" 
    177         WarningLevel="3" 
    178         Detect64BitPortabilityProblems="TRUE" 
    179         DebugInformationFormat="4"/> 
    180       <Tool 
    181         Name="VCCustomBuildTool"/> 
    182       <Tool 
    183         Name="VCLinkerTool" 
    184         OutputFile="../../Debug/modules/$(ProjectName).dll" 
    185         LinkIncremental="2" 
    186         ModuleDefinitionFile="CheckDisk.def" 
    187         GenerateDebugInformation="TRUE" 
    188         ProgramDatabaseFile="$(OutDir)/CheckDisk.pdb" 
    189         SubSystem="2" 
    190         ImportLibrary="$(OutDir)/CheckDisk.lib" 
    191         TargetMachine="1"/> 
    192       <Tool 
    193         Name="VCMIDLTool"/> 
    194       <Tool 
    195         Name="VCPostBuildEventTool"/> 
    196       <Tool 
    197         Name="VCPreBuildEventTool"/> 
    198       <Tool 
    199         Name="VCPreLinkEventTool"/> 
    200       <Tool 
    201         Name="VCResourceCompilerTool"/> 
    202       <Tool 
    203         Name="VCWebServiceProxyGeneratorTool"/> 
    204       <Tool 
    205         Name="VCXMLDataGeneratorTool"/> 
    206       <Tool 
    207         Name="VCWebDeploymentTool"/> 
    208       <Tool 
    209         Name="VCManagedWrapperGeneratorTool"/> 
    210       <Tool 
    211         Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
    212     </Configuration> 
    213     <Configuration 
    214114      Name="Distribution|Win32" 
    215115      OutputDirectory="$(ConfigurationName)" 
     
    292192        </FileConfiguration> 
    293193        <FileConfiguration 
    294           Name="Dynamic Linkage|Win32"> 
     194          Name="Distribution|Win32"> 
    295195          <Tool 
    296196            Name="VCCLCompilerTool" 
    297197            UsePrecompiledHeader="1"/> 
    298198        </FileConfiguration> 
    299         <FileConfiguration 
    300           Name="Debug Dynamic Linkage|Win32"> 
    301           <Tool 
    302             Name="VCCLCompilerTool" 
    303             UsePrecompiledHeader="1"/> 
     199      </File> 
     200      <File 
     201        RelativePath="..\..\include\utils.cpp"> 
     202        <FileConfiguration 
     203          Name="Debug|Win32"> 
     204          <Tool 
     205            Name="VCCLCompilerTool" 
     206            UsePrecompiledHeader="0"/> 
     207        </FileConfiguration> 
     208        <FileConfiguration 
     209          Name="Release|Win32"> 
     210          <Tool 
     211            Name="VCCLCompilerTool" 
     212            UsePrecompiledHeader="0"/> 
    304213        </FileConfiguration> 
    305214        <FileConfiguration 
     
    307216          <Tool 
    308217            Name="VCCLCompilerTool" 
    309             UsePrecompiledHeader="1"/> 
     218            UsePrecompiledHeader="0"/> 
    310219        </FileConfiguration> 
    311220      </File> 
     
    323232      <File 
    324233        RelativePath=".\stdafx.h"> 
     234      </File> 
     235      <File 
     236        RelativePath="..\..\include\utils.h"> 
    325237      </File> 
    326238    </Filter> 
  • trunk/modules/FileLogger/FileLogger.cpp

    rebcb766 r5d8e0b5  
    1919 
    2020bool FileLogger::loadModule() { 
    21   file_ = NSCModuleHelper::getSettingsString("log", "file", "nsclient.log"); 
     21  file_ = NSCModuleHelper::getSettingsString(LOG_SECTION_TITLE, LOG_FILENAME, LOG_FILENAME_DEFAULT); 
    2222  return true; 
    2323} 
     
    2626} 
    2727std::string FileLogger::getModuleName() { 
    28   return "File logger: " + NSCModuleHelper::getSettingsString("log", "file", "nsclient.log"); 
     28  return "File logger: " + NSCModuleHelper::getSettingsString(LOG_SECTION_TITLE, LOG_FILENAME, LOG_FILENAME_DEFAULT); 
    2929} 
    3030NSCModuleWrapper::module_version FileLogger::getModuleVersion() { 
  • trunk/modules/FileLogger/FileLogger.vcproj

    rebcb766 r5d8e0b5  
    204204      UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> 
    205205      <File 
     206        RelativePath="..\..\include\config.h"> 
     207      </File> 
     208      <File 
    206209        RelativePath=".\FileLogger.h"> 
    207210      </File> 
  • trunk/modules/FileLogger/stdafx.h

    re0705d4 r5d8e0b5  
    1616#include <fstream> 
    1717 
     18#include <config.h> 
     19 
    1820 
    1921// TODO: reference additional headers your program requires here 
  • trunk/modules/NRPEListener/NRPEListener.cpp

    rebcb766 r5d8e0b5  
    77#include <time.h> 
    88#include <config.h> 
     9#include "NRPEPacket.h" 
    910 
    1011NRPEListener gNRPEListener; 
     
    2425 
    2526bool NRPEListener::loadModule() { 
    26   timeout = NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_TIMEOUT ,60); 
     27  bUseSSL_ = NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_USE_SSL ,NRPE_SETTINGS_USE_SSL_DEFAULT)==1; 
     28  timeout = NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_TIMEOUT ,NRPE_SETTINGS_TIMEOUT_DEFAULT); 
    2729  std::list<std::string> commands = NSCModuleHelper::getSettingsSection(NRPE_HANDLER_SECTION_TITLE); 
    2830  std::list<std::string>::iterator it; 
     
    4042  } 
    4143 
    42   socket.setAllowedHosts(strEx::splitEx(NSCModuleHelper::getSettingsString(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOWED, ""), ",")); 
     44  allowedHosts.setAllowedHosts(strEx::splitEx(NSCModuleHelper::getSettingsString(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOWED, NRPE_SETTINGS_ALLOWED_DEFAULT), ",")); 
    4345  try { 
    44     socket.StartListen(NSCModuleHelper::getSettingsInt("NSClient", NRPE_SETTINGS_PORT, DEFAULT_NRPE_PORT)); 
     46    if (bUseSSL_) { 
     47      socket_ssl_.setHandler(this); 
     48      socket_ssl_.StartListener(NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_PORT, NRPE_SETTINGS_PORT_DEFAULT)); 
     49    } else { 
     50      socket_.setHandler(this); 
     51      socket_.StartListener(NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_PORT, NRPE_SETTINGS_PORT_DEFAULT)); 
     52    } 
    4553  } catch (simpleSocket::SocketException e) { 
    4654    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
    4755    return false; 
    48   } 
     56  } catch (simpleSSL::SSLException e) { 
     57    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
     58    return false; 
     59  } 
     60 
    4961  return true; 
    5062} 
    5163bool NRPEListener::unloadModule() { 
    5264  try { 
    53     socket.close(); 
     65    if (bUseSSL_) { 
     66      socket_ssl_.removeHandler(this); 
     67      socket_ssl_.StopListener(); 
     68    } else { 
     69      socket_.removeHandler(this); 
     70      socket_.StopListener(); 
     71    } 
    5472  } catch (simpleSocket::SocketException e) { 
     73    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
     74    return false; 
     75  } catch (simpleSSL::SSLException e) { 
    5576    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
    5677    return false; 
     
    81102 
    82103  std::string str = (*it).second; 
    83   if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_ARGUMENTS, 0) == 1) { 
     104  if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_ARGUMENTS, NRPE_SETTINGS_ALLOW_ARGUMENTS_DEFAULT) == 1) { 
    84105    arrayBuffer::arrayList arr = arrayBuffer::arrayBuffer2list(argLen, char_args); 
    85106    arrayBuffer::arrayList::const_iterator cit = arr.begin(); 
     
    87108 
    88109    for (;cit!=arr.end();cit++,i++) { 
    89       if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_NASTY_META, 0) == 0) { 
     110      if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_NASTY_META, NRPE_SETTINGS_ALLOW_NASTY_META_DEFAULT) == 0) { 
    90111        if ((*cit).find_first_of(NASTY_METACHARS) != std::string::npos) { 
    91112          NSC_LOG_ERROR("Request string contained illegal metachars!"); 
     
    199220  return result; 
    200221} 
    201  
     222void NRPEListener::onClose() 
     223{} 
     224 
     225void NRPEListener::onAccept(simpleSocket::Socket &client)  
     226{ 
     227  if (!allowedHosts.inAllowedHosts(client.getAddrString())) { 
     228    NSC_LOG_ERROR("Unothorized access from: " + client.getAddrString()); 
     229    client.close(); 
     230    return; 
     231  } 
     232  try { 
     233    simpleSocket::DataBuffer block; 
     234 
     235    for (int i=0;i<100;i++) { 
     236      client.readAll(block); 
     237      if (block.getLength() >= NRPEPacket::getBufferLength()) 
     238        break; 
     239      Sleep(100); 
     240    } 
     241    if (i == 100) { 
     242      NSC_LOG_ERROR_STD("Could not retrieve NRPE packet."); 
     243      client.close(); 
     244      return; 
     245    } 
     246 
     247    if (block.getLength() == NRPEPacket::getBufferLength()) { 
     248      try { 
     249        NRPEPacket out = handlePacket(NRPEPacket(block.getBuffer(), block.getLength())); 
     250        block.copyFrom(out.getBuffer(), out.getBufferLength()); 
     251      } catch (NRPEPacket::NRPEPacketException e) { 
     252        NSC_LOG_ERROR_STD("NRPESocketException: " + e.getMessage()); 
     253        client.close(); 
     254        return; 
     255      } 
     256      client.send(block); 
     257    } 
     258  } catch (simpleSocket::SocketException e) { 
     259    NSC_LOG_ERROR_STD("SocketException: " + e.getMessage()); 
     260  } catch (NRPEException e) { 
     261    NSC_LOG_ERROR_STD("NRPEException: " + e.getMessage()); 
     262  } 
     263  client.close(); 
     264} 
     265 
     266NRPEPacket NRPEListener::handlePacket(NRPEPacket p) { 
     267  if (p.getType() != NRPEPacket::queryPacket) { 
     268    NSC_LOG_ERROR("Request is not a query."); 
     269    throw NRPEException("Invalid query type"); 
     270  } 
     271  if (p.getVersion() != NRPEPacket::version2) { 
     272    NSC_LOG_ERROR("Request had unsupported version."); 
     273    throw NRPEException("Invalid version"); 
     274  } 
     275  if (!p.verifyCRC()) { 
     276    NSC_LOG_ERROR("Request had invalid checksum."); 
     277    throw NRPEException("Invalid checksum"); 
     278  } 
     279  strEx::token cmd = strEx::getToken(p.getPayload(), '!'); 
     280  std::string msg, perf; 
     281  NSC_DEBUG_MSG_STD("Command: " + cmd.first); 
     282  NSC_DEBUG_MSG_STD("Arguments: " + cmd.second); 
     283 
     284  if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_ARGUMENTS, NRPE_SETTINGS_ALLOW_ARGUMENTS_DEFAULT) == 0) { 
     285    if (!cmd.second.empty()) { 
     286      NSC_LOG_ERROR("Request contained arguments (not currently allowed)."); 
     287      throw NRPEException("Request contained arguments (not currently allowed)."); 
     288    } 
     289  } 
     290  if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_NASTY_META, NRPE_SETTINGS_ALLOW_NASTY_META_DEFAULT) == 0) { 
     291    if (cmd.first.find_first_of(NASTY_METACHARS) != std::string::npos) { 
     292      NSC_LOG_ERROR("Request command contained illegal metachars!"); 
     293      throw NRPEException("Request command contained illegal metachars!"); 
     294    } 
     295    if (cmd.second.find_first_of(NASTY_METACHARS) != std::string::npos) { 
     296      NSC_LOG_ERROR("Request arguments contained illegal metachars!"); 
     297      throw NRPEException("Request command contained illegal metachars!"); 
     298    } 
     299  } 
     300 
     301  NSCAPI::nagiosReturn ret = NSCModuleHelper::InjectSplitAndCommand(cmd.first, cmd.second, '!', msg, perf); 
     302  if (perf.empty()) { 
     303    return NRPEPacket(NRPEPacket::responsePacket, NRPEPacket::version2, ret, msg); 
     304  } else { 
     305    return NRPEPacket(NRPEPacket::responsePacket, NRPEPacket::version2, ret, msg + "|" + perf); 
     306  } 
     307} 
    202308 
    203309NSC_WRAPPERS_MAIN_DEF(gNRPEListener); 
  • trunk/modules/NRPEListener/NRPEListener.h

    rf705d34 r5d8e0b5  
    11NSC_WRAPPERS_MAIN(); 
     2#include <Socket.h> 
     3#include <SSLSocket.h> 
     4#include <map> 
     5#include "NRPEPacket.h" 
    26 
    3  
    4 #include "NRPESocket.h" 
    5 #include <Socket.h> 
    6 #include <map> 
    7  
    8 class NRPEListener { 
     7class NRPEListener : public simpleSocket::ListenerHandler { 
    98private: 
    10   NRPESocket socket; 
     9  bool bUseSSL_; 
     10  simpleSSL::Listener socket_ssl_; 
     11  simpleSocket::Listener<> socket_; 
    1112  typedef std::map<std::string, std::string> commandList; 
    1213  commandList commands; 
    1314  unsigned int timeout; 
     15  socketHelpers::allowedHosts allowedHosts; 
    1416 
    1517public: 
     
    2628 
    2729private: 
     30  class NRPEException { 
     31    std::string error_; 
     32  public: 
     33/*    NRPESocketException(simpleSSL::SSLException e) { 
     34      error_ = e.getMessage(); 
     35    } 
     36    NRPEException(NRPEPacket::NRPEPacketException e) { 
     37      error_ = e.getMessage(); 
     38    } 
     39    */ 
     40    NRPEException(std::string s) { 
     41      error_ = s; 
     42    } 
     43    std::string getMessage() { 
     44      return error_; 
     45    } 
     46  }; 
     47 
     48 
     49private: 
     50  void onAccept(simpleSocket::Socket &client); 
     51  void onClose(); 
     52 
     53 
     54  NRPEPacket handlePacket(NRPEPacket p); 
    2855  int executeNRPECommand(std::string command, std::string &msg, std::string &perf); 
    2956  void addCommand(std::string key, std::string args) { 
    3057    commands[key] = args; 
    3158  } 
     59 
    3260}; 
    3361 
  • trunk/modules/NRPEListener/NRPEListener.vcproj

    rebcb766 r5d8e0b5  
    3333      <Tool 
    3434        Name="VCLinkerTool" 
    35         AdditionalDependencies="ws2_32.lib" 
     35        AdditionalDependencies="ws2_32.lib ssleay32.lib libeay32.lib" 
    3636        OutputFile="../../Debug/modules/$(ProjectName).dll" 
    3737        LinkIncremental="2" 
     38        AdditionalLibraryDirectories="&quot;C:\Source\openssl-0.9.7f\out32dll.dbg&quot;" 
    3839        ModuleDefinitionFile="NRPEListener.def" 
    3940        GenerateDebugInformation="TRUE" 
     
    8283      <Tool 
    8384        Name="VCLinkerTool" 
    84         AdditionalDependencies="ws2_32.lib" 
     85        AdditionalDependencies="ws2_32.lib ssleay32.lib libeay32.lib" 
    8586        OutputFile="../../Release/modules/$(ProjectName).dll" 
    8687        LinkIncremental="1" 
     88        AdditionalLibraryDirectories="&quot;C:\Source\openssl-0.9.7f\out32dll&quot;" 
    8789        ModuleDefinitionFile="NRPEListener.def" 
    8890        GenerateDebugInformation="TRUE" 
     
    132134      <Tool 
    133135        Name="VCLinkerTool" 
    134         AdditionalDependencies="ws2_32.lib" 
     136        AdditionalDependencies="ws2_32.lib ssleay32.lib libeay32.lib" 
    135137        OutputFile="../../Dist/modules/$(ProjectName).dll" 
    136138        LinkIncremental="1" 
     
    181183      </File> 
    182184      <File 
    183         RelativePath=".\NRPESocket.cpp"> 
     185        RelativePath=".\NRPEPacket.cpp"> 
    184186      </File> 
    185187      <File 
     
    190192      </File> 
    191193      <File 
     194        RelativePath="..\..\include\SSLSocket.cpp"> 
     195      </File> 
     196      <File 
    192197        RelativePath=".\stdafx.cpp"> 
    193198        <FileConfiguration 
     
    208213            Name="VCCLCompilerTool" 
    209214            UsePrecompiledHeader="1"/> 
     215        </FileConfiguration> 
     216      </File> 
     217      <File 
     218        RelativePath="..\..\include\utils.cpp"> 
     219        <FileConfiguration 
     220          Name="Debug|Win32"> 
     221          <Tool 
     222            Name="VCCLCompilerTool" 
     223            UsePrecompiledHeader="0"/> 
     224        </FileConfiguration> 
     225        <FileConfiguration 
     226          Name="Release|Win32"> 
     227          <Tool 
     228            Name="VCCLCompilerTool" 
     229            UsePrecompiledHeader="0"/> 
     230        </FileConfiguration> 
     231        <FileConfiguration 
     232          Name="Distribution|Win32"> 
     233          <Tool 
     234            Name="VCCLCompilerTool" 
     235            UsePrecompiledHeader="0"/> 
    210236        </FileConfiguration> 
    211237      </File> 
     
    219245      </File> 
    220246      <File 
     247        RelativePath="..\..\include\config.h"> 
     248      </File> 
     249      <File 
    221250        RelativePath=".\NRPEListener.h"> 
    222251      </File> 
    223252      <File 
    224         RelativePath=".\NRPESocket.h"> 
    225       </File> 
    226       <File 
    227253        RelativePath="..\..\include\NSCHelper.h"> 
    228254      </File> 
     
    231257      </File> 
    232258      <File 
     259        RelativePath="..\..\include\SSLSocket.h"> 
     260      </File> 
     261      <File 
    233262        RelativePath=".\stdafx.h"> 
    234263      </File> 
    235264      <File 
    236265        RelativePath="..\..\include\thread.h"> 
     266      </File> 
     267      <File 
     268        RelativePath="..\..\include\utils.h"> 
    237269      </File> 
    238270    </Filter> 
  • trunk/modules/NRPEListener/NRPESocket.cpp

    rebcb766 r5d8e0b5  
    33#include "NRPESocket.h" 
    44 
    5 /** 
    6  * Default c-tor 
    7  */ 
    8 NRPESocket::NRPESocket() { 
    9 } 
    10  
    11 NRPESocket::~NRPESocket() { 
    12 } 
    135 
    146 
    157 
    16 typedef short int16_t; 
    17 typedef unsigned long u_int32_t; 
    188 
    19 static unsigned long crc32_table[256]; 
    20 static bool hascrc32 = false; 
    21 void generate_crc32_table(void){ 
    22   unsigned long crc, poly; 
    23   int i, j; 
    24   poly=0xEDB88320L; 
    25   for(i=0;i<256;i++){ 
    26     crc=i; 
    27     for(j=8;j>0;j--){ 
    28       if(crc & 1) 
    29         crc=(crc>>1)^poly; 
    30       else 
    31         crc>>=1; 
    32     } 
    33     crc32_table[i]=crc; 
    34   } 
    35   hascrc32 = true; 
    36 } 
    37 unsigned long calculate_crc32(const char *buffer, int buffer_size){ 
    38   if (!hascrc32) 
    39     generate_crc32_table(); 
    40   register unsigned long crc; 
    41   int this_char; 
    42   int current_index; 
    43  
    44   crc=0xFFFFFFFF; 
    45  
    46   for(current_index=0;current_index<buffer_size;current_index++){ 
    47     this_char=(int)buffer[current_index]; 
    48     crc=((crc>>8) & 0x00FFFFFF) ^ crc32_table[(crc ^ this_char) & 0xFF]; 
    49   } 
    50  
    51   return (crc ^ 0xFFFFFFFF); 
     9const char* NRPEPacket::getBuffer() { 
     10  delete [] tmpBuffer; 
     11  tmpBuffer = new char[getBufferLength()]; 
     12  packet *p = reinterpret_cast<packet*>(tmpBuffer); 
     13  p->result_code = htons(NSCHelper::nagios2int(result_)); 
     14  p->packet_type = htons(type_); 
     15  p->packet_version = htons(version_); 
     16  p->crc32_value = 0; 
     17  strncpy(p->buffer, payload_.c_str(), 1023); 
     18  p->buffer[1024] = 0; 
     19  p->crc32_value = htonl(calculate_crc32(tmpBuffer, getBufferLength())); 
     20  return tmpBuffer; 
    5221} 
    5322 
    54  
    55 class NRPEPacket { 
    56 public: 
    57   static const short queryPacket = 1; 
    58   static const short responsePacket = 2; 
    59   static const short version2 = 2; 
    60 private: 
    61   typedef struct packet { 
    62     int16_t   packet_version; 
    63     int16_t   packet_type; 
    64     u_int32_t crc32_value; 
    65     int16_t   result_code; 
    66     char      buffer[1024]; 
    67   } packet; 
    68   std::string payload_; 
    69   short type_; 
    70   short version_; 
    71   NSCAPI::nagiosReturn result_; 
    72   unsigned int crc32_; 
    73   unsigned int calculatedCRC32_; 
    74   char *tmpBuffer; 
    75 public: 
    76   NRPEPacket(const char *buffer) : tmpBuffer(NULL) { 
    77     const packet *p = reinterpret_cast<const packet*>(buffer); 
    78     type_ = ntohs(p->packet_type); 
    79     assert( (type_ == queryPacket)||(type_ == responsePacket)); 
    80     version_ = ntohs(p->packet_version); 
    81     assert(version_ == version2); 
    82     crc32_ = ntohl(p->crc32_value); 
    83     // Verify CRC32 
    84     // @todo Fix this, currently we need a const buffer so we cannot change the crc to 0. 
    85     char * tb = new char[getBufferLength()]; 
    86     memcpy(tb, buffer, getBufferLength()); 
    87     packet *p2 = reinterpret_cast<packet*>(tb); 
    88     p2->crc32_value = 0; 
    89     calculatedCRC32_ = calculate_crc32(tb, getBufferLength()); 
    90     delete [] tb; 
    91     // Verify CRC32 end 
    92     result_ = NSCHelper::int2nagios(ntohs(p->result_code)); 
    93     payload_ = std::string(p->buffer); 
    94   } 
    95   NRPEPacket(short type, short version, NSCAPI::nagiosReturn result, std::string payLoad)  
    96     : tmpBuffer(NULL)  
    97     ,type_(type) 
    98     ,version_(version) 
    99     ,result_(result) 
    100     ,payload_(payLoad) 
    101   { 
    102   } 
    103   ~NRPEPacket() { 
    104     delete [] tmpBuffer; 
    105   } 
    106   unsigned short getVersion() const { return version_; } 
    107   unsigned short getType() const { return type_; } 
    108   unsigned short getResult() const { return result_; } 
    109   std::string getPayload() const { return payload_; } 
    110   const char* getBuffer() { 
    111     delete [] tmpBuffer; 
    112     tmpBuffer = new char[getBufferLength()]; 
    113     packet *p = reinterpret_cast<packet*>(tmpBuffer); 
    114     p->result_code = htons(NSCHelper::nagios2int(result_)); 
    115     p->packet_type = htons(type_); 
    116     p->packet_version = htons(version_); 
    117     p->crc32_value = 0; 
    118     strncpy(p->buffer, payload_.c_str(), 1023); 
    119     p->buffer[1024] = 0; 
    120     p->crc32_value = htonl(calculate_crc32(tmpBuffer, getBufferLength())); 
    121     return tmpBuffer; 
    122   } 
    123   bool verifyCRC() { 
    124     return calculatedCRC32_ == crc32_; 
    125   } 
    126   const unsigned int getBufferLength() const { 
    127     return sizeof(packet); 
    128   } 
    129 }; 
    130  
    131 void NRPESocket::onAccept(simpleSocket::Socket client) { 
    132   if (!inAllowedHosts(client.getAddrString())) { 
    133     NSC_LOG_ERROR("Unothorized access from: " + client.getAddrString()); 
    134     client.close(); 
    135     return; 
    136   } 
    137   simpleSocket::DataBuffer block; 
    138   client.readAll(block); 
    139   NRPEPacket p(block.getBuffer()); 
    140   if (p.getType() != NRPEPacket::queryPacket) { 
    141     NSC_LOG_ERROR("Request is not a query."); 
    142     client.close(); 
    143     return; 
    144   } 
    145   if (p.getVersion() != NRPEPacket::version2) { 
    146     NSC_LOG_ERROR("Request had unsupported version."); 
    147     client.close(); 
    148     return; 
    149   } 
    150   if (!p.verifyCRC()) { 
    151     NSC_LOG_ERROR("Request had invalid checksum."); 
    152     client.close(); 
    153     return; 
    154   } 
    155   strEx::token cmd = strEx::getToken(p.getPayload(), '!'); 
    156   std::string msg, perf; 
    157   NSC_DEBUG_MSG_STD("Command: " + cmd.first); 
    158   NSC_DEBUG_MSG_STD("Arguments: " + cmd.second); 
    159  
    160   if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_ARGUMENTS, 0) == 0) { 
    161     if (!cmd.second.empty()) { 
    162       NSC_LOG_ERROR("Request contained arguments (not currently allowed)."); 
    163       client.close(); 
    164       return; 
    165     } 
    166   } 
    167   if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_NASTY_META, 0) == 0) { 
    168     if (cmd.first.find_first_of(NASTY_METACHARS) != std::string::npos) { 
    169       NSC_LOG_ERROR("Request command contained illegal metachars!"); 
    170       client.close(); 
    171       return; 
    172     } 
    173     if (cmd.second.find_first_of(NASTY_METACHARS) != std::string::npos) { 
    174       NSC_LOG_ERROR("Request arguments contained illegal metachars!"); 
    175       client.close(); 
    176       return; 
    177     } 
    178   } 
    179  
    180   NSCAPI::nagiosReturn ret = NSCModuleHelper::InjectSplitAndCommand(cmd.first, cmd.second, '!', msg, perf); 
    181   if (perf.empty()) { 
    182     NRPEPacket p2(NRPEPacket::responsePacket, NRPEPacket::version2, ret, msg); 
    183     client.send(p2.getBuffer(), p2.getBufferLength(), 0); 
    184   } else { 
    185     NRPEPacket p2(NRPEPacket::responsePacket, NRPEPacket::version2, ret, msg + "|" + perf); 
    186     client.send(p2.getBuffer(), p2.getBufferLength(), 0); 
    187   } 
    188   client.close(); 
    189 } 
    190  
  • trunk/modules/NRPEListener/NRPESocket.h

    rebcb766 r5d8e0b5  
    22#include "resource.h" 
    33#include <Socket.h> 
     4#include <SSLSocket.h> 
     5 
    46/** 
    57 * @ingroup NSClient++ 
     
    3032#define NASTY_METACHARS         "|`&><'\"\\[]{}"        /* This may need to be modified for windows directory seperator */ 
    3133 
    32 class NRPESocket : public simpleSocket::Listener { 
     34typedef short int16_t; 
     35typedef unsigned long u_int32_t; 
     36 
     37 
     38template <class TBase> 
     39class NRPESocket : public TBase { 
    3340private: 
    3441  strEx::splitList allowedHosts_; 
    3542 
     43  class NRPESocketException { 
     44    std::string error_; 
     45  public: 
     46    NRPESocketException(simpleSSL::SSLException e) { 
     47      error_ = e.getMessage(); 
     48    } 
     49    NRPESocketException(NRPEPacket::NRPEPacketException e) { 
     50      error_ = e.getMessage(); 
     51    } 
     52    NRPESocketException(std::string s) { 
     53      error_ = s; 
     54    } 
     55    std::string getMessage() { 
     56      return error_; 
     57    } 
     58  }; 
     59 
     60 
    3661public: 
    37   NRPESocket(); 
    38   virtual ~NRPESocket(); 
    39  
    40   void setAllowedHosts(strEx::splitList allowedHosts) { 
    41     allowedHosts_ = allowedHosts; 
     62  NRPESocket() { 
    4263  } 
    43   bool inAllowedHosts(std::string s) { 
    44     if (allowedHosts_.empty()) 
    45       return true; 
    46     strEx::splitList::const_iterator cit; 
    47     for (cit = allowedHosts_.begin();cit!=allowedHosts_.end();++cit) { 
    48       if ( (*cit) == s) 
    49         return true; 
    50     } 
    51     return false; 
     64  virtual ~NRPESocket() { 
    5265  } 
    5366 
     67 
    5468private: 
    55   virtual void onAccept(simpleSocket::Socket client); 
     69  NRPEPacket handlePacket(NRPEPacket p) { 
     70    if (p.getType() != NRPEPacket::queryPacket) { 
     71      NSC_LOG_ERROR("Request is not a query."); 
     72      throw NRPESocketException("Invalid query type"); 
     73    } 
     74    if (p.getVersion() != NRPEPacket::version2) { 
     75      NSC_LOG_ERROR("Request had unsupported version."); 
     76      throw NRPESocketException("Invalid version"); 
     77    } 
     78    if (!p.verifyCRC()) { 
     79      NSC_LOG_ERROR("Request had invalid checksum."); 
     80      throw NRPESocketException("Invalid checksum"); 
     81    } 
     82    strEx::token cmd = strEx::getToken(p.getPayload(), '!'); 
     83    std::string msg, perf; 
     84    NSC_DEBUG_MSG_STD("Command: " + cmd.first); 
     85    NSC_DEBUG_MSG_STD("Arguments: " + cmd.second); 
     86 
     87    if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_ARGUMENTS, NRPE_SETTINGS_ALLOW_ARGUMENTS_DEFAULT) == 0) { 
     88      if (!cmd.second.empty()) { 
     89        NSC_LOG_ERROR("Request contained arguments (not currently allowed)."); 
     90        throw NRPESocketException("Request contained arguments (not currently allowed)."); 
     91      } 
     92    } 
     93    if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_NASTY_META, NRPE_SETTINGS_ALLOW_NASTY_META_DEFAULT) == 0) { 
     94      if (cmd.first.find_first_of(NASTY_METACHARS) != std::string::npos) { 
     95        NSC_LOG_ERROR("Request command contained illegal metachars!"); 
     96        throw NRPESocketException("Request command contained illegal metachars!"); 
     97      } 
     98      if (cmd.second.find_first_of(NASTY_METACHARS) != std::string::npos) { 
     99        NSC_LOG_ERROR("Request arguments contained illegal metachars!"); 
     100        throw NRPESocketException("Request command contained illegal metachars!"); 
     101      } 
     102    } 
     103 
     104    NSCAPI::nagiosReturn ret = NSCModuleHelper::InjectSplitAndCommand(cmd.first, cmd.second, '!', msg, perf); 
     105    if (perf.empty()) { 
     106      return NRPEPacket(NRPEPacket::responsePacket, NRPEPacket::version2, ret, msg); 
     107    } else { 
     108      return NRPEPacket(NRPEPacket::responsePacket, NRPEPacket::version2, ret, msg + "|" + perf); 
     109    } 
     110  } 
     111  void setupDH(simpleSSL::DH &dh); 
    56112}; 
    57  
    58  
    59  
    60  
  • trunk/modules/NRPEListener/stdafx.h

    rebcb766 r5d8e0b5  
    1515 
    1616#include <config.h> 
     17#include <utils.h> 
    1718 
    1819#include <NSCAPI.h> 
  • trunk/modules/NSClientCompat/NSClientCompat.vcproj

    rebcb766 r5d8e0b5  
    254254      UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"> 
    255255    </Filter> 
    256     <File 
    257       RelativePath=".\ReadMe.txt"> 
    258     </File> 
    259256  </Files> 
    260257  <Globals> 
  • trunk/modules/NSClientListener/NSClientListener.cpp

    rebcb766 r5d8e0b5  
    99 
    1010NSClientListener gNSClientListener; 
     11 
     12 
     13#define REQ_CLIENTVERSION 1 // Works fine! 
     14#define REQ_CPULOAD     2 // Quirks 
     15#define REQ_UPTIME      3 // Works fine! 
     16#define REQ_USEDDISKSPACE 4 // Works fine! 
     17#define REQ_SERVICESTATE  5 // Works fine! 
     18#define REQ_PROCSTATE   6 // Works fine! 
     19#define REQ_MEMUSE      7 // Works fine! 
     20//#define REQ_COUNTER   8 // ! - not implemented Have to look at this, if anyone has a sample let me know... 
     21//#define REQ_FILEAGE   9 // ! - not implemented Dont know how to use 
     22//#define REQ_INSTANCES 10  // ! - not implemented Dont know how to use 
    1123 
    1224BOOL APIENTRY DllMain( HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved) 
     
    2234 
    2335bool NSClientListener::loadModule() { 
    24   socket.setAllowedHosts(strEx::splitEx(NSCModuleHelper::getSettingsString("NRPE", "allowed_hosts", ""), ",")); 
     36  allowedHosts.setAllowedHosts(strEx::splitEx(NSCModuleHelper::getSettingsString(NSCLIENT_SECTION_TITLE, NSCLIENT_SETTINGS_ALLOWED, NSCLIENT_SETTINGS_ALLOWED_DEFAULT), ",")); 
    2537  try { 
    26     socket.StartListen(NSCModuleHelper::getSettingsInt("NSClient", "port", DEFAULT_NSCLIENT_PORT)); 
     38    socket.setHandler(this); 
     39    socket.StartListener(NSCModuleHelper::getSettingsInt(NSCLIENT_SECTION_TITLE, NSCLIENT_SETTINGS_PORT, NSCLIENT_SETTINGS_PORT_DEFAULT)); 
    2740  } catch (simpleSocket::SocketException e) { 
    2841    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
     
    3346bool NSClientListener::unloadModule() { 
    3447  try { 
    35     socket.close(); 
     48    socket.removeHandler(this); 
     49    socket.StopListener(); 
    3650  } catch (simpleSocket::SocketException e) { 
    3751    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
     
    4963} 
    5064 
     65 
     66std::string NSClientListener::parseRequest(std::string buffer)  { 
     67  strEx::token pwd = strEx::getToken(buffer, '&'); 
     68  NSC_DEBUG_MSG("Password: " + pwd.first); 
     69  if ( (pwd.first.empty()) || (pwd.first != NSCModuleHelper::getSettingsString(NSCLIENT_SECTION_TITLE, NSCLIENT_SETTINGS_PWD, NSCLIENT_SETTINGS_PWD_DEFAULT)) ) 
     70    return "ERROR: Invalid password."; 
     71  if (pwd.second.empty()) 
     72    return "ERRRO: No command specified."; 
     73  strEx::token cmd = strEx::getToken(pwd.second, '&'); 
     74  if (cmd.first.empty()) 
     75    return "ERRRO: No command specified."; 
     76  NSC_DEBUG_MSG("Command: " + cmd.first); 
     77 
     78  int c = atoi(cmd.first.c_str()); 
     79 
     80  // prefix various commands 
     81  switch (c) { 
     82    case REQ_CPULOAD: 
     83      cmd.first = "checkCPU"; 
     84      cmd.second += "&nsclient"; 
     85      break; 
     86    case REQ_UPTIME: 
     87      cmd.first = "checkUpTime"; 
     88      cmd.second = "nsclient"; 
     89      break; 
     90    case REQ_USEDDISKSPACE: 
     91      cmd.first = "CheckDriveSize"; 
     92      cmd.second += "&nsclient"; 
     93      break; 
     94    case REQ_CLIENTVERSION: 
     95      { 
     96        std::string v = NSCModuleHelper::getSettingsString("nsclient compat", "version", "modern"); 
     97        if (v == "modern") 
     98          return NSCModuleHelper::getApplicationName() + " " + NSCModuleHelper::getApplicationVersionString(); 
     99        return NSCModuleHelper::getSettingsString("nsclient compat", "version", "modern"); 
     100      } 
     101    case REQ_SERVICESTATE: 
     102      cmd.first = "checkServiceState"; 
     103      break; 
     104    case REQ_PROCSTATE: 
     105      cmd.first = "checkProcState"; 
     106      break; 
     107    case REQ_MEMUSE: 
     108      cmd.first = "checkMem"; 
     109      cmd.second = "nsclient"; 
     110      break; 
     111  } 
     112 
     113 
     114  std::string message, perf; 
     115  NSCAPI::nagiosReturn ret = NSCModuleHelper::InjectSplitAndCommand(cmd.first.c_str(), cmd.second.c_str(), '&', message, perf); 
     116  if (!NSCHelper::isNagiosReturnCode(ret)) { 
     117    if (message.empty()) 
     118      return "ERROR: Could not complete the request check log file for more information."; 
     119    return "ERROR: " + message; 
     120  } 
     121  switch (c) { 
     122    case REQ_UPTIME:    // Some check_nt commands has no return code syntax 
     123    case REQ_MEMUSE: 
     124    case REQ_CPULOAD: 
     125    case REQ_CLIENTVERSION: 
     126    case REQ_USEDDISKSPACE: 
     127      return message; 
     128 
     129    case REQ_SERVICESTATE:  // Some check_nt commands return the return code (coded as a string) 
     130    case REQ_PROCSTATE: 
     131      return NSCHelper::translateReturn(ret) + "&" + message; 
     132 
     133    default:        // "New" check_nscp also returns performance data 
     134      if (perf.empty()) 
     135        return NSCHelper::translateReturn(ret) + "&" + message; 
     136      return NSCHelper::translateReturn(ret) + "&" + message + "|" + perf; 
     137  } 
     138} 
     139 
     140void NSClientListener::onClose() 
     141{} 
     142 
     143void NSClientListener::onAccept(simpleSocket::Socket &client) { 
     144  if (!allowedHosts.inAllowedHosts(client.getAddrString())) { 
     145    NSC_LOG_ERROR("Unothorized access from: " + client.getAddrString()); 
     146    client.close(); 
     147    return; 
     148  } 
     149  simpleSocket::DataBuffer db; 
     150  client.readAll(db); 
     151  if (db.getLength() > 0) { 
     152    std::string incoming(db.getBuffer(), db.getLength()); 
     153    NSC_DEBUG_MSG_STD("Incoming data: " + incoming); 
     154    std::string response = parseRequest(incoming); 
     155    NSC_DEBUG_MSG("Outgoing data: " + response); 
     156    client.send(response.c_str(), static_cast<int>(response.length()), 0); 
     157  } 
     158  client.close(); 
     159} 
     160 
    51161NSC_WRAPPERS_MAIN_DEF(gNSClientListener); 
    52162NSC_WRAPPERS_IGNORE_MSG_DEF(); 
  • trunk/modules/NSClientListener/NSClientListener.h

    rf705d34 r5d8e0b5  
    1 #include "NSClientSocket.h" 
     1#include <Socket.h> 
     2#include <string> 
     3#include <utils.h> 
    24 
    35NSC_WRAPPERS_MAIN(); 
    46 
    5 class NSClientListener { 
     7class NSClientListener  : public simpleSocket::ListenerHandler { 
    68private: 
    7   NSClientSocket socket; 
     9  simpleSocket::Listener<> socket; 
     10  socketHelpers::allowedHosts allowedHosts; 
    811 
    912public: 
     
    1518  std::string getModuleName(); 
    1619  NSCModuleWrapper::module_version getModuleVersion(); 
     20  std::string parseRequest(std::string buffer); 
     21 
     22  // simpleSocket::ListenerHandler implementation 
     23  void onAccept(simpleSocket::Socket &client); 
     24  void onClose(); 
     25 
    1726}; 
  • trunk/modules/NSClientListener/NSClientListener.vcproj

    rebcb766 r5d8e0b5  
    122122        Name="VCCLCompilerTool" 
    123123        AdditionalIncludeDirectories="../include;../../include" 
    124         PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;NSCLIENTLISTENER_EXPORTS" 
     124        PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS" 
    125125        RuntimeLibrary="2" 
    126126        UsePrecompiledHeader="3" 
     
    179179      <File 
    180180        RelativePath=".\NSClientListener.cpp"> 
    181       </File> 
    182       <File 
    183         RelativePath=".\NSClientSocket.cpp"> 
    184181      </File> 
    185182      <File 
     
    219216      </File> 
    220217      <File 
     218        RelativePath="..\..\include\config.h"> 
     219      </File> 
     220      <File 
    221221        RelativePath=".\NSClientListener.h"> 
    222       </File> 
    223       <File 
    224         RelativePath=".\NSClientSocket.h"> 
    225222      </File> 
    226223      <File 
  • trunk/modules/SysTray/SysTray.vcproj

    rebcb766 r5d8e0b5  
    207207      UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> 
    208208      <File 
     209        RelativePath="..\..\include\config.h"> 
     210      </File> 
     211      <File 
    209212        RelativePath="..\..\include\NSCHelper.h"> 
    210213      </File> 
Note: See TracChangeset for help on using the changeset viewer.