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