Code

Merge branches 'ff/dns' and 'sh/email' into next
[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  **/
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  */
37 #include "collectd.h"
38 #include "common.h"
39 #include "plugin.h"
41 #include <pthread.h>
43 #if HAVE_SYS_SELECT_H
44 #       include <sys/select.h>
45 #endif /* HAVE_SYS_SELECT_H */
47 #if HAVE_SYS_SOCKET_H
48 #       include <sys/socket.h>
49 #endif /* HAVE_SYS_SOCKET_H */
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 */
58 #if HAVE_GRP_H
59 #       include <grp.h>
60 #endif /* HAVE_GRP_H */
62 #define MODULE_NAME "email"
64 /* 256 bytes ought to be enough for anybody ;-) */
65 #define BUFSIZE 256
67 #define SOCK_PATH "/tmp/.collectd-email"
68 #define MAX_CONNS 5
70 /* linked list of email and check types */
71 typedef struct type {
72         char        *name;
73         int         value;
74         struct type *next;
75 } type_t;
77 typedef struct {
78         type_t *head;
79         type_t *tail;
80 } type_list_t;
82 /* linked list of collector thread control information */
83 typedef struct collector {
84         pthread_t thread;
86         /* socket to read data from */
87         int socket;
89         /* buffer to read data to */
90         char buffer[BUFSIZE];
91         int  idx; /* current position in buffer */
93         struct collector *next;
94 } collector_t;
96 typedef struct {
97         collector_t *head;
98         collector_t *tail;
99 } collector_list_t;
101 /* state of the plugin */
102 static int disabled = 0;
104 /* thread managing "client" connections */
105 static pthread_t connector;
107 /* tell the connector thread that a collector is available */
108 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
110 /* collector threads that are in use */
111 static pthread_mutex_t active_mutex = PTHREAD_MUTEX_INITIALIZER;
112 static collector_list_t active;
114 /* collector threads that are available for use */
115 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
116 static collector_list_t available;
118 #define COUNT_FILE "email/email-%s.rrd"
119 static char *count_ds_def[] =
121         "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
122         NULL
123 };
124 static int count_ds_num = 1;
126 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
127 static type_list_t count;
129 #define SIZE_FILE  "email/email_size-%s.rrd"
130 static char *size_ds_def[] =
132         "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
133         NULL
134 };
135 static int size_ds_num = 1;
137 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
138 static type_list_t size;
140 #define SCORE_FILE "email/spam_score.rrd"
141 static char *score_ds_def[] =
143         "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
144         NULL
145 };
146 static int score_ds_num = 1;
148 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
149 static double score;
150 static int score_count;
152 #define CHECK_FILE "email/spam_check-%s.rrd"
153 static char *check_ds_def[] =
155         "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
156         NULL
157 };
158 static int check_ds_num = 1;
160 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
161 static type_list_t check;
163 /* Increment the value of the given name in the given list by incr. */
164 static void type_list_incr (type_list_t *list, char *name, int incr)
166         if (NULL == list->head) {
167                 list->head = (type_t *)smalloc (sizeof (type_t));
169                 list->head->name  = sstrdup (name);
170                 list->head->value = incr;
171                 list->head->next  = NULL;
173                 list->tail = list->head;
174         }
175         else {
176                 type_t *ptr;
178                 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
179                         if (0 == strcmp (name, ptr->name))
180                                 break;
181                 }
183                 if (NULL == ptr) {
184                         list->tail->next = (type_t *)smalloc (sizeof (type_t));
185                         list->tail = list->tail->next;
187                         list->tail->name  = sstrdup (name);
188                         list->tail->value = incr;
189                         list->tail->next  = NULL;
190                 }
191                 else {
192                         ptr->value += incr;
193                 }
194         }
195         return;
196 } /* static void type_list_incr (type_list_t *, char *) */
198 /* Read a single character from the socket. If an error occurs or end-of-file
199  * is reached return '\0'. */
200 char read_char (collector_t *src)
202         char ret = '\0';
204         fd_set fdset;
206         FD_ZERO (&fdset);
207         FD_SET (src->socket, &fdset);
209         if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
210                 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
211                 return '\0';
212         }
214         assert (FD_ISSET (src->socket, &fdset));
216         do {
217                 ssize_t len = 0;
219                 errno = 0;
220                 if (0 > (len = read (src->socket, (void *)&ret, 1))) {
221                         if (EINTR != errno) {
222                                 syslog (LOG_ERR, "read() failed: %s", strerror (errno));
223                                 return '\0';
224                         }
225                 }
227                 if (0 == len)
228                         return '\0';
229         } while (EINTR == errno);
230         return ret;
231 } /* char read_char (collector_t *) */
233 /* Read a single line (terminated by '\n') from the the socket.
234  *
235  * The return value is zero terminated and does not contain any newline
236  * characters. In case that no complete line is available (non-blocking mode
237  * should be enabled) an empty string is returned.
238  *
239  * If an error occurs or end-of-file is reached return NULL.
240  *
241  * IMPORTANT NOTE: If there is no newline character found in BUFSIZE
242  * characters of the input stream, the line will will be ignored! By
243  * definition we should not get any longer input lines, thus this is
244  * acceptable in this case ;-) */
245 char *read_line (collector_t *src)
247         int  i = 0;
248         char *ret;
250         assert (BUFSIZE > src->idx);
252         for (i = 0; i < src->idx; ++i) {
253                 if ('\n' == src->buffer[i])
254                         break;
255         }
257         if ('\n' != src->buffer[i]) {
258                 fd_set fdset;
259         
260                 ssize_t len = 0;
262                 FD_ZERO (&fdset);
263                 FD_SET (src->socket, &fdset);
265                 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
266                         syslog (LOG_ERR, "select() failed: %s", strerror (errno));
267                         return NULL;
268                 }
270                 assert (FD_ISSET (src->socket, &fdset));
272                 do {
273                         errno = 0;
274                         if (0 > (len = read (src->socket,
275                                                         (void *)(&(src->buffer[0]) + src->idx),
276                                                         BUFSIZE - src->idx))) {
277                                 if (EINTR != errno) {
278                                         syslog (LOG_ERR, "read() failed: %s", strerror (errno));
279                                         return NULL;
280                                 }
281                         }
283                         if (0 == len)
284                                 return NULL;
285                 } while (EINTR == errno);
287                 src->idx += len;
289                 for (i = src->idx - len; i < src->idx; ++i) {
290                         if ('\n' == src->buffer[i])
291                                 break;
292                 }
294                 if ('\n' != src->buffer[i]) {
295                         ret = (char *)smalloc (1);
297                         ret[0] = '\0';
299                         if (BUFSIZE == src->idx) { /* no space left in buffer */
300                                 while ('\n' != read_char (src))
301                                         /* ignore complete line */;
303                                 src->idx = 0;
304                         }
305                         return ret;
306                 }
307         }
309         ret = (char *)smalloc (i + 1);
310         memcpy (ret, &(src->buffer[0]), i + 1);
311         ret[i] = '\0';
313         src->idx -= (i + 1);
315         if (0 == src->idx)
316                 src->buffer[0] = '\0';
317         else
318                 memmove (&(src->buffer[0]), &(src->buffer[i + 1]), src->idx);
319         return ret;
320 } /* char *read_line (collector_t *) */
322 static void *collect (void *arg)
324         collector_t *this = (collector_t *)arg;
325         
326         int loop = 1;
328         { /* put the socket in non-blocking mode */
329                 int flags = 0;
331                 errno = 0;
332                 if (-1 == fcntl (this->socket, F_GETFL, &flags)) {
333                         syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
334                         loop = 0;
335                 }
337                 errno = 0;
338                 if (-1 == fcntl (this->socket, F_SETFL, flags | O_NONBLOCK)) {
339                         syslog (LOG_ERR, "fcntl() failed: %s", strerror (errno));
340                         loop = 0;
341                 }
342         }
344         while (loop) {
345                 char *line = read_line (this);
347                 if (NULL == line) {
348                         loop = 0;
349                         break;
350                 }
352                 if ('\0' == line[0]) {
353                         free (line);
354                         continue;
355                 }
357                 if (':' != line[1]) {
358                         syslog (LOG_ERR, "email: syntax error in line '%s'", line);
359                         free (line);
360                         continue;
361                 }
363                 if ('e' == line[0]) { /* e:<type>:<bytes> */
364                         char *ptr  = NULL;
365                         char *type = strtok_r (line + 2, ":", &ptr);
366                         char *tmp  = strtok_r (NULL, ":", &ptr);
367                         int  bytes = 0;
369                         if (NULL == tmp) {
370                                 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
371                                 free (line);
372                                 continue;
373                         }
375                         bytes = atoi (tmp);
377                         pthread_mutex_lock (&count_mutex);
378                         type_list_incr (&count, type, 1);
379                         pthread_mutex_unlock (&count_mutex);
381                         pthread_mutex_lock (&size_mutex);
382                         type_list_incr (&size, type, bytes);
383                         pthread_mutex_unlock (&size_mutex);
384                 }
385                 else if ('s' == line[0]) { /* s:<value> */
386                         pthread_mutex_lock (&score_mutex);
387                         score = (score * (double)score_count + atof (line + 2))
388                                         / (double)(score_count + 1);
389                         ++score_count;
390                         pthread_mutex_unlock (&score_mutex);
391                 }
392                 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
393                         char *ptr  = NULL;
394                         char *type = strtok_r (line + 2, ",", &ptr);
396                         do {
397                                 pthread_mutex_lock (&check_mutex);
398                                 type_list_incr (&check, type, 1);
399                                 pthread_mutex_unlock (&check_mutex);
400                         } while (NULL != (type = strtok_r (NULL, ",", &ptr)));
401                 }
402                 else {
403                         syslog (LOG_ERR, "email: unknown type '%c'", line[0]);
404                 }
406                 free (line);
407         }
409         /* put this thread back into the available list */
410         pthread_mutex_lock (&active_mutex);
411         {
412                 collector_t *last;
413                 collector_t *ptr;
415                 last = NULL;
417                 for (ptr = active.head; NULL != ptr; last = ptr, ptr = ptr->next) {
418                         if (0 != pthread_equal (ptr->thread, this->thread))
419                                 break;
420                 }
422                 /* the current thread _has_ to be in the active list */
423                 assert (NULL != ptr);
425                 if (NULL == last) {
426                         active.head = ptr->next;
427                 }
428                 else {
429                         last->next = ptr->next;
431                         if (NULL == last->next) {
432                                 active.tail = last;
433                         }
434                 }
435         }
436         pthread_mutex_unlock (&active_mutex);
438         this->next = NULL;
440         pthread_mutex_lock (&available_mutex);
442         if (NULL == available.head) {
443                 available.head = this;
444                 available.tail = this;
445         }
446         else {
447                 available.tail->next = this;
448                 available.tail = this;
449         }
451         pthread_mutex_unlock (&available_mutex);
453         pthread_cond_signal (&collector_available);
454         pthread_exit ((void *)0);
455 } /* void *collect (void *) */
457 static void *open_connection (void *arg)
459         int local = 0;
461         struct sockaddr_un addr;
463         /* create UNIX socket */
464         errno = 0;
465         if (-1 == (local = socket (PF_UNIX, SOCK_STREAM, 0))) {
466                 disabled = 1;
467                 syslog (LOG_ERR, "socket() failed: %s", strerror (errno));
468                 pthread_exit ((void *)1);
469         }
471         addr.sun_family = AF_UNIX;
473         strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
474         addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
475         unlink (addr.sun_path);
477         errno = 0;
478         if (-1 == bind (local, (struct sockaddr *)&addr,
479                                 offsetof (struct sockaddr_un, sun_path)
480                                         + strlen(addr.sun_path))) {
481                 disabled = 1;
482                 syslog (LOG_ERR, "bind() failed: %s", strerror (errno));
483                 pthread_exit ((void *)1);
484         }
486         errno = 0;
487         if (-1 == listen (local, 5)) {
488                 disabled = 1;
489                 syslog (LOG_ERR, "listen() failed: %s", strerror (errno));
490                 pthread_exit ((void *)1);
491         }
493         if ((uid_t)0 == geteuid ()) {
494                 struct group *grp;
496                 errno = 0;
497                 if (NULL != (grp = getgrnam (COLLECTD_GRP_NAME))) {
498                         errno = 0;
499                         if (0 != chown (SOCK_PATH, (uid_t)-1, grp->gr_gid)) {
500                                 syslog (LOG_WARNING, "chown() failed: %s", strerror (errno));
501                         }
502                 }
503                 else {
504                         syslog (LOG_WARNING, "getgrnam() failed: %s", strerror (errno));
505                 }
506         }
507         else {
508                 syslog (LOG_WARNING, "not running as root");
509         }
511         errno = 0;
512         if (0 != chmod (SOCK_PATH, S_IRWXU | S_IRWXG)) {
513                 syslog (LOG_WARNING, "chmod() failed: %s", strerror (errno));
514         }
516         { /* initialize queue of available threads */
517                 int i = 0;
519                 collector_t *last;
521                 active.head = NULL;
522                 active.tail = NULL;
524                 available.head = (collector_t *)smalloc (sizeof (collector_t));
525                 available.tail = available.head;
526                 available.tail->next = NULL;
528                 last = available.head;
530                 for (i = 1; i < MAX_CONNS; ++i) {
531                         last->next = (collector_t *)smalloc (sizeof (collector_t));
532                         last = last->next;
533                         available.tail = last;
534                         available.tail->next = NULL;
535                 }
536         }
538         while (1) {
539                 int remote = 0;
540                 int err    = 0;
542                 collector_t *collector;
544                 pthread_attr_t ptattr;
546                 pthread_mutex_lock (&available_mutex);
547                 while (NULL == available.head) {
548                         pthread_cond_wait (&collector_available, &available_mutex);
549                 }
550                 pthread_mutex_unlock (&available_mutex);
552                 do {
553                         errno = 0;
554                         if (-1 == (remote = accept (local, NULL, NULL))) {
555                                 if (EINTR != errno) {
556                                         disabled = 1;
557                                         syslog (LOG_ERR, "accept() failed: %s", strerror (errno));
558                                         pthread_exit ((void *)1);
559                                 }
560                         }
561                 } while (EINTR == errno);
563                 /* assign connection to next available thread */
564                 pthread_mutex_lock (&available_mutex);
566                 collector = available.head;
567                 collector->socket = remote;
569                 if (available.head == available.tail) {
570                         available.head = NULL;
571                         available.tail = NULL;
572                 }
573                 else {
574                         available.head = available.head->next;
575                 }
577                 pthread_mutex_unlock (&available_mutex);
579                 collector->idx  = 0;
580                 collector->next = NULL;
582                 pthread_attr_init (&ptattr);
583                 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
585                 if (0 == (err = pthread_create (&collector->thread, &ptattr, collect,
586                                 (void *)collector))) {
587                         pthread_mutex_lock (&active_mutex);
589                         if (NULL == active.head) {
590                                 active.head = collector;
591                                 active.tail = collector;
592                         }
593                         else {
594                                 active.tail->next = collector;
595                                 active.tail = collector;
596                         }
598                         pthread_mutex_unlock (&active_mutex);
599                 }
600                 else {
601                         pthread_mutex_lock (&available_mutex);
603                         if (NULL == available.head) {
604                                 available.head = collector;
605                                 available.tail = collector;
606                         }
607                         else {
608                                 available.tail->next = collector;
609                                 available.tail = collector;
610                         }
612                         pthread_mutex_unlock (&available_mutex);
614                         close (remote);
615                         syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
616                 }
618                 pthread_attr_destroy (&ptattr);
619         }
620         pthread_exit ((void *)0);
621 } /* void *open_connection (void *) */
623 static void email_init (void)
625         int err = 0;
627         if (0 != (err = pthread_create (&connector, NULL,
628                                 open_connection, NULL))) {
629                 disabled = 1;
630                 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
631                 return;
632         }
633         return;
634 } /* static void email_init (void) */
636 static void count_write (char *host, char *inst, char *val)
638         char file[BUFSIZE] = "";
639         int  len           = 0;
641         len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
642         if ((len < 0) || (len >= BUFSIZE))
643                 return;
645         rrd_update_file (host, file, val, count_ds_def, count_ds_num);
646         return;
647 } /* static void email_write (char *host, char *inst, char *val) */
649 static void size_write (char *host, char *inst, char *val)
651         char file[BUFSIZE] = "";
652         int  len           = 0;
654         len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
655         if ((len < 0) || (len >= BUFSIZE))
656                 return;
658         rrd_update_file (host, file, val, size_ds_def, size_ds_num);
659         return;
660 } /* static void size_write (char *host, char *inst, char *val) */
662 static void score_write (char *host, char *inst, char *val)
664         rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
665         return;
666 } /* static void score_write (char *host, char *inst, char *val) */
668 static void check_write (char *host, char *inst, char *val)
670         char file[BUFSIZE] = "";
671         int  len           = 0;
673         len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
674         if ((len < 0) || (len >= BUFSIZE))
675                 return;
677         rrd_update_file (host, file, val, check_ds_def, check_ds_num);
678         return;
679 } /* static void check_write (char *host, char *inst, char *val) */
681 static void type_submit (char *plugin, char *inst, int value)
683         char buf[BUFSIZE] = "";
684         int  len          = 0;
686         if (0 == value)
687                 return;
689         len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
690         if ((len < 0) || (len >= BUFSIZE))
691                 return;
693         plugin_submit (plugin, inst, buf);
694         return;
695 } /* static void type_submit (char *, char *, int) */
697 static void score_submit (double value)
699         char buf[BUFSIZE] = "";
700         int  len          = 0;
702         if (0.0 == value)
703                 return;
705         len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
706         if ((len < 0) || (len >= BUFSIZE))
707                 return;
709         plugin_submit ("email_spam_score", NULL, buf);
710         return;
713 static void email_read (void)
715         type_t *ptr;
717         if (disabled)
718                 return;
720         pthread_mutex_lock (&count_mutex);
722         for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
723                 type_submit ("email_count", ptr->name, ptr->value);
724                 ptr->value = 0;
725         }
727         pthread_mutex_unlock (&count_mutex);
729         pthread_mutex_lock (&size_mutex);
731         for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
732                 type_submit ("email_size", ptr->name, ptr->value);
733                 ptr->value = 0;
734         }
736         pthread_mutex_unlock (&size_mutex);
738         pthread_mutex_lock (&score_mutex);
740         score_submit (score);
741         score = 0.0;
742         score_count = 0;
744         pthread_mutex_unlock (&score_mutex);
746         pthread_mutex_lock (&check_mutex);
748         for (ptr = check.head; NULL != ptr; ptr = ptr->next) {
749                 type_submit ("email_spam_check", ptr->name, ptr->value);
750                 ptr->value = 0;
751         }
753         pthread_mutex_unlock (&check_mutex);
754         return;
755 } /* static void read (void) */
757 void module_register (void)
759         plugin_register (MODULE_NAME, email_init, email_read, NULL);
760         plugin_register ("email_count", NULL, NULL, count_write);
761         plugin_register ("email_size", NULL, NULL, size_write);
762         plugin_register ("email_spam_score", NULL, NULL, score_write);
763         plugin_register ("email_spam_check", NULL, NULL, check_write);
764         return;
765 } /* void module_register (void) */
767 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */