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