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