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