1 #include "cetlib/PluginTypeDeducer.h"
2 #include "fhiclcpp/ParameterSet.h"
3 #if MESSAGEFACILITY_HEX_VERSION >= 0x20103
4 #include "fhiclcpp/types/ConfigurationTable.h"
5 #include "fhiclcpp/types/Sequence.h"
6 #include "fhiclcpp/types/TableFragment.h"
10 #include "messagefacility/MessageService/ELdestination.h"
11 #include "messagefacility/Utilities/ELseverityLevel.h"
12 #if MESSAGEFACILITY_HEX_VERSION < 0x20002 // v2_00_02 is s50, pre v2_00_02 is s48
13 # include "messagefacility/MessageService/ELcontextSupplier.h"
14 # include "messagefacility/MessageLogger/MessageDrop.h"
16 # include "messagefacility/MessageService/MessageDrop.h"
18 #include "messagefacility/Utilities/exception.h"
26 #include <arpa/inet.h>
29 #include <netinet/in.h>
30 #include <boost/thread.hpp>
32 #include <QtCore/QString>
37 using mf::service::ELdestination;
38 using mf::ELseverityLevel;
40 # if MESSAGEFACILITY_HEX_VERSION < 0x20002 // v2_00_02 is s50, pre v2_00_02 is s48
41 using mf::service::ELcontextSupplier;
49 #if MESSAGEFACILITY_HEX_VERSION >= 0x20103
52 using strings_t = fhicl::Sequence<std::string>::default_type;
54 fhicl::TableFragment<ELdestination::Config> elDestConfig;
55 fhicl::Atom<std::string> host{ fhicl::Name{
"host" },fhicl::Comment{
"SMTP Server hostname" },
"smtp.fnal.gov" };
56 fhicl::Atom<int> port{ fhicl::Name{
"port" },fhicl::Comment{
"SMTP Server port" },25 };
57 fhicl::Sequence<std::string> to{ fhicl::Name{
"to_addresses" }, fhicl::Comment{
"The list of email addresses that SMTP mfPlugin should sent to" } , strings_t {} };
58 fhicl::Atom<std::string> from{ fhicl::Name{
"from_address" },fhicl::Comment{
"Source email address" } };
59 fhicl::Atom<std::string> subject{ fhicl::Name{
"subject" },fhicl::Comment{
"Subject of the email message" },
"MessageFacility SMTP Message Digest" };
60 fhicl::Atom<std::string> messageHeader{ fhicl::Name{
"message_header" },fhicl::Comment{
"String to preface messages with in email body" },
"" };
61 fhicl::Atom<bool> useSmtps{ fhicl::Name{
"use_smtps" },fhicl::Comment{
"Use SMTPS protocol" },
false };
62 fhicl::Atom<std::string> user{ fhicl::Name{
"smtp_username" },fhicl::Comment{
"Username for SMTP server" },
"" };
63 fhicl::Atom<std::string> pw{ fhicl::Name{
"smtp_password" },fhicl::Comment{
"Password for SMTP server" },
"" };
64 fhicl::Atom<bool> verifyCert{ fhicl::Name{
"verify_host_ssl_certificate" },fhicl::Comment{
"Whether to run full SSL verify on SMTP server in SMTPS mode" },
true };
65 fhicl::Atom<size_t> sendInterval{ fhicl::Name{
"email_send_interval_seconds" },fhicl::Comment{
"Only send email every N seconds" }, 15};
67 using Parameters = fhicl::WrappedTable<Config>;
70 #if MESSAGEFACILITY_HEX_VERSION < 0x20103 // v2_01_03 is s58, pre v2_01_03 is s50
71 ELSMTP(
const fhicl::ParameterSet& pset);
73 ELSMTP(Parameters
const& pset);
79 while (sending_thread_active_) usleep(1000);
82 virtual void routePayload(
const std::ostringstream&,
const ErrorObj& msg
83 #
if MESSAGEFACILITY_HEX_VERSION < 0x20002
84 ,
const ELcontextSupplier&
90 std::string generateMessageId_()
const;
91 std::string dateTimeNow_();
92 std::string to_html(std::string msgString,
const ErrorObj& msg);
94 std::string smtp_host_;
96 std::vector<std::string> to_;
99 std::string message_prefix_;
103 std::string hostname_;
104 std::string hostaddr_;
108 std::string username_;
109 std::string password_;
110 bool ssl_verify_host_cert_;
112 std::atomic<bool> sending_thread_active_;
113 std::atomic<bool> abort_sleep_;
114 size_t send_interval_s_;
115 mutable std::mutex message_mutex_;
116 std::ostringstream message_contents_;
127 #if MESSAGEFACILITY_HEX_VERSION < 0x20103 // v2_01_03 is s58, pre v2_01_03 is s50
128 ELSMTP::ELSMTP(
const fhicl::ParameterSet& pset)
129 : ELdestination(pset)
130 , smtp_host_(pset.get<std::string>(
"host",
"smtp.fnal.gov"))
131 , port_(pset.get<int>(
"port", 25))
132 , to_(pset.get<std::vector<std::string>>(
"to_addresses"))
133 , from_(pset.get<std::string>(
"from_address"))
134 , subject_(pset.get<std::string>(
"subject",
"MessageFacility SMTP Message Digest"))
135 , message_prefix_(pset.get<std::string>(
"message_header",
""))
136 , pid_(static_cast<long>(getpid()))
137 , use_ssl_(pset.get<bool>(
"use_smtps", false))
138 , username_(pset.get<std::string>(
"smtp_username",
""))
139 , password_(pset.get<std::string>(
"smtp_password",
""))
140 , ssl_verify_host_cert_(pset.get<bool>(
"verify_host_ssl_certificate", true))
141 , sending_thread_active_(false)
142 , abort_sleep_(false)
143 , send_interval_s_(pset.get<size_t>(
"email_send_interval_seconds", 15))
146 : ELdestination(pset().elDestConfig())
147 , smtp_host_(pset().host())
148 , port_(pset().port())
150 , from_(pset().from())
151 , subject_(pset().subject())
152 , message_prefix_(pset().messageHeader())
153 , pid_(static_cast<long>(getpid()))
154 , use_ssl_(pset().useSmtps())
155 , username_(pset().user())
156 , password_(pset().pw())
157 , ssl_verify_host_cert_(pset().verifyCert())
158 , sending_thread_active_(false)
159 , abort_sleep_(false)
160 , send_interval_s_(pset().sendInterval())
164 char hostname_c[1024];
165 hostname_ = (gethostname(hostname_c, 1023) == 0) ? hostname_c :
"Unkonwn Host";
168 hostent* host =
nullptr;
169 host = gethostbyname(hostname_c);
174 char* ip = inet_ntoa(*(
struct in_addr *)host->h_addr);
180 struct ifaddrs* ifAddrStruct =
nullptr;
181 struct ifaddrs* ifa =
nullptr;
182 void* tmpAddrPtr =
nullptr;
184 if (getifaddrs(&ifAddrStruct))
187 hostaddr_ =
"127.0.0.1";
192 for (ifa = ifAddrStruct; ifa !=
nullptr; ifa = ifa->ifa_next)
194 if (ifa->ifa_addr->sa_family == AF_INET)
197 tmpAddrPtr = &((
struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
198 char addressBuffer[INET_ADDRSTRLEN];
199 inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
200 hostaddr_ = addressBuffer;
203 else if (ifa->ifa_addr->sa_family == AF_INET6)
206 tmpAddrPtr = &((
struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
207 char addressBuffer[INET6_ADDRSTRLEN];
208 inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
209 hostaddr_ = addressBuffer;
213 if (!hostaddr_.empty()
214 && hostaddr_.compare(
"127.0.0.1")
215 && hostaddr_.compare(
"::1"))
219 if (hostaddr_.empty())
220 hostaddr_ =
"127.0.0.1";
226 std::ostringstream pid_ostr;
227 pid_ostr <<
"/proc/" << pid_ <<
"/exe";
228 exe = realpath(pid_ostr.str().c_str(), NULL);
230 size_t end = exe.find(
'\0');
231 size_t start = exe.find_last_of(
'/', end);
233 app_ = exe.substr(start + 1, end - start - 1);
237 std::string ELSMTP::to_html(std::string msgString,
const ErrorObj& msg)
239 # if MESSAGEFACILITY_HEX_VERSION >= 0x20002 // an indication of a switch from s48 to s50
240 auto sevid = msg.xid().severity().getLevel();
242 auto sevid = msg.xid().severity.getLevel();
245 QString text_ = QString(
"<font color=");
249 # if MESSAGEFACILITY_HEX_VERSION < 0x20002 // v2_00_02 is s50, pre v2_00_02 is s48
250 case mf::ELseverityLevel::ELsev_incidental:
252 case mf::ELseverityLevel::ELsev_success:
253 case mf::ELseverityLevel::ELsev_zeroSeverity:
254 case mf::ELseverityLevel::ELsev_unspecified:
255 text_ += QString(
"#505050>");
258 case mf::ELseverityLevel::ELsev_info:
259 text_ += QString(
"#008000>");
262 case mf::ELseverityLevel::ELsev_warning:
263 # if MESSAGEFACILITY_HEX_VERSION < 0x20002 // v2_00_02 is s50, pre v2_00_02 is s48
264 case mf::ELseverityLevel::ELsev_warning2:
266 text_ += QString(
"#E08000>");
269 case mf::ELseverityLevel::ELsev_error:
270 # if MESSAGEFACILITY_HEX_VERSION < 0x20002 // v2_00_02 is s50, pre v2_00_02 is s48
271 case mf::ELseverityLevel::ELsev_error2:
272 case mf::ELseverityLevel::ELsev_next:
273 case mf::ELseverityLevel::ELsev_severe2:
274 case mf::ELseverityLevel::ELsev_abort:
275 case mf::ELseverityLevel::ELsev_fatal:
277 case mf::ELseverityLevel::ELsev_severe:
278 case mf::ELseverityLevel::ELsev_highestSeverity:
279 text_ += QString(
"#FF0000>");
286 text_ += QString(
"<pre>")
287 + QString(msgString.c_str()).toHtmlEscaped()
290 text_ += QString(
"</font>");
291 return text_.toStdString();
297 void ELSMTP::routePayload(
const std::ostringstream& oss
298 #
if MESSAGEFACILITY_HEX_VERSION < 0x20002
299 ,
const ErrorObj& msg, ELcontextSupplier
const&
301 ,
const ErrorObj& msg
305 std::unique_lock<std::mutex>(message_mutex_);
306 message_contents_ << to_html(oss.str(), msg);
308 if (!sending_thread_active_)
310 sending_thread_active_ =
true;
311 boost::thread t([=] { send_message_(); });
316 void ELSMTP::send_message_()
319 while (!abort_sleep_ && slept < send_interval_s_ * 1000000)
327 std::unique_lock<std::mutex> lk(message_mutex_);
328 payload = message_contents_.str();
329 message_contents_.str(
"");
331 std::string destination = (use_ssl_ ?
"smtps://" :
"smtp://") + smtp_host_ +
":" + std::to_string(port_);
334 std::vector<const char*> to;
335 to.reserve(to_.size());
336 std::string toString;
337 for (
size_t i = 0; i < to_.size(); ++i)
339 to.push_back(to_[i].c_str());
341 if (i < to_.size() - 1)
347 std::ostringstream headers_builder;
349 headers_builder <<
"Date: " << dateTimeNow_() <<
"\r\n";
350 headers_builder <<
"To: " << toString <<
"\r\n";
351 headers_builder <<
"From: " << from_ <<
"\r\n";
352 headers_builder <<
"Message-ID: <" + generateMessageId_() +
"@" + from_.substr(from_.find(
'@') + 1) +
">\r\n";
353 headers_builder <<
"Subject: " << subject_ <<
" @ " << dateTimeNow_() <<
" from PID " << getpid() <<
"\r\n";
354 headers_builder <<
"Content-Type: text/html; charset=\"UTF-8\"\r\n";
355 headers_builder <<
"\r\n";
357 std::string headers = headers_builder.str();
358 std::ostringstream message_builder;
359 message_builder << headers <<
"<html><body><p>" << message_prefix_ <<
"</p>" << payload <<
"</body></html>";
360 std::string payloadWithHeaders = message_builder.str();
365 send_message_ssl(destination.c_str(), &to[0], to_.size(), from_.c_str(), payloadWithHeaders.c_str(), payloadWithHeaders.size(), username_.c_str(), password_.c_str(), !ssl_verify_host_cert_);
369 send_message(destination.c_str(), &to[0], to_.size(), from_.c_str(), payloadWithHeaders.c_str(), payloadWithHeaders.size());
371 sending_thread_active_ =
false;
375 std::string ELSMTP::generateMessageId_()
const
377 const size_t MESSAGE_ID_LEN = 37;
384 ret.resize(MESSAGE_ID_LEN);
385 size_t datelen = std::strftime(&ret[0], MESSAGE_ID_LEN,
"%Y%m%d%H%M%S", &t);
386 static const std::string alphaNum{
388 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
389 "abcdefghijklmnopqrstuvwxyz" };
391 std::uniform_int_distribution<> dis(0, alphaNum.length() - 1);
392 std::generate_n(ret.begin() + datelen, MESSAGE_ID_LEN - datelen, [&]() {
return alphaNum[dis(gen)]; });
396 std::string ELSMTP::dateTimeNow_()
398 const int RFC5322_TIME_LEN = 32;
401 ret.resize(RFC5322_TIME_LEN);
408 strftime(&ret[0], RFC5322_TIME_LEN,
"%a, %d %b %Y %H:%M:%S %z", t);
422 auto makePlugin(
const std::string&,
423 const fhicl::ParameterSet& pset)
425 return std::make_unique<mfplugins::ELSMTP>(pset);
429 DEFINE_BASIC_PLUGINTYPE_FUNC(mf::service::ELdestination)
void send_message_ssl(const char *dest, const char *to[], size_t to_size, const char *from, const char *payload, size_t payload_size, const char *username, const char *pw, int disableVerify)
Sends a message to the given SMTP server, using SSL encryption.
SMTP Message Facility destination plugin (Using libcurl)
void send_message(const char *dest, const char *to[], size_t to_size, const char *from, const char *payload, size_t payload_size)
Sends a message to the given SMTP server.