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 */
65 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
67 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
68 #endif /* UNIX_PATH_MAX */
72 #endif /* HAVE_GRP_H */
74 #define MODULE_NAME "email"
76 /* 256 bytes ought to be enough for anybody ;-) */
79 #ifndef COLLECTD_SOCKET_PREFIX
80 # define COLLECTD_SOCKET_PREFIX "/tmp/.collectd-"
81 #endif /* COLLECTD_SOCKET_PREFIX */
83 #define SOCK_PATH COLLECTD_SOCKET_PREFIX"email"
85 #define MAX_CONNS_LIMIT 16384
88 * Private data structures
91 /* linked list of email and check types */
103 /* linked list of collector thread control information */
104 typedef struct collector {
107 /* socket to read data from */
110 /* buffer to read data to */
111 char buffer[BUFSIZE];
112 int idx; /* current position in buffer */
114 struct collector *next;
121 #endif /* EMAIL_HAVE_READ */
127 /* valid configuration file keys */
128 static char *config_keys[] =
135 static int config_keys_num = 3;
137 /* socket configuration */
138 static char *sock_group = COLLECTD_GRP_NAME;
139 static int sock_perms = S_IRWXU | S_IRWXG;
140 static int max_conns = MAX_CONNS;
142 /* state of the plugin */
143 static int disabled = 0;
145 /* thread managing "client" connections */
146 static pthread_t connector;
147 static int connector_socket;
149 /* tell the connector thread that a collector is available */
150 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
152 /* collector threads that are in use */
153 static pthread_mutex_t active_mutex = PTHREAD_MUTEX_INITIALIZER;
154 static collector_list_t active;
156 /* collector threads that are available for use */
157 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
158 static collector_list_t available;
160 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
161 static type_list_t count;
163 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
164 static type_list_t size;
166 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
168 static int score_count;
170 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
171 static type_list_t check;
172 #endif /* EMAIL_HAVE_READ */
174 #define COUNT_FILE "email/email-%s.rrd"
175 static char *count_ds_def[] =
177 "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
180 static int count_ds_num = 1;
182 #define SIZE_FILE "email/email_size-%s.rrd"
183 static char *size_ds_def[] =
185 "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
188 static int size_ds_num = 1;
190 #define SCORE_FILE "email/spam_score.rrd"
191 static char *score_ds_def[] =
193 "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
196 static int score_ds_num = 1;
198 #define CHECK_FILE "email/spam_check-%s.rrd"
199 static char *check_ds_def[] =
201 "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
204 static int check_ds_num = 1;
207 static int email_config (char *key, char *value)
209 if (0 == strcasecmp (key, "SocketGroup")) {
210 sock_group = sstrdup (value);
212 else if (0 == strcasecmp (key, "SocketPerms")) {
213 /* the user is responsible for providing reasonable values */
214 sock_perms = (int)strtol (value, NULL, 8);
216 else if (0 == strcasecmp (key, "MaxConns")) {
217 long int tmp = strtol (value, NULL, 0);
220 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
221 "value %li, will use default %i.\n",
223 max_conns = MAX_CONNS;
225 else if (tmp > MAX_CONNS_LIMIT) {
226 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
227 "value %li, will use hardcoded limit %i.\n",
228 tmp, MAX_CONNS_LIMIT);
229 max_conns = MAX_CONNS_LIMIT;
232 max_conns = (int)tmp;
239 } /* static int email_config (char *, char *) */
241 /* Increment the value of the given name in the given list by incr. */
242 static void type_list_incr (type_list_t *list, char *name, int incr)
244 if (NULL == list->head) {
245 list->head = (type_t *)smalloc (sizeof (type_t));
247 list->head->name = sstrdup (name);
248 list->head->value = incr;
249 list->head->next = NULL;
251 list->tail = list->head;
256 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
257 if (0 == strcmp (name, ptr->name))
262 list->tail->next = (type_t *)smalloc (sizeof (type_t));
263 list->tail = list->tail->next;
265 list->tail->name = sstrdup (name);
266 list->tail->value = incr;
267 list->tail->next = NULL;
274 } /* static void type_list_incr (type_list_t *, char *) */
276 /* Read a single character from the socket. If an error occurs or end-of-file
277 * is reached return '\0'. */
278 char read_char (collector_t *src)
285 FD_SET (src->socket, &fdset);
287 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
288 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
292 assert (FD_ISSET (src->socket, &fdset));
298 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
299 if (EINTR != errno) {
300 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
307 } while (EINTR == errno);
309 } /* char read_char (collector_t *) */
311 /* Read a single line (terminated by '\n') from the the socket.
313 * The return value is zero terminated and does not contain any newline
314 * characters. In case that no complete line is available (non-blocking mode
315 * should be enabled) an empty string is returned.
317 * If an error occurs or end-of-file is reached return NULL.
319 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
320 * characters of the input stream, the line will will be ignored! By
321 * definition we should not get any longer input lines, thus this is
322 * acceptable in this case ;-) */
323 char *read_line (collector_t *src)
328 assert (BUFSIZE > src->idx);
330 for (i = 0; i < src->idx; ++i) {
331 if ('\n' == src->buffer[i])
335 if ('\n' != src->buffer[i]) {
341 FD_SET (src->socket, &fdset);
343 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
344 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
348 assert (FD_ISSET (src->socket, &fdset));
352 if (0 > (len = read (src->socket,
353 (void *)(&(src->buffer[0]) + src->idx),
354 BUFSIZE - src->idx))) {
355 if (EINTR != errno) {
356 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
363 } while (EINTR == errno);
367 for (i = src->idx - len; i < src->idx; ++i) {
368 if ('\n' == src->buffer[i])
372 if ('\n' != src->buffer[i]) {
373 ret = (char *)smalloc (1);
377 if (BUFSIZE == src->idx) { /* no space left in buffer */
378 while ('\n' != read_char (src))
379 /* ignore complete line */;
387 ret = (char *)smalloc (i + 1);
388 memcpy (ret, &(src->buffer[0]), i + 1);
394 src->buffer[0] = '\0';
396 memmove (&(src->buffer[0]), &(src->buffer[i + 1]), src->idx);
398 } /* char *read_line (collector_t *) */
400 static void *collect (void *arg)
402 collector_t *this = (collector_t *)arg;
406 { /* put the socket in non-blocking mode */
410 if (-1 == fcntl (this->socket, F_GETFL, &flags)) {
411 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
416 if (-1 == fcntl (this->socket, F_SETFL, flags | O_NONBLOCK)) {
417 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
423 char *line = read_line (this);
430 if ('\0' == line[0]) {
435 if (':' != line[1]) {
436 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
441 if ('e' == line[0]) { /* e:<type>:<bytes> */
443 char *type = strtok_r (line + 2, ":", &ptr);
444 char *tmp = strtok_r (NULL, ":", &ptr);
448 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
455 pthread_mutex_lock (&count_mutex);
456 type_list_incr (&count, type, 1);
457 pthread_mutex_unlock (&count_mutex);
459 pthread_mutex_lock (&size_mutex);
460 type_list_incr (&size, type, bytes);
461 pthread_mutex_unlock (&size_mutex);
463 else if ('s' == line[0]) { /* s:<value> */
464 pthread_mutex_lock (&score_mutex);
465 score = (score * (double)score_count + atof (line + 2))
466 / (double)(score_count + 1);
468 pthread_mutex_unlock (&score_mutex);
470 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
472 char *type = strtok_r (line + 2, ",", &ptr);
475 pthread_mutex_lock (&check_mutex);
476 type_list_incr (&check, type, 1);
477 pthread_mutex_unlock (&check_mutex);
478 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
481 syslog (LOG_ERR, "email: unknown type '%c'", line[0]);
487 /* put this thread back into the available list */
488 pthread_mutex_lock (&active_mutex);
495 for (ptr = active.head; NULL != ptr; last = ptr, ptr = ptr->next) {
496 if (0 != pthread_equal (ptr->thread, this->thread))
500 /* the current thread _has_ to be in the active list */
501 assert (NULL != ptr);
504 active.head = ptr->next;
507 last->next = ptr->next;
509 if (NULL == last->next) {
514 pthread_mutex_unlock (&active_mutex);
518 pthread_mutex_lock (&available_mutex);
520 if (NULL == available.head) {
521 available.head = this;
522 available.tail = this;
525 available.tail->next = this;
526 available.tail = this;
529 pthread_mutex_unlock (&available_mutex);
531 pthread_cond_signal (&collector_available);
532 pthread_exit ((void *)0);
533 } /* void *collect (void *) */
535 static void *open_connection (void *arg)
537 struct sockaddr_un addr;
539 /* create UNIX socket */
541 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
543 syslog (LOG_ERR, "socket() failed: %s", strerror (errno));
544 pthread_exit ((void *)1);
547 addr.sun_family = AF_UNIX;
549 strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
550 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
551 unlink (addr.sun_path);
554 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
555 offsetof (struct sockaddr_un, sun_path)
556 + strlen(addr.sun_path))) {
558 syslog (LOG_ERR, "bind() failed: %s", strerror (errno));
559 pthread_exit ((void *)1);
563 if (-1 == listen (connector_socket, 5)) {
565 syslog (LOG_ERR, "listen() failed: %s", strerror (errno));
566 pthread_exit ((void *)1);
569 if ((uid_t)0 == geteuid ()) {
573 if (NULL != (grp = getgrnam (sock_group))) {
575 if (0 != chown (SOCK_PATH, (uid_t)-1, grp->gr_gid)) {
576 syslog (LOG_WARNING, "chown() failed: %s", strerror (errno));
580 syslog (LOG_WARNING, "getgrnam() failed: %s", strerror (errno));
584 syslog (LOG_WARNING, "not running as root");
588 if (0 != chmod (SOCK_PATH, sock_perms)) {
589 syslog (LOG_WARNING, "chmod() failed: %s", strerror (errno));
592 { /* initialize queue of available threads */
600 available.head = (collector_t *)smalloc (sizeof (collector_t));
601 available.tail = available.head;
602 available.tail->next = NULL;
604 last = available.head;
606 for (i = 1; i < max_conns; ++i) {
607 last->next = (collector_t *)smalloc (sizeof (collector_t));
609 available.tail = last;
610 available.tail->next = NULL;
618 collector_t *collector;
620 pthread_attr_t ptattr;
622 pthread_mutex_lock (&available_mutex);
623 while (NULL == available.head) {
624 pthread_cond_wait (&collector_available, &available_mutex);
626 pthread_mutex_unlock (&available_mutex);
630 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
631 if (EINTR != errno) {
633 syslog (LOG_ERR, "accept() failed: %s", strerror (errno));
634 pthread_exit ((void *)1);
637 } while (EINTR == errno);
639 /* assign connection to next available thread */
640 pthread_mutex_lock (&available_mutex);
642 collector = available.head;
643 collector->socket = remote;
645 if (available.head == available.tail) {
646 available.head = NULL;
647 available.tail = NULL;
650 available.head = available.head->next;
653 pthread_mutex_unlock (&available_mutex);
656 collector->next = NULL;
658 pthread_attr_init (&ptattr);
659 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
661 if (0 == (err = pthread_create (&collector->thread, &ptattr, collect,
662 (void *)collector))) {
663 pthread_mutex_lock (&active_mutex);
665 if (NULL == active.head) {
666 active.head = collector;
667 active.tail = collector;
670 active.tail->next = collector;
671 active.tail = collector;
674 pthread_mutex_unlock (&active_mutex);
677 pthread_mutex_lock (&available_mutex);
679 if (NULL == available.head) {
680 available.head = collector;
681 available.tail = collector;
684 available.tail->next = collector;
685 available.tail = collector;
688 pthread_mutex_unlock (&available_mutex);
691 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
694 pthread_attr_destroy (&ptattr);
696 pthread_exit ((void *)0);
697 } /* void *open_connection (void *) */
698 #endif /* EMAIL_HAVE_READ */
700 static void email_init (void)
705 if (0 != (err = pthread_create (&connector, NULL,
706 open_connection, NULL))) {
708 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
711 #endif /* EMAIL_HAVE_READ */
713 } /* static void email_init (void) */
716 static void email_shutdown (void)
723 close (connector_socket);
724 pthread_kill (connector, SIGTERM);
726 pthread_mutex_lock (&active_mutex);
728 for (ptr = active.head; NULL != ptr; ptr = ptr->next) {
730 pthread_kill (ptr->thread, SIGTERM);
733 pthread_mutex_unlock (&active_mutex);
737 } /* static void email_shutdown (void) */
738 #endif /* EMAIL_HAVE_READ */
740 static void count_write (char *host, char *inst, char *val)
742 char file[BUFSIZE] = "";
745 len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
746 if ((len < 0) || (len >= BUFSIZE))
749 rrd_update_file (host, file, val, count_ds_def, count_ds_num);
751 } /* static void email_write (char *host, char *inst, char *val) */
753 static void size_write (char *host, char *inst, char *val)
755 char file[BUFSIZE] = "";
758 len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
759 if ((len < 0) || (len >= BUFSIZE))
762 rrd_update_file (host, file, val, size_ds_def, size_ds_num);
764 } /* static void size_write (char *host, char *inst, char *val) */
766 static void score_write (char *host, char *inst, char *val)
768 rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
770 } /* static void score_write (char *host, char *inst, char *val) */
772 static void check_write (char *host, char *inst, char *val)
774 char file[BUFSIZE] = "";
777 len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
778 if ((len < 0) || (len >= BUFSIZE))
781 rrd_update_file (host, file, val, check_ds_def, check_ds_num);
783 } /* static void check_write (char *host, char *inst, char *val) */
786 static void type_submit (char *plugin, char *inst, int value)
788 char buf[BUFSIZE] = "";
794 len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
795 if ((len < 0) || (len >= BUFSIZE))
798 plugin_submit (plugin, inst, buf);
800 } /* static void type_submit (char *, char *, int) */
802 static void score_submit (double value)
804 char buf[BUFSIZE] = "";
810 len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
811 if ((len < 0) || (len >= BUFSIZE))
814 plugin_submit ("email_spam_score", NULL, buf);
818 static void email_read (void)
825 pthread_mutex_lock (&count_mutex);
827 for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
828 type_submit ("email_count", ptr->name, ptr->value);
832 pthread_mutex_unlock (&count_mutex);
834 pthread_mutex_lock (&size_mutex);
836 for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
837 type_submit ("email_size", ptr->name, ptr->value);
841 pthread_mutex_unlock (&size_mutex);
843 pthread_mutex_lock (&score_mutex);
845 score_submit (score);
849 pthread_mutex_unlock (&score_mutex);
851 pthread_mutex_lock (&check_mutex);
853 for (ptr = check.head; NULL != ptr; ptr = ptr->next) {
854 type_submit ("email_spam_check", ptr->name, ptr->value);
858 pthread_mutex_unlock (&check_mutex);
860 } /* static void read (void) */
861 #else /* if !EMAIL_HAVE_READ */
862 # define email_read NULL
865 void module_register (void)
867 plugin_register (MODULE_NAME, email_init, email_read, NULL);
868 plugin_register ("email_count", NULL, NULL, count_write);
869 plugin_register ("email_size", NULL, NULL, size_write);
870 plugin_register ("email_spam_score", NULL, NULL, score_write);
871 plugin_register ("email_spam_check", NULL, NULL, check_write);
873 plugin_register_shutdown (MODULE_NAME, email_shutdown);
874 cf_register (MODULE_NAME, email_config, config_keys, config_keys_num);
875 #endif /* EMAIL_HAVE_READ */
877 } /* void module_register (void) */
879 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */