1027eb90ad1fed60e77219fa8b71dc399ab315e7
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 <stddef.h>
48 #include <sys/un.h>
49 #include <sys/select.h>
51 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
52 #ifndef UNIX_PATH_MAX
53 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
54 #endif /* UNIX_PATH_MAX */
56 #if HAVE_GRP_H
57 # include <grp.h>
58 #endif /* HAVE_GRP_H */
60 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
61 #define MAX_CONNS 5
62 #define MAX_CONNS_LIMIT 16384
64 #define log_debug(...) DEBUG ("email: "__VA_ARGS__)
65 #define log_err(...) ERROR ("email: "__VA_ARGS__)
66 #define log_warn(...) WARNING ("email: "__VA_ARGS__)
68 /*
69 * Private data structures
70 */
71 /* linked list of email and check types */
72 typedef struct type {
73 char *name;
74 int value;
75 struct type *next;
76 } type_t;
78 typedef struct {
79 type_t *head;
80 type_t *tail;
81 } type_list_t;
83 /* collector thread control information */
84 typedef struct collector {
85 pthread_t thread;
87 /* socket descriptor of the current/last connection */
88 FILE *socket;
89 } collector_t;
91 /* linked list of pending connections */
92 typedef struct conn {
93 /* socket to read data from */
94 FILE *socket;
96 /* linked list of connections */
97 struct conn *next;
98 } conn_t;
100 typedef struct {
101 conn_t *head;
102 conn_t *tail;
103 } conn_list_t;
105 /*
106 * Private variables
107 */
108 /* valid configuration file keys */
109 static const char *config_keys[] =
110 {
111 "SocketFile",
112 "SocketGroup",
113 "SocketPerms",
114 "MaxConns"
115 };
116 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
118 /* socket configuration */
119 static char *sock_file = NULL;
120 static char *sock_group = NULL;
121 static int sock_perms = S_IRWXU | S_IRWXG;
122 static int max_conns = MAX_CONNS;
124 /* state of the plugin */
125 static int disabled = 0;
127 /* thread managing "client" connections */
128 static pthread_t connector = (pthread_t) 0;
129 static int connector_socket = -1;
131 /* tell the collector threads that a new connection is available */
132 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
134 /* connections that are waiting to be processed */
135 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
136 static conn_list_t conns;
138 /* tell the connector thread that a collector is available */
139 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
141 /* collector threads */
142 static collector_t **collectors = NULL;
144 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
145 static int available_collectors;
147 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
148 static type_list_t list_count;
149 static type_list_t list_count_copy;
151 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
152 static type_list_t list_size;
153 static type_list_t list_size_copy;
155 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
156 static double score;
157 static int score_count;
159 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
160 static type_list_t list_check;
161 static type_list_t list_check_copy;
163 /*
164 * Private functions
165 */
166 static int email_config (const char *key, const char *value)
167 {
168 if (0 == strcasecmp (key, "SocketFile")) {
169 if (NULL != sock_file)
170 free (sock_file);
171 sock_file = sstrdup (value);
172 }
173 else if (0 == strcasecmp (key, "SocketGroup")) {
174 if (NULL != sock_group)
175 free (sock_group);
176 sock_group = sstrdup (value);
177 }
178 else if (0 == strcasecmp (key, "SocketPerms")) {
179 /* the user is responsible for providing reasonable values */
180 sock_perms = (int)strtol (value, NULL, 8);
181 }
182 else if (0 == strcasecmp (key, "MaxConns")) {
183 long int tmp = strtol (value, NULL, 0);
185 if (tmp < 1) {
186 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
187 "value %li, will use default %i.\n",
188 tmp, MAX_CONNS);
189 ERROR ("email plugin: `MaxConns' was set to invalid "
190 "value %li, will use default %i.\n",
191 tmp, MAX_CONNS);
192 max_conns = MAX_CONNS;
193 }
194 else if (tmp > MAX_CONNS_LIMIT) {
195 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
196 "value %li, will use hardcoded limit %i.\n",
197 tmp, MAX_CONNS_LIMIT);
198 ERROR ("email plugin: `MaxConns' was set to invalid "
199 "value %li, will use hardcoded limit %i.\n",
200 tmp, MAX_CONNS_LIMIT);
201 max_conns = MAX_CONNS_LIMIT;
202 }
203 else {
204 max_conns = (int)tmp;
205 }
206 }
207 else {
208 return -1;
209 }
210 return 0;
211 } /* static int email_config (char *, char *) */
213 /* Increment the value of the given name in the given list by incr. */
214 static void type_list_incr (type_list_t *list, char *name, int incr)
215 {
216 if (NULL == list->head) {
217 list->head = smalloc (sizeof (*list->head));
219 list->head->name = sstrdup (name);
220 list->head->value = incr;
221 list->head->next = NULL;
223 list->tail = list->head;
224 }
225 else {
226 type_t *ptr;
228 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
229 if (0 == strcmp (name, ptr->name))
230 break;
231 }
233 if (NULL == ptr) {
234 list->tail->next = smalloc (sizeof (*list->tail->next));
235 list->tail = list->tail->next;
237 list->tail->name = sstrdup (name);
238 list->tail->value = incr;
239 list->tail->next = NULL;
240 }
241 else {
242 ptr->value += incr;
243 }
244 }
245 return;
246 } /* static void type_list_incr (type_list_t *, char *) */
248 static void *collect (void *arg)
249 {
250 collector_t *this = (collector_t *)arg;
252 while (1) {
253 conn_t *connection;
255 pthread_mutex_lock (&conns_mutex);
257 while (NULL == conns.head) {
258 pthread_cond_wait (&conn_available, &conns_mutex);
259 }
261 connection = conns.head;
262 conns.head = conns.head->next;
264 if (NULL == conns.head) {
265 conns.tail = NULL;
266 }
268 pthread_mutex_unlock (&conns_mutex);
270 /* make the socket available to the global
271 * thread and connection management */
272 this->socket = connection->socket;
274 log_debug ("collect: handling connection on fd #%i",
275 fileno (this->socket));
277 while (42) {
278 /* 256 bytes ought to be enough for anybody ;-) */
279 char line[256 + 1]; /* line + '\0' */
280 int len = 0;
282 errno = 0;
283 if (NULL == fgets (line, sizeof (line), this->socket)) {
284 if (0 != errno) {
285 char errbuf[1024];
286 log_err ("collect: reading from socket (fd #%i) "
287 "failed: %s", fileno (this->socket),
288 sstrerror (errno, errbuf, sizeof (errbuf)));
289 }
290 break;
291 }
293 len = strlen (line);
294 if (('\n' != line[len - 1]) && ('\r' != line[len - 1])) {
295 log_warn ("collect: line too long (> %zu characters): "
296 "'%s' (truncated)", sizeof (line) - 1, line);
298 while (NULL != fgets (line, sizeof (line), this->socket))
299 if (('\n' == line[len - 1]) || ('\r' == line[len - 1]))
300 break;
301 continue;
302 }
303 if (len < 3) { /* [a-z] ':' '\n' */
304 continue;
305 }
307 line[len - 1] = 0;
309 log_debug ("collect: line = '%s'", line);
311 if (':' != line[1]) {
312 log_err ("collect: syntax error in line '%s'", line);
313 continue;
314 }
316 if ('e' == line[0]) { /* e:<type>:<bytes> */
317 char *ptr = NULL;
318 char *type = strtok_r (line + 2, ":", &ptr);
319 char *tmp = strtok_r (NULL, ":", &ptr);
320 int bytes = 0;
322 if (NULL == tmp) {
323 log_err ("collect: syntax error in line '%s'", line);
324 continue;
325 }
327 bytes = atoi (tmp);
329 pthread_mutex_lock (&count_mutex);
330 type_list_incr (&list_count, type, /* increment = */ 1);
331 pthread_mutex_unlock (&count_mutex);
333 if (bytes > 0) {
334 pthread_mutex_lock (&size_mutex);
335 type_list_incr (&list_size, type, /* increment = */ bytes);
336 pthread_mutex_unlock (&size_mutex);
337 }
338 }
339 else if ('s' == line[0]) { /* s:<value> */
340 pthread_mutex_lock (&score_mutex);
341 score = (score * (double)score_count + atof (line + 2))
342 / (double)(score_count + 1);
343 ++score_count;
344 pthread_mutex_unlock (&score_mutex);
345 }
346 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
347 char *dummy = line + 2;
348 char *endptr = NULL;
349 char *type;
351 pthread_mutex_lock (&check_mutex);
352 while ((type = strtok_r (dummy, ",", &endptr)) != NULL)
353 {
354 dummy = NULL;
355 type_list_incr (&list_check, type, /* increment = */ 1);
356 }
357 pthread_mutex_unlock (&check_mutex);
358 }
359 else {
360 log_err ("collect: unknown type '%c'", line[0]);
361 }
362 } /* while (42) */
364 log_debug ("Shutting down connection on fd #%i",
365 fileno (this->socket));
367 fclose (connection->socket);
368 free (connection);
370 this->socket = NULL;
372 pthread_mutex_lock (&available_mutex);
373 ++available_collectors;
374 pthread_mutex_unlock (&available_mutex);
376 pthread_cond_signal (&collector_available);
377 } /* while (1) */
379 pthread_exit ((void *)0);
380 return ((void *) 0);
381 } /* static void *collect (void *) */
383 static void *open_connection (void __attribute__((unused)) *arg)
384 {
385 struct sockaddr_un addr;
387 const char *path = (NULL == sock_file) ? SOCK_PATH : sock_file;
388 const char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
390 /* create UNIX socket */
391 errno = 0;
392 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
393 char errbuf[1024];
394 disabled = 1;
395 log_err ("socket() failed: %s",
396 sstrerror (errno, errbuf, sizeof (errbuf)));
397 pthread_exit ((void *)1);
398 }
400 addr.sun_family = AF_UNIX;
401 sstrncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
403 errno = 0;
404 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
405 offsetof (struct sockaddr_un, sun_path)
406 + strlen(addr.sun_path))) {
407 char errbuf[1024];
408 disabled = 1;
409 close (connector_socket);
410 connector_socket = -1;
411 log_err ("bind() failed: %s",
412 sstrerror (errno, errbuf, sizeof (errbuf)));
413 pthread_exit ((void *)1);
414 }
416 errno = 0;
417 if (-1 == listen (connector_socket, 5)) {
418 char errbuf[1024];
419 disabled = 1;
420 close (connector_socket);
421 connector_socket = -1;
422 log_err ("listen() failed: %s",
423 sstrerror (errno, errbuf, sizeof (errbuf)));
424 pthread_exit ((void *)1);
425 }
427 {
428 struct group sg;
429 struct group *grp;
430 char grbuf[2048];
431 int status;
433 grp = NULL;
434 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
435 if (status != 0)
436 {
437 char errbuf[1024];
438 log_warn ("getgrnam_r (%s) failed: %s", group,
439 sstrerror (errno, errbuf, sizeof (errbuf)));
440 }
441 else if (grp == NULL)
442 {
443 log_warn ("No such group: `%s'", group);
444 }
445 else
446 {
447 status = chown (path, (uid_t) -1, grp->gr_gid);
448 if (status != 0)
449 {
450 char errbuf[1024];
451 log_warn ("chown (%s, -1, %i) failed: %s",
452 path, (int) grp->gr_gid,
453 sstrerror (errno, errbuf, sizeof (errbuf)));
454 }
455 }
456 }
458 errno = 0;
459 if (0 != chmod (path, sock_perms)) {
460 char errbuf[1024];
461 log_warn ("chmod() failed: %s",
462 sstrerror (errno, errbuf, sizeof (errbuf)));
463 }
465 { /* initialize collector threads */
466 pthread_attr_t ptattr;
468 conns.head = NULL;
469 conns.tail = NULL;
471 pthread_attr_init (&ptattr);
472 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
474 available_collectors = max_conns;
476 collectors =
477 smalloc (max_conns * sizeof (*collectors));
479 for (int i = 0; i < max_conns; ++i) {
480 collectors[i] = smalloc (sizeof (*collectors[i]));
481 collectors[i]->socket = NULL;
483 if (plugin_thread_create (&collectors[i]->thread,
484 &ptattr, collect, collectors[i]) != 0) {
485 char errbuf[1024];
486 log_err ("plugin_thread_create() failed: %s",
487 sstrerror (errno, errbuf, sizeof (errbuf)));
488 collectors[i]->thread = (pthread_t) 0;
489 }
490 }
492 pthread_attr_destroy (&ptattr);
493 }
495 while (1) {
496 int remote = 0;
498 conn_t *connection;
500 pthread_mutex_lock (&available_mutex);
502 while (0 == available_collectors) {
503 pthread_cond_wait (&collector_available, &available_mutex);
504 }
506 --available_collectors;
508 pthread_mutex_unlock (&available_mutex);
510 while (42) {
511 errno = 0;
513 remote = accept (connector_socket, NULL, NULL);
514 if (remote == -1) {
515 char errbuf[1024];
517 if (errno == EINTR)
518 continue;
520 disabled = 1;
521 close (connector_socket);
522 connector_socket = -1;
523 log_err ("accept() failed: %s",
524 sstrerror (errno, errbuf, sizeof (errbuf)));
525 pthread_exit ((void *)1);
526 }
528 /* access() succeeded. */
529 break;
530 }
532 connection = calloc (1, sizeof (*connection));
533 if (connection == NULL)
534 {
535 close (remote);
536 continue;
537 }
539 connection->socket = fdopen (remote, "r");
540 connection->next = NULL;
542 if (NULL == connection->socket) {
543 close (remote);
544 sfree (connection);
545 continue;
546 }
548 pthread_mutex_lock (&conns_mutex);
550 if (NULL == conns.head) {
551 conns.head = connection;
552 conns.tail = connection;
553 }
554 else {
555 conns.tail->next = connection;
556 conns.tail = conns.tail->next;
557 }
559 pthread_mutex_unlock (&conns_mutex);
561 pthread_cond_signal (&conn_available);
562 }
564 pthread_exit ((void *) 0);
565 return ((void *) 0);
566 } /* static void *open_connection (void *) */
568 static int email_init (void)
569 {
570 if (plugin_thread_create (&connector, NULL,
571 open_connection, NULL) != 0) {
572 char errbuf[1024];
573 disabled = 1;
574 log_err ("plugin_thread_create() failed: %s",
575 sstrerror (errno, errbuf, sizeof (errbuf)));
576 return (-1);
577 }
579 return (0);
580 } /* int email_init */
582 static void type_list_free (type_list_t *t)
583 {
584 type_t *this;
586 this = t->head;
587 while (this != NULL)
588 {
589 type_t *next = this->next;
591 sfree (this->name);
592 sfree (this);
594 this = next;
595 }
597 t->head = NULL;
598 t->tail = NULL;
599 }
601 static int email_shutdown (void)
602 {
603 if (connector != ((pthread_t) 0)) {
604 pthread_kill (connector, SIGTERM);
605 connector = (pthread_t) 0;
606 }
608 if (connector_socket >= 0) {
609 close (connector_socket);
610 connector_socket = -1;
611 }
613 /* don't allow any more connections to be processed */
614 pthread_mutex_lock (&conns_mutex);
616 available_collectors = 0;
618 if (collectors != NULL) {
619 for (int i = 0; i < max_conns; ++i) {
620 if (collectors[i] == NULL)
621 continue;
623 if (collectors[i]->thread != ((pthread_t) 0)) {
624 pthread_kill (collectors[i]->thread, SIGTERM);
625 collectors[i]->thread = (pthread_t) 0;
626 }
628 if (collectors[i]->socket != NULL) {
629 fclose (collectors[i]->socket);
630 collectors[i]->socket = NULL;
631 }
633 sfree (collectors[i]);
634 }
635 sfree (collectors);
636 } /* if (collectors != NULL) */
638 pthread_mutex_unlock (&conns_mutex);
640 type_list_free (&list_count);
641 type_list_free (&list_count_copy);
642 type_list_free (&list_size);
643 type_list_free (&list_size_copy);
644 type_list_free (&list_check);
645 type_list_free (&list_check_copy);
647 unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
649 sfree (sock_file);
650 sfree (sock_group);
651 return (0);
652 } /* static void email_shutdown (void) */
654 static void email_submit (const char *type, const char *type_instance, gauge_t value)
655 {
656 value_list_t vl = VALUE_LIST_INIT;
658 vl.values = &(value_t) { .gauge = value };
659 vl.values_len = 1;
660 sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
661 sstrncpy (vl.type, type, sizeof (vl.type));
662 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
664 plugin_dispatch_values (&vl);
665 } /* void email_submit */
667 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
668 * that neither the order nor the name of any element of either list is
669 * changed and no elements are deleted. The values of l1 are reset to zero
670 * after they have been copied to l2. */
671 static void copy_type_list (type_list_t *l1, type_list_t *l2)
672 {
673 type_t *last = NULL;
675 for (type_t *ptr1 = l1->head, *ptr2 = l2->head; NULL != ptr1;
676 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
677 if (NULL == ptr2) {
678 ptr2 = smalloc (sizeof (*ptr2));
679 ptr2->name = NULL;
680 ptr2->next = NULL;
682 if (NULL == last) {
683 l2->head = ptr2;
684 }
685 else {
686 last->next = ptr2;
687 }
689 l2->tail = ptr2;
690 }
692 if (NULL == ptr2->name) {
693 ptr2->name = sstrdup (ptr1->name);
694 }
696 ptr2->value = ptr1->value;
697 ptr1->value = 0;
698 }
699 return;
700 }
702 static int email_read (void)
703 {
704 double score_old;
705 int score_count_old;
707 if (disabled)
708 return (-1);
710 /* email count */
711 pthread_mutex_lock (&count_mutex);
713 copy_type_list (&list_count, &list_count_copy);
715 pthread_mutex_unlock (&count_mutex);
717 for (type_t *ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
718 email_submit ("email_count", ptr->name, ptr->value);
719 }
721 /* email size */
722 pthread_mutex_lock (&size_mutex);
724 copy_type_list (&list_size, &list_size_copy);
726 pthread_mutex_unlock (&size_mutex);
728 for (type_t *ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
729 email_submit ("email_size", ptr->name, ptr->value);
730 }
732 /* spam score */
733 pthread_mutex_lock (&score_mutex);
735 score_old = score;
736 score_count_old = score_count;
737 score = 0.0;
738 score_count = 0;
740 pthread_mutex_unlock (&score_mutex);
742 if (score_count_old > 0)
743 email_submit ("spam_score", "", score_old);
745 /* spam checks */
746 pthread_mutex_lock (&check_mutex);
748 copy_type_list (&list_check, &list_check_copy);
750 pthread_mutex_unlock (&check_mutex);
752 for (type_t *ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
753 email_submit ("spam_check", ptr->name, ptr->value);
755 return (0);
756 } /* int email_read */
758 void module_register (void)
759 {
760 plugin_register_config ("email", email_config, config_keys, config_keys_num);
761 plugin_register_init ("email", email_init);
762 plugin_register_read ("email", email_read);
763 plugin_register_shutdown ("email", email_shutdown);
764 } /* void module_register */
766 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */