Changeset 6817602 in nscp


Ignore:
Timestamp:
02/22/06 21:47:57 (7 years ago)
Author:
Michael Medin <michael@…>
Branches:
master, 0.4.0, 0.4.1, 0.4.2, stable
Children:
1b7ae3d
Parents:
89f1a84
Message:

Lots of update (I really should checkin more often :)

Files:
38 edited

Legend:

Unmodified
Added
Removed
  • NSC.dist

    r89f1a84 r6817602  
    1616;CheckEventLog.dll 
    1717;CheckHelpers.dll 
     18; 
     19; CheckWMI IS AN EXTREM EARLY IDEA SO DONT USE FOR PRODUCTION ENVIROMNEMTS! 
     20;CheckWMI.dll 
    1821 
    1922[Settings] 
  • NSCPlugin.cpp

    r75d5e70 r6817602  
    2020  ,fGetConfigurationMeta(NULL) 
    2121  ,fGetVersion(NULL) 
     22  ,fCommandLineExec(NULL) 
    2223  ,bLoaded_(false) 
    2324{ 
     
    3536  ,fGetConfigurationMeta(NULL) 
    3637  ,fGetVersion(NULL) 
     38  ,fCommandLineExec(NULL) 
    3739  ,bLoaded_(false) 
    3840{ 
     
    256258 
    257259  fGetConfigurationMeta = (lpGetConfigurationMeta)GetProcAddress(hModule_, "NSGetConfigurationMeta"); 
     260  fCommandLineExec = (lpCommandLineExec)GetProcAddress(hModule_, "NSCommandLineExec"); 
    258261} 
    259262 
     
    274277  return fGetConfigurationMeta(buflen, buf)?true:false; 
    275278} 
     279 
     280int NSCPlugin::commandLineExec(const char* command, const unsigned int argLen, char **arguments) { 
     281  if (fCommandLineExec== NULL) 
     282    throw NSPluginException(file_, "Module does not support CommandLineExec"); 
     283  return fCommandLineExec(command, argLen, arguments); 
     284} 
  • NSCPlugin.h

    re26cfe0 r6817602  
    9797  typedef INT (*lpHasMessageHandler)(); 
    9898  typedef NSCAPI::nagiosReturn (*lpHandleCommand)(const char*,const unsigned int, char**,char*,unsigned int,char *,unsigned int); 
     99  typedef INT (*lpCommandLineExec)(const char*,const unsigned int,char**); 
    99100  typedef INT (*lpHandleMessage)(int,const char*,const int,const char*); 
    100101  typedef INT (*lpUnLoadModule)(); 
     
    113114  lpUnLoadModule fUnLoadModule; 
    114115  lpGetConfigurationMeta fGetConfigurationMeta; 
     116  lpCommandLineExec fCommandLineExec; 
    115117 
    116118public: 
     
    130132  void unload(void); 
    131133  std::string getCongifurationMeta(); 
     134  int commandLineExec(const char* command, const unsigned int argLen, char **arguments); 
    132135 
    133136private: 
  • NSClient++.cpp

    r75d5e70 r6817602  
    2121#include <b64/b64.h> 
    2222#include <PDHCounter.h> 
     23#include <PDHCollectors.h> 
     24 
    2325 
    2426NSClient mainClient;  // Global core instance. 
     
    4446      try { 
    4547        serviceControll::Install(SZSERVICENAME, SZSERVICEDISPLAYNAME, SZDEPENDENCIES); 
    46         serviceControll::SetDescription(SZSERVICENAME, SZSERVICEDESCRIPTION); 
    4748      } catch (const serviceControll::SCException& e) { 
    4849        LOG_MESSAGE_STD("Service installation failed: " + e.error_); 
    4950        return -1; 
     51      } 
     52      try { 
     53        serviceControll::SetDescription(SZSERVICENAME, SZSERVICEDESCRIPTION); 
     54      } catch (const serviceControll::SCException& e) { 
     55        LOG_MESSAGE_STD("Couldn't set service description: " + e.error_); 
    5056      } 
    5157      LOG_MESSAGE("Service installed!"); 
     
    100106        } 
    101107      } 
     108    } else if ( _stricmp( "debugpdh", argv[1]+1 ) == 0 ) { 
     109      PDH::Enumerations::Objects lst = PDH::Enumerations::EnumObjects(); 
     110      for (PDH::Enumerations::Objects::iterator it = lst.begin();it!=lst.end();++it) { 
     111        if ((*it).instances.size() > 0) { 
     112          for (PDH::Enumerations::Instances::const_iterator it2 = (*it).instances.begin();it2!=(*it).instances.end();++it2) { 
     113            for (PDH::Enumerations::Counters::const_iterator it3 = (*it).counters.begin();it3!=(*it).counters.end();++it3) { 
     114              std::string counter = "\\" + (*it).name + "(" + (*it2).name + ")\\" + (*it3).name; 
     115              std::cout << "testing: " << counter << ": "; 
     116              std::string error; 
     117              if (PDH::Enumerations::validate(counter, error)) { 
     118                std::cout << " found "; 
     119              } else { 
     120                std::cout << " *NOT* found (" << error << ") " << std::endl; 
     121                break; 
     122              } 
     123              bool bOpend = false; 
     124              try { 
     125                PDH::PDHQuery pdh; 
     126                PDHCollectors::StaticPDHCounterListener<double, PDH_FMT_DOUBLE> cDouble; 
     127                pdh.addCounter(counter, &cDouble); 
     128                pdh.open(); 
     129                pdh.gatherData(); 
     130                pdh.close(); 
     131                bOpend = true; 
     132              } catch (const PDH::PDHException e) { 
     133                std::cout << " could *not* be open (" << e.getError() << ") " << std::endl; 
     134                break; 
     135              } 
     136              std::cout << " open "; 
     137              std::cout << std::endl; 
     138            } 
     139          } 
     140        } else { 
     141          for (PDH::Enumerations::Counters::const_iterator it2 = (*it).counters.begin();it2!=(*it).counters.end();++it2) { 
     142            std::string counter = "\\" + (*it).name + "\\" + (*it2).name; 
     143            std::cout << "testing: " << counter << ": "; 
     144            std::string error; 
     145            if (PDH::Enumerations::validate(counter, error)) { 
     146              std::cout << " found "; 
     147            } else { 
     148              std::cout << " *NOT* found (" << error << ") " << std::endl; 
     149              break; 
     150            } 
     151            bool bOpend = false; 
     152            try { 
     153              PDH::PDHQuery pdh; 
     154              PDHCollectors::StaticPDHCounterListener<double, PDH_FMT_DOUBLE> cDouble; 
     155              pdh.addCounter(counter, &cDouble); 
     156              pdh.open(); 
     157              pdh.gatherData(); 
     158              pdh.close(); 
     159              bOpend = true; 
     160            } catch (const PDH::PDHException e) { 
     161              std::cout << " could *not* be open (" << e.getError() << ") " << std::endl; 
     162              break; 
     163            } 
     164            std::cout << " open "; 
     165            std::cout << std::endl;; 
     166          } 
     167        } 
     168      } 
    102169    } else if ( _stricmp( "test", argv[1]+1 ) == 0 ) { 
    103170#ifdef _DEBUG 
     
    135202      return 0; 
    136203    } else { 
    137       LOG_MESSAGE("Usage: -version, -about, -install, -uninstall, -start, -stop"); 
    138     } 
     204      LOG_MESSAGE("Usage: -version, -about, -install, -uninstall, -start, -stop, -encrypt"); 
     205      LOG_MESSAGE("Usage: <ModuleName> <commnd> [arguments]"); 
     206    } 
     207    return nRetCode; 
     208  } else if (argc > 2) { 
     209    g_bConsoleLog = true; 
     210    mainClient.InitiateService(); 
     211    if (argc>=3) 
     212      mainClient.commandLineExec(argv[1], argv[2], argc-3, &argv[3]); 
     213    else 
     214      mainClient.commandLineExec(argv[1], argv[2], 0, NULL); 
     215    mainClient.TerminateService(); 
    139216    return nRetCode; 
    140217  } 
     
    206283// Member functions 
    207284 
     285int NSClientT::commandLineExec(const char* module, const char* command, const unsigned int argLen, char** args) { 
     286  std::string sModule = module; 
     287  ReadLock readLock(&m_mutexRW, true, 10000); 
     288  if (!readLock.IsLocked()) { 
     289    LOG_ERROR("FATAL ERROR: Could not get read-mutex."); 
     290    return -1; 
     291  } 
     292  for (pluginList::size_type i=0;i<plugins_.size();++i) { 
     293    NSCPlugin *p = plugins_[i]; 
     294    if (p->getName() == sModule) { 
     295      LOG_DEBUG_STD("Found module: " + p->getName() + "..."); 
     296      try { 
     297        return p->commandLineExec(command, argLen, args); 
     298      } catch (NSPluginException e) { 
     299        LOG_ERROR_STD("Could not execute command: " + e.error_ + " in " + e.file_); 
     300      } 
     301    } 
     302  } 
     303  LOG_ERROR("Module not found."); 
     304  return 0; 
     305} 
    208306 
    209307/** 
  • NSClient++.h

    re26cfe0 r6817602  
    6565  std::string execute(std::string password, std::string cmd, std::list<std::string> args); 
    6666  void reportMessage(int msgType, const char* file, const int line, std::string message); 
     67  int commandLineExec(const char* module, const char* command, const unsigned int argLen, char** args); 
    6768 
    6869  void addPlugins(const std::list<std::string> plugins); 
  • NSClient++.sln

    re26cfe0 r6817602  
    4343EndProject 
    4444Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ConfWiz", "ConfWiz\ConfWiz.vcproj", "{BD93F0C3-E342-4D68-9717-FCAC2E7189AA}" 
     45  ProjectSection(ProjectDependencies) = postProject 
     46  EndProjectSection 
     47EndProject 
     48Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CheckWMI", "modules\CheckWMI\CheckWMI.vcproj", "{E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}" 
    4549  ProjectSection(ProjectDependencies) = postProject 
    4650  EndProjectSection 
     
    116120    {BD93F0C3-E342-4D68-9717-FCAC2E7189AA}.Release.ActiveCfg = Release|Win32 
    117121    {BD93F0C3-E342-4D68-9717-FCAC2E7189AA}.Release.Build.0 = Release|Win32 
     122    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.ActiveCfg = Debug|Win32 
     123    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Debug.Build.0 = Debug|Win32 
     124    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Distribution.ActiveCfg = Distribution|Win32 
     125    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Distribution.Build.0 = Distribution|Win32 
     126    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.ActiveCfg = Release|Win32 
     127    {E6E588AB-EFEF-481C-9AF7-DCDCB95CFF45}.Release.Build.0 = Release|Win32 
    118128  EndGlobalSection 
    119129  GlobalSection(ExtensibilityGlobals) = postSolution 
  • changelog

    r75d5e70 r6817602  
     1TODO:  
     2 * Process times and similar ? 
     3 * Add bind_to_address in the socket 
     4 * Fix configuration GUI (low priority) 
     5 * Fix installer (low priority) 
     6 * Service check to use Auto (filter by started setting etc.) 
     7 * Add module for relaying events 
     8 * Check multitasking problems on the sockets. 
     9 
     102006-02-12 MickeM 
     11 + Added new Interface for MOdules (NSCommandLineExec that allows modules to execute things give from command line. 
     12   Syntax is NSClient++ <module name> <command> [arguments] and if a mpodule doesn't support this it is simply ignored. 
     13 + Added new install/uninstall command to SystemTray module: 
     14   NSClient++.exe SystemTray install  
     15   NSClient++.exe SystemTray uninstall  
     16   That will install/uninstall the system tray module this sets the "Allow Service to Interact with Desktop" flag for the service. 
     17 * Removed the "Allow Service to Interact with Desktop" flag from the /install option so that it no longer defaults to on (see commands to set this above). 
     18 * Fixed so checkProcess isn't case sensetive. 
     19 
     202006-02-12 MickeM 
     21 + Added support for host name resolve to allowed_hosts 
     22 
     232006-02-08 MickeM 
     24 ! Fixed filter-eventID in EventLog module (now works for all IDs regardless of severity state) 
     25 + Added new filters to EventLog (filter-severity that can filter based on event severity success, error, warning, informational) 
     26 
     272006-02-07 MickeM 
     28 + Added new filter option to eventlog filter-eventID 
     29 + Added new operator to all numeric filters in:number,number,... etc. (for instance filter-eventID=in:123,456,789 to check for lists. 
     30 
     312006-02-05 MickeM 
     32 + Added CheckFile check command 
     33   This new command (in development) will allow various file checks such as age, size, date, etc on single or multiple files. 
     34 + Added FILEAGE support to NSClient 
     35 + Started to convert the webpage to WIKI 
     36  
     372006-01-21 MickeM 
     38 + Added WMI Check module (early alpha) 
     39   This is an extremely early alpha more to see if there is an interest and how to progress with it. 
     40   To use the WMI module enable the WMICheck.dll (nsc.ini) and then run the following check: 
     41   CheckWMI MaxWarn=10 MaxCrit=15 "Query:load=Select LoadPercentage from win32_Processor" 
     42   The Max* are as every other check and sets limits.  
     43   The Query works similarly to other check commands ie. Query:<name>=<WMI query> 
     44   So any other WMI query should work (notice this is experimental and not stable and has virtually  
     45   no error handling so it is likely to crash nsclient if you ask anything "non working".) 
     46   I would *really* *really* like to get feedback on how to expand this concept to work better so feel free to come with feedback. 
     47  * Fixed NT4 /install (should work now!) 
     48 
     492006-01-02 MickeM 
     50 * Fixed ChangeServiceConfig2 on NT4 
     51 + Added support for more then 4GB memory (8GB?) 
     52   Since I don't have this much memory this needs to be verified... 
     53 * Fixed syntax of performance data 
     54 
     552005-09-24 MickeM 
     56 * Fixed memory size bug (free and used were swapped) 
     57 
     582005-09-20 MickeM 
     59 + Added option to debug all PDH counters /debugpdh 
     60 
     612005-09-17 MickeM 
     62 + Added support for checking service by display name 
     63 
     642005-09-03 MickeM 
     65 * First off, sorry for lack of updates, but was on vacation :) 
     66 + Added ShowAll=long to CPULoad 
     67 + Added several new types to checkMem (type=paged, type=physical, type=page, type=virtual) 
     68 
    1692005-07-31 MickeM 
    2  + /install now sets the serive to autostart 
    3  * Did some cleanup of minor code sctions 
    4  * (done before but not repported i think) /listpdh option added to list all pdh counters (nsclient++ /listpdh) 
     70 + /install now sets the service to autostart 
     71 * Did some cleanup of minor code sections 
     72 * (done before but not reported i think) /listpdh option added to list all PDH counters (nsclient++ /listpdh) 
    573 + Added service description 
    6  * Eventlog reworked (again) this time I hope it is better (and even usefull, but syntax has changed) 
     74 * Event log reworked (again) this time I hope it is better (and even useful, but syntax has changed) 
    775 
    8762005-07-26 MickeM 
    9  + Added support for ShowAll=long (to show long and short info, only applies to some areas, but avalible everywhere) 
     77 + Added support for ShowAll=long (to show long and short info, only applies to some areas, but available everywhere) 
    1078 + Extended Drive and memory check syntax to facilitate both Free and Used space checks: MaxWarnFree / MaxWarnUsed etc) 
    1179 
     
    1583 
    16842005-07-16 MickeM 
    17  * Fixed drivechecks from NSClient 
     85 * Fixed drive checks from NSClient 
    1886 
    19872005-07-11 MickeM 
    20  * *ALOT* of bugfixes and enhancements all checking code has been centralzed and rewritten also my nternal check scripts  
    21    have been extenden to check alot more things. 
     88 * *ALOT* of bug fixes and enhancements all checking code has been centralized and rewritten also my internal check scripts  
     89   have been extended to check a lot more things. 
    2290   *NOTICE* that EventLog has not been upgraded yet neither has the documentation. 
    23  + Added MaxWarnCount / MinWarnCount to checkProcState to checknumber of processes running 
     91 + Added MaxWarnCount / MinWarnCount to checkProcState to check number of processes running 
    2492 
    25932005-06-09 MickeM 
  • docs/CheckDisk/index.html

    r75d5e70 r6817602  
    3535  A request has one or more options described in the table below. The order  
    3636  only matter in that the size has to be specified before the File option  
    37   this becous you can change the size for each drive by specifying multiple  
     37  this becaous you can change the size for each drive by specifying multiple  
    3838  Size options.</p> 
    3939  <table class="MsoNormalTable" border="0" cellspacing="0" cellpadding="0" id="table5"> 
  • docs/CheckEventLog/index.html

    r75d5e70 r6817602  
    8383      error, warning, etc</td> 
    8484      <td valign="top"> 
    85       An eventtype to filter out: error, warning, info, auditSuccess or  
     85      An event type to filter out: error, warning, info, auditSuccess or  
    8686      auditFailure.</td> 
    8787    </tr> 
     
    122122  </table> 
    123123  <p>&nbsp;</p> 
    124   <p>A time expression is a date/time intervall as a number prefixed by a  
     124  <p>A time expression is a date/time interval as a number prefixed by a  
    125125  filter prefix (&lt;, &gt;, =, !=) and followed by a unit postfix (m, s, h, d, w).  
    126126  A few examples of time expression are: filter-generated=&gt;2d means filter  
     
    135135    <ul> 
    136136      <li> 
    137       <p><b>Check the Application and System event log for errors in the  
    138       last 24 hours. Filter out any Cdrom and NSClient errors as well as  
     137      <p><b>Check the Application event log for errors in the  
     138      last 48 hours. Filter out any Cdrom and NSClient errors as well as  
    139139      all warnings. Allow 3 errors before a warning is issued and 7 before  
    140140      a critical state.</b></p> 
  • docs/CheckSystem/index.html

    r75d5e70 r6817602  
    105105      <td valign="top">Option</td> 
    106106      <td valign="top">Values</td> 
    107       <td valign="top">Description</td> 
     107      <td valign="top" width="743">Description</td> 
    108108    </tr> 
    109109    <tr> 
    110110      <td valign="top">warn</td> 
    111111      <td valign="top">load in %</td> 
    112       <td valign="top">Load to go above to generate a warning.</td> 
     112      <td valign="top" width="743">Load to go above to generate a warning.</td> 
    113113    </tr> 
    114114    <tr> 
    115115      <td valign="top">crit</td> 
    116116      <td valign="top">load in %</td> 
    117       <td valign="top">Load to go above to generate a critical state.</td> 
    118     </tr> 
    119     <tr> 
    120       <td valign="top">time</td> 
    121       <td valign="top">time</td> 
    122       <td valign="top">The time to calculate average over.</td> 
     117      <td valign="top" width="743">Load to go above to generate a critical state.</td> 
     118    </tr> 
     119    <tr> 
     120      <td valign="top">Time</td> 
     121      <td valign="top">time with optional prefix</td> 
     122      <td valign="top" width="743">The time to calculate average over.</td> 
    123123    </tr> 
    124124    <tr> 
    125125      <td valign="top">nsclient</td> 
    126126      <td valign="top">&nbsp;</td> 
    127       <td valign="top">Flag to make the plug in run in NSClient compatibility  
     127      <td valign="top" width="743">Flag to make the plug in run in NSClient compatibility  
    128128      mode</td> 
     129    </tr> 
     130    <tr> 
     131      <td valign="top">ShowAll</td> 
     132      <td valign="top">none, long</td> 
     133      <td valign="top" width="743">Add this option to show info even if no  
     134      errors are detected. Set it to long to show detailed information.</td> 
    129135    </tr> 
    130136  </table> 
     
    176182      <td valign="top">Flag to make the plug in run in NSClient compatibility  
    177183      mode</td> 
     184    </tr> 
     185    <tr> 
     186      <td valign="top">ShowAll</td> 
     187      <td valign="top">&nbsp;</td> 
     188      <td valign="top">Add this option to show details even if an error is  
     189      not encountered.</td> 
     190    </tr> 
     191    <tr> 
     192      <td valign="top">Alias</td> 
     193      <td valign="top">string</td> 
     194      <td valign="top">A string to use as alias for the values (default is  
     195      uptime)</td> 
    178196    </tr> 
    179197  </table> 
     
    212230      <td valign="top">service=state</td> 
    213231      <td valign="top">&nbsp;</td> 
    214       <td valign="top">A service name and a state the service should have.  
     232      <td valign="top">A service name or service display name and a state the service should have.  
    215233      The state can be either started or stopped. If no state is given started  
    216234      is assumed.</td> 
     
    311329      (?).</td> 
    312330    </tr> 
     331    <tr> 
     332      <td valign="top">type</td> 
     333      <td valign="top">page, paged, virtual, physical</td> 
     334      <td valign="top">What kind of memory to check (does not yet support  
     335      stacking to check multiple kinds)</td> 
     336    </tr> 
    313337  </table> 
    314338  <h3>Examples</h3> 
     
    319343      <p><code>checkMem MaxWarn=80% MaxCrit=90% ShowAll</code></p> 
    320344      <p><code>OK: page: 758M (795205632B)|page=30% 80%;90%;</code></p> 
     345      </li> 
     346      <li> 
     347      <p>Check that the physical is below 80%:</p> 
     348      <p><code>checkMem type=physical MaxWarn=80% MaxCrit=90% ShowAll</code></p> 
     349      <p><code>OK: physical: 758M (795205632B)|page=30% 80%;90%;</code></p> 
    321350      </li> 
    322351    </ul> 
     
    353382      <td valign="top">MinCrit</td> 
    354383      <td valign="top">Number</td> 
    355       <td valign="top">Minimumallowed number</td> 
     384      <td valign="top">Minimum allowed number</td> 
    356385    </tr> 
    357386    <tr> 
     
    370399      <td valign="top">Add a named performance counter. The &lt;name&gt; will be  
    371400      used as an alias.</td> 
     401    </tr> 
     402    <tr> 
     403      <td valign="top">Averages</td> 
     404      <td valign="top">true, false</td> 
     405      <td valign="top">Set this to false to make performance checking  
     406      faster of counters that doesn't represent average values.</td> 
    372407    </tr> 
    373408  </table> 
  • docs/welcome.html

    r75d5e70 r6817602  
    3333  <table id="table17" border="0" cellspacing="0" cellpadding="0" class="MsoNormalTable"> 
    3434    <tr> 
    35       <td valign="top">2005-07-31</td> 
    36       <td>Mainly fixes some minor issues, also adds support for FreeSpace  
    37       checks (in addition to UsedSpace check) as well as &quot;long description  
    38       support&quot; and a reworked EventLog checker.<br> 
    39       <br> 
    40       No updated documentation yet but hopefully all outstanding issues  
    41       has been fixed.<br> 
    42       <br> 
    43       Extract from change log:<br> 
    44       + /install now sets the serivice to autostart<br> 
    45       + Added service description<br> 
    46       * added /listpdh option added to list all pdh counters<br> 
    47       * Eventlog reworked (again) this time I hope it is better <br> 
    48       + Added support for ShowAll=long (to show more information)<br> 
    49       + Extended Drive and memory check syntax to facilitate both Free and  
    50       Used space checks: MaxWarnFree / MaxWarnUsed etc)<br> 
    51       * Changed thread API to use _creatthreadex as opposed to _creatthread  
    52       (works better now!)<br> 
    53       * Fixed UNKNOWN return code (was 4 should have been 3)<br> 
    54       * Fixed drivechecks from NSClient<br> 
    55 &nbsp;</td> 
    56     </tr> 
    57     <tr> 
    58       <td valign="top">2005-07-12</td> 
    59       <td>Update with a lot bugfixes 
     35      <td valign="top">2006-01-21</td> 
     36      <td><p><b>Added</b> WMI Check module (early alpha)</p> 
     37      This is an extremely early alpha more to see if there is an interest  
     38      and how to progress with it.<br> 
     39      To use the WMI module enable the WMICheck.dll (nsc.ini) and then run  
     40      the following check:<br> 
     41      CheckWMI MaxWarn=10 MaxCrit=15 &quot;Query:load=Select LoadPercentage  
     42      from win32_Processor&quot;<br> 
     43      The Max* are as every other check and sets limits. <br> 
     44      The Query works similarly to other check commands ie. Query:&lt;name&gt;=&lt;WMI  
     45      query&gt;<br> 
     46      So any other WMI query should work (notice this is experimental and  
     47      not stable and has virtually <br> 
     48      no error handling so it is likely to crash nsclient if you ask  
     49      anything &quot;non working&quot;.)<br> 
     50      I would *really* *really* like to get feedback on how to expand this  
     51      concept to work better so feel free to come with feedback.<br> 
     52      <p><b>Fixed</b> NT4 /install (should work now!)</p></td> 
     53    </tr> 
     54    <tr> 
     55      <td valign="top">2006-01-02</td> 
     56      <td><p>Minor fixes (but Im starting to be a tad more active now, or so  
     57      I hope :)</p><p>Changes in this version:</p> 
     58      <p><b>Fixed</b> ChangeServiceConfig2 on NT4<br> 
     59      <b>Added </b>support for more then 4GB memory (8GB?)<br> 
     60      Since I dont have this much memory this needs to be verified...<br> 
     61      <b>Fixed </b>syntax of performance data</td> 
     62    </tr> 
     63    <tr> 
     64      <td valign="top">2005-09-26</td> 
     65      <td><p>Minor additions and a bugfixrequests as well as updates to the documentation</p> 
     66      <p>Changes in this version:</p> 
     67      <p><b>Fixed </b>memory size bug (free and used were swapped)<br> 
     68      <b>Added </b>option to debug all PDH counters /debugpdh<br> 
     69      <b>Added </b>support for checking service by display name<br> 
    6070      </td> 
    6171    </tr> 
     
    6575  <a href="http://nscplus.sf.net" target="_top">http://nscplus.sf.net</a></p> 
    6676  <p>Latest version is 
    67   <a href="http://prdownloads.sourceforge.net/nscplus/NSClient++-0.2.4d.zip?download"> 
    68   NSClient++ 0.2.4.zip</a></p> 
     77  <a href="http://prdownloads.sourceforge.net/nscplus/NSClient++-0.2.5a.zip?download"> 
     78  NSClient++ 0.2.5a.zip</a></p> 
    6979  <h1>Modules</h1> 
    7080  <p>NSClient++ comes with a few modules out of the box that does various checks.  
  • include/EnumNtSrv.cpp

    re26cfe0 r6817602  
    177177} 
    178178 
     179#define SC_BUF_LEN 1024 
    179180TNtServiceInfo TNtServiceInfo::GetService(std::string name) 
    180181{ 
     
    187188  SC_HANDLE sh = ::OpenService(scman,name.c_str(),SERVICE_QUERY_STATUS); 
    188189  if (!sh) { 
    189     throw NTServiceException(name, "Could not open Service", GetLastError()); 
    190     ::CloseServiceHandle(scman); 
     190    DWORD bufLen = SC_BUF_LEN; 
     191    TCHAR *buf = new TCHAR[bufLen]; 
     192    if (!GetServiceKeyName(scman, name.c_str(), buf, &bufLen)) { 
     193      throw NTServiceException(name, "Could not open Service", GetLastError()); 
     194      ::CloseServiceHandle(scman); 
     195    } 
     196    if (bufLen >= SC_BUF_LEN) { 
     197      throw NTServiceException(name, "Could not open Service", GetLastError()); 
     198      ::CloseServiceHandle(scman); 
     199    } 
     200    buf[bufLen] = 0; 
     201    SC_HANDLE sh = ::OpenService(scman,buf,SERVICE_QUERY_STATUS); 
     202    if (!sh) { 
     203      throw NTServiceException(name, "Could not open Service", GetLastError()); 
     204      ::CloseServiceHandle(scman); 
     205    } 
    191206  } 
    192207  SERVICE_STATUS state; 
  • include/NSCHelper.cpp

    re26cfe0 r6817602  
    381381    throw NSCMHExcpetion("NSCore has not been initiated..."); 
    382382  unsigned int len = 0; 
    383   fNSAPIEncrypt(algorithm, str.c_str(), str.size(), NULL, &len); 
     383  // @todo investigate potential problems with static_cast<unsigned int> 
     384  fNSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len); 
    384385  len+=2; 
    385386  char *buf = new char[len+1]; 
    386   NSCAPI::errorReturn ret = fNSAPIEncrypt(algorithm, str.c_str(), str.size(), buf, &len); 
     387  NSCAPI::errorReturn ret = fNSAPIEncrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len); 
    387388  if (ret == NSCAPI::isSuccess) { 
    388389    std::string ret = buf; 
     
    396397    throw NSCMHExcpetion("NSCore has not been initiated..."); 
    397398  unsigned int len = 0; 
    398   fNSAPIDecrypt(algorithm, str.c_str(), str.size(), NULL, &len); 
     399  // @todo investigate potential problems with: static_cast<unsigned int>(str.size()) 
     400  fNSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), NULL, &len); 
    399401  len+=2; 
    400402  char *buf = new char[len+1]; 
    401   NSCAPI::errorReturn ret = fNSAPIDecrypt(algorithm, str.c_str(), str.size(), buf, &len); 
     403  NSCAPI::errorReturn ret = fNSAPIDecrypt(algorithm, str.c_str(), static_cast<unsigned int>(str.size()), buf, &len); 
    402404  if (ret == NSCAPI::isSuccess) { 
    403405    std::string ret = buf; 
  • include/NSCHelper.h

    re26cfe0 r6817602  
    8383  typedef NSCAPI::errorReturn (*lpNSAPIStopServer)(void); 
    8484  typedef NSCAPI::nagiosReturn (*lpNSAPIInject)(const char*, const unsigned int, char **, char *, unsigned int, char *, unsigned int); 
    85   typedef LPVOID (*lpNSAPILoader)(char*); 
     85  typedef void* (*lpNSAPILoader)(char*); 
    8686  typedef NSCAPI::boolReturn (*lpNSAPICheckLogMessages)(int); 
    8787  typedef NSCAPI::errorReturn (*lpNSAPIEncrypt)(unsigned int, const char*, unsigned int, char*, unsigned int *); 
     
    144144  extern int NSGetConfigurationMeta(int IN_retBufLen, char *OUT_retBuf) 
    145145 
     146#define NSC_WRAPPERS_CLI() \ 
     147  extern int NSCommandLineExec(const char*,const unsigned int,char**) 
    146148 
    147149 
     
    224226  } 
    225227 
     228#define NSC_WRAPPERS_CLI_DEF(toObject) \ 
     229  extern int NSCommandLineExec(const char* command,const unsigned int argLen,char** args) { \ 
     230    return toObject.commandLineExec(command, argLen, args); \ 
     231  } \ 
     232 
    226233////////////////////////////////////////////////////////////////////////// 
    227234#define MODULE_SETTINGS_START(class, name, description) \ 
  • include/PDHCounter.h

    r75d5e70 r6817602  
    201201    } 
    202202 
    203     static DWORD lookupCounterByName(std::string count, std::string machine = "") { 
    204     } 
    205  
    206203    PDHCounter* addCounter(std::string name, PDHCounterListener *listener) { 
    207204      PDHCounter *counter = new PDHCounter(name, listener); 
  • include/ServiceCmd.cpp

    r75d5e70 r6817602  
    1616#include "stdafx.h" 
    1717#include "ServiceCmd.h" 
     18#include <strEx.h> 
    1819 
    1920namespace serviceControll { 
     
    3031   * 
    3132   */ 
    32   void Install(LPCTSTR szName, LPCTSTR szDisplayName, LPCTSTR szDependencies) { 
     33  void Install(LPCTSTR szName, LPCTSTR szDisplayName, LPCTSTR szDependencies, DWORD dwServiceType) { 
    3334    SC_HANDLE   schService; 
    3435    SC_HANDLE   schSCManager; 
     
    4647      TEXT(szDisplayName),     // name to display 
    4748      SERVICE_ALL_ACCESS,         // desired access 
    48       SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS ,  // service type 
     49      dwServiceType,        // service type 
    4950      SERVICE_AUTO_START,       // start type 
    5051      SERVICE_ERROR_NORMAL,       // error control type 
     
    5758 
    5859    if (!schService) { 
    59       CloseServiceHandle(schSCManager); 
    60       throw SCException("Unable to install service."); 
    61     } 
    62     CloseServiceHandle(schService); 
    63     CloseServiceHandle(schSCManager); 
     60      DWORD err = GetLastError(); 
     61      CloseServiceHandle(schSCManager); 
     62      if (err==ERROR_SERVICE_EXISTS) { 
     63        throw SCException("Service already installed!"); 
     64      } 
     65      throw SCException("Unable to install service.", err); 
     66    } 
     67    CloseServiceHandle(schService); 
     68    CloseServiceHandle(schSCManager); 
     69  } 
     70 
     71  void ModifyServiceType(LPCTSTR szName, DWORD dwServiceType) { 
     72    SC_HANDLE   schService; 
     73    SC_HANDLE   schSCManager; 
     74    TCHAR szPath[512]; 
     75 
     76    if ( GetModuleFileName( NULL, szPath, 512 ) == 0 ) 
     77      throw SCException("Could not get module"); 
     78 
     79    schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); 
     80    if (!schSCManager) 
     81      throw SCException("OpenSCManager failed."); 
     82    schService = OpenService(schSCManager, TEXT(szName), SERVICE_ALL_ACCESS); 
     83    if (!schService) { 
     84      DWORD err = GetLastError(); 
     85      CloseServiceHandle(schSCManager); 
     86      throw SCException("Unable to open service.", err); 
     87    } 
     88    BOOL result = ChangeServiceConfig(schService, dwServiceType, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE , NULL, NULL, NULL,  
     89      NULL, NULL, NULL, NULL); 
     90    CloseServiceHandle(schService); 
     91    CloseServiceHandle(schSCManager); 
     92    if (result != TRUE) 
     93      throw SCException("Could not query service information"); 
     94  } 
     95 
     96  DWORD GetServiceType(LPCTSTR szName) { 
     97    LPQUERY_SERVICE_CONFIG lpqscBuf = (LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, 4096);  
     98    if (lpqscBuf == NULL) { 
     99      throw SCException("Could not allocate memory"); 
     100    } 
     101    SC_HANDLE schService; 
     102    SC_HANDLE schSCManager; 
     103    TCHAR szPath[512]; 
     104 
     105    if ( GetModuleFileName( NULL, szPath, 512 ) == 0 ) 
     106      throw SCException("Could not get module"); 
     107 
     108    schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); 
     109    if (!schSCManager) 
     110      throw SCException("OpenSCManager failed."); 
     111    schService = OpenService(schSCManager, TEXT(szName), SERVICE_ALL_ACCESS); 
     112    if (!schService) { 
     113      DWORD err = GetLastError(); 
     114      CloseServiceHandle(schSCManager); 
     115      throw SCException("Unable to open service.", err); 
     116    } 
     117 
     118 
     119    DWORD dwBytesNeeded = 0; 
     120    BOOL success = QueryServiceConfig(schService, lpqscBuf,  4096, &dwBytesNeeded); 
     121    CloseServiceHandle(schService); 
     122    CloseServiceHandle(schSCManager); 
     123    if (success != TRUE) 
     124      throw SCException("Could not query service information"); 
     125    DWORD ret = lpqscBuf->dwServiceType; 
     126    LocalFree(lpqscBuf); 
     127    return ret; 
    64128  } 
    65129 
     
    188252  } 
    189253 
     254 
     255  typedef BOOL (WINAPI*PFChangeServiceConfig2)(SC_HANDLE hService,DWORD dwInfoLevel,LPVOID lpInfo); 
     256 
    190257  void SetDescription(std::string name, std::string desc) { 
     258    PFChangeServiceConfig2 FChangeServiceConfig2; 
     259    HMODULE ADVAPI= ::LoadLibrary(_TEXT("Advapi32")); 
     260    if (!ADVAPI) { 
     261      throw SCException("Couldn't set extended service info (ignore this on NT4)."); 
     262    } 
     263#ifdef UNICODE 
     264    FChangeServiceConfig2 = (PFChangeServiceConfig2)::GetProcAddress(ADVAPI, _TEXT("ChangeServiceConfig2W")); 
     265#else 
     266    FChangeServiceConfig2 = (PFChangeServiceConfig2)::GetProcAddress(ADVAPI, _TEXT("ChangeServiceConfig2A")); 
     267#endif 
     268    if (!FChangeServiceConfig2) { 
     269      FreeLibrary(ADVAPI); 
     270      throw SCException("Couldn't set extended service info (ignore this on NT4)."); 
     271    } 
    191272    SERVICE_DESCRIPTION descr; 
    192273    SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); 
     
    195276    SC_HANDLE schService = OpenService(schSCManager, TEXT(name.c_str()), SERVICE_ALL_ACCESS); 
    196277    if (!schService) { 
    197       CloseServiceHandle(schSCManager); 
    198       throw SCException("OpenService failed."); 
    199     } 
    200  
    201     LPSTR d = new char[desc.length()+1]; 
     278      FreeLibrary(ADVAPI); 
     279      CloseServiceHandle(schSCManager); 
     280      throw SCException("OpenService failed."); 
     281    } 
     282 
     283    LPSTR d = new char[desc.length()+2]; 
    202284    strncpy(d, desc.c_str(), desc.length()); 
    203285    descr.lpDescription = d; 
    204     BOOL bResult = ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &descr); 
     286    BOOL bResult = FChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &descr); 
    205287    delete [] d; 
     288    FreeLibrary(ADVAPI); 
    206289    CloseServiceHandle(schService); 
    207290    CloseServiceHandle(schSCManager); 
  • include/ServiceCmd.h

    r75d5e70 r6817602  
    11#pragma once 
     2 
     3#include <sstream> 
    24 
    35namespace serviceControll { 
     
    79    SCException(std::string error) : error_(error) { 
    810    } 
     11    SCException(std::string error, int code) : error_(error) { 
     12      std::stringstream ss; 
     13      ss << ": "; 
     14      ss << code; 
     15      error += ss.str(); 
     16    } 
    917  }; 
    10   void Install(LPCTSTR,LPCTSTR,LPCTSTR); 
     18  void Install(LPCTSTR,LPCTSTR,LPCTSTR,DWORD=SERVICE_WIN32_OWN_PROCESS); 
     19  void ModifyServiceType(LPCTSTR szName, DWORD dwServiceType); 
    1120  void Uninstall(std::string); 
    1221  void Start(std::string); 
    1322  void Stop(std::string); 
    1423  void SetDescription(std::string,std::string); 
     24  DWORD GetServiceType(LPCTSTR szName); 
    1525} 
  • include/Settings.h

    r89f1a84 r6817602  
    22 
    33#include <Singleton.h> 
     4#include <string> 
     5#include <map> 
     6#include <windows.h> 
    47#define BUFF_LEN 4096 
    58 
     
    1013{ 
    1114private: 
     15  typedef std::map<std::string,std::string> saveKeyList; 
     16  typedef std::map<std::string,saveKeyList> saveSectionList; 
    1217  std::string file_; 
     18  saveSectionList data_; 
     19  bool bHasInternalData; 
    1320public: 
    1421  typedef std::list<std::string> sectionList; 
    15  
    16   SettingsT(void) 
     22  SettingsT(void) : bHasInternalData(false) 
    1723  { 
    1824  } 
     
    2935    file_ = file; 
    3036  } 
     37 
     38  sectionList getSections() { 
     39    sectionList ret; 
     40    char* buffer = new char[BUFF_LEN+1]; 
     41    unsigned int count = ::GetPrivateProfileSectionNames(buffer, BUFF_LEN, file_.c_str()); 
     42    if (count == BUFF_LEN-2) 
     43      throw "Fuck..."; 
     44    unsigned int last = 0; 
     45    for (unsigned int i=0;i<count;i++) { 
     46      if (buffer[i] == '\0') { 
     47        std::string s = &buffer[last]; 
     48        ret.push_back(s); 
     49        last = i+1; 
     50      } 
     51    } 
     52    delete [] buffer; 
     53    if (bHasInternalData) { 
     54      for (saveSectionList::const_iterator it = data_.begin(); it != data_.end(); ++it) { 
     55      } 
     56    } 
     57    ret.sort(); 
     58    ret.unique(); 
     59    return ret; 
     60  } 
     61 
    3162  /** 
    3263   * Get all keys from a section as a list<string> 
     
    3465   * @return A list with all keys from the section 
    3566   */ 
    36   std::list<std::string> getSection(std::string section) { 
    37     std::list<std::string> ret; 
     67  sectionList getSection(std::string section) { 
     68    sectionList ret; 
    3869    char* buffer = new char[BUFF_LEN+1]; 
    3970    unsigned int count = GetPrivateProfileSection(section.c_str(), buffer, BUFF_LEN, file_.c_str()); 
     
    4980    } 
    5081    delete [] buffer; 
     82    if (bHasInternalData) { 
     83      saveSectionList::const_iterator it = data_.find(section); 
     84      if (it != data_.end()) { 
     85        for (saveKeyList::const_iterator kit = it->second.begin(); kit != it->second.end(); ++kit) { 
     86          ret.push_back(kit->first); 
     87        } 
     88      } 
     89    } 
     90    ret.sort(); 
     91    ret.unique(); 
    5192    return ret; 
    5293  } 
     
    59100   */ 
    60101  std::string getString(std::string section, std::string key, std::string defaultValue = "") const { 
     102    if (bHasInternalData) { 
     103      saveSectionList::const_iterator it = data_.find(section); 
     104      if (it != data_.end()) { 
     105        saveKeyList::const_iterator kit = it->second.find(key); 
     106        if (kit != it->second.end()) { 
     107          return kit->second; 
     108        } 
     109      } 
     110    } 
    61111    char* buffer = new char[1024]; 
    62112    GetPrivateProfileString(section.c_str(), key.c_str(), defaultValue.c_str(), buffer, 1023, file_.c_str()); 
     
    65115    return ret; 
    66116  } 
     117 
     118  void setString(std::string section, std::string key, std::string value) { 
     119    bHasInternalData = true; 
     120    (data_[section])[key] = value; 
     121  } 
     122 
    67123  /** 
    68124   * Get an integer from the settings file 
  • include/Socket.h

    r1d9338a r6817602  
    100100      unsigned long NoBlock = 1; 
    101101      this->ioctlsocket(FIONBIO, &NoBlock); 
     102    } 
     103    static std::string getHostByName(std::string ip) { 
     104      hostent* remoteHost; 
     105      remoteHost = gethostbyname(ip.c_str()); 
     106      if (remoteHost == NULL) 
     107        throw SocketException("gethostbyname failed for " + ip + ": ", ::WSAGetLastError()); 
     108      // @todo investigate it this is "correct" and dont use before! 
     109      return inet_ntoa(*reinterpret_cast<in_addr*>(remoteHost->h_addr)); 
     110    } 
     111    static std::string getHostByAddr(std::string ip) { 
     112      hostent* remoteHost; 
     113      remoteHost = gethostbyaddr(ip.c_str(), static_cast<int>(ip.length()), AF_INET); 
     114      if (remoteHost == NULL) 
     115        throw SocketException("gethostbyaddr failed for " + ip + ": ", ::WSAGetLastError()); 
     116      return remoteHost->h_name; 
    102117    } 
    103118    virtual void readAll(DataBuffer &buffer, unsigned int tmpBufferLength = 1024); 
     
    397412  return 0; 
    398413} 
     414 
     415 
     416 
     417namespace socketHelpers { 
     418  class allowedHosts { 
     419  public: 
     420    typedef std::list<std::string> host_list;  
     421  private: 
     422    host_list allowedHosts_; 
     423  public: 
     424    void setAllowedHosts(host_list allowedHosts) { 
     425      if ((!allowedHosts.empty()) && (allowedHosts.front() == "") ) 
     426        allowedHosts.pop_front(); 
     427      allowedHosts_ = allowedHosts; 
     428      for (host_list::iterator it = allowedHosts_.begin();it!=allowedHosts_.end();++it) { 
     429        if (((*it).length() > 0) && (std::isalpha((*it)[0]))) { 
     430          std::string s = (*it); 
     431          try { 
     432            *it = simpleSocket::Socket::getHostByName(s); 
     433          } catch (simpleSocket::SocketException e) { 
     434            e; 
     435          } 
     436        } 
     437      } 
     438    } 
     439    bool inAllowedHosts(std::string s) { 
     440      if (allowedHosts_.empty()) 
     441        return true; 
     442      host_list::const_iterator cit; 
     443      for (cit = allowedHosts_.begin();cit!=allowedHosts_.end();++cit) { 
     444        if ( (*cit) == s) 
     445          return true; 
     446      } 
     447      return false; 
     448    } 
     449  }; 
     450} 
  • include/checkHelpers.hpp

    r75d5e70 r6817602  
    44#include <strEx.h> 
    55 
     6#define MAKE_PERFDATA(alias, value, unit, warn, crit) "'" + alias + "'=" + value + unit + ";" + warn + ";" + crit + "; " 
    67 
    78namespace checkHolders { 
     
    133134      return "Free: "; 
    134135    } 
     136    static std::string key_prefix() { 
     137      return ""; 
     138    } 
     139    static std::string key_postfix() { 
     140      return ""; 
     141    } 
     142 
    135143  }; 
    136144 
     
    154162      return strEx::itos(value); 
    155163    } 
     164    static std::string key_prefix() { 
     165      return ""; 
     166    } 
     167    static std::string key_postfix() { 
     168      return ""; 
     169    } 
     170 
    156171  }; 
    157172 
     
    174189      return strEx::itos(value) + "%"; 
    175190    } 
     191    static std::string key_prefix() { 
     192      return ""; 
     193    } 
     194    static std::string key_postfix() { 
     195      return ""; 
     196    } 
    176197  }; 
    177198  class int64_handler { 
     
    209230    static std::string print_percent(double value) { 
    210231      return strEx::itos(value) + "%"; 
     232    } 
     233    static std::string key_prefix() { 
     234      return ""; 
     235    } 
     236    static std::string key_postfix() { 
     237      return ""; 
    211238    } 
    212239  }; 
     
    268295 
    269296    static std::string toStringLong(TType value) { 
    270       return THandler::print(value); 
     297      return THandler::key_prefix() + THandler::print(value) + THandler::key_postfix(); 
    271298    } 
    272299    static std::string toStringShort(TType value) { 
     
    286313    } 
    287314    static std::string gatherPerfData(std::string alias, TType &value, TType warn, TType crit) { 
    288       return alias + ";" 
    289         + THandler::print_unformated(value) + ";" 
    290         + THandler::print_unformated(warn) + ";" 
    291         + THandler::print_unformated(crit) + "; "; 
     315      return MAKE_PERFDATA(alias, THandler::print_unformated(value), "", THandler::print_unformated(warn), THandler::print_unformated(crit)); 
    292316    } 
    293317 
     
    335359      } 
    336360      const InternalValue & operator=(std::string value) { 
    337         std::cout << "Setting value: " << value << std::endl; 
    338361        std::string::size_type p = value.find_first_of('%'); 
    339362        if (p != std::string::npos) { 
     
    372395    checkResultType check(TType value) const { 
    373396      if (type_ == percentage_lower) { 
    374         std::cout << "Checking: percentage_lower " << value.getLowerPercentage() << " < " << value_ << std::endl; 
    375397        if (value.getLowerPercentage() == value_) 
    376398          return same; 
     
    378400          return above; 
    379401      } else if (type_ == percentage_upper) { 
    380         std::cout << "Checking: percentage_upper " << value.getUpperPercentage() << " < " << value_ << std::endl; 
    381402        if (value.getUpperPercentage() == value_) 
    382403          return same; 
     
    384405          return above; 
    385406      } else if (type_ == value_lower) { 
    386         std::cout << "Checking: value_lower " << value.total << " < " << value_ << std::endl; 
    387407        if (value.value == value_) 
    388408          return same; 
     
    390410          return above; 
    391411      } else if (type_ == value_upper) { 
    392         std::cout << "Checking: value_upper " << (value.total-value.value) << " < " << value_ << std::endl; 
    393412        if ((value.total-value.value) == value_) 
    394413          return same; 
     
    421440    std::string gatherPerfData(std::string alias, TType &value, typename TType::TValueType warn, typename TType::TValueType crit) { 
    422441      if (type_ == percentage_upper) { 
    423         return alias + ";" 
    424           + THandler::print_unformated(value.getUpperPercentage()) + "%;" 
    425           + THandler::print_unformated(warn) + ";" 
    426           + THandler::print_unformated(crit) + "; "; 
     442        return  
     443          MAKE_PERFDATA(alias, THandler::print_unformated(value.getUpperPercentage()), "%",  
     444          THandler::print_unformated(warn), THandler::print_unformated(crit)); 
    427445      } else if (type_ == percentage_lower) { 
    428           return alias + ";" 
    429             + THandler::print_unformated(value.getLowerPercentage()) + "%;" 
    430             + THandler::print_unformated(warn) + ";" 
    431             + THandler::print_unformated(crit) + "; "; 
     446          return  
     447            MAKE_PERFDATA(alias, THandler::print_unformated(value.getLowerPercentage()), "%",  
     448            THandler::print_unformated(warn), THandler::print_unformated(crit)); 
    432449      } else { 
    433         return alias + ";" 
    434           + THandler::print_unformated(value.value) + ";" 
    435           + THandler::print_unformated(warn) + ";" 
    436           + THandler::print_unformated(crit) + "; "; 
     450        return  
     451          MAKE_PERFDATA(alias, THandler::print_unformated(value.value), "",  
     452          THandler::print_unformated(warn), THandler::print_unformated(crit)); 
    437453      } 
    438454    } 
    439455  private: 
    440456    void setUpper(std::string s) { 
    441       std::cout << "Setting value:U " << s << std::endl; 
    442457      value_ = THandler::parse(s); 
    443458      type_ = value_upper; 
    444459    } 
    445460    void setLower(std::string s) { 
    446       std::cout << "Setting value:L " << s << std::endl; 
    447461      value_ = THandler::parse(s); 
    448462      type_ = value_lower; 
  • include/config.h

    r75d5e70 r6817602  
    55 
    66// Version 
    7 #define SZVERSION "0.2.0 2005-05-21" 
     7#define SZVERSION "0.2.5f 2006-02-14" 
    88 
    99// internal name of the service 
    10 #define SZSERVICENAME        "NSClient++" 
     10#define SZSERVICENAME        "NSClientpp" 
    1111 
    1212// Description of service 
  • include/filter_framework.hpp

    r89f1a84 r6817602  
    11#pragma once 
     2 
     3#include <strEx.h> 
    24 
    35namespace filters { 
     
    4042    struct numeric_equals_filter { 
    4143      static bool filter(TType filter, TType value) { 
    42         return value = filter; 
     44        return value == filter; 
    4345      } 
    4446    }; 
     
    4749      static bool filter(TType filter, TType value) { 
    4850        return value != filter; 
     51      } 
     52    }; 
     53    template <typename TType> 
     54    struct always_true_filter { 
     55      static bool filter(TType filter, TType value) { 
     56        return true; 
     57      } 
     58    }; 
     59    template <typename TListType, typename TType> 
     60    struct numeric_inlist_filter { 
     61      static bool filter(const TListType &filter, const TType value) { 
     62        for (TListType::const_iterator it = filter.begin(); it != filter.end(); ++it) { 
     63          if ((*it) == value) 
     64            return true; 
     65        } 
     66        return false; 
    4967      } 
    5068    }; 
     
    5775      static std::string parse(std::string str) { 
    5876        return str; 
     77      } 
     78    }; 
     79    template<class TType, class TSubHandler> 
     80    struct numeric_list_handler { 
     81      static std::list<TType> parse(std::string str) { 
     82        std::list<TType> ret; 
     83        std::list<std::string> tmp = strEx::splitEx(str, ","); 
     84        for (std::list<std::string>::const_iterator it = tmp.begin(); it != tmp.end(); ++it) { 
     85          ret.push_back(TSubHandler::parse(*it)); 
     86        } 
     87        return ret; 
    5988      } 
    6089    }; 
     
    6998    }; 
    7099    struct eventtype_handler { 
    71  
    72100      static unsigned int parse(std::string str) { 
    73101        if (str == "error") 
     
    97125      }    
    98126    }; 
    99   } 
     127    struct eventseverity_handler { 
     128      static unsigned int parse(std::string str) { 
     129        if (str == "success") 
     130          return 0; 
     131        if (str == "informational") 
     132          return 1; 
     133        if (str == "warning") 
     134          return 2; 
     135        if (str == "error") 
     136          return 3; 
     137        return strEx::stoi(str); 
     138      } 
     139      static std::string toString(unsigned int dwType) { 
     140        if (dwType == 0) 
     141          return "success"; 
     142        if (dwType == 1) 
     143          return "informational"; 
     144        if (dwType == 2) 
     145          return "warning"; 
     146        if (dwType == 3) 
     147          return "error"; 
     148        return strEx::itos(dwType); 
     149      }    
     150    };  } 
    100151 
    101152  template <typename TFilterType, typename TValueType, class THandler, class TFilter> 
     
    104155    bool hasFilter_; 
    105156    filter_one() : hasFilter_(false) {} 
     157    filter_one(const filter_one &other) : hasFilter_(other.hasFilter_), filter(other.filter) { 
     158    } 
    106159 
    107160    inline bool hasFilter() const { 
    108161      return hasFilter_; 
    109162    } 
    110     bool matchFilter(TValueType str) const { 
    111       return TFilter::filter(filter, str); 
     163    bool matchFilter(const TValueType value) const { 
     164      return TFilter::filter(filter, value); 
    112165    } 
    113166    const filter_one & operator=(std::string value) { 
     
    134187      return sub.hasFilter() || regexp.hasFilter(); 
    135188    } 
    136     bool matchFilter(std::string str) const { 
     189    bool matchFilter(const std::string str) const { 
    137190      if ((regexp.hasFilter())&&(regexp.matchFilter(str))) 
    138191        return true; 
     
    161214    filter_one<TType, TType, THandler, filter::numeric_equals_filter<TType> > eq; 
    162215    filter_one<TType, TType, THandler, filter::numeric_nequals_filter<TType> > neq; 
    163  
     216    filter_one<std::list<TType>, TType, handlers::numeric_list_handler<TType, THandler>, filter::numeric_inlist_filter<std::list<TType>, TType> > inList; 
     217 
     218    filter_all_numeric() {} 
     219    filter_all_numeric(const filter_all_numeric &other) { 
     220      max = other.max; 
     221      min = other.min; 
     222      eq = other.eq; 
     223      neq = other.neq; 
     224      inList = other.inList; 
     225    } 
    164226    inline bool hasFilter() const { 
    165       return max.hasFilter() || min.hasFilter() || eq.hasFilter() || neq.hasFilter(); 
    166     } 
    167     bool matchFilter(TType value) const { 
     227      return max.hasFilter() || min.hasFilter() || eq.hasFilter() || neq.hasFilter() || inList.hasFilter(); 
     228    } 
     229    bool matchFilter(const TType value) const { 
    168230      if ((max.hasFilter())&&(max.matchFilter(value))) 
    169231        return true; 
     
    173235        return true; 
    174236      else if ((neq.hasFilter())&&(neq.matchFilter(value))) 
     237        return true; 
     238      else if ((inList.hasFilter())&&(inList.matchFilter(value))) 
    175239        return true; 
    176240      return false; 
     
    185249      } else if (value.substr(0,2) == "!=") { 
    186250        neq = value.substr(2); 
     251      } else if (value.substr(0,3) == "in:") { 
     252        inList = value.substr(3); 
    187253      } else { 
    188254        throw parse_exception("Unknown filter key: " + value); 
     
    191257    } 
    192258  }; 
    193   typedef filter_all_numeric<unsigned int, checkHolders::time_handler<unsigned int> > filter_all_times; 
     259  typedef filter_all_numeric<unsigned long long, checkHolders::time_handler<unsigned long long> > filter_all_times; 
    194260} 
  • include/strEx.h

    r75d5e70 r6817602  
    66#include <utility> 
    77#include <list> 
     8#include <functional> 
    89#ifdef _DEBUG 
    910#include <iostream> 
     
    260261  typedef std::basic_string<char, blind_traits<char>, std::allocator<char> >  blindstr; 
    261262 
     263  struct case_blind_string_compare : public std::binary_function<std::string, std::string, bool> 
     264  { 
     265    bool operator() (const std::string& x, const std::string& y) const { 
     266      return stricmp( x.c_str(), y.c_str() ) < 0; 
     267    } 
     268  }; 
    262269#ifdef _DEBUG 
    263270  inline void test_getToken(std::string in1, char in2, std::string out1, std::string out2) { 
  • include/utils.h

    r75d5e70 r6817602  
    77unsigned long calculate_crc32(const char *buffer, int buffer_size); 
    88 
    9 namespace socketHelpers { 
    10   class allowedHosts { 
    11   private: 
    12     strEx::splitList allowedHosts_; 
    13   public: 
    14     void setAllowedHosts(strEx::splitList allowedHosts) { 
    15       if ((!allowedHosts.empty()) && (allowedHosts.front() == "") ) 
    16         allowedHosts.pop_front(); 
    17       allowedHosts_ = allowedHosts; 
    18     } 
    19     bool inAllowedHosts(std::string s) { 
    20       if (allowedHosts_.empty()) 
    21         return true; 
    22       strEx::splitList::const_iterator cit; 
    23       for (cit = allowedHosts_.begin();cit!=allowedHosts_.end();++cit) { 
    24         if ( (*cit) == s) 
    25           return true; 
    26       } 
    27       return false; 
    28     } 
    29   }; 
    30 } 
    319 
    3210#define MAP_OPTIONS_BEGIN(args) \ 
     
    5836      else if (p__.first == ("MinCrit" postfix)) { obj.crit.min = p__.second; } 
    5937 
     38#define MAP_OPTIONS_PUSH_WTYPE(type, value, obj, list) \ 
     39      else if (p__.first == value) { type o; o.obj = p__.second; list.push_back(o); } 
    6040#define MAP_OPTIONS_PUSH(value, list) \ 
    6141      else if (p__.first == value) { list.push_back(p__.second); } 
     
    7454#define MAP_OPTIONS_BOOL_VALUE(value, obj, tStr) \ 
    7555      else if ((p__.first == value)&&(p__.second == tStr)) { obj = true; }  
     56#define MAP_OPTIONS_MODE(value, tStr, obj, oVal) \ 
     57      else if ((p__.first == value)&&(p__.second == tStr)) { obj = oVal; }  
    7658#define MAP_OPTIONS_BOOL_EX(value, obj, tStr, fStr) \ 
    7759      else if ((p__.first == value)&&(p__.second == tStr)) { obj = true; } \ 
     
    7961#define MAP_OPTIONS_MISSING(arg, str) \ 
    8062      else { arg = str + p__.first; return NSCAPI::returnUNKNOWN; } 
     63#define MAP_OPTIONS_FALLBACK(obj) \ 
     64      else { obj = p__.first;} 
    8165#define MAP_OPTIONS_FALLBACK_AND(obj, extra) \ 
    8266      else { obj = p__.first; extra;} 
  • modules/CheckDisk/CheckDisk.cpp

    r75d5e70 r6817602  
    66#include <strEx.h> 
    77#include <time.h> 
    8  
    9  
     8#include <filter_framework.hpp> 
    109 
    1110 
     
    3837} 
    3938 
    40 typedef std::unary_function<const WIN32_FIND_DATA&, bool> baseClass; 
    41 struct GetSize : public baseClass 
     39struct file_finder_data { 
     40  file_finder_data(const WIN32_FIND_DATA wfd_, const std::string path_) : wfd(wfd_), path(path_) {} 
     41  const WIN32_FIND_DATA wfd; 
     42  const std::string path; 
     43}; 
     44typedef std::unary_function<const file_finder_data&, bool> baseFinderFunction; 
     45struct get_size : public baseFinderFunction 
    4246{ 
    43   GetSize() : size(0) { } 
    44   result_type operator()(argument_type wfd) { 
    45     if (!(wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) { 
    46       size += (wfd.nFileSizeHigh * ((unsigned long long)MAXDWORD+1)) + (unsigned long long)wfd.nFileSizeLow; 
     47  get_size() : size(0) { } 
     48  result_type operator()(argument_type ffd) { 
     49    if (!(ffd.wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) { 
     50      size += (ffd.wfd.nFileSizeHigh * ((unsigned long long)MAXDWORD+1)) + (unsigned long long)ffd.wfd.nFileSizeLow; 
    4751    } 
    4852    return true; 
     
    5559}; 
    5660 
    57 void RecursiveScanDirectory(std::string dir, GetSize & f) { 
     61 
     62template <class finder_function> 
     63void recursive_scan(std::string dir, finder_function & f) { 
    5864  std::string baseDir; 
    5965  std::string::size_type pos = dir.find_last_of('\\'); 
     
    6672  if (hFind != INVALID_HANDLE_VALUE) { 
    6773    do { 
    68       if (!f(wfd)) 
     74      if (!f(file_finder_data(wfd, baseDir))) 
    6975        break; 
    7076      if ((wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) { 
    7177        if ( (strcmp(wfd.cFileName, ".") != 0) && (strcmp(wfd.cFileName, "..") != 0) ) 
    72           RecursiveScanDirectory(baseDir + "\\" + wfd.cFileName + "\\*.*", f); 
     78          recursive_scan<finder_function>(baseDir + "\\" + wfd.cFileName + "\\*.*", f); 
    7379      } 
    7480    } while (FindNextFile(hFind, &wfd)); 
     
    7682  FindClose(hFind); 
    7783} 
     84 
    7885 
    7986 
     
    220227    std::string tstr; 
    221228    std::string sName = path.getAlias(); 
    222     GetSize sizeFinder; 
    223     RecursiveScanDirectory(path.data, sizeFinder); 
     229    get_size sizeFinder; 
     230    recursive_scan<get_size>(path.data, sizeFinder); 
    224231    path.setDefault(tmpObject); 
    225232 
     
    234241} 
    235242 
     243 
     244struct file_info { 
     245  file_info() {} 
     246  file_info(const BY_HANDLE_FILE_INFORMATION info, std::string filename_) : filename(filename_) { 
     247    ullSize = ((info.nFileSizeHigh * ((unsigned long long)MAXDWORD+1)) + (unsigned long long)info.nFileSizeLow); 
     248    ullCreationTime = ((info.ftCreationTime.dwHighDateTime * ((unsigned long long)MAXDWORD+1)) + (unsigned long long)info.ftCreationTime.dwLowDateTime); 
     249    ullLastAccessTime = ((info.ftLastAccessTime.dwHighDateTime * ((unsigned long long)MAXDWORD+1)) + (unsigned long long)info.ftLastAccessTime.dwLowDateTime); 
     250    ullLastWriteTime = ((info.ftLastWriteTime.dwHighDateTime * ((unsigned long long)MAXDWORD+1)) + (unsigned long long)info.ftLastWriteTime.dwLowDateTime); 
     251  }; 
     252 
     253  unsigned long long ullSize; 
     254  unsigned long long ullCreationTime; 
     255  unsigned long long ullLastAccessTime; 
     256  unsigned long long ullLastWriteTime; 
     257  unsigned long long ullNow; 
     258  std::string filename; 
     259 
     260}; 
     261 
     262struct file_filter { 
     263  filters::filter_all_numeric<unsigned long long, checkHolders::disk_size_handler<checkHolders::disk_size_type> > fileSize; 
     264  filters::filter_all_times fileCreation; 
     265  filters::filter_all_times fileAccessed; 
     266  filters::filter_all_times fileWritten; 
     267 
     268  inline bool hasFilter() { 
     269    return fileSize.hasFilter() || fileCreation.hasFilter() ||  
     270      fileAccessed.hasFilter() || fileWritten.hasFilter(); 
     271  } 
     272  bool matchFilter(const file_info &value) const { 
     273    if ((fileSize.hasFilter())&&(fileSize.matchFilter(value.ullSize))) 
     274      return true; 
     275    else if ((fileCreation.hasFilter())&&(fileCreation.matchFilter(value.ullNow-value.ullCreationTime))) 
     276      return true; 
     277    else if ((fileAccessed.hasFilter())&&(fileAccessed.matchFilter(value.ullNow-value.ullLastAccessTime))) 
     278      return true; 
     279    else if ((fileWritten.hasFilter())&&(fileWritten.matchFilter(value.ullNow-value.ullLastWriteTime))) 
     280      return true; 
     281    return false; 
     282  } 
     283}; 
     284 
     285 
     286struct find_first_file_info : public baseFinderFunction 
     287{ 
     288 
     289  file_info info; 
     290  bool bError; 
     291  std::string message; 
     292  find_first_file_info() : bError(false) {} 
     293  result_type operator()(argument_type ffd) { 
     294    if ((ffd.wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) 
     295      return true; 
     296    BY_HANDLE_FILE_INFORMATION _info; 
     297 
     298    HANDLE hFile = CreateFile((ffd.path + "\\" + ffd.wfd.cFileName).c_str(), GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, 
     299      0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); 
     300    if (hFile == INVALID_HANDLE_VALUE) { 
     301      message = "Could not open file: " + ffd.path + "\\" + ffd.wfd.cFileName + ": " + strEx::itos(GetLastError()); 
     302      bError = true; 
     303      return false; 
     304    } 
     305    GetFileInformationByHandle(hFile, &_info); 
     306    CloseHandle(hFile); 
     307    info = file_info(_info, ffd.wfd.cFileName); 
     308    return false; 
     309  } 
     310}; 
     311 
     312struct file_filter_function : public baseFinderFunction 
     313{ 
     314  std::list<file_filter> filter_chain; 
     315  bool bFilterAll; 
     316  bool bFilterIn; 
     317  bool bError; 
     318  std::string message; 
     319  unsigned long long now; 
     320  unsigned int hit_count; 
     321 
     322  file_filter_function() : hit_count(0), bError(false), bFilterIn(true), bFilterAll(true) {} 
     323  result_type operator()(argument_type ffd) { 
     324    if ((ffd.wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)) 
     325      return true; 
     326    BY_HANDLE_FILE_INFORMATION _info; 
     327 
     328    HANDLE hFile = CreateFile((ffd.path + "\\" + ffd.wfd.cFileName).c_str(), GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, 
     329      0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); 
     330    if (hFile == INVALID_HANDLE_VALUE) { 
     331      message = "Could not open file: " + ffd.path + "\\" + ffd.wfd.cFileName + ": " + strEx::itos(GetLastError()); 
     332      bError = true; 
     333      return false; 
     334    } 
     335    GetFileInformationByHandle(hFile, &_info); 
     336    CloseHandle(hFile); 
     337    file_info info(_info, ffd.wfd.cFileName); 
     338    info.ullNow = now; 
     339 
     340    for (std::list<file_filter>::const_iterator cit3 = filter_chain.begin(); cit3 != filter_chain.end(); ++cit3 ) { 
     341      bool bMatch = bFilterAll; 
     342      bool bTmpMatched = (*cit3).matchFilter(info); 
     343      if (bFilterAll) { 
     344        if (!bTmpMatched) { 
     345          bMatch = false; 
     346          break; 
     347        } 
     348      } else { 
     349        if (bTmpMatched) { 
     350          bMatch = true; 
     351          break; 
     352        } 
     353      } 
     354      if ((bFilterIn&&bMatch)||(!bFilterIn&&!bMatch)) { 
     355        strEx::append_list(message, info.filename); 
     356        hit_count++; 
     357      } 
     358    } 
     359    return true; 
     360  } 
     361}; 
     362 
     363NSCAPI::nagiosReturn CheckDisk::getFileAge(const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
     364  NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK; 
     365  std::list<std::string> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args); 
     366  typedef checkHolders::CheckConatiner<checkHolders::MaxMinBoundsUInteger> CheckFileConatiner; 
     367  if (stl_args.empty()) { 
     368    message = "Missing argument(s)."; 
     369    return NSCAPI::returnUNKNOWN; 
     370  } 
     371  std::string dstr, path; 
     372  find_first_file_info finder; 
     373  MAP_OPTIONS_BEGIN(stl_args) 
     374    MAP_OPTIONS_STR("path", path) 
     375    MAP_OPTIONS_FALLBACK(dstr) 
     376  MAP_OPTIONS_END() 
     377 
     378  recursive_scan<find_first_file_info>(path, finder); 
     379  if (finder.bError) { 
     380    message = "ERROR: could not find file."; 
     381    return NSCAPI::returnUNKNOWN; 
     382  } 
     383  FILETIME now_; 
     384  GetSystemTimeAsFileTime(&now_); 
     385  unsigned long long now = ((now_.dwHighDateTime * ((unsigned long long)MAXDWORD+1)) + (unsigned long long)now_.dwLowDateTime); 
     386  time_t value = (now-finder.info.ullLastWriteTime)/10000000; 
     387 
     388  char buf[51]; 
     389  int l = strftime(buf, 50, dstr.c_str(), gmtime(&value)); 
     390  if (l <= 0 || l >= 50) { 
     391    message = "ERROR: could format time."; 
     392    return NSCAPI::returnUNKNOWN; 
     393  } 
     394  buf[l] = 0; 
     395  message = strEx::itos(value) + "&" + buf; 
     396  return NSCAPI::returnOK; 
     397} 
     398 
     399 
     400NSCAPI::nagiosReturn CheckDisk::CheckFile(const unsigned int argLen, char **char_args, std::string &message, std::string &perf) { 
     401  NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK; 
     402  std::list<std::string> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args); 
     403  typedef checkHolders::CheckConatiner<checkHolders::MaxMinBoundsUInteger> CheckFileConatiner; 
     404  if (stl_args.empty()) { 
     405    message = "Missing argument(s)."; 
     406    return NSCAPI::returnUNKNOWN; 
     407  } 
     408  file_filter_function finder; 
     409  PathConatiner tmpObject; 
     410  std::list<std::string> paths; 
     411  unsigned int truncate = 0; 
     412  CheckFileConatiner query; 
     413 
     414  try { 
     415    MAP_OPTIONS_BEGIN(stl_args) 
     416      MAP_OPTIONS_NUMERIC_ALL(query, "") 
     417      MAP_OPTIONS_STR2INT("truncate", truncate) 
     418      MAP_OPTIONS_PUSH("path", paths) 
     419      MAP_OPTIONS_PUSH("file", paths) 
     420      MAP_OPTIONS_BOOL_EX("filter", finder.bFilterIn, "in", "out") 
     421      MAP_OPTIONS_BOOL_EX("filter", finder.bFilterAll, "all", "any") 
     422      MAP_OPTIONS_PUSH_WTYPE(file_filter, "filter-size", fileSize, finder.filter_chain) 
     423      MAP_OPTIONS_PUSH_WTYPE(file_filter, "filter-creation", fileCreation, finder.filter_chain) 
     424      MAP_OPTIONS_PUSH_WTYPE(file_filter, "filter-written", fileWritten, finder.filter_chain) 
     425      MAP_OPTIONS_PUSH_WTYPE(file_filter, "filter-accessed", fileAccessed, finder.filter_chain) 
     426      MAP_OPTIONS_MISSING(message, "Unknown argument: ") 
     427    MAP_OPTIONS_END() 
     428  } catch (filters::parse_exception e) { 
     429    message = e.getMessage(); 
     430    return NSCAPI::returnUNKNOWN; 
     431  } catch (filters::filter_exception e) { 
     432    message = e.getMessage(); 
     433    return NSCAPI::returnUNKNOWN; 
     434  } 
     435  FILETIME now; 
     436  GetSystemTimeAsFileTime(&now); 
     437  finder.now = ((now.dwHighDateTime * ((unsigned long long)MAXDWORD+1)) + (unsigned long long)now.dwLowDateTime); 
     438 
     439 
     440  for (std::list<std::string>::const_iterator pit = paths.begin(); pit != paths.end(); ++pit) { 
     441    recursive_scan<file_filter_function>((*pit), finder); 
     442  } 
     443  message = finder.message; 
     444  if (finder.bError) 
     445    return NSCAPI::returnUNKNOWN; 
     446  query.runCheck(finder.hit_count, returnCode, message, perf); 
     447  if ((truncate > 0) && (message.length() > (truncate-4))) 
     448    message = message.substr(0, truncate-4) + "..."; 
     449  if (message.empty()) 
     450    message = "CheckFile is ok"; 
     451  return returnCode; 
     452} 
     453 
     454 
    236455NSCAPI::nagiosReturn CheckDisk::handleCommand(const strEx::blindstr command, const unsigned int argLen, char **char_args, std::string &msg, std::string &perf) { 
    237456  if (command == "CheckFileSize") { 
     
    239458  } else if (command == "CheckDriveSize") { 
    240459    return CheckDriveSize(argLen, char_args, msg, perf); 
     460  } else if (command == "CheckFile") { 
     461    return CheckFile(argLen, char_args, msg, perf); 
     462  } else if (command == "getFileAge") { 
     463    return getFileAge(argLen, char_args, msg, perf); 
    241464  }  
    242465  return NSCAPI::returnIgnored; 
  • modules/CheckDisk/CheckDisk.h

    re26cfe0 r6817602  
    3333  NSCAPI::nagiosReturn CheckFileSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
    3434  NSCAPI::nagiosReturn CheckDriveSize(const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
    35  
     35  NSCAPI::nagiosReturn CheckFile(const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
     36  NSCAPI::nagiosReturn getFileAge(const unsigned int argLen, char **char_args, std::string &message, std::string &perf); 
    3637 
    3738private: 
  • modules/CheckDisk/stdafx.h

    ra1e1922 r6817602  
    1313#include <string> 
    1414#include <functional> 
     15#include <boost/regex.hpp>  
    1516 
    1617#include <NSCAPI.h> 
  • modules/CheckEventLog/CheckEventLog.cpp

    r75d5e70 r6817602  
    4040class EventLogRecord { 
    4141  EVENTLOGRECORD *pevlr_; 
    42   DWORD currentTime_; 
     42  __int64 currentTime_; 
    4343public: 
    44   EventLogRecord(EVENTLOGRECORD *pevlr, DWORD currentTime) : pevlr_(pevlr), currentTime_(currentTime) { 
    45   } 
    46   inline DWORD timeGenerated() const { 
     44  EventLogRecord(EVENTLOGRECORD *pevlr, __int64 currentTime) : pevlr_(pevlr), currentTime_(currentTime) { 
     45  } 
     46  inline __int64 timeGenerated() const { 
    4747    return (currentTime_-pevlr_->TimeGenerated)*1000; 
    4848  } 
    49   inline DWORD timeWritten() const { 
     49  inline __int64 timeWritten() const { 
    5050    return (currentTime_-pevlr_->TimeWritten)*1000; 
    5151  } 
    5252  inline std::string eventSource() const { 
    5353    return reinterpret_cast<LPSTR>(reinterpret_cast<LPBYTE>(pevlr_) + sizeof(EVENTLOGRECORD)); 
     54  } 
     55  inline DWORD eventID() const { 
     56    return (pevlr_->EventID&0xffff); 
     57  } 
     58  inline DWORD severity() const { 
     59    return (pevlr_->EventID>>30); 
    5460  } 
    5561 
     
    119125    return strEx::itos(dwType); 
    120126  } 
    121  
     127  static DWORD translateSeverity(std::string sType) { 
     128    if (sType == "success") 
     129      return 0; 
     130    if (sType == "informational") 
     131      return 1; 
     132    if (sType == "warning") 
     133      return 2; 
     134    if (sType == "error") 
     135      return 3; 
     136    return strEx::stoi(sType); 
     137  } 
     138  static std::string translateSeverity(DWORD dwType) { 
     139    if (dwType == 0) 
     140      return "success"; 
     141    if (dwType == 1) 
     142      return "informational"; 
     143    if (dwType == 2) 
     144      return "warning"; 
     145    if (dwType == 3) 
     146      return "error"; 
     147    return strEx::itos(dwType); 
     148  } 
    122149}; 
    123150 
     
    126153  filters::filter_all_strings eventSource; 
    127154  filters::filter_all_numeric<unsigned int, filters::handlers::eventtype_handler> eventType; 
     155  filters::filter_all_numeric<unsigned int, filters::handlers::eventseverity_handler> eventSeverity; 
    128156  filters::filter_all_strings message; 
    129157  filters::filter_all_times timeWritten; 
    130158  filters::filter_all_times timeGenerated; 
     159  filters::filter_all_numeric<DWORD, filters::handlers::eventtype_handler> eventID; 
    131160 
    132161  inline bool hasFilter() { 
    133     return eventSource.hasFilter() || eventType.hasFilter() || message.hasFilter() ||  
     162    return eventSource.hasFilter() || eventType.hasFilter() || eventID.hasFilter() || eventSeverity.hasFilter() || message.hasFilter() ||  
    134163      timeWritten.hasFilter() || timeGenerated.hasFilter(); 
    135164  } 
     
    138167      return true; 
    139168    else if ((eventType.hasFilter())&&(eventType.matchFilter(value.eventType()))) 
     169      return true; 
     170    else if ((eventSeverity.hasFilter())&&(eventSeverity.matchFilter(value.severity()))) 
     171      return true; 
     172    else if ((eventID.hasFilter())&&(eventID.matchFilter(value.eventID())))  
    140173      return true; 
    141174    else if ((message.hasFilter())&&(message.matchFilter(value.enumStrings()))) 
     
    180213      MAP_OPTIONS_BOOL_EX("filter", bFilterAll, "all", "any") 
    181214      MAP_FILTER("filter-eventType", eventType) 
     215      MAP_FILTER("filter-severity", eventSeverity) 
     216      MAP_FILTER("filter-eventID", eventID) 
    182217      MAP_FILTER("filter-eventSource", eventSource) 
    183218      MAP_FILTER("filter-generated", timeGenerated) 
     
    211246    __time64_t ltime; 
    212247    _time64(&ltime); 
    213     DWORD currentTime = ltime; 
    214248 
    215249    GetOldestEventLogRecord(hLog, &dwThisRecord); 
     
    221255      {  
    222256        bool bMatch = bFilterAll; 
    223         EventLogRecord record(pevlr, currentTime); 
     257        EventLogRecord record(pevlr, ltime); 
    224258 
    225259        for (std::list<eventlog_filter>::const_iterator cit3 = filter_chain.begin(); cit3 != filter_chain.end(); ++cit3 ) { 
     
    241275          strEx::append_list(message, record.eventSource()); 
    242276          if (bShowDescriptions) { 
    243             message += "(" + EventLogRecord::translateType(record.eventType()) + ")"; 
     277            message += "(" + EventLogRecord::translateType(record.eventType()) + ", " + strEx::itos(record.eventID()) + ", " + EventLogRecord::translateSeverity(record.severity()) + ")"; 
    244278            message += "[" + record.enumStrings() + "]"; 
    245279          } 
  • modules/CheckSystem/CheckSystem.cpp

    r75d5e70 r6817602  
    1010#include <sysinfo.h> 
    1111#include <checkHelpers.hpp> 
     12#include <map> 
    1213 
    1314CheckSystem gNSClientCompat; 
     
    137138} 
    138139 
     140 
     141class cpuload_handler { 
     142public: 
     143  static int parse(std::string s) { 
     144    return strEx::stoi(s); 
     145  } 
     146  static int parse_percent(std::string s) { 
     147    return strEx::stoi(s); 
     148  } 
     149  static std::string print(int value) { 
     150    return strEx::itos(value) + "%"; 
     151  } 
     152  static std::string print_unformated(int value) { 
     153    return strEx::itos(value); 
     154  } 
     155  static std::string print_percent(int value) { 
     156    return strEx::itos(value) + "%"; 
     157  } 
     158  static std::string key_prefix() { 
     159    return "average load "; 
     160  } 
     161  static std::string key_postfix() { 
     162    return ""; 
     163  } 
     164}; 
    139165NSCAPI::nagiosReturn CheckSystem::checkCPU(const unsigned int argLen, char **char_args, std::string &msg, std::string &perf)  
    140166{ 
    141   typedef checkHolders::CheckConatiner<checkHolders::MaxMinBoundsInteger> CPULoadConatiner; 
     167  typedef checkHolders::CheckConatiner<checkHolders::MaxMinBounds<checkHolders::NumericBounds<int, cpuload_handler> > > CPULoadConatiner; 
    142168 
    143169  std::list<std::string> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args); 
     
    179205      return NSCAPI::returnUNKNOWN; 
    180206    } 
     207    int value = pObject->getCPUAvrage(load.data + "m"); 
     208    if (value == -1) { 
     209      msg = "ERROR: We don't collect data this far back: " + load.getAlias(); 
     210      return NSCAPI::returnUNKNOWN; 
     211    } 
    181212    if (bNSClient) { 
    182       int value = pObject->getCPUAvrage(load.data + "m"); 
    183       if (value == -1) { 
    184         msg = "ERROR: We don't collect data this far back: " + load.getAlias(); 
    185         return NSCAPI::returnUNKNOWN; 
    186       } 
    187213      if (!msg.empty()) msg += "&"; 
    188214      msg += strEx::itos(value); 
    189215    } else { 
    190       int value = pObject->getCPUAvrage(load.data); 
    191       if (value == -1) { 
    192         msg = "ERROR: We don't collect data this far back: " + load.getAlias(); 
    193         return NSCAPI::returnUNKNOWN; 
    194       } else { 
    195         load.setDefault(tmpObject); 
    196         load.runCheck(value, returnCode, msg, perf); 
    197       } 
     216      load.setDefault(tmpObject); 
     217      load.runCheck(value, returnCode, msg, perf); 
    198218    } 
    199219  } 
     
    380400NSCAPI::nagiosReturn CheckSystem::checkMem(const unsigned int argLen, char **char_args, std::string &msg, std::string &perf) 
    381401{ 
    382   typedef checkHolders::CheckConatiner<checkHolders::MaxMinPercentageBoundsDiskSizei64 > MemoryConatiner; 
     402  typedef checkHolders::CheckConatiner<checkHolders::MaxMinBounds<checkHolders::NumericPercentageBounds<checkHolders::PercentageValueType<unsigned __int64, unsigned __int64>, checkHolders::disk_size_handler<unsigned __int64> > > > MemoryConatiner; 
    383403  std::list<std::string> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args); 
    384404  if (stl_args.empty()) { 
     
    390410  bool bNSClient = false; 
    391411  MemoryConatiner bounds; 
    392  
    393   bounds.data = "page"; 
     412  typedef enum { tPaged, tPage, tVirtual, tPhysical } check_type; 
     413  check_type type = tPaged; 
    394414 
    395415  MAP_OPTIONS_BEGIN(stl_args) 
     
    398418    MAP_OPTIONS_SHOWALL(bounds) 
    399419    MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient) 
     420    MAP_OPTIONS_MODE("type", "paged", type, tPaged) 
     421    MAP_OPTIONS_MODE("type", "page", type, tPage) 
     422    MAP_OPTIONS_MODE("type", "virtual", type, tVirtual) 
     423    MAP_OPTIONS_MODE("type", "physical", type, tPhysical) 
    400424    MAP_OPTIONS_MISSING(msg, "Unknown argument: ") 
    401425  MAP_OPTIONS_END() 
    402426 
    403   PDHCollector *pObject = pdhThread.getThread(); 
    404   if (!pObject) { 
    405     msg = "ERROR: PDH Collection thread not running."; 
    406     return NSCAPI::returnUNKNOWN; 
    407   } 
    408   checkHolders::PercentageValueType<long long, long long> value; 
    409   value.value = pObject->getMemCommit(); 
    410   value.total = pObject->getMemCommitLimit(); 
     427 
     428  checkHolders::PercentageValueType<unsigned long long, unsigned long long> value; 
     429  if (type == tPaged) { 
     430    PDHCollector *pObject = pdhThread.getThread(); 
     431    if (!pObject) { 
     432      msg = "ERROR: PDH Collection thread not running."; 
     433      return NSCAPI::returnUNKNOWN; 
     434    } 
     435    value.value = pObject->getMemCommit(); 
     436    value.total = pObject->getMemCommitLimit(); 
     437    if (bounds.data.empty()) 
     438      bounds.data = "paged bytes"; 
     439  } else { 
     440    CheckMemory::memData data; 
     441    try { 
     442      data = memoryChecker.getMemoryStatus(); 
     443    } catch (CheckMemoryException e) { 
     444      msg = e.getError() + ":" + strEx::itos(e.getErrorCode()); 
     445      return NSCAPI::returnCRIT; 
     446    } 
     447//    MEMORYSTATUS mem; 
     448//    GlobalMemoryStatus(&mem); 
     449    if (type == tPage) { 
     450      value.value = data.pageFile.total-data.pageFile.avail; // mem.dwTotalPageFile-mem.dwAvailPageFile; 
     451      value.total = data.pageFile.total; //mem.dwTotalPageFile; 
     452      if (bounds.data.empty()) 
     453        bounds.data = "page file"; 
     454    } else  if (type == tPhysical) { 
     455      value.value = data.phys.total-data.phys.avail; //mem.dwTotalPhys-mem.dwAvailPhys; 
     456      value.total = data.phys.total; //mem.dwTotalPhys; 
     457      if (bounds.data.empty()) 
     458        bounds.data = "physical memory"; 
     459    } else  if (type == tVirtual) { 
     460      value.value = data.virtualMem.total-data.virtualMem.avail;//mem.dwTotalVirtual-mem.dwAvailVirtual; 
     461      value.total = data.virtualMem.total;//mem.dwTotalVirtual; 
     462      if (bounds.data.empty()) 
     463        bounds.data = "virtual memory"; 
     464    } 
     465  } 
     466 
    411467  if (bNSClient) { 
    412468    msg = strEx::itos(value.total) + "&" + strEx::itos(value.value); 
     
    431487  CEnumProcess::CProcessEntry entry; 
    432488} NSPROCDATA; 
    433 typedef std::hash_map<std::string,NSPROCDATA> NSPROCLST; 
     489typedef std::map<std::string,NSPROCDATA,strEx::case_blind_string_compare> NSPROCLST; 
    434490/** 
    435491* Get a hash_map with all running processes. 
     
    613669      pdh.addCounter(counter.data, &cDouble); 
    614670      pdh.open(); 
    615       pdh.collect(); 
    616       Sleep(1000); 
     671      if (bCheckAverages) { 
     672        pdh.collect(); 
     673        Sleep(1000); 
     674      } 
    617675      pdh.gatherData(); 
    618676      pdh.close(); 
  • modules/CheckSystem/CheckSystem.h

    re26cfe0 r6817602  
    11#pragma once 
    22#include "PDHCollector.h" 
     3#include <CheckMemory.h> 
    34 
    45NSC_WRAPPERS_MAIN(); 
     
    67class CheckSystem { 
    78private: 
     9  CheckMemory memoryChecker; 
    810  int processMethod_; 
    911  PDHCollectorThread pdhThread; 
  • modules/CheckSystem/PDHCollector.cpp

    r75d5e70 r6817602  
    199199* @return Some form of memory check 
    200200*/ 
    201 long long PDHCollector::getMemCommitLimit() { 
     201unsigned long long PDHCollector::getMemCommitLimit() { 
    202202  MutexLock mutex(mutexHandler); 
    203203  if (!mutex.hasMutex()) { 
     
    212212* @return Some form of memory check 
    213213*/ 
    214 long long PDHCollector::getMemCommit() { 
     214unsigned long long PDHCollector::getMemCommit() { 
    215215  MutexLock mutex(mutexHandler); 
    216216  if (!mutex.hasMutex()) { 
  • modules/CheckSystem/PDHCollector.h

    re26cfe0 r6817602  
    3030  int checkIntervall_; 
    3131 
    32   PDHCollectors::StaticPDHCounterListener<__int64, PDHCollectors::format_large> memCmtLim; 
    33   PDHCollectors::StaticPDHCounterListener<__int64, PDHCollectors::format_large> memCmt; 
     32  PDHCollectors::StaticPDHCounterListener<unsigned __int64, PDHCollectors::format_large> memCmtLim; 
     33  PDHCollectors::StaticPDHCounterListener<unsigned __int64, PDHCollectors::format_large> memCmt; 
    3434  PDHCollectors::StaticPDHCounterListener<__int64, PDHCollectors::format_large> upTime; 
    3535  PDHCollectors::RoundINTPDHBufferListener<__int64, PDHCollectors::format_large> cpu; 
     
    4444  int getCPUAvrage(std::string time); 
    4545  long long getUptime(); 
    46   long long getMemCommitLimit(); 
    47   long long getMemCommit(); 
     46  unsigned long long getMemCommitLimit(); 
     47  unsigned long long getMemCommit(); 
    4848 
    4949 
  • modules/FileLogger/FileLogger.cpp

    re26cfe0 r6817602  
    5353  struct tm *today = _localtime64( &ltime ); 
    5454  if (today) { 
    55     int len = strftime(buffer, 63, format_.c_str(), today); 
     55    size_t len = strftime(buffer, 63, format_.c_str(), today); 
    5656    if ((len < 1)||(len > 64)) 
    5757      strncpy(buffer, "???", 63); 
  • modules/NSClientListener/NSClientListener.cpp

    re26cfe0 r6817602  
    1818#define REQ_PROCSTATE   6 // Works fine! 
    1919#define REQ_MEMUSE      7 // Works fine! 
    20 #define REQ_COUNTER     8 // ... in the works ... 
    21 //#define REQ_FILEAGE   9 // ! - not implemented Don't know how to use 
     20#define REQ_COUNTER     8 // Works fine! 
     21#define REQ_FILEAGE     9 // ... in the works ... 
    2222//#define REQ_INSTANCES 10  // ! - not implemented Don't know how to use 
    2323 
     
    152152      cmd.second += "&nsclient"; 
    153153      break; 
     154    case REQ_FILEAGE: 
     155      cmd.first = "getFileAge"; 
     156      cmd.second = "path=" + cmd.second; 
     157      break; 
    154158  } 
    155159 
     
    168172    case REQ_USEDDISKSPACE: 
    169173    case REQ_COUNTER: 
     174    case REQ_FILEAGE: 
    170175      return message; 
    171176 
     
    191196  } 
    192197  simpleSocket::DataBuffer db; 
    193  
    194  
    195198 
    196199  for (int i=0;i<100;i++) { 
  • modules/SysTray/SysTray.cpp

    re26cfe0 r6817602  
    55#include "SysTray.h" 
    66#include "TrayIcon.h" 
     7#include <ServiceCmd.h> 
     8#include <config.h> 
    79 
    810SysTray gSysTray; 
     
    1719SysTray::~SysTray() {} 
    1820bool SysTray::loadModule() { 
     21  std::cout << "Systray: " << serviceControll::GetServiceType(SZSERVICENAME) << std::endl; 
     22  if ((serviceControll::GetServiceType(SZSERVICENAME)&SERVICE_INTERACTIVE_PROCESS)!=SERVICE_INTERACTIVE_PROCESS) { 
     23    NSC_LOG_ERROR("SysTray is not installed (or it cannot interact with the desktop) SysTray wont be loaded. Run " SZAPPNAME " SysTray install ti change this."); 
     24    return true; 
     25  } 
    1926  icon.createThread(); 
    2027  return true; 
     
    2936} 
    3037 
     38int SysTray::commandLineExec(const char* command,const unsigned int argLen,char** args) { 
     39  if (stricmp(command, "install") == 0) { 
     40    try { 
     41      serviceControll::ModifyServiceType(SZSERVICENAME, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS); 
     42      NSC_LOG_MESSAGE(MODULE_NAME " is now able to run as the SERVICE_INTERACTIVE_PROCESS flag has been set."); 
     43    } catch (const serviceControll::SCException& e) { 
     44      NSC_LOG_ERROR("Could not modify service: " + e.error_); 
     45      return -1; 
     46    } 
     47  } else if (stricmp(command, "uninstall") == 0) { 
     48    try { 
     49      serviceControll::ModifyServiceType(SZSERVICENAME, SERVICE_WIN32_OWN_PROCESS); 
     50      NSC_LOG_MESSAGE(MODULE_NAME " is now not able to run as the SERVICE_INTERACTIVE_PROCESS flag has been reset."); 
     51    } catch (const serviceControll::SCException& e) { 
     52      NSC_LOG_ERROR("Could not modify service: " + e.error_); 
     53      return -1; 
     54    } 
     55  } 
     56  return 0; 
     57} 
    3158 
    3259bool SysTray::hasCommandHandler() { 
     
    4067NSC_WRAPPERS_IGNORE_MSG_DEF(); 
    4168NSC_WRAPPERS_IGNORE_CMD_DEF(); 
     69NSC_WRAPPERS_CLI_DEF(gSysTray); 
    4270 
  • modules/SysTray/SysTray.def

    re26cfe0 r6817602  
    1212  NSUnloadModule 
    1313  NSGetModuleDescription 
     14  NSCommandLineExec 
  • modules/SysTray/SysTray.h

    re26cfe0 r6817602  
    44 
    55NSC_WRAPPERS_MAIN(); 
     6NSC_WRAPPERS_CLI(); 
    67 
     8 
     9#define MODULE_NAME "SystemTray" 
    710class SysTray { 
    811private: 
     
    1720 
    1821  std::string getModuleName() { 
    19     return "System Tray icon"; 
     22    return MODULE_NAME; 
    2023  } 
    2124  NSCModuleWrapper::module_version getModuleVersion() { 
     
    3033  bool hasCommandHandler(); 
    3134  bool hasMessageHandler(); 
     35  int commandLineExec(const char* command,const unsigned int argLen,char** args); 
     36 
    3237}; 
  • modules/SysTray/SysTray.vcproj

    rcea178b r6817602  
    170170      <File 
    171171        RelativePath="..\..\include\NSCHelper.cpp"> 
     172      </File> 
     173      <File 
     174        RelativePath="..\..\include\ServiceCmd.cpp"> 
    172175      </File> 
    173176      <File 
     
    216219      </File> 
    217220      <File 
     221        RelativePath="..\..\include\ServiceCmd.h"> 
     222      </File> 
     223      <File 
    218224        RelativePath=".\stdafx.h"> 
    219225      </File> 
Note: See TracChangeset for help on using the changeset viewer.