New plugin "email" to collectd ham, spam, ... statistics
[collectd.git] / src / email.c
1 /**
2  * collectd - src/email.c
3  * Copyright (C) 2006  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; either version 2 of the License, or (at your
8  * option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Author:
20  *   Sebastian Harl <sh at tokkee.org>
21  **/
22
23 /*
24  * This plugin communicates with a spam filter, a virus scanner or similar
25  * software using a UNIX socket and a very simple protocol:
26  * 
27  * e-mail type (e.g. ham, spam, virus, ...) and size
28  * e:<type>:<bytes>
29  *
30  * spam score
31  * s:<value>
32  *
33  * successful spam checks
34  * c:<type1>[,<type2>,...]
35  */
36
37 #include "collectd.h"
38 #include "common.h"
39 #include "plugin.h"
40
41 #include <pthread.h>
42
43 #if HAVE_SYS_SELECT_H
44 #       include <sys/select.h>
45 #endif /* HAVE_SYS_SELECT_H */
46
47 #if HAVE_SYS_SOCKET_H
48 #       include <sys/socket.h>
49 #endif /* HAVE_SYS_SOCKET_H */
50
51 /* *sigh* glibc does not define UNIX_PATH_MAX in sys/un.h ... */
52 #if HAVE_LINUX_UN_H
53 #       include <linux/un.h>
54 #elif HAVE_SYS_UN_H
55 #       include <sys/un.h>
56 #endif /* HAVE_LINUX_UN_H | HAVE_SYS_UN_H */
57
58 #define MODULE_NAME "email"
59
60 /* 256 bytes ought to be enough for anybody ;-) */
61 #define BUFSIZE 256
62
63 #define SOCK_PATH "/tmp/.collectd-email"
64 #define MAX_CONNS 5
65
66 /* linked list of email and check types */
67 typedef struct type {
68         char        *name;
69         int         value;
70         struct type *next;
71 } type_t;
72
73 typedef struct {
74         type_t *head;
75         type_t *tail;
76 } type_list_t;
77
78 /* linked list of collector thread control information */
79 typedef struct collector {
80         pthread_t thread;
81
82         /* socket to read data from */
83         int socket;
84
85         /* buffer to read data to */
86         char buffer[BUFSIZE];
87         int  idx; /* current position in buffer */
88
89         struct collector *next;
90 } collector_t;
91
92 typedef struct {
93         collector_t *head;
94         collector_t *tail;
95 } collector_list_t;
96
97 /* state of the plugin */
98 static int disabled = 0;
99
100 /* thread managing "client" connections */
101 static pthread_t connector;
102
103 /* tell the connector thread that a collector is available */
104 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
105
106 /* collector threads that are in use */
107 static pthread_mutex_t active_mutex = PTHREAD_MUTEX_INITIALIZER;
108 static collector_list_t active;
109
110 /* collector threads that are available for use */
111 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
112 static collector_list_t available;
113
114 #define COUNT_FILE "email/email-%s.rrd"
115 static char *count_ds_def[] =
116 {
117         "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
118         NULL
119 };
120 static int count_ds_num = 1;
121
122 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
123 static type_list_t count;
124
125 #define SIZE_FILE  "email/email_size-%s.rrd"
126 static char *size_ds_def[] = 
127 {
128         "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
129         NULL
130 };
131 static int size_ds_num = 1;
132
133 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
134 static type_list_t size;
135
136 #define SCORE_FILE "email/spam_score.rrd"
137 static char *score_ds_def[] =
138 {
139         "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
140         NULL
141 };
142 static int score_ds_num = 1;
143
144 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
145 static double score;
146 static int score_count;
147
148 #define CHECK_FILE "email/spam_check-%s.rrd"
149 static char *check_ds_def[] =
150 {
151         "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
152         NULL
153 };
154 static int check_ds_num = 1;
155
156 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
157 static type_list_t check;
158
159 /* Increment the value of the given name in the given list by incr. */
160 static void type_list_incr (type_list_t *list, char *name, int incr)
161 {
162         if (NULL == list->head) {
163                 list->head = (type_t *)smalloc (sizeof (type_t));
164
165                 list->head->name  = sstrdup (name);
166                 list->head->value = incr;
167                 list->head->next  = NULL;
168
169                 list->tail = list->head;
170         }
171         else {
172                 type_t *ptr;
173
174                 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
175                         if (0 == strcmp (name, ptr->name))
176                                 break;
177                 }
178
179                 if (NULL == ptr) {
180                         list->tail->next = (type_t *)smalloc (sizeof (type_t));
181                         list->tail = list->tail->next;
182
183                         list->tail->name  = sstrdup (name);
184                         list->tail->value = incr;
185                         list->tail->next  = NULL;
186                 }
187                 else {
188                         ptr->value += incr;
189                 }
190         }
191         return;
192 } /* static void type_list_incr (type_list_t *, char *) */
193
194 /* Read a single character from the socket. If an error occurs or end-of-file
195  * is reached return '\0'. */
196 char read_char (collector_t *src)
197 {
198         char ret = '\0';
199
200         fd_set fdset;
201
202         FD_ZERO (&fdset);
203         FD_SET (src->socket, &fdset);
204
205         if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
206                 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
207                 return '\0';
208         }
209
210         assert (FD_ISSET (src->socket, &fdset));
211
212         do {
213                 ssize_t len = 0;
214
215                 errno = 0;
216                 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
217                         if (EINTR != errno) {
218                                 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
219                                 return '\0';
220                         }
221                 }
222
223                 if (0 == len)
224                         return '\0';
225         } while (EINTR == errno);
226         return ret;
227 } /* char read_char (collector_t *) */
228
229 /* Read a single line (terminated by '\n') from the the socket.
230  *
231  * The return value is zero terminated and does not contain any newline
232  * characters. In case that no complete line is available (non-blocking mode
233  * should be enabled) an empty string is returned.
234  *
235  * If an error occurs or end-of-file is reached return NULL.
236  *
237  * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
238  * characters of the input stream, the line will will be ignored! By
239  * definition we should not get any longer input lines, thus this is
240  * acceptable in this case ;-) */
241 char *read_line (collector_t *src)
242 {
243         int  i = 0;
244         char *ret;
245
246         assert (BUFSIZE > src->idx);
247
248         for (i = 0; i < src->idx; ++i) {
249                 if ('\n' == src->buffer[i])
250                         break;
251         }
252
253         if ('\n' != src->buffer[i]) {
254                 fd_set fdset;
255         
256                 ssize_t len = 0;
257
258                 FD_ZERO (&fdset);
259                 FD_SET (src->socket, &fdset);
260
261                 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
262                         syslog (LOG_ERR, "select() failed: %s", strerror (errno));
263                         return NULL;
264                 }
265
266                 assert (FD_ISSET (src->socket, &fdset));
267
268                 do {
269                         errno = 0;
270                         if (0 > (len = read (src->socket, 
271                                                         (void *)(&(src->buffer[0]) + src->idx), 
272                                                         BUFSIZE - src->idx))) {
273                                 if (EINTR != errno) {
274                                         syslog (LOG_ERR, "read() failed: %s", strerror (errno));
275                                         return NULL;
276                                 }
277                         }
278
279                         if (0 == len)
280                                 return NULL;
281                 } while (EINTR == errno);
282
283                 src->idx += len;
284
285                 for (i = src->idx - len; i < src->idx; ++i) {
286                         if ('\n' == src->buffer[i])
287                                 break;
288                 }
289
290                 if ('\n' != src->buffer[i]) {
291                         ret = (char *)smalloc (1);
292
293                         ret[0] = '\0';
294
295                         if (BUFSIZE == src->idx) { /* no space left in buffer */
296                                 while ('\n' != read_char (src))
297                                         /* ignore complete line */;
298
299                                 src->idx = 0;
300                         }
301                         return ret;
302                 }
303         }
304
305         ret = (char *)smalloc (i + 1);
306         memcpy (ret, &(src->buffer[0]), i + 1);
307         ret[i] = '\0';
308
309         src->idx -= (i + 1);
310
311         if (0 == src->idx)
312                 src->buffer[0] = '\0';
313         else
314                 memmove (&(src->buffer[0]), &(src->buffer[i + 1]), src->idx);
315         return ret;
316 } /* char *read_line (collector_t *) */
317
318 static void *collect (void *arg)
319 {
320         collector_t *this = (collector_t *)arg;
321         
322         int loop = 1;
323
324         { /* put the socket in non-blocking mode */
325                 int flags = 0;
326
327                 errno = 0;
328                 if (-1 == fcntl (this->socket, F_GETFL, &flags)) {
329                         syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
330                         loop = 0;
331                 }
332
333                 errno = 0;
334                 if (-1 == fcntl (this->socket, F_SETFL, flags | O_NONBLOCK)) {
335                         syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
336                         loop = 0;
337                 }
338         }
339
340         while (loop) {
341                 char *line = read_line (this);
342
343                 if (NULL == line) {
344                         loop = 0;
345                         break;
346                 }
347
348                 if ('\0' == line[0]) {
349                         free (line);
350                         continue;
351                 }
352
353                 if (':' != line[1]) {
354                         syslog (LOG_ERR, "email: syntax error in line '%s'", line);
355                         free (line);
356                         continue;
357                 }
358
359                 if ('e' == line[0]) { /* e:<type>:<bytes> */
360                         char *type = strtok (line + 2, ":");
361                         char *tmp  = strtok (NULL, ":");
362                         int  bytes = 0;
363
364                         if (NULL == tmp) {
365                                 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
366                                 free (line);
367                                 continue;
368                         }
369
370                         bytes = atoi (tmp);
371
372                         pthread_mutex_lock (&count_mutex);
373                         type_list_incr (&count, type, 1);
374                         pthread_mutex_unlock (&count_mutex);
375
376                         pthread_mutex_lock (&size_mutex);
377                         type_list_incr (&size, type, bytes);
378                         pthread_mutex_unlock (&size_mutex);
379                 }
380                 else if ('s' == line[0]) { /* s:<value> */
381                         pthread_mutex_lock (&score_mutex);
382                         score = (score * (double)score_count + atof (line + 2)) 
383                                         / (double)(score_count + 1);
384                         ++score_count;
385                         pthread_mutex_unlock (&score_mutex);
386                 }
387                 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
388                         char *type = strtok (line + 2, ",");
389
390                         do {
391                                 pthread_mutex_lock (&check_mutex);
392                                 type_list_incr (&check, type, 1);
393                                 pthread_mutex_unlock (&check_mutex);
394                         } while (NULL != (type = strtok (NULL, ",")));
395                 }
396                 else {
397                         syslog (LOG_ERR, "email: unknown type '%c'", line[0]);
398                 }
399
400                 free (line);
401         }
402
403         /* put this thread back into the available list */
404         pthread_mutex_lock (&active_mutex);
405         {
406                 collector_t *last;
407                 collector_t *ptr;
408
409                 last = NULL;
410
411                 for (ptr = active.head; NULL != ptr; last = ptr, ptr = ptr->next) {
412                         if (0 != pthread_equal (ptr->thread, this->thread))
413                                 break;
414                 }
415
416                 /* the current thread _has_ to be in the active list */
417                 assert (NULL != ptr);
418
419                 if (NULL == last) {
420                         active.head = ptr->next;
421                 }
422                 else {
423                         last->next = ptr->next;
424
425                         if (NULL == last->next) {
426                                 active.tail = last;
427                         }
428                 }
429         }
430         pthread_mutex_unlock (&active_mutex);
431
432         this->next = NULL;
433
434         pthread_mutex_lock (&available_mutex);
435
436         if (NULL == available.head) {
437                 available.head = this;
438                 available.tail = this;
439         }
440         else {
441                 available.tail->next = this;
442                 available.tail = this;
443         }
444
445         pthread_mutex_unlock (&available_mutex);
446
447         pthread_cond_signal (&collector_available);
448         pthread_exit ((void *)0);
449 } /* void *collect (void *) */
450
451 static void *open_connection (void *arg)
452 {
453         int local = 0;
454
455         struct sockaddr_un addr;
456
457         /* create UNIX socket */
458         errno = 0;
459         if (-1 == (local = socket (PF_UNIX, SOCK_STREAM, 0))) {
460                 disabled = 1;
461                 syslog (LOG_ERR, "socket() failed: %s", strerror (errno));
462                 pthread_exit ((void *)1);
463         }
464
465         addr.sun_family = AF_UNIX;
466
467         strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
468         addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
469         unlink (addr.sun_path);
470
471         errno = 0;
472         if (-1 == bind (local, (struct sockaddr *)&addr,
473                                 offsetof (struct sockaddr_un, sun_path) 
474                                         + strlen(addr.sun_path))) {
475                 disabled = 1;
476                 syslog (LOG_ERR, "bind() failed: %s", strerror (errno));
477                 pthread_exit ((void *)1);
478         }
479
480         errno = 0;
481         if (-1 == listen (local, 5)) {
482                 disabled = 1;
483                 syslog (LOG_ERR, "listen() failed: %s", strerror (errno));
484                 pthread_exit ((void *)1);
485         }
486
487         { /* initialize queue of available threads */
488                 int i = 0;
489
490                 collector_t *last;
491
492                 active.head = NULL;
493                 active.tail = NULL;
494
495                 available.head = (collector_t *)smalloc (sizeof (collector_t));
496                 available.tail = available.head;
497                 available.tail->next = NULL;
498
499                 last = available.head;
500
501                 for (i = 1; i < MAX_CONNS; ++i) {
502                         last->next = (collector_t *)smalloc (sizeof (collector_t));
503                         last = last->next;
504                         available.tail = last;
505                         available.tail->next = NULL;
506                 }
507         }
508
509         while (1) {
510                 int remote = 0;
511                 int err    = 0;
512
513                 collector_t *collector;
514
515                 pthread_attr_t ptattr;
516
517                 pthread_mutex_lock (&available_mutex);
518                 while (NULL == available.head) {
519                         pthread_cond_wait (&collector_available, &available_mutex);
520                 }
521                 pthread_mutex_unlock (&available_mutex);
522
523                 do {
524                         errno = 0;
525                         if (-1 == (remote = accept (local, NULL, NULL))) {
526                                 if (EINTR != errno) {
527                                         disabled = 1;
528                                         syslog (LOG_ERR, "accept() failed: %s", strerror (errno));
529                                         pthread_exit ((void *)1);
530                                 }
531                         }
532                 } while (EINTR == errno);
533
534                 /* assign connection to next available thread */
535                 pthread_mutex_lock (&available_mutex);
536
537                 collector = available.head;
538                 collector->socket = remote;
539
540                 if (available.head == available.tail) {
541                         available.head = NULL;
542                         available.tail = NULL;
543                 }
544                 else {
545                         available.head = available.head->next;
546                 }
547
548                 pthread_mutex_unlock (&available_mutex);
549
550                 collector->idx  = 0;
551                 collector->next = NULL;
552
553                 pthread_attr_init (&ptattr);
554                 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
555
556                 if (0 == (err = pthread_create (&collector->thread, &ptattr, collect, 
557                                 (void *)collector))) {
558                         pthread_mutex_lock (&active_mutex);
559
560                         if (NULL == active.head) {
561                                 active.head = collector;
562                                 active.tail = collector;
563                         }
564                         else {
565                                 active.tail->next = collector;
566                                 active.tail = collector;
567                         }
568
569                         pthread_mutex_unlock (&active_mutex);
570                 }
571                 else {
572                         pthread_mutex_lock (&available_mutex);
573
574                         if (NULL == available.head) {
575                                 available.head = collector;
576                                 available.tail = collector;
577                         }
578                         else {
579                                 available.tail->next = collector;
580                                 available.tail = collector;
581                         }
582
583                         pthread_mutex_unlock (&available_mutex);
584
585                         close (remote);
586                         syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
587                 }
588
589                 pthread_attr_destroy (&ptattr);
590         }
591         pthread_exit ((void *)0);
592 } /* void *open_connection (void *) */
593
594 static void email_init (void)
595 {
596         int err = 0;
597
598         if (0 != (err = pthread_create (&connector, NULL, 
599                                 open_connection, NULL))) {
600                 disabled = 1;
601                 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
602                 return;
603         }
604         return;
605 } /* static void email_init (void) */
606
607 static void count_write (char *host, char *inst, char *val)
608 {
609         char file[BUFSIZE] = "";
610         int  len           = 0;
611
612         len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
613         if ((len < 0) || (len >= BUFSIZE))
614                 return;
615
616         rrd_update_file (host, file, val, count_ds_def, count_ds_num);
617         return;
618 } /* static void email_write (char *host, char *inst, char *val) */
619
620 static void size_write (char *host, char *inst, char *val)
621 {
622         char file[BUFSIZE] = "";
623         int  len           = 0;
624
625         len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
626         if ((len < 0) || (len >= BUFSIZE))
627                 return;
628
629         rrd_update_file (host, file, val, size_ds_def, size_ds_num);
630         return;
631 } /* static void size_write (char *host, char *inst, char *val) */
632
633 static void score_write (char *host, char *inst, char *val)
634 {
635         rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
636         return;
637 } /* static void score_write (char *host, char *inst, char *val) */
638
639 static void check_write (char *host, char *inst, char *val)
640 {
641         char file[BUFSIZE] = "";
642         int  len           = 0;
643
644         len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
645         if ((len < 0) || (len >= BUFSIZE))
646                 return;
647
648         rrd_update_file (host, file, val, check_ds_def, check_ds_num);
649         return;
650 } /* static void check_write (char *host, char *inst, char *val) */
651
652 static void type_submit (char *plugin, char *inst, int value)
653 {
654         char buf[BUFSIZE] = "";
655         int  len          = 0;
656
657         if (0 == value)
658                 return;
659
660         len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
661         if ((len < 0) || (len >= BUFSIZE))
662                 return;
663
664         plugin_submit (plugin, inst, buf);
665 fprintf(stderr, "plugin_submit (\"%s\", \"%s\", \"%s\")\n", plugin, inst, buf);
666         return;
667 } /* static void type_submit (char *, char *, int) */
668
669 static void score_submit (double value)
670 {
671         char buf[BUFSIZE] = "";
672         int  len          = 0;
673
674         if (0.0 == value)
675                 return;
676
677         len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
678         if ((len < 0) || (len >= BUFSIZE))
679                 return;
680
681         plugin_submit ("email_spam_score", NULL, buf);
682 fprintf(stderr, "plugin_submit (\"%s\", \"%s\", \"%s\")\n", "email_spam_score", "\0", buf);
683         return;
684 }
685
686 static void email_read (void)
687 {
688         type_t *ptr;
689
690         if (disabled)
691                 return;
692
693         pthread_mutex_lock (&count_mutex);
694
695         for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
696                 type_submit ("email_count", ptr->name, ptr->value);
697                 ptr->value = 0;
698         }
699
700         pthread_mutex_unlock (&count_mutex);
701
702         pthread_mutex_lock (&size_mutex);
703
704         for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
705                 type_submit ("email_size", ptr->name, ptr->value);
706                 ptr->value = 0;
707         }
708
709         pthread_mutex_unlock (&size_mutex);
710
711         pthread_mutex_lock (&score_mutex);
712
713         score_submit (score);
714         score = 0.0;
715         score_count = 0;
716
717         pthread_mutex_unlock (&score_mutex);
718
719         pthread_mutex_lock (&check_mutex);
720
721         for (ptr = check.head; NULL != ptr; ptr = ptr->next) {
722                 type_submit ("email_spam_check", ptr->name, ptr->value);
723                 ptr->value = 0;
724         }
725
726         pthread_mutex_unlock (&check_mutex);
727         return;
728 } /* static void read (void) */
729
730 void module_register (void)
731 {
732         plugin_register (MODULE_NAME, email_init, email_read, NULL);
733         plugin_register ("email_count", NULL, NULL, count_write);
734         plugin_register ("email_size", NULL, NULL, size_write);
735         plugin_register ("email_spam_score", NULL, NULL, score_write);
736         plugin_register ("email_spam_check", NULL, NULL, check_write);
737         return;
738 } /* void module_register (void) */
739
740 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
741