Merge branch 'collectd-5.5' into collectd-5.6
[collectd.git] / src / notify_email.c
1 /**
2  * collectd - src/notify_email.c
3  * Copyright (C) 2008  Oleg King
4  * Copyright (C) 2010  Florian Forster
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; either version 2 of the License, or (at your
9  * option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Oleg King <king2 at kaluga.ru>
22  *   Florian Forster <octo at collectd.org>
23  **/
24
25 #include "collectd.h"
26
27 #include "common.h"
28 #include "plugin.h"
29
30 #include <auth-client.h>
31 #include <libesmtp.h>
32
33 #define MAXSTRING               256
34
35 static const char *config_keys[] =
36 {
37   "SMTPServer",
38   "SMTPPort",
39   "SMTPUser",
40   "SMTPPassword",
41   "From",
42   "Recipient",
43   "Subject"
44 };
45 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
46
47 static char **recipients;
48 static int recipients_len = 0;
49
50 static smtp_session_t session;
51 static pthread_mutex_t session_lock = PTHREAD_MUTEX_INITIALIZER;
52 static smtp_message_t message;
53 static auth_context_t authctx = NULL;
54
55 static int smtp_port = 25;
56 static char *smtp_host = NULL;
57 static char *smtp_user = NULL;
58 static char *smtp_password = NULL;
59 static char *email_from = NULL;
60 static char *email_subject = NULL;
61
62 #define DEFAULT_SMTP_HOST       "localhost"
63 #define DEFAULT_SMTP_FROM       "root@localhost"
64 #define DEFAULT_SMTP_SUBJECT    "Collectd notify: %s@%s"
65
66 /* Callback to get username and password */
67 static int authinteract (auth_client_request_t request, char **result,
68     int fields, void __attribute__((unused)) *arg)
69 {
70   for (int i = 0; i < fields; i++)
71   {
72     if (request[i].flags & AUTH_USER)
73       result[i] = smtp_user;
74     else if (request[i].flags & AUTH_PASS)
75       result[i] = smtp_password;
76     else
77       return 0;
78   }
79   return 1;
80 } /* int authinteract */
81
82 /* Callback to print the recipient status */
83 static void print_recipient_status (smtp_recipient_t recipient,
84     const char *mailbox, void __attribute__((unused)) *arg)
85 {
86   const smtp_status_t *status;
87
88   status = smtp_recipient_status (recipient);
89   if (status->text[strlen(status->text) - 2] == '\r')
90     status->text[strlen(status->text) - 2] = 0;
91   INFO ("notify_email: notify sent to %s: %d %s", mailbox, status->code,
92       status->text);
93 } /* void print_recipient_status */
94
95 /* Callback to monitor SMTP activity */
96 static void monitor_cb (const char *buf, int buflen, int writing,
97     void __attribute__((unused)) *arg)
98 {
99   char log_str[MAXSTRING];
100
101   sstrncpy (log_str, buf, sizeof (log_str));
102   if (buflen > 2)
103     log_str[buflen - 2] = 0; /* replace \n with \0 */
104
105   if (writing == SMTP_CB_HEADERS) {
106     DEBUG ("notify_email plugin: SMTP --- H: %s", log_str);
107     return;
108   }
109   DEBUG (writing
110       ? "notify_email plugin: SMTP >>> C: %s"
111       : "notify_email plugin: SMTP <<< S: %s",
112       log_str);
113 } /* void monitor_cb */
114
115 static int notify_email_init (void)
116 {
117   char server[MAXSTRING];
118
119   ssnprintf(server, sizeof (server), "%s:%i",
120       (smtp_host == NULL) ? DEFAULT_SMTP_HOST : smtp_host,
121       smtp_port);
122
123   pthread_mutex_lock (&session_lock);
124
125   auth_client_init();
126
127   session = smtp_create_session ();
128   if (session == NULL) {
129     pthread_mutex_unlock (&session_lock);
130     ERROR ("notify_email plugin: cannot create SMTP session");
131     return (-1);
132   }
133
134   smtp_set_monitorcb (session, monitor_cb, NULL, 1);
135   smtp_set_hostname (session, hostname_g);
136   smtp_set_server (session, server);
137
138   if (smtp_user && smtp_password) {
139     authctx = auth_create_context ();
140     auth_set_mechanism_flags (authctx, AUTH_PLUGIN_PLAIN, 0);
141     auth_set_interact_cb (authctx, authinteract, NULL);
142   }
143
144   if ( !smtp_auth_set_context (session, authctx)) {
145     pthread_mutex_unlock (&session_lock);
146     ERROR ("notify_email plugin: cannot set SMTP auth context");
147     return (-1);
148   }
149
150   pthread_mutex_unlock (&session_lock);
151   return (0);
152 } /* int notify_email_init */
153
154 static int notify_email_shutdown (void)
155 {
156   pthread_mutex_lock (&session_lock);
157
158   if (session != NULL)
159     smtp_destroy_session (session);
160   session = NULL;
161
162   if (authctx != NULL)
163     auth_destroy_context (authctx);
164   authctx = NULL;
165
166   auth_client_exit();
167
168   pthread_mutex_unlock (&session_lock);
169   return (0);
170 } /* int notify_email_shutdown */
171
172 static int notify_email_config (const char *key, const char *value)
173 {
174   if (strcasecmp (key, "Recipient") == 0)
175   {
176     char **tmp;
177
178     tmp = realloc (recipients, (recipients_len + 1) * sizeof (char *));
179     if (tmp == NULL) {
180       ERROR ("notify_email: realloc failed.");
181       return (-1);
182     }
183
184     recipients = tmp;
185     recipients[recipients_len] = strdup (value);
186     if (recipients[recipients_len] == NULL) {
187       ERROR ("notify_email: strdup failed.");
188       return (-1);
189     }
190     recipients_len++;
191   }
192   else if (0 == strcasecmp (key, "SMTPServer")) {
193     sfree (smtp_host);
194     smtp_host = strdup (value);
195   }
196   else if (0 == strcasecmp (key, "SMTPPort")) {
197     int port_tmp = atoi (value);
198     if (port_tmp < 1 || port_tmp > 65535)
199     {
200       WARNING ("notify_email plugin: Invalid SMTP port: %i", port_tmp);
201       return (1);
202     }
203     smtp_port = port_tmp;
204   }
205   else if (0 == strcasecmp (key, "SMTPUser")) {
206     sfree (smtp_user);
207     smtp_user = strdup (value);
208   }
209   else if (0 == strcasecmp (key, "SMTPPassword")) {
210     sfree (smtp_password);
211     smtp_password = strdup (value);
212   }
213   else if (0 == strcasecmp (key, "From")) {
214     sfree (email_from);
215     email_from = strdup (value);
216   }
217   else if (0 == strcasecmp (key, "Subject")) {
218     sfree (email_subject);
219     email_subject = strdup (value);
220   }
221   else {
222     return -1;
223   }
224   return 0;
225 } /* int notify_email_config (const char *, const char *) */
226
227 static int notify_email_notification (const notification_t *n,
228     user_data_t __attribute__((unused)) *user_data)
229 {
230
231   time_t tt;
232   struct tm timestamp_tm;
233   char timestamp_str[64];
234
235   char severity[32];
236   char subject[MAXSTRING];
237
238   char buf[4096] = "";
239   int  buf_len = sizeof (buf);
240   int i;
241
242   ssnprintf (severity, sizeof (severity), "%s",
243       (n->severity == NOTIF_FAILURE) ? "FAILURE"
244       : ((n->severity == NOTIF_WARNING) ? "WARNING"
245         : ((n->severity == NOTIF_OKAY) ? "OKAY" : "UNKNOWN")));
246
247   ssnprintf (subject, sizeof (subject),
248       (email_subject == NULL) ? DEFAULT_SMTP_SUBJECT : email_subject,
249       severity, n->host);
250
251   tt = CDTIME_T_TO_TIME_T (n->time);
252   localtime_r (&tt, &timestamp_tm);
253   strftime (timestamp_str, sizeof (timestamp_str), "%Y-%m-%d %H:%M:%S",
254       &timestamp_tm);
255   timestamp_str[sizeof (timestamp_str) - 1] = '\0';
256
257   /* Let's make RFC822 message text with \r\n EOLs */
258   ssnprintf (buf, buf_len,
259       "MIME-Version: 1.0\r\n"
260       "Content-Type: text/plain; charset=\"US-ASCII\"\r\n"
261       "Content-Transfer-Encoding: 8bit\r\n"
262       "Subject: %s\r\n"
263       "\r\n"
264       "%s - %s@%s\r\n"
265       "\r\n"
266       "Message: %s",
267       subject,
268       timestamp_str,
269       severity,
270       n->host,
271       n->message);
272
273   pthread_mutex_lock (&session_lock);
274
275   if (session == NULL) {
276     /* Initialization failed or we're in the process of shutting down. */
277     pthread_mutex_unlock (&session_lock);
278     return (-1);
279   }
280
281   if (!(message = smtp_add_message (session))) {
282     pthread_mutex_unlock (&session_lock);
283     ERROR ("notify_email plugin: cannot set SMTP message");
284     return (-1);
285   }
286   smtp_set_reverse_path (message, email_from);
287   smtp_set_header (message, "To", NULL, NULL);
288   smtp_set_message_str (message, buf);
289
290   for (i = 0; i < recipients_len; i++)
291     smtp_add_recipient (message, recipients[i]);
292
293   /* Initiate a connection to the SMTP server and transfer the message. */
294   if (!smtp_start_session (session)) {
295     ERROR ("notify_email plugin: SMTP server problem: %s",
296         smtp_strerror (smtp_errno (), buf, sizeof buf));
297     pthread_mutex_unlock (&session_lock);
298     return (-1);
299   } else {
300     #if COLLECT_DEBUG
301     const smtp_status_t *status;
302     /* Report on the success or otherwise of the mail transfer. */
303     status = smtp_message_transfer_status (message);
304     DEBUG ("notify_email plugin: SMTP server report: %d %s",
305       status->code, (status->text != NULL) ? status->text : "\n");
306     #endif
307     smtp_enumerate_recipients (message, print_recipient_status, NULL);
308   }
309
310   pthread_mutex_unlock (&session_lock);
311   return (0);
312 } /* int notify_email_notification */
313
314 void module_register (void)
315 {
316   plugin_register_init ("notify_email", notify_email_init);
317   plugin_register_shutdown ("notify_email", notify_email_shutdown);
318   plugin_register_config ("notify_email", notify_email_config,
319       config_keys, config_keys_num);
320   plugin_register_notification ("notify_email", notify_email_notification,
321       /* user_data = */ NULL);
322 } /* void module_register (void) */
323
324 /* vim: set sw=2 sts=2 ts=8 et : */