a0278336f059bd5a79fe1fde2d69c43e0e4b795e
1 /**
2 * collectd - src/email.c
3 * Copyright (C) 2006,2007 Sebastian Harl
4 *
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.
9 *
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.
14 *
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
18 *
19 * Author:
20 * Sebastian Harl <sh at tokkee.org>
21 **/
23 /*
24 * This plugin communicates with a spam filter, a virus scanner or similar
25 * software using a UNIX socket and a very simple protocol:
26 *
27 * e-mail type (e.g. ham, spam, virus, ...) and size
28 * e:<type>:<bytes>
29 *
30 * spam score
31 * s:<value>
32 *
33 * successful spam checks
34 * c:<type1>[,<type2>,...]
35 */
37 #include "collectd.h"
38 #include "common.h"
39 #include "plugin.h"
41 #include "configfile.h"
43 #if HAVE_LIBPTHREAD
44 # include <pthread.h>
45 #endif
47 #if HAVE_SYS_SELECT_H
48 # include <sys/select.h>
49 #endif /* HAVE_SYS_SELECT_H */
51 #if HAVE_SYS_SOCKET_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 ... */
56 #if HAVE_LINUX_UN_H
57 # include <linux/un.h>
58 #elif HAVE_SYS_UN_H
59 # include <sys/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 */
63 #ifndef UNIX_PATH_MAX
64 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
65 #endif /* UNIX_PATH_MAX */
67 #if HAVE_GRP_H
68 # include <grp.h>
69 #endif /* HAVE_GRP_H */
71 #define MODULE_NAME "email"
73 /* 256 bytes ought to be enough for anybody ;-) */
74 #define BUFSIZE 256
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"
81 #define MAX_CONNS 5
82 #define MAX_CONNS_LIMIT 16384
84 #define log_err(...) ERROR (MODULE_NAME": "__VA_ARGS__)
85 #define log_warn(...) WARNING (MODULE_NAME": "__VA_ARGS__)
87 /*
88 * Private data structures
89 */
90 /* linked list of email and check types */
91 typedef struct type {
92 char *name;
93 int value;
94 struct type *next;
95 } type_t;
97 typedef struct {
98 type_t *head;
99 type_t *tail;
100 } type_list_t;
102 /* collector thread control information */
103 typedef struct collector {
104 pthread_t thread;
106 /* socket descriptor of the current/last connection */
107 int socket;
108 } collector_t;
110 /* linked list of pending connections */
111 typedef struct conn {
112 /* socket to read data from */
113 int socket;
115 /* buffer to read data to */
116 char *buffer;
117 int idx; /* current write position in buffer */
118 int length; /* length of the current line, i.e. index of '\0' */
120 struct conn *next;
121 } conn_t;
123 typedef struct {
124 conn_t *head;
125 conn_t *tail;
126 } conn_list_t;
128 /*
129 * Private variables
130 */
131 /* valid configuration file keys */
132 static const char *config_keys[] =
133 {
134 "SocketGroup",
135 "SocketPerms",
136 "MaxConns"
137 };
138 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
140 static data_source_t gauge_dsrc[1] =
141 {
142 {"value", DS_TYPE_GAUGE, 0.0, NAN}
143 };
145 static data_set_t email_count_ds =
146 {
147 "email_count", 1, gauge_dsrc
148 };
150 static data_set_t email_size_ds =
151 {
152 "email_size", 1, gauge_dsrc
153 };
155 static data_set_t spam_check_ds =
156 {
157 "spam_check", 1, gauge_dsrc
158 };
160 static data_source_t spam_score_dsrc[1] =
161 {
162 {"score", DS_TYPE_GAUGE, NAN, NAN}
163 };
165 static data_set_t spam_score_ds =
166 {
167 "spam_score", 1, spam_score_dsrc
168 };
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;
205 static double score;
206 static int score_count;
208 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
209 static type_list_t check;
211 /*
212 * Private functions
213 */
214 static int email_config (const char *key, const char *value)
215 {
216 if (0 == strcasecmp (key, "SocketGroup")) {
217 sock_group = sstrdup (value);
218 }
219 else if (0 == strcasecmp (key, "SocketPerms")) {
220 /* the user is responsible for providing reasonable values */
221 sock_perms = (int)strtol (value, NULL, 8);
222 }
223 else if (0 == strcasecmp (key, "MaxConns")) {
224 long int tmp = strtol (value, NULL, 0);
226 if (tmp < 1) {
227 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
228 "value %li, will use default %i.\n",
229 tmp, MAX_CONNS);
230 max_conns = MAX_CONNS;
231 }
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;
237 }
238 else {
239 max_conns = (int)tmp;
240 }
241 }
242 else {
243 return -1;
244 }
245 return 0;
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)
250 {
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;
259 }
260 else {
261 type_t *ptr;
263 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
264 if (0 == strcmp (name, ptr->name))
265 break;
266 }
268 if (NULL == ptr) {
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;
275 }
276 else {
277 ptr->value += incr;
278 }
279 }
280 return;
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)
286 {
287 char ret = '\0';
289 fd_set fdset;
291 FD_ZERO (&fdset);
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));
296 return '\0';
297 }
299 assert (FD_ISSET (src->socket, &fdset));
301 do {
302 ssize_t len = 0;
304 errno = 0;
305 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
306 if (EINTR != errno) {
307 log_err ("read() failed: %s", strerror (errno));
308 return '\0';
309 }
310 }
312 if (0 == len)
313 return '\0';
314 } while (EINTR == errno);
315 return ret;
316 } /* static char read_char (conn_t *) */
318 /* Read a single line (terminated by '\n') from the the socket.
319 *
320 * The return value is zero terminated and does not contain any newline
321 * characters.
322 *
323 * If an error occurs or end-of-file is reached return NULL.
324 *
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)
330 {
331 int i = 0;
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);
339 src->length = 0;
340 }
342 for (i = 0; i < src->idx; ++i) {
343 if ('\n' == src->buffer[i])
344 break;
345 }
347 if (i == src->idx) {
348 fd_set fdset;
350 ssize_t len = 0;
352 FD_ZERO (&fdset);
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));
357 return NULL;
358 }
360 assert (FD_ISSET (src->socket, &fdset));
362 do {
363 errno = 0;
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));
369 return NULL;
370 }
371 }
373 if (0 == len)
374 return NULL;
375 } while (EINTR == errno);
377 src->idx += len;
379 for (i = src->idx - len; i < src->idx; ++i) {
380 if ('\n' == src->buffer[i])
381 break;
382 }
384 if (i == src->idx) {
385 src->length = 0;
387 if (BUFSIZE == src->idx) { /* no space left in buffer */
388 while ('\n' != read_char (src))
389 /* ignore complete line */;
391 src->idx = 0;
392 }
393 return read_line (src);
394 }
395 }
397 src->buffer[i] = '\0';
398 src->length = i;
400 return src->buffer;
401 } /* static char *read_line (conn_t *) */
403 static void *collect (void *arg)
404 {
405 collector_t *this = (collector_t *)arg;
407 char *buffer = (char *)smalloc (BUFSIZE);
409 while (1) {
410 int loop = 1;
412 conn_t *connection;
414 pthread_mutex_lock (&conns_mutex);
416 while (NULL == conns.head) {
417 pthread_cond_wait (&conn_available, &conns_mutex);
418 }
420 connection = conns.head;
421 conns.head = conns.head->next;
423 if (NULL == conns.head) {
424 conns.tail = NULL;
425 }
427 this->socket = connection->socket;
429 pthread_mutex_unlock (&conns_mutex);
431 connection->buffer = buffer;
432 connection->idx = 0;
433 connection->length = 0;
435 { /* put the socket in non-blocking mode */
436 int flags = 0;
438 errno = 0;
439 if (-1 == fcntl (connection->socket, F_GETFL, &flags)) {
440 log_err ("fcntl() failed: %s", strerror (errno));
441 loop = 0;
442 }
444 errno = 0;
445 if (-1 == fcntl (connection->socket, F_SETFL, flags | O_NONBLOCK)) {
446 log_err ("fcntl() failed: %s", strerror (errno));
447 loop = 0;
448 }
449 }
451 while (loop) {
452 char *line = read_line (connection);
454 if (NULL == line) {
455 loop = 0;
456 break;
457 }
459 if (':' != line[1]) {
460 log_err ("syntax error in line '%s'", line);
461 continue;
462 }
464 if ('e' == line[0]) { /* e:<type>:<bytes> */
465 char *ptr = NULL;
466 char *type = strtok_r (line + 2, ":", &ptr);
467 char *tmp = strtok_r (NULL, ":", &ptr);
468 int bytes = 0;
470 if (NULL == tmp) {
471 log_err ("syntax error in line '%s'", line);
472 continue;
473 }
475 bytes = atoi (tmp);
477 pthread_mutex_lock (&count_mutex);
478 type_list_incr (&count, type, 1);
479 pthread_mutex_unlock (&count_mutex);
481 if (bytes > 0) {
482 pthread_mutex_lock (&size_mutex);
483 type_list_incr (&size, type, bytes);
484 pthread_mutex_unlock (&size_mutex);
485 }
486 }
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);
491 ++score_count;
492 pthread_mutex_unlock (&score_mutex);
493 }
494 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
495 char *ptr = NULL;
496 char *type = strtok_r (line + 2, ",", &ptr);
498 do {
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)));
503 }
504 else {
505 log_err ("unknown type '%c'", line[0]);
506 }
507 } /* while (loop) */
509 close (connection->socket);
511 free (connection);
513 pthread_mutex_lock (&available_mutex);
514 ++available_collectors;
515 pthread_mutex_unlock (&available_mutex);
517 pthread_cond_signal (&collector_available);
518 } /* while (1) */
520 free (buffer);
521 pthread_exit ((void *)0);
522 } /* static void *collect (void *) */
524 static void *open_connection (void *arg)
525 {
526 struct sockaddr_un addr;
528 /* create UNIX socket */
529 errno = 0;
530 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
531 disabled = 1;
532 log_err ("socket() failed: %s", strerror (errno));
533 pthread_exit ((void *)1);
534 }
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);
542 errno = 0;
543 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
544 offsetof (struct sockaddr_un, sun_path)
545 + strlen(addr.sun_path))) {
546 disabled = 1;
547 log_err ("bind() failed: %s", strerror (errno));
548 pthread_exit ((void *)1);
549 }
551 errno = 0;
552 if (-1 == listen (connector_socket, 5)) {
553 disabled = 1;
554 log_err ("listen() failed: %s", strerror (errno));
555 pthread_exit ((void *)1);
556 }
558 if ((uid_t) 0 == geteuid ())
559 {
560 struct group sg;
561 struct group *grp;
562 char grbuf[2048];
563 int status;
565 grp = NULL;
566 status = getgrnam_r (sock_group, &sg, grbuf, sizeof (grbuf), &grp);
567 if (status != 0)
568 {
569 log_warn ("getgrnam_r (%s) failed: %s", sock_group, strerror (status));
570 }
571 else if (grp == NULL)
572 {
573 log_warn ("No such group: `%s'", sock_group);
574 }
575 else
576 {
577 status = chown (SOCK_PATH, (uid_t) -1, grp->gr_gid);
578 if (status != 0)
579 log_warn ("chown (%s, -1, %i) failed: %s",
580 SOCK_PATH, (int) grp->gr_gid, strerror (errno));
581 }
582 }
583 else /* geteuid != 0 */
584 {
585 log_warn ("not running as root");
586 }
588 errno = 0;
589 if (0 != chmod (SOCK_PATH, sock_perms)) {
590 log_warn ("chmod() failed: %s", strerror (errno));
591 }
593 { /* initialize collector threads */
594 int i = 0;
595 int err = 0;
597 pthread_attr_t ptattr;
599 conns.head = NULL;
600 conns.tail = NULL;
602 pthread_attr_init (&ptattr);
603 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
605 available_collectors = max_conns;
607 collectors =
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));
617 }
618 }
620 pthread_attr_destroy (&ptattr);
621 }
623 while (1) {
624 int remote = 0;
626 conn_t *connection;
628 pthread_mutex_lock (&available_mutex);
630 while (0 == available_collectors) {
631 pthread_cond_wait (&collector_available, &available_mutex);
632 }
634 --available_collectors;
636 pthread_mutex_unlock (&available_mutex);
638 do {
639 errno = 0;
640 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
641 if (EINTR != errno) {
642 disabled = 1;
643 log_err ("accept() failed: %s", strerror (errno));
644 pthread_exit ((void *)1);
645 }
646 }
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;
659 }
660 else {
661 conns.tail->next = connection;
662 conns.tail = conns.tail->next;
663 }
665 pthread_mutex_unlock (&conns_mutex);
667 pthread_cond_signal (&conn_available);
668 }
669 pthread_exit ((void *)0);
670 } /* static void *open_connection (void *) */
672 static int email_init (void)
673 {
674 int err = 0;
676 if (0 != (err = pthread_create (&connector, NULL,
677 open_connection, NULL))) {
678 disabled = 1;
679 log_err ("pthread_create() failed: %s", strerror (err));
680 return (-1);
681 }
683 return (0);
684 } /* int email_init */
686 static int email_shutdown (void)
687 {
688 int i = 0;
690 if (disabled)
691 return (0);
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);
702 }
704 pthread_mutex_unlock (&conns_mutex);
706 unlink (SOCK_PATH);
708 return (0);
709 } /* static void email_shutdown (void) */
711 static void email_submit (const char *type, const char *type_instance, gauge_t value)
712 {
713 value_t values[1];
714 value_list_t vl = VALUE_LIST_INIT;
716 values[0].gauge = value;
718 vl.values = values;
719 vl.values_len = 1;
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)
733 {
734 type_t *ptr1;
735 type_t *ptr2;
737 type_t *last = NULL;
739 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
740 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
741 if (NULL == ptr2) {
742 ptr2 = (type_t *)smalloc (sizeof (type_t));
743 ptr2->name = NULL;
744 ptr2->next = NULL;
746 if (NULL == last) {
747 l2->head = ptr2;
748 }
749 else {
750 last->next = ptr2;
751 }
753 l2->tail = ptr2;
754 }
756 if (NULL == ptr2->name) {
757 ptr2->name = sstrdup (ptr1->name);
758 }
760 ptr2->value = ptr1->value;
761 ptr1->value = 0;
762 }
763 return;
764 }
766 static int email_read (void)
767 {
768 type_t *ptr;
770 double sc;
772 static type_list_t *cnt;
773 static type_list_t *sz;
774 static type_list_t *chk;
776 if (disabled)
777 return (-1);
779 if (NULL == cnt) {
780 cnt = (type_list_t *)smalloc (sizeof (type_list_t));
781 cnt->head = NULL;
782 }
784 if (NULL == sz) {
785 sz = (type_list_t *)smalloc (sizeof (type_list_t));
786 sz->head = NULL;
787 }
789 if (NULL == chk) {
790 chk = (type_list_t *)smalloc (sizeof (type_list_t));
791 chk->head = NULL;
792 }
794 /* email count */
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);
803 }
805 /* email size */
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);
814 }
816 /* spam score */
817 pthread_mutex_lock (&score_mutex);
819 sc = score;
820 score = 0.0;
821 score_count = 0;
823 pthread_mutex_unlock (&score_mutex);
825 email_submit ("spam_score", "", sc);
827 /* spam checks */
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);
837 return (0);
838 } /* int email_read */
840 void module_register (void)
841 {
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 : */