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