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