Code

common.c: fields_num is unsigned
[collectd.git] / src / email.c
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/un.h>
54 #include <sys/select.h>
56 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
57 #ifndef UNIX_PATH_MAX
58 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
59 #endif /* UNIX_PATH_MAX */
61 #if HAVE_GRP_H
62 #       include <grp.h>
63 #endif /* HAVE_GRP_H */
65 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
66 #define MAX_CONNS 5
67 #define MAX_CONNS_LIMIT 16384
69 #define log_debug(...) DEBUG ("email: "__VA_ARGS__)
70 #define log_err(...) ERROR ("email: "__VA_ARGS__)
71 #define log_warn(...) WARNING ("email: "__VA_ARGS__)
73 /*
74  * Private data structures
75  */
76 /* linked list of email and check types */
77 typedef struct type {
78         char        *name;
79         int         value;
80         struct type *next;
81 } type_t;
83 typedef struct {
84         type_t *head;
85         type_t *tail;
86 } type_list_t;
88 /* collector thread control information */
89 typedef struct collector {
90         pthread_t thread;
92         /* socket descriptor of the current/last connection */
93         FILE *socket;
94 } collector_t;
96 /* linked list of pending connections */
97 typedef struct conn {
98         /* socket to read data from */
99         FILE *socket;
101         /* linked list of connections */
102         struct conn *next;
103 } conn_t;
105 typedef struct {
106         conn_t *head;
107         conn_t *tail;
108 } conn_list_t;
110 /*
111  * Private variables
112  */
113 /* valid configuration file keys */
114 static const char *config_keys[] =
116         "SocketFile",
117         "SocketGroup",
118         "SocketPerms",
119         "MaxConns"
120 };
121 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
123 /* socket configuration */
124 static char *sock_file  = NULL;
125 static char *sock_group = NULL;
126 static int  sock_perms  = S_IRWXU | S_IRWXG;
127 static int  max_conns   = MAX_CONNS;
129 /* state of the plugin */
130 static int disabled = 0;
132 /* thread managing "client" connections */
133 static pthread_t connector = (pthread_t) 0;
134 static int connector_socket = -1;
136 /* tell the collector threads that a new connection is available */
137 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
139 /* connections that are waiting to be processed */
140 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
141 static conn_list_t conns;
143 /* tell the connector thread that a collector is available */
144 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
146 /* collector threads */
147 static collector_t **collectors = NULL;
149 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
150 static int available_collectors;
152 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
153 static type_list_t list_count;
154 static type_list_t list_count_copy;
156 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
157 static type_list_t list_size;
158 static type_list_t list_size_copy;
160 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
161 static double score;
162 static int score_count;
164 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
165 static type_list_t list_check;
166 static type_list_t list_check_copy;
168 /*
169  * Private functions
170  */
171 static int email_config (const char *key, const char *value)
173         if (0 == strcasecmp (key, "SocketFile")) {
174                 if (NULL != sock_file)
175                         free (sock_file);
176                 sock_file = sstrdup (value);
177         }
178         else if (0 == strcasecmp (key, "SocketGroup")) {
179                 if (NULL != sock_group)
180                         free (sock_group);
181                 sock_group = sstrdup (value);
182         }
183         else if (0 == strcasecmp (key, "SocketPerms")) {
184                 /* the user is responsible for providing reasonable values */
185                 sock_perms = (int)strtol (value, NULL, 8);
186         }
187         else if (0 == strcasecmp (key, "MaxConns")) {
188                 long int tmp = strtol (value, NULL, 0);
190                 if (tmp < 1) {
191                         fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
192                                         "value %li, will use default %i.\n",
193                                         tmp, MAX_CONNS);
194                         ERROR ("email plugin: `MaxConns' was set to invalid "
195                                         "value %li, will use default %i.\n",
196                                         tmp, MAX_CONNS);
197                         max_conns = MAX_CONNS;
198                 }
199                 else if (tmp > MAX_CONNS_LIMIT) {
200                         fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
201                                         "value %li, will use hardcoded limit %i.\n",
202                                         tmp, MAX_CONNS_LIMIT);
203                         ERROR ("email plugin: `MaxConns' was set to invalid "
204                                         "value %li, will use hardcoded limit %i.\n",
205                                         tmp, MAX_CONNS_LIMIT);
206                         max_conns = MAX_CONNS_LIMIT;
207                 }
208                 else {
209                         max_conns = (int)tmp;
210                 }
211         }
212         else {
213                 return -1;
214         }
215         return 0;
216 } /* static int email_config (char *, char *) */
218 /* Increment the value of the given name in the given list by incr. */
219 static void type_list_incr (type_list_t *list, char *name, int incr)
221         if (NULL == list->head) {
222                 list->head = smalloc (sizeof (*list->head));
224                 list->head->name  = sstrdup (name);
225                 list->head->value = incr;
226                 list->head->next  = NULL;
228                 list->tail = list->head;
229         }
230         else {
231                 type_t *ptr;
233                 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
234                         if (0 == strcmp (name, ptr->name))
235                                 break;
236                 }
238                 if (NULL == ptr) {
239                         list->tail->next = smalloc (sizeof (*list->tail->next));
240                         list->tail = list->tail->next;
242                         list->tail->name  = sstrdup (name);
243                         list->tail->value = incr;
244                         list->tail->next  = NULL;
245                 }
246                 else {
247                         ptr->value += incr;
248                 }
249         }
250         return;
251 } /* static void type_list_incr (type_list_t *, char *) */
253 static void *collect (void *arg)
255         collector_t *this = (collector_t *)arg;
257         while (1) {
258                 conn_t *connection;
260                 pthread_mutex_lock (&conns_mutex);
262                 while (NULL == conns.head) {
263                         pthread_cond_wait (&conn_available, &conns_mutex);
264                 }
266                 connection = conns.head;
267                 conns.head = conns.head->next;
269                 if (NULL == conns.head) {
270                         conns.tail = NULL;
271                 }
273                 pthread_mutex_unlock (&conns_mutex);
275                 /* make the socket available to the global
276                  * thread and connection management */
277                 this->socket = connection->socket;
279                 log_debug ("collect: handling connection on fd #%i",
280                                 fileno (this->socket));
282                 while (42) {
283                         /* 256 bytes ought to be enough for anybody ;-) */
284                         char line[256 + 1]; /* line + '\0' */
285                         int  len = 0;
287                         errno = 0;
288                         if (NULL == fgets (line, sizeof (line), this->socket)) {
289                                 if (0 != errno) {
290                                         char errbuf[1024];
291                                         log_err ("collect: reading from socket (fd #%i) "
292                                                         "failed: %s", fileno (this->socket),
293                                                         sstrerror (errno, errbuf, sizeof (errbuf)));
294                                 }
295                                 break;
296                         }
298                         len = strlen (line);
299                         if (('\n' != line[len - 1]) && ('\r' != line[len - 1])) {
300                                 log_warn ("collect: line too long (> %zu characters): "
301                                                 "'%s' (truncated)", sizeof (line) - 1, line);
303                                 while (NULL != fgets (line, sizeof (line), this->socket))
304                                         if (('\n' == line[len - 1]) || ('\r' == line[len - 1]))
305                                                 break;
306                                 continue;
307                         }
308                         if (len < 3) { /* [a-z] ':' '\n' */
309                                 continue;
310                         }
312                         line[len - 1] = 0;
314                         log_debug ("collect: line = '%s'", line);
316                         if (':' != line[1]) {
317                                 log_err ("collect: syntax error in line '%s'", line);
318                                 continue;
319                         }
321                         if ('e' == line[0]) { /* e:<type>:<bytes> */
322                                 char *ptr  = NULL;
323                                 char *type = strtok_r (line + 2, ":", &ptr);
324                                 char *tmp  = strtok_r (NULL, ":", &ptr);
325                                 int  bytes = 0;
327                                 if (NULL == tmp) {
328                                         log_err ("collect: syntax error in line '%s'", line);
329                                         continue;
330                                 }
332                                 bytes = atoi (tmp);
334                                 pthread_mutex_lock (&count_mutex);
335                                 type_list_incr (&list_count, type, /* increment = */ 1);
336                                 pthread_mutex_unlock (&count_mutex);
338                                 if (bytes > 0) {
339                                         pthread_mutex_lock (&size_mutex);
340                                         type_list_incr (&list_size, type, /* increment = */ bytes);
341                                         pthread_mutex_unlock (&size_mutex);
342                                 }
343                         }
344                         else if ('s' == line[0]) { /* s:<value> */
345                                 pthread_mutex_lock (&score_mutex);
346                                 score = (score * (double)score_count + atof (line + 2))
347                                                 / (double)(score_count + 1);
348                                 ++score_count;
349                                 pthread_mutex_unlock (&score_mutex);
350                         }
351                         else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
352                                 char *dummy = line + 2;
353                                 char *endptr = NULL;
354                                 char *type;
356                                 pthread_mutex_lock (&check_mutex);
357                                 while ((type = strtok_r (dummy, ",", &endptr)) != NULL)
358                                 {
359                                         dummy = NULL;
360                                         type_list_incr (&list_check, type, /* increment = */ 1);
361                                 }
362                                 pthread_mutex_unlock (&check_mutex);
363                         }
364                         else {
365                                 log_err ("collect: unknown type '%c'", line[0]);
366                         }
367                 } /* while (42) */
369                 log_debug ("Shutting down connection on fd #%i",
370                                 fileno (this->socket));
372                 fclose (connection->socket);
373                 free (connection);
375                 this->socket = NULL;
377                 pthread_mutex_lock (&available_mutex);
378                 ++available_collectors;
379                 pthread_mutex_unlock (&available_mutex);
381                 pthread_cond_signal (&collector_available);
382         } /* while (1) */
384         pthread_exit ((void *)0);
385         return ((void *) 0);
386 } /* static void *collect (void *) */
388 static void *open_connection (void __attribute__((unused)) *arg)
390         struct sockaddr_un addr;
392         const char *path  = (NULL == sock_file) ? SOCK_PATH : sock_file;
393         const char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
395         /* create UNIX socket */
396         errno = 0;
397         if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
398                 char errbuf[1024];
399                 disabled = 1;
400                 log_err ("socket() failed: %s",
401                                 sstrerror (errno, errbuf, sizeof (errbuf)));
402                 pthread_exit ((void *)1);
403         }
405         addr.sun_family = AF_UNIX;
406         sstrncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
408         errno = 0;
409         if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
410                                 offsetof (struct sockaddr_un, sun_path)
411                                         + strlen(addr.sun_path))) {
412                 char errbuf[1024];
413                 disabled = 1;
414                 close (connector_socket);
415                 connector_socket = -1;
416                 log_err ("bind() failed: %s",
417                                 sstrerror (errno, errbuf, sizeof (errbuf)));
418                 pthread_exit ((void *)1);
419         }
421         errno = 0;
422         if (-1 == listen (connector_socket, 5)) {
423                 char errbuf[1024];
424                 disabled = 1;
425                 close (connector_socket);
426                 connector_socket = -1;
427                 log_err ("listen() failed: %s",
428                                 sstrerror (errno, errbuf, sizeof (errbuf)));
429                 pthread_exit ((void *)1);
430         }
432         {
433                 struct group sg;
434                 struct group *grp;
435                 char grbuf[2048];
436                 int status;
438                 grp = NULL;
439                 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
440                 if (status != 0)
441                 {
442                         char errbuf[1024];
443                         log_warn ("getgrnam_r (%s) failed: %s", group,
444                                         sstrerror (errno, errbuf, sizeof (errbuf)));
445                 }
446                 else if (grp == NULL)
447                 {
448                         log_warn ("No such group: `%s'", group);
449                 }
450                 else
451                 {
452                         status = chown (path, (uid_t) -1, grp->gr_gid);
453                         if (status != 0)
454                         {
455                                 char errbuf[1024];
456                                 log_warn ("chown (%s, -1, %i) failed: %s",
457                                                 path, (int) grp->gr_gid,
458                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
459                         }
460                 }
461         }
463         errno = 0;
464         if (0 != chmod (path, sock_perms)) {
465                 char errbuf[1024];
466                 log_warn ("chmod() failed: %s",
467                                 sstrerror (errno, errbuf, sizeof (errbuf)));
468         }
470         { /* initialize collector threads */
471                 int i   = 0;
472                 int err = 0;
474                 pthread_attr_t ptattr;
476                 conns.head = NULL;
477                 conns.tail = NULL;
479                 pthread_attr_init (&ptattr);
480                 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
482                 available_collectors = max_conns;
484                 collectors =
485                         smalloc (max_conns * sizeof (*collectors));
487                 for (i = 0; i < max_conns; ++i) {
488                         collectors[i] = smalloc (sizeof (*collectors[i]));
489                         collectors[i]->socket = NULL;
491                         if (0 != (err = plugin_thread_create (&collectors[i]->thread,
492                                                         &ptattr, collect, collectors[i]))) {
493                                 char errbuf[1024];
494                                 log_err ("pthread_create() failed: %s",
495                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
496                                 collectors[i]->thread = (pthread_t) 0;
497                         }
498                 }
500                 pthread_attr_destroy (&ptattr);
501         }
503         while (1) {
504                 int remote = 0;
506                 conn_t *connection;
508                 pthread_mutex_lock (&available_mutex);
510                 while (0 == available_collectors) {
511                         pthread_cond_wait (&collector_available, &available_mutex);
512                 }
514                 --available_collectors;
516                 pthread_mutex_unlock (&available_mutex);
518                 while (42) {
519                         errno = 0;
521                         remote = accept (connector_socket, NULL, NULL);
522                         if (remote == -1) {
523                                 char errbuf[1024];
525                                 if (errno == EINTR)
526                                         continue;
528                                 disabled = 1;
529                                 close (connector_socket);
530                                 connector_socket = -1;
531                                 log_err ("accept() failed: %s",
532                                                  sstrerror (errno, errbuf, sizeof (errbuf)));
533                                 pthread_exit ((void *)1);
534                         }
536                         /* access() succeeded. */
537                         break;
538                 }
540                 connection = calloc (1, sizeof (*connection));
541                 if (connection == NULL)
542                 {
543                         close (remote);
544                         continue;
545                 }
547                 connection->socket = fdopen (remote, "r");
548                 connection->next   = NULL;
550                 if (NULL == connection->socket) {
551                         close (remote);
552                         sfree (connection);
553                         continue;
554                 }
556                 pthread_mutex_lock (&conns_mutex);
558                 if (NULL == conns.head) {
559                         conns.head = connection;
560                         conns.tail = connection;
561                 }
562                 else {
563                         conns.tail->next = connection;
564                         conns.tail = conns.tail->next;
565                 }
567                 pthread_mutex_unlock (&conns_mutex);
569                 pthread_cond_signal (&conn_available);
570         }
572         pthread_exit ((void *) 0);
573         return ((void *) 0);
574 } /* static void *open_connection (void *) */
576 static int email_init (void)
578         int err = 0;
580         if (0 != (err = plugin_thread_create (&connector, NULL,
581                                 open_connection, NULL))) {
582                 char errbuf[1024];
583                 disabled = 1;
584                 log_err ("pthread_create() failed: %s",
585                                 sstrerror (errno, errbuf, sizeof (errbuf)));
586                 return (-1);
587         }
589         return (0);
590 } /* int email_init */
592 static void type_list_free (type_list_t *t)
594         type_t *this;
596         this = t->head;
597         while (this != NULL)
598         {
599                 type_t *next = this->next;
601                 sfree (this->name);
602                 sfree (this);
604                 this = next;
605         }
607         t->head = NULL;
608         t->tail = NULL;
611 static int email_shutdown (void)
613         int i = 0;
615         if (connector != ((pthread_t) 0)) {
616                 pthread_kill (connector, SIGTERM);
617                 connector = (pthread_t) 0;
618         }
620         if (connector_socket >= 0) {
621                 close (connector_socket);
622                 connector_socket = -1;
623         }
625         /* don't allow any more connections to be processed */
626         pthread_mutex_lock (&conns_mutex);
628         available_collectors = 0;
630         if (collectors != NULL) {
631                 for (i = 0; i < max_conns; ++i) {
632                         if (collectors[i] == NULL)
633                                 continue;
635                         if (collectors[i]->thread != ((pthread_t) 0)) {
636                                 pthread_kill (collectors[i]->thread, SIGTERM);
637                                 collectors[i]->thread = (pthread_t) 0;
638                         }
640                         if (collectors[i]->socket != NULL) {
641                                 fclose (collectors[i]->socket);
642                                 collectors[i]->socket = NULL;
643                         }
645                         sfree (collectors[i]);
646                 }
647                 sfree (collectors);
648         } /* if (collectors != NULL) */
650         pthread_mutex_unlock (&conns_mutex);
652         type_list_free (&list_count);
653         type_list_free (&list_count_copy);
654         type_list_free (&list_size);
655         type_list_free (&list_size_copy);
656         type_list_free (&list_check);
657         type_list_free (&list_check_copy);
659         unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
661         sfree (sock_file);
662         sfree (sock_group);
663         return (0);
664 } /* static void email_shutdown (void) */
666 static void email_submit (const char *type, const char *type_instance, gauge_t value)
668         value_t values[1];
669         value_list_t vl = VALUE_LIST_INIT;
671         values[0].gauge = value;
673         vl.values = values;
674         vl.values_len = 1;
675         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
676         sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
677         sstrncpy (vl.type, type, sizeof (vl.type));
678         sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
680         plugin_dispatch_values (&vl);
681 } /* void email_submit */
683 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
684  * that neither the order nor the name of any element of either list is
685  * changed and no elements are deleted. The values of l1 are reset to zero
686  * after they have been copied to l2. */
687 static void copy_type_list (type_list_t *l1, type_list_t *l2)
689         type_t *ptr1;
690         type_t *ptr2;
692         type_t *last = NULL;
694         for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
695                         ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
696                 if (NULL == ptr2) {
697                         ptr2 = smalloc (sizeof (*ptr2));
698                         ptr2->name = NULL;
699                         ptr2->next = NULL;
701                         if (NULL == last) {
702                                 l2->head = ptr2;
703                         }
704                         else {
705                                 last->next = ptr2;
706                         }
708                         l2->tail = ptr2;
709                 }
711                 if (NULL == ptr2->name) {
712                         ptr2->name = sstrdup (ptr1->name);
713                 }
715                 ptr2->value = ptr1->value;
716                 ptr1->value = 0;
717         }
718         return;
721 static int email_read (void)
723         type_t *ptr;
725         double score_old;
726         int score_count_old;
728         if (disabled)
729                 return (-1);
731         /* email count */
732         pthread_mutex_lock (&count_mutex);
734         copy_type_list (&list_count, &list_count_copy);
736         pthread_mutex_unlock (&count_mutex);
738         for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
739                 email_submit ("email_count", ptr->name, ptr->value);
740         }
742         /* email size */
743         pthread_mutex_lock (&size_mutex);
745         copy_type_list (&list_size, &list_size_copy);
747         pthread_mutex_unlock (&size_mutex);
749         for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
750                 email_submit ("email_size", ptr->name, ptr->value);
751         }
753         /* spam score */
754         pthread_mutex_lock (&score_mutex);
756         score_old = score;
757         score_count_old = score_count;
758         score = 0.0;
759         score_count = 0;
761         pthread_mutex_unlock (&score_mutex);
763         if (score_count_old > 0)
764                 email_submit ("spam_score", "", score_old);
766         /* spam checks */
767         pthread_mutex_lock (&check_mutex);
769         copy_type_list (&list_check, &list_check_copy);
771         pthread_mutex_unlock (&check_mutex);
773         for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
774                 email_submit ("spam_check", ptr->name, ptr->value);
776         return (0);
777 } /* int email_read */
779 void module_register (void)
781         plugin_register_config ("email", email_config, config_keys, config_keys_num);
782         plugin_register_init ("email", email_init);
783         plugin_register_read ("email", email_read);
784         plugin_register_shutdown ("email", email_shutdown);
785 } /* void module_register */
787 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */