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;
148 /* tell the connector thread that a collector is available */
149 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
151 /* collector threads that are in use */
152 static pthread_mutex_t active_mutex = PTHREAD_MUTEX_INITIALIZER;
153 static collector_list_t active;
155 /* collector threads that are available for use */
156 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
157 static collector_list_t available;
159 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
160 static type_list_t count;
162 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
163 static type_list_t size;
165 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
167 static int score_count;
169 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
170 static type_list_t check;
171 #endif /* EMAIL_HAVE_READ */
173 #define COUNT_FILE "email/email-%s.rrd"
174 static char *count_ds_def[] =
176 "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
179 static int count_ds_num = 1;
181 #define SIZE_FILE "email/email_size-%s.rrd"
182 static char *size_ds_def[] =
184 "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
187 static int size_ds_num = 1;
189 #define SCORE_FILE "email/spam_score.rrd"
190 static char *score_ds_def[] =
192 "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
195 static int score_ds_num = 1;
197 #define CHECK_FILE "email/spam_check-%s.rrd"
198 static char *check_ds_def[] =
200 "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
203 static int check_ds_num = 1;
206 static int email_config (char *key, char *value)
208 if (0 == strcasecmp (key, "SocketGroup")) {
209 sock_group = sstrdup (value);
211 else if (0 == strcasecmp (key, "SocketPerms")) {
212 /* the user is responsible for providing reasonable values */
213 sock_perms = (int)strtol (value, NULL, 0);
215 else if (0 == strcasecmp (key, "MaxConns")) {
216 long int tmp = strtol (value, NULL, 0);
219 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
220 "value %li, will use default %i.\n",
222 max_conns = MAX_CONNS;
224 else if (tmp > MAX_CONNS_LIMIT) {
225 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
226 "value %li, will use hardcoded limit %i.\n",
227 tmp, MAX_CONNS_LIMIT);
228 max_conns = MAX_CONNS_LIMIT;
231 max_conns = (int)tmp;
238 } /* static int email_config (char *, char *) */
240 /* Increment the value of the given name in the given list by incr. */
241 static void type_list_incr (type_list_t *list, char *name, int incr)
243 if (NULL == list->head) {
244 list->head = (type_t *)smalloc (sizeof (type_t));
246 list->head->name = sstrdup (name);
247 list->head->value = incr;
248 list->head->next = NULL;
250 list->tail = list->head;
255 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
256 if (0 == strcmp (name, ptr->name))
261 list->tail->next = (type_t *)smalloc (sizeof (type_t));
262 list->tail = list->tail->next;
264 list->tail->name = sstrdup (name);
265 list->tail->value = incr;
266 list->tail->next = NULL;
273 } /* static void type_list_incr (type_list_t *, char *) */
275 /* Read a single character from the socket. If an error occurs or end-of-file
276 * is reached return '\0'. */
277 char read_char (collector_t *src)
284 FD_SET (src->socket, &fdset);
286 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
287 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
291 assert (FD_ISSET (src->socket, &fdset));
297 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
298 if (EINTR != errno) {
299 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
306 } while (EINTR == errno);
308 } /* char read_char (collector_t *) */
310 /* Read a single line (terminated by '\n') from the the socket.
312 * The return value is zero terminated and does not contain any newline
313 * characters. In case that no complete line is available (non-blocking mode
314 * should be enabled) an empty string is returned.
316 * If an error occurs or end-of-file is reached return NULL.
318 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
319 * characters of the input stream, the line will will be ignored! By
320 * definition we should not get any longer input lines, thus this is
321 * acceptable in this case ;-) */
322 char *read_line (collector_t *src)
327 assert (BUFSIZE > src->idx);
329 for (i = 0; i < src->idx; ++i) {
330 if ('\n' == src->buffer[i])
334 if ('\n' != src->buffer[i]) {
340 FD_SET (src->socket, &fdset);
342 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
343 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
347 assert (FD_ISSET (src->socket, &fdset));
351 if (0 > (len = read (src->socket,
352 (void *)(&(src->buffer[0]) + src->idx),
353 BUFSIZE - src->idx))) {
354 if (EINTR != errno) {
355 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
362 } while (EINTR == errno);
366 for (i = src->idx - len; i < src->idx; ++i) {
367 if ('\n' == src->buffer[i])
371 if ('\n' != src->buffer[i]) {
372 ret = (char *)smalloc (1);
376 if (BUFSIZE == src->idx) { /* no space left in buffer */
377 while ('\n' != read_char (src))
378 /* ignore complete line */;
386 ret = (char *)smalloc (i + 1);
387 memcpy (ret, &(src->buffer[0]), i + 1);
393 src->buffer[0] = '\0';
395 memmove (&(src->buffer[0]), &(src->buffer[i + 1]), src->idx);
397 } /* char *read_line (collector_t *) */
399 static void *collect (void *arg)
401 collector_t *this = (collector_t *)arg;
405 { /* put the socket in non-blocking mode */
409 if (-1 == fcntl (this->socket, F_GETFL, &flags)) {
410 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
415 if (-1 == fcntl (this->socket, F_SETFL, flags | O_NONBLOCK)) {
416 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
422 char *line = read_line (this);
429 if ('\0' == line[0]) {
434 if (':' != line[1]) {
435 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
440 if ('e' == line[0]) { /* e:<type>:<bytes> */
442 char *type = strtok_r (line + 2, ":", &ptr);
443 char *tmp = strtok_r (NULL, ":", &ptr);
447 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
454 pthread_mutex_lock (&count_mutex);
455 type_list_incr (&count, type, 1);
456 pthread_mutex_unlock (&count_mutex);
458 pthread_mutex_lock (&size_mutex);
459 type_list_incr (&size, type, bytes);
460 pthread_mutex_unlock (&size_mutex);
462 else if ('s' == line[0]) { /* s:<value> */
463 pthread_mutex_lock (&score_mutex);
464 score = (score * (double)score_count + atof (line + 2))
465 / (double)(score_count + 1);
467 pthread_mutex_unlock (&score_mutex);
469 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
471 char *type = strtok_r (line + 2, ",", &ptr);
474 pthread_mutex_lock (&check_mutex);
475 type_list_incr (&check, type, 1);
476 pthread_mutex_unlock (&check_mutex);
477 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
480 syslog (LOG_ERR, "email: unknown type '%c'", line[0]);
486 /* put this thread back into the available list */
487 pthread_mutex_lock (&active_mutex);
494 for (ptr = active.head; NULL != ptr; last = ptr, ptr = ptr->next) {
495 if (0 != pthread_equal (ptr->thread, this->thread))
499 /* the current thread _has_ to be in the active list */
500 assert (NULL != ptr);
503 active.head = ptr->next;
506 last->next = ptr->next;
508 if (NULL == last->next) {
513 pthread_mutex_unlock (&active_mutex);
517 pthread_mutex_lock (&available_mutex);
519 if (NULL == available.head) {
520 available.head = this;
521 available.tail = this;
524 available.tail->next = this;
525 available.tail = this;
528 pthread_mutex_unlock (&available_mutex);
530 pthread_cond_signal (&collector_available);
531 pthread_exit ((void *)0);
532 } /* void *collect (void *) */
534 static void *open_connection (void *arg)
538 struct sockaddr_un addr;
540 /* create UNIX socket */
542 if (-1 == (local = socket (PF_UNIX, SOCK_STREAM, 0))) {
544 syslog (LOG_ERR, "socket() failed: %s", strerror (errno));
545 pthread_exit ((void *)1);
548 addr.sun_family = AF_UNIX;
550 strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
551 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
552 unlink (addr.sun_path);
555 if (-1 == bind (local, (struct sockaddr *)&addr,
556 offsetof (struct sockaddr_un, sun_path)
557 + strlen(addr.sun_path))) {
559 syslog (LOG_ERR, "bind() failed: %s", strerror (errno));
560 pthread_exit ((void *)1);
564 if (-1 == listen (local, 5)) {
566 syslog (LOG_ERR, "listen() failed: %s", strerror (errno));
567 pthread_exit ((void *)1);
570 if ((uid_t)0 == geteuid ()) {
574 if (NULL != (grp = getgrnam (sock_group))) {
576 if (0 != chown (SOCK_PATH, (uid_t)-1, grp->gr_gid)) {
577 syslog (LOG_WARNING, "chown() failed: %s", strerror (errno));
581 syslog (LOG_WARNING, "getgrnam() failed: %s", strerror (errno));
585 syslog (LOG_WARNING, "not running as root");
589 if (0 != chmod (SOCK_PATH, sock_perms)) {
590 syslog (LOG_WARNING, "chmod() failed: %s", strerror (errno));
593 { /* initialize queue of available threads */
601 available.head = (collector_t *)smalloc (sizeof (collector_t));
602 available.tail = available.head;
603 available.tail->next = NULL;
605 last = available.head;
607 for (i = 1; i < max_conns; ++i) {
608 last->next = (collector_t *)smalloc (sizeof (collector_t));
610 available.tail = last;
611 available.tail->next = NULL;
619 collector_t *collector;
621 pthread_attr_t ptattr;
623 pthread_mutex_lock (&available_mutex);
624 while (NULL == available.head) {
625 pthread_cond_wait (&collector_available, &available_mutex);
627 pthread_mutex_unlock (&available_mutex);
631 if (-1 == (remote = accept (local, NULL, NULL))) {
632 if (EINTR != errno) {
634 syslog (LOG_ERR, "accept() failed: %s", strerror (errno));
635 pthread_exit ((void *)1);
638 } while (EINTR == errno);
640 /* assign connection to next available thread */
641 pthread_mutex_lock (&available_mutex);
643 collector = available.head;
644 collector->socket = remote;
646 if (available.head == available.tail) {
647 available.head = NULL;
648 available.tail = NULL;
651 available.head = available.head->next;
654 pthread_mutex_unlock (&available_mutex);
657 collector->next = NULL;
659 pthread_attr_init (&ptattr);
660 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
662 if (0 == (err = pthread_create (&collector->thread, &ptattr, collect,
663 (void *)collector))) {
664 pthread_mutex_lock (&active_mutex);
666 if (NULL == active.head) {
667 active.head = collector;
668 active.tail = collector;
671 active.tail->next = collector;
672 active.tail = collector;
675 pthread_mutex_unlock (&active_mutex);
678 pthread_mutex_lock (&available_mutex);
680 if (NULL == available.head) {
681 available.head = collector;
682 available.tail = collector;
685 available.tail->next = collector;
686 available.tail = collector;
689 pthread_mutex_unlock (&available_mutex);
692 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
695 pthread_attr_destroy (&ptattr);
697 pthread_exit ((void *)0);
698 } /* void *open_connection (void *) */
699 #endif /* EMAIL_HAVE_READ */
701 static void email_init (void)
706 if (0 != (err = pthread_create (&connector, NULL,
707 open_connection, NULL))) {
709 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
712 #endif /* EMAIL_HAVE_READ */
714 } /* static void email_init (void) */
716 static void count_write (char *host, char *inst, char *val)
718 char file[BUFSIZE] = "";
721 len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
722 if ((len < 0) || (len >= BUFSIZE))
725 rrd_update_file (host, file, val, count_ds_def, count_ds_num);
727 } /* static void email_write (char *host, char *inst, char *val) */
729 static void size_write (char *host, char *inst, char *val)
731 char file[BUFSIZE] = "";
734 len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
735 if ((len < 0) || (len >= BUFSIZE))
738 rrd_update_file (host, file, val, size_ds_def, size_ds_num);
740 } /* static void size_write (char *host, char *inst, char *val) */
742 static void score_write (char *host, char *inst, char *val)
744 rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
746 } /* static void score_write (char *host, char *inst, char *val) */
748 static void check_write (char *host, char *inst, char *val)
750 char file[BUFSIZE] = "";
753 len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
754 if ((len < 0) || (len >= BUFSIZE))
757 rrd_update_file (host, file, val, check_ds_def, check_ds_num);
759 } /* static void check_write (char *host, char *inst, char *val) */
762 static void type_submit (char *plugin, char *inst, int value)
764 char buf[BUFSIZE] = "";
770 len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
771 if ((len < 0) || (len >= BUFSIZE))
774 plugin_submit (plugin, inst, buf);
776 } /* static void type_submit (char *, char *, int) */
778 static void score_submit (double value)
780 char buf[BUFSIZE] = "";
786 len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
787 if ((len < 0) || (len >= BUFSIZE))
790 plugin_submit ("email_spam_score", NULL, buf);
794 static void email_read (void)
801 pthread_mutex_lock (&count_mutex);
803 for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
804 type_submit ("email_count", ptr->name, ptr->value);
808 pthread_mutex_unlock (&count_mutex);
810 pthread_mutex_lock (&size_mutex);
812 for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
813 type_submit ("email_size", ptr->name, ptr->value);
817 pthread_mutex_unlock (&size_mutex);
819 pthread_mutex_lock (&score_mutex);
821 score_submit (score);
825 pthread_mutex_unlock (&score_mutex);
827 pthread_mutex_lock (&check_mutex);
829 for (ptr = check.head; NULL != ptr; ptr = ptr->next) {
830 type_submit ("email_spam_check", ptr->name, ptr->value);
834 pthread_mutex_unlock (&check_mutex);
836 } /* static void read (void) */
837 #else /* if !EMAIL_HAVE_READ */
838 # define email_read NULL
841 void module_register (void)
843 plugin_register (MODULE_NAME, email_init, email_read, NULL);
844 plugin_register ("email_count", NULL, NULL, count_write);
845 plugin_register ("email_size", NULL, NULL, size_write);
846 plugin_register ("email_spam_score", NULL, NULL, score_write);
847 plugin_register ("email_spam_check", NULL, NULL, check_write);
849 cf_register (MODULE_NAME, email_config, config_keys, config_keys_num);
850 #endif /* EMAIL_HAVE_READ */
852 } /* void module_register (void) */
854 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */