fdcf0677837e25cb27e50e78ad6c69f17be7bc3c
[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                         ERROR ("email plugin: `MaxConns' was set to invalid "
191                                         "value %li, will use default %i.\n",
192                                         tmp, MAX_CONNS);
193                         max_conns = MAX_CONNS;
194                 }
195                 else if (tmp > MAX_CONNS_LIMIT) {
196                         fprintf (stderr, "email plugin: `MaxConns' was set to invalid "
197                                         "value %li, will use hardcoded limit %i.\n",
198                                         tmp, MAX_CONNS_LIMIT);
199                         ERROR ("email plugin: `MaxConns' was set to invalid "
200                                         "value %li, will use hardcoded limit %i.\n",
201                                         tmp, MAX_CONNS_LIMIT);
202                         max_conns = MAX_CONNS_LIMIT;
203                 }
204                 else {
205                         max_conns = (int)tmp;
206                 }
207         }
208         else {
209                 return -1;
210         }
211         return 0;
212 } /* static int email_config (char *, char *) */
213
214 /* Increment the value of the given name in the given list by incr. */
215 static void type_list_incr (type_list_t *list, char *name, int incr)
216 {
217         if (NULL == list->head) {
218                 list->head = (type_t *)smalloc (sizeof (type_t));
219
220                 list->head->name  = sstrdup (name);
221                 list->head->value = incr;
222                 list->head->next  = NULL;
223
224                 list->tail = list->head;
225         }
226         else {
227                 type_t *ptr;
228
229                 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
230                         if (0 == strcmp (name, ptr->name))
231                                 break;
232                 }
233
234                 if (NULL == ptr) {
235                         list->tail->next = (type_t *)smalloc (sizeof (type_t));
236                         list->tail = list->tail->next;
237
238                         list->tail->name  = sstrdup (name);
239                         list->tail->value = incr;
240                         list->tail->next  = NULL;
241                 }
242                 else {
243                         ptr->value += incr;
244                 }
245         }
246         return;
247 } /* static void type_list_incr (type_list_t *, char *) */
248
249 static void *collect (void *arg)
250 {
251         collector_t *this = (collector_t *)arg;
252
253         while (1) {
254                 conn_t *connection;
255
256                 pthread_mutex_lock (&conns_mutex);
257
258                 while (NULL == conns.head) {
259                         pthread_cond_wait (&conn_available, &conns_mutex);
260                 }
261
262                 connection = conns.head;
263                 conns.head = conns.head->next;
264
265                 if (NULL == conns.head) {
266                         conns.tail = NULL;
267                 }
268
269                 pthread_mutex_unlock (&conns_mutex);
270
271                 /* make the socket available to the global
272                  * thread and connection management */
273                 this->socket = connection->socket;
274
275                 log_debug ("collect: handling connection on fd #%i",
276                                 fileno (this->socket));
277
278                 while (42) {
279                         /* 256 bytes ought to be enough for anybody ;-) */
280                         char line[256 + 1]; /* line + '\0' */
281                         int  len = 0;
282
283                         errno = 0;
284                         if (NULL == fgets (line, sizeof (line), this->socket)) {
285                                 if (0 != errno) {
286                                         char errbuf[1024];
287                                         log_err ("collect: reading from socket (fd #%i) "
288                                                         "failed: %s", fileno (this->socket),
289                                                         sstrerror (errno, errbuf, sizeof (errbuf)));
290                                 }
291                                 break;
292                         }
293
294                         len = strlen (line);
295                         if (('\n' != line[len - 1]) && ('\r' != line[len - 1])) {
296                                 log_warn ("collect: line too long (> %zu characters): "
297                                                 "'%s' (truncated)", sizeof (line) - 1, line);
298
299                                 while (NULL != fgets (line, sizeof (line), this->socket))
300                                         if (('\n' == line[len - 1]) || ('\r' == line[len - 1]))
301                                                 break;
302                                 continue;
303                         }
304
305                         line[len - 1] = '\0';
306
307                         log_debug ("collect: line = '%s'", line);
308
309                         if (':' != line[1]) {
310                                 log_err ("collect: syntax error in line '%s'", line);
311                                 continue;
312                         }
313
314                         if ('e' == line[0]) { /* e:<type>:<bytes> */
315                                 char *ptr  = NULL;
316                                 char *type = strtok_r (line + 2, ":", &ptr);
317                                 char *tmp  = strtok_r (NULL, ":", &ptr);
318                                 int  bytes = 0;
319
320                                 if (NULL == tmp) {
321                                         log_err ("collect: syntax error in line '%s'", line);
322                                         continue;
323                                 }
324
325                                 bytes = atoi (tmp);
326
327                                 pthread_mutex_lock (&count_mutex);
328                                 type_list_incr (&list_count, type, 1);
329                                 pthread_mutex_unlock (&count_mutex);
330
331                                 if (bytes > 0) {
332                                         pthread_mutex_lock (&size_mutex);
333                                         type_list_incr (&list_size, type, bytes);
334                                         pthread_mutex_unlock (&size_mutex);
335                                 }
336                         }
337                         else if ('s' == line[0]) { /* s:<value> */
338                                 pthread_mutex_lock (&score_mutex);
339                                 score = (score * (double)score_count + atof (line + 2))
340                                                 / (double)(score_count + 1);
341                                 ++score_count;
342                                 pthread_mutex_unlock (&score_mutex);
343                         }
344                         else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
345                                 char *ptr  = NULL;
346                                 char *type = strtok_r (line + 2, ",", &ptr);
347
348                                 do {
349                                         pthread_mutex_lock (&check_mutex);
350                                         type_list_incr (&list_check, type, 1);
351                                         pthread_mutex_unlock (&check_mutex);
352                                 } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
353                         }
354                         else {
355                                 log_err ("collect: unknown type '%c'", line[0]);
356                         }
357                 } /* while (42) */
358
359                 log_debug ("Shutting down connection on fd #%i",
360                                 fileno (this->socket));
361
362                 fclose (connection->socket);
363                 free (connection);
364
365                 this->socket = NULL;
366
367                 pthread_mutex_lock (&available_mutex);
368                 ++available_collectors;
369                 pthread_mutex_unlock (&available_mutex);
370
371                 pthread_cond_signal (&collector_available);
372         } /* while (1) */
373
374         pthread_exit ((void *)0);
375         return ((void *) 0);
376 } /* static void *collect (void *) */
377
378 static void *open_connection (void __attribute__((unused)) *arg)
379 {
380         struct sockaddr_un addr;
381
382         char *path  = (NULL == sock_file) ? SOCK_PATH : sock_file;
383         char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
384
385         /* create UNIX socket */
386         errno = 0;
387         if (-1 == (connector_socket = socket (PF_UNIX, SOCK_STREAM, 0))) {
388                 char errbuf[1024];
389                 disabled = 1;
390                 log_err ("socket() failed: %s",
391                                 sstrerror (errno, errbuf, sizeof (errbuf)));
392                 pthread_exit ((void *)1);
393         }
394
395         addr.sun_family = AF_UNIX;
396         sstrncpy (addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
397
398         errno = 0;
399         if (-1 == bind (connector_socket, (struct sockaddr *)&addr,
400                                 offsetof (struct sockaddr_un, sun_path)
401                                         + strlen(addr.sun_path))) {
402                 char errbuf[1024];
403                 disabled = 1;
404                 close (connector_socket);
405                 connector_socket = -1;
406                 log_err ("bind() failed: %s",
407                                 sstrerror (errno, errbuf, sizeof (errbuf)));
408                 pthread_exit ((void *)1);
409         }
410
411         errno = 0;
412         if (-1 == listen (connector_socket, 5)) {
413                 char errbuf[1024];
414                 disabled = 1;
415                 close (connector_socket);
416                 connector_socket = -1;
417                 log_err ("listen() failed: %s",
418                                 sstrerror (errno, errbuf, sizeof (errbuf)));
419                 pthread_exit ((void *)1);
420         }
421
422         {
423                 struct group sg;
424                 struct group *grp;
425                 char grbuf[2048];
426                 int status;
427
428                 grp = NULL;
429                 status = getgrnam_r (group, &sg, grbuf, sizeof (grbuf), &grp);
430                 if (status != 0)
431                 {
432                         char errbuf[1024];
433                         log_warn ("getgrnam_r (%s) failed: %s", group,
434                                         sstrerror (errno, errbuf, sizeof (errbuf)));
435                 }
436                 else if (grp == NULL)
437                 {
438                         log_warn ("No such group: `%s'", group);
439                 }
440                 else
441                 {
442                         status = chown (path, (uid_t) -1, grp->gr_gid);
443                         if (status != 0)
444                         {
445                                 char errbuf[1024];
446                                 log_warn ("chown (%s, -1, %i) failed: %s",
447                                                 path, (int) grp->gr_gid,
448                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
449                         }
450                 }
451         }
452
453         errno = 0;
454         if (0 != chmod (path, sock_perms)) {
455                 char errbuf[1024];
456                 log_warn ("chmod() failed: %s",
457                                 sstrerror (errno, errbuf, sizeof (errbuf)));
458         }
459
460         { /* initialize collector threads */
461                 int i   = 0;
462                 int err = 0;
463
464                 pthread_attr_t ptattr;
465
466                 conns.head = NULL;
467                 conns.tail = NULL;
468
469                 pthread_attr_init (&ptattr);
470                 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
471
472                 available_collectors = max_conns;
473
474                 collectors =
475                         (collector_t **)smalloc (max_conns * sizeof (collector_t *));
476
477                 for (i = 0; i < max_conns; ++i) {
478                         collectors[i] = (collector_t *)smalloc (sizeof (collector_t));
479                         collectors[i]->socket = NULL;
480
481                         if (0 != (err = plugin_thread_create (&collectors[i]->thread,
482                                                         &ptattr, collect, collectors[i]))) {
483                                 char errbuf[1024];
484                                 log_err ("pthread_create() failed: %s",
485                                                 sstrerror (errno, errbuf, sizeof (errbuf)));
486                                 collectors[i]->thread = (pthread_t) 0;
487                         }
488                 }
489
490                 pthread_attr_destroy (&ptattr);
491         }
492
493         while (1) {
494                 int remote = 0;
495
496                 conn_t *connection;
497
498                 pthread_mutex_lock (&available_mutex);
499
500                 while (0 == available_collectors) {
501                         pthread_cond_wait (&collector_available, &available_mutex);
502                 }
503
504                 --available_collectors;
505
506                 pthread_mutex_unlock (&available_mutex);
507
508                 do {
509                         errno = 0;
510                         if (-1 == (remote = accept (connector_socket, NULL, NULL))) {
511                                 if (EINTR != errno) {
512                                         char errbuf[1024];
513                                         disabled = 1;
514                                         close (connector_socket);
515                                         connector_socket = -1;
516                                         log_err ("accept() failed: %s",
517                                                         sstrerror (errno, errbuf, sizeof (errbuf)));
518                                         pthread_exit ((void *)1);
519                                 }
520                         }
521                 } while (EINTR == errno);
522
523                 connection = (conn_t *)smalloc (sizeof (conn_t));
524
525                 connection->socket = fdopen (remote, "r");
526                 connection->next   = NULL;
527
528                 if (NULL == connection->socket) {
529                         close (remote);
530                         continue;
531                 }
532
533                 pthread_mutex_lock (&conns_mutex);
534
535                 if (NULL == conns.head) {
536                         conns.head = connection;
537                         conns.tail = connection;
538                 }
539                 else {
540                         conns.tail->next = connection;
541                         conns.tail = conns.tail->next;
542                 }
543
544                 pthread_mutex_unlock (&conns_mutex);
545
546                 pthread_cond_signal (&conn_available);
547         }
548
549         pthread_exit ((void *) 0);
550         return ((void *) 0);
551 } /* static void *open_connection (void *) */
552
553 static int email_init (void)
554 {
555         int err = 0;
556
557         if (0 != (err = plugin_thread_create (&connector, NULL,
558                                 open_connection, NULL))) {
559                 char errbuf[1024];
560                 disabled = 1;
561                 log_err ("pthread_create() failed: %s",
562                                 sstrerror (errno, errbuf, sizeof (errbuf)));
563                 return (-1);
564         }
565
566         return (0);
567 } /* int email_init */
568
569 static void type_list_free (type_list_t *t)
570 {
571         type_t *this;
572
573         this = t->head;
574         while (this != NULL)
575         {
576                 type_t *next = this->next;
577
578                 sfree (this->name);
579                 sfree (this);
580
581                 this = next;
582         }
583
584         t->head = NULL;
585         t->tail = NULL;
586 }
587
588 static int email_shutdown (void)
589 {
590         int i = 0;
591
592         if (connector != ((pthread_t) 0)) {
593                 pthread_kill (connector, SIGTERM);
594                 connector = (pthread_t) 0;
595         }
596
597         if (connector_socket >= 0) {
598                 close (connector_socket);
599                 connector_socket = -1;
600         }
601
602         /* don't allow any more connections to be processed */
603         pthread_mutex_lock (&conns_mutex);
604
605         available_collectors = 0;
606
607         if (collectors != NULL) {
608                 for (i = 0; i < max_conns; ++i) {
609                         if (collectors[i] == NULL)
610                                 continue;
611
612                         if (collectors[i]->thread != ((pthread_t) 0)) {
613                                 pthread_kill (collectors[i]->thread, SIGTERM);
614                                 collectors[i]->thread = (pthread_t) 0;
615                         }
616
617                         if (collectors[i]->socket != NULL) {
618                                 fclose (collectors[i]->socket);
619                                 collectors[i]->socket = NULL;
620                         }
621
622                         sfree (collectors[i]);
623                 }
624                 sfree (collectors);
625         } /* if (collectors != NULL) */
626
627         pthread_mutex_unlock (&conns_mutex);
628
629         type_list_free (&list_count);
630         type_list_free (&list_count_copy);
631         type_list_free (&list_size);
632         type_list_free (&list_size_copy);
633         type_list_free (&list_check);
634         type_list_free (&list_check_copy);
635
636         unlink ((NULL == sock_file) ? SOCK_PATH : sock_file);
637
638         sfree (sock_file);
639         sfree (sock_group);
640         return (0);
641 } /* static void email_shutdown (void) */
642
643 static void email_submit (const char *type, const char *type_instance, gauge_t value)
644 {
645         value_t values[1];
646         value_list_t vl = VALUE_LIST_INIT;
647
648         values[0].gauge = value;
649
650         vl.values = values;
651         vl.values_len = 1;
652         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
653         sstrncpy (vl.plugin, "email", sizeof (vl.plugin));
654         sstrncpy (vl.type, type, sizeof (vl.type));
655         sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
656
657         plugin_dispatch_values (&vl);
658 } /* void email_submit */
659
660 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
661  * that neither the order nor the name of any element of either list is
662  * changed and no elements are deleted. The values of l1 are reset to zero
663  * after they have been copied to l2. */
664 static void copy_type_list (type_list_t *l1, type_list_t *l2)
665 {
666         type_t *ptr1;
667         type_t *ptr2;
668
669         type_t *last = NULL;
670
671         for (ptr1 = l1->head, ptr2 = l2->head; NULL != ptr1;
672                         ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
673                 if (NULL == ptr2) {
674                         ptr2 = (type_t *)smalloc (sizeof (type_t));
675                         ptr2->name = NULL;
676                         ptr2->next = NULL;
677
678                         if (NULL == last) {
679                                 l2->head = ptr2;
680                         }
681                         else {
682                                 last->next = ptr2;
683                         }
684
685                         l2->tail = ptr2;
686                 }
687
688                 if (NULL == ptr2->name) {
689                         ptr2->name = sstrdup (ptr1->name);
690                 }
691
692                 ptr2->value = ptr1->value;
693                 ptr1->value = 0;
694         }
695         return;
696 }
697
698 static int email_read (void)
699 {
700         type_t *ptr;
701
702         double score_old;
703         int score_count_old;
704
705         if (disabled)
706                 return (-1);
707
708         /* email count */
709         pthread_mutex_lock (&count_mutex);
710
711         copy_type_list (&list_count, &list_count_copy);
712
713         pthread_mutex_unlock (&count_mutex);
714
715         for (ptr = list_count_copy.head; NULL != ptr; ptr = ptr->next) {
716                 email_submit ("email_count", ptr->name, ptr->value);
717         }
718
719         /* email size */
720         pthread_mutex_lock (&size_mutex);
721
722         copy_type_list (&list_size, &list_size_copy);
723
724         pthread_mutex_unlock (&size_mutex);
725
726         for (ptr = list_size_copy.head; NULL != ptr; ptr = ptr->next) {
727                 email_submit ("email_size", ptr->name, ptr->value);
728         }
729
730         /* spam score */
731         pthread_mutex_lock (&score_mutex);
732
733         score_old = score;
734         score_count_old = score_count;
735         score = 0.0;
736         score_count = 0;
737
738         pthread_mutex_unlock (&score_mutex);
739
740         if (score_count_old > 0)
741                 email_submit ("spam_score", "", score_old);
742
743         /* spam checks */
744         pthread_mutex_lock (&check_mutex);
745
746         copy_type_list (&list_check, &list_check_copy);
747
748         pthread_mutex_unlock (&check_mutex);
749
750         for (ptr = list_check_copy.head; NULL != ptr; ptr = ptr->next)
751                 email_submit ("spam_check", ptr->name, ptr->value);
752
753         return (0);
754 } /* int email_read */
755
756 void module_register (void)
757 {
758         plugin_register_config ("email", email_config, config_keys, config_keys_num);
759         plugin_register_init ("email", email_init);
760         plugin_register_read ("email", email_read);
761         plugin_register_shutdown ("email", email_shutdown);
762 } /* void module_register */
763
764 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */