network plugin: Avoid "status may be used uninitialized" warning.
[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                 private_list_head = NULL;
2542                 private_list_tail = NULL;
2543                 private_list_length = 0;
2544
2545                 pthread_cond_signal (&receive_list_cond);
2546                 pthread_mutex_unlock (&receive_list_lock);
2547         }
2548
2549         return (status);
2550 } /* }}} int network_receive */
2551
2552 static void *receive_thread (void __attribute__((unused)) *arg)
2553 {
2554         return (network_receive () ? (void *) 1 : (void *) 0);
2555 } /* void *receive_thread */
2556
2557 static void network_init_buffer (void)
2558 {
2559         memset (send_buffer, 0, network_config_packet_size);
2560         send_buffer_ptr = send_buffer;
2561         send_buffer_fill = 0;
2562
2563         memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2564 } /* int network_init_buffer */
2565
2566 static void networt_send_buffer_plain (sockent_t *se, /* {{{ */
2567                 const char *buffer, size_t buffer_size)
2568 {
2569         int status;
2570
2571         while (42)
2572         {
2573                 status = sockent_client_connect (se);
2574                 if (status != 0)
2575                         return;
2576
2577                 status = sendto (se->data.client.fd, buffer, buffer_size,
2578                                 /* flags = */ 0,
2579                                 (struct sockaddr *) se->data.client.addr,
2580                                 se->data.client.addrlen);
2581                 if (status < 0)
2582                 {
2583                         char errbuf[1024];
2584
2585                         if ((errno == EINTR) || (errno == EAGAIN))
2586                                 continue;
2587
2588                         ERROR ("network plugin: sendto failed: %s. Closing sending socket.",
2589                                         sstrerror (errno, errbuf, sizeof (errbuf)));
2590                         sockent_client_disconnect (se);
2591                         return;
2592                 }
2593
2594                 break;
2595         } /* while (42) */
2596 } /* }}} void networt_send_buffer_plain */
2597
2598 #if HAVE_LIBGCRYPT
2599 #define BUFFER_ADD(p,s) do { \
2600   memcpy (buffer + buffer_offset, (p), (s)); \
2601   buffer_offset += (s); \
2602 } while (0)
2603
2604 static void networt_send_buffer_signed (sockent_t *se, /* {{{ */
2605                 const char *in_buffer, size_t in_buffer_size)
2606 {
2607   part_signature_sha256_t ps;
2608   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2609   size_t buffer_offset;
2610   size_t username_len;
2611
2612   gcry_md_hd_t hd;
2613   gcry_error_t err;
2614   unsigned char *hash;
2615
2616   hd = NULL;
2617   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2618   if (err != 0)
2619   {
2620     ERROR ("network plugin: Creating HMAC object failed: %s",
2621         gcry_strerror (err));
2622     return;
2623   }
2624
2625   err = gcry_md_setkey (hd, se->data.client.password,
2626       strlen (se->data.client.password));
2627   if (err != 0)
2628   {
2629     ERROR ("network plugin: gcry_md_setkey failed: %s",
2630         gcry_strerror (err));
2631     gcry_md_close (hd);
2632     return;
2633   }
2634
2635   username_len = strlen (se->data.client.username);
2636   if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2637   {
2638     ERROR ("network plugin: Username too long: %s",
2639         se->data.client.username);
2640     return;
2641   }
2642
2643   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2644       se->data.client.username, username_len);
2645   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2646       in_buffer, in_buffer_size);
2647
2648   /* Initialize the `ps' structure. */
2649   memset (&ps, 0, sizeof (ps));
2650   ps.head.type = htons (TYPE_SIGN_SHA256);
2651   ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2652
2653   /* Calculate the hash value. */
2654   gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2655       username_len + in_buffer_size);
2656   hash = gcry_md_read (hd, GCRY_MD_SHA256);
2657   if (hash == NULL)
2658   {
2659     ERROR ("network plugin: gcry_md_read failed.");
2660     gcry_md_close (hd);
2661     return;
2662   }
2663   memcpy (ps.hash, hash, sizeof (ps.hash));
2664
2665   /* Add the header */
2666   buffer_offset = 0;
2667
2668   BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2669   BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2670   BUFFER_ADD (ps.hash, sizeof (ps.hash));
2671
2672   assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2673
2674   gcry_md_close (hd);
2675   hd = NULL;
2676
2677   buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2678   networt_send_buffer_plain (se, buffer, buffer_offset);
2679 } /* }}} void networt_send_buffer_signed */
2680
2681 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2682                 const char *in_buffer, size_t in_buffer_size)
2683 {
2684   part_encryption_aes256_t pea;
2685   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2686   size_t buffer_size;
2687   size_t buffer_offset;
2688   size_t header_size;
2689   size_t username_len;
2690   gcry_error_t err;
2691   gcry_cipher_hd_t cypher;
2692
2693   /* Initialize the header fields */
2694   memset (&pea, 0, sizeof (pea));
2695   pea.head.type = htons (TYPE_ENCR_AES256);
2696
2697   pea.username = se->data.client.username;
2698
2699   username_len = strlen (pea.username);
2700   if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2701   {
2702     ERROR ("network plugin: Username too long: %s", pea.username);
2703     return;
2704   }
2705
2706   buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2707   header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2708     - sizeof (pea.hash);
2709
2710   assert (buffer_size <= sizeof (buffer));
2711   DEBUG ("network plugin: networt_send_buffer_encrypted: "
2712       "buffer_size = %zu;", buffer_size);
2713
2714   pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2715         + username_len + in_buffer_size));
2716   pea.username_length = htons ((uint16_t) username_len);
2717
2718   /* Chose a random initialization vector. */
2719   gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2720
2721   /* Create hash of the payload */
2722   gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2723
2724   /* Initialize the buffer */
2725   buffer_offset = 0;
2726   memset (buffer, 0, sizeof (buffer));
2727
2728
2729   BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2730   BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2731   BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2732   BUFFER_ADD (pea.username, username_len);
2733   BUFFER_ADD (pea.iv, sizeof (pea.iv));
2734   assert (buffer_offset == header_size);
2735   BUFFER_ADD (pea.hash, sizeof (pea.hash));
2736   BUFFER_ADD (in_buffer, in_buffer_size);
2737
2738   assert (buffer_offset == buffer_size);
2739
2740   cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2741       se->data.client.password);
2742   if (cypher == NULL)
2743     return;
2744
2745   /* Encrypt the buffer in-place */
2746   err = gcry_cipher_encrypt (cypher,
2747       buffer      + header_size,
2748       buffer_size - header_size,
2749       /* in = */ NULL, /* in len = */ 0);
2750   if (err != 0)
2751   {
2752     ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2753         gcry_strerror (err));
2754     return;
2755   }
2756
2757   /* Send it out without further modifications */
2758   networt_send_buffer_plain (se, buffer, buffer_size);
2759 } /* }}} void networt_send_buffer_encrypted */
2760 #undef BUFFER_ADD
2761 #endif /* HAVE_LIBGCRYPT */
2762
2763 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2764 {
2765   sockent_t *se;
2766
2767   DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2768
2769   for (se = sending_sockets; se != NULL; se = se->next)
2770   {
2771 #if HAVE_LIBGCRYPT
2772     if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2773       networt_send_buffer_encrypted (se, buffer, buffer_len);
2774     else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2775       networt_send_buffer_signed (se, buffer, buffer_len);
2776     else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2777 #endif /* HAVE_LIBGCRYPT */
2778       networt_send_buffer_plain (se, buffer, buffer_len);
2779   } /* for (sending_sockets) */
2780 } /* }}} void network_send_buffer */
2781
2782 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2783                 value_list_t *vl_def,
2784                 const data_set_t *ds, const value_list_t *vl)
2785 {
2786         char *buffer_orig = buffer;
2787
2788         if (strcmp (vl_def->host, vl->host) != 0)
2789         {
2790                 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2791                                         vl->host, strlen (vl->host)) != 0)
2792                         return (-1);
2793                 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2794         }
2795
2796         if (vl_def->time != vl->time)
2797         {
2798                 if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
2799                                         (uint64_t) vl->time))
2800                         return (-1);
2801                 vl_def->time = vl->time;
2802         }
2803
2804         if (vl_def->interval != vl->interval)
2805         {
2806                 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
2807                                         (uint64_t) vl->interval))
2808                         return (-1);
2809                 vl_def->interval = vl->interval;
2810         }
2811
2812         if (strcmp (vl_def->plugin, vl->plugin) != 0)
2813         {
2814                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2815                                         vl->plugin, strlen (vl->plugin)) != 0)
2816                         return (-1);
2817                 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2818         }
2819
2820         if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2821         {
2822                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2823                                         vl->plugin_instance,
2824                                         strlen (vl->plugin_instance)) != 0)
2825                         return (-1);
2826                 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2827         }
2828
2829         if (strcmp (vl_def->type, vl->type) != 0)
2830         {
2831                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2832                                         vl->type, strlen (vl->type)) != 0)
2833                         return (-1);
2834                 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2835         }
2836
2837         if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2838         {
2839                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2840                                         vl->type_instance,
2841                                         strlen (vl->type_instance)) != 0)
2842                         return (-1);
2843                 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2844         }
2845
2846         if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2847                 return (-1);
2848
2849         return (buffer - buffer_orig);
2850 } /* }}} int add_to_buffer */
2851
2852 static void flush_buffer (void)
2853 {
2854         DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2855                         send_buffer_fill);
2856
2857         network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2858
2859         stats_octets_tx += ((uint64_t) send_buffer_fill);
2860         stats_packets_tx++;
2861
2862         network_init_buffer ();
2863 }
2864
2865 static int network_write (const data_set_t *ds, const value_list_t *vl,
2866                 user_data_t __attribute__((unused)) *user_data)
2867 {
2868         int status;
2869
2870         if (!check_send_okay (vl))
2871         {
2872 #if COLLECT_DEBUG
2873           char name[6*DATA_MAX_NAME_LEN];
2874           FORMAT_VL (name, sizeof (name), vl);
2875           name[sizeof (name) - 1] = 0;
2876           DEBUG ("network plugin: network_write: "
2877               "NOT sending %s.", name);
2878 #endif
2879           /* Counter is not protected by another lock and may be reached by
2880            * multiple threads */
2881           pthread_mutex_lock (&stats_lock);
2882           stats_values_not_sent++;
2883           pthread_mutex_unlock (&stats_lock);
2884           return (0);
2885         }
2886
2887         uc_meta_data_add_unsigned_int (vl,
2888             "network:time_sent", (uint64_t) vl->time);
2889
2890         pthread_mutex_lock (&send_buffer_lock);
2891
2892         status = add_to_buffer (send_buffer_ptr,
2893                         network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2894                         &send_buffer_vl,
2895                         ds, vl);
2896         if (status >= 0)
2897         {
2898                 /* status == bytes added to the buffer */
2899                 send_buffer_fill += status;
2900                 send_buffer_ptr  += status;
2901
2902                 stats_values_sent++;
2903         }
2904         else
2905         {
2906                 flush_buffer ();
2907
2908                 status = add_to_buffer (send_buffer_ptr,
2909                                 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2910                                 &send_buffer_vl,
2911                                 ds, vl);
2912
2913                 if (status >= 0)
2914                 {
2915                         send_buffer_fill += status;
2916                         send_buffer_ptr  += status;
2917
2918                         stats_values_sent++;
2919                 }
2920         }
2921
2922         if (status < 0)
2923         {
2924                 ERROR ("network plugin: Unable to append to the "
2925                                 "buffer for some weird reason");
2926         }
2927         else if ((network_config_packet_size - send_buffer_fill) < 15)
2928         {
2929                 flush_buffer ();
2930         }
2931
2932         pthread_mutex_unlock (&send_buffer_lock);
2933
2934         return ((status < 0) ? -1 : 0);
2935 } /* int network_write */
2936
2937 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2938     int *retval)
2939 {
2940   if ((ci->values_num != 1)
2941       || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2942         && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2943   {
2944     ERROR ("network plugin: The `%s' config option needs "
2945         "exactly one boolean argument.", ci->key);
2946     return (-1);
2947   }
2948
2949   if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2950   {
2951     if (ci->values[0].value.boolean)
2952       *retval = 1;
2953     else
2954       *retval = 0;
2955   }
2956   else
2957   {
2958     char *str = ci->values[0].value.string;
2959
2960     if (IS_TRUE (str))
2961       *retval = 1;
2962     else if (IS_FALSE (str))
2963       *retval = 0;
2964     else
2965     {
2966       ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2967           "option as boolean value.",
2968           str, ci->key);
2969       return (-1);
2970     }
2971   }
2972
2973   return (0);
2974 } /* }}} int network_config_set_boolean */
2975
2976 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2977 {
2978   int tmp;
2979   if ((ci->values_num != 1)
2980       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2981   {
2982     WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2983         "one numeric argument.");
2984     return (-1);
2985   }
2986
2987   tmp = (int) ci->values[0].value.number;
2988   if ((tmp > 0) && (tmp <= 255))
2989     network_config_ttl = tmp;
2990   else {
2991     WARNING ("network plugin: The `TimeToLive' must be between 1 and 255.");
2992     return (-1);    
2993   }
2994
2995   return (0);
2996 } /* }}} int network_config_set_ttl */
2997
2998 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2999     int *interface)
3000 {
3001   if ((ci->values_num != 1)
3002       || (ci->values[0].type != OCONFIG_TYPE_STRING))
3003   {
3004     WARNING ("network plugin: The `Interface' config option needs exactly "
3005         "one string argument.");
3006     return (-1);
3007   }
3008
3009   if (interface == NULL)
3010     return (-1);
3011
3012   *interface = if_nametoindex (ci->values[0].value.string);
3013
3014   return (0);
3015 } /* }}} int network_config_set_interface */
3016
3017 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
3018 {
3019   int tmp;
3020   if ((ci->values_num != 1)
3021       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
3022   {
3023     WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
3024         "one numeric argument.");
3025     return (-1);
3026   }
3027
3028   tmp = (int) ci->values[0].value.number;
3029   if ((tmp >= 1024) && (tmp <= 65535))
3030     network_config_packet_size = tmp;
3031
3032   return (0);
3033 } /* }}} int network_config_set_buffer_size */
3034
3035 #if HAVE_LIBGCRYPT
3036 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
3037     char **ret_string)
3038 {
3039   char *tmp;
3040   if ((ci->values_num != 1)
3041       || (ci->values[0].type != OCONFIG_TYPE_STRING))
3042   {
3043     WARNING ("network plugin: The `%s' config option needs exactly "
3044         "one string argument.", ci->key);
3045     return (-1);
3046   }
3047
3048   tmp = strdup (ci->values[0].value.string);
3049   if (tmp == NULL)
3050     return (-1);
3051
3052   sfree (*ret_string);
3053   *ret_string = tmp;
3054
3055   return (0);
3056 } /* }}} int network_config_set_string */
3057 #endif /* HAVE_LIBGCRYPT */
3058
3059 #if HAVE_LIBGCRYPT
3060 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
3061     int *retval)
3062 {
3063   char *str;
3064   if ((ci->values_num != 1)
3065       || (ci->values[0].type != OCONFIG_TYPE_STRING))
3066   {
3067     WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
3068         "one string argument.");
3069     return (-1);
3070   }
3071
3072   str = ci->values[0].value.string;
3073   if (strcasecmp ("Encrypt", str) == 0)
3074     *retval = SECURITY_LEVEL_ENCRYPT;
3075   else if (strcasecmp ("Sign", str) == 0)
3076     *retval = SECURITY_LEVEL_SIGN;
3077   else if (strcasecmp ("None", str) == 0)
3078     *retval = SECURITY_LEVEL_NONE;
3079   else
3080   {
3081     WARNING ("network plugin: Unknown security level: %s.", str);
3082     return (-1);
3083   }
3084
3085   return (0);
3086 } /* }}} int network_config_set_security_level */
3087 #endif /* HAVE_LIBGCRYPT */
3088
3089 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
3090 {
3091   sockent_t *se;
3092   int status;
3093   int i;
3094
3095   if ((ci->values_num < 1) || (ci->values_num > 2)
3096       || (ci->values[0].type != OCONFIG_TYPE_STRING)
3097       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3098   {
3099     ERROR ("network plugin: The `%s' config option needs "
3100         "one or two string arguments.", ci->key);
3101     return (-1);
3102   }
3103
3104   se = sockent_create (SOCKENT_TYPE_SERVER);
3105   if (se == NULL)
3106   {
3107     ERROR ("network plugin: sockent_create failed.");
3108     return (-1);
3109   }
3110
3111   se->node = strdup (ci->values[0].value.string);
3112   if (ci->values_num >= 2)
3113     se->service = strdup (ci->values[1].value.string);
3114
3115   for (i = 0; i < ci->children_num; i++)
3116   {
3117     oconfig_item_t *child = ci->children + i;
3118
3119 #if HAVE_LIBGCRYPT
3120     if (strcasecmp ("AuthFile", child->key) == 0)
3121       network_config_set_string (child, &se->data.server.auth_file);
3122     else if (strcasecmp ("SecurityLevel", child->key) == 0)
3123       network_config_set_security_level (child,
3124           &se->data.server.security_level);
3125     else
3126 #endif /* HAVE_LIBGCRYPT */
3127     if (strcasecmp ("Interface", child->key) == 0)
3128       network_config_set_interface (child,
3129           &se->interface);
3130     else
3131     {
3132       WARNING ("network plugin: Option `%s' is not allowed here.",
3133           child->key);
3134     }
3135   }
3136
3137 #if HAVE_LIBGCRYPT
3138   if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3139       && (se->data.server.auth_file == NULL))
3140   {
3141     ERROR ("network plugin: A security level higher than `none' was "
3142         "requested, but no AuthFile option was given. Cowardly refusing to "
3143         "open this socket!");
3144     sockent_destroy (se);
3145     return (-1);
3146   }
3147 #endif /* HAVE_LIBGCRYPT */
3148
3149   status = sockent_init_crypto (se);
3150   if (status != 0)
3151   {
3152     ERROR ("network plugin: network_config_add_listen: sockent_init_crypto() failed.");
3153     sockent_destroy (se);
3154     return (-1);
3155   }
3156
3157   status = sockent_server_listen (se);
3158   if (status != 0)
3159   {
3160     ERROR ("network plugin: network_config_add_server: sockent_server_listen failed.");
3161     sockent_destroy (se);
3162     return (-1);
3163   }
3164
3165   status = sockent_add (se);
3166   if (status != 0)
3167   {
3168     ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3169     sockent_destroy (se);
3170     return (-1);
3171   }
3172
3173   return (0);
3174 } /* }}} int network_config_add_listen */
3175
3176 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3177 {
3178   sockent_t *se;
3179   int status;
3180   int i;
3181
3182   if ((ci->values_num < 1) || (ci->values_num > 2)
3183       || (ci->values[0].type != OCONFIG_TYPE_STRING)
3184       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3185   {
3186     ERROR ("network plugin: The `%s' config option needs "
3187         "one or two string arguments.", ci->key);
3188     return (-1);
3189   }
3190
3191   se = sockent_create (SOCKENT_TYPE_CLIENT);
3192   if (se == NULL)
3193   {
3194     ERROR ("network plugin: sockent_create failed.");
3195     return (-1);
3196   }
3197
3198   se->node = strdup (ci->values[0].value.string);
3199   if (ci->values_num >= 2)
3200     se->service = strdup (ci->values[1].value.string);
3201
3202   for (i = 0; i < ci->children_num; i++)
3203   {
3204     oconfig_item_t *child = ci->children + i;
3205
3206 #if HAVE_LIBGCRYPT
3207     if (strcasecmp ("Username", child->key) == 0)
3208       network_config_set_string (child, &se->data.client.username);
3209     else if (strcasecmp ("Password", child->key) == 0)
3210       network_config_set_string (child, &se->data.client.password);
3211     else if (strcasecmp ("SecurityLevel", child->key) == 0)
3212       network_config_set_security_level (child,
3213           &se->data.client.security_level);
3214     else
3215 #endif /* HAVE_LIBGCRYPT */
3216     if (strcasecmp ("Interface", child->key) == 0)
3217       network_config_set_interface (child,
3218           &se->interface);
3219     else
3220     {
3221       WARNING ("network plugin: Option `%s' is not allowed here.",
3222           child->key);
3223     }
3224   }
3225
3226 #if HAVE_LIBGCRYPT
3227   if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3228       && ((se->data.client.username == NULL)
3229         || (se->data.client.password == NULL)))
3230   {
3231     ERROR ("network plugin: A security level higher than `none' was "
3232         "requested, but no Username or Password option was given. "
3233         "Cowardly refusing to open this socket!");
3234     sockent_destroy (se);
3235     return (-1);
3236   }
3237 #endif /* HAVE_LIBGCRYPT */
3238
3239   status = sockent_init_crypto (se);
3240   if (status != 0)
3241   {
3242     ERROR ("network plugin: network_config_add_server: sockent_init_crypto() failed.");
3243     sockent_destroy (se);
3244     return (-1);
3245   }
3246
3247   /* No call to sockent_client_connect() here -- it is called from
3248    * networt_send_buffer_plain(). */
3249
3250   status = sockent_add (se);
3251   if (status != 0)
3252   {
3253     ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3254     sockent_destroy (se);
3255     return (-1);
3256   }
3257
3258   return (0);
3259 } /* }}} int network_config_add_server */
3260
3261 static int network_config (oconfig_item_t *ci) /* {{{ */
3262 {
3263   int i;
3264
3265   /* The options need to be applied first */
3266   for (i = 0; i < ci->children_num; i++)
3267   {
3268     oconfig_item_t *child = ci->children + i;
3269     if (strcasecmp ("TimeToLive", child->key) == 0)
3270       network_config_set_ttl (child);
3271   }
3272
3273   for (i = 0; i < ci->children_num; i++)
3274   {
3275     oconfig_item_t *child = ci->children + i;
3276
3277     if (strcasecmp ("Listen", child->key) == 0)
3278       network_config_add_listen (child);
3279     else if (strcasecmp ("Server", child->key) == 0)
3280       network_config_add_server (child);
3281     else if (strcasecmp ("TimeToLive", child->key) == 0) {
3282       /* Handled earlier */
3283     }
3284     else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3285       network_config_set_buffer_size (child);
3286     else if (strcasecmp ("Forward", child->key) == 0)
3287       network_config_set_boolean (child, &network_config_forward);
3288     else if (strcasecmp ("ReportStats", child->key) == 0)
3289       network_config_set_boolean (child, &network_config_stats);
3290     else
3291     {
3292       WARNING ("network plugin: Option `%s' is not allowed here.",
3293           child->key);
3294     }
3295   }
3296
3297   return (0);
3298 } /* }}} int network_config */
3299
3300 static int network_notification (const notification_t *n,
3301     user_data_t __attribute__((unused)) *user_data)
3302 {
3303   char  buffer[network_config_packet_size];
3304   char *buffer_ptr = buffer;
3305   int   buffer_free = sizeof (buffer);
3306   int   status;
3307
3308   if (!check_send_notify_okay (n))
3309     return (0);
3310
3311   memset (buffer, 0, sizeof (buffer));
3312
3313   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3314       (uint64_t) n->time);
3315   if (status != 0)
3316     return (-1);
3317
3318   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3319       (uint64_t) n->severity);
3320   if (status != 0)
3321     return (-1);
3322
3323   if (strlen (n->host) > 0)
3324   {
3325     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3326         n->host, strlen (n->host));
3327     if (status != 0)
3328       return (-1);
3329   }
3330
3331   if (strlen (n->plugin) > 0)
3332   {
3333     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3334         n->plugin, strlen (n->plugin));
3335     if (status != 0)
3336       return (-1);
3337   }
3338
3339   if (strlen (n->plugin_instance) > 0)
3340   {
3341     status = write_part_string (&buffer_ptr, &buffer_free,
3342         TYPE_PLUGIN_INSTANCE,
3343         n->plugin_instance, strlen (n->plugin_instance));
3344     if (status != 0)
3345       return (-1);
3346   }
3347
3348   if (strlen (n->type) > 0)
3349   {
3350     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3351         n->type, strlen (n->type));
3352     if (status != 0)
3353       return (-1);
3354   }
3355
3356   if (strlen (n->type_instance) > 0)
3357   {
3358     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3359         n->type_instance, strlen (n->type_instance));
3360     if (status != 0)
3361       return (-1);
3362   }
3363
3364   status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3365       n->message, strlen (n->message));
3366   if (status != 0)
3367     return (-1);
3368
3369   network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3370
3371   return (0);
3372 } /* int network_notification */
3373
3374 static int network_shutdown (void)
3375 {
3376         sockent_t *se;
3377
3378         listen_loop++;
3379
3380         /* Kill the listening thread */
3381         if (receive_thread_running != 0)
3382         {
3383                 INFO ("network plugin: Stopping receive thread.");
3384                 pthread_kill (receive_thread_id, SIGTERM);
3385                 pthread_join (receive_thread_id, NULL /* no return value */);
3386                 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3387                 receive_thread_running = 0;
3388         }
3389
3390         /* Shutdown the dispatching thread */
3391         if (dispatch_thread_running != 0)
3392         {
3393                 INFO ("network plugin: Stopping dispatch thread.");
3394                 pthread_mutex_lock (&receive_list_lock);
3395                 pthread_cond_broadcast (&receive_list_cond);
3396                 pthread_mutex_unlock (&receive_list_lock);
3397                 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3398                 dispatch_thread_running = 0;
3399         }
3400
3401         sockent_destroy (listen_sockets);
3402
3403         if (send_buffer_fill > 0)
3404                 flush_buffer ();
3405
3406         sfree (send_buffer);
3407
3408         for (se = sending_sockets; se != NULL; se = se->next)
3409                 sockent_client_disconnect (se);
3410         sockent_destroy (sending_sockets);
3411
3412         plugin_unregister_config ("network");
3413         plugin_unregister_init ("network");
3414         plugin_unregister_write ("network");
3415         plugin_unregister_shutdown ("network");
3416
3417         return (0);
3418 } /* int network_shutdown */
3419
3420 static int network_stats_read (void) /* {{{ */
3421 {
3422         derive_t copy_octets_rx;
3423         derive_t copy_octets_tx;
3424         derive_t copy_packets_rx;
3425         derive_t copy_packets_tx;
3426         derive_t copy_values_dispatched;
3427         derive_t copy_values_not_dispatched;
3428         derive_t copy_values_sent;
3429         derive_t copy_values_not_sent;
3430         derive_t copy_receive_list_length;
3431         value_list_t vl = VALUE_LIST_INIT;
3432         value_t values[2];
3433
3434         copy_octets_rx = stats_octets_rx;
3435         copy_octets_tx = stats_octets_tx;
3436         copy_packets_rx = stats_packets_rx;
3437         copy_packets_tx = stats_packets_tx;
3438         copy_values_dispatched = stats_values_dispatched;
3439         copy_values_not_dispatched = stats_values_not_dispatched;
3440         copy_values_sent = stats_values_sent;
3441         copy_values_not_sent = stats_values_not_sent;
3442         copy_receive_list_length = receive_list_length;
3443
3444         /* Initialize `vl' */
3445         vl.values = values;
3446         vl.values_len = 2;
3447         vl.time = 0;
3448         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3449         sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3450
3451         /* Octets received / sent */
3452         vl.values[0].derive = (derive_t) copy_octets_rx;
3453         vl.values[1].derive = (derive_t) copy_octets_tx;
3454         sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3455         plugin_dispatch_values (&vl);
3456
3457         /* Packets received / send */
3458         vl.values[0].derive = (derive_t) copy_packets_rx;
3459         vl.values[1].derive = (derive_t) copy_packets_tx;
3460         sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3461         plugin_dispatch_values (&vl);
3462
3463         /* Values (not) dispatched and (not) send */
3464         sstrncpy (vl.type, "total_values", sizeof (vl.type));
3465         vl.values_len = 1;
3466
3467         vl.values[0].derive = (derive_t) copy_values_dispatched;
3468         sstrncpy (vl.type_instance, "dispatch-accepted",
3469                         sizeof (vl.type_instance));
3470         plugin_dispatch_values (&vl);
3471
3472         vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3473         sstrncpy (vl.type_instance, "dispatch-rejected",
3474                         sizeof (vl.type_instance));
3475         plugin_dispatch_values (&vl);
3476
3477         vl.values[0].derive = (derive_t) copy_values_sent;
3478         sstrncpy (vl.type_instance, "send-accepted",
3479                         sizeof (vl.type_instance));
3480         plugin_dispatch_values (&vl);
3481
3482         vl.values[0].derive = (derive_t) copy_values_not_sent;
3483         sstrncpy (vl.type_instance, "send-rejected",
3484                         sizeof (vl.type_instance));
3485         plugin_dispatch_values (&vl);
3486
3487         /* Receive queue length */
3488         vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3489         sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3490         vl.type_instance[0] = 0;
3491         plugin_dispatch_values (&vl);
3492
3493         return (0);
3494 } /* }}} int network_stats_read */
3495
3496 static int network_init (void)
3497 {
3498         static _Bool have_init = 0;
3499
3500         /* Check if we were already initialized. If so, just return - there's
3501          * nothing more to do (for now, that is). */
3502         if (have_init)
3503                 return (0);
3504         have_init = 1;
3505
3506 #if HAVE_LIBGCRYPT
3507         network_init_gcrypt ();
3508 #endif
3509
3510         if (network_config_stats != 0)
3511                 plugin_register_read ("network", network_stats_read);
3512
3513         plugin_register_shutdown ("network", network_shutdown);
3514
3515         send_buffer = malloc (network_config_packet_size);
3516         if (send_buffer == NULL)
3517         {
3518                 ERROR ("network plugin: malloc failed.");
3519                 return (-1);
3520         }
3521         network_init_buffer ();
3522
3523         /* setup socket(s) and so on */
3524         if (sending_sockets != NULL)
3525         {
3526                 plugin_register_write ("network", network_write,
3527                                 /* user_data = */ NULL);
3528                 plugin_register_notification ("network", network_notification,
3529                                 /* user_data = */ NULL);
3530         }
3531
3532         /* If no threads need to be started, return here. */
3533         if ((listen_sockets_num == 0)
3534                         || ((dispatch_thread_running != 0)
3535                                 && (receive_thread_running != 0)))
3536                 return (0);
3537
3538         if (dispatch_thread_running == 0)
3539         {
3540                 int status;
3541                 status = plugin_thread_create (&dispatch_thread_id,
3542                                 NULL /* no attributes */,
3543                                 dispatch_thread,
3544                                 NULL /* no argument */);
3545                 if (status != 0)
3546                 {
3547                         char errbuf[1024];
3548                         ERROR ("network: pthread_create failed: %s",
3549                                         sstrerror (errno, errbuf,
3550                                                 sizeof (errbuf)));
3551                 }
3552                 else
3553                 {
3554                         dispatch_thread_running = 1;
3555                 }
3556         }
3557
3558         if (receive_thread_running == 0)
3559         {
3560                 int status;
3561                 status = plugin_thread_create (&receive_thread_id,
3562                                 NULL /* no attributes */,
3563                                 receive_thread,
3564                                 NULL /* no argument */);
3565                 if (status != 0)
3566                 {
3567                         char errbuf[1024];
3568                         ERROR ("network: pthread_create failed: %s",
3569                                         sstrerror (errno, errbuf,
3570                                                 sizeof (errbuf)));
3571                 }
3572                 else
3573                 {
3574                         receive_thread_running = 1;
3575                 }
3576         }
3577
3578         return (0);
3579 } /* int network_init */
3580
3581 /*
3582  * The flush option of the network plugin cannot flush individual identifiers.
3583  * All the values are added to a buffer and sent when the buffer is full, the
3584  * requested value may or may not be in there, it's not worth finding out. We
3585  * just send the buffer if `flush'  is called - if the requested value was in
3586  * there, good. If not, well, then there is nothing to flush.. -octo
3587  */
3588 static int network_flush (__attribute__((unused)) cdtime_t timeout,
3589                 __attribute__((unused)) const char *identifier,
3590                 __attribute__((unused)) user_data_t *user_data)
3591 {
3592         pthread_mutex_lock (&send_buffer_lock);
3593
3594         if (send_buffer_fill > 0)
3595           flush_buffer ();
3596
3597         pthread_mutex_unlock (&send_buffer_lock);
3598
3599         return (0);
3600 } /* int network_flush */
3601
3602 void module_register (void)
3603 {
3604         plugin_register_complex_config ("network", network_config);
3605         plugin_register_init   ("network", network_init);
3606         plugin_register_flush   ("network", network_flush,
3607                         /* user_data = */ NULL);
3608 } /* void module_register */
3609
3610 /* vim: set fdm=marker : */