Merge pull request #2874 from elfiesmelfie/feat_virt_block_info
[collectd.git] / src / network.c
1 /**
2  * collectd - src/network.c
3  * Copyright (C) 2005-2013  Florian octo Forster
4  * Copyright (C) 2009       Aman Gupta
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation; only version 2.1 of the License is
9  * applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * Authors:
21  *   Florian octo Forster <octo at collectd.org>
22  *   Aman Gupta <aman at tmm1.net>
23  **/
24
25 #define _DEFAULT_SOURCE
26 #define _BSD_SOURCE /* For struct ip_mreq */
27
28 #include "collectd.h"
29
30 #include "plugin.h"
31 #include "utils/common/common.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   struct sockaddr_storage *bind_addr;
117 };
118
119 struct sockent_server {
120   int *fd;
121   size_t fd_num;
122 #if HAVE_GCRYPT_H
123   int security_level;
124   char *auth_file;
125   fbhash_t *userdb;
126   gcry_cipher_hd_t cypher;
127 #endif
128 };
129
130 typedef struct sockent {
131 #define SOCKENT_TYPE_CLIENT 1
132 #define SOCKENT_TYPE_SERVER 2
133   int type;
134
135   char *node;
136   char *service;
137   int interface;
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   sfree(sec->bind_addr);
1506 #if HAVE_GCRYPT_H
1507   sfree(sec->username);
1508   sfree(sec->password);
1509   if (sec->cypher != NULL)
1510     gcry_cipher_close(sec->cypher);
1511 #endif
1512 } /* }}} void free_sockent_client */
1513
1514 static void free_sockent_server(struct sockent_server *ses) /* {{{ */
1515 {
1516   for (size_t i = 0; i < ses->fd_num; i++) {
1517     if (ses->fd[i] >= 0) {
1518       close(ses->fd[i]);
1519       ses->fd[i] = -1;
1520     }
1521   }
1522
1523   sfree(ses->fd);
1524 #if HAVE_GCRYPT_H
1525   sfree(ses->auth_file);
1526   fbh_destroy(ses->userdb);
1527   if (ses->cypher != NULL)
1528     gcry_cipher_close(ses->cypher);
1529 #endif
1530 } /* }}} void free_sockent_server */
1531
1532 static void sockent_destroy(sockent_t *se) /* {{{ */
1533 {
1534   sockent_t *next;
1535
1536   DEBUG("network plugin: sockent_destroy (se = %p);", (void *)se);
1537
1538   while (se != NULL) {
1539     next = se->next;
1540
1541     sfree(se->node);
1542     sfree(se->service);
1543
1544     if (se->type == SOCKENT_TYPE_CLIENT)
1545       free_sockent_client(&se->data.client);
1546     else
1547       free_sockent_server(&se->data.server);
1548
1549     sfree(se);
1550     se = next;
1551   }
1552 } /* }}} void sockent_destroy */
1553
1554 /*
1555  * int network_set_ttl
1556  *
1557  * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1558  * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1559  *
1560  * The `struct addrinfo' is used to destinguish between unicast and multicast
1561  * sockets.
1562  */
1563 static int network_set_ttl(const sockent_t *se, const struct addrinfo *ai) {
1564   DEBUG("network plugin: network_set_ttl: network_config_ttl = %i;",
1565         network_config_ttl);
1566
1567   assert(se->type == SOCKENT_TYPE_CLIENT);
1568
1569   if ((network_config_ttl < 1) || (network_config_ttl > 255))
1570     return -1;
1571
1572   if (ai->ai_family == AF_INET) {
1573     struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1574     int optname;
1575
1576     if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr)))
1577       optname = IP_MULTICAST_TTL;
1578     else
1579       optname = IP_TTL;
1580
1581     if (setsockopt(se->data.client.fd, IPPROTO_IP, optname, &network_config_ttl,
1582                    sizeof(network_config_ttl)) != 0) {
1583       ERROR("network plugin: setsockopt (ipv4-ttl): %s", STRERRNO);
1584       return -1;
1585     }
1586   } else if (ai->ai_family == AF_INET6) {
1587     /* Useful example:
1588      * http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1589     struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1590     int optname;
1591
1592     if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr))
1593       optname = IPV6_MULTICAST_HOPS;
1594     else
1595       optname = IPV6_UNICAST_HOPS;
1596
1597     if (setsockopt(se->data.client.fd, IPPROTO_IPV6, optname,
1598                    &network_config_ttl, sizeof(network_config_ttl)) != 0) {
1599       ERROR("network plugin: setsockopt(ipv6-ttl): %s", STRERRNO);
1600       return -1;
1601     }
1602   }
1603
1604   return 0;
1605 } /* int network_set_ttl */
1606
1607 static int network_set_interface(const sockent_t *se,
1608                                  const struct addrinfo *ai) /* {{{ */
1609 {
1610   DEBUG("network plugin: network_set_interface: interface index = %i;",
1611         se->interface);
1612
1613   assert(se->type == SOCKENT_TYPE_CLIENT);
1614
1615   if (ai->ai_family == AF_INET) {
1616     struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1617
1618     if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr))) {
1619 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1620       /* If possible, use the "ip_mreqn" structure which has
1621        * an "interface index" member. Using the interface
1622        * index is preferred here, because of its similarity
1623        * to the way IPv6 handles this. Unfortunately, it
1624        * appears not to be portable. */
1625       struct ip_mreqn mreq = {.imr_multiaddr.s_addr = addr->sin_addr.s_addr,
1626                               .imr_address.s_addr = ntohl(INADDR_ANY),
1627                               .imr_ifindex = se->interface};
1628 #else
1629       struct ip_mreq mreq = {.imr_multiaddr.s_addr = addr->sin_addr.s_addr,
1630                              .imr_interface.s_addr = ntohl(INADDR_ANY)};
1631 #endif
1632
1633       if (setsockopt(se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq,
1634                      sizeof(mreq)) != 0) {
1635         ERROR("network plugin: setsockopt (ipv4-multicast-if): %s", STRERRNO);
1636         return -1;
1637       }
1638
1639       return 0;
1640     }
1641   } else if (ai->ai_family == AF_INET6) {
1642     struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1643
1644     if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr)) {
1645       if (setsockopt(se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1646                      &se->interface, sizeof(se->interface)) != 0) {
1647         ERROR("network plugin: setsockopt (ipv6-multicast-if): %s", STRERRNO);
1648         return -1;
1649       }
1650
1651       return 0;
1652     }
1653   }
1654
1655   /* else: Not a multicast interface. */
1656   if (se->interface != 0) {
1657 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME &&                     \
1658     defined(SO_BINDTODEVICE)
1659     char interface_name[IFNAMSIZ];
1660
1661     if (if_indextoname(se->interface, interface_name) == NULL)
1662       return -1;
1663
1664     DEBUG("network plugin: Binding socket to interface %s", interface_name);
1665
1666     if (setsockopt(se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1667                    interface_name, sizeof(interface_name)) == -1) {
1668       ERROR("network plugin: setsockopt (bind-if): %s", STRERRNO);
1669       return -1;
1670     }
1671 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1672
1673 #else
1674     WARNING("network plugin: Cannot set the interface on a unicast "
1675             "socket because "
1676 #if !defined(SO_BINDTODEVICE)
1677             "the \"SO_BINDTODEVICE\" socket option "
1678 #else
1679             "the \"if_indextoname\" function "
1680 #endif
1681             "is not available on your system.");
1682 #endif
1683   }
1684
1685   return 0;
1686 } /* }}} network_set_interface */
1687
1688 static int network_bind_socket_to_addr(sockent_t *se,
1689                                        const struct addrinfo *ai) {
1690
1691   if (se->data.client.bind_addr == NULL)
1692     return 0;
1693
1694   DEBUG("network_plugin: fd %i: bind socket to address", se->data.client.fd);
1695   char pbuffer[64];
1696
1697   if (ai->ai_family == AF_INET) {
1698     struct sockaddr_in *addr =
1699         (struct sockaddr_in *)(se->data.client.bind_addr);
1700     inet_ntop(AF_INET, &(addr->sin_addr), pbuffer, 64);
1701     DEBUG("network_plugin: binding client socket to ipv4 address: %s", pbuffer);
1702     if (bind(se->data.client.fd, (struct sockaddr *)addr, sizeof(*addr)) ==
1703         -1) {
1704       ERROR("network plugin: failed to bind client socket (ipv4) to %s: %s",
1705             pbuffer, STRERRNO);
1706       return -1;
1707     }
1708   } else if (ai->ai_family == AF_INET6) {
1709     struct sockaddr_in6 *addr =
1710         (struct sockaddr_in6 *)(se->data.client.bind_addr);
1711     inet_ntop(AF_INET6, &(addr->sin6_addr), pbuffer, 64);
1712     DEBUG("network_plugin: binding client socket to ipv6 address: %s", pbuffer);
1713     if (bind(se->data.client.fd, (struct sockaddr *)addr, sizeof(*addr)) ==
1714         -1) {
1715       ERROR("network plugin: failed to bind client socket (ipv6) to %s: %s",
1716             pbuffer, STRERRNO);
1717       return -1;
1718     }
1719   }
1720
1721   return 0;
1722 } /* int network_bind_socket_to_addr */
1723
1724 static int network_bind_socket(int fd, const struct addrinfo *ai,
1725                                const int interface_idx) {
1726 #if KERNEL_SOLARIS
1727   char loop = 0;
1728 #else
1729   int loop = 0;
1730 #endif
1731
1732   /* allow multiple sockets to use the same PORT number */
1733   if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) == -1) {
1734     ERROR("network plugin: setsockopt (reuseaddr): %s", STRERRNO);
1735     return -1;
1736   }
1737
1738   DEBUG("fd = %i; calling `bind'", fd);
1739
1740   if (bind(fd, ai->ai_addr, ai->ai_addrlen) == -1) {
1741     ERROR("bind: %s", STRERRNO);
1742     return -1;
1743   }
1744
1745   if (ai->ai_family == AF_INET) {
1746     struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1747     if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr))) {
1748 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1749       struct ip_mreqn mreq;
1750 #else
1751       struct ip_mreq mreq;
1752 #endif
1753
1754       DEBUG("fd = %i; IPv4 multicast address found", fd);
1755
1756       mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1757 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1758       /* Set the interface using the interface index if
1759        * possible (available). Unfortunately, the struct
1760        * ip_mreqn is not portable. */
1761       mreq.imr_address.s_addr = ntohl(INADDR_ANY);
1762       mreq.imr_ifindex = interface_idx;
1763 #else
1764       mreq.imr_interface.s_addr = ntohl(INADDR_ANY);
1765 #endif
1766
1767       if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) ==
1768           -1) {
1769         ERROR("network plugin: setsockopt (multicast-loop): %s", STRERRNO);
1770         return -1;
1771       }
1772
1773       if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) ==
1774           -1) {
1775         ERROR("network plugin: setsockopt (add-membership): %s", STRERRNO);
1776         return -1;
1777       }
1778
1779       return 0;
1780     }
1781   } else if (ai->ai_family == AF_INET6) {
1782     /* Useful example:
1783      * http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1784     struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1785     if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr)) {
1786       struct ipv6_mreq mreq;
1787
1788       DEBUG("fd = %i; IPv6 multicast address found", fd);
1789
1790       memcpy(&mreq.ipv6mr_multiaddr, &addr->sin6_addr, sizeof(addr->sin6_addr));
1791
1792       /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1793        * ipv6mr_interface may be set to zeroes to
1794        * choose the default multicast interface or to
1795        * the index of a particular multicast-capable
1796        * interface if the host is multihomed.
1797        * Membership is associ-associated with a
1798        * single interface; programs running on
1799        * multihomed hosts may need to join the same
1800        * group on more than one interface.*/
1801       mreq.ipv6mr_interface = interface_idx;
1802
1803       if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop,
1804                      sizeof(loop)) == -1) {
1805         ERROR("network plugin: setsockopt (ipv6-multicast-loop): %s", STRERRNO);
1806         return -1;
1807       }
1808
1809       if (setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq,
1810                      sizeof(mreq)) == -1) {
1811         ERROR("network plugin: setsockopt (ipv6-add-membership): %s", STRERRNO);
1812         return -1;
1813       }
1814
1815       return 0;
1816     }
1817   }
1818
1819 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME &&                     \
1820     defined(SO_BINDTODEVICE)
1821   /* if a specific interface was set, bind the socket to it. But to avoid
1822    * possible problems with multicast routing, only do that for non-multicast
1823    * addresses */
1824   if (interface_idx != 0) {
1825     char interface_name[IFNAMSIZ];
1826
1827     if (if_indextoname(interface_idx, interface_name) == NULL)
1828       return -1;
1829
1830     DEBUG("fd = %i; Binding socket to interface %s", fd, interface_name);
1831
1832     if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, interface_name,
1833                    sizeof(interface_name)) == -1) {
1834       ERROR("network plugin: setsockopt (bind-if): %s", STRERRNO);
1835       return -1;
1836     }
1837   }
1838 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1839
1840   return 0;
1841 } /* int network_bind_socket */
1842
1843 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1844  * or `SOCKENT_TYPE_SERVER' */
1845 static sockent_t *sockent_create(int type) /* {{{ */
1846 {
1847   sockent_t *se;
1848
1849   if ((type != SOCKENT_TYPE_CLIENT) && (type != SOCKENT_TYPE_SERVER))
1850     return NULL;
1851
1852   se = calloc(1, sizeof(*se));
1853   if (se == NULL)
1854     return NULL;
1855
1856   se->type = type;
1857   se->node = NULL;
1858   se->service = NULL;
1859   se->interface = 0;
1860   se->next = NULL;
1861
1862   if (type == SOCKENT_TYPE_SERVER) {
1863     se->data.server.fd = NULL;
1864     se->data.server.fd_num = 0;
1865 #if HAVE_GCRYPT_H
1866     se->data.server.security_level = SECURITY_LEVEL_NONE;
1867     se->data.server.auth_file = NULL;
1868     se->data.server.userdb = NULL;
1869     se->data.server.cypher = NULL;
1870 #endif
1871   } else {
1872     se->data.client.fd = -1;
1873     se->data.client.addr = NULL;
1874     se->data.client.bind_addr = NULL;
1875     se->data.client.resolve_interval = 0;
1876     se->data.client.next_resolve_reconnect = 0;
1877 #if HAVE_GCRYPT_H
1878     se->data.client.security_level = SECURITY_LEVEL_NONE;
1879     se->data.client.username = NULL;
1880     se->data.client.password = NULL;
1881     se->data.client.cypher = NULL;
1882 #endif
1883   }
1884
1885   return se;
1886 } /* }}} sockent_t *sockent_create */
1887
1888 static int sockent_init_crypto(sockent_t *se) /* {{{ */
1889 {
1890 #if HAVE_GCRYPT_H /* {{{ */
1891   if (se->type == SOCKENT_TYPE_CLIENT) {
1892     if (se->data.client.security_level > SECURITY_LEVEL_NONE) {
1893       if (network_init_gcrypt() < 0) {
1894         ERROR("network plugin: Cannot configure client socket with "
1895               "security: Failed to initialize crypto library.");
1896         return -1;
1897       }
1898
1899       if ((se->data.client.username == NULL) ||
1900           (se->data.client.password == NULL)) {
1901         ERROR("network plugin: Client socket with "
1902               "security requested, but no "
1903               "credentials are configured.");
1904         return -1;
1905       }
1906       gcry_md_hash_buffer(GCRY_MD_SHA256, se->data.client.password_hash,
1907                           se->data.client.password,
1908                           strlen(se->data.client.password));
1909     }
1910   } else /* (se->type == SOCKENT_TYPE_SERVER) */
1911   {
1912     if ((se->data.server.security_level > SECURITY_LEVEL_NONE) &&
1913         (se->data.server.auth_file == NULL)) {
1914       ERROR("network plugin: Server socket with security requested, "
1915             "but no \"AuthFile\" is configured.");
1916       return -1;
1917     }
1918     if (se->data.server.auth_file != NULL) {
1919       if (network_init_gcrypt() < 0) {
1920         ERROR("network plugin: Cannot configure server socket with security: "
1921               "Failed to initialize crypto library.");
1922         return -1;
1923       }
1924
1925       se->data.server.userdb = fbh_create(se->data.server.auth_file);
1926       if (se->data.server.userdb == NULL) {
1927         ERROR("network plugin: Reading password file \"%s\" failed.",
1928               se->data.server.auth_file);
1929         return -1;
1930       }
1931     }
1932   }
1933 #endif /* }}} HAVE_GCRYPT_H */
1934
1935   return 0;
1936 } /* }}} int sockent_init_crypto */
1937
1938 static int sockent_client_disconnect(sockent_t *se) /* {{{ */
1939 {
1940   struct sockent_client *client;
1941
1942   if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
1943     return EINVAL;
1944
1945   client = &se->data.client;
1946   if (client->fd >= 0) /* connected */
1947   {
1948     close(client->fd);
1949     client->fd = -1;
1950   }
1951
1952   sfree(client->addr);
1953   client->addrlen = 0;
1954
1955   return 0;
1956 } /* }}} int sockent_client_disconnect */
1957
1958 static int sockent_client_connect(sockent_t *se) /* {{{ */
1959 {
1960   static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
1961
1962   struct sockent_client *client;
1963   struct addrinfo *ai_list;
1964   int status;
1965   bool reconnect = false;
1966   cdtime_t now;
1967
1968   if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
1969     return EINVAL;
1970
1971   client = &se->data.client;
1972
1973   now = cdtime();
1974   if (client->resolve_interval != 0 && client->next_resolve_reconnect < now) {
1975     DEBUG("network plugin: Reconnecting socket, resolve_interval = %lf, "
1976           "next_resolve_reconnect = %lf",
1977           CDTIME_T_TO_DOUBLE(client->resolve_interval),
1978           CDTIME_T_TO_DOUBLE(client->next_resolve_reconnect));
1979     reconnect = true;
1980   }
1981
1982   if (client->fd >= 0 && !reconnect) /* already connected and not stale*/
1983     return 0;
1984
1985   struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
1986                               .ai_flags = AI_ADDRCONFIG,
1987                               .ai_protocol = IPPROTO_UDP,
1988                               .ai_socktype = SOCK_DGRAM};
1989
1990   status = getaddrinfo(se->node,
1991                        (se->service != NULL) ? se->service : NET_DEFAULT_PORT,
1992                        &ai_hints, &ai_list);
1993   if (status != 0) {
1994     c_complain(
1995         LOG_ERR, &complaint, "network plugin: getaddrinfo (%s, %s) failed: %s",
1996         (se->node == NULL) ? "(null)" : se->node,
1997         (se->service == NULL) ? "(null)" : se->service, gai_strerror(status));
1998     return -1;
1999   } else {
2000     c_release(LOG_NOTICE, &complaint,
2001               "network plugin: Successfully resolved \"%s\".", se->node);
2002   }
2003
2004   for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
2005        ai_ptr = ai_ptr->ai_next) {
2006     if (client->fd >= 0) /* when we reconnect */
2007       sockent_client_disconnect(se);
2008
2009     client->fd =
2010         socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
2011     if (client->fd < 0) {
2012       ERROR("network plugin: socket(2) failed: %s", STRERRNO);
2013       continue;
2014     }
2015
2016     client->addr = calloc(1, sizeof(*client->addr));
2017     if (client->addr == NULL) {
2018       ERROR("network plugin: calloc failed.");
2019       close(client->fd);
2020       client->fd = -1;
2021       continue;
2022     }
2023
2024     assert(sizeof(*client->addr) >= ai_ptr->ai_addrlen);
2025     memcpy(client->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2026     client->addrlen = ai_ptr->ai_addrlen;
2027
2028     network_set_ttl(se, ai_ptr);
2029     network_set_interface(se, ai_ptr);
2030     network_bind_socket_to_addr(se, ai_ptr);
2031
2032     /* We don't open more than one write-socket per
2033      * node/service pair.. */
2034     break;
2035   }
2036
2037   freeaddrinfo(ai_list);
2038   if (client->fd < 0)
2039     return -1;
2040
2041   if (client->resolve_interval > 0)
2042     client->next_resolve_reconnect = now + client->resolve_interval;
2043   return 0;
2044 } /* }}} int sockent_client_connect */
2045
2046 /* Open the file descriptors for a initialized sockent structure. */
2047 static int sockent_server_listen(sockent_t *se) /* {{{ */
2048 {
2049   struct addrinfo *ai_list;
2050   int status;
2051
2052   const char *node;
2053   const char *service;
2054
2055   if (se == NULL)
2056     return -1;
2057
2058   assert(se->data.server.fd == NULL);
2059   assert(se->data.server.fd_num == 0);
2060
2061   node = se->node;
2062   service = se->service;
2063
2064   if (service == NULL)
2065     service = NET_DEFAULT_PORT;
2066
2067   DEBUG("network plugin: sockent_server_listen: node = %s; service = %s;", node,
2068         service);
2069
2070   struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
2071                               .ai_flags = AI_ADDRCONFIG | AI_PASSIVE,
2072                               .ai_protocol = IPPROTO_UDP,
2073                               .ai_socktype = SOCK_DGRAM};
2074
2075   status = getaddrinfo(node, service, &ai_hints, &ai_list);
2076   if (status != 0) {
2077     ERROR("network plugin: getaddrinfo (%s, %s) failed: %s",
2078           (se->node == NULL) ? "(null)" : se->node,
2079           (se->service == NULL) ? "(null)" : se->service, gai_strerror(status));
2080     return -1;
2081   }
2082
2083   for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
2084        ai_ptr = ai_ptr->ai_next) {
2085     int *tmp;
2086
2087     tmp = realloc(se->data.server.fd,
2088                   sizeof(*tmp) * (se->data.server.fd_num + 1));
2089     if (tmp == NULL) {
2090       ERROR("network plugin: realloc failed.");
2091       continue;
2092     }
2093     se->data.server.fd = tmp;
2094     tmp = se->data.server.fd + se->data.server.fd_num;
2095
2096     *tmp = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
2097     if (*tmp < 0) {
2098       ERROR("network plugin: socket(2) failed: %s", STRERRNO);
2099       continue;
2100     }
2101
2102     status = network_bind_socket(*tmp, ai_ptr, se->interface);
2103     if (status != 0) {
2104       close(*tmp);
2105       *tmp = -1;
2106       continue;
2107     }
2108
2109     se->data.server.fd_num++;
2110     continue;
2111   } /* for (ai_list) */
2112
2113   freeaddrinfo(ai_list);
2114
2115   if (se->data.server.fd_num == 0)
2116     return -1;
2117   return 0;
2118 } /* }}} int sockent_server_listen */
2119
2120 /* Add a sockent to the global list of sockets */
2121 static int sockent_add(sockent_t *se) /* {{{ */
2122 {
2123   sockent_t *last_ptr;
2124
2125   if (se == NULL)
2126     return -1;
2127
2128   if (se->type == SOCKENT_TYPE_SERVER) {
2129     struct pollfd *tmp;
2130
2131     tmp = realloc(listen_sockets_pollfd,
2132                   sizeof(*tmp) * (listen_sockets_num + se->data.server.fd_num));
2133     if (tmp == NULL) {
2134       ERROR("network plugin: realloc failed.");
2135       return -1;
2136     }
2137     listen_sockets_pollfd = tmp;
2138     tmp = listen_sockets_pollfd + listen_sockets_num;
2139
2140     for (size_t i = 0; i < se->data.server.fd_num; i++) {
2141       memset(tmp + i, 0, sizeof(*tmp));
2142       tmp[i].fd = se->data.server.fd[i];
2143       tmp[i].events = POLLIN | POLLPRI;
2144       tmp[i].revents = 0;
2145     }
2146
2147     listen_sockets_num += se->data.server.fd_num;
2148
2149     if (listen_sockets == NULL) {
2150       listen_sockets = se;
2151       return 0;
2152     }
2153     last_ptr = listen_sockets;
2154   } else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2155   {
2156     if (sending_sockets == NULL) {
2157       sending_sockets = se;
2158       return 0;
2159     }
2160     last_ptr = sending_sockets;
2161   }
2162
2163   while (last_ptr->next != NULL)
2164     last_ptr = last_ptr->next;
2165   last_ptr->next = se;
2166
2167   return 0;
2168 } /* }}} int sockent_add */
2169
2170 static void *dispatch_thread(void __attribute__((unused)) * arg) /* {{{ */
2171 {
2172   while (42) {
2173     receive_list_entry_t *ent;
2174     sockent_t *se;
2175
2176     /* Lock and wait for more data to come in */
2177     pthread_mutex_lock(&receive_list_lock);
2178     while ((listen_loop == 0) && (receive_list_head == NULL))
2179       pthread_cond_wait(&receive_list_cond, &receive_list_lock);
2180
2181     /* Remove the head entry and unlock */
2182     ent = receive_list_head;
2183     if (ent != NULL)
2184       receive_list_head = ent->next;
2185     receive_list_length--;
2186     pthread_mutex_unlock(&receive_list_lock);
2187
2188     /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2189      * because we dispatch all missing packets before shutting down. */
2190     if (ent == NULL)
2191       break;
2192
2193     /* Look for the correct `sockent_t' */
2194     se = listen_sockets;
2195     while (se != NULL) {
2196       size_t i;
2197
2198       for (i = 0; i < se->data.server.fd_num; i++)
2199         if (se->data.server.fd[i] == ent->fd)
2200           break;
2201
2202       if (i < se->data.server.fd_num)
2203         break;
2204
2205       se = se->next;
2206     }
2207
2208     if (se == NULL) {
2209       ERROR("network plugin: Got packet from FD %i, but can't "
2210             "find an appropriate socket entry.",
2211             ent->fd);
2212       sfree(ent->data);
2213       sfree(ent);
2214       continue;
2215     }
2216
2217     parse_packet(se, ent->data, ent->data_len, /* flags = */ 0,
2218                  /* username = */ NULL);
2219     sfree(ent->data);
2220     sfree(ent);
2221   } /* while (42) */
2222
2223   return NULL;
2224 } /* }}} void *dispatch_thread */
2225
2226 static int network_receive(void) /* {{{ */
2227 {
2228   char buffer[network_config_packet_size];
2229   int buffer_len;
2230
2231   int status = 0;
2232
2233   receive_list_entry_t *private_list_head;
2234   receive_list_entry_t *private_list_tail;
2235   uint64_t private_list_length;
2236
2237   assert(listen_sockets_num > 0);
2238
2239   private_list_head = NULL;
2240   private_list_tail = NULL;
2241   private_list_length = 0;
2242
2243   while (listen_loop == 0) {
2244     status = poll(listen_sockets_pollfd, listen_sockets_num, -1);
2245     if (status <= 0) {
2246       if (errno == EINTR)
2247         continue;
2248       ERROR("network plugin: poll(2) failed: %s", STRERRNO);
2249       break;
2250     }
2251
2252     for (size_t i = 0; (i < listen_sockets_num) && (status > 0); i++) {
2253       receive_list_entry_t *ent;
2254
2255       if ((listen_sockets_pollfd[i].revents & (POLLIN | POLLPRI)) == 0)
2256         continue;
2257       status--;
2258
2259       buffer_len = recv(listen_sockets_pollfd[i].fd, buffer, sizeof(buffer),
2260                         0 /* no flags */);
2261       if (buffer_len < 0) {
2262         status = (errno != 0) ? errno : -1;
2263         ERROR("network plugin: recv(2) failed: %s", STRERRNO);
2264         break;
2265       }
2266
2267       stats_octets_rx += ((uint64_t)buffer_len);
2268       stats_packets_rx++;
2269
2270       /* TODO: Possible performance enhancement: Do not free
2271        * these entries in the dispatch thread but put them in
2272        * another list, so we don't have to allocate more and
2273        * more of these structures. */
2274       ent = calloc(1, sizeof(*ent));
2275       if (ent == NULL) {
2276         ERROR("network plugin: calloc failed.");
2277         status = ENOMEM;
2278         break;
2279       }
2280
2281       ent->data = malloc(network_config_packet_size);
2282       if (ent->data == NULL) {
2283         sfree(ent);
2284         ERROR("network plugin: malloc failed.");
2285         status = ENOMEM;
2286         break;
2287       }
2288       ent->fd = listen_sockets_pollfd[i].fd;
2289       ent->next = NULL;
2290
2291       memcpy(ent->data, buffer, buffer_len);
2292       ent->data_len = buffer_len;
2293
2294       if (private_list_head == NULL)
2295         private_list_head = ent;
2296       else
2297         private_list_tail->next = ent;
2298       private_list_tail = ent;
2299       private_list_length++;
2300
2301       /* Do not block here. Blocking here has led to
2302        * insufficient performance in the past. */
2303       if (pthread_mutex_trylock(&receive_list_lock) == 0) {
2304         assert(((receive_list_head == NULL) && (receive_list_length == 0)) ||
2305                ((receive_list_head != NULL) && (receive_list_length != 0)));
2306
2307         if (receive_list_head == NULL)
2308           receive_list_head = private_list_head;
2309         else
2310           receive_list_tail->next = private_list_head;
2311         receive_list_tail = private_list_tail;
2312         receive_list_length += private_list_length;
2313
2314         pthread_cond_signal(&receive_list_cond);
2315         pthread_mutex_unlock(&receive_list_lock);
2316
2317         private_list_head = NULL;
2318         private_list_tail = NULL;
2319         private_list_length = 0;
2320       }
2321
2322       status = 0;
2323     } /* for (listen_sockets_pollfd) */
2324
2325     if (status != 0)
2326       break;
2327   } /* while (listen_loop == 0) */
2328
2329   /* Make sure everything is dispatched before exiting. */
2330   if (private_list_head != NULL) {
2331     pthread_mutex_lock(&receive_list_lock);
2332
2333     if (receive_list_head == NULL)
2334       receive_list_head = private_list_head;
2335     else
2336       receive_list_tail->next = private_list_head;
2337     receive_list_tail = private_list_tail;
2338     receive_list_length += private_list_length;
2339
2340     pthread_cond_signal(&receive_list_cond);
2341     pthread_mutex_unlock(&receive_list_lock);
2342   }
2343
2344   return status;
2345 } /* }}} int network_receive */
2346
2347 static void *receive_thread(void __attribute__((unused)) * arg) {
2348   return network_receive() ? (void *)1 : (void *)0;
2349 } /* void *receive_thread */
2350
2351 static void network_init_buffer(void) {
2352   memset(send_buffer, 0, network_config_packet_size);
2353   send_buffer_ptr = send_buffer;
2354   send_buffer_fill = 0;
2355   send_buffer_last_update = 0;
2356
2357   memset(&send_buffer_vl, 0, sizeof(send_buffer_vl));
2358 } /* int network_init_buffer */
2359
2360 static void network_send_buffer_plain(sockent_t *se, /* {{{ */
2361                                       const char *buffer, size_t buffer_size) {
2362   int status;
2363
2364   while (42) {
2365     status = sockent_client_connect(se);
2366     if (status != 0)
2367       return;
2368
2369     status = sendto(se->data.client.fd, buffer, buffer_size,
2370                     /* flags = */ 0, (struct sockaddr *)se->data.client.addr,
2371                     se->data.client.addrlen);
2372     if (status < 0) {
2373       if ((errno == EINTR) || (errno == EAGAIN))
2374         continue;
2375
2376       ERROR("network plugin: sendto failed: %s. Closing sending socket.",
2377             STRERRNO);
2378       sockent_client_disconnect(se);
2379       return;
2380     }
2381
2382     break;
2383   } /* while (42) */
2384 } /* }}} void network_send_buffer_plain */
2385
2386 #if HAVE_GCRYPT_H
2387 #define BUFFER_ADD(p, s)                                                       \
2388   do {                                                                         \
2389     memcpy(buffer + buffer_offset, (p), (s));                                  \
2390     buffer_offset += (s);                                                      \
2391   } while (0)
2392
2393 static void network_send_buffer_signed(sockent_t *se, /* {{{ */
2394                                        const char *in_buffer,
2395                                        size_t in_buffer_size) {
2396   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2397   size_t buffer_offset;
2398   size_t username_len;
2399
2400   gcry_md_hd_t hd;
2401   gcry_error_t err;
2402   unsigned char *hash;
2403
2404   hd = NULL;
2405   err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2406   if (err != 0) {
2407     ERROR("network plugin: Creating HMAC object failed: %s",
2408           gcry_strerror(err));
2409     return;
2410   }
2411
2412   err = gcry_md_setkey(hd, se->data.client.password,
2413                        strlen(se->data.client.password));
2414   if (err != 0) {
2415     ERROR("network plugin: gcry_md_setkey failed: %s", gcry_strerror(err));
2416     gcry_md_close(hd);
2417     return;
2418   }
2419
2420   username_len = strlen(se->data.client.username);
2421   if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE)) {
2422     ERROR("network plugin: Username too long: %s", se->data.client.username);
2423     return;
2424   }
2425
2426   memcpy(buffer + PART_SIGNATURE_SHA256_SIZE, se->data.client.username,
2427          username_len);
2428   memcpy(buffer + PART_SIGNATURE_SHA256_SIZE + username_len, in_buffer,
2429          in_buffer_size);
2430
2431   /* Initialize the `ps' structure. */
2432   part_signature_sha256_t ps = {
2433       .head.type = htons(TYPE_SIGN_SHA256),
2434       .head.length = htons(PART_SIGNATURE_SHA256_SIZE + username_len)};
2435
2436   /* Calculate the hash value. */
2437   gcry_md_write(hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2438                 username_len + in_buffer_size);
2439   hash = gcry_md_read(hd, GCRY_MD_SHA256);
2440   if (hash == NULL) {
2441     ERROR("network plugin: gcry_md_read failed.");
2442     gcry_md_close(hd);
2443     return;
2444   }
2445   memcpy(ps.hash, hash, sizeof(ps.hash));
2446
2447   /* Add the header */
2448   buffer_offset = 0;
2449
2450   BUFFER_ADD(&ps.head.type, sizeof(ps.head.type));
2451   BUFFER_ADD(&ps.head.length, sizeof(ps.head.length));
2452   BUFFER_ADD(ps.hash, sizeof(ps.hash));
2453
2454   assert(buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2455
2456   gcry_md_close(hd);
2457   hd = NULL;
2458
2459   buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2460   network_send_buffer_plain(se, buffer, buffer_offset);
2461 } /* }}} void network_send_buffer_signed */
2462
2463 static void network_send_buffer_encrypted(sockent_t *se, /* {{{ */
2464                                           const char *in_buffer,
2465                                           size_t in_buffer_size) {
2466   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2467   size_t buffer_size;
2468   size_t buffer_offset;
2469   size_t header_size;
2470   size_t username_len;
2471   gcry_error_t err;
2472   gcry_cipher_hd_t cypher;
2473
2474   /* Initialize the header fields */
2475   part_encryption_aes256_t pea = {.head.type = htons(TYPE_ENCR_AES256),
2476                                   .username = se->data.client.username};
2477
2478   username_len = strlen(pea.username);
2479   if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE) {
2480     ERROR("network plugin: Username too long: %s", pea.username);
2481     return;
2482   }
2483
2484   buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2485   header_size = PART_ENCRYPTION_AES256_SIZE + username_len - sizeof(pea.hash);
2486
2487   assert(buffer_size <= sizeof(buffer));
2488   DEBUG("network plugin: network_send_buffer_encrypted: "
2489         "buffer_size = %" PRIsz ";",
2490         buffer_size);
2491
2492   pea.head.length = htons(
2493       (uint16_t)(PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size));
2494   pea.username_length = htons((uint16_t)username_len);
2495
2496   /* Chose a random initialization vector. */
2497   gcry_randomize((void *)&pea.iv, sizeof(pea.iv), GCRY_STRONG_RANDOM);
2498
2499   /* Create hash of the payload */
2500   gcry_md_hash_buffer(GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2501
2502   /* Initialize the buffer */
2503   buffer_offset = 0;
2504   memset(buffer, 0, sizeof(buffer));
2505
2506   BUFFER_ADD(&pea.head.type, sizeof(pea.head.type));
2507   BUFFER_ADD(&pea.head.length, sizeof(pea.head.length));
2508   BUFFER_ADD(&pea.username_length, sizeof(pea.username_length));
2509   BUFFER_ADD(pea.username, username_len);
2510   BUFFER_ADD(pea.iv, sizeof(pea.iv));
2511   assert(buffer_offset == header_size);
2512   BUFFER_ADD(pea.hash, sizeof(pea.hash));
2513   BUFFER_ADD(in_buffer, in_buffer_size);
2514
2515   assert(buffer_offset == buffer_size);
2516
2517   cypher = network_get_aes256_cypher(se, pea.iv, sizeof(pea.iv),
2518                                      se->data.client.password);
2519   if (cypher == NULL)
2520     return;
2521
2522   /* Encrypt the buffer in-place */
2523   err = gcry_cipher_encrypt(cypher, buffer + header_size,
2524                             buffer_size - header_size,
2525                             /* in = */ NULL, /* in len = */ 0);
2526   if (err != 0) {
2527     ERROR("network plugin: gcry_cipher_encrypt returned: %s",
2528           gcry_strerror(err));
2529     return;
2530   }
2531
2532   /* Send it out without further modifications */
2533   network_send_buffer_plain(se, buffer, buffer_size);
2534 } /* }}} void network_send_buffer_encrypted */
2535 #undef BUFFER_ADD
2536 #endif /* HAVE_GCRYPT_H */
2537
2538 static void network_send_buffer(char *buffer, size_t buffer_len) /* {{{ */
2539 {
2540   DEBUG("network plugin: network_send_buffer: buffer_len = %" PRIsz,
2541         buffer_len);
2542
2543   for (sockent_t *se = sending_sockets; se != NULL; se = se->next) {
2544 #if HAVE_GCRYPT_H
2545     if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2546       network_send_buffer_encrypted(se, buffer, buffer_len);
2547     else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2548       network_send_buffer_signed(se, buffer, buffer_len);
2549     else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2550 #endif   /* HAVE_GCRYPT_H */
2551       network_send_buffer_plain(se, buffer, buffer_len);
2552   } /* for (sending_sockets) */
2553 } /* }}} void network_send_buffer */
2554
2555 static int add_to_buffer(char *buffer, size_t buffer_size, /* {{{ */
2556                          value_list_t *vl_def, const data_set_t *ds,
2557                          const value_list_t *vl) {
2558   char *buffer_orig = buffer;
2559
2560   if (strcmp(vl_def->host, vl->host) != 0) {
2561     if (write_part_string(&buffer, &buffer_size, TYPE_HOST, vl->host,
2562                           strlen(vl->host)) != 0)
2563       return -1;
2564     sstrncpy(vl_def->host, vl->host, sizeof(vl_def->host));
2565   }
2566
2567   if (vl_def->time != vl->time) {
2568     if (write_part_number(&buffer, &buffer_size, TYPE_TIME_HR,
2569                           (uint64_t)vl->time))
2570       return -1;
2571     vl_def->time = vl->time;
2572   }
2573
2574   if (vl_def->interval != vl->interval) {
2575     if (write_part_number(&buffer, &buffer_size, TYPE_INTERVAL_HR,
2576                           (uint64_t)vl->interval))
2577       return -1;
2578     vl_def->interval = vl->interval;
2579   }
2580
2581   if (strcmp(vl_def->plugin, vl->plugin) != 0) {
2582     if (write_part_string(&buffer, &buffer_size, TYPE_PLUGIN, vl->plugin,
2583                           strlen(vl->plugin)) != 0)
2584       return -1;
2585     sstrncpy(vl_def->plugin, vl->plugin, sizeof(vl_def->plugin));
2586   }
2587
2588   if (strcmp(vl_def->plugin_instance, vl->plugin_instance) != 0) {
2589     if (write_part_string(&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2590                           vl->plugin_instance,
2591                           strlen(vl->plugin_instance)) != 0)
2592       return -1;
2593     sstrncpy(vl_def->plugin_instance, vl->plugin_instance,
2594              sizeof(vl_def->plugin_instance));
2595   }
2596
2597   if (strcmp(vl_def->type, vl->type) != 0) {
2598     if (write_part_string(&buffer, &buffer_size, TYPE_TYPE, vl->type,
2599                           strlen(vl->type)) != 0)
2600       return -1;
2601     sstrncpy(vl_def->type, ds->type, sizeof(vl_def->type));
2602   }
2603
2604   if (strcmp(vl_def->type_instance, vl->type_instance) != 0) {
2605     if (write_part_string(&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2606                           vl->type_instance, strlen(vl->type_instance)) != 0)
2607       return -1;
2608     sstrncpy(vl_def->type_instance, vl->type_instance,
2609              sizeof(vl_def->type_instance));
2610   }
2611
2612   if (write_part_values(&buffer, &buffer_size, ds, vl) != 0)
2613     return -1;
2614
2615   return buffer - buffer_orig;
2616 } /* }}} int add_to_buffer */
2617
2618 static void flush_buffer(void) {
2619   DEBUG("network plugin: flush_buffer: send_buffer_fill = %i",
2620         send_buffer_fill);
2621
2622   network_send_buffer(send_buffer, (size_t)send_buffer_fill);
2623
2624   stats_octets_tx += ((uint64_t)send_buffer_fill);
2625   stats_packets_tx++;
2626
2627   network_init_buffer();
2628 }
2629
2630 static int network_write(const data_set_t *ds, const value_list_t *vl,
2631                          user_data_t __attribute__((unused)) * user_data) {
2632   int status;
2633
2634   /* listen_loop is set to non-zero in the shutdown callback, which is
2635    * guaranteed to be called *after* all the write threads have been shut
2636    * down. */
2637   assert(listen_loop == 0);
2638
2639   if (!check_send_okay(vl)) {
2640 #if COLLECT_DEBUG
2641     char name[6 * DATA_MAX_NAME_LEN];
2642     FORMAT_VL(name, sizeof(name), vl);
2643     name[sizeof(name) - 1] = '\0';
2644     DEBUG("network plugin: network_write: "
2645           "NOT sending %s.",
2646           name);
2647 #endif
2648     /* Counter is not protected by another lock and may be reached by
2649      * multiple threads */
2650     pthread_mutex_lock(&stats_lock);
2651     stats_values_not_sent++;
2652     pthread_mutex_unlock(&stats_lock);
2653     return 0;
2654   }
2655
2656   uc_meta_data_add_unsigned_int(vl, "network:time_sent", (uint64_t)vl->time);
2657
2658   pthread_mutex_lock(&send_buffer_lock);
2659
2660   status = add_to_buffer(send_buffer_ptr,
2661                          network_config_packet_size -
2662                              (send_buffer_fill + BUFF_SIG_SIZE),
2663                          &send_buffer_vl, ds, vl);
2664   if (status >= 0) {
2665     /* status == bytes added to the buffer */
2666     send_buffer_fill += status;
2667     send_buffer_ptr += status;
2668     send_buffer_last_update = cdtime();
2669
2670     stats_values_sent++;
2671   } else {
2672     flush_buffer();
2673
2674     status = add_to_buffer(send_buffer_ptr,
2675                            network_config_packet_size -
2676                                (send_buffer_fill + BUFF_SIG_SIZE),
2677                            &send_buffer_vl, ds, vl);
2678
2679     if (status >= 0) {
2680       send_buffer_fill += status;
2681       send_buffer_ptr += status;
2682
2683       stats_values_sent++;
2684     }
2685   }
2686
2687   if (status < 0) {
2688     ERROR("network plugin: Unable to append to the "
2689           "buffer for some weird reason");
2690   } else if ((network_config_packet_size - send_buffer_fill) < 15) {
2691     flush_buffer();
2692   }
2693
2694   pthread_mutex_unlock(&send_buffer_lock);
2695
2696   return (status < 0) ? -1 : 0;
2697 } /* int network_write */
2698
2699 static int network_config_set_ttl(const oconfig_item_t *ci) /* {{{ */
2700 {
2701   int tmp = 0;
2702
2703   if (cf_util_get_int(ci, &tmp) != 0)
2704     return -1;
2705   else if ((tmp > 0) && (tmp <= 255))
2706     network_config_ttl = tmp;
2707   else {
2708     WARNING("network plugin: The `TimeToLive' must be between 1 and 255.");
2709     return -1;
2710   }
2711
2712   return 0;
2713 } /* }}} int network_config_set_ttl */
2714
2715 static int network_config_set_interface(const oconfig_item_t *ci, /* {{{ */
2716                                         int *interface) {
2717   char if_name[256];
2718
2719   if (cf_util_get_string_buffer(ci, if_name, sizeof(if_name)) != 0)
2720     return -1;
2721
2722   *interface = if_nametoindex(if_name);
2723   return 0;
2724 } /* }}} int network_config_set_interface */
2725
2726 static int
2727 network_config_set_bind_address(const oconfig_item_t *ci,
2728                                 struct sockaddr_storage **bind_address) {
2729   if ((*bind_address) != NULL) {
2730     ERROR("network_plugin: only a single bind address is allowed");
2731     return -1;
2732   }
2733
2734   char addr_text[256];
2735
2736   if (cf_util_get_string_buffer(ci, addr_text, sizeof(addr_text)) != 0)
2737     return -1;
2738
2739   int ret;
2740   struct addrinfo *res = NULL;
2741   struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
2742                               .ai_flags = AI_NUMERICHOST,
2743                               .ai_protocol = IPPROTO_UDP,
2744                               .ai_socktype = SOCK_DGRAM};
2745
2746   ret = getaddrinfo(addr_text, NULL, &ai_hints, &res);
2747   if (ret) {
2748     ERROR("network plugin: Bind address option has invalid address set: %s",
2749           gai_strerror(ret));
2750     return -1;
2751   }
2752
2753   *bind_address = malloc(sizeof(**bind_address));
2754   if (*bind_address == NULL) {
2755     ERROR("network plugin: network_config_set_bind_address: malloc failed.");
2756     return -1;
2757   }
2758   (*bind_address)->ss_family = res->ai_family;
2759   if (res->ai_family == AF_INET) {
2760     struct sockaddr_in *addr = (struct sockaddr_in *)(*bind_address);
2761     inet_pton(AF_INET, addr_text, &(addr->sin_addr));
2762   } else if (res->ai_family == AF_INET6) {
2763     struct sockaddr_in6 *addr = (struct sockaddr_in6 *)(*bind_address);
2764     inet_pton(AF_INET6, addr_text, &(addr->sin6_addr));
2765   } else {
2766     ERROR("network plugin: %s is an unknown address format %d\n", addr_text,
2767           res->ai_family);
2768     sfree(*bind_address);
2769     freeaddrinfo(res);
2770     return -1;
2771   }
2772
2773   freeaddrinfo(res);
2774   return 0;
2775 } /* int network_config_set_bind_address */
2776
2777 static int network_config_set_buffer_size(const oconfig_item_t *ci) /* {{{ */
2778 {
2779   int tmp = 0;
2780
2781   if (cf_util_get_int(ci, &tmp) != 0)
2782     return -1;
2783   else if ((tmp >= 1024) && (tmp <= 65535))
2784     network_config_packet_size = tmp;
2785   else {
2786     WARNING(
2787         "network plugin: The `MaxPacketSize' must be between 1024 and 65535.");
2788     return -1;
2789   }
2790
2791   return 0;
2792 } /* }}} int network_config_set_buffer_size */
2793
2794 #if HAVE_GCRYPT_H
2795 static int network_config_set_security_level(oconfig_item_t *ci, /* {{{ */
2796                                              int *retval) {
2797   char *str;
2798   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
2799     WARNING("network plugin: The `SecurityLevel' config option needs exactly "
2800             "one string argument.");
2801     return -1;
2802   }
2803
2804   str = ci->values[0].value.string;
2805   if (strcasecmp("Encrypt", str) == 0)
2806     *retval = SECURITY_LEVEL_ENCRYPT;
2807   else if (strcasecmp("Sign", str) == 0)
2808     *retval = SECURITY_LEVEL_SIGN;
2809   else if (strcasecmp("None", str) == 0)
2810     *retval = SECURITY_LEVEL_NONE;
2811   else {
2812     WARNING("network plugin: Unknown security level: %s.", str);
2813     return -1;
2814   }
2815
2816   return 0;
2817 } /* }}} int network_config_set_security_level */
2818 #endif /* HAVE_GCRYPT_H */
2819
2820 static int network_config_add_listen(const oconfig_item_t *ci) /* {{{ */
2821 {
2822   sockent_t *se;
2823   int status;
2824
2825   if ((ci->values_num < 1) || (ci->values_num > 2) ||
2826       (ci->values[0].type != OCONFIG_TYPE_STRING) ||
2827       ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING))) {
2828     ERROR("network plugin: The `%s' config option needs "
2829           "one or two string arguments.",
2830           ci->key);
2831     return -1;
2832   }
2833
2834   se = sockent_create(SOCKENT_TYPE_SERVER);
2835   if (se == NULL) {
2836     ERROR("network plugin: sockent_create failed.");
2837     return -1;
2838   }
2839
2840   se->node = strdup(ci->values[0].value.string);
2841   if (ci->values_num >= 2)
2842     se->service = strdup(ci->values[1].value.string);
2843
2844   for (int i = 0; i < ci->children_num; i++) {
2845     oconfig_item_t *child = ci->children + i;
2846
2847 #if HAVE_GCRYPT_H
2848     if (strcasecmp("AuthFile", child->key) == 0)
2849       cf_util_get_string(child, &se->data.server.auth_file);
2850     else if (strcasecmp("SecurityLevel", child->key) == 0)
2851       network_config_set_security_level(child, &se->data.server.security_level);
2852     else
2853 #endif /* HAVE_GCRYPT_H */
2854         if (strcasecmp("Interface", child->key) == 0)
2855       network_config_set_interface(child, &se->interface);
2856     else {
2857       WARNING("network plugin: Option `%s' is not allowed here.", child->key);
2858     }
2859   }
2860
2861 #if HAVE_GCRYPT_H
2862   if ((se->data.server.security_level > SECURITY_LEVEL_NONE) &&
2863       (se->data.server.auth_file == NULL)) {
2864     ERROR("network plugin: A security level higher than `none' was "
2865           "requested, but no AuthFile option was given. Cowardly refusing to "
2866           "open this socket!");
2867     sockent_destroy(se);
2868     return -1;
2869   }
2870 #endif /* HAVE_GCRYPT_H */
2871
2872   status = sockent_init_crypto(se);
2873   if (status != 0) {
2874     ERROR("network plugin: network_config_add_listen: sockent_init_crypto() "
2875           "failed.");
2876     sockent_destroy(se);
2877     return -1;
2878   }
2879
2880   status = sockent_server_listen(se);
2881   if (status != 0) {
2882     ERROR("network plugin: network_config_add_listen: sockent_server_listen "
2883           "failed.");
2884     sockent_destroy(se);
2885     return -1;
2886   }
2887
2888   status = sockent_add(se);
2889   if (status != 0) {
2890     ERROR("network plugin: network_config_add_listen: sockent_add failed.");
2891     sockent_destroy(se);
2892     return -1;
2893   }
2894
2895   return 0;
2896 } /* }}} int network_config_add_listen */
2897
2898 static int network_config_add_server(const oconfig_item_t *ci) /* {{{ */
2899 {
2900   sockent_t *se;
2901   int status;
2902
2903   if ((ci->values_num < 1) || (ci->values_num > 2) ||
2904       (ci->values[0].type != OCONFIG_TYPE_STRING) ||
2905       ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING))) {
2906     ERROR("network plugin: The `%s' config option needs "
2907           "one or two string arguments.",
2908           ci->key);
2909     return -1;
2910   }
2911
2912   se = sockent_create(SOCKENT_TYPE_CLIENT);
2913   if (se == NULL) {
2914     ERROR("network plugin: sockent_create failed.");
2915     return -1;
2916   }
2917
2918   se->node = strdup(ci->values[0].value.string);
2919   if (ci->values_num >= 2)
2920     se->service = strdup(ci->values[1].value.string);
2921
2922   for (int i = 0; i < ci->children_num; i++) {
2923     oconfig_item_t *child = ci->children + i;
2924
2925 #if HAVE_GCRYPT_H
2926     if (strcasecmp("Username", child->key) == 0)
2927       cf_util_get_string(child, &se->data.client.username);
2928     else if (strcasecmp("Password", child->key) == 0)
2929       cf_util_get_string(child, &se->data.client.password);
2930     else if (strcasecmp("SecurityLevel", child->key) == 0)
2931       network_config_set_security_level(child, &se->data.client.security_level);
2932     else
2933 #endif /* HAVE_GCRYPT_H */
2934         if (strcasecmp("Interface", child->key) == 0)
2935       network_config_set_interface(child, &se->interface);
2936     else if (strcasecmp("BindAddress", child->key) == 0)
2937       network_config_set_bind_address(child, &se->data.client.bind_addr);
2938     else if (strcasecmp("ResolveInterval", child->key) == 0)
2939       cf_util_get_cdtime(child, &se->data.client.resolve_interval);
2940     else {
2941       WARNING("network plugin: Option `%s' is not allowed here.", child->key);
2942     }
2943   }
2944
2945 #if HAVE_GCRYPT_H
2946   if ((se->data.client.security_level > SECURITY_LEVEL_NONE) &&
2947       ((se->data.client.username == NULL) ||
2948        (se->data.client.password == NULL))) {
2949     ERROR("network plugin: A security level higher than `none' was "
2950           "requested, but no Username or Password option was given. "
2951           "Cowardly refusing to open this socket!");
2952     sockent_destroy(se);
2953     return -1;
2954   }
2955 #endif /* HAVE_GCRYPT_H */
2956
2957   status = sockent_init_crypto(se);
2958   if (status != 0) {
2959     ERROR("network plugin: network_config_add_server: sockent_init_crypto() "
2960           "failed.");
2961     sockent_destroy(se);
2962     return -1;
2963   }
2964
2965   /* No call to sockent_client_connect() here -- it is called from
2966    * network_send_buffer_plain(). */
2967
2968   status = sockent_add(se);
2969   if (status != 0) {
2970     ERROR("network plugin: network_config_add_server: sockent_add failed.");
2971     sockent_destroy(se);
2972     return -1;
2973   }
2974
2975   return 0;
2976 } /* }}} int network_config_add_server */
2977
2978 static int network_config(oconfig_item_t *ci) /* {{{ */
2979 {
2980   /* The options need to be applied first */
2981   for (int i = 0; i < ci->children_num; i++) {
2982     oconfig_item_t *child = ci->children + i;
2983     if (strcasecmp("TimeToLive", child->key) == 0)
2984       network_config_set_ttl(child);
2985   }
2986
2987   for (int i = 0; i < ci->children_num; i++) {
2988     oconfig_item_t *child = ci->children + i;
2989
2990     if (strcasecmp("Listen", child->key) == 0)
2991       network_config_add_listen(child);
2992     else if (strcasecmp("Server", child->key) == 0)
2993       network_config_add_server(child);
2994     else if (strcasecmp("TimeToLive", child->key) == 0) {
2995       /* Handled earlier */
2996     } else if (strcasecmp("MaxPacketSize", child->key) == 0)
2997       network_config_set_buffer_size(child);
2998     else if (strcasecmp("Forward", child->key) == 0)
2999       cf_util_get_boolean(child, &network_config_forward);
3000     else if (strcasecmp("ReportStats", child->key) == 0)
3001       cf_util_get_boolean(child, &network_config_stats);
3002     else {
3003       WARNING("network plugin: Option `%s' is not allowed here.", child->key);
3004     }
3005   }
3006
3007   return 0;
3008 } /* }}} int network_config */
3009
3010 static int network_notification(const notification_t *n,
3011                                 user_data_t __attribute__((unused)) *
3012                                     user_data) {
3013   char buffer[network_config_packet_size];
3014   char *buffer_ptr = buffer;
3015   size_t buffer_free = sizeof(buffer);
3016   int status;
3017
3018   if (!check_send_notify_okay(n))
3019     return 0;
3020
3021   memset(buffer, 0, sizeof(buffer));
3022
3023   status = write_part_number(&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3024                              (uint64_t)n->time);
3025   if (status != 0)
3026     return -1;
3027
3028   status = write_part_number(&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3029                              (uint64_t)n->severity);
3030   if (status != 0)
3031     return -1;
3032
3033   if (strlen(n->host) > 0) {
3034     status = write_part_string(&buffer_ptr, &buffer_free, TYPE_HOST, n->host,
3035                                strlen(n->host));
3036     if (status != 0)
3037       return -1;
3038   }
3039
3040   if (strlen(n->plugin) > 0) {
3041     status = write_part_string(&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3042                                n->plugin, strlen(n->plugin));
3043     if (status != 0)
3044       return -1;
3045   }
3046
3047   if (strlen(n->plugin_instance) > 0) {
3048     status = write_part_string(&buffer_ptr, &buffer_free, TYPE_PLUGIN_INSTANCE,
3049                                n->plugin_instance, strlen(n->plugin_instance));
3050     if (status != 0)
3051       return -1;
3052   }
3053
3054   if (strlen(n->type) > 0) {
3055     status = write_part_string(&buffer_ptr, &buffer_free, TYPE_TYPE, n->type,
3056                                strlen(n->type));
3057     if (status != 0)
3058       return -1;
3059   }
3060
3061   if (strlen(n->type_instance) > 0) {
3062     status = write_part_string(&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3063                                n->type_instance, strlen(n->type_instance));
3064     if (status != 0)
3065       return -1;
3066   }
3067
3068   status = write_part_string(&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3069                              n->message, strlen(n->message));
3070   if (status != 0)
3071     return -1;
3072
3073   network_send_buffer(buffer, sizeof(buffer) - buffer_free);
3074
3075   return 0;
3076 } /* int network_notification */
3077
3078 static int network_shutdown(void) {
3079   listen_loop++;
3080
3081   /* Kill the listening thread */
3082   if (receive_thread_running != 0) {
3083     INFO("network plugin: Stopping receive thread.");
3084     pthread_kill(receive_thread_id, SIGTERM);
3085     pthread_join(receive_thread_id, NULL /* no return value */);
3086     memset(&receive_thread_id, 0, sizeof(receive_thread_id));
3087     receive_thread_running = 0;
3088   }
3089
3090   /* Shutdown the dispatching thread */
3091   if (dispatch_thread_running != 0) {
3092     INFO("network plugin: Stopping dispatch thread.");
3093     pthread_mutex_lock(&receive_list_lock);
3094     pthread_cond_broadcast(&receive_list_cond);
3095     pthread_mutex_unlock(&receive_list_lock);
3096     pthread_join(dispatch_thread_id, /* ret = */ NULL);
3097     dispatch_thread_running = 0;
3098   }
3099
3100   sockent_destroy(listen_sockets);
3101
3102   if (send_buffer_fill > 0)
3103     flush_buffer();
3104
3105   sfree(send_buffer);
3106
3107   for (sockent_t *se = sending_sockets; se != NULL; se = se->next)
3108     sockent_client_disconnect(se);
3109   sockent_destroy(sending_sockets);
3110
3111   plugin_unregister_config("network");
3112   plugin_unregister_init("network");
3113   plugin_unregister_write("network");
3114   plugin_unregister_shutdown("network");
3115
3116   return 0;
3117 } /* int network_shutdown */
3118
3119 static int network_stats_read(void) /* {{{ */
3120 {
3121   derive_t copy_octets_rx;
3122   derive_t copy_octets_tx;
3123   derive_t copy_packets_rx;
3124   derive_t copy_packets_tx;
3125   derive_t copy_values_dispatched;
3126   derive_t copy_values_not_dispatched;
3127   derive_t copy_values_sent;
3128   derive_t copy_values_not_sent;
3129   derive_t copy_receive_list_length;
3130   value_list_t vl = VALUE_LIST_INIT;
3131   value_t values[2];
3132
3133   copy_octets_rx = stats_octets_rx;
3134   copy_octets_tx = stats_octets_tx;
3135   copy_packets_rx = stats_packets_rx;
3136   copy_packets_tx = stats_packets_tx;
3137   copy_values_dispatched = stats_values_dispatched;
3138   copy_values_not_dispatched = stats_values_not_dispatched;
3139   copy_values_sent = stats_values_sent;
3140   copy_values_not_sent = stats_values_not_sent;
3141   copy_receive_list_length = receive_list_length;
3142
3143   /* Initialize `vl' */
3144   vl.values = values;
3145   vl.values_len = 2;
3146   vl.time = 0;
3147   sstrncpy(vl.plugin, "network", sizeof(vl.plugin));
3148
3149   /* Octets received / sent */
3150   vl.values[0].derive = (derive_t)copy_octets_rx;
3151   vl.values[1].derive = (derive_t)copy_octets_tx;
3152   sstrncpy(vl.type, "if_octets", sizeof(vl.type));
3153   plugin_dispatch_values(&vl);
3154
3155   /* Packets received / send */
3156   vl.values[0].derive = (derive_t)copy_packets_rx;
3157   vl.values[1].derive = (derive_t)copy_packets_tx;
3158   sstrncpy(vl.type, "if_packets", sizeof(vl.type));
3159   plugin_dispatch_values(&vl);
3160
3161   /* Values (not) dispatched and (not) send */
3162   sstrncpy(vl.type, "total_values", sizeof(vl.type));
3163   vl.values_len = 1;
3164
3165   vl.values[0].derive = (derive_t)copy_values_dispatched;
3166   sstrncpy(vl.type_instance, "dispatch-accepted", sizeof(vl.type_instance));
3167   plugin_dispatch_values(&vl);
3168
3169   vl.values[0].derive = (derive_t)copy_values_not_dispatched;
3170   sstrncpy(vl.type_instance, "dispatch-rejected", sizeof(vl.type_instance));
3171   plugin_dispatch_values(&vl);
3172
3173   vl.values[0].derive = (derive_t)copy_values_sent;
3174   sstrncpy(vl.type_instance, "send-accepted", sizeof(vl.type_instance));
3175   plugin_dispatch_values(&vl);
3176
3177   vl.values[0].derive = (derive_t)copy_values_not_sent;
3178   sstrncpy(vl.type_instance, "send-rejected", sizeof(vl.type_instance));
3179   plugin_dispatch_values(&vl);
3180
3181   /* Receive queue length */
3182   vl.values[0].gauge = (gauge_t)copy_receive_list_length;
3183   sstrncpy(vl.type, "queue_length", sizeof(vl.type));
3184   vl.type_instance[0] = 0;
3185   plugin_dispatch_values(&vl);
3186
3187   return 0;
3188 } /* }}} int network_stats_read */
3189
3190 static int network_init(void) {
3191   static bool have_init;
3192
3193   /* Check if we were already initialized. If so, just return - there's
3194    * nothing more to do (for now, that is). */
3195   if (have_init)
3196     return 0;
3197   have_init = true;
3198
3199   if (network_config_stats)
3200     plugin_register_read("network", network_stats_read);
3201
3202   plugin_register_shutdown("network", network_shutdown);
3203
3204   send_buffer = malloc(network_config_packet_size);
3205   if (send_buffer == NULL) {
3206     ERROR("network plugin: malloc failed.");
3207     return -1;
3208   }
3209   network_init_buffer();
3210
3211   /* setup socket(s) and so on */
3212   if (sending_sockets != NULL) {
3213     plugin_register_write("network", network_write,
3214                           /* user_data = */ NULL);
3215     plugin_register_notification("network", network_notification,
3216                                  /* user_data = */ NULL);
3217   }
3218
3219   /* If no threads need to be started, return here. */
3220   if ((listen_sockets_num == 0) ||
3221       ((dispatch_thread_running != 0) && (receive_thread_running != 0)))
3222     return 0;
3223
3224   if (dispatch_thread_running == 0) {
3225     int status;
3226     status = plugin_thread_create(&dispatch_thread_id, NULL /* no attributes */,
3227                                   dispatch_thread, NULL /* no argument */,
3228                                   "network disp");
3229     if (status != 0) {
3230       ERROR("network: pthread_create failed: %s", STRERRNO);
3231     } else {
3232       dispatch_thread_running = 1;
3233     }
3234   }
3235
3236   if (receive_thread_running == 0) {
3237     int status;
3238     status = plugin_thread_create(&receive_thread_id, NULL /* no attributes */,
3239                                   receive_thread, NULL /* no argument */,
3240                                   "network recv");
3241     if (status != 0) {
3242       ERROR("network: pthread_create failed: %s", STRERRNO);
3243     } else {
3244       receive_thread_running = 1;
3245     }
3246   }
3247
3248   return 0;
3249 } /* int network_init */
3250
3251 /*
3252  * The flush option of the network plugin cannot flush individual identifiers.
3253  * All the values are added to a buffer and sent when the buffer is full, the
3254  * requested value may or may not be in there, it's not worth finding out. We
3255  * just send the buffer if `flush'  is called - if the requested value was in
3256  * there, good. If not, well, then there is nothing to flush.. -octo
3257  */
3258 static int network_flush(cdtime_t timeout,
3259                          __attribute__((unused)) const char *identifier,
3260                          __attribute__((unused)) user_data_t *user_data) {
3261   pthread_mutex_lock(&send_buffer_lock);
3262
3263   if (send_buffer_fill > 0) {
3264     if (timeout > 0) {
3265       cdtime_t now = cdtime();
3266       if ((send_buffer_last_update + timeout) > now) {
3267         pthread_mutex_unlock(&send_buffer_lock);
3268         return 0;
3269       }
3270     }
3271     flush_buffer();
3272   }
3273   pthread_mutex_unlock(&send_buffer_lock);
3274
3275   return 0;
3276 } /* int network_flush */
3277
3278 void module_register(void) {
3279   plugin_register_complex_config("network", network_config);
3280   plugin_register_init("network", network_init);
3281   plugin_register_flush("network", network_flush,
3282                         /* user_data = */ NULL);
3283 } /* void module_register */