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>,...]
45 #include "configfile.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 ERROR ("email plugin: `MaxConns' was set to invalid "
191 "value %li, will use default %i.\n",
193 max_conns = MAX_CONNS;
195 else if (tmp > MAX_CONNS_LIMIT) {
196 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
197 "value %li, will use hardcoded limit %i.\n",
198 tmp, MAX_CONNS_LIMIT);
199 ERROR ("email plugin: `MaxConns' was set to invalid "
200 "value %li, will use hardcoded limit %i.\n",
201 tmp, MAX_CONNS_LIMIT);
202 max_conns = MAX_CONNS_LIMIT;
205 max_conns = (int)tmp;
212 } /* static int email_config (char *, char *) */
214 /* Increment the value of the given name in the given list by incr. */
215 static void type_list_incr (type_list_t *list, char *name, int incr)
217 if (NULL == list->head) {
218 list->head = smalloc (sizeof (*list->head));
220 list->head->name = sstrdup (name);
221 list->head->value = incr;
222 list->head->next = NULL;
224 list->tail = list->head;
229 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
230 if (0 == strcmp (name, ptr->name))
235 list->tail->next = smalloc (sizeof (*list->tail->next));
236 list->tail = list->tail->next;
238 list->tail->name = sstrdup (name);
239 list->tail->value = incr;
240 list->tail->next = NULL;
247 } /* static void type_list_incr (type_list_t *, char *) */
249 static void *collect (void *arg)
251 collector_t *this = (collector_t *)arg;
256 pthread_mutex_lock (&conns_mutex);
258 while (NULL == conns.head) {
259 pthread_cond_wait (&conn_available, &conns_mutex);
262 connection = conns.head;
263 conns.head = conns.head->next;
265 if (NULL == conns.head) {
269 pthread_mutex_unlock (&conns_mutex);
271 /* make the socket available to the global
272 * thread and connection management */
273 this->socket = connection->socket;
275 log_debug ("collect: handling connection on fd #%i",
276 fileno (this->socket));
279 /* 256 bytes ought to be enough for anybody ;-) */
280 char line[256 + 1]; /* line + '\0' */
284 if (NULL == fgets (line, sizeof (line), this->socket)) {
287 log_err ("collect: reading from socket (fd #%i) "
288 "failed: %s", fileno (this->socket),
289 sstrerror (errno, errbuf, sizeof (errbuf)));
295 if (('\n' != line[len - 1]) && ('\r' != line[len - 1])) {
296 log_warn ("collect: line too long (> %zu characters): "
297 "'%s' (truncated)", sizeof (line) - 1, line);
299 while (NULL != fgets (line, sizeof (line), this->socket))
300 if (('\n' == line[len - 1]) || ('\r' == line[len - 1]))
304 if (len < 3) { /* [a-z] ':' '\n' */
310 log_debug ("collect: line = '%s'", line);
312 if (':' != line[1]) {
313 log_err ("collect: syntax error in line '%s'", line);
317 if ('e' == line[0]) { /* e:<type>:<bytes> */
319 char *type = strtok_r (line + 2, ":", &ptr);
320 char *tmp = strtok_r (NULL, ":", &ptr);
324 log_err ("collect: syntax error in line '%s'", line);
330 pthread_mutex_lock (&count_mutex);
331 type_list_incr (&list_count, type, /* increment = */ 1);
332 pthread_mutex_unlock (&count_mutex);
335 pthread_mutex_lock (&size_mutex);
336 type_list_incr (&list_size, type, /* increment = */ bytes);
337 pthread_mutex_unlock (&size_mutex);
340 else if ('s' == line[0]) { /* s:<value> */
341 pthread_mutex_lock (&score_mutex);
342 score = (score * (double)score_count + atof (line + 2))
343 / (double)(score_count + 1);
345 pthread_mutex_unlock (&score_mutex);
347 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
348 char *dummy = line + 2;
352 pthread_mutex_lock (&check_mutex);
353 while ((type = strtok_r (dummy, ",", &endptr)) != NULL)
356 type_list_incr (&list_check, type, /* increment = */ 1);
358 pthread_mutex_unlock (&check_mutex);
361 log_err ("collect: unknown type '%c'", line[0]);
365 log_debug ("Shutting down connection on fd #%i",
366 fileno (this->socket));
368 fclose (connection->socket);
373 pthread_mutex_lock (&available_mutex);
374 ++available_collectors;
375 pthread_mutex_unlock (&available_mutex);
377 pthread_cond_signal (&collector_available);
380 pthread_exit ((void *)0);
382 } /* static void *collect (void *) */
384 static void *open_connection (void __attribute__((unused)) *arg)
386 struct sockaddr_un addr;
388 const char *path = (NULL == sock_file) ? SOCK_PATH : sock_file;
389 const char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
391 /* create UNIX socket */
393 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
396 log_err ("socket() failed: %s",
397 sstrerror (errno, errbuf, sizeof (errbuf)));
398 pthread_exit ((void *)1);
401 addr.sun_family = AF_UNIX;
402 sstrncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
405 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
406 offsetof (struct sockaddr_un, sun_path)
407 + strlen(addr.sun_path))) {
410 close (connector_socket);
411 connector_socket = -1;
412 log_err ("bind() failed: %s",
413 sstrerror (errno, errbuf, sizeof (errbuf)));
414 pthread_exit ((void *)1);
418 if (-1 == listen (connector_socket, 5)) {
421 close (connector_socket);
422 connector_socket = -1;
423 log_err ("listen() failed: %s",
424 sstrerror (errno, errbuf, sizeof (errbuf)));
425 pthread_exit ((void *)1);
435 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
439 log_warn ("getgrnam_r (%s) failed: %s", group,
440 sstrerror (errno, errbuf, sizeof (errbuf)));
442 else if (grp == NULL)
444 log_warn ("No such group: `%s'", group);
448 status = chown (path, (uid_t) -1, grp->gr_gid);
452 log_warn ("chown (%s, -1, %i) failed: %s",
453 path, (int) grp->gr_gid,
454 sstrerror (errno, errbuf, sizeof (errbuf)));
460 if (0 != chmod (path, sock_perms)) {
462 log_warn ("chmod() failed: %s",
463 sstrerror (errno, errbuf, sizeof (errbuf)));
466 { /* 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 (0 != (err = plugin_thread_create (&collectors[i]->thread,
488 &ptattr, collect, collectors[i]))) {
490 log_err ("pthread_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)
576 if (0 != (err = plugin_thread_create (&connector, NULL,
577 open_connection, NULL))) {
580 log_err ("pthread_create() failed: %s",
581 sstrerror (errno, errbuf, sizeof (errbuf)));
586 } /* int email_init */
588 static void type_list_free (type_list_t *t)
595 type_t *next = this->next;
607 static int email_shutdown (void)
611 if (connector != ((pthread_t) 0)) {
612 pthread_kill (connector, SIGTERM);
613 connector = (pthread_t) 0;
616 if (connector_socket >= 0) {
617 close (connector_socket);
618 connector_socket = -1;
621 /* don't allow any more connections to be processed */
622 pthread_mutex_lock (&conns_mutex);
624 available_collectors = 0;
626 if (collectors != NULL) {
627 for (i = 0; i < max_conns; ++i) {
628 if (collectors[i] == NULL)
631 if (collectors[i]->thread != ((pthread_t) 0)) {
632 pthread_kill (collectors[i]->thread, SIGTERM);
633 collectors[i]->thread = (pthread_t) 0;
636 if (collectors[i]->socket != NULL) {
637 fclose (collectors[i]->socket);
638 collectors[i]->socket = NULL;
641 sfree (collectors[i]);
644 } /* if (collectors != NULL) */
646 pthread_mutex_unlock (&conns_mutex);
648 type_list_free (&list_count);
649 type_list_free (&list_count_copy);
650 type_list_free (&list_size);
651 type_list_free (&list_size_copy);
652 type_list_free (&list_check);
653 type_list_free (&list_check_copy);
655 unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
660 } /* static void email_shutdown (void) */
662 static void email_submit (const char *type, const char *type_instance, gauge_t value)
665 value_list_t vl = VALUE_LIST_INIT;
667 values[0].gauge = value;
671 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
672 sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
673 sstrncpy (vl.type, type, sizeof (vl.type));
674 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
676 plugin_dispatch_values (&vl);
677 } /* void email_submit */
679 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
680 * that neither the order nor the name of any element of either list is
681 * changed and no elements are deleted. The values of l1 are reset to zero
682 * after they have been copied to l2. */
683 static void copy_type_list (type_list_t *l1, type_list_t *l2)
690 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
691 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
693 ptr2 = smalloc (sizeof (*ptr2));
707 if (NULL == ptr2->name) {
708 ptr2->name = sstrdup (ptr1->name);
711 ptr2->value = ptr1->value;
717 static int email_read (void)
728 pthread_mutex_lock (&count_mutex);
730 copy_type_list (&list_count, &list_count_copy);
732 pthread_mutex_unlock (&count_mutex);
734 for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
735 email_submit ("email_count", ptr->name, ptr->value);
739 pthread_mutex_lock (&size_mutex);
741 copy_type_list (&list_size, &list_size_copy);
743 pthread_mutex_unlock (&size_mutex);
745 for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
746 email_submit ("email_size", ptr->name, ptr->value);
750 pthread_mutex_lock (&score_mutex);
753 score_count_old = score_count;
757 pthread_mutex_unlock (&score_mutex);
759 if (score_count_old > 0)
760 email_submit ("spam_score", "", score_old);
763 pthread_mutex_lock (&check_mutex);
765 copy_type_list (&list_check, &list_check_copy);
767 pthread_mutex_unlock (&check_mutex);
769 for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
770 email_submit ("spam_check", ptr->name, ptr->value);
773 } /* int email_read */
775 void module_register (void)
777 plugin_register_config ("email", email_config, config_keys, config_keys_num);
778 plugin_register_init ("email", email_init);
779 plugin_register_read ("email", email_read);
780 plugin_register_shutdown ("email", email_shutdown);
781 } /* void module_register */
783 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */