Code

Merge branch 'collectd-5.4' into collectd-5.5
[collectd.git] / src / email.c
1 /**
2  * collectd - src/email.c
3  * Copyright (C) 2006-2008  Sebastian Harl
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Sebastian Harl <sh at tokkee.org>
25  **/
27 /*
28  * This plugin communicates with a spam filter, a virus scanner or similar
29  * software using a UNIX socket and a very simple protocol:
30  *
31  * e-mail type (e.g. ham, spam, virus, ...) and size
32  * e:<type>:<bytes>
33  *
34  * spam score
35  * s:<value>
36  *
37  * successful spam checks
38  * c:<type1>[,<type2>,...]
39  */
41 #include "collectd.h"
42 #include "common.h"
43 #include "plugin.h"
45 #include "configfile.h"
47 #include <stddef.h>
49 #if HAVE_LIBPTHREAD
50 # include <pthread.h>
51 #endif
53 #include <sys/socket.h>
54 #include <sys/un.h>
55 #include <sys/select.h>
57 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
58 #ifndef UNIX_PATH_MAX
59 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
60 #endif /* UNIX_PATH_MAX */
62 #if HAVE_GRP_H
63 #       include <grp.h>
64 #endif /* HAVE_GRP_H */
66 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
67 #define MAX_CONNS 5
68 #define MAX_CONNS_LIMIT 16384
70 #define log_debug(...) DEBUG ("email: "__VA_ARGS__)
71 #define log_err(...) ERROR ("email: "__VA_ARGS__)
72 #define log_warn(...) WARNING ("email: "__VA_ARGS__)
74 /*
75  * Private data structures
76  */
77 /* linked list of email and check types */
78 typedef struct type {
79         char        *name;
80         int         value;
81         struct type *next;
82 } type_t;
84 typedef struct {
85         type_t *head;
86         type_t *tail;
87 } type_list_t;
89 /* collector thread control information */
90 typedef struct collector {
91         pthread_t thread;
93         /* socket descriptor of the current/last connection */
94         FILE *socket;
95 } collector_t;
97 /* linked list of pending connections */
98 typedef struct conn {
99         /* socket to read data from */
100         FILE *socket;
102         /* linked list of connections */
103         struct conn *next;
104 } conn_t;
106 typedef struct {
107         conn_t *head;
108         conn_t *tail;
109 } conn_list_t;
111 /*
112  * Private variables
113  */
114 /* valid configuration file keys */
115 static const char *config_keys[] =
117         "SocketFile",
118         "SocketGroup",
119         "SocketPerms",
120         "MaxConns"
121 };
122 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
124 /* socket configuration */
125 static char *sock_file  = NULL;
126 static char *sock_group = NULL;
127 static int  sock_perms  = S_IRWXU | S_IRWXG;
128 static int  max_conns   = MAX_CONNS;
130 /* state of the plugin */
131 static int disabled = 0;
133 /* thread managing "client" connections */
134 static pthread_t connector = (pthread_t) 0;
135 static int connector_socket = -1;
137 /* tell the collector threads that a new connection is available */
138 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
140 /* connections that are waiting to be processed */
141 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
142 static conn_list_t conns;
144 /* tell the connector thread that a collector is available */
145 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
147 /* collector threads */
148 static collector_t **collectors = NULL;
150 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
151 static int available_collectors;
153 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
154 static type_list_t list_count;
155 static type_list_t list_count_copy;
157 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
158 static type_list_t list_size;
159 static type_list_t list_size_copy;
161 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
162 static double score;
163 static int score_count;
165 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
166 static type_list_t list_check;
167 static type_list_t list_check_copy;
169 /*
170  * Private functions
171  */
172 static int email_config (const char *key, const char *value)
174         if (0 == strcasecmp (key, "SocketFile")) {
175                 if (NULL != sock_file)
176                         free (sock_file);
177                 sock_file = sstrdup (value);
178         }
179         else if (0 == strcasecmp (key, "SocketGroup")) {
180                 if (NULL != sock_group)
181                         free (sock_group);
182                 sock_group = sstrdup (value);
183         }
184         else if (0 == strcasecmp (key, "SocketPerms")) {
185                 /* the user is responsible for providing reasonable values */
186                 sock_perms = (int)strtol (value, NULL, 8);
187         }
188         else if (0 == strcasecmp (key, "MaxConns")) {
189                 long int tmp = strtol (value, NULL, 0);
191                 if (tmp < 1) {
192                         fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
193                                         "value %li, will use default %i.\n",
194                                         tmp, MAX_CONNS);
195                         ERROR ("email plugin: `MaxConns' was set to invalid "
196                                         "value %li, will use default %i.\n",
197                                         tmp, MAX_CONNS);
198                         max_conns = MAX_CONNS;
199                 }
200                 else if (tmp > MAX_CONNS_LIMIT) {
201                         fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
202                                         "value %li, will use hardcoded limit %i.\n",
203                                         tmp, MAX_CONNS_LIMIT);
204                         ERROR ("email plugin: `MaxConns' was set to invalid "
205                                         "value %li, will use hardcoded limit %i.\n",
206                                         tmp, MAX_CONNS_LIMIT);
207                         max_conns = MAX_CONNS_LIMIT;
208                 }
209                 else {
210                         max_conns = (int)tmp;
211                 }
212         }
213         else {
214                 return -1;
215         }
216         return 0;
217 } /* static int email_config (char *, char *) */
219 /* Increment the value of the given name in the given list by incr. */
220 static void type_list_incr (type_list_t *list, char *name, int incr)
222         if (NULL == list->head) {
223                 list->head = (type_t *)smalloc (sizeof (type_t));
225                 list->head->name  = sstrdup (name);
226                 list->head->value = incr;
227                 list->head->next  = NULL;
229                 list->tail = list->head;
230         }
231         else {
232                 type_t *ptr;
234                 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
235                         if (0 == strcmp (name, ptr->name))
236                                 break;
237                 }
239                 if (NULL == ptr) {
240                         list->tail->next = (type_t *)smalloc (sizeof (type_t));
241                         list->tail = list->tail->next;
243                         list->tail->name  = sstrdup (name);
244                         list->tail->value = incr;
245                         list->tail->next  = NULL;
246                 }
247                 else {
248                         ptr->value += incr;
249                 }
250         }
251         return;
252 } /* static void type_list_incr (type_list_t *, char *) */
254 static void *collect (void *arg)
256         collector_t *this = (collector_t *)arg;
258         while (1) {
259                 conn_t *connection;
261                 pthread_mutex_lock (&conns_mutex);
263                 while (NULL == conns.head) {
264                         pthread_cond_wait (&conn_available, &conns_mutex);
265                 }
267                 connection = conns.head;
268                 conns.head = conns.head->next;
270                 if (NULL == conns.head) {
271                         conns.tail = NULL;
272                 }
274                 pthread_mutex_unlock (&conns_mutex);
276                 /* make the socket available to the global
277                  * thread and connection management */
278                 this->socket = connection->socket;
280                 log_debug ("collect: handling connection on fd #%i",
281                                 fileno (this->socket));
283                 while (42) {
284                         /* 256 bytes ought to be enough for anybody ;-) */
285                         char line[256 + 1]; /* line + '\0' */
286                         int  len = 0;
288                         errno = 0;
289                         if (NULL == fgets (line, sizeof (line), this->socket)) {
290                                 if (0 != errno) {
291                                         char errbuf[1024];
292                                         log_err ("collect: reading from socket (fd #%i) "
293                                                         "failed: %s", fileno (this->socket),
294                                                         sstrerror (errno, errbuf, sizeof (errbuf)));
295                                 }
296                                 break;
297                         }
299                         len = strlen (line);
300                         if (('\n' != line[len - 1]) && ('\r' != line[len - 1])) {
301                                 log_warn ("collect: line too long (> %zu characters): "
302                                                 "'%s' (truncated)", sizeof (line) - 1, line);
304                                 while (NULL != fgets (line, sizeof (line), this->socket))
305                                         if (('\n' == line[len - 1]) || ('\r' == line[len - 1]))
306                                                 break;
307                                 continue;
308                         }
310                         line[len - 1] = '\0';
312                         log_debug ("collect: line = '%s'", line);
314                         if (':' != line[1]) {
315                                 log_err ("collect: syntax error in line '%s'", line);
316                                 continue;
317                         }
319                         if ('e' == line[0]) { /* e:<type>:<bytes> */
320                                 char *ptr  = NULL;
321                                 char *type = strtok_r (line + 2, ":", &ptr);
322                                 char *tmp  = strtok_r (NULL, ":", &ptr);
323                                 int  bytes = 0;
325                                 if (NULL == tmp) {
326                                         log_err ("collect: syntax error in line '%s'", line);
327                                         continue;
328                                 }
330                                 bytes = atoi (tmp);
332                                 pthread_mutex_lock (&count_mutex);
333                                 type_list_incr (&list_count, type, 1);
334                                 pthread_mutex_unlock (&count_mutex);
336                                 if (bytes > 0) {
337                                         pthread_mutex_lock (&size_mutex);
338                                         type_list_incr (&list_size, type, bytes);
339                                         pthread_mutex_unlock (&size_mutex);
340                                 }
341                         }
342                         else if ('s' == line[0]) { /* s:<value> */
343                                 pthread_mutex_lock (&score_mutex);
344                                 score = (score * (double)score_count + atof (line + 2))
345                                                 / (double)(score_count + 1);
346                                 ++score_count;
347                                 pthread_mutex_unlock (&score_mutex);
348                         }
349                         else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
350                                 char *ptr  = NULL;
351                                 char *type = strtok_r (line + 2, ",", &ptr);
353                                 do {
354                                         pthread_mutex_lock (&check_mutex);
355                                         type_list_incr (&list_check, type, 1);
356                                         pthread_mutex_unlock (&check_mutex);
357                                 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
358                         }
359                         else {
360                                 log_err ("collect: unknown type '%c'", line[0]);
361                         }
362                 } /* while (42) */
364                 log_debug ("Shutting down connection on fd #%i",
365                                 fileno (this->socket));
367                 fclose (connection->socket);
368                 free (connection);
370                 this->socket = NULL;
372                 pthread_mutex_lock (&available_mutex);
373                 ++available_collectors;
374                 pthread_mutex_unlock (&available_mutex);
376                 pthread_cond_signal (&collector_available);
377         } /* while (1) */
379         pthread_exit ((void *)0);
380         return ((void *) 0);
381 } /* static void *collect (void *) */
383 static void *open_connection (void __attribute__((unused)) *arg)
385         struct sockaddr_un addr;
387         char *path  = (NULL == sock_file) ? SOCK_PATH : sock_file;
388         char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
390         /* create UNIX socket */
391         errno = 0;
392         if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
393                 char errbuf[1024];
394                 disabled = 1;
395                 log_err ("socket() failed: %s",
396                                 sstrerror (errno, errbuf, sizeof (errbuf)));
397                 pthread_exit ((void *)1);
398         }
400         addr.sun_family = AF_UNIX;
401         sstrncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
403         errno = 0;
404         if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
405                                 offsetof (struct sockaddr_un, sun_path)
406                                         + strlen(addr.sun_path))) {
407                 char errbuf[1024];
408                 disabled = 1;
409                 close (connector_socket);
410                 connector_socket = -1;
411                 log_err ("bind() failed: %s",
412                                 sstrerror (errno, errbuf, sizeof (errbuf)));
413                 pthread_exit ((void *)1);
414         }
416         errno = 0;
417         if (-1 == listen (connector_socket, 5)) {
418                 char errbuf[1024];
419                 disabled = 1;
420                 close (connector_socket);
421                 connector_socket = -1;
422                 log_err ("listen() failed: %s",
423                                 sstrerror (errno, errbuf, sizeof (errbuf)));
424                 pthread_exit ((void *)1);
425         }
427         {
428                 struct group sg;
429                 struct group *grp;
430                 char grbuf[2048];
431                 int status;
433                 grp = NULL;
434                 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
435                 if (status != 0)
436                 {
437                         char errbuf[1024];
438                         log_warn ("getgrnam_r (%s) failed: %s", group,
439                                         sstrerror (errno, errbuf, sizeof (errbuf)));
440                 }
441                 else if (grp == NULL)
442                 {
443                         log_warn ("No such group: `%s'", group);
444                 }
445                 else
446                 {
447                         status = chown (path, (uid_t) -1, grp->gr_gid);
448                         if (status != 0)
449                         {
450                                 char errbuf[1024];
451                                 log_warn ("chown (%s, -1, %i) failed: %s",
452                                                 path, (int) grp->gr_gid,
453                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
454                         }
455                 }
456         }
458         errno = 0;
459         if (0 != chmod (path, sock_perms)) {
460                 char errbuf[1024];
461                 log_warn ("chmod() failed: %s",
462                                 sstrerror (errno, errbuf, sizeof (errbuf)));
463         }
465         { /* initialize collector threads */
466                 int i   = 0;
467                 int err = 0;
469                 pthread_attr_t ptattr;
471                 conns.head = NULL;
472                 conns.tail = NULL;
474                 pthread_attr_init (&ptattr);
475                 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
477                 available_collectors = max_conns;
479                 collectors =
480                         (collector_t **)smalloc (max_conns * sizeof (collector_t *));
482                 for (i = 0; i < max_conns; ++i) {
483                         collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
484                         collectors[i]->socket = NULL;
486                         if (0 != (err = plugin_thread_create (&collectors[i]->thread,
487                                                         &ptattr, collect, collectors[i]))) {
488                                 char errbuf[1024];
489                                 log_err ("pthread_create() failed: %s",
490                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
491                                 collectors[i]->thread = (pthread_t) 0;
492                         }
493                 }
495                 pthread_attr_destroy (&ptattr);
496         }
498         while (1) {
499                 int remote = 0;
501                 conn_t *connection;
503                 pthread_mutex_lock (&available_mutex);
505                 while (0 == available_collectors) {
506                         pthread_cond_wait (&collector_available, &available_mutex);
507                 }
509                 --available_collectors;
511                 pthread_mutex_unlock (&available_mutex);
513                 while (42) {
514                         errno = 0;
516                         remote = accept (connector_socket, NULL, NULL);
517                         if (remote == -1) {
518                                 char errbuf[1024];
520                                 if (errno == EINTR)
521                                         continue;
523                                 disabled = 1;
524                                 close (connector_socket);
525                                 connector_socket = -1;
526                                 log_err ("accept() failed: %s",
527                                                  sstrerror (errno, errbuf, sizeof (errbuf)));
528                                 pthread_exit ((void *)1);
529                         }
531                         /* access() succeeded. */
532                         break;
533                 }
535                 connection = malloc (sizeof (*connection));
536                 if (connection != NULL)
537                 {
538                         close (remote);
539                         continue;
540                 }
541                 memset (connection, 0, sizeof (*connection));
543                 connection->socket = fdopen (remote, "r");
544                 connection->next   = NULL;
546                 if (NULL == connection->socket) {
547                         close (remote);
548                         sfree (connection);
549                         continue;
550                 }
552                 pthread_mutex_lock (&conns_mutex);
554                 if (NULL == conns.head) {
555                         conns.head = connection;
556                         conns.tail = connection;
557                 }
558                 else {
559                         conns.tail->next = connection;
560                         conns.tail = conns.tail->next;
561                 }
563                 pthread_mutex_unlock (&conns_mutex);
565                 pthread_cond_signal (&conn_available);
566         }
568         pthread_exit ((void *) 0);
569         return ((void *) 0);
570 } /* static void *open_connection (void *) */
572 static int email_init (void)
574         int err = 0;
576         if (0 != (err = plugin_thread_create (&connector, NULL,
577                                 open_connection, NULL))) {
578                 char errbuf[1024];
579                 disabled = 1;
580                 log_err ("pthread_create() failed: %s",
581                                 sstrerror (errno, errbuf, sizeof (errbuf)));
582                 return (-1);
583         }
585         return (0);
586 } /* int email_init */
588 static void type_list_free (type_list_t *t)
590         type_t *this;
592         this = t->head;
593         while (this != NULL)
594         {
595                 type_t *next = this->next;
597                 sfree (this->name);
598                 sfree (this);
600                 this = next;
601         }
603         t->head = NULL;
604         t->tail = NULL;
607 static int email_shutdown (void)
609         int i = 0;
611         if (connector != ((pthread_t) 0)) {
612                 pthread_kill (connector, SIGTERM);
613                 connector = (pthread_t) 0;
614         }
616         if (connector_socket >= 0) {
617                 close (connector_socket);
618                 connector_socket = -1;
619         }
621         /* don't allow any more connections to be processed */
622         pthread_mutex_lock (&conns_mutex);
624         available_collectors = 0;
626         if (collectors != NULL) {
627                 for (i = 0; i < max_conns; ++i) {
628                         if (collectors[i] == NULL)
629                                 continue;
631                         if (collectors[i]->thread != ((pthread_t) 0)) {
632                                 pthread_kill (collectors[i]->thread, SIGTERM);
633                                 collectors[i]->thread = (pthread_t) 0;
634                         }
636                         if (collectors[i]->socket != NULL) {
637                                 fclose (collectors[i]->socket);
638                                 collectors[i]->socket = NULL;
639                         }
641                         sfree (collectors[i]);
642                 }
643                 sfree (collectors);
644         } /* if (collectors != NULL) */
646         pthread_mutex_unlock (&conns_mutex);
648         type_list_free (&list_count);
649         type_list_free (&list_count_copy);
650         type_list_free (&list_size);
651         type_list_free (&list_size_copy);
652         type_list_free (&list_check);
653         type_list_free (&list_check_copy);
655         unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
657         sfree (sock_file);
658         sfree (sock_group);
659         return (0);
660 } /* static void email_shutdown (void) */
662 static void email_submit (const char *type, const char *type_instance, gauge_t value)
664         value_t values[1];
665         value_list_t vl = VALUE_LIST_INIT;
667         values[0].gauge = value;
669         vl.values = values;
670         vl.values_len = 1;
671         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
672         sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
673         sstrncpy (vl.type, type, sizeof (vl.type));
674         sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
676         plugin_dispatch_values (&vl);
677 } /* void email_submit */
679 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
680  * that neither the order nor the name of any element of either list is
681  * changed and no elements are deleted. The values of l1 are reset to zero
682  * after they have been copied to l2. */
683 static void copy_type_list (type_list_t *l1, type_list_t *l2)
685         type_t *ptr1;
686         type_t *ptr2;
688         type_t *last = NULL;
690         for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
691                         ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
692                 if (NULL == ptr2) {
693                         ptr2 = (type_t *)smalloc (sizeof (type_t));
694                         ptr2->name = NULL;
695                         ptr2->next = NULL;
697                         if (NULL == last) {
698                                 l2->head = ptr2;
699                         }
700                         else {
701                                 last->next = ptr2;
702                         }
704                         l2->tail = ptr2;
705                 }
707                 if (NULL == ptr2->name) {
708                         ptr2->name = sstrdup (ptr1->name);
709                 }
711                 ptr2->value = ptr1->value;
712                 ptr1->value = 0;
713         }
714         return;
717 static int email_read (void)
719         type_t *ptr;
721         double score_old;
722         int score_count_old;
724         if (disabled)
725                 return (-1);
727         /* email count */
728         pthread_mutex_lock (&count_mutex);
730         copy_type_list (&list_count, &list_count_copy);
732         pthread_mutex_unlock (&count_mutex);
734         for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
735                 email_submit ("email_count", ptr->name, ptr->value);
736         }
738         /* email size */
739         pthread_mutex_lock (&size_mutex);
741         copy_type_list (&list_size, &list_size_copy);
743         pthread_mutex_unlock (&size_mutex);
745         for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
746                 email_submit ("email_size", ptr->name, ptr->value);
747         }
749         /* spam score */
750         pthread_mutex_lock (&score_mutex);
752         score_old = score;
753         score_count_old = score_count;
754         score = 0.0;
755         score_count = 0;
757         pthread_mutex_unlock (&score_mutex);
759         if (score_count_old > 0)
760                 email_submit ("spam_score", "", score_old);
762         /* spam checks */
763         pthread_mutex_lock (&check_mutex);
765         copy_type_list (&list_check, &list_check_copy);
767         pthread_mutex_unlock (&check_mutex);
769         for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
770                 email_submit ("spam_check", ptr->name, ptr->value);
772         return (0);
773 } /* int email_read */
775 void module_register (void)
777         plugin_register_config ("email", email_config, config_keys, config_keys_num);
778         plugin_register_init ("email", email_init);
779         plugin_register_read ("email", email_read);
780         plugin_register_shutdown ("email", email_shutdown);
781 } /* void module_register */
783 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */