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