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"
43 #include "common.h"
44 #include "plugin.h"
46 #include "configfile.h"
48 #include <stddef.h>
50 #include <sys/un.h>
51 #include <sys/select.h>
53 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
54 #ifndef UNIX_PATH_MAX
55 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
56 #endif /* UNIX_PATH_MAX */
58 #if HAVE_GRP_H
59 # include <grp.h>
60 #endif /* HAVE_GRP_H */
62 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
63 #define MAX_CONNS 5
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__)
70 /*
71 * Private data structures
72 */
73 /* linked list of email and check types */
74 typedef struct type {
75 char *name;
76 int value;
77 struct type *next;
78 } type_t;
80 typedef struct {
81 type_t *head;
82 type_t *tail;
83 } type_list_t;
85 /* collector thread control information */
86 typedef struct collector {
87 pthread_t thread;
89 /* socket descriptor of the current/last connection */
90 FILE *socket;
91 } collector_t;
93 /* linked list of pending connections */
94 typedef struct conn {
95 /* socket to read data from */
96 FILE *socket;
98 /* linked list of connections */
99 struct conn *next;
100 } conn_t;
102 typedef struct {
103 conn_t *head;
104 conn_t *tail;
105 } conn_list_t;
107 /*
108 * Private variables
109 */
110 /* valid configuration file keys */
111 static const char *config_keys[] =
112 {
113 "SocketFile",
114 "SocketGroup",
115 "SocketPerms",
116 "MaxConns"
117 };
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;
158 static double score;
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;
165 /*
166 * Private functions
167 */
168 static int email_config (const char *key, const char *value)
169 {
170 if (0 == strcasecmp (key, "SocketFile")) {
171 if (NULL != sock_file)
172 free (sock_file);
173 sock_file = sstrdup (value);
174 }
175 else if (0 == strcasecmp (key, "SocketGroup")) {
176 if (NULL != sock_group)
177 free (sock_group);
178 sock_group = sstrdup (value);
179 }
180 else if (0 == strcasecmp (key, "SocketPerms")) {
181 /* the user is responsible for providing reasonable values */
182 sock_perms = (int)strtol (value, NULL, 8);
183 }
184 else if (0 == strcasecmp (key, "MaxConns")) {
185 long int tmp = strtol (value, NULL, 0);
187 if (tmp < 1) {
188 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
189 "value %li, will use default %i.\n",
190 tmp, MAX_CONNS);
191 ERROR ("email plugin: `MaxConns' was set to invalid "
192 "value %li, will use default %i.\n",
193 tmp, MAX_CONNS);
194 max_conns = MAX_CONNS;
195 }
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;
204 }
205 else {
206 max_conns = (int)tmp;
207 }
208 }
209 else {
210 return -1;
211 }
212 return 0;
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)
217 {
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;
226 }
227 else {
228 type_t *ptr;
230 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
231 if (0 == strcmp (name, ptr->name))
232 break;
233 }
235 if (NULL == ptr) {
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;
242 }
243 else {
244 ptr->value += incr;
245 }
246 }
247 return;
248 } /* static void type_list_incr (type_list_t *, char *) */
250 static void *collect (void *arg)
251 {
252 collector_t *this = (collector_t *)arg;
254 while (1) {
255 conn_t *connection;
257 pthread_mutex_lock (&conns_mutex);
259 while (NULL == conns.head) {
260 pthread_cond_wait (&conn_available, &conns_mutex);
261 }
263 connection = conns.head;
264 conns.head = conns.head->next;
266 if (NULL == conns.head) {
267 conns.tail = NULL;
268 }
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));
279 while (42) {
280 /* 256 bytes ought to be enough for anybody ;-) */
281 char line[256 + 1]; /* line + '\0' */
282 int len = 0;
284 errno = 0;
285 if (NULL == fgets (line, sizeof (line), this->socket)) {
286 if (0 != errno) {
287 char errbuf[1024];
288 log_err ("collect: reading from socket (fd #%i) "
289 "failed: %s", fileno (this->socket),
290 sstrerror (errno, errbuf, sizeof (errbuf)));
291 }
292 break;
293 }
295 len = strlen (line);
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]))
302 break;
303 continue;
304 }
305 if (len < 3) { /* [a-z] ':' '\n' */
306 continue;
307 }
309 line[len - 1] = 0;
311 log_debug ("collect: line = '%s'", line);
313 if (':' != line[1]) {
314 log_err ("collect: syntax error in line '%s'", line);
315 continue;
316 }
318 if ('e' == line[0]) { /* e:<type>:<bytes> */
319 char *ptr = NULL;
320 char *type = strtok_r (line + 2, ":", &ptr);
321 char *tmp = strtok_r (NULL, ":", &ptr);
322 int bytes = 0;
324 if (NULL == tmp) {
325 log_err ("collect: syntax error in line '%s'", line);
326 continue;
327 }
329 bytes = atoi (tmp);
331 pthread_mutex_lock (&count_mutex);
332 type_list_incr (&list_count, type, /* increment = */ 1);
333 pthread_mutex_unlock (&count_mutex);
335 if (bytes > 0) {
336 pthread_mutex_lock (&size_mutex);
337 type_list_incr (&list_size, type, /* increment = */ bytes);
338 pthread_mutex_unlock (&size_mutex);
339 }
340 }
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);
345 ++score_count;
346 pthread_mutex_unlock (&score_mutex);
347 }
348 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
349 char *dummy = line + 2;
350 char *endptr = NULL;
351 char *type;
353 pthread_mutex_lock (&check_mutex);
354 while ((type = strtok_r (dummy, ",", &endptr)) != NULL)
355 {
356 dummy = NULL;
357 type_list_incr (&list_check, type, /* increment = */ 1);
358 }
359 pthread_mutex_unlock (&check_mutex);
360 }
361 else {
362 log_err ("collect: unknown type '%c'", line[0]);
363 }
364 } /* while (42) */
366 log_debug ("Shutting down connection on fd #%i",
367 fileno (this->socket));
369 fclose (connection->socket);
370 free (connection);
372 this->socket = NULL;
374 pthread_mutex_lock (&available_mutex);
375 ++available_collectors;
376 pthread_mutex_unlock (&available_mutex);
378 pthread_cond_signal (&collector_available);
379 } /* while (1) */
381 pthread_exit ((void *)0);
382 return ((void *) 0);
383 } /* static void *collect (void *) */
385 static void *open_connection (void __attribute__((unused)) *arg)
386 {
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 */
393 errno = 0;
394 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
395 char errbuf[1024];
396 disabled = 1;
397 log_err ("socket() failed: %s",
398 sstrerror (errno, errbuf, sizeof (errbuf)));
399 pthread_exit ((void *)1);
400 }
402 addr.sun_family = AF_UNIX;
403 sstrncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
405 errno = 0;
406 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
407 offsetof (struct sockaddr_un, sun_path)
408 + strlen(addr.sun_path))) {
409 char errbuf[1024];
410 disabled = 1;
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);
416 }
418 errno = 0;
419 if (-1 == listen (connector_socket, 5)) {
420 char errbuf[1024];
421 disabled = 1;
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);
427 }
429 {
430 struct group sg;
431 struct group *grp;
432 char grbuf[2048];
433 int status;
435 grp = NULL;
436 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
437 if (status != 0)
438 {
439 char errbuf[1024];
440 log_warn ("getgrnam_r (%s) failed: %s", group,
441 sstrerror (errno, errbuf, sizeof (errbuf)));
442 }
443 else if (grp == NULL)
444 {
445 log_warn ("No such group: `%s'", group);
446 }
447 else
448 {
449 status = chown (path, (uid_t) -1, grp->gr_gid);
450 if (status != 0)
451 {
452 char errbuf[1024];
453 log_warn ("chown (%s, -1, %i) failed: %s",
454 path, (int) grp->gr_gid,
455 sstrerror (errno, errbuf, sizeof (errbuf)));
456 }
457 }
458 }
460 errno = 0;
461 if (0 != chmod (path, sock_perms)) {
462 char errbuf[1024];
463 log_warn ("chmod() failed: %s",
464 sstrerror (errno, errbuf, sizeof (errbuf)));
465 }
467 { /* initialize collector threads */
468 int i = 0;
470 pthread_attr_t ptattr;
472 conns.head = NULL;
473 conns.tail = NULL;
475 pthread_attr_init (&ptattr);
476 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
478 available_collectors = max_conns;
480 collectors =
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) {
489 char errbuf[1024];
490 log_err ("plugin_thread_create() failed: %s",
491 sstrerror (errno, errbuf, sizeof (errbuf)));
492 collectors[i]->thread = (pthread_t) 0;
493 }
494 }
496 pthread_attr_destroy (&ptattr);
497 }
499 while (1) {
500 int remote = 0;
502 conn_t *connection;
504 pthread_mutex_lock (&available_mutex);
506 while (0 == available_collectors) {
507 pthread_cond_wait (&collector_available, &available_mutex);
508 }
510 --available_collectors;
512 pthread_mutex_unlock (&available_mutex);
514 while (42) {
515 errno = 0;
517 remote = accept (connector_socket, NULL, NULL);
518 if (remote == -1) {
519 char errbuf[1024];
521 if (errno == EINTR)
522 continue;
524 disabled = 1;
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);
530 }
532 /* access() succeeded. */
533 break;
534 }
536 connection = calloc (1, sizeof (*connection));
537 if (connection == NULL)
538 {
539 close (remote);
540 continue;
541 }
543 connection->socket = fdopen (remote, "r");
544 connection->next = NULL;
546 if (NULL == connection->socket) {
547 close (remote);
548 sfree (connection);
549 continue;
550 }
552 pthread_mutex_lock (&conns_mutex);
554 if (NULL == conns.head) {
555 conns.head = connection;
556 conns.tail = connection;
557 }
558 else {
559 conns.tail->next = connection;
560 conns.tail = conns.tail->next;
561 }
563 pthread_mutex_unlock (&conns_mutex);
565 pthread_cond_signal (&conn_available);
566 }
568 pthread_exit ((void *) 0);
569 return ((void *) 0);
570 } /* static void *open_connection (void *) */
572 static int email_init (void)
573 {
574 if (plugin_thread_create (&connector, NULL,
575 open_connection, NULL) != 0) {
576 char errbuf[1024];
577 disabled = 1;
578 log_err ("plugin_thread_create() failed: %s",
579 sstrerror (errno, errbuf, sizeof (errbuf)));
580 return (-1);
581 }
583 return (0);
584 } /* int email_init */
586 static void type_list_free (type_list_t *t)
587 {
588 type_t *this;
590 this = t->head;
591 while (this != NULL)
592 {
593 type_t *next = this->next;
595 sfree (this->name);
596 sfree (this);
598 this = next;
599 }
601 t->head = NULL;
602 t->tail = NULL;
603 }
605 static int email_shutdown (void)
606 {
607 int i = 0;
609 if (connector != ((pthread_t) 0)) {
610 pthread_kill (connector, SIGTERM);
611 connector = (pthread_t) 0;
612 }
614 if (connector_socket >= 0) {
615 close (connector_socket);
616 connector_socket = -1;
617 }
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)
627 continue;
629 if (collectors[i]->thread != ((pthread_t) 0)) {
630 pthread_kill (collectors[i]->thread, SIGTERM);
631 collectors[i]->thread = (pthread_t) 0;
632 }
634 if (collectors[i]->socket != NULL) {
635 fclose (collectors[i]->socket);
636 collectors[i]->socket = NULL;
637 }
639 sfree (collectors[i]);
640 }
641 sfree (collectors);
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);
655 sfree (sock_file);
656 sfree (sock_group);
657 return (0);
658 } /* static void email_shutdown (void) */
660 static void email_submit (const char *type, const char *type_instance, gauge_t value)
661 {
662 value_t values[1];
663 value_list_t vl = VALUE_LIST_INIT;
665 values[0].gauge = value;
667 vl.values = values;
668 vl.values_len = 1;
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)
682 {
683 type_t *ptr1;
684 type_t *ptr2;
686 type_t *last = NULL;
688 for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
689 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
690 if (NULL == ptr2) {
691 ptr2 = smalloc (sizeof (*ptr2));
692 ptr2->name = NULL;
693 ptr2->next = NULL;
695 if (NULL == last) {
696 l2->head = ptr2;
697 }
698 else {
699 last->next = ptr2;
700 }
702 l2->tail = ptr2;
703 }
705 if (NULL == ptr2->name) {
706 ptr2->name = sstrdup (ptr1->name);
707 }
709 ptr2->value = ptr1->value;
710 ptr1->value = 0;
711 }
712 return;
713 }
715 static int email_read (void)
716 {
717 type_t *ptr;
719 double score_old;
720 int score_count_old;
722 if (disabled)
723 return (-1);
725 /* email count */
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);
734 }
736 /* email size */
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);
745 }
747 /* spam score */
748 pthread_mutex_lock (&score_mutex);
750 score_old = score;
751 score_count_old = score_count;
752 score = 0.0;
753 score_count = 0;
755 pthread_mutex_unlock (&score_mutex);
757 if (score_count_old > 0)
758 email_submit ("spam_score", "", score_old);
760 /* spam checks */
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);
770 return (0);
771 } /* int email_read */
773 void module_register (void)
774 {
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 : */