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"
48 #include <sys/socket.h>
50 #include <sys/select.h>
52 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
54 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
55 #endif /* UNIX_PATH_MAX */
59 #endif /* HAVE_GRP_H */
61 #define MODULE_NAME "email"
63 /* 256 bytes ought to be enough for anybody ;-) */
66 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
68 #define MAX_CONNS_LIMIT 16384
70 #define log_err(...) ERROR (MODULE_NAME": "__VA_ARGS__)
71 #define log_warn(...) WARNING (MODULE_NAME": "__VA_ARGS__)
74 * Private data structures
76 /* linked list of email and check types */
88 /* collector thread control information */
89 typedef struct collector {
92 /* socket descriptor of the current/last connection */
96 /* linked list of pending connections */
98 /* socket to read data from */
101 /* buffer to read data to */
103 int idx; /* current write position in buffer */
104 int length; /* length of the current line, i.e. index of '\0' */
117 /* valid configuration file keys */
118 static const char *config_keys[] =
125 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
127 /* socket configuration */
128 static char *sock_file = SOCK_PATH;
129 static char *sock_group = COLLECTD_GRP_NAME;
130 static int sock_perms = S_IRWXU | S_IRWXG;
131 static int max_conns = MAX_CONNS;
133 /* state of the plugin */
134 static int disabled = 0;
136 /* thread managing "client" connections */
137 static pthread_t connector = (pthread_t) 0;
138 static int connector_socket = -1;
140 /* tell the collector threads that a new connection is available */
141 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
143 /* connections that are waiting to be processed */
144 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
145 static conn_list_t conns;
147 /* tell the connector thread that a collector is available */
148 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
150 /* collector threads */
151 static collector_t **collectors = NULL;
153 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
154 static int available_collectors;
156 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
157 static type_list_t count;
159 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
160 static type_list_t size;
162 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
164 static int score_count;
166 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
167 static type_list_t check;
172 static int email_config (const char *key, const char *value)
174 if (0 == strcasecmp (key, "SocketFile")) {
175 sock_file = sstrdup (value);
177 else if (0 == strcasecmp (key, "SocketGroup")) {
178 sock_group = sstrdup (value);
180 else if (0 == strcasecmp (key, "SocketPerms")) {
181 /* the user is responsible for providing reasonable values */
182 sock_perms = (int)strtol (value, NULL, 8);
184 else if (0 == strcasecmp (key, "MaxConns")) {
185 long int tmp = strtol (value, NULL, 0);
188 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
189 "value %li, will use default %i.\n",
191 max_conns = MAX_CONNS;
193 else if (tmp > MAX_CONNS_LIMIT) {
194 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
195 "value %li, will use hardcoded limit %i.\n",
196 tmp, MAX_CONNS_LIMIT);
197 max_conns = MAX_CONNS_LIMIT;
200 max_conns = (int)tmp;
207 } /* static int email_config (char *, char *) */
209 /* Increment the value of the given name in the given list by incr. */
210 static void type_list_incr (type_list_t *list, char *name, int incr)
212 if (NULL == list->head) {
213 list->head = (type_t *)smalloc (sizeof (type_t));
215 list->head->name = sstrdup (name);
216 list->head->value = incr;
217 list->head->next = NULL;
219 list->tail = list->head;
224 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
225 if (0 == strcmp (name, ptr->name))
230 list->tail->next = (type_t *)smalloc (sizeof (type_t));
231 list->tail = list->tail->next;
233 list->tail->name = sstrdup (name);
234 list->tail->value = incr;
235 list->tail->next = NULL;
242 } /* static void type_list_incr (type_list_t *, char *) */
244 /* Read a single character from the socket. If an error occurs or end-of-file
245 * is reached return '\0'. */
246 static char read_char (conn_t *src)
253 FD_SET (src->socket, &fdset);
255 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
257 log_err ("select() failed: %s",
258 sstrerror (errno, errbuf, sizeof (errbuf)));
262 assert (FD_ISSET (src->socket, &fdset));
268 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
269 if (EINTR != errno) {
271 log_err ("read() failed: %s",
272 sstrerror (errno, errbuf, sizeof (errbuf)));
279 } while (EINTR == errno);
281 } /* static char read_char (conn_t *) */
283 /* Read a single line (terminated by '\n') from the the socket.
285 * The return value is zero terminated and does not contain any newline
288 * If an error occurs or end-of-file is reached return NULL.
290 * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
291 * characters of the input stream, the line will will be ignored! By
292 * definition we should not get any longer input lines, thus this is
293 * acceptable in this case ;-) */
294 static char *read_line (conn_t *src)
298 assert ((BUFSIZE >= src->idx) && (src->idx >= 0));
299 assert ((src->idx > src->length) || (src->length == 0));
301 if (src->length > 0) { /* remove old line */
302 src->idx -= (src->length + 1);
303 memmove (src->buffer, src->buffer + src->length + 1, src->idx);
307 for (i = 0; i < src->idx; ++i) {
308 if ('\n' == src->buffer[i])
318 FD_SET (src->socket, &fdset);
320 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
322 log_err ("select() failed: %s",
323 sstrerror (errno, errbuf, sizeof (errbuf)));
327 assert (FD_ISSET (src->socket, &fdset));
331 if (0 > (len = read (src->socket,
332 (void *)(src->buffer + src->idx),
333 BUFSIZE - src->idx))) {
334 if (EINTR != errno) {
336 log_err ("read() failed: %s",
337 sstrerror (errno, errbuf, sizeof (errbuf)));
344 } while (EINTR == errno);
348 for (i = src->idx - len; i < src->idx; ++i) {
349 if ('\n' == src->buffer[i])
356 if (BUFSIZE == src->idx) { /* no space left in buffer */
357 while ('\n' != read_char (src))
358 /* ignore complete line */;
362 return read_line (src);
366 src->buffer[i] = '\0';
370 } /* static char *read_line (conn_t *) */
372 static void *collect (void *arg)
374 collector_t *this = (collector_t *)arg;
376 char *buffer = (char *)smalloc (BUFSIZE);
383 pthread_mutex_lock (&conns_mutex);
385 while (NULL == conns.head) {
386 pthread_cond_wait (&conn_available, &conns_mutex);
389 connection = conns.head;
390 conns.head = conns.head->next;
392 if (NULL == conns.head) {
396 this->socket = connection->socket;
398 pthread_mutex_unlock (&conns_mutex);
400 connection->buffer = buffer;
402 connection->length = 0;
404 { /* put the socket in non-blocking mode */
408 if (-1 == fcntl (connection->socket, F_GETFL, &flags)) {
410 log_err ("fcntl() failed: %s",
411 sstrerror (errno, errbuf, sizeof (errbuf)));
416 if (-1 == fcntl (connection->socket, F_SETFL, flags | O_NONBLOCK)) {
418 log_err ("fcntl() failed: %s",
419 sstrerror (errno, errbuf, sizeof (errbuf)));
425 char *line = read_line (connection);
432 if (':' != line[1]) {
433 log_err ("syntax error in line '%s'", line);
437 if ('e' == line[0]) { /* e:<type>:<bytes> */
439 char *type = strtok_r (line + 2, ":", &ptr);
440 char *tmp = strtok_r (NULL, ":", &ptr);
444 log_err ("syntax error in line '%s'", line);
450 pthread_mutex_lock (&count_mutex);
451 type_list_incr (&count, type, 1);
452 pthread_mutex_unlock (&count_mutex);
455 pthread_mutex_lock (&size_mutex);
456 type_list_incr (&size, type, bytes);
457 pthread_mutex_unlock (&size_mutex);
460 else if ('s' == line[0]) { /* s:<value> */
461 pthread_mutex_lock (&score_mutex);
462 score = (score * (double)score_count + atof (line + 2))
463 / (double)(score_count + 1);
465 pthread_mutex_unlock (&score_mutex);
467 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
469 char *type = strtok_r (line + 2, ",", &ptr);
472 pthread_mutex_lock (&check_mutex);
473 type_list_incr (&check, type, 1);
474 pthread_mutex_unlock (&check_mutex);
475 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
478 log_err ("unknown type '%c'", line[0]);
482 close (connection->socket);
487 pthread_mutex_lock (&available_mutex);
488 ++available_collectors;
489 pthread_mutex_unlock (&available_mutex);
491 pthread_cond_signal (&collector_available);
495 pthread_exit ((void *)0);
496 } /* static void *collect (void *) */
498 static void *open_connection (void *arg)
500 struct sockaddr_un addr;
502 /* create UNIX socket */
504 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
507 log_err ("socket() failed: %s",
508 sstrerror (errno, errbuf, sizeof (errbuf)));
509 pthread_exit ((void *)1);
512 addr.sun_family = AF_UNIX;
514 strncpy (addr.sun_path, sock_file, (size_t)(UNIX_PATH_MAX - 1));
515 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
518 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
519 offsetof (struct sockaddr_un, sun_path)
520 + strlen(addr.sun_path))) {
523 connector_socket = -1; /* TODO: close? */
524 log_err ("bind() failed: %s",
525 sstrerror (errno, errbuf, sizeof (errbuf)));
526 pthread_exit ((void *)1);
530 if (-1 == listen (connector_socket, 5)) {
533 connector_socket = -1; /* TODO: close? */
534 log_err ("listen() failed: %s",
535 sstrerror (errno, errbuf, sizeof (errbuf)));
536 pthread_exit ((void *)1);
539 if ((uid_t) 0 == geteuid ())
547 status = getgrnam_r (sock_group, &sg, grbuf, sizeof (grbuf), &grp);
551 log_warn ("getgrnam_r (%s) failed: %s", sock_group,
552 sstrerror (errno, errbuf, sizeof (errbuf)));
554 else if (grp == NULL)
556 log_warn ("No such group: `%s'", sock_group);
560 status = chown (sock_file, (uid_t) -1, grp->gr_gid);
564 log_warn ("chown (%s, -1, %i) failed: %s",
565 sock_file, (int) grp->gr_gid,
566 sstrerror (errno, errbuf, sizeof (errbuf)));
570 else /* geteuid != 0 */
572 log_warn ("not running as root");
576 if (0 != chmod (sock_file, sock_perms)) {
578 log_warn ("chmod() failed: %s",
579 sstrerror (errno, errbuf, sizeof (errbuf)));
582 { /* initialize collector threads */
586 pthread_attr_t ptattr;
591 pthread_attr_init (&ptattr);
592 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
594 available_collectors = max_conns;
597 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
599 for (i = 0; i < max_conns; ++i) {
600 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
601 collectors[i]->socket = -1;
603 if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
604 collect, collectors[i]))) {
606 log_err ("pthread_create() failed: %s",
607 sstrerror (errno, errbuf, sizeof (errbuf)));
608 collectors[i]->thread = (pthread_t) 0;
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) {
636 connector_socket = -1; /* TODO: close? */
637 log_err ("accept() failed: %s",
638 sstrerror (errno, errbuf, sizeof (errbuf)));
639 pthread_exit ((void *)1);
642 } while (EINTR == errno);
644 connection = (conn_t *)smalloc (sizeof (conn_t));
646 connection->socket = remote;
647 connection->next = NULL;
649 pthread_mutex_lock (&conns_mutex);
651 if (NULL == conns.head) {
652 conns.head = connection;
653 conns.tail = connection;
656 conns.tail->next = connection;
657 conns.tail = conns.tail->next;
660 pthread_mutex_unlock (&conns_mutex);
662 pthread_cond_signal (&conn_available);
664 pthread_exit ((void *)0);
665 } /* static void *open_connection (void *) */
667 static int email_init (void)
671 if (0 != (err = pthread_create (&connector, NULL,
672 open_connection, NULL))) {
675 log_err ("pthread_create() failed: %s",
676 sstrerror (errno, errbuf, sizeof (errbuf)));
681 } /* int email_init */
683 static int email_shutdown (void)
687 if (connector != ((pthread_t) 0)) {
688 pthread_kill (connector, SIGTERM);
689 connector = (pthread_t) 0;
692 if (connector_socket >= 0) {
693 close (connector_socket);
694 connector_socket = -1;
697 /* don't allow any more connections to be processed */
698 pthread_mutex_lock (&conns_mutex);
700 if (collectors != NULL) {
701 for (i = 0; i < max_conns; ++i) {
702 if (collectors[i] == NULL)
705 if (collectors[i]->thread != ((pthread_t) 0)) {
706 pthread_kill (collectors[i]->thread, SIGTERM);
707 collectors[i]->thread = (pthread_t) 0;
710 if (collectors[i]->socket >= 0) {
711 close (collectors[i]->socket);
712 collectors[i]->socket = -1;
715 } /* if (collectors != NULL) */
717 pthread_mutex_unlock (&conns_mutex);
723 } /* static void email_shutdown (void) */
725 static void email_submit (const char *type, const char *type_instance, gauge_t value)
728 value_list_t vl = VALUE_LIST_INIT;
730 values[0].gauge = value;
734 vl.time = time (NULL);
735 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
736 sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
737 strncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
739 plugin_dispatch_values (type, &vl);
740 } /* void email_submit */
742 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
743 * that neither the order nor the name of any element of either list is
744 * changed and no elements are deleted. The values of l1 are reset to zero
745 * after they have been copied to l2. */
746 static void copy_type_list (type_list_t *l1, type_list_t *l2)
753 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
754 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
756 ptr2 = (type_t *)smalloc (sizeof (type_t));
770 if (NULL == ptr2->name) {
771 ptr2->name = sstrdup (ptr1->name);
774 ptr2->value = ptr1->value;
780 static int email_read (void)
787 static type_list_t *cnt;
788 static type_list_t *sz;
789 static type_list_t *chk;
795 cnt = (type_list_t *)smalloc (sizeof (type_list_t));
800 sz = (type_list_t *)smalloc (sizeof (type_list_t));
805 chk = (type_list_t *)smalloc (sizeof (type_list_t));
810 pthread_mutex_lock (&count_mutex);
812 copy_type_list (&count, cnt);
814 pthread_mutex_unlock (&count_mutex);
816 for (ptr = cnt->head; NULL != ptr; ptr = ptr->next) {
817 email_submit ("email_count", ptr->name, ptr->value);
821 pthread_mutex_lock (&size_mutex);
823 copy_type_list (&size, sz);
825 pthread_mutex_unlock (&size_mutex);
827 for (ptr = sz->head; NULL != ptr; ptr = ptr->next) {
828 email_submit ("email_size", ptr->name, ptr->value);
832 pthread_mutex_lock (&score_mutex);
835 score_count_old = score_count;
839 pthread_mutex_unlock (&score_mutex);
841 if (score_count_old > 0)
842 email_submit ("spam_score", "", score_old);
845 pthread_mutex_lock (&check_mutex);
847 copy_type_list (&check, chk);
849 pthread_mutex_unlock (&check_mutex);
851 for (ptr = chk->head; NULL != ptr; ptr = ptr->next)
852 email_submit ("spam_check", ptr->name, ptr->value);
855 } /* int email_read */
857 void module_register (void)
859 plugin_register_config ("email", email_config, config_keys, config_keys_num);
860 plugin_register_init ("email", email_init);
861 plugin_register_read ("email", email_read);
862 plugin_register_shutdown ("email", email_shutdown);
863 } /* void module_register */
865 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */