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';
516 unlink (addr.sun_path);
519 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
520 offsetof (struct sockaddr_un, sun_path)
521 + strlen(addr.sun_path))) {
524 connector_socket = -1; /* TODO: close? */
525 log_err ("bind() failed: %s",
526 sstrerror (errno, errbuf, sizeof (errbuf)));
527 pthread_exit ((void *)1);
531 if (-1 == listen (connector_socket, 5)) {
534 connector_socket = -1; /* TODO: close? */
535 log_err ("listen() failed: %s",
536 sstrerror (errno, errbuf, sizeof (errbuf)));
537 pthread_exit ((void *)1);
540 if ((uid_t) 0 == geteuid ())
548 status = getgrnam_r (sock_group, &sg, grbuf, sizeof (grbuf), &grp);
552 log_warn ("getgrnam_r (%s) failed: %s", sock_group,
553 sstrerror (errno, errbuf, sizeof (errbuf)));
555 else if (grp == NULL)
557 log_warn ("No such group: `%s'", sock_group);
561 status = chown (sock_file, (uid_t) -1, grp->gr_gid);
565 log_warn ("chown (%s, -1, %i) failed: %s",
566 sock_file, (int) grp->gr_gid,
567 sstrerror (errno, errbuf, sizeof (errbuf)));
571 else /* geteuid != 0 */
573 log_warn ("not running as root");
577 if (0 != chmod (sock_file, sock_perms)) {
579 log_warn ("chmod() failed: %s",
580 sstrerror (errno, errbuf, sizeof (errbuf)));
583 { /* initialize collector threads */
587 pthread_attr_t ptattr;
592 pthread_attr_init (&ptattr);
593 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
595 available_collectors = max_conns;
598 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
600 for (i = 0; i < max_conns; ++i) {
601 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
602 collectors[i]->socket = -1;
604 if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
605 collect, collectors[i]))) {
607 log_err ("pthread_create() failed: %s",
608 sstrerror (errno, errbuf, sizeof (errbuf)));
609 collectors[i]->thread = (pthread_t) 0;
613 pthread_attr_destroy (&ptattr);
621 pthread_mutex_lock (&available_mutex);
623 while (0 == available_collectors) {
624 pthread_cond_wait (&collector_available, &available_mutex);
627 --available_collectors;
629 pthread_mutex_unlock (&available_mutex);
633 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
634 if (EINTR != errno) {
637 connector_socket = -1; /* TODO: close? */
638 log_err ("accept() failed: %s",
639 sstrerror (errno, errbuf, sizeof (errbuf)));
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 *) */
668 static int email_init (void)
672 if (0 != (err = pthread_create (&connector, NULL,
673 open_connection, NULL))) {
676 log_err ("pthread_create() failed: %s",
677 sstrerror (errno, errbuf, sizeof (errbuf)));
682 } /* int email_init */
684 static int email_shutdown (void)
688 if (connector != ((pthread_t) 0)) {
689 pthread_kill (connector, SIGTERM);
690 connector = (pthread_t) 0;
693 if (connector_socket >= 0) {
694 close (connector_socket);
695 connector_socket = -1;
698 /* don't allow any more connections to be processed */
699 pthread_mutex_lock (&conns_mutex);
701 if (collectors != NULL) {
702 for (i = 0; i < max_conns; ++i) {
703 if (collectors[i] == NULL)
706 if (collectors[i]->thread != ((pthread_t) 0)) {
707 pthread_kill (collectors[i]->thread, SIGTERM);
708 collectors[i]->thread = (pthread_t) 0;
711 if (collectors[i]->socket >= 0) {
712 close (collectors[i]->socket);
713 collectors[i]->socket = -1;
716 } /* if (collectors != NULL) */
718 pthread_mutex_unlock (&conns_mutex);
724 } /* static void email_shutdown (void) */
726 static void email_submit (const char *type, const char *type_instance, gauge_t value)
729 value_list_t vl = VALUE_LIST_INIT;
731 values[0].gauge = value;
735 vl.time = time (NULL);
736 strcpy (vl.host, hostname_g);
737 strcpy (vl.plugin, "email");
738 strncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
740 plugin_dispatch_values (type, &vl);
741 } /* void email_submit */
743 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
744 * that neither the order nor the name of any element of either list is
745 * changed and no elements are deleted. The values of l1 are reset to zero
746 * after they have been copied to l2. */
747 static void copy_type_list (type_list_t *l1, type_list_t *l2)
754 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
755 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
757 ptr2 = (type_t *)smalloc (sizeof (type_t));
771 if (NULL == ptr2->name) {
772 ptr2->name = sstrdup (ptr1->name);
775 ptr2->value = ptr1->value;
781 static int email_read (void)
788 static type_list_t *cnt;
789 static type_list_t *sz;
790 static type_list_t *chk;
796 cnt = (type_list_t *)smalloc (sizeof (type_list_t));
801 sz = (type_list_t *)smalloc (sizeof (type_list_t));
806 chk = (type_list_t *)smalloc (sizeof (type_list_t));
811 pthread_mutex_lock (&count_mutex);
813 copy_type_list (&count, cnt);
815 pthread_mutex_unlock (&count_mutex);
817 for (ptr = cnt->head; NULL != ptr; ptr = ptr->next) {
818 email_submit ("email_count", ptr->name, ptr->value);
822 pthread_mutex_lock (&size_mutex);
824 copy_type_list (&size, sz);
826 pthread_mutex_unlock (&size_mutex);
828 for (ptr = sz->head; NULL != ptr; ptr = ptr->next) {
829 email_submit ("email_size", ptr->name, ptr->value);
833 pthread_mutex_lock (&score_mutex);
836 score_count_old = score_count;
840 pthread_mutex_unlock (&score_mutex);
842 if (score_count_old > 0)
843 email_submit ("spam_score", "", score_old);
846 pthread_mutex_lock (&check_mutex);
848 copy_type_list (&check, chk);
850 pthread_mutex_unlock (&check_mutex);
852 for (ptr = chk->head; NULL != ptr; ptr = ptr->next)
853 email_submit ("spam_check", ptr->name, ptr->value);
856 } /* int email_read */
858 void module_register (void)
860 plugin_register_config ("email", email_config, config_keys, config_keys_num);
861 plugin_register_init ("email", email_init);
862 plugin_register_read ("email", email_read);
863 plugin_register_shutdown ("email", email_shutdown);
864 } /* void module_register */
866 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */