int NSCPClient::clp_handler_impl::send(connection_data &con, ::NSCPIPC::Common_MessageTypes type, const std::string &request_message, std::string &response_message) { NSCPIPC::PayloadMessage request_payload; nscp::packet request_packet; request_payload.set_type(type); request_payload.set_message(request_message); request_packet.add_payload(request_payload.SerializeAsString()); nscp::packet response_packet = send(con, request_packet); NSCPIPC::PayloadMessage response_payload; std::string tmp; if (response_packet.get_error(tmp)) { NSCPIPC::ErrorMessage error; error.ParseFromString(tmp); for (int i=0;i<error.error_size();i++) NSC_LOG_ERROR("Invalid response: " + error.error(i).message()); return NSCAPI::hasFailed; } else if (response_packet.get_payload(tmp)) { response_payload.ParseFromString(tmp); response_message = response_payload.message(); } else { NSC_LOG_ERROR("Invalid response"); return NSCAPI::hasFailed; } return NSCAPI::isSuccess; }
std::string SyslogClient::parse_priority(std::string severity, std::string facility) { syslog_map::const_iterator cit1 = facilities.find(facility); if (cit1 == facilities.end()) { NSC_LOG_ERROR("Undefined facility: " + facility); return "<0>"; } syslog_map::const_iterator cit2 = severities.find(severity); if (cit2 == severities.end()) { NSC_LOG_ERROR("Undefined severity: " + severity); return "<0>"; } std::stringstream ss; ss << '<' << (cit1->second*8+cit2->second) << '>'; return ss.str(); }
void CheckExternalScripts::add_wrapping(std::string key, std::string command) { if (!provider_) { NSC_LOG_ERROR("Failed to add: " + key); return; } add_command(key, provider_->generate_wrapped_command(command)); }
void smtp_client::connection::resolved(boost::system::error_code ec,boost::asio::ip::tcp::resolver::iterator iter) { if (ec) { NSC_LOG_ERROR("smtp failed resolving: " + ec.message()); boost::lock_guard<boost::mutex> lg(sc->m); sc->active_connection.reset(); return; } if (iter == boost::asio::ip::tcp::resolver::iterator()) { NSC_LOG_ERROR("smtp ran out of server addresses"); boost::lock_guard<boost::mutex> lg(sc->m); sc->active_connection.reset(); return; } NSC_DEBUG_MSG("smtp connecting to " + iter->endpoint().address().to_string()); serv.async_connect(*iter, boost::bind(&connection::connected, shared_from_this(), iter, _1)); }
long long read_mem_line(std::stringstream &iss) { std::string unit; unsigned long long value; iss >> value >> unit; if (unit == "kB") { value*=1024; } else if (!unit.empty()) { NSC_LOG_ERROR("Invalid memory unit: " + unit); } return value; }
bool Scheduler::handle_schedule(schedules::target_object item) { try { std::string response; nscapi::core_helper ch(get_core(), get_id()); if (!ch.simple_query(item->command.c_str(), item->arguments, response)) { NSC_LOG_ERROR("Failed to execute: " + item->command); if (item->channel.empty()) { NSC_LOG_ERROR_WA("No channel specified for ", item->get_alias()); return true; } nscapi::protobuf::functions::create_simple_submit_request(item->channel, item->command, NSCAPI::query_return_codes::returnUNKNOWN, "Command was not found: " + item->command, "", response); std::string result; get_core()->submit_message(item->channel, response, result); return true; } Plugin::QueryResponseMessage resp_msg; resp_msg.ParseFromString(response); Plugin::QueryResponseMessage resp_msg_send; resp_msg_send.mutable_header()->CopyFrom(resp_msg.header()); BOOST_FOREACH(const Plugin::QueryResponseMessage::Response &p, resp_msg.payload()) { if (nscapi::report::matches(item->report, nscapi::protobuf::functions::gbp_to_nagios_status(p.result()))) resp_msg_send.add_payload()->CopyFrom(p); } if (resp_msg_send.payload_size() > 0) { if (item->channel.empty()) { NSC_LOG_ERROR_STD("No channel specified for " + item->get_alias() + " mssage will not be sent."); return true; } nscapi::protobuf::functions::make_submit_from_query(response, item->channel, item->get_alias(), item->target_id, item->source_id); std::string result; if (!get_core()->submit_message(item->channel, response, result)) { NSC_LOG_ERROR_STD("Failed to submit: " + item->get_alias()); return true; } std::string error; if (!nscapi::protobuf::functions::parse_simple_submit_response(result, error)) { NSC_LOG_ERROR_STD("Failed to submit " + item->get_alias() + ": " + error); return true; } } else { NSC_DEBUG_MSG("Filter not matched for: " + item->get_alias() + " so nothing is reported"); } return true; } catch (nscapi::nscapi_exception &e) { NSC_LOG_ERROR_EXR("Failed to register command: ", e); return false; } catch (std::exception &e) { NSC_LOG_ERROR_EXR("Exception: ", e); return false; } catch (...) { NSC_LOG_ERROR_EX(item->get_alias()); return false; } }
void smtp_client::connection::sent(boost::shared_ptr<boost::asio::const_buffers_1>, boost::system::error_code ec, size_t) { if (ec) { NSC_LOG_ERROR("smtp failure in reading: " + ec.message()); boost::lock_guard<boost::mutex> lg(sc->m); if (cur) sc->ready.push_back(cur); sc->active_connection.reset(); return; } async_read_response(); }
void smtp_client::connection::connected(boost::asio::ip::tcp::resolver::iterator iter, boost::system::error_code ec) { if (ec) { NSC_LOG_ERROR("smtp failed to connect to " + iter->endpoint().address().to_string() + ": " + ec.message()); iter++; resolved(boost::system::error_code(), iter); return; } NSC_DEBUG_MSG("smtp connected to " + iter->endpoint().address().to_string()); state = BANNER; async_read_response(); }
std::string CheckExternalScripts::generate_wrapped_command(std::string command) { strEx::s::token tok = strEx::s::getToken(command, ' '); std::string::size_type pos = tok.first.find_last_of("."); std::string type = "none"; if (pos != std::wstring::npos) type = tok.first.substr(pos+1); std::string tpl = wrappings_[type]; if (tpl.empty()) { NSC_LOG_ERROR("Failed to find wrapping for type: " + type); } else { strEx::replace(tpl, "%SCRIPT%", tok.first); strEx::replace(tpl, "%ARGS%", tok.second); return tpl; } return ""; }
void NSClientSocket::onAccept(simpleSocket::Socket client) { if (!inAllowedHosts(client.getAddrString())) { NSC_LOG_ERROR("Unothorized access from: " + client.getAddrString()); client.close(); return; } simpleSocket::DataBuffer db; client.readAll(db); if (db.getLength() > 0) { std::string incoming(db.getBuffer(), db.getLength()); NSC_DEBUG_MSG_STD("Incoming data: " + incoming); std::string response = parseRequest(incoming); NSC_DEBUG_MSG("Outgoing data: " + response); client.send(response.c_str(), static_cast<int>(response.length()), 0); } client.close(); }
bool CheckMKClient::add_script(std::string alias, std::string file) { try { if (file.empty()) { file = alias; alias = ""; } boost::optional<boost::filesystem::path> ofile = lua::lua_script::find_script(root_, file); if (!ofile) return false; scripts_->add(alias, ofile->string()); return true; } catch (...) { NSC_LOG_ERROR("Could not load script: " + file); } return false; }
NSCAPI::nagiosReturn NSHandleCommand(const char* request_buffer, const unsigned int request_buffer_len, char** reply_buffer, unsigned int *reply_buffer_len) { try { std::string request(request_buffer, request_buffer_len), reply; NSCAPI::nagiosReturn retCode = instance->handleRAWCommand(request, reply); helpers::wrap_string(reply, reply_buffer, reply_buffer_len); if (!nscapi::plugin_helper::isMyNagiosReturn(retCode)) { NSC_LOG_ERROR("A module returned an invalid return code"); } return retCode; } catch (const std::exception &e) { NSC_LOG_ERROR_EXR("NSHandleCommand", e); return NSCAPI::returnUNKNOWN; } catch (...) { NSC_LOG_ERROR_EX("NSHandleCommand"); return NSCAPI::returnUNKNOWN; } return NSCAPI::returnIgnored; }
std::list<nscp::packet> DistributedClient::send_nossl(std::string host, int timeout, const std::list<nscp::packet> &chunks) { zmq::context_t context(1); zeromq::zeromq_client_handshake_reader handshaker("0987654321", nscp::factory::create_message_envelope_request(0)); zeromq::zeromq_client client(zeromq::zeromq_client::connection_info(host, timeout), &handshaker, &context); client.connect(); std::list<nscp::packet> responses; NSC_DEBUG_MSG_STD(_T("Sending data: ") + to_wstring(chunks.size())); BOOST_FOREACH(const nscp::packet packet, chunks) { zeromq::zeromq_client_message_reader reader(&handshaker, packet); if (client.send(&reader)) { NSC_DEBUG_MSG(_T("Got response: ") + to_wstring(reader.response.signature.payload_type)); responses.push_back(reader.response); } else { NSC_LOG_ERROR(_T("Failed to read response!")); responses.push_back(nscp::factory::create_error(_T("Failed to send data to server."))); } }
void CheckExternalScripts::add_command(std::string key, std::string arg) { try { if (!provider_) { NSC_LOG_ERROR("Failed to add (no provider): " + key); return; } provider_->add_command(key, arg); if (arg.find("$ARG") != std::string::npos) { if (!allowArgs_) { NSC_DEBUG_MSG_STD("Detected a $ARG??$ expression with allowed arguments flag set to false (perhaps this is not the intent)"); } } if (arg.find("%ARG") != std::string::npos) { if (!allowArgs_) { NSC_DEBUG_MSG_STD("Detected a %ARG??% expression with allowed arguments flag set to false (perhaps this is not the intent)"); } } } catch (const std::exception &e) { NSC_LOG_ERROR_EXR("Failed to add: " + key, e); } catch (...) { NSC_LOG_ERROR_EX("Failed to add: " + key); } }
void DistributedClient::setup(client::configuration &config, const ::Plugin::Common_Header& header) { boost::shared_ptr<clp_handler_impl> handler = boost::shared_ptr<clp_handler_impl>(new clp_handler_impl(this)); add_local_options(config.local, config.data); config.data->recipient.id = header.recipient_id(); std::wstring recipient = utf8::cvt<std::wstring>(config.data->recipient.id); if (!targets.has_object(recipient)) { NSC_LOG_ERROR(_T("Target not found (using default): ") + recipient); recipient = _T("default"); } nscapi::targets::optional_target_object opt = targets.find_object(recipient); if (opt) { nscapi::targets::target_object t = *opt; nscapi::functions::destination_container def = t.to_destination_container(); config.data->recipient.apply(def); } config.data->host_self.id = "self"; //config.data->host_self.host = hostname_; config.target_lookup = handler; config.handler = handler; }
log_lock() : lock(thread_support::mutex, boost::get_system_time() + boost::posix_time::seconds(2)) { if (!lock.owns_lock()) NSC_LOG_ERROR("Failed to get mutex: thread_locker"); }
nrpe::packet handler_impl::handle(nrpe::packet p) { strEx::s::token cmd = strEx::s::getToken(p.getPayload(), '!'); if (cmd.first == "_NRPE_CHECK") { return nrpe::packet::create_response(NSCAPI::returnOK, "I (" + utf8::cvt<std::string>(nscapi::plugin_singleton->get_core()->getApplicationVersionString()) + ") seem to be doing fine...", p.get_payload_length()); } if (!allowArgs_) { if (!cmd.second.empty()) { NSC_LOG_ERROR("Request contained arguments (not currently allowed, check the allow arguments option)."); throw nrpe::nrpe_exception("Request contained arguments (not currently allowed, check the allow arguments option)."); } } if (!allowNasty_) { if (cmd.first.find_first_of(NASTY_METACHARS) != std::wstring::npos) { NSC_LOG_ERROR("Request command contained illegal metachars!"); throw nrpe::nrpe_exception("Request command contained illegal metachars!"); } if (cmd.second.find_first_of(NASTY_METACHARS) != std::wstring::npos) { NSC_LOG_ERROR("Request arguments contained illegal metachars!"); throw nrpe::nrpe_exception("Request command contained illegal metachars!"); } } std::string wmsg, wperf; NSCAPI::nagiosReturn ret = -3; try { if (encoding_.empty()) { ret = nscapi::core_helper::simple_query_from_nrpe(utf8::cvt<std::string>(utf8::to_unicode(cmd.first)), utf8::cvt<std::string>(utf8::to_unicode(cmd.second)), wmsg, wperf); } else { ret = nscapi::core_helper::simple_query_from_nrpe(utf8::cvt<std::string>(utf8::from_encoding(cmd.first, encoding_)), utf8::cvt<std::string>(utf8::from_encoding(cmd.second, encoding_)), wmsg, wperf); } } catch (...) { return nrpe::packet::create_response(NSCAPI::returnUNKNOWN, "UNKNOWN: Internal exception", p.get_payload_length()); } switch (ret) { case NSCAPI::returnInvalidBufferLen: return nrpe::packet::create_response(NSCAPI::returnUNKNOWN, "UNKNOWN: Return buffer to small to handle this command.", p.get_payload_length()); case NSCAPI::returnIgnored: return nrpe::packet::create_response(NSCAPI::returnUNKNOWN, "UNKNOWN: No handler for that command.", p.get_payload_length()); case NSCAPI::returnOK: case NSCAPI::returnWARN: case NSCAPI::returnCRIT: case NSCAPI::returnUNKNOWN: break; default: return nrpe::packet::create_response(NSCAPI::returnUNKNOWN, "UNKNOWN: Internal error.", p.get_payload_length()); } std::string data,msg, perf; if (encoding_.empty()) { msg = utf8::to_system(utf8::cvt<std::wstring>(wmsg)); perf = utf8::to_system(utf8::cvt<std::wstring>(wperf)); } else { msg = utf8::to_encoding(utf8::cvt<std::wstring>(wmsg), encoding_); perf = utf8::to_encoding(utf8::cvt<std::wstring>(wperf), encoding_); } const unsigned int max_len = p.get_payload_length()-1; if (msg.length() >= max_len) { data = msg.substr(0, max_len); } else if (perf.empty() || noPerfData_) { data = msg; } else if (msg.length() + perf.length() + 1 > max_len) { data = msg; } else { data = msg + "|" + perf; } return nrpe::packet::create_response(ret, data, p.get_payload_length()); }
bool Scheduler::loadModuleEx(std::string alias, NSCAPI::moduleLoadMode mode) { if (mode == NSCAPI::reloadStart) { scheduler_.unset_handler(); scheduler_.clear(); } sh::settings_registry settings(get_settings_proxy()); settings.set_alias(alias, "scheduler"); schedules_.set_path(settings.alias().get_settings_path("schedules")); settings.alias().add_path_to_settings() ("SCHEDULER SECTION", "Section for the Scheduler module.") ; settings.alias().add_key_to_settings() ("threads", sh::int_fun_key<unsigned int>(boost::bind(&schedules::scheduler::set_threads, &scheduler_, _1), 5), "THREAD COUNT", "Number of threads to use.") ; settings.alias().add_path_to_settings() ("schedules", sh::fun_values_path(boost::bind(&Scheduler::add_schedule, this, _1, _2)), "SCHEDULER SECTION", "Section for the Scheduler module.", "SCHEDULE", "For more configuration options add a dedicated section") ; settings.alias().add_templates() ("schedules", "plus", "Add a simple schedule", "Add a simple scheduled job for passive monitoring", "{" "\"fields\": [ " " { \"id\": \"alias\", \"title\" : \"Alias\", \"type\" : \"input\", \"desc\" : \"This will identify the command\"} , " " { \"id\": \"command\", \"title\" : \"Command\", \"type\" : \"data-choice\", \"desc\" : \"The name of the command to execute\",\"exec\" : \"CheckExternalScripts list --json --query\" } , " " { \"id\": \"args\", \"title\" : \"Arguments\", \"type\" : \"input\", \"desc\" : \"Command line arguments for the command\" } , " " { \"id\": \"cmd\", \"key\" : \"command\", \"title\" : \"A\", \"type\" : \"hidden\", \"desc\" : \"A\" } " " ], " "\"events\": { " "\"onSave\": \"(function (node) { node.save_path = self.path; var f = node.get_field('cmd'); f.key = node.get_field('alias').value(); var val = node.get_field('command').value(); if (node.get_field('args').value()) { val += ' ' + node.get_field('args').value(); }; f.value(val)})\"" "}" "}") ; settings.register_all(); settings.notify(); schedules_.ensure_default(); BOOST_FOREACH(const schedules::schedule_handler::object_list_type::value_type &o, schedules_.get_object_list()) { if (o->duration && (*o->duration).total_seconds() == 0) { NSC_LOG_ERROR("WE cant add schedules with 0 duration: " + o->to_string()); continue; } if (o->duration && o->schedule) { NSC_LOG_ERROR("WE cant add schedules with both duration and schedule: " + o->to_string()); continue; } if (!o->duration && !o->schedule) { NSC_LOG_ERROR("WE need wither duration or schedule: " + o->to_string()); continue; } NSC_DEBUG_MSG("Adding scheduled item: " + o->to_string()); scheduler_.add_task(o); } if (mode == NSCAPI::normalStart) { scheduler_.set_handler(this); scheduler_.start(); } if (mode == NSCAPI::reloadStart) { scheduler_.set_handler(this); scheduler_.start(); } return true; }
void Scheduler::on_error(std::string error) { NSC_LOG_ERROR(error); }
void smtp_client::connection::got_response(std::string resp, boost::system::error_code ec, size_t bytes) { if (ec) { NSC_LOG_ERROR("smtp failure in reading: " + ec.message()); boost::lock_guard<boost::mutex> lg(sc->m); if (cur) sc->ready.push_back(cur); sc->active_connection.reset(); return; } std::string line; line.reserve(bytes); for (size_t i = 0; i < bytes; i++) line += char(readbuf.sbumpc()); resp += line; if (line.length() >= 4 && line[3] == '-') { boost::asio::async_read_until(serv, readbuf, "\r\n", boost::bind(&connection::got_response, shared_from_this(), resp, _1, _2)); return; } NSC_DEBUG_MSG("smtp read " + resp); bool broken_resp = resp.empty() || !('2' <= resp[0] && resp[0] <= '5') || (resp[0] == '3' && (state != DATA || resp.substr(0,3) != "354")); // FIXME deferral / drop-on-the-floor notifications if (broken_resp || resp[0] == '4') { boost::lock_guard<boost::mutex> lg(sc->m); if (cur) sc->deferred.push_back(cur); } if (broken_resp || state == QUIT) { NSC_LOG_ERROR("smtp terminating"); boost::lock_guard<boost::mutex> lg(sc->m); sc->active_connection.reset(); return; } if ((resp[0] == '4' || resp[0] == '5' || state == DATA_354) && (resp.substr(0,3) != "502" || state != EHLO)) { cur.reset(); if (sc->ready.empty() || state <= RSET) { state = QUIT; send_line("QUIT"); } else { state = RSET; send_line("RSET"); } return; } assert(!resp.empty()); switch (state) { case BANNER: assert(resp[0] == '2'); state = EHLO; send_line("EHLO " + config["canonical-name"]); break; case EHLO: if (resp.substr(0,3) == "502") { state = HELO; send_line("HELO" + config["canonical-name"]); break; } assert(resp[0] == '2'); /* passthrough */ case HELO: case RSET: assert(resp[0] == '2'); assert(!cur); { boost::lock_guard<boost::mutex> lg(sc->m); if (sc->ready.empty()) { state = QUIT; send_line("QUIT"); break; } cur = sc->ready.front(); sc->ready.pop_front(); } assert(cur); state = MAIL_FROM; send_line("MAIL FROM: <" + cur->sender + ">"); break; case MAIL_FROM: assert(resp[0] == '2'); assert(cur); state = RCPT_TO; send_line("RCPT TO: <" + cur->recipient + ">"); break; case RCPT_TO: assert(resp[0] == '2'); assert(cur); state = DATA; send_line("DATA"); break; case DATA: assert(resp.substr(0,3) == "354"); assert(cur); state = DATA_354; send_raw(cur->data + ".\r\n"); break; case DATA_354: case QUIT: assert(0); // handled above break; } }