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

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