Changeset 739db5a in nscp for include


Ignore:
Timestamp:
09/27/08 19:06:35 (5 years ago)
Author:
Michael Medin <michael@…>
Branches:
master, 0.4.0, 0.4.1, 0.4.2
Children:
37e6081
Parents:
9567d4b
Message:

First attempt at merging stable changes over to here (probably needs more work, but compiles and starts...)

Location:
include
Files:
5 added
24 edited

Legend:

Unmodified
Added
Removed
  • include/EnumNtSrv.cpp

    r9567d4b r739db5a  
    1919#include <windows.h> 
    2020#include <WinSvc.h> 
     21#include <error.hpp> 
    2122#include "EnumNtSrv.h" 
    2223 
     
    2627static char THIS_FILE[] = __FILE__; 
    2728#endif 
    28  
    29 #define ASSERT(x) 
    3029 
    3130//============================================================================= 
     
    105104std::wstring TNtServiceInfo::GetErrorControl(void) 
    106105{ 
    107   ASSERT(m_dwErrorControl < 4); 
     106  if (m_dwErrorControl >= 4) 
     107    throw std::exception(); 
    108108  TCHAR *types[] = { 
    109109    _T("ERROR_IGNORE"),   // 0 
     
    118118std::wstring TNtServiceInfo::GetCurrentState(void) 
    119119{ 
    120   ASSERT(m_dwCurrentState < 8); 
     120  if (m_dwErrorControl >= 8) 
     121    throw std::exception(); 
    121122  TCHAR *types[] = { 
    122123    _T("UNKNOWN"), 
     
    184185  SC_HANDLE scman = ::OpenSCManager(NULL,NULL,SC_MANAGER_ENUMERATE_SERVICE); 
    185186  if (!scman) { 
    186     throw NTServiceException(name, _T("Could not open ServiceControl manager"), GetLastError()); 
     187    throw NTServiceException(name, _T("Could not open ServiceControl manager: ") + error::lookup::last_error()); 
    187188  } 
    188189  SC_HANDLE sh = ::OpenService(scman,name.c_str(),SERVICE_QUERY_STATUS); 
    189190  if (!sh) { 
     191    std::wstring short_name; 
    190192    DWORD bufLen = SC_BUF_LEN; 
    191193    TCHAR *buf = new TCHAR[bufLen+1]; 
    192194    if (GetServiceKeyName(scman, name.c_str(), buf, &bufLen) == 0) { 
    193       ::CloseServiceHandle(scman); 
    194       delete [] buf; 
    195       throw NTServiceException(name, _T("GetServiceKeyName: Could not translate service name"), GetLastError()); 
     195      short_name = name; 
     196    } else { 
     197      short_name = buf; 
    196198    } 
    197     /* 
    198     Why does this not work? (a bug in the API? says it should return the correct size?) 
    199     if (bufLen >= SC_BUF_LEN) { 
    200       ::CloseServiceHandle(scman); 
    201       throw NTServiceException(name, "Service name to long to handle", GetLastError()); 
    202     } 
    203     buf[bufLen] = 0; 
    204     */ 
    205     sh = ::OpenService(scman,buf,SERVICE_QUERY_STATUS); 
     199    delete [] buf; 
     200    sh = ::OpenService(scman,short_name.c_str(),SERVICE_QUERY_STATUS); 
    206201    delete [] buf; 
    207202    if (sh == NULL) { 
     203      DWORD dwErr = GetLastError(); 
    208204      ::CloseServiceHandle(scman); 
    209       throw NTServiceException(name, _T("OpenService: Could not open Service"), GetLastError()); 
     205      if (dwErr == ERROR_SERVICE_DOES_NOT_EXIST) { 
     206        info.m_dwCurrentState = MY_SERVICE_NOT_FOUND; 
     207        info.m_dwServiceType = MY_SERVICE_NOT_FOUND; 
     208        return info; 
     209      } else { 
     210        throw NTServiceException(name, _T("OpenService: Could not open Service: ") + error::lookup::last_error(dwErr)); 
     211      } 
    210212    } 
    211213  } 
     
    217219    ::CloseServiceHandle(sh); 
    218220    ::CloseServiceHandle(scman); 
    219     throw NTServiceException(name, _T("QueryServiceStatus: Could not query service status"), GetLastError()); 
     221    throw NTServiceException(name, _T("QueryServiceStatus: Could not query service status: ") + error::lookup::last_error()); 
    220222  } 
    221223  // TODO: Get more info here  
     
    225227} 
    226228 
    227 /* 
    228 // Enumerate services on this machine and return an STL list of service objects  
    229 // dwType = bit OR of SERVICE_WIN32, SERVICE_DRIVER 
    230 // dwState = bit OR of SERVICE_ACTIVE, SERVICE_INACTIVE 
    231 void TNtServiceInfo::EnumServices(DWORD dwType, DWORD dwState, TNtServiceInfoList *pList) 
    232 { 
    233   ASSERT(pList != NULL); 
    234   TNtServiceInfo *pSrvList = NULL; 
    235   DWORD dwCount = 0; 
    236   pSrvList = TNtServiceInfo::EnumServices(dwType, dwState, &dwCount); 
    237   for (DWORD dwIndex = 0; dwIndex < dwCount; dwIndex ++) { 
    238     pList->insert(pList->end(), pSrvList[dwIndex]); 
    239   } 
    240   delete [] pSrvList; 
    241 } 
    242 */ 
    243229/*############################################################################# 
    244230# End of file ENUMNTSRV.CPP 
  • include/EnumNtSrv.h

    r9567d4b r739db5a  
    4040  std::wstring name_; 
    4141  std::wstring msg_; 
    42   unsigned int error_; 
    4342public: 
    44   NTServiceException(std::wstring name,std::wstring msg,unsigned int error) : name_(name), error_(error), msg_(msg) {}; 
     43  NTServiceException(std::wstring name,std::wstring msg) : name_(name), msg_(msg) {}; 
    4544 
    4645  std::wstring getError() { 
    47     return _T("Service: ") + name_ + _T(" caused: ") + msg_ + _T("(") + strEx::itos(error_) + _T(")"); 
     46    return _T("Service: '") + name_ + _T("' caused: ") + msg_; 
    4847  } 
    4948}; 
     49#define MY_SERVICE_NOT_FOUND                        0xffff0000 
    5050 
    5151class TNtServiceInfo { 
  • include/EnumProcess.cpp

    rb7ed6ac r739db5a  
    237237  if (lpBuffer == NULL) 
    238238    throw EnumProcException(_T("Failed to allocate buffer")); 
    239   DWORD dwBytesRead; 
     239  SIZE_T dwBytesRead; 
    240240  if (!ReadProcessMemory( hProcess, mbi.BaseAddress, (LPVOID)lpBuffer, sysinfo.dwPageSize, &dwBytesRead)) { 
    241241    free(lpBuffer); 
     
    313313  } 
    314314  CloseHandle(hProc); 
     315  return TRUE; 
    315316} 
    316317 
  • include/EnumProcess.h

    rb7ed6ac r739db5a  
    7575    CProcessEntry(const CProcessEntry &e) : dwPID(e.dwPID), fill(e.fill), filename(e.filename), command_line(e.command_line) {} 
    7676    virtual ~CProcessEntry() {} 
    77     bool getCommandLine() const { return fill&fill_command_line!=0; } 
    78     bool getFilename() const { return fill&fill_filename!=0; } 
     77    bool getCommandLine() const { return (fill&fill_command_line)!=0; } 
     78    bool getFilename() const { return (fill&fill_filename)!=0; } 
    7979  }; 
    8080 
  • include/Mutex.h

    r9567d4b r739db5a  
    2525#include <windows.h> 
    2626#include <iostream> 
     27#include <error.hpp> 
     28 
     29class mutex_exception { 
     30  std::wstring what_; 
     31public: 
     32  mutex_exception(std::wstring what) : what_(what) {} 
     33  std::wstring what() { return what_; } 
     34}; 
    2735 
    2836/** 
     
    5058 */ 
    5159class MutexHandler { 
     60public: 
    5261private: 
    5362  HANDLE hMutex; 
     63  DWORD dwWaitResult; 
     64  bool bCreated; 
    5465public: 
    5566  /** 
     
    5768   * Creates an unnamed mutex. 
    5869   */ 
    59   MutexHandler() : hMutex(NULL) { 
    60     hMutex = CreateMutex(NULL, FALSE, NULL); 
     70  MutexHandler(std::wstring name = _T("")) : hMutex(NULL), dwWaitResult(0), bCreated(false) { 
     71    //std::wcout << _T("Creating mutex: ") << name << std::endl; 
     72    hMutex = CreateMutex(NULL, FALSE, name.empty()?NULL:name.c_str()); 
    6173    if (hMutex == NULL && GetLastError() == ERROR_ALREADY_EXISTS ) 
    62       hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, NULL); 
    63     if (hMutex == NULL) { 
    64       std::wcout << _T("*** *** *** Error in mutex creation: ") << GetLastError() << std::endl; 
    65     } 
     74      hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, name.empty()?NULL:name.c_str()); 
     75    else  
     76      bCreated = true; 
     77    if (hMutex == NULL) 
     78      throw mutex_exception(_T("Failed to create mutex: ") + error::lookup::last_error()); 
    6679  } 
    6780  /** 
     
    7487    hMutex = NULL; 
    7588  } 
     89  void close() { 
     90    if (hMutex) 
     91      CloseHandle(hMutex); 
     92    hMutex = NULL; 
     93  } 
     94  bool mutexWasCreated() { 
     95    return bCreated; 
     96  } 
    7697  /** 
    7798   * HANDLe cast operator to retrieve the handle from the enclosed mutex object. 
     
    80101  operator HANDLE () const { 
    81102    return hMutex; 
     103  } 
     104  /** 
     105  * Release the mutex 
     106  */ 
     107  void releaseLock() { 
     108    if (hMutex == NULL) 
     109      throw mutex_exception(_T("Failed to release mutex lock (mutex handle is null)")); 
     110    if (!ReleaseMutex(hMutex)) 
     111      throw mutex_exception(_T("Failed to relase the mutex: ") + error::lookup::last_error()); 
     112  } 
     113  /** 
     114  * Waits for the mutex object. 
     115  * @timeout The timeout before abandoning wait 
     116  */ 
     117  bool accuireLock(DWORD timeout = 5000L) { 
     118    if (hMutex == NULL) 
     119      throw mutex_exception(_T("Failed to get mutex lock (mutex handle is null)")); 
     120    dwWaitResult = WaitForSingleObject(hMutex, timeout); 
     121    switch (dwWaitResult) { 
     122      // The thread got mutex ownership. 
     123    case WAIT_OBJECT_0: 
     124      return true; 
     125    case WAIT_TIMEOUT:  
     126      return false; 
     127    case WAIT_ABANDONED:  
     128      return true; 
     129    default: 
     130      throw mutex_exception(_T("Unknown returncode from the mutex: ") + strEx::itos(dwWaitResult)); 
     131       
     132    } 
     133  } 
     134  /** 
     135  * Get the result of the wait operation. 
     136  * @return Result of the wait operation 
     137  */ 
     138  DWORD getWaitResult() const { 
     139    return dwWaitResult; 
    82140  } 
    83141}; 
     
    125183  MutexLock(HANDLE hMutex, DWORD timeout = 5000L) : bHasMutex(false), hMutex_(hMutex) { 
    126184    if (hMutex_ == NULL) { 
    127       std::wcout << _T("*** *** *** Error in mutex lock: ") << std::endl; 
     185      throw mutex_exception(_T("Failed to get mutex lock (mutex handle is null)")); 
     186      /* 
    128187      bHasMutex = false; 
    129188      return; 
     189      */ 
    130190    } 
    131191    dwWaitResult = WaitForSingleObject(hMutex_, timeout); 
     
    135195      bHasMutex = true; 
    136196      break; 
    137         case WAIT_TIMEOUT:  
    138       bHasMutex = false; 
    139       break; 
    140         case WAIT_ABANDONED:  
     197        case WAIT_TIMEOUT: 
     198      bHasMutex = false; 
     199      break; 
     200        case WAIT_ABANDONED: 
    141201      bHasMutex = false; 
    142202      break; 
     
    195255  void lock(DWORD timeout = 5000L) { 
    196256    if (hMutex_ == NULL) { 
    197       std::wcout << _T("*** *** *** Error in mutex lock: ") << std::endl; 
     257      throw mutex_exception(_T("Failed to get mutex lock (mutex handle is null)")); 
     258      /* 
     259      std::wcout << _T("Error in mutex lock: ") << std::endl; 
    198260      bHasMutex = false; 
    199261      return; 
     262      */ 
    200263    } 
    201264    dwWaitResult = WaitForSingleObject(hMutex_, timeout); 
  • include/MutexRW.h

    r978bd31 r739db5a  
    2222 
    2323#include <iostream> 
    24 #include <assert.h> 
    2524 
    2625//#define TRACE(x, y)  
     
    8281    if (dwEvent != WAIT_OBJECT_0) 
    8382      return false; 
    84     //      assert(dwEvent == WAIT_OBJECT_0); 
    8583 
    8684    m_nReaders++; 
     
    9492        return false; 
    9593      } 
    96       //assert(dwEvent == WAIT_OBJECT_0); 
    9794    } 
    9895    // V( semReaders ) 
     
    105102    // P( semReaders ) 
    106103    dwEvent = ::WaitForSingleObject( m_semReaders, INFINITE ); 
    107     assert(dwEvent == WAIT_OBJECT_0); 
     104    if (dwEvent != WAIT_OBJECT_0) 
     105      throw std::exception("Unlock_DataRead::this is really bad..."); 
    108106 
    109107    m_nReaders--; 
     
    126124    if (dwEvent != WAIT_OBJECT_0) 
    127125      return false; 
    128     //assert(dwEvent == WAIT_OBJECT_0); 
    129126    return true; 
    130127  } 
     
    146143    :  m_pMutexRW(pMutexRW), m_bIsLocked(false) 
    147144  { 
    148     assert(m_pMutexRW); 
     145    if (!m_pMutexRW) 
     146      throw std::exception("No mutex in lock: this is really bad..."); 
    149147    if (bInitialLock){ 
    150148      m_bIsLocked = m_pMutexRW->Lock_DataRead(dwMilliseconds); 
     
    157155 
    158156  inline void Lock(DWORD dwMilliseconds = INFINITE){ 
    159     assert(m_bIsLocked == false); 
     157    if (m_bIsLocked) 
     158      throw std::exception("Mutex locked when trying to lock: this is really bad..."); 
    160159    m_bIsLocked = m_pMutexRW->Lock_DataRead(dwMilliseconds); 
    161160  }; 
    162161 
    163162  inline void Unlock(){ 
    164     assert(m_bIsLocked); 
     163    if (!m_bIsLocked) 
     164      throw std::exception("Mutex unlocked when trying to unlock:: this is really bad..."); 
    165165    m_pMutexRW->Unlock_DataRead(); 
    166166    m_bIsLocked = false; 
     
    182182    :  m_pMutexRW(pMutexRW), m_bIsLocked(false) 
    183183  { 
    184     assert(m_pMutexRW); 
     184    if (!m_pMutexRW) 
     185      throw std::exception("No mutex in lock: this is really bad..."); 
    185186    if (bInitialLock){ 
    186187      m_bIsLocked = m_pMutexRW->Lock_DataWrite(dwMilliseconds); 
     
    193194 
    194195  inline void Lock(DWORD dwMilliseconds = INFINITE){ 
    195     assert(m_bIsLocked == false); 
     196    if (m_bIsLocked) 
     197      throw std::exception("already locked...this is really bad..."); 
    196198    m_bIsLocked = m_pMutexRW->Lock_DataWrite(dwMilliseconds); 
    197199  }; 
    198200 
    199201  inline void Unlock(){ 
    200     assert(m_bIsLocked); 
     202    if (!m_bIsLocked) 
     203      throw std::exception("already un-locked...this is really bad..."); 
    201204    m_pMutexRW->Unlock_DataWrite(); 
    202205    m_bIsLocked = false; 
  • include/NSCHelper.cpp

    r9567d4b r739db5a  
    2121 
    2222#include <NSCHelper.h> 
    23 #include <assert.h> 
    2423#include <msvc_wrappers.h> 
    2524#include <config.h> 
     
    119118    return _T("BAD_CODE"); 
    120119} 
     120/** 
     121* Translate a string into the corresponding return code  
     122* @param returnCode  
     123* @return  
     124*/ 
     125NSCAPI::nagiosReturn NSCHelper::translateReturn(std::wstring str) { 
     126  if (str == _T("OK")) 
     127    return NSCAPI::returnOK; 
     128  else if (str == _T("CRITICAL")) 
     129    return NSCAPI::returnCRIT; 
     130  else if (str == _T("WARNING")) 
     131    return NSCAPI::returnWARN; 
     132  else  
     133    return NSCAPI::returnUNKNOWN; 
     134} 
    121135 
    122136 
     
    132146  lpNSAPIMessage fNSAPIMessage = NULL; 
    133147  lpNSAPIStopServer fNSAPIStopServer = NULL; 
     148  lpNSAPIExit fNSAPIExit = NULL; 
    134149  lpNSAPIInject fNSAPIInject = NULL; 
    135150  lpNSAPICheckLogMessages fNSAPICheckLogMessages = NULL; 
     
    242257      break; 
    243258    default: 
    244       throw NSCMHExcpetion(_T("Unknown inject error.")); 
     259      delete [] msgBuffer; 
     260      delete [] perfBuffer; 
     261      throw NSCMHExcpetion(_T("Unknown return code when injecting: ") + std::wstring(command)); 
    245262  } 
    246263  delete [] msgBuffer; 
     
    248265  return retC; 
    249266} 
     267 
     268/** 
     269* Inject a request command in the core (this will then be sent to the plug-in stack for processing) 
     270* @param command Command to inject (password should not be included. 
     271* @param argLen The length of the argument buffer 
     272* @param **argument The argument buffer 
     273* @param message The return message buffer 
     274* @param perf The return performance data buffer 
     275* @return The return of the command 
     276*/ 
     277NSCAPI::nagiosReturn NSCModuleHelper::InjectCommand(const TCHAR* command, std::list<std::wstring> argument, std::wstring & message, std::wstring & perf)  
     278{ 
     279  if (!fNSAPIInject) 
     280    throw NSCMHExcpetion(_T("NSCore has not been initiated...")); 
     281  unsigned int buf_len = getBufferLength(); 
     282 
     283 
     284  unsigned int argLen; 
     285  TCHAR ** aBuffer = arrayBuffer::list2arrayBuffer(argument, argLen); 
     286  TCHAR *msgBuffer = new TCHAR[buf_len+1]; 
     287  TCHAR *perfBuffer = new TCHAR[buf_len+1]; 
     288  msgBuffer[0] = 0; 
     289  perfBuffer[0] = 0; 
     290  NSCAPI::nagiosReturn retC = InjectCommandRAW(command, argLen, aBuffer, msgBuffer, buf_len, perfBuffer, buf_len); 
     291  switch (retC) { 
     292    case NSCAPI::returnIgnored: 
     293      NSC_LOG_MESSAGE_STD(_T("No handler for command '") + command + _T("'.")); 
     294      break; 
     295    case NSCAPI::returnInvalidBufferLen: 
     296      NSC_LOG_ERROR(_T("Inject buffer to small, increase the value of: string_length.")); 
     297      break; 
     298    case NSCAPI::returnOK: 
     299    case NSCAPI::returnCRIT: 
     300    case NSCAPI::returnWARN: 
     301    case NSCAPI::returnUNKNOWN: 
     302      message = msgBuffer; 
     303      perf = perfBuffer; 
     304      break; 
     305    default: 
     306      delete [] msgBuffer; 
     307      delete [] perfBuffer; 
     308      throw NSCMHExcpetion(_T("Unknown return code when injecting: ") + std::wstring(command)); 
     309  } 
     310  delete [] msgBuffer; 
     311  delete [] perfBuffer; 
     312  return retC; 
     313} 
     314 
    250315/** 
    251316 * A wrapper around the InjetCommand that is simpler to use. 
     
    304369} 
    305370/** 
     371 * Close the program (usefull for tray/testmode) without stopping the service (unless this is the service). 
     372 * @author mickem 
     373 */ 
     374void NSCModuleHelper::Exit(void) { 
     375  if (fNSAPIExit) 
     376    fNSAPIExit(); 
     377} 
     378/** 
    306379 * Retrieve a string from the settings subsystem (INI-file) 
    307380 * Might possibly be located in the registry in the future. 
     
    343416    throw NSCMHExcpetion(_T("Settings could not be destroyed.")); 
    344417  } 
    345   assert(aBuffer == NULL); 
     418  if (aBuffer != NULL) 
     419    throw NSCMHExcpetion(_T("buffer is not null?.")); 
    346420  return ret; 
    347421} 
     
    565639    throw NSCMHExcpetion(_T("Commands could not be destroyed.")); 
    566640  } 
    567   assert(aBuffer == NULL); 
     641  if (aBuffer != NULL) 
     642    throw NSCMHExcpetion(_T("buffer is not null?.")); 
    568643  return ret; 
    569644} 
     
    658733  NSCModuleHelper::fNSAPIMessage = (NSCModuleHelper::lpNSAPIMessage)f(_T("NSAPIMessage")); 
    659734  NSCModuleHelper::fNSAPIStopServer = (NSCModuleHelper::lpNSAPIStopServer)f(_T("NSAPIStopServer")); 
     735  NSCModuleHelper::fNSAPIExit = (NSCModuleHelper::lpNSAPIExit)f(_T("NSAPIExit")); 
    660736  NSCModuleHelper::fNSAPIInject = (NSCModuleHelper::lpNSAPIInject)f(_T("NSAPIInject")); 
    661737  NSCModuleHelper::fNSAPIGetBasePath = (NSCModuleHelper::lpNSAPIGetBasePath)f(_T("NSAPIGetBasePath")); 
  • include/NSCHelper.h

    r9567d4b r739db5a  
    4040  std::wstring translateMessageType(NSCAPI::messageTypes msgType); 
    4141  std::wstring translateReturn(NSCAPI::nagiosReturn returnCode); 
     42  NSCAPI::nagiosReturn translateReturn(std::wstring str); 
    4243  NSCAPI::nagiosReturn maxState(NSCAPI::nagiosReturn a, NSCAPI::nagiosReturn b); 
    4344 
     
    116117  typedef void (*lpNSAPIMessage)(int, const TCHAR*, const int, const TCHAR*); 
    117118  typedef NSCAPI::errorReturn (*lpNSAPIStopServer)(void); 
     119  typedef NSCAPI::errorReturn (*lpNSAPIExit)(void); 
    118120  typedef NSCAPI::nagiosReturn (*lpNSAPIInject)(const TCHAR*, const unsigned int, TCHAR **, TCHAR *, unsigned int, TCHAR *, unsigned int); 
    119121  typedef void* (*lpNSAPILoader)(TCHAR*); 
     
    154156  NSCAPI::nagiosReturn InjectCommandRAW(const TCHAR* command, const unsigned int argLen, TCHAR **argument, TCHAR *returnMessageBuffer, unsigned int returnMessageBufferLen, TCHAR *returnPerfBuffer, unsigned int returnPerfBufferLen); 
    155157  NSCAPI::nagiosReturn InjectCommand(const TCHAR* command, const unsigned int argLen, TCHAR **argument, std::wstring & message, std::wstring & perf); 
     158  NSCAPI::nagiosReturn InjectCommand(const TCHAR* command, std::list<std::wstring> argument, std::wstring & message, std::wstring & perf); 
    156159  NSCAPI::nagiosReturn InjectSplitAndCommand(const TCHAR* command, TCHAR* buffer, TCHAR splitChar, std::wstring & message, std::wstring & perf); 
    157160  NSCAPI::nagiosReturn InjectSplitAndCommand(const std::wstring command, const std::wstring buffer, TCHAR splitChar, std::wstring & message, std::wstring & perf, bool escape = false); 
    158161  void StopService(void); 
     162  void Exit(void); 
    159163  std::wstring getBasePath(); 
    160164  bool logDebug(); 
     
    358362    } catch (...) { \ 
    359363      NSC_LOG_CRITICAL(_T("Unknown exception in: commandLineExec(...)")); \ 
     364      std::wcerr << _T("Unknown exception in: commandLineExec(...)") << std::endl; \ 
    360365      return NSCAPI::hasFailed; \ 
    361366    } \ 
  • include/NTService.h

    r978bd31 r739db5a  
    2222 
    2323#include <string> 
    24  
    25  
     24#include <sysinfo.h> 
     25 
     26namespace service_helper { 
     27  class service_exception { 
     28    std::wstring what_; 
     29  public: 
     30    service_exception(std::wstring what) : what_(what) { 
     31      OutputDebugString((std::wstring(_T("ERROR:")) + what).c_str()); 
     32    } 
     33    std::wstring what() { 
     34      return what_; 
     35    } 
     36  }; 
    2637/** 
    2738 * @ingroup NSClient++ 
     
    5061class NTService : public TBase 
    5162{ 
     63public: 
    5264private: 
    5365  HANDLE  hServerStopEvent; 
    5466  SERVICE_STATUS          ssStatus; 
    5567  SERVICE_STATUS_HANDLE   sshStatusHandle; 
    56   DWORD                   dwErr; 
    5768  SERVICE_TABLE_ENTRY *dispatchTable; 
     69  DWORD dwControlsAccepted; 
     70  std::wstring name_; 
     71  wchar_t *serviceName_; 
    5872public: 
    59   NTService() : dispatchTable(NULL), hServerStopEvent(NULL), dwErr(0) { 
    60     // TODO This ought to be made dynamic somehow... 
     73  NTService(std::wstring name) : dispatchTable(NULL), hServerStopEvent(NULL), name_(name), dwControlsAccepted(SERVICE_ACCEPT_STOP) { 
     74    serviceName_ = new wchar_t[name.length()+2]; 
     75    wcsncpy(serviceName_, name.c_str(), name.length()); 
    6176    dispatchTable = new SERVICE_TABLE_ENTRY[2]; 
    62     dispatchTable[0].lpServiceName = SZSERVICENAME; 
     77    dispatchTable[0].lpServiceName = serviceName_; 
    6378    dispatchTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)TBase::service_main_dispatch; 
    6479    dispatchTable[1].lpServiceName = NULL; 
     
    6782  virtual ~NTService() { 
    6883    delete [] dispatchTable; 
     84    delete [] serviceName_; 
    6985  } 
    7086 
     
    7288    BOOL ret = ::StartServiceCtrlDispatcher(dispatchTable); 
    7389    if (ret == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) { 
    74       std::wcout << "We are running in console mode, terminating..." << std::endl; 
     90      OutputDebugString(_T("We are running in console mode, terminating...")); 
    7591      return false; 
    7692    } 
    7793    return ret != 0; 
    7894  } 
     95 
     96 
     97 
     98  typedef DWORD (WINAPI *LPHANDLER_FUNCTION_EX) ( 
     99    DWORD dwControl,     // requested control code 
     100    DWORD dwEventType,   // event type 
     101    LPVOID lpEventData,  // event data 
     102    LPVOID lpContext     // user-defined context data 
     103    ); 
     104  typedef SERVICE_STATUS_HANDLE (WINAPI *REGISTER_SERVICE_CTRL_HANDLER_EX) ( 
     105    LPCTSTR lpServiceName,                // name of service 
     106    LPHANDLER_FUNCTION_EX lpHandlerProc,  // handler function 
     107    LPVOID lpContext                      // user data 
     108    ); 
     109 
     110  SERVICE_STATUS_HANDLE RegisterServiceCtrlHandlerEx_(LPCTSTR lpServiceName, LPHANDLER_FUNCTION_EX lpHandlerProc, LPVOID lpContext) { 
     111    HMODULE hAdvapi32 = NULL; 
     112    REGISTER_SERVICE_CTRL_HANDLER_EX fRegisterServiceCtrlHandlerEx = NULL; 
     113 
     114    if ((hAdvapi32 = GetModuleHandle(TEXT("Advapi32.dll"))) == NULL) 
     115      return 0; 
     116#ifdef _UNICODE 
     117    fRegisterServiceCtrlHandlerEx = (REGISTER_SERVICE_CTRL_HANDLER_EX)GetProcAddress(hAdvapi32, "RegisterServiceCtrlHandlerExW"); 
     118#else 
     119    fRegisterServiceCtrlHandlerEx = (REGISTER_SERVICE_CTRL_HANDLER_EX)GetProcAddress(hAdvapi32, "RegisterServiceCtrlHandlerExA"); 
     120#endif // _UNICODE 
     121    if (!fRegisterServiceCtrlHandlerEx) 
     122      return 0; 
     123    return fRegisterServiceCtrlHandlerEx(lpServiceName, lpHandlerProc, lpContext); 
     124  } 
     125 
     126 
    79127 
    80128  void service_main(DWORD dwArgc, LPTSTR *lpszArgv) 
    81129  { 
    82     // register our service control handler: 
    83     sshStatusHandle = RegisterServiceCtrlHandler( SZSERVICENAME, TBase::service_ctrl_dispatch); 
    84  
    85     // SERVICE_STATUS members that don't change in example 
     130    OutputDebugString(_T("service_main launcing...")); 
     131    sshStatusHandle = RegisterServiceCtrlHandlerEx_(name_.c_str(), TBase::service_ctrl_dispatch_ex, NULL); 
     132    if (sshStatusHandle == 0) { 
     133      OutputDebugString(_T("Failed to register RegisterServiceCtrlHandlerEx_ (attempting to use normal one)...")); 
     134      sshStatusHandle = RegisterServiceCtrlHandler(name_.c_str(), TBase::service_ctrl_dispatch); 
     135    } else { 
     136      if (systemInfo::isAboveXP(systemInfo::getOSVersion())) { 
     137        dwControlsAccepted |= SERVICE_ACCEPT_SESSIONCHANGE; 
     138        OutputDebugString(_T("Windows XP or above detected so enabling session messages...")); 
     139      } else 
     140        OutputDebugString(_T("Windows 2000 or older detected (disabling session messages)")); 
     141    } 
     142    if (sshStatusHandle == 0) 
     143      throw service_exception(_T("Failed to register service: ") + error::lookup::last_error()); 
     144 
     145 
    86146    ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; 
    87147    ssStatus.dwServiceSpecificExitCode = 0; 
     148    ssStatus.dwControlsAccepted = dwControlsAccepted; 
    88149 
    89150    // report the status to the service control manager. 
    90     if (!ReportStatusToSCMgr(SERVICE_START_PENDING,NO_ERROR,3000)) { 
    91       if (sshStatusHandle) 
    92         ReportStatusToSCMgr(SERVICE_STOPPED,dwErr,0); 
    93     } 
    94  
    95     ServiceStart( dwArgc, lpszArgv ); 
    96  
    97     // try to report the stopped status to the service control manager. 
    98     if (sshStatusHandle) 
    99       ReportStatusToSCMgr(SERVICE_STOPPED,dwErr,0); 
    100   } 
    101  
    102  
    103   void service_ctrl(DWORD dwCtrlCode) { 
     151    if (!ReportStatusToSCMgr(SERVICE_START_PENDING,3000)) { 
     152      ReportStatusToSCMgr(SERVICE_STOPPED,0); 
     153      throw service_exception(_T("Failed to report service status: ") + error::lookup::last_error()); 
     154    } 
     155    try { 
     156      OutputDebugString(std::wstring(_T("Attempting to start service with: ") + strEx::ihextos(dwControlsAccepted)).c_str()); 
     157      ServiceStart(dwArgc, lpszArgv); 
     158    } catch (...) { 
     159      throw service_exception(_T("Uncaught exception in service... terminating: ") + error::lookup::last_error()); 
     160    } 
     161    ReportStatusToSCMgr(SERVICE_STOPPED,0); 
     162  } 
     163 
     164  typedef struct tagWTSSESSION_NOTIFICATION 
     165  { 
     166    DWORD cbSize; 
     167    DWORD dwSessionId; 
     168 
     169  } WTSSESSION_NOTIFICATION, *PWTSSESSION_NOTIFICATION; 
     170#define WTS_SESSION_LOGON                  0x5 
     171#define WTS_SESSION_LOGOFF                 0x6 
     172 
     173  DWORD service_ctrl_ex(DWORD dwCtrlCode, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext) { 
    104174    switch(dwCtrlCode)  
    105175    { 
    106176    case SERVICE_CONTROL_STOP: 
    107       ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, 0); 
     177      ReportStatusToSCMgr(SERVICE_STOP_PENDING, 0); 
    108178      ServiceStop(); 
    109       return; 
     179      return 0; 
    110180 
    111181    case SERVICE_CONTROL_INTERROGATE: 
    112182      break; 
    113183 
     184    case SERVICE_CONTROL_SESSIONCHANGE: 
     185      if (lpEventData != NULL && dwEventType == WTS_SESSION_LOGON) 
     186        service_on_session_changed(reinterpret_cast<WTSSESSION_NOTIFICATION*>(lpEventData)->dwSessionId, true, dwEventType); 
     187      else if (lpEventData != NULL && dwEventType == WTS_SESSION_LOGOFF) 
     188        service_on_session_changed(reinterpret_cast<WTSSESSION_NOTIFICATION*>(lpEventData)->dwSessionId, false, dwEventType); 
     189      else { 
     190        service_on_session_changed(reinterpret_cast<WTSSESSION_NOTIFICATION*>(lpEventData)->dwSessionId, false, dwEventType); 
     191      } 
     192      break; 
     193 
    114194    default: 
    115195      break; 
    116196 
    117197    } 
    118     ReportStatusToSCMgr(ssStatus.dwCurrentState, NO_ERROR, 0); 
     198    ReportStatusToSCMgr(ssStatus.dwCurrentState, 0); 
     199    return 0; 
    119200  } 
    120201 
     
    134215  * 
    135216  */ 
    136   BOOL ReportStatusToSCMgr(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint) { 
     217  BOOL ReportStatusToSCMgr(DWORD dwCurrentState, DWORD dwWaitHint) { 
    137218    static DWORD dwCheckPoint = 1; 
    138219    BOOL fResult = TRUE; 
     
    141222      ssStatus.dwControlsAccepted = 0; 
    142223    else 
    143       ssStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; 
     224      ssStatus.dwControlsAccepted = dwControlsAccepted; 
    144225 
    145226    ssStatus.dwCurrentState = dwCurrentState; 
    146     ssStatus.dwWin32ExitCode = dwWin32ExitCode; 
     227    ssStatus.dwWin32ExitCode = 0; 
    147228    ssStatus.dwWaitHint = dwWaitHint; 
    148229 
     
    171252  void ServiceStart(DWORD dwArgc, LPTSTR *lpszArgv) { 
    172253    hServerStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); 
    173     if (!ReportStatusToSCMgr(SERVICE_RUNNING,NO_ERROR,0)) { 
     254    if (!ReportStatusToSCMgr(SERVICE_RUNNING,0)) { 
    174255      if (hServerStopEvent) 
    175256        CloseHandle(hServerStopEvent); 
     
    203284  } 
    204285}; 
     286} 
  • include/PDHCounter.h

    r3f69109 r739db5a  
    2424#include <pdh.h> 
    2525#include <pdhmsg.h> 
    26 #include <assert.h> 
    2726#include <sstream> 
     27#include <error.hpp> 
    2828 
    2929namespace PDH { 
     
    178178 
    179179    PDHCounterInfo getCounterInfo(BOOL bExplainText = FALSE) { 
    180       assert(hCounter_ != NULL); 
     180      if (hCounter_ == NULL) 
     181        throw PDHException(_T("Counter is null!")); 
    181182      PDH_STATUS status; 
    182183      BYTE *lpBuffer = new BYTE[1025]; 
     
    206207        throw PDHException(name_, _T("PdhAddCounter failed"), status); 
    207208      } 
    208       assert(hCounter_ != NULL); 
     209      if (hCounter_ == NULL) 
     210        throw PDHException(_T("Counter is null!")); 
    209211    } 
    210212    void remove() { 
     
    279281 
    280282    void open() { 
    281       assert(hQuery_ == NULL); 
     283      if (hQuery_ != NULL) 
     284        throw PDHException(_T("query is not null!")); 
    282285      PDH_STATUS status; 
    283286      if( (status = PdhOpenQuery( NULL, 0, &hQuery_ )) != ERROR_SUCCESS) 
     
    289292 
    290293    void close() { 
    291       assert(hQuery_ != NULL); 
     294      if (hQuery_ == NULL) 
     295        throw PDHException(_T("query is null!")); 
    292296      PDH_STATUS status; 
    293297      for (CounterList::iterator it = counters_.begin(); it != counters_.end(); it++) { 
     
    444448          error = _T("The specified counter was not found in the performance object."); 
    445449          break; 
     450        case PDH_CSTATUS_NO_OBJECT: 
     451          error = _T("The specified performance object was not found on the computer."); 
     452          break; 
    446453        case PDH_CSTATUS_NO_MACHINE: 
    447454          error = _T("The specified computer could not be found or connected to."); 
     
    453460          error = _T("The function is unable to allocate a required temporary buffer."); 
    454461          break; 
     462        default: 
     463          error = _T("Unknown error: ") + error::lookup::last_error(status); 
     464          break; 
    455465      } 
    456466      return false; 
  • include/SSLSocket.h

    r2f01f93 r739db5a  
    112112 
    113113    void destroy() { 
    114       if (ctx_ != NULL) 
    115         throw SSLException(_T("Error: SSL Context already initalized.")); 
     114      if (ctx_ == NULL) 
     115        throw SSLException(_T("Error: SSL Context not initalized.")); 
    116116      SSL_CTX_free(ctx_); 
    117117      ctx_ = NULL; 
     
    139139    } 
    140140    void setTmpDH(::DH* dh) { 
    141       assert(ctx_); 
    142       assert(dh); 
     141      if (!ctx_) 
     142        throw SSLException(_T("setTmpDH:: Invalid context")); 
     143      if (!dh) 
     144        throw SSLException(_T("setTmpDH:: Invalid dh")); 
    143145      SSL_CTX_set_tmp_dh(ctx_, dh); 
    144146    } 
     
    282284    } 
    283285    void attach(SOCKET s) { 
    284       assert(s); 
     286      if (!s) 
     287        throw SSLException(_T("attach:: Invalid socket")); 
    285288      try { 
    286289        tBase::attach(s); 
  • include/ServiceCmd.cpp

    rb5ef837 r739db5a  
    9595    CloseServiceHandle(schSCManager); 
    9696    if (result != TRUE) 
    97       throw SCException(_T("Could not query service information")); 
     97      throw SCException(_T("Could not change service information")); 
    9898  } 
    9999 
  • include/Socket.h

    rd76af81 r739db5a  
    202202    } 
    203203    virtual void attach(SOCKET s) { 
    204       assert(socket_ == NULL); 
     204      if (socket_ != NULL) 
     205        throw SocketException(_T("Cant attach to existing socket!")); 
    205206      socket_ = s; 
    206207    } 
     
    314315    virtual bool sendAll(const char * buffer, unsigned int len); 
    315316 
    316     int inline sendAll(DataBuffer &buffer) { 
     317    bool inline sendAll(DataBuffer &buffer) { 
    317318      return sendAll(buffer.getBuffer(), buffer.getLength()); 
    318319    } 
    319320 
    320321    virtual int send(const char * buf, unsigned int len, int flags = 0) { 
    321       assert(socket_); 
     322      if (!socket_) 
     323        throw SocketException(_T("send:: cant send to uninitialized socket")); 
    322324      return ::send(socket_, buf, len, flags); 
    323325    } 
     
    328330    virtual void socket(int af, int type, int protocol ) { 
    329331      socket_ = ::socket(af, type, protocol); 
    330       assert(socket_ != INVALID_SOCKET); 
     332      if (socket_ == INVALID_SOCKET) 
     333        throw SocketException(_T("Failed to create socket"), WSAGetLastError()); 
    331334    } 
    332335    virtual void bind() { 
    333       assert(socket_); 
     336      if (!socket_) 
     337        throw SocketException(_T("bind:: Invalid socket")); 
    334338      int fromlen=sizeof(from_); 
    335339      if (::bind(socket_, (sockaddr*)&from_, fromlen) == SOCKET_ERROR) 
     
    337341    } 
    338342    virtual void listen(int backlog = SOMAXCONN) { 
    339       assert(socket_); 
     343      if (!socket_) 
     344        throw SocketException(_T("listen:: Invalid socket")); 
    340345      if (::listen(socket_, backlog) == SOCKET_ERROR) 
    341346        throw SocketException(_T("listen failed: "), ::WSAGetLastError()); 
     
    359364    } 
    360365    virtual void ioctlsocket(long cmd, u_long *argp) { 
    361       assert(socket_); 
     366      if (!socket_) 
     367        throw SocketException(_T("ioctlsocket:: Invalid socket")); 
    362368      if (::ioctlsocket(socket_, cmd, argp) == SOCKET_ERROR) 
    363369        throw SocketException(_T("ioctlsocket failed: "), ::WSAGetLastError()); 
     
    440446      } 
    441447      void exitThread(void) { 
    442         assert(hStopEvent_ != NULL); 
     448        if (hStopEvent_ == NULL) 
     449          throw SocketException(_T("exitThread:: no stop event??")); 
    443450        if (!SetEvent(hStopEvent_)) 
    444451          throw SocketException(_T("SetEvent failed.")); 
  • include/arrayBuffer.cpp

    r9567d4b r739db5a  
    5656    wcsncpy_s(arrayBuffer[i], alen+2, (*it).c_str(), alen+1); 
    5757  } 
    58   assert(i == argLen); 
     58  if (i != argLen) 
     59    throw ArrayBufferException(_T("Invalid length!")); 
    5960  return arrayBuffer; 
    6061} 
     
    107108*/ 
    108109arrayBuffer::arrayBuffer arrayBuffer::split2arrayBuffer(const TCHAR* buffer, TCHAR splitChar, unsigned int &argLen) { 
    109   assert(buffer); 
     110  if (!buffer) 
     111    throw ArrayBufferException(_T("Invalid buffer specified!")); 
    110112  argLen = 0; 
    111113  const TCHAR *p = buffer; 
     
    135137void arrayBuffer::set(arrayBuffer arrayBuffer, const unsigned int argLen, const unsigned int position, std::wstring argument) { 
    136138  if (position >= argLen) 
    137     assert(false); 
     139    throw ArrayBufferException(_T("position is outside the buffer")); 
    138140  delete [] arrayBuffer[position]; 
    139141  size_t len = argument.length(); 
     
    168170    if (p2 == std::wstring::npos) 
    169171      p2 = inBuf.size(); 
     172    if (p1 == p2 && p1 != inBuf.size()) { 
     173      p1++; 
     174      continue; 
     175    } 
    170176    // p1 = start of "this token" 
    171177    // p2 = end of "this token" (next split char) 
    172178 
    173     assert(p2>p1); 
     179    if (p2<=p1) 
     180      throw ArrayBufferException(_T("Invalid position")); 
    174181    std::wstring token = inBuf.substr(p1,p2-p1); 
    175182    if (escape && token[0] == '\"') 
     
    238245      p = inBuf.size(); 
    239246    //    TCHAR *q = strchr(p, (i<argLen-1)?splitChar:0); 
    240     assert(p>l); 
    241247    unsigned int len = static_cast<unsigned int>(p-l); 
    242248    arrayBuffer[i] = new TCHAR[len+1]; 
  • include/arrayBuffer.h

    r47b843a r739db5a  
    2424#include <string> 
    2525#include <list> 
    26 #include <assert.h> 
    2726#include <iostream> 
    2827/** 
     
    5150 */ 
    5251namespace arrayBuffer { 
     52  class ArrayBufferException { 
     53  public: 
     54    ArrayBufferException(std::wstring error) {} 
     55  }; 
    5356  typedef TCHAR* arrayBufferItem; 
    5457  typedef arrayBufferItem* arrayBuffer; 
  • include/charEx.h

    r978bd31 r739db5a  
    2020***************************************************************************/ 
    2121#pragma once 
    22 #include <assert.h> 
    2322#include <windows.h> 
    2423#include <tchar.h> 
     
    4746 
    4847  inline char* tchar_to_char( const wchar_t* pStr, int len, int &nChars) { 
    49     assert(pStr != NULL); 
    50     assert(len >= 0 || len == -1); 
     48    if (pStr == NULL) 
     49      throw std::exception(); 
     50    if (len < -1) 
     51      throw std::exception(); 
    5152 
    5253    // figure out how many narrow characters we are going to get  
     
    6768 
    6869  inline wchar_t* char_to_tchar(const char* pStr, int len, int &nChars) { 
    69     assert( pStr != NULL); 
    70     assert( len >= 0 || len == -1); 
     70    if (pStr == NULL) 
     71      throw std::exception(); 
     72    if (len < -1) 
     73      throw std::exception(); 
    7174 
    7275    // figure out how many wide characters we are going to get 
     
    9093  typedef std::pair<std::wstring,TCHAR*> token; 
    9194  inline token getToken(TCHAR *buffer, TCHAR split) { 
    92     assert(buffer != NULL); 
     95    if (buffer == NULL) 
     96      throw std::exception(); 
    9397    TCHAR *p = wcschr(buffer, split); 
    9498    if (!p) 
  • include/checkHelpers.hpp

    rde8ef76 r739db5a  
    6666  typedef enum {showLong, showShort, showProblems, showUnknown} showType; 
    6767  template <class TContents> 
    68   struct CheckConatiner { 
    69     typedef CheckConatiner<TContents> TThisType; 
     68  struct CheckContainer { 
     69    typedef CheckContainer<TContents> TThisType; 
    7070    TContents warn; 
    7171    TContents crit; 
     
    7777 
    7878 
    79     CheckConatiner() : show(showUnknown), perfData(true) 
     79    CheckContainer() : show(showUnknown), perfData(true) 
    8080    {} 
    81     CheckConatiner(std::wstring data_, TContents warn_, TContents crit_)  
     81    CheckContainer(std::wstring data_, TContents warn_, TContents crit_)  
    8282      : data(data_), warn(warn_), crit(crit_), show(showUnknown)  
    8383    {} 
    84     CheckConatiner(std::wstring name_, std::wstring alias_, TContents warn_, TContents crit_)  
     84    CheckContainer(std::wstring name_, std::wstring alias_, TContents warn_, TContents crit_)  
    8585      : data(data_), alias(alias_), warn(warn_), crit(crit_), show(showUnknown)  
    8686    {} 
    87     CheckConatiner(const TThisType &other)  
     87    CheckContainer(const TThisType &other)  
    8888      : data(other.data), alias(other.alias), warn(other.warn), crit(other.crit), show(other.show)  
    8989    {} 
     
    278278    } 
    279279    static std::wstring print_perf(double value, std::wstring unit) { 
    280       return strEx::itos(value); 
     280      return strEx::itos_non_sci(value); 
    281281    } 
    282282    static std::wstring print(double value) { 
     
    298298 
    299299  typedef unsigned long state_type; 
    300   const int state_none  = 0x00; 
    301   const int state_started = 0x01; 
    302   const int state_stopped = 0x02; 
     300  const int state_none    = 0x00; 
     301  const int state_started   = 0x01; 
     302  const int state_stopped   = 0x02; 
     303  const int state_not_found = 0x06; 
    303304 
    304305  class state_handler { 
     
    314315        else if (*it == _T("ignored")) 
    315316          ret |= state_none; 
     317        else if (*it == _T("not found")) 
     318          ret |= state_not_found; 
    316319      } 
    317320      return ret; 
     
    324327      else if (value == state_none) 
    325328        return _T("none"); 
     329      else if (value == state_not_found) 
     330        return _T("not found"); 
    326331      return _T("unknown"); 
    327332    } 
     
    510515            MAKE_PERFDATA(alias, THandler::print_unformated(value.getLowerPercentage()), _T("%"),  
    511516            THandler::print_unformated(warn), THandler::print_unformated(crit)); 
     517      } else if (type_ == value_upper) { 
     518        std::wstring unit = THandler::get_perf_unit(min(warn, min(crit, value.value))); 
     519        return  
     520          MAKE_PERFDATA(alias, THandler::print_perf((value.value), unit), unit,  
     521          THandler::print_perf(value.total-warn, unit), THandler::print_perf(value.total-crit, unit)); 
    512522      } else { 
    513523        std::wstring unit = THandler::get_perf_unit(min(warn, min(crit, value.value))); 
     
    677687        message = lable + _T(": ") + formatState(TStateHolder::toStringLong(value), type); 
    678688        return true; 
    679       } else { 
    680         //std::cout << "No bounds specified..." << std::endl; 
    681689      } 
    682690      return false; 
     
    752760} 
    753761 
     762 
  • include/config.h

    r9567d4b r739db5a  
    2323#include "../AutoBuild.h" 
    2424#include <tchar.h>  
     25#include <string> 
    2526// Application Name 
    2627#define SZAPPNAME _T("NSClient++") 
    2728 
    2829// Version 
    29 //#define SZBETATAG _T(" ") // _T(" RC ")  _T(" BETA ")  
     30//#define SZBETATAG _T(" ") 
     31//#define SZBETATAG _T(" RC ")   
    3032#define SZBETATAG _T(" BETA ")  
    3133#define SZVERSION STRPRODUCTVER SZBETATAG STRPRODUCTDATE 
     
    7476  const std::wstring name = _T(key); \ 
    7577  const std::wstring name ## _DEFAULT = _T(value); 
     78#define NSCLIENT_SETTINGS_SYSTRAY_EXE _T("systray_exe") 
     79#define NSCLIENT_SETTINGS_SYSTRAY_EXE_DEFAULT _T("nstray.exe") 
    7680 
    7781#define DEFINE_PATH(name, path) \ 
     
    240244    DEFINE_SETTING_I(PAYLOAD_LEN, DEFAULT_SECTION, "payload length", 4096); 
    241245    DESCRIBE_SETTING(PAYLOAD_LEN, "PAYLOAD LENGTH", "..."); 
     246 
     247    DEFINE_SETTING_B(SHARED_SESSION, DEFAULT_SECTION, "shared session", true); 
     248    DESCRIBE_SETTING(SHARED_SESSION, "SHARED SESSION", "TODO"); 
     249 
     250  } 
     251 
     252  namespace shared_session { 
     253    DEFINE_SETTING_S(SYSTRAY_EXE, DEFAULT_SECTION, "tray", ""); 
     254    DESCRIBE_SETTING(SYSTRAY_EXE, "SYSTEM TRAY EXE", "TODO"); 
     255     
    242256  } 
    243257 
     
    265279    DESCRIBE_SETTING_ADVANCED(DEBUG_KEY, "DEBUG", "Log all \"hits\" and \"misses\" on the eventlog filter chain, useful for debugging eventlog checks but very very very noisy so you don't want to accidentally set this on a real machine."); 
    266280 
     281    DEFINE_SETTING_B(LOOKUP_NAMES, EVENT_LOG_SECTION, "lookup_names", false); 
     282    DESCRIBE_SETTING_ADVANCED(LOOKUP_NAMES, "TODO", "TODO"); 
     283 
    267284    DEFINE_SETTING_S(SYNTAX, EVENT_LOG_SECTION, "syntax", ""); 
    268285    DESCRIBE_SETTING(SYNTAX, "SYNTAX", "Set this to use a specific syntax string for all commands (that don't specify one)."); 
     286 
     287    DEFINE_SETTING_I(BUFFER_SIZE, EVENT_LOG_SECTION, "buffer_size", 4096); 
     288    DESCRIBE_SETTING(BUFFER_SIZE, "BUFFER SIZE", "The size of the bugfer to use when getting messages this affects the speed and maximum size of messages you can recieve."); 
    269289  } 
    270290 
     
    407427    DEFINE_SETTING_S(FILENAME, LOG_SECTION, "file", "nsclient.log"); 
    408428    DESCRIBE_SETTING_ADVANCED(FILENAME, "SYNTAX", "The file to write log data to. If no directory is used this is relative to the NSClient++ binary."); 
     429 
     430    DEFINE_SETTING_S(ROOT, LOG_SECTION, "root", "auto"); 
     431    DESCRIBE_SETTING_ADVANCED(ROOT, "TODO", "TODO"); 
    409432 
    410433    DEFINE_SETTING_S(DATEMASK, LOG_SECTION, "date format", "%Y-%m-%d %H:%M:%S"); 
  • include/error.hpp

    rb7ed6ac r739db5a  
    99  public: 
    1010    static std::wstring from_system(unsigned long dwError) { 
    11       LPVOID lpMsgBuf; 
     11      LPVOID lpMsgBuf = NULL; 
    1212      unsigned long dwRet = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,NULL,dwError,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPTSTR)&lpMsgBuf,0,NULL); 
    1313      if (dwRet == 0) { 
     
    1717      wsprintf(szBuf, _T("%d: %s"), dwError, lpMsgBuf);  
    1818      std::wstring str = szBuf; 
     19      delete [] szBuf; 
    1920      LocalFree(lpMsgBuf); 
    2021      return str; 
     
    2223    static std::wstring from_module(std::wstring module, unsigned long dwError) { 
    2324      LPVOID lpMsgBuf; 
    24       unsigned long dwRet = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS,GetModuleHandle(module.c_str()),dwError,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPTSTR)&lpMsgBuf,0,NULL); 
     25      unsigned long dwRet = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS, 
     26        GetModuleHandle(module.c_str()),dwError,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPTSTR)&lpMsgBuf,0,NULL); 
    2527      if (dwRet == 0) { 
    2628        return _T("failed to lookup error code: ") + strEx::itos(dwError) + _T("( reson: ") + strEx::itos(GetLastError()) + _T(")"); 
     
    2931      wsprintf(szBuf, _T("%d: %s"), dwError, lpMsgBuf);  
    3032      std::wstring str = szBuf; 
     33      delete [] szBuf; 
    3134      LocalFree(lpMsgBuf); 
    3235      return str; 
     
    4750      wsprintf(szBuf, _T("%d: %s"), dwError, lpMsgBuf);  
    4851      std::wstring str = szBuf; 
     52      delete [] szBuf; 
    4953      LocalFree(lpMsgBuf); 
    5054      FreeLibrary(hevt); 
     
    5357    class message { 
    5458    public: 
     59      static std::wstring from_module(std::wstring module, unsigned long dwError) { 
     60        HMODULE hDLL = LoadLibraryEx(module.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES); 
     61        if (hDLL == NULL) { 
     62          return _T("failed to load: ") + module + _T("( reson: ") + strEx::itos(GetLastError()) + _T(")"); 
     63        } 
     64        LPVOID lpMsgBuf; 
     65        unsigned long dwRet = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS,hDLL, 
     66          dwError,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPTSTR)&lpMsgBuf,0,NULL); 
     67        if (dwRet == 0) { 
     68          FreeLibrary(hDLL); 
     69          DWORD err = GetLastError(); 
     70          if (err == 317) { 
     71            return _T(""); 
     72          } 
     73          return _T("failed to lookup error code: ") + strEx::itos(dwError) + _T(" from DLL: ") + module + _T("( reson: ") + strEx::itos(err) + _T(")"); 
     74        } 
     75        std::wstring str = reinterpret_cast<TCHAR*>(lpMsgBuf); 
     76        LocalFree(lpMsgBuf); 
     77        FreeLibrary(hDLL); 
     78        return str; 
     79      } 
    5580      static std::wstring from_module(std::wstring module, unsigned long dwError, DWORD *arguments) { 
    5681        HMODULE hDLL = LoadLibraryEx(module.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES); 
  • include/execute_process.hpp

    r5b9d247 r739db5a  
    9191    delete [] cmd; 
    9292    if (processOK) { 
     93      DWORD dwAvail = 0; 
    9394      std::string str; 
    9495      HANDLE handles[2]; 
     
    9798      char *buffer = createBuffer(); 
    9899      for (unsigned int i=0;i<timeout;i++) { 
    99         DWORD dwAvail = 0; 
    100100        if (!::PeekNamedPipe(hChildOutR, NULL, 0, NULL, &dwAvail, NULL)) 
    101101          break; 
     
    110110      CloseHandle(hChildOutW); 
    111111 
    112       str += readFromFile(buffer, hChildOutR); 
     112      dwAvail = 0; 
     113      if (!::PeekNamedPipe(hChildOutR, NULL, 0, NULL, &dwAvail, NULL)) 
     114        NSC_LOG_ERROR_STD(_T("Failed to peek buffer: ") + error::lookup::last_error()); 
     115      if (dwAvail > 0) 
     116        str += readFromFile(buffer, hChildOutR); 
    113117      msg = strEx::string_to_wstring(str); 
    114118      destroyBuffer(buffer); 
     
    144148      CloseHandle(hChildOutR); 
    145149    } else { 
    146       msg = _T("NRPE_NT failed to create process (") + command + _T("): ") + error::lookup::last_error(); 
     150      DWORD error = GetLastError(); 
     151      if (error == ERROR_BAD_EXE_FORMAT) { 
     152        NSC_LOG_ERROR_STD(command + _T(" is not an .exe file or a valid image (if you run a script you usually need to prefix the command with the interpreter like so: \"command=c:\\perl.exe <script>\"")); 
     153        msg = _T("ExternalCommands: failed to create process (") + command + _T("): it is not an exe file (check NSC.log for more info) - ") + error::lookup::last_error(error); 
     154      } else { 
     155        msg = _T("ExternalCommands: failed to create process (") + command + _T("): ") + error::lookup::last_error(error); 
     156      } 
    147157      result = NSCAPI::returnUNKNOWN; 
    148158      CloseHandle(hChildInR); 
  • include/filter_framework.hpp

    r367bf20 r739db5a  
    266266        throw parse_exception(_T("Regular expression support not enabled!") + value); 
    267267#endif 
     268      } else if (t.first.length() > 1 && t.first[0] == L'=') { 
     269        exact = t.first.substr(1); 
    268270      } else { 
    269271        exact = t.first; 
  • include/nrpe/nrpepacket.hpp

    r5b9d247 r739db5a  
    117117      throw NRPEPacketException(_T("No buffer.")); 
    118118    if (length != getBufferLength()) 
    119       throw NRPEPacketException(_T("Invalid length.")); 
     119      throw NRPEPacketException(_T("Invalid length: ") + strEx::itos(length) + _T(" != ") + strEx::itos(getBufferLength())); 
    120120    const packet *p = reinterpret_cast<const packet*>(buffer); 
    121121    type_ = ntohs(p->packet_type); 
  • include/strEx.h

    r367bf20 r739db5a  
    3535 
    3636namespace strEx { 
     37  class string_exception : public std::exception { 
     38    std::wstring _what; 
     39  public: 
     40    string_exception(std::wstring what) : _what(what) {} 
     41    std::wstring what() { 
     42      return _what; 
     43    } 
     44  }; 
    3745  namespace s { 
    3846    inline std::string itos(float i) { 
     
    6068 
    6169  inline std::string wstring_to_string( const wchar_t* pStr, int len) { 
    62     //ASSERT_PTR( pStr ) ;  
    63     //ASSERT( len >= 0 || len == -1 , _T("Invalid string length: ") << len ) ;  
     70    if (pStr == NULL) 
     71      throw string_exception(_T("Invalid pointer in wstring_to_string")); 
     72    if (len < 0 && len != -1)  
     73      throw string_exception(_T("Invalid string length in wstring_to_string")); 
    6474 
    6575    // figure out how many narrow characters we are going to get  
     
    8494 
    8595  inline std::wstring string_to_wstring( const char* pStr , int len ) { 
    86     //ASSERT_PTR( pStr ) ;  
    87     //ASSERT( len >= 0 || len == -1 , _T("Invalid string length: ") << len ) ;  
     96    if (pStr == NULL) 
     97      throw string_exception(_T("Invalid pointer in wstring_to_string")); 
     98    if (len < 0 && len != -1)  
     99      throw string_exception(_T("Invalid string length in wstring_to_string")); 
    88100 
    89101    // figure out how many wide characters we are going to get  
     
    201213    } 
    202214  } 
     215  inline std::wstring ctos(TCHAR c) { 
     216    return std::wstring(1, c); 
     217  } 
     218  inline TCHAR stoc(std::wstring str) { 
     219    if (str.length() == 0) 
     220      return L' '; 
     221    return str[0]; 
     222  } 
    203223  inline std::wstring itos(unsigned int i) { 
    204224    std::wstringstream ss; 
     
    230250    ss << i; 
    231251    return ss.str(); 
     252  } 
     253  inline std::wstring itos_non_sci(double i) { 
     254    std::wstringstream ss; 
     255    if (i < 10) 
     256      ss.precision(20); 
     257    ss << std::noshowpoint << std::fixed << i; 
     258    std::wstring s = ss.str(); 
     259    std::wstring::size_type pos = s.find_last_not_of('0'); 
     260    if (pos == std::wstring::npos) 
     261      return s; 
     262    if (s[pos] != '.') 
     263      pos++; 
     264    return s.substr(0, pos); 
    232265  } 
    233266  inline std::wstring itos(float i) { 
  • include/sysinfo.h

    r7e33d82 r739db5a  
    5858    return ((osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)&&(osVersion.dwMajorVersion>4)); 
    5959  } 
     60  inline bool isAboveXP(const OSVERSIONINFO &osVersion) { 
     61    if ((osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osVersion.dwMajorVersion==5)&&(osVersion.dwMinorVersion>=1)) 
     62      return true; 
     63    if ((osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osVersion.dwMajorVersion>5)) 
     64      return true; 
     65    return false; 
     66  } 
     67  inline bool isBelowXP(const OSVERSIONINFO &osVersion) { 
     68    if ((osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osVersion.dwMajorVersion<4)) 
     69      return true; 
     70    if ((osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osVersion.dwMajorVersion==4)&&(osVersion.dwMinorVersion<1)) 
     71      return true; 
     72    return false; 
     73  } 
    6074 
    6175} 
Note: See TracChangeset for help on using the changeset viewer.