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 write position in buffer */
119 int length; /* length of the current line, i.e. index of '\0' */
128 #endif /* EMAIL_HAVE_READ */
134 /* valid configuration file keys */
135 static char *config_keys[] =
142 static int config_keys_num = 3;
144 /* socket configuration */
145 static char *sock_group = COLLECTD_GRP_NAME;
146 static int sock_perms = S_IRWXU | S_IRWXG;
147 static int max_conns = MAX_CONNS;
149 /* state of the plugin */
150 static int disabled = 0;
152 /* thread managing "client" connections */
153 static pthread_t connector;
154 static int connector_socket;
156 /* tell the collector threads that a new connection is available */
157 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
159 /* connections that are waiting to be processed */
160 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
161 static conn_list_t conns;
163 /* tell the connector thread that a collector is available */
164 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
166 /* collector threads */
167 static collector_t **collectors;
169 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
170 static int available_collectors;
172 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
173 static type_list_t count;
175 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
176 static type_list_t size;
178 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
180 static int score_count;
182 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
183 static type_list_t check;
184 #endif /* EMAIL_HAVE_READ */
186 #define COUNT_FILE "email/email-%s.rrd"
187 static char *count_ds_def[] =
189 "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
192 static int count_ds_num = 1;
194 #define SIZE_FILE "email/email_size-%s.rrd"
195 static char *size_ds_def[] =
197 "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
200 static int size_ds_num = 1;
202 #define SCORE_FILE "email/spam_score.rrd"
203 static char *score_ds_def[] =
205 "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
208 static int score_ds_num = 1;
210 #define CHECK_FILE "email/spam_check-%s.rrd"
211 static char *check_ds_def[] =
213 "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
216 static int check_ds_num = 1;
219 static int email_config (char *key, char *value)
221 if (0 == strcasecmp (key, "SocketGroup")) {
222 sock_group = sstrdup (value);
224 else if (0 == strcasecmp (key, "SocketPerms")) {
225 /* the user is responsible for providing reasonable values */
226 sock_perms = (int)strtol (value, NULL, 8);
228 else if (0 == strcasecmp (key, "MaxConns")) {
229 long int tmp = strtol (value, NULL, 0);
232 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
233 "value %li, will use default %i.\n",
235 max_conns = MAX_CONNS;
237 else if (tmp > MAX_CONNS_LIMIT) {
238 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
239 "value %li, will use hardcoded limit %i.\n",
240 tmp, MAX_CONNS_LIMIT);
241 max_conns = MAX_CONNS_LIMIT;
244 max_conns = (int)tmp;
251 } /* static int email_config (char *, char *) */
253 /* Increment the value of the given name in the given list by incr. */
254 static void type_list_incr (type_list_t *list, char *name, int incr)
256 if (NULL == list->head) {
257 list->head = (type_t *)smalloc (sizeof (type_t));
259 list->head->name = sstrdup (name);
260 list->head->value = incr;
261 list->head->next = NULL;
263 list->tail = list->head;
268 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
269 if (0 == strcmp (name, ptr->name))
274 list->tail->next = (type_t *)smalloc (sizeof (type_t));
275 list->tail = list->tail->next;
277 list->tail->name = sstrdup (name);
278 list->tail->value = incr;
279 list->tail->next = NULL;
286 } /* static void type_list_incr (type_list_t *, char *) */
288 /* Read a single character from the socket. If an error occurs or end-of-file
289 * is reached return '\0'. */
290 char read_char (conn_t *src)
297 FD_SET (src->socket, &fdset);
299 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
300 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
304 assert (FD_ISSET (src->socket, &fdset));
310 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
311 if (EINTR != errno) {
312 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
319 } while (EINTR == errno);
321 } /* char read_char (conn_t *) */
323 /* Read a single line (terminated by '\n') from the the socket.
325 * The return value is zero terminated and does not contain any newline
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)
338 assert ((BUFSIZE >= src->idx) && (src->idx >= 0));
339 assert ((src->idx > src->length) || (src->length == 0));
341 if (src->length > 0) { /* remove old line */
342 src->idx -= (src->length + 1);
343 memmove (src->buffer, src->buffer + src->length + 1, src->idx);
347 for (i = 0; i < src->idx; ++i) {
348 if ('\n' == src->buffer[i])
358 FD_SET (src->socket, &fdset);
360 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
361 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
365 assert (FD_ISSET (src->socket, &fdset));
369 if (0 > (len = read (src->socket,
370 (void *)(src->buffer + src->idx),
371 BUFSIZE - src->idx))) {
372 if (EINTR != errno) {
373 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
380 } while (EINTR == errno);
384 for (i = src->idx - len; i < src->idx; ++i) {
385 if ('\n' == src->buffer[i])
392 if (BUFSIZE == src->idx) { /* no space left in buffer */
393 while ('\n' != read_char (src))
394 /* ignore complete line */;
398 return read_line (src);
402 src->buffer[i] = '\0';
406 } /* char *read_line (conn_t *) */
408 static void *collect (void *arg)
410 collector_t *this = (collector_t *)arg;
412 char *buffer = (char *)smalloc (BUFSIZE);
419 pthread_mutex_lock (&conns_mutex);
421 while (NULL == conns.head) {
422 pthread_cond_wait (&conn_available, &conns_mutex);
425 connection = conns.head;
426 conns.head = conns.head->next;
428 if (NULL == conns.head) {
432 this->socket = connection->socket;
434 pthread_mutex_unlock (&conns_mutex);
436 connection->buffer = buffer;
438 connection->length = 0;
440 { /* put the socket in non-blocking mode */
444 if (-1 == fcntl (connection->socket, F_GETFL, &flags)) {
445 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
450 if (-1 == fcntl (connection->socket, F_SETFL, flags | O_NONBLOCK)) {
451 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
457 char *line = read_line (connection);
464 if (':' != line[1]) {
465 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
469 if ('e' == line[0]) { /* e:<type>:<bytes> */
471 char *type = strtok_r (line + 2, ":", &ptr);
472 char *tmp = strtok_r (NULL, ":", &ptr);
476 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
482 pthread_mutex_lock (&count_mutex);
483 type_list_incr (&count, type, 1);
484 pthread_mutex_unlock (&count_mutex);
486 pthread_mutex_lock (&size_mutex);
487 type_list_incr (&size, type, bytes);
488 pthread_mutex_unlock (&size_mutex);
490 else if ('s' == line[0]) { /* s:<value> */
491 pthread_mutex_lock (&score_mutex);
492 score = (score * (double)score_count + atof (line + 2))
493 / (double)(score_count + 1);
495 pthread_mutex_unlock (&score_mutex);
497 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
499 char *type = strtok_r (line + 2, ",", &ptr);
502 pthread_mutex_lock (&check_mutex);
503 type_list_incr (&check, type, 1);
504 pthread_mutex_unlock (&check_mutex);
505 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
508 syslog (LOG_ERR, "email: unknown type '%c'", line[0]);
512 close (connection->socket);
516 pthread_mutex_lock (&available_mutex);
517 ++available_collectors;
518 pthread_mutex_unlock (&available_mutex);
520 pthread_cond_signal (&collector_available);
524 pthread_exit ((void *)0);
525 } /* void *collect (void *) */
527 static void *open_connection (void *arg)
529 struct sockaddr_un addr;
531 /* create UNIX socket */
533 if (-1 == (connector_socket = 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 (connector_socket, (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 (connector_socket, 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 collector threads */
588 pthread_attr_t ptattr;
593 pthread_attr_init (&ptattr);
594 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
596 available_collectors = max_conns;
599 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
601 for (i = 0; i < max_conns; ++i) {
602 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
603 collectors[i]->socket = 0;
605 if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
606 collect, collectors[i]))) {
607 syslog (LOG_ERR, "pthread_create() failed: %s",
612 pthread_attr_destroy (&ptattr);
620 pthread_mutex_lock (&available_mutex);
622 while (0 == available_collectors) {
623 pthread_cond_wait (&collector_available, &available_mutex);
626 --available_collectors;
628 pthread_mutex_unlock (&available_mutex);
632 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
633 if (EINTR != errno) {
635 syslog (LOG_ERR, "accept() failed: %s", strerror (errno));
636 pthread_exit ((void *)1);
639 } while (EINTR == errno);
641 connection = (conn_t *)smalloc (sizeof (conn_t));
643 connection->socket = remote;
644 connection->next = NULL;
646 pthread_mutex_lock (&conns_mutex);
648 if (NULL == conns.head) {
649 conns.head = connection;
650 conns.tail = connection;
653 conns.tail->next = connection;
654 conns.tail = conns.tail->next;
657 pthread_mutex_unlock (&conns_mutex);
659 pthread_cond_signal (&conn_available);
661 pthread_exit ((void *)0);
662 } /* void *open_connection (void *) */
663 #endif /* EMAIL_HAVE_READ */
665 static void email_init (void)
670 if (0 != (err = pthread_create (&connector, NULL,
671 open_connection, NULL))) {
673 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
676 #endif /* EMAIL_HAVE_READ */
678 } /* static void email_init (void) */
681 static void email_shutdown (void)
688 pthread_kill (connector, SIGTERM);
689 close (connector_socket);
691 /* don't allow any more connections to be processed */
692 pthread_mutex_lock (&conns_mutex);
694 for (i = 0; i < max_conns; ++i) {
695 pthread_kill (collectors[i]->thread, SIGTERM);
696 close (collectors[i]->socket);
699 pthread_mutex_unlock (&conns_mutex);
703 } /* static void email_shutdown (void) */
704 #endif /* EMAIL_HAVE_READ */
706 static void count_write (char *host, char *inst, char *val)
708 char file[BUFSIZE] = "";
711 len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
712 if ((len < 0) || (len >= BUFSIZE))
715 rrd_update_file (host, file, val, count_ds_def, count_ds_num);
717 } /* static void email_write (char *host, char *inst, char *val) */
719 static void size_write (char *host, char *inst, char *val)
721 char file[BUFSIZE] = "";
724 len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
725 if ((len < 0) || (len >= BUFSIZE))
728 rrd_update_file (host, file, val, size_ds_def, size_ds_num);
730 } /* static void size_write (char *host, char *inst, char *val) */
732 static void score_write (char *host, char *inst, char *val)
734 rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
736 } /* static void score_write (char *host, char *inst, char *val) */
738 static void check_write (char *host, char *inst, char *val)
740 char file[BUFSIZE] = "";
743 len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
744 if ((len < 0) || (len >= BUFSIZE))
747 rrd_update_file (host, file, val, check_ds_def, check_ds_num);
749 } /* static void check_write (char *host, char *inst, char *val) */
752 static void type_submit (char *plugin, char *inst, int value)
754 char buf[BUFSIZE] = "";
760 len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
761 if ((len < 0) || (len >= BUFSIZE))
764 plugin_submit (plugin, inst, buf);
766 } /* static void type_submit (char *, char *, int) */
768 static void score_submit (double value)
770 char buf[BUFSIZE] = "";
776 len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
777 if ((len < 0) || (len >= BUFSIZE))
780 plugin_submit ("email_spam_score", NULL, buf);
784 static void email_read (void)
791 pthread_mutex_lock (&count_mutex);
793 for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
794 type_submit ("email_count", ptr->name, ptr->value);
798 pthread_mutex_unlock (&count_mutex);
800 pthread_mutex_lock (&size_mutex);
802 for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
803 type_submit ("email_size", ptr->name, ptr->value);
807 pthread_mutex_unlock (&size_mutex);
809 pthread_mutex_lock (&score_mutex);
811 score_submit (score);
815 pthread_mutex_unlock (&score_mutex);
817 pthread_mutex_lock (&check_mutex);
819 for (ptr = check.head; NULL != ptr; ptr = ptr->next) {
820 type_submit ("email_spam_check", ptr->name, ptr->value);
824 pthread_mutex_unlock (&check_mutex);
826 } /* static void read (void) */
827 #else /* if !EMAIL_HAVE_READ */
828 # define email_read NULL
831 void module_register (void)
833 plugin_register (MODULE_NAME, email_init, email_read, NULL);
834 plugin_register ("email_count", NULL, NULL, count_write);
835 plugin_register ("email_size", NULL, NULL, size_write);
836 plugin_register ("email_spam_score", NULL, NULL, score_write);
837 plugin_register ("email_spam_check", NULL, NULL, check_write);
839 plugin_register_shutdown (MODULE_NAME, email_shutdown);
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 : */