2 * collectd - src/email.c
3 * Copyright (C) 2006,2007 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"
48 # include <sys/select.h>
49 #endif /* HAVE_SYS_SELECT_H */
52 # include <sys/socket.h>
53 #endif /* HAVE_SYS_SOCKET_H */
55 /* *sigh* glibc does not define UNIX_PATH_MAX in sys/un.h ... */
57 # include <linux/un.h>
60 #endif /* HAVE_LINUX_UN_H | HAVE_SYS_UN_H */
62 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
64 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
65 #endif /* UNIX_PATH_MAX */
69 #endif /* HAVE_GRP_H */
71 #define MODULE_NAME "email"
73 /* 256 bytes ought to be enough for anybody ;-) */
76 #ifndef COLLECTD_SOCKET_PREFIX
77 # define COLLECTD_SOCKET_PREFIX "/tmp/.collectd-"
78 #endif /* COLLECTD_SOCKET_PREFIX */
80 #define SOCK_PATH COLLECTD_SOCKET_PREFIX"email"
82 #define MAX_CONNS_LIMIT 16384
84 #define log_err(...) ERROR (MODULE_NAME": "__VA_ARGS__)
85 #define log_warn(...) WARNING (MODULE_NAME": "__VA_ARGS__)
88 * Private data structures
90 /* linked list of email and check types */
102 /* collector thread control information */
103 typedef struct collector {
106 /* socket descriptor of the current/last connection */
110 /* linked list of pending connections */
111 typedef struct conn {
112 /* socket to read data from */
115 /* buffer to read data to */
117 int idx; /* current write position in buffer */
118 int length; /* length of the current line, i.e. index of '\0' */
131 /* valid configuration file keys */
132 static const char *config_keys[] =
138 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
140 static data_source_t gauge_dsrc[1] =
142 {"value", DS_TYPE_GAUGE, 0.0, NAN}
145 static data_set_t email_count_ds =
147 "email_count", 1, gauge_dsrc
150 static data_set_t email_size_ds =
152 "email_size", 1, gauge_dsrc
155 static data_set_t spam_check_ds =
157 "spam_check", 1, gauge_dsrc
160 static data_source_t spam_score_dsrc[1] =
162 {"score", DS_TYPE_GAUGE, NAN, NAN}
165 static data_set_t spam_score_ds =
167 "spam_score", 1, spam_score_dsrc
170 /* socket configuration */
171 static char *sock_group = COLLECTD_GRP_NAME;
172 static int sock_perms = S_IRWXU | S_IRWXG;
173 static int max_conns = MAX_CONNS;
175 /* state of the plugin */
176 static int disabled = 0;
178 /* thread managing "client" connections */
179 static pthread_t connector;
180 static int connector_socket;
182 /* tell the collector threads that a new connection is available */
183 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
185 /* connections that are waiting to be processed */
186 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
187 static conn_list_t conns;
189 /* tell the connector thread that a collector is available */
190 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
192 /* collector threads */
193 static collector_t **collectors;
195 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
196 static int available_collectors;
198 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
199 static type_list_t count;
201 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
202 static type_list_t size;
204 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
206 static int score_count;
208 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
209 static type_list_t check;
214 static int email_config (const char *key, const char *value)
216 if (0 == strcasecmp (key, "SocketGroup")) {
217 sock_group = sstrdup (value);
219 else if (0 == strcasecmp (key, "SocketPerms")) {
220 /* the user is responsible for providing reasonable values */
221 sock_perms = (int)strtol (value, NULL, 8);
223 else if (0 == strcasecmp (key, "MaxConns")) {
224 long int tmp = strtol (value, NULL, 0);
227 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
228 "value %li, will use default %i.\n",
230 max_conns = MAX_CONNS;
232 else if (tmp > MAX_CONNS_LIMIT) {
233 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
234 "value %li, will use hardcoded limit %i.\n",
235 tmp, MAX_CONNS_LIMIT);
236 max_conns = MAX_CONNS_LIMIT;
239 max_conns = (int)tmp;
246 } /* static int email_config (char *, char *) */
248 /* Increment the value of the given name in the given list by incr. */
249 static void type_list_incr (type_list_t *list, char *name, int incr)
251 if (NULL == list->head) {
252 list->head = (type_t *)smalloc (sizeof (type_t));
254 list->head->name = sstrdup (name);
255 list->head->value = incr;
256 list->head->next = NULL;
258 list->tail = list->head;
263 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
264 if (0 == strcmp (name, ptr->name))
269 list->tail->next = (type_t *)smalloc (sizeof (type_t));
270 list->tail = list->tail->next;
272 list->tail->name = sstrdup (name);
273 list->tail->value = incr;
274 list->tail->next = NULL;
281 } /* static void type_list_incr (type_list_t *, char *) */
283 /* Read a single character from the socket. If an error occurs or end-of-file
284 * is reached return '\0'. */
285 static char read_char (conn_t *src)
292 FD_SET (src->socket, &fdset);
294 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
295 log_err ("select() failed: %s", strerror (errno));
299 assert (FD_ISSET (src->socket, &fdset));
305 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
306 if (EINTR != errno) {
307 log_err ("read() failed: %s", strerror (errno));
314 } while (EINTR == errno);
316 } /* static char read_char (conn_t *) */
318 /* Read a single line (terminated by '\n') from the the socket.
320 * The return value is zero terminated and does not contain any newline
323 * If an error occurs or end-of-file is reached return NULL.
325 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
326 * characters of the input stream, the line will will be ignored! By
327 * definition we should not get any longer input lines, thus this is
328 * acceptable in this case ;-) */
329 static char *read_line (conn_t *src)
333 assert ((BUFSIZE >= src->idx) && (src->idx >= 0));
334 assert ((src->idx > src->length) || (src->length == 0));
336 if (src->length > 0) { /* remove old line */
337 src->idx -= (src->length + 1);
338 memmove (src->buffer, src->buffer + src->length + 1, src->idx);
342 for (i = 0; i < src->idx; ++i) {
343 if ('\n' == src->buffer[i])
353 FD_SET (src->socket, &fdset);
355 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
356 log_err ("select() failed: %s", strerror (errno));
360 assert (FD_ISSET (src->socket, &fdset));
364 if (0 > (len = read (src->socket,
365 (void *)(src->buffer + src->idx),
366 BUFSIZE - src->idx))) {
367 if (EINTR != errno) {
368 log_err ("read() failed: %s", strerror (errno));
375 } while (EINTR == errno);
379 for (i = src->idx - len; i < src->idx; ++i) {
380 if ('\n' == src->buffer[i])
387 if (BUFSIZE == src->idx) { /* no space left in buffer */
388 while ('\n' != read_char (src))
389 /* ignore complete line */;
393 return read_line (src);
397 src->buffer[i] = '\0';
401 } /* static char *read_line (conn_t *) */
403 static void *collect (void *arg)
405 collector_t *this = (collector_t *)arg;
407 char *buffer = (char *)smalloc (BUFSIZE);
414 pthread_mutex_lock (&conns_mutex);
416 while (NULL == conns.head) {
417 pthread_cond_wait (&conn_available, &conns_mutex);
420 connection = conns.head;
421 conns.head = conns.head->next;
423 if (NULL == conns.head) {
427 this->socket = connection->socket;
429 pthread_mutex_unlock (&conns_mutex);
431 connection->buffer = buffer;
433 connection->length = 0;
435 { /* put the socket in non-blocking mode */
439 if (-1 == fcntl (connection->socket, F_GETFL, &flags)) {
440 log_err ("fcntl() failed: %s", strerror (errno));
445 if (-1 == fcntl (connection->socket, F_SETFL, flags | O_NONBLOCK)) {
446 log_err ("fcntl() failed: %s", strerror (errno));
452 char *line = read_line (connection);
459 if (':' != line[1]) {
460 log_err ("syntax error in line '%s'", line);
464 if ('e' == line[0]) { /* e:<type>:<bytes> */
466 char *type = strtok_r (line + 2, ":", &ptr);
467 char *tmp = strtok_r (NULL, ":", &ptr);
471 log_err ("syntax error in line '%s'", line);
477 pthread_mutex_lock (&count_mutex);
478 type_list_incr (&count, type, 1);
479 pthread_mutex_unlock (&count_mutex);
482 pthread_mutex_lock (&size_mutex);
483 type_list_incr (&size, type, bytes);
484 pthread_mutex_unlock (&size_mutex);
487 else if ('s' == line[0]) { /* s:<value> */
488 pthread_mutex_lock (&score_mutex);
489 score = (score * (double)score_count + atof (line + 2))
490 / (double)(score_count + 1);
492 pthread_mutex_unlock (&score_mutex);
494 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
496 char *type = strtok_r (line + 2, ",", &ptr);
499 pthread_mutex_lock (&check_mutex);
500 type_list_incr (&check, type, 1);
501 pthread_mutex_unlock (&check_mutex);
502 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
505 log_err ("unknown type '%c'", line[0]);
509 close (connection->socket);
513 pthread_mutex_lock (&available_mutex);
514 ++available_collectors;
515 pthread_mutex_unlock (&available_mutex);
517 pthread_cond_signal (&collector_available);
521 pthread_exit ((void *)0);
522 } /* static void *collect (void *) */
524 static void *open_connection (void *arg)
526 struct sockaddr_un addr;
528 /* create UNIX socket */
530 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
532 log_err ("socket() failed: %s", strerror (errno));
533 pthread_exit ((void *)1);
536 addr.sun_family = AF_UNIX;
538 strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
539 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
540 unlink (addr.sun_path);
543 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
544 offsetof (struct sockaddr_un, sun_path)
545 + strlen(addr.sun_path))) {
547 log_err ("bind() failed: %s", strerror (errno));
548 pthread_exit ((void *)1);
552 if (-1 == listen (connector_socket, 5)) {
554 log_err ("listen() failed: %s", strerror (errno));
555 pthread_exit ((void *)1);
558 if ((uid_t) 0 == geteuid ())
566 status = getgrnam_r (sock_group, &sg, grbuf, sizeof (grbuf), &grp);
569 log_warn ("getgrnam_r (%s) failed: %s", sock_group, strerror (status));
571 else if (grp == NULL)
573 log_warn ("No such group: `%s'", sock_group);
577 status = chown (SOCK_PATH, (uid_t) -1, grp->gr_gid);
579 log_warn ("chown (%s, -1, %i) failed: %s",
580 SOCK_PATH, (int) grp->gr_gid, strerror (errno));
583 else /* geteuid != 0 */
585 log_warn ("not running as root");
589 if (0 != chmod (SOCK_PATH, sock_perms)) {
590 log_warn ("chmod() failed: %s", strerror (errno));
593 { /* initialize collector threads */
597 pthread_attr_t ptattr;
602 pthread_attr_init (&ptattr);
603 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
605 available_collectors = max_conns;
608 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
610 for (i = 0; i < max_conns; ++i) {
611 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
612 collectors[i]->socket = 0;
614 if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
615 collect, collectors[i]))) {
616 log_err ("pthread_create() failed: %s", strerror (err));
620 pthread_attr_destroy (&ptattr);
628 pthread_mutex_lock (&available_mutex);
630 while (0 == available_collectors) {
631 pthread_cond_wait (&collector_available, &available_mutex);
634 --available_collectors;
636 pthread_mutex_unlock (&available_mutex);
640 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
641 if (EINTR != errno) {
643 log_err ("accept() failed: %s", strerror (errno));
644 pthread_exit ((void *)1);
647 } while (EINTR == errno);
649 connection = (conn_t *)smalloc (sizeof (conn_t));
651 connection->socket = remote;
652 connection->next = NULL;
654 pthread_mutex_lock (&conns_mutex);
656 if (NULL == conns.head) {
657 conns.head = connection;
658 conns.tail = connection;
661 conns.tail->next = connection;
662 conns.tail = conns.tail->next;
665 pthread_mutex_unlock (&conns_mutex);
667 pthread_cond_signal (&conn_available);
669 pthread_exit ((void *)0);
670 } /* static void *open_connection (void *) */
672 static int email_init (void)
676 if (0 != (err = pthread_create (&connector, NULL,
677 open_connection, NULL))) {
679 log_err ("pthread_create() failed: %s", strerror (err));
684 } /* int email_init */
686 static int email_shutdown (void)
693 pthread_kill (connector, SIGTERM);
694 close (connector_socket);
696 /* don't allow any more connections to be processed */
697 pthread_mutex_lock (&conns_mutex);
699 for (i = 0; i < max_conns; ++i) {
700 pthread_kill (collectors[i]->thread, SIGTERM);
701 close (collectors[i]->socket);
704 pthread_mutex_unlock (&conns_mutex);
709 } /* static void email_shutdown (void) */
711 static void email_submit (const char *type, const char *type_instance, gauge_t value)
714 value_list_t vl = VALUE_LIST_INIT;
716 values[0].gauge = value;
720 vl.time = time (NULL);
721 strcpy (vl.host, hostname_g);
722 strcpy (vl.plugin, "email");
723 strncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
725 plugin_dispatch_values (type, &vl);
726 } /* void email_submit */
728 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
729 * that neither the order nor the name of any element of either list is
730 * changed and no elements are deleted. The values of l1 are reset to zero
731 * after they have been copied to l2. */
732 static void copy_type_list (type_list_t *l1, type_list_t *l2)
739 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
740 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
742 ptr2 = (type_t *)smalloc (sizeof (type_t));
756 if (NULL == ptr2->name) {
757 ptr2->name = sstrdup (ptr1->name);
760 ptr2->value = ptr1->value;
766 static int email_read (void)
772 static type_list_t *cnt;
773 static type_list_t *sz;
774 static type_list_t *chk;
780 cnt = (type_list_t *)smalloc (sizeof (type_list_t));
785 sz = (type_list_t *)smalloc (sizeof (type_list_t));
790 chk = (type_list_t *)smalloc (sizeof (type_list_t));
795 pthread_mutex_lock (&count_mutex);
797 copy_type_list (&count, cnt);
799 pthread_mutex_unlock (&count_mutex);
801 for (ptr = cnt->head; NULL != ptr; ptr = ptr->next) {
802 email_submit ("email_count", ptr->name, ptr->value);
806 pthread_mutex_lock (&size_mutex);
808 copy_type_list (&size, sz);
810 pthread_mutex_unlock (&size_mutex);
812 for (ptr = sz->head; NULL != ptr; ptr = ptr->next) {
813 email_submit ("email_size", ptr->name, ptr->value);
817 pthread_mutex_lock (&score_mutex);
823 pthread_mutex_unlock (&score_mutex);
825 email_submit ("spam_score", "", sc);
828 pthread_mutex_lock (&check_mutex);
830 copy_type_list (&check, chk);
832 pthread_mutex_unlock (&check_mutex);
834 for (ptr = chk->head; NULL != ptr; ptr = ptr->next)
835 email_submit ("spam_check", ptr->name, ptr->value);
838 } /* int email_read */
840 void module_register (void)
842 plugin_register_data_set (&email_count_ds);
843 plugin_register_data_set (&email_size_ds);
844 plugin_register_data_set (&spam_check_ds);
845 plugin_register_data_set (&spam_score_ds);
847 plugin_register_config ("email", email_config, config_keys, config_keys_num);
848 plugin_register_init ("email", email_init);
849 plugin_register_read ("email", email_read);
850 plugin_register_shutdown ("email", email_shutdown);
851 } /* void module_register (void) */
853 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */