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