source: nscp/modules/NSCAClient/NSCAClient.cpp @ b67d231

0.4.00.4.10.4.2
Last change on this file since b67d231 was b67d231, checked in by Michael Medin <michael@…>, 12 months ago
  • Added log level = off to disable logging.
  • Added option in NSCAClient to hostname (auto-lc) to use lower case version of hostname. #533
  • Reworked how commands are read. If a command is defined without a section (default) no section will be added and instead a comment will be addded on how to add the section. This should (I hope) resolve the "missing command" for good.
  • Improved error messages for missing commands
  • Fixed scientific notation on performance data (#)
  • Property mode set to 100644
File size: 17.2 KB
Line 
1/**************************************************************************
2*   Copyright (C) 2004-2007 by Michael Medin <michael@medin.name>         *
3*                                                                         *
4*   This code is part of NSClient++ - http://trac.nakednuns.org/nscp      *
5*                                                                         *
6*   This program is free software; you can redistribute it and/or modify  *
7*   it under the terms of the GNU General Public License as published by  *
8*   the Free Software Foundation; either version 2 of the License, or     *
9*   (at your option) any later version.                                   *
10*                                                                         *
11*   This program is distributed in the hope that it will be useful,       *
12*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14*   GNU General Public License for more details.                          *
15*                                                                         *
16*   You should have received a copy of the GNU General Public License     *
17*   along with this program; if not, write to the                         *
18*   Free Software Foundation, Inc.,                                       *
19*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
20***************************************************************************/
21#include "stdafx.h"
22#include "NSCAClient.h"
23
24#include <utils.h>
25#include <strEx.h>
26
27#include <nsca/nsca_enrypt.hpp>
28#include <nsca/nsca_packet.hpp>
29#include <nsca/nsca_socket.hpp>
30
31#include <settings/client/settings_client.hpp>
32#include <nscapi/nscapi_protobuf_functions.hpp>
33
34namespace sh = nscapi::settings_helper;
35
36const std::wstring NSCAAgent::command_prefix = _T("nsca");
37/**
38 * Default c-tor
39 * @return
40 */
41NSCAAgent::NSCAAgent() {}
42
43/**
44 * Default d-tor
45 * @return
46 */
47NSCAAgent::~NSCAAgent() {}
48
49/**
50 * Load (initiate) module.
51 * Start the background collector thread and let it run until unloadModule() is called.
52 * @return true
53 */
54bool NSCAAgent::loadModule() {
55        return false;
56}
57
58bool NSCAAgent::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) {
59
60        try {
61
62                sh::settings_registry settings(get_settings_proxy());
63                settings.set_alias(_T("NSCA"), alias, _T("client"));
64                target_path = settings.alias().get_settings_path(_T("targets"));
65
66                settings.alias().add_path_to_settings()
67                        (_T("NSCA CLIENT SECTION"), _T("Section for NSCA passive check module."))
68
69                        (_T("handlers"), sh::fun_values_path(boost::bind(&NSCAAgent::add_command, this, _1, _2)),
70                        _T("CLIENT HANDLER SECTION"), _T(""))
71
72                        (_T("targets"), sh::fun_values_path(boost::bind(&NSCAAgent::add_target, this, _1, _2)),
73                        _T("REMOTE TARGET DEFINITIONS"), _T(""))
74                        ;
75
76                settings.alias().add_key_to_settings()
77                        (_T("hostname"), sh::string_key(&hostname_, "auto"),
78                        _T("HOSTNAME"), _T("The host name of this host if set to blank (default) the windows name of the computer will be used."))
79
80                        (_T("channel"), sh::wstring_key(&channel_, _T("NSCA")),
81                        _T("CHANNEL"), _T("The channel to listen to."))
82
83                        (_T("delay"), sh::string_fun_key<std::wstring>(boost::bind(&NSCAAgent::set_delay, this, _1), _T("0")),
84                        _T("DELAY"), _T(""), true)
85                        ;
86
87                settings.register_all();
88                settings.notify();
89
90                targets.add_missing(get_settings_proxy(), target_path, _T("default"), _T(""), true);
91
92
93                get_core()->registerSubmissionListener(get_id(), channel_);
94
95                register_command(_T("nsca_query"), _T("Check remote NRPE host"));
96                register_command(_T("nsca_submit"), _T("Submit (via query) remote NRPE host"));
97                register_command(_T("nsca_forward"), _T("Forward query to remote NRPE host"));
98                register_command(_T("nsca_exec"), _T("Execute (via query) remote NRPE host"));
99                register_command(_T("nsca_help"), _T("Help on using NRPE Client"));
100
101                if (hostname_ == "auto") {
102                        hostname_ = boost::asio::ip::host_name();
103                } else if (hostname_ == "auto-lc") {
104                        hostname_ = boost::asio::ip::host_name();
105                        std::transform(hostname_.begin(), hostname_.end(), hostname_.begin(), ::tolower);
106                } else {
107                        std::pair<std::string,std::string> dn = strEx::split<std::string>(boost::asio::ip::host_name(), ".");
108
109                        try {
110                                boost::asio::io_service svc;
111                                boost::asio::ip::tcp::resolver resolver (svc);
112                                boost::asio::ip::tcp::resolver::query query (boost::asio::ip::host_name(), "");
113                                boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve (query), end;
114
115                                std::string s;
116                                while (iter != end) {
117                                        s += iter->host_name();
118                                        s += " - ";
119                                        s += iter->endpoint().address().to_string();
120                                        iter++;
121                                }
122                        } catch (const std::exception& e) {
123                                NSC_LOG_ERROR_STD(_T("Failed to resolve: ") + utf8::to_unicode(e.what()));
124                        }
125
126
127                        strEx::replace(hostname_, "${host}", dn.first);
128                        strEx::replace(hostname_, "${domain}", dn.second);
129                }
130        } catch (nscapi::nscapi_exception &e) {
131                NSC_LOG_ERROR_STD(_T("NSClient API exception: ") + utf8::to_unicode(e.what()));
132                return false;
133        } catch (std::exception &e) {
134                NSC_LOG_ERROR_STD(_T("Exception caught: ") + utf8::to_unicode(e.what()));
135                return false;
136        } catch (...) {
137                NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>"));
138                return false;
139        }
140        return true;
141}
142
143std::wstring NSCAAgent::getCryptos() {
144        std::wstring ret = _T("{");
145        for (int i=0;i<LAST_ENCRYPTION_ID;i++) {
146                if (nsca::nsca_encrypt::hasEncryption(i)) {
147                        std::wstring name;
148                        try {
149                                boost::shared_ptr<nsca::nsca_encrypt::any_encryption> core(nsca::nsca_encrypt::get_encryption_core(i));
150                                if (core == NULL)
151                                        name = _T("Broken<NULL>");
152                                else
153                                        name = utf8::to_unicode(core->getName());
154                        } catch (nsca::nsca_encrypt::encryption_exception &e) {
155                                name = utf8::to_unicode(e.what());
156                        }
157                        if (ret.size() > 1)
158                                ret += _T(", ");
159                        ret += strEx::itos(i) + _T("=") + name;
160                }
161        }
162        return ret + _T("}");
163}
164
165std::string get_command(std::string alias, std::string command = "") {
166        if (!alias.empty())
167                return alias;
168        if (!command.empty())
169                return command;
170        return "host_check";
171}
172
173//////////////////////////////////////////////////////////////////////////
174// Settings helpers
175//
176
177void NSCAAgent::add_target(std::wstring key, std::wstring arg) {
178        try {
179                targets.add(get_settings_proxy(), target_path , key, arg);
180        } catch (const std::exception &e) {
181                NSC_LOG_ERROR_STD(_T("Failed to add target: ") + key + _T(", ") + utf8::to_unicode(e.what()));
182        } catch (...) {
183                NSC_LOG_ERROR_STD(_T("Failed to add target: ") + key);
184        }
185}
186
187void NSCAAgent::add_command(std::wstring name, std::wstring args) {
188        try {
189                std::wstring key = commands.add_command(name, args);
190                if (!key.empty())
191                        register_command(key.c_str(), _T("NSCA relay for: ") + name);
192        } catch (boost::program_options::validation_error &e) {
193                NSC_LOG_ERROR_STD(_T("Could not add command ") + name + _T(": ") + utf8::to_unicode(e.what()));
194        } catch (...) {
195                NSC_LOG_ERROR_STD(_T("Could not add command ") + name);
196        }
197}
198
199/**
200 * Unload (terminate) module.
201 * Attempt to stop the background processing thread.
202 * @return true if successfully, false if not (if not things might be bad)
203 */
204bool NSCAAgent::unloadModule() {
205        return true;
206}
207
208NSCAPI::nagiosReturn NSCAAgent::handleRAWCommand(const wchar_t* char_command, const std::string &request, std::string &result) {
209        std::wstring cmd = client::command_line_parser::parse_command(char_command, command_prefix);
210
211        Plugin::QueryRequestMessage message;
212        message.ParseFromString(request);
213
214        client::configuration config;
215        setup(config, message.header());
216
217        return commands.process_query(cmd, config, message, result);
218}
219
220NSCAPI::nagiosReturn NSCAAgent::commandRAWLineExec(const wchar_t* char_command, const std::string &request, std::string &result) {
221        std::wstring cmd = client::command_line_parser::parse_command(char_command, command_prefix);
222
223        Plugin::ExecuteRequestMessage message;
224        message.ParseFromString(request);
225
226        client::configuration config;
227        setup(config, message.header());
228
229        return commands.process_exec(cmd, config, message, result);
230}
231
232NSCAPI::nagiosReturn NSCAAgent::handleRAWNotification(const wchar_t* channel, std::string request, std::string &result) {
233        Plugin::SubmitRequestMessage message;
234        message.ParseFromString(request);
235
236        client::configuration config;
237        setup(config, message.header());
238
239        return client::command_line_parser::do_relay_submit(config, message, result);
240}
241
242//////////////////////////////////////////////////////////////////////////
243// Parser setup/Helpers
244//
245
246void NSCAAgent::add_local_options(po::options_description &desc, client::configuration::data_type data) {
247        desc.add_options()
248                ("encryption,e", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "encryption", _1)),
249                "Length of payload (has to be same as on the server)")
250
251                ("payload-length,l", po::value<unsigned int>()->notifier(boost::bind(&nscapi::functions::destination_container::set_int_data, &data->recipient, "payload length", _1)),
252                "Length of payload (has to be same as on the server)")
253
254                ("timeout", po::value<unsigned int>()->notifier(boost::bind(&nscapi::functions::destination_container::set_int_data, &data->recipient, "timeout", _1)),
255                "")
256
257                ("password", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "password", _1)),
258                "Password")
259
260                ("source-host", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->host_self, "host", _1)),
261                "Source/sender host name (default is auto which means use the name of the actual host)")
262
263                ("sender-host", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->host_self, "host", _1)),
264                "Source/sender host name (default is auto which means use the name of the actual host)")
265
266                ("time-offset", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "time offset", _1)),
267                "")
268                ;
269}
270
271void NSCAAgent::setup(client::configuration &config, const ::Plugin::Common_Header& header) {
272        boost::shared_ptr<clp_handler_impl> handler(new clp_handler_impl(this));
273        add_local_options(config.local, config.data);
274
275        config.data->recipient.id = header.recipient_id();
276        std::wstring recipient = utf8::cvt<std::wstring>(config.data->recipient.id);
277        if (!targets.has_object(recipient)) {
278                recipient = _T("default");
279        }
280        nscapi::targets::optional_target_object opt = targets.find_object(recipient);
281
282        if (opt) {
283                nscapi::targets::target_object t = *opt;
284                nscapi::functions::destination_container def = t.to_destination_container();
285                config.data->recipient.apply(def);
286        }
287        config.data->host_self.id = "self";
288        config.data->host_self.address.host = hostname_;
289
290        config.target_lookup = handler;
291        config.handler = handler;
292}
293
294NSCAAgent::connection_data NSCAAgent::parse_header(const ::Plugin::Common_Header &header, client::configuration::data_type data) {
295        nscapi::functions::destination_container recipient, sender;
296        nscapi::functions::parse_destination(header, header.recipient_id(), recipient, true);
297        nscapi::functions::parse_destination(header, header.sender_id(), sender, true);
298        return connection_data(recipient, data->recipient, sender);
299}
300
301//////////////////////////////////////////////////////////////////////////
302// Parser implementations
303//
304
305int NSCAAgent::clp_handler_impl::query(client::configuration::data_type data, const Plugin::QueryRequestMessage &request_message, std::string &reply) {
306        const ::Plugin::Common_Header& request_header = request_message.header();
307        connection_data con = parse_header(request_header, data);
308
309        Plugin::QueryResponseMessage response_message;
310        nscapi::functions::make_return_header(response_message.mutable_header(), request_header);
311
312        std::list<nsca::packet> list;
313        for (int i=0;i < request_message.payload_size(); ++i) {
314                nsca::packet packet(con.sender_hostname, con.buffer_length, con.time_delta);
315                nscapi::functions::decoded_simple_command_data data = nscapi::functions::parse_simple_query_request(request_message.payload(i));
316                packet.code = 0;
317                packet.result = utf8::cvt<std::string>(data.command);
318                list.push_back(packet);
319        }
320
321        boost::tuple<int,std::wstring> ret = instance->send(con, list);
322
323        nscapi::functions::append_simple_query_response_payload(response_message.add_payload(), "TODO", ret.get<0>(), utf8::cvt<std::string>(ret.get<1>()), "");
324        response_message.SerializeToString(&reply);
325        return NSCAPI::isSuccess;
326}
327
328int NSCAAgent::clp_handler_impl::submit(client::configuration::data_type data, const Plugin::SubmitRequestMessage &request_message, std::string &reply) {
329        const ::Plugin::Common_Header& request_header = request_message.header();
330        connection_data con = parse_header(request_header, data);
331        std::wstring channel = utf8::cvt<std::wstring>(request_message.channel());
332
333        Plugin::SubmitResponseMessage response_message;
334        nscapi::functions::make_return_header(response_message.mutable_header(), request_header);
335
336        std::list<nsca::packet> list;
337
338        for (int i=0;i < request_message.payload_size(); ++i) {
339                nsca::packet packet(con.sender_hostname, con.buffer_length, con.time_delta);
340                std::wstring alias, msg, perf;
341                packet.code = nscapi::functions::parse_simple_submit_request_payload(request_message.payload(i), alias, msg, perf);
342                if (alias != _T("host_check"))
343                        packet.service = utf8::cvt<std::string>(alias);
344                if (perf.empty())
345                        packet.result = utf8::cvt<std::string>(msg);
346                else
347                        packet.result = utf8::cvt<std::string>(msg + _T("|") + perf);
348                list.push_back(packet);
349        }
350
351        boost::tuple<int,std::wstring> ret = instance->send(con, list);
352        nscapi::functions::append_simple_submit_response_payload(response_message.add_payload(), "TODO", ret.get<0>(), utf8::cvt<std::string>(ret.get<1>()));
353        response_message.SerializeToString(&reply);
354        return NSCAPI::isSuccess;
355}
356
357int NSCAAgent::clp_handler_impl::exec(client::configuration::data_type data, const Plugin::ExecuteRequestMessage &request_message, std::string &reply) {
358        const ::Plugin::Common_Header& request_header = request_message.header();
359        connection_data con = parse_header(request_header, data);
360
361        Plugin::ExecuteResponseMessage response_message;
362        nscapi::functions::make_return_header(response_message.mutable_header(), request_header);
363
364        std::list<nsca::packet> list;
365        for (int i=0;i < request_message.payload_size(); ++i) {
366                nsca::packet packet(con.sender_hostname, con.buffer_length, con.time_delta);
367                nscapi::functions::decoded_simple_command_data data = nscapi::functions::parse_simple_exec_request_payload(request_message.payload(i));
368                packet.code = 0;
369                if (data.command != _T("host_check"))
370                        packet.service = utf8::cvt<std::string>(data.command);
371                //packet.result = data.;
372                list.push_back(packet);
373        }
374        boost::tuple<int,std::wstring> ret = instance->send(con, list);
375        nscapi::functions::append_simple_exec_response_payload(response_message.add_payload(), "TODO", ret.get<0>(), utf8::cvt<std::string>(ret.get<1>()));
376        response_message.SerializeToString(&reply);
377        return NSCAPI::isSuccess;
378}
379
380//////////////////////////////////////////////////////////////////////////
381// Protocol implementations
382//
383
384boost::tuple<int,std::wstring> NSCAAgent::send(connection_data data, const std::list<nsca::packet> packets) {
385        try {
386                NSC_DEBUG_MSG_STD(_T("Connection details: ") + data.to_wstring());
387                boost::asio::io_service io_service;
388                nsca::socket socket(io_service);
389                socket.connect(data.host, data.port);
390                if (!socket.recv_iv(data.password, data.get_encryption(), boost::posix_time::seconds(data.timeout<5?30:data.timeout))) {
391                        NSC_LOG_ERROR_STD(_T("Failed to read iv"));
392                        return NSCAPI::hasFailed;
393                }
394                NSC_DEBUG_MSG_STD(_T("Got IV sending packets: ") + strEx::itos(packets.size()));
395                BOOST_FOREACH(const nsca::packet &packet, packets) {
396                        NSC_DEBUG_MSG_STD(_T("Sending (data): ") + utf8::cvt<std::wstring>(packet.to_string()));
397                        socket.send_nsca(packet, boost::posix_time::seconds(data.timeout));
398                }
399                socket.shutdown();
400                return boost::make_tuple(NSCAPI::returnUNKNOWN, _T(""));
401        } catch (const nsca::nsca_encrypt::encryption_exception &e) {
402                NSC_LOG_ERROR_STD(_T("NSCA Error: ") + utf8::to_unicode(e.what()));
403                return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("NSCA error: ") + utf8::to_unicode(e.what()));
404        } catch (const std::runtime_error &e) {
405                NSC_LOG_ERROR_STD(_T("Socket error: ") + utf8::to_unicode(e.what()));
406                return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("Socket error: ") + utf8::to_unicode(e.what()));
407        } catch (const std::exception &e) {
408                NSC_LOG_ERROR_STD(_T("Error: ") + utf8::to_unicode(e.what()));
409                return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("Error: ") + utf8::to_unicode(e.what()));
410        } catch (...) {
411                NSC_LOG_ERROR_STD(_T("Unknown exception when sending NSCA data: "));
412                return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("Unknown error -- REPORT THIS!"));
413        }
414}
415
416NSC_WRAP_DLL();
417NSC_WRAPPERS_MAIN_DEF(NSCAAgent);
418NSC_WRAPPERS_IGNORE_MSG_DEF();
419NSC_WRAPPERS_HANDLE_CMD_DEF();
420NSC_WRAPPERS_CLI_DEF();
421NSC_WRAPPERS_HANDLE_NOTIFICATION_DEF();
422
Note: See TracBrowser for help on using the repository browser.