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