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