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 #define SOCK_PATH "/tmp/.collectd-email"
76 #define MAX_CONNS_LIMIT 16384
79 * Private data structures
82 /* linked list of email and check types */
94 /* linked list of collector thread control information */
95 typedef struct collector {
98 /* socket to read data from */
101 /* buffer to read data to */
102 char buffer[BUFSIZE];
103 int idx; /* current position in buffer */
105 struct collector *next;
112 #endif /* EMAIL_HAVE_READ */
118 /* valid configuration file keys */
119 static char *config_keys[] =
126 static int config_keys_num = 3;
128 /* socket configuration */
129 static char *sock_group = COLLECTD_GRP_NAME;
130 static int sock_perms = S_IRWXU | S_IRWXG;
131 static int max_conns = MAX_CONNS;
133 /* state of the plugin */
134 static int disabled = 0;
136 /* thread managing "client" connections */
137 static pthread_t connector;
139 /* tell the connector thread that a collector is available */
140 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
142 /* collector threads that are in use */
143 static pthread_mutex_t active_mutex = PTHREAD_MUTEX_INITIALIZER;
144 static collector_list_t active;
146 /* collector threads that are available for use */
147 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
148 static collector_list_t available;
150 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
151 static type_list_t count;
153 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
154 static type_list_t size;
156 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
158 static int score_count;
160 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
161 static type_list_t check;
162 #endif /* EMAIL_HAVE_READ */
164 #define COUNT_FILE "email/email-%s.rrd"
165 static char *count_ds_def[] =
167 "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
170 static int count_ds_num = 1;
172 #define SIZE_FILE "email/email_size-%s.rrd"
173 static char *size_ds_def[] =
175 "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
178 static int size_ds_num = 1;
180 #define SCORE_FILE "email/spam_score.rrd"
181 static char *score_ds_def[] =
183 "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
186 static int score_ds_num = 1;
188 #define CHECK_FILE "email/spam_check-%s.rrd"
189 static char *check_ds_def[] =
191 "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
194 static int check_ds_num = 1;
197 static int email_config (char *key, char *value)
199 if (0 == strcasecmp (key, "SocketGroup")) {
200 sock_group = sstrdup (value);
202 else if (0 == strcasecmp (key, "SocketPerms")) {
203 /* the user is responsible for providing reasonable values */
204 sock_perms = (int)strtol (value, NULL, 0);
206 else if (0 == strcasecmp (key, "MaxConns")) {
207 long int tmp = strtol (value, NULL, 0);
210 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
211 "value %li, will use default %i.\n",
213 max_conns = MAX_CONNS;
215 else if (tmp > MAX_CONNS_LIMIT) {
216 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
217 "value %li, will use hardcoded limit %i.\n",
218 tmp, MAX_CONNS_LIMIT);
219 max_conns = MAX_CONNS_LIMIT;
222 max_conns = (int)tmp;
229 } /* static int email_config (char *, char *) */
231 /* Increment the value of the given name in the given list by incr. */
232 static void type_list_incr (type_list_t *list, char *name, int incr)
234 if (NULL == list->head) {
235 list->head = (type_t *)smalloc (sizeof (type_t));
237 list->head->name = sstrdup (name);
238 list->head->value = incr;
239 list->head->next = NULL;
241 list->tail = list->head;
246 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
247 if (0 == strcmp (name, ptr->name))
252 list->tail->next = (type_t *)smalloc (sizeof (type_t));
253 list->tail = list->tail->next;
255 list->tail->name = sstrdup (name);
256 list->tail->value = incr;
257 list->tail->next = NULL;
264 } /* static void type_list_incr (type_list_t *, char *) */
266 /* Read a single character from the socket. If an error occurs or end-of-file
267 * is reached return '\0'. */
268 char read_char (collector_t *src)
275 FD_SET (src->socket, &fdset);
277 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
278 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
282 assert (FD_ISSET (src->socket, &fdset));
288 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
289 if (EINTR != errno) {
290 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
297 } while (EINTR == errno);
299 } /* char read_char (collector_t *) */
301 /* Read a single line (terminated by '\n') from the the socket.
303 * The return value is zero terminated and does not contain any newline
304 * characters. In case that no complete line is available (non-blocking mode
305 * should be enabled) an empty string is returned.
307 * If an error occurs or end-of-file is reached return NULL.
309 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
310 * characters of the input stream, the line will will be ignored! By
311 * definition we should not get any longer input lines, thus this is
312 * acceptable in this case ;-) */
313 char *read_line (collector_t *src)
318 assert (BUFSIZE > src->idx);
320 for (i = 0; i < src->idx; ++i) {
321 if ('\n' == src->buffer[i])
325 if ('\n' != src->buffer[i]) {
331 FD_SET (src->socket, &fdset);
333 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
334 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
338 assert (FD_ISSET (src->socket, &fdset));
342 if (0 > (len = read (src->socket,
343 (void *)(&(src->buffer[0]) + src->idx),
344 BUFSIZE - src->idx))) {
345 if (EINTR != errno) {
346 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
353 } while (EINTR == errno);
357 for (i = src->idx - len; i < src->idx; ++i) {
358 if ('\n' == src->buffer[i])
362 if ('\n' != src->buffer[i]) {
363 ret = (char *)smalloc (1);
367 if (BUFSIZE == src->idx) { /* no space left in buffer */
368 while ('\n' != read_char (src))
369 /* ignore complete line */;
377 ret = (char *)smalloc (i + 1);
378 memcpy (ret, &(src->buffer[0]), i + 1);
384 src->buffer[0] = '\0';
386 memmove (&(src->buffer[0]), &(src->buffer[i + 1]), src->idx);
388 } /* char *read_line (collector_t *) */
390 static void *collect (void *arg)
392 collector_t *this = (collector_t *)arg;
396 { /* put the socket in non-blocking mode */
400 if (-1 == fcntl (this->socket, F_GETFL, &flags)) {
401 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
406 if (-1 == fcntl (this->socket, F_SETFL, flags | O_NONBLOCK)) {
407 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
413 char *line = read_line (this);
420 if ('\0' == line[0]) {
425 if (':' != line[1]) {
426 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
431 if ('e' == line[0]) { /* e:<type>:<bytes> */
433 char *type = strtok_r (line + 2, ":", &ptr);
434 char *tmp = strtok_r (NULL, ":", &ptr);
438 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
445 pthread_mutex_lock (&count_mutex);
446 type_list_incr (&count, type, 1);
447 pthread_mutex_unlock (&count_mutex);
449 pthread_mutex_lock (&size_mutex);
450 type_list_incr (&size, type, bytes);
451 pthread_mutex_unlock (&size_mutex);
453 else if ('s' == line[0]) { /* s:<value> */
454 pthread_mutex_lock (&score_mutex);
455 score = (score * (double)score_count + atof (line + 2))
456 / (double)(score_count + 1);
458 pthread_mutex_unlock (&score_mutex);
460 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
462 char *type = strtok_r (line + 2, ",", &ptr);
465 pthread_mutex_lock (&check_mutex);
466 type_list_incr (&check, type, 1);
467 pthread_mutex_unlock (&check_mutex);
468 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
471 syslog (LOG_ERR, "email: unknown type '%c'", line[0]);
477 /* put this thread back into the available list */
478 pthread_mutex_lock (&active_mutex);
485 for (ptr = active.head; NULL != ptr; last = ptr, ptr = ptr->next) {
486 if (0 != pthread_equal (ptr->thread, this->thread))
490 /* the current thread _has_ to be in the active list */
491 assert (NULL != ptr);
494 active.head = ptr->next;
497 last->next = ptr->next;
499 if (NULL == last->next) {
504 pthread_mutex_unlock (&active_mutex);
508 pthread_mutex_lock (&available_mutex);
510 if (NULL == available.head) {
511 available.head = this;
512 available.tail = this;
515 available.tail->next = this;
516 available.tail = this;
519 pthread_mutex_unlock (&available_mutex);
521 pthread_cond_signal (&collector_available);
522 pthread_exit ((void *)0);
523 } /* void *collect (void *) */
525 static void *open_connection (void *arg)
529 struct sockaddr_un addr;
531 /* create UNIX socket */
533 if (-1 == (local = socket (PF_UNIX, SOCK_STREAM, 0))) {
535 syslog (LOG_ERR, "socket() failed: %s", strerror (errno));
536 pthread_exit ((void *)1);
539 addr.sun_family = AF_UNIX;
541 strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
542 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
543 unlink (addr.sun_path);
546 if (-1 == bind (local, (struct sockaddr *)&addr,
547 offsetof (struct sockaddr_un, sun_path)
548 + strlen(addr.sun_path))) {
550 syslog (LOG_ERR, "bind() failed: %s", strerror (errno));
551 pthread_exit ((void *)1);
555 if (-1 == listen (local, 5)) {
557 syslog (LOG_ERR, "listen() failed: %s", strerror (errno));
558 pthread_exit ((void *)1);
561 if ((uid_t)0 == geteuid ()) {
565 if (NULL != (grp = getgrnam (sock_group))) {
567 if (0 != chown (SOCK_PATH, (uid_t)-1, grp->gr_gid)) {
568 syslog (LOG_WARNING, "chown() failed: %s", strerror (errno));
572 syslog (LOG_WARNING, "getgrnam() failed: %s", strerror (errno));
576 syslog (LOG_WARNING, "not running as root");
580 if (0 != chmod (SOCK_PATH, sock_perms)) {
581 syslog (LOG_WARNING, "chmod() failed: %s", strerror (errno));
584 { /* initialize queue of available threads */
592 available.head = (collector_t *)smalloc (sizeof (collector_t));
593 available.tail = available.head;
594 available.tail->next = NULL;
596 last = available.head;
598 for (i = 1; i < max_conns; ++i) {
599 last->next = (collector_t *)smalloc (sizeof (collector_t));
601 available.tail = last;
602 available.tail->next = NULL;
610 collector_t *collector;
612 pthread_attr_t ptattr;
614 pthread_mutex_lock (&available_mutex);
615 while (NULL == available.head) {
616 pthread_cond_wait (&collector_available, &available_mutex);
618 pthread_mutex_unlock (&available_mutex);
622 if (-1 == (remote = accept (local, NULL, NULL))) {
623 if (EINTR != errno) {
625 syslog (LOG_ERR, "accept() failed: %s", strerror (errno));
626 pthread_exit ((void *)1);
629 } while (EINTR == errno);
631 /* assign connection to next available thread */
632 pthread_mutex_lock (&available_mutex);
634 collector = available.head;
635 collector->socket = remote;
637 if (available.head == available.tail) {
638 available.head = NULL;
639 available.tail = NULL;
642 available.head = available.head->next;
645 pthread_mutex_unlock (&available_mutex);
648 collector->next = NULL;
650 pthread_attr_init (&ptattr);
651 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
653 if (0 == (err = pthread_create (&collector->thread, &ptattr, collect,
654 (void *)collector))) {
655 pthread_mutex_lock (&active_mutex);
657 if (NULL == active.head) {
658 active.head = collector;
659 active.tail = collector;
662 active.tail->next = collector;
663 active.tail = collector;
666 pthread_mutex_unlock (&active_mutex);
669 pthread_mutex_lock (&available_mutex);
671 if (NULL == available.head) {
672 available.head = collector;
673 available.tail = collector;
676 available.tail->next = collector;
677 available.tail = collector;
680 pthread_mutex_unlock (&available_mutex);
683 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
686 pthread_attr_destroy (&ptattr);
688 pthread_exit ((void *)0);
689 } /* void *open_connection (void *) */
690 #endif /* EMAIL_HAVE_READ */
692 static void email_init (void)
697 if (0 != (err = pthread_create (&connector, NULL,
698 open_connection, NULL))) {
700 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
703 #endif /* EMAIL_HAVE_READ */
705 } /* static void email_init (void) */
707 static void count_write (char *host, char *inst, char *val)
709 char file[BUFSIZE] = "";
712 len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
713 if ((len < 0) || (len >= BUFSIZE))
716 rrd_update_file (host, file, val, count_ds_def, count_ds_num);
718 } /* static void email_write (char *host, char *inst, char *val) */
720 static void size_write (char *host, char *inst, char *val)
722 char file[BUFSIZE] = "";
725 len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
726 if ((len < 0) || (len >= BUFSIZE))
729 rrd_update_file (host, file, val, size_ds_def, size_ds_num);
731 } /* static void size_write (char *host, char *inst, char *val) */
733 static void score_write (char *host, char *inst, char *val)
735 rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
737 } /* static void score_write (char *host, char *inst, char *val) */
739 static void check_write (char *host, char *inst, char *val)
741 char file[BUFSIZE] = "";
744 len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
745 if ((len < 0) || (len >= BUFSIZE))
748 rrd_update_file (host, file, val, check_ds_def, check_ds_num);
750 } /* static void check_write (char *host, char *inst, char *val) */
753 static void type_submit (char *plugin, char *inst, int value)
755 char buf[BUFSIZE] = "";
761 len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
762 if ((len < 0) || (len >= BUFSIZE))
765 plugin_submit (plugin, inst, buf);
767 } /* static void type_submit (char *, char *, int) */
769 static void score_submit (double value)
771 char buf[BUFSIZE] = "";
777 len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
778 if ((len < 0) || (len >= BUFSIZE))
781 plugin_submit ("email_spam_score", NULL, buf);
785 static void email_read (void)
792 pthread_mutex_lock (&count_mutex);
794 for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
795 type_submit ("email_count", ptr->name, ptr->value);
799 pthread_mutex_unlock (&count_mutex);
801 pthread_mutex_lock (&size_mutex);
803 for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
804 type_submit ("email_size", ptr->name, ptr->value);
808 pthread_mutex_unlock (&size_mutex);
810 pthread_mutex_lock (&score_mutex);
812 score_submit (score);
816 pthread_mutex_unlock (&score_mutex);
818 pthread_mutex_lock (&check_mutex);
820 for (ptr = check.head; NULL != ptr; ptr = ptr->next) {
821 type_submit ("email_spam_check", ptr->name, ptr->value);
825 pthread_mutex_unlock (&check_mutex);
827 } /* static void read (void) */
828 #else /* if !EMAIL_HAVE_READ */
829 # define email_read NULL
832 void module_register (void)
834 plugin_register (MODULE_NAME, email_init, email_read, NULL);
835 plugin_register ("email_count", NULL, NULL, count_write);
836 plugin_register ("email_size", NULL, NULL, size_write);
837 plugin_register ("email_spam_score", NULL, NULL, score_write);
838 plugin_register ("email_spam_check", NULL, NULL, check_write);
840 cf_register (MODULE_NAME, email_config, config_keys, config_keys_num);
841 #endif /* EMAIL_HAVE_READ */
843 } /* void module_register (void) */
845 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */