2 * collectd - src/email.c
3 * Copyright (C) 2006,2007 Sebastian Harl
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * Sebastian Harl <sh at tokkee.org>
24 * This plugin communicates with a spam filter, a virus scanner or similar
25 * software using a UNIX socket and a very simple protocol:
27 * e-mail type (e.g. ham, spam, virus, ...) and size
33 * successful spam checks
34 * c:<type1>[,<type2>,...]
41 #include "configfile.h"
48 # include <sys/select.h>
49 #endif /* HAVE_SYS_SELECT_H */
52 # include <sys/socket.h>
53 #endif /* HAVE_SYS_SOCKET_H */
55 /* *sigh* glibc does not define UNIX_PATH_MAX in sys/un.h ... */
57 # include <linux/un.h>
60 #endif /* HAVE_LINUX_UN_H | HAVE_SYS_UN_H */
62 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
64 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
65 #endif /* UNIX_PATH_MAX */
69 #endif /* HAVE_GRP_H */
71 #define MODULE_NAME "email"
73 /* 256 bytes ought to be enough for anybody ;-) */
76 #ifndef COLLECTD_SOCKET_PREFIX
77 # define COLLECTD_SOCKET_PREFIX "/tmp/.collectd-"
78 #endif /* COLLECTD_SOCKET_PREFIX */
80 #define SOCK_PATH COLLECTD_SOCKET_PREFIX"email"
82 #define MAX_CONNS_LIMIT 16384
84 #define log_err(...) ERROR (MODULE_NAME": "__VA_ARGS__)
85 #define log_warn(...) WARNING (MODULE_NAME": "__VA_ARGS__)
88 * Private data structures
90 /* linked list of email and check types */
102 /* collector thread control information */
103 typedef struct collector {
106 /* socket descriptor of the current/last connection */
110 /* linked list of pending connections */
111 typedef struct conn {
112 /* socket to read data from */
115 /* buffer to read data to */
117 int idx; /* current write position in buffer */
118 int length; /* length of the current line, i.e. index of '\0' */
131 /* valid configuration file keys */
132 static const char *config_keys[] =
138 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
140 /* socket configuration */
141 static char *sock_group = COLLECTD_GRP_NAME;
142 static int sock_perms = S_IRWXU | S_IRWXG;
143 static int max_conns = MAX_CONNS;
145 /* state of the plugin */
146 static int disabled = 0;
148 /* thread managing "client" connections */
149 static pthread_t connector = (pthread_t) 0;
150 static int connector_socket = -1;
152 /* tell the collector threads that a new connection is available */
153 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
155 /* connections that are waiting to be processed */
156 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
157 static conn_list_t conns;
159 /* tell the connector thread that a collector is available */
160 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
162 /* collector threads */
163 static collector_t **collectors = NULL;
165 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
166 static int available_collectors;
168 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
169 static type_list_t count;
171 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
172 static type_list_t size;
174 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
176 static int score_count;
178 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
179 static type_list_t check;
184 static int email_config (const char *key, const char *value)
186 if (0 == strcasecmp (key, "SocketGroup")) {
187 sock_group = sstrdup (value);
189 else if (0 == strcasecmp (key, "SocketPerms")) {
190 /* the user is responsible for providing reasonable values */
191 sock_perms = (int)strtol (value, NULL, 8);
193 else if (0 == strcasecmp (key, "MaxConns")) {
194 long int tmp = strtol (value, NULL, 0);
197 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
198 "value %li, will use default %i.\n",
200 max_conns = MAX_CONNS;
202 else if (tmp > MAX_CONNS_LIMIT) {
203 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
204 "value %li, will use hardcoded limit %i.\n",
205 tmp, MAX_CONNS_LIMIT);
206 max_conns = MAX_CONNS_LIMIT;
209 max_conns = (int)tmp;
216 } /* static int email_config (char *, char *) */
218 /* Increment the value of the given name in the given list by incr. */
219 static void type_list_incr (type_list_t *list, char *name, int incr)
221 if (NULL == list->head) {
222 list->head = (type_t *)smalloc (sizeof (type_t));
224 list->head->name = sstrdup (name);
225 list->head->value = incr;
226 list->head->next = NULL;
228 list->tail = list->head;
233 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
234 if (0 == strcmp (name, ptr->name))
239 list->tail->next = (type_t *)smalloc (sizeof (type_t));
240 list->tail = list->tail->next;
242 list->tail->name = sstrdup (name);
243 list->tail->value = incr;
244 list->tail->next = NULL;
251 } /* static void type_list_incr (type_list_t *, char *) */
253 /* Read a single character from the socket. If an error occurs or end-of-file
254 * is reached return '\0'. */
255 static char read_char (conn_t *src)
262 FD_SET (src->socket, &fdset);
264 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
266 log_err ("select() failed: %s",
267 sstrerror (errno, errbuf, sizeof (errbuf)));
271 assert (FD_ISSET (src->socket, &fdset));
277 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
278 if (EINTR != errno) {
280 log_err ("read() failed: %s",
281 sstrerror (errno, errbuf, sizeof (errbuf)));
288 } while (EINTR == errno);
290 } /* static char read_char (conn_t *) */
292 /* Read a single line (terminated by '\n') from the the socket.
294 * The return value is zero terminated and does not contain any newline
297 * If an error occurs or end-of-file is reached return NULL.
299 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
300 * characters of the input stream, the line will will be ignored! By
301 * definition we should not get any longer input lines, thus this is
302 * acceptable in this case ;-) */
303 static char *read_line (conn_t *src)
307 assert ((BUFSIZE >= src->idx) && (src->idx >= 0));
308 assert ((src->idx > src->length) || (src->length == 0));
310 if (src->length > 0) { /* remove old line */
311 src->idx -= (src->length + 1);
312 memmove (src->buffer, src->buffer + src->length + 1, src->idx);
316 for (i = 0; i < src->idx; ++i) {
317 if ('\n' == src->buffer[i])
327 FD_SET (src->socket, &fdset);
329 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
331 log_err ("select() failed: %s",
332 sstrerror (errno, errbuf, sizeof (errbuf)));
336 assert (FD_ISSET (src->socket, &fdset));
340 if (0 > (len = read (src->socket,
341 (void *)(src->buffer + src->idx),
342 BUFSIZE - src->idx))) {
343 if (EINTR != errno) {
345 log_err ("read() failed: %s",
346 sstrerror (errno, errbuf, sizeof (errbuf)));
353 } while (EINTR == errno);
357 for (i = src->idx - len; i < src->idx; ++i) {
358 if ('\n' == src->buffer[i])
365 if (BUFSIZE == src->idx) { /* no space left in buffer */
366 while ('\n' != read_char (src))
367 /* ignore complete line */;
371 return read_line (src);
375 src->buffer[i] = '\0';
379 } /* static char *read_line (conn_t *) */
381 static void *collect (void *arg)
383 collector_t *this = (collector_t *)arg;
385 char *buffer = (char *)smalloc (BUFSIZE);
392 pthread_mutex_lock (&conns_mutex);
394 while (NULL == conns.head) {
395 pthread_cond_wait (&conn_available, &conns_mutex);
398 connection = conns.head;
399 conns.head = conns.head->next;
401 if (NULL == conns.head) {
405 this->socket = connection->socket;
407 pthread_mutex_unlock (&conns_mutex);
409 connection->buffer = buffer;
411 connection->length = 0;
413 { /* put the socket in non-blocking mode */
417 if (-1 == fcntl (connection->socket, F_GETFL, &flags)) {
419 log_err ("fcntl() failed: %s",
420 sstrerror (errno, errbuf, sizeof (errbuf)));
425 if (-1 == fcntl (connection->socket, F_SETFL, flags | O_NONBLOCK)) {
427 log_err ("fcntl() failed: %s",
428 sstrerror (errno, errbuf, sizeof (errbuf)));
434 char *line = read_line (connection);
441 if (':' != line[1]) {
442 log_err ("syntax error in line '%s'", line);
446 if ('e' == line[0]) { /* e:<type>:<bytes> */
448 char *type = strtok_r (line + 2, ":", &ptr);
449 char *tmp = strtok_r (NULL, ":", &ptr);
453 log_err ("syntax error in line '%s'", line);
459 pthread_mutex_lock (&count_mutex);
460 type_list_incr (&count, type, 1);
461 pthread_mutex_unlock (&count_mutex);
464 pthread_mutex_lock (&size_mutex);
465 type_list_incr (&size, type, bytes);
466 pthread_mutex_unlock (&size_mutex);
469 else if ('s' == line[0]) { /* s:<value> */
470 pthread_mutex_lock (&score_mutex);
471 score = (score * (double)score_count + atof (line + 2))
472 / (double)(score_count + 1);
474 pthread_mutex_unlock (&score_mutex);
476 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
478 char *type = strtok_r (line + 2, ",", &ptr);
481 pthread_mutex_lock (&check_mutex);
482 type_list_incr (&check, type, 1);
483 pthread_mutex_unlock (&check_mutex);
484 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
487 log_err ("unknown type '%c'", line[0]);
491 close (connection->socket);
496 pthread_mutex_lock (&available_mutex);
497 ++available_collectors;
498 pthread_mutex_unlock (&available_mutex);
500 pthread_cond_signal (&collector_available);
504 pthread_exit ((void *)0);
505 } /* static void *collect (void *) */
507 static void *open_connection (void *arg)
509 struct sockaddr_un addr;
511 /* create UNIX socket */
513 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
516 log_err ("socket() failed: %s",
517 sstrerror (errno, errbuf, sizeof (errbuf)));
518 pthread_exit ((void *)1);
521 addr.sun_family = AF_UNIX;
523 strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
524 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
525 unlink (addr.sun_path);
528 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
529 offsetof (struct sockaddr_un, sun_path)
530 + strlen(addr.sun_path))) {
533 connector_socket = -1; /* TODO: close? */
534 log_err ("bind() failed: %s",
535 sstrerror (errno, errbuf, sizeof (errbuf)));
536 pthread_exit ((void *)1);
540 if (-1 == listen (connector_socket, 5)) {
543 connector_socket = -1; /* TODO: close? */
544 log_err ("listen() failed: %s",
545 sstrerror (errno, errbuf, sizeof (errbuf)));
546 pthread_exit ((void *)1);
549 if ((uid_t) 0 == geteuid ())
557 status = getgrnam_r (sock_group, &sg, grbuf, sizeof (grbuf), &grp);
561 log_warn ("getgrnam_r (%s) failed: %s", sock_group,
562 sstrerror (errno, errbuf, sizeof (errbuf)));
564 else if (grp == NULL)
566 log_warn ("No such group: `%s'", sock_group);
570 status = chown (SOCK_PATH, (uid_t) -1, grp->gr_gid);
574 log_warn ("chown (%s, -1, %i) failed: %s",
575 SOCK_PATH, (int) grp->gr_gid,
576 sstrerror (errno, errbuf, sizeof (errbuf)));
580 else /* geteuid != 0 */
582 log_warn ("not running as root");
586 if (0 != chmod (SOCK_PATH, sock_perms)) {
588 log_warn ("chmod() failed: %s",
589 sstrerror (errno, errbuf, sizeof (errbuf)));
592 { /* initialize collector threads */
596 pthread_attr_t ptattr;
601 pthread_attr_init (&ptattr);
602 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
604 available_collectors = max_conns;
607 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
609 for (i = 0; i < max_conns; ++i) {
610 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
611 collectors[i]->socket = -1;
613 if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
614 collect, collectors[i]))) {
616 log_err ("pthread_create() failed: %s",
617 sstrerror (errno, errbuf, sizeof (errbuf)));
618 collectors[i]->thread = (pthread_t) 0;
622 pthread_attr_destroy (&ptattr);
630 pthread_mutex_lock (&available_mutex);
632 while (0 == available_collectors) {
633 pthread_cond_wait (&collector_available, &available_mutex);
636 --available_collectors;
638 pthread_mutex_unlock (&available_mutex);
642 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
643 if (EINTR != errno) {
646 connector_socket = -1; /* TODO: close? */
647 log_err ("accept() failed: %s",
648 sstrerror (errno, errbuf, sizeof (errbuf)));
649 pthread_exit ((void *)1);
652 } while (EINTR == errno);
654 connection = (conn_t *)smalloc (sizeof (conn_t));
656 connection->socket = remote;
657 connection->next = NULL;
659 pthread_mutex_lock (&conns_mutex);
661 if (NULL == conns.head) {
662 conns.head = connection;
663 conns.tail = connection;
666 conns.tail->next = connection;
667 conns.tail = conns.tail->next;
670 pthread_mutex_unlock (&conns_mutex);
672 pthread_cond_signal (&conn_available);
674 pthread_exit ((void *)0);
675 } /* static void *open_connection (void *) */
677 static int email_init (void)
681 if (0 != (err = pthread_create (&connector, NULL,
682 open_connection, NULL))) {
685 log_err ("pthread_create() failed: %s",
686 sstrerror (errno, errbuf, sizeof (errbuf)));
691 } /* int email_init */
693 static int email_shutdown (void)
697 if (connector != ((pthread_t) 0)) {
698 pthread_kill (connector, SIGTERM);
699 connector = (pthread_t) 0;
702 if (connector_socket >= 0) {
703 close (connector_socket);
704 connector_socket = -1;
707 /* don't allow any more connections to be processed */
708 pthread_mutex_lock (&conns_mutex);
710 if (collectors != NULL) {
711 for (i = 0; i < max_conns; ++i) {
712 if (collectors[i] == NULL)
715 if (collectors[i]->thread != ((pthread_t) 0)) {
716 pthread_kill (collectors[i]->thread, SIGTERM);
717 collectors[i]->thread = (pthread_t) 0;
720 if (collectors[i]->socket >= 0) {
721 close (collectors[i]->socket);
722 collectors[i]->socket = -1;
725 } /* if (collectors != NULL) */
727 pthread_mutex_unlock (&conns_mutex);
733 } /* static void email_shutdown (void) */
735 static void email_submit (const char *type, const char *type_instance, gauge_t value)
738 value_list_t vl = VALUE_LIST_INIT;
740 values[0].gauge = value;
744 vl.time = time (NULL);
745 strcpy (vl.host, hostname_g);
746 strcpy (vl.plugin, "email");
747 strncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
749 plugin_dispatch_values (type, &vl);
750 } /* void email_submit */
752 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
753 * that neither the order nor the name of any element of either list is
754 * changed and no elements are deleted. The values of l1 are reset to zero
755 * after they have been copied to l2. */
756 static void copy_type_list (type_list_t *l1, type_list_t *l2)
763 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
764 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
766 ptr2 = (type_t *)smalloc (sizeof (type_t));
780 if (NULL == ptr2->name) {
781 ptr2->name = sstrdup (ptr1->name);
784 ptr2->value = ptr1->value;
790 static int email_read (void)
796 static type_list_t *cnt;
797 static type_list_t *sz;
798 static type_list_t *chk;
804 cnt = (type_list_t *)smalloc (sizeof (type_list_t));
809 sz = (type_list_t *)smalloc (sizeof (type_list_t));
814 chk = (type_list_t *)smalloc (sizeof (type_list_t));
819 pthread_mutex_lock (&count_mutex);
821 copy_type_list (&count, cnt);
823 pthread_mutex_unlock (&count_mutex);
825 for (ptr = cnt->head; NULL != ptr; ptr = ptr->next) {
826 email_submit ("email_count", ptr->name, ptr->value);
830 pthread_mutex_lock (&size_mutex);
832 copy_type_list (&size, sz);
834 pthread_mutex_unlock (&size_mutex);
836 for (ptr = sz->head; NULL != ptr; ptr = ptr->next) {
837 email_submit ("email_size", ptr->name, ptr->value);
841 pthread_mutex_lock (&score_mutex);
847 pthread_mutex_unlock (&score_mutex);
849 email_submit ("spam_score", "", sc);
852 pthread_mutex_lock (&check_mutex);
854 copy_type_list (&check, chk);
856 pthread_mutex_unlock (&check_mutex);
858 for (ptr = chk->head; NULL != ptr; ptr = ptr->next)
859 email_submit ("spam_check", ptr->name, ptr->value);
862 } /* int email_read */
864 void module_register (void)
866 plugin_register_config ("email", email_config, config_keys, config_keys_num);
867 plugin_register_init ("email", email_init);
868 plugin_register_read ("email", email_read);
869 plugin_register_shutdown ("email", email_shutdown);
870 } /* void module_register */
872 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */