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