network plugin: Implement signing and encryption of network traffic.
[collectd.git] / src / network.c
1 /**
2  * collectd - src/network.c
3  * Copyright (C) 2005-2009  Florian octo Forster
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; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #include "collectd.h"
23 #include "plugin.h"
24 #include "common.h"
25 #include "configfile.h"
26 #include "utils_avltree.h"
27
28 #include "network.h"
29
30 #if HAVE_PTHREAD_H
31 # include <pthread.h>
32 #endif
33 #if HAVE_SYS_SOCKET_H
34 # include <sys/socket.h>
35 #endif
36 #if HAVE_NETDB_H
37 # include <netdb.h>
38 #endif
39 #if HAVE_NETINET_IN_H
40 # include <netinet/in.h>
41 #endif
42 #if HAVE_ARPA_INET_H
43 # include <arpa/inet.h>
44 #endif
45 #if HAVE_POLL_H
46 # include <poll.h>
47 #endif
48
49 #if HAVE_GCRYPT_H
50 # include <gcrypt.h>
51 #endif
52
53 /* 1500 - 40 - 8  =  Ethernet packet - IPv6 header - UDP header */
54 /* #define BUFF_SIZE 1452 */
55
56 #ifndef IPV6_ADD_MEMBERSHIP
57 # ifdef IPV6_JOIN_GROUP
58 #  define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
59 # else
60 #  error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
61 # endif
62 #endif /* !IP_ADD_MEMBERSHIP */
63
64 /* Buffer size to allocate. */
65 #define BUFF_SIZE 1024
66
67 /*
68  * Maximum size required for encryption / signing:
69  * Type/length:       4
70  * Hash/orig length: 32
71  * Padding (up to):  16
72  * --------------------
73  *                   52
74  */
75 #define BUFF_SIG_SIZE 52
76
77 /*
78  * Private data types
79  */
80 typedef struct sockent
81 {
82         int                      fd;
83         struct sockaddr_storage *addr;
84         socklen_t                addrlen;
85
86 #define SECURITY_LEVEL_NONE     0
87 #if HAVE_GCRYPT_H
88 # define SECURITY_LEVEL_SIGN    1
89 # define SECURITY_LEVEL_ENCRYPT 2
90         int security_level;
91         char *shared_secret;
92         gcry_cipher_hd_t cypher;
93 #endif /* HAVE_GCRYPT_H */
94
95         struct sockent          *next;
96 } sockent_t;
97
98 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
99  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
100  * +-------+-----------------------+-------------------------------+
101  * ! Ver.  !                       ! Length                        !
102  * +-------+-----------------------+-------------------------------+
103  */
104 struct part_header_s
105 {
106         uint16_t type;
107         uint16_t length;
108 };
109 typedef struct part_header_s part_header_t;
110
111 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
112  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
113  * +-------------------------------+-------------------------------+
114  * ! Type                          ! Length                        !
115  * +-------------------------------+-------------------------------+
116  * : (Length - 4) Bytes                                            :
117  * +---------------------------------------------------------------+
118  */
119 struct part_string_s
120 {
121         part_header_t *head;
122         char *value;
123 };
124 typedef struct part_string_s part_string_t;
125
126 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
127  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
128  * +-------------------------------+-------------------------------+
129  * ! Type                          ! Length                        !
130  * +-------------------------------+-------------------------------+
131  * : (Length - 4 == 2 || 4 || 8) Bytes                             :
132  * +---------------------------------------------------------------+
133  */
134 struct part_number_s
135 {
136         part_header_t *head;
137         uint64_t *value;
138 };
139 typedef struct part_number_s part_number_t;
140
141 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
142  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
143  * +-------------------------------+-------------------------------+
144  * ! Type                          ! Length                        !
145  * +-------------------------------+---------------+---------------+
146  * ! Num of values                 ! Type0         ! Type1         !
147  * +-------------------------------+---------------+---------------+
148  * ! Value0                                                        !
149  * !                                                               !
150  * +---------------------------------------------------------------+
151  * ! Value1                                                        !
152  * !                                                               !
153  * +---------------------------------------------------------------+
154  */
155 struct part_values_s
156 {
157         part_header_t *head;
158         uint16_t *num_values;
159         uint8_t  *values_types;
160         value_t  *values;
161 };
162 typedef struct part_values_s part_values_t;
163
164 struct part_signature_sha256_s
165 {
166   part_header_t head;
167   char hash[32];
168 };
169 typedef struct part_signature_sha256_s part_signature_sha256_t;
170
171 struct part_encryption_aes256_s
172 {
173   part_header_t head;
174   uint16_t orig_length;
175   uint16_t random;
176   char hash[28];
177 };
178 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
179
180 struct receive_list_entry_s
181 {
182   char data[BUFF_SIZE];
183   int  data_len;
184   int  fd;
185   struct receive_list_entry_s *next;
186 };
187 typedef struct receive_list_entry_s receive_list_entry_t;
188
189 /*
190  * Private variables
191  */
192 #if HAVE_GCRYPT_H
193 static char network_encryption_iv[] = NET_ENCR_IV;
194 #endif /* HAVE_GCRYPT_H */
195
196 static int network_config_ttl = 0;
197 static int network_config_forward = 0;
198
199 static sockent_t *sending_sockets = NULL;
200
201 static receive_list_entry_t *receive_list_head = NULL;
202 static receive_list_entry_t *receive_list_tail = NULL;
203 static pthread_mutex_t       receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
204 static pthread_cond_t        receive_list_cond = PTHREAD_COND_INITIALIZER;
205
206 static sockent_t     *listen_sockets = NULL;
207 static struct pollfd *listen_sockets_pollfd = NULL;
208 static int            listen_sockets_num = 0;
209
210 /* The receive and dispatch threads will run as long as `listen_loop' is set to
211  * zero. */
212 static int       listen_loop = 0;
213 static int       receive_thread_running = 0;
214 static pthread_t receive_thread_id;
215 static int       dispatch_thread_running = 0;
216 static pthread_t dispatch_thread_id;
217
218 /* Buffer in which to-be-sent network packets are constructed. */
219 static char             send_buffer[BUFF_SIZE];
220 static char            *send_buffer_ptr;
221 static int              send_buffer_fill;
222 static value_list_t     send_buffer_vl = VALUE_LIST_STATIC;
223 static pthread_mutex_t  send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
224
225 /* In this cache we store all the values we received, so we can send out only
226  * those values which were *not* received via the network plugin, too. This is
227  * used for the `Forward false' option. */
228 static c_avl_tree_t    *cache_tree = NULL;
229 static pthread_mutex_t  cache_lock = PTHREAD_MUTEX_INITIALIZER;
230 static time_t           cache_flush_last = 0;
231 static int              cache_flush_interval = 1800;
232
233 /*
234  * Private functions
235  */
236 static int cache_flush (void)
237 {
238         char **keys = NULL;
239         int    keys_num = 0;
240
241         char **tmp;
242         int    i;
243
244         char   *key;
245         time_t *value;
246         c_avl_iterator_t *iter;
247
248         time_t curtime = time (NULL);
249
250         iter = c_avl_get_iterator (cache_tree);
251         while (c_avl_iterator_next (iter, (void *) &key, (void *) &value) == 0)
252         {
253                 if ((curtime - *value) <= cache_flush_interval)
254                         continue;
255                 tmp = (char **) realloc (keys,
256                                 (keys_num + 1) * sizeof (char *));
257                 if (tmp == NULL)
258                 {
259                         sfree (keys);
260                         c_avl_iterator_destroy (iter);
261                         ERROR ("network plugin: cache_flush: realloc"
262                                         " failed.");
263                         return (-1);
264                 }
265                 keys = tmp;
266                 keys[keys_num] = key;
267                 keys_num++;
268         } /* while (c_avl_iterator_next) */
269         c_avl_iterator_destroy (iter);
270
271         for (i = 0; i < keys_num; i++)
272         {
273                 if (c_avl_remove (cache_tree, keys[i], (void *) &key,
274                                         (void *) &value) != 0)
275                 {
276                         WARNING ("network plugin: cache_flush: c_avl_remove"
277                                         " (%s) failed.", keys[i]);
278                         continue;
279                 }
280
281                 sfree (key);
282                 sfree (value);
283         }
284
285         sfree (keys);
286
287         DEBUG ("network plugin: cache_flush: Removed %i %s",
288                         keys_num, (keys_num == 1) ? "entry" : "entries");
289         cache_flush_last = curtime;
290         return (0);
291 } /* int cache_flush */
292
293 static int cache_check (const value_list_t *vl)
294 {
295         char key[1024];
296         time_t *value = NULL;
297         int retval = -1;
298
299         if (cache_tree == NULL)
300                 return (-1);
301
302         if (format_name (key, sizeof (key), vl->host, vl->plugin,
303                                 vl->plugin_instance, vl->type, vl->type_instance))
304                 return (-1);
305
306         pthread_mutex_lock (&cache_lock);
307
308         if (c_avl_get (cache_tree, key, (void *) &value) == 0)
309         {
310                 if (*value < vl->time)
311                 {
312                         *value = vl->time;
313                         retval = 0;
314                 }
315                 else
316                 {
317                         DEBUG ("network plugin: cache_check: *value = %i >= vl->time = %i",
318                                         (int) *value, (int) vl->time);
319                         retval = 1;
320                 }
321         }
322         else
323         {
324                 char *key_copy = strdup (key);
325                 value = malloc (sizeof (time_t));
326                 if ((key_copy != NULL) && (value != NULL))
327                 {
328                         *value = vl->time;
329                         c_avl_insert (cache_tree, key_copy, value);
330                         retval = 0;
331                 }
332                 else
333                 {
334                         sfree (key_copy);
335                         sfree (value);
336                 }
337         }
338
339         if ((time (NULL) - cache_flush_last) > cache_flush_interval)
340                 cache_flush ();
341
342         pthread_mutex_unlock (&cache_lock);
343
344         return (retval);
345 } /* int cache_check */
346
347 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
348                 const data_set_t *ds, const value_list_t *vl)
349 {
350         char *packet_ptr;
351         int packet_len;
352         int num_values;
353
354         part_header_t pkg_ph;
355         uint16_t      pkg_num_values;
356         uint8_t      *pkg_values_types;
357         value_t      *pkg_values;
358
359         int offset;
360         int i;
361
362         num_values = vl->values_len;
363         packet_len = sizeof (part_header_t) + sizeof (uint16_t)
364                 + (num_values * sizeof (uint8_t))
365                 + (num_values * sizeof (value_t));
366
367         if (*ret_buffer_len < packet_len)
368                 return (-1);
369
370         pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
371         if (pkg_values_types == NULL)
372         {
373                 ERROR ("network plugin: write_part_values: malloc failed.");
374                 return (-1);
375         }
376
377         pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
378         if (pkg_values == NULL)
379         {
380                 free (pkg_values_types);
381                 ERROR ("network plugin: write_part_values: malloc failed.");
382                 return (-1);
383         }
384
385         pkg_ph.type = htons (TYPE_VALUES);
386         pkg_ph.length = htons (packet_len);
387
388         pkg_num_values = htons ((uint16_t) vl->values_len);
389
390         for (i = 0; i < num_values; i++)
391         {
392                 if (ds->ds[i].type == DS_TYPE_COUNTER)
393                 {
394                         pkg_values_types[i] = DS_TYPE_COUNTER;
395                         pkg_values[i].counter = htonll (vl->values[i].counter);
396                 }
397                 else
398                 {
399                         pkg_values_types[i] = DS_TYPE_GAUGE;
400                         pkg_values[i].gauge = htond (vl->values[i].gauge);
401                 }
402         }
403
404         /*
405          * Use `memcpy' to write everything to the buffer, because the pointer
406          * may be unaligned and some architectures, such as SPARC, can't handle
407          * that.
408          */
409         packet_ptr = *ret_buffer;
410         offset = 0;
411         memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
412         offset += sizeof (pkg_ph);
413         memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
414         offset += sizeof (pkg_num_values);
415         memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
416         offset += num_values * sizeof (uint8_t);
417         memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
418         offset += num_values * sizeof (value_t);
419
420         assert (offset == packet_len);
421
422         *ret_buffer = packet_ptr + packet_len;
423         *ret_buffer_len -= packet_len;
424
425         free (pkg_values_types);
426         free (pkg_values);
427
428         return (0);
429 } /* int write_part_values */
430
431 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
432                 int type, uint64_t value)
433 {
434         char *packet_ptr;
435         int packet_len;
436
437         part_header_t pkg_head;
438         uint64_t pkg_value;
439         
440         int offset;
441
442         packet_len = sizeof (pkg_head) + sizeof (pkg_value);
443
444         if (*ret_buffer_len < packet_len)
445                 return (-1);
446
447         pkg_head.type = htons (type);
448         pkg_head.length = htons (packet_len);
449         pkg_value = htonll (value);
450
451         packet_ptr = *ret_buffer;
452         offset = 0;
453         memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
454         offset += sizeof (pkg_head);
455         memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
456         offset += sizeof (pkg_value);
457
458         assert (offset == packet_len);
459
460         *ret_buffer = packet_ptr + packet_len;
461         *ret_buffer_len -= packet_len;
462
463         return (0);
464 } /* int write_part_number */
465
466 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
467                 int type, const char *str, int str_len)
468 {
469         char *buffer;
470         int buffer_len;
471
472         uint16_t pkg_type;
473         uint16_t pkg_length;
474
475         int offset;
476
477         buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
478         if (*ret_buffer_len < buffer_len)
479                 return (-1);
480
481         pkg_type = htons (type);
482         pkg_length = htons (buffer_len);
483
484         buffer = *ret_buffer;
485         offset = 0;
486         memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
487         offset += sizeof (pkg_type);
488         memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
489         offset += sizeof (pkg_length);
490         memcpy (buffer + offset, str, str_len);
491         offset += str_len;
492         memset (buffer + offset, '\0', 1);
493         offset += 1;
494
495         assert (offset == buffer_len);
496
497         *ret_buffer = buffer + buffer_len;
498         *ret_buffer_len -= buffer_len;
499
500         return (0);
501 } /* int write_part_string */
502
503 static int parse_part_values (void **ret_buffer, int *ret_buffer_len,
504                 value_t **ret_values, int *ret_num_values)
505 {
506         char *buffer = *ret_buffer;
507         int   buffer_len = *ret_buffer_len;
508
509         uint16_t tmp16;
510         size_t exp_size;
511         int   i;
512
513         uint16_t pkg_length;
514         uint16_t pkg_type;
515         uint16_t pkg_numval;
516
517         uint8_t *pkg_types;
518         value_t *pkg_values;
519
520         if (buffer_len < (15))
521         {
522                 DEBUG ("network plugin: packet is too short: buffer_len = %i",
523                                 buffer_len);
524                 return (-1);
525         }
526
527         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
528         buffer += sizeof (tmp16);
529         pkg_type = ntohs (tmp16);
530
531         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
532         buffer += sizeof (tmp16);
533         pkg_length = ntohs (tmp16);
534
535         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
536         buffer += sizeof (tmp16);
537         pkg_numval = ntohs (tmp16);
538
539         assert (pkg_type == TYPE_VALUES);
540
541         exp_size = 3 * sizeof (uint16_t)
542                 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
543         if ((buffer_len < 0) || ((size_t) buffer_len < exp_size))
544         {
545                 WARNING ("network plugin: parse_part_values: "
546                                 "Packet too short: "
547                                 "Chunk of size %u expected, "
548                                 "but buffer has only %i bytes left.",
549                                 (unsigned int) exp_size, buffer_len);
550                 return (-1);
551         }
552
553         if (pkg_length != exp_size)
554         {
555                 WARNING ("network plugin: parse_part_values: "
556                                 "Length and number of values "
557                                 "in the packet don't match.");
558                 return (-1);
559         }
560
561         pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
562         pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
563         if ((pkg_types == NULL) || (pkg_values == NULL))
564         {
565                 sfree (pkg_types);
566                 sfree (pkg_values);
567                 ERROR ("network plugin: parse_part_values: malloc failed.");
568                 return (-1);
569         }
570
571         memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
572         buffer += pkg_numval * sizeof (uint8_t);
573         memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
574         buffer += pkg_numval * sizeof (value_t);
575
576         for (i = 0; i < pkg_numval; i++)
577         {
578                 if (pkg_types[i] == DS_TYPE_COUNTER)
579                         pkg_values[i].counter = ntohll (pkg_values[i].counter);
580                 else if (pkg_types[i] == DS_TYPE_GAUGE)
581                         pkg_values[i].gauge = ntohd (pkg_values[i].gauge);
582         }
583
584         *ret_buffer     = buffer;
585         *ret_buffer_len = buffer_len - pkg_length;
586         *ret_num_values = pkg_numval;
587         *ret_values     = pkg_values;
588
589         sfree (pkg_types);
590
591         return (0);
592 } /* int parse_part_values */
593
594 static int parse_part_number (void **ret_buffer, int *ret_buffer_len,
595                 uint64_t *value)
596 {
597         char *buffer = *ret_buffer;
598         int buffer_len = *ret_buffer_len;
599
600         uint16_t tmp16;
601         uint64_t tmp64;
602         size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
603
604         uint16_t pkg_length;
605         uint16_t pkg_type;
606
607         if ((buffer_len < 0) || ((size_t) buffer_len < exp_size))
608         {
609                 WARNING ("network plugin: parse_part_number: "
610                                 "Packet too short: "
611                                 "Chunk of size %u expected, "
612                                 "but buffer has only %i bytes left.",
613                                 (unsigned int) exp_size, buffer_len);
614                 return (-1);
615         }
616
617         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
618         buffer += sizeof (tmp16);
619         pkg_type = ntohs (tmp16);
620
621         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
622         buffer += sizeof (tmp16);
623         pkg_length = ntohs (tmp16);
624
625         memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
626         buffer += sizeof (tmp64);
627         *value = ntohll (tmp64);
628
629         *ret_buffer = buffer;
630         *ret_buffer_len = buffer_len - pkg_length;
631
632         return (0);
633 } /* int parse_part_number */
634
635 static int parse_part_string (void **ret_buffer, int *ret_buffer_len,
636                 char *output, int output_len)
637 {
638         char *buffer = *ret_buffer;
639         int   buffer_len = *ret_buffer_len;
640
641         uint16_t tmp16;
642         size_t header_size = 2 * sizeof (uint16_t);
643
644         uint16_t pkg_length;
645         uint16_t pkg_type;
646
647         if ((buffer_len < 0) || ((size_t) buffer_len < header_size))
648         {
649                 WARNING ("network plugin: parse_part_string: "
650                                 "Packet too short: "
651                                 "Chunk of at least size %u expected, "
652                                 "but buffer has only %i bytes left.",
653                                 (unsigned int) header_size, buffer_len);
654                 return (-1);
655         }
656
657         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
658         buffer += sizeof (tmp16);
659         pkg_type = ntohs (tmp16);
660
661         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
662         buffer += sizeof (tmp16);
663         pkg_length = ntohs (tmp16);
664
665         /* Check that packet fits in the input buffer */
666         if (pkg_length > buffer_len)
667         {
668                 WARNING ("network plugin: parse_part_string: "
669                                 "Packet too big: "
670                                 "Chunk of size %hu received, "
671                                 "but buffer has only %i bytes left.",
672                                 pkg_length, buffer_len);
673                 return (-1);
674         }
675
676         /* Check that pkg_length is in the valid range */
677         if (pkg_length <= header_size)
678         {
679                 WARNING ("network plugin: parse_part_string: "
680                                 "Packet too short: "
681                                 "Header claims this packet is only %hu "
682                                 "bytes long.", pkg_length);
683                 return (-1);
684         }
685
686         /* Check that the package data fits into the output buffer.
687          * The previous if-statement ensures that:
688          * `pkg_length > header_size' */
689         if ((output_len < 0)
690                         || ((size_t) output_len < ((size_t) pkg_length - header_size)))
691         {
692                 WARNING ("network plugin: parse_part_string: "
693                                 "Output buffer too small.");
694                 return (-1);
695         }
696
697         /* All sanity checks successfull, let's copy the data over */
698         output_len = pkg_length - header_size;
699         memcpy ((void *) output, (void *) buffer, output_len);
700         buffer += output_len;
701
702         /* For some very weird reason '\0' doesn't do the trick on SPARC in
703          * this statement. */
704         if (output[output_len - 1] != 0)
705         {
706                 WARNING ("network plugin: parse_part_string: "
707                                 "Received string does not end "
708                                 "with a NULL-byte.");
709                 return (-1);
710         }
711
712         *ret_buffer = buffer;
713         *ret_buffer_len = buffer_len - pkg_length;
714
715         return (0);
716 } /* int parse_part_string */
717
718 #if HAVE_GCRYPT_H
719 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
720     void **ret_buffer, int *ret_buffer_len)
721 {
722   char *buffer = *ret_buffer;
723   size_t buffer_len = (size_t) *ret_buffer_len;
724
725   part_signature_sha256_t ps_received;
726   part_signature_sha256_t ps_expected;
727
728   if (se->shared_secret == NULL)
729   {
730     NOTICE ("network plugin: Received signed network packet but can't verify "
731         "it because no shared secret has been configured. Will accept it.");
732     return (0);
733   }
734
735   if (buffer_len < sizeof (ps_received))
736     return (-ENOMEM);
737
738   memcpy (&ps_received, buffer, sizeof (ps_received));
739
740   memset (&ps_expected, 0, sizeof (ps_expected));
741   ps_expected.head.type = htons (TYPE_SIGN_SHA256);
742   ps_expected.head.length = htons (sizeof (ps_expected));
743   sstrncpy (ps_expected.hash, se->shared_secret, sizeof (ps_expected.hash));
744   memcpy (buffer, &ps_expected, sizeof (ps_expected));
745
746   gcry_md_hash_buffer (GCRY_MD_SHA256, ps_expected.hash, buffer, buffer_len);
747
748   *ret_buffer += sizeof (ps_received);
749
750   if (memcmp (ps_received.hash, ps_expected.hash,
751         sizeof (ps_received.hash)) == 0)
752     return (0);
753   else /* hashes do not match. */
754     return (1);
755 } /* }}} int parse_part_sign_sha256 */
756 /* #endif HAVE_GCRYPT_H */
757
758 #else /* if !HAVE_GCRYPT_H */
759 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
760     void **ret_buffer, int *ret_buffer_len)
761 {
762   INFO ("network plugin: Received signed packet, but the network "
763       "plugin was not linked with libgcrypt, so I cannot "
764       "verify the signature. The packet will be accepted.");
765   return (0);
766 } /* }}} int parse_part_sign_sha256 */
767 #endif /* !HAVE_GCRYPT_H */
768
769 #if HAVE_GCRYPT_H
770 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
771                 void **ret_buffer, int *ret_buffer_len)
772 {
773   char *buffer = *ret_buffer;
774   int   buffer_len = *ret_buffer_len;
775   int   orig_buffer_len;
776   part_encryption_aes256_t pea;
777   char hash[28];
778   gcry_error_t err;
779
780   if (se->cypher == NULL)
781   {
782     NOTICE ("network plugin: Unable to decrypt packet, because no cypher "
783         "instance is present.");
784     return (-1);
785   }
786
787   /* Decrypt the packet in-place */
788   err = gcry_cipher_decrypt (se->cypher,
789       buffer + sizeof (pea.head), buffer_len - sizeof (pea.head),
790       /* in = */ NULL, /* in len = */ 0);
791   if (err != 0)
792   {
793     ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
794         gcry_strerror (err));
795     return (-1);
796   }
797
798   /* Copy the header information to `pea' */
799   memcpy (&pea, buffer, sizeof (pea));
800   buffer += sizeof (pea);
801   buffer_len -= sizeof (pea);
802
803   /* Check sanity of the original length */
804   orig_buffer_len = ntohs (pea.orig_length);
805   if (orig_buffer_len > buffer_len)
806   {
807     ERROR ("network plugin: Decryption failed: Invalid original length.");
808     return (-1);
809   }
810
811   /* Check hash sum */
812   memset (hash, 0, sizeof (hash));
813   gcry_md_hash_buffer (GCRY_MD_SHA224, hash, buffer, orig_buffer_len);
814   
815   if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
816   {
817     ERROR ("network plugin: Decryption failed: Checksum mismatch.");
818     return (-1);
819   }
820
821   /* Update return values */
822   *ret_buffer = buffer;
823   *ret_buffer_len = orig_buffer_len;
824
825   return (0);
826 } /* }}} int parse_part_encr_aes256 */
827 /* #endif HAVE_GCRYPT_H */
828
829 #else /* if !HAVE_GCRYPT_H */
830 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
831     void **ret_buffer, int *ret_buffer_len)
832 {
833   INFO ("network plugin: Received encrypted packet, but the network "
834       "plugin was not linked with libgcrypt, so I cannot "
835       "decrypt it. The packet will be discarded.");
836   return (-1);
837 } /* }}} int parse_part_encr_aes256 */
838 #endif /* !HAVE_GCRYPT_H */
839
840 static int parse_packet (receive_list_entry_t *rle) /* {{{ */
841 {
842         int status;
843
844         void *buffer;
845         int buffer_len;
846         sockent_t *se;
847
848         value_list_t vl = VALUE_LIST_INIT;
849         notification_t n;
850
851         int packet_was_encrypted = 0;
852         int packet_was_signed = 0;
853 #if HAVE_GCRYPT_H
854         int printed_ignore_warning = 0;
855 #endif /* HAVE_GCRYPT_H */
856
857         buffer = rle->data;
858         buffer_len = rle->data_len;
859
860         /* Look for the correct `sockent_t' */
861         se = listen_sockets;
862         while ((se != NULL) && (se->fd != rle->fd))
863                 se = se->next;
864
865         if (se == NULL)
866         {
867                 ERROR ("network plugin: Got packet from FD %i, but can't "
868                                 "find an appropriate socket entry.",
869                                 rle->fd);
870                 return (-1);
871         }
872
873         memset (&vl, '\0', sizeof (vl));
874         memset (&n, '\0', sizeof (n));
875         status = 0;
876
877         while ((status == 0) && (0 < buffer_len)
878                         && ((unsigned int) buffer_len > sizeof (part_header_t)))
879         {
880                 uint16_t pkg_length;
881                 uint16_t pkg_type;
882
883                 memcpy ((void *) &pkg_type,
884                                 (void *) buffer,
885                                 sizeof (pkg_type));
886                 memcpy ((void *) &pkg_length,
887                                 (void *) (buffer + sizeof (pkg_type)),
888                                 sizeof (pkg_length));
889
890                 pkg_length = ntohs (pkg_length);
891                 pkg_type = ntohs (pkg_type);
892
893                 if (pkg_length > buffer_len)
894                         break;
895                 /* Ensure that this loop terminates eventually */
896                 if (pkg_length < (2 * sizeof (uint16_t)))
897                         break;
898
899                 if (pkg_type == TYPE_ENCR_AES256)
900                 {
901                         status = parse_part_encr_aes256 (se, &buffer, &buffer_len);
902                         if (status != 0)
903                         {
904                                 ERROR ("network plugin: Decrypting AES256 "
905                                                 "part failed "
906                                                 "with status %i.", status);
907                                 break;
908                         }
909                         else
910                         {
911                                 packet_was_encrypted = 1;
912                         }
913                 }
914 #if HAVE_GCRYPT_H
915                 else if ((se->security_level == SECURITY_LEVEL_ENCRYPT)
916                                 && (packet_was_encrypted == 0))
917                 {
918                         if (printed_ignore_warning == 0)
919                         {
920                                 INFO ("network plugin: Unencrypted packet or "
921                                                 "part has been ignored.");
922                                 printed_ignore_warning = 1;
923                         }
924                         buffer = ((char *) buffer) + pkg_length;
925                         continue;
926                 }
927 #endif /* HAVE_GCRYPT_H */
928                 else if (pkg_type == TYPE_SIGN_SHA256)
929                 {
930                         status = parse_part_sign_sha256 (se, &buffer, &buffer_len);
931                         if (status < 0)
932                         {
933                                 ERROR ("network plugin: Verifying SHA-256 "
934                                                 "signature failed "
935                                                 "with status %i.", status);
936                                 break;
937                         }
938                         else if (status > 0)
939                         {
940                                 ERROR ("network plugin: Ignoring packet with "
941                                                 "invalid SHA-256 signature.");
942                                 break;
943                         }
944                         else
945                         {
946                                 packet_was_signed = 1;
947                         }
948                 }
949 #if HAVE_GCRYPT_H
950                 else if ((se->security_level == SECURITY_LEVEL_SIGN)
951                                 && (packet_was_encrypted == 0)
952                                 && (packet_was_signed == 0))
953                 {
954                         if (printed_ignore_warning == 0)
955                         {
956                                 INFO ("network plugin: Unsigned packet or "
957                                                 "part has been ignored.");
958                                 printed_ignore_warning = 1;
959                         }
960                         buffer = ((char *) buffer) + pkg_length;
961                         continue;
962                 }
963 #endif /* HAVE_GCRYPT_H */
964                 else if (pkg_type == TYPE_VALUES)
965                 {
966                         status = parse_part_values (&buffer, &buffer_len,
967                                         &vl.values, &vl.values_len);
968
969                         if (status != 0)
970                                 break;
971
972                         if ((vl.time > 0)
973                                         && (strlen (vl.host) > 0)
974                                         && (strlen (vl.plugin) > 0)
975                                         && (strlen (vl.type) > 0)
976                                         && (cache_check (&vl) == 0))
977                         {
978                                 plugin_dispatch_values (&vl);
979                         }
980                         else
981                         {
982                                 DEBUG ("network plugin: parse_packet:"
983                                                 " NOT dispatching values");
984                         }
985
986                         sfree (vl.values);
987                 }
988                 else if (pkg_type == TYPE_TIME)
989                 {
990                         uint64_t tmp = 0;
991                         status = parse_part_number (&buffer, &buffer_len,
992                                         &tmp);
993                         if (status == 0)
994                         {
995                                 vl.time = (time_t) tmp;
996                                 n.time = (time_t) tmp;
997                         }
998                 }
999                 else if (pkg_type == TYPE_INTERVAL)
1000                 {
1001                         uint64_t tmp = 0;
1002                         status = parse_part_number (&buffer, &buffer_len,
1003                                         &tmp);
1004                         if (status == 0)
1005                                 vl.interval = (int) tmp;
1006                 }
1007                 else if (pkg_type == TYPE_HOST)
1008                 {
1009                         status = parse_part_string (&buffer, &buffer_len,
1010                                         vl.host, sizeof (vl.host));
1011                         if (status == 0)
1012                                 sstrncpy (n.host, vl.host, sizeof (n.host));
1013                 }
1014                 else if (pkg_type == TYPE_PLUGIN)
1015                 {
1016                         status = parse_part_string (&buffer, &buffer_len,
1017                                         vl.plugin, sizeof (vl.plugin));
1018                         if (status == 0)
1019                                 sstrncpy (n.plugin, vl.plugin,
1020                                                 sizeof (n.plugin));
1021                 }
1022                 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1023                 {
1024                         status = parse_part_string (&buffer, &buffer_len,
1025                                         vl.plugin_instance,
1026                                         sizeof (vl.plugin_instance));
1027                         if (status == 0)
1028                                 sstrncpy (n.plugin_instance,
1029                                                 vl.plugin_instance,
1030                                                 sizeof (n.plugin_instance));
1031                 }
1032                 else if (pkg_type == TYPE_TYPE)
1033                 {
1034                         status = parse_part_string (&buffer, &buffer_len,
1035                                         vl.type, sizeof (vl.type));
1036                         if (status == 0)
1037                                 sstrncpy (n.type, vl.type, sizeof (n.type));
1038                 }
1039                 else if (pkg_type == TYPE_TYPE_INSTANCE)
1040                 {
1041                         status = parse_part_string (&buffer, &buffer_len,
1042                                         vl.type_instance,
1043                                         sizeof (vl.type_instance));
1044                         if (status == 0)
1045                                 sstrncpy (n.type_instance, vl.type_instance,
1046                                                 sizeof (n.type_instance));
1047                 }
1048                 else if (pkg_type == TYPE_MESSAGE)
1049                 {
1050                         status = parse_part_string (&buffer, &buffer_len,
1051                                         n.message, sizeof (n.message));
1052
1053                         if (status != 0)
1054                         {
1055                                 /* do nothing */
1056                         }
1057                         else if ((n.severity != NOTIF_FAILURE)
1058                                         && (n.severity != NOTIF_WARNING)
1059                                         && (n.severity != NOTIF_OKAY))
1060                         {
1061                                 INFO ("network plugin: "
1062                                                 "Ignoring notification with "
1063                                                 "unknown severity %i.",
1064                                                 n.severity);
1065                         }
1066                         else if (n.time <= 0)
1067                         {
1068                                 INFO ("network plugin: "
1069                                                 "Ignoring notification with "
1070                                                 "time == 0.");
1071                         }
1072                         else if (strlen (n.message) <= 0)
1073                         {
1074                                 INFO ("network plugin: "
1075                                                 "Ignoring notification with "
1076                                                 "an empty message.");
1077                         }
1078                         else
1079                         {
1080                                 plugin_dispatch_notification (&n);
1081                         }
1082                 }
1083                 else if (pkg_type == TYPE_SEVERITY)
1084                 {
1085                         uint64_t tmp = 0;
1086                         status = parse_part_number (&buffer, &buffer_len,
1087                                         &tmp);
1088                         if (status == 0)
1089                                 n.severity = (int) tmp;
1090                 }
1091                 else
1092                 {
1093                         DEBUG ("network plugin: parse_packet: Unknown part"
1094                                         " type: 0x%04hx", pkg_type);
1095                         buffer = ((char *) buffer) + pkg_length;
1096                 }
1097         } /* while (buffer_len > sizeof (part_header_t)) */
1098
1099         return (status);
1100 } /* }}} int parse_packet */
1101
1102 static void free_sockent (sockent_t *se) /* {{{ */
1103 {
1104         sockent_t *next;
1105         while (se != NULL)
1106         {
1107                 next = se->next;
1108
1109 #if HAVE_GCRYPT_H
1110                 if (se->cypher != NULL)
1111                 {
1112                         gcry_cipher_close (se->cypher);
1113                         se->cypher = NULL;
1114                 }
1115                 free (se->shared_secret);
1116 #endif /* HAVE_GCRYPT_H */
1117
1118                 free (se->addr);
1119                 free (se);
1120
1121                 se = next;
1122         }
1123 } /* }}} void free_sockent */
1124
1125 /*
1126  * int network_set_ttl
1127  *
1128  * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1129  * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1130  *
1131  * The `struct addrinfo' is used to destinguish between unicast and multicast
1132  * sockets.
1133  */
1134 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1135 {
1136         if ((network_config_ttl < 1) || (network_config_ttl > 255))
1137                 return (-1);
1138
1139         DEBUG ("ttl = %i", network_config_ttl);
1140
1141         if (ai->ai_family == AF_INET)
1142         {
1143                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1144                 int optname;
1145
1146                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1147                         optname = IP_MULTICAST_TTL;
1148                 else
1149                         optname = IP_TTL;
1150
1151                 if (setsockopt (se->fd, IPPROTO_IP, optname,
1152                                         &network_config_ttl,
1153                                         sizeof (network_config_ttl)) == -1)
1154                 {
1155                         char errbuf[1024];
1156                         ERROR ("setsockopt: %s",
1157                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1158                         return (-1);
1159                 }
1160         }
1161         else if (ai->ai_family == AF_INET6)
1162         {
1163                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1164                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1165                 int optname;
1166
1167                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1168                         optname = IPV6_MULTICAST_HOPS;
1169                 else
1170                         optname = IPV6_UNICAST_HOPS;
1171
1172                 if (setsockopt (se->fd, IPPROTO_IPV6, optname,
1173                                         &network_config_ttl,
1174                                         sizeof (network_config_ttl)) == -1)
1175                 {
1176                         char errbuf[1024];
1177                         ERROR ("setsockopt: %s",
1178                                         sstrerror (errno, errbuf,
1179                                                 sizeof (errbuf)));
1180                         return (-1);
1181                 }
1182         }
1183
1184         return (0);
1185 } /* int network_set_ttl */
1186
1187 #if HAVE_GCRYPT_H
1188 static int network_set_encryption (sockent_t *se, /* {{{ */
1189                 const char *shared_secret)
1190 {
1191   char hash[32];
1192   gcry_error_t err;
1193
1194   se->shared_secret = sstrdup (shared_secret);
1195
1196   err = gcry_cipher_open (&se->cypher,
1197       GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, /* flags = */ 0);
1198   if (err != 0)
1199   {
1200     ERROR ("network plugin: gcry_cipher_open returned: %s",
1201         gcry_strerror (err));
1202     return (-1);
1203   }
1204
1205   err = gcry_cipher_setiv (se->cypher, network_encryption_iv,
1206       sizeof (network_encryption_iv));
1207   if (err != 0)
1208   {
1209     ERROR ("network plugin: gcry_cipher_setiv returned: %s",
1210         gcry_strerror (err));
1211     gcry_cipher_close (se->cypher);
1212     se->cypher = NULL;
1213     return (-1);
1214   }
1215
1216   assert (se->shared_secret != NULL);
1217   gcry_md_hash_buffer (GCRY_MD_SHA256, hash,
1218       se->shared_secret, strlen (se->shared_secret));
1219
1220   err = gcry_cipher_setkey (se->cypher, hash, sizeof (hash));
1221   if (err != 0)
1222   {
1223     DEBUG ("network plugin: gcry_cipher_setkey returned: %s",
1224         gcry_strerror (err));
1225     gcry_cipher_close (se->cypher);
1226     se->cypher = NULL;
1227     return (-1);
1228   }
1229
1230   return (0);
1231 } /* }}} int network_set_encryption */
1232 #endif /* HAVE_GCRYPT_H */
1233
1234 static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
1235 {
1236         int loop = 0;
1237         int yes  = 1;
1238
1239         /* allow multiple sockets to use the same PORT number */
1240         if (setsockopt(se->fd, SOL_SOCKET, SO_REUSEADDR,
1241                                 &yes, sizeof(yes)) == -1) {
1242                 char errbuf[1024];
1243                 ERROR ("setsockopt: %s", 
1244                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1245                 return (-1);
1246         }
1247
1248         DEBUG ("fd = %i; calling `bind'", se->fd);
1249
1250         if (bind (se->fd, ai->ai_addr, ai->ai_addrlen) == -1)
1251         {
1252                 char errbuf[1024];
1253                 ERROR ("bind: %s",
1254                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1255                 return (-1);
1256         }
1257
1258         if (ai->ai_family == AF_INET)
1259         {
1260                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1261                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1262                 {
1263                         struct ip_mreq mreq;
1264
1265                         DEBUG ("fd = %i; IPv4 multicast address found", se->fd);
1266
1267                         mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1268                         mreq.imr_interface.s_addr = htonl (INADDR_ANY);
1269
1270                         if (setsockopt (se->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1271                                                 &loop, sizeof (loop)) == -1)
1272                         {
1273                                 char errbuf[1024];
1274                                 ERROR ("setsockopt: %s",
1275                                                 sstrerror (errno, errbuf,
1276                                                         sizeof (errbuf)));
1277                                 return (-1);
1278                         }
1279
1280                         if (setsockopt (se->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1281                                                 &mreq, sizeof (mreq)) == -1)
1282                         {
1283                                 char errbuf[1024];
1284                                 ERROR ("setsockopt: %s",
1285                                                 sstrerror (errno, errbuf,
1286                                                         sizeof (errbuf)));
1287                                 return (-1);
1288                         }
1289                 }
1290         }
1291         else if (ai->ai_family == AF_INET6)
1292         {
1293                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1294                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1295                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1296                 {
1297                         struct ipv6_mreq mreq;
1298
1299                         DEBUG ("fd = %i; IPv6 multicast address found", se->fd);
1300
1301                         memcpy (&mreq.ipv6mr_multiaddr,
1302                                         &addr->sin6_addr,
1303                                         sizeof (addr->sin6_addr));
1304
1305                         /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1306                          * ipv6mr_interface may be set to zeroes to
1307                          * choose the default multicast interface or to
1308                          * the index of a particular multicast-capable
1309                          * interface if the host is multihomed.
1310                          * Membership is associ-associated with a
1311                          * single interface; programs running on
1312                          * multihomed hosts may need to join the same
1313                          * group on more than one interface.*/
1314                         mreq.ipv6mr_interface = 0;
1315
1316                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1317                                                 &loop, sizeof (loop)) == -1)
1318                         {
1319                                 char errbuf[1024];
1320                                 ERROR ("setsockopt: %s",
1321                                                 sstrerror (errno, errbuf,
1322                                                         sizeof (errbuf)));
1323                                 return (-1);
1324                         }
1325
1326                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1327                                                 &mreq, sizeof (mreq)) == -1)
1328                         {
1329                                 char errbuf[1024];
1330                                 ERROR ("setsockopt: %s",
1331                                                 sstrerror (errno, errbuf,
1332                                                         sizeof (errbuf)));
1333                                 return (-1);
1334                         }
1335                 }
1336         }
1337
1338         return (0);
1339 } /* int network_bind_socket */
1340
1341 #define CREATE_SOCKET_FLAGS_LISTEN    0x0001
1342 static sockent_t *network_create_socket (const char *node, /* {{{ */
1343                 const char *service,
1344                 const char *shared_secret,
1345                 int security_level,
1346                 int flags)
1347 {
1348         struct addrinfo  ai_hints;
1349         struct addrinfo *ai_list, *ai_ptr;
1350         int              ai_return;
1351
1352         sockent_t *se_head = NULL;
1353         sockent_t *se_tail = NULL;
1354
1355         DEBUG ("node = %s, service = %s", node, service);
1356
1357         memset (&ai_hints, '\0', sizeof (ai_hints));
1358         ai_hints.ai_flags    = 0;
1359 #ifdef AI_PASSIVE
1360         ai_hints.ai_flags |= AI_PASSIVE;
1361 #endif
1362 #ifdef AI_ADDRCONFIG
1363         ai_hints.ai_flags |= AI_ADDRCONFIG;
1364 #endif
1365         ai_hints.ai_family   = AF_UNSPEC;
1366         ai_hints.ai_socktype = SOCK_DGRAM;
1367         ai_hints.ai_protocol = IPPROTO_UDP;
1368
1369         ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
1370         if (ai_return != 0)
1371         {
1372                 char errbuf[1024];
1373                 ERROR ("getaddrinfo (%s, %s): %s",
1374                                 (node == NULL) ? "(null)" : node,
1375                                 (service == NULL) ? "(null)" : service,
1376                                 (ai_return == EAI_SYSTEM)
1377                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
1378                                 : gai_strerror (ai_return));
1379                 return (NULL);
1380         }
1381
1382         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1383         {
1384                 sockent_t *se;
1385                 int status;
1386
1387                 if ((se = (sockent_t *) malloc (sizeof (sockent_t))) == NULL)
1388                 {
1389                         char errbuf[1024];
1390                         ERROR ("malloc: %s",
1391                                         sstrerror (errno, errbuf,
1392                                                 sizeof (errbuf)));
1393                         continue;
1394                 }
1395
1396                 if ((se->addr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage))) == NULL)
1397                 {
1398                         char errbuf[1024];
1399                         ERROR ("malloc: %s",
1400                                         sstrerror (errno, errbuf,
1401                                                 sizeof (errbuf)));
1402                         free (se);
1403                         continue;
1404                 }
1405
1406                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1407                 memset (se->addr, '\0', sizeof (struct sockaddr_storage));
1408                 memcpy (se->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1409                 se->addrlen = ai_ptr->ai_addrlen;
1410
1411                 se->fd   = socket (ai_ptr->ai_family,
1412                                 ai_ptr->ai_socktype,
1413                                 ai_ptr->ai_protocol);
1414                 se->next = NULL;
1415
1416                 if (se->fd == -1)
1417                 {
1418                         char errbuf[1024];
1419                         ERROR ("socket: %s",
1420                                         sstrerror (errno, errbuf,
1421                                                 sizeof (errbuf)));
1422                         free (se->addr);
1423                         free (se);
1424                         continue;
1425                 }
1426
1427                 if ((flags & CREATE_SOCKET_FLAGS_LISTEN) != 0)
1428                 {
1429                         status = network_bind_socket (se, ai_ptr);
1430                         if (status != 0)
1431                         {
1432                                 close (se->fd);
1433                                 free (se->addr);
1434                                 free (se);
1435                                 continue;
1436                         }
1437                 }
1438                 else /* sending socket */
1439                 {
1440                         network_set_ttl (se, ai_ptr);
1441                 }
1442
1443 #if HAVE_GCRYPT_H
1444                 se->security_level = security_level;
1445                 se->shared_secret = NULL;
1446                 se->cypher = NULL;
1447                 if (shared_secret != NULL)
1448                 {
1449                         status = network_set_encryption (se, shared_secret);
1450                         if ((status != 0) && (security_level <= SECURITY_LEVEL_SIGN))
1451                         {
1452                                 WARNING ("network plugin: Starting cryptograp"
1453                                                 "hic subsystem failed. Since "
1454                                                 "security level `Sign' or "
1455                                                 "`None' is configured I will "
1456                                                 "continue.");
1457                         }
1458                         else if (status != 0)
1459                         {
1460                                 ERROR ("network plugin: Starting cryptograp"
1461                                                 "hic subsystem failed. "
1462                                                 "Because the security level "
1463                                                 "is set to `Encrypt' I will "
1464                                                 "not continue!");
1465                                 close (se->fd);
1466                                 free (se->addr);
1467                                 free (se);
1468                                 continue;
1469                         }
1470                 } /* if (shared_secret != NULL) */
1471 #else
1472                 /* Make compiler happy */
1473                 security_level = 0;
1474                 shared_secret = NULL;
1475 #endif /* HAVE_GCRYPT_H */
1476
1477                 if (se_tail == NULL)
1478                 {
1479                         se_head = se;
1480                         se_tail = se;
1481                 }
1482                 else
1483                 {
1484                         se_tail->next = se;
1485                         se_tail = se;
1486                 }
1487
1488                 /* We don't open more than one write-socket per node/service pair.. */
1489                 if ((flags & CREATE_SOCKET_FLAGS_LISTEN) == 0)
1490                         break;
1491         }
1492
1493         freeaddrinfo (ai_list);
1494
1495         return (se_head);
1496 } /* }}} sockent_t *network_create_socket */
1497
1498 static sockent_t *network_create_default_socket (int flags) /* {{{ */
1499 {
1500         sockent_t *se_ptr  = NULL;
1501         sockent_t *se_head = NULL;
1502         sockent_t *se_tail = NULL;
1503
1504         se_ptr = network_create_socket (NET_DEFAULT_V6_ADDR, NET_DEFAULT_PORT,
1505                         /* shared secret = */ NULL, SECURITY_LEVEL_NONE,
1506                         flags);
1507
1508         /* Don't send to the same machine in IPv6 and IPv4 if both are available. */
1509         if (((flags & CREATE_SOCKET_FLAGS_LISTEN) == 0) && (se_ptr != NULL))
1510                 return (se_ptr);
1511
1512         if (se_ptr != NULL)
1513         {
1514                 se_head = se_ptr;
1515                 se_tail = se_ptr;
1516                 while (se_tail->next != NULL)
1517                         se_tail = se_tail->next;
1518         }
1519
1520         se_ptr = network_create_socket (NET_DEFAULT_V4_ADDR, NET_DEFAULT_PORT,
1521                         /* shared secret = */ NULL, SECURITY_LEVEL_NONE,
1522                         flags);
1523
1524         if (se_tail == NULL)
1525                 return (se_ptr);
1526
1527         se_tail->next = se_ptr;
1528         return (se_head);
1529 } /* }}} sockent_t *network_create_default_socket */
1530
1531 static int network_add_listen_socket (const char *node, /* {{{ */
1532     const char *service, const char *shared_secret, int security_level)
1533 {
1534         sockent_t *se;
1535         sockent_t *se_ptr;
1536         int se_num = 0;
1537
1538         int flags;
1539
1540         flags = CREATE_SOCKET_FLAGS_LISTEN;
1541
1542         if (service == NULL)
1543                 service = NET_DEFAULT_PORT;
1544
1545         if (node == NULL)
1546                 se = network_create_default_socket (flags);
1547         else
1548                 se = network_create_socket (node, service,
1549                     shared_secret, security_level, flags);
1550
1551         if (se == NULL)
1552                 return (-1);
1553
1554         for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
1555                 se_num++;
1556
1557         listen_sockets_pollfd = realloc (listen_sockets_pollfd,
1558                         (listen_sockets_num + se_num)
1559                         * sizeof (struct pollfd));
1560
1561         for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
1562         {
1563                 listen_sockets_pollfd[listen_sockets_num].fd = se_ptr->fd;
1564                 listen_sockets_pollfd[listen_sockets_num].events = POLLIN | POLLPRI;
1565                 listen_sockets_pollfd[listen_sockets_num].revents = 0;
1566                 listen_sockets_num++;
1567         } /* for (se) */
1568
1569         se_ptr = listen_sockets;
1570         while ((se_ptr != NULL) && (se_ptr->next != NULL))
1571                 se_ptr = se_ptr->next;
1572
1573         if (se_ptr == NULL)
1574                 listen_sockets = se;
1575         else
1576                 se_ptr->next = se;
1577
1578         return (0);
1579 } /* }}} int network_add_listen_socket */
1580
1581 static int network_add_sending_socket (const char *node, /* {{{ */
1582     const char *service, const char *shared_secret, int security_level)
1583 {
1584         sockent_t *se;
1585         sockent_t *se_ptr;
1586
1587         if (service == NULL)
1588                 service = NET_DEFAULT_PORT;
1589
1590         if (node == NULL)
1591                 se = network_create_default_socket (/* flags = */ 0);
1592         else
1593                 se = network_create_socket (node, service,
1594                                 shared_secret, security_level,
1595                                 /* flags = */ 0);
1596
1597         if (se == NULL)
1598                 return (-1);
1599
1600         if (sending_sockets == NULL)
1601         {
1602                 sending_sockets = se;
1603                 return (0);
1604         }
1605
1606         for (se_ptr = sending_sockets; se_ptr->next != NULL; se_ptr = se_ptr->next)
1607                 /* seek end */;
1608
1609         se_ptr->next = se;
1610         return (0);
1611 } /* }}} int network_add_sending_socket */
1612
1613 static void *dispatch_thread (void __attribute__((unused)) *arg)
1614 {
1615   while (42)
1616   {
1617     receive_list_entry_t *ent;
1618
1619     /* Lock and wait for more data to come in */
1620     pthread_mutex_lock (&receive_list_lock);
1621     while ((listen_loop == 0)
1622         && (receive_list_head == NULL))
1623       pthread_cond_wait (&receive_list_cond, &receive_list_lock);
1624
1625     /* Remove the head entry and unlock */
1626     ent = receive_list_head;
1627     if (ent != NULL)
1628       receive_list_head = ent->next;
1629     pthread_mutex_unlock (&receive_list_lock);
1630
1631     /* Check whether we are supposed to exit. We do NOT check `listen_loop'
1632      * because we dispatch all missing packets before shutting down. */
1633     if (ent == NULL)
1634       break;
1635
1636     parse_packet (ent);
1637
1638     sfree (ent);
1639   } /* while (42) */
1640
1641   return (NULL);
1642 } /* void *dispatch_thread */
1643
1644 static int network_receive (void)
1645 {
1646         char buffer[BUFF_SIZE];
1647         int  buffer_len;
1648
1649         int i;
1650         int status;
1651
1652         receive_list_entry_t *private_list_head;
1653         receive_list_entry_t *private_list_tail;
1654
1655         if (listen_sockets_num == 0)
1656                 network_add_listen_socket (/* node = */ NULL,
1657                                 /* service = */ NULL,
1658                                 /* shared secret = */ NULL,
1659                                 /* encryption = */ 0);
1660
1661         if (listen_sockets_num == 0)
1662         {
1663                 ERROR ("network: Failed to open a listening socket.");
1664                 return (-1);
1665         }
1666
1667         private_list_head = NULL;
1668         private_list_tail = NULL;
1669
1670         while (listen_loop == 0)
1671         {
1672                 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
1673
1674                 if (status <= 0)
1675                 {
1676                         char errbuf[1024];
1677                         if (errno == EINTR)
1678                                 continue;
1679                         ERROR ("poll failed: %s",
1680                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1681                         return (-1);
1682                 }
1683
1684                 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
1685                 {
1686                         receive_list_entry_t *ent;
1687
1688                         if ((listen_sockets_pollfd[i].revents
1689                                                 & (POLLIN | POLLPRI)) == 0)
1690                                 continue;
1691                         status--;
1692
1693                         buffer_len = recv (listen_sockets_pollfd[i].fd,
1694                                         buffer, sizeof (buffer),
1695                                         0 /* no flags */);
1696                         if (buffer_len < 0)
1697                         {
1698                                 char errbuf[1024];
1699                                 ERROR ("recv failed: %s",
1700                                                 sstrerror (errno, errbuf,
1701                                                         sizeof (errbuf)));
1702                                 return (-1);
1703                         }
1704
1705                         /* TODO: Possible performance enhancement: Do not free
1706                          * these entries in the dispatch thread but put them in
1707                          * another list, so we don't have to allocate more and
1708                          * more of these structures. */
1709                         ent = malloc (sizeof (receive_list_entry_t));
1710                         if (ent == NULL)
1711                         {
1712                                 ERROR ("network plugin: malloc failed.");
1713                                 return (-1);
1714                         }
1715                         memset (ent, 0, sizeof (receive_list_entry_t));
1716                         ent->fd = listen_sockets_pollfd[i].fd;
1717                         ent->next = NULL;
1718
1719                         /* Hopefully this be optimized out by the compiler. It
1720                          * might help prevent stupid bugs in the future though.
1721                          */
1722                         assert (sizeof (ent->data) == sizeof (buffer));
1723
1724                         memcpy (ent->data, buffer, buffer_len);
1725                         ent->data_len = buffer_len;
1726
1727                         if (private_list_head == NULL)
1728                                 private_list_head = ent;
1729                         else
1730                                 private_list_tail->next = ent;
1731                         private_list_tail = ent;
1732
1733                         /* Do not block here. Blocking here has led to
1734                          * insufficient performance in the past. */
1735                         if (pthread_mutex_trylock (&receive_list_lock) == 0)
1736                         {
1737                                 if (receive_list_head == NULL)
1738                                         receive_list_head = private_list_head;
1739                                 else
1740                                         receive_list_tail->next = private_list_head;
1741                                 receive_list_tail = private_list_tail;
1742
1743                                 private_list_head = NULL;
1744                                 private_list_tail = NULL;
1745
1746                                 pthread_cond_signal (&receive_list_cond);
1747                                 pthread_mutex_unlock (&receive_list_lock);
1748                         }
1749                 } /* for (listen_sockets_pollfd) */
1750         } /* while (listen_loop == 0) */
1751
1752         /* Make sure everything is dispatched before exiting. */
1753         if (private_list_head != NULL)
1754         {
1755                 pthread_mutex_lock (&receive_list_lock);
1756
1757                 if (receive_list_head == NULL)
1758                         receive_list_head = private_list_head;
1759                 else
1760                         receive_list_tail->next = private_list_head;
1761                 receive_list_tail = private_list_tail;
1762
1763                 private_list_head = NULL;
1764                 private_list_tail = NULL;
1765
1766                 pthread_cond_signal (&receive_list_cond);
1767                 pthread_mutex_unlock (&receive_list_lock);
1768         }
1769
1770         return (0);
1771 } /* int network_receive */
1772
1773 static void *receive_thread (void __attribute__((unused)) *arg)
1774 {
1775         return (network_receive () ? (void *) 1 : (void *) 0);
1776 } /* void *receive_thread */
1777
1778 static void network_init_buffer (void)
1779 {
1780         memset (send_buffer, 0, sizeof (send_buffer));
1781         send_buffer_ptr = send_buffer;
1782         send_buffer_fill = 0;
1783
1784         memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
1785 } /* int network_init_buffer */
1786
1787 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
1788                 const char *buffer, size_t buffer_size)
1789 {
1790         int status;
1791
1792         while (42)
1793         {
1794                 status = sendto (se->fd, buffer, buffer_size, 0 /* no flags */,
1795                                 (struct sockaddr *) se->addr, se->addrlen);
1796                 if (status < 0)
1797                 {
1798                         char errbuf[1024];
1799                         if (errno == EINTR)
1800                                 continue;
1801                         ERROR ("network plugin: sendto failed: %s",
1802                                         sstrerror (errno, errbuf,
1803                                                 sizeof (errbuf)));
1804                         break;
1805                 }
1806
1807                 break;
1808         } /* while (42) */
1809 } /* }}} void networt_send_buffer_plain */
1810
1811 #if HAVE_GCRYPT_H
1812 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
1813                 const char *in_buffer, size_t in_buffer_size)
1814 {
1815         part_signature_sha256_t ps;
1816         char buffer[sizeof (ps) + in_buffer_size];
1817         char hash[sizeof (ps.hash)];
1818
1819         /* Initialize the `ps' structure. */
1820         memset (&ps, 0, sizeof (ps));
1821         ps.head.type = htons (TYPE_SIGN_SHA256);
1822         ps.head.length = htons ((uint16_t) sizeof (ps));
1823         sstrncpy (ps.hash, se->shared_secret, sizeof (ps.hash));
1824
1825         /* Prepend the signature. */
1826         memcpy (buffer, &ps, sizeof (ps));
1827         memcpy (buffer + sizeof (ps), in_buffer, in_buffer_size);
1828
1829         /* Calculate the hash value. */
1830         gcry_md_hash_buffer (GCRY_MD_SHA256, hash, buffer, sizeof (buffer));
1831
1832         /* Copy the hash value into the buffer. */
1833         memcpy (ps.hash, hash, sizeof (ps.hash));
1834         memcpy (buffer, &ps, sizeof (ps));
1835
1836         networt_send_buffer_plain (se, buffer, sizeof (buffer));
1837 } /* }}} void networt_send_buffer_signed */
1838
1839 static void networt_send_buffer_encrypted (const sockent_t *se, /* {{{ */
1840                 const char *in_buffer, size_t in_buffer_size)
1841 {
1842   part_encryption_aes256_t pea;
1843   char buffer[sizeof (pea) + in_buffer_size + 16];
1844   size_t buffer_size;
1845   gcry_error_t err;
1846
1847   /* Round to the next multiple of 16, because AES has a block size of 128 bit.
1848    * the first four bytes of `pea' are not encrypted and must be subtracted. */
1849   buffer_size = (sizeof (pea) + in_buffer_size + 15 - sizeof (pea.head)) / 16;
1850   buffer_size = buffer_size * 16;
1851   buffer_size += sizeof (pea.head);
1852
1853   DEBUG ("network plugin: networt_send_buffer_encrypted: "
1854       "buffer_size = %zu;", buffer_size);
1855
1856   /* Initialize the header fields */
1857   memset (&pea, 0, sizeof (pea));
1858   pea.head.type = htons (TYPE_ENCR_AES256);
1859   pea.head.length = htons ((uint16_t) buffer_size);
1860   pea.orig_length = htons ((uint16_t) in_buffer_size);
1861
1862   /* Fill the extra field with random values. Some entropy in the encrypted
1863    * data is usually not a bad thing, I hope. */
1864   gcry_randomize (&pea.random, sizeof (pea.random), GCRY_STRONG_RANDOM);
1865
1866   /* Create hash of the payload */
1867   gcry_md_hash_buffer (GCRY_MD_SHA224, pea.hash, in_buffer, in_buffer_size);
1868
1869   /* Initialize the buffer */
1870   memset (buffer, 0, sizeof (buffer));
1871   memcpy (buffer, &pea, sizeof (pea));
1872   memcpy (buffer + sizeof (pea), in_buffer, in_buffer_size);
1873
1874   /* Encrypt the buffer in-place */
1875   err = gcry_cipher_encrypt (se->cypher,
1876       buffer + sizeof (pea.head), buffer_size - sizeof (pea.head),
1877       /* in = */ NULL, /* in len = */ 0);
1878   if (err != 0)
1879   {
1880     ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
1881         gcry_strerror (err));
1882     return;
1883   }
1884
1885   /* Send it out without further modifications */
1886   networt_send_buffer_plain (se, buffer, buffer_size);
1887 } /* }}} void networt_send_buffer_encrypted */
1888 #endif /* HAVE_GCRYPT_H */
1889
1890 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
1891 {
1892   sockent_t *se;
1893
1894   DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
1895
1896   for (se = sending_sockets; se != NULL; se = se->next)
1897   {
1898 #if HAVE_GCRYPT_H
1899     if (se->security_level == SECURITY_LEVEL_ENCRYPT)
1900       networt_send_buffer_encrypted (se, buffer, buffer_len);
1901     else if (se->security_level == SECURITY_LEVEL_SIGN)
1902       networt_send_buffer_signed (se, buffer, buffer_len);
1903     else /* if (se->security_level == SECURITY_LEVEL_NONE) */
1904 #endif /* HAVE_GCRYPT_H */
1905       networt_send_buffer_plain (se, buffer, buffer_len);
1906   } /* for (sending_sockets) */
1907 } /* }}} void network_send_buffer */
1908
1909 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
1910                 value_list_t *vl_def,
1911                 const data_set_t *ds, const value_list_t *vl)
1912 {
1913         char *buffer_orig = buffer;
1914
1915         if (strcmp (vl_def->host, vl->host) != 0)
1916         {
1917                 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
1918                                         vl->host, strlen (vl->host)) != 0)
1919                         return (-1);
1920                 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
1921         }
1922
1923         if (vl_def->time != vl->time)
1924         {
1925                 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
1926                                         (uint64_t) vl->time))
1927                         return (-1);
1928                 vl_def->time = vl->time;
1929         }
1930
1931         if (vl_def->interval != vl->interval)
1932         {
1933                 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
1934                                         (uint64_t) vl->interval))
1935                         return (-1);
1936                 vl_def->interval = vl->interval;
1937         }
1938
1939         if (strcmp (vl_def->plugin, vl->plugin) != 0)
1940         {
1941                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
1942                                         vl->plugin, strlen (vl->plugin)) != 0)
1943                         return (-1);
1944                 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
1945         }
1946
1947         if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
1948         {
1949                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
1950                                         vl->plugin_instance,
1951                                         strlen (vl->plugin_instance)) != 0)
1952                         return (-1);
1953                 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
1954         }
1955
1956         if (strcmp (vl_def->type, vl->type) != 0)
1957         {
1958                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
1959                                         vl->type, strlen (vl->type)) != 0)
1960                         return (-1);
1961                 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
1962         }
1963
1964         if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
1965         {
1966                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
1967                                         vl->type_instance,
1968                                         strlen (vl->type_instance)) != 0)
1969                         return (-1);
1970                 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
1971         }
1972         
1973         if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
1974                 return (-1);
1975
1976         return (buffer - buffer_orig);
1977 } /* }}} int add_to_buffer */
1978
1979 static void flush_buffer (void)
1980 {
1981         DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
1982                         send_buffer_fill);
1983
1984         network_send_buffer (send_buffer, (size_t) send_buffer_fill);
1985         network_init_buffer ();
1986 }
1987
1988 static int network_write (const data_set_t *ds, const value_list_t *vl,
1989                 user_data_t __attribute__((unused)) *user_data)
1990 {
1991         int status;
1992
1993         /* If the value is already in the cache, we have received it via the
1994          * network. We write it again if forwarding is activated. It's then in
1995          * the cache and should we receive it again we will ignore it. */
1996         status = cache_check (vl);
1997         if ((network_config_forward == 0)
1998                         && (status != 0))
1999                 return (0);
2000
2001         pthread_mutex_lock (&send_buffer_lock);
2002
2003         status = add_to_buffer (send_buffer_ptr,
2004                         sizeof (send_buffer) - (send_buffer_fill + BUFF_SIG_SIZE),
2005                         &send_buffer_vl,
2006                         ds, vl);
2007         if (status >= 0)
2008         {
2009                 /* status == bytes added to the buffer */
2010                 send_buffer_fill += status;
2011                 send_buffer_ptr  += status;
2012         }
2013         else
2014         {
2015                 flush_buffer ();
2016
2017                 status = add_to_buffer (send_buffer_ptr,
2018                                 sizeof (send_buffer) - (send_buffer_fill + BUFF_SIG_SIZE),
2019                                 &send_buffer_vl,
2020                                 ds, vl);
2021
2022                 if (status >= 0)
2023                 {
2024                         send_buffer_fill += status;
2025                         send_buffer_ptr  += status;
2026                 }
2027         }
2028
2029         if (status < 0)
2030         {
2031                 ERROR ("network plugin: Unable to append to the "
2032                                 "buffer for some weird reason");
2033         }
2034         else if ((sizeof (send_buffer) - send_buffer_fill) < 15)
2035         {
2036                 flush_buffer ();
2037         }
2038
2039         pthread_mutex_unlock (&send_buffer_lock);
2040
2041         return ((status < 0) ? -1 : 0);
2042 } /* int network_write */
2043
2044 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2045     int *retval)
2046 {
2047   if ((ci->values_num != 1)
2048       || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2049         && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2050   {
2051     ERROR ("network plugin: The `%s' config option needs "
2052         "exactly one boolean argument.", ci->key);
2053     return (-1);
2054   }
2055
2056   if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2057   {
2058     if (ci->values[0].value.boolean)
2059       *retval = 1;
2060     else
2061       *retval = 0;
2062   }
2063   else
2064   {
2065     char *str = ci->values[0].value.string;
2066
2067     if ((strcasecmp ("true", str) == 0)
2068         || (strcasecmp ("yes", str) == 0)
2069         || (strcasecmp ("on", str) == 0))
2070       *retval = 1;
2071     else if ((strcasecmp ("false", str) == 0)
2072         || (strcasecmp ("no", str) == 0)
2073         || (strcasecmp ("off", str) == 0))
2074       *retval = 0;
2075     else
2076     {
2077       ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2078           "option as boolean value.",
2079           str, ci->key);
2080       return (-1);
2081     }
2082   }
2083
2084   return (0);
2085 } /* }}} int network_config_set_boolean */
2086
2087 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2088 {
2089   int tmp;
2090   if ((ci->values_num != 1)
2091       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2092   {
2093     WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2094         "one numeric argument.");
2095     return (-1);
2096   }
2097
2098   tmp = (int) ci->values[0].value.number;
2099   if ((tmp > 0) && (tmp <= 255))
2100     network_config_ttl = tmp;
2101
2102   return (0);
2103 } /* }}} int network_config_set_ttl */
2104
2105 #if HAVE_GCRYPT_H
2106 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2107     int *retval)
2108 {
2109   char *str;
2110   if ((ci->values_num != 1)
2111       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2112   {
2113     WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2114         "one string argument.");
2115     return (-1);
2116   }
2117
2118   str = ci->values[0].value.string;
2119   if (strcasecmp ("Encrypt", str) == 0)
2120     *retval = SECURITY_LEVEL_ENCRYPT;
2121   else if (strcasecmp ("Sign", str) == 0)
2122     *retval = SECURITY_LEVEL_SIGN;
2123   else if (strcasecmp ("None", str) == 0)
2124     *retval = SECURITY_LEVEL_NONE;
2125   else
2126   {
2127     WARNING ("network plugin: Unknown security level: %s.", str);
2128     return (-1);
2129   }
2130
2131   return (0);
2132 } /* }}} int network_config_set_security_level */
2133 #endif /* HAVE_GCRYPT_H */
2134
2135 static int network_config_listen_server (const oconfig_item_t *ci) /* {{{ */
2136 {
2137   char *node;
2138   char *service;
2139   char *shared_secret = NULL;
2140   int security_level = SECURITY_LEVEL_NONE;
2141   int i;
2142
2143   if ((ci->values_num < 1) || (ci->values_num > 2)
2144       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2145       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2146   {
2147     ERROR ("network plugin: The `%s' config option needs "
2148         "one or two string arguments.", ci->key);
2149     return (-1);
2150   }
2151
2152   node = ci->values[0].value.string;
2153   if (ci->values_num >= 2)
2154     service = ci->values[1].value.string;
2155   else
2156     service = NULL;
2157
2158   for (i = 0; i < ci->children_num; i++)
2159   {
2160     oconfig_item_t *child = ci->children + i;
2161
2162 #if HAVE_GCRYPT_H
2163     if (strcasecmp ("Secret", child->key) == 0)
2164     {
2165       if ((child->values_num == 1)
2166           && (child->values[0].type == OCONFIG_TYPE_STRING))
2167         shared_secret = child->values[0].value.string;
2168       else
2169         ERROR ("network plugin: The `Secret' option needs exactly one string "
2170             "argument.");
2171     }
2172     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2173       network_config_set_security_level (child, &security_level);
2174     else
2175 #endif /* HAVE_GCRYPT_H */
2176     {
2177       WARNING ("network plugin: Option `%s' is not allowed here.",
2178           child->key);
2179     }
2180   }
2181
2182   if ((security_level > SECURITY_LEVEL_NONE) && (shared_secret == NULL))
2183   {
2184     ERROR ("network plugin: A security level higher than `none' was "
2185         "requested, but no shared key was given. Cowardly refusing to open "
2186         "this socket!");
2187     return (-1);
2188   }
2189
2190   if (strcasecmp ("Listen", ci->key) == 0)
2191     network_add_listen_socket (node, service, shared_secret, security_level);
2192   else
2193     network_add_sending_socket (node, service, shared_secret, security_level);
2194
2195   return (0);
2196 } /* }}} int network_config_listen_server */
2197
2198 static int network_config_set_cache_flush (const oconfig_item_t *ci) /* {{{ */
2199 {
2200   int tmp;
2201   if ((ci->values_num != 1)
2202       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2203   {
2204     WARNING ("network plugin: The `CacheFlush' config option needs exactly "
2205         "one numeric argument.");
2206     return (-1);
2207   }
2208
2209   tmp = (int) ci->values[0].value.number;
2210   if (tmp > 0)
2211     network_config_ttl = tmp;
2212
2213   return (0);
2214 } /* }}} int network_config_set_cache_flush */
2215
2216 static int network_config (oconfig_item_t *ci) /* {{{ */
2217 {
2218   int i;
2219
2220   for (i = 0; i < ci->children_num; i++)
2221   {
2222     oconfig_item_t *child = ci->children + i;
2223
2224     if ((strcasecmp ("Listen", child->key) == 0)
2225         || (strcasecmp ("Server", child->key) == 0))
2226       network_config_listen_server (child);
2227     else if (strcasecmp ("TimeToLive", child->key) == 0)
2228       network_config_set_ttl (child);
2229     else if (strcasecmp ("Forward", child->key) == 0)
2230       network_config_set_boolean (child, &network_config_forward);
2231     else if (strcasecmp ("CacheFlush", child->key) == 0)
2232       network_config_set_cache_flush (child);
2233     else
2234     {
2235       WARNING ("network plugin: Option `%s' is not allowed here.",
2236           child->key);
2237     }
2238   }
2239
2240   return (0);
2241 } /* }}} int network_config */
2242
2243 static int network_notification (const notification_t *n,
2244                 user_data_t __attribute__((unused)) *user_data)
2245 {
2246   char  buffer[BUFF_SIZE];
2247   char *buffer_ptr = buffer;
2248   int   buffer_free = sizeof (buffer);
2249   int   status;
2250
2251   memset (buffer, '\0', sizeof (buffer));
2252
2253
2254   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
2255       (uint64_t) n->time);
2256   if (status != 0)
2257     return (-1);
2258
2259   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
2260       (uint64_t) n->severity);
2261   if (status != 0)
2262     return (-1);
2263
2264   if (strlen (n->host) > 0)
2265   {
2266     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
2267         n->host, strlen (n->host));
2268     if (status != 0)
2269       return (-1);
2270   }
2271
2272   if (strlen (n->plugin) > 0)
2273   {
2274     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
2275         n->plugin, strlen (n->plugin));
2276     if (status != 0)
2277       return (-1);
2278   }
2279
2280   if (strlen (n->plugin_instance) > 0)
2281   {
2282     status = write_part_string (&buffer_ptr, &buffer_free,
2283         TYPE_PLUGIN_INSTANCE,
2284         n->plugin_instance, strlen (n->plugin_instance));
2285     if (status != 0)
2286       return (-1);
2287   }
2288
2289   if (strlen (n->type) > 0)
2290   {
2291     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
2292         n->type, strlen (n->type));
2293     if (status != 0)
2294       return (-1);
2295   }
2296
2297   if (strlen (n->type_instance) > 0)
2298   {
2299     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
2300         n->type_instance, strlen (n->type_instance));
2301     if (status != 0)
2302       return (-1);
2303   }
2304
2305   status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
2306       n->message, strlen (n->message));
2307   if (status != 0)
2308     return (-1);
2309
2310   network_send_buffer (buffer, sizeof (buffer) - buffer_free);
2311
2312   return (0);
2313 } /* int network_notification */
2314
2315 static int network_shutdown (void)
2316 {
2317         listen_loop++;
2318
2319         /* Kill the listening thread */
2320         if (receive_thread_running != 0)
2321         {
2322                 INFO ("network plugin: Stopping receive thread.");
2323                 pthread_kill (receive_thread_id, SIGTERM);
2324                 pthread_join (receive_thread_id, NULL /* no return value */);
2325                 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
2326                 receive_thread_running = 0;
2327         }
2328
2329         /* Shutdown the dispatching thread */
2330         if (dispatch_thread_running != 0)
2331         {
2332                 INFO ("network plugin: Stopping dispatch thread.");
2333                 pthread_mutex_lock (&receive_list_lock);
2334                 pthread_cond_broadcast (&receive_list_cond);
2335                 pthread_mutex_unlock (&receive_list_lock);
2336                 pthread_join (dispatch_thread_id, /* ret = */ NULL);
2337                 dispatch_thread_running = 0;
2338         }
2339
2340         free_sockent (listen_sockets);
2341
2342         if (send_buffer_fill > 0)
2343                 flush_buffer ();
2344
2345         if (cache_tree != NULL)
2346         {
2347                 void *key;
2348                 void *value;
2349
2350                 while (c_avl_pick (cache_tree, &key, &value) == 0)
2351                 {
2352                         sfree (key);
2353                         sfree (value);
2354                 }
2355                 c_avl_destroy (cache_tree);
2356                 cache_tree = NULL;
2357         }
2358
2359         /* TODO: Close `sending_sockets' */
2360
2361         plugin_unregister_config ("network");
2362         plugin_unregister_init ("network");
2363         plugin_unregister_write ("network");
2364         plugin_unregister_shutdown ("network");
2365
2366         /* Let the init function do it's move again ;) */
2367         cache_flush_last = 0;
2368
2369         return (0);
2370 } /* int network_shutdown */
2371
2372 static int network_init (void)
2373 {
2374         /* Check if we were already initialized. If so, just return - there's
2375          * nothing more to do (for now, that is). */
2376         if (cache_flush_last != 0)
2377                 return (0);
2378
2379         plugin_register_shutdown ("network", network_shutdown);
2380
2381         network_init_buffer ();
2382
2383         cache_tree = c_avl_create ((int (*) (const void *, const void *)) strcmp);
2384         cache_flush_last = time (NULL);
2385
2386         /* setup socket(s) and so on */
2387         if (sending_sockets != NULL)
2388         {
2389                 plugin_register_write ("network", network_write,
2390                                 /* user_data = */ NULL);
2391                 plugin_register_notification ("network", network_notification,
2392                                 /* user_data = */ NULL);
2393         }
2394
2395         /* If no threads need to be started, return here. */
2396         if ((listen_sockets_num == 0)
2397                         || ((dispatch_thread_running != 0)
2398                                 && (receive_thread_running != 0)))
2399                 return (0);
2400
2401         if (dispatch_thread_running == 0)
2402         {
2403                 int status;
2404                 status = pthread_create (&dispatch_thread_id,
2405                                 NULL /* no attributes */,
2406                                 dispatch_thread,
2407                                 NULL /* no argument */);
2408                 if (status != 0)
2409                 {
2410                         char errbuf[1024];
2411                         ERROR ("network: pthread_create failed: %s",
2412                                         sstrerror (errno, errbuf,
2413                                                 sizeof (errbuf)));
2414                 }
2415                 else
2416                 {
2417                         dispatch_thread_running = 1;
2418                 }
2419         }
2420
2421         if (receive_thread_running == 0)
2422         {
2423                 int status;
2424                 status = pthread_create (&receive_thread_id,
2425                                 NULL /* no attributes */,
2426                                 receive_thread,
2427                                 NULL /* no argument */);
2428                 if (status != 0)
2429                 {
2430                         char errbuf[1024];
2431                         ERROR ("network: pthread_create failed: %s",
2432                                         sstrerror (errno, errbuf,
2433                                                 sizeof (errbuf)));
2434                 }
2435                 else
2436                 {
2437                         receive_thread_running = 1;
2438                 }
2439         }
2440
2441         return (0);
2442 } /* int network_init */
2443
2444 /* 
2445  * The flush option of the network plugin cannot flush individual identifiers.
2446  * All the values are added to a buffer and sent when the buffer is full, the
2447  * requested value may or may not be in there, it's not worth finding out. We
2448  * just send the buffer if `flush'  is called - if the requested value was in
2449  * there, good. If not, well, then there is nothing to flush.. -octo
2450  */
2451 static int network_flush (int timeout,
2452                 const char __attribute__((unused)) *identifier,
2453                 user_data_t __attribute__((unused)) *user_data)
2454 {
2455         pthread_mutex_lock (&send_buffer_lock);
2456
2457         if (((time (NULL) - cache_flush_last) >= timeout)
2458                         && (send_buffer_fill > 0))
2459         {
2460                 flush_buffer ();
2461         }
2462
2463         pthread_mutex_unlock (&send_buffer_lock);
2464
2465         return (0);
2466 } /* int network_flush */
2467
2468 void module_register (void)
2469 {
2470         plugin_register_complex_config ("network", network_config);
2471         plugin_register_init   ("network", network_init);
2472         plugin_register_flush   ("network", network_flush,
2473                         /* user_data = */ NULL);
2474 } /* void module_register */
2475
2476 /* vim: set fdm=marker : */