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