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