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