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 */
470 pthread_attr_t ptattr;
475 pthread_attr_init (&ptattr);
476 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
478 available_collectors = max_conns;
481 smalloc (max_conns * sizeof (*collectors));
483 for (i = 0; i < max_conns; ++i) {
484 collectors[i] = smalloc (sizeof (*collectors[i]));
485 collectors[i]->socket = NULL;
487 if (plugin_thread_create (&collectors[i]->thread,
488 &ptattr, collect, collectors[i]) != 0) {
490 log_err ("plugin_thread_create() failed: %s",
491 sstrerror (errno, errbuf, sizeof (errbuf)));
492 collectors[i]->thread = (pthread_t) 0;
496 pthread_attr_destroy (&ptattr);
504 pthread_mutex_lock (&available_mutex);
506 while (0 == available_collectors) {
507 pthread_cond_wait (&collector_available, &available_mutex);
510 --available_collectors;
512 pthread_mutex_unlock (&available_mutex);
517 remote = accept (connector_socket, NULL, NULL);
525 close (connector_socket);
526 connector_socket = -1;
527 log_err ("accept() failed: %s",
528 sstrerror (errno, errbuf, sizeof (errbuf)));
529 pthread_exit ((void *)1);
532 /* access() succeeded. */
536 connection = calloc (1, sizeof (*connection));
537 if (connection == NULL)
543 connection->socket = fdopen (remote, "r");
544 connection->next = NULL;
546 if (NULL == connection->socket) {
552 pthread_mutex_lock (&conns_mutex);
554 if (NULL == conns.head) {
555 conns.head = connection;
556 conns.tail = connection;
559 conns.tail->next = connection;
560 conns.tail = conns.tail->next;
563 pthread_mutex_unlock (&conns_mutex);
565 pthread_cond_signal (&conn_available);
568 pthread_exit ((void *) 0);
570 } /* static void *open_connection (void *) */
572 static int email_init (void)
574 if (plugin_thread_create (&connector, NULL,
575 open_connection, NULL) != 0) {
578 log_err ("plugin_thread_create() failed: %s",
579 sstrerror (errno, errbuf, sizeof (errbuf)));
584 } /* int email_init */
586 static void type_list_free (type_list_t *t)
593 type_t *next = this->next;
605 static int email_shutdown (void)
609 if (connector != ((pthread_t) 0)) {
610 pthread_kill (connector, SIGTERM);
611 connector = (pthread_t) 0;
614 if (connector_socket >= 0) {
615 close (connector_socket);
616 connector_socket = -1;
619 /* don't allow any more connections to be processed */
620 pthread_mutex_lock (&conns_mutex);
622 available_collectors = 0;
624 if (collectors != NULL) {
625 for (i = 0; i < max_conns; ++i) {
626 if (collectors[i] == NULL)
629 if (collectors[i]->thread != ((pthread_t) 0)) {
630 pthread_kill (collectors[i]->thread, SIGTERM);
631 collectors[i]->thread = (pthread_t) 0;
634 if (collectors[i]->socket != NULL) {
635 fclose (collectors[i]->socket);
636 collectors[i]->socket = NULL;
639 sfree (collectors[i]);
642 } /* if (collectors != NULL) */
644 pthread_mutex_unlock (&conns_mutex);
646 type_list_free (&list_count);
647 type_list_free (&list_count_copy);
648 type_list_free (&list_size);
649 type_list_free (&list_size_copy);
650 type_list_free (&list_check);
651 type_list_free (&list_check_copy);
653 unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
658 } /* static void email_shutdown (void) */
660 static void email_submit (const char *type, const char *type_instance, gauge_t value)
663 value_list_t vl = VALUE_LIST_INIT;
665 values[0].gauge = value;
669 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
670 sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
671 sstrncpy (vl.type, type, sizeof (vl.type));
672 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
674 plugin_dispatch_values (&vl);
675 } /* void email_submit */
677 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
678 * that neither the order nor the name of any element of either list is
679 * changed and no elements are deleted. The values of l1 are reset to zero
680 * after they have been copied to l2. */
681 static void copy_type_list (type_list_t *l1, type_list_t *l2)
688 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
689 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
691 ptr2 = smalloc (sizeof (*ptr2));
705 if (NULL == ptr2->name) {
706 ptr2->name = sstrdup (ptr1->name);
709 ptr2->value = ptr1->value;
715 static int email_read (void)
726 pthread_mutex_lock (&count_mutex);
728 copy_type_list (&list_count, &list_count_copy);
730 pthread_mutex_unlock (&count_mutex);
732 for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
733 email_submit ("email_count", ptr->name, ptr->value);
737 pthread_mutex_lock (&size_mutex);
739 copy_type_list (&list_size, &list_size_copy);
741 pthread_mutex_unlock (&size_mutex);
743 for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
744 email_submit ("email_size", ptr->name, ptr->value);
748 pthread_mutex_lock (&score_mutex);
751 score_count_old = score_count;
755 pthread_mutex_unlock (&score_mutex);
757 if (score_count_old > 0)
758 email_submit ("spam_score", "", score_old);
761 pthread_mutex_lock (&check_mutex);
763 copy_type_list (&list_check, &list_check_copy);
765 pthread_mutex_unlock (&check_mutex);
767 for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
768 email_submit ("spam_check", ptr->name, ptr->value);
771 } /* int email_read */
773 void module_register (void)
775 plugin_register_config ("email", email_config, config_keys, config_keys_num);
776 plugin_register_init ("email", email_init);
777 plugin_register_read ("email", email_read);
778 plugin_register_shutdown ("email", email_shutdown);
779 } /* void module_register */
781 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */