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; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Sebastian Harl <sh at tokkee.org>
23 * This plugin communicates with a spam filter, a virus scanner or similar
24 * software using a UNIX socket and a very simple protocol:
26 * e-mail type (e.g. ham, spam, virus, ...) and size
32 * successful spam checks
33 * c:<type1>[,<type2>,...]
40 #include "configfile.h"
46 #include <sys/socket.h>
48 #include <sys/select.h>
50 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
52 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
53 #endif /* UNIX_PATH_MAX */
57 #endif /* HAVE_GRP_H */
59 #define MODULE_NAME "email"
61 /* 256 bytes ought to be enough for anybody ;-) */
64 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
66 #define MAX_CONNS_LIMIT 16384
68 #define log_err(...) ERROR (MODULE_NAME": "__VA_ARGS__)
69 #define log_warn(...) WARNING (MODULE_NAME": "__VA_ARGS__)
72 * Private data structures
74 /* linked list of email and check types */
86 /* collector thread control information */
87 typedef struct collector {
90 /* socket descriptor of the current/last connection */
94 /* linked list of pending connections */
96 /* socket to read data from */
99 /* buffer to read data to */
101 int idx; /* current write position in buffer */
102 int length; /* length of the current line, i.e. index of '\0' */
115 /* valid configuration file keys */
116 static const char *config_keys[] =
123 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
125 /* socket configuration */
126 static char *sock_file = SOCK_PATH;
127 static char *sock_group = COLLECTD_GRP_NAME;
128 static int sock_perms = S_IRWXU | S_IRWXG;
129 static int max_conns = MAX_CONNS;
131 /* state of the plugin */
132 static int disabled = 0;
134 /* thread managing "client" connections */
135 static pthread_t connector = (pthread_t) 0;
136 static int connector_socket = -1;
138 /* tell the collector threads that a new connection is available */
139 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
141 /* connections that are waiting to be processed */
142 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
143 static conn_list_t conns;
145 /* tell the connector thread that a collector is available */
146 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
148 /* collector threads */
149 static collector_t **collectors = NULL;
151 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
152 static int available_collectors;
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;
170 static int email_config (const char *key, const char *value)
172 if (0 == strcasecmp (key, "SocketFile")) {
173 sock_file = sstrdup (value);
175 else if (0 == strcasecmp (key, "SocketGroup")) {
176 sock_group = sstrdup (value);
178 else if (0 == strcasecmp (key, "SocketPerms")) {
179 /* the user is responsible for providing reasonable values */
180 sock_perms = (int)strtol (value, NULL, 8);
182 else if (0 == strcasecmp (key, "MaxConns")) {
183 long int tmp = strtol (value, NULL, 0);
186 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
187 "value %li, will use default %i.\n",
189 max_conns = MAX_CONNS;
191 else if (tmp > MAX_CONNS_LIMIT) {
192 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
193 "value %li, will use hardcoded limit %i.\n",
194 tmp, MAX_CONNS_LIMIT);
195 max_conns = MAX_CONNS_LIMIT;
198 max_conns = (int)tmp;
205 } /* static int email_config (char *, char *) */
207 /* Increment the value of the given name in the given list by incr. */
208 static void type_list_incr (type_list_t *list, char *name, int incr)
210 if (NULL == list->head) {
211 list->head = (type_t *)smalloc (sizeof (type_t));
213 list->head->name = sstrdup (name);
214 list->head->value = incr;
215 list->head->next = NULL;
217 list->tail = list->head;
222 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
223 if (0 == strcmp (name, ptr->name))
228 list->tail->next = (type_t *)smalloc (sizeof (type_t));
229 list->tail = list->tail->next;
231 list->tail->name = sstrdup (name);
232 list->tail->value = incr;
233 list->tail->next = NULL;
240 } /* static void type_list_incr (type_list_t *, char *) */
242 /* Read a single character from the socket. If an error occurs or end-of-file
243 * is reached return '\0'. */
244 static char read_char (conn_t *src)
251 FD_SET (src->socket, &fdset);
253 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
255 log_err ("select() failed: %s",
256 sstrerror (errno, errbuf, sizeof (errbuf)));
260 assert (FD_ISSET (src->socket, &fdset));
266 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
267 if (EINTR != errno) {
269 log_err ("read() failed: %s",
270 sstrerror (errno, errbuf, sizeof (errbuf)));
277 } while (EINTR == errno);
279 } /* static char read_char (conn_t *) */
281 /* Read a single line (terminated by '\n') from the the socket.
283 * The return value is zero terminated and does not contain any newline
286 * If an error occurs or end-of-file is reached return NULL.
288 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
289 * characters of the input stream, the line will will be ignored! By
290 * definition we should not get any longer input lines, thus this is
291 * acceptable in this case ;-) */
292 static char *read_line (conn_t *src)
296 assert ((BUFSIZE >= src->idx) && (src->idx >= 0));
297 assert ((src->idx > src->length) || (src->length == 0));
299 if (src->length > 0) { /* remove old line */
300 src->idx -= (src->length + 1);
301 memmove (src->buffer, src->buffer + src->length + 1, src->idx);
305 for (i = 0; i < src->idx; ++i) {
306 if ('\n' == src->buffer[i])
316 FD_SET (src->socket, &fdset);
318 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
320 log_err ("select() failed: %s",
321 sstrerror (errno, errbuf, sizeof (errbuf)));
325 assert (FD_ISSET (src->socket, &fdset));
329 if (0 > (len = read (src->socket,
330 (void *)(src->buffer + src->idx),
331 BUFSIZE - src->idx))) {
332 if (EINTR != errno) {
334 log_err ("read() failed: %s",
335 sstrerror (errno, errbuf, sizeof (errbuf)));
342 } while (EINTR == errno);
346 for (i = src->idx - len; i < src->idx; ++i) {
347 if ('\n' == src->buffer[i])
354 if (BUFSIZE == src->idx) { /* no space left in buffer */
355 while ('\n' != read_char (src))
356 /* ignore complete line */;
360 return read_line (src);
364 src->buffer[i] = '\0';
368 } /* static char *read_line (conn_t *) */
370 static void *collect (void *arg)
372 collector_t *this = (collector_t *)arg;
374 char *buffer = (char *)smalloc (BUFSIZE);
381 pthread_mutex_lock (&conns_mutex);
383 while (NULL == conns.head) {
384 pthread_cond_wait (&conn_available, &conns_mutex);
387 connection = conns.head;
388 conns.head = conns.head->next;
390 if (NULL == conns.head) {
394 this->socket = connection->socket;
396 pthread_mutex_unlock (&conns_mutex);
398 connection->buffer = buffer;
400 connection->length = 0;
402 { /* put the socket in non-blocking mode */
406 if (-1 == fcntl (connection->socket, F_GETFL, &flags)) {
408 log_err ("fcntl() failed: %s",
409 sstrerror (errno, errbuf, sizeof (errbuf)));
414 if (-1 == fcntl (connection->socket, F_SETFL, flags | O_NONBLOCK)) {
416 log_err ("fcntl() failed: %s",
417 sstrerror (errno, errbuf, sizeof (errbuf)));
423 char *line = read_line (connection);
430 if (':' != line[1]) {
431 log_err ("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 log_err ("syntax error in line '%s'", line);
448 pthread_mutex_lock (&count_mutex);
449 type_list_incr (&count, type, 1);
450 pthread_mutex_unlock (&count_mutex);
453 pthread_mutex_lock (&size_mutex);
454 type_list_incr (&size, type, bytes);
455 pthread_mutex_unlock (&size_mutex);
458 else if ('s' == line[0]) { /* s:<value> */
459 pthread_mutex_lock (&score_mutex);
460 score = (score * (double)score_count + atof (line + 2))
461 / (double)(score_count + 1);
463 pthread_mutex_unlock (&score_mutex);
465 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
467 char *type = strtok_r (line + 2, ",", &ptr);
470 pthread_mutex_lock (&check_mutex);
471 type_list_incr (&check, type, 1);
472 pthread_mutex_unlock (&check_mutex);
473 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
476 log_err ("unknown type '%c'", line[0]);
480 close (connection->socket);
485 pthread_mutex_lock (&available_mutex);
486 ++available_collectors;
487 pthread_mutex_unlock (&available_mutex);
489 pthread_cond_signal (&collector_available);
493 pthread_exit ((void *)0);
494 } /* static void *collect (void *) */
496 static void *open_connection (void *arg)
498 struct sockaddr_un addr;
500 /* create UNIX socket */
502 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
505 log_err ("socket() failed: %s",
506 sstrerror (errno, errbuf, sizeof (errbuf)));
507 pthread_exit ((void *)1);
510 addr.sun_family = AF_UNIX;
512 strncpy (addr.sun_path, sock_file, (size_t)(UNIX_PATH_MAX - 1));
513 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
514 unlink (addr.sun_path);
517 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
518 offsetof (struct sockaddr_un, sun_path)
519 + strlen(addr.sun_path))) {
522 connector_socket = -1; /* TODO: close? */
523 log_err ("bind() failed: %s",
524 sstrerror (errno, errbuf, sizeof (errbuf)));
525 pthread_exit ((void *)1);
529 if (-1 == listen (connector_socket, 5)) {
532 connector_socket = -1; /* TODO: close? */
533 log_err ("listen() failed: %s",
534 sstrerror (errno, errbuf, sizeof (errbuf)));
535 pthread_exit ((void *)1);
538 if ((uid_t) 0 == geteuid ())
546 status = getgrnam_r (sock_group, &sg, grbuf, sizeof (grbuf), &grp);
550 log_warn ("getgrnam_r (%s) failed: %s", sock_group,
551 sstrerror (errno, errbuf, sizeof (errbuf)));
553 else if (grp == NULL)
555 log_warn ("No such group: `%s'", sock_group);
559 status = chown (sock_file, (uid_t) -1, grp->gr_gid);
563 log_warn ("chown (%s, -1, %i) failed: %s",
564 sock_file, (int) grp->gr_gid,
565 sstrerror (errno, errbuf, sizeof (errbuf)));
569 else /* geteuid != 0 */
571 log_warn ("not running as root");
575 if (0 != chmod (sock_file, sock_perms)) {
577 log_warn ("chmod() failed: %s",
578 sstrerror (errno, errbuf, sizeof (errbuf)));
581 { /* initialize collector threads */
585 pthread_attr_t ptattr;
590 pthread_attr_init (&ptattr);
591 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
593 available_collectors = max_conns;
596 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
598 for (i = 0; i < max_conns; ++i) {
599 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
600 collectors[i]->socket = -1;
602 if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
603 collect, collectors[i]))) {
605 log_err ("pthread_create() failed: %s",
606 sstrerror (errno, errbuf, sizeof (errbuf)));
607 collectors[i]->thread = (pthread_t) 0;
611 pthread_attr_destroy (&ptattr);
619 pthread_mutex_lock (&available_mutex);
621 while (0 == available_collectors) {
622 pthread_cond_wait (&collector_available, &available_mutex);
625 --available_collectors;
627 pthread_mutex_unlock (&available_mutex);
631 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
632 if (EINTR != errno) {
635 connector_socket = -1; /* TODO: close? */
636 log_err ("accept() failed: %s",
637 sstrerror (errno, errbuf, sizeof (errbuf)));
638 pthread_exit ((void *)1);
641 } while (EINTR == errno);
643 connection = (conn_t *)smalloc (sizeof (conn_t));
645 connection->socket = remote;
646 connection->next = NULL;
648 pthread_mutex_lock (&conns_mutex);
650 if (NULL == conns.head) {
651 conns.head = connection;
652 conns.tail = connection;
655 conns.tail->next = connection;
656 conns.tail = conns.tail->next;
659 pthread_mutex_unlock (&conns_mutex);
661 pthread_cond_signal (&conn_available);
663 pthread_exit ((void *)0);
664 } /* static void *open_connection (void *) */
666 static int email_init (void)
670 if (0 != (err = pthread_create (&connector, NULL,
671 open_connection, NULL))) {
674 log_err ("pthread_create() failed: %s",
675 sstrerror (errno, errbuf, sizeof (errbuf)));
680 } /* int email_init */
682 static int email_shutdown (void)
686 if (connector != ((pthread_t) 0)) {
687 pthread_kill (connector, SIGTERM);
688 connector = (pthread_t) 0;
691 if (connector_socket >= 0) {
692 close (connector_socket);
693 connector_socket = -1;
696 /* don't allow any more connections to be processed */
697 pthread_mutex_lock (&conns_mutex);
699 if (collectors != NULL) {
700 for (i = 0; i < max_conns; ++i) {
701 if (collectors[i] == NULL)
704 if (collectors[i]->thread != ((pthread_t) 0)) {
705 pthread_kill (collectors[i]->thread, SIGTERM);
706 collectors[i]->thread = (pthread_t) 0;
709 if (collectors[i]->socket >= 0) {
710 close (collectors[i]->socket);
711 collectors[i]->socket = -1;
714 } /* if (collectors != NULL) */
716 pthread_mutex_unlock (&conns_mutex);
722 } /* static void email_shutdown (void) */
724 static void email_submit (const char *type, const char *type_instance, gauge_t value)
727 value_list_t vl = VALUE_LIST_INIT;
729 values[0].gauge = value;
733 vl.time = time (NULL);
734 strcpy (vl.host, hostname_g);
735 strcpy (vl.plugin, "email");
736 strncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
738 plugin_dispatch_values (type, &vl);
739 } /* void email_submit */
741 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
742 * that neither the order nor the name of any element of either list is
743 * changed and no elements are deleted. The values of l1 are reset to zero
744 * after they have been copied to l2. */
745 static void copy_type_list (type_list_t *l1, type_list_t *l2)
752 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
753 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
755 ptr2 = (type_t *)smalloc (sizeof (type_t));
769 if (NULL == ptr2->name) {
770 ptr2->name = sstrdup (ptr1->name);
773 ptr2->value = ptr1->value;
779 static int email_read (void)
786 static type_list_t *cnt;
787 static type_list_t *sz;
788 static type_list_t *chk;
794 cnt = (type_list_t *)smalloc (sizeof (type_list_t));
799 sz = (type_list_t *)smalloc (sizeof (type_list_t));
804 chk = (type_list_t *)smalloc (sizeof (type_list_t));
809 pthread_mutex_lock (&count_mutex);
811 copy_type_list (&count, cnt);
813 pthread_mutex_unlock (&count_mutex);
815 for (ptr = cnt->head; NULL != ptr; ptr = ptr->next) {
816 email_submit ("email_count", ptr->name, ptr->value);
820 pthread_mutex_lock (&size_mutex);
822 copy_type_list (&size, sz);
824 pthread_mutex_unlock (&size_mutex);
826 for (ptr = sz->head; NULL != ptr; ptr = ptr->next) {
827 email_submit ("email_size", ptr->name, ptr->value);
831 pthread_mutex_lock (&score_mutex);
834 score_count_old = score_count;
838 pthread_mutex_unlock (&score_mutex);
840 if (score_count_old > 0)
841 email_submit ("spam_score", "", score_old);
844 pthread_mutex_lock (&check_mutex);
846 copy_type_list (&check, chk);
848 pthread_mutex_unlock (&check_mutex);
850 for (ptr = chk->head; NULL != ptr; ptr = ptr->next)
851 email_submit ("spam_check", ptr->name, ptr->value);
854 } /* int email_read */
856 void module_register (void)
858 plugin_register_config ("email", email_config, config_keys, config_keys_num);
859 plugin_register_init ("email", email_init);
860 plugin_register_read ("email", email_read);
861 plugin_register_shutdown ("email", email_shutdown);
862 } /* void module_register */
864 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */