Merge branch 'collectd-4.3' into collectd-4.4
[collectd.git] / src / email.c
1 /**
2  * collectd - src/email.c
3  * Copyright (C) 2006-2008  Sebastian Harl
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Author:
19  *   Sebastian Harl <sh at tokkee.org>
20  **/
21
22 /*
23  * This plugin communicates with a spam filter, a virus scanner or similar
24  * software using a UNIX socket and a very simple protocol:
25  *
26  * e-mail type (e.g. ham, spam, virus, ...) and size
27  * e:<type>:<bytes>
28  *
29  * spam score
30  * s:<value>
31  *
32  * successful spam checks
33  * c:<type1>[,<type2>,...]
34  */
35
36 #include "collectd.h"
37 #include "common.h"
38 #include "plugin.h"
39
40 #include "configfile.h"
41
42 #include <stddef.h>
43
44 #if HAVE_LIBPTHREAD
45 # include <pthread.h>
46 #endif
47
48 #include <sys/socket.h>
49 #include <sys/un.h>
50 #include <sys/select.h>
51
52 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
53 #ifndef UNIX_PATH_MAX
54 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
55 #endif /* UNIX_PATH_MAX */
56
57 #if HAVE_GRP_H
58 #       include <grp.h>
59 #endif /* HAVE_GRP_H */
60
61 #define SOCK_PATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-email"
62 #define MAX_CONNS 5
63 #define MAX_CONNS_LIMIT 16384
64
65 #define log_debug(...) DEBUG ("email: "__VA_ARGS__)
66 #define log_err(...) ERROR ("email: "__VA_ARGS__)
67 #define log_warn(...) WARNING ("email: "__VA_ARGS__)
68
69 /*
70  * Private data structures
71  */
72 /* linked list of email and check types */
73 typedef struct type {
74         char        *name;
75         int         value;
76         struct type *next;
77 } type_t;
78
79 typedef struct {
80         type_t *head;
81         type_t *tail;
82 } type_list_t;
83
84 /* collector thread control information */
85 typedef struct collector {
86         pthread_t thread;
87
88         /* socket descriptor of the current/last connection */
89         FILE *socket;
90 } collector_t;
91
92 /* linked list of pending connections */
93 typedef struct conn {
94         /* socket to read data from */
95         FILE *socket;
96
97         /* linked list of connections */
98         struct conn *next;
99 } conn_t;
100
101 typedef struct {
102         conn_t *head;
103         conn_t *tail;
104 } conn_list_t;
105
106 /*
107  * Private variables
108  */
109 /* valid configuration file keys */
110 static const char *config_keys[] =
111 {
112         "SocketFile",
113         "SocketGroup",
114         "SocketPerms",
115         "MaxConns"
116 };
117 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
118
119 /* socket configuration */
120 static char *sock_file  = NULL;
121 static char *sock_group = NULL;
122 static int  sock_perms  = S_IRWXU | S_IRWXG;
123 static int  max_conns   = MAX_CONNS;
124
125 /* state of the plugin */
126 static int disabled = 0;
127
128 /* thread managing "client" connections */
129 static pthread_t connector = (pthread_t) 0;
130 static int connector_socket = -1;
131
132 /* tell the collector threads that a new connection is available */
133 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
134
135 /* connections that are waiting to be processed */
136 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
137 static conn_list_t conns;
138
139 /* tell the connector thread that a collector is available */
140 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
141
142 /* collector threads */
143 static collector_t **collectors = NULL;
144
145 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
146 static int available_collectors;
147
148 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
149 static type_list_t list_count;
150 static type_list_t list_count_copy;
151
152 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
153 static type_list_t list_size;
154 static type_list_t list_size_copy;
155
156 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
157 static double score;
158 static int score_count;
159
160 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
161 static type_list_t list_check;
162 static type_list_t list_check_copy;
163
164 /*
165  * Private functions
166  */
167 static int email_config (const char *key, const char *value)
168 {
169         if (0 == strcasecmp (key, "SocketFile")) {
170                 if (NULL != sock_file)
171                         free (sock_file);
172                 sock_file = sstrdup (value);
173         }
174         else if (0 == strcasecmp (key, "SocketGroup")) {
175                 if (NULL != sock_group)
176                         free (sock_group);
177                 sock_group = sstrdup (value);
178         }
179         else if (0 == strcasecmp (key, "SocketPerms")) {
180                 /* the user is responsible for providing reasonable values */
181                 sock_perms = (int)strtol (value, NULL, 8);
182         }
183         else if (0 == strcasecmp (key, "MaxConns")) {
184                 long int tmp = strtol (value, NULL, 0);
185
186                 if (tmp < 1) {
187                         fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
188                                         "value %li, will use default %i.\n",
189                                         tmp, MAX_CONNS);
190                         max_conns = MAX_CONNS;
191                 }
192                 else if (tmp > MAX_CONNS_LIMIT) {
193                         fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
194                                         "value %li, will use hardcoded limit %i.\n",
195                                         tmp, MAX_CONNS_LIMIT);
196                         max_conns = MAX_CONNS_LIMIT;
197                 }
198                 else {
199                         max_conns = (int)tmp;
200                 }
201         }
202         else {
203                 return -1;
204         }
205         return 0;
206 } /* static int email_config (char *, char *) */
207
208 /* Increment the value of the given name in the given list by incr. */
209 static void type_list_incr (type_list_t *list, char *name, int incr)
210 {
211         if (NULL == list->head) {
212                 list->head = (type_t *)smalloc (sizeof (type_t));
213
214                 list->head->name  = sstrdup (name);
215                 list->head->value = incr;
216                 list->head->next  = NULL;
217
218                 list->tail = list->head;
219         }
220         else {
221                 type_t *ptr;
222
223                 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
224                         if (0 == strcmp (name, ptr->name))
225                                 break;
226                 }
227
228                 if (NULL == ptr) {
229                         list->tail->next = (type_t *)smalloc (sizeof (type_t));
230                         list->tail = list->tail->next;
231
232                         list->tail->name  = sstrdup (name);
233                         list->tail->value = incr;
234                         list->tail->next  = NULL;
235                 }
236                 else {
237                         ptr->value += incr;
238                 }
239         }
240         return;
241 } /* static void type_list_incr (type_list_t *, char *) */
242
243 static void *collect (void *arg)
244 {
245         collector_t *this = (collector_t *)arg;
246
247         while (1) {
248                 int loop = 1;
249
250                 conn_t *connection;
251
252                 pthread_mutex_lock (&conns_mutex);
253
254                 while (NULL == conns.head) {
255                         pthread_cond_wait (&conn_available, &conns_mutex);
256                 }
257
258                 connection = conns.head;
259                 conns.head = conns.head->next;
260
261                 if (NULL == conns.head) {
262                         conns.tail = NULL;
263                 }
264
265                 pthread_mutex_unlock (&conns_mutex);
266
267                 /* make the socket available to the global
268                  * thread and connection management */
269                 this->socket = connection->socket;
270
271                 log_debug ("collect: handling connection on fd #%i",
272                                 fileno (this->socket));
273
274                 while (loop) {
275                         /* 256 bytes ought to be enough for anybody ;-) */
276                         char line[256 + 1]; /* line + '\0' */
277                         int  len = 0;
278
279                         errno = 0;
280                         if (NULL == fgets (line, sizeof (line), this->socket)) {
281                                 loop = 0;
282
283                                 if (0 != errno) {
284                                         char errbuf[1024];
285                                         log_err ("collect: reading from socket (fd #%i) "
286                                                         "failed: %s", fileno (this->socket),
287                                                         sstrerror (errno, errbuf, sizeof (errbuf)));
288                                 }
289                                 break;
290                         }
291
292                         len = strlen (line);
293                         if (('\n' != line[len - 1]) && ('\r' != line[len - 1])) {
294                                 log_warn ("collect: line too long (> %zu characters): "
295                                                 "'%s' (truncated)", sizeof (line) - 1, line);
296
297                                 while (NULL != fgets (line, sizeof (line), this->socket))
298                                         if (('\n' == line[len - 1]) || ('\r' == line[len - 1]))
299                                                 break;
300                                 continue;
301                         }
302
303                         line[len - 1] = '\0';
304
305                         log_debug ("collect: line = '%s'", line);
306
307                         if (':' != line[1]) {
308                                 log_err ("collect: syntax error in line '%s'", line);
309                                 continue;
310                         }
311
312                         if ('e' == line[0]) { /* e:<type>:<bytes> */
313                                 char *ptr  = NULL;
314                                 char *type = strtok_r (line + 2, ":", &ptr);
315                                 char *tmp  = strtok_r (NULL, ":", &ptr);
316                                 int  bytes = 0;
317
318                                 if (NULL == tmp) {
319                                         log_err ("collect: syntax error in line '%s'", line);
320                                         continue;
321                                 }
322
323                                 bytes = atoi (tmp);
324
325                                 pthread_mutex_lock (&count_mutex);
326                                 type_list_incr (&list_count, type, 1);
327                                 pthread_mutex_unlock (&count_mutex);
328
329                                 if (bytes > 0) {
330                                         pthread_mutex_lock (&size_mutex);
331                                         type_list_incr (&list_size, type, bytes);
332                                         pthread_mutex_unlock (&size_mutex);
333                                 }
334                         }
335                         else if ('s' == line[0]) { /* s:<value> */
336                                 pthread_mutex_lock (&score_mutex);
337                                 score = (score * (double)score_count + atof (line + 2))
338                                                 / (double)(score_count + 1);
339                                 ++score_count;
340                                 pthread_mutex_unlock (&score_mutex);
341                         }
342                         else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
343                                 char *ptr  = NULL;
344                                 char *type = strtok_r (line + 2, ",", &ptr);
345
346                                 do {
347                                         pthread_mutex_lock (&check_mutex);
348                                         type_list_incr (&list_check, type, 1);
349                                         pthread_mutex_unlock (&check_mutex);
350                                 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
351                         }
352                         else {
353                                 log_err ("collect: unknown type '%c'", line[0]);
354                         }
355                 } /* while (loop) */
356
357                 log_debug ("[thread #%5lu] shutting down connection on fd #%i",
358                                 pthread_self (), fileno (this->socket));
359
360                 fclose (connection->socket);
361                 free (connection);
362
363                 this->socket = NULL;
364
365                 pthread_mutex_lock (&available_mutex);
366                 ++available_collectors;
367                 pthread_mutex_unlock (&available_mutex);
368
369                 pthread_cond_signal (&collector_available);
370         } /* while (1) */
371
372         pthread_exit ((void *)0);
373 } /* static void *collect (void *) */
374
375 static void *open_connection (void *arg)
376 {
377         struct sockaddr_un addr;
378
379         char *path  = (NULL == sock_file) ? SOCK_PATH : sock_file;
380         char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
381
382         /* create UNIX socket */
383         errno = 0;
384         if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
385                 char errbuf[1024];
386                 disabled = 1;
387                 log_err ("socket() failed: %s",
388                                 sstrerror (errno, errbuf, sizeof (errbuf)));
389                 pthread_exit ((void *)1);
390         }
391
392         addr.sun_family = AF_UNIX;
393
394         strncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
395         addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
396
397         errno = 0;
398         if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
399                                 offsetof (struct sockaddr_un, sun_path)
400                                         + strlen(addr.sun_path))) {
401                 char errbuf[1024];
402                 disabled = 1;
403                 close (connector_socket);
404                 connector_socket = -1;
405                 log_err ("bind() failed: %s",
406                                 sstrerror (errno, errbuf, sizeof (errbuf)));
407                 pthread_exit ((void *)1);
408         }
409
410         errno = 0;
411         if (-1 == listen (connector_socket, 5)) {
412                 char errbuf[1024];
413                 disabled = 1;
414                 close (connector_socket);
415                 connector_socket = -1;
416                 log_err ("listen() failed: %s",
417                                 sstrerror (errno, errbuf, sizeof (errbuf)));
418                 pthread_exit ((void *)1);
419         }
420
421         {
422                 struct group sg;
423                 struct group *grp;
424                 char grbuf[2048];
425                 int status;
426
427                 grp = NULL;
428                 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
429                 if (status != 0)
430                 {
431                         char errbuf[1024];
432                         log_warn ("getgrnam_r (%s) failed: %s", group,
433                                         sstrerror (errno, errbuf, sizeof (errbuf)));
434                 }
435                 else if (grp == NULL)
436                 {
437                         log_warn ("No such group: `%s'", group);
438                 }
439                 else
440                 {
441                         status = chown (path, (uid_t) -1, grp->gr_gid);
442                         if (status != 0)
443                         {
444                                 char errbuf[1024];
445                                 log_warn ("chown (%s, -1, %i) failed: %s",
446                                                 path, (int) grp->gr_gid,
447                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
448                         }
449                 }
450         }
451
452         errno = 0;
453         if (0 != chmod (path, sock_perms)) {
454                 char errbuf[1024];
455                 log_warn ("chmod() failed: %s",
456                                 sstrerror (errno, errbuf, sizeof (errbuf)));
457         }
458
459         { /* initialize collector threads */
460                 int i   = 0;
461                 int err = 0;
462
463                 pthread_attr_t ptattr;
464
465                 conns.head = NULL;
466                 conns.tail = NULL;
467
468                 pthread_attr_init (&ptattr);
469                 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
470
471                 available_collectors = max_conns;
472
473                 collectors =
474                         (collector_t **)smalloc (max_conns * sizeof (collector_t *));
475
476                 for (i = 0; i < max_conns; ++i) {
477                         collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
478                         collectors[i]->socket = NULL;
479
480                         if (0 != (err = pthread_create (&collectors[i]->thread, &ptattr,
481                                                         collect, collectors[i]))) {
482                                 char errbuf[1024];
483                                 log_err ("pthread_create() failed: %s",
484                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
485                                 collectors[i]->thread = (pthread_t) 0;
486                         }
487                 }
488
489                 pthread_attr_destroy (&ptattr);
490         }
491
492         while (1) {
493                 int remote = 0;
494
495                 conn_t *connection;
496
497                 pthread_mutex_lock (&available_mutex);
498
499                 while (0 == available_collectors) {
500                         pthread_cond_wait (&collector_available, &available_mutex);
501                 }
502
503                 --available_collectors;
504
505                 pthread_mutex_unlock (&available_mutex);
506
507                 do {
508                         errno = 0;
509                         if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
510                                 if (EINTR != errno) {
511                                         char errbuf[1024];
512                                         disabled = 1;
513                                         close (connector_socket);
514                                         connector_socket = -1;
515                                         log_err ("accept() failed: %s",
516                                                         sstrerror (errno, errbuf, sizeof (errbuf)));
517                                         pthread_exit ((void *)1);
518                                 }
519                         }
520                 } while (EINTR == errno);
521
522                 connection = (conn_t *)smalloc (sizeof (conn_t));
523
524                 connection->socket = fdopen (remote, "r");
525                 connection->next   = NULL;
526
527                 if (NULL == connection->socket) {
528                         close (remote);
529                         continue;
530                 }
531
532                 pthread_mutex_lock (&conns_mutex);
533
534                 if (NULL == conns.head) {
535                         conns.head = connection;
536                         conns.tail = connection;
537                 }
538                 else {
539                         conns.tail->next = connection;
540                         conns.tail = conns.tail->next;
541                 }
542
543                 pthread_mutex_unlock (&conns_mutex);
544
545                 pthread_cond_signal (&conn_available);
546         }
547         pthread_exit ((void *)0);
548 } /* static void *open_connection (void *) */
549
550 static int email_init (void)
551 {
552         int err = 0;
553
554         if (0 != (err = pthread_create (&connector, NULL,
555                                 open_connection, NULL))) {
556                 char errbuf[1024];
557                 disabled = 1;
558                 log_err ("pthread_create() failed: %s",
559                                 sstrerror (errno, errbuf, sizeof (errbuf)));
560                 return (-1);
561         }
562
563         return (0);
564 } /* int email_init */
565
566 static int email_shutdown (void)
567 {
568         type_t *ptr = NULL;
569
570         int i = 0;
571
572         if (connector != ((pthread_t) 0)) {
573                 pthread_kill (connector, SIGTERM);
574                 connector = (pthread_t) 0;
575         }
576
577         if (connector_socket >= 0) {
578                 close (connector_socket);
579                 connector_socket = -1;
580         }
581
582         /* don't allow any more connections to be processed */
583         pthread_mutex_lock (&conns_mutex);
584
585         available_collectors = 0;
586
587         if (collectors != NULL) {
588                 for (i = 0; i < max_conns; ++i) {
589                         if (collectors[i] == NULL)
590                                 continue;
591
592                         if (collectors[i]->thread != ((pthread_t) 0)) {
593                                 pthread_kill (collectors[i]->thread, SIGTERM);
594                                 collectors[i]->thread = (pthread_t) 0;
595                         }
596
597                         if (collectors[i]->socket != NULL) {
598                                 fclose (collectors[i]->socket);
599                                 collectors[i]->socket = NULL;
600                         }
601
602                         sfree (collectors[i]);
603                 }
604                 sfree (collectors);
605         } /* if (collectors != NULL) */
606
607         pthread_mutex_unlock (&conns_mutex);
608
609         for (ptr = list_count.head; NULL != ptr; ptr = ptr->next) {
610                 free (ptr->name);
611                 free (ptr);
612         }
613
614         for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
615                 free (ptr->name);
616                 free (ptr);
617         }
618
619         for (ptr = list_size.head; NULL != ptr; ptr = ptr->next) {
620                 free (ptr->name);
621                 free (ptr);
622         }
623
624         for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
625                 free (ptr->name);
626                 free (ptr);
627         }
628
629         for (ptr = list_check.head; NULL != ptr; ptr = ptr->next) {
630                 free (ptr->name);
631                 free (ptr);
632         }
633
634         for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next) {
635                 free (ptr->name);
636                 free (ptr);
637         }
638
639         unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
640
641         sfree (sock_file);
642         sfree (sock_group);
643         return (0);
644 } /* static void email_shutdown (void) */
645
646 static void email_submit (const char *type, const char *type_instance, gauge_t value)
647 {
648         value_t values[1];
649         value_list_t vl = VALUE_LIST_INIT;
650
651         values[0].gauge = value;
652
653         vl.values = values;
654         vl.values_len = 1;
655         vl.time = time (NULL);
656         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
657         sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
658         strncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
659
660         plugin_dispatch_values (type, &vl);
661 } /* void email_submit */
662
663 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
664  * that neither the order nor the name of any element of either list is
665  * changed and no elements are deleted. The values of l1 are reset to zero
666  * after they have been copied to l2. */
667 static void copy_type_list (type_list_t *l1, type_list_t *l2)
668 {
669         type_t *ptr1;
670         type_t *ptr2;
671
672         type_t *last = NULL;
673
674         for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
675                         ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
676                 if (NULL == ptr2) {
677                         ptr2 = (type_t *)smalloc (sizeof (type_t));
678                         ptr2->name = NULL;
679                         ptr2->next = NULL;
680
681                         if (NULL == last) {
682                                 l2->head = ptr2;
683                         }
684                         else {
685                                 last->next = ptr2;
686                         }
687
688                         l2->tail = ptr2;
689                 }
690
691                 if (NULL == ptr2->name) {
692                         ptr2->name = sstrdup (ptr1->name);
693                 }
694
695                 ptr2->value = ptr1->value;
696                 ptr1->value = 0;
697         }
698         return;
699 }
700
701 static int email_read (void)
702 {
703         type_t *ptr;
704
705         double score_old;
706         int score_count_old;
707
708         if (disabled)
709                 return (-1);
710
711         /* email count */
712         pthread_mutex_lock (&count_mutex);
713
714         copy_type_list (&list_count, &list_count_copy);
715
716         pthread_mutex_unlock (&count_mutex);
717
718         for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
719                 email_submit ("email_count", ptr->name, ptr->value);
720         }
721
722         /* email size */
723         pthread_mutex_lock (&size_mutex);
724
725         copy_type_list (&list_size, &list_size_copy);
726
727         pthread_mutex_unlock (&size_mutex);
728
729         for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
730                 email_submit ("email_size", ptr->name, ptr->value);
731         }
732
733         /* spam score */
734         pthread_mutex_lock (&score_mutex);
735
736         score_old = score;
737         score_count_old = score_count;
738         score = 0.0;
739         score_count = 0;
740
741         pthread_mutex_unlock (&score_mutex);
742
743         if (score_count_old > 0)
744                 email_submit ("spam_score", "", score_old);
745
746         /* spam checks */
747         pthread_mutex_lock (&check_mutex);
748
749         copy_type_list (&list_check, &list_check_copy);
750
751         pthread_mutex_unlock (&check_mutex);
752
753         for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
754                 email_submit ("spam_check", ptr->name, ptr->value);
755
756         return (0);
757 } /* int email_read */
758
759 void module_register (void)
760 {
761         plugin_register_config ("email", email_config, config_keys, config_keys_num);
762         plugin_register_init ("email", email_init);
763         plugin_register_read ("email", email_read);
764         plugin_register_shutdown ("email", email_shutdown);
765 } /* void module_register */
766
767 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */