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>,...]
49 #include <sys/select.h>
51 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
53 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
54 #endif /* UNIX_PATH_MAX */
58 #endif /* HAVE_GRP_H */
60 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
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__)
69 * Private data structures
71 /* linked list of email and check types */
83 /* collector thread control information */
84 typedef struct collector {
87 /* socket descriptor of the current/last connection */
91 /* linked list of pending connections */
93 /* socket to read data from */
96 /* linked list of connections */
108 /* valid configuration file keys */
109 static const char *config_keys[] =
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;
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;
166 static int email_config (const char *key, const char *value)
168 if (0 == strcasecmp (key, "SocketFile")) {
169 if (NULL != sock_file)
171 sock_file = sstrdup (value);
173 else if (0 == strcasecmp (key, "SocketGroup")) {
174 if (NULL != sock_group)
176 sock_group = sstrdup (value);
178 else if (0 == strcasecmp (key, "SocketPerms")) {
179 /* the user is responsible for providing reasonable values */
180 sock_perms = (int)strtol (value, NULL, 8);
182 else if (0 == strcasecmp (key, "MaxConns")) {
183 long int tmp = strtol (value, NULL, 0);
186 fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
187 "value %li, will use default %i.\n",
189 ERROR ("email plugin: `MaxConns' was set to invalid "
190 "value %li, will use default %i.\n",
192 max_conns = MAX_CONNS;
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;
204 max_conns = (int)tmp;
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)
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;
228 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
229 if (0 == strcmp (name, ptr->name))
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;
246 } /* static void type_list_incr (type_list_t *, char *) */
248 static void *collect (void *arg)
250 collector_t *this = (collector_t *)arg;
255 pthread_mutex_lock (&conns_mutex);
257 while (NULL == conns.head) {
258 pthread_cond_wait (&conn_available, &conns_mutex);
261 connection = conns.head;
262 conns.head = conns.head->next;
264 if (NULL == conns.head) {
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));
278 /* 256 bytes ought to be enough for anybody ;-) */
279 char line[256 + 1]; /* line + '\0' */
283 if (NULL == fgets (line, sizeof (line), this->socket)) {
286 log_err ("collect: reading from socket (fd #%i) "
287 "failed: %s", fileno (this->socket),
288 sstrerror (errno, errbuf, sizeof (errbuf)));
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]))
303 if (len < 3) { /* [a-z] ':' '\n' */
309 log_debug ("collect: line = '%s'", line);
311 if (':' != line[1]) {
312 log_err ("collect: syntax error in line '%s'", line);
316 if ('e' == line[0]) { /* e:<type>:<bytes> */
318 char *type = strtok_r (line + 2, ":", &ptr);
319 char *tmp = strtok_r (NULL, ":", &ptr);
323 log_err ("collect: syntax error in line '%s'", line);
329 pthread_mutex_lock (&count_mutex);
330 type_list_incr (&list_count, type, /* increment = */ 1);
331 pthread_mutex_unlock (&count_mutex);
334 pthread_mutex_lock (&size_mutex);
335 type_list_incr (&list_size, type, /* increment = */ bytes);
336 pthread_mutex_unlock (&size_mutex);
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);
344 pthread_mutex_unlock (&score_mutex);
346 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
347 char *dummy = line + 2;
351 pthread_mutex_lock (&check_mutex);
352 while ((type = strtok_r (dummy, ",", &endptr)) != NULL)
355 type_list_incr (&list_check, type, /* increment = */ 1);
357 pthread_mutex_unlock (&check_mutex);
360 log_err ("collect: unknown type '%c'", line[0]);
364 log_debug ("Shutting down connection on fd #%i",
365 fileno (this->socket));
367 fclose (connection->socket);
372 pthread_mutex_lock (&available_mutex);
373 ++available_collectors;
374 pthread_mutex_unlock (&available_mutex);
376 pthread_cond_signal (&collector_available);
379 pthread_exit ((void *)0);
381 } /* static void *collect (void *) */
383 static void *open_connection (void __attribute__((unused)) *arg)
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 */
392 if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
395 log_err ("socket() failed: %s",
396 sstrerror (errno, errbuf, sizeof (errbuf)));
397 pthread_exit ((void *)1);
400 addr.sun_family = AF_UNIX;
401 sstrncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
404 if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
405 offsetof (struct sockaddr_un, sun_path)
406 + strlen(addr.sun_path))) {
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);
417 if (-1 == listen (connector_socket, 5)) {
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);
434 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
438 log_warn ("getgrnam_r (%s) failed: %s", group,
439 sstrerror (errno, errbuf, sizeof (errbuf)));
441 else if (grp == NULL)
443 log_warn ("No such group: `%s'", group);
447 status = chown (path, (uid_t) -1, grp->gr_gid);
451 log_warn ("chown (%s, -1, %i) failed: %s",
452 path, (int) grp->gr_gid,
453 sstrerror (errno, errbuf, sizeof (errbuf)));
459 if (0 != chmod (path, sock_perms)) {
461 log_warn ("chmod() failed: %s",
462 sstrerror (errno, errbuf, sizeof (errbuf)));
465 { /* initialize collector threads */
466 pthread_attr_t ptattr;
471 pthread_attr_init (&ptattr);
472 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
474 available_collectors = max_conns;
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) {
486 log_err ("plugin_thread_create() failed: %s",
487 sstrerror (errno, errbuf, sizeof (errbuf)));
488 collectors[i]->thread = (pthread_t) 0;
492 pthread_attr_destroy (&ptattr);
500 pthread_mutex_lock (&available_mutex);
502 while (0 == available_collectors) {
503 pthread_cond_wait (&collector_available, &available_mutex);
506 --available_collectors;
508 pthread_mutex_unlock (&available_mutex);
513 remote = accept (connector_socket, NULL, NULL);
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);
528 /* access() succeeded. */
532 connection = calloc (1, sizeof (*connection));
533 if (connection == NULL)
539 connection->socket = fdopen (remote, "r");
540 connection->next = NULL;
542 if (NULL == connection->socket) {
548 pthread_mutex_lock (&conns_mutex);
550 if (NULL == conns.head) {
551 conns.head = connection;
552 conns.tail = connection;
555 conns.tail->next = connection;
556 conns.tail = conns.tail->next;
559 pthread_mutex_unlock (&conns_mutex);
561 pthread_cond_signal (&conn_available);
564 pthread_exit ((void *) 0);
566 } /* static void *open_connection (void *) */
568 static int email_init (void)
570 if (plugin_thread_create (&connector, NULL,
571 open_connection, NULL) != 0) {
574 log_err ("plugin_thread_create() failed: %s",
575 sstrerror (errno, errbuf, sizeof (errbuf)));
580 } /* int email_init */
582 static void type_list_free (type_list_t *t)
589 type_t *next = this->next;
601 static int email_shutdown (void)
603 if (connector != ((pthread_t) 0)) {
604 pthread_kill (connector, SIGTERM);
605 connector = (pthread_t) 0;
608 if (connector_socket >= 0) {
609 close (connector_socket);
610 connector_socket = -1;
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)
623 if (collectors[i]->thread != ((pthread_t) 0)) {
624 pthread_kill (collectors[i]->thread, SIGTERM);
625 collectors[i]->thread = (pthread_t) 0;
628 if (collectors[i]->socket != NULL) {
629 fclose (collectors[i]->socket);
630 collectors[i]->socket = NULL;
633 sfree (collectors[i]);
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);
652 } /* static void email_shutdown (void) */
654 static void email_submit (const char *type, const char *type_instance, gauge_t value)
657 value_list_t vl = VALUE_LIST_INIT;
659 values[0].gauge = value;
663 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
664 sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
665 sstrncpy (vl.type, type, sizeof (vl.type));
666 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
668 plugin_dispatch_values (&vl);
669 } /* void email_submit */
671 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
672 * that neither the order nor the name of any element of either list is
673 * changed and no elements are deleted. The values of l1 are reset to zero
674 * after they have been copied to l2. */
675 static void copy_type_list (type_list_t *l1, type_list_t *l2)
679 for (type_t *ptr1 = l1->head, *ptr2 = l2->head; NULL != ptr1;
680 ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
682 ptr2 = smalloc (sizeof (*ptr2));
696 if (NULL == ptr2->name) {
697 ptr2->name = sstrdup (ptr1->name);
700 ptr2->value = ptr1->value;
706 static int email_read (void)
715 pthread_mutex_lock (&count_mutex);
717 copy_type_list (&list_count, &list_count_copy);
719 pthread_mutex_unlock (&count_mutex);
721 for (type_t *ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
722 email_submit ("email_count", ptr->name, ptr->value);
726 pthread_mutex_lock (&size_mutex);
728 copy_type_list (&list_size, &list_size_copy);
730 pthread_mutex_unlock (&size_mutex);
732 for (type_t *ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
733 email_submit ("email_size", ptr->name, ptr->value);
737 pthread_mutex_lock (&score_mutex);
740 score_count_old = score_count;
744 pthread_mutex_unlock (&score_mutex);
746 if (score_count_old > 0)
747 email_submit ("spam_score", "", score_old);
750 pthread_mutex_lock (&check_mutex);
752 copy_type_list (&list_check, &list_check_copy);
754 pthread_mutex_unlock (&check_mutex);
756 for (type_t *ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
757 email_submit ("spam_check", ptr->name, ptr->value);
760 } /* int email_read */
762 void module_register (void)
764 plugin_register_config ("email", email_config, config_keys, config_keys_num);
765 plugin_register_init ("email", email_init);
766 plugin_register_read ("email", email_read);
767 plugin_register_shutdown ("email", email_shutdown);
768 } /* void module_register */
770 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */