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