2 * collectd - src/email.c
3 * Copyright (C) 2006-2008 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 SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
63 #define MAX_CONNS_LIMIT 16384
65 #define log_debug(...) DEBUG ("email: "__VA_ARGS__)
66 #define log_err(...) ERROR ("email: "__VA_ARGS__)
67 #define log_warn(...) WARNING ("email: "__VA_ARGS__)
70 * Private data structures
72 /* linked list of email and check types */
84 /* collector thread control information */
85 typedef struct collector {
88 /* socket descriptor of the current/last connection */
92 /* linked list of pending connections */
94 /* socket to read data from */
97 /* linked list of connections */
109 /* valid configuration file keys */
110 static const char *config_keys[] =
117 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
119 /* socket configuration */
120 static char *sock_file = NULL;
121 static char *sock_group = NULL;
122 static int sock_perms = S_IRWXU | S_IRWXG;
123 static int max_conns = MAX_CONNS;
125 /* state of the plugin */
126 static int disabled = 0;
128 /* thread managing "client" connections */
129 static pthread_t connector = (pthread_t) 0;
130 static int connector_socket = -1;
132 /* tell the collector threads that a new connection is available */
133 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
135 /* connections that are waiting to be processed */
136 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
137 static conn_list_t conns;
139 /* tell the connector thread that a collector is available */
140 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
142 /* collector threads */
143 static collector_t **collectors = NULL;
145 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
146 static int available_collectors;
148 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
149 static type_list_t list_count;
150 static type_list_t list_count_copy;
152 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
153 static type_list_t list_size;
154 static type_list_t list_size_copy;
156 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
158 static int score_count;
160 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
161 static type_list_t list_check;
162 static type_list_t list_check_copy;
167 static int email_config (const char *key, const char *value)
169 if (0 == strcasecmp (key, "SocketFile")) {
170 if (NULL != sock_file)
172 sock_file = sstrdup (value);
174 else if (0 == strcasecmp (key, "SocketGroup")) {
175 if (NULL != sock_group)
177 sock_group = sstrdup (value);
179 else if (0 == strcasecmp (key, "SocketPerms")) {
180 /* the user is responsible for providing reasonable values */
181 sock_perms = (int)strtol (value, NULL, 8);
183 else if (0 == strcasecmp (key, "MaxConns")) {
184 long int tmp = strtol (value, NULL, 0);
187 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
188 "value %li, will use default %i.\n",
190 max_conns = MAX_CONNS;
192 else if (tmp > MAX_CONNS_LIMIT) {
193 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
194 "value %li, will use hardcoded limit %i.\n",
195 tmp, MAX_CONNS_LIMIT);
196 max_conns = MAX_CONNS_LIMIT;
199 max_conns = (int)tmp;
206 } /* static int email_config (char *, char *) */
208 /* Increment the value of the given name in the given list by incr. */
209 static void type_list_incr (type_list_t *list, char *name, int incr)
211 if (NULL == list->head) {
212 list->head = (type_t *)smalloc (sizeof (type_t));
214 list->head->name = sstrdup (name);
215 list->head->value = incr;
216 list->head->next = NULL;
218 list->tail = list->head;
223 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
224 if (0 == strcmp (name, ptr->name))
229 list->tail->next = (type_t *)smalloc (sizeof (type_t));
230 list->tail = list->tail->next;
232 list->tail->name = sstrdup (name);
233 list->tail->value = incr;
234 list->tail->next = NULL;
241 } /* static void type_list_incr (type_list_t *, char *) */
243 static void *collect (void *arg)
245 collector_t *this = (collector_t *)arg;
246 pthread_t self = pthread_self ();
253 pthread_mutex_lock (&conns_mutex);
255 while (NULL == conns.head) {
256 pthread_cond_wait (&conn_available, &conns_mutex);
259 connection = conns.head;
260 conns.head = conns.head->next;
262 if (NULL == conns.head) {
266 pthread_mutex_unlock (&conns_mutex);
268 /* make the socket available to the global
269 * thread and connection management */
270 this->socket = connection->socket;
272 log_debug ("[thread #%5lu] handling connection on fd #%i",
273 self, fileno (this->socket));
276 /* 256 bytes ought to be enough for anybody ;-) */
277 char line[256 + 1]; /* line + '\0' */
281 if (NULL == fgets (line, sizeof (line), this->socket)) {
286 log_err ("[thread #%5lu] reading from socket (fd #%i) "
287 "failed: %s", self, fileno (this->socket),
288 sstrerror (errno, errbuf, sizeof (errbuf)));
294 if (('\n' != line[len - 1]) && ('\r' != line[len - 1])) {
295 log_warn ("[thread #%5lu] line too long (> %lu characters): "
296 "'%s' (truncated)", self, sizeof (line) - 1, line);
298 while (NULL != fgets (line, sizeof (line), this->socket))
299 if (('\n' == line[len - 1]) || ('\r' == line[len - 1]))
304 line[len - 1] = '\0';
306 log_debug ("[thread #%5lu] line = '%s'", self, line);
308 if (':' != line[1]) {
309 log_err ("[thread #%5lu] syntax error in line '%s'",
314 if ('e' == line[0]) { /* e:<type>:<bytes> */
316 char *type = strtok_r (line + 2, ":", &ptr);
317 char *tmp = strtok_r (NULL, ":", &ptr);
321 log_err ("[thread #%5lu] syntax error in line '%s'",
328 pthread_mutex_lock (&count_mutex);
329 type_list_incr (&list_count, type, 1);
330 pthread_mutex_unlock (&count_mutex);
333 pthread_mutex_lock (&size_mutex);
334 type_list_incr (&list_size, type, bytes);
335 pthread_mutex_unlock (&size_mutex);
338 else if ('s' == line[0]) { /* s:<value> */
339 pthread_mutex_lock (&score_mutex);
340 score = (score * (double)score_count + atof (line + 2))
341 / (double)(score_count + 1);
343 pthread_mutex_unlock (&score_mutex);
345 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
347 char *type = strtok_r (line + 2, ",", &ptr);
350 pthread_mutex_lock (&check_mutex);
351 type_list_incr (&list_check, type, 1);
352 pthread_mutex_unlock (&check_mutex);
353 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
356 log_err ("[thread #%5lu] unknown type '%c'", self, line[0]);
360 log_debug ("[thread #%5lu] shutting down connection on fd #%i",
361 pthread_self (), fileno (this->socket));
363 fclose (connection->socket);
368 pthread_mutex_lock (&available_mutex);
369 ++available_collectors;
370 pthread_mutex_unlock (&available_mutex);
372 pthread_cond_signal (&collector_available);
375 pthread_exit ((void *)0);
376 } /* static void *collect (void *) */
378 static void *open_connection (void *arg)
380 struct sockaddr_un addr;
382 char *path = (NULL == sock_file) ? SOCK_PATH : sock_file;
383 char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
385 /* create UNIX socket */
387 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
390 log_err ("socket() failed: %s",
391 sstrerror (errno, errbuf, sizeof (errbuf)));
392 pthread_exit ((void *)1);
395 addr.sun_family = AF_UNIX;
397 strncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
398 addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
399 unlink (addr.sun_path);
402 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
403 offsetof (struct sockaddr_un, sun_path)
404 + strlen(addr.sun_path))) {
407 close (connector_socket);
408 connector_socket = -1;
409 log_err ("bind() failed: %s",
410 sstrerror (errno, errbuf, sizeof (errbuf)));
411 pthread_exit ((void *)1);
415 if (-1 == listen (connector_socket, 5)) {
418 close (connector_socket);
419 connector_socket = -1;
420 log_err ("listen() failed: %s",
421 sstrerror (errno, errbuf, sizeof (errbuf)));
422 pthread_exit ((void *)1);
432 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
436 log_warn ("getgrnam_r (%s) failed: %s", group,
437 sstrerror (errno, errbuf, sizeof (errbuf)));
439 else if (grp == NULL)
441 log_warn ("No such group: `%s'", group);
445 status = chown (path, (uid_t) -1, grp->gr_gid);
449 log_warn ("chown (%s, -1, %i) failed: %s",
450 path, (int) grp->gr_gid,
451 sstrerror (errno, errbuf, sizeof (errbuf)));
457 if (0 != chmod (path, sock_perms)) {
459 log_warn ("chmod() failed: %s",
460 sstrerror (errno, errbuf, sizeof (errbuf)));
463 { /* initialize collector threads */
467 pthread_attr_t ptattr;
472 pthread_attr_init (&ptattr);
473 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
475 available_collectors = max_conns;
478 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
480 for (i = 0; i < max_conns; ++i) {
481 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
482 collectors[i]->socket = NULL;
484 if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
485 collect, collectors[i]))) {
487 log_err ("pthread_create() failed: %s",
488 sstrerror (errno, errbuf, sizeof (errbuf)));
489 collectors[i]->thread = (pthread_t) 0;
493 pthread_attr_destroy (&ptattr);
501 pthread_mutex_lock (&available_mutex);
503 while (0 == available_collectors) {
504 pthread_cond_wait (&collector_available, &available_mutex);
507 --available_collectors;
509 pthread_mutex_unlock (&available_mutex);
513 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
514 if (EINTR != errno) {
517 close (connector_socket);
518 connector_socket = -1;
519 log_err ("accept() failed: %s",
520 sstrerror (errno, errbuf, sizeof (errbuf)));
521 pthread_exit ((void *)1);
524 } while (EINTR == errno);
526 connection = (conn_t *)smalloc (sizeof (conn_t));
528 connection->socket = fdopen (remote, "r");
529 connection->next = NULL;
531 if (NULL == connection->socket) {
536 pthread_mutex_lock (&conns_mutex);
538 if (NULL == conns.head) {
539 conns.head = connection;
540 conns.tail = connection;
543 conns.tail->next = connection;
544 conns.tail = conns.tail->next;
547 pthread_mutex_unlock (&conns_mutex);
549 pthread_cond_signal (&conn_available);
551 pthread_exit ((void *)0);
552 } /* static void *open_connection (void *) */
554 static int email_init (void)
558 if (0 != (err = pthread_create (&connector, NULL,
559 open_connection, NULL))) {
562 log_err ("pthread_create() failed: %s",
563 sstrerror (errno, errbuf, sizeof (errbuf)));
568 } /* int email_init */
570 static int email_shutdown (void)
576 if (connector != ((pthread_t) 0)) {
577 pthread_kill (connector, SIGTERM);
578 connector = (pthread_t) 0;
581 if (connector_socket >= 0) {
582 close (connector_socket);
583 connector_socket = -1;
586 /* don't allow any more connections to be processed */
587 pthread_mutex_lock (&conns_mutex);
589 available_collectors = 0;
591 if (collectors != NULL) {
592 for (i = 0; i < max_conns; ++i) {
593 if (collectors[i] == NULL)
596 if (collectors[i]->thread != ((pthread_t) 0)) {
597 pthread_kill (collectors[i]->thread, SIGTERM);
598 collectors[i]->thread = (pthread_t) 0;
601 if (collectors[i]->socket != NULL) {
602 fclose (collectors[i]->socket);
603 collectors[i]->socket = NULL;
606 sfree (collectors[i]);
609 } /* if (collectors != NULL) */
611 pthread_mutex_unlock (&conns_mutex);
613 for (ptr = list_count.head; NULL != ptr; ptr = ptr->next) {
618 for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
623 for (ptr = list_size.head; NULL != ptr; ptr = ptr->next) {
628 for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
633 for (ptr = list_check.head; NULL != ptr; ptr = ptr->next) {
638 for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next) {
643 unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
648 } /* static void email_shutdown (void) */
650 static void email_submit (const char *type, const char *type_instance, gauge_t value)
653 value_list_t vl = VALUE_LIST_INIT;
655 values[0].gauge = value;
659 vl.time = time (NULL);
660 strcpy (vl.host, hostname_g);
661 strcpy (vl.plugin, "email");
662 strncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
664 plugin_dispatch_values (type, &vl);
665 } /* void email_submit */
667 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
668 * that neither the order nor the name of any element of either list is
669 * changed and no elements are deleted. The values of l1 are reset to zero
670 * after they have been copied to l2. */
671 static void copy_type_list (type_list_t *l1, type_list_t *l2)
678 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
679 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
681 ptr2 = (type_t *)smalloc (sizeof (type_t));
695 if (NULL == ptr2->name) {
696 ptr2->name = sstrdup (ptr1->name);
699 ptr2->value = ptr1->value;
705 static int email_read (void)
716 pthread_mutex_lock (&count_mutex);
718 copy_type_list (&list_count, &list_count_copy);
720 pthread_mutex_unlock (&count_mutex);
722 for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
723 email_submit ("email_count", ptr->name, ptr->value);
727 pthread_mutex_lock (&size_mutex);
729 copy_type_list (&list_size, &list_size_copy);
731 pthread_mutex_unlock (&size_mutex);
733 for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
734 email_submit ("email_size", ptr->name, ptr->value);
738 pthread_mutex_lock (&score_mutex);
741 score_count_old = score_count;
745 pthread_mutex_unlock (&score_mutex);
747 if (score_count_old > 0)
748 email_submit ("spam_score", "", score_old);
751 pthread_mutex_lock (&check_mutex);
753 copy_type_list (&list_check, &list_check_copy);
755 pthread_mutex_unlock (&check_mutex);
757 for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
758 email_submit ("spam_check", ptr->name, ptr->value);
761 } /* int email_read */
763 void module_register (void)
765 plugin_register_config ("email", email_config, config_keys, config_keys_num);
766 plugin_register_init ("email", email_init);
767 plugin_register_read ("email", email_read);
768 plugin_register_shutdown ("email", email_shutdown);
769 } /* void module_register */
771 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */