Changes in / [20:30]

Show
Ignore:
Location:
/trunk
Files:
55 added
51 modified

Legend:

Unmodified
Added
Removed
  • /trunk/StdAfx.h

    r8 r24  
    1212 
    1313#define VC_EXTRALEAN    // Exclude rarely-used stuff from Windows headers 
    14 #include <winsock2.h> 
     14#include <WinSock2.h> 
    1515#include <windows.h> 
    1616 
     
    2121#include <list> 
    2222#include <sstream> 
     23#include <vector> 
    2324 
    2425#include "config.h" 
  • /trunk/include/Mutex.h

    r14 r30  
    9898   * Waits for the mutex object. 
    9999   * @param hMutex The mutex to use 
     100   * @timeout The timeout before abandoning wait 
    100101   */ 
    101102  MutexLock(HANDLE hMutex, DWORD timeout = 5000L) : bHasMutex(false), hMutex_(hMutex) { 
     103    if (hMutex_ == NULL) 
     104      std::cout << "Whops..." << std::endl; 
    102105    assert(hMutex_ != NULL); 
    103106    dwWaitResult = WaitForSingleObject(hMutex_, timeout); 
     
    134137   */ 
    135138  virtual ~MutexLock() { 
    136         ReleaseMutex(hMutex_); 
     139    if (bHasMutex) 
     140          ReleaseMutex(hMutex_); 
    137141    bHasMutex = false; 
    138142  } 
  • /trunk/include/arrayBuffer.cpp

    r20 r28  
    44 
    55/** 
    6 * Make a list out of a array of char arrays (arguments type) 
    7 * @param argLen Length of argument array 
    8 * @param *argument[] Argument array 
    9 * @return Argument wrapped as a list 
    10 */ 
    11 std::list<std::string> arrayBuffer::arrayBuffer2list(const unsigned int argLen, char *argument[]) { 
    12   std::list<std::string> ret; 
     6 * Make a list out of a array of char arrays (arguments type) 
     7 * @param argLen Length of argument array 
     8 * @param *argument[] Argument array 
     9 * @return Argument wrapped as a list 
     10 */ 
     11arrayBuffer::arrayList arrayBuffer::arrayBuffer2list(const unsigned int argLen, char *argument[]) { 
     12  arrayList ret; 
    1313  int i=0; 
    1414  for (unsigned int i=0;i<argLen;i++) { 
     
    2727* @return A pointer that is managed by the caller. 
    2828*/ 
    29 char ** arrayBuffer::list2arrayBuffer(const std::list<std::string> lst, unsigned int &argLen) { 
     29char ** arrayBuffer::list2arrayBuffer(const arrayList lst, unsigned int &argLen) { 
    3030  argLen = static_cast<unsigned int>(lst.size()); 
    3131  char **arrayBuffer = new char*[argLen]; 
    32   std::list<std::string>::const_iterator it = lst.begin(); 
     32  arrayList::const_iterator it = lst.begin(); 
    3333  for (int i=0;it!=lst.end();++it,i++) { 
    3434    std::string::size_type alen = (*it).size(); 
     
    4949  return arrayBuffer; 
    5050} 
    51  
    52  
    53  
    5451/** 
    5552* Joins an arrayBuffer back into a string 
     
    6966} 
    7067/** 
    71 * Split a string into elements as an arrayBuffer 
     68* Split a string into elements as a newly created arrayBuffer 
    7269* @param buffer The CharArray to split along 
    7370* @param splitChar The char to use as splitter 
     
    10097  return arrayBuffer; 
    10198} 
     99/** 
     100 * Split a string into elements as a newly created arrayBuffer 
     101 * @param inBuf The CharArray to split along 
     102 * @param splitChar The char to use as splitter 
     103 * @param &argLen [OUT] The length of the Array 
     104 * @return The arrayBuffer 
     105 */ 
    102106char ** arrayBuffer::split2arrayBuffer(const std::string inBuf, char splitChar, unsigned int &argLen) { 
    103107  if (inBuf.empty()) 
     
    121125    strncpy(arrayBuffer[i], inBuf.substr(l,p).c_str(), len); 
    122126    arrayBuffer[i][len] = 0; 
     127    l = ++p; 
    123128    p = inBuf.find(splitChar, p); 
    124129  } 
     
    143148 
    144149#ifdef _DEBUG 
     150/** 
     151 * Test function for createEmptyArrayBuffer 
     152 */ 
    145153void arrayBuffer::test_createEmptyArrayBuffer() { 
    146154  std::cout << "arrayBuffer::test_createEmptyArrayBuffer() : "; 
     
    153161  destroyArrayBuffer(c, argLen); 
    154162} 
     163/** 
     164 * Test function for split2arrayBuffer 
     165 * @param buffer  
     166 * @param splitter  
     167 * @param OUT_argLen  
     168 */ 
    155169void arrayBuffer::test_split2arrayBuffer_str(std::string buffer, char splitter, int OUT_argLen) { 
    156170  std::cout << "arrayBuffer::test_split2arrayBuffer(" << buffer << ", ...) : "; 
     
    163177  destroyArrayBuffer(c, argLen); 
    164178} 
     179/** 
     180 * Test function for split2arrayBuffer 
     181 * @param buffer  
     182 * @param splitter  
     183 * @param OUT_argLen  
     184 */ 
    165185void arrayBuffer::test_split2arrayBuffer_char(char* buffer, char splitter, int OUT_argLen) { 
    166186  std::cout << "arrayBuffer::test_split2arrayBuffer(" << buffer << ", ...) : "; 
     
    174194} 
    175195 
     196/** 
     197 * Test function for ArrayBuffer 
     198 */ 
    176199void arrayBuffer::run_testArrayBuffer() { 
    177200  test_createEmptyArrayBuffer(); 
     
    194217  test_split2arrayBuffer_char("foo&&&", '&', 4); 
    195218} 
    196  
    197219#endif 
  • /trunk/include/strEx.h

    r20 r28  
    44#include <string> 
    55#include <utility> 
     6#include <list> 
     7#ifdef _DEBUG 
     8#include <iostream> 
     9#endif 
    610 
    711namespace strEx { 
    812 
     13  inline void replace(std::string &string, std::string replace, std::string with) { 
     14    std::string::size_type pos = string.find(replace); 
     15    std::string::size_type len = replace.length(); 
     16    while (pos != std::string::npos) { 
     17      string = string.substr(0,pos)+with+string.substr(pos+len); 
     18      pos = string.find(replace, pos+1); 
     19    } 
     20  } 
     21  inline std::string itos(unsigned int i) { 
     22    std::stringstream ss; 
     23    ss << i; 
     24    return ss.str(); 
     25  } 
    926  inline std::string itos(int i) { 
    1027    std::stringstream ss; 
     
    1229    return ss.str(); 
    1330  } 
     31  inline std::string itos(unsigned long long i) { 
     32    std::stringstream ss; 
     33    ss << i; 
     34    return ss.str(); 
     35  } 
    1436  inline std::string itos(__int64 i) { 
    1537    std::stringstream ss; 
     
    1739    return ss.str(); 
    1840  } 
    19   inline std::string itos(DWORD i) { 
     41  inline std::string itos(unsigned long i) { 
    2042    std::stringstream ss; 
    2143    ss << i; 
     
    2547    return atoi(s.c_str()); 
    2648  } 
     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 
    27100  inline long long stoi64_as_BKMG(std::string s) { 
    28     std::string::size_type p = s.find_first_of("BMKG"); 
     101    std::string::size_type p = s.find_first_of("BMKGT"); 
    29102    if (p == std::string::npos) 
    30103      return _atoi64(s.c_str()); 
     
    37110    else if (s[p] == 'G')  
    38111      return _atoi64(s.c_str())*1024*1024*1024; 
     112    else if (s[p] == 'T')  
     113      return _atoi64(s.c_str())*1024*1024*1024*1024; 
    39114    else 
    40115      return _atoi64(s.c_str()); 
    41116  } 
    42   inline std::string itos_as_BKMG(long long i) { 
    43     if (i > (1024*1024*1024)) 
    44       return itos(i/(1024*1024*1024))+"G (" + itos(i) + "B)"; 
    45     if (i > (1024*1024)) 
    46       return itos(i/(1024*1024))+"M (" + itos(i) + "B)"; 
    47     if (i > (1024)) 
    48       return itos(i/(1024))+"K (" + itos(i) + "B)"; 
    49     return itos(i>>24)+"B"; 
    50   } 
     117#define BKMG_RANGE "BKMGTP" 
     118#define BKMG_SIZE 5 
     119 
     120  inline std::string itos_as_BKMG(unsigned __int64 i) { 
     121    unsigned __int64 cpy = i; 
     122    char postfix[] = BKMG_RANGE; 
     123    int idx = 0; 
     124    while ((cpy > 1024)&&(idx<BKMG_SIZE)) { 
     125      cpy/=1024; 
     126      idx++; 
     127    } 
     128    std::string ret = itos(cpy); 
     129    ret += postfix[idx]; 
     130    if (idx > 0) { 
     131      ret += " (" + itos(i) + "B)"; 
     132    } 
     133    return ret; 
     134  } 
     135 
     136  typedef std::list<std::string> splitList; 
     137  inline splitList splitEx(std::string str, std::string key) { 
     138    splitList ret; 
     139    std::string::size_type pos = 0, lpos = 0; 
     140    while ((pos = str.find(key, pos)) !=  std::string::npos) { 
     141      ret.push_back(str.substr(lpos, pos-lpos)); 
     142      lpos = ++pos; 
     143    } 
     144    if (lpos < str.size()) 
     145      ret.push_back(str.substr(lpos)); 
     146    return ret; 
     147  } 
     148 
    51149  inline std::pair<std::string,std::string> split(std::string str, std::string key) { 
    52150    std::string::size_type pos = str.find(key); 
     
    64162    return token(buffer.substr(0, pos-1), buffer.substr(++pos)); 
    65163  } 
     164 
     165 
     166  template<class _E> 
     167  struct blind_traits : public std::char_traits<_E> 
     168  { 
     169    static bool eq(const _E& x, const _E& y) { 
     170      return tolower( x ) == tolower( y );  
     171    } 
     172    static bool lt(const _E& x, const _E& y) { 
     173      return tolower( x ) < tolower( y );  
     174    } 
     175 
     176    static int compare(const _E *x, const _E *y, size_t n) {  
     177      return strnicmp( x, y, n ); 
     178    } 
     179 
     180    //  There's no memichr(), so we roll our own.  It ain't rocket science. 
     181    static const _E * __cdecl find(const _E *buf, size_t len, const _E& ch) { 
     182      //  Jerry says that x86s have special mojo for memchr(), so the  
     183      //  memchr() calls end up being reasonably efficient in practice. 
     184      const _E *pu = (const _E *)memchr(buf, ch, len); 
     185      const _E *pl = (const _E *)memchr(buf, tolower( ch ), len); 
     186      if ( ! pu ) 
     187        return pl;  //  Might be NULL; if so, NULL's the word. 
     188      else if ( ! pl ) 
     189        return pu; 
     190      else 
     191        //  If either one was NULL, we return the other; if neither is  
     192        //  NULL, we return the lesser of the two. 
     193        return ( pu < pl ) ? pu : pl; 
     194    } 
     195 
     196    //  I'm reasonably sure that this is eq() for wide characters.  Maybe. 
     197    static bool eq_int_type(const int_type& ch1, const int_type& ch2) {  
     198      return char_traits<_E>::eq_int_type( tolower( ch1 ), tolower( ch2 ) );  
     199    } 
     200  }; 
     201 
     202  //  And here's our case-blind string class. 
     203  typedef std::basic_string<char, blind_traits<char>, std::allocator<char> >  blindstr; 
     204 
    66205#ifdef _DEBUG 
    67206  inline void test_getToken(std::string in1, char in2, std::string out1, std::string out2) { 
     
    82221    test_getToken("foo&bar&test", '&', "foo", "bar&test"); 
    83222  } 
     223 
     224  inline void test_replace(std::string source, std::string replace, std::string with, std::string out) { 
     225    std::cout << "strEx::test_replace(" << source << ", " << replace << ", " << with << ") : "; 
     226    std::string s = source; 
     227    strEx::replace(s, replace, with); 
     228    if (s == out) 
     229      std::cout << "Succeeded" << std::endl; 
     230    else 
     231      std::cout << "Failed [" << s << "=" << out << "]" << std::endl; 
     232  } 
     233  inline void run_test_replace() { 
     234    test_replace("", "", "", ""); 
     235    test_replace("foo", "", "", "foo"); 
     236    test_replace("foobar", "foo", "", "bar"); 
     237    test_replace("foobar", "foo", "bar", "barbar"); 
     238  } 
     239 
    84240#endif 
    85241} 
  • /trunk/include/PDHCollectors.h

    r3 r30  
    44 
    55namespace PDHCollectors { 
    6   class StaticPDHCounterListener : public PDH::PDHCounterListener { 
     6  class StaticPDHCounterListenerInt : public PDH::PDHCounterListener { 
    77    __int64 value_; 
    88  public: 
     
    1919    } 
    2020  }; 
     21  class StaticPDHCounterListenerDouble : public PDH::PDHCounterListener { 
     22    double value_; 
     23  public: 
     24    virtual void collect(const PDH::PDHCounter &counter) { 
     25      setValue(counter.getDoubleValue()); 
     26    } 
     27    void attach(const PDH::PDHCounter &counter){} 
     28    void detach(const PDH::PDHCounter &counter){} 
     29    void setValue(double value) { 
     30      value_ = value; 
     31    } 
     32    double getValue() const { 
     33      return value_; 
     34    } 
     35  }; 
    2136 
    2237 
     
    2641    unsigned int current; 
    2742  public: 
     43    RoundINTPDHBufferListener() : buffer(NULL), length(0), current(0) {} 
    2844    RoundINTPDHBufferListener(int length_) : length(length_), current(0) { 
    2945      buffer = new int[length]; 
     
    3450      delete [] buffer; 
    3551    } 
     52     
     53    /** 
     54     * Resize the buffer to a new length 
     55     * 
     56     * @todo Make this copy the old buffer if there is one. 
     57     * 
     58     * @param newLength The new length 
     59     */ 
     60    void resize(int newLength) { 
     61      delete [] buffer; 
     62 
     63      current = 0; 
     64      length = newLength; 
     65 
     66      buffer = new int[length]; 
     67      for (unsigned int i=0; i<length;i++) 
     68        buffer[i] = 0; 
     69         
     70    } 
    3671    virtual void collect(const PDH::PDHCounter &counter) { 
    3772      pushValue(static_cast<int>(counter.getInt64Value())); 
     
    4075    void detach(const PDH::PDHCounter &counter){} 
    4176    void pushValue(int value) { 
     77      if (buffer == NULL) 
     78        return; 
     79      if (current >= length) 
     80        return; 
    4281      buffer[current++] = value; 
    4382      if (current >= length) 
     
    61100      return static_cast<int>(ret/backItems); 
    62101    } 
     102    inline unsigned int getLength() const { 
     103      return length; 
     104    } 
    63105  }; 
    64106 
  • /trunk/include/thread.h

    r13 r30  
    1 // Thread.h: interface for the Thread class. 
    2 // 
    3 ////////////////////////////////////////////////////////////////////// 
    4  
    51#pragma once 
    62 
     3#include <process.h> 
     4#include <Mutex.h> 
    75 
    8 /** 
    9  * @ingroup NSClientCompat 
    10  * Simple unnamed mutex to handle thread exit wait (used by the Thread class below) 
    11  * 
    12  * @version 1.0 
    13  * first version 
    14  * 
    15  * @date 02-13-2005 
    16  * 
    17  * @author mickem 
    18  * 
    19  * @par license 
    20  * This code is absolutely free to use and modify. The code is provided "as is" with 
    21  * no expressed or implied warranty. The author accepts no liability if it causes 
    22  * any damage to your computer, causes your pet to fall ill, increases baldness 
    23  * or makes your car start emitting strange noises when you start it up. 
    24  * This code has no bugs, just undocumented features! 
    25  *  
    26  */ 
    27 class UnnamedMutex { 
    28 private: 
    29   HANDLE hMutex_; 
     6class ThreadException { 
    307public: 
    31   /** 
    32    * Default c-tor. 
    33    * Creates an unnamed mutex with a given owner status 
    34    * @param owner true if we want to become owner of the mutex 
    35    */ 
    36   UnnamedMutex(bool owner = false) { 
    37     hMutex_ = ::CreateMutex(NULL, owner, NULL); 
    38   } 
    39   /** 
    40    * Default d-tor. 
    41    * Closes the mutex 
    42    */ 
    43   virtual ~UnnamedMutex() { 
    44     CloseHandle(hMutex_); 
    45   } 
    46   /** 
    47    * Wait for the mutex or timeout in dwMilliseconds milliseconds. 
    48    * @param dwMilliseconds The timeout value 
    49    * @return status 
    50    */ 
    51   DWORD wait(DWORD dwMilliseconds = 0L) { 
    52     return ::WaitForSingleObject(hMutex_, dwMilliseconds); 
    53   } 
    54   /** 
    55    * Release the mutex 
    56    * @return status 
    57    */ 
    58   BOOL free() { 
    59     return ::ReleaseMutex(hMutex_); 
     8  std::string e_; 
     9  ThreadException(std::string e) : e_(e) { 
     10    std::cout << e << std::endl; 
    6011  } 
    6112}; 
     
    8839private: 
    8940  HANDLE hThread_;    // Thread handle 
    90   DWORD dwThreadID_;    // Thread ID 
    91   UnnamedMutex endMutext; // mutex to wait for end of thread 
    9241  T* pObject_;      // Wrapped object 
     42  HANDLE hStopEvent_;   // Event to signal that the thread has stopped 
     43  HANDLE hMutex_;     // Mutex to protect internal data 
     44 
    9345 
    9446  typedef struct thread_param { 
    95     Thread* core; 
    96     T *instance; 
    97     LPVOID lpParam; 
     47    HANDLE hStopEvent;  // The stop event to signal when thread dies 
     48    T *instance;    // The thread instance object 
     49    LPVOID lpParam;   // The optional argument to the thread 
     50    Thread *pCore; 
    9851  } thread_param; 
    9952 
     
    10356   * Sets up default values 
    10457   */ 
    105   Thread() : endMutext(false), hThread_(NULL), dwThreadID_(0), pObject_(NULL) {} 
     58  Thread() : hThread_(NULL), pObject_(NULL), hStopEvent_(NULL) { 
     59    hMutex_ = CreateMutex(NULL, FALSE, NULL); 
     60    assert(hMutex_ != NULL); 
     61  } 
    10662  /** 
    10763   * Default d-tor. 
     
    11066   */ 
    11167  virtual ~Thread() { 
    112     if (hThread_) 
    113       CloseHandle(hThread_); 
     68    { 
     69      MutexLock mutex(hMutex_, 5000L); 
     70      if (!mutex.hasMutex()) { 
     71        throw ThreadException("Could not retrieve mutex when killing thread, we are fucked..."); 
     72      } 
     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; 
    11483  } 
    11584 
     
    12291   * @return exit status 
    12392   */ 
    124   static DWORD WINAPI threadProc(LPVOID lpParameter) { 
     93  static void threadProc(LPVOID lpParameter) { 
    12594    thread_param* param = static_cast<thread_param*>(lpParameter); 
    12695    T* instance = param->instance; 
    127     Thread *core = param->core; 
     96    HANDLE hStopEvent = param->hStopEvent; 
    12897    LPVOID lpParam = param->lpParam; 
     98    Thread *pCore = param->pCore; 
    12999    delete param; 
    130     core->endMutext.wait(); 
    131     DWORD ret = instance->threadProc(lpParam); 
    132     core->endMutext.free(); 
    133     return 0; 
     100 
     101    instance->threadProc(lpParam); 
     102    pCore->terminate(); 
     103    SetEvent(hStopEvent); 
     104    _endthread(); 
    134105  } 
    135106 
     
    142113   * @param lpParam An argument to the thread 
    143114   * @return An instance of the thread object. 
    144    * @throws char 
    145115   * @bug the object return thing is *unsafe* and should be changed (if the thread is terminated that pointer is invalidated without any signal). 
    146116   */ 
    147   T* createThread(LPVOID lpParam = NULL) { 
    148     if (pObject_) 
    149       throw "Could not create thread"; 
    150     pObject_ = new T; 
    151     thread_param* param = new thread_param; 
    152     param->instance = pObject_; 
    153     param->core = this; 
    154     param->lpParam = lpParam; 
    155     hThread_ = ::CreateThread(NULL,0,threadProc,reinterpret_cast<VOID*>(param),0,&dwThreadID_); 
    156     return pObject_; 
     117  void createThread(LPVOID lpParam = NULL) { 
     118    thread_param* param = NULL; 
     119    { 
     120      MutexLock mutex(hMutex_, 5000L); 
     121      if (!mutex.hasMutex()) { 
     122        throw ThreadException("Could not retrieve mutex, thread not started..."); 
     123      } 
     124      if (pObject_) { 
     125        throw ThreadException("Thread already started, thread not started..."); 
     126      } 
     127      assert(hStopEvent_ == NULL); 
     128      param = new thread_param; 
     129      param->instance = pObject_ = new T; 
     130      param->hStopEvent = hStopEvent_ = CreateEvent(NULL, TRUE, FALSE, NULL); 
     131      param->lpParam = lpParam; 
     132      param->pCore = this; 
     133    } 
     134    hThread_ = reinterpret_cast<HANDLE>(::_beginthread(threadProc, 0, reinterpret_cast<VOID*>(param))); 
    157135  } 
    158136  /** 
     
    162140   */ 
    163141  bool exitThread(const unsigned int delay = 5000L) { 
    164     if (!pObject_) 
    165       throw "Could not terminate thread, has not been started yet..."; 
    166     pObject_->exitThread(); 
    167     DWORD dwWaitResult = endMutext.wait(delay); 
     142    DWORD dwWaitResult = -1; 
     143    { 
     144      MutexLock mutex(hMutex_, 5000L); 
     145      if (!mutex.hasMutex()) { 
     146        throw ThreadException("Could not retrieve mutex, thread not stopped..."); 
     147      } 
     148      if (!pObject_) 
     149        return true; 
     150      assert(hStopEvent_ != NULL); 
     151      pObject_->exitThread(); 
     152    } 
     153    dwWaitResult = WaitForSingleObject(hStopEvent_, delay); 
    168154    switch (dwWaitResult) { 
    169155      // The thread got mutex ownership. 
    170156      case WAIT_OBJECT_0: 
    171         // TODO: Potential race condition if multipåle threads try to terminate the thread... 
    172         delete pObject_; 
    173         pObject_ = NULL; 
    174         endMutext.free(); 
    175157        return true; 
    176         // Cannot get mutex ownership due to time-out. 
     158        // Did not get a signal due to time-out. 
    177159      case WAIT_TIMEOUT:  
    178160        return false;  
    179  
    180         // Got ownership of the abandoned mutex object. 
     161        // Never got a signal. 
    181162      case WAIT_ABANDONED:  
    182163        return false;  
     
    184165    return false; 
    185166  } 
     167  bool hasActiveThread() const { 
     168    MutexLock mutex(hMutex_, 5000L); 
     169    if (!mutex.hasMutex()) { 
     170      throw ThreadException("Could not retrieve mutex, thread not stopped..."); 
     171    } 
     172    return pObject_ != NULL; 
     173  } 
     174  const T* getThreadConst() const { 
     175    MutexLock mutex(hMutex_, 5000L); 
     176    if (!mutex.hasMutex()) { 
     177      throw ThreadException("Could not retrieve mutex, thread not stopped..."); 
     178    } 
     179    return pObject_; 
     180  } 
     181  T* getThread() { 
     182    MutexLock mutex(hMutex_, 5000L); 
     183    if (!mutex.hasMutex()) { 
     184      throw ThreadException("Could not retrieve mutex, thread not stopped..."); 
     185    } 
     186    return pObject_; 
     187  } 
     188private: 
     189  void terminate() { 
     190    MutexLock mutex(hMutex_, 5000L); 
     191    if (!mutex.hasMutex()) { 
     192      throw ThreadException("Could not retrieve mutex, thread not stopped..."); 
     193    } 
     194    delete pObject_; 
     195    pObject_ = NULL; 
     196    hThread_ = NULL; 
     197  } 
    186198}; 
    187199 
  • /trunk/include/arrayBuffer.h

    r20 r28  
    11#pragma once 
    22 
    3  
     3/** 
     4 * @ingroup NSClient++ 
     5 * 
     6 * A simple namespace (wrapper) to wrap functions to manipulate an array buffer. 
     7 * 
     8 * @version 1.0 
     9 * first version 
     10 * 
     11 * @date 05-14-2005 
     12 * 
     13 * @author mickem 
     14 * 
     15 * @par license 
     16 * This code is absolutely free to use and modify. The code is provided "as is" with 
     17 * no expressed or implied warranty. The author accepts no liability if it causes 
     18 * any damage to your computer, causes your pet to fall ill, increases baldness 
     19 * or makes your car start emitting strange noises when you start it up. 
     20 * This code has no bugs, just undocumented features! 
     21 *  
     22 * @todo  
     23 * 
     24 * @bug  
     25 * 
     26 */ 
    427namespace arrayBuffer { 
    5  
    6  
    7   std::list<std::string> arrayBuffer2list(const unsigned int argLen, char **argument); 
    8   char ** list2arrayBuffer(const std::list<std::string> lst, unsigned int &argLen); 
     28  typedef std::list<std::string> arrayList; 
     29  arrayList arrayBuffer2list(const unsigned int argLen, char **argument); 
     30  char ** list2arrayBuffer(const arrayList lst, unsigned int &argLen); 
    931  char ** split2arrayBuffer(const char* buffer, char splitChar, unsigned int &argLen); 
    1032  char ** split2arrayBuffer(const std::string buffer, char splitChar, unsigned int &argLen); 
     
    1335  void destroyArrayBuffer(char **argument, const unsigned int argLen); 
    1436 
    15  
    1637#ifdef _DEBUG 
    1738  void test_createEmptyArrayBuffer(); 
    1839  void test_split2arrayBuffer_str(std::string buffer, char splitter, int OUT_argLen); 
    1940  void test_split2arrayBuffer_char(char* buffer, char splitter, int OUT_argLen); 
    20  
    2141  void run_testArrayBuffer(); 
    2242#endif 
    23  
    2443} 
  • /trunk/include/PDHCounter.h

    r13 r30  
    5050      PDH_STATUS status; 
    5151      assert(hQuery != NULL); 
    52       assert(hCounter_ == NULL); 
     52      if (hCounter_ != NULL) 
     53        throw PDHException("addToQuery failed (already opened): " + name_); 
    5354      if (listener_) 
    5455        listener_->attach(*this); 
    5556      if ((status = PdhAddCounter(hQuery, name_.c_str(), 0, &hCounter_)) != ERROR_SUCCESS)  
    56         throw PDHException("PdhOpenQuery failed", status); 
     57        throw PDHException("PdhOpenQuery failed: " + name_, status); 
    5758      assert(hCounter_ != NULL); 
    5859    } 
    5960    void remove() { 
    60       assert(hCounter_ != NULL); 
     61      if (hCounter_ == NULL) 
     62        return; 
    6163      PDH_STATUS status; 
    6264      if (listener_) 
     
    6769    } 
    6870    void collect() { 
    69       assert(hCounter_ != NULL); 
     71      if (hCounter_ == NULL) 
     72        return; 
    7073      PDH_STATUS status; 
    7174      if ((status = PdhGetFormattedCounterValue(hCounter_, PDH_FMT_LARGE , NULL, &data_)) != ERROR_SUCCESS) 
     
    7376      if (listener_) 
    7477        listener_->collect(*this); 
     78    } 
     79    double getDoubleValue() const { 
     80      return data_.doubleValue; 
    7581    } 
    7682    __int64 getInt64Value() const { 
     
    125131        throw PDHException("PdhCloseQuery failed", status); 
    126132      hQuery_ = NULL; 
     133      for (CounterList::iterator it = counters_.begin(); it != counters_.end(); it++) { 
     134        delete (*it); 
     135      } 
     136      counters_.clear(); 
    127137    } 
    128138 
  • /trunk/include/NSCAPI.h

    r18 r30  
    2222  } errorReturn; 
    2323#else 
    24   const int returnCRIT = 2; 
    2524  const int returnOK = 0; 
    2625  const int returnWARN = 1; 
     26  const int returnCRIT = 2; 
    2727  const int returnUNKNOWN = 4; 
    2828  const int returnInvalidBufferLen = -2; 
     
    3838#endif 
    3939 
     40  const int xor = 1; 
    4041 
    4142  // Various message Types 
  • /trunk/include/NSCHelper.cpp

    r20 r30  
    66 
    77 
     8#ifdef DEBUG 
    89/** 
    910* Wrap a return string. 
     
    1516* @return NSCAPI::success unless the buffer is to short then it will be NSCAPI::invalidBufferLen 
    1617*/ 
    17 #ifdef DEBUG 
    1818NSCAPI::nagiosReturn NSCHelper::wrapReturnString(char *buffer, unsigned int bufLen, std::string str, NSCAPI::nagiosReturn defaultReturnCode /* = NSCAPI::success */) { 
    1919  if (str.length() >= bufLen) 
     
    2222  return defaultReturnCode; 
    2323} 
     24/** 
     25* Wrap a return string. 
     26* This function copies a string to a char buffer making sure the buffer has the correct length. 
     27* 
     28* @param *buffer Buffer to copy the string to. 
     29* @param bufLen Length of the buffer 
     30* @param str Th string to copy 
     31* @return NSCAPI::success unless the buffer is to short then it will be NSCAPI::invalidBufferLen 
     32*/ 
    2433NSCAPI::errorReturn NSCHelper::wrapReturnString(char *buffer, unsigned int bufLen, std::string str, NSCAPI::errorReturn defaultReturnCode /* = NSCAPI::success */) { 
    2534  if (str.length() >= bufLen) 
     
    2938} 
    3039#else 
     40/** 
     41* Wrap a return string. 
     42* This function copies a string to a char buffer making sure the buffer has the correct length. 
     43* 
     44* @param *buffer Buffer to copy the string to. 
     45* @param bufLen Length of the buffer 
     46* @param str Th string to copy 
     47* @param defaultReturnCode The default return code 
     48* @return NSCAPI::success unless the buffer is to short then it will be NSCAPI::invalidBufferLen 
     49*/ 
    3150int NSCHelper::wrapReturnString(char *buffer, unsigned int bufLen, std::string str, int defaultReturnCode ) { 
    3251  // @todo deprecate this 
    3352  if (str.length() >= bufLen) 
    34     return -1; 
     53    return NSCAPI::isInvalidBufferLen; 
    3554  strncpy(buffer, str.c_str(), bufLen); 
    3655  return defaultReturnCode; 
     
    6079  return "unknown"; 
    6180} 
     81/** 
     82 * Translate a return code into the corresponding string 
     83 * @param returnCode  
     84 * @return  
     85 */ 
    6286std::string NSCHelper::translateReturn(NSCAPI::nagiosReturn returnCode) { 
    6387  if (returnCode == NSCAPI::returnOK) 
     
    77101  lpNSAPIGetApplicationName fNSAPIGetApplicationName = NULL; 
    78102  lpNSAPIGetApplicationVersionStr fNSAPIGetApplicationVersionStr = NULL; 
     103  lpNSAPIGetSettingsSection fNSAPIGetSettingsSection = NULL; 
    79104  lpNSAPIGetSettingsString fNSAPIGetSettingsString = NULL; 
    80105  lpNSAPIGetSettingsInt fNSAPIGetSettingsInt = NULL; 
     
    82107  lpNSAPIStopServer fNSAPIStopServer = NULL; 
    83108  lpNSAPIInject fNSAPIInject = NULL; 
     109  lpNSAPICheckLogMessages fNSAPICheckLogMessages = NULL; 
     110  lpNSAPIEncrypt fNSAPIEncrypt = NULL; 
     111  lpNSAPIDecrypt fNSAPIDecrypt = NULL; 
    84112} 
    85113 
     
    98126 */ 
    99127void NSCModuleHelper::Message(int msgType, std::string file, int line, std::string message) { 
    100   if (!fNSAPIMessage) 
    101     throw NSCMHExcpetion("NSCore has not been initiated..."); 
    102   return fNSAPIMessage(msgType, file.c_str(), line, message.c_str()); 
     128  if (fNSAPIMessage) { 
     129    if ((msgType == NSCAPI::debug) && (!logDebug())) 
     130      return; 
     131    return fNSAPIMessage(msgType, file.c_str(), line, message.c_str()); 
     132  } 
     133  else 
     134    std::cout << "NSCore not loaded..." << std::endl << message << std::endl; 
    103135} 
    104136/** 
     
    108140 * @throws NSCMHExcpetion When core pointer set is unavailable or an unknown inject error occurs. 
    109141 */ 
     142 
     143/** 
     144 * Inject a request command in the core (this will then be sent to the plug-in stack for processing) 
     145 * @param command Command to inject 
     146 * @param argLen The length of the argument buffer 
     147 * @param **argument The argument buffer 
     148 * @param *returnMessageBuffer Buffer to hold the returned message 
     149 * @param returnMessageBufferLen Length of returnMessageBuffer 
     150 * @param *returnPerfBuffer Buffer to hold the returned performance data 
     151 * @param returnPerfBufferLen returnPerfBuffer 
     152 * @return The returned status of the command 
     153 */ 
    110154NSCAPI::nagiosReturn NSCModuleHelper::InjectCommandRAW(const char* command, const unsigned int argLen, char **argument, char *returnMessageBuffer, unsigned int returnMessageBufferLen, char *returnPerfBuffer, unsigned int returnPerfBufferLen)  
    111155{ 
     
    114158  return fNSAPIInject(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen); 
    115159} 
     160/** 
     161 * Inject a request command in the core (this will then be sent to the plug-in stack for processing) 
     162 * @param command Command to inject (password should not be included. 
     163 * @param argLen The length of the argument buffer 
     164 * @param **argument The argument buffer 
     165 * @param message The return message buffer 
     166 * @param perf The return performance data buffer 
     167 * @return The return of the command 
     168 */ 
    116169NSCAPI::nagiosReturn NSCModuleHelper::InjectCommand(const char* command, const unsigned int argLen, char **argument, std::string & message, std::string & perf)  
    117170{ 
     
    149202 * Parses a string by splitting and makes the array and also manages return buffers and such. 
    150203 * @param command The command to execute 
    151  * @param buffer The buffer to splitwww.ikea.se 
    152  
     204 * @param buffer The buffer to split 
    153205 * @param splitChar The char to use as splitter 
     206 * @param message The return message buffer 
     207 * @param perf The return performance data buffer 
    154208 * @return The result of the command 
    155209 */ 
     
    168222  return ret; 
    169223} 
     224/** 
     225 * A wrapper around the InjetCommand that is simpler to use. 
     226 * @param command The command to execute 
     227 * @param buffer The buffer to split 
     228 * @param splitChar The char to use as splitter 
     229 * @param message The return message buffer 
     230 * @param perf The return performance data buffer 
     231 * @return The result of the command 
     232 */ 
    170233NSCAPI::nagiosReturn NSCModuleHelper::InjectSplitAndCommand(const std::string command, const std::string buffer, char splitChar, std::string & message, std::string & perf) 
    171234{ 
     
    213276} 
    214277/** 
     278 * Get a section of settings strings 
     279 * @param section The section to retrieve 
     280 * @return The keys in the section 
     281 */ 
     282std::list<std::string> NSCModuleHelper::getSettingsSection(std::string section) { 
     283  if (!fNSAPIGetSettingsSection) 
     284    throw NSCMHExcpetion("NSCore has not been initiated..."); 
     285  char ** aBuffer = NULL; 
     286  unsigned int argLen = 0; 
     287  if (fNSAPIGetSettingsSection(section.c_str(), &aBuffer, &argLen) != NSCAPI::isSuccess) { 
     288    throw NSCMHExcpetion("Settings could not be retrieved."); 
     289  } 
     290  std::list<std::string> ret = arrayBuffer::arrayBuffer2list(argLen, aBuffer); 
     291  arrayBuffer::destroyArrayBuffer(aBuffer, argLen); 
     292  return ret; 
     293} 
     294/** 
    215295 * Retrieve an int from the settings subsystem (INI-file) 
    216296 * Might possibly be located in the registry in the future. 
     
    228308} 
    229309/** 
     310 * Returns the biggest of the two states 
     311 * STATE_UNKNOWN < STATE_OK < STATE_WARNING < STATE_CRITICAL 
     312 * @param a  
     313 * @param b  
     314 * @return  
     315 */ 
     316NSCAPI::nagiosReturn NSCHelper::maxState(NSCAPI::nagiosReturn a, NSCAPI::nagiosReturn b) 
     317{ 
     318  if (a == NSCAPI::returnCRIT || b == NSCAPI::returnCRIT) 
     319    return NSCAPI::returnCRIT; 
     320  else if (a == NSCAPI::returnWARN || b == NSCAPI::returnWARN) 
     321    return NSCAPI::returnWARN; 
     322  else if (a == NSCAPI::returnOK || b == NSCAPI::returnOK) 
     323    return NSCAPI::returnOK; 
     324  else if (a == NSCAPI::returnUNKNOWN || b == NSCAPI::returnUNKNOWN) 
     325    return NSCAPI::returnUNKNOWN; 
     326  return NSCAPI::returnUNKNOWN; 
     327} 
     328/** 
    230329 * Retrieve the application name (in human readable format) from the core. 
    231330 * @return A string representing the application name. 
     
    261360  return ret; 
    262361} 
     362 
     363 
     364bool NSCModuleHelper::logDebug() { 
     365  typedef enum status {unknown, debug, nodebug }; 
     366  static status d = unknown; 
     367  if (d == unknown) { 
     368    if (checkLogMessages(debug)== NSCAPI::istrue) 
     369      d = debug; 
     370    else 
     371      d = nodebug; 
     372  } 
     373  return (d == debug); 
     374} 
     375 
     376 
     377 
     378 
     379std::string NSCModuleHelper::Encrypt(std::string str, unsigned int algorithm) { 
     380  if (!fNSAPIEncrypt) 
     381    throw NSCMHExcpetion("NSCore has not been initiated..."); 
     382  unsigned int len = 0; 
     383  fNSAPIEncrypt(algorithm, str.c_str(), str.size(), NULL, &len); 
     384  len+=2; 
     385  char *buf = new char[len+1]; 
     386  NSCAPI::errorReturn ret = fNSAPIEncrypt(algorithm, str.c_str(), str.size(), buf, &len); 
     387  if (ret == NSCAPI::isSuccess) { 
     388    std::string ret = buf; 
     389    delete [] buf; 
     390    return ret; 
     391  } 
     392  return ""; 
     393} 
     394std::string NSCModuleHelper::Decrypt(std::string str, unsigned int algorithm) { 
     395  if (!fNSAPIDecrypt) 
     396    throw NSCMHExcpetion("NSCore has not been initiated..."); 
     397  unsigned int len = 0; 
     398  fNSAPIDecrypt(algorithm, str.c_str(), str.size(), NULL, &len); 
     399  len+=2; 
     400  char *buf = new char[len+1]; 
     401  NSCAPI::errorReturn ret = fNSAPIDecrypt(algorithm, str.c_str(), str.size(), buf, &len); 
     402  if (ret == NSCAPI::isSuccess) { 
     403    std::string ret = buf; 
     404    delete [] buf; 
     405    return ret; 
     406  } 
     407  return ""; 
     408} 
     409 
     410 
     411bool NSCModuleHelper::checkLogMessages(int type) { 
     412  if (!fNSAPICheckLogMessages) 
     413    throw NSCMHExcpetion("NSCore has not been initiated..."); 
     414  return fNSAPICheckLogMessages(type) == NSCAPI::istrue; 
     415} 
    263416/** 
    264417 * Retrieve the application version as a string (in human readable format) from the core. 
     
    276429} 
    277430 
    278 ////////////////////////////////////////////////////////////////////////// 
    279 // Module helper functions 
    280 ////////////////////////////////////////////////////////////////////////// 
    281431namespace NSCModuleWrapper { 
    282432  HINSTANCE hModule_ = NULL; 
     
    321471  NSCModuleHelper::fNSAPIGetSettingsInt = (NSCModuleHelper::lpNSAPIGetSettingsInt)f("NSAPIGetSettingsInt"); 
    322472  NSCModuleHelper::fNSAPIGetSettingsString = (NSCModuleHelper::lpNSAPIGetSettingsString)f("NSAPIGetSettingsString"); 
     473  NSCModuleHelper::fNSAPIGetSettingsSection = (NSCModuleHelper::lpNSAPIGetSettingsSection)f("NSAPIGetSettingsSection"); 
    323474  NSCModuleHelper::fNSAPIMessage = (NSCModuleHelper::lpNSAPIMessage)f("NSAPIMessage"); 
    324475  NSCModuleHelper::fNSAPIStopServer = (NSCModuleHelper::lpNSAPIStopServer)f("NSAPIStopServer"); 
    325476  NSCModuleHelper::fNSAPIInject = (NSCModuleHelper::lpNSAPIInject)f("NSAPIInject"); 
    326477  NSCModuleHelper::fNSAPIGetBasePath = (NSCModuleHelper::lpNSAPIGetBasePath)f("NSAPIGetBasePath"); 
     478  NSCModuleHelper::fNSAPICheckLogMessages = (NSCModuleHelper::lpNSAPICheckLogMessages)f("NSAPICheckLogMessages"); 
     479  NSCModuleHelper::fNSAPIDecrypt = (NSCModuleHelper::lpNSAPIDecrypt)f("NSAPIDecrypt"); 
     480  NSCModuleHelper::fNSAPIEncrypt = (NSCModuleHelper::lpNSAPIEncrypt)f("NSAPIEncrypt"); 
    327481  return NSCAPI::isSuccess; 
    328482} 
     
    373527/** 
    374528 * Wrap the HandleCommand call 
    375  * @param retStr The string to return to the core 
    376  * @param *returnBuffer A buffer to copy the return string to 
    377  * @param returnBufferLen length of returnBuffer 
    378  * @return copy status or NSCAPI::isfalse if retStr is empty 
     529 * @param retResult The returned result 
     530 * @param retMessage The returned message 
     531 * @param retPerformance The returned performance data 
     532 * @param *returnBufferMessage The return message buffer 
     533 * @param returnBufferMessageLen The return message buffer length 
     534 * @param *returnBufferPerf The return perfomance data buffer 
     535 * @param returnBufferPerfLen The return perfomance data buffer length 
     536 * @return the return code 
    379537 */ 
    380538NSCAPI::nagiosReturn NSCModuleWrapper::wrapHandleCommand(NSCAPI::nagiosReturn retResult, const std::string retMessage, const std::string retPerformance, char *returnBufferMessage, unsigned int returnBufferMessageLen, char *returnBufferPerf, unsigned int returnBufferPerfLen) { 
  • /trunk/include/ServiceCmd.cpp

    r3 r28  
    6767   * Stars the service. 
    6868   * 
    69    * @param szName  
     69   * @param name The name of the service to start  
    7070   * 
    7171   * @author mickem 
     
    112112   * Stops and removes the service 
    113113   * 
    114    * @param szName  
     114   * @param name The name of the service to uninstall  
    115115   * 
    116116   * @author mickem 
     
    145145   * Stops the service 
    146146   * 
    147    * @param szName  
     147   * @param name The name of the serive to stop  
    148148   * 
    149149   * @author MickeM 
  • /trunk/include/NSCHelper.h

    r20 r30  
    1818  std::string translateMessageType(NSCAPI::messageTypes msgType); 
    1919  std::string translateReturn(NSCAPI::nagiosReturn returnCode); 
    20  
    21   /* 
    22   / * ************************************************************************** 
    23   * max_state(STATE_x, STATE_y) 
    24   * compares STATE_x to  STATE_y and returns result based on the following 
    25   * STATE_UNKNOWN < STATE_OK < STATE_WARNING < STATE_CRITICAL 
    26   * 
    27   * Note that numerically the above does not hold 
    28   **************************************************************************** / 
    29  
    30   int 
    31     max_state (int a, int b) 
    32   { 
    33     if (a == STATE_CRITICAL || b == STATE_CRITICAL) 
    34       return STATE_CRITICAL; 
    35     else if (a == STATE_WARNING || b == STATE_WARNING) 
    36       return STATE_WARNING; 
    37     else if (a == STATE_OK || b == STATE_OK) 
    38       return STATE_OK; 
    39     else if (a == STATE_UNKNOWN || b == STATE_UNKNOWN) 
    40       return STATE_UNKNOWN; 
    41     else if (a == STATE_DEPENDENT || b == STATE_DEPENDENT) 
    42       return STATE_DEPENDENT; 
    43     else 
    44       return max (a, b); 
    45   } 
    46   @bug Use this scheme instead!! 
    47 */ 
    48  
    49  
    50   inline void escalteReturnCode(NSCAPI::nagiosReturn &currentReturnCode, NSCAPI::nagiosReturn newReturnCode) { 
    51     if (newReturnCode == NSCAPI::returnCRIT) 
    52       currentReturnCode = NSCAPI::returnCRIT; 
    53     else if ((newReturnCode == NSCAPI::returnWARN) && (currentReturnCode != NSCAPI::returnCRIT) ) 
    54       currentReturnCode = NSCAPI::returnWARN; 
    55     else if ((newReturnCode == NSCAPI::returnUNKNOWN)  
    56       && (currentReturnCode != NSCAPI::returnCRIT)  
    57       && (currentReturnCode != NSCAPI::returnWARN) ) 
    58       currentReturnCode = NSCAPI::returnUNKNOWN; 
    59   } 
     20  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  } 
     27 
     28#ifdef DEBUG 
     29  inline NSCAPI::nagiosReturn int2nagios(int code) { 
     30    if (code == 0) 
     31      return NSCAPI::returnOK; 
     32    if (code == 1) 
     33      return NSCAPI::returnWARN; 
     34    if (code == 2) 
     35      return NSCAPI::returnCRIT; 
     36    if (code == 4) 
     37      return NSCAPI::returnUNKNOWN; 
     38    throw "@fixme bad code"; 
     39  } 
     40  inline int nagios2int(NSCAPI::nagiosReturn code) { 
     41    if (code == NSCAPI::returnOK) 
     42      return 0; 
     43    if (code == NSCAPI::returnWARN) 
     44      return 1; 
     45    if (code == NSCAPI::returnCRIT) 
     46      return 2; 
     47    if (code == NSCAPI::returnUNKNOWN) 
     48      return 4; 
     49    throw "@fixme bad code"; 
     50  } 
     51#else 
     52  inline NSCAPI::nagiosReturn int2nagios(int code) { 
     53    return code; 
     54  } 
     55  inline int nagios2int(NSCAPI::nagiosReturn code) { 
     56    return code; 
     57  } 
     58#endif 
    6059  inline void escalteReturnCodeToCRIT(NSCAPI::nagiosReturn &currentReturnCode) { 
    6160    currentReturnCode = NSCAPI::returnCRIT; 
     
    6564      currentReturnCode = NSCAPI::returnWARN; 
    6665  } 
    67  
    6866}; 
    6967 
     
    8179  typedef NSCAPI::errorReturn (*lpNSAPIGetSettingsString)(const char*,const char*,const char*,char*,unsigned int); 
    8280  typedef NSCAPI::errorReturn (*lpNSAPIGetSettingsInt)(const char*, const char*, int); 
     81  typedef NSCAPI::errorReturn (*lpNSAPIGetSettingsSection)(const char*, char***, unsigned int *); 
    8382  typedef void (*lpNSAPIMessage)(int, const char*, const int, const char*); 
    8483  typedef NSCAPI::errorReturn (*lpNSAPIStopServer)(void); 
    8584  typedef NSCAPI::nagiosReturn (*lpNSAPIInject)(const char*, const unsigned int, char **, char *, unsigned int, char *, unsigned int); 
    8685  typedef LPVOID (*lpNSAPILoader)(char*); 
     86  typedef NSCAPI::boolReturn (*lpNSAPICheckLogMessages)(int); 
     87  typedef NSCAPI::errorReturn (*lpNSAPIEncrypt)(unsigned int, const char*, unsigned int, char*, unsigned int *); 
     88  typedef NSCAPI::errorReturn (*lpNSAPIDecrypt)(unsigned int, const char*, unsigned int, char*, unsigned int *); 
    8789 
    8890  // Helper functions for calling into the core 
    8991  std::string getApplicationName(void); 
    9092  std::string getApplicationVersionString(void); 
     93  std::list<std::string> getSettingsSection(std::string section); 
    9194  std::string getSettingsString(std::string section, std::string key, std::string defaultValue); 
    9295  int getSettingsInt(std::string section, std::string key, int defaultValue); 
     
    98101  void StopService(void); 
    99102  std::string getBasePath(); 
     103  bool logDebug(); 
     104  bool checkLogMessages(int type); 
     105  std::string Encrypt(std::string str, unsigned int algorithm = NSCAPI::xor); 
     106  std::string Decrypt(std::string str, unsigned int algorithm = NSCAPI::xor); 
    100107}; 
    101108 
     
    152159  NSCModuleHelper::Message(NSCAPI::debug, __FILE__, __LINE__, msg) 
    153160 
     161/* 
     162#define NSC_DEBUG_MSG_STD(msg) 
     163#define NSC_DEBUG_MSG(msg) 
     164*/ 
    154165////////////////////////////////////////////////////////////////////////// 
    155166// Message wrappers below this point 
  • /trunk/include/Socket.cpp

    r17 r30  
    11#include "stdafx.h" 
    22#include <Socket.h> 
     3#include <NSCHelper.h> 
    34 
    4  
    5 SimpleSocketListsner::~SimpleSocketListsner() { 
    6   // @todo: Force cleanup here 
     5/** 
     6 * Print an error message  
     7 * @param error  
     8 */ 
     9void simpleSocket::Socket::printError(std::string FILE, int LINE, std::string error) { 
     10  NSCModuleHelper::Message(NSCAPI::error, FILE, LINE, error); 
    711} 
    812 
    913 
    1014/** 
    11 * Thread procedure for the socket listener 
    12 * @param lpParameter Potential argument to the thread proc. 
    13 * @return thread exit status 
    14 * @todo This needs to be reworked, possibly completely redone ? 
    15 */ 
    16 DWORD SimpleSocketListsner::threadProc(LPVOID lpParameter) 
    17 { 
    18   hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
    19   if (!hStopEvent) { 
    20     NSC_LOG_ERROR_STD("Create StopEvent failed: " + strEx::itos(GetLastError())); 
    21     return 0; 
     15 * Read all data on the socket 
     16 * @param buffer  
     17 * @param tmpBufferLength Length of temporary buffer to use (generally larger then expected data) 
     18 */ 
     19void simpleSocket::Socket::readAll(DataBuffer& buffer, unsigned int tmpBufferLength /* = 1024*/) { 
     20  // @todo this could be optimized a bit if we want to 
     21  // If only one buffer is needed we could "reuse" the buffer instead of copying it. 
     22  char *tmpBuffer = new char[tmpBufferLength+1]; 
     23  int n=recv(socket_,tmpBuffer,tmpBufferLength,0); 
     24  while ((n!=SOCKET_ERROR )&&(n!=0)) { 
     25    if (n == tmpBufferLength) { 
     26      // We filled the buffer (There is more to get) 
     27      buffer.append(tmpBuffer, n); 
     28      n=recv(socket_,tmpBuffer,tmpBufferLength,0); 
     29 
     30    } else { 
     31      // Buffer not full, we got it "all" 
     32      buffer.append(tmpBuffer, n); 
     33      break; 
     34    } 
    2235  } 
    23  
    24   WSADATA wsaData; 
    25   sockaddr_in local; 
    26   int wsaret=WSAStartup(0x101,&wsaData); 
    27   if(wsaret!=0) { 
    28     NSC_LOG_ERROR_STD("WSA Startup failed: " + strEx::itos(wsaret)); 
    29     return 0; 
    30   } 
    31  
    32   local.sin_family=AF_INET; 
    33   local.sin_addr.s_addr=INADDR_ANY; 
    34   local.sin_port=htons(port_); 
    35   server=socket(AF_INET,SOCK_STREAM,0); 
    36   if(server==INVALID_SOCKET) { 
    37     WSACleanup(); 
    38     NSC_LOG_ERROR_STD("Could not create listening socket: " + strEx::itos(GetLastError())); 
    39     return 0; 
    40   } 
    41  
    42   if(bind(server,(sockaddr*)&local,sizeof(local))!=0) { 
    43     closesocket(server); 
    44     WSACleanup(); 
    45     NSC_LOG_ERROR_STD("Could not bind socket: " + strEx::itos(GetLastError())); 
    46     return 0; 
    47   } 
    48  
    49   if(listen(server,10)!=0) { 
    50     closesocket(server); 
    51     WSACleanup(); 
    52     NSC_LOG_ERROR_STD("Could not open socket: " + strEx::itos(GetLastError())); 
    53     return 0; 
    54   } 
    55  
    56   SOCKET client; 
    57   sockaddr_in from; 
    58   int fromlen=sizeof(from); 
    59   while (!(WaitForSingleObject(hStopEvent, 100) == WAIT_OBJECT_0)) { 
    60     client=accept(server, (struct sockaddr*)&from,&fromlen); 
    61     if (client != INVALID_SOCKET) 
    62       onAccept(client); 
    63   } 
    64   closesocket(server); 
    65   WSACleanup(); 
    66   NSC_DEBUG_MSG("Socket closed!"); 
    67   return 0; 
    68 } 
    69  
    70 /** 
    71 * Exit thread callback proc.  
    72 * This is called by the thread manager when the thread should initiate a shutdown procedure. 
    73 * The thread manager is responsible for waiting for the actual termination of the thread. 
    74 */ 
    75 void SimpleSocketListsner::exitThread(void) { 
    76   NSC_DEBUG_MSG("Requesting Socket shutdown!"); 
    77   if (!SetEvent(hStopEvent)) { 
    78     NSC_LOG_ERROR_STD("SetStopEvent failed"); 
    79   } 
     36  delete [] tmpBuffer; 
    8037} 
    8138 
    8239 
    83  
    84  
    85  
    86  
     40/** 
     41 * Startup WSA 
     42 * @param wVersionRequested Version to use 
     43 * @return stuff 
     44 */ 
     45WSADATA simpleSocket::WSAStartup(WORD wVersionRequested /* = 0x202 */) { 
     46  WSADATA wsaData; 
     47  int wsaret=::WSAStartup(wVersionRequested,&wsaData); 
     48  if(wsaret != 0) 
     49    throw SocketException("WSAStartup failed: " + strEx::itos(wsaret)); 
     50  return wsaData; 
     51} 
     52/** 
     53 * Cleanup (Shutdown) WSA 
     54 */ 
     55void simpleSocket::WSACleanup() { 
     56  if (::WSACleanup() != 0) 
     57    throw SocketException("WSACleanup failed: ", ::WSAGetLastError()); 
     58} 
  • /trunk/include/Socket.h

    r20 r30  
    44#include <Mutex.h> 
    55#include <WinSock2.h> 
    6 /** 
    7  * @ingroup NSClient++ 
    8  * Socket responder class. 
    9  * This is a background thread that listens to the socket and executes incoming commands. 
    10  * 
    11  * @version 1.0 
    12  * first version 
    13  * 
    14  * @date 02-12-2005 
    15  * 
    16  * @author mickem 
    17  * 
    18  * @par license 
    19  * This code is absolutely free to use and modify. The code is provided "as is" with 
    20  * no expressed or implied warranty. The author accepts no liability if it causes 
    21  * any damage to your computer, causes your pet to fall ill, increases baldness 
    22  * or makes your car start emitting strange noises when you start it up. 
    23  * This code has no bugs, just undocumented features! 
    24  *  
    25  * @todo This is not very well written and should probably be reworked. 
    26  * 
    27  * @bug  
    28  * 
    29  */ 
    30 class SimpleSocketListsner { 
    31 private: 
    32   MutexHandler mutexHandler; 
    33   SOCKET server; 
    34   HANDLE hStopEvent; 
    35   u_short port_; 
    36  
    37 public: 
    38   SimpleSocketListsner(u_short port) : port_(port), hStopEvent(NULL) {}; 
    39   virtual ~SimpleSocketListsner(); 
    40   DWORD threadProc(LPVOID lpParameter); 
    41   void exitThread(void); 
    42 #define RECV_BUFFER_LEN 1024 
    43   typedef std::pair<char*,unsigned int> readAllDataBlock; 
    44   static readAllDataBlock readAll(SOCKET socket) { 
    45     // @bug Is this even working ? 
    46     // @todo Nedds *alot* more work... 
    47     unsigned int buffLen = RECV_BUFFER_LEN; 
    48     char *retBuf = NULL; 
    49     char *buff = new char[buffLen]; 
    50     int n=recv(socket,buff,RECV_BUFFER_LEN,0); 
    51     while ((n!=SOCKET_ERROR )||(n!=0)) { 
    52       if (n == RECV_BUFFER_LEN) { 
    53         char* newBuf = new char[buffLen+RECV_BUFFER_LEN]; 
    54         memcpy(newBuf, buff, buffLen); 
    55         n = recv(socket, buff, RECV_BUFFER_LEN, 0); 
    56         if ((n!=SOCKET_ERROR )&&(n!=0)) { 
    57           memcpy(&newBuf[buffLen], buff, n); 
    58           buffLen += n; 
     6 
     7 
     8namespace simpleSocket { 
     9  class SocketException { 
     10  private: 
     11    std::string error_; 
     12  public: 
     13    SocketException(std::string error) : error_(error) {} 
     14    SocketException(std::string error, int errorCode) : error_(error) { 
     15      error_ += strEx::itos(errorCode); 
     16    } 
     17    std::string getMessage() const { 
     18      return error_; 
     19    } 
     20 
     21  }; 
     22  class DataBuffer { 
     23  private: 
     24    char *buffer_; 
     25    unsigned int length_; 
     26  public: 
     27    DataBuffer() : buffer_(NULL), length_(0){ 
     28    } 
     29    DataBuffer(const DataBuffer &other) { 
     30      buffer_ = new char[other.getLength()]; 
     31      memcpy(buffer_, other.getBuffer(), other.getLength()); 
     32      length_ = other.getLength(); 
     33    } 
     34    virtual ~DataBuffer() { 
     35      delete [] buffer_; 
     36      length_ = 0; 
     37    } 
     38    void append(const char* buffer, const unsigned int length) { 
     39      char *tBuf = new char[length_+length+1]; 
     40      memcpy(tBuf, buffer_, length_); 
     41      memcpy(&tBuf[length_], buffer, length); 
     42      delete [] buffer_; 
     43      buffer_ = tBuf; 
     44      length_ += length; 
     45    } 
     46    const char * getBuffer() const { 
     47      return buffer_; 
     48    } 
     49    unsigned int getLength() const { 
     50      return length_; 
     51    } 
     52    void copyFrom(const char* buffer, const unsigned int length) { 
     53      delete [] buffer_; 
     54      buffer_ = new char[length+1]; 
     55      memcpy(buffer_, buffer, length); 
     56      length_ = length; 
     57    } 
     58  }; 
     59 
     60  class Socket { 
     61  protected: 
     62    SOCKET socket_; 
     63    sockaddr_in from_; 
     64 
     65  public: 
     66    Socket() : socket_(NULL) { 
     67    } 
     68    Socket(SOCKET socket) : socket_(socket) { 
     69    } 
     70    Socket(Socket &other) { 
     71      socket_ = other.socket_; 
     72      from_ = other.from_; 
     73      other.socket_ = NULL; 
     74    } 
     75    virtual ~Socket() { 
     76      if (socket_) 
     77        closesocket(socket_); 
     78      socket_ = NULL; 
     79    } 
     80    virtual SOCKET detach() { 
     81      SOCKET s = socket_; 
     82      socket_ = NULL; 
     83      return s; 
     84    } 
     85    virtual void attach(SOCKET s) { 
     86      assert(socket_ == NULL); 
     87      socket_ = s; 
     88    } 
     89    virtual void shutdown(int how = SD_BOTH) { 
     90      if (socket_) 
     91        ::shutdown(socket_, how); 
     92    } 
     93 
     94    virtual void close() { 
     95      if (socket_) 
     96        closesocket(socket_); 
     97      socket_ = NULL; 
     98    } 
     99    virtual void setNonBlock() { 
     100      unsigned long NoBlock = 1; 
     101      this->ioctlsocket(FIONBIO, &NoBlock); 
     102    } 
     103    virtual void readAll(DataBuffer &buffer, unsigned int tmpBufferLength = 1024); 
     104 
     105    virtual void socket(int af, int type, int protocol ) { 
     106      socket_ = ::socket(af, type, protocol); 
     107      assert(socket_ != INVALID_SOCKET); 
     108    } 
     109    virtual void bind() { 
     110      assert(socket_); 
     111      int fromlen=sizeof(from_); 
     112      if (::bind(socket_, (sockaddr*)&from_, fromlen) == SOCKET_ERROR) 
     113        throw SocketException("bind failed: ", ::WSAGetLastError()); 
     114    } 
     115    virtual void listen(int backlog = 0) { 
     116      assert(socket_); 
     117      if (::listen(socket_, backlog) == SOCKET_ERROR) 
     118        throw SocketException("listen failed: ", ::WSAGetLastError()); 
     119    } 
     120    virtual bool accept(Socket &client) { 
     121      int fromlen=sizeof(client.from_); 
     122      SOCKET s = ::accept(socket_, (sockaddr*)&client.from_, &fromlen); 
     123      if(s == INVALID_SOCKET) { 
     124        int err = ::WSAGetLastError(); 
     125        if (err == WSAEWOULDBLOCK) 
     126          return false; 
     127        throw SocketException("accept failed: ", ::WSAGetLastError()); 
     128      } 
     129      client.attach(s); 
     130      return true; 
     131    } 
     132    virtual void setAddr(short family, u_long addr, u_short port) { 
     133      from_.sin_family=family; 
     134      from_.sin_addr.s_addr=addr; 
     135      from_.sin_port=port; 
     136    } 
     137    virtual int send(const char * buf, unsigned int len, int flags = 0) { 
     138      assert(socket_); 
     139      return ::send(socket_, buf, len, flags); 
     140    } 
     141    int inline send(DataBuffer &buffer, int flags = 0) { 
     142      return send(buffer.getBuffer(), buffer.getLength(), flags); 
     143    } 
     144    virtual void ioctlsocket(long cmd, u_long *argp) { 
     145      assert(socket_); 
     146      if (::ioctlsocket(socket_, cmd, argp) == SOCKET_ERROR) 
     147        throw SocketException("ioctlsocket failed: ", ::WSAGetLastError()); 
     148    } 
     149    virtual std::string getAddrString() { 
     150      return inet_ntoa(from_.sin_addr); 
     151    } 
     152    virtual void printError(std::string file, int line, std::string error); 
     153  }; 
     154 
     155  class ListenerHandler { 
     156  public: 
     157    virtual void onAccept(Socket *client) = 0; 
     158    virtual void onClose() = 0; 
     159  }; 
     160 
     161 
     162  /** 
     163  * @ingroup NSClient++ 
     164  * Socket responder class. 
     165  * This is a background thread that listens to the socket and executes incoming commands. 
     166  * 
     167  * @version 1.0 
     168  * first version 
     169  * 
     170  * @date 02-12-2005 
     171  * 
     172  * @author mickem 
     173  * 
     174  * @par license 
     175  * This code is absolutely free to use and modify. The code is provided "as is" with 
     176  * no expressed or implied warranty. The author accepts no liability if it causes 
     177  * any damage to your computer, causes your pet to fall ill, increases baldness 
     178  * or makes your car start emitting strange noises when you start it up. 
     179  * This code has no bugs, just undocumented features! 
     180  *  
     181  * @todo This is not very well written and should probably be reworked. 
     182  * 
     183  * @bug  
     184  * 
     185  */ 
     186  template <class TListenerType = simpleSocket::Socket, class TSocketType = TListenerType> 
     187  class Listener : public TListenerType { 
     188  public: 
     189    typedef TListenerType tListener; 
     190    typedef TSocketType tSocket; 
     191  private: 
     192    struct simpleResponderBundle { 
     193      bool terminated; 
     194      HANDLE hThread; 
     195      unsigned dwThreadID; 
     196    }; 
     197    typedef std::list<simpleResponderBundle> socketResponses; 
     198    typedef TListenerType tBase; 
     199    class ListenerThread; 
     200    typedef Thread<ListenerThread> listenThreadManager; 
     201 
     202    u_short port_; 
     203    listenThreadManager threadManager_; 
     204    socketResponses responderList_; 
     205    MutexHandler responderMutex_; 
     206 
     207  public: 
     208    class ListenerThread { 
     209    private: 
     210      typedef TListenerType tParentBase; 
     211      typedef TSocketType tSocket; 
     212 
     213      HANDLE hStopEvent_; 
     214    public: 
     215      ListenerThread() : hStopEvent_(NULL) {} 
     216      DWORD threadProc(LPVOID lpParameter); 
     217      void exitThread(void) { 
     218        assert(hStopEvent_ != NULL); 
     219        if (!SetEvent(hStopEvent_)) 
     220          throw new SocketException("SetEvent failed."); 
     221      } 
     222    }; 
     223  private: 
     224    ListenerHandler *pHandler_; 
     225 
     226  public: 
     227    Listener() : pHandler_(NULL) {}; 
     228    virtual ~Listener() { 
     229      if (responderList_.size() > 0) { 
     230        MutexLock lock(responderMutex_); 
     231        if (!lock.hasMutex()) { 
     232          printError(__FILE__, __LINE__, "Failed to get responder mutex (cannot terminate socket threads)."); 
     233        } else { 
     234          for (socketResponses::iterator it = responderList_.begin(); it != responderList_.end(); ++it) { 
     235            if (WaitForSingleObject( (*it).hThread, 1000) == WAIT_OBJECT_0) { 
     236            } else { 
     237              if (!TerminateThread((*it).hThread, -1)) { 
     238                printError(__FILE__, __LINE__, "We failed to terminate check thread."); 
     239              } else { 
     240                if (WaitForSingleObject( (*it).hThread, 5000) == WAIT_OBJECT_0) { 
     241                  CloseHandle((*it).hThread); 
     242                } else { 
     243                  printError(__FILE__, __LINE__, "We failed to terminate check thread (wait timed out)."); 
     244                } 
     245              } 
     246            } 
     247          } 
     248          responderList_.clear(); 
    59249        } 
    60         if (retBuf) 
    61           delete [] retBuf; 
    62         retBuf = newBuf; 
    63       } else { 
    64         buffLen = n; 
    65         break; 
    66       } 
    67     } 
    68     if (retBuf) { 
    69       delete [] buff; 
    70       return readAllDataBlock(retBuf,buffLen); 
    71     } 
    72     return readAllDataBlock(buff,buffLen); 
    73   } 
    74  
    75  
    76 private: 
    77   virtual void onAccept(SOCKET client) {} 
    78 }; 
    79  
    80  
     250      } 
     251    }; 
     252 
     253    virtual void StartListener(int port) { 
     254      port_ = port; 
     255      threadManager_.createThread(this); 
     256    } 
     257    virtual void StopListener() { 
     258      if (threadManager_.hasActiveThread()) 
     259        if (!threadManager_.exitThread()) 
     260          throw new SocketException("Could not terminate thread."); 
     261      tBase::close(); 
     262    } 
     263    void setHandler(ListenerHandler* pHandler) { 
     264      pHandler_ = pHandler; 
     265    } 
     266    void removeHandler(ListenerHandler* pHandler) { 
     267      if (pHandler != pHandler_) 
     268        throw SocketException("Not a registered handler!"); 
     269      pHandler_ = NULL; 
     270    } 
     271    static unsigned __stdcall socketResponceProc(void* lpParameter); 
     272    struct srp_data { 
     273      Listener *pCore; 
     274      tSocket *client; 
     275    }; 
     276    void addResponder(tSocket *client) { 
     277      MutexLock lock(responderMutex_); 
     278      if (!lock.hasMutex()) { 
     279        printError(__FILE__, __LINE__, "Failed to get responder mutex."); 
     280        return; 
     281      } 
     282      for (socketResponses::iterator it = responderList_.begin(); it != responderList_.end();) { 
     283        if ( (*it).terminated) { 
     284          if (WaitForSingleObject( (*it).hThread, 500) == WAIT_OBJECT_0) { 
     285            CloseHandle((*it).hThread); 
     286            responderList_.erase(it++); 
     287          } 
     288        } else 
     289          ++it; 
     290      } 
     291      simpleResponderBundle data; 
     292      srp_data *lpData = new srp_data; 
     293      lpData->pCore = this; 
     294      lpData->client = client; 
     295 
     296      data.hThread = reinterpret_cast<HANDLE>(::_beginthreadex( NULL, 0, &socketResponceProc, lpData, 0, &data.dwThreadID)); 
     297      data.terminated = false; 
     298      responderList_.push_back(data); 
     299    } 
     300    bool removeResponder(DWORD dwThreadID) { 
     301      MutexLock lock(responderMutex_); 
     302      if (!lock.hasMutex()) { 
     303        printError(__FILE__, __LINE__, "Failed to get responder mutex when trying to free thread."); 
     304        return false; 
     305      } 
     306      for (socketResponses::iterator it = responderList_.begin(); it != responderList_.end(); ++it) { 
     307        if ( (*it).dwThreadID == dwThreadID) { 
     308          (*it).terminated = true; 
     309          return true; 
     310        } 
     311      } 
     312      return false; 
     313    } 
     314 
     315 
     316  private: 
     317    void onAccept(tSocket *client) { 
     318      if (pHandler_) 
     319        pHandler_->onAccept(client); 
     320    } 
     321    void onClose() { 
     322      if (pHandler_) 
     323        pHandler_->onClose(); 
     324    } 
     325    virtual bool accept(tSocket &client) { 
     326      return tBase::accept(client); 
     327    } 
     328  }; 
     329 
     330  WSADATA WSAStartup(WORD wVersionRequested = 0x202); 
     331  void WSACleanup(); 
     332 
     333} 
     334 
     335template <class TListenerType, class TSocketType> 
     336unsigned simpleSocket::Listener<TListenerType, TSocketType>::socketResponceProc(void* lpParameter) 
     337{ 
     338  // @todo make sure this terminates after X seconds! 
     339 
     340  srp_data *data = reinterpret_cast<srp_data*>(lpParameter); 
     341  Listener *pCore = data->pCore; 
     342  tSocket *client = data->client; 
     343  delete data; 
     344  try { 
     345    pCore->onAccept(client); 
     346  } catch (SocketException e) { 
     347    pCore->printError(__FILE__, __LINE__, e.getMessage() + " killing socket..."); 
     348  } 
     349  client->close(); 
     350  delete client; 
     351  if (!pCore->removeResponder(GetCurrentThreadId())) { 
     352    pCore->printError(__FILE__, __LINE__, "Could not remove thread: " + strEx::itos(GetCurrentThreadId())); 
     353  } 
     354  _endthreadex(0); 
     355  return 0; 
     356} 
     357 
     358 
     359template <class TListenerType, class TSocketType> 
     360DWORD simpleSocket::Listener<TListenerType, TSocketType>::ListenerThread::threadProc(LPVOID lpParameter) 
     361{ 
     362  Listener *core = reinterpret_cast<Listener*>(lpParameter); 
     363 
     364  hStopEvent_ = CreateEvent(NULL, TRUE, FALSE, NULL); 
     365  if (!hStopEvent_) { 
     366    core->printError(__FILE__, __LINE__, "Create StopEvent failed: " + strEx::itos(GetLastError())); 
     367    return 0; 
     368  } 
     369 
     370  try { 
     371    core->socket(AF_INET,SOCK_STREAM,0); 
     372    core->setAddr(AF_INET, INADDR_ANY, htons(core->port_)); 
     373    core->bind(); 
     374    core->listen(10); 
     375    core->setNonBlock(); 
     376    while (!(WaitForSingleObject(hStopEvent_, 100) == WAIT_OBJECT_0)) { 
     377      try { 
     378        tSocket client; 
     379        if (core->accept(client)) { 
     380          core->addResponder(new tSocket(client)); 
     381        } 
     382      } catch (SocketException e) { 
     383        core->printError(__FILE__, __LINE__, e.getMessage() + ", attempting to resume..."); 
     384      } 
     385    } 
     386  } catch (SocketException e) { 
     387    core->printError(__FILE__, __LINE__, e.getMessage()); 
     388  } 
     389  core->shutdown(SD_BOTH); 
     390  core->close(); 
     391  core->onClose(); 
     392  HANDLE hTmp = hStopEvent_; 
     393  hStopEvent_ = NULL; 
     394  if (!CloseHandle(hTmp)) { 
     395    core->printError(__FILE__, __LINE__, "CloseHandle StopEvent failed: " + strEx::itos(GetLastError())); 
     396  } 
     397  return 0; 
     398} 
  • /trunk/Doxyfile

    r3 r28  
    5252HIDE_IN_BODY_DOCS      = NO 
    5353INTERNAL_DOCS          = NO 
    54 CASE_SENSE_NAMES       = YES 
     54CASE_SENSE_NAMES       = NO 
    5555HIDE_SCOPE_NAMES       = NO 
    5656SHOW_INCLUDE_FILES     = YES 
     
    7171# configuration options related to warning and progress messages 
    7272#--------------------------------------------------------------------------- 
    73 QUIET                  = NO 
     73QUIET                  = YES 
    7474WARNINGS               = YES 
    7575WARN_IF_UNDOCUMENTED   = YES 
    7676WARN_IF_DOC_ERROR      = YES 
    7777WARN_NO_PARAMDOC       = YES 
    78 WARN_FORMAT            = "$file($line) $text" 
     78WARN_FORMAT            = "$file($line) : $text" 
    7979WARN_LOGFILE           =  
    8080#--------------------------------------------------------------------------- 
    8181# configuration options related to the input files 
    8282#--------------------------------------------------------------------------- 
    83 INPUT                  = C:\Source\NSClient++ 
     83INPUT                  = C:\Source\nscplus 
    8484FILE_PATTERNS          = *.cpp \ 
    8585                         *.h \ 
  • /trunk/NSCPlugin.cpp

    r16 r28  
    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 
     
    104127 * Plug ins may refuse to handle the plug in (if not applicable) by returning an empty string. 
    105128 * 
    106  * @param *command The command name (is a string encoded number for legacy commands) 
     129 * @param command The command name (is a string encoded number for legacy commands) 
    107130 * @param argLen The length of the argument buffer. 
    108131 * @param **arguments The arguments for this command 
    109  * @param returnBuffer Return buffer for plug in to store the result of the executed command. 
    110  * @param returnBufferLen Size of the return buffer. 
     132 * @param returnMessageBuffer Return buffer for plug in to store the result of the executed command. 
     133 * @param returnMessageBufferLen Size of returnMessageBuffer 
     134 * @param returnPerfBuffer Return buffer for performance data 
     135 * @param returnPerfBufferLen Sixe of returnPerfBuffer 
    111136 * @return Status of execution. Could be error codes, buffer length messages etc. 
    112137 * @throws NSPluginException if the module is not loaded. 
    113  * 
    114  * @todo Implement return status as an enum to make it simpler for clients to see potential return stats? 
    115  */ 
    116 NSCAPI::nagiosReturn NSCPlugin::handleCommand(const char *command, const unsigned int argLen, char **arguments, char* returnMessageBuffer, unsigned int returnMessageBufferLen, char* returnPerfBuffer, unsigned int returnPerfBufferLen) { 
     138 */ 
     139NSCAPI::nagiosReturn NSCPlugin::handleCommand(const char* command, const unsigned int argLen, char **arguments, char* returnMessageBuffer, unsigned int returnMessageBufferLen, char* returnPerfBuffer, unsigned int returnPerfBufferLen) { 
    117140  if (!isLoaded()) 
    118141    throw NSPluginException(file_, "Library is not loaded"); 
     
    127150 * @param line The line in the file that generated the message generally __LINE__ 
    128151 * @throws NSPluginException if the module is not loaded. 
    129  * @throws  
    130152 */ 
    131153void NSCPlugin::handleMessage(int msgType, const char* file, const int line, const char *message) { 
  • /trunk/NSClient++.cpp

    r20 r30  
    1818#include "Settings.h" 
    1919#include <charEx.h> 
     20#include <Socket.h> 
     21#include <b64/b64.h> 
     22 
    2023 
    2124NSClient mainClient;  // Global core instance. 
     
    5457        return -1; 
    5558      } 
     59    } else if ( _stricmp( "encrypt", argv[1]+1 ) == 0 ) { 
     60      g_bConsoleLog = true; 
     61      std::string password; 
     62      Settings::getInstance()->setFile(mainClient.getBasePath() + "NSC.ini"); 
     63      std::cout << "Enter password to encrypt (has to be a single word): "; 
     64      std::cin >> password; 
     65      std::string xor_pwd = Encrypt(password); 
     66      std::cout << "obfuscated_password=" << xor_pwd << std::endl; 
     67      if (password != Decrypt(xor_pwd))  
     68        std::cout << "ERROR: Password did not match!" << std::endl; 
     69      Settings::destroyInstance(); 
     70      return 0; 
    5671    } else if ( _stricmp( "start", argv[1]+1 ) == 0 ) { 
    5772      g_bConsoleLog = true; 
     
    6984    } else if ( _stricmp( "test", argv[1]+1 ) == 0 ) { 
    7085#ifdef _DEBUG 
     86      /* 
    7187      strEx::run_test_getToken(); 
     88      strEx::run_test_replace(); 
    7289      charEx::run_test_getToken(); 
    7390      arrayBuffer::run_testArrayBuffer(); 
     91      */ 
    7492#endif 
     93 
    7594      g_bConsoleLog = true; 
    7695      mainClient.InitiateService(); 
     
    7998      std::cin >> s; 
    8099      while (s != "exit") { 
    81 //        mainClient.inject(s); 
     100        strEx::token t = strEx::getToken(s, ','); 
     101        std::string msg, perf; 
     102        NSCAPI::nagiosReturn ret = mainClient.inject(t.first, t.second, ',', msg, perf); 
     103        if (perf.empty()) 
     104          std::cout << NSCHelper::translateReturn(ret) << ":" << msg << std::endl; 
     105        else 
     106          std::cout << NSCHelper::translateReturn(ret) << ":" << msg << "|" << perf << std::endl; 
    82107        std::cin >> s; 
    83108      } 
    84109      mainClient.TerminateService(); 
    85       LOG_MESSAGE("DONE!"); 
    86  
    87110      return 0; 
    88111    } else { 
     
    104127void NSClientT::InitiateService(void) { 
    105128  Settings::getInstance()->setFile(getBasePath() + "NSC.ini"); 
     129 
     130  try { 
     131    simpleSocket::WSAStartup(); 
     132  } catch (simpleSocket::SocketException e) { 
     133    LOG_ERROR_STD("Uncaught exception: " + e.getMessage()); 
     134  } 
    106135 
    107136  SettingsT::sectionList list = Settings::getInstance()->getSection("modules"); 
     
    121150void NSClientT::TerminateService(void) { 
    122151  try { 
    123     LOG_DEBUG("Socket closed, unloading plugins..."); 
    124152    mainClient.unloadPlugins(); 
    125     LOG_DEBUG("Plugins unloaded..."); 
    126153  } catch(NSPluginException *e) { 
    127154    std::cout << "Exception raised: " << e->error_ << " in module: " << e->file_ << std::endl;; 
     155  } 
     156  try { 
     157    simpleSocket::WSACleanup(); 
     158  } catch (simpleSocket::SocketException e) { 
     159    LOG_ERROR_STD("Uncaught exception: " + e.getMessage()); 
    128160  } 
    129161  Settings::destroyInstance(); 
     
    155187 */ 
    156188void NSClientT::loadPlugins(const std::list<std::string> plugins) { 
    157   MutexLock lock(pluginMutex); 
    158   if (!lock.hasMutex()) { 
    159     LOG_ERROR("FATAL ERROR: Could not get mutex."); 
     189  ReadLock readLock(&m_mutexRW, true, 10000); 
     190  if (!readLock.IsLocked()) { 
     191    LOG_ERROR("FATAL ERROR: Could not get read-mutex."); 
    160192    return; 
    161193  } 
     
    169201 */ 
    170202void NSClientT::unloadPlugins() { 
    171   MutexLock lock(pluginMutex,20000); 
    172   if (!lock.hasMutex()) { 
    173     LOG_ERROR("FATAL ERROR: Could not get mutex."); 
    174     return; 
    175   } 
    176   pluginList::reverse_iterator it; 
    177   for (it = plugins_.rbegin(); it != plugins_.rend(); ++it) { 
    178     LOG_DEBUG_STD("Unloading plugin: " + (*it)->getName() + "..."); 
    179     (*it)->unload(); 
    180   } 
    181203  { 
    182     MutexLock lock2(messageMutex,20000); 
    183     if (!lock2.hasMutex()) { 
    184       LOG_ERROR("FATAL ERROR: Could not get mutex (we will now crash BTW)."); 
    185     } else { 
    186       messageHandlers_.clear(); 
    187     } 
    188   } 
    189   commandHandlers_.clear(); 
    190   for (it = plugins_.rbegin(); it != plugins_.rend(); ++it) { 
    191     delete (*it); 
    192   } 
    193   plugins_.clear(); 
     204    WriteLock writeLock(&m_mutexRW, true, 10000); 
     205    if (!writeLock.IsLocked()) { 
     206      LOG_ERROR("FATAL ERROR: Could not get read-mutex."); 
     207      return; 
     208    } 
     209    commandHandlers_.clear(); 
     210    messageHandlers_.clear(); 
     211  } 
     212  { 
     213    ReadLock readLock(&m_mutexRW, true, 10000); 
     214    if (!readLock.IsLocked()) { 
     215      LOG_ERROR("FATAL ERROR: Could not get read-mutex."); 
     216      return; 
     217    } 
     218    for (pluginList::size_type i=plugins_.size();i>0;i--) { 
     219      NSCPlugin *p = plugins_[i-1]; 
     220      LOG_DEBUG_STD("Unloading plugin: " + p->getName() + "..."); 
     221      p->unload(); 
     222    } 
     223  } 
     224  { 
     225    WriteLock writeLock(&m_mutexRW, true, 10000); 
     226    if (!writeLock.IsLocked()) { 
     227      LOG_ERROR("FATAL ERROR: Could not get read-mutex."); 
     228      return; 
     229    } 
     230    for (unsigned int i=plugins_.size();i>0;i--) { 
     231      NSCPlugin *p = plugins_[i-1]; 
     232      plugins_[i-1] = NULL; 
     233      delete p; 
     234    } 
     235    plugins_.clear(); 
     236  } 
    194237} 
    195238/** 
     
    198241 */ 
    199242void NSClientT::loadPlugin(const std::string file) { 
     243  LOG_DEBUG_STD("Loading: " + file); 
    200244  addPlugin(new NSCPlugin(file)); 
    201245} 
     
    205249 */ 
    206250void NSClientT::addPlugin(plugin_type plugin) { 
    207   MutexLock lock(pluginMutex); 
    208   if (!lock.hasMutex()) { 
    209     LOG_ERROR("FATAL ERROR: Could not get mutex."); 
    210     return; 
    211   } 
    212251  plugin->load(); 
    213   LOG_DEBUG_STD("Loading: " + plugin->getName()); 
    214   // @todo Catch here and unload if we fail perhaps ? 
    215   plugins_.push_back(plugin); 
    216   if (plugin->hasCommandHandler()) 
    217     commandHandlers_.push_back(plugin); 
    218   if (plugin->hasMessageHandler()) 
    219     messageHandlers_.push_back(plugin); 
    220 } 
     252  { 
     253    WriteLock writeLock(&m_mutexRW, true, 10000); 
     254    if (!writeLock.IsLocked()) { 
     255      LOG_ERROR("FATAL ERROR: Could not get read-mutex."); 
     256      return; 
     257    } 
     258    // @todo Catch here and unload if we fail perhaps ? 
     259    plugins_.insert(plugins_.end(), plugin); 
     260    if (plugin->hasCommandHandler()) 
     261      commandHandlers_.insert(commandHandlers_.end(), plugin); 
     262    if (plugin->hasMessageHandler()) 
     263      messageHandlers_.insert(messageHandlers_.end(), plugin); 
     264  } 
     265 
     266} 
     267 
     268NSCAPI::nagiosReturn NSClientT::inject(std::string command, std::string arguments, char splitter, std::string &msg, std::string & perf) { 
     269  unsigned int aLen = 0; 
     270  char ** aBuf = arrayBuffer::split2arrayBuffer(arguments, splitter, aLen); 
     271  char * mBuf = new char[1024]; 
     272  char * pBuf = new char[1024]; 
     273  NSCAPI::nagiosReturn ret = injectRAW(command.c_str(), aLen, aBuf, mBuf, 1023, pBuf, 1023); 
     274  arrayBuffer::destroyArrayBuffer(aBuf, aLen); 
     275  if ( (ret == NSCAPI::returnInvalidBufferLen) || (ret == NSCAPI::returnIgnored) ) { 
     276    delete [] mBuf; 
     277    delete [] pBuf; 
     278    return ret; 
     279  } 
     280  msg = mBuf; 
     281  perf = pBuf; 
     282  delete [] mBuf; 
     283  delete [] pBuf; 
     284  return ret; 
     285} 
     286 
    221287/** 
    222288 * Inject a command into the plug-in stack. 
    223289 * 
    224  * @param buffer A command string to inject. This should be a unparsed command string such as command&arg1&arg2&arg... 
    225  * @return The result, empty string if no result 
     290 * @param command Command to inject 
     291 * @param argLen Length of argument buffer 
     292 * @param **argument Argument buffer 
     293 * @param *returnMessageBuffer Message buffer 
     294 * @param returnMessageBufferLen Length of returnMessageBuffer 
     295 * @param *returnPerfBuffer Performance data buffer 
     296 * @param returnPerfBufferLen Length of returnPerfBuffer 
     297 * @return The command status 
    226298 */ 
    227299NSCAPI::nagiosReturn NSClientT::injectRAW(const char* command, const unsigned int argLen, char **argument, char *returnMessageBuffer, unsigned int returnMessageBufferLen, char *returnPerfBuffer, unsigned int returnPerfBufferLen) { 
    228   MutexLock lock(pluginMutex); 
    229  
    230   LOG_MESSAGE_STD("Injecting: " + command); 
    231  
    232   pluginList::const_iterator plit; 
    233   for (plit = commandHandlers_.begin(); plit != commandHandlers_.end(); ++plit) { 
     300  if (logDebug()) { 
     301    LOG_DEBUG_STD("Injecting: " + (std::string) command + ": " + arrayBuffer::arrayBuffer2string(argument, argLen, ", ")); 
     302  } 
     303  ReadLock readLock(&m_mutexRW, true, 5000); 
     304  if (!readLock.IsLocked()) { 
     305    LOG_ERROR("FATAL ERROR: Could not get read-mutex."); 
     306    return NSCAPI::returnUNKNOWN; 
     307  } 
     308  for (pluginList::size_type i = 0; i < commandHandlers_.size(); i++) { 
    234309    try { 
    235       NSCAPI::nagiosReturn c = (*plit)->handleCommand(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen); 
     310      NSCAPI::nagiosReturn c = commandHandlers_[i]->handleCommand(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen); 
    236311      switch (c) { 
    237312        case NSCAPI::returnInvalidBufferLen: 
     
    239314          return c; 
    240315        case NSCAPI::returnIgnored: 
    241           LOG_DEBUG("A module ignored this message"); 
    242316          break; 
    243317        case NSCAPI::returnOK: 
     
    245319        case NSCAPI::returnCRIT: 
    246320        case NSCAPI::returnUNKNOWN: 
    247           LOG_DEBUG_STD("Injected Result: " +(std::string) returnMessageBuffer); 
     321          LOG_DEBUG_STD("Injected Result: " + NSCHelper::translateReturn(c) + "  --  " + (std::string)(returnMessageBuffer)); 
    248322          LOG_DEBUG_STD("Injected Performance Result: " +(std::string) returnPerfBuffer); 
    249323          return c; 
     
    260334  return NSCAPI::returnIgnored; 
    261335} 
    262 /** 
    263  * Helper function to return the current password (perhaps this should be static ?) 
    264  * 
    265  * @return The current password 
    266  */ 
    267 std::string NSClientT::getPassword() { 
    268   return Settings::getInstance()->getString("generic", "password", ""); 
    269 } 
    270 /** 
    271  * Execute a command. 
    272  * 
    273  * @param password The password 
    274  * @param cmd The command 
    275  * @param args Arguments as a list<string> 
    276  * @return The result if any, empty string if no result. 
    277  * 
    278  * @todo Make an int return value to set critical/warning/ok/unknown status. 
    279  * ie. pair<int,string> 
    280  */ 
    281 /* 
    282 std::string NSClientT::execute(std::string password, std::string cmd, std::list<std::string> args) { 
    283   MutexLock lock(pluginMutex); 
    284   if (!lock.hasMutex()) { 
    285     LOG_ERROR("FATAL ERROR: Could not execute command with a reasonable timeframe. (could not get mutex so core is most likely locked down)."); 
    286     return "ERROR: Core was locked down"; 
    287   } 
    288   static unsigned int bufferSize = 0; 
    289   if (bufferSize == 0) 
    290     bufferSize = static_cast<unsigned int>(Settings::getInstance()->getInt("main", "bufferSize", 4096)); 
    291  
    292   if (password != getPassword()) 
    293     return "ERROR: Authorization denied."; 
    294  
    295   std::string ret; 
    296   unsigned int len; 
    297   char **arguments = NSCHelper::list2arrayBuffer(args, len); 
    298   // Allocate return buffer 
    299   char* returnbuffer = new char[bufferSize+1]; 
    300   pluginList::const_iterator plit; 
    301   for (plit = commandHandlers_.begin(); plit != commandHandlers_.end(); ++plit) { 
    302     try { 
    303       int c = (*plit)->handleCommand(cmd.c_str(), len, arguments, returnbuffer, bufferSize); 
    304       if (c == NSCAPI::handled) {         // module handled the message "we are done..." 
    305         ret = returnbuffer; 
    306         break; 
    307       } else if (c == NSCAPI::isfalse) {      // Module ignored the message 
    308         LOG_DEBUG("A module ignored this message"); 
    309       } else if (c == NSCAPI::invalidBufferLen) { // Buffer is to small 
    310         LOG_ERROR("Return buffer to small, need to increase it in the ini file."); 
    311       } else {                  // Something else went wrong... 
    312         LOG_ERROR_STD("Unknown error from handleCommand: " + strEx::itos(c)); 
    313       } 
    314     } catch(const NSPluginException& e) { 
    315       LOG_ERROR_STD("Exception raised: " + e.error_ + " in module: " + e.file_); 
    316     } 
    317   } 
    318   // delete buffers 
    319   delete [] returnbuffer; 
    320   NSCHelper::destroyArrayBuffer(arguments, len); 
    321   return ret; 
    322 } 
    323 */ 
     336 
     337bool NSClientT::logDebug() { 
     338  if (g_bConsoleLog) 
     339    return true; 
     340  typedef enum status {unknown, debug, nodebug }; 
     341  static status d = unknown; 
     342  if (d == unknown) { 
     343    if (Settings::getInstance()->getInt("log", "debug", 0) == 1) 
     344      d = debug; 
     345    else 
     346      d = nodebug; 
     347  } 
     348  return (d == debug); 
     349} 
     350 
    324351/** 
    325352 * Report a message to all logging enabled modules. 
     
    331358 */ 
    332359void NSClientT::reportMessage(int msgType, const char* file, const int line, std::string message) { 
     360  ReadLock readLock(&m_mutexRW, true, 5000); 
     361  if (!readLock.IsLocked()) { 
     362    std::cout << "Message was lost as the core was locked..." << std::endl; 
     363    return; 
     364  } 
    333365  MutexLock lock(messageMutex); 
    334366  if (!lock.hasMutex()) { 
     
    338370  } 
    339371  if (g_bConsoleLog) { 
    340     std::cout << NSCHelper::translateMessageType(msgType) << " " << file << "(" << line << ") " << message << std::endl; 
    341   } 
    342   if (msgType == NSCAPI::debug) { 
    343     typedef enum status {unknown, debug, nodebug }; 
    344     static status d = unknown; 
    345     if (d == unknown) { 
    346       if (Settings::getInstance()->getInt("log", "debug", 0) == 1) 
    347         d = debug; 
    348       else 
    349         d = nodebug; 
    350     } 
    351     if (d == nodebug) 
    352       return; 
    353   } 
    354   pluginList::const_iterator plit; 
    355   for (plit = messageHandlers_.begin(); plit != messageHandlers_.end(); ++plit) { 
     372    std::string k = "?"; 
     373    switch (msgType) { 
     374      case NSCAPI::critical: 
     375        k ="c"; 
     376        break; 
     377      case NSCAPI::warning: 
     378        k ="w"; 
     379        break; 
     380      case NSCAPI::error: 
     381        k ="e"; 
     382        break; 
     383      case NSCAPI::log: 
     384        k ="l"; 
     385        break; 
     386      case NSCAPI::debug: 
     387        k ="d"; 
     388        break; 
     389    } 
     390    std::cout << k << " " << file << "(" << line << ") " << message << std::endl; 
     391  } 
     392  if ((msgType == NSCAPI::debug)&&(!logDebug())) { 
     393    return; 
     394  } 
     395  for (pluginList::size_type i = 0; i< messageHandlers_.size(); i++) { 
    356396    try { 
    357       (*plit)->handleMessage(msgType, file, line, message.c_str()); 
     397      messageHandlers_[i]->handleMessage(msgType, file, line, message.c_str()); 
    358398    } catch(const NSPluginException& e) { 
    359399      // Here we are pretty much fucked! (as logging this might cause a loop :) 
     
    364404} 
    365405std::string NSClientT::getBasePath(void) { 
    366   MutexLock lock(pluginMutex); 
     406  MutexLock lock(internalVariables); 
    367407  if (!lock.hasMutex()) { 
    368408    LOG_ERROR("FATAL ERROR: Could not get mutex."); 
     
    406446  return mainClient.injectRAW(command, argLen, argument, returnMessageBuffer, returnMessageBufferLen, returnPerfBuffer, returnPerfBufferLen); 
    407447} 
     448NSCAPI::errorReturn NSAPIGetSettingsSection(const char* section, char*** aBuffer, unsigned int * bufLen) { 
     449  unsigned int len = 0; 
     450  *aBuffer = arrayBuffer::list2arrayBuffer(Settings::getInstance()->getSection(section), len); 
     451  *bufLen = len; 
     452  return NSCAPI::isSuccess; 
     453} 
     454 
     455NSCAPI::boolReturn NSAPICheckLogMessages(int messageType) { 
     456  if (mainClient.logDebug()) 
     457    return NSCAPI::istrue; 
     458  return NSCAPI::isfalse; 
     459} 
     460 
     461std::string Encrypt(std::string str, unsigned int algorithm) { 
     462  unsigned int len = 0; 
     463  NSAPIEncrypt(algorithm, str.c_str(), str.size(), NULL, &len); 
     464  len+=2; 
     465  char *buf = new char[len+1]; 
     466  NSCAPI::errorReturn ret = NSAPIEncrypt(algorithm, str.c_str(), str.size(), buf, &len); 
     467  if (ret == NSCAPI::isSuccess) { 
     468    std::string ret = buf; 
     469    delete [] buf; 
     470    return ret; 
     471  } 
     472  return ""; 
     473} 
     474std::string Decrypt(std::string str, unsigned int algorithm) { 
     475  unsigned int len = 0; 
     476  NSAPIDecrypt(algorithm, str.c_str(), str.size(), NULL, &len); 
     477  len+=2; 
     478  char *buf = new char[len+1]; 
     479  NSCAPI::errorReturn ret = NSAPIDecrypt(algorithm, str.c_str(), str.size(), buf, &len); 
     480  if (ret == NSCAPI::isSuccess) { 
     481    std::string ret = buf; 
     482    delete [] buf; 
     483    return ret; 
     484  } 
     485  return ""; 
     486} 
     487 
     488NSCAPI::errorReturn NSAPIEncrypt(unsigned int algorithm, const char* inBuffer, unsigned int inBufLen, char* outBuf, unsigned int *outBufLen) { 
     489  if (algorithm != NSCAPI::xor) { 
     490    LOG_ERROR("Unknown algortihm requested."); 
     491    return NSCAPI::hasFailed; 
     492  } 
     493  std::string s = inBuffer; 
     494  std::string key = Settings::getInstance()->getString(MAIN_SECTION_TITLE, MAIN_MASTERKEY, MAIN_MASTERKEY_DEFAULT); 
     495  char *c = new char[inBufLen+1]; 
     496  strncpy(c, inBuffer, inBufLen); 
     497  for (int i=0,j=0;i<inBufLen;i++,j++) { 
     498    if (j > key.size()) 
     499      j = 0; 
     500    c[i] ^= key[j]; 
     501  } 
     502  unsigned int len = b64::b64_encode(reinterpret_cast<void*>(c), inBufLen, outBuf, *outBufLen); 
     503  delete [] c; 
     504  if (outBuf) { 
     505    if ((len == 0)||(len >= *outBufLen)) { 
     506      LOG_ERROR("Invalid out buffer length."); 
     507      return NSCAPI::isInvalidBufferLen; 
     508    } 
     509    outBuf[len] = 0; 
     510    *outBufLen = len; 
     511  } else { 
     512    *outBufLen = len; 
     513  } 
     514  return NSCAPI::isSuccess; 
     515} 
     516 
     517NSCAPI::errorReturn NSAPIDecrypt(unsigned int algorithm, const char* inBuffer, unsigned int inBufLen, char* outBuf, unsigned int *outBufLen) { 
     518  if (algorithm != NSCAPI::xor) { 
     519    LOG_ERROR("Unknown algortihm requested."); 
     520    return NSCAPI::hasFailed; 
     521  } 
     522  unsigned int len =  b64::b64_decode(inBuffer, inBufLen, reinterpret_cast<void*>(outBuf), *outBufLen); 
     523  if (outBuf) { 
     524    if ((len == 0)||(len >= *outBufLen)) { 
     525      LOG_ERROR("Invalid out buffer length."); 
     526      return NSCAPI::isInvalidBufferLen; 
     527    } 
     528    std::string key = Settings::getInstance()->getString(MAIN_SECTION_TITLE, MAIN_MASTERKEY, MAIN_MASTERKEY_DEFAULT); 
     529    for (int i=0,j=0;i<len;i++,j++) { 
     530      if (j > key.size()) 
     531        j = 0; 
     532      outBuf[i] ^= key[j]; 
     533    } 
     534    outBuf[len] = 0; 
     535    *outBufLen = len; 
     536  } else { 
     537    *outBufLen = len; 
     538  } 
     539  return NSCAPI::isSuccess; 
     540} 
    408541 
    409542LPVOID NSAPILoader(char*buffer) { 
     
    412545  if (stricmp(buffer, "NSAPIGetApplicationVersionStr") == 0) 
    413546    return &NSAPIGetApplicationVersionStr; 
     547  if (stricmp(buffer, "NSAPIGetSettingsSection") == 0) 
     548    return &NSAPIGetSettingsSection; 
    414549  if (stricmp(buffer, "NSAPIGetSettingsString") == 0) 
    415550    return &NSAPIGetSettingsString; 
     
    424559  if (stricmp(buffer, "NSAPIGetBasePath") == 0) 
    425560    return &NSAPIGetBasePath; 
     561  if (stricmp(buffer, "NSAPICheckLogMessages") == 0) 
     562    return &NSAPICheckLogMessages; 
     563  if (stricmp(buffer, "NSAPIEncrypt") == 0) 
     564    return &NSAPIEncrypt; 
     565  if (stricmp(buffer, "NSAPIDecrypt") == 0) 
     566    return &NSAPIDecrypt; 
    426567  return NULL; 
    427568} 
  • /trunk/changelog

    r20 r30  
     12005-05-23 MickeM 
     2 + Added obfuscated password support 
     3 + Added some more debug info on commands (returncode, and input args) 
     4 + Added some more comments  ot the NSC.ini 
     5 + Added central password "override" 
     6 + Added central "host override" 
     7 + Fixed bug with external commands always getting WARNING state 
     8 
     92005-05-22 MickeM 
     10 + Added debug outout for command 
     11 + Added timestamps for log-to-file (date_mask to configure format) 
     12 + Added support for "no password" with check_nt 
     13 + Added log of bad password on NSClient requests. 
     14 * Some threading issues fixed (I hate threading :) 
     15 
     162005-05-19 MickeM 
     17 * Verified NT4 compatibility 
     18 
     192005-05-18 MickeM 
     20 * Fixed bug in NSC.ini (section title for Check System was wrong) 
     21 + Added multitasking for plug-ins (now two plug-ins can handle requests simultaneously) 
     22 * Fixed some minor issues here and there 
     23 
     242005-05-15 MickeM 
     25 + Added NRPE support for checkCounter 
     26 + Updated documentation 
     27 * Make check commands ignore case 
     28 + Added CheckHelpers module to alter the result of various check and similar things  
     29 
     302005-05-14 MickeM 
     31 + Added support for Volumes (CheckDisk) 
     32 + Added support for checking all drives of a certain kind 
     33 + Added support for altering filter (makes it possible to check removable drives) 
     34 + Created web page and better documentation 
     35 
     362005-04-20 MickeM 
     37 + Added multitasking to socket listener (it can now handle multiple connections) 
     38 * Fixed bug in NSClientListener now "seqv" in check_nt shouldn't happen. 
     39 + Added COUNTER support to NSClient and CheckSystem 
     40 
     412005-04-19 MickeM 
     42 + Added SSL support 
     43 + Added a lot of new options 
     44 + Added documentation 
     45 * Renamed and restructured NSCLientCompat to CheckSystem 
     46 * *ALOT* of fixes all over 
     47 : We are now starting to get to something that is "stable" 
     48 : This means that soon you might actually be able to use this. 
     49  
     502005-03-28 MickeM 
     51 * Changed the Thread class a bit (mutex -> signal, and CreatThread does not return the instance) 
     52 * Moved settings "keys" fro NRPE to config.h 
     53 * Changed build options (added Distribution) which builds a zip file under ./dist (requires 7z installed) 
     54 * Minor tweaks to error/debug logging and small fixes "here and there" 
     55 
     562005-03-26 MickeM 
     57 + NRPE Support (very basic, no encryption, and nothing fancy) 
     58 * Socket classes rewritten 
     59 + Added NSCModuleHelper::getSettingsSection to the API 
     60 
    1612005-03-22 MickeM 
    262 * Fixed NSClientListener return codes for basic commands 
     
    868 * Fixed BUG in inject command (now things should "work" again, but far from stable) 
    969 + Added NRPE return code 
    10  * Fixed some return states to NSClientListener (not verified yet, but soon they wil lbe back in order :) 
     70 * Fixed some return states to NSClientListener (not verified yet, but soon they will be back in order :) 
    1171 
    12722005-03-20 MickeM 
  • /trunk/NSCPlugin.h

    r16 r28  
    4242   * 
    4343   * @param file DLL filename (for which the exception is thrown) 
    44    * @param error An error message (human readable format) 
     44   * @param sError An error message (human readable format) 
    4545   * @param nError Error code to be appended at the end of the string 
    4646   * @todo Change this to be some form of standard error code and merge with above. 
     
    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++.h

    r16 r30  
    77#include <Mutex.h> 
    88#include <NSCAPI.h> 
     9#include <MutexRW.h> 
    910 
    1011 
     
    3738private: 
    3839  typedef NSCPlugin* plugin_type; 
    39   typedef std::list<plugin_type> pluginList; 
     40  typedef std::vector<plugin_type> pluginList; 
    4041  pluginList plugins_; 
    4142  pluginList commandHandlers_; 
    4243  pluginList messageHandlers_; 
    4344  std::string basePath; 
    44   MutexHandler pluginMutex; 
     45  MutexHandler internalVariables; 
    4546  MutexHandler messageMutex; 
     47  MutexRW  m_mutexRW; 
    4648 
    4749public: 
     
    5759 
    5860  // Member functions 
    59   static std::string getPassword(void); 
    6061  std::string getBasePath(void); 
    6162  NSCAPI::nagiosReturn injectRAW(const char* command, const unsigned int argLen, char **argument, char *returnMessageBuffer, unsigned int returnMessageBufferLen, char *returnPerfBuffer, unsigned int returnPerfBufferLen); 
     63  NSCAPI::nagiosReturn NSClientT::inject(std::string command, std::string arguments, char splitter, std::string &msg, std::string & perf); 
    6264//  std::string inject(const std::string buffer); 
    6365  std::string execute(std::string password, std::string cmd, std::list<std::string> args); 
     
    6971  void unloadPlugins(void); 
    7072 
     73  bool logDebug(); 
     74 
    7175private: 
    7276  void addPlugin(plugin_type plugin); 
     
    7579 
    7680typedef NTService<NSClientT> NSClient; 
     81 
     82 
     83std::string Encrypt(std::string str, unsigned int algorithm = NSCAPI::xor); 
     84std::string Decrypt(std::string str, unsigned int algorithm = NSCAPI::xor); 
    7785 
    7886////////////////////////////////////////////////////////////////////////// 
     
    9199void NSAPIStopServer(void); 
    92100NSCAPI::nagiosReturn NSAPIInject(const char* command, const unsigned int argLen, char **argument, char *returnMessageBuffer, unsigned int returnMessageBufferLen, char *returnPerfBuffer, unsigned int returnPerfBufferLen); 
    93  
     101NSCAPI::errorReturn NSAPIGetSettingsSection(const char*, char***, unsigned int *); 
     102NSCAPI::boolReturn NSAPICheckLogMessages(int messageType); 
     103NSCAPI::errorReturn NSAPIEncrypt(unsigned int algorithm, const char* inBuffer, unsigned int inBufLen, char* outBuf, unsigned int *outBufLen); 
     104NSCAPI::errorReturn NSAPIDecrypt(unsigned int algorithm, const char* inBuffer, unsigned int inBufLen, char* outBuf, unsigned int *outBufLen); 
    94105////////////////////////////////////////////////////////////////////////// 
    95106// Log macros to simplify logging 
     
    106117#define LOG_MESSAGE(msg) \ 
    107118  NSAPIMessage(NSCAPI::log, __FILE__, __LINE__, msg) 
     119 
    108120#define LOG_DEBUG_STD(msg) LOG_DEBUG(((std::string)msg).c_str()) 
    109121#define LOG_DEBUG(msg) \ 
    110122  NSAPIMessage(NSCAPI::debug, __FILE__, __LINE__, msg) 
     123/* 
     124#define LOG_DEBUG_STD(msg) 
     125#define LOG_DEBUG(msg) 
     126*/ 
  • /trunk/NSClient++.sln

    r15 r28  
    22Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NSClient++", "NSClient++.vcproj", "{2286162D-7571-4735-BAC8-4A8D33A4F42D}" 
    33  ProjectSection(ProjectDependencies) = postProject 
     4    {BA246C01-063A-4548-8957-32D5CC76171B} = {BA246C01-063A-4548-8957-32D5CC76171B} 
     5    {BBFF8362-C626-4838-B0A2-F695D638AD24} = {BBFF8362-C626-4838-B0A2-F695D638AD24} 
     6    {08D6246D-1B4A-47A3-965D-296DCC54A4E8} = {08D6246D-1B4A-47A3-965D-296DCC54A4E8} 
     7    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45} = {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45} 
     8    {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F} = {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F} 
     9    {2FF60AF6-09AA-49AB-B414-2E8FD01655C6} = {2FF60AF6-09AA-49AB-B414-2E8FD01655C6} 
    410  EndProjectSection 
    511EndProject 
    612Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SysTray", "modules\SysTray\SysTray.vcproj", "{BBFF8362-C626-4838-B0A2-F695D638AD24}" 
    7   ProjectSection(ProjectDependencies) = postProject 
    8   EndProjectSection 
    9 EndProject 
    10 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NSClientCompat", "modules\NSClientCompat\NSClientCompat.vcproj", "{79F1F571-78A6-4B20-8BD5-0F65CD60012C}" 
    1113  ProjectSection(ProjectDependencies) = postProject 
    1214  EndProjectSection 
     
    3234  EndProjectSection 
    3335EndProject 
     36Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CheckSystem", "modules\CheckSystem\CheckSystem.vcproj", "{2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}" 
     37  ProjectSection(ProjectDependencies) = postProject 
     38  EndProjectSection 
     39EndProject 
     40Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CheckHelpers", "modules\CheckHelpers\CheckHelpers.vcproj", "{E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}" 
     41  ProjectSection(ProjectDependencies) = postProject 
     42  EndProjectSection 
     43EndProject 
    3444Global 
    3545  GlobalSection(DPCodeReviewSolutionGUID) = preSolution 
     
    3848  GlobalSection(SolutionConfiguration) = preSolution 
    3949    Debug = Debug 
     50    Distribution = Distribution 
    4051    Release = Release 
    4152  EndGlobalSection 
     
    4354    {2286162D-7571-4735-BAC8-4A8D33A4F42D}.Debug.ActiveCfg = Debug|Win32 
    4455    {2286162D-7571-4735-BAC8-4A8D33A4F42D}.Debug.Build.0 = Debug|Win32 
     56    {2286162D-7571-4735-BAC8-4A8D33A4F42D}.Distribution.ActiveCfg = Distribution|Win32 
     57    {2286162D-7571-4735-BAC8-4A8D33A4F42D}.Distribution.Build.0 = Distribution|Win32 
    4558    {2286162D-7571-4735-BAC8-4A8D33A4F42D}.Release.ActiveCfg = Release|Win32 
    4659    {2286162D-7571-4735-BAC8-4A8D33A4F42D}.Release.Build.0 = Release|Win32 
    4760    {BBFF8362-C626-4838-B0A2-F695D638AD24}.Debug.ActiveCfg = Debug|Win32 
    4861    {BBFF8362-C626-4838-B0A2-F695D638AD24}.Debug.Build.0 = Debug|Win32 
     62    {BBFF8362-C626-4838-B0A2-F695D638AD24}.Distribution.ActiveCfg = Distribution|Win32 
     63    {BBFF8362-C626-4838-B0A2-F695D638AD24}.Distribution.Build.0 = Distribution|Win32 
    4964    {BBFF8362-C626-4838-B0A2-F695D638AD24}.Release.ActiveCfg = Release|Win32 
    5065    {BBFF8362-C626-4838-B0A2-F695D638AD24}.Release.Build.0 = Release|Win32 
    51     {79F1F571-78A6-4B20-8BD5-0F65CD60012C}.Debug.ActiveCfg = Debug|Win32 
    52     {79F1F571-78A6-4B20-8BD5-0F65CD60012C}.Debug.Build.0 = Debug|Win32 
    53     {79F1F571-78A6-4B20-8BD5-0F65CD60012C}.Release.ActiveCfg = Release|Win32 
    54     {79F1F571-78A6-4B20-8BD5-0F65CD60012C}.Release.Build.0 = Release|Win32 
    5566    {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F}.Debug.ActiveCfg = Debug|Win32 
    5667    {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F}.Debug.Build.0 = Debug|Win32 
     68    {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F}.Distribution.ActiveCfg = Distribution|Win32 
     69    {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F}.Distribution.Build.0 = Distribution|Win32 
    5770    {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F}.Release.ActiveCfg = Release|Win32 
    5871    {62B685D7-3A2E-4F3E-B2B8-B17F20C0217F}.Release.Build.0 = Release|Win32 
    5972    {BA246C01-063A-4548-8957-32D5CC76171B}.Debug.ActiveCfg = Debug|Win32 
    6073    {BA246C01-063A-4548-8957-32D5CC76171B}.Debug.Build.0 = Debug|Win32 
     74    {BA246C01-063A-4548-8957-32D5CC76171B}.Distribution.ActiveCfg = Distribution|Win32 
     75    {BA246C01-063A-4548-8957-32D5CC76171B}.Distribution.Build.0 = Distribution|Win32 
    6176    {BA246C01-063A-4548-8957-32D5CC76171B}.Release.ActiveCfg = Release|Win32 
    6277    {BA246C01-063A-4548-8957-32D5CC76171B}.Release.Build.0 = Release|Win32 
    63     {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.ActiveCfg = Debug Dynamic Linkage|Win32 
    64     {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.Build.0 = Debug Dynamic Linkage|Win32 
    65     {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.ActiveCfg = Dynamic Linkage|Win32 
    66     {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.Build.0 = Dynamic Linkage|Win32 
     78    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.ActiveCfg = Debug|Win32 
     79    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.Build.0 = Debug|Win32 
     80    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Distribution.ActiveCfg = Distribution|Win32 
     81    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Distribution.Build.0 = Distribution|Win32 
     82    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.ActiveCfg = Release|Win32 
     83    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.Build.0 = Release|Win32 
    6784    {2FF60AF6-09AA-49AB-B414-2E8FD01655C6}.Debug.ActiveCfg = Debug|Win32 
    6885    {2FF60AF6-09AA-49AB-B414-2E8FD01655C6}.Debug.Build.0 = Debug|Win32 
     86    {2FF60AF6-09AA-49AB-B414-2E8FD01655C6}.Distribution.ActiveCfg = Distribution|Win32 
     87    {2FF60AF6-09AA-49AB-B414-2E8FD01655C6}.Distribution.Build.0 = Distribution|Win32 
    6988    {2FF60AF6-09AA-49AB-B414-2E8FD01655C6}.Release.ActiveCfg = Release|Win32 
    7089    {2FF60AF6-09AA-49AB-B414-2E8FD01655C6}.Release.Build.0 = Release|Win32 
    7190    {08D6246D-1B4A-47A3-965D-296DCC54A4E8}.Debug.ActiveCfg = Debug|Win32 
    7291    {08D6246D-1B4A-47A3-965D-296DCC54A4E8}.Debug.Build.0 = Debug|Win32 
     92    {08D6246D-1B4A-47A3-965D-296DCC54A4E8}.Distribution.ActiveCfg = Distribution|Win32 
     93    {08D6246D-1B4A-47A3-965D-296DCC54A4E8}.Distribution.Build.0 = Distribution|Win32 
    7394    {08D6246D-1B4A-47A3-965D-296DCC54A4E8}.Release.ActiveCfg = Release|Win32 
    7495    {08D6246D-1B4A-47A3-965D-296DCC54A4E8}.Release.Build.0 = Release|Win32 
     96    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Debug.ActiveCfg = Debug|Win32 
     97    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Debug.Build.0 = Debug|Win32 
     98    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Distribution.ActiveCfg = Distribution|Win32 
     99    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Distribution.Build.0 = Distribution|Win32 
     100    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Release.ActiveCfg = Release|Win32 
     101    {2FCAF54B-AAD3-4F59-895A-8F9CEAFDC65D}.Release.Build.0 = Release|Win32 
     102    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.ActiveCfg = Debug|Win32 
     103    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.Build.0 = Debug|Win32 
     104    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Distribution.ActiveCfg = Distribution|Win32 
     105    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Distribution.Build.0 = Distribution|Win32 
     106    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.ActiveCfg = Release|Win32 
     107    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.Build.0 = Release|Win32 
    75108  EndGlobalSection 
    76109  GlobalSection(ExtensibilityGlobals) = postSolution 
  • /trunk/NSClient++.vcproj

    r15 r30  
    4040        SuppressStartupBanner="TRUE"/> 
    4141      <Tool 
    42         Name="VCCustomBuildTool"/> 
     42        Name="VCCustomBuildTool" 
     43        CommandLine="echo Copying dependency DLLs 
     44cmd /c &quot;copy $(InputDir)\dist_dll\*.* $(InputDir)\$(OutDir)\&quot; 
     45" 
     46        Outputs="$(InputDir)\$(OutDir)\msvcp71.dll"/> 
    4347      <Tool 
    4448        Name="VCLinkerTool" 
     
    143147        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
    144148    </Configuration> 
     149    <Configuration 
     150      Name="Distribution|Win32" 
     151      OutputDirectory="$(ConfigurationName)" 
     152      IntermediateDirectory="$(ConfigurationName)" 
     153      ConfigurationType="1" 
     154      UseOfMFC="0" 
     155      ATLMinimizesCRunTimeLibraryUsage="FALSE" 
     156      CharacterSet="2"> 
     157      <Tool 
     158        Name="VCCLCompilerTool" 
     159        Optimization="2" 
     160        InlineFunctionExpansion="1" 
     161        AdditionalIncludeDirectories="include" 
     162        PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE" 
     163        StringPooling="TRUE" 
     164        RuntimeLibrary="2" 
     165        EnableFunctionLevelLinking="TRUE" 
     166        UsePrecompiledHeader="3" 
     167        PrecompiledHeaderThrough="stdafx.h" 
     168        PrecompiledHeaderFile=".\Release/IconService.pch" 
     169        AssemblerListingLocation=".\Release/" 
     170        ObjectFile=".\Release/" 
     171        ProgramDataBaseFileName=".\Release/" 
     172        WarningLevel="3" 
     173        SuppressStartupBanner="TRUE"/> 
     174      <Tool 
     175        Name="VCCustomBuildTool" 
     176        CommandLine="echo Copying dependency DLLs 
     177cmd /c &quot;xcopy /Q /Y $(InputDir)\dist_dll\*.dll $(InputDir)\Dist\&quot; 
     178echo Removing old archive 
     179cmd /c &quot;del $(InputDir)\Dist\$(InputName).zip&quot; 
     180echo Copying documenation 
     181mkdir $(TargetDir)\docs 
     182xcopy /s /e /c /q /y $(InputDir)\docs $(TargetDir)\docs 
     183echo Making archive 
     1847z.exe a -r -tzip -bd $(InputDir)\Dist\$(InputName).zip $(InputDir)\Dist\* 
     185" 
     186        Outputs="$(InputDir)\Dist\$(ProjectName).zip"/> 
     187      <Tool 
     188        Name="VCLinkerTool" 
     189        AdditionalDependencies="kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib" 
     190        OutputFile=".\Dist/NSClient++.exe" 
     191        LinkIncremental="1" 
     192        SuppressStartupBanner="TRUE" 
     193        IgnoreAllDefaultLibraries="FALSE" 
     194        IgnoreDefaultLibraryNames="" 
     195        ModuleDefinitionFile="" 
     196        ProgramDatabaseFile=".\Release/IconService.pdb" 
     197        SubSystem="1" 
     198        OptimizeForWindows98="1" 
     199        TargetMachine="1"/> 
     200      <Tool 
     201        Name="VCMIDLTool" 
     202        TypeLibraryName=".\Release/IconService.tlb" 
     203        HeaderFileName=""/> 
     204      <Tool 
     205        Name="VCPostBuildEventTool"/> 
     206      <Tool 
     207        Name="VCPreBuildEventTool"/> 
     208      <Tool 
     209        Name="VCPreLinkEventTool"/> 
     210      <Tool 
     211        Name="VCResourceCompilerTool" 
     212        PreprocessorDefinitions="NDEBUG" 
     213        Culture="1036" 
     214        AdditionalIncludeDirectories="./res/"/> 
     215      <Tool 
     216        Name="VCWebServiceProxyGeneratorTool"/> 
     217      <Tool 
     218        Name="VCXMLDataGeneratorTool"/> 
     219      <Tool 
     220        Name="VCWebDeploymentTool"/> 
     221      <Tool 
     222        Name="VCManagedWrapperGeneratorTool"/> 
     223      <Tool 
     224        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
     225    </Configuration> 
    145226  </Configurations> 
    146227  <References> 
     
    151232      Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"> 
    152233      <File 
     234        RelativePath=".\include\arrayBuffer.cpp"> 
     235      </File> 
     236      <File 
     237        RelativePath=".\include\b64\b64.c"> 
     238        <FileConfiguration 
     239          Name="Release|Win32"> 
     240          <Tool 
     241            Name="VCCLCompilerTool" 
     242            UsePrecompiledHeader="0"/> 
     243        </FileConfiguration> 
     244        <FileConfiguration 
     245          Name="Debug|Win32"> 
     246          <Tool 
     247            Name="VCCLCompilerTool" 
     248            UsePrecompiledHeader="0"/> 
     249        </FileConfiguration> 
     250        <FileConfiguration 
     251          Name="Distribution|Win32"> 
     252          <Tool 
     253            Name="VCCLCompilerTool" 
     254            UsePrecompiledHeader="0"/> 
     255        </FileConfiguration> 
     256      </File> 
     257      <File 
    153258        RelativePath=".\include\NSCHelper.cpp"> 
    154259      </File> 
     
    157262      </File> 
    158263      <File 
    159         RelativePath=".\NSClient++.def"> 
    160       </File> 
    161       <File 
    162264        RelativePath=".\NSCPlugin.cpp"> 
    163265      </File> 
    164266      <File 
    165267        RelativePath=".\include\ServiceCmd.cpp"> 
     268      </File> 
     269      <File 
     270        RelativePath=".\include\Socket.cpp"> 
    166271      </File> 
    167272      <File 
     
    184289            UsePrecompiledHeader="1"/> 
    185290        </FileConfiguration> 
     291        <FileConfiguration 
     292          Name="Distribution|Win32"> 
     293          <Tool 
     294            Name="VCCLCompilerTool" 
     295            Optimization="2" 
     296            PreprocessorDefinitions="" 
     297            UsePrecompiledHeader="1"/> 
     298        </FileConfiguration> 
    186299      </File> 
    187300    </Filter> 
     
    190303      Filter="h;hpp;hxx;hm;inl"> 
    191304      <File 
     305        RelativePath=".\include\arrayBuffer.h"> 
     306      </File> 
     307      <File 
    192308        RelativePath=".\include\charEx.h"> 
    193309      </File> 
    194310      <File 
    195         RelativePath=".\config.h"> 
     311        RelativePath=".\include\config.h"> 
    196312      </File> 
    197313      <File 
    198314        RelativePath=".\include\Mutex.h"> 
     315      </File> 
     316      <File 
     317        RelativePath=".\include\MutexRW.h"> 
    199318      </File> 
    200319      <File 
     
    232351      <File 
    233352        RelativePath=".\changelog"> 
     353        <FileConfiguration 
     354          Name="Distribution|Win32"> 
     355          <Tool 
     356            Name="VCCustomBuildTool" 
     357            CommandLine="echo Copying $(InputFileName)... 
     358cmd /c &quot;copy $(InputDir)\$(InputName) $(InputDir)\Dist\&quot; 
     359" 
     360            Outputs="$(InputDir)\Dist\$(InputFileName)"/> 
     361        </FileConfiguration> 
    234362      </File> 
    235363      <File 
    236364        RelativePath=".\Doxyfile"> 
    237365        <FileConfiguration 
    238           Name="Release|Win32"> 
     366          Name="Release|Win32" 
     367          ExcludedFromBuild="TRUE"> 
    239368          <Tool 
    240369            Name="VCCustomBuildTool" 
     
    251380"/> 
    252381        </FileConfiguration> 
     382        <FileConfiguration 
     383          Name="Distribution|Win32" 
     384          ExcludedFromBuild="TRUE"> 
     385          <Tool 
     386            Name="VCCustomBuildTool" 
     387            CommandLine="doxygen.exe $(InputPath) 
     388" 
     389            Outputs=".\Doc"/> 
     390        </FileConfiguration> 
    253391      </File> 
    254392      <File 
     
    258396        RelativePath=".\NSC.ini"> 
    259397        <FileConfiguration 
    260           Name="Release|Win32" 
    261           ExcludedFromBuild="TRUE"> 
    262           <Tool 
    263             Name="VCCustomBuildTool" 
    264             CommandLine="copy $(InputPath) $(OutDir)\$(InputFileName) 
     398          Name="Release|Win32"> 
     399          <Tool 
     400            Name="VCCustomBuildTool" 
     401            CommandLine="echo Copying $(InputFileName)... 
     402cmd /c &quot;copy $(InputDir)\$(InputFileName) $(InputDir)\$(OutDir)&quot; 
    265403" 
    266404            AdditionalDependencies="" 
    267             Outputs="$(OutDir)\$(InputFileName)"/> 
    268         </FileConfiguration> 
    269         <FileConfiguration 
    270           Name="Debug|Win32" 
    271           ExcludedFromBuild="TRUE"> 
    272           <Tool 
    273             Name="VCCustomBuildTool" 
    274             CommandLine="copy $(InputPath) $(OutDir)\$(InputFileName) 
    275 " 
    276             Outputs="$(OutDir)\$(InputFileName)"/> 
     405            Outputs="$(InputDir)\$(OutDir)\$(InputFileName)"/> 
     406        </FileConfiguration> 
     407        <FileConfiguration 
     408          Name="Debug|Win32"> 
     409          <Tool 
     410            Name="VCCustomBuildTool" 
     411            CommandLine="echo Copying $(InputFileName)... 
     412cmd /c &quot;copy $(InputDir)\$(InputFileName) $(InputDir)\$(OutDir)&quot; 
     413" 
     414            Outputs="$(InputDir)\$(OutDir)\$(InputFileName)"/> 
     415        </FileConfiguration> 
     416        <FileConfiguration 
     417          Name="Distribution|Win32"> 
     418          <Tool 
     419            Name="VCCustomBuildTool" 
     420            CommandLine="echo Copying $(InputFileName)... 
     421cmd /c &quot;copy $(InputDir)\$(InputFileName) $(InputDir)\Dist\&quot; 
     422" 
     423            AdditionalDependencies="" 
     424            Outputs="$(InputDir)\Dist\$(InputFileName)"/> 
     425        </FileConfiguration> 
     426      </File> 
     427      <File 
     428        RelativePath=".\readme.html"> 
     429      </File> 
     430      <File 
     431        RelativePath=".\readme.txt"> 
     432        <FileConfiguration 
     433          Name="Release|Win32"> 
     434          <Tool 
     435            Name="VCCustomBuildTool" 
     436            CommandLine="" 
     437            Outputs=""/> 
     438        </FileConfiguration> 
     439        <FileConfiguration 
     440          Name="Debug|Win32"> 
     441          <Tool 
     442            Name="VCCustomBuildTool" 
     443            CommandLine="" 
     444            Outputs=""/> 
     445        </FileConfiguration> 
     446        <FileConfiguration 
     447          Name="Distribution|Win32"> 
     448          <Tool 
     449            Name="VCCustomBuildTool" 
     450            CommandLine="echo Copying $(InputFileName)... 
     451cmd /c &quot;copy $(InputDir)\$(InputFileName) $(InputDir)\Dist\&quot; 
     452" 
     453            Outputs="$(InputDir)\Dist\$(InputFileName)"/> 
    277454        </FileConfiguration> 
    278455      </File> 
  • /trunk/modules/FileLogger/stdafx.h

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

    r3 r30  
    44#include "stdafx.h" 
    55#include "FileLogger.h" 
     6 
     7#include <sys/timeb.h> 
     8#include <time.h> 
    69 
    710FileLogger gFileLogger; 
     
    1821} 
    1922 
     23std::string FileLogger::getFileName() 
     24{ 
     25  if (file_.empty()) { 
     26    file_ = NSCModuleHelper::getSettingsString(LOG_SECTION_TITLE, LOG_FILENAME, LOG_FILENAME_DEFAULT); 
     27    if (file_.find("\\") == std::string::npos) 
     28      file_ = NSCModuleHelper::getBasePath() + "\\" + file_; 
     29  } 
     30  return file_; 
     31} 
     32 
    2033bool FileLogger::loadModule() { 
    21   file_ = NSCModuleHelper::getSettingsString("log", "file", "nsclient.log"); 
     34  _tzset(); 
     35  getFileName(); 
     36  format_ = NSCModuleHelper::getSettingsString(LOG_SECTION_TITLE, LOG_DATEMASK, LOG_DATEMASK_DEFAULT); 
    2237  return true; 
    2338} 
     
    2641} 
    2742std::string FileLogger::getModuleName() { 
    28   return "Simple console logger (used for debug purposes)."; 
     43  return "File logger: " + getFileName(); 
    2944} 
    3045NSCModuleWrapper::module_version FileLogger::getModuleVersion() { 
     
    3954} 
    4055void FileLogger::handleMessage(int msgType, char* file, int line, char* message) { 
     56  char buffer[64]; 
    4157  std::ofstream stream(file_.c_str(), std::ios::app); 
    42   stream << NSCHelper::translateMessageType(msgType) << ":" << file << ":" << line << ": " << message << std::endl; 
     58  __time64_t ltime; 
     59  _time64( &ltime ); 
     60  struct tm *today = _localtime64( &ltime ); 
     61  if (today) { 
     62    int len = strftime(buffer, 63, format_.c_str(), today); 
     63    if ((len < 1)||(len > 64)) 
     64      strncpy(buffer, "???", 63); 
     65    else 
     66      buffer[len] = 0; 
     67  } else { 
     68    strncpy(buffer, "???", 63); 
     69  } 
     70  stream << buffer << ": " << NSCHelper::translateMessageType(msgType) << ":" << file << ":" << line << ": " << message << std::endl; 
    4371} 
    4472 
  • /trunk/modules/FileLogger/FileLogger.vcproj

    r15 r24  
    111111        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
    112112    </Configuration> 
     113    <Configuration 
     114      Name="Distribution|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="../../Dist/modules/$(ProjectName).dll" 
     133        LinkIncremental="1" 
     134        ModuleDefinitionFile="FileLogger.def" 
     135        GenerateDebugInformation="TRUE" 
     136        SubSystem="2" 
     137        OptimizeReferences="2" 
     138        EnableCOMDATFolding="2" 
     139        ImportLibrary="$(OutDir)/FileLogger.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> 
    113162  </Configurations> 
    114163  <References> 
     
    119168      Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" 
    120169      UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> 
     170      <File 
     171        RelativePath="..\..\include\arrayBuffer.cpp"> 
     172      </File> 
    121173      <File 
    122174        RelativePath=".\FileLogger.cpp"> 
     
    139191            UsePrecompiledHeader="1"/> 
    140192        </FileConfiguration> 
     193        <FileConfiguration 
     194          Name="Distribution|Win32"> 
     195          <Tool 
     196            Name="VCCLCompilerTool" 
     197            UsePrecompiledHeader="1"/> 
     198        </FileConfiguration> 
    141199      </File> 
    142200    </Filter> 
     
    145203      Filter="h;hpp;hxx;hm;inl;inc;xsd" 
    146204      UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> 
     205      <File 
     206        RelativePath="..\..\include\config.h"> 
     207      </File> 
    147208      <File 
    148209        RelativePath=".\FileLogger.h"> 
  • /trunk/modules/FileLogger/FileLogger.h

    r3 r30  
    66private: 
    77  std::string file_; 
     8  std::string format_; 
    89 
    910public: 
     
    1920  void handleMessage(int msgType, char* file, int line, char* message); 
    2021  int handleCommand(char* command, char **argument, char *returnBuffer, int returnBufferLen); 
     22 
     23 
     24  std::string getFileName(); 
    2125}; 
  • /trunk/modules/CheckEventLog/CheckEventLog.cpp

    r16 r28  
    296296#define BUFFER_SIZE 1024*64 
    297297 
    298 NSCAPI::nagiosReturn CheckEventLog::handleCommand(const std::string command, const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
     298NSCAPI::nagiosReturn CheckEventLog::handleCommand(const strEx::blindstr command, const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
    299299  if (command != "CheckEventLog") 
    300300    return NSCAPI::returnIgnored; 
    301301  NSCAPI::nagiosReturn rCode = NSCAPI::returnOK; 
    302   std::list<std::string> args = NSCHelper::arrayBuffer2list(argLen, char_args); 
     302  std::list<std::string> args = arrayBuffer::arrayBuffer2list(argLen, char_args); 
    303303  if (args.size() < 2) { 
    304304    message = "Missing argument"; 
    305305    return NSCAPI::returnCRIT; 
     306  } 
     307 
     308  std::list<std::string>::iterator it = args.begin(); 
     309  for (;it != args.end();it++) { 
     310    NSC_DEBUG_MSG_STD("Arguments: " + (*it)); 
    306311  } 
    307312  std::string ret; 
     
    400405 
    401406  CloseEventLog(hLog); 
    402   if (critical) 
     407  if (critical) { 
    403408    ret = "CRITICAL: " + ret; 
    404   else if (!ret.empty()) 
     409    rCode = NSCAPI::returnCRIT; 
     410  } 
     411  else if (!ret.empty()) { 
    405412    ret = "WARNING: " + ret; 
    406   else  
     413    rCode = NSCAPI::returnWARN; 
     414  } else  
    407415    ret = "OK: No errors/warnings in event log."; 
    408416  if (query.truncate != 0) 
  • /trunk/modules/CheckEventLog/CheckEventLog.vcproj

    r15 r22  
    7171        Optimization="0" 
    7272        AdditionalIncludeDirectories="../include;../../include" 
    73         PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_STLP_USE_NEWALLOC;_STLP_DEBUG=1" 
     73        PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_STLP_USE_NEWALLOC;_STLP_DEBUG=1;BOOST_REGEX_DYN_LINK" 
    7474        MinimalRebuild="TRUE" 
    7575        BasicRuntimeChecks="3" 
     
    8989        ProgramDatabaseFile="$(OutDir)/CheckEventLog.pdb" 
    9090        SubSystem="2" 
     91        ImportLibrary="$(OutDir)/CheckEventLog.lib" 
     92        TargetMachine="1"/> 
     93      <Tool 
     94        Name="VCMIDLTool"/> 
     95      <Tool 
     96        Name="VCPostBuildEventTool"/> 
     97      <Tool 
     98        Name="VCPreBuildEventTool" 
     99        ExcludedFromBuild="TRUE"/> 
     100      <Tool 
     101        Name="VCPreLinkEventTool"/> 
     102      <Tool 
     103        Name="VCResourceCompilerTool"/> 
     104      <Tool 
     105        Name="VCWebServiceProxyGeneratorTool"/> 
     106      <Tool 
     107        Name="VCXMLDataGeneratorTool"/> 
     108      <Tool 
     109        Name="VCWebDeploymentTool"/> 
     110      <Tool 
     111        Name="VCManagedWrapperGeneratorTool"/> 
     112      <Tool 
     113        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
     114    </Configuration> 
     115    <Configuration 
     116      Name="Distribution|Win32" 
     117      OutputDirectory="$(ConfigurationName)" 
     118      IntermediateDirectory="$(ConfigurationName)" 
     119      ConfigurationType="2" 
     120      CharacterSet="2"> 
     121      <Tool 
     122        Name="VCCLCompilerTool" 
     123        AdditionalIncludeDirectories="../include;../../include" 
     124        PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;BOOST_REGEX_DYN_LINK" 
     125        RuntimeLibrary="2" 
     126        UsePrecompiledHeader="3" 
     127        WarningLevel="3" 
     128        Detect64BitPortabilityProblems="TRUE" 
     129        DebugInformationFormat="3"/> 
     130      <Tool 
     131        Name="VCCustomBuildTool"/> 
     132      <Tool 
     133        Name="VCLinkerTool" 
     134        OutputFile="../../Dist/modules/$(ProjectName).dll" 
     135        LinkIncremental="1" 
     136        ModuleDefinitionFile="CheckEventLog.def" 
     137        GenerateDebugInformation="TRUE" 
     138        SubSystem="2" 
     139        OptimizeReferences="2" 
     140        EnableCOMDATFolding="2" 
    91141        ImportLibrary="$(OutDir)/CheckEventLog.lib" 
    92142        TargetMachine="1"/> 
     
    121171      Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" 
    122172      UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> 
     173      <File 
     174        RelativePath="..\..\include\arrayBuffer.cpp"> 
     175      </File> 
    123176      <File 
    124177        RelativePath=".\CheckEventLog.cpp"> 
     
    141194            UsePrecompiledHeader="1"/> 
    142195        </FileConfiguration> 
     196        <FileConfiguration 
     197          Name="Distribution|Win32"> 
     198          <Tool 
     199            Name="VCCLCompilerTool" 
     200            UsePrecompiledHeader="1"/> 
     201        </FileConfiguration> 
    143202      </File> 
    144203    </Filter> 
  • /trunk/modules/CheckEventLog/CheckEventLog.h

    r16 r28  
    11NSC_WRAPPERS_MAIN(); 
     2 
     3#include <strEx.h> 
    24 
    35class CheckEventLog { 
     
    1416  bool hasCommandHandler(); 
    1517  bool hasMessageHandler(); 
    16   NSCAPI::nagiosReturn handleCommand(const std::string command, const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
     18  NSCAPI::nagiosReturn handleCommand(const strEx::blindstr command, const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
    1719}; 
  • /trunk/modules/NSClientCompat/PDHCollector.cpp

    r13 r22  
    2222 
    2323 
    24 PDHCollector::PDHCollector() : cpu(BACK_INTERVAL*60/CHECK_INTERVAL), running_(true) { 
     24PDHCollector::PDHCollector() : cpu(BACK_INTERVAL*60/CHECK_INTERVAL), hStopEvent_(NULL) { 
    2525} 
    2626PDHCollector::~PDHCollector()  
    2727{ 
    28 } 
    29  
    30 /** 
    31  * Check running status (mutex locked) 
    32  * @return current status of the running flag (or false if we could  not get the mutex, though this is most likely a critical state) 
    33  */ 
    34 bool PDHCollector::isRunning(void) { 
    35   MutexLock mutex(mutexHandler); 
    36   if (!mutex.hasMutex()) { 
    37     NSC_LOG_ERROR("Failed to get Mutex!"); 
    38     return false; 
    39   } 
    40   return running_; 
    41 } 
    42 /** 
    43  * set running status (to stopped)  
    44  */ 
    45 void PDHCollector::stopRunning(void) { 
    46   MutexLock mutex(mutexHandler); 
    47   if (!mutex.hasMutex()) { 
    48     NSC_LOG_ERROR("Failed to get Mutex!"); 
    49     return; 
    50   } 
    51   running_ = false; 
    52 } 
    53 /** 
    54  *set running status (to started)  
    55  */ 
    56 void PDHCollector::startRunning(void) { 
    57   MutexLock mutex(mutexHandler); 
    58   if (!mutex.hasMutex()) { 
    59     NSC_LOG_ERROR("Failed to get Mutex!"); 
    60     return; 
    61   } 
    62   running_ = true; 
     28  if (hStopEvent_) 
     29    CloseHandle(hStopEvent_); 
    6330} 
    6431 
     
    9259  } 
    9360 
    94   startRunning(); 
    95   while(isRunning()) { 
    96     { 
    97       MutexLock mutex(mutexHandler); 
    98       if (!mutex.hasMutex())  
    99         NSC_LOG_ERROR("Failed to get Mutex!"); 
    100       else { 
    101         try { 
    102           pdh.collect(); 
    103         } catch (const PDH::PDHException &e) { 
    104           NSC_LOG_ERROR_STD("Failed to query performance counters: " + e.str_); 
    105         } 
    106       } 
    107     } 
    108     Sleep(CHECK_INTERVAL*1000); 
     61  hStopEvent_ = CreateEvent(NULL, TRUE, FALSE, NULL); 
     62  if (!hStopEvent_) { 
     63    NSC_LOG_ERROR_STD("Create StopEvent failed: " + strEx::itos(GetLastError())); 
     64    return 0; 
    10965  } 
    11066 
     67  do { 
     68    MutexLock mutex(mutexHandler); 
     69    if (!mutex.hasMutex())  
     70      NSC_LOG_ERROR("Failed to get Mutex!"); 
     71    else { 
     72      try { 
     73        pdh.collect(); 
     74      } catch (const PDH::PDHException &e) { 
     75        NSC_LOG_ERROR_STD("Failed to query performance counters: " + e.str_); 
     76      } 
     77    }  
     78  }while (!(WaitForSingleObject(hStopEvent_, CHECK_INTERVAL*1000) == WAIT_OBJECT_0)); 
     79 
     80  if (!CloseHandle(hStopEvent_)) 
     81    NSC_LOG_ERROR_STD("Failed to close stopEvent handle: " + strEx::itos(GetLastError())); 
     82  else 
     83    hStopEvent_ = NULL; 
    11184  try { 
    11285    pdh.close(); 
     
    11487    NSC_LOG_ERROR_STD("Failed to close performance counters: " + e.str_); 
    11588  } 
    116   NSC_DEBUG_MSG("PDHCollector - shutdown!"); 
    11789  return 0; 
    11890} 
     
    12395 */ 
    12496void PDHCollector::exitThread(void) { 
    125   NSC_DEBUG_MSG("PDHCollector - Requesting shutdown!"); 
    126   stopRunning(); 
     97  if (hStopEvent_ == NULL) 
     98    NSC_LOG_ERROR("Failed to get Mutex!"); 
     99  else 
     100    if (!SetEvent(hStopEvent_)) { 
     101      NSC_LOG_ERROR_STD("SetStopEvent failed"); 
     102  } 
    127103} 
    128104/** 
  • /trunk/modules/NSClientCompat/NSClientCompat.cpp

    r20 r22  
    2626 * @return  
    2727 */ 
    28 NSClientCompat::NSClientCompat() : pdhCollector(NULL) {} 
     28NSClientCompat::NSClientCompat() {} 
    2929/** 
    3030 * Default d-tor 
     
    3838 */ 
    3939bool NSClientCompat::loadModule() { 
    40   pdhCollector = pdhThread.createThread(); 
     40  pdhThread.createThread(); 
    4141  return true; 
    4242} 
     
    110110  std::list<std::string> stl_args; 
    111111  NSClientCompat::returnBundle rb; 
     112  if (command == "checkCPU") { 
     113    stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args); 
     114    if (stl_args.empty()) { 
     115      msg = "ERROR: Missing argument exception."; 
     116      return NSCAPI::returnUNKNOWN; 
     117    } 
     118    int warn; 
     119    int crit; 
     120    msg = "CPU Load: "; 
     121    NSCAPI::nagiosReturn ret = NSCAPI::returnOK; 
     122    for (arrayBuffer::arrayList::const_iterator it = stl_args.begin(); it != stl_args.end(); ++it) { 
     123      strEx::token t = strEx::getToken((*it), '='); 
     124      if (t.first == "crit") 
     125        crit = strEx::stoi(t.second); 
     126      else if (t.first == "warn") 
     127        warn = strEx::stoi(t.second); 
     128      else { 
     129        PDHCollector *pObject = pdhThread.getThread(); 
     130        assert(pObject); 
     131        int v = pObject->getCPUAvrage(strEx::stoi(*it)*(60/CHECK_INTERVAL)); 
     132        if (v == -1) { 
     133          msg = "ERROR: We don't collect data that far back."; 
     134          return NSCAPI::returnCRIT; 
     135        } else { 
     136          if (v > warn) 
     137            NSCHelper::escalteReturnCodeToWARN(ret); 
     138          if (v > crit) 
     139            NSCHelper::escalteReturnCodeToCRIT(ret); 
     140          msg += strEx::itos(v) + "% (" + (*it) + " min average) "; 
     141          perf += "'" + (*it) + " min average'=" + strEx::itos(v) + "%;" + strEx::itos(warn) + ";" + strEx::itos(crit) + "; "; 
     142        } 
     143      } 
     144    } 
     145    return ret; 
     146  } 
    112147 
    113148  int id = atoi(command.c_str()); 
    114   if (id == 0) 
     149  if (id == 0) { 
    115150    return NSCAPI::returnIgnored; 
     151  } 
    116152  switch (id) { 
    117153    case REQ_CLIENTVERSION: 
     
    123159      } 
    124160    case REQ_UPTIME: 
    125       msg= strEx::itos(pdhCollector->getUptime()); 
    126       return NSCAPI::returnOK; 
    127  
     161      { 
     162        PDHCollector *pObject = pdhThread.getThread(); 
     163        assert(pObject); 
     164        msg = strEx::itos(pObject->getUptime()); 
     165        return NSCAPI::returnOK; 
     166      } 
    128167    case REQ_CPULOAD: 
    129168      { 
     
    135174        while (!stl_args.empty()) { 
    136175          std::string s = stl_args.front(); stl_args.pop_front(); 
    137           int v = pdhCollector->getCPUAvrage(strEx::stoi(s)*(60/CHECK_INTERVAL)); 
     176          PDHCollector *pObject = pdhThread.getThread(); 
     177          assert(pObject); 
     178          int v = pObject->getCPUAvrage(strEx::stoi(s)*(60/CHECK_INTERVAL)); 
    138179          if (v == -1) { 
    139180            msg = "ERROR: We don't collect data that far back."; 
     
    160201 
    161202    case REQ_MEMUSE: 
    162       msg = strEx::itos(pdhCollector->getMemCommitLimit()) + "&" +  
    163         strEx::itos(pdhCollector->getMemCommit()); 
     203      { 
     204        PDHCollector *pObject = pdhThread.getThread(); 
     205        assert(pObject); 
     206        msg = strEx::itos(pObject->getMemCommitLimit()) + "&" +  
     207          strEx::itos(pObject->getMemCommit()); 
     208 
     209      } 
    164210      return NSCAPI::returnOK; 
    165211 
  • /trunk/modules/NSClientCompat/NSClientCompat.vcproj

    r20 r24  
    113113        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
    114114    </Configuration> 
     115    <Configuration 
     116      Name="Distribution|Win32" 
     117      OutputDirectory="$(ConfigurationName)" 
     118      IntermediateDirectory="$(ConfigurationName)" 
     119      ConfigurationType="2" 
     120      CharacterSet="2"> 
     121      <Tool 
     122        Name="VCCLCompilerTool" 
     123        AdditionalIncludeDirectories="../include;../../include" 
     124        PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS" 
     125        RuntimeLibrary="2" 
     126        UsePrecompiledHeader="3" 
     127        WarningLevel="3" 
     128        Detect64BitPortabilityProblems="TRUE" 
     129        DebugInformationFormat="3"/> 
     130      <Tool 
     131        Name="VCCustomBuildTool"/> 
     132      <Tool 
     133        Name="VCLinkerTool" 
     134        AdditionalDependencies="Pdh.lib" 
     135        OutputFile="../../Dist/modules/$(ProjectName).dll" 
     136        LinkIncremental="1" 
     137        ModuleDefinitionFile="NSClientCompat.def" 
     138        GenerateDebugInformation="TRUE" 
     139        SubSystem="2" 
     140        OptimizeReferences="2" 
     141        EnableCOMDATFolding="2" 
     142        ImportLibrary="$(OutDir)/NSClientCompat.lib" 
     143        TargetMachine="1"/> 
     144      <Tool 
     145        Name="VCMIDLTool"/> 
     146      <Tool 
     147        Name="VCPostBuildEventTool"/> 
     148      <Tool 
     149        Name="VCPreBuildEventTool"/> 
     150      <Tool 
     151        Name="VCPreLinkEventTool"/> 
     152      <Tool 
     153        Name="VCResourceCompilerTool"/> 
     154      <Tool 
     155        Name="VCWebServiceProxyGeneratorTool"/> 
     156      <Tool 
     157        Name="VCXMLDataGeneratorTool"/> 
     158      <Tool 
     159        Name="VCWebDeploymentTool"/> 
     160      <Tool 
     161        Name="VCManagedWrapperGeneratorTool"/> 
     162      <Tool 
     163        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
     164    </Configuration> 
    115165  </Configurations> 
    116166  <References> 
     
    156206            UsePrecompiledHeader="1"/> 
    157207        </FileConfiguration> 
     208        <FileConfiguration 
     209          Name="Distribution|Win32"> 
     210          <Tool 
     211            Name="VCCLCompilerTool" 
     212            UsePrecompiledHeader="1"/> 
     213        </FileConfiguration> 
    158214      </File> 
    159215    </Filter> 
     
    198254      UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"> 
    199255    </Filter> 
    200     <File 
    201       RelativePath=".\ReadMe.txt"> 
    202     </File> 
    203256  </Files> 
    204257  <Globals> 
  • /trunk/modules/NSClientCompat/PDHCollector.h

    r12 r22  
    2727private: 
    2828  MutexHandler mutexHandler; 
    29   bool running_; 
     29  HANDLE hStopEvent_; 
    3030 
    3131  PDHCollectors::StaticPDHCounterListener memCmtLim; 
  • /trunk/modules/NSClientCompat/NSClientCompat.h

    r19 r22  
    77private: 
    88  PDHCollectorThread pdhThread; 
    9   PDHCollector *pdhCollector; 
    109 
    1110public: 
  • /trunk/modules/NSClientListener/NSClientListener.cpp

    r15 r30  
    66#include <strEx.h> 
    77#include <time.h> 
     8#include <config.h> 
    89 
    910NSClientListener 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 // ... in the works ... 
     21//#define REQ_FILEAGE   9 // ! - not implemented Dont know how to use 
     22//#define REQ_INSTANCES 10  // ! - not implemented Dont know how to use 
    1023 
    1124BOOL APIENTRY DllMain( HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved) 
     
    1932NSClientListener::~NSClientListener() { 
    2033} 
    21  
     34std::string getAllowedHosts() { 
     35  std::string ret = NSCModuleHelper::getSettingsString(NRPE_SECTION_TITLE, MAIN_ALLOWED_HOSTS, ""); 
     36  if (ret.empty()) 
     37    ret = NSCModuleHelper::getSettingsString(MAIN_SECTION_TITLE, MAIN_ALLOWED_HOSTS, MAIN_ALLOWED_HOSTS_DEFAULT); 
     38  return ret; 
     39} 
    2240 
    2341bool NSClientListener::loadModule() { 
    24   socketThreadManager.createThread(NULL); 
     42  allowedHosts.setAllowedHosts(strEx::splitEx(getAllowedHosts(), ",")); 
     43  try { 
     44    socket.setHandler(this); 
     45    socket.StartListener(NSCModuleHelper::getSettingsInt(NSCLIENT_SECTION_TITLE, NSCLIENT_SETTINGS_PORT, NSCLIENT_SETTINGS_PORT_DEFAULT)); 
     46  } catch (simpleSocket::SocketException e) { 
     47    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
     48    return false; 
     49  } 
    2550  return true; 
    2651} 
    2752bool NSClientListener::unloadModule() { 
    28   socketThreadManager.exitThread(); 
     53  try { 
     54    socket.removeHandler(this); 
     55    socket.StopListener(); 
     56  } catch (simpleSocket::SocketException e) { 
     57    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
     58    return false; 
     59  } 
    2960  return true; 
    3061} 
     
    3869} 
    3970 
     71/** 
     72* Main command parser and delegator. 
     73* This also handles a lot of the simpler responses (though some are deferred to other helper functions) 
     74* 
     75#define REQ_CLIENTVERSION 1 // Works fine! 
     76#define REQ_CPULOAD   2 // Quirks 
     77- Needs settings for default buffer size (backlog) and possibly other things. 
     78- Buffer needs to be synced with the client (don't know the size of that) 
     79- I think the idea was that the buffer would recursive to make a smaller memory footprint. 
     80(ie. the first level buffer have samples from every second, next level samples from every minute, next level hours etc...) 
     81(and I don't know the status of this, doesn't seem to be that way) 
     82#define REQ_UPTIME      3 // Works fine! 
     83#define REQ_USEDDISKSPACE 4 // Works fine! 
     84#define REQ_SERVICESTATE  5 // Works fine! 
     85#define REQ_PROCSTATE   6 // Works fine! 
     86#define REQ_MEMUSE      7 // Works fine! 
     87//#define REQ_COUNTER   8 // ! - not implemented Have to look at this, if anyone has a sample let me know... 
     88//#define REQ_FILEAGE   9 // ! - not implemented Don't know how to use 
     89//#define REQ_INSTANCES 10  // ! - not implemented Don't know how to use 
     90* 
     91*/ 
     92 
     93 
     94std::string getPassword() { 
     95  static std::string password = ""; 
     96  if (password.empty()) { 
     97    password = NSCModuleHelper::getSettingsString(NSCLIENT_SECTION_TITLE, MAIN_OBFUSCATED_PASWD, MAIN_OBFUSCATED_PASWD_DEFAULT); 
     98    if (password.empty()) 
     99      password= NSCModuleHelper::getSettingsString(MAIN_SECTION_TITLE, MAIN_OBFUSCATED_PASWD, MAIN_OBFUSCATED_PASWD_DEFAULT); 
     100    if (!password.empty()) { 
     101      password = NSCModuleHelper::Decrypt(password); 
     102    } else { 
     103      password = NSCModuleHelper::getSettingsString(NSCLIENT_SECTION_TITLE, MAIN_SETTINGS_PWD, MAIN_SETTINGS_PWD_DEFAULT); 
     104      if (password.empty()) 
     105        password = NSCModuleHelper::getSettingsString(MAIN_SECTION_TITLE, MAIN_SETTINGS_PWD, MAIN_SETTINGS_PWD_DEFAULT); 
     106    } 
     107  } 
     108  return password; 
     109} 
     110 
     111std::string NSClientListener::parseRequest(std::string buffer)  { 
     112  strEx::token pwd = strEx::getToken(buffer, '&'); 
     113  std::string rPwd = getPassword(); 
     114  if ((pwd.first != rPwd) && ((pwd.first == "None") && (!rPwd.empty())) ) { 
     115    NSC_LOG_ERROR_STD("Invalid password (" + pwd.first + ")."); 
     116    return "ERROR: Invalid password.";  
     117  } if (pwd.second.empty()) 
     118    return "ERRRO: No command specified."; 
     119  strEx::token cmd = strEx::getToken(pwd.second, '&'); 
     120  if (cmd.first.empty()) 
     121    return "ERRRO: No command specified."; 
     122 
     123  int c = atoi(cmd.first.c_str()); 
     124 
     125  // prefix various commands 
     126  switch (c) { 
     127    case REQ_CPULOAD: 
     128      cmd.first = "checkCPU"; 
     129      cmd.second += "&nsclient"; 
     130      break; 
     131    case REQ_UPTIME: 
     132      cmd.first = "checkUpTime"; 
     133      cmd.second = "nsclient"; 
     134      break; 
     135    case REQ_USEDDISKSPACE: 
     136      cmd.first = "CheckDriveSize"; 
     137      cmd.second += "&nsclient"; 
     138      break; 
     139    case REQ_CLIENTVERSION: 
     140      { 
     141        std::string v = NSCModuleHelper::getSettingsString(NSCLIENT_SECTION_TITLE, NSCLIENT_SETTINGS_VERSION, NSCLIENT_SETTINGS_VERSION_DEFAULT); 
     142        if (v == "auto") 
     143          return NSCModuleHelper::getApplicationName() + " " + NSCModuleHelper::getApplicationVersionString(); 
     144        return v; 
     145      } 
     146    case REQ_SERVICESTATE: 
     147      cmd.first = "checkServiceState"; 
     148      cmd.second += "&nsclient"; 
     149      break; 
     150    case REQ_PROCSTATE: 
     151      cmd.first = "checkProcState"; 
     152      cmd.second += "&nsclient"; 
     153      break; 
     154    case REQ_MEMUSE: 
     155      cmd.first = "checkMem"; 
     156      cmd.second = "nsclient"; 
     157      break; 
     158    case REQ_COUNTER: 
     159      cmd.first = "checkCounter"; 
     160      cmd.second += "&nsclient"; 
     161      break; 
     162  } 
     163 
     164  std::string message, perf; 
     165  NSCAPI::nagiosReturn ret = NSCModuleHelper::InjectSplitAndCommand(cmd.first.c_str(), cmd.second.c_str(), '&', message, perf); 
     166  if (!NSCHelper::isNagiosReturnCode(ret)) { 
     167    if (message.empty()) 
     168      return "ERROR: Could not complete the request check log file for more information."; 
     169    return "ERROR: " + message; 
     170  } 
     171  switch (c) { 
     172    case REQ_UPTIME:    // Some check_nt commands has no return code syntax 
     173    case REQ_MEMUSE: 
     174    case REQ_CPULOAD: 
     175    case REQ_CLIENTVERSION: 
     176    case REQ_USEDDISKSPACE: 
     177    case REQ_COUNTER: 
     178      return message; 
     179 
     180    case REQ_SERVICESTATE:  // Some check_nt commands return the return code (coded as a string) 
     181    case REQ_PROCSTATE: 
     182      return NSCHelper::translateReturn(ret) + "&" + message; 
     183 
     184    default:        // "New" check_nscp also returns performance data 
     185      if (perf.empty()) 
     186        return NSCHelper::translateReturn(ret) + "&" + message; 
     187      return NSCHelper::translateReturn(ret) + "&" + message + "|" + perf; 
     188  } 
     189} 
     190 
     191void NSClientListener::onClose() 
     192{} 
     193 
     194void NSClientListener::onAccept(simpleSocket::Socket *client) { 
     195  if (!allowedHosts.inAllowedHosts(client->getAddrString())) { 
     196    NSC_LOG_ERROR("Unothorized access from: " + client->getAddrString()); 
     197    client->close(); 
     198    return; 
     199  } 
     200  simpleSocket::DataBuffer db; 
     201 
     202 
     203 
     204  for (int i=0;i<100;i++) { 
     205    client->readAll(db); 
     206    // @todo Make this check if a pcket is read instead of just if we have data 
     207    if (db.getLength() > 0) 
     208      break; 
     209    Sleep(100); 
     210  } 
     211  if (i == 100) { 
     212    NSC_LOG_ERROR_STD("Could not retrieve NSClient packet."); 
     213    client->close(); 
     214    return; 
     215  } 
     216 
     217 
     218 
     219//  client->readAll(db); 
     220  if (db.getLength() > 0) { 
     221    std::string incoming(db.getBuffer(), db.getLength()); 
     222//    NSC_DEBUG_MSG_STD("Incoming data: " + incoming); 
     223    std::string response = parseRequest(incoming); 
     224//    NSC_DEBUG_MSG("Outgoing data: " + response); 
     225    client->send(response.c_str(), static_cast<int>(response.length()), 0); 
     226  } 
     227  client->close(); 
     228} 
     229 
    40230NSC_WRAPPERS_MAIN_DEF(gNSClientListener); 
    41231NSC_WRAPPERS_IGNORE_MSG_DEF(); 
  • /trunk/modules/NSClientListener/NSClientListener.vcproj

    r20 r24  
    113113        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
    114114    </Configuration> 
     115    <Configuration 
     116      Name="Distribution|Win32" 
     117      OutputDirectory="$(ConfigurationName)" 
     118      IntermediateDirectory="$(ConfigurationName)" 
     119      ConfigurationType="2" 
     120      CharacterSet="2"> 
     121      <Tool 
     122        Name="VCCLCompilerTool" 
     123        AdditionalIncludeDirectories="../include;../../include" 
     124        PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS" 
     125        RuntimeLibrary="2" 
     126        UsePrecompiledHeader="3" 
     127        WarningLevel="3" 
     128        Detect64BitPortabilityProblems="TRUE" 
     129        DebugInformationFormat="3"/> 
     130      <Tool 
     131        Name="VCCustomBuildTool"/> 
     132      <Tool 
     133        Name="VCLinkerTool" 
     134        AdditionalDependencies="ws2_32.lib" 
     135        OutputFile="../../Dist/modules/$(ProjectName).dll" 
     136        LinkIncremental="1" 
     137        ModuleDefinitionFile="NSClientListener.def" 
     138        GenerateDebugInformation="TRUE" 
     139        SubSystem="2" 
     140        OptimizeReferences="2" 
     141        EnableCOMDATFolding="2" 
     142        ImportLibrary="$(OutDir)/NSClientListener.lib" 
     143        TargetMachine="1"/> 
     144      <Tool 
     145        Name="VCMIDLTool"/> 
     146      <Tool 
     147        Name="VCPostBuildEventTool"/> 
     148      <Tool 
     149        Name="VCPreBuildEventTool"/> 
     150      <Tool 
     151        Name="VCPreLinkEventTool"/> 
     152      <Tool 
     153        Name="VCResourceCompilerTool"/> 
     154      <Tool 
     155        Name="VCWebServiceProxyGeneratorTool"/> 
     156      <Tool 
     157        Name="VCXMLDataGeneratorTool"/> 
     158      <Tool 
     159        Name="VCWebDeploymentTool"/> 
     160      <Tool 
     161        Name="VCManagedWrapperGeneratorTool"/> 
     162      <Tool 
     163        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
     164    </Configuration> 
    115165  </Configurations> 
    116166  <References> 
     
    129179      <File 
    130180        RelativePath=".\NSClientListener.cpp"> 
    131       </File> 
    132       <File 
    133         RelativePath=".\NSClientSocket.cpp"> 
    134181      </File> 
    135182      <File 
     
    150197            UsePrecompiledHeader="1"/> 
    151198        </FileConfiguration> 
     199        <FileConfiguration 
     200          Name="Distribution|Win32"> 
     201          <Tool 
     202            Name="VCCLCompilerTool" 
     203            UsePrecompiledHeader="1"/> 
     204        </FileConfiguration> 
    152205      </File> 
    153206    </Filter> 
     
    163216      </File> 
    164217      <File 
     218        RelativePath="..\..\include\config.h"> 
     219      </File> 
     220      <File 
    165221        RelativePath=".\NSClientListener.h"> 
    166       </File> 
    167       <File 
    168         RelativePath=".\NSClientSocket.h"> 
    169222      </File> 
    170223      <File 
  • /trunk/modules/NSClientListener/NSClientSocket.cpp

    r20 r22  
    66 * Default c-tor 
    77 */ 
    8 NSClientSocket::NSClientSocket() : SimpleSocketListsner(DEFAULT_TCP_PORT) { 
     8NSClientSocket::NSClientSocket() { 
    99} 
    1010 
     
    1818  strEx::token pwd = strEx::getToken(buffer, '&'); 
    1919  NSC_DEBUG_MSG("Password: " + pwd.first); 
    20   if ( (pwd.first.empty()) || (pwd.first != NSCModuleHelper::getSettingsString("generic", "password", "")) ) 
     20  if ( (pwd.first.empty()) || (pwd.first != NSCModuleHelper::getSettingsString("NSClient", "password", "")) ) 
    2121    return "ERROR: Invalid password."; 
    2222  if (pwd.second.empty()) 
     
    4848} 
    4949 
    50 void NSClientSocket::onAccept(SOCKET client) { 
    51  
    52   readAllDataBlock rdb = readAll(client); 
    53   if (rdb.second > 0) { 
    54     NSC_DEBUG_MSG_STD("Incoming data length: " + strEx::itos((int)rdb.second)); 
    55     std::string incoming((char*)rdb.first, (unsigned int)rdb.second); 
     50void NSClientSocket::onAccept(simpleSocket::Socket client) { 
     51  if (!inAllowedHosts(client.getAddrString())) { 
     52    NSC_LOG_ERROR("Unothorized access from: " + client.getAddrString()); 
     53    client.close(); 
     54    return; 
     55  } 
     56  simpleSocket::DataBuffer db; 
     57  client.readAll(db); 
     58  if (db.getLength() > 0) { 
     59    std::string incoming(db.getBuffer(), db.getLength()); 
    5660    NSC_DEBUG_MSG_STD("Incoming data: " + incoming); 
    5761    std::string response = parseRequest(incoming); 
    5862    NSC_DEBUG_MSG("Outgoing data: " + response); 
    59     send(client, response.c_str(), static_cast<int>(response.length()), 0); 
     63    client.send(response.c_str(), static_cast<int>(response.length()), 0); 
    6064  } 
    61   delete [] rdb.first; 
    62   closesocket(client); 
     65  client.close(); 
    6366} 
  • /trunk/modules/NSClientListener/NSClientListener.h

    r15 r25  
    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   NSClientSocketThread socketThreadManager; 
     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/NSClientSocket.h

    r20 r22  
    11#pragma once 
    22#include "resource.h" 
    3 #include <Thread.h> 
    4 #include <Mutex.h> 
    5 #include <WinSock2.h> 
    6 #include <strEx.h> 
    7 #include <charEx.h> 
    83#include <Socket.h> 
    94/** 
     
    3126 * 
    3227 */ 
    33 class NSClientSocket : public SimpleSocketListsner { 
     28class NSClientSocket : public simpleSocket::Listener { 
    3429private: 
     30  strEx::splitList allowedHosts_; 
    3531 
    3632public: 
     
    3935 
    4036private: 
    41   virtual void onAccept(SOCKET client); 
     37  virtual void onAccept(simpleSocket::Socket client); 
    4238  std::string parseRequest(std::string buffer); 
     39  bool inAllowedHosts(std::string s) { 
     40    if (allowedHosts_.empty()) 
     41      return true; 
     42    strEx::splitList::const_iterator cit; 
     43    for (cit = allowedHosts_.begin();cit!=allowedHosts_.end();++cit) { 
     44      if ( (*cit) == s) 
     45        return true; 
     46    } 
     47    return false; 
     48  } 
     49 
     50public: 
     51  void setAllowedHosts(strEx::splitList allowedHosts) { 
     52    allowedHosts_ = allowedHosts; 
     53  } 
     54 
    4355}; 
    4456 
    45 #define DEFAULT_TCP_PORT 12489 
    4657 
    4758#define REQ_CLIENTVERSION 1 // Works fine! 
     
    5768 
    5869 
    59 typedef Thread<NSClientSocket> NSClientSocketThread; // Thread manager 
    60  
    61  
  • /trunk/modules/CheckDisk/CheckDisk.cpp

    r16 r30  
    66#include <strEx.h> 
    77#include <time.h> 
     8#include <utils.h> 
    89 
    910CheckDisk gCheckDisk; 
     
    8283} 
    8384 
     85 
     86#define MY_FILTER_UNKNOWN     0 
     87#define MY_FILTER_NO_ROOT_DIR 1 
     88#define MY_FILTER_REMOVABLE   2 
     89#define MY_FILTER_FIXED       4 
     90#define MY_FILTER_REMOTE      8 
     91#define MY_FILTER_CDROM       16 
     92#define MY_FILTER_RAMDISK     32 
     93 
     94NSCAPI::nagiosReturn CheckDisk::CheckDriveSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
     95  NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK; 
     96  std::list<std::string> args = arrayBuffer::arrayBuffer2list(argLen, char_args); 
     97  if (args.empty()) { 
     98    message = "Missing argument(s)."; 
     99    return NSCAPI::returnCRIT; 
     100  } 
     101 
     102  checkHolders::SizeMaxMinPercentage<> warn; 
     103  checkHolders::SizeMaxMinPercentage<> crit; 
     104  bool bShowAll = false; 
     105  bool bNSClient = false; 
     106  bool bCheckAll = false; 
     107 
     108  bool bFilter = false; 
     109  bool bFilterRemote = false; 
     110  bool bFilterRemovable = false; 
     111  bool bFilterFixed = false; 
     112  bool bFilterCDROM = false; 
     113  std::list<std::string> drives; 
     114 
     115  std::list<std::string>::const_iterator cit; 
     116  for (cit=args.begin();cit!=args.end();++cit) { 
     117    std::string arg = *cit; 
     118    std::pair<std::string,std::string> p = strEx::split(arg,"="); 
     119    if (p.first == "Drive") { 
     120      drives.push_back(p.second); 
     121    } else if (p.first == "MaxWarn") { 
     122      warn.max.set(p.second); 
     123    } else if (p.first == "MinWarn") { 
     124      warn.min.set(p.second); 
     125    } else if (p.first == "MaxCrit") { 
     126      crit.max.set(p.second); 
     127    } else if (p.first == "MinCrit") { 
     128      crit.min.set(p.second); 
     129    } else if (p.first == SHOW_ALL) { 
     130      bShowAll = true; 
     131    } else if (p.first == "nsclient") { 
     132      bNSClient = true; 
     133    } else if (p.first == "FilterType") { 
     134      bFilter = true; 
     135      if (p.second == "FIXED") { 
     136        bFilterFixed = true; 
     137      } else if (p.second == "CDROM") { 
     138        bFilterCDROM= true; 
     139      } else if (p.second == "REMOVABLE") { 
     140        bFilterRemovable = true; 
     141      } else if (p.second == "REMOTE") { 
     142        bFilterRemote= true; 
     143      } 
     144    } else if (p.first == "CheckAll") { 
     145      bCheckAll = true; 
     146    } else { 
     147      drives.push_back(p.first); 
     148    } 
     149  } 
     150 
     151  if (bCheckAll) { 
     152    DWORD dwDrives = GetLogicalDrives(); 
     153    int idx = 0; 
     154    while (dwDrives != 0) { 
     155      if (dwDrives & 0x1) { 
     156        std::string drv; 
     157        drv += static_cast<char>('A' + idx); drv += ":\\"; 
     158        UINT drvType = GetDriveType(drv.c_str()); 
     159        if ((!bFilter)&&(drvType == DRIVE_FIXED)) { 
     160          drives.push_back(drv); 
     161        } else if ((bFilter)&&(bFilterFixed)&&(drvType==DRIVE_FIXED)) { 
     162          drives.push_back(drv); 
     163        } else if ((bFilter)&&(bFilterCDROM)&&(drvType==DRIVE_CDROM)) { 
     164          drives.push_back(drv); 
     165        } else if ((bFilter)&&(bFilterRemote)&&(drvType==DRIVE_REMOTE)) { 
     166          drives.push_back(drv); 
     167        } else if ((bFilter)&&(bFilterRemovable)&&(drvType==DRIVE_REMOVABLE)) { 
     168          drives.push_back(drv); 
     169        } 
     170      } 
     171      idx++; 
     172      dwDrives >>= 1; 
     173    } 
     174  } 
     175 
     176  for (std::list<std::string>::iterator it = drives.begin();it!=drives.end();it++) { 
     177    std::string drive = (*it); 
     178    if (drive.length() == 1) 
     179      drive += ":"; 
     180    UINT drvType = GetDriveType(drive.c_str()); 
     181 
     182    if ((!bFilter)&&(drvType != DRIVE_FIXED)) { 
     183      message = "UNKNOWN: Drive is not a fixed drive: " + drive + " (it is a: " + strEx::itos(drvType) + ")"; 
     184      return NSCAPI::returnUNKNOWN; 
     185    } else if ((bFilter)&&(!bFilterFixed)&&(drvType==DRIVE_FIXED)) { 
     186      message = "UNKNOWN: Drive does not match the current filter: " + drive + " (it is a: " + strEx::itos(drvType) + ")"; 
     187      return NSCAPI::returnUNKNOWN; 
     188    } else if ((bFilter)&&(!bFilterCDROM)&&(drvType==DRIVE_CDROM)) { 
     189      message = "UNKNOWN: Drive does not match the current filter: " + drive + " (it is a: " + strEx::itos(drvType) + ")"; 
     190      return NSCAPI::returnUNKNOWN; 
     191    } else if ((bFilter)&&(!bFilterRemote)&&(drvType==DRIVE_REMOTE)) { 
     192      message = "UNKNOWN: Drive does not match the current filter: " + drive + " (it is a: " + strEx::itos(drvType) + ")"; 
     193      return NSCAPI::returnUNKNOWN; 
     194    } else if ((bFilter)&&(!bFilterRemovable)&&(drvType==DRIVE_REMOVABLE)) { 
     195      message = "UNKNOWN: Drive does not match the current filter: " + drive + " (it is a: " + strEx::itos(drvType) + ")"; 
     196      return NSCAPI::returnUNKNOWN; 
     197    } 
     198 
     199    ULARGE_INTEGER freeBytesAvailableToCaller; 
     200    ULARGE_INTEGER totalNumberOfBytes; 
     201    ULARGE_INTEGER totalNumberOfFreeBytes; 
     202    if (!GetDiskFreeSpaceEx(drive.c_str(), &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes)) { 
     203      message = "UNKNOWN: Could not get free space for: " + drive; 
     204      return NSCAPI::returnUNKNOWN; 
     205    } 
     206    //10597515264&80015491072 
     207 
     208    if (bNSClient) { 
     209      if (!message.empty()) 
     210        message += "&"; 
     211      message += strEx::itos(totalNumberOfFreeBytes.QuadPart); 
     212      message += "&"; 
     213      message += strEx::itos(totalNumberOfBytes.QuadPart); 
     214    } else { 
     215      std::string tStr; 
     216      checkHolders::drive_size usedSpace = totalNumberOfBytes.QuadPart-totalNumberOfFreeBytes.QuadPart; 
     217      checkHolders::drive_size totalSpace = totalNumberOfBytes.QuadPart; 
     218      if (crit.max.hasBounds() && crit.max.checkMAX(usedSpace, totalSpace)) { 
     219        tStr += crit.max.prettyPrint(drive, usedSpace, totalSpace) + " > critical"; 
     220        NSCHelper::escalteReturnCodeToCRIT(returnCode); 
     221      } else if (crit.min.hasBounds() && crit.min.checkMIN(usedSpace, totalSpace)) { 
     222        tStr = crit.min.prettyPrint(drive, usedSpace, totalSpace) + " < critical"; 
     223        NSCHelper::escalteReturnCodeToCRIT(returnCode); 
     224      } else if (warn.max.hasBounds() && warn.max.checkMAX(usedSpace, totalSpace)) { 
     225        tStr = warn.max.prettyPrint(drive, usedSpace, totalSpace) + " > warning"; 
     226        NSCHelper::escalteReturnCodeToWARN(returnCode); 
     227      } else if (warn.min.hasBounds() && warn.min.checkMIN(usedSpace, totalSpace)) { 
     228        tStr = warn.min.prettyPrint(drive, usedSpace, totalSpace) + " < warning"; 
     229        NSCHelper::escalteReturnCodeToWARN(returnCode); 
     230      } else if (bShowAll) { 
     231        tStr = drive + ": " + strEx::itos_as_BKMG(usedSpace); 
     232      } 
     233      perf += checkHolders::SizeMaxMinPercentage<>::printPerf(drive, usedSpace, totalSpace, warn, crit); 
     234      if (!message.empty() && !tStr.empty()) 
     235        message += ", "; 
     236      if (!tStr.empty()) 
     237        message += tStr; 
     238    } 
     239  } 
     240  if (message.empty()) 
     241    message = "All drive sizes are within bounds."; 
     242  else if (!bNSClient) 
     243    message = NSCHelper::translateReturn(returnCode) + ": " + message; 
     244  return returnCode; 
     245} 
     246 
    84247NSCAPI::nagiosReturn CheckDisk::CheckFileSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
    85248  // CheckFileSize 
    86   // request: CheckFileSize&<option>&<option>... 
     249  // request: CheckFileSize <option> <option>... 
    87250  // <option>     MaxWarn=<size gmkb> 
    88251  //          MaxCrit=<size gmkb> 
     
    100263  // Examples: 
    101264  // <return string>  <directory> <size gmkb> ... |<shortname>=<size>:<warn>:<crit> 
    102   // test: CheckFileSize&ShowAll&MaxWarn=1024M&MaxCrit=4096M&File:WIN=c:\WINDOWS\*.* 
     265  // test: CheckFileSize ShowAll MaxWarn=1024M MaxCrit=4096M File:WIN=c:\WINDOWS\*.* 
    103266  //       CheckFileSize 
    104267  // 
     
    107270  // ./check_nscp -H 192.168.0.167 -p 1234 -s pwd -c 'CheckFileSize&ShowAll&MaxWarn=1024M&MaxCrit=4096M&File:WIN=c:\WINDOWS\*.*' 
    108271  // WIN: 1G (2110962363B)|WIN:2110962363:1073741824:4294967296 
    109   NSC_DEBUG_MSG("CheckFileSize"); 
    110272  NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK; 
    111   std::list<std::string> args = NSCHelper::arrayBuffer2list(argLen, char_args); 
     273  std::list<std::string> args = arrayBuffer::arrayBuffer2list(argLen, char_args); 
    112274  if (args.empty()) { 
    113275    message = "Missing argument(s)."; 
     
    135297    } else if (p.first == "MinCrit") { 
    136298      minCrit = strEx::stoi64_as_BKMG(p.second); 
    137     } else if (p.first == "ShowAll") { 
     299    } else if (p.first == SHOW_ALL) { 
    138300      bShowAll = true; 
    139301    } else if (p.first.find(":") != std::string::npos) { 
     
    150312    } 
    151313  } 
    152   NSC_DEBUG_MSG_STD("Bounds: critical " + strEx::itos(minCrit) + " > siez > " + strEx::itos(maxCrit)); 
    153   NSC_DEBUG_MSG_STD("Bounds: warning " + strEx::itos(minWarn) + " > size > " + strEx::itos(maxWarn)); 
    154   NSC_DEBUG_MSG_STD("Showall: " + ((bShowAll)?"yeap":"noop")); 
    155314 
    156315  std::list<std::pair<std::string,std::string> >::const_iterator pit; 
     
    187346  if (message.empty()) 
    188347    message = "OK all file sizes are within bounds."; 
     348  else 
     349    message = NSCHelper::translateReturn(returnCode) + ": " + message; 
    189350  return returnCode; 
    190351} 
     
    193354#define BUFFER_SIZE 1024*64 
    194355 
    195 NSCAPI::nagiosReturn CheckDisk::handleCommand(const std::string command, const unsigned int argLen, char **char_args, std::string &msg, std::string &perf) { 
     356NSCAPI::nagiosReturn CheckDisk::handleCommand(const strEx::blindstr command, const unsigned int argLen, char **char_args, std::string &msg, std::string &perf) { 
    196357  if (command == "CheckFileSize") { 
    197358    return CheckFileSize(argLen, char_args, msg, perf); 
     359  } else if (command == "CheckDriveSize") { 
     360    return CheckDriveSize(argLen, char_args, msg, perf); 
     361 
    198362//  } else if (command == "CheckFileDate") { 
    199363  }  
  • /trunk/modules/CheckDisk/CheckDisk.vcproj

    r13 r24  
    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" 
     114      Name="Distribution|Win32" 
    115115      OutputDirectory="$(ConfigurationName)" 
    116116      IntermediateDirectory="$(ConfigurationName)" 
     
    130130      <Tool 
    131131        Name="VCLinkerTool" 
    132         OutputFile="../../Release/modules/$(ProjectName).dll" 
     132        OutputFile="../../Dist/modules/$(ProjectName).dll" 
    133133        LinkIncremental="1" 
    134134        ModuleDefinitionFile="CheckDisk.def" 
     
    137137        OptimizeReferences="2" 
    138138        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" 
    190139        ImportLibrary="$(OutDir)/CheckDisk.lib" 
    191140        TargetMachine="1"/> 
     
    220169      UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> 
    221170      <File 
     171        RelativePath="..\..\include\arrayBuffer.cpp"> 
     172      </File> 
     173      <File 
    222174        RelativePath=".\CheckDisk.cpp"> 
    223175      </File> 
     
    240192        </FileConfiguration> 
    241193        <FileConfiguration 
    242           Name="Dynamic Linkage|Win32"> 
     194          Name="Distribution|Win32"> 
    243195          <Tool 
    244196            Name="VCCLCompilerTool" 
    245197            UsePrecompiledHeader="1"/> 
    246198        </FileConfiguration> 
    247         <FileConfiguration 
    248           Name="Debug Dynamic Linkage|Win32"> 
    249           <Tool 
    250             Name="VCCLCompilerTool" 
    251             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"/> 
     213        </FileConfiguration> 
     214        <FileConfiguration 
     215          Name="Distribution|Win32"> 
     216          <Tool 
     217            Name="VCCLCompilerTool" 
     218            UsePrecompiledHeader="0"/> 
    252219        </FileConfiguration> 
    253220      </File> 
     
    265232      <File 
    266233        RelativePath=".\stdafx.h"> 
     234      </File> 
     235      <File 
     236        RelativePath="..\..\include\utils.h"> 
    267237      </File> 
    268238    </Filter> 
  • /trunk/modules/CheckDisk/CheckDisk.h

    r16 r28  
    11NSC_WRAPPERS_MAIN(); 
     2#include <config.h> 
     3#include <strEx.h> 
    24 
    35class CheckDisk { 
     
    1416  bool hasCommandHandler(); 
    1517  bool hasMessageHandler(); 
    16   NSCAPI::nagiosReturn handleCommand(const std::string command, const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
     18  NSCAPI::nagiosReturn handleCommand(const strEx::blindstr command, const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
    1719 
    1820  // Check commands 
    1921  NSCAPI::nagiosReturn CheckFileSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
     22  NSCAPI::nagiosReturn CheckDriveSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
    2023}; 
  • /trunk/modules/NRPEListener/stdafx.h

    r15 r24  
    1414#include <functional> 
    1515 
     16#include <config.h> 
     17#include <utils.h> 
     18 
    1619#include <NSCAPI.h> 
    1720#include <NSCHelper.h> 
  • /trunk/modules/NRPEListener/NRPEListener.h

    r16 r28  
    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  
    7 class NRPEListener { 
     7class NRPEListener : public simpleSocket::ListenerHandler { 
    88private: 
    9   NRPESocketThread socketThreadManager; 
     9  bool bUseSSL_; 
     10  simpleSSL::Listener socket_ssl_; 
     11  simpleSocket::Listener<> socket_; 
     12  typedef std::map<strEx::blindstr, std::string> commandList; 
     13  commandList commands; 
     14  unsigned int timeout; 
     15  socketHelpers::allowedHosts allowedHosts; 
    1016 
    1117public: 
     
    1925  bool hasCommandHandler(); 
    2026  bool hasMessageHandler(); 
    21   NSCAPI::nagiosReturn handleCommand(const std::string command, const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
     27  NSCAPI::nagiosReturn handleCommand(const strEx::blindstr command, const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
     28 
     29private: 
     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); 
     55  int executeNRPECommand(std::string command, std::string &msg, std::string &perf); 
     56  void addCommand(strEx::blindstr key, std::string args) { 
     57    commands[key] = args; 
     58  } 
     59 
    2260}; 
    2361 
  • /trunk/modules/NRPEListener/NRPESocket.h

    r16 r25  
    11#pragma once 
    22#include "resource.h" 
    3 #include <Thread.h> 
    4 #include <Mutex.h> 
    5 #include <WinSock2.h> 
    63#include <Socket.h> 
     4#include <SSLSocket.h> 
     5 
    76/** 
    87 * @ingroup NSClient++ 
     
    3029 */ 
    3130 
    32 #define DEFAULT_NRPE_PORT 5666 
     31 
     32#define NASTY_METACHARS         "|`&><'\"\\[]{}"        /* This may need to be modified for windows directory seperator */ 
     33 
     34typedef short int16_t; 
     35typedef unsigned long u_int32_t; 
    3336 
    3437 
    35 class NRPESocket : public SimpleSocketListsner { 
     38template <class TBase> 
     39class NRPESocket : public TBase { 
    3640private: 
     41  strEx::splitList allowedHosts_; 
     42 
     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 
    3760 
    3861public: 
    39   NRPESocket(); 
    40   virtual ~NRPESocket(); 
     62  NRPESocket() { 
     63  } 
     64  virtual ~NRPESocket() { 
     65  } 
     66 
    4167 
    4268private: 
    43   virtual void onAccept(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 
     85    if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_ARGUMENTS, NRPE_SETTINGS_ALLOW_ARGUMENTS_DEFAULT) == 0) { 
     86      if (!cmd.second.empty()) { 
     87        NSC_LOG_ERROR("Request contained arguments (not currently allowed)."); 
     88        throw NRPESocketException("Request contained arguments (not currently allowed)."); 
     89      } 
     90    } 
     91    if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_NASTY_META, NRPE_SETTINGS_ALLOW_NASTY_META_DEFAULT) == 0) { 
     92      if (cmd.first.find_first_of(NASTY_METACHARS) != std::string::npos) { 
     93        NSC_LOG_ERROR("Request command contained illegal metachars!"); 
     94        throw NRPESocketException("Request command contained illegal metachars!"); 
     95      } 
     96      if (cmd.second.find_first_of(NASTY_METACHARS) != std::string::npos) { 
     97        NSC_LOG_ERROR("Request arguments contained illegal metachars!"); 
     98        throw NRPESocketException("Request command contained illegal metachars!"); 
     99      } 
     100    } 
     101 
     102    NSCAPI::nagiosReturn ret = NSCModuleHelper::InjectSplitAndCommand(cmd.first, cmd.second, '!', msg, perf); 
     103    if (perf.empty()) { 
     104      return NRPEPacket(NRPEPacket::responsePacket, NRPEPacket::version2, ret, msg); 
     105    } else { 
     106      return NRPEPacket(NRPEPacket::responsePacket, NRPEPacket::version2, ret, msg + "|" + perf); 
     107    } 
     108  } 
     109  void setupDH(simpleSSL::DH &dh); 
    44110}; 
    45  
    46  
    47 typedef Thread<NRPESocket> NRPESocketThread; // Thread manager 
    48  
    49  
  • /trunk/modules/NRPEListener/NRPEListener.cpp

    r16 r30  
    66#include <strEx.h> 
    77#include <time.h> 
     8#include <config.h> 
     9#include "NRPEPacket.h" 
    810 
    911NRPEListener gNRPEListener; 
     
    2022} 
    2123 
     24std::string getAllowedHosts() { 
     25  std::string ret = NSCModuleHelper::getSettingsString(NRPE_SECTION_TITLE, MAIN_ALLOWED_HOSTS, ""); 
     26  if (ret.empty()) 
     27    ret = NSCModuleHelper::getSettingsString(MAIN_SECTION_TITLE, MAIN_ALLOWED_HOSTS, MAIN_ALLOWED_HOSTS_DEFAULT); 
     28  return ret; 
     29} 
    2230 
    2331bool NRPEListener::loadModule() { 
    24   socketThreadManager.createThread(NULL); 
     32  bUseSSL_ = NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_USE_SSL ,NRPE_SETTINGS_USE_SSL_DEFAULT)==1; 
     33  timeout = NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_TIMEOUT ,NRPE_SETTINGS_TIMEOUT_DEFAULT); 
     34  std::list<std::string> commands = NSCModuleHelper::getSettingsSection(NRPE_HANDLER_SECTION_TITLE); 
     35  std::list<std::string>::iterator it; 
     36  for (it = commands.begin(); it != commands.end(); it++) { 
     37    strEx::token t = strEx::getToken(*it, '='); 
     38    if (t.first.substr(0,7) == "command") { 
     39      strEx::token t2 = strEx::getToken(t.first, '['); 
     40      t2 = strEx::getToken(t2.second, ']'); 
     41      t.first = t2.first; 
     42    } 
     43    if (t.first.empty() || t.second.empty()) { 
     44      NSC_LOG_ERROR_STD("Invalid command definition: " + (*it)); 
     45    } else { 
     46      addCommand(t.first.c_str(), t.second); 
     47    } 
     48  } 
     49 
     50  allowedHosts.setAllowedHosts(strEx::splitEx(getAllowedHosts(), ",")); 
     51  try { 
     52    if (bUseSSL_) { 
     53      socket_ssl_.setHandler(this); 
     54      socket_ssl_.StartListener(NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_PORT, NRPE_SETTINGS_PORT_DEFAULT)); 
     55    } else { 
     56      socket_.setHandler(this); 
     57      socket_.StartListener(NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_PORT, NRPE_SETTINGS_PORT_DEFAULT)); 
     58    } 
     59  } catch (simpleSocket::SocketException e) { 
     60    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
     61    return false; 
     62  } catch (simpleSSL::SSLException e) { 
     63    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
     64    return false; 
     65  } 
     66 
    2567  return true; 
    2668} 
    2769bool NRPEListener::unloadModule() { 
    28   socketThreadManager.exitThread(); 
     70  try { 
     71    if (bUseSSL_) { 
     72      socket_ssl_.removeHandler(this); 
     73      socket_ssl_.StopListener(); 
     74    } else { 
     75      socket_.removeHandler(this); 
     76      socket_.StopListener(); 
     77    } 
     78  } catch (simpleSocket::SocketException e) { 
     79    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
     80    return false; 
     81  } catch (simpleSSL::SSLException e) { 
     82    NSC_LOG_ERROR_STD("Exception caught: " + e.getMessage()); 
     83    return false; 
     84  } 
    2985  return true; 
    3086} 
    3187 
    3288std::string NRPEListener::getModuleName() { 
    33   return "CheckDisk Various Disk related checks."; 
     89  return "NRPE module."; 
    3490} 
    3591NSCModuleWrapper::module_version NRPEListener::getModuleVersion() { 
     
    46102 
    47103 
    48 NSCAPI::nagiosReturn NRPEListener::handleCommand(const std::string command, const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
    49   return NSCAPI::returnIgnored; 
    50 } 
    51  
     104NSCAPI::nagiosReturn NRPEListener::handleCommand(const strEx::blindstr command, const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
     105  commandList::iterator it = commands.find(command); 
     106  if (it == commands.end()) 
     107    return NSCAPI::returnIgnored; 
     108 
     109  std::string str = (*it).second; 
     110  if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_ARGUMENTS, NRPE_SETTINGS_ALLOW_ARGUMENTS_DEFAULT) == 1) { 
     111    arrayBuffer::arrayList arr = arrayBuffer::arrayBuffer2list(argLen, char_args); 
     112    arrayBuffer::arrayList::const_iterator cit = arr.begin(); 
     113    int i=1; 
     114 
     115    for (;cit!=arr.end();cit++,i++) { 
     116      if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_NASTY_META, NRPE_SETTINGS_ALLOW_NASTY_META_DEFAULT) == 0) { 
     117        if ((*cit).find_first_of(NASTY_METACHARS) != std::string::npos) { 
     118          NSC_LOG_ERROR("Request string contained illegal metachars!"); 
     119          return NSCAPI::returnIgnored; 
     120        } 
     121      } 
     122      strEx::replace(str, "$ARG" + strEx::itos(i) + "$", (*cit)); 
     123    } 
     124  } 
     125 
     126  if ((str.substr(0,6) == "inject")&&(str.length() > 7)) { 
     127    strEx::token t = strEx::getToken(str.substr(7), ' '); 
     128    return NSCModuleHelper::InjectSplitAndCommand(t.first, t.second, ' ', message, perf); 
     129  } 
     130 
     131  return executeNRPECommand(str, message, perf); 
     132} 
     133#define MAX_INPUT_BUFFER 1024 
     134 
     135int NRPEListener::executeNRPECommand(std::string command, std::string &msg, std::string &perf) 
     136{ 
     137  NSCAPI::nagiosReturn result; 
     138  PROCESS_INFORMATION pi; 
     139  STARTUPINFO si; 
     140  HANDLE hChildOutR, hChildOutW, hChildInR, hChildInW; 
     141  SECURITY_ATTRIBUTES sec; 
     142  DWORD dwstate, dwexitcode; 
     143  int retval; 
     144 
     145 
     146  // Set up members of SECURITY_ATTRIBUTES structure.  
     147 
     148  sec.nLength = sizeof(SECURITY_ATTRIBUTES); 
     149  sec.bInheritHandle = TRUE; 
     150  sec.lpSecurityDescriptor = NULL; 
     151 
     152  // Create Pipes 
     153  CreatePipe(&hChildInR, &hChildInW, &sec, 0); 
     154  CreatePipe(&hChildOutR, &hChildOutW, &sec, 0); 
     155 
     156  // Set up members of STARTUPINFO structure.  
     157 
     158  ZeroMemory(&si, sizeof(STARTUPINFO)); 
     159  si.cb = sizeof(STARTUPINFO); 
     160  si.dwFlags = STARTF_USESTDHANDLES; 
     161  si.hStdInput = hChildInR; 
     162  si.hStdOutput = hChildOutW; 
     163  si.hStdError = hChildOutW; 
     164 
     165 
     166  // CreateProcess doesn't work with a const command 
     167  char *cmd = new char[command.length()+1]; 
     168  strncpy(cmd, command.c_str(), command.length()); 
     169  cmd[command.length()] = 0; 
     170 
     171  // Create the child process.  
     172  BOOL processOK = CreateProcess(NULL, cmd,        // command line  
     173    NULL, // process security attributes  
     174    NULL, // primary thread security attributes  
     175    TRUE, // handles are inherited  
     176    0,    // creation flags  
     177    NULL, // use parent's environment  
     178    NULL, // use parent's current directory  
     179    &si,  // STARTUPINFO pointer  
     180    &pi); // receives PROCESS_INFORMATION  
     181  delete [] cmd; 
     182 
     183  if (processOK) { 
     184    dwstate = WaitForSingleObject(pi.hProcess, 1000*timeout); 
     185    CloseHandle(hChildInR); 
     186    CloseHandle(hChildInW); 
     187    CloseHandle(hChildOutW); 
     188 
     189    if (dwstate == WAIT_TIMEOUT) { 
     190      TerminateProcess(pi.hProcess, 5); 
     191      msg = "The check didn't respond within the timeout period!"; 
     192      result = NSCAPI::returnUNKNOWN; 
     193    } else { 
     194      DWORD dwread; 
     195      char *buf = new char[MAX_INPUT_BUFFER+1]; 
     196      retval = ReadFile(hChildOutR, buf, MAX_INPUT_BUFFER, &dwread, NULL); 
     197      if (!retval || dwread == 0) { 
     198        msg = "No output available from command..."; 
     199      } else { 
     200        buf[dwread] = 0; 
     201        msg = buf; 
     202        strEx::token t = strEx::getToken(msg, '\n'); 
     203        t = strEx::getToken(t.first, '|'); 
     204        msg = t.first; 
     205        perf = t.second; 
     206      } 
     207      delete [] buf; 
     208      GetExitCodeProcess(pi.hProcess, &dwexitcode); 
     209      result = NSCHelper::int2nagios(dwexitcode); 
     210    } 
     211    CloseHandle(pi.hThread); 
     212    CloseHandle(pi.hProcess); 
     213    CloseHandle(hChildOutR); 
     214  } 
     215  else { 
     216    msg = "NRPE_NT failed to create process, exiting..."; 
     217    result = NSCAPI::returnUNKNOWN; 
     218    CloseHandle(hChildInR); 
     219    CloseHandle(hChildInW); 
     220    CloseHandle(hChildOutW); 
     221    CloseHandle(pi.hThread); 
     222    CloseHandle(pi.hProcess); 
     223    CloseHandle(hChildOutR); 
     224  } 
     225  return result; 
     226} 
     227void NRPEListener::onClose() 
     228{} 
     229 
     230void NRPEListener::onAccept(simpleSocket::Socket *client)  
     231{ 
     232  if (!allowedHosts.inAllowedHosts(client->getAddrString())) { 
     233    NSC_LOG_ERROR("Unothorized access from: " + client->getAddrString()); 
     234    client->close(); 
     235    return; 
     236  } 
     237  try { 
     238    simpleSocket::DataBuffer block; 
     239 
     240    for (int i=0;i<100;i++) { 
     241      client->readAll(block, 1048); 
     242      if (block.getLength() >= NRPEPacket::getBufferLength()) 
     243        break; 
     244      Sleep(100); 
     245    } 
     246    if (i == 100) { 
     247      NSC_LOG_ERROR_STD("Could not retrieve NRPE packet."); 
     248      client->close(); 
     249      return; 
     250    } 
     251    if (block.getLength() == NRPEPacket::getBufferLength()) { 
     252      try { 
     253        NRPEPacket out = handlePacket(NRPEPacket(block.getBuffer(), block.getLength())); 
     254        block.copyFrom(out.getBuffer(), out.getBufferLength()); 
     255      } catch (NRPEPacket::NRPEPacketException e) { 
     256        NSC_LOG_ERROR_STD("NRPESocketException: " + e.getMessage()); 
     257        client->close(); 
     258        return; 
     259      } 
     260      client->send(block); 
     261    } 
     262  } catch (simpleSocket::SocketException e) { 
     263    NSC_LOG_ERROR_STD("SocketException: " + e.getMessage()); 
     264  } catch (NRPEException e) { 
     265    NSC_LOG_ERROR_STD("NRPEException: " + e.getMessage()); 
     266  } 
     267  client->close(); 
     268} 
     269 
     270NRPEPacket NRPEListener::handlePacket(NRPEPacket p) { 
     271  if (p.getType() != NRPEPacket::queryPacket) { 
     272    NSC_LOG_ERROR("Request is not a query."); 
     273    throw NRPEException("Invalid query type"); 
     274  } 
     275  if (p.getVersion() != NRPEPacket::version2) { 
     276    NSC_LOG_ERROR("Request had unsupported version."); 
     277    throw NRPEException("Invalid version"); 
     278  } 
     279  if (!p.verifyCRC()) { 
     280    NSC_LOG_ERROR("Request had invalid checksum."); 
     281    throw NRPEException("Invalid checksum"); 
     282  } 
     283  strEx::token cmd = strEx::getToken(p.getPayload(), '!'); 
     284  std::string msg, perf; 
     285 
     286  if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_ARGUMENTS, NRPE_SETTINGS_ALLOW_ARGUMENTS_DEFAULT) == 0) { 
     287    if (!cmd.second.empty()) { 
     288      NSC_LOG_ERROR("Request contained arguments (not currently allowed)."); 
     289      throw NRPEException("Request contained arguments (not currently allowed)."); 
     290    } 
     291  } 
     292  if (NSCModuleHelper::getSettingsInt(NRPE_SECTION_TITLE, NRPE_SETTINGS_ALLOW_NASTY_META, NRPE_SETTINGS_ALLOW_NASTY_META_DEFAULT) == 0) { 
     293    if (cmd.first.find_first_of(NASTY_METACHARS) != std::string::npos) { 
     294      NSC_LOG_ERROR("Request command contained illegal metachars!"); 
     295      throw NRPEException("Request command contained illegal metachars!"); 
     296    } 
     297    if (cmd.second.find_first_of(NASTY_METACHARS) != std::string::npos) { 
     298      NSC_LOG_ERROR("Request arguments contained illegal metachars!"); 
     299      throw NRPEException("Request command contained illegal metachars!"); 
     300    } 
     301  } 
     302 
     303  NSCAPI::nagiosReturn ret = NSCModuleHelper::InjectSplitAndCommand(cmd.first, cmd.second, '!', msg, perf); 
     304  if (perf.empty()) { 
     305    return NRPEPacket(NRPEPacket::responsePacket, NRPEPacket::version2, ret, msg); 
     306  } else { 
     307    return NRPEPacket(NRPEPacket::responsePacket, NRPEPacket::version2, ret, msg + "|" + perf); 
     308  } 
     309} 
    52310 
    53311NSC_WRAPPERS_MAIN_DEF(gNRPEListener); 
  • /trunk/modules/NRPEListener/NRPEListener.vcproj

    r16 r24  
    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" 
     87        LinkIncremental="1" 
     88        AdditionalLibraryDirectories="&quot;C:\Source\openssl-0.9.7f\out32dll&quot;" 
     89        ModuleDefinitionFile="NRPEListener.def" 
     90        GenerateDebugInformation="TRUE" 
     91        SubSystem="2" 
     92        OptimizeReferences="2" 
     93        EnableCOMDATFolding="2" 
     94        ImportLibrary="$(OutDir)/NRPEListener.lib" 
     95        TargetMachine="1"/> 
     96      <Tool 
     97        Name="VCMIDLTool"/> 
     98      <Tool 
     99        Name="VCPostBuildEventTool"/> 
     100      <Tool 
     101        Name="VCPreBuildEventTool"/> 
     102      <Tool 
     103        Name="VCPreLinkEventTool"/> 
     104      <Tool 
     105        Name="VCResourceCompilerTool"/> 
     106      <Tool 
     107        Name="VCWebServiceProxyGeneratorTool"/> 
     108      <Tool 
     109        Name="VCXMLDataGeneratorTool"/> 
     110      <Tool 
     111        Name="VCWebDeploymentTool"/> 
     112      <Tool 
     113        Name="VCManagedWrapperGeneratorTool"/> 
     114      <Tool 
     115        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
     116    </Configuration> 
     117    <Configuration 
     118      Name="Distribution|Win32" 
     119      OutputDirectory="$(ConfigurationName)" 
     120      IntermediateDirectory="$(ConfigurationName)" 
     121      ConfigurationType="2" 
     122      CharacterSet="2"> 
     123      <Tool 
     124        Name="VCCLCompilerTool" 
     125        AdditionalIncludeDirectories="../include;../../include" 
     126        PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS" 
     127        RuntimeLibrary="2" 
     128        UsePrecompiledHeader="3" 
     129        WarningLevel="3" 
     130        Detect64BitPortabilityProblems="TRUE" 
     131        DebugInformationFormat="3"/> 
     132      <Tool 
     133        Name="VCCustomBuildTool"/> 
     134      <Tool 
     135        Name="VCLinkerTool" 
     136        AdditionalDependencies="ws2_32.lib ssleay32.lib libeay32.lib" 
     137        OutputFile="../../Dist/modules/$(ProjectName).dll" 
    86138        LinkIncremental="1" 
    87139        ModuleDefinitionFile="NRPEListener.def" 
     
    122174      UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> 
    123175      <File 
     176        RelativePath="..\..\include\arrayBuffer.cpp"> 
     177      </File> 
     178      <File 
    124179        RelativePath=".\NRPEListener.cpp"> 
    125180      </File> 
     
    128183      </File> 
    129184      <File 
    130         RelativePath=".\NRPESocket.cpp"> 
     185        RelativePath=".\NRPEPacket.cpp"> 
    131186      </File> 
    132187      <File 
     
    137192      </File> 
    138193      <File 
     194        RelativePath="..\..\include\SSLSocket.cpp"> 
     195      </File> 
     196      <File 
    139197        RelativePath=".\stdafx.cpp"> 
    140198        <FileConfiguration 
     
    149207            Name="VCCLCompilerTool" 
    150208            UsePrecompiledHeader="1"/> 
     209        </FileConfiguration> 
     210        <FileConfiguration 
     211          Name="Distribution|Win32"> 
     212          <Tool 
     213            Name="VCCLCompilerTool" 
     214            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"/> 
    151236        </FileConfiguration> 
    152237      </File> 
     
    160245      </File> 
    161246      <File 
     247        RelativePath="..\..\include\config.h"> 
     248      </File> 
     249      <File 
    162250        RelativePath=".\NRPEListener.h"> 
    163251      </File> 
    164252      <File 
    165         RelativePath=".\NRPESocket.h"> 
    166       </File> 
    167       <File 
    168253        RelativePath="..\..\include\NSCHelper.h"> 
    169254      </File> 
     
    172257      </File> 
    173258      <File 
     259        RelativePath="..\..\include\SSLSocket.h"> 
     260      </File> 
     261      <File 
    174262        RelativePath=".\stdafx.h"> 
     263      </File> 
     264      <File 
     265        RelativePath="..\..\include\thread.h"> 
     266      </File> 
     267      <File 
     268        RelativePath="..\..\include\utils.h"> 
    175269      </File> 
    176270    </Filter> 
  • /trunk/modules/NRPEListener/NRPESocket.cpp

    r19 r24  
    33#include "NRPESocket.h" 
    44 
    5 /** 
    6  * Default c-tor 
    7  */ 
    8 NRPESocket::NRPESocket(): SimpleSocketListsner(DEFAULT_NRPE_PORT) { 
     5 
     6 
     7 
     8 
     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; 
    921} 
    1022 
    11 NRPESocket::~NRPESocket() { 
    12 } 
    13  
    14 typedef short int16_t; 
    15 typedef unsigned long u_int32_t; 
    16  
    17 typedef struct packet_struct{ 
    18   int16_t   packet_version; 
    19   int16_t   packet_type; 
    20   u_int32_t crc32_value; 
    21   int16_t   result_code; 
    22   char      buffer[1024]; 
    23 }packet; 
    24  
    25 static unsigned long crc32_table[256]; 
    26  
    27 /* build the crc table - must be called before calculating the crc value */ 
    28 void generate_crc32_table(void){ 
    29   unsigned long crc, poly; 
    30   int i, j; 
    31  
    32   poly=0xEDB88320L; 
    33   for(i=0;i<256;i++){ 
    34     crc=i; 
    35     for(j=8;j>0;j--){ 
    36       if(crc & 1) 
    37         crc=(crc>>1)^poly; 
    38       else 
    39         crc>>=1; 
    40     } 
    41     crc32_table[i]=crc; 
    42   } 
    43  
    44   return; 
    45 } 
    46  
    47 /* calculates the CRC 32 value for a buffer */ 
    48 unsigned long calculate_crc32(char *buffer, int buffer_size){ 
    49   register unsigned long crc; 
    50   int this_char; 
    51   int current_index; 
    52  
    53   crc=0xFFFFFFFF; 
    54  
    55   for(current_index=0;current_index<buffer_size;current_index++){ 
    56     this_char=(int)buffer[current_index]; 
    57     crc=((crc>>8) & 0x00FFFFFF) ^ crc32_table[(crc ^ this_char) & 0xFF]; 
    58   } 
    59  
    60   return (crc ^ 0xFFFFFFFF); 
    61 } 
    62  
    63 void NRPESocket::onAccept(SOCKET client) { 
    64   NSC_DEBUG_MSG("Accepting connection from remote host"); 
    65  
    66   SimpleSocketListsner::readAllDataBlock block = SimpleSocketListsner::readAll(client); 
    67   packet *p = reinterpret_cast<packet*>(block.first); 
    68   // @todo Verify versions and stuff, and ofcource add SSL (but thats in the future :) 
    69   NSC_DEBUG_MSG_STD("Incoming data: " + p->buffer); 
    70  
    71   charEx::token cmd = charEx::getToken(p->buffer, '!'); 
    72   std::string msg, perf; 
    73   NSCAPI::nagiosReturn ret = NSCModuleHelper::InjectSplitAndCommand(cmd.first.c_str(), cmd.second, '!', msg, perf); 
    74 //QUERY_PACKET 
    75   packet p2; 
    76   strncpy(p2.buffer, (msg+"|"+perf).c_str(), 1023); 
    77   p2.buffer[1023] = 0; 
    78   p2.packet_type = htons(2); 
    79   p2.packet_version = htons(2); 
    80   p2.result_code = htons(static_cast<int>(ret)); 
    81  
    82   generate_crc32_table(); 
    83   p2.crc32_value = 0; 
    84   p2.crc32_value = htonl(calculate_crc32(reinterpret_cast<char*>(&p2),sizeof(p2))); 
    85   send(client, reinterpret_cast<char*>(&p2), sizeof(p2), 0); 
    86  
    87   delete [] block.first; 
    88   closesocket(client); 
    89 } 
    90  
  • /trunk/modules/SysTray/SysTray.cpp

    r7 r22  
    5151 
    5252std::string SysTray::getModuleName() { 
    53   return "This is a nice systray module."; 
     53  return "System Tray icon Module."; 
    5454} 
    5555NSCModuleWrapper::module_version SysTray::getModuleVersion() { 
  • /trunk/modules/SysTray/SysTray.vcproj

    r15 r24  
    108108        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
    109109    </Configuration> 
     110    <Configuration 
     111      Name="Distribution|Win32" 
     112      OutputDirectory="$(ConfigurationName)" 
     113      IntermediateDirectory="$(ConfigurationName)" 
     114      ConfigurationType="2" 
     115      CharacterSet="2"> 
     116      <Tool 
     117        Name="VCCLCompilerTool" 
     118        AdditionalIncludeDirectories="../include;../../include" 
     119        PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS" 
     120        RuntimeLibrary="2" 
     121        UsePrecompiledHeader="3" 
     122        WarningLevel="3" 
     123        Detect64BitPortabilityProblems="TRUE" 
     124        DebugInformationFormat="3"/> 
     125      <Tool 
     126        Name="VCCustomBuildTool"/> 
     127      <Tool 
     128        Name="VCLinkerTool" 
     129        OutputFile="../../Dist/modules/$(ProjectName).dll" 
     130        LinkIncremental="1" 
     131        ModuleDefinitionFile="SysTray.def" 
     132        GenerateDebugInformation="TRUE" 
     133        SubSystem="2" 
     134        OptimizeReferences="2" 
     135        EnableCOMDATFolding="2" 
     136        ImportLibrary="$(OutDir)/SysTray.lib" 
     137        TargetMachine="1"/> 
     138      <Tool 
     139        Name="VCMIDLTool"/> 
     140      <Tool 
     141        Name="VCPostBuildEventTool"/> 
     142      <Tool 
     143        Name="VCPreBuildEventTool"/> 
     144      <Tool 
     145        Name="VCPreLinkEventTool"/> 
     146      <Tool 
     147        Name="VCResourceCompilerTool"/> 
     148      <Tool 
     149        Name="VCWebServiceProxyGeneratorTool"/> 
     150      <Tool 
     151        Name="VCXMLDataGeneratorTool"/> 
     152      <Tool 
     153        Name="VCWebDeploymentTool"/> 
     154      <Tool 
     155        Name="VCManagedWrapperGeneratorTool"/> 
     156      <Tool 
     157        Name="VCAuxiliaryManagedWrapperGeneratorTool"/> 
     158    </Configuration> 
    110159  </Configurations> 
    111160  <References> 
     
    116165      Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" 
    117166      UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> 
     167      <File 
     168        RelativePath="..\..\include\arrayBuffer.cpp"> 
     169      </File> 
    118170      <File 
    119171        RelativePath="..\..\include\NSCHelper.cpp"> 
     
    133185            UsePrecompiledHeader="1"/> 
    134186        </FileConfiguration> 
     187        <FileConfiguration 
     188          Name="Distribution|Win32"> 
     189          <Tool 
     190            Name="VCCLCompilerTool" 
     191            UsePrecompiledHeader="1"/> 
     192        </FileConfiguration> 
    135193      </File> 
    136194      <File 
     
    148206      Filter="h;hpp;hxx;hm;inl;inc;xsd" 
    149207      UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> 
     208      <File 
     209        RelativePath="..\..\include\config.h"> 
     210      </File> 
    150211      <File 
    151212        RelativePath="..\..\include\NSCHelper.h"> 
  • /trunk/readme.txt

    r13 r22  
    11NSClient++ is a windows service that allows performance metrics to be gathered by Nagios  
    2 (and possibly other monitoring tools). It is an attempt to create a NSClient compatible  
     2(and possibly other monitoring tools). It is an attempt to create a NSClient and NRPE compatible  
    33but yet extendable performance service for windows. 
    44 
    5  
    6 This is an initial NSClient++ test release. 
    7  
    8 This version has many of the features from NSClient. 
     5NSClient 
    96The following commands (from check_nt) are supported. 
    107 * CLIENTVERSION 
     
    1613 * PROCSTATE 
    1714 
     15NRPE 
     16All scripts "should" work (haven't actually tried myself though). 
     17Notice that encryption is still missing. 
     18 
    1819Installation: 
    1920To install simply copy all files to directory on the server and run  
    20 the following command: "NSClient++ /install" to uninstall run:  
     21the following command: "NSClient++ /install" to un-install run:  
    2122"NSClient++ /uninstall". 
    2223 
     
    2930    about - Show some info (version et.al.) 
    3031    version - Show some info 
    31     test  - Run interactively (hint: enable ConsoleLogger for  
    32       this to make sense). Useful for debugging purposes. 
     32    test  - Run interactively. Useful for debugging purposes. 
    3333 
    3434The directory structure: 
    3535  <install root> 
    3636    - NSClient++.exe  - The executable (and service) 
    37     - NSC.ini   - The INI file (settings) 
     37    - NSC.ini     - The INI file (settings) 
     38    - changelog     - "Whats new" 
     39    - *.dll       - Various runtime DLLs 
     40    - readme.txt    - This file 
    3841    <modules> 
    3942      - Various NSClient++ modules available to this instance. 
    4043 
    41 The default modules: 
    42 CheckEventLog.dll 
    43   An eventlog checker (has yet to get a Unix client) 
    44 ConsoleLogger.dll 
    45   Log messages to console. (Usefull when run with -test) 
    46 FileLogger.dll 
    47   Log messages to file (Usefull when run as service) 
    48 NSClientCompat.dll 
    49   NSCLient compatibility module. Provides NSClient commands. 
    50 SysTray.dll 
    51   Shows a sytray when the service (exe) is started and allows you to  
    52   view the logfile and inject commands. 
     44A quick description of the included modules: 
     45* CheckDisk.dll 
     46  Dick check plug-in (not very complete as of yet). 
     47* CheckEventLog.dll 
     48  A very basic event log checker (HINT feedback wanted :) 
     49* FileLogger.dll 
     50  Log messages to file (Useful when reporting bugs, also please enable debug=1) 
     51* NRPEListener.dll 
     52  NRPE client code. Both listener and executer.  
     53  Might in the future rename this to NRPE or I will split the module into two. 
     54* NSClientCompat.dll 
     55  NSCLient compatibility module. Provides NSClient commands. 
     56  This module will be migrated in to various other modules in the "near" future. 
     57* NSClientListener.dll 
     58  The NSClient listener. 
     59* SysTray.dll 
     60  Shows a system tray when the service (exe) is started and allows you to view the log file and inject commands. 
    5361 
    5462Settings: 
    55 The following things can be changed ion the NSC.ini file. 
     63For details refer to NSC.ini. 
    5664 
    57 [generic] 
    58 password=secret-password 
    59 # The password to use. 
     65About NSClient++ 
     66URL: http://www.sf.net/projects/nscplus 
    6067 
    61 port=1234 
    62 # The port to bind to 
    63  
    64 [main] 
    65 bufferSize=4096 
    66 # Maximum buffer size for commands to return 
    67  
    68 [log] 
    69 file=nsclient.log 
    70 # The file to log to. 
    71  
    72 [nsclient compat] 
    73 version=modern 
    74 # The version string to return to the client. 
    75 # Modern returns the nsclient++ version string in a new syntax: 
    76 # <application> <version> <date> 
    77 # Notice this is not automated as of yet (as in date/version is not updated). 
    78  
    79 [systray] 
    80 defaultCommand= 
    81 # The default command to show in the inject command dialog. 
    82  
    83  
    84 Using the API: 
    85 The following functions are available for a module to "export": (think DLL) 
    86  
    87 NSLoadModule 
    88 - Loading of modules (done when the service starts) 
    89 NSGetModuleName 
    90 - Used to get a nice name for the module. 
    91 NSGetModuleVersion 
    92 - Not really used but... 
    93 NSHasCommandHandler 
    94 - Let the "core" know it can handle commands (from nagios) 
    95 NSHasMessageHandler 
    96 - Used to let the "core" know it wants to see all log/debug/error messages that are generated. 
    97 NSHandleMessage 
    98 - Used to digest a log/debug/error message. 
    99 NSHandleCommand 
    100 - Used to (possibly) digest a command. 
    101 When a command is "injected" then command is parsed and then sent along to all plugins (which accept commands) in order (they are listed in NSC.ini) and they are allowed to act on the command. If they do act on the command the "injection" is aborted and the resulting "return string" is returned to the "injecter" (normaly check_nt through a TCP stream. The ordering can thus be used to 1, optimize if things are slow (though I fail to see that unless someone makes some pretty f*cked up modules) and priority if one module overlaps the command of another (though then I would recommend someone to change the plugin command strings :) 
    102  
    103 NSUnloadModule 
    104 - Used to unload and terminate "stuff" nicely. (Generally this is when the service terminates) 
    105 NSModuleHelperInit 
    106 - Used to send along callbacks to the module (for making calls to the "core". (Ie. To allow the module to inject commands, get versions, names, and settings) 
    107  
    108 So the API is quite simple and straight forward (I hope :) 
    109  
    110 To make a simple call graph: 
    111  
    112 * Service starts: 
    113 * For each plugin 
    114         - call NSLoadModule 
    115         - call NSModuleHelperInit 
    116         - if NSHasCommandHandler 
    117                 . Send to "command plugin" stack 
    118         - if NSHasMessageHandler 
    119                 . Send to "message plugin" stack 
    120 * Wait for socket data 
    121         - Parse socket data 
    122         - For each "command plugin" 
    123                 . call NSHandleCommand 
    124                 . if Command handled abort 
    125  
    126 <termination signal sent to service> 
    127 * For each plugin 
    128         - NSUnloadModule 
    129 * Terminate service 
    130  
    131 <Log/debug/error message generated in a module> 
    132 * On incoming message: 
    133         - For each "message plugin" 
    134                 . call NSHandleMessage 
    135  
    136 There are a few more things to this but overall I have tried to keep things simple. 
    137  
    138 The extensions (to the API) I'm considering as of now (depending on the fallout) is: 
    139 * "SettingsHandler" to allow registry/INI/* settings modules. As the overhead of reg/ini settings system is quite low, perhaps this is overkill. But I don't know: thinking wildly there might be a reason for someone to want to load settings from a central server or whatever :) 
    140  
    141 * "SocketHandlers" though this will not be a specific handler I have considered to refactor out the code and allow the socket handler (that reads the TCP socket and parses the command) to be a plugin when I do SSL as I assume SSL will come with quite a high overhead and thus I might not need it all the time. 
    142  
    143 Also as mentioned this might be a good place to do a NRPE socket parser module to allow compatibility with NRPE. But this I assume is a bit in the future as I need to get "NSClient++" before I can get "NRPEClient++"... 
    144  
    145 As for PassiveChecks that could be implemented as a plugin today as any plugin can inject commands into the "core". Thus a plugin can be loaded, have a background thread that every X minutes calls "core".injectCommand(); and sends the result over to nagios. (This is how I assume that passive checks work) 
    146  
    147  
    148  
    149  
    150 // Michael Medin - michael <at> medin <dot> name - http://www.medin.name 
     68Contact the author: 
     69Michael Medin 
     70EMail: michael <at> medin <dot> name 
     71Address: (feel free to send a postcard if you find this useful :) 
     72Michael Medin 
     73Terapivaegen 6b 3tr 
     74SE-141 55 HUDDINGE 
     75SWEDEN