Changeset 9b9be81 in nscp


Ignore:
Timestamp:
09/27/11 22:25:27 (20 months ago)
Author:
Michael Medin <michael@…>
Branches:
master, 0.4.0, 0.4.1, 0.4.2
Children:
234a037
Parents:
a629015
Message:
  • Fixed many many issues all over the place as I tried to make things working for my pressention at nwc.
Files:
41 edited

Legend:

Unmodified
Added
Removed
  • changelog

    ra629015 r9b9be81  
    66 * Fix RtlStringFromGUID problem on NT4 
    77 
     82011-09-27 MickeM 
     9 * Fixed many many issues all over the place as I tried to make things working for my pressention at nwc. 
     10  
    8112011-09-24 MickeM 
    912 * Started on NSCA unit-tests in python 
  • include/NSCAPI.h

    ra629015 r9b9be81  
    173173    typedef NSCAPI::errorReturn (*lpNSAPIRegisterSubmissionListener)(unsigned int plugin_id, const wchar_t* channel); 
    174174    typedef NSCAPI::errorReturn (*lpNSAPIRegisterRoutingListener)(unsigned int plugin_id, const wchar_t* channel); 
     175    typedef NSCAPI::errorReturn (*lpNSAPIReload)(const wchar_t* module); 
    175176 
    176177  } 
  • include/client/command_line_parser.cpp

    ra629015 r9b9be81  
    250250  modify_header(config, message.mutable_header(), config.data->recipient); 
    251251  std::list<std::string> errors = config.handler->submit(config.data, message.mutable_header(), message.SerializeAsString(), response); 
     252  if (response.empty()) { 
     253    std::wstring msg; 
     254    BOOST_FOREACH(std::string &e, errors) { 
     255      msg += utf8::cvt<std::wstring>(e); 
     256    } 
     257    nscapi::functions::create_simple_submit_response(_T(""), _T(""), errors.empty()?NSCAPI::hasFailed:NSCAPI::isSuccess, msg, response); 
     258  } 
    252259  BOOST_FOREACH(std::string &e, errors) { 
    253260    //config.handler->error(e); 
  • include/nsca/nsca_enrypt.hpp

    ra629015 r9b9be81  
    2020#include <cryptopp/osrng.h> 
    2121#endif 
     22 
     23#include <strEx.h> 
    2224 
    2325#define TRANSMITTED_IV_SIZE     128     /* size of IV to transmit - must be as big as largest IV needed for any crypto algorithm */ 
     
    7072    struct helpers { 
    7173      static int encryption_to_int(std::string encryption) { 
     74        if (encryption.size() > 0 && std::isdigit(encryption[0])) { 
     75          int enc = strEx::stoi(encryption); 
     76          if (enc == ENCRYPT_XOR  
     77#ifdef HAVE_LIBCRYPTOPP 
     78            || enc == ENCRYPT_DES || enc == ENCRYPT_3DES || enc == ENCRYPT_CAST128 || enc == ENCRYPT_XTEA || enc == ENCRYPT_3WAY || enc == ENCRYPT_BLOWFISH || enc == ENCRYPT_TWOFISH || enc == ENCRYPT_RC2 || enc == ENCRYPT_RIJNDAEL128 || enc == ENCRYPT_SERPENT || enc == ENCRYPT_GOST 
     79#endif 
     80            ) 
     81            return enc; 
     82          return ENCRYPT_NONE; 
     83        } 
    7284        if (encryption == "xor") 
    7385          return ENCRYPT_XOR; 
     
    98110        return ENCRYPT_NONE; 
    99111      } 
     112      static std::string encryption_to_string(int encryption) { 
     113        if (encryption == ENCRYPT_XOR) 
     114          return "xor"; 
     115#ifdef HAVE_LIBCRYPTOPP 
     116        if (encryption == ENCRYPT_DES) 
     117          return "des"; 
     118        if (encryption == ENCRYPT_3DES) 
     119          return "3des"; 
     120        if (encryption == ENCRYPT_CAST128) 
     121          return "cast128"; 
     122        if (encryption == ENCRYPT_XTEA) 
     123          return "xtea"; 
     124        if (encryption == ENCRYPT_3WAY) 
     125          return "3way"; 
     126        if (encryption == ENCRYPT_BLOWFISH) 
     127          return "blowfish"; 
     128        if (encryption == ENCRYPT_TWOFISH) 
     129          return "twofish"; 
     130        if (encryption == ENCRYPT_RC2) 
     131          return "rc2"; 
     132        if (encryption == ENCRYPT_RIJNDAEL128) 
     133          return "aes"; 
     134        if (encryption == ENCRYPT_SERPENT) 
     135          return "serpent"; 
     136        if (encryption == ENCRYPT_GOST) 
     137          return "gost"; 
     138#endif 
     139        if (encryption == ENCRYPT_NONE) 
     140          return "none"; 
     141        return "unknown"; 
     142      } 
     143 
    100144 
    101145    }; 
     
    112156    private: 
    113157      typedef CryptoPP::CFB_Mode_ExternalCipher::Encryption TEncryption; 
     158      typedef CryptoPP::CFB_Mode_ExternalCipher::Decryption TDecryption; 
    114159      typedef typename TMethod::Encryption TCipher; 
    115160      TEncryption crypto_; 
     161      TDecryption decrypto_; 
    116162      TCipher cipher_; 
    117163      int keysize_; 
     
    161207          cipher_.SetKey(key, keysize); 
    162208          crypto_.SetCipherWithIV(cipher_, iv, 1); 
     209          decrypto_.SetCipherWithIV(cipher_, iv, 1); 
    163210        } catch (...) { 
    164211          throw encryption_exception("Unknown exception when trying to setup crypto"); 
     
    183230      } 
    184231      void decrypt(unsigned char *buffer, int buffer_size) { 
    185         throw encryption_exception("Decryption not supported"); 
     232        try { 
     233          for(int x=0;x<buffer_size;x++) 
     234            decrypto_.ProcessData(&buffer[x], &buffer[x], 1); 
     235        } catch (...) { 
     236          throw encryption_exception("Unknown exception when trying to setup crypto"); 
     237        } 
    186238      } 
    187239      std::string getName() { 
     
    240292      } 
    241293      void decrypt(std::string &buffer) { 
    242         throw encryption_exception("Decryption not supported"); 
     294        /* rotate over IV we received from the server... */ 
     295        unsigned int buf_len =  buffer.size(); 
     296        unsigned int iv_len = iv_.size(); 
     297        unsigned int pwd_len = password_.size(); 
     298        for (int y=0,x=0,z=0;y<buf_len;y++,x++,z++) { 
     299          /* keep rotating over Password */ 
     300          if (z >= pwd_len) 
     301            z = 0; 
     302          buffer[y] ^= password_[z]; 
     303          /* keep rotating over IV */ 
     304          if (x >= iv_len) 
     305            x = 0; 
     306          buffer[y] ^= iv_[x]; 
     307        } 
    243308      } 
    244309      std::string getName() { 
    245         return "XOR (not safe)"; 
     310        return "XOR"; 
    246311      } 
    247312    }; 
     
    368433      core_->encrypt(buffer); 
    369434    } 
     435    /* encrypt a buffer */ 
     436    void decrypt_buffer(std::string &buffer) { 
     437      if (core_ == NULL) 
     438        throw encryption_exception("No encryption core!"); 
     439      core_->decrypt(buffer); 
     440    } 
    370441    std::string get_rand_buffer(int length) { 
    371442      std::string buffer; buffer.resize(length); 
  • include/nsca/nsca_socket.hpp

    ra629015 r9b9be81  
    5757 
    5858    virtual void send_nsca(const nsca::packet &packet, const boost::posix_time::seconds timeout) { 
    59       NSC_DEBUG_MSG(_T("About to send: ") + utf8::cvt<std::wstring>(packet.to_string())); 
    6059      if (!get_socket().is_open()) { 
    6160        NSC_DEBUG_MSG(_T("is closed...")); 
     
    6564      packet.get_buffer(buffer); 
    6665      crypt_inst.encrypt_buffer(buffer); 
    67       NSC_LOG_ERROR_STD(_T("About to write: ") + strEx::itos(buffer.size())); 
    6866      write_with_timeout(buffer, timeout); 
    6967    } 
    7068    virtual bool recv_iv(std::string password, int encryption_method, boost::posix_time::seconds timeout) { 
    71       NSC_DEBUG_MSG(_T("Socket...")); 
    7269      if (!get_socket().is_open()) { 
    7370        NSC_DEBUG_MSG(_T("is closed...")); 
     
    7673      unsigned int len = nsca::length::iv::get_packet_length(); 
    7774      std::vector<char> buf(len); 
    78       NSC_DEBUG_MSG(_T("About t read IV: ") + strEx::itos(len)); 
    7975      if (!read_with_timeout(buf, timeout)) { 
    8076        NSC_LOG_ERROR_STD(_T("Failed to read IV from server.")); 
     
    8278      } 
    8379      std::string str_buf(buf.begin(), buf.end()); 
    84       NSC_DEBUG_MSG(_T("Encrypting using: ") + strEx::itos(encryption_method)); 
     80      NSC_DEBUG_MSG(_T("Encrypting using when sending: ") + utf8::cvt<std::wstring>(nsca::nsca_encrypt::helpers::encryption_to_string(encryption_method)) + _T(" and ") + utf8::cvt<std::wstring>(password)); 
    8581      crypt_inst.encrypt_init(password, encryption_method, str_buf); 
    8682      return true; 
     
    9288      socket_helpers::io::write_with_timeout(*socket_, get_socket(), boost::asio::buffer(buf), timeout); 
    9389    } 
    94     /* 
    95     virtual void read_with_timeout(std::string &buf, boost::posix_time::seconds timeout) { 
    96       socketHelpers::io::read_with_timeout(*socket_, get_socket(), boost::asio::mutable_buffer(buf), timeout); 
    97     } 
    98     virtual void write_with_timeout(std::string &buf, boost::posix_time::seconds timeout) { 
    99       socketHelpers::io::write_with_timeout(*socket_, get_socket(), boost::asio::buffer(buf), timeout); 
    100     } 
    101     */ 
    10290  }; 
    10391} 
  • include/nsca/server/connection.cpp

    ra629015 r9b9be81  
    3030      handler_->log_debug(__FILE__, __LINE__, _T("starting data connection...")); 
    3131      std::vector<boost::asio::const_buffer> buffers; 
    32       nsca::iv_packet packet(nsca_encrypt::generate_transmitted_iv()); 
     32 
     33      std::string iv = nsca::nsca_encrypt::generate_transmitted_iv(); 
     34      handler_->log_debug(__FILE__, __LINE__, _T("Encrypting using when receieving: ") + utf8::cvt<std::wstring>(nsca::nsca_encrypt::helpers::encryption_to_string(handler_->get_encryption())) + _T(" and ") + utf8::cvt<std::wstring>(handler_->get_password())); 
     35      encryption_instance_.encrypt_init(handler_->get_password(), handler_->get_encryption(), iv); 
     36 
     37      nsca::iv_packet packet(iv); 
    3338      buffers.push_back(buf(packet.get_buffer())); 
    34       handler_->log_debug(__FILE__, __LINE__, _T("About to write: ") + strEx::itos(packet.get_buffer().size())); 
    3539      start_write_request(buffers, 30); 
    3640    } 
     
    6872    void connection::handle_read_request(const boost::system::error_code& e, std::size_t bytes_transferred) { 
    6973      if (!e) { 
    70         handler_->log_error(__FILE__, __LINE__, _T("Got data (server): ") + strEx::itos(bytes_transferred)); 
    7174        bool result; 
    7275        buffer_type::iterator begin = buffer_.begin(); 
     
    8285            nsca::packet response; 
    8386            try { 
    84               // TODO decrypt data here... 
    85               //NSC_DEBUG_MSG(_T("Encrypting using: ") + strEx::itos(encryption_method)); 
    86               nsca::packet request = parser_.parse(); 
     87              nsca::packet request = parser_.parse(encryption_instance_); 
    8788              handler_->handle(request); 
    8889            } catch (nsca::nsca_exception &e) { 
     90              handler_->log_error(__FILE__, __LINE__, str::to_wstring(e.what())); 
     91            } catch (const std::exception &e) { 
    8992              handler_->log_error(__FILE__, __LINE__, str::to_wstring(e.what())); 
    9093            } catch (...) { 
     
    9295            } 
    9396            cancel_timer(); 
    94             handler_->log_error(__FILE__, __LINE__, _T("Done reading packet (server), shutting down...")); 
    9597            // Initiate graceful connection closure. 
    9698            boost::system::error_code ignored_ec; 
  • include/nsca/server/connection.hpp

    ra629015 r9b9be81  
    66#include <boost/shared_ptr.hpp> 
    77#include <boost/enable_shared_from_this.hpp> 
     8 
     9#include <nsca/nsca_enrypt.hpp> 
    810 
    911#include "handler.hpp" 
     
    7274      boost::asio::ip::tcp::socket socket_; 
    7375 
     76      nsca::nsca_encrypt encryption_instance_; 
     77 
    7478    }; 
    7579 
  • include/nsca/server/handler.hpp

    ra629015 r9b9be81  
    2020      virtual void set_channel(std::wstring channel) = 0; 
    2121      virtual std::wstring get_channel() = 0; 
    22  
     22      virtual void set_encryption(std::string encryption) = 0; 
     23      virtual int get_encryption() = 0; 
     24      virtual std::string get_password() = 0; 
     25      virtual void set_password(std::string pwd) = 0; 
    2326    }; 
    2427  }// namespace server 
  • include/nsca/server/parser.hpp

    ra629015 r9b9be81  
    55 
    66#include <nsca/nsca_packet.hpp> 
     7#include <nsca/nsca_enrypt.hpp> 
    78 
    89#include "handler.hpp" 
     
    2829      } 
    2930 
    30       nsca::packet parse() { 
     31      nsca::packet parse(nsca::nsca_encrypt &encryption) { 
    3132        nsca::packet packet(payload_length_); 
     33        //std::string buffer = encryption.get_rand_buffer(packet.get_packet_length()); 
     34        //packet.get_buffer(buffer); 
     35        encryption.decrypt_buffer(buffer_); 
    3236        packet.parse_data(buffer_.c_str(), buffer_.size()); 
    3337        buffer_.clear(); 
  • include/nscapi/functions.hpp

    ra629015 r9b9be81  
    6161      return NSCAPI::returnUNKNOWN; 
    6262    } 
     63    static Plugin::Common::Status::StatusType status_to_gpb(int ret) { 
     64      if (ret == NSCAPI::isSuccess) 
     65        return Plugin::Common_Status_StatusType_OK; 
     66      return Plugin::Common_Status_StatusType_PROBLEM; 
     67    } 
     68    static int gbp_to_status(Plugin::Common::Status::StatusType ret) { 
     69      if (ret == Plugin::Common_Status_StatusType_OK) 
     70        return NSCAPI::isSuccess; 
     71      return NSCAPI::hasFailed; 
     72    } 
    6373    static Plugin::LogEntry::Entry::Level log_to_gpb(NSCAPI::messageTypes ret) { 
    6474      if (ret == NSCAPI::critical) 
     
    236246      message.SerializeToString(&buffer); 
    237247    } 
    238     static void create_simple_submit_response(std::wstring channel, NSCAPI::nagiosReturn ret, std::wstring msg, std::string &buffer) { 
     248    static void create_simple_submit_response(std::wstring channel, std::wstring command, NSCAPI::nagiosReturn ret, std::wstring msg, std::string &buffer) { 
    239249      Plugin::SubmitResponseMessage message; 
    240250      create_simple_header(message.mutable_header()); 
     
    242252 
    243253      Plugin::SubmitResponseMessage::Response *payload = message.add_payload(); 
    244       payload->set_message(to_string(msg)); 
    245       //payload->set_result(nagios_status_to_gpb(ret)); 
     254      payload->set_command(utf8::cvt<std::string>(command)); 
     255      payload->mutable_status()->set_message(to_string(msg)); 
     256      payload->mutable_status()->set_status(status_to_gpb(ret)); 
    246257      message.SerializeToString(&buffer); 
    247258    } 
    248     static NSCAPI::errorReturn parse_simple_submit_request(const std::string &request, std::wstring &command, std::wstring &msg, std::wstring &perf) { 
     259    static NSCAPI::errorReturn parse_simple_submit_request(const std::string &request, std::wstring &source, std::wstring &command, std::wstring &msg, std::wstring &perf) { 
    249260      Plugin::SubmitRequestMessage message; 
    250261      message.ParseFromString(request); 
     
    254265      } 
    255266      Plugin::QueryResponseMessage::Response payload = message.payload().Get(0); 
     267      source = utf8::cvt<std::wstring>(payload.source()); 
    256268      command = utf8::cvt<std::wstring>(payload.command()); 
    257269      msg = utf8::cvt<std::wstring>(payload.message()); 
    258270      perf = utf8::cvt<std::wstring>(build_performance_data(payload)); 
    259       return -1; 
     271      return gbp_to_nagios_status(payload.result()); 
    260272    } 
    261273    static NSCAPI::errorReturn parse_simple_submit_request_payload(const Plugin::QueryResponseMessage::Response &payload, std::wstring &command, std::wstring &msg, std::wstring &perf) { 
     
    273285      } 
    274286      ::Plugin::SubmitResponseMessage::Response payload = message.payload().Get(0); 
    275       response = to_wstring(payload.message()); 
    276       return -1; 
    277     } 
     287      response = to_wstring(payload.mutable_status()->message()); 
     288      return gbp_to_status(payload.mutable_status()->status()); 
     289    } 
     290    /* 
     291    static void create_simple_submit_response(std::wstring msg, int status, std::string &buffer) { 
     292      Plugin::SubmitResponseMessage message; 
     293      create_simple_header(message.mutable_header()); 
     294 
     295      Plugin::SubmitResponseMessage::Response *payload = message.add_payload(); 
     296      payload->mutable_status()->set_message(to_string(msg)); 
     297      payload->mutable_status()->set_status(status_to_gpb(status)); 
     298 
     299      message.SerializeToString(&buffer); 
     300    }*/ 
    278301 
    279302    static void create_simple_query_request(std::wstring command, std::list<std::wstring> arguments, std::string &buffer) { 
  • include/nscapi/nscapi_core_wrapper.cpp

    ra629015 r9b9be81  
    140140  DestroyBuffer(&buffer); 
    141141  return ret; 
     142} 
     143 
     144NSCAPI::errorReturn nscapi::core_wrapper::reload(std::wstring module) { 
     145 
     146  if (!fNSAPIReload) 
     147    throw nscapi::nscapi_exception(_T("NSCore has not been initiated...")); 
     148  return fNSAPIReload(module.c_str()); 
    142149} 
    143150 
     
    640647  fNSAPIReadSettings = (nscapi::core_api::lpNSAPIReadSettings)f(_T("NSAPIReadSettings")); 
    641648  fNSAPIRehash = (nscapi::core_api::lpNSAPIRehash)f(_T("NSAPIRehash")); 
     649  fNSAPIReload = (nscapi::core_api::lpNSAPIReload)f(_T("NSAPIReload")); 
    642650 
    643651  fNSAPIDescribeCommand = (nscapi::core_api::lpNSAPIDescribeCommand)f(_T("NSAPIDescribeCommand")); 
  • include/nscapi/nscapi_core_wrapper.hpp

    ra629015 r9b9be81  
    5252    nscapi::core_api::lpNSAPIDestroyBuffer fNSAPIDestroyBuffer; 
    5353    nscapi::core_api::lpNSAPINotify fNSAPINotify; 
     54    nscapi::core_api::lpNSAPIReload fNSAPIReload; 
    5455    nscapi::core_api::lpNSAPICheckLogMessages fNSAPICheckLogMessages; 
    5556    nscapi::core_api::lpNSAPIEncrypt fNSAPIEncrypt; 
     
    144145    NSCAPI::errorReturn submit_message(const wchar_t* channel, const char *request, const unsigned int request_len, char **response, unsigned int *response_len); 
    145146    NSCAPI::errorReturn submit_message(std::wstring channel, std::string request, std::string &response); 
     147    NSCAPI::errorReturn reload(std::wstring module); 
    146148    void StopService(void); 
    147149    void Exit(void); 
  • include/nscapi/nscapi_plugin_wrapper.cpp

    ra629015 r9b9be81  
    110110NSCAPI::nagiosReturn nscapi::impl::simple_submission_handler::handleRAWNotification(const wchar_t* channel, std::string request, std::string &response) { 
    111111  try { 
    112     std::wstring command, msg, perf; 
    113     int code = nscapi::functions::parse_simple_submit_request(request, command, msg, perf); 
    114     NSCAPI::nagiosReturn ret = handleSimpleNotification(channel, command, code, msg, perf); 
     112    std::wstring source, command, msg, perf; 
     113    int code = nscapi::functions::parse_simple_submit_request(request, source, command, msg, perf); 
     114    NSCAPI::nagiosReturn ret = handleSimpleNotification(channel, source, command, code, msg, perf); 
    115115    if (ret == NSCAPI::returnIgnored) 
    116116      return NSCAPI::returnIgnored; 
    117     nscapi::functions::create_simple_submit_response(channel, ret, _T(""), response); 
     117    nscapi::functions::create_simple_submit_response(channel, command, ret, _T(""), response); 
    118118  } catch (std::exception &e) { 
    119119    nscapi::plugin_singleton->get_core()->Message(NSCAPI::error, __FILE__, __LINE__, utf8::cvt<std::wstring>("Failed to parse data from: " + strEx::strip_hex(request) + ": " + e.what())); 
  • include/nscapi/nscapi_plugin_wrapper.hpp

    ra629015 r9b9be81  
    123123    public: 
    124124      NSCAPI::nagiosReturn handleRAWNotification(const wchar_t* channel, std::string request, std::string &response); 
    125       virtual NSCAPI::nagiosReturn handleSimpleNotification(const std::wstring channel, const std::wstring command, NSCAPI::nagiosReturn code, std::wstring msg, std::wstring perf) = 0; 
     125      virtual NSCAPI::nagiosReturn handleSimpleNotification(const std::wstring channel, const std::wstring source, const std::wstring command, NSCAPI::nagiosReturn code, std::wstring msg, std::wstring perf) = 0; 
    126126 
    127127    }; 
  • include/settings/Settings.h

    r7515d00 r9b9be81  
    3535 
    3636namespace Settings { 
    37   class SettingsException { 
     37  class SettingsException : public std::exception { 
    3838    std::wstring error_; 
    3939  public: 
     
    4343    /// 
    4444    /// @author mickem 
    45     SettingsException(std::wstring error) : error_(error) {} 
     45    SettingsException(std::wstring error) : error_(utf8::cvt<std::wstring>(error)) {} 
     46    SettingsException(std::string error) : error_(error) {} 
     47 
     48    ~SettingsException() throw() {} 
    4649 
    4750    ////////////////////////////////////////////////////////////////////////// 
     
    5053    /// 
    5154    /// @author mickem 
    52     std::wstring getError() const { return error_; } 
    53     std::wstring getMessage() const { return error_; } 
     55    const char* what() const throw() { return error_.c_str(); } 
    5456  }; 
    5557  class KeyNotFoundException : public SettingsException { 
  • include/settings/client/settings_client.hpp

    r7515d00 r9b9be81  
    582582          core_->register_path(v->path_name, v->description.title, v->description.description, v->description.advanced); 
    583583        } 
     584      } 
     585      void clear() { 
     586        keys_.clear(); 
     587        paths_.clear(); 
    584588      } 
    585589 
  • libs/protobuf/plugin.proto

    ra629015 r9b9be81  
    137137  message Request { 
    138138    optional int32 id = 1; 
     139    optional string target = 7; 
    139140    required string command = 2; 
    140141    optional string alias = 3; 
     
    152153 
    153154    optional int32 id = 1; 
     155    optional string source = 7; 
    154156    required string command = 2; 
    155157    optional string alias = 3; 
     
    239241    required string command = 2; 
    240242    required Common.Status status = 3; 
    241     optional string message = 4; 
    242243    repeated Common.Attachment attachments = 17; 
    243244  }; 
  • modules/CheckExternalScripts/CheckExternalScripts.cpp

    ra78a985 r9b9be81  
    8383      _T("EXTERNAL SCRIPT SCRIPT SECTION"), _T("A list of scripts available to run from the CheckExternalScripts module. Syntax is: <command>=<script> <arguments>")) 
    8484 
     85      (_T("wrappings"), sh::wstring_map_path(&wrappings_) 
     86      , _T("EXTERNAL SCRIPT WRAPPINGS SECTION"), _T("A list of templates for wrapped scripts")) 
     87 
    8588      (_T("alias"), sh::fun_values_path(boost::bind(&CheckExternalScripts::add_alias, this, _1, _2)),  
    8689      _T("EXTERNAL SCRIPT ALIAS SECTION"), _T("A list of aliases available. An alias is an internal command that has been \"wrapped\" (to add arguments). Be careful so you don't create loops (ie check_loop=check_a, check_a=check_loop)")) 
    8790 
    88       (_T("wrappings"), sh::wstring_map_path(&wrappings_) 
    89       , _T("EXTERNAL SCRIPT WRAPPINGS SECTION"), _T("")) 
    90  
    91       (_T("wrapped scripts"), sh::fun_values_path(boost::bind(&CheckExternalScripts::add_wrapping, this, _1, _2)),  
    92       _T("EXTERNAL SCRIPT WRAPPED SCRIPTS SECTION"), _T("")) 
    9391      ; 
    9492 
     
    107105      ; 
    108106 
     107    settings.register_all(); 
     108    settings.notify(); 
     109    settings.clear(); 
     110 
     111    settings.alias().add_path_to_settings() 
     112 
     113      (_T("wrapped scripts"), sh::fun_values_path(boost::bind(&CheckExternalScripts::add_wrapping, this, _1, _2)),  
     114      _T("EXTERNAL SCRIPT WRAPPED SCRIPTS SECTION"), _T("A list of wrappped scripts (ie. using the template mechanism)")) 
     115 
     116      ; 
    109117    settings.register_all(); 
    110118    settings.notify(); 
  • modules/CheckExternalScripts/CheckExternalScripts.h

    ra44cb15 r9b9be81  
    138138    strEx::replace(tpl, _T("%ARGS%"), tok.second); 
    139139 
     140    NSC_DEBUG_MSG(_T("Adding wrapped script: ") + key); 
     141    NSC_DEBUG_MSG(_T("Adding wrapped script: ") + tpl); 
    140142    add_command(key,tpl); 
    141143  } 
  • modules/DistributedServer/DistributedServer.cpp

    r2b2e9b8 r9b9be81  
    7171    settings.notify(); 
    7272 
    73     context = new zmq::context_t(2); 
     73    if (mode == NSCAPI::normalStart) { 
     74      context = new zmq::context_t(2); 
    7475 
    75     zeromq_queue::connection_info queue_info(to_string(host), to_string(suffix)); 
    76     zeromq_queue::queue_manager queue; 
    77     queue.start(context, threads, queue_info); 
     76      zeromq_queue::connection_info queue_info(to_string(host), to_string(suffix)); 
     77      zeromq_queue::queue_manager queue; 
     78      queue.start(context, threads, queue_info); 
    7879 
    79     zeromq_worker::connection_info worker_info(queue_info.get_backend(), to_string(suffix), thread_count); 
    80     zeromq_worker::worker_manager workers; 
    81     workers.start(context, threads, worker_info); 
     80      zeromq_worker::connection_info worker_info(queue_info.get_backend(), to_string(suffix), thread_count); 
     81      zeromq_worker::worker_manager workers; 
     82      workers.start(context, threads, worker_info); 
     83    } 
    8284 
    8385  } catch (std::exception &e) { 
  • modules/NSCAClient/CMakeLists.txt

    ra629015 r9b9be81  
    1616 
    1717IF(HAVE_CRYPTOPP) 
    18   SET(EXTRA_LIBS ${EXTRA_LIBS} cryptopp_static) 
    19   SET(EXTRA_DEFINES ${EXTRA_DEFINES} -DHAVE_LIBCRYPTOPP) 
     18  SET(CRYPTOPP_LIB cryptopp_static) 
     19  ADD_DEFINITIONS(-DHAVE_LIBCRYPTOPP) 
     20  INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR}) 
    2021ELSE(HAVE_CRYPTOPP) 
    2122  message(STATUS "WARNING: No libCrypto++ in NSCA Module") 
     
    2324 
    2425ADD_DEFINITIONS(${NSCP_GLOBAL_DEFINES}) 
    25 ADD_DEFINITIONS(${EXTRA_DEFINES}) 
    2626 
    2727IF(WIN32) 
     
    4343 
    4444add_library(${TARGET} MODULE ${SRCS}) 
    45 INCLUDE_DIRECTORIES(${OPENSSL_INCLUDE_DIR}) 
    4645 
    4746target_link_libraries(${TARGET} 
    4847  ${Boost_FILESYSTEM_LIBRARY} 
    4948  ${NSCP_DEF_PLUGIN_LIB} 
    50   ${OPENSSL_LIBRARIES} 
    51   ${EXTRA_LIBS} 
     49  ${CRYPTOPP_LIB} 
    5250) 
    5351INCLUDE(${BUILD_CMAKE_FOLDER}/module.cmake) 
     52SOURCE_GROUP("Server" REGULAR_EXPRESSION .*include/nsca/.*) 
  • modules/NSCAClient/NSCAClient.cpp

    ra629015 r9b9be81  
    114114    settings.notify(); 
    115115 
    116     NSC_DEBUG_MSG(_T("==> Registring listsner for: ") + channel_ + _T(" for ") + to_wstring(get_id())); 
    117116    get_core()->registerSubmissionListener(get_id(), channel_); 
    118117 
     
    211210    } 
    212211    return NSCAPI::isSuccess; 
    213     /* 
    214     boost::asio::io_service io_service; 
    215     nsca::socket socket(io_service); 
    216     socket.connect(nscahost_, nscaport_); 
    217     nsca::packet packet(hostname_, payload_length_, time_delta_); 
    218     packet.code = code; 
    219     packet.service = utf8::cvt<std::string>(command); 
    220     packet.result = utf8::cvt<std::string>(msg) + "|" + utf8::cvt<std::string>(perf); 
    221     socket.recv_iv(password_, encryption_method_, boost::posix_time::seconds(timeout_)); 
    222     socket.send_nsca(packet, boost::posix_time::seconds(timeout_)); 
    223     return NSCAPI::isSuccess; 
    224     */ 
    225212  } catch (nsca::nsca_encrypt::encryption_exception &e) { 
    226213    NSC_LOG_ERROR_STD(_T("Failed to encrypt data: ") + str::to_wstring(e.what())); 
     
    270257  std::list<std::string> result; 
    271258  try { 
    272     NSC_DEBUG_MSG(_T(">>>") + str::to_wstring(strEx::format_buffer(request))); 
    273259    Plugin::SubmitRequestMessage message; 
    274260    message.ParseFromString(request); 
    275     NSC_DEBUG_MSG(_T("<<<") + str::to_wstring(strEx::format_buffer(message.SerializeAsString()))); 
    276261    std::list<nsca::packet> list; 
    277262 
    278263    std::wstring command, msg, perf; 
    279264    nscapi::functions::destination_container recipient; // = data->host_default_recipient; 
    280     //recipient.address = data->host; // "default host" 
    281     // this should be set before calling... 
    282     /* 
    283     if (recipient.data.find("password") == recipient.data.end()) 
    284       recipient.data["password"] = "default password"; 
    285     if (recipient.data.find("encryption") == recipient.data.end()) 
    286       recipient.data["encryption"] = "default encryption"; 
    287     if (recipient.data.find("payload length") != recipient.data.end()) 
    288       local_data.payload_length = strEx::stoi(recipient.data["payload length"]); 
    289     if (recipient.data.find("time offset") != recipient.data.end()) 
    290       local_data.time_delta = strEx::stol_as_time_sec(to_wstring(recipient.data["time offset"]), 1); 
    291     */ 
    292265    nscapi::functions::parse_destination(*header, header->recipient_id(), recipient, true); 
    293266    nscapi::functions::destination_container source; 
    294     //source.host = hostname_; 
    295267    nscapi::functions::parse_destination(*header, header->source_id(), source); 
    296268 
  • modules/NSCAClient/NSCAClient.h

    ra629015 r9b9be81  
    5959    int port; 
    6060    unsigned int get_encryption() { 
    61       if (encryption.size() > 1 && std::isalnum(encryption[0])) 
    62         return strEx::stoi(encryption); 
    6361      return nsca::nsca_encrypt::helpers::encryption_to_int(encryption); 
    64  
    6562    } 
    6663  }; 
  • modules/NSCAServer/CMakeLists.txt

    ra629015 r9b9be81  
    4646ENDIF(WIN32) 
    4747 
     48 
    4849add_library(${TARGET} MODULE ${SRCS}) 
    4950 
  • modules/NSCAServer/NSCAServer.cpp

    ra629015 r9b9be81  
    5656      _T("PERFORMANCE DATA"), _T("Send performance data back to nagios (set this to 0 to remove all performance data).")) 
    5757 
     58      (_T("encryption"), sh::string_fun_key<std::string>(boost::bind(&nsca::server::handler::set_encryption, info_.request_handler, _1), "aes"), 
     59      _T("ENCRYPTION"), _T("Encryption to use")) 
     60 
     61      (_T("password"), sh::string_fun_key<std::string>(boost::bind(&nsca::server::handler::set_password, info_.request_handler, _1), ""), 
     62      _T("PASSWORD"), _T("Password to use")) 
     63 
     64 
    5865      ; 
    5966 
     
    8592    settings.register_all(); 
    8693    settings.notify(); 
    87  
    8894 
    8995    if (info_.request_handler->get_payload_length() != 512) 
  • modules/NSCAServer/handler_impl.cpp

    ra629015 r9b9be81  
    77void handler_impl::handle(nsca::packet p) { 
    88  std::wstring response; 
    9   std::wstring msg = utf8::cvt<std::wstring>(p.result); 
     9  std::string::size_type pos = p.result.find('|'); 
     10  if (pos != std::string::npos) { 
     11    std::wstring msg = utf8::cvt<std::wstring>(p.result.substr(0, pos)); 
     12    std::wstring perf = utf8::cvt<std::wstring>(p.result.substr(++pos)); 
     13    GET_CORE()->submit_simple_message(channel_, utf8::cvt<std::wstring>(p.service), p.code, msg, perf, response); 
     14  } else { 
     15    std::wstring empty; 
     16    GET_CORE()->submit_simple_message(channel_, utf8::cvt<std::wstring>(p.service), p.code, utf8::cvt<std::wstring>(p.result), empty, response); 
     17 
     18  } 
    1019  std::wstring perf = _T(""); // @todo fix this! 
    1120 
    12   GET_CORE()->submit_simple_message(channel_, utf8::cvt<std::wstring>(p.service), p.code, msg, perf, response); 
    1321  NSC_DEBUG_MSG(_T("Got response: ") + response); 
    1422} 
  • modules/NSCAServer/handler_impl.hpp

    ra629015 r9b9be81  
    44 
    55#include <nsca/nsca_packet.hpp> 
     6#include <nsca/nsca_enrypt.hpp> 
    67#include <nsca/server/handler.hpp> 
    78 
     
    1415  bool noPerfData_; 
    1516  std::wstring channel_; 
     17  int encryption_; 
     18  std::string password_; 
    1619public: 
    1720  handler_impl(unsigned int payload_length) : payload_length_(payload_length), noPerfData_(false), allowNasty_(false), allowArgs_(false) {} 
     
    2831  std::wstring get_channel() { 
    2932    return channel_; 
     33  } 
     34  void set_encryption(std::string enc) { 
     35    encryption_ = nsca::nsca_encrypt::helpers::encryption_to_int(enc); 
     36  } 
     37  int get_encryption() { 
     38    return encryption_; 
     39  } 
     40  std::string get_password() { 
     41    return password_; 
     42  } 
     43  void set_password(std::string pwd) { 
     44    password_ = pwd; 
    3045  } 
    3146 
  • modules/NSCPClient/NSCPClient.cpp

    ra629015 r9b9be81  
    8181    settings.notify(); 
    8282 
    83     NSC_LOG_ERROR_STD(_T("Targets: ") + targets.to_wstring()); 
    84  
    8583  } catch (...) { 
    8684    NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>")); 
  • modules/PythonScript/PythonScript.cpp

    ra629015 r9b9be81  
    4747using namespace boost::python; 
    4848 
     49template<class T> 
     50void caller(auto_ptr<T> obj) 
     51{ 
     52  new_owner_function(obj.get()); 
     53  obj.release(); 
     54} 
    4955 
    5056 
    5157BOOST_PYTHON_MODULE(NSCP) 
    5258{ 
     59  PyEval_InitThreads(); 
    5360  class_<script_wrapper::settings_wrapper, boost::shared_ptr<script_wrapper::settings_wrapper> >("Settings", no_init) 
    5461    .def("get",&script_wrapper::settings_wrapper::create) 
     
    9097    .def("simple_submit", &script_wrapper::command_wrapper::simple_submit) 
    9198    .def("submit", &script_wrapper::command_wrapper::submit) 
     99    .def("reload", &script_wrapper::command_wrapper::reload) 
    92100    ; 
    93101 
     
    99107    ; 
    100108  def("log", script_wrapper::log_msg); 
     109  def("log_err", script_wrapper::log_error); 
     110  def("log_deb", script_wrapper::log_debug); 
     111  def("log_error", script_wrapper::log_error); 
     112  def("log_debug", script_wrapper::log_debug); 
    101113//  def("get_module_alias", script_wrapper::get_module_alias); 
    102114//  def("get_script_alias", script_wrapper::get_script_alias); 
     
    206218  std::list<boost::filesystem::wpath> checks; 
    207219  checks.push_back(file); 
     220  checks.push_back((file + _T(".py"))); 
    208221  checks.push_back(root_ / _T("scripts") / _T("python") / file); 
     222  checks.push_back(root_ / _T("scripts") / _T("python") / (file + _T(".py"))); 
    209223  checks.push_back(root_ / _T("scripts") / file); 
    210   checks.push_back(root_ / _T("python") / file); 
     224  checks.push_back(root_ / _T("scripts") / (file + _T(".py"))); 
    211225  checks.push_back(root_ / file); 
    212226  BOOST_FOREACH(boost::filesystem::wpath c, checks) { 
     
    308322NSCAPI::nagiosReturn PythonScript::commandRAWLineExec(const wchar_t* char_command, const std::string &request, std::string &response) { 
    309323  std::wstring command = char_command; 
    310   if (command == _T("execute-and-load-python")) { 
     324  if (command == _T("execute-and-load-python") || command == _T("execute-python") || command == _T("run")) { 
    311325    nscapi::functions::decoded_simple_command_data data = nscapi::functions::parse_simple_exec_request(char_command, request); 
    312326    return execute_and_load_python(data.args); 
     
    355369  std::string chnl = utf8::cvt<std::string>(channel); 
    356370  if (inst->has_message_handler(chnl)) { 
    357     return inst->handle_message(chnl, request, response); 
     371    NSCAPI::nagiosReturn ret = inst->handle_message(chnl, request, response); 
     372    if (ret != NSCAPI::returnIgnored) 
     373      return ret; 
    358374  } 
    359375  if (inst->has_simple_message_handler(chnl)) { 
    360     std::wstring cmd, msg, perf; 
    361     int code = nscapi::functions::parse_simple_submit_request(request, cmd, msg, perf); 
    362     int ret = inst->handle_simple_message(chnl, to_string(cmd), code, msg, perf); 
    363     nscapi::functions::parse_simple_submit_response(response, _T("")); 
     376    std::wstring src, cmd, msg, perf; 
     377    int code = nscapi::functions::parse_simple_submit_request(request, src, cmd, msg, perf); 
     378    int ret = inst->handle_simple_message(chnl, to_string(src), to_string(cmd), code, msg, perf); 
     379    nscapi::functions::create_simple_submit_response(channel, cmd, ret, _T(""), response); 
    364380    return ret; 
    365381  } 
  • modules/PythonScript/script_wrapper.cpp

    ra629015 r9b9be81  
    44#include "script_wrapper.hpp" 
    55#include "PythonScript.h" 
     6#include <nscapi/functions.hpp> 
    67 
    78using namespace boost::python; 
     9namespace py = boost::python; 
    810 
    911boost::shared_ptr<script_wrapper::functions> script_wrapper::functions::instance; 
     
    1315 
    1416void script_wrapper::log_msg(std::wstring x) { 
     17  NSC_LOG_MESSAGE(utf8::cvt<std::wstring>(x)); 
     18} 
     19void script_wrapper::log_error(std::wstring x) { 
    1520  NSC_LOG_ERROR_STD(utf8::cvt<std::wstring>(x)); 
     21} 
     22void script_wrapper::log_debug(std::wstring x) { 
     23  NSC_DEBUG_MSG(utf8::cvt<std::wstring>(x)); 
    1624} 
    1725/* 
     
    3240    NSC_LOG_ERROR_STD(_T("Failed to parse error: ") + utf8::cvt<std::wstring>(e.what())); 
    3341    PyErr_Clear(); 
     42  } catch (...) { 
     43    NSC_LOG_ERROR_STD(_T("Failed to parse python error")); 
     44    PyErr_Clear(); 
    3445  } 
    3546} 
     
    125136    } 
    126137 
    127     boost::python::list l; 
     138    py::list l; 
    128139    BOOST_FOREACH(std::wstring a, arguments) { 
    129140      l.append(utf8::cvt<std::string>(a)); 
     
    239250} 
    240251 
    241 int script_wrapper::function_wrapper::handle_message(const std::string channel, const std::string command, std::string &message) const { 
     252int script_wrapper::function_wrapper::handle_message(const std::string channel, const std::string &request, std::string &response) const { 
    242253  try { 
    243254    functions::function_map_type::iterator it = functions::get()->normal_handler.find(channel); 
     
    246257      return NSCAPI::returnIgnored; 
    247258    } 
    248     object ret = boost::python::call<object>(boost::python::object(it->second).ptr(), channel, command, message); 
    249     if (ret.ptr() == Py_None) { 
    250       return NSCAPI::returnUNKNOWN; 
    251     } 
    252     return extract<int>(ret); 
     259    PyGILState_STATE gstate = PyGILState_Ensure(); 
     260    tuple ret = boost::python::call<tuple>(boost::python::object(it->second).ptr(), channel, request); 
     261    if (ret.ptr() == Py_None) { 
     262      return NSCAPI::returnIgnored; 
     263    } 
     264    int ret_code = NSCAPI::returnIgnored; 
     265    if (len(ret) > 0) 
     266      ret_code = extract<bool>(ret[0])?NSCAPI::isSuccess:NSCAPI::returnIgnored; 
     267    if (len(ret) > 1) 
     268      response = extract<std::string>(ret[1]); 
     269    PyGILState_Release( gstate ); 
     270    return ret_code; 
    253271  } catch( error_already_set e) { 
    254272    log_exception(); 
     
    282300} 
    283301 
    284 int script_wrapper::function_wrapper::handle_simple_message(const std::string channel, const std::string command, int code, std::wstring &msg, std::wstring &perf) const { 
     302int script_wrapper::function_wrapper::handle_simple_message(const std::string channel, const std::string source, const std::string command, int code, std::wstring &msg, std::wstring &perf) const { 
    285303  try { 
    286304    functions::function_map_type::iterator it = functions::get()->simple_handler.find(channel); 
     
    289307      return NSCAPI::returnIgnored; 
    290308    } 
    291     object ret = boost::python::call<object>(boost::python::object(it->second).ptr(), channel, command, nagios_return_to_py(code), utf8::cvt<std::string>(msg), utf8::cvt<std::string>(perf)); 
    292     if (ret.ptr() == Py_None) { 
    293       return NSCAPI::returnUNKNOWN; 
    294     } 
    295     return extract<int>(ret); 
     309    PyGILState_STATE gstate = PyGILState_Ensure(); 
     310    object ret = boost::python::call<object>(boost::python::object(it->second).ptr(), channel, source, command, nagios_return_to_py(code), utf8::cvt<std::string>(msg), utf8::cvt<std::string>(perf)); 
     311    int ret_code = NSCAPI::returnIgnored; 
     312    if (ret.ptr() == Py_None) { 
     313      ret_code = NSCAPI::isSuccess; 
     314    } else { 
     315      ret_code = extract<bool>(ret)?NSCAPI::isSuccess:NSCAPI::returnIgnored; 
     316    } 
     317    PyGILState_Release( gstate ); 
     318    return ret_code; 
    296319  } catch( error_already_set e) { 
    297320    log_exception(); 
    298     return NSCAPI::returnUNKNOWN; 
     321    return NSCAPI::hasFailed; 
    299322  } 
    300323} 
     
    327350 
    328351 
    329 std::list<std::wstring> script_wrapper::convert(list lst) { 
     352std::list<std::wstring> script_wrapper::convert(py::list lst) { 
    330353  std::list<std::wstring> ret; 
    331354  for (int i = 0;i<len(lst);i++) 
     
    333356  return ret; 
    334357} 
    335 list script_wrapper::convert(std::list<std::wstring> lst) { 
    336    list ret; 
     358py::list script_wrapper::convert(std::list<std::wstring> lst) { 
     359  py::list ret; 
    337360   BOOST_FOREACH(std::wstring s, lst) { 
    338361     ret.append(utf8::cvt<std::string>(s)); 
     
    359382  std::wstring wchannel = utf8::cvt<std::wstring>(channel); 
    360383  std::string response; 
    361   int ret = core->submit_message(wchannel, request, response); 
    362   return make_tuple(ret,response); 
    363 } 
    364  
    365  
    366 tuple script_wrapper::command_wrapper::simple_query(std::string command, list args) { 
     384  int ret; 
     385  Py_BEGIN_ALLOW_THREADS 
     386  ret = core->submit_message(wchannel, request, response); 
     387  Py_END_ALLOW_THREADS  
     388  std::wstring err; 
     389  nscapi::functions::parse_simple_submit_response(response, err); 
     390  return make_tuple(ret==NSCAPI::isSuccess,err); 
     391} 
     392 
     393bool script_wrapper::command_wrapper::reload(std::string module) { 
     394  std::wstring wmodule = utf8::cvt<std::wstring>(module); 
     395  int ret = core->reload(wmodule); 
     396  return ret==NSCAPI::isSuccess; 
     397} 
     398 
     399 
     400tuple script_wrapper::command_wrapper::simple_query(std::string command, py::list args) { 
    367401  std::wstring msg, perf; 
    368402  int ret = core->simple_query(utf8::cvt<std::wstring>(command), convert(args), msg, perf); 
     
    375409} 
    376410 
    377 object script_wrapper::command_wrapper::simple_exec(std::string command, list args) { 
     411object script_wrapper::command_wrapper::simple_exec(std::string command, py::list args) { 
    378412  try { 
    379413    std::list<std::wstring> result; 
  • modules/PythonScript/script_wrapper.hpp

    ra629015 r9b9be81  
    1818  void log_exception(); 
    1919  void log_msg(std::wstring x); 
     20  void log_debug(std::wstring x); 
     21  void log_error(std::wstring x); 
    2022  //std::string get_alias(); 
    2123 
     
    8385 
    8486 
    85     int handle_simple_message(const std::string channel, const std::string wcmd, int code, std::wstring &msg, std::wstring &perf) const; 
    86     int handle_message(const std::string channel, const std::string wcmd, std::string &message) const; 
     87    int handle_simple_message(const std::string channel, const std::string wsrc, const std::string wcmd, int code, std::wstring &msg, std::wstring &perf) const; 
     88    int handle_message(const std::string channel, const std::string &request, std::string &response) const; 
    8789    bool has_message_handler(const std::string command); 
    8890    bool has_simple_message_handler(const std::string command); 
     
    113115    tuple simple_submit(std::string channel, std::string command, status code, std::string message, std::string perf); 
    114116    tuple submit(std::string channel, std::string request); 
     117    bool reload(std::string module); 
    115118  }; 
    116119 
  • scripts/python/lib/test_helper.py

    ra629015 r9b9be81  
    1 from NSCP import Settings, Registry, Core, log, status 
     1from NSCP import Settings, Registry, Core, log, log_error, status 
    22 
    33class Callable: 
     
    4141    return (fail_count, 9) 
    4242 
    43 def run_test(plugin_id, prefix, cls): 
    44   instance = cls.getInstance() 
    45   instance.setup(plugin_id, prefix) 
    46   ret = instance.run_test() 
    47   instance.teardown() 
    48   log('Tested %s (%s of %s)'%(instance.desc(), ret[0], ret[1])) 
    49   return ret 
     43class TestResult: 
     44  class Entry: 
     45    status = False 
     46    desc = 'Unassigned result' 
     47    level = 0 
     48    error = None 
     49    def __init__(self, status, desc, error): 
     50      self.status = status 
     51      self.desc = desc 
     52      self.error = error 
    5053 
    51 class TestResult: 
    52   fail_count = 0 
    53   count = 0 
     54    def log(self): 
     55      if self.status: 
     56        log('%s%s'%(''.rjust(self.level, ' '), self)) 
     57      else: 
     58        log_error('%s%s'%(''.rjust(self.level, ' '), self)) 
     59     
     60    def is_ok(self): 
     61      return self.status 
     62   
     63    def indent(self): 
     64      self.level = self.level + 1 
     65       
     66    def __str__(self): 
     67      if self.status: 
     68        return 'OK: %s'%self.desc 
     69      else: 
     70        return 'ERROR: %s (%s)'%(self.desc, self.error) 
     71 
     72  results = [] 
    5473   
    5574  def __init__(self): 
    56     None 
     75    self.results = [] 
    5776 
    58   def add_message(self, status, message): 
    59     if status: 
    60       log('OK: %s'%message) 
    61       self.add(0, 1) 
    62     else: 
    63       log('TEST FAILED: %s'%message) 
    64       self.add(1, 1) 
     77  def add_message(self, status, message, error = None): 
     78    e = TestResult.Entry(status, message, error) 
     79    e.log() 
     80    self.add_entry(e) 
     81     
     82  def assert_equals(self, s1, s2, msg): 
     83    self.add_message(s1 == s2, msg, '%s != %s'%(s1, s2)) 
     84 
     85  def add_entry(self, e): 
     86    self.results.append(e) 
    6587   
    66   def add(self, failed, total = None): 
    67     if total == None: 
    68       (failed, total) = failed 
    69     self.fail_count += failed 
    70     self.count += total 
     88  def add(self, result): 
     89    for e in result.results: 
     90      e.indent() 
     91    self.results.extend(result.results) 
    7192 
    7293  def log(self): 
    73     if self.fail_count > 0: 
    74       log("ERROR: %d/%d test(s) failed"%(self.fail_count,self.count)) 
     94    okcount = 0 
     95    count = len(self.results) 
     96    for e in self.results: 
     97      e.log() 
     98      if e.is_ok(): 
     99        okcount = okcount + 1 
     100    if okcount == count: 
     101      log("OK: %d test(s) successfull"%count) 
    75102    else: 
    76       log("OK: %d test(s) successfull"%self.count) 
    77     return (self.fail_count, self.count) 
     103      log("ERROR: %d/%d test(s) failed"%(count-okcount, count)) 
     104    return self 
    78105     
     106  def __str__(self): 
     107    s = '' 
     108    for e in self.results: 
     109      s += '%s, '%e 
     110    return s 
     111 
    79112  def return_nagios(self): 
     113    okcount = 0 
     114    count = len(self.results) 
    80115    self.log() 
    81     if self.fail_count == 0: 
    82       return (status.OK, 'All tests ok: %d'%self.count) 
     116    if okcount == count: 
     117      return (status.OK, "OK: %d test(s) successfull"%count) 
    83118    else: 
    84       return (status.CRITICAL, 'Tests failed %d of %d'%(self.fail_count, self.count)) 
    85      
    86    
    87 def log_test_result(status, message): 
    88   if status: 
    89     log('OK: %s'%message) 
    90     return (0, 1) 
    91   else: 
    92     log('TEST FAILED: %s'%message) 
    93     return (1, 1) 
     119      return (status.CRITICAL, "ERROR: %d/%d test(s) failed"%(count-okcount, count)) 
     120 
    94121     
    95122def log_result(result): 
     
    100127  return (result.fail_count, result.count) 
    101128 
     129   
     130def run_test(plugin_id, prefix, cls): 
     131  result = TestResult() 
     132  instance = cls.getInstance() 
     133  instance.setup(plugin_id, prefix) 
     134  result.add(instance.run_test()) 
     135  instance.teardown() 
     136  return result 
     137 
    102138def run_tests(plugin_id, prefix, list): 
    103   all_failed = 0 
    104   all_count = 0 
     139  result = TestResult() 
    105140  for c in list: 
    106     (failed, count) = run_test(plugin_id, prefix, c) 
    107     all_failed += failed 
    108     all_count += count 
    109   return (all_failed, all_count) 
     141    result.add(run_test(plugin_id, prefix, c)) 
     142  return result 
    110143 
    111144def test_usage_sample(arguments): 
  • scripts/python/test_nsca.py

    ra629015 r9b9be81  
    11from NSCP import Settings, Registry, Core, log, status 
    2 from test_helper import Callable, run_tests, log_test_result, log_result, TestResult 
     2from test_helper import Callable, run_tests, TestResult 
    33import plugin_pb2 
    44from types import * 
     
    2828  reg = None 
    2929  got_response = False 
     30  last_source = None 
     31  last_command = None 
     32  last_status = None 
     33  last_message = None 
     34  last_perfdata = None 
     35  got_simple_response = None 
    3036   
    3137  class SingletonHelper: 
     
    4450    self.key = '_%stest_command'%prefix 
    4551    self.reg = Registry.get(plugin_id) 
    46     self.reg.simple_subscription('nsca_test_inbox', NSCAServerTest.inbox_handler) 
     52    self.reg.simple_subscription('nsca_test_inbox', NSCAServerTest.simple_inbox_handler) 
     53    self.reg.subscription('nsca_test_inbox', NSCAServerTest.inbox_handler) 
    4754 
    48   def inbox_handler(channel, command, code, message, perf): 
     55  def simple_inbox_handler(channel, source, command, code, message, perf): 
    4956    instance = NSCAServerTest.getInstance() 
    50     instance.inbox_handler_wrapped(channel, command, code, message, perf) 
     57    return instance.simple_inbox_handler_wrapped(channel, source, command, code, message, perf) 
     58  simple_inbox_handler = Callable(simple_inbox_handler) 
     59 
     60  def inbox_handler(channel, request): 
     61    instance = NSCAServerTest.getInstance() 
     62    return instance.inbox_handler_wrapped(channel, request) 
    5163  inbox_handler = Callable(inbox_handler) 
    5264   
    53   def inbox_handler_wrapped(self, channel, command, code, message, perf): 
    54     log('Got message %s on %s'%(command, channel)) 
     65  def simple_inbox_handler_wrapped(self, channel, source, command, status, message, perf): 
     66    log('Got simple message %s on %s'%(command, channel)) 
     67    self.got_simple_response = True 
     68    self.last_source = source 
     69    self.last_command = command 
     70    self.last_status = status 
     71    self.last_message = message 
     72    self.last_perfdata = perf 
     73    return True 
     74 
     75  def inbox_handler_wrapped(self, channel, request): 
    5576    self.got_response = True 
     77    return (False, '') 
    5678     
    5779  def teardown(self): 
    5880    None 
    5981     
    60   def submit_payload(self): 
     82  def submit_payload(self, encryption, source, command, status, msg, perf): 
    6183    message = plugin_pb2.SubmitRequestMessage() 
    6284     
    6385    message.header.version = plugin_pb2.Common.VERSION_1 
    6486    message.header.recipient_id = "test_rp" 
    65     message.channel = 'TESTNSCA' 
     87    message.channel = 'nsca_test_outbox' 
    6688    host = message.header.hosts.add() 
    6789    host.address = "127.0.0.1:15667" 
    6890    host.id = "test_rp" 
     91    enc = host.metadata.add() 
     92    enc.key = "encryption" 
     93    enc.value = encryption 
     94    enc = host.metadata.add() 
     95    enc.key = "password" 
     96    enc.value = 'pwd-%s'%encryption 
    6997 
    7098    payload = message.payload.add() 
    71     payload.result = status.UNKNOWN 
    72     payload.command = 'hello_world' 
    73     payload.message = 'test' 
     99    payload.result = status 
     100    payload.command = command 
     101    payload.message = msg 
     102    payload.source = source 
    74103    self.got_response = False 
    75     (state, result) = core.submit('TESTNSCA', message.SerializeToString()) 
    76     log("Status: %s"%status) 
    77     return self.got_response 
     104    self.got_simple_response = False 
     105    (result_code, err) = core.submit('nsca_test_outbox', message.SerializeToString()) 
     106    result = TestResult() 
     107    result.add_message(len(err) == 0, 'Testing to send message using %s'%encryption, err) 
     108    result.add_message(self.got_simple_response, 'Testing to recieve simple message using %s'%encryption) 
     109    #result.assert_equals(self.last_source, source, 'Verify that source is sent through') 
     110    result.assert_equals(self.last_command, command, 'Verify that command is sent through') 
     111    result.assert_equals(self.last_message, msg, 'Verify that message is sent through') 
     112    result.assert_equals(self.last_perfdata, perf, 'Verify that performance data is sent through') 
     113    result.add_message(self.got_response, 'Testing to recieve message') 
     114    return result 
     115 
     116  def test_one_full(self, encryption, state, key): 
     117    return self.submit_payload(encryption, '%ssrc%s'%(key, key), '%scmd%s'%(key, key), state, '%smsg%s'%(key, key), '') 
     118 
     119  def test_one(self, crypto): 
     120    conf = Settings.get() 
     121    conf.set_string('/settings/NSCA/test_nsca_server', 'encryption', '%s'%crypto) 
     122    conf.set_string('/settings/NSCA/test_nsca_server', 'password', 'pwd-%s'%crypto) 
     123    core.reload('test_nsca_server') 
     124    result = TestResult() 
     125    result.add(self.test_one_full(crypto, status.UNKNOWN, 'unknown')) 
     126    result.add(self.test_one_full(crypto, status.OK, 'ok')) 
     127    result.add(self.test_one_full(crypto, status.WARNING, 'warn')) 
     128    result.add(self.test_one_full(crypto, status.CRITICAL, 'crit')) 
     129    return result 
    78130 
    79131  def run_test(self): 
    80132    result = TestResult() 
    81133    result.add_message(isOpen('localhost', 15667), 'Checking that port is open') 
    82     result.add_message(self.submit_payload(), 'Submitting payload to target') 
     134    # seems broken: "xor", "3way" 
     135    for c in ["des", "cast128", "xtea", "blowfish", "twofish", "rc2", "aes", "serpent", "gost", "none"]: 
     136      result.add(self.test_one(c)) 
    83137     
    84     return result.log() 
     138    return result 
    85139 
    86140def test(arguments): 
     
    97151  log(' | To use this please run nsclient++ in "test mode" like so:                |') 
    98152  log(' | nscp --test                                                              |') 
    99   log(' | Then start the pytest_test command by typing it and press enter like so: |') 
    100   log(' | pytest_test                                                              |') 
     153  log(' | Then start the test_nsca command by typing it and press enter like so:  |') 
     154  log(' | test_nsca                                                                |') 
    101155  log(' | Lastly exit by typing exit like so:                                      |') 
    102156  log(' | exit                                                                     |') 
     
    105159  conf.set_string('/modules', 'test_nsca_server', 'NSCAServer') 
    106160  conf.set_string('/modules', 'test_nsca_client', 'NSCAClient') 
     161  conf.set_string('/modules', 'pytest', 'PythonScript') 
     162 
    107163  conf.set_string('/settings/pytest/scripts', 'test_nsca', 'test_nsca.py') 
    108164   
    109165  conf.set_string('/settings/NSCA/test_nsca_server', 'port', '15667') 
    110166  conf.set_string('/settings/NSCA/test_nsca_server', 'inbox', 'nsca_test_inbox') 
     167  conf.set_string('/settings/NSCA/test_nsca_server', 'encryption', '1') 
    111168 
    112169  conf.set_string('/settings/NSCA/test_nsca_client/targets', 'nsca_test_local', 'nsca://127.0.0.1:15667') 
     170  conf.set_string('/settings/NSCA/test_nsca_client', 'channel', 'nsca_test_outbox') 
    113171   
    114172  conf.save() 
  • service/NSCPlugin.cpp

    ra629015 r9b9be81  
    6060  if (isLoaded()) { 
    6161    try { 
    62       unload(); 
     62      unload_plugin(); 
     63      unload_dll(); 
    6364    } catch (NSPluginException &e) { 
    6465      // ... 
     
    311312 * @throws NSPluginException if the module is not loaded and/or cannot be unloaded (plug in remains loaded if so). 
    312313 */ 
    313 void NSCPlugin::unload() { 
     314void NSCPlugin::unload_plugin() { 
    314315  if (!isLoaded()) 
    315316    return; 
     
    322323    throw NSPluginException(module_, _T("Unhandled exception in fUnLoadModule.")); 
    323324  } 
     325} 
     326void NSCPlugin::unload_dll() { 
     327  if (isLoaded()) 
     328    return; 
    324329  module_.unload_library(); 
    325330} 
  • service/NSCPlugin.h

    ra629015 r9b9be81  
    143143  void deleteBuffer(char**buffer); 
    144144  void handleMessage(const char* data, unsigned int len); 
    145   void unload(void); 
     145  void unload_dll(void); 
     146  void unload_plugin(void); 
    146147  std::wstring getCongifurationMeta(); 
    147148  int commandLineExec(const wchar_t* command, std::string &request, std::string &reply); 
  • service/NSClient++.cpp

    ra629015 r9b9be81  
    855855        if (unloadLoggers || !p->hasMessageHandler()) { 
    856856          LOG_DEBUG_CORE_STD(_T("Unloading plugin: ") + p->getModule() + _T("...")); 
    857           p->unload(); 
     857          p->unload_plugin(); 
    858858        } else { 
    859859          LOG_DEBUG_CORE_STD(_T("Skipping log plugin: ") + p->getModule() + _T("...")); 
     
    891891} 
    892892 
     893NSCAPI::errorReturn NSClientT::reload(const wchar_t *module) { 
     894  { 
     895    std::wstring m = module; 
     896    boost::unique_lock<boost::shared_mutex> writeLock(m_mutexRW, boost::get_system_time() + boost::posix_time::seconds(10)); 
     897    if (!writeLock.owns_lock()) { 
     898      LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (007a).")); 
     899      return NSCAPI::hasFailed; 
     900    } 
     901 
     902    BOOST_FOREACH(plugin_type &p, plugins_) { 
     903      if (p->get_alias() == m) { 
     904        LOG_DEBUG_CORE_STD(_T("Found module: ") + m + _T(", reloading...")); 
     905        p->unload_plugin(); 
     906        p->load_plugin(NSCAPI::normalStart); 
     907        return NSCAPI::isSuccess; 
     908      } 
     909    } 
     910  } 
     911  return NSCAPI::hasFailed; 
     912} 
     913 
    893914void NSClientT::loadPlugins(NSCAPI::moduleLoadMode mode) { 
    894915  bool hasBroken = false; 
     
    960981    if (plugin->has_routing_handler()) 
    961982      routers_.add_plugin(plugin); 
    962     //settings_manager::get_core()->register_key(_T("/modules"), plugin->getModule(), settings::settings_core::key_string, plugin->getName(), plugin->getDescription(), _T(""), false); 
     983    settings_manager::get_core()->register_key(_T("/modules"), plugin->getModule(), settings::settings_core::key_string, plugin->getName(), plugin->getDescription(), _T(""), false); 
    963984    // TODO add comments elsewhere to the settings store for all loaded modules... 
    964985  } 
     
    10371058    } 
    10381059  } else */{ 
    1039     boost::shared_lock<boost::shared_mutex> readLock(m_mutexRW, boost::get_system_time() + boost::posix_time::milliseconds(5000)); 
    1040     if (!readLock.owns_lock()) { 
    1041       LOG_ERROR_CORE(_T("FATAL ERROR: Could not get read-mutex (008).")); 
    1042       return NSCAPI::returnUNKNOWN; 
    1043     } 
    10441060    try { 
    10451061      nsclient::commands::plugin_type plugin = commands_.get(cmd); 
  • service/NSClient++.h

    ra629015 r9b9be81  
    175175  NSCAPI::errorReturn register_submission_listener(unsigned int plugin_id, const wchar_t* channel); 
    176176  NSCAPI::errorReturn register_routing_listener(unsigned int plugin_id, const wchar_t* channel); 
     177 
     178  NSCAPI::errorReturn reload(const wchar_t *module); 
    177179 
    178180  struct service_controller { 
  • service/cli_parser.hpp

    rfb7e36a r9b9be81  
    5757      ("path", po::value<std::wstring>()->default_value(_T("")), "Path of key to work with.") 
    5858      ("key", po::value<std::wstring>()->default_value(_T("")), "Key to work with.") 
    59       ("set", po::value<std::wstring>(), "Set a key and path to a given value.") 
     59      ("set", po::value<std::wstring>()->implicit_value(_T("")), "Set a key and path to a given value.") 
    6060      ("switch", po::value<std::wstring>(), "Set default context to use (similar to migrate but does NOT copy values)") 
    6161      ("show", "Set a value given a key and path.") 
     
    129129 
    130130      if (vm.count("settings")) { 
    131         mainClient.set_console_log(); 
    132131        return parse_settings(argc-1, &argv[1]); 
    133132      } 
     
    176175      po::store(po::parse_command_line(argc, argv, all), vm); 
    177176      po::notify(vm); 
     177 
     178      if (debug) 
     179        mainClient.set_console_log(); 
    178180 
    179181      if (process_common_options()) 
  • service/core_api.cpp

    ra629015 r9b9be81  
    250250  try { 
    251251    settings_manager::get_settings()->set_string(section, key, value); 
     252  } catch (const std::exception &e) { 
     253    LOG_ERROR_STD(_T("Failed to setString: ") + key + _T(": ") + utf8::cvt<std::wstring>(e.what())); 
     254    return NSCAPI::hasFailed; 
    252255  } catch (...) { 
    253256    LOG_ERROR_STD(_T("Failed to setString: ") + key); 
     
    398401 
    399402 
     403NSCAPI::errorReturn NSAPIReload(const wchar_t *module) { 
     404  try { 
     405    return mainClient.reload(module); 
     406  } catch (...) { 
     407    LOG_ERROR_STD(_T("Failed to reload: ") + module); 
     408    return NSCAPI::hasFailed; 
     409  } 
     410  return NSCAPI::isSuccess; 
     411} 
     412 
    400413NSCAPI::errorReturn NSAPISettingsSave(void) { 
    401414  try { 
     
    410423  return NSCAPI::isSuccess; 
    411424} 
     425 
    412426 
    413427 
     
    482496  if (wcscasecmp(buffer, _T("NSAPIRegisterRoutingListener")) == 0) 
    483497    return reinterpret_cast<LPVOID>(&NSAPIRegisterRoutingListener); 
     498  if (wcscasecmp(buffer, _T("NSAPIReload")) == 0) 
     499    return reinterpret_cast<LPVOID>(&NSAPIReload); 
    484500 
    485501  LOG_ERROR_STD(_T("Function not found: ") + buffer); 
  • service/core_api.h

    ra629015 r9b9be81  
    6565NSCAPI::errorReturn NSAPIRegisterSubmissionListener(unsigned int plugin_id, const wchar_t* channel); 
    6666NSCAPI::errorReturn NSAPIRegisterRoutingListener(unsigned int plugin_id, const wchar_t* channel); 
     67NSCAPI::errorReturn NSAPIReload(const wchar_t*); 
  • service/settings_client.hpp

    rfb7e36a r9b9be81  
    1212 
    1313  public: 
    14     settings_client(NSClient* core) : core_(core) {} 
     14    settings_client(NSClient* core) : core_(core), default_(false) {} 
    1515 
    1616    std::wstring get_source() { 
     
    2929        return; 
    3030      } 
    31       if (default_) 
     31      if (default_) { 
     32        std::wcout << _T("Adding default values") << std::endl; 
    3233        settings_manager::get_core()->update_defaults(); 
     34      } 
    3335    } 
    3436 
Note: See TracChangeset for help on using the changeset viewer.