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