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 /* collector thread control information */
104 typedef struct collector {
107 /* socket descriptor of the current/last connection */
111 /* linked list of pending connections */
112 typedef struct conn {
113 /* socket to read data from */
116 /* buffer to read data to */
118 int idx; /* current position in buffer */
127 #endif /* EMAIL_HAVE_READ */
133 /* valid configuration file keys */
134 static char *config_keys[] =
141 static int config_keys_num = 3;
143 /* socket configuration */
144 static char *sock_group = COLLECTD_GRP_NAME;
145 static int sock_perms = S_IRWXU | S_IRWXG;
146 static int max_conns = MAX_CONNS;
148 /* state of the plugin */
149 static int disabled = 0;
151 /* thread managing "client" connections */
152 static pthread_t connector;
153 static int connector_socket;
155 /* tell the collector threads that a new connection is available */
156 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
158 /* connections that are waiting to be processed */
159 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
160 static conn_list_t conns;
162 /* tell the connector thread that a collector is available */
163 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
165 /* collector threads */
166 static collector_t **collectors;
168 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
169 static int available_collectors;
171 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
172 static type_list_t count;
174 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
175 static type_list_t size;
177 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
179 static int score_count;
181 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
182 static type_list_t check;
183 #endif /* EMAIL_HAVE_READ */
185 #define COUNT_FILE "email/email-%s.rrd"
186 static char *count_ds_def[] =
188 "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
191 static int count_ds_num = 1;
193 #define SIZE_FILE "email/email_size-%s.rrd"
194 static char *size_ds_def[] =
196 "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
199 static int size_ds_num = 1;
201 #define SCORE_FILE "email/spam_score.rrd"
202 static char *score_ds_def[] =
204 "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
207 static int score_ds_num = 1;
209 #define CHECK_FILE "email/spam_check-%s.rrd"
210 static char *check_ds_def[] =
212 "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
215 static int check_ds_num = 1;
218 static int email_config (char *key, char *value)
220 if (0 == strcasecmp (key, "SocketGroup")) {
221 sock_group = sstrdup (value);
223 else if (0 == strcasecmp (key, "SocketPerms")) {
224 /* the user is responsible for providing reasonable values */
225 sock_perms = (int)strtol (value, NULL, 8);
227 else if (0 == strcasecmp (key, "MaxConns")) {
228 long int tmp = strtol (value, NULL, 0);
231 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
232 "value %li, will use default %i.\n",
234 max_conns = MAX_CONNS;
236 else if (tmp > MAX_CONNS_LIMIT) {
237 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
238 "value %li, will use hardcoded limit %i.\n",
239 tmp, MAX_CONNS_LIMIT);
240 max_conns = MAX_CONNS_LIMIT;
243 max_conns = (int)tmp;
250 } /* static int email_config (char *, char *) */
252 /* Increment the value of the given name in the given list by incr. */
253 static void type_list_incr (type_list_t *list, char *name, int incr)
255 if (NULL == list->head) {
256 list->head = (type_t *)smalloc (sizeof (type_t));
258 list->head->name = sstrdup (name);
259 list->head->value = incr;
260 list->head->next = NULL;
262 list->tail = list->head;
267 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
268 if (0 == strcmp (name, ptr->name))
273 list->tail->next = (type_t *)smalloc (sizeof (type_t));
274 list->tail = list->tail->next;
276 list->tail->name = sstrdup (name);
277 list->tail->value = incr;
278 list->tail->next = NULL;
285 } /* static void type_list_incr (type_list_t *, char *) */
287 /* Read a single character from the socket. If an error occurs or end-of-file
288 * is reached return '\0'. */
289 char read_char (conn_t *src)
296 FD_SET (src->socket, &fdset);
298 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
299 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
303 assert (FD_ISSET (src->socket, &fdset));
309 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
310 if (EINTR != errno) {
311 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
318 } while (EINTR == errno);
320 } /* char read_char (conn_t *) */
322 /* Read a single line (terminated by '\n') from the the socket.
324 * The return value is zero terminated and does not contain any newline
325 * characters. In case that no complete line is available (non-blocking mode
326 * should be enabled) an empty string is returned.
328 * If an error occurs or end-of-file is reached return NULL.
330 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
331 * characters of the input stream, the line will will be ignored! By
332 * definition we should not get any longer input lines, thus this is
333 * acceptable in this case ;-) */
334 char *read_line (conn_t *src)
339 assert (BUFSIZE > src->idx);
341 for (i = 0; i < src->idx; ++i) {
342 if ('\n' == src->buffer[i])
352 FD_SET (src->socket, &fdset);
354 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
355 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
359 assert (FD_ISSET (src->socket, &fdset));
363 if (0 > (len = read (src->socket,
364 (void *)(src->buffer + src->idx),
365 BUFSIZE - src->idx))) {
366 if (EINTR != errno) {
367 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
374 } while (EINTR == errno);
378 for (i = src->idx - len; i < src->idx; ++i) {
379 if ('\n' == src->buffer[i])
384 ret = (char *)smalloc (1);
388 if (BUFSIZE == src->idx) { /* no space left in buffer */
389 while ('\n' != read_char (src))
390 /* ignore complete line */;
398 ret = (char *)smalloc (i + 1);
399 memcpy (ret, src->buffer, i + 1);
405 src->buffer[0] = '\0';
407 memmove (src->buffer, src->buffer + i + 1, src->idx);
409 } /* char *read_line (conn_t *) */
411 static void *collect (void *arg)
413 collector_t *this = (collector_t *)arg;
415 char *buffer = (char *)smalloc (BUFSIZE);
422 pthread_mutex_lock (&conns_mutex);
424 while (NULL == conns.head) {
425 pthread_cond_wait (&conn_available, &conns_mutex);
428 connection = conns.head;
429 conns.head = conns.head->next;
431 if (NULL == conns.head) {
435 this->socket = connection->socket;
437 pthread_mutex_unlock (&conns_mutex);
439 connection->buffer = buffer;
442 { /* put the socket in non-blocking mode */
446 if (-1 == fcntl (connection->socket, F_GETFL, &flags)) {
447 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
452 if (-1 == fcntl (connection->socket, F_SETFL, flags | O_NONBLOCK)) {
453 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
459 char *line = read_line (connection);
466 if ('\0' == line[0]) {
471 if (':' != line[1]) {
472 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
477 if ('e' == line[0]) { /* e:<type>:<bytes> */
479 char *type = strtok_r (line + 2, ":", &ptr);
480 char *tmp = strtok_r (NULL, ":", &ptr);
484 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
491 pthread_mutex_lock (&count_mutex);
492 type_list_incr (&count, type, 1);
493 pthread_mutex_unlock (&count_mutex);
495 pthread_mutex_lock (&size_mutex);
496 type_list_incr (&size, type, bytes);
497 pthread_mutex_unlock (&size_mutex);
499 else if ('s' == line[0]) { /* s:<value> */
500 pthread_mutex_lock (&score_mutex);
501 score = (score * (double)score_count + atof (line + 2))
502 / (double)(score_count + 1);
504 pthread_mutex_unlock (&score_mutex);
506 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
508 char *type = strtok_r (line + 2, ",", &ptr);
511 pthread_mutex_lock (&check_mutex);
512 type_list_incr (&check, type, 1);
513 pthread_mutex_unlock (&check_mutex);
514 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
517 syslog (LOG_ERR, "email: unknown type '%c'", line[0]);
523 close (connection->socket);
527 pthread_mutex_lock (&available_mutex);
528 ++available_collectors;
529 pthread_mutex_unlock (&available_mutex);
531 pthread_cond_signal (&collector_available);
535 pthread_exit ((void *)0);
536 } /* void *collect (void *) */
538 static void *open_connection (void *arg)
540 struct sockaddr_un addr;
542 /* create UNIX socket */
544 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
546 syslog (LOG_ERR, "socket() failed: %s", strerror (errno));
547 pthread_exit ((void *)1);
550 addr.sun_family = AF_UNIX;
552 strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
553 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
554 unlink (addr.sun_path);
557 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
558 offsetof (struct sockaddr_un, sun_path)
559 + strlen(addr.sun_path))) {
561 syslog (LOG_ERR, "bind() failed: %s", strerror (errno));
562 pthread_exit ((void *)1);
566 if (-1 == listen (connector_socket, 5)) {
568 syslog (LOG_ERR, "listen() failed: %s", strerror (errno));
569 pthread_exit ((void *)1);
572 if ((uid_t)0 == geteuid ()) {
576 if (NULL != (grp = getgrnam (sock_group))) {
578 if (0 != chown (SOCK_PATH, (uid_t)-1, grp->gr_gid)) {
579 syslog (LOG_WARNING, "chown() failed: %s", strerror (errno));
583 syslog (LOG_WARNING, "getgrnam() failed: %s", strerror (errno));
587 syslog (LOG_WARNING, "not running as root");
591 if (0 != chmod (SOCK_PATH, sock_perms)) {
592 syslog (LOG_WARNING, "chmod() failed: %s", strerror (errno));
595 { /* initialize collector threads */
599 pthread_attr_t ptattr;
604 pthread_attr_init (&ptattr);
605 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
607 available_collectors = max_conns;
610 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
612 for (i = 0; i < max_conns; ++i) {
613 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
614 collectors[i]->socket = 0;
616 if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
617 collect, collectors[i]))) {
618 syslog (LOG_ERR, "pthread_create() failed: %s",
623 pthread_attr_destroy (&ptattr);
631 pthread_mutex_lock (&available_mutex);
633 while (0 == available_collectors) {
634 pthread_cond_wait (&collector_available, &available_mutex);
637 --available_collectors;
639 pthread_mutex_unlock (&available_mutex);
643 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
644 if (EINTR != errno) {
646 syslog (LOG_ERR, "accept() failed: %s", strerror (errno));
647 pthread_exit ((void *)1);
650 } while (EINTR == errno);
652 connection = (conn_t *)smalloc (sizeof (conn_t));
654 connection->socket = remote;
655 connection->next = NULL;
657 pthread_mutex_lock (&conns_mutex);
659 if (NULL == conns.head) {
660 conns.head = connection;
661 conns.tail = connection;
664 conns.tail->next = connection;
665 conns.tail = conns.tail->next;
668 pthread_mutex_unlock (&conns_mutex);
670 pthread_cond_signal (&conn_available);
672 pthread_exit ((void *)0);
673 } /* void *open_connection (void *) */
674 #endif /* EMAIL_HAVE_READ */
676 static void email_init (void)
681 if (0 != (err = pthread_create (&connector, NULL,
682 open_connection, NULL))) {
684 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
687 #endif /* EMAIL_HAVE_READ */
689 } /* static void email_init (void) */
692 static void email_shutdown (void)
699 close (connector_socket);
700 pthread_kill (connector, SIGTERM);
702 /* don't allow any more connections to be processed */
703 pthread_mutex_lock (&conns_mutex);
705 for (i = 0; i < max_conns; ++i) {
706 close (collectors[i]->socket);
707 pthread_kill (collectors[i]->thread, SIGTERM);
710 pthread_mutex_unlock (&conns_mutex);
714 } /* static void email_shutdown (void) */
715 #endif /* EMAIL_HAVE_READ */
717 static void count_write (char *host, char *inst, char *val)
719 char file[BUFSIZE] = "";
722 len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
723 if ((len < 0) || (len >= BUFSIZE))
726 rrd_update_file (host, file, val, count_ds_def, count_ds_num);
728 } /* static void email_write (char *host, char *inst, char *val) */
730 static void size_write (char *host, char *inst, char *val)
732 char file[BUFSIZE] = "";
735 len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
736 if ((len < 0) || (len >= BUFSIZE))
739 rrd_update_file (host, file, val, size_ds_def, size_ds_num);
741 } /* static void size_write (char *host, char *inst, char *val) */
743 static void score_write (char *host, char *inst, char *val)
745 rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
747 } /* static void score_write (char *host, char *inst, char *val) */
749 static void check_write (char *host, char *inst, char *val)
751 char file[BUFSIZE] = "";
754 len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
755 if ((len < 0) || (len >= BUFSIZE))
758 rrd_update_file (host, file, val, check_ds_def, check_ds_num);
760 } /* static void check_write (char *host, char *inst, char *val) */
763 static void type_submit (char *plugin, char *inst, int value)
765 char buf[BUFSIZE] = "";
771 len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
772 if ((len < 0) || (len >= BUFSIZE))
775 plugin_submit (plugin, inst, buf);
777 } /* static void type_submit (char *, char *, int) */
779 static void score_submit (double value)
781 char buf[BUFSIZE] = "";
787 len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
788 if ((len < 0) || (len >= BUFSIZE))
791 plugin_submit ("email_spam_score", NULL, buf);
795 static void email_read (void)
802 pthread_mutex_lock (&count_mutex);
804 for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
805 type_submit ("email_count", ptr->name, ptr->value);
809 pthread_mutex_unlock (&count_mutex);
811 pthread_mutex_lock (&size_mutex);
813 for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
814 type_submit ("email_size", ptr->name, ptr->value);
818 pthread_mutex_unlock (&size_mutex);
820 pthread_mutex_lock (&score_mutex);
822 score_submit (score);
826 pthread_mutex_unlock (&score_mutex);
828 pthread_mutex_lock (&check_mutex);
830 for (ptr = check.head; NULL != ptr; ptr = ptr->next) {
831 type_submit ("email_spam_check", ptr->name, ptr->value);
835 pthread_mutex_unlock (&check_mutex);
837 } /* static void read (void) */
838 #else /* if !EMAIL_HAVE_READ */
839 # define email_read NULL
842 void module_register (void)
844 plugin_register (MODULE_NAME, email_init, email_read, NULL);
845 plugin_register ("email_count", NULL, NULL, count_write);
846 plugin_register ("email_size", NULL, NULL, size_write);
847 plugin_register ("email_spam_score", NULL, NULL, score_write);
848 plugin_register ("email_spam_check", NULL, NULL, check_write);
850 plugin_register_shutdown (MODULE_NAME, email_shutdown);
851 cf_register (MODULE_NAME, email_config, config_keys, config_keys_num);
852 #endif /* EMAIL_HAVE_READ */
854 } /* void module_register (void) */
856 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */