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"
53 #include <sys/socket.h>
55 #include <sys/select.h>
57 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
59 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
60 #endif /* UNIX_PATH_MAX */
64 #endif /* HAVE_GRP_H */
66 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
68 #define MAX_CONNS_LIMIT 16384
70 #define log_debug(...) DEBUG ("email: "__VA_ARGS__)
71 #define log_err(...) ERROR ("email: "__VA_ARGS__)
72 #define log_warn(...) WARNING ("email: "__VA_ARGS__)
75 * Private data structures
77 /* linked list of email and check types */
89 /* collector thread control information */
90 typedef struct collector {
93 /* socket descriptor of the current/last connection */
97 /* linked list of pending connections */
99 /* socket to read data from */
102 /* linked list of connections */
114 /* valid configuration file keys */
115 static const char *config_keys[] =
122 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
124 /* socket configuration */
125 static char *sock_file = NULL;
126 static char *sock_group = NULL;
127 static int sock_perms = S_IRWXU | S_IRWXG;
128 static int max_conns = MAX_CONNS;
130 /* state of the plugin */
131 static int disabled = 0;
133 /* thread managing "client" connections */
134 static pthread_t connector = (pthread_t) 0;
135 static int connector_socket = -1;
137 /* tell the collector threads that a new connection is available */
138 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
140 /* connections that are waiting to be processed */
141 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
142 static conn_list_t conns;
144 /* tell the connector thread that a collector is available */
145 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
147 /* collector threads */
148 static collector_t **collectors = NULL;
150 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
151 static int available_collectors;
153 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
154 static type_list_t list_count;
155 static type_list_t list_count_copy;
157 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
158 static type_list_t list_size;
159 static type_list_t list_size_copy;
161 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
163 static int score_count;
165 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
166 static type_list_t list_check;
167 static type_list_t list_check_copy;
172 static int email_config (const char *key, const char *value)
174 if (0 == strcasecmp (key, "SocketFile")) {
175 if (NULL != sock_file)
177 sock_file = sstrdup (value);
179 else if (0 == strcasecmp (key, "SocketGroup")) {
180 if (NULL != sock_group)
182 sock_group = sstrdup (value);
184 else if (0 == strcasecmp (key, "SocketPerms")) {
185 /* the user is responsible for providing reasonable values */
186 sock_perms = (int)strtol (value, NULL, 8);
188 else if (0 == strcasecmp (key, "MaxConns")) {
189 long int tmp = strtol (value, NULL, 0);
192 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
193 "value %li, will use default %i.\n",
195 ERROR ("email plugin: `MaxConns' was set to invalid "
196 "value %li, will use default %i.\n",
198 max_conns = MAX_CONNS;
200 else if (tmp > MAX_CONNS_LIMIT) {
201 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
202 "value %li, will use hardcoded limit %i.\n",
203 tmp, MAX_CONNS_LIMIT);
204 ERROR ("email plugin: `MaxConns' was set to invalid "
205 "value %li, will use hardcoded limit %i.\n",
206 tmp, MAX_CONNS_LIMIT);
207 max_conns = MAX_CONNS_LIMIT;
210 max_conns = (int)tmp;
217 } /* static int email_config (char *, char *) */
219 /* Increment the value of the given name in the given list by incr. */
220 static void type_list_incr (type_list_t *list, char *name, int incr)
222 if (NULL == list->head) {
223 list->head = (type_t *)smalloc (sizeof (type_t));
225 list->head->name = sstrdup (name);
226 list->head->value = incr;
227 list->head->next = NULL;
229 list->tail = list->head;
234 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
235 if (0 == strcmp (name, ptr->name))
240 list->tail->next = (type_t *)smalloc (sizeof (type_t));
241 list->tail = list->tail->next;
243 list->tail->name = sstrdup (name);
244 list->tail->value = incr;
245 list->tail->next = NULL;
252 } /* static void type_list_incr (type_list_t *, char *) */
254 static void *collect (void *arg)
256 collector_t *this = (collector_t *)arg;
263 pthread_mutex_lock (&conns_mutex);
265 while (NULL == conns.head) {
266 pthread_cond_wait (&conn_available, &conns_mutex);
269 connection = conns.head;
270 conns.head = conns.head->next;
272 if (NULL == conns.head) {
276 pthread_mutex_unlock (&conns_mutex);
278 /* make the socket available to the global
279 * thread and connection management */
280 this->socket = connection->socket;
282 log_debug ("collect: handling connection on fd #%i",
283 fileno (this->socket));
286 /* 256 bytes ought to be enough for anybody ;-) */
287 char line[256 + 1]; /* line + '\0' */
291 if (NULL == fgets (line, sizeof (line), this->socket)) {
296 log_err ("collect: reading from socket (fd #%i) "
297 "failed: %s", fileno (this->socket),
298 sstrerror (errno, errbuf, sizeof (errbuf)));
304 if (('\n' != line[len - 1]) && ('\r' != line[len - 1])) {
305 log_warn ("collect: line too long (> %zu characters): "
306 "'%s' (truncated)", sizeof (line) - 1, line);
308 while (NULL != fgets (line, sizeof (line), this->socket))
309 if (('\n' == line[len - 1]) || ('\r' == line[len - 1]))
314 line[len - 1] = '\0';
316 log_debug ("collect: line = '%s'", line);
318 if (':' != line[1]) {
319 log_err ("collect: syntax error in line '%s'", line);
323 if ('e' == line[0]) { /* e:<type>:<bytes> */
325 char *type = strtok_r (line + 2, ":", &ptr);
326 char *tmp = strtok_r (NULL, ":", &ptr);
330 log_err ("collect: syntax error in line '%s'", line);
336 pthread_mutex_lock (&count_mutex);
337 type_list_incr (&list_count, type, 1);
338 pthread_mutex_unlock (&count_mutex);
341 pthread_mutex_lock (&size_mutex);
342 type_list_incr (&list_size, type, bytes);
343 pthread_mutex_unlock (&size_mutex);
346 else if ('s' == line[0]) { /* s:<value> */
347 pthread_mutex_lock (&score_mutex);
348 score = (score * (double)score_count + atof (line + 2))
349 / (double)(score_count + 1);
351 pthread_mutex_unlock (&score_mutex);
353 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
355 char *type = strtok_r (line + 2, ",", &ptr);
358 pthread_mutex_lock (&check_mutex);
359 type_list_incr (&list_check, type, 1);
360 pthread_mutex_unlock (&check_mutex);
361 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
364 log_err ("collect: unknown type '%c'", line[0]);
368 log_debug ("Shutting down connection on fd #%i",
369 fileno (this->socket));
371 fclose (connection->socket);
376 pthread_mutex_lock (&available_mutex);
377 ++available_collectors;
378 pthread_mutex_unlock (&available_mutex);
380 pthread_cond_signal (&collector_available);
383 pthread_exit ((void *)0);
385 } /* static void *collect (void *) */
387 static void *open_connection (void __attribute__((unused)) *arg)
389 struct sockaddr_un addr;
391 char *path = (NULL == sock_file) ? SOCK_PATH : sock_file;
392 char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
394 /* create UNIX socket */
396 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
399 log_err ("socket() failed: %s",
400 sstrerror (errno, errbuf, sizeof (errbuf)));
401 pthread_exit ((void *)1);
404 addr.sun_family = AF_UNIX;
405 sstrncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
408 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
409 offsetof (struct sockaddr_un, sun_path)
410 + strlen(addr.sun_path))) {
413 close (connector_socket);
414 connector_socket = -1;
415 log_err ("bind() failed: %s",
416 sstrerror (errno, errbuf, sizeof (errbuf)));
417 pthread_exit ((void *)1);
421 if (-1 == listen (connector_socket, 5)) {
424 close (connector_socket);
425 connector_socket = -1;
426 log_err ("listen() failed: %s",
427 sstrerror (errno, errbuf, sizeof (errbuf)));
428 pthread_exit ((void *)1);
438 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
442 log_warn ("getgrnam_r (%s) failed: %s", group,
443 sstrerror (errno, errbuf, sizeof (errbuf)));
445 else if (grp == NULL)
447 log_warn ("No such group: `%s'", group);
451 status = chown (path, (uid_t) -1, grp->gr_gid);
455 log_warn ("chown (%s, -1, %i) failed: %s",
456 path, (int) grp->gr_gid,
457 sstrerror (errno, errbuf, sizeof (errbuf)));
463 if (0 != chmod (path, sock_perms)) {
465 log_warn ("chmod() failed: %s",
466 sstrerror (errno, errbuf, sizeof (errbuf)));
469 { /* initialize collector threads */
473 pthread_attr_t ptattr;
478 pthread_attr_init (&ptattr);
479 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
481 available_collectors = max_conns;
484 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
486 for (i = 0; i < max_conns; ++i) {
487 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
488 collectors[i]->socket = NULL;
490 if (0 != (err = plugin_thread_create (&collectors[i]->thread,
491 &ptattr, collect, collectors[i]))) {
493 log_err ("pthread_create() failed: %s",
494 sstrerror (errno, errbuf, sizeof (errbuf)));
495 collectors[i]->thread = (pthread_t) 0;
499 pthread_attr_destroy (&ptattr);
507 pthread_mutex_lock (&available_mutex);
509 while (0 == available_collectors) {
510 pthread_cond_wait (&collector_available, &available_mutex);
513 --available_collectors;
515 pthread_mutex_unlock (&available_mutex);
519 if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
520 if (EINTR != errno) {
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 } while (EINTR == errno);
532 connection = (conn_t *)smalloc (sizeof (conn_t));
534 connection->socket = fdopen (remote, "r");
535 connection->next = NULL;
537 if (NULL == connection->socket) {
542 pthread_mutex_lock (&conns_mutex);
544 if (NULL == conns.head) {
545 conns.head = connection;
546 conns.tail = connection;
549 conns.tail->next = connection;
550 conns.tail = conns.tail->next;
553 pthread_mutex_unlock (&conns_mutex);
555 pthread_cond_signal (&conn_available);
558 pthread_exit ((void *) 0);
560 } /* static void *open_connection (void *) */
562 static int email_init (void)
566 if (0 != (err = plugin_thread_create (&connector, NULL,
567 open_connection, NULL))) {
570 log_err ("pthread_create() failed: %s",
571 sstrerror (errno, errbuf, sizeof (errbuf)));
576 } /* int email_init */
578 static int email_shutdown (void)
584 if (connector != ((pthread_t) 0)) {
585 pthread_kill (connector, SIGTERM);
586 connector = (pthread_t) 0;
589 if (connector_socket >= 0) {
590 close (connector_socket);
591 connector_socket = -1;
594 /* don't allow any more connections to be processed */
595 pthread_mutex_lock (&conns_mutex);
597 available_collectors = 0;
599 if (collectors != NULL) {
600 for (i = 0; i < max_conns; ++i) {
601 if (collectors[i] == NULL)
604 if (collectors[i]->thread != ((pthread_t) 0)) {
605 pthread_kill (collectors[i]->thread, SIGTERM);
606 collectors[i]->thread = (pthread_t) 0;
609 if (collectors[i]->socket != NULL) {
610 fclose (collectors[i]->socket);
611 collectors[i]->socket = NULL;
614 sfree (collectors[i]);
617 } /* if (collectors != NULL) */
619 pthread_mutex_unlock (&conns_mutex);
621 for (ptr = list_count.head; NULL != ptr; ptr = ptr->next) {
626 for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
631 for (ptr = list_size.head; NULL != ptr; ptr = ptr->next) {
636 for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
641 for (ptr = list_check.head; NULL != ptr; ptr = ptr->next) {
646 for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next) {
651 unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
656 } /* static void email_shutdown (void) */
658 static void email_submit (const char *type, const char *type_instance, gauge_t value)
661 value_list_t vl = VALUE_LIST_INIT;
663 values[0].gauge = value;
667 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
668 sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
669 sstrncpy (vl.type, type, sizeof (vl.type));
670 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
672 plugin_dispatch_values (&vl);
673 } /* void email_submit */
675 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
676 * that neither the order nor the name of any element of either list is
677 * changed and no elements are deleted. The values of l1 are reset to zero
678 * after they have been copied to l2. */
679 static void copy_type_list (type_list_t *l1, type_list_t *l2)
686 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
687 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
689 ptr2 = (type_t *)smalloc (sizeof (type_t));
703 if (NULL == ptr2->name) {
704 ptr2->name = sstrdup (ptr1->name);
707 ptr2->value = ptr1->value;
713 static int email_read (void)
724 pthread_mutex_lock (&count_mutex);
726 copy_type_list (&list_count, &list_count_copy);
728 pthread_mutex_unlock (&count_mutex);
730 for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
731 email_submit ("email_count", ptr->name, ptr->value);
735 pthread_mutex_lock (&size_mutex);
737 copy_type_list (&list_size, &list_size_copy);
739 pthread_mutex_unlock (&size_mutex);
741 for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
742 email_submit ("email_size", ptr->name, ptr->value);
746 pthread_mutex_lock (&score_mutex);
749 score_count_old = score_count;
753 pthread_mutex_unlock (&score_mutex);
755 if (score_count_old > 0)
756 email_submit ("spam_score", "", score_old);
759 pthread_mutex_lock (&check_mutex);
761 copy_type_list (&list_check, &list_check_copy);
763 pthread_mutex_unlock (&check_mutex);
765 for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
766 email_submit ("spam_check", ptr->name, ptr->value);
769 } /* int email_read */
771 void module_register (void)
773 plugin_register_config ("email", email_config, config_keys, config_keys_num);
774 plugin_register_init ("email", email_init);
775 plugin_register_read ("email", email_read);
776 plugin_register_shutdown ("email", email_shutdown);
777 } /* void module_register */
779 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */