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
87 #define log_err(...) syslog (LOG_ERR, MODULE_NAME": "__VA_ARGS__)
88 #define log_warn(...) syslog (LOG_WARNING, MODULE_NAME": "__VA_ARGS__)
91 * Private data structures
94 /* linked list of email and check types */
106 /* collector thread control information */
107 typedef struct collector {
110 /* socket descriptor of the current/last connection */
114 /* linked list of pending connections */
115 typedef struct conn {
116 /* socket to read data from */
119 /* buffer to read data to */
121 int idx; /* current write position in buffer */
122 int length; /* length of the current line, i.e. index of '\0' */
131 #endif /* EMAIL_HAVE_READ */
137 /* valid configuration file keys */
138 static char *config_keys[] =
145 static int config_keys_num = 3;
147 /* socket configuration */
148 static char *sock_group = COLLECTD_GRP_NAME;
149 static int sock_perms = S_IRWXU | S_IRWXG;
150 static int max_conns = MAX_CONNS;
152 /* state of the plugin */
153 static int disabled = 0;
155 /* thread managing "client" connections */
156 static pthread_t connector;
157 static int connector_socket;
159 /* tell the collector threads that a new connection is available */
160 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
162 /* connections that are waiting to be processed */
163 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
164 static conn_list_t conns;
166 /* tell the connector thread that a collector is available */
167 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
169 /* collector threads */
170 static collector_t **collectors;
172 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
173 static int available_collectors;
175 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
176 static type_list_t count;
178 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
179 static type_list_t size;
181 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
183 static int score_count;
185 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
186 static type_list_t check;
187 #endif /* EMAIL_HAVE_READ */
189 #define COUNT_FILE "email/email-%s.rrd"
190 static char *count_ds_def[] =
192 "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
195 static int count_ds_num = 1;
197 #define SIZE_FILE "email/email_size-%s.rrd"
198 static char *size_ds_def[] =
200 "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
203 static int size_ds_num = 1;
205 #define SCORE_FILE "email/spam_score.rrd"
206 static char *score_ds_def[] =
208 "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
211 static int score_ds_num = 1;
213 #define CHECK_FILE "email/spam_check-%s.rrd"
214 static char *check_ds_def[] =
216 "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
219 static int check_ds_num = 1;
222 static int email_config (char *key, char *value)
224 if (0 == strcasecmp (key, "SocketGroup")) {
225 sock_group = sstrdup (value);
227 else if (0 == strcasecmp (key, "SocketPerms")) {
228 /* the user is responsible for providing reasonable values */
229 sock_perms = (int)strtol (value, NULL, 8);
231 else if (0 == strcasecmp (key, "MaxConns")) {
232 long int tmp = strtol (value, NULL, 0);
235 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
236 "value %li, will use default %i.\n",
238 max_conns = MAX_CONNS;
240 else if (tmp > MAX_CONNS_LIMIT) {
241 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
242 "value %li, will use hardcoded limit %i.\n",
243 tmp, MAX_CONNS_LIMIT);
244 max_conns = MAX_CONNS_LIMIT;
247 max_conns = (int)tmp;
254 } /* static int email_config (char *, char *) */
256 /* Increment the value of the given name in the given list by incr. */
257 static void type_list_incr (type_list_t *list, char *name, int incr)
259 if (NULL == list->head) {
260 list->head = (type_t *)smalloc (sizeof (type_t));
262 list->head->name = sstrdup (name);
263 list->head->value = incr;
264 list->head->next = NULL;
266 list->tail = list->head;
271 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
272 if (0 == strcmp (name, ptr->name))
277 list->tail->next = (type_t *)smalloc (sizeof (type_t));
278 list->tail = list->tail->next;
280 list->tail->name = sstrdup (name);
281 list->tail->value = incr;
282 list->tail->next = NULL;
289 } /* static void type_list_incr (type_list_t *, char *) */
291 /* Read a single character from the socket. If an error occurs or end-of-file
292 * is reached return '\0'. */
293 static char read_char (conn_t *src)
300 FD_SET (src->socket, &fdset);
302 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
303 log_err ("select() failed: %s", strerror (errno));
307 assert (FD_ISSET (src->socket, &fdset));
313 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
314 if (EINTR != errno) {
315 log_err ("read() failed: %s", strerror (errno));
322 } while (EINTR == errno);
324 } /* static char read_char (conn_t *) */
326 /* Read a single line (terminated by '\n') from the the socket.
328 * The return value is zero terminated and does not contain any newline
331 * If an error occurs or end-of-file is reached return NULL.
333 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
334 * characters of the input stream, the line will will be ignored! By
335 * definition we should not get any longer input lines, thus this is
336 * acceptable in this case ;-) */
337 static char *read_line (conn_t *src)
341 assert ((BUFSIZE >= src->idx) && (src->idx >= 0));
342 assert ((src->idx > src->length) || (src->length == 0));
344 if (src->length > 0) { /* remove old line */
345 src->idx -= (src->length + 1);
346 memmove (src->buffer, src->buffer + src->length + 1, src->idx);
350 for (i = 0; i < src->idx; ++i) {
351 if ('\n' == src->buffer[i])
361 FD_SET (src->socket, &fdset);
363 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
364 log_err ("select() failed: %s", strerror (errno));
368 assert (FD_ISSET (src->socket, &fdset));
372 if (0 > (len = read (src->socket,
373 (void *)(src->buffer + src->idx),
374 BUFSIZE - src->idx))) {
375 if (EINTR != errno) {
376 log_err ("read() failed: %s", strerror (errno));
383 } while (EINTR == errno);
387 for (i = src->idx - len; i < src->idx; ++i) {
388 if ('\n' == src->buffer[i])
395 if (BUFSIZE == src->idx) { /* no space left in buffer */
396 while ('\n' != read_char (src))
397 /* ignore complete line */;
401 return read_line (src);
405 src->buffer[i] = '\0';
409 } /* static 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;
441 connection->length = 0;
443 { /* put the socket in non-blocking mode */
447 if (-1 == fcntl (connection->socket, F_GETFL, &flags)) {
448 log_err ("fcntl() failed: %s", strerror (errno));
453 if (-1 == fcntl (connection->socket, F_SETFL, flags | O_NONBLOCK)) {
454 log_err ("fcntl() failed: %s", strerror (errno));
460 char *line = read_line (connection);
467 if (':' != line[1]) {
468 log_err ("syntax error in line '%s'", line);
472 if ('e' == line[0]) { /* e:<type>:<bytes> */
474 char *type = strtok_r (line + 2, ":", &ptr);
475 char *tmp = strtok_r (NULL, ":", &ptr);
479 log_err ("syntax error in line '%s'", line);
485 pthread_mutex_lock (&count_mutex);
486 type_list_incr (&count, type, 1);
487 pthread_mutex_unlock (&count_mutex);
490 pthread_mutex_lock (&size_mutex);
491 type_list_incr (&size, type, bytes);
492 pthread_mutex_unlock (&size_mutex);
495 else if ('s' == line[0]) { /* s:<value> */
496 pthread_mutex_lock (&score_mutex);
497 score = (score * (double)score_count + atof (line + 2))
498 / (double)(score_count + 1);
500 pthread_mutex_unlock (&score_mutex);
502 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
504 char *type = strtok_r (line + 2, ",", &ptr);
507 pthread_mutex_lock (&check_mutex);
508 type_list_incr (&check, type, 1);
509 pthread_mutex_unlock (&check_mutex);
510 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
513 log_err ("unknown type '%c'", line[0]);
517 close (connection->socket);
521 pthread_mutex_lock (&available_mutex);
522 ++available_collectors;
523 pthread_mutex_unlock (&available_mutex);
525 pthread_cond_signal (&collector_available);
529 pthread_exit ((void *)0);
530 } /* static void *collect (void *) */
532 static void *open_connection (void *arg)
534 struct sockaddr_un addr;
536 /* create UNIX socket */
538 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
540 log_err ("socket() failed: %s", strerror (errno));
541 pthread_exit ((void *)1);
544 addr.sun_family = AF_UNIX;
546 strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
547 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
548 unlink (addr.sun_path);
551 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
552 offsetof (struct sockaddr_un, sun_path)
553 + strlen(addr.sun_path))) {
555 log_err ("bind() failed: %s", strerror (errno));
556 pthread_exit ((void *)1);
560 if (-1 == listen (connector_socket, 5)) {
562 log_err ("listen() failed: %s", strerror (errno));
563 pthread_exit ((void *)1);
566 if ((uid_t)0 == geteuid ()) {
570 if (NULL != (grp = getgrnam (sock_group))) {
572 if (0 != chown (SOCK_PATH, (uid_t)-1, grp->gr_gid)) {
573 log_warn ("chown() failed: %s", strerror (errno));
577 log_warn ("getgrnam() failed: %s", strerror (errno));
581 log_warn ("not running as root");
585 if (0 != chmod (SOCK_PATH, sock_perms)) {
586 log_warn ("chmod() failed: %s", strerror (errno));
589 { /* initialize collector threads */
593 pthread_attr_t ptattr;
598 pthread_attr_init (&ptattr);
599 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
601 available_collectors = max_conns;
604 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
606 for (i = 0; i < max_conns; ++i) {
607 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
608 collectors[i]->socket = 0;
610 if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
611 collect, collectors[i]))) {
612 log_err ("pthread_create() failed: %s", strerror (err));
616 pthread_attr_destroy (&ptattr);
624 pthread_mutex_lock (&available_mutex);
626 while (0 == available_collectors) {
627 pthread_cond_wait (&collector_available, &available_mutex);
630 --available_collectors;
632 pthread_mutex_unlock (&available_mutex);
636 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
637 if (EINTR != errno) {
639 log_err ("accept() failed: %s", strerror (errno));
640 pthread_exit ((void *)1);
643 } while (EINTR == errno);
645 connection = (conn_t *)smalloc (sizeof (conn_t));
647 connection->socket = remote;
648 connection->next = NULL;
650 pthread_mutex_lock (&conns_mutex);
652 if (NULL == conns.head) {
653 conns.head = connection;
654 conns.tail = connection;
657 conns.tail->next = connection;
658 conns.tail = conns.tail->next;
661 pthread_mutex_unlock (&conns_mutex);
663 pthread_cond_signal (&conn_available);
665 pthread_exit ((void *)0);
666 } /* static void *open_connection (void *) */
667 #endif /* EMAIL_HAVE_READ */
669 static void email_init (void)
674 if (0 != (err = pthread_create (&connector, NULL,
675 open_connection, NULL))) {
677 log_err ("pthread_create() failed: %s", strerror (err));
680 #endif /* EMAIL_HAVE_READ */
682 } /* static void email_init (void) */
685 static void email_shutdown (void)
692 pthread_kill (connector, SIGTERM);
693 close (connector_socket);
695 /* don't allow any more connections to be processed */
696 pthread_mutex_lock (&conns_mutex);
698 for (i = 0; i < max_conns; ++i) {
699 pthread_kill (collectors[i]->thread, SIGTERM);
700 close (collectors[i]->socket);
703 pthread_mutex_unlock (&conns_mutex);
707 } /* static void email_shutdown (void) */
708 #endif /* EMAIL_HAVE_READ */
710 static void count_write (char *host, char *inst, char *val)
712 char file[BUFSIZE] = "";
715 len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
716 if ((len < 0) || (len >= BUFSIZE))
719 rrd_update_file (host, file, val, count_ds_def, count_ds_num);
721 } /* static void email_write (char *host, char *inst, char *val) */
723 static void size_write (char *host, char *inst, char *val)
725 char file[BUFSIZE] = "";
728 len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
729 if ((len < 0) || (len >= BUFSIZE))
732 rrd_update_file (host, file, val, size_ds_def, size_ds_num);
734 } /* static void size_write (char *host, char *inst, char *val) */
736 static void score_write (char *host, char *inst, char *val)
738 rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
740 } /* static void score_write (char *host, char *inst, char *val) */
742 static void check_write (char *host, char *inst, char *val)
744 char file[BUFSIZE] = "";
747 len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
748 if ((len < 0) || (len >= BUFSIZE))
751 rrd_update_file (host, file, val, check_ds_def, check_ds_num);
753 } /* static void check_write (char *host, char *inst, char *val) */
756 static void type_submit (char *plugin, char *inst, int value)
758 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] = "";
774 len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
775 if ((len < 0) || (len >= BUFSIZE))
778 plugin_submit ("email_spam_score", "-", buf);
780 } /* static void score_submit (double) */
782 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
783 * that neither the order nor the name of any element of either list is
784 * changed and no elements are deleted. The values of l1 are reset to zero
785 * after they have been copied to l2. */
786 static void copy_type_list (type_list_t *l1, type_list_t *l2)
793 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
794 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
796 ptr2 = (type_t *)smalloc (sizeof (type_t));
810 if (NULL == ptr2->name) {
811 ptr2->name = sstrdup (ptr1->name);
814 ptr2->value = ptr1->value;
820 static void email_read (void)
826 static type_list_t *cnt;
827 static type_list_t *sz;
828 static type_list_t *chk;
834 cnt = (type_list_t *)smalloc (sizeof (type_list_t));
839 sz = (type_list_t *)smalloc (sizeof (type_list_t));
844 chk = (type_list_t *)smalloc (sizeof (type_list_t));
849 pthread_mutex_lock (&count_mutex);
851 copy_type_list (&count, cnt);
853 pthread_mutex_unlock (&count_mutex);
855 for (ptr = cnt->head; NULL != ptr; ptr = ptr->next) {
856 type_submit ("email_count", ptr->name, ptr->value);
860 pthread_mutex_lock (&size_mutex);
862 copy_type_list (&size, sz);
864 pthread_mutex_unlock (&size_mutex);
866 for (ptr = sz->head; NULL != ptr; ptr = ptr->next) {
867 type_submit ("email_size", ptr->name, ptr->value);
871 pthread_mutex_lock (&score_mutex);
877 pthread_mutex_unlock (&score_mutex);
882 pthread_mutex_lock (&check_mutex);
884 copy_type_list (&check, chk);
886 pthread_mutex_unlock (&check_mutex);
888 for (ptr = chk->head; NULL != ptr; ptr = ptr->next) {
889 type_submit ("email_spam_check", ptr->name, ptr->value);
892 } /* static void read (void) */
893 #else /* if !EMAIL_HAVE_READ */
894 # define email_read NULL
897 void module_register (void)
899 plugin_register (MODULE_NAME, email_init, email_read, NULL);
900 plugin_register ("email_count", NULL, NULL, count_write);
901 plugin_register ("email_size", NULL, NULL, size_write);
902 plugin_register ("email_spam_score", NULL, NULL, score_write);
903 plugin_register ("email_spam_check", NULL, NULL, check_write);
905 plugin_register_shutdown (MODULE_NAME, email_shutdown);
906 cf_register (MODULE_NAME, email_config, config_keys, config_keys_num);
907 #endif /* EMAIL_HAVE_READ */
909 } /* void module_register (void) */
911 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */