email plugin: Use strtok_r() instead of strtok().
[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 #if HAVE_GRP_H
59 #       include <grp.h>
60 #endif /* HAVE_GRP_H */
61
62 #define MODULE_NAME "email"
63
64 /* 256 bytes ought to be enough for anybody ;-) */
65 #define BUFSIZE 256
66
67 #define SOCK_PATH "/tmp/.collectd-email"
68 #define MAX_CONNS 5
69
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;
76
77 typedef struct {
78         type_t *head;
79         type_t *tail;
80 } type_list_t;
81
82 /* linked list of collector thread control information */
83 typedef struct collector {
84         pthread_t thread;
85
86         /* socket to read data from */
87         int socket;
88
89         /* buffer to read data to */
90         char buffer[BUFSIZE];
91         int  idx; /* current position in buffer */
92
93         struct collector *next;
94 } collector_t;
95
96 typedef struct {
97         collector_t *head;
98         collector_t *tail;
99 } collector_list_t;
100
101 /* state of the plugin */
102 static int disabled = 0;
103
104 /* thread managing "client" connections */
105 static pthread_t connector;
106
107 /* tell the connector thread that a collector is available */
108 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
109
110 /* collector threads that are in use */
111 static pthread_mutex_t active_mutex = PTHREAD_MUTEX_INITIALIZER;
112 static collector_list_t active;
113
114 /* collector threads that are available for use */
115 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
116 static collector_list_t available;
117
118 #define COUNT_FILE "email/email-%s.rrd"
119 static char *count_ds_def[] =
120 {
121         "DS:count:GAUGE:"COLLECTD_HEARTBEAT":0:U",
122         NULL
123 };
124 static int count_ds_num = 1;
125
126 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
127 static type_list_t count;
128
129 #define SIZE_FILE  "email/email_size-%s.rrd"
130 static char *size_ds_def[] =
131 {
132         "DS:size:GAUGE:"COLLECTD_HEARTBEAT":0:U",
133         NULL
134 };
135 static int size_ds_num = 1;
136
137 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
138 static type_list_t size;
139
140 #define SCORE_FILE "email/spam_score.rrd"
141 static char *score_ds_def[] =
142 {
143         "DS:score:GAUGE:"COLLECTD_HEARTBEAT":U:U",
144         NULL
145 };
146 static int score_ds_num = 1;
147
148 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
149 static double score;
150 static int score_count;
151
152 #define CHECK_FILE "email/spam_check-%s.rrd"
153 static char *check_ds_def[] =
154 {
155         "DS:hits:GAUGE:"COLLECTD_HEARTBEAT":0:U",
156         NULL
157 };
158 static int check_ds_num = 1;
159
160 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
161 static type_list_t check;
162
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)
165 {
166         if (NULL == list->head) {
167                 list->head = (type_t *)smalloc (sizeof (type_t));
168
169                 list->head->name  = sstrdup (name);
170                 list->head->value = incr;
171                 list->head->next  = NULL;
172
173                 list->tail = list->head;
174         }
175         else {
176                 type_t *ptr;
177
178                 for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
179                         if (0 == strcmp (name, ptr->name))
180                                 break;
181                 }
182
183                 if (NULL == ptr) {
184                         list->tail->next = (type_t *)smalloc (sizeof (type_t));
185                         list->tail = list->tail->next;
186
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 *) */
197
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)
201 {
202         char ret = '\0';
203
204         fd_set fdset;
205
206         FD_ZERO (&fdset);
207         FD_SET (src->socket, &fdset);
208
209         if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
210                 syslog (LOG_ERR, "select() failed: %s", strerror (errno));
211                 return '\0';
212         }
213
214         assert (FD_ISSET (src->socket, &fdset));
215
216         do {
217                 ssize_t len = 0;
218
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                 }
226
227                 if (0 == len)
228                         return '\0';
229         } while (EINTR == errno);
230         return ret;
231 } /* char read_char (collector_t *) */
232
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)
246 {
247         int  i = 0;
248         char *ret;
249
250         assert (BUFSIZE > src->idx);
251
252         for (i = 0; i < src->idx; ++i) {
253                 if ('\n' == src->buffer[i])
254                         break;
255         }
256
257         if ('\n' != src->buffer[i]) {
258                 fd_set fdset;
259         
260                 ssize_t len = 0;
261
262                 FD_ZERO (&fdset);
263                 FD_SET (src->socket, &fdset);
264
265                 if (-1 == select (src->socket + 1, &fdset, NULL, NULL, NULL)) {
266                         syslog (LOG_ERR, "select() failed: %s", strerror (errno));
267                         return NULL;
268                 }
269
270                 assert (FD_ISSET (src->socket, &fdset));
271
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                         }
282
283                         if (0 == len)
284                                 return NULL;
285                 } while (EINTR == errno);
286
287                 src->idx += len;
288
289                 for (i = src->idx - len; i < src->idx; ++i) {
290                         if ('\n' == src->buffer[i])
291                                 break;
292                 }
293
294                 if ('\n' != src->buffer[i]) {
295                         ret = (char *)smalloc (1);
296
297                         ret[0] = '\0';
298
299                         if (BUFSIZE == src->idx) { /* no space left in buffer */
300                                 while ('\n' != read_char (src))
301                                         /* ignore complete line */;
302
303                                 src->idx = 0;
304                         }
305                         return ret;
306                 }
307         }
308
309         ret = (char *)smalloc (i + 1);
310         memcpy (ret, &(src->buffer[0]), i + 1);
311         ret[i] = '\0';
312
313         src->idx -= (i + 1);
314
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 *) */
321
322 static void *collect (void *arg)
323 {
324         collector_t *this = (collector_t *)arg;
325         
326         int loop = 1;
327
328         { /* put the socket in non-blocking mode */
329                 int flags = 0;
330
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                 }
336
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         }
343
344         while (loop) {
345                 char *line = read_line (this);
346
347                 if (NULL == line) {
348                         loop = 0;
349                         break;
350                 }
351
352                 if ('\0' == line[0]) {
353                         free (line);
354                         continue;
355                 }
356
357                 if (':' != line[1]) {
358                         syslog (LOG_ERR, "email: syntax error in line '%s'", line);
359                         free (line);
360                         continue;
361                 }
362
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;
368
369                         if (NULL == tmp) {
370                                 syslog (LOG_ERR, "email: syntax error in line '%s'", line);
371                                 free (line);
372                                 continue;
373                         }
374
375                         bytes = atoi (tmp);
376
377                         pthread_mutex_lock (&count_mutex);
378                         type_list_incr (&count, type, 1);
379                         pthread_mutex_unlock (&count_mutex);
380
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);
395
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                 }
405
406                 free (line);
407         }
408
409         /* put this thread back into the available list */
410         pthread_mutex_lock (&active_mutex);
411         {
412                 collector_t *last;
413                 collector_t *ptr;
414
415                 last = NULL;
416
417                 for (ptr = active.head; NULL != ptr; last = ptr, ptr = ptr->next) {
418                         if (0 != pthread_equal (ptr->thread, this->thread))
419                                 break;
420                 }
421
422                 /* the current thread _has_ to be in the active list */
423                 assert (NULL != ptr);
424
425                 if (NULL == last) {
426                         active.head = ptr->next;
427                 }
428                 else {
429                         last->next = ptr->next;
430
431                         if (NULL == last->next) {
432                                 active.tail = last;
433                         }
434                 }
435         }
436         pthread_mutex_unlock (&active_mutex);
437
438         this->next = NULL;
439
440         pthread_mutex_lock (&available_mutex);
441
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         }
450
451         pthread_mutex_unlock (&available_mutex);
452
453         pthread_cond_signal (&collector_available);
454         pthread_exit ((void *)0);
455 } /* void *collect (void *) */
456
457 static void *open_connection (void *arg)
458 {
459         int local = 0;
460
461         struct sockaddr_un addr;
462
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         }
470
471         addr.sun_family = AF_UNIX;
472
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);
476
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         }
485
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         }
492
493         if ((uid_t)0 == geteuid ()) {
494                 struct group *grp;
495
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         }
510
511         errno = 0;
512         if (0 != chmod (SOCK_PATH, S_IRWXU | S_IRWXG)) {
513                 syslog (LOG_WARNING, "chmod() failed: %s", strerror (errno));
514         }
515
516         { /* initialize queue of available threads */
517                 int i = 0;
518
519                 collector_t *last;
520
521                 active.head = NULL;
522                 active.tail = NULL;
523
524                 available.head = (collector_t *)smalloc (sizeof (collector_t));
525                 available.tail = available.head;
526                 available.tail->next = NULL;
527
528                 last = available.head;
529
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         }
537
538         while (1) {
539                 int remote = 0;
540                 int err    = 0;
541
542                 collector_t *collector;
543
544                 pthread_attr_t ptattr;
545
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);
551
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);
562
563                 /* assign connection to next available thread */
564                 pthread_mutex_lock (&available_mutex);
565
566                 collector = available.head;
567                 collector->socket = remote;
568
569                 if (available.head == available.tail) {
570                         available.head = NULL;
571                         available.tail = NULL;
572                 }
573                 else {
574                         available.head = available.head->next;
575                 }
576
577                 pthread_mutex_unlock (&available_mutex);
578
579                 collector->idx  = 0;
580                 collector->next = NULL;
581
582                 pthread_attr_init (&ptattr);
583                 pthread_attr_setdetachstate (&ptattr, PTHREAD_CREATE_DETACHED);
584
585                 if (0 == (err = pthread_create (&collector->thread, &ptattr, collect,
586                                 (void *)collector))) {
587                         pthread_mutex_lock (&active_mutex);
588
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                         }
597
598                         pthread_mutex_unlock (&active_mutex);
599                 }
600                 else {
601                         pthread_mutex_lock (&available_mutex);
602
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                         }
611
612                         pthread_mutex_unlock (&available_mutex);
613
614                         close (remote);
615                         syslog (LOG_ERR, "pthread_create() failed: %s", strerror (err));
616                 }
617
618                 pthread_attr_destroy (&ptattr);
619         }
620         pthread_exit ((void *)0);
621 } /* void *open_connection (void *) */
622
623 static void email_init (void)
624 {
625         int err = 0;
626
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) */
635
636 static void count_write (char *host, char *inst, char *val)
637 {
638         char file[BUFSIZE] = "";
639         int  len           = 0;
640
641         len = snprintf (file, BUFSIZE, COUNT_FILE, inst);
642         if ((len < 0) || (len >= BUFSIZE))
643                 return;
644
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) */
648
649 static void size_write (char *host, char *inst, char *val)
650 {
651         char file[BUFSIZE] = "";
652         int  len           = 0;
653
654         len = snprintf (file, BUFSIZE, SIZE_FILE, inst);
655         if ((len < 0) || (len >= BUFSIZE))
656                 return;
657
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) */
661
662 static void score_write (char *host, char *inst, char *val)
663 {
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) */
667
668 static void check_write (char *host, char *inst, char *val)
669 {
670         char file[BUFSIZE] = "";
671         int  len           = 0;
672
673         len = snprintf (file, BUFSIZE, CHECK_FILE, inst);
674         if ((len < 0) || (len >= BUFSIZE))
675                 return;
676
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) */
680
681 static void type_submit (char *plugin, char *inst, int value)
682 {
683         char buf[BUFSIZE] = "";
684         int  len          = 0;
685
686         if (0 == value)
687                 return;
688
689         len = snprintf (buf, BUFSIZE, "%u:%i", (unsigned int)curtime, value);
690         if ((len < 0) || (len >= BUFSIZE))
691                 return;
692
693         plugin_submit (plugin, inst, buf);
694         return;
695 } /* static void type_submit (char *, char *, int) */
696
697 static void score_submit (double value)
698 {
699         char buf[BUFSIZE] = "";
700         int  len          = 0;
701
702         if (0.0 == value)
703                 return;
704
705         len = snprintf (buf, BUFSIZE, "%u:%.2f", (unsigned int)curtime, value);
706         if ((len < 0) || (len >= BUFSIZE))
707                 return;
708
709         plugin_submit ("email_spam_score", NULL, buf);
710         return;
711 }
712
713 static void email_read (void)
714 {
715         type_t *ptr;
716
717         if (disabled)
718                 return;
719
720         pthread_mutex_lock (&count_mutex);
721
722         for (ptr = count.head; NULL != ptr; ptr = ptr->next) {
723                 type_submit ("email_count", ptr->name, ptr->value);
724                 ptr->value = 0;
725         }
726
727         pthread_mutex_unlock (&count_mutex);
728
729         pthread_mutex_lock (&size_mutex);
730
731         for (ptr = size.head; NULL != ptr; ptr = ptr->next) {
732                 type_submit ("email_size", ptr->name, ptr->value);
733                 ptr->value = 0;
734         }
735
736         pthread_mutex_unlock (&size_mutex);
737
738         pthread_mutex_lock (&score_mutex);
739
740         score_submit (score);
741         score = 0.0;
742         score_count = 0;
743
744         pthread_mutex_unlock (&score_mutex);
745
746         pthread_mutex_lock (&check_mutex);
747
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         }
752
753         pthread_mutex_unlock (&check_mutex);
754         return;
755 } /* static void read (void) */
756
757 void module_register (void)
758 {
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) */
766
767 /* vim: set sw=4 ts=4 tw=78 noexpandtab : */
768