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