artdaq_mfextensions  v1_05_00
SMTP_mfPlugin.cc
1 #include "cetlib/PluginTypeDeducer.h"
2 #include "fhiclcpp/ParameterSet.h"
3 #include "fhiclcpp/types/ConfigurationTable.h"
4 #include "fhiclcpp/types/Sequence.h"
5 #include "fhiclcpp/types/TableFragment.h"
6 
7 #include "messagefacility/MessageService/ELdestination.h"
8 #include "messagefacility/Utilities/ELseverityLevel.h"
9 #if MESSAGEFACILITY_HEX_VERSION < 0x20201 // v2_02_01 is s67
10 #include "messagefacility/MessageService/MessageDrop.h"
11 #else
12 #include "messagefacility/MessageLogger/MessageLogger.h"
13 #endif
14 #include "messagefacility/Utilities/exception.h"
15 
16 // C/C++ includes
17 #include <arpa/inet.h>
18 #include <ifaddrs.h>
19 #include <netdb.h>
20 #include <netinet/in.h>
21 #include <algorithm>
22 #include <atomic>
23 #include <boost/thread.hpp>
24 #include <memory>
25 #include <mutex>
26 #include <random>
27 
28 #include <QtCore/QString>
29 #include "cetlib/compiler_macros.h"
31 
32 namespace mfplugins {
33 using mf::ELseverityLevel;
34 using mf::ErrorObj;
35 using mf::service::ELdestination;
36 
40 class ELSMTP : public ELdestination
41 {
42 public:
46  struct Config
47  {
49  fhicl::TableFragment<ELdestination::Config> elDestConfig;
51  fhicl::Atom<std::string> host =
52  fhicl::Atom<std::string>{fhicl::Name{"host"}, fhicl::Comment{"SMTP Server hostname"}, "smtp.fnal.gov"};
54  fhicl::Atom<int> port = fhicl::Atom<int>{fhicl::Name{"port"}, fhicl::Comment{"SMTP Server port"}, 25};
56  fhicl::Sequence<std::string> to = fhicl::Sequence<std::string>{
57  fhicl::Name{"to_addresses"}, fhicl::Comment{"The list of email addresses that SMTP mfPlugin should sent to"},
58  fhicl::Sequence<std::string>::default_type{}};
60  fhicl::Atom<std::string> from =
61  fhicl::Atom<std::string>{fhicl::Name{"from_address"}, fhicl::Comment{"Source email address"}};
63  fhicl::Atom<std::string> subject = fhicl::Atom<std::string>{
64  fhicl::Name{"subject"}, fhicl::Comment{"Subject of the email message"}, "MessageFacility SMTP Message Digest"};
66  fhicl::Atom<std::string> messageHeader = fhicl::Atom<std::string>{
67  fhicl::Name{"message_header"}, fhicl::Comment{"String to preface messages with in email body"}, ""};
69  fhicl::Atom<bool> useSmtps =
70  fhicl::Atom<bool>{fhicl::Name{"use_smtps"}, fhicl::Comment{"Use SMTPS protocol"}, false};
72  fhicl::Atom<std::string> user =
73  fhicl::Atom<std::string>{fhicl::Name{"smtp_username"}, fhicl::Comment{"Username for SMTP server"}, ""};
75  fhicl::Atom<std::string> pw =
76  fhicl::Atom<std::string>{fhicl::Name{"smtp_password"}, fhicl::Comment{"Password for SMTP server"}, ""};
78  fhicl::Atom<bool> verifyCert =
79  fhicl::Atom<bool>{fhicl::Name{"verify_host_ssl_certificate"},
80  fhicl::Comment{"Whether to run full SSL verify on SMTP server in SMTPS mode"}, true};
82  fhicl::Atom<size_t> sendInterval = fhicl::Atom<size_t>{fhicl::Name{"email_send_interval_seconds"},
83  fhicl::Comment{"Only send email every N seconds"}, 15};
84  };
86  using Parameters = fhicl::WrappedTable<Config>;
87 
88 public:
93  ELSMTP(Parameters const& pset);
94 
95  ~ELSMTP()
96  {
97  abort_sleep_ = true;
98  while (sending_thread_active_) usleep(1000);
99  }
100 
106  virtual void routePayload(const std::ostringstream& o, const ErrorObj& msg) override;
107 
108 private:
109  void send_message_();
110  std::string generateMessageId_() const;
111  std::string dateTimeNow_();
112  std::string to_html(std::string msgString, const ErrorObj& msg);
113 
114  std::string smtp_host_;
115  int port_;
116  std::vector<std::string> to_;
117  std::string from_;
118  std::string subject_;
119  std::string message_prefix_;
120 
121  // Message information
122  long pid_;
123  std::string hostname_;
124  std::string hostaddr_;
125  std::string app_;
126 
127  bool use_ssl_;
128  std::string username_;
129  std::string password_;
130  bool ssl_verify_host_cert_;
131 
132  std::atomic<bool> sending_thread_active_;
133  std::atomic<bool> abort_sleep_;
134  size_t send_interval_s_;
135  mutable std::mutex message_mutex_;
136  std::ostringstream message_contents_;
137 };
138 
139 // END DECLARATION
140 //======================================================================
141 // BEGIN IMPLEMENTATION
142 
143 //======================================================================
144 // ELSMTP c'tor
145 //======================================================================
147  : ELdestination(pset().elDestConfig()), smtp_host_(pset().host()), port_(pset().port()), to_(pset().to()), from_(pset().from()), subject_(pset().subject()), message_prefix_(pset().messageHeader()), pid_(static_cast<long>(getpid())), use_ssl_(pset().useSmtps()), username_(pset().user()), password_(pset().pw()), ssl_verify_host_cert_(pset().verifyCert()), sending_thread_active_(false), abort_sleep_(false), send_interval_s_(pset().sendInterval())
148 {
149  // hostname
150  char hostname_c[1024];
151  hostname_ = (gethostname(hostname_c, 1023) == 0) ? hostname_c : "Unkonwn Host";
152 
153  // host ip address
154  hostent* host = nullptr;
155  host = gethostbyname(hostname_c);
156 
157  if (host != nullptr)
158  {
159  // ip address from hostname if the entry exists in /etc/hosts
160  char* ip = inet_ntoa(*(struct in_addr*)host->h_addr);
161  hostaddr_ = ip;
162  }
163  else
164  {
165  // enumerate all network interfaces
166  struct ifaddrs* ifAddrStruct = nullptr;
167  struct ifaddrs* ifa = nullptr;
168  void* tmpAddrPtr = nullptr;
169 
170  if (getifaddrs(&ifAddrStruct))
171  {
172  // failed to get addr struct
173  hostaddr_ = "127.0.0.1";
174  }
175  else
176  {
177  // iterate through all interfaces
178  for (ifa = ifAddrStruct; ifa != nullptr; ifa = ifa->ifa_next)
179  {
180  if (ifa->ifa_addr->sa_family == AF_INET)
181  {
182  // a valid IPv4 addres
183  tmpAddrPtr = &((struct sockaddr_in*)ifa->ifa_addr)->sin_addr;
184  char addressBuffer[INET_ADDRSTRLEN];
185  inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
186  hostaddr_ = addressBuffer;
187  }
188 
189  else if (ifa->ifa_addr->sa_family == AF_INET6)
190  {
191  // a valid IPv6 address
192  tmpAddrPtr = &((struct sockaddr_in6*)ifa->ifa_addr)->sin6_addr;
193  char addressBuffer[INET6_ADDRSTRLEN];
194  inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
195  hostaddr_ = addressBuffer;
196  }
197 
198  // find first non-local address
199  if (!hostaddr_.empty() && hostaddr_.compare("127.0.0.1") && hostaddr_.compare("::1")) break;
200  }
201 
202  if (hostaddr_.empty()) // failed to find anything
203  hostaddr_ = "127.0.0.1";
204  }
205  }
206 
207  // get process name from '/proc/pid/exe'
208  std::string exe;
209  std::ostringstream pid_ostr;
210  pid_ostr << "/proc/" << pid_ << "/exe";
211  exe = realpath(pid_ostr.str().c_str(), NULL);
212 
213  size_t end = exe.find('\0');
214  size_t start = exe.find_last_of('/', end);
215 
216  app_ = exe.substr(start + 1, end - start - 1);
217 }
218 
219 std::string ELSMTP::to_html(std::string msgString, const ErrorObj& msg)
220 {
221  auto sevid = msg.xid().severity().getLevel();
222 
223  QString text_ = QString("<font color=");
224 
225  switch (sevid)
226  {
227  case mf::ELseverityLevel::ELsev_success:
228  case mf::ELseverityLevel::ELsev_zeroSeverity:
229  case mf::ELseverityLevel::ELsev_unspecified:
230  text_ += QString("#505050>");
231  break;
232 
233  case mf::ELseverityLevel::ELsev_info:
234  text_ += QString("#008000>");
235  break;
236 
237  case mf::ELseverityLevel::ELsev_warning:
238  text_ += QString("#E08000>");
239  break;
240 
241  case mf::ELseverityLevel::ELsev_error:
242  case mf::ELseverityLevel::ELsev_severe:
243  case mf::ELseverityLevel::ELsev_highestSeverity:
244  text_ += QString("#FF0000>");
245  break;
246 
247  default:
248  break;
249  }
250 
251  // std::cout << "qt_mf_msg.cc:" << msg.message() << std::endl;
252  text_ += QString("<pre>") + QString(msgString.c_str()).toHtmlEscaped() // + "<br>"
253  + QString("</pre>");
254 
255  text_ += QString("</font>");
256  return text_.toStdString();
257 }
258 
259 //======================================================================
260 // Message router ( overriddes ELdestination::routePayload )
261 //======================================================================
262 void ELSMTP::routePayload(const std::ostringstream& oss, const ErrorObj& msg)
263 {
264  std::lock_guard<std::mutex> lk(message_mutex_);
265  message_contents_ << to_html(oss.str(), msg);
266 
267  if (!sending_thread_active_)
268  {
269  sending_thread_active_ = true;
270  boost::thread t([=] { send_message_(); });
271  t.detach();
272  }
273 }
274 
275 void ELSMTP::send_message_()
276 {
277  size_t slept = 0;
278  while (!abort_sleep_ && slept < send_interval_s_ * 1000000)
279  {
280  usleep(10000);
281  slept += 10000;
282  }
283 
284  std::string payload;
285  {
286  std::lock_guard<std::mutex> lk(message_mutex_);
287  payload = message_contents_.str();
288  message_contents_.str("");
289  }
290  std::string destination = (use_ssl_ ? "smtps://" : "smtp://") + smtp_host_ + ":" + std::to_string(port_);
291 
292  std::vector<const char*> to;
293  to.reserve(to_.size());
294  std::string toString;
295  for (size_t i = 0; i < to_.size(); ++i)
296  {
297  to.push_back(to_[i].c_str());
298  toString += to_[i];
299  if (i < to_.size() - 1)
300  {
301  toString += ", ";
302  }
303  }
304 
305  std::ostringstream headers_builder;
306 
307  headers_builder << "Date: " << dateTimeNow_() << "\r\n";
308  headers_builder << "To: " << toString << "\r\n";
309  headers_builder << "From: " << from_ << "\r\n";
310  headers_builder << "Message-ID: <" + generateMessageId_() + "@" + from_.substr(from_.find('@') + 1) + ">\r\n";
311  headers_builder << "Subject: " << subject_ << " @ " << dateTimeNow_() << " from PID " << getpid() << "\r\n";
312  headers_builder << "Content-Type: text/html; charset=\"UTF-8\"\r\n";
313  headers_builder << "\r\n";
314 
315  std::string headers = headers_builder.str();
316  std::ostringstream message_builder;
317  message_builder << headers << "<html><body><p>" << message_prefix_ << "</p>" << payload << "</body></html>";
318  std::string payloadWithHeaders = message_builder.str();
319 
320  if (use_ssl_)
321  {
322  send_message_ssl(destination.c_str(), &to[0], to_.size(), from_.c_str(), payloadWithHeaders.c_str(),
323  payloadWithHeaders.size(), username_.c_str(), password_.c_str(), !ssl_verify_host_cert_);
324  }
325  else
326  {
327  send_message(destination.c_str(), &to[0], to_.size(), from_.c_str(), payloadWithHeaders.c_str(),
328  payloadWithHeaders.size());
329  }
330  sending_thread_active_ = false;
331 }
332 
333 // https://codereview.stackexchange.com/questions/140409/sending-email-using-libcurl-follow-up/140562
334 std::string ELSMTP::generateMessageId_() const
335 {
336  const size_t MESSAGE_ID_LEN = 37;
337  tm t;
338  time_t tt;
339  time(&tt);
340  gmtime_r(&tt, &t);
341 
342  std::string ret;
343  ret.resize(MESSAGE_ID_LEN);
344  size_t datelen = std::strftime(&ret[0], MESSAGE_ID_LEN, "%Y%m%d%H%M%S", &t);
345  static const std::string alphaNum{
346  "0123456789"
347  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
348  "abcdefghijklmnopqrstuvwxyz"};
349  std::mt19937 gen;
350  std::uniform_int_distribution<> dis(0, alphaNum.length() - 1);
351  std::generate_n(ret.begin() + datelen, MESSAGE_ID_LEN - datelen, [&]() { return alphaNum[dis(gen)]; });
352  return ret;
353 }
354 
355 std::string ELSMTP::dateTimeNow_()
356 {
357  const int RFC5322_TIME_LEN = 32;
358 
359  std::string ret;
360  ret.resize(RFC5322_TIME_LEN);
361 
362  time_t tt;
363  tm tv, *t = &tv;
364  tt = time(&tt);
365  localtime_r(&tt, t);
366 
367  strftime(&ret[0], RFC5322_TIME_LEN, "%a, %d %b %Y %H:%M:%S %z", t);
368 
369  return ret;
370 }
371 } // end namespace mfplugins
372 
373 //======================================================================
374 //
375 // makePlugin function
376 //
377 //======================================================================
378 
379 #ifndef EXTERN_C_FUNC_DECLARE_START
380 #define EXTERN_C_FUNC_DECLARE_START extern "C" {
381 #endif
382 
383 EXTERN_C_FUNC_DECLARE_START
384 auto makePlugin(const std::string&, const fhicl::ParameterSet& pset)
385 {
386  return std::make_unique<mfplugins::ELSMTP>(pset);
387 }
388 }
389 
390 DEFINE_BASIC_PLUGINTYPE_FUNC(mf::service::ELdestination)
fhicl::Atom< std::string > from
&quot;from_address&quot; (REQUIRED): Source email address
fhicl::Atom< std::string > user
&quot;smtp_username&quot; (Default: &quot;&quot;): Username for SMTP server
fhicl::Sequence< std::string > to
&quot;to_addresses&quot; (Default: {}): The list of email addresses that SMTP mfPlugin should sent to ...
fhicl::Atom< size_t > sendInterval
&quot;email_send_interval_seconds&quot; (Default: 15): Only send email every N seconds
fhicl::WrappedTable< Config > Parameters
Used for ParameterSet validation.
fhicl::Atom< std::string > host
&quot;host&quot; (Default: &quot;smtp.fnal.gov&quot;): SMTP Server hostname
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)
fhicl::Atom< std::string > messageHeader
&quot;message_header&quot; (Default: &quot;&quot;): String to preface messages with in email body
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.
fhicl::Atom< std::string > subject
&quot;subject&quot; (Default: &quot;MessageFacility SMTP Message Digest&quot;): Subject of the email message ...
virtual void routePayload(const std::ostringstream &o, const ErrorObj &msg) override
Serialize a MessageFacility message to the output.
fhicl::TableFragment< ELdestination::Config > elDestConfig
ELDestination common config parameters.
fhicl::Atom< bool > verifyCert
&quot;verify_host_ssl_certificate&quot; (Default: true): Whether to run full SSL verify on SMTP server in SMTPS...
ELSMTP(Parameters const &pset)
ELSMTP Constructor
fhicl::Atom< std::string > pw
&quot;smtp_password&quot; (Default: &quot;&quot;): Password for SMTP server
fhicl::Atom< bool > useSmtps
&quot;use_smtps&quot; (Default: false): Use SMTPS protocol
Configuration parameters for ELSMTP.
fhicl::Atom< int > port
&quot;port&quot; (Default: 25): SMTP Server port