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