Replace zu with PRIu64 and llu with new macro, PRIsz, which will make it easier to...
[collectd.git] / src / email.c
1 /**
2  * collectd - src/email.c
3  * Copyright (C) 2006-2008  Sebastian Harl
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Sebastian Harl <sh at tokkee.org>
25  **/
26
27 /*
28  * This plugin communicates with a spam filter, a virus scanner or similar
29  * software using a UNIX socket and a very simple protocol:
30  *
31  * e-mail type (e.g. ham, spam, virus, ...) and size
32  * e:<type>:<bytes>
33  *
34  * spam score
35  * s:<value>
36  *
37  * successful spam checks
38  * c:<type1>[,<type2>,...]
39  */
40
41 #include "collectd.h"
42
43 #include "common.h"
44 #include "plugin.h"
45
46 #include <stddef.h>
47
48 #include <sys/select.h>
49 #include <sys/un.h>
50
51 /* some systems (e.g. Darwin) seem to not define UNIX_PATH_MAX at all */
52 #ifndef UNIX_PATH_MAX
53 #define UNIX_PATH_MAX sizeof(((struct sockaddr_un *)0)->sun_path)
54 #endif /* UNIX_PATH_MAX */
55
56 #if HAVE_GRP_H
57 #include <grp.h>
58 #endif /* HAVE_GRP_H */
59
60 #define SOCK_PATH LOCALSTATEDIR "/run/" PACKAGE_NAME "-email"
61 #define MAX_CONNS 5
62 #define MAX_CONNS_LIMIT 16384
63
64 #define log_debug(...) DEBUG("email: "__VA_ARGS__)
65 #define log_err(...) ERROR("email: "__VA_ARGS__)
66 #define log_warn(...) WARNING("email: "__VA_ARGS__)
67
68 /*
69  * Private data structures
70  */
71 /* linked list of email and check types */
72 typedef struct type {
73   char *name;
74   int value;
75   struct type *next;
76 } type_t;
77
78 typedef struct {
79   type_t *head;
80   type_t *tail;
81 } type_list_t;
82
83 /* collector thread control information */
84 typedef struct collector {
85   pthread_t thread;
86
87   /* socket descriptor of the current/last connection */
88   FILE *socket;
89 } collector_t;
90
91 /* linked list of pending connections */
92 typedef struct conn {
93   /* socket to read data from */
94   FILE *socket;
95
96   /* linked list of connections */
97   struct conn *next;
98 } conn_t;
99
100 typedef struct {
101   conn_t *head;
102   conn_t *tail;
103 } conn_list_t;
104
105 /*
106  * Private variables
107  */
108 /* valid configuration file keys */
109 static const char *config_keys[] = {"SocketFile", "SocketGroup", "SocketPerms",
110                                     "MaxConns"};
111 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
112
113 /* socket configuration */
114 static char *sock_file = NULL;
115 static char *sock_group = NULL;
116 static int sock_perms = S_IRWXU | S_IRWXG;
117 static int max_conns = MAX_CONNS;
118
119 /* state of the plugin */
120 static int disabled = 0;
121
122 /* thread managing "client" connections */
123 static pthread_t connector = (pthread_t)0;
124 static int connector_socket = -1;
125
126 /* tell the collector threads that a new connection is available */
127 static pthread_cond_t conn_available = PTHREAD_COND_INITIALIZER;
128
129 /* connections that are waiting to be processed */
130 static pthread_mutex_t conns_mutex = PTHREAD_MUTEX_INITIALIZER;
131 static conn_list_t conns;
132
133 /* tell the connector thread that a collector is available */
134 static pthread_cond_t collector_available = PTHREAD_COND_INITIALIZER;
135
136 /* collector threads */
137 static collector_t **collectors = NULL;
138
139 static pthread_mutex_t available_mutex = PTHREAD_MUTEX_INITIALIZER;
140 static int available_collectors;
141
142 static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
143 static type_list_t list_count;
144 static type_list_t list_count_copy;
145
146 static pthread_mutex_t size_mutex = PTHREAD_MUTEX_INITIALIZER;
147 static type_list_t list_size;
148 static type_list_t list_size_copy;
149
150 static pthread_mutex_t score_mutex = PTHREAD_MUTEX_INITIALIZER;
151 static double score;
152 static int score_count;
153
154 static pthread_mutex_t check_mutex = PTHREAD_MUTEX_INITIALIZER;
155 static type_list_t list_check;
156 static type_list_t list_check_copy;
157
158 /*
159  * Private functions
160  */
161 static int email_config(const char *key, const char *value) {
162   if (strcasecmp(key, "SocketFile") == 0) {
163     if (sock_file != NULL)
164       free(sock_file);
165     sock_file = sstrdup(value);
166   } else if (strcasecmp(key, "SocketGroup") == 0) {
167     if (sock_group != NULL)
168       free(sock_group);
169     sock_group = sstrdup(value);
170   } else if (strcasecmp(key, "SocketPerms") == 0) {
171     /* the user is responsible for providing reasonable values */
172     sock_perms = (int)strtol(value, NULL, 8);
173   } else if (strcasecmp(key, "MaxConns") == 0) {
174     long int tmp = strtol(value, NULL, 0);
175
176     if (tmp < 1) {
177       fprintf(stderr, "email plugin: `MaxConns' was set to invalid "
178                       "value %li, will use default %i.\n",
179               tmp, MAX_CONNS);
180       ERROR("email plugin: `MaxConns' was set to invalid "
181             "value %li, will use default %i.\n",
182             tmp, MAX_CONNS);
183       max_conns = MAX_CONNS;
184     } else if (tmp > MAX_CONNS_LIMIT) {
185       fprintf(stderr, "email plugin: `MaxConns' was set to invalid "
186                       "value %li, will use hardcoded limit %i.\n",
187               tmp, MAX_CONNS_LIMIT);
188       ERROR("email plugin: `MaxConns' was set to invalid "
189             "value %li, will use hardcoded limit %i.\n",
190             tmp, MAX_CONNS_LIMIT);
191       max_conns = MAX_CONNS_LIMIT;
192     } else {
193       max_conns = (int)tmp;
194     }
195   } else {
196     return -1;
197   }
198   return 0;
199 } /* static int email_config (char *, char *) */
200
201 /* Increment the value of the given name in the given list by incr. */
202 static void type_list_incr(type_list_t *list, char *name, int incr) {
203   if (list->head == NULL) {
204     list->head = smalloc(sizeof(*list->head));
205
206     list->head->name = sstrdup(name);
207     list->head->value = incr;
208     list->head->next = NULL;
209
210     list->tail = list->head;
211   } else {
212     type_t *ptr;
213
214     for (ptr = list->head; NULL != ptr; ptr = ptr->next) {
215       if (strcmp(name, ptr->name) == 0)
216         break;
217     }
218
219     if (ptr == NULL) {
220       list->tail->next = smalloc(sizeof(*list->tail->next));
221       list->tail = list->tail->next;
222
223       list->tail->name = sstrdup(name);
224       list->tail->value = incr;
225       list->tail->next = NULL;
226     } else {
227       ptr->value += incr;
228     }
229   }
230   return;
231 } /* static void type_list_incr (type_list_t *, char *) */
232
233 static void *collect(void *arg) {
234   collector_t *this = (collector_t *)arg;
235
236   while (1) {
237     conn_t *connection;
238
239     pthread_mutex_lock(&conns_mutex);
240
241     while (conns.head == NULL) {
242       pthread_cond_wait(&conn_available, &conns_mutex);
243     }
244
245     connection = conns.head;
246     conns.head = conns.head->next;
247
248     if (conns.head == NULL) {
249       conns.tail = NULL;
250     }
251
252     pthread_mutex_unlock(&conns_mutex);
253
254     /* make the socket available to the global
255      * thread and connection management */
256     this->socket = connection->socket;
257
258     log_debug("collect: handling connection on fd #%i", fileno(this->socket));
259
260     while (42) {
261       /* 256 bytes ought to be enough for anybody ;-) */
262       char line[256 + 1]; /* line + '\0' */
263       int len = 0;
264
265       errno = 0;
266       if (fgets(line, sizeof(line), this->socket) == NULL) {
267         if (errno != 0) {
268           char errbuf[1024];
269           log_err("collect: reading from socket (fd #%i) "
270                   "failed: %s",
271                   fileno(this->socket),
272                   sstrerror(errno, errbuf, sizeof(errbuf)));
273         }
274         break;
275       }
276
277       len = strlen(line);
278       if ((line[len - 1] != '\n') && (line[len - 1] != '\r')) {
279         log_warn("collect: line too long (> %" PRIsz " characters): "
280                  "'%s' (truncated)",
281                  sizeof(line) - 1, line);
282
283         while (fgets(line, sizeof(line), this->socket) != NULL)
284           if ((line[len - 1] == '\n') || (line[len - 1] == '\r'))
285             break;
286         continue;
287       }
288       if (len < 3) { /* [a-z] ':' '\n' */
289         continue;
290       }
291
292       line[len - 1] = 0;
293
294       log_debug("collect: line = '%s'", line);
295
296       if (line[1] != ':') {
297         log_err("collect: syntax error in line '%s'", line);
298         continue;
299       }
300
301       if (line[0] == 'e') { /* e:<type>:<bytes> */
302         char *ptr = NULL;
303         char *type = strtok_r(line + 2, ":", &ptr);
304         char *tmp = strtok_r(NULL, ":", &ptr);
305         int bytes = 0;
306
307         if (tmp == NULL) {
308           log_err("collect: syntax error in line '%s'", line);
309           continue;
310         }
311
312         bytes = atoi(tmp);
313
314         pthread_mutex_lock(&count_mutex);
315         type_list_incr(&list_count, type, /* increment = */ 1);
316         pthread_mutex_unlock(&count_mutex);
317
318         if (bytes > 0) {
319           pthread_mutex_lock(&size_mutex);
320           type_list_incr(&list_size, type, /* increment = */ bytes);
321           pthread_mutex_unlock(&size_mutex);
322         }
323       } else if (line[0] == 's') { /* s:<value> */
324         pthread_mutex_lock(&score_mutex);
325         score = (score * (double)score_count + atof(line + 2)) /
326                 (double)(score_count + 1);
327         ++score_count;
328         pthread_mutex_unlock(&score_mutex);
329       } else if (line[0] == 'c') { /* c:<type1>[,<type2>,...] */
330         char *dummy = line + 2;
331         char *endptr = NULL;
332         char *type;
333
334         pthread_mutex_lock(&check_mutex);
335         while ((type = strtok_r(dummy, ",", &endptr)) != NULL) {
336           dummy = NULL;
337           type_list_incr(&list_check, type, /* increment = */ 1);
338         }
339         pthread_mutex_unlock(&check_mutex);
340       } else {
341         log_err("collect: unknown type '%c'", line[0]);
342       }
343     } /* while (42) */
344
345     log_debug("Shutting down connection on fd #%i", fileno(this->socket));
346
347     fclose(connection->socket);
348     free(connection);
349
350     this->socket = NULL;
351
352     pthread_mutex_lock(&available_mutex);
353     ++available_collectors;
354     pthread_mutex_unlock(&available_mutex);
355
356     pthread_cond_signal(&collector_available);
357   } /* while (1) */
358
359   pthread_exit((void *)0);
360   return (void *)0;
361 } /* static void *collect (void *) */
362
363 static void *open_connection(void __attribute__((unused)) * arg) {
364   const char *path = (NULL == sock_file) ? SOCK_PATH : sock_file;
365   const char *group = (NULL == sock_group) ? COLLECTD_GRP_NAME : sock_group;
366
367   /* create UNIX socket */
368   errno = 0;
369   if ((connector_socket = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
370     char errbuf[1024];
371     disabled = 1;
372     log_err("socket() failed: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
373     pthread_exit((void *)1);
374   }
375
376   struct sockaddr_un addr = {.sun_family = AF_UNIX};
377   sstrncpy(addr.sun_path, path, (size_t)(UNIX_PATH_MAX - 1));
378
379   errno = 0;
380   if (bind(connector_socket, (struct sockaddr *)&addr,
381            offsetof(struct sockaddr_un, sun_path) + strlen(addr.sun_path)) ==
382       -1) {
383     char errbuf[1024];
384     disabled = 1;
385     close(connector_socket);
386     connector_socket = -1;
387     log_err("bind() failed: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
388     pthread_exit((void *)1);
389   }
390
391   errno = 0;
392   if (listen(connector_socket, 5) == -1) {
393     char errbuf[1024];
394     disabled = 1;
395     close(connector_socket);
396     connector_socket = -1;
397     log_err("listen() failed: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
398     pthread_exit((void *)1);
399   }
400
401   {
402     struct group sg;
403     struct group *grp;
404     int status;
405
406     long int grbuf_size = sysconf(_SC_GETGR_R_SIZE_MAX);
407     if (grbuf_size <= 0)
408       grbuf_size = sysconf(_SC_PAGESIZE);
409     if (grbuf_size <= 0)
410       grbuf_size = 4096;
411     char grbuf[grbuf_size];
412
413     grp = NULL;
414     status = getgrnam_r(group, &sg, grbuf, sizeof(grbuf), &grp);
415     if (status != 0) {
416       char errbuf[1024];
417       log_warn("getgrnam_r (%s) failed: %s", group,
418                sstrerror(status, errbuf, sizeof(errbuf)));
419     } else if (grp == NULL) {
420       log_warn("No such group: `%s'", group);
421     } else {
422       status = chown(path, (uid_t)-1, grp->gr_gid);
423       if (status != 0) {
424         char errbuf[1024];
425         log_warn("chown (%s, -1, %i) failed: %s", path, (int)grp->gr_gid,
426                  sstrerror(errno, errbuf, sizeof(errbuf)));
427       }
428     }
429   }
430
431   errno = 0;
432   if (chmod(path, sock_perms) != 0) {
433     char errbuf[1024];
434     log_warn("chmod() failed: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
435   }
436
437   { /* initialize collector threads */
438     pthread_attr_t ptattr;
439
440     conns.head = NULL;
441     conns.tail = NULL;
442
443     pthread_attr_init(&ptattr);
444     pthread_attr_setdetachstate(&ptattr, PTHREAD_CREATE_DETACHED);
445
446     available_collectors = max_conns;
447
448     collectors = smalloc(max_conns * sizeof(*collectors));
449
450     for (int i = 0; i < max_conns; ++i) {
451       collectors[i] = smalloc(sizeof(*collectors[i]));
452       collectors[i]->socket = NULL;
453
454       if (plugin_thread_create(&collectors[i]->thread, &ptattr, collect,
455                                collectors[i], "email collector") != 0) {
456         char errbuf[1024];
457         log_err("plugin_thread_create() failed: %s",
458                 sstrerror(errno, errbuf, sizeof(errbuf)));
459         collectors[i]->thread = (pthread_t)0;
460       }
461     }
462
463     pthread_attr_destroy(&ptattr);
464   }
465
466   while (1) {
467     int remote = 0;
468
469     conn_t *connection;
470
471     pthread_mutex_lock(&available_mutex);
472
473     while (available_collectors == 0) {
474       pthread_cond_wait(&collector_available, &available_mutex);
475     }
476
477     --available_collectors;
478
479     pthread_mutex_unlock(&available_mutex);
480
481     while (42) {
482       errno = 0;
483
484       remote = accept(connector_socket, NULL, NULL);
485       if (remote == -1) {
486         char errbuf[1024];
487
488         if (errno == EINTR)
489           continue;
490
491         disabled = 1;
492         close(connector_socket);
493         connector_socket = -1;
494         log_err("accept() failed: %s",
495                 sstrerror(errno, errbuf, sizeof(errbuf)));
496         pthread_exit((void *)1);
497       }
498
499       /* access() succeeded. */
500       break;
501     }
502
503     connection = calloc(1, sizeof(*connection));
504     if (connection == NULL) {
505       close(remote);
506       continue;
507     }
508
509     connection->socket = fdopen(remote, "r");
510     connection->next = NULL;
511
512     if (connection->socket == NULL) {
513       close(remote);
514       sfree(connection);
515       continue;
516     }
517
518     pthread_mutex_lock(&conns_mutex);
519
520     if (conns.head == NULL) {
521       conns.head = connection;
522       conns.tail = connection;
523     } else {
524       conns.tail->next = connection;
525       conns.tail = conns.tail->next;
526     }
527
528     pthread_mutex_unlock(&conns_mutex);
529
530     pthread_cond_signal(&conn_available);
531   }
532
533   pthread_exit((void *)0);
534   return (void *)0;
535 } /* static void *open_connection (void *) */
536
537 static int email_init(void) {
538   if (plugin_thread_create(&connector, NULL, open_connection, NULL,
539                            "email listener") != 0) {
540     char errbuf[1024];
541     disabled = 1;
542     log_err("plugin_thread_create() failed: %s",
543             sstrerror(errno, errbuf, sizeof(errbuf)));
544     return -1;
545   }
546
547   return 0;
548 } /* int email_init */
549
550 static void type_list_free(type_list_t *t) {
551   type_t *this;
552
553   this = t->head;
554   while (this != NULL) {
555     type_t *next = this->next;
556
557     sfree(this->name);
558     sfree(this);
559
560     this = next;
561   }
562
563   t->head = NULL;
564   t->tail = NULL;
565 }
566
567 static int email_shutdown(void) {
568   if (connector != ((pthread_t)0)) {
569     pthread_kill(connector, SIGTERM);
570     connector = (pthread_t)0;
571   }
572
573   if (connector_socket >= 0) {
574     close(connector_socket);
575     connector_socket = -1;
576   }
577
578   /* don't allow any more connections to be processed */
579   pthread_mutex_lock(&conns_mutex);
580
581   available_collectors = 0;
582
583   if (collectors != NULL) {
584     for (int i = 0; i < max_conns; ++i) {
585       if (collectors[i] == NULL)
586         continue;
587
588       if (collectors[i]->thread != ((pthread_t)0)) {
589         pthread_kill(collectors[i]->thread, SIGTERM);
590         collectors[i]->thread = (pthread_t)0;
591       }
592
593       if (collectors[i]->socket != NULL) {
594         fclose(collectors[i]->socket);
595         collectors[i]->socket = NULL;
596       }
597
598       sfree(collectors[i]);
599     }
600     sfree(collectors);
601   } /* if (collectors != NULL) */
602
603   pthread_mutex_unlock(&conns_mutex);
604
605   type_list_free(&list_count);
606   type_list_free(&list_count_copy);
607   type_list_free(&list_size);
608   type_list_free(&list_size_copy);
609   type_list_free(&list_check);
610   type_list_free(&list_check_copy);
611
612   unlink((sock_file == NULL) ? SOCK_PATH : sock_file);
613
614   sfree(sock_file);
615   sfree(sock_group);
616   return 0;
617 } /* static void email_shutdown (void) */
618
619 static void email_submit(const char *type, const char *type_instance,
620                          gauge_t value) {
621   value_list_t vl = VALUE_LIST_INIT;
622
623   vl.values = &(value_t){.gauge = value};
624   vl.values_len = 1;
625   sstrncpy(vl.plugin, "email", sizeof(vl.plugin));
626   sstrncpy(vl.type, type, sizeof(vl.type));
627   sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
628
629   plugin_dispatch_values(&vl);
630 } /* void email_submit */
631
632 /* Copy list l1 to list l2. l2 may partly exist already, but it is assumed
633  * that neither the order nor the name of any element of either list is
634  * changed and no elements are deleted. The values of l1 are reset to zero
635  * after they have been copied to l2. */
636 static void copy_type_list(type_list_t *l1, type_list_t *l2) {
637   type_t *last = NULL;
638
639   for (type_t *ptr1 = l1->head, *ptr2 = l2->head; ptr1 != NULL;
640        ptr1 = ptr1->next, last = ptr2, ptr2 = ptr2->next) {
641     if (ptr2 == NULL) {
642       ptr2 = smalloc(sizeof(*ptr2));
643       ptr2->name = NULL;
644       ptr2->next = NULL;
645
646       if (last == NULL) {
647         l2->head = ptr2;
648       } else {
649         last->next = ptr2;
650       }
651
652       l2->tail = ptr2;
653     }
654
655     if (ptr2->name == NULL) {
656       ptr2->name = sstrdup(ptr1->name);
657     }
658
659     ptr2->value = ptr1->value;
660     ptr1->value = 0;
661   }
662   return;
663 }
664
665 static int email_read(void) {
666   double score_old;
667   int score_count_old;
668
669   if (disabled)
670     return -1;
671
672   /* email count */
673   pthread_mutex_lock(&count_mutex);
674
675   copy_type_list(&list_count, &list_count_copy);
676
677   pthread_mutex_unlock(&count_mutex);
678
679   for (type_t *ptr = list_count_copy.head; ptr != NULL; ptr = ptr->next) {
680     email_submit("email_count", ptr->name, ptr->value);
681   }
682
683   /* email size */
684   pthread_mutex_lock(&size_mutex);
685
686   copy_type_list(&list_size, &list_size_copy);
687
688   pthread_mutex_unlock(&size_mutex);
689
690   for (type_t *ptr = list_size_copy.head; ptr != NULL; ptr = ptr->next) {
691     email_submit("email_size", ptr->name, ptr->value);
692   }
693
694   /* spam score */
695   pthread_mutex_lock(&score_mutex);
696
697   score_old = score;
698   score_count_old = score_count;
699   score = 0.0;
700   score_count = 0;
701
702   pthread_mutex_unlock(&score_mutex);
703
704   if (score_count_old > 0)
705     email_submit("spam_score", "", score_old);
706
707   /* spam checks */
708   pthread_mutex_lock(&check_mutex);
709
710   copy_type_list(&list_check, &list_check_copy);
711
712   pthread_mutex_unlock(&check_mutex);
713
714   for (type_t *ptr = list_check_copy.head; ptr != NULL; ptr = ptr->next)
715     email_submit("spam_check", ptr->name, ptr->value);
716
717   return 0;
718 } /* int email_read */
719
720 void module_register(void) {
721   plugin_register_config("email", email_config, config_keys, config_keys_num);
722   plugin_register_init("email", email_init);
723   plugin_register_read("email", email_read);
724   plugin_register_shutdown("email", email_shutdown);
725 } /* void module_register */