Code

email plugin: Change owner and mode of the UNIX socket if possible.
[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 *type = strtok (line + 2, ":");
365                         char *tmp  = strtok (NULL, ":");
366                         int  bytes = 0;
368                         if (NULL == tmp) {
369                                 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
370                                 free (line);
371                                 continue;
372                         }
374                         bytes = atoi (tmp);
376                         pthread_mutex_lock (&count_mutex);
377                         type_list_incr (&count, type, 1);
378                         pthread_mutex_unlock (&count_mutex);
380                         pthread_mutex_lock (&size_mutex);
381                         type_list_incr (&size, type, bytes);
382                         pthread_mutex_unlock (&size_mutex);
383                 }
384                 else if ('s' == line[0]) { /* s:<value> */
385                         pthread_mutex_lock (&score_mutex);
386                         score = (score * (double)score_count + atof (line + 2))
387                                         / (double)(score_count + 1);
388                         ++score_count;
389                         pthread_mutex_unlock (&score_mutex);
390                 }
391                 else if ('c' == line[0]) { /* c:<type1>[,<type2>,...] */
392                         char *type = strtok (line + 2, ",");
394                         do {
395                                 pthread_mutex_lock (&check_mutex);
396                                 type_list_incr (&check, type, 1);
397                                 pthread_mutex_unlock (&check_mutex);
398                         } while (NULL != (type = strtok (NULL, ",")));
399                 }
400                 else {
401                         syslog (LOG_ERR, "email: unknown type '%c'", line[0]);
402                 }
404                 free (line);
405         }
407         /* put this thread back into the available list */
408         pthread_mutex_lock (&active_mutex);
409         {
410                 collector_t *last;
411                 collector_t *ptr;
413                 last = NULL;
415                 for (ptr = active.head; NULL != ptr; last = ptr, ptr = ptr->next) {
416                         if (0 != pthread_equal (ptr->thread, this->thread))
417                                 break;
418                 }
420                 /* the current thread _has_ to be in the active list */
421                 assert (NULL != ptr);
423                 if (NULL == last) {
424                         active.head = ptr->next;
425                 }
426                 else {
427                         last->next = ptr->next;
429                         if (NULL == last->next) {
430                                 active.tail = last;
431                         }
432                 }
433         }
434         pthread_mutex_unlock (&active_mutex);
436         this->next = NULL;
438         pthread_mutex_lock (&available_mutex);
440         if (NULL == available.head) {
441                 available.head = this;
442                 available.tail = this;
443         }
444         else {
445                 available.tail->next = this;
446                 available.tail = this;
447         }
449         pthread_mutex_unlock (&available_mutex);
451         pthread_cond_signal (&collector_available);
452         pthread_exit ((void *)0);
453 } /* void *collect (void *) */
455 static void *open_connection (void *arg)
457         int local = 0;
459         struct sockaddr_un addr;
461         /* create UNIX socket */
462         errno = 0;
463         if (-1 == (local = socket (PF_UNIX, SOCK_STREAM, 0))) {
464                 disabled = 1;
465                 syslog (LOG_ERR, "socket() failed: %s", strerror (errno));
466                 pthread_exit ((void *)1);
467         }
469         addr.sun_family = AF_UNIX;
471         strncpy (addr.sun_path, SOCK_PATH, (size_t)(UNIX_PATH_MAX - 1));
472         addr.sun_path[UNIX_PATH_MAX - 1] = '\0';
473         unlink (addr.sun_path);
475         errno = 0;
476         if (-1 == bind (local, (struct sockaddr *)&addr,
477                                 offsetof (struct sockaddr_un, sun_path)
478                                         + strlen(addr.sun_path))) {
479                 disabled = 1;
480                 syslog (LOG_ERR, "bind() failed: %s", strerror (errno));
481                 pthread_exit ((void *)1);
482         }
484         errno = 0;
485         if (-1 == listen (local, 5)) {
486                 disabled = 1;
487                 syslog (LOG_ERR, "listen() failed: %s", strerror (errno));
488                 pthread_exit ((void *)1);
489         }
491         if ((uid_t)0 == geteuid ()) {
492                 struct group *grp;
494                 errno = 0;
495                 if (NULL != (grp = getgrnam (COLLECTD_GRP_NAME))) {
496                         errno = 0;
497                         if (0 != chown (SOCK_PATH, (uid_t)-1, grp->gr_gid)) {
498                                 syslog (LOG_WARNING, "chown() failed: %s", strerror (errno));
499                         }
500                 }
501                 else {
502                         syslog (LOG_WARNING, "getgrnam() failed: %s", strerror (errno));
503                 }
504         }
505         else {
506                 syslog (LOG_WARNING, "not running as root");
507         }
509         errno = 0;
510         if (0 != chmod (SOCK_PATH, S_IRWXU | S_IRWXG)) {
511                 syslog (LOG_WARNING, "chmod() failed: %s", strerror (errno));
512         }
514         { /* initialize queue of available threads */
515                 int i = 0;
517                 collector_t *last;
519                 active.head = NULL;
520                 active.tail = NULL;
522                 available.head = (collector_t *)smalloc (sizeof (collector_t));
523                 available.tail = available.head;
524                 available.tail->next = NULL;
526                 last = available.head;
528                 for (i = 1; i < MAX_CONNS; ++i) {
529                         last->next = (collector_t *)smalloc (sizeof (collector_t));
530                         last = last->next;
531                         available.tail = last;
532                         available.tail->next = NULL;
533                 }
534         }
536         while (1) {
537                 int remote = 0;
538                 int err    = 0;
540                 collector_t *collector;
542                 pthread_attr_t ptattr;
544                 pthread_mutex_lock (&available_mutex);
545                 while (NULL == available.head) {
546                         pthread_cond_wait (&collector_available, &available_mutex);
547                 }
548                 pthread_mutex_unlock (&available_mutex);
550                 do {
551                         errno = 0;
552                         if (-1 == (remote = accept (local, NULL, NULL))) {
553                                 if (EINTR != errno) {
554                                         disabled = 1;
555                                         syslog (LOG_ERR, "accept() failed: %s", strerror (errno));
556                                         pthread_exit ((void *)1);
557                                 }
558                         }
559                 } while (EINTR == errno);
561                 /* assign connection to next available thread */
562                 pthread_mutex_lock (&available_mutex);
564                 collector = available.head;
565                 collector->socket = remote;
567                 if (available.head == available.tail) {
568                         available.head = NULL;
569                         available.tail = NULL;
570                 }
571                 else {
572                         available.head = available.head->next;
573                 }
575                 pthread_mutex_unlock (&available_mutex);
577                 collector->idx  = 0;
578                 collector->next = NULL;
580                 pthread_attr_init (&ptattr);
581                 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
583                 if (0 == (err = pthread_create (&collector->thread, &ptattr, collect,
584                                 (void *)collector))) {
585                         pthread_mutex_lock (&active_mutex);
587                         if (NULL == active.head) {
588                                 active.head = collector;
589                                 active.tail = collector;
590                         }
591                         else {
592                                 active.tail->next = collector;
593                                 active.tail = collector;
594                         }
596                         pthread_mutex_unlock (&active_mutex);
597                 }
598                 else {
599                         pthread_mutex_lock (&available_mutex);
601                         if (NULL == available.head) {
602                                 available.head = collector;
603                                 available.tail = collector;
604                         }
605                         else {
606                                 available.tail->next = collector;
607                                 available.tail = collector;
608                         }
610                         pthread_mutex_unlock (&available_mutex);
612                         close (remote);
613                         syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
614                 }
616                 pthread_attr_destroy (&ptattr);
617         }
618         pthread_exit ((void *)0);
619 } /* void *open_connection (void *) */
621 static void email_init (void)
623         int err = 0;
625         if (0 != (err = pthread_create (&connector, NULL,
626                                 open_connection, NULL))) {
627                 disabled = 1;
628                 syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
629                 return;
630         }
631         return;
632 } /* static void email_init (void) */
634 static void count_write (char *host, char *inst, char *val)
636         char file[BUFSIZE] = "";
637         int  len           = 0;
639         len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
640         if ((len < 0) || (len >= BUFSIZE))
641                 return;
643         rrd_update_file (host, file, val, count_ds_def, count_ds_num);
644         return;
645 } /* static void email_write (char *host, char *inst, char *val) */
647 static void size_write (char *host, char *inst, char *val)
649         char file[BUFSIZE] = "";
650         int  len           = 0;
652         len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
653         if ((len < 0) || (len >= BUFSIZE))
654                 return;
656         rrd_update_file (host, file, val, size_ds_def, size_ds_num);
657         return;
658 } /* static void size_write (char *host, char *inst, char *val) */
660 static void score_write (char *host, char *inst, char *val)
662         rrd_update_file (host, SCORE_FILE, val, score_ds_def, score_ds_num);
663         return;
664 } /* static void score_write (char *host, char *inst, char *val) */
666 static void check_write (char *host, char *inst, char *val)
668         char file[BUFSIZE] = "";
669         int  len           = 0;
671         len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
672         if ((len < 0) || (len >= BUFSIZE))
673                 return;
675         rrd_update_file (host, file, val, check_ds_def, check_ds_num);
676         return;
677 } /* static void check_write (char *host, char *inst, char *val) */
679 static void type_submit (char *plugin, char *inst, int value)
681         char buf[BUFSIZE] = "";
682         int  len          = 0;
684         if (0 == value)
685                 return;
687         len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
688         if ((len < 0) || (len >= BUFSIZE))
689                 return;
691         plugin_submit (plugin, inst, buf);
692         return;
693 } /* static void type_submit (char *, char *, int) */
695 static void score_submit (double value)
697         char buf[BUFSIZE] = "";
698         int  len          = 0;
700         if (0.0 == value)
701                 return;
703         len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
704         if ((len < 0) || (len >= BUFSIZE))
705                 return;
707         plugin_submit ("email_spam_score", NULL, buf);
708         return;
711 static void email_read (void)
713         type_t *ptr;
715         if (disabled)
716                 return;
718         pthread_mutex_lock (&count_mutex);
720         for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
721                 type_submit ("email_count", ptr->name, ptr->value);
722                 ptr->value = 0;
723         }
725         pthread_mutex_unlock (&count_mutex);
727         pthread_mutex_lock (&size_mutex);
729         for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
730                 type_submit ("email_size", ptr->name, ptr->value);
731                 ptr->value = 0;
732         }
734         pthread_mutex_unlock (&size_mutex);
736         pthread_mutex_lock (&score_mutex);
738         score_submit (score);
739         score = 0.0;
740         score_count = 0;
742         pthread_mutex_unlock (&score_mutex);
744         pthread_mutex_lock (&check_mutex);
746         for (ptr = check.head; NULL != ptr; ptr = ptr->next) {
747                 type_submit ("email_spam_check", ptr->name, ptr->value);
748                 ptr->value = 0;
749         }
751         pthread_mutex_unlock (&check_mutex);
752         return;
753 } /* static void read (void) */
755 void module_register (void)
757         plugin_register (MODULE_NAME, email_init, email_read, NULL);
758         plugin_register ("email_count", NULL, NULL, count_write);
759         plugin_register ("email_size", NULL, NULL, size_write);
760         plugin_register ("email_spam_score", NULL, NULL, score_write);
761         plugin_register ("email_spam_check", NULL, NULL, check_write);
762         return;
763 } /* void module_register (void) */
765 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */