2 * collectd - src/email.c
3 * Copyright (C) 2006 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"
45 # define EMAIL_HAVE_READ 1
47 # define EMAIL_HAVE_READ 0
51 # include <sys/select.h>
52 #endif /* HAVE_SYS_SELECT_H */
55 # include <sys/socket.h>
56 #endif /* HAVE_SYS_SOCKET_H */
58 /* *sigh* glibc does not define UNIX_PATH_MAX in sys/un.h ... */
60 # include <linux/un.h>
63 #endif /* HAVE_LINUX_UN_H | HAVE_SYS_UN_H */
67 #endif /* HAVE_GRP_H */
69 #define MODULE_NAME "email"
71 /* 256 bytes ought to be enough for anybody ;-) */
74 #ifndef COLLECTD_SOCKET_PREFIX
75 # define COLLECTD_SOCKET_PREFIX "/tmp/.collectd-"
76 #endif /* COLLECTD_SOCKET_PREFIX */
78 #define SOCK_PATH COLLECTD_SOCKET_PREFIX"email"
80 #define MAX_CONNS_LIMIT 16384
83 * Private data structures
86 /* linked list of email and check types */
98 /* linked list of collector thread control information */
99 typedef struct collector {
102 /* socket to read data from */
105 /* buffer to read data to */
106 char buffer[BUFSIZE];
107 int idx; /* current position in buffer */
109 struct collector *next;
116 #endif /* EMAIL_HAVE_READ */
122 /* valid configuration file keys */
123 static char *config_keys[] =
130 static int config_keys_num = 3;
132 /* socket configuration */
133 static char *sock_group = COLLECTD_GRP_NAME;
134 static int sock_perms = S_IRWXU | S_IRWXG;
135 static int max_conns = MAX_CONNS;
137 /* state of the plugin */
138 static int disabled = 0;
140 /* thread managing "client" connections */
141 static pthread_t connector;
142 static int connector_socket;
144 /* tell the connector thread that a collector is available */
145 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
147 /* collector threads that are in use */
148 static pthread_mutex_t active_mutex = PTHREAD_MUTEX_INITIALIZER;
149 static collector_list_t active;
151 /* collector threads that are available for use */
152 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
153 static collector_list_t available;
155 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
156 static type_list_t count;
158 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
159 static type_list_t size;
161 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
163 static int score_count;
165 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
166 static type_list_t check;
167 #endif /* EMAIL_HAVE_READ */
169 #define COUNT_FILE "email/email-%s.rrd"
170 static char *count_ds_def[] =
172 "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
175 static int count_ds_num = 1;
177 #define SIZE_FILE "email/email_size-%s.rrd"
178 static char *size_ds_def[] =
180 "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
183 static int size_ds_num = 1;
185 #define SCORE_FILE "email/spam_score.rrd"
186 static char *score_ds_def[] =
188 "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
191 static int score_ds_num = 1;
193 #define CHECK_FILE "email/spam_check-%s.rrd"
194 static char *check_ds_def[] =
196 "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
199 static int check_ds_num = 1;
202 static int email_config (char *key, char *value)
204 if (0 == strcasecmp (key, "SocketGroup")) {
205 sock_group = sstrdup (value);
207 else if (0 == strcasecmp (key, "SocketPerms")) {
208 /* the user is responsible for providing reasonable values */
209 sock_perms = (int)strtol (value, NULL, 0);
211 else if (0 == strcasecmp (key, "MaxConns")) {
212 long int tmp = strtol (value, NULL, 0);
215 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
216 "value %li, will use default %i.\n",
218 max_conns = MAX_CONNS;
220 else if (tmp > MAX_CONNS_LIMIT) {
221 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
222 "value %li, will use hardcoded limit %i.\n",
223 tmp, MAX_CONNS_LIMIT);
224 max_conns = MAX_CONNS_LIMIT;
227 max_conns = (int)tmp;
234 } /* static int email_config (char *, char *) */
236 /* Increment the value of the given name in the given list by incr. */
237 static void type_list_incr (type_list_t *list, char *name, int incr)
239 if (NULL == list->head) {
240 list->head = (type_t *)smalloc (sizeof (type_t));
242 list->head->name = sstrdup (name);
243 list->head->value = incr;
244 list->head->next = NULL;
246 list->tail = list->head;
251 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
252 if (0 == strcmp (name, ptr->name))
257 list->tail->next = (type_t *)smalloc (sizeof (type_t));
258 list->tail = list->tail->next;
260 list->tail->name = sstrdup (name);
261 list->tail->value = incr;
262 list->tail->next = NULL;
269 } /* static void type_list_incr (type_list_t *, char *) */
271 /* Read a single character from the socket. If an error occurs or end-of-file
272 * is reached return '\0'. */
273 char read_char (collector_t *src)
280 FD_SET (src->socket, &fdset);
282 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
283 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
287 assert (FD_ISSET (src->socket, &fdset));
293 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
294 if (EINTR != errno) {
295 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
302 } while (EINTR == errno);
304 } /* char read_char (collector_t *) */
306 /* Read a single line (terminated by '\n') from the the socket.
308 * The return value is zero terminated and does not contain any newline
309 * characters. In case that no complete line is available (non-blocking mode
310 * should be enabled) an empty string is returned.
312 * If an error occurs or end-of-file is reached return NULL.
314 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
315 * characters of the input stream, the line will will be ignored! By
316 * definition we should not get any longer input lines, thus this is
317 * acceptable in this case ;-) */
318 char *read_line (collector_t *src)
323 assert (BUFSIZE > src->idx);
325 for (i = 0; i < src->idx; ++i) {
326 if ('\n' == src->buffer[i])
330 if ('\n' != src->buffer[i]) {
336 FD_SET (src->socket, &fdset);
338 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
339 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
343 assert (FD_ISSET (src->socket, &fdset));
347 if (0 > (len = read (src->socket,
348 (void *)(&(src->buffer[0]) + src->idx),
349 BUFSIZE - src->idx))) {
350 if (EINTR != errno) {
351 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
358 } while (EINTR == errno);
362 for (i = src->idx - len; i < src->idx; ++i) {
363 if ('\n' == src->buffer[i])
367 if ('\n' != src->buffer[i]) {
368 ret = (char *)smalloc (1);
372 if (BUFSIZE == src->idx) { /* no space left in buffer */
373 while ('\n' != read_char (src))
374 /* ignore complete line */;
382 ret = (char *)smalloc (i + 1);
383 memcpy (ret, &(src->buffer[0]), i + 1);
389 src->buffer[0] = '\0';
391 memmove (&(src->buffer[0]), &(src->buffer[i + 1]), src->idx);
393 } /* char *read_line (collector_t *) */
395 static void *collect (void *arg)
397 collector_t *this = (collector_t *)arg;
401 { /* put the socket in non-blocking mode */
405 if (-1 == fcntl (this->socket, F_GETFL, &flags)) {
406 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
411 if (-1 == fcntl (this->socket, F_SETFL, flags | O_NONBLOCK)) {
412 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
418 char *line = read_line (this);
425 if ('\0' == line[0]) {
430 if (':' != line[1]) {
431 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
436 if ('e' == line[0]) { /* e:<type>:<bytes> */
438 char *type = strtok_r (line + 2, ":", &ptr);
439 char *tmp = strtok_r (NULL, ":", &ptr);
443 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
450 pthread_mutex_lock (&count_mutex);
451 type_list_incr (&count, type, 1);
452 pthread_mutex_unlock (&count_mutex);
454 pthread_mutex_lock (&size_mutex);
455 type_list_incr (&size, type, bytes);
456 pthread_mutex_unlock (&size_mutex);
458 else if ('s' == line[0]) { /* s:<value> */
459 pthread_mutex_lock (&score_mutex);
460 score = (score * (double)score_count + atof (line + 2))
461 / (double)(score_count + 1);
463 pthread_mutex_unlock (&score_mutex);
465 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
467 char *type = strtok_r (line + 2, ",", &ptr);
470 pthread_mutex_lock (&check_mutex);
471 type_list_incr (&check, type, 1);
472 pthread_mutex_unlock (&check_mutex);
473 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
476 syslog (LOG_ERR, "email: unknown type '%c'", line[0]);
482 /* put this thread back into the available list */
483 pthread_mutex_lock (&active_mutex);
490 for (ptr = active.head; NULL != ptr; last = ptr, ptr = ptr->next) {
491 if (0 != pthread_equal (ptr->thread, this->thread))
495 /* the current thread _has_ to be in the active list */
496 assert (NULL != ptr);
499 active.head = ptr->next;
502 last->next = ptr->next;
504 if (NULL == last->next) {
509 pthread_mutex_unlock (&active_mutex);
513 pthread_mutex_lock (&available_mutex);
515 if (NULL == available.head) {
516 available.head = this;
517 available.tail = this;
520 available.tail->next = this;
521 available.tail = this;
524 pthread_mutex_unlock (&available_mutex);
526 pthread_cond_signal (&collector_available);
527 pthread_exit ((void *)0);
528 } /* void *collect (void *) */
530 static void *open_connection (void *arg)
532 struct sockaddr_un addr;
534 /* create UNIX socket */
536 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
538 syslog (LOG_ERR, "socket() failed: %s", strerror (errno));
539 pthread_exit ((void *)1);
542 addr.sun_family = AF_UNIX;
544 strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
545 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
546 unlink (addr.sun_path);
549 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
550 offsetof (struct sockaddr_un, sun_path)
551 + strlen(addr.sun_path))) {
553 syslog (LOG_ERR, "bind() failed: %s", strerror (errno));
554 pthread_exit ((void *)1);
558 if (-1 == listen (connector_socket, 5)) {
560 syslog (LOG_ERR, "listen() failed: %s", strerror (errno));
561 pthread_exit ((void *)1);
564 if ((uid_t)0 == geteuid ()) {
568 if (NULL != (grp = getgrnam (sock_group))) {
570 if (0 != chown (SOCK_PATH, (uid_t)-1, grp->gr_gid)) {
571 syslog (LOG_WARNING, "chown() failed: %s", strerror (errno));
575 syslog (LOG_WARNING, "getgrnam() failed: %s", strerror (errno));
579 syslog (LOG_WARNING, "not running as root");
583 if (0 != chmod (SOCK_PATH, sock_perms)) {
584 syslog (LOG_WARNING, "chmod() failed: %s", strerror (errno));
587 { /* initialize queue of available threads */
595 available.head = (collector_t *)smalloc (sizeof (collector_t));
596 available.tail = available.head;
597 available.tail->next = NULL;
599 last = available.head;
601 for (i = 1; i < max_conns; ++i) {
602 last->next = (collector_t *)smalloc (sizeof (collector_t));
604 available.tail = last;
605 available.tail->next = NULL;
613 collector_t *collector;
615 pthread_attr_t ptattr;
617 pthread_mutex_lock (&available_mutex);
618 while (NULL == available.head) {
619 pthread_cond_wait (&collector_available, &available_mutex);
621 pthread_mutex_unlock (&available_mutex);
625 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
626 if (EINTR != errno) {
628 syslog (LOG_ERR, "accept() failed: %s", strerror (errno));
629 pthread_exit ((void *)1);
632 } while (EINTR == errno);
634 /* assign connection to next available thread */
635 pthread_mutex_lock (&available_mutex);
637 collector = available.head;
638 collector->socket = remote;
640 if (available.head == available.tail) {
641 available.head = NULL;
642 available.tail = NULL;
645 available.head = available.head->next;
648 pthread_mutex_unlock (&available_mutex);
651 collector->next = NULL;
653 pthread_attr_init (&ptattr);
654 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
656 if (0 == (err = pthread_create (&collector->thread, &ptattr, collect,
657 (void *)collector))) {
658 pthread_mutex_lock (&active_mutex);
660 if (NULL == active.head) {
661 active.head = collector;
662 active.tail = collector;
665 active.tail->next = collector;
666 active.tail = collector;
669 pthread_mutex_unlock (&active_mutex);
672 pthread_mutex_lock (&available_mutex);
674 if (NULL == available.head) {
675 available.head = collector;
676 available.tail = collector;
679 available.tail->next = collector;
680 available.tail = collector;
683 pthread_mutex_unlock (&available_mutex);
686 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
689 pthread_attr_destroy (&ptattr);
691 pthread_exit ((void *)0);
692 } /* void *open_connection (void *) */
693 #endif /* EMAIL_HAVE_READ */
695 static void email_init (void)
700 if (0 != (err = pthread_create (&connector, NULL,
701 open_connection, NULL))) {
703 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
706 #endif /* EMAIL_HAVE_READ */
708 } /* static void email_init (void) */
711 static void email_shutdown (void)
718 close (connector_socket);
719 pthread_kill (connector, SIGTERM);
721 pthread_mutex_lock (&active_mutex);
723 for (ptr = active.head; NULL != ptr; ptr = ptr->next) {
725 pthread_kill (ptr->thread, SIGTERM);
728 pthread_mutex_unlock (&active_mutex);
732 } /* static void email_shutdown (void) */
733 #endif /* EMAIL_HAVE_READ */
735 static void count_write (char *host, char *inst, char *val)
737 char file[BUFSIZE] = "";
740 len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
741 if ((len < 0) || (len >= BUFSIZE))
744 rrd_update_file (host, file, val, count_ds_def, count_ds_num);
746 } /* static void email_write (char *host, char *inst, char *val) */
748 static void size_write (char *host, char *inst, char *val)
750 char file[BUFSIZE] = "";
753 len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
754 if ((len < 0) || (len >= BUFSIZE))
757 rrd_update_file (host, file, val, size_ds_def, size_ds_num);
759 } /* static void size_write (char *host, char *inst, char *val) */
761 static void score_write (char *host, char *inst, char *val)
763 rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
765 } /* static void score_write (char *host, char *inst, char *val) */
767 static void check_write (char *host, char *inst, char *val)
769 char file[BUFSIZE] = "";
772 len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
773 if ((len < 0) || (len >= BUFSIZE))
776 rrd_update_file (host, file, val, check_ds_def, check_ds_num);
778 } /* static void check_write (char *host, char *inst, char *val) */
781 static void type_submit (char *plugin, char *inst, int value)
783 char buf[BUFSIZE] = "";
789 len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
790 if ((len < 0) || (len >= BUFSIZE))
793 plugin_submit (plugin, inst, buf);
795 } /* static void type_submit (char *, char *, int) */
797 static void score_submit (double value)
799 char buf[BUFSIZE] = "";
805 len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
806 if ((len < 0) || (len >= BUFSIZE))
809 plugin_submit ("email_spam_score", NULL, buf);
813 static void email_read (void)
820 pthread_mutex_lock (&count_mutex);
822 for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
823 type_submit ("email_count", ptr->name, ptr->value);
827 pthread_mutex_unlock (&count_mutex);
829 pthread_mutex_lock (&size_mutex);
831 for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
832 type_submit ("email_size", ptr->name, ptr->value);
836 pthread_mutex_unlock (&size_mutex);
838 pthread_mutex_lock (&score_mutex);
840 score_submit (score);
844 pthread_mutex_unlock (&score_mutex);
846 pthread_mutex_lock (&check_mutex);
848 for (ptr = check.head; NULL != ptr; ptr = ptr->next) {
849 type_submit ("email_spam_check", ptr->name, ptr->value);
853 pthread_mutex_unlock (&check_mutex);
855 } /* static void read (void) */
856 #else /* if !EMAIL_HAVE_READ */
857 # define email_read NULL
860 void module_register (void)
862 plugin_register (MODULE_NAME, email_init, email_read, NULL);
863 plugin_register ("email_count", NULL, NULL, count_write);
864 plugin_register ("email_size", NULL, NULL, size_write);
865 plugin_register ("email_spam_score", NULL, NULL, score_write);
866 plugin_register ("email_spam_check", NULL, NULL, check_write);
868 plugin_register_shutdown (MODULE_NAME, email_shutdown);
869 cf_register (MODULE_NAME, email_config, config_keys, config_keys_num);
870 #endif /* EMAIL_HAVE_READ */
872 } /* void module_register (void) */
874 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */