f5dcf7090fa37f53737aa7bd559aecf98fdf65e7
1 /**
2 * collectd - src/email.c
3 * Copyright (C) 2006-2008 Sebastian Harl
4 *
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:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
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.
22 *
23 * Authors:
24 * Sebastian Harl <sh at tokkee.org>
25 **/
27 /*
28 * This plugin communicates with a spam filter, a virus scanner or similar
29 * software using a UNIX socket and a very simple protocol:
30 *
31 * e-mail type (e.g. ham, spam, virus, ...) and size
32 * e:<type>:<bytes>
33 *
34 * spam score
35 * s:<value>
36 *
37 * successful spam checks
38 * c:<type1>[,<type2>,...]
39 */
41 #include "collectd.h"
42 #include "common.h"
43 #include "plugin.h"
45 #include "configfile.h"
47 #include <stddef.h>
49 #if HAVE_LIBPTHREAD
50 # include <pthread.h>
51 #endif
53 #include <sys/socket.h>
54 #include <sys/un.h>
55 #include <sys/select.h>
57 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
58 #ifndef UNIX_PATH_MAX
59 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
60 #endif /* UNIX_PATH_MAX */
62 #if HAVE_GRP_H
63 # include <grp.h>
64 #endif /* HAVE_GRP_H */
66 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
67 #define MAX_CONNS 5
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__)
74 /*
75 * Private data structures
76 */
77 /* linked list of email and check types */
78 typedef struct type {
79 char *name;
80 int value;
81 struct type *next;
82 } type_t;
84 typedef struct {
85 type_t *head;
86 type_t *tail;
87 } type_list_t;
89 /* collector thread control information */
90 typedef struct collector {
91 pthread_t thread;
93 /* socket descriptor of the current/last connection */
94 FILE *socket;
95 } collector_t;
97 /* linked list of pending connections */
98 typedef struct conn {
99 /* socket to read data from */
100 FILE *socket;
102 /* linked list of connections */
103 struct conn *next;
104 } conn_t;
106 typedef struct {
107 conn_t *head;
108 conn_t *tail;
109 } conn_list_t;
111 /*
112 * Private variables
113 */
114 /* valid configuration file keys */
115 static const char *config_keys[] =
116 {
117 "SocketFile",
118 "SocketGroup",
119 "SocketPerms",
120 "MaxConns"
121 };
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;
162 static double score;
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;
169 /*
170 * Private functions
171 */
172 static int email_config (const char *key, const char *value)
173 {
174 if (0 == strcasecmp (key, "SocketFile")) {
175 if (NULL != sock_file)
176 free (sock_file);
177 sock_file = sstrdup (value);
178 }
179 else if (0 == strcasecmp (key, "SocketGroup")) {
180 if (NULL != sock_group)
181 free (sock_group);
182 sock_group = sstrdup (value);
183 }
184 else if (0 == strcasecmp (key, "SocketPerms")) {
185 /* the user is responsible for providing reasonable values */
186 sock_perms = (int)strtol (value, NULL, 8);
187 }
188 else if (0 == strcasecmp (key, "MaxConns")) {
189 long int tmp = strtol (value, NULL, 0);
191 if (tmp < 1) {
192 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
193 "value %li, will use default %i.\n",
194 tmp, MAX_CONNS);
195 ERROR ("email plugin: `MaxConns' was set to invalid "
196 "value %li, will use default %i.\n",
197 tmp, MAX_CONNS);
198 max_conns = MAX_CONNS;
199 }
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;
208 }
209 else {
210 max_conns = (int)tmp;
211 }
212 }
213 else {
214 return -1;
215 }
216 return 0;
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)
221 {
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;
230 }
231 else {
232 type_t *ptr;
234 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
235 if (0 == strcmp (name, ptr->name))
236 break;
237 }
239 if (NULL == ptr) {
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;
246 }
247 else {
248 ptr->value += incr;
249 }
250 }
251 return;
252 } /* static void type_list_incr (type_list_t *, char *) */
254 static void *collect (void *arg)
255 {
256 collector_t *this = (collector_t *)arg;
258 while (1) {
259 conn_t *connection;
261 pthread_mutex_lock (&conns_mutex);
263 while (NULL == conns.head) {
264 pthread_cond_wait (&conn_available, &conns_mutex);
265 }
267 connection = conns.head;
268 conns.head = conns.head->next;
270 if (NULL == conns.head) {
271 conns.tail = NULL;
272 }
274 pthread_mutex_unlock (&conns_mutex);
276 /* make the socket available to the global
277 * thread and connection management */
278 this->socket = connection->socket;
280 log_debug ("collect: handling connection on fd #%i",
281 fileno (this->socket));
283 while (42) {
284 /* 256 bytes ought to be enough for anybody ;-) */
285 char line[256 + 1]; /* line + '\0' */
286 int len = 0;
288 errno = 0;
289 if (NULL == fgets (line, sizeof (line), this->socket)) {
290 if (0 != errno) {
291 char errbuf[1024];
292 log_err ("collect: reading from socket (fd #%i) "
293 "failed: %s", fileno (this->socket),
294 sstrerror (errno, errbuf, sizeof (errbuf)));
295 }
296 break;
297 }
299 len = strlen (line);
300 if (('\n' != line[len - 1]) && ('\r' != line[len - 1])) {
301 log_warn ("collect: line too long (> %zu characters): "
302 "'%s' (truncated)", sizeof (line) - 1, line);
304 while (NULL != fgets (line, sizeof (line), this->socket))
305 if (('\n' == line[len - 1]) || ('\r' == line[len - 1]))
306 break;
307 continue;
308 }
309 if (len < 3) { /* [a-z] ':' '\n' */
310 continue;
311 }
313 line[len - 1] = 0;
315 log_debug ("collect: line = '%s'", line);
317 if (':' != line[1]) {
318 log_err ("collect: syntax error in line '%s'", line);
319 continue;
320 }
322 if ('e' == line[0]) { /* e:<type>:<bytes> */
323 char *ptr = NULL;
324 char *type = strtok_r (line + 2, ":", &ptr);
325 char *tmp = strtok_r (NULL, ":", &ptr);
326 int bytes = 0;
328 if (NULL == tmp) {
329 log_err ("collect: syntax error in line '%s'", line);
330 continue;
331 }
333 bytes = atoi (tmp);
335 pthread_mutex_lock (&count_mutex);
336 type_list_incr (&list_count, type, /* increment = */ 1);
337 pthread_mutex_unlock (&count_mutex);
339 if (bytes > 0) {
340 pthread_mutex_lock (&size_mutex);
341 type_list_incr (&list_size, type, /* increment = */ bytes);
342 pthread_mutex_unlock (&size_mutex);
343 }
344 }
345 else if ('s' == line[0]) { /* s:<value> */
346 pthread_mutex_lock (&score_mutex);
347 score = (score * (double)score_count + atof (line + 2))
348 / (double)(score_count + 1);
349 ++score_count;
350 pthread_mutex_unlock (&score_mutex);
351 }
352 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
353 char *dummy = line + 2;
354 char *endptr = NULL;
355 char *type;
357 pthread_mutex_lock (&check_mutex);
358 while ((type = strtok_r (dummy, ",", &endptr)) != NULL)
359 {
360 dummy = NULL;
361 type_list_incr (&list_check, type, /* increment = */ 1);
362 }
363 pthread_mutex_unlock (&check_mutex);
364 }
365 else {
366 log_err ("collect: unknown type '%c'", line[0]);
367 }
368 } /* while (42) */
370 log_debug ("Shutting down connection on fd #%i",
371 fileno (this->socket));
373 fclose (connection->socket);
374 free (connection);
376 this->socket = NULL;
378 pthread_mutex_lock (&available_mutex);
379 ++available_collectors;
380 pthread_mutex_unlock (&available_mutex);
382 pthread_cond_signal (&collector_available);
383 } /* while (1) */
385 pthread_exit ((void *)0);
386 return ((void *) 0);
387 } /* static void *collect (void *) */
389 static void *open_connection (void __attribute__((unused)) *arg)
390 {
391 struct sockaddr_un addr;
393 char *path = (NULL == sock_file) ? SOCK_PATH : sock_file;
394 char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
396 /* create UNIX socket */
397 errno = 0;
398 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
399 char errbuf[1024];
400 disabled = 1;
401 log_err ("socket() failed: %s",
402 sstrerror (errno, errbuf, sizeof (errbuf)));
403 pthread_exit ((void *)1);
404 }
406 addr.sun_family = AF_UNIX;
407 sstrncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
409 errno = 0;
410 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
411 offsetof (struct sockaddr_un, sun_path)
412 + strlen(addr.sun_path))) {
413 char errbuf[1024];
414 disabled = 1;
415 close (connector_socket);
416 connector_socket = -1;
417 log_err ("bind() failed: %s",
418 sstrerror (errno, errbuf, sizeof (errbuf)));
419 pthread_exit ((void *)1);
420 }
422 errno = 0;
423 if (-1 == listen (connector_socket, 5)) {
424 char errbuf[1024];
425 disabled = 1;
426 close (connector_socket);
427 connector_socket = -1;
428 log_err ("listen() failed: %s",
429 sstrerror (errno, errbuf, sizeof (errbuf)));
430 pthread_exit ((void *)1);
431 }
433 {
434 struct group sg;
435 struct group *grp;
436 char grbuf[2048];
437 int status;
439 grp = NULL;
440 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
441 if (status != 0)
442 {
443 char errbuf[1024];
444 log_warn ("getgrnam_r (%s) failed: %s", group,
445 sstrerror (errno, errbuf, sizeof (errbuf)));
446 }
447 else if (grp == NULL)
448 {
449 log_warn ("No such group: `%s'", group);
450 }
451 else
452 {
453 status = chown (path, (uid_t) -1, grp->gr_gid);
454 if (status != 0)
455 {
456 char errbuf[1024];
457 log_warn ("chown (%s, -1, %i) failed: %s",
458 path, (int) grp->gr_gid,
459 sstrerror (errno, errbuf, sizeof (errbuf)));
460 }
461 }
462 }
464 errno = 0;
465 if (0 != chmod (path, sock_perms)) {
466 char errbuf[1024];
467 log_warn ("chmod() failed: %s",
468 sstrerror (errno, errbuf, sizeof (errbuf)));
469 }
471 { /* initialize collector threads */
472 int i = 0;
473 int err = 0;
475 pthread_attr_t ptattr;
477 conns.head = NULL;
478 conns.tail = NULL;
480 pthread_attr_init (&ptattr);
481 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
483 available_collectors = max_conns;
485 collectors =
486 (collector_t **)smalloc (max_conns * sizeof (collector_t *));
488 for (i = 0; i < max_conns; ++i) {
489 collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
490 collectors[i]->socket = NULL;
492 if (0 != (err = plugin_thread_create (&collectors[i]->thread,
493 &ptattr, collect, collectors[i]))) {
494 char errbuf[1024];
495 log_err ("pthread_create() failed: %s",
496 sstrerror (errno, errbuf, sizeof (errbuf)));
497 collectors[i]->thread = (pthread_t) 0;
498 }
499 }
501 pthread_attr_destroy (&ptattr);
502 }
504 while (1) {
505 int remote = 0;
507 conn_t *connection;
509 pthread_mutex_lock (&available_mutex);
511 while (0 == available_collectors) {
512 pthread_cond_wait (&collector_available, &available_mutex);
513 }
515 --available_collectors;
517 pthread_mutex_unlock (&available_mutex);
519 while (42) {
520 errno = 0;
522 remote = accept (connector_socket, NULL, NULL);
523 if (remote == -1) {
524 char errbuf[1024];
526 if (errno == EINTR)
527 continue;
529 disabled = 1;
530 close (connector_socket);
531 connector_socket = -1;
532 log_err ("accept() failed: %s",
533 sstrerror (errno, errbuf, sizeof (errbuf)));
534 pthread_exit ((void *)1);
535 }
537 /* access() succeeded. */
538 break;
539 }
541 connection = malloc (sizeof (*connection));
542 if (connection != NULL)
543 {
544 close (remote);
545 continue;
546 }
547 memset (connection, 0, sizeof (*connection));
549 connection->socket = fdopen (remote, "r");
550 connection->next = NULL;
552 if (NULL == connection->socket) {
553 close (remote);
554 sfree (connection);
555 continue;
556 }
558 pthread_mutex_lock (&conns_mutex);
560 if (NULL == conns.head) {
561 conns.head = connection;
562 conns.tail = connection;
563 }
564 else {
565 conns.tail->next = connection;
566 conns.tail = conns.tail->next;
567 }
569 pthread_mutex_unlock (&conns_mutex);
571 pthread_cond_signal (&conn_available);
572 }
574 pthread_exit ((void *) 0);
575 return ((void *) 0);
576 } /* static void *open_connection (void *) */
578 static int email_init (void)
579 {
580 int err = 0;
582 if (0 != (err = plugin_thread_create (&connector, NULL,
583 open_connection, NULL))) {
584 char errbuf[1024];
585 disabled = 1;
586 log_err ("pthread_create() failed: %s",
587 sstrerror (errno, errbuf, sizeof (errbuf)));
588 return (-1);
589 }
591 return (0);
592 } /* int email_init */
594 static void type_list_free (type_list_t *t)
595 {
596 type_t *this;
598 this = t->head;
599 while (this != NULL)
600 {
601 type_t *next = this->next;
603 sfree (this->name);
604 sfree (this);
606 this = next;
607 }
609 t->head = NULL;
610 t->tail = NULL;
611 }
613 static int email_shutdown (void)
614 {
615 int i = 0;
617 if (connector != ((pthread_t) 0)) {
618 pthread_kill (connector, SIGTERM);
619 connector = (pthread_t) 0;
620 }
622 if (connector_socket >= 0) {
623 close (connector_socket);
624 connector_socket = -1;
625 }
627 /* don't allow any more connections to be processed */
628 pthread_mutex_lock (&conns_mutex);
630 available_collectors = 0;
632 if (collectors != NULL) {
633 for (i = 0; i < max_conns; ++i) {
634 if (collectors[i] == NULL)
635 continue;
637 if (collectors[i]->thread != ((pthread_t) 0)) {
638 pthread_kill (collectors[i]->thread, SIGTERM);
639 collectors[i]->thread = (pthread_t) 0;
640 }
642 if (collectors[i]->socket != NULL) {
643 fclose (collectors[i]->socket);
644 collectors[i]->socket = NULL;
645 }
647 sfree (collectors[i]);
648 }
649 sfree (collectors);
650 } /* if (collectors != NULL) */
652 pthread_mutex_unlock (&conns_mutex);
654 type_list_free (&list_count);
655 type_list_free (&list_count_copy);
656 type_list_free (&list_size);
657 type_list_free (&list_size_copy);
658 type_list_free (&list_check);
659 type_list_free (&list_check_copy);
661 unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
663 sfree (sock_file);
664 sfree (sock_group);
665 return (0);
666 } /* static void email_shutdown (void) */
668 static void email_submit (const char *type, const char *type_instance, gauge_t value)
669 {
670 value_t values[1];
671 value_list_t vl = VALUE_LIST_INIT;
673 values[0].gauge = value;
675 vl.values = values;
676 vl.values_len = 1;
677 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
678 sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
679 sstrncpy (vl.type, type, sizeof (vl.type));
680 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
682 plugin_dispatch_values (&vl);
683 } /* void email_submit */
685 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
686 * that neither the order nor the name of any element of either list is
687 * changed and no elements are deleted. The values of l1 are reset to zero
688 * after they have been copied to l2. */
689 static void copy_type_list (type_list_t *l1, type_list_t *l2)
690 {
691 type_t *ptr1;
692 type_t *ptr2;
694 type_t *last = NULL;
696 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
697 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
698 if (NULL == ptr2) {
699 ptr2 = (type_t *)smalloc (sizeof (type_t));
700 ptr2->name = NULL;
701 ptr2->next = NULL;
703 if (NULL == last) {
704 l2->head = ptr2;
705 }
706 else {
707 last->next = ptr2;
708 }
710 l2->tail = ptr2;
711 }
713 if (NULL == ptr2->name) {
714 ptr2->name = sstrdup (ptr1->name);
715 }
717 ptr2->value = ptr1->value;
718 ptr1->value = 0;
719 }
720 return;
721 }
723 static int email_read (void)
724 {
725 type_t *ptr;
727 double score_old;
728 int score_count_old;
730 if (disabled)
731 return (-1);
733 /* email count */
734 pthread_mutex_lock (&count_mutex);
736 copy_type_list (&list_count, &list_count_copy);
738 pthread_mutex_unlock (&count_mutex);
740 for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
741 email_submit ("email_count", ptr->name, ptr->value);
742 }
744 /* email size */
745 pthread_mutex_lock (&size_mutex);
747 copy_type_list (&list_size, &list_size_copy);
749 pthread_mutex_unlock (&size_mutex);
751 for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
752 email_submit ("email_size", ptr->name, ptr->value);
753 }
755 /* spam score */
756 pthread_mutex_lock (&score_mutex);
758 score_old = score;
759 score_count_old = score_count;
760 score = 0.0;
761 score_count = 0;
763 pthread_mutex_unlock (&score_mutex);
765 if (score_count_old > 0)
766 email_submit ("spam_score", "", score_old);
768 /* spam checks */
769 pthread_mutex_lock (&check_mutex);
771 copy_type_list (&list_check, &list_check_copy);
773 pthread_mutex_unlock (&check_mutex);
775 for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
776 email_submit ("spam_check", ptr->name, ptr->value);
778 return (0);
779 } /* int email_read */
781 void module_register (void)
782 {
783 plugin_register_config ("email", email_config, config_keys, config_keys_num);
784 plugin_register_init ("email", email_init);
785 plugin_register_read ("email", email_read);
786 plugin_register_shutdown ("email", email_shutdown);
787 } /* void module_register */
789 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */