2 * collectd - src/email.c
3 * Copyright (C) 2006-2008 Sebastian Harl
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
24 * Sebastian Harl <sh at tokkee.org>
28 * This plugin communicates with a spam filter, a virus scanner or similar
29 * software using a UNIX socket and a very simple protocol:
31 * e-mail type (e.g. ham, spam, virus, ...) and size
37 * successful spam checks
38 * c:<type1>[,<type2>,...]
46 #include "configfile.h"
51 #include <sys/select.h>
53 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
55 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
56 #endif /* UNIX_PATH_MAX */
60 #endif /* HAVE_GRP_H */
62 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
64 #define MAX_CONNS_LIMIT 16384
66 #define log_debug(...) DEBUG ("email: "__VA_ARGS__)
67 #define log_err(...) ERROR ("email: "__VA_ARGS__)
68 #define log_warn(...) WARNING ("email: "__VA_ARGS__)
71 * Private data structures
73 /* linked list of email and check types */
85 /* collector thread control information */
86 typedef struct collector {
89 /* socket descriptor of the current/last connection */
93 /* linked list of pending connections */
95 /* socket to read data from */
98 /* linked list of connections */
110 /* valid configuration file keys */
111 static const char *config_keys[] =
118 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
120 /* socket configuration */
121 static char *sock_file = NULL;
122 static char *sock_group = NULL;
123 static int sock_perms = S_IRWXU | S_IRWXG;
124 static int max_conns = MAX_CONNS;
126 /* state of the plugin */
127 static int disabled = 0;
129 /* thread managing "client" connections */
130 static pthread_t connector = (pthread_t) 0;
131 static int connector_socket = -1;
133 /* tell the collector threads that a new connection is available */
134 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
136 /* connections that are waiting to be processed */
137 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
138 static conn_list_t conns;
140 /* tell the connector thread that a collector is available */
141 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
143 /* collector threads */
144 static collector_t **collectors = NULL;
146 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
147 static int available_collectors;
149 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
150 static type_list_t list_count;
151 static type_list_t list_count_copy;
153 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
154 static type_list_t list_size;
155 static type_list_t list_size_copy;
157 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
159 static int score_count;
161 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
162 static type_list_t list_check;
163 static type_list_t list_check_copy;
168 static int email_config (const char *key, const char *value)
170 if (0 == strcasecmp (key, "SocketFile")) {
171 if (NULL != sock_file)
173 sock_file = sstrdup (value);
175 else if (0 == strcasecmp (key, "SocketGroup")) {
176 if (NULL != sock_group)
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 ERROR ("email plugin: `MaxConns' was set to invalid "
192 "value %li, will use default %i.\n",
194 max_conns = MAX_CONNS;
196 else if (tmp > MAX_CONNS_LIMIT) {
197 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
198 "value %li, will use hardcoded limit %i.\n",
199 tmp, MAX_CONNS_LIMIT);
200 ERROR ("email plugin: `MaxConns' was set to invalid "
201 "value %li, will use hardcoded limit %i.\n",
202 tmp, MAX_CONNS_LIMIT);
203 max_conns = MAX_CONNS_LIMIT;
206 max_conns = (int)tmp;
213 } /* static int email_config (char *, char *) */
215 /* Increment the value of the given name in the given list by incr. */
216 static void type_list_incr (type_list_t *list, char *name, int incr)
218 if (NULL == list->head) {
219 list->head = smalloc (sizeof (*list->head));
221 list->head->name = sstrdup (name);
222 list->head->value = incr;
223 list->head->next = NULL;
225 list->tail = list->head;
230 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
231 if (0 == strcmp (name, ptr->name))
236 list->tail->next = smalloc (sizeof (*list->tail->next));
237 list->tail = list->tail->next;
239 list->tail->name = sstrdup (name);
240 list->tail->value = incr;
241 list->tail->next = NULL;
248 } /* static void type_list_incr (type_list_t *, char *) */
250 static void *collect (void *arg)
252 collector_t *this = (collector_t *)arg;
257 pthread_mutex_lock (&conns_mutex);
259 while (NULL == conns.head) {
260 pthread_cond_wait (&conn_available, &conns_mutex);
263 connection = conns.head;
264 conns.head = conns.head->next;
266 if (NULL == conns.head) {
270 pthread_mutex_unlock (&conns_mutex);
272 /* make the socket available to the global
273 * thread and connection management */
274 this->socket = connection->socket;
276 log_debug ("collect: handling connection on fd #%i",
277 fileno (this->socket));
280 /* 256 bytes ought to be enough for anybody ;-) */
281 char line[256 + 1]; /* line + '\0' */
285 if (NULL == fgets (line, sizeof (line), this->socket)) {
288 log_err ("collect: reading from socket (fd #%i) "
289 "failed: %s", fileno (this->socket),
290 sstrerror (errno, errbuf, sizeof (errbuf)));
296 if (('\n' != line[len - 1]) && ('\r' != line[len - 1])) {
297 log_warn ("collect: line too long (> %zu characters): "
298 "'%s' (truncated)", sizeof (line) - 1, line);
300 while (NULL != fgets (line, sizeof (line), this->socket))
301 if (('\n' == line[len - 1]) || ('\r' == line[len - 1]))
305 if (len < 3) { /* [a-z] ':' '\n' */
311 log_debug ("collect: line = '%s'", line);
313 if (':' != line[1]) {
314 log_err ("collect: syntax error in line '%s'", line);
318 if ('e' == line[0]) { /* e:<type>:<bytes> */
320 char *type = strtok_r (line + 2, ":", &ptr);
321 char *tmp = strtok_r (NULL, ":", &ptr);
325 log_err ("collect: syntax error in line '%s'", line);
331 pthread_mutex_lock (&count_mutex);
332 type_list_incr (&list_count, type, /* increment = */ 1);
333 pthread_mutex_unlock (&count_mutex);
336 pthread_mutex_lock (&size_mutex);
337 type_list_incr (&list_size, type, /* increment = */ bytes);
338 pthread_mutex_unlock (&size_mutex);
341 else if ('s' == line[0]) { /* s:<value> */
342 pthread_mutex_lock (&score_mutex);
343 score = (score * (double)score_count + atof (line + 2))
344 / (double)(score_count + 1);
346 pthread_mutex_unlock (&score_mutex);
348 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
349 char *dummy = line + 2;
353 pthread_mutex_lock (&check_mutex);
354 while ((type = strtok_r (dummy, ",", &endptr)) != NULL)
357 type_list_incr (&list_check, type, /* increment = */ 1);
359 pthread_mutex_unlock (&check_mutex);
362 log_err ("collect: unknown type '%c'", line[0]);
366 log_debug ("Shutting down connection on fd #%i",
367 fileno (this->socket));
369 fclose (connection->socket);
374 pthread_mutex_lock (&available_mutex);
375 ++available_collectors;
376 pthread_mutex_unlock (&available_mutex);
378 pthread_cond_signal (&collector_available);
381 pthread_exit ((void *)0);
383 } /* static void *collect (void *) */
385 static void *open_connection (void __attribute__((unused)) *arg)
387 struct sockaddr_un addr;
389 const char *path = (NULL == sock_file) ? SOCK_PATH : sock_file;
390 const char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
392 /* create UNIX socket */
394 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
397 log_err ("socket() failed: %s",
398 sstrerror (errno, errbuf, sizeof (errbuf)));
399 pthread_exit ((void *)1);
402 addr.sun_family = AF_UNIX;
403 sstrncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
406 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
407 offsetof (struct sockaddr_un, sun_path)
408 + strlen(addr.sun_path))) {
411 close (connector_socket);
412 connector_socket = -1;
413 log_err ("bind() failed: %s",
414 sstrerror (errno, errbuf, sizeof (errbuf)));
415 pthread_exit ((void *)1);
419 if (-1 == listen (connector_socket, 5)) {
422 close (connector_socket);
423 connector_socket = -1;
424 log_err ("listen() failed: %s",
425 sstrerror (errno, errbuf, sizeof (errbuf)));
426 pthread_exit ((void *)1);
436 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
440 log_warn ("getgrnam_r (%s) failed: %s", group,
441 sstrerror (errno, errbuf, sizeof (errbuf)));
443 else if (grp == NULL)
445 log_warn ("No such group: `%s'", group);
449 status = chown (path, (uid_t) -1, grp->gr_gid);
453 log_warn ("chown (%s, -1, %i) failed: %s",
454 path, (int) grp->gr_gid,
455 sstrerror (errno, errbuf, sizeof (errbuf)));
461 if (0 != chmod (path, sock_perms)) {
463 log_warn ("chmod() failed: %s",
464 sstrerror (errno, errbuf, sizeof (errbuf)));
467 { /* initialize collector threads */
468 pthread_attr_t ptattr;
473 pthread_attr_init (&ptattr);
474 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
476 available_collectors = max_conns;
479 smalloc (max_conns * sizeof (*collectors));
481 for (int i = 0; i < max_conns; ++i) {
482 collectors[i] = smalloc (sizeof (*collectors[i]));
483 collectors[i]->socket = NULL;
485 if (plugin_thread_create (&collectors[i]->thread,
486 &ptattr, collect, collectors[i]) != 0) {
488 log_err ("plugin_thread_create() failed: %s",
489 sstrerror (errno, errbuf, sizeof (errbuf)));
490 collectors[i]->thread = (pthread_t) 0;
494 pthread_attr_destroy (&ptattr);
502 pthread_mutex_lock (&available_mutex);
504 while (0 == available_collectors) {
505 pthread_cond_wait (&collector_available, &available_mutex);
508 --available_collectors;
510 pthread_mutex_unlock (&available_mutex);
515 remote = accept (connector_socket, NULL, NULL);
523 close (connector_socket);
524 connector_socket = -1;
525 log_err ("accept() failed: %s",
526 sstrerror (errno, errbuf, sizeof (errbuf)));
527 pthread_exit ((void *)1);
530 /* access() succeeded. */
534 connection = calloc (1, sizeof (*connection));
535 if (connection == NULL)
541 connection->socket = fdopen (remote, "r");
542 connection->next = NULL;
544 if (NULL == connection->socket) {
550 pthread_mutex_lock (&conns_mutex);
552 if (NULL == conns.head) {
553 conns.head = connection;
554 conns.tail = connection;
557 conns.tail->next = connection;
558 conns.tail = conns.tail->next;
561 pthread_mutex_unlock (&conns_mutex);
563 pthread_cond_signal (&conn_available);
566 pthread_exit ((void *) 0);
568 } /* static void *open_connection (void *) */
570 static int email_init (void)
572 if (plugin_thread_create (&connector, NULL,
573 open_connection, NULL) != 0) {
576 log_err ("plugin_thread_create() failed: %s",
577 sstrerror (errno, errbuf, sizeof (errbuf)));
582 } /* int email_init */
584 static void type_list_free (type_list_t *t)
591 type_t *next = this->next;
603 static int email_shutdown (void)
605 if (connector != ((pthread_t) 0)) {
606 pthread_kill (connector, SIGTERM);
607 connector = (pthread_t) 0;
610 if (connector_socket >= 0) {
611 close (connector_socket);
612 connector_socket = -1;
615 /* don't allow any more connections to be processed */
616 pthread_mutex_lock (&conns_mutex);
618 available_collectors = 0;
620 if (collectors != NULL) {
621 for (int i = 0; i < max_conns; ++i) {
622 if (collectors[i] == NULL)
625 if (collectors[i]->thread != ((pthread_t) 0)) {
626 pthread_kill (collectors[i]->thread, SIGTERM);
627 collectors[i]->thread = (pthread_t) 0;
630 if (collectors[i]->socket != NULL) {
631 fclose (collectors[i]->socket);
632 collectors[i]->socket = NULL;
635 sfree (collectors[i]);
638 } /* if (collectors != NULL) */
640 pthread_mutex_unlock (&conns_mutex);
642 type_list_free (&list_count);
643 type_list_free (&list_count_copy);
644 type_list_free (&list_size);
645 type_list_free (&list_size_copy);
646 type_list_free (&list_check);
647 type_list_free (&list_check_copy);
649 unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
654 } /* static void email_shutdown (void) */
656 static void email_submit (const char *type, const char *type_instance, gauge_t value)
659 value_list_t vl = VALUE_LIST_INIT;
661 values[0].gauge = value;
665 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
666 sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
667 sstrncpy (vl.type, type, sizeof (vl.type));
668 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
670 plugin_dispatch_values (&vl);
671 } /* void email_submit */
673 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
674 * that neither the order nor the name of any element of either list is
675 * changed and no elements are deleted. The values of l1 are reset to zero
676 * after they have been copied to l2. */
677 static void copy_type_list (type_list_t *l1, type_list_t *l2)
681 for (type_t *ptr1 = l1->head, *ptr2 = l2->head; NULL != ptr1;
682 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
684 ptr2 = smalloc (sizeof (*ptr2));
698 if (NULL == ptr2->name) {
699 ptr2->name = sstrdup (ptr1->name);
702 ptr2->value = ptr1->value;
708 static int email_read (void)
717 pthread_mutex_lock (&count_mutex);
719 copy_type_list (&list_count, &list_count_copy);
721 pthread_mutex_unlock (&count_mutex);
723 for (type_t *ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
724 email_submit ("email_count", ptr->name, ptr->value);
728 pthread_mutex_lock (&size_mutex);
730 copy_type_list (&list_size, &list_size_copy);
732 pthread_mutex_unlock (&size_mutex);
734 for (type_t *ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
735 email_submit ("email_size", ptr->name, ptr->value);
739 pthread_mutex_lock (&score_mutex);
742 score_count_old = score_count;
746 pthread_mutex_unlock (&score_mutex);
748 if (score_count_old > 0)
749 email_submit ("spam_score", "", score_old);
752 pthread_mutex_lock (&check_mutex);
754 copy_type_list (&list_check, &list_check_copy);
756 pthread_mutex_unlock (&check_mutex);
758 for (type_t *ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
759 email_submit ("spam_check", ptr->name, ptr->value);
762 } /* int email_read */
764 void module_register (void)
766 plugin_register_config ("email", email_config, config_keys, config_keys_num);
767 plugin_register_init ("email", email_init);
768 plugin_register_read ("email", email_read);
769 plugin_register_shutdown ("email", email_shutdown);
770 } /* void module_register */
772 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */