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