source: nscp/modules/SyslogClient/SyslogClient.cpp @ 9853bc3

0.4.00.4.10.4.2
Last change on this file since 9853bc3 was 9853bc3, checked in by Michael Medin <michael@…>, 19 months ago
  • Fixed some NSCA issues (reading from new conf)
  • Fixed some linux build issues (related to refactoring)
  • 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 "SyslogClient.h"
23
24#include <utils.h>
25#include <list>
26#include <string>
27
28#include <boost/asio.hpp>
29
30#include <strEx.h>
31
32#include <settings/client/settings_client.hpp>
33
34namespace sh = nscapi::settings_helper;
35namespace ip = boost::asio::ip;
36
37/**
38 * Default c-tor
39 * @return
40 */
41SyslogClient::SyslogClient() {}
42
43/**
44 * Default d-tor
45 * @return
46 */
47SyslogClient::~SyslogClient() {}
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 SyslogClient::loadModule() {
55        return false;
56}
57bool SyslogClient::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) {
58
59        facilities["kernel"] = 0;
60        facilities["user"] = 1;
61        facilities["mail"] = 2;
62        facilities["system"] = 3;
63        facilities["security"] = 4;
64        facilities["internal"] = 5;
65        facilities["printer"] = 6;
66        facilities["news"] = 7;
67        facilities["UUCP"] = 8;
68        facilities["clock"] = 9;
69        facilities["authorization"] = 10;
70        facilities["FTP"] = 11;
71        facilities["NTP"] = 12;
72        facilities["audit"] = 13;
73        facilities["alert"] = 14;
74        facilities["clock"] = 15;
75        facilities["local0"] = 16;
76        facilities["local1"] = 17;
77        facilities["local2"] = 18;
78        facilities["local3"] = 19;
79        facilities["local4"] = 20;
80        facilities["local5"] = 21;
81        facilities["local6"] = 22;
82        facilities["local7"] = 23;
83        severities["emergency"] = 0;
84        severities["alert"] = 1;
85        severities["critical"] = 2;
86        severities["error"] = 3;
87        severities["warning"] = 4;
88        severities["notice"] = 5;
89        severities["informational"] = 6;
90        severities["debug"] = 7;
91
92        std::wstring severity, facility, tag_syntax, message_syntax;
93        std::wstring ok_severity, warn_severity, crit_severity, unknown_severity;
94        try {
95                sh::settings_registry settings(get_settings_proxy());
96                settings.set_alias(_T("syslog"), alias, _T("client"));
97                target_path = settings.alias().get_settings_path(_T("targets"));
98
99                settings.alias().add_path_to_settings()
100                        (_T("SYSLOG CLIENT SECTION"), _T("Section for SYSLOG passive check module."))
101                        (_T("handlers"), sh::fun_values_path(boost::bind(&SyslogClient::add_command, this, _1, _2)),
102                        _T("CLIENT HANDLER SECTION"), _T(""))
103
104                        (_T("targets"), sh::fun_values_path(boost::bind(&SyslogClient::add_target, this, _1, _2)),
105                        _T("REMOTE TARGET DEFINITIONS"), _T(""))
106                        ;
107
108                settings.alias().add_key_to_settings()
109                        (_T("hostname"), sh::string_key(&hostname_),
110                        _T("HOSTNAME"), _T("The host name of this host if set to blank (default) the windows name of the computer will be used."))
111
112                        (_T("channel"), sh::wstring_key(&channel_, _T("syslog")),
113                        _T("CHANNEL"), _T("The channel to listen to."))
114
115                        ;
116
117                settings.alias().add_key_to_settings(_T("targets/default"))
118
119                        (_T("severity"), sh::wpath_key(&severity, _T("error")),
120                        _T("SSL CERTIFICATE"), _T(""))
121
122                        (_T("facility"), sh::wpath_key(&facility, _T("kernel")),
123                        _T("SSL CERTIFICATE"), _T(""))
124
125                        (_T("tag_syntax"), sh::wpath_key(&tag_syntax, _T("NSCP")),
126                        _T("SSL CERTIFICATE"), _T(""))
127
128                        (_T("message_syntax"), sh::wpath_key(&message_syntax, _T("%message%")),
129                        _T("SSL CERTIFICATE"), _T(""))
130
131                        (_T("ok severity"), sh::wpath_key(&ok_severity, _T("informational")),
132                        _T("SSL CERTIFICATE"), _T(""))
133
134                        (_T("warning severity"), sh::wpath_key(&warn_severity, _T("warning")),
135                        _T("SSL CERTIFICATE"), _T(""))
136
137                        (_T("critical severity"), sh::wpath_key(&crit_severity, _T("critical")),
138                        _T("SSL CERTIFICATE"), _T(""))
139
140                        (_T("unknown severity"), sh::wpath_key(&unknown_severity, _T("emergency")),
141                        _T("SSL CERTIFICATE"), _T(""))
142
143                        ;
144
145                settings.register_all();
146                settings.notify();
147
148                get_core()->registerSubmissionListener(get_id(), channel_);
149
150                if (!targets.has_target(_T("default"))) {
151                        add_target(_T("default"), _T("default"));
152                        targets.rebuild();
153                }
154                nscapi::target_handler::optarget t = targets.find_target(_T("default"));
155                if (t) {
156                        if (!t->has_option("severity"))
157                                t->options[_T("severity")] = severity;
158                        if (!t->has_option("facility"))
159                                t->options[_T("facility")] = facility;
160                        if (!t->has_option("tag syntax"))
161                                t->options[_T("tag syntax")] = tag_syntax;
162                        if (!t->has_option("message syntax"))
163                                t->options[_T("message syntax")] = message_syntax;
164                        if (!t->has_option("ok severity"))
165                                t->options[_T("ok severity")] = ok_severity;
166                        if (!t->has_option("warning severity"))
167                                t->options[_T("warning severity")] = warn_severity;
168                        if (!t->has_option("critical severity"))
169                                t->options[_T("critical severity")] = crit_severity;
170                        if (!t->has_option("unknown severity"))
171                                t->options[_T("unknown severity")] = unknown_severity;
172                        targets.add(*t);
173                } else {
174                        NSC_LOG_ERROR(_T("Default target not found!"));
175                }
176
177        } catch (nscapi::nscapi_exception &e) {
178                NSC_LOG_ERROR_STD(_T("NSClient API exception: ") + utf8::to_unicode(e.what()));
179                return false;
180        } catch (std::exception &e) {
181                NSC_LOG_ERROR_STD(_T("Exception caught: ") + utf8::to_unicode(e.what()));
182                return false;
183        } catch (...) {
184                NSC_LOG_ERROR_STD(_T("Exception caught: <UNKNOWN EXCEPTION>"));
185                return false;
186        }
187        return true;
188}
189
190
191//////////////////////////////////////////////////////////////////////////
192// Settings helpers
193//
194
195void SyslogClient::add_target(std::wstring key, std::wstring arg) {
196        try {
197                targets.add(get_settings_proxy(), target_path , key, arg);
198        } catch (...) {
199                NSC_LOG_ERROR_STD(_T("Failed to add target: ") + key);
200        }
201}
202
203void SyslogClient::add_command(std::wstring name, std::wstring args) {
204        try {
205                std::wstring key = commands.add_command(name, args);
206                if (!key.empty())
207                        register_command(key.c_str(), _T("NRPE relay for: ") + name);
208        } catch (boost::program_options::validation_error &e) {
209                NSC_LOG_ERROR_STD(_T("Could not add command ") + name + _T(": ") + utf8::to_unicode(e.what()));
210        } catch (...) {
211                NSC_LOG_ERROR_STD(_T("Could not add command ") + name);
212        }
213}
214
215/**
216 * Unload (terminate) module.
217 * Attempt to stop the background processing thread.
218 * @return true if successfully, false if not (if not things might be bad)
219 */
220bool SyslogClient::unloadModule() {
221        return true;
222}
223
224NSCAPI::nagiosReturn SyslogClient::handleCommand(const std::wstring &target, const std::wstring &command, std::list<std::wstring> &arguments, std::wstring &message, std::wstring &perf) {
225        std::wstring cmd = client::command_line_parser::parse_command(command, _T("nsca"));
226
227        client::configuration config;
228        setup(config);
229        if (cmd == _T("query"))
230                return client::command_line_parser::query(config, cmd, arguments, message, perf);
231        if (cmd == _T("submit")) {
232                boost::tuple<int,std::wstring> result = client::command_line_parser::simple_submit(config, cmd, arguments);
233                message = result.get<1>();
234                return result.get<0>();
235        }
236        if (cmd == _T("exec")) {
237                return client::command_line_parser::exec(config, cmd, arguments, message);
238        }
239        return commands.exec_simple(config, target, command, arguments, message, perf);
240}
241
242int SyslogClient::commandLineExec(const std::wstring &command, std::list<std::wstring> &arguments, std::wstring &result) {
243        std::wstring cmd = client::command_line_parser::parse_command(command, _T("nsca"));
244        if (!client::command_line_parser::is_command(cmd))
245                return NSCAPI::returnIgnored;
246
247        client::configuration config;
248        setup(config);
249        return client::command_line_parser::commandLineExec(config, cmd, arguments, result);
250}
251
252NSCAPI::nagiosReturn SyslogClient::handleRAWNotification(const wchar_t* channel, std::string request, std::string &response) {
253        try {
254                client::configuration config;
255                setup(config);
256
257                if (!client::command_line_parser::relay_submit(config, request, response)) {
258                        NSC_LOG_ERROR_STD(_T("Failed to submit message..."));
259                        return NSCAPI::hasFailed;
260                }
261                return NSCAPI::isSuccess;
262        } catch (std::exception &e) {
263                NSC_LOG_ERROR_STD(_T("Failed to send data: ") + utf8::to_unicode(e.what()));
264                return NSCAPI::hasFailed;
265        } catch (...) {
266                NSC_LOG_ERROR_STD(_T("Failed to send data: UNKNOWN"));
267                return NSCAPI::hasFailed;
268        }
269}
270
271//////////////////////////////////////////////////////////////////////////
272// Parser setup/Helpers
273//
274
275void SyslogClient::add_local_options(po::options_description &desc, client::configuration::data_type data) {
276        desc.add_options()
277                ("severity,s", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "severity", _1)),
278                "Severity of error message")
279
280                ("unknown-severity", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "unknown_severity", _1)),
281                "Severity of error message")
282
283                ("ok-severity", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "ok_severity", _1)),
284                "Severity of error message")
285
286                ("warning-severity", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "warning_severity", _1)),
287                "Severity of error message")
288
289                ("critical-severity", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "critical_severity", _1)),
290                "Severity of error message")
291
292                ("facility,f", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "facility", _1)),
293                "Facility of error message")
294
295                ("tag template", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "tag template", _1)),
296                "Tag template (TODO)")
297
298                ("message template", po::value<std::string>()->notifier(boost::bind(&nscapi::functions::destination_container::set_string_data, &data->recipient, "message template", _1)),
299                "Message template (TODO)")
300                ;
301}
302
303void SyslogClient::setup(client::configuration &config) {
304        boost::shared_ptr<clp_handler_impl> handler = boost::shared_ptr<clp_handler_impl>(new clp_handler_impl(this));
305        add_local_options(config.local, config.data);
306
307        net::wurl url;
308        url.protocol = _T("syslog");
309        url.port = 514;
310        nscapi::target_handler::optarget opt = targets.find_target(_T("default"));
311        if (opt) {
312                nscapi::target_handler::target t = *opt;
313                url.host = t.host;
314                if (t.has_option("port")) {
315                        try {
316                                url.port = strEx::stoi(t.options[_T("port")]);
317                        } catch (...) {}
318                }
319                std::string keys[] = {"message template", "tag template", "severity", "ok_severity", "warning_severity", "critical_severity", "unknown_severity", "facility"};
320                BOOST_FOREACH(std::string s, keys) {
321                        config.data->recipient.data[s] = utf8::cvt<std::string>(t.options[utf8::cvt<std::wstring>(s)]);
322                }
323        }
324        config.data->recipient.id = "default";
325        config.data->recipient.address = utf8::cvt<std::string>(url.to_string());
326        config.data->host_self.id = "self";
327        config.data->host_self.host = hostname_;
328
329        config.target_lookup = handler;
330        config.handler = handler;
331}
332
333SyslogClient::connection_data SyslogClient::parse_header(const ::Plugin::Common_Header &header) {
334        nscapi::functions::destination_container recipient;
335        nscapi::functions::parse_destination(header, header.recipient_id(), recipient, true);
336        return connection_data(recipient);
337}
338
339//////////////////////////////////////////////////////////////////////////
340// Parser implementations
341//
342
343int SyslogClient::clp_handler_impl::query(client::configuration::data_type data, ::Plugin::Common_Header* header, const std::string &request, std::string &reply) {
344        NSC_LOG_ERROR_STD(_T("SYSLOG does not support query patterns"));
345        return NSCAPI::hasFailed;
346}
347
348int SyslogClient::clp_handler_impl::submit(client::configuration::data_type data, ::Plugin::Common_Header* header, const std::string &request, std::string &reply) {
349        std::wstring channel;
350        try {
351                Plugin::SubmitRequestMessage message;
352                message.ParseFromString(request);
353                connection_data con = parse_header(*header);
354                channel = utf8::cvt<std::wstring>(message.channel());
355
356                //TODO: Map seveity!
357
358                std::list<std::string> messages;
359                for (int i=0;i < message.payload_size(); ++i) {
360                        const ::Plugin::QueryResponseMessage::Response& payload = message.payload(i);
361                        std::string date = "Nov 10 00:12:00"; // TODO is this actually used?
362                        std::string tag = con.tag_syntax;
363                        std::string message = con.message_syntax;
364                        strEx::replace(message, "%message%", payload.message());
365                        strEx::replace(tag, "%message%", payload.message());
366
367                        std::string severity = con.severity;
368                        if (payload.result() == ::Plugin::Common_ResultCode_OK)
369                                severity = con.ok_severity;
370                        if (payload.result() == ::Plugin::Common_ResultCode_WARNING)
371                                severity = con.warn_severity;
372                        if (payload.result() == ::Plugin::Common_ResultCode_CRITCAL)
373                                severity = con.crit_severity;
374                        if (payload.result() == ::Plugin::Common_ResultCode_UNKNOWN)
375                                severity = con.unknown_severity;
376
377                        messages.push_back(instance->parse_priority(severity, con.facility) + date + " " + tag + " " + message);
378                }
379                boost::tuple<int,std::wstring> ret = instance->send(con, messages);
380                nscapi::functions::create_simple_submit_response(channel, _T("UNKNOWN"), ret.get<0>(), _T("Message submitted successfully: ") + ret.get<1>(), reply);
381                return NSCAPI::isSuccess;
382        } catch (std::exception &e) {
383                NSC_LOG_ERROR_STD(_T("Exception: ") + utf8::to_unicode(e.what()));
384                nscapi::functions::create_simple_submit_response(channel, _T("UNKNOWN"), NSCAPI::returnUNKNOWN, utf8::to_unicode(e.what()), reply);
385                return NSCAPI::hasFailed;
386        }
387}
388
389int SyslogClient::clp_handler_impl::exec(client::configuration::data_type data, ::Plugin::Common_Header* header, const std::string &request, std::string &reply) {
390        NSC_LOG_ERROR_STD(_T("SYSLOG does not support exec patterns"));
391        return NSCAPI::hasFailed;
392}
393std::string     SyslogClient::parse_priority(std::string severity, std::string facility) {
394        syslog_map::const_iterator cit1 = facilities.find(facility);
395        if (cit1 == facilities.end()) {
396                NSC_LOG_ERROR("Undefined facility: " + facility);
397                return "<0>";
398        }
399        syslog_map::const_iterator cit2 = severities.find(severity);
400        if (cit2 == severities.end()) {
401                NSC_LOG_ERROR("Undefined severity: " + severity);
402                return "<0>";
403        }
404        std::stringstream ss;
405        ss << '<' << (cit1->second*8+cit2->second) << '>';
406        return ss.str();
407}
408
409//////////////////////////////////////////////////////////////////////////
410// Protocol implementations
411//
412
413boost::tuple<int,std::wstring> SyslogClient::send(connection_data con, std::list<std::string> messages) {
414        try {
415                NSC_DEBUG_MSG_STD(_T("NRPE Connection details: ") + con.to_wstring());
416
417                boost::asio::io_service io_service;
418                ip::udp::resolver resolver(io_service);
419                ip::udp::resolver::query query(ip::udp::v4(), con.host, con.port);
420                ip::udp::endpoint receiver_endpoint = *resolver.resolve(query);
421
422                ip::udp::socket socket(io_service);
423                socket.open(ip::udp::v4());
424
425                BOOST_FOREACH(const std::string msg, messages) {
426                        NSC_DEBUG_MSG_STD(_T("Sending data: ") + utf8::cvt<std::wstring>(msg));
427                        socket.send_to(boost::asio::buffer(msg), receiver_endpoint);
428                }
429                return boost::make_tuple(NSCAPI::returnOK, _T("OK"));
430        } catch (std::runtime_error &e) {
431                NSC_LOG_ERROR_STD(_T("Socket error: ") + utf8::to_unicode(e.what()));
432                return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("Socket error: ") + utf8::to_unicode(e.what()));
433        } catch (std::exception &e) {
434                NSC_LOG_ERROR_STD(_T("Error: ") + utf8::to_unicode(e.what()));
435                return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("Error: ") + utf8::to_unicode(e.what()));
436        } catch (...) {
437                return boost::make_tuple(NSCAPI::returnUNKNOWN, _T("Unknown error -- REPORT THIS!"));
438        }
439}
440
441
442NSC_WRAP_DLL();
443NSC_WRAPPERS_MAIN_DEF(SyslogClient);
444NSC_WRAPPERS_IGNORE_MSG_DEF();
445NSC_WRAPPERS_HANDLE_CMD_DEF();
446NSC_WRAPPERS_CLI_DEF();
447NSC_WRAPPERS_HANDLE_NOTIFICATION_DEF();
448
Note: See TracBrowser for help on using the repository browser.