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 */
67 #endif /* HAVE_GRP_H */
69 #define MODULE_NAME "email"
71 /* 256 bytes ought to be enough for anybody ;-) */
74 #ifndef COLLECTD_SOCKET_PREFIX
75 # define COLLECTD_SOCKET_PREFIX "/tmp/.collectd-"
76 #endif /* COLLECTD_SOCKET_PREFIX */
78 #define SOCK_PATH COLLECTD_SOCKET_PREFIX"email"
80 #define MAX_CONNS_LIMIT 16384
83 * Private data structures
86 /* linked list of email and check types */
98 /* linked list of collector thread control information */
99 typedef struct collector {
102 /* socket to read data from */
105 /* buffer to read data to */
106 char buffer[BUFSIZE];
107 int idx; /* current position in buffer */
109 struct collector *next;
116 #endif /* EMAIL_HAVE_READ */
122 /* valid configuration file keys */
123 static char *config_keys[] =
130 static int config_keys_num = 3;
132 /* socket configuration */
133 static char *sock_group = COLLECTD_GRP_NAME;
134 static int sock_perms = S_IRWXU | S_IRWXG;
135 static int max_conns = MAX_CONNS;
137 /* state of the plugin */
138 static int disabled = 0;
140 /* thread managing "client" connections */
141 static pthread_t connector;
143 /* tell the connector thread that a collector is available */
144 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
146 /* collector threads that are in use */
147 static pthread_mutex_t active_mutex = PTHREAD_MUTEX_INITIALIZER;
148 static collector_list_t active;
150 /* collector threads that are available for use */
151 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
152 static collector_list_t available;
154 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
155 static type_list_t count;
157 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
158 static type_list_t size;
160 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
162 static int score_count;
164 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
165 static type_list_t check;
166 #endif /* EMAIL_HAVE_READ */
168 #define COUNT_FILE "email/email-%s.rrd"
169 static char *count_ds_def[] =
171 "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
174 static int count_ds_num = 1;
176 #define SIZE_FILE "email/email_size-%s.rrd"
177 static char *size_ds_def[] =
179 "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
182 static int size_ds_num = 1;
184 #define SCORE_FILE "email/spam_score.rrd"
185 static char *score_ds_def[] =
187 "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
190 static int score_ds_num = 1;
192 #define CHECK_FILE "email/spam_check-%s.rrd"
193 static char *check_ds_def[] =
195 "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
198 static int check_ds_num = 1;
201 static int email_config (char *key, char *value)
203 if (0 == strcasecmp (key, "SocketGroup")) {
204 sock_group = sstrdup (value);
206 else if (0 == strcasecmp (key, "SocketPerms")) {
207 /* the user is responsible for providing reasonable values */
208 sock_perms = (int)strtol (value, NULL, 0);
210 else if (0 == strcasecmp (key, "MaxConns")) {
211 long int tmp = strtol (value, NULL, 0);
214 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
215 "value %li, will use default %i.\n",
217 max_conns = MAX_CONNS;
219 else if (tmp > MAX_CONNS_LIMIT) {
220 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
221 "value %li, will use hardcoded limit %i.\n",
222 tmp, MAX_CONNS_LIMIT);
223 max_conns = MAX_CONNS_LIMIT;
226 max_conns = (int)tmp;
233 } /* static int email_config (char *, char *) */
235 /* Increment the value of the given name in the given list by incr. */
236 static void type_list_incr (type_list_t *list, char *name, int incr)
238 if (NULL == list->head) {
239 list->head = (type_t *)smalloc (sizeof (type_t));
241 list->head->name = sstrdup (name);
242 list->head->value = incr;
243 list->head->next = NULL;
245 list->tail = list->head;
250 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
251 if (0 == strcmp (name, ptr->name))
256 list->tail->next = (type_t *)smalloc (sizeof (type_t));
257 list->tail = list->tail->next;
259 list->tail->name = sstrdup (name);
260 list->tail->value = incr;
261 list->tail->next = NULL;
268 } /* static void type_list_incr (type_list_t *, char *) */
270 /* Read a single character from the socket. If an error occurs or end-of-file
271 * is reached return '\0'. */
272 char read_char (collector_t *src)
279 FD_SET (src->socket, &fdset);
281 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
282 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
286 assert (FD_ISSET (src->socket, &fdset));
292 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
293 if (EINTR != errno) {
294 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
301 } while (EINTR == errno);
303 } /* char read_char (collector_t *) */
305 /* Read a single line (terminated by '\n') from the the socket.
307 * The return value is zero terminated and does not contain any newline
308 * characters. In case that no complete line is available (non-blocking mode
309 * should be enabled) an empty string is returned.
311 * If an error occurs or end-of-file is reached return NULL.
313 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
314 * characters of the input stream, the line will will be ignored! By
315 * definition we should not get any longer input lines, thus this is
316 * acceptable in this case ;-) */
317 char *read_line (collector_t *src)
322 assert (BUFSIZE > src->idx);
324 for (i = 0; i < src->idx; ++i) {
325 if ('\n' == src->buffer[i])
329 if ('\n' != src->buffer[i]) {
335 FD_SET (src->socket, &fdset);
337 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
338 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
342 assert (FD_ISSET (src->socket, &fdset));
346 if (0 > (len = read (src->socket,
347 (void *)(&(src->buffer[0]) + src->idx),
348 BUFSIZE - src->idx))) {
349 if (EINTR != errno) {
350 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
357 } while (EINTR == errno);
361 for (i = src->idx - len; i < src->idx; ++i) {
362 if ('\n' == src->buffer[i])
366 if ('\n' != src->buffer[i]) {
367 ret = (char *)smalloc (1);
371 if (BUFSIZE == src->idx) { /* no space left in buffer */
372 while ('\n' != read_char (src))
373 /* ignore complete line */;
381 ret = (char *)smalloc (i + 1);
382 memcpy (ret, &(src->buffer[0]), i + 1);
388 src->buffer[0] = '\0';
390 memmove (&(src->buffer[0]), &(src->buffer[i + 1]), src->idx);
392 } /* char *read_line (collector_t *) */
394 static void *collect (void *arg)
396 collector_t *this = (collector_t *)arg;
400 { /* put the socket in non-blocking mode */
404 if (-1 == fcntl (this->socket, F_GETFL, &flags)) {
405 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
410 if (-1 == fcntl (this->socket, F_SETFL, flags | O_NONBLOCK)) {
411 syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
417 char *line = read_line (this);
424 if ('\0' == line[0]) {
429 if (':' != line[1]) {
430 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
435 if ('e' == line[0]) { /* e:<type>:<bytes> */
437 char *type = strtok_r (line + 2, ":", &ptr);
438 char *tmp = strtok_r (NULL, ":", &ptr);
442 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
449 pthread_mutex_lock (&count_mutex);
450 type_list_incr (&count, type, 1);
451 pthread_mutex_unlock (&count_mutex);
453 pthread_mutex_lock (&size_mutex);
454 type_list_incr (&size, type, bytes);
455 pthread_mutex_unlock (&size_mutex);
457 else if ('s' == line[0]) { /* s:<value> */
458 pthread_mutex_lock (&score_mutex);
459 score = (score * (double)score_count + atof (line + 2))
460 / (double)(score_count + 1);
462 pthread_mutex_unlock (&score_mutex);
464 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
466 char *type = strtok_r (line + 2, ",", &ptr);
469 pthread_mutex_lock (&check_mutex);
470 type_list_incr (&check, type, 1);
471 pthread_mutex_unlock (&check_mutex);
472 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
475 syslog (LOG_ERR, "email: unknown type '%c'", line[0]);
481 /* put this thread back into the available list */
482 pthread_mutex_lock (&active_mutex);
489 for (ptr = active.head; NULL != ptr; last = ptr, ptr = ptr->next) {
490 if (0 != pthread_equal (ptr->thread, this->thread))
494 /* the current thread _has_ to be in the active list */
495 assert (NULL != ptr);
498 active.head = ptr->next;
501 last->next = ptr->next;
503 if (NULL == last->next) {
508 pthread_mutex_unlock (&active_mutex);
512 pthread_mutex_lock (&available_mutex);
514 if (NULL == available.head) {
515 available.head = this;
516 available.tail = this;
519 available.tail->next = this;
520 available.tail = this;
523 pthread_mutex_unlock (&available_mutex);
525 pthread_cond_signal (&collector_available);
526 pthread_exit ((void *)0);
527 } /* void *collect (void *) */
529 static void *open_connection (void *arg)
533 struct sockaddr_un addr;
535 /* create UNIX socket */
537 if (-1 == (local = socket (PF_UNIX, SOCK_STREAM, 0))) {
539 syslog (LOG_ERR, "socket() failed: %s", strerror (errno));
540 pthread_exit ((void *)1);
543 addr.sun_family = AF_UNIX;
545 strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
546 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
547 unlink (addr.sun_path);
550 if (-1 == bind (local, (struct sockaddr *)&addr,
551 offsetof (struct sockaddr_un, sun_path)
552 + strlen(addr.sun_path))) {
554 syslog (LOG_ERR, "bind() failed: %s", strerror (errno));
555 pthread_exit ((void *)1);
559 if (-1 == listen (local, 5)) {
561 syslog (LOG_ERR, "listen() failed: %s", strerror (errno));
562 pthread_exit ((void *)1);
565 if ((uid_t)0 == geteuid ()) {
569 if (NULL != (grp = getgrnam (sock_group))) {
571 if (0 != chown (SOCK_PATH, (uid_t)-1, grp->gr_gid)) {
572 syslog (LOG_WARNING, "chown() failed: %s", strerror (errno));
576 syslog (LOG_WARNING, "getgrnam() failed: %s", strerror (errno));
580 syslog (LOG_WARNING, "not running as root");
584 if (0 != chmod (SOCK_PATH, sock_perms)) {
585 syslog (LOG_WARNING, "chmod() failed: %s", strerror (errno));
588 { /* initialize queue of available threads */
596 available.head = (collector_t *)smalloc (sizeof (collector_t));
597 available.tail = available.head;
598 available.tail->next = NULL;
600 last = available.head;
602 for (i = 1; i < max_conns; ++i) {
603 last->next = (collector_t *)smalloc (sizeof (collector_t));
605 available.tail = last;
606 available.tail->next = NULL;
614 collector_t *collector;
616 pthread_attr_t ptattr;
618 pthread_mutex_lock (&available_mutex);
619 while (NULL == available.head) {
620 pthread_cond_wait (&collector_available, &available_mutex);
622 pthread_mutex_unlock (&available_mutex);
626 if (-1 == (remote = accept (local, NULL, NULL))) {
627 if (EINTR != errno) {
629 syslog (LOG_ERR, "accept() failed: %s", strerror (errno));
630 pthread_exit ((void *)1);
633 } while (EINTR == errno);
635 /* assign connection to next available thread */
636 pthread_mutex_lock (&available_mutex);
638 collector = available.head;
639 collector->socket = remote;
641 if (available.head == available.tail) {
642 available.head = NULL;
643 available.tail = NULL;
646 available.head = available.head->next;
649 pthread_mutex_unlock (&available_mutex);
652 collector->next = NULL;
654 pthread_attr_init (&ptattr);
655 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
657 if (0 == (err = pthread_create (&collector->thread, &ptattr, collect,
658 (void *)collector))) {
659 pthread_mutex_lock (&active_mutex);
661 if (NULL == active.head) {
662 active.head = collector;
663 active.tail = collector;
666 active.tail->next = collector;
667 active.tail = collector;
670 pthread_mutex_unlock (&active_mutex);
673 pthread_mutex_lock (&available_mutex);
675 if (NULL == available.head) {
676 available.head = collector;
677 available.tail = collector;
680 available.tail->next = collector;
681 available.tail = collector;
684 pthread_mutex_unlock (&available_mutex);
687 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
690 pthread_attr_destroy (&ptattr);
692 pthread_exit ((void *)0);
693 } /* void *open_connection (void *) */
694 #endif /* EMAIL_HAVE_READ */
696 static void email_init (void)
701 if (0 != (err = pthread_create (&connector, NULL,
702 open_connection, NULL))) {
704 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
707 #endif /* EMAIL_HAVE_READ */
709 } /* static void email_init (void) */
711 static void count_write (char *host, char *inst, char *val)
713 char file[BUFSIZE] = "";
716 len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
717 if ((len < 0) || (len >= BUFSIZE))
720 rrd_update_file (host, file, val, count_ds_def, count_ds_num);
722 } /* static void email_write (char *host, char *inst, char *val) */
724 static void size_write (char *host, char *inst, char *val)
726 char file[BUFSIZE] = "";
729 len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
730 if ((len < 0) || (len >= BUFSIZE))
733 rrd_update_file (host, file, val, size_ds_def, size_ds_num);
735 } /* static void size_write (char *host, char *inst, char *val) */
737 static void score_write (char *host, char *inst, char *val)
739 rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
741 } /* static void score_write (char *host, char *inst, char *val) */
743 static void check_write (char *host, char *inst, char *val)
745 char file[BUFSIZE] = "";
748 len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
749 if ((len < 0) || (len >= BUFSIZE))
752 rrd_update_file (host, file, val, check_ds_def, check_ds_num);
754 } /* static void check_write (char *host, char *inst, char *val) */
757 static void type_submit (char *plugin, char *inst, int value)
759 char buf[BUFSIZE] = "";
765 len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
766 if ((len < 0) || (len >= BUFSIZE))
769 plugin_submit (plugin, inst, buf);
771 } /* static void type_submit (char *, char *, int) */
773 static void score_submit (double value)
775 char buf[BUFSIZE] = "";
781 len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
782 if ((len < 0) || (len >= BUFSIZE))
785 plugin_submit ("email_spam_score", NULL, buf);
789 static void email_read (void)
796 pthread_mutex_lock (&count_mutex);
798 for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
799 type_submit ("email_count", ptr->name, ptr->value);
803 pthread_mutex_unlock (&count_mutex);
805 pthread_mutex_lock (&size_mutex);
807 for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
808 type_submit ("email_size", ptr->name, ptr->value);
812 pthread_mutex_unlock (&size_mutex);
814 pthread_mutex_lock (&score_mutex);
816 score_submit (score);
820 pthread_mutex_unlock (&score_mutex);
822 pthread_mutex_lock (&check_mutex);
824 for (ptr = check.head; NULL != ptr; ptr = ptr->next) {
825 type_submit ("email_spam_check", ptr->name, ptr->value);
829 pthread_mutex_unlock (&check_mutex);
831 } /* static void read (void) */
832 #else /* if !EMAIL_HAVE_READ */
833 # define email_read NULL
836 void module_register (void)
838 plugin_register (MODULE_NAME, email_init, email_read, NULL);
839 plugin_register ("email_count", NULL, NULL, count_write);
840 plugin_register ("email_size", NULL, NULL, size_write);
841 plugin_register ("email_spam_score", NULL, NULL, score_write);
842 plugin_register ("email_spam_check", NULL, NULL, check_write);
844 cf_register (MODULE_NAME, email_config, config_keys, config_keys_num);
845 #endif /* EMAIL_HAVE_READ */
847 } /* void module_register (void) */
849 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */