2 * collectd - src/network.c
3 * Copyright (C) 2005-2013 Florian octo Forster
4 * Copyright (C) 2009 Aman Gupta
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
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.
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
21 * Florian octo Forster <octo at collectd.org>
22 * Aman Gupta <aman at tmm1.net>
25 #define _DEFAULT_SOURCE
26 #define _BSD_SOURCE /* For struct ip_mreq */
32 #include "utils_cache.h"
33 #include "utils_complain.h"
34 #include "utils_fbhash.h"
42 #include <netinet/in.h>
45 #include <arpa/inet.h>
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
60 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
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
66 #define GCRYPT_NO_DEPRECATED
69 /* Re enable deprecation warnings */
70 #pragma GCC diagnostic warning "-Wdeprecated-declarations"
72 #if GCRYPT_VERSION_NUMBER < 0x010600
73 GCRY_THREAD_OPTION_PTHREAD_IMPL;
77 #ifndef IPV6_ADD_MEMBERSHIP
78 #ifdef IPV6_JOIN_GROUP
79 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
81 #error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
83 #endif /* !IP_ADD_MEMBERSHIP */
86 * Maximum size required for encryption / signing:
88 * 42 bytes for the encryption header
89 * + 64 bytes for the username
93 #define BUFF_SIG_SIZE 106
98 #define SECURITY_LEVEL_NONE 0
100 #define SECURITY_LEVEL_SIGN 1
101 #define SECURITY_LEVEL_ENCRYPT 2
103 struct sockent_client {
105 struct sockaddr_storage *addr;
111 gcry_cipher_hd_t cypher;
112 unsigned char password_hash[32];
114 cdtime_t next_resolve_reconnect;
115 cdtime_t resolve_interval;
116 struct sockaddr_storage *bind_addr;
119 struct sockent_server {
126 gcry_cipher_hd_t cypher;
130 typedef struct sockent {
131 #define SOCKENT_TYPE_CLIENT 1
132 #define SOCKENT_TYPE_SERVER 2
140 struct sockent_client client;
141 struct sockent_server server;
144 struct sockent *next;
147 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
148 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
149 * +-------+-----------------------+-------------------------------+
150 * ! Ver. ! ! Length !
151 * +-------+-----------------------+-------------------------------+
153 struct part_header_s {
157 typedef struct part_header_s part_header_t;
159 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
160 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
161 * +-------------------------------+-------------------------------+
163 * +-------------------------------+-------------------------------+
164 * : (Length - 4) Bytes :
165 * +---------------------------------------------------------------+
167 struct part_string_s {
171 typedef struct part_string_s part_string_t;
173 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
174 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
175 * +-------------------------------+-------------------------------+
177 * +-------------------------------+-------------------------------+
178 * : (Length - 4 == 2 || 4 || 8) Bytes :
179 * +---------------------------------------------------------------+
181 struct part_number_s {
185 typedef struct part_number_s part_number_t;
187 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
188 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
189 * +-------------------------------+-------------------------------+
191 * +-------------------------------+---------------+---------------+
192 * ! Num of values ! Type0 ! Type1 !
193 * +-------------------------------+---------------+---------------+
196 * +---------------------------------------------------------------+
199 * +---------------------------------------------------------------+
201 struct part_values_s {
203 uint16_t *num_values;
204 uint8_t *values_types;
207 typedef struct part_values_s part_values_t;
209 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
210 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
211 * +-------------------------------+-------------------------------+
213 * +-------------------------------+-------------------------------+
214 * ! Hash (Bits 0 - 31) !
216 * ! Hash (Bits 224 - 255) !
217 * +---------------------------------------------------------------+
220 #define PART_SIGNATURE_SHA256_SIZE 36
221 struct part_signature_sha256_s {
223 unsigned char hash[32];
226 typedef struct part_signature_sha256_s part_signature_sha256_t;
228 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
229 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
230 * +-------------------------------+-------------------------------+
232 * +-------------------------------+-------------------------------+
233 * ! Original length ! Padding (0 - 15 bytes) !
234 * +-------------------------------+-------------------------------+
235 * ! Hash (Bits 0 - 31) !
237 * ! Hash (Bits 128 - 159) !
238 * +---------------------------------------------------------------+
241 #define PART_ENCRYPTION_AES256_SIZE 42
242 struct part_encryption_aes256_s {
244 uint16_t username_length;
246 unsigned char iv[16];
248 unsigned char hash[20];
252 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
254 struct receive_list_entry_s {
258 struct receive_list_entry_s *next;
260 typedef struct receive_list_entry_s receive_list_entry_t;
265 static int network_config_ttl;
266 /* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
267 static size_t network_config_packet_size = 1452;
268 static bool network_config_forward;
269 static bool network_config_stats;
271 static sockent_t *sending_sockets;
273 static receive_list_entry_t *receive_list_head;
274 static receive_list_entry_t *receive_list_tail;
275 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
276 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
277 static uint64_t receive_list_length;
279 static sockent_t *listen_sockets;
280 static struct pollfd *listen_sockets_pollfd;
281 static size_t listen_sockets_num;
283 /* The receive and dispatch threads will run as long as `listen_loop' is set to
285 static int listen_loop;
286 static int receive_thread_running;
287 static pthread_t receive_thread_id;
288 static int dispatch_thread_running;
289 static pthread_t dispatch_thread_id;
291 /* Buffer in which to-be-sent network packets are constructed. */
292 static char *send_buffer;
293 static char *send_buffer_ptr;
294 static int send_buffer_fill;
295 static cdtime_t send_buffer_last_update;
296 static value_list_t send_buffer_vl = VALUE_LIST_INIT;
297 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
299 /* XXX: These counters are incremented from one place only. The spot in which
300 * the values are incremented is either only reachable by one thread (the
301 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
302 * example). Only if neither is true, the stats_lock is acquired. The counters
303 * are always read without holding a lock in the hope that writing 8 bytes to
304 * memory is an atomic operation. */
305 static derive_t stats_octets_rx;
306 static derive_t stats_octets_tx;
307 static derive_t stats_packets_rx;
308 static derive_t stats_packets_tx;
309 static derive_t stats_values_dispatched;
310 static derive_t stats_values_not_dispatched;
311 static derive_t stats_values_sent;
312 static derive_t stats_values_not_sent;
313 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
318 static bool check_receive_okay(const value_list_t *vl) /* {{{ */
320 uint64_t time_sent = 0;
323 status = uc_meta_data_get_unsigned_int(vl, "network:time_sent", &time_sent);
325 /* This is a value we already sent. Don't allow it to be received again in
326 * order to avoid looping. */
327 if ((status == 0) && (time_sent >= ((uint64_t)vl->time)))
331 } /* }}} bool check_receive_okay */
333 static bool check_send_okay(const value_list_t *vl) /* {{{ */
338 if (network_config_forward)
341 if (vl->meta == NULL)
344 status = meta_data_get_boolean(vl->meta, "network:received", &received);
345 if (status == -ENOENT)
347 else if (status != 0) {
348 ERROR("network plugin: check_send_okay: meta_data_get_boolean failed "
354 /* By default, only *send* value lists that were not *received* by the
357 } /* }}} bool check_send_okay */
359 static bool check_notify_received(const notification_t *n) /* {{{ */
361 for (notification_meta_t *ptr = n->meta; ptr != NULL; ptr = ptr->next)
362 if ((strcmp("network:received", ptr->name) == 0) &&
363 (ptr->type == NM_TYPE_BOOLEAN))
364 return (bool)ptr->nm_value.nm_boolean;
367 } /* }}} bool check_notify_received */
369 static bool check_send_notify_okay(const notification_t *n) /* {{{ */
371 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
377 received = check_notify_received(n);
379 if (network_config_forward && received) {
381 LOG_ERR, &complain_forwarding,
382 "network plugin: A notification has been received via the network "
383 "and forwarding is enabled. Forwarding of notifications is currently "
384 "not supported, because there is not loop-deteciton available. "
385 "Please contact the collectd mailing list if you need this "
389 /* By default, only *send* value lists that were not *received* by the
392 } /* }}} bool check_send_notify_okay */
394 static int network_dispatch_values(value_list_t *vl, /* {{{ */
395 const char *username) {
398 if ((vl->time == 0) || (strlen(vl->host) == 0) || (strlen(vl->plugin) == 0) ||
399 (strlen(vl->type) == 0))
402 if (!check_receive_okay(vl)) {
404 char name[6 * DATA_MAX_NAME_LEN];
405 FORMAT_VL(name, sizeof(name), vl);
406 name[sizeof(name) - 1] = 0;
407 DEBUG("network plugin: network_dispatch_values: "
408 "NOT dispatching %s.",
411 stats_values_not_dispatched++;
415 assert(vl->meta == NULL);
417 vl->meta = meta_data_create();
418 if (vl->meta == NULL) {
419 ERROR("network plugin: meta_data_create failed.");
423 status = meta_data_add_boolean(vl->meta, "network:received", 1);
425 ERROR("network plugin: meta_data_add_boolean failed.");
426 meta_data_destroy(vl->meta);
431 if (username != NULL) {
432 status = meta_data_add_string(vl->meta, "network:username", username);
434 ERROR("network plugin: meta_data_add_string failed.");
435 meta_data_destroy(vl->meta);
441 plugin_dispatch_values(vl);
442 stats_values_dispatched++;
444 meta_data_destroy(vl->meta);
448 } /* }}} int network_dispatch_values */
450 static int network_dispatch_notification(notification_t *n) /* {{{ */
454 assert(n->meta == NULL);
456 status = plugin_notification_meta_add_boolean(n, "network:received", 1);
458 ERROR("network plugin: plugin_notification_meta_add_boolean failed.");
459 plugin_notification_meta_free(n->meta);
464 status = plugin_dispatch_notification(n);
466 plugin_notification_meta_free(n->meta);
470 } /* }}} int network_dispatch_notification */
473 static int network_init_gcrypt(void) /* {{{ */
477 /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
478 * Because you can't know in a library whether another library has
479 * already initialized the library */
480 if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P))
483 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
484 * To ensure thread-safety, it's important to set GCRYCTL_SET_THREAD_CBS
485 * *before* initalizing Libgcrypt with gcry_check_version(), which itself must
486 * be called before any other gcry_* function. GCRYCTL_ANY_INITIALIZATION_P
487 * above doesn't count, as it doesn't implicitly initalize Libgcrypt.
489 * tl;dr: keep all these gry_* statements in this exact order please. */
490 #if GCRYPT_VERSION_NUMBER < 0x010600
491 err = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
493 ERROR("network plugin: gcry_control (GCRYCTL_SET_THREAD_CBS) failed: %s",
499 gcry_check_version(NULL);
501 err = gcry_control(GCRYCTL_INIT_SECMEM, 32768);
503 ERROR("network plugin: gcry_control (GCRYCTL_INIT_SECMEM) failed: %s",
508 gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
510 } /* }}} int network_init_gcrypt */
512 static gcry_cipher_hd_t network_get_aes256_cypher(sockent_t *se, /* {{{ */
515 const char *username) {
517 gcry_cipher_hd_t *cyper_ptr;
518 unsigned char password_hash[32];
520 if (se->type == SOCKENT_TYPE_CLIENT) {
521 cyper_ptr = &se->data.client.cypher;
522 memcpy(password_hash, se->data.client.password_hash, sizeof(password_hash));
526 cyper_ptr = &se->data.server.cypher;
528 if (username == NULL)
531 secret = fbh_get(se->data.server.userdb, username);
535 gcry_md_hash_buffer(GCRY_MD_SHA256, password_hash, secret, strlen(secret));
540 if (*cyper_ptr == NULL) {
541 err = gcry_cipher_open(cyper_ptr, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB,
544 ERROR("network plugin: gcry_cipher_open returned: %s",
550 gcry_cipher_reset(*cyper_ptr);
552 assert(*cyper_ptr != NULL);
554 err = gcry_cipher_setkey(*cyper_ptr, password_hash, sizeof(password_hash));
556 ERROR("network plugin: gcry_cipher_setkey returned: %s",
558 gcry_cipher_close(*cyper_ptr);
563 err = gcry_cipher_setiv(*cyper_ptr, iv, iv_size);
565 ERROR("network plugin: gcry_cipher_setkey returned: %s",
567 gcry_cipher_close(*cyper_ptr);
573 } /* }}} int network_get_aes256_cypher */
574 #endif /* HAVE_GCRYPT_H */
576 static int write_part_values(char **ret_buffer, size_t *ret_buffer_len,
577 const data_set_t *ds, const value_list_t *vl) {
582 part_header_t pkg_ph;
583 uint16_t pkg_num_values;
584 uint8_t *pkg_values_types;
589 num_values = vl->values_len;
590 packet_len = sizeof(part_header_t) + sizeof(uint16_t) +
591 (num_values * sizeof(uint8_t)) + (num_values * sizeof(value_t));
593 if (*ret_buffer_len < packet_len)
596 pkg_values_types = malloc(num_values * sizeof(*pkg_values_types));
597 if (pkg_values_types == NULL) {
598 ERROR("network plugin: write_part_values: malloc failed.");
602 pkg_values = malloc(num_values * sizeof(*pkg_values));
603 if (pkg_values == NULL) {
604 free(pkg_values_types);
605 ERROR("network plugin: write_part_values: malloc failed.");
609 pkg_ph.type = htons(TYPE_VALUES);
610 pkg_ph.length = htons(packet_len);
612 pkg_num_values = htons((uint16_t)vl->values_len);
614 for (int i = 0; i < num_values; i++) {
615 pkg_values_types[i] = (uint8_t)ds->ds[i].type;
616 switch (ds->ds[i].type) {
617 case DS_TYPE_COUNTER:
618 pkg_values[i].counter = htonll(vl->values[i].counter);
622 pkg_values[i].gauge = htond(vl->values[i].gauge);
626 pkg_values[i].derive = htonll(vl->values[i].derive);
629 case DS_TYPE_ABSOLUTE:
630 pkg_values[i].absolute = htonll(vl->values[i].absolute);
634 free(pkg_values_types);
636 ERROR("network plugin: write_part_values: "
637 "Unknown data source type: %i",
640 } /* switch (ds->ds[i].type) */
641 } /* for (num_values) */
644 * Use `memcpy' to write everything to the buffer, because the pointer
645 * may be unaligned and some architectures, such as SPARC, can't handle
648 packet_ptr = *ret_buffer;
650 memcpy(packet_ptr + offset, &pkg_ph, sizeof(pkg_ph));
651 offset += sizeof(pkg_ph);
652 memcpy(packet_ptr + offset, &pkg_num_values, sizeof(pkg_num_values));
653 offset += sizeof(pkg_num_values);
654 memcpy(packet_ptr + offset, pkg_values_types, num_values * sizeof(uint8_t));
655 offset += num_values * sizeof(uint8_t);
656 memcpy(packet_ptr + offset, pkg_values, num_values * sizeof(value_t));
657 offset += num_values * sizeof(value_t);
659 assert(offset == packet_len);
661 *ret_buffer = packet_ptr + packet_len;
662 *ret_buffer_len -= packet_len;
664 free(pkg_values_types);
668 } /* int write_part_values */
670 static int write_part_number(char **ret_buffer, size_t *ret_buffer_len,
671 int type, uint64_t value) {
675 part_header_t pkg_head;
680 packet_len = sizeof(pkg_head) + sizeof(pkg_value);
682 if (*ret_buffer_len < packet_len)
685 pkg_head.type = htons(type);
686 pkg_head.length = htons(packet_len);
687 pkg_value = htonll(value);
689 packet_ptr = *ret_buffer;
691 memcpy(packet_ptr + offset, &pkg_head, sizeof(pkg_head));
692 offset += sizeof(pkg_head);
693 memcpy(packet_ptr + offset, &pkg_value, sizeof(pkg_value));
694 offset += sizeof(pkg_value);
696 assert(offset == packet_len);
698 *ret_buffer = packet_ptr + packet_len;
699 *ret_buffer_len -= packet_len;
702 } /* int write_part_number */
704 static int write_part_string(char **ret_buffer, size_t *ret_buffer_len,
705 int type, const char *str, size_t str_len) {
714 buffer_len = 2 * sizeof(uint16_t) + str_len + 1;
715 if (*ret_buffer_len < buffer_len)
718 pkg_type = htons(type);
719 pkg_length = htons(buffer_len);
721 buffer = *ret_buffer;
723 memcpy(buffer + offset, (void *)&pkg_type, sizeof(pkg_type));
724 offset += sizeof(pkg_type);
725 memcpy(buffer + offset, (void *)&pkg_length, sizeof(pkg_length));
726 offset += sizeof(pkg_length);
727 memcpy(buffer + offset, str, str_len);
729 memset(buffer + offset, '\0', 1);
732 assert(offset == buffer_len);
734 *ret_buffer = buffer + buffer_len;
735 *ret_buffer_len -= buffer_len;
738 } /* int write_part_string */
740 static int parse_part_values(void **ret_buffer, size_t *ret_buffer_len,
741 value_t **ret_values, size_t *ret_num_values) {
742 char *buffer = *ret_buffer;
743 size_t buffer_len = *ret_buffer_len;
755 if (buffer_len < 15) {
756 NOTICE("network plugin: packet is too short: "
757 "buffer_len = %" PRIsz,
762 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
763 buffer += sizeof(tmp16);
764 pkg_type = ntohs(tmp16);
766 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
767 buffer += sizeof(tmp16);
768 pkg_length = ntohs(tmp16);
770 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
771 buffer += sizeof(tmp16);
772 pkg_numval = (size_t)ntohs(tmp16);
774 assert(pkg_type == TYPE_VALUES);
777 3 * sizeof(uint16_t) + pkg_numval * (sizeof(uint8_t) + sizeof(value_t));
778 if (buffer_len < exp_size) {
779 WARNING("network plugin: parse_part_values: "
781 "Chunk of size %" PRIsz " expected, "
782 "but buffer has only %" PRIsz " bytes left.",
783 exp_size, buffer_len);
786 assert(pkg_numval <= ((buffer_len - 6) / 9));
788 if (pkg_length != exp_size) {
789 WARNING("network plugin: parse_part_values: "
790 "Length and number of values "
791 "in the packet don't match.");
795 pkg_types = calloc(pkg_numval, sizeof(*pkg_types));
796 pkg_values = calloc(pkg_numval, sizeof(*pkg_values));
797 if ((pkg_types == NULL) || (pkg_values == NULL)) {
800 ERROR("network plugin: parse_part_values: calloc failed.");
804 memcpy(pkg_types, buffer, pkg_numval * sizeof(*pkg_types));
805 buffer += pkg_numval * sizeof(*pkg_types);
806 memcpy(pkg_values, buffer, pkg_numval * sizeof(*pkg_values));
807 buffer += pkg_numval * sizeof(*pkg_values);
809 for (size_t i = 0; i < pkg_numval; i++) {
810 switch (pkg_types[i]) {
811 case DS_TYPE_COUNTER:
812 pkg_values[i].counter = (counter_t)ntohll(pkg_values[i].counter);
816 pkg_values[i].gauge = (gauge_t)ntohd(pkg_values[i].gauge);
820 pkg_values[i].derive = (derive_t)ntohll(pkg_values[i].derive);
823 case DS_TYPE_ABSOLUTE:
824 pkg_values[i].absolute = (absolute_t)ntohll(pkg_values[i].absolute);
828 NOTICE("network plugin: parse_part_values: "
829 "Don't know how to handle data source type %" PRIu8,
834 } /* switch (pkg_types[i]) */
837 *ret_buffer = buffer;
838 *ret_buffer_len = buffer_len - pkg_length;
839 *ret_num_values = pkg_numval;
840 *ret_values = pkg_values;
845 } /* int parse_part_values */
847 static int parse_part_number(void **ret_buffer, size_t *ret_buffer_len,
849 char *buffer = *ret_buffer;
850 size_t buffer_len = *ret_buffer_len;
854 size_t exp_size = 2 * sizeof(uint16_t) + sizeof(uint64_t);
858 if (buffer_len < exp_size) {
859 WARNING("network plugin: parse_part_number: "
861 "Chunk of size %" PRIsz " expected, "
862 "but buffer has only %" PRIsz " bytes left.",
863 exp_size, buffer_len);
867 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
868 buffer += sizeof(tmp16);
869 /* pkg_type = ntohs (tmp16); */
871 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
872 buffer += sizeof(tmp16);
873 pkg_length = ntohs(tmp16);
875 memcpy((void *)&tmp64, buffer, sizeof(tmp64));
876 buffer += sizeof(tmp64);
877 *value = ntohll(tmp64);
879 *ret_buffer = buffer;
880 *ret_buffer_len = buffer_len - pkg_length;
883 } /* int parse_part_number */
885 static int parse_part_string(void **ret_buffer, size_t *ret_buffer_len,
886 char *output, size_t const output_len) {
887 char *buffer = *ret_buffer;
888 size_t buffer_len = *ret_buffer_len;
891 size_t const header_size = 2 * sizeof(uint16_t);
899 if (buffer_len < header_size) {
900 WARNING("network plugin: parse_part_string: "
902 "Chunk of at least size %" PRIsz " expected, "
903 "but buffer has only %" PRIsz " bytes left.",
904 header_size, buffer_len);
908 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
909 buffer += sizeof(tmp16);
910 /* pkg_type = ntohs (tmp16); */
912 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
913 buffer += sizeof(tmp16);
914 pkg_length = ntohs(tmp16);
915 payload_size = ((size_t)pkg_length) - header_size;
917 /* Check that packet fits in the input buffer */
918 if (pkg_length > buffer_len) {
919 WARNING("network plugin: parse_part_string: "
921 "Chunk of size %" PRIu16 " received, "
922 "but buffer has only %" PRIsz " bytes left.",
923 pkg_length, buffer_len);
927 /* Check that pkg_length is in the valid range */
928 if (pkg_length <= header_size) {
929 WARNING("network plugin: parse_part_string: "
931 "Header claims this packet is only %hu "
937 /* Check that the package data fits into the output buffer.
938 * The previous if-statement ensures that:
939 * `pkg_length > header_size' */
940 if (output_len < payload_size) {
941 WARNING("network plugin: parse_part_string: "
943 "Output buffer holds %" PRIsz " bytes, "
944 "which is too small to hold the received "
945 "%" PRIsz " byte string.",
946 output_len, payload_size);
950 /* All sanity checks successfull, let's copy the data over */
951 memcpy((void *)output, (void *)buffer, payload_size);
952 buffer += payload_size;
954 /* For some very weird reason '\0' doesn't do the trick on SPARC in
956 if (output[payload_size - 1] != 0) {
957 WARNING("network plugin: parse_part_string: "
958 "Received string does not end "
959 "with a NULL-byte.");
963 *ret_buffer = buffer;
964 *ret_buffer_len = buffer_len - pkg_length;
967 } /* int parse_part_string */
969 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
970 * parse_packet and vice versa. */
971 #define PP_SIGNED 0x01
972 #define PP_ENCRYPTED 0x02
973 static int parse_packet(sockent_t *se, void *buffer, size_t buffer_size,
974 int flags, const char *username);
976 #define BUFFER_READ(p, s) \
978 memcpy((p), buffer + buffer_offset, (s)); \
979 buffer_offset += (s); \
983 static int parse_part_sign_sha256(sockent_t *se, /* {{{ */
984 void **ret_buffer, size_t *ret_buffer_len,
986 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
990 size_t buffer_offset;
995 part_signature_sha256_t pss;
996 uint16_t pss_head_length;
997 char hash[sizeof(pss.hash)];
1001 unsigned char *hash_ptr;
1003 buffer = *ret_buffer;
1004 buffer_len = *ret_buffer_len;
1007 /* Check if the buffer has enough data for this structure. */
1008 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1011 /* Read type and length header */
1012 BUFFER_READ(&pss.head.type, sizeof(pss.head.type));
1013 BUFFER_READ(&pss.head.length, sizeof(pss.head.length));
1014 pss_head_length = ntohs(pss.head.length);
1016 /* Check if the `pss_head_length' is within bounds. */
1017 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE) ||
1018 (pss_head_length > buffer_len)) {
1019 ERROR("network plugin: HMAC-SHA-256 with invalid length received.");
1023 if (se->data.server.userdb == NULL) {
1025 LOG_NOTICE, &complain_no_users,
1026 "network plugin: Received signed network packet but can't verify it "
1027 "because no user DB has been configured. Will accept it.");
1029 *ret_buffer = buffer + pss_head_length;
1030 *ret_buffer_len -= pss_head_length;
1035 /* Copy the hash. */
1036 BUFFER_READ(pss.hash, sizeof(pss.hash));
1038 /* Calculate username length (without null byte) and allocate memory */
1039 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1040 pss.username = malloc(username_len + 1);
1041 if (pss.username == NULL)
1044 /* Read the username */
1045 BUFFER_READ(pss.username, username_len);
1046 pss.username[username_len] = 0;
1048 assert(buffer_offset == pss_head_length);
1050 /* Query the password */
1051 secret = fbh_get(se->data.server.userdb, pss.username);
1052 if (secret == NULL) {
1053 ERROR("network plugin: Unknown user: %s", pss.username);
1054 sfree(pss.username);
1058 /* Create a hash device and check the HMAC */
1060 err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1062 ERROR("network plugin: Creating HMAC-SHA-256 object failed: %s",
1063 gcry_strerror(err));
1065 sfree(pss.username);
1069 err = gcry_md_setkey(hd, secret, strlen(secret));
1071 ERROR("network plugin: gcry_md_setkey failed: %s", gcry_strerror(err));
1074 sfree(pss.username);
1078 gcry_md_write(hd, buffer + PART_SIGNATURE_SHA256_SIZE,
1079 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1080 hash_ptr = gcry_md_read(hd, GCRY_MD_SHA256);
1081 if (hash_ptr == NULL) {
1082 ERROR("network plugin: gcry_md_read failed.");
1085 sfree(pss.username);
1088 memcpy(hash, hash_ptr, sizeof(hash));
1094 if (memcmp(pss.hash, hash, sizeof(pss.hash)) != 0) {
1095 WARNING("network plugin: Verifying HMAC-SHA-256 signature failed: "
1096 "Hash mismatch. Username: %s",
1099 parse_packet(se, buffer + buffer_offset, buffer_len - buffer_offset,
1100 flags | PP_SIGNED, pss.username);
1104 sfree(pss.username);
1106 *ret_buffer = buffer + buffer_len;
1107 *ret_buffer_len = 0;
1110 } /* }}} int parse_part_sign_sha256 */
1111 /* #endif HAVE_GCRYPT_H */
1113 #else /* if !HAVE_GCRYPT_H */
1114 static int parse_part_sign_sha256(sockent_t *se, /* {{{ */
1115 void **ret_buffer, size_t *ret_buffer_size,
1117 static int warning_has_been_printed;
1121 size_t buffer_offset;
1124 part_signature_sha256_t pss;
1126 buffer = *ret_buffer;
1127 buffer_size = *ret_buffer_size;
1130 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1133 BUFFER_READ(&pss.head.type, sizeof(pss.head.type));
1134 BUFFER_READ(&pss.head.length, sizeof(pss.head.length));
1135 part_len = ntohs(pss.head.length);
1137 if ((part_len <= PART_SIGNATURE_SHA256_SIZE) || (part_len > buffer_size))
1140 if (warning_has_been_printed == 0) {
1141 WARNING("network plugin: Received signed packet, but the network "
1142 "plugin was not linked with libgcrypt, so I cannot "
1143 "verify the signature. The packet will be accepted.");
1144 warning_has_been_printed = 1;
1147 parse_packet(se, buffer + part_len, buffer_size - part_len, flags,
1148 /* username = */ NULL);
1150 *ret_buffer = buffer + buffer_size;
1151 *ret_buffer_size = 0;
1154 } /* }}} int parse_part_sign_sha256 */
1155 #endif /* !HAVE_GCRYPT_H */
1158 static int parse_part_encr_aes256(sockent_t *se, /* {{{ */
1159 void **ret_buffer, size_t *ret_buffer_len,
1161 char *buffer = *ret_buffer;
1162 size_t buffer_len = *ret_buffer_len;
1165 size_t buffer_offset;
1166 uint16_t username_len;
1167 part_encryption_aes256_t pea;
1168 unsigned char hash[sizeof(pea.hash)] = {0};
1170 gcry_cipher_hd_t cypher;
1173 /* Make sure at least the header if available. */
1174 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE) {
1175 NOTICE("network plugin: parse_part_encr_aes256: "
1176 "Discarding short packet.");
1182 /* Copy the unencrypted information into `pea'. */
1183 BUFFER_READ(&pea.head.type, sizeof(pea.head.type));
1184 BUFFER_READ(&pea.head.length, sizeof(pea.head.length));
1186 /* Check the `part size'. */
1187 part_size = ntohs(pea.head.length);
1188 if ((part_size <= PART_ENCRYPTION_AES256_SIZE) || (part_size > buffer_len)) {
1189 NOTICE("network plugin: parse_part_encr_aes256: "
1190 "Discarding part with invalid size.");
1194 /* Read the username */
1195 BUFFER_READ(&username_len, sizeof(username_len));
1196 username_len = ntohs(username_len);
1198 if ((username_len == 0) ||
1199 (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1)))) {
1200 NOTICE("network plugin: parse_part_encr_aes256: "
1201 "Discarding part with invalid username length.");
1205 assert(username_len > 0);
1206 pea.username = malloc(username_len + 1);
1207 if (pea.username == NULL)
1209 BUFFER_READ(pea.username, username_len);
1210 pea.username[username_len] = 0;
1212 /* Last but not least, the initialization vector */
1213 BUFFER_READ(pea.iv, sizeof(pea.iv));
1215 /* Make sure we are at the right position */
1216 assert(buffer_offset ==
1217 (username_len + PART_ENCRYPTION_AES256_SIZE - sizeof(pea.hash)));
1219 cypher = network_get_aes256_cypher(se, pea.iv, sizeof(pea.iv), pea.username);
1220 if (cypher == NULL) {
1221 ERROR("network plugin: Failed to get cypher. Username: %s", pea.username);
1222 sfree(pea.username);
1226 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1227 assert(payload_len > 0);
1229 /* Decrypt the packet in-place */
1230 err = gcry_cipher_decrypt(cypher, buffer + buffer_offset,
1231 part_size - buffer_offset,
1232 /* in = */ NULL, /* in len = */ 0);
1234 ERROR("network plugin: gcry_cipher_decrypt returned: %s. Username: %s",
1235 gcry_strerror(err), pea.username);
1236 sfree(pea.username);
1241 BUFFER_READ(pea.hash, sizeof(pea.hash));
1243 /* Make sure we're at the right position - again */
1244 assert(buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1245 assert(buffer_offset == (part_size - payload_len));
1247 /* Check hash sum */
1248 gcry_md_hash_buffer(GCRY_MD_SHA1, hash, buffer + buffer_offset, payload_len);
1249 if (memcmp(hash, pea.hash, sizeof(hash)) != 0) {
1250 ERROR("network plugin: Checksum mismatch. Username: %s", pea.username);
1251 sfree(pea.username);
1255 parse_packet(se, buffer + buffer_offset, payload_len, flags | PP_ENCRYPTED,
1258 /* Update return values */
1259 *ret_buffer = buffer + part_size;
1260 *ret_buffer_len = buffer_len - part_size;
1262 sfree(pea.username);
1265 } /* }}} int parse_part_encr_aes256 */
1266 /* #endif HAVE_GCRYPT_H */
1268 #else /* if !HAVE_GCRYPT_H */
1269 static int parse_part_encr_aes256(sockent_t *se, /* {{{ */
1270 void **ret_buffer, size_t *ret_buffer_size,
1272 static int warning_has_been_printed;
1276 size_t buffer_offset;
1281 buffer = *ret_buffer;
1282 buffer_size = *ret_buffer_size;
1285 /* parse_packet assures this minimum size. */
1286 assert(buffer_size >= (sizeof(ph.type) + sizeof(ph.length)));
1288 BUFFER_READ(&ph.type, sizeof(ph.type));
1289 BUFFER_READ(&ph.length, sizeof(ph.length));
1290 ph_length = ntohs(ph.length);
1292 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE) || (ph_length > buffer_size)) {
1293 ERROR("network plugin: AES-256 encrypted part "
1294 "with invalid length received.");
1298 if (warning_has_been_printed == 0) {
1299 WARNING("network plugin: Received encrypted packet, but the network "
1300 "plugin was not linked with libgcrypt, so I cannot "
1301 "decrypt it. The part will be discarded.");
1302 warning_has_been_printed = 1;
1305 *ret_buffer = (void *)(((char *)*ret_buffer) + ph_length);
1306 *ret_buffer_size -= ph_length;
1309 } /* }}} int parse_part_encr_aes256 */
1310 #endif /* !HAVE_GCRYPT_H */
1314 static int parse_packet(sockent_t *se, /* {{{ */
1315 void *buffer, size_t buffer_size, int flags,
1316 const char *username) {
1319 value_list_t vl = VALUE_LIST_INIT;
1320 notification_t n = {0};
1323 int packet_was_signed = (flags & PP_SIGNED);
1324 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1325 int printed_ignore_warning = 0;
1326 #endif /* HAVE_GCRYPT_H */
1328 memset(&vl, '\0', sizeof(vl));
1331 while ((status == 0) && (0 < buffer_size) &&
1332 ((unsigned int)buffer_size > sizeof(part_header_t))) {
1333 uint16_t pkg_length;
1336 memcpy((void *)&pkg_type, (void *)buffer, sizeof(pkg_type));
1337 memcpy((void *)&pkg_length, (void *)(((char *)buffer) + sizeof(pkg_type)),
1338 sizeof(pkg_length));
1340 pkg_length = ntohs(pkg_length);
1341 pkg_type = ntohs(pkg_type);
1343 if (pkg_length > buffer_size)
1345 /* Ensure that this loop terminates eventually */
1346 if (pkg_length < (2 * sizeof(uint16_t)))
1349 if (pkg_type == TYPE_ENCR_AES256) {
1350 status = parse_part_encr_aes256(se, &buffer, &buffer_size, flags);
1352 ERROR("network plugin: Decrypting AES256 "
1360 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT) &&
1361 (packet_was_encrypted == 0)) {
1362 if (printed_ignore_warning == 0) {
1363 INFO("network plugin: Unencrypted packet or "
1364 "part has been ignored.");
1365 printed_ignore_warning = 1;
1367 buffer = ((char *)buffer) + pkg_length;
1368 buffer_size -= (size_t)pkg_length;
1371 #endif /* HAVE_GCRYPT_H */
1372 else if (pkg_type == TYPE_SIGN_SHA256) {
1373 status = parse_part_sign_sha256(se, &buffer, &buffer_size, flags);
1375 ERROR("network plugin: Verifying HMAC-SHA-256 "
1383 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN) &&
1384 (packet_was_encrypted == 0) && (packet_was_signed == 0)) {
1385 if (printed_ignore_warning == 0) {
1386 INFO("network plugin: Unsigned packet or "
1387 "part has been ignored.");
1388 printed_ignore_warning = 1;
1390 buffer = ((char *)buffer) + pkg_length;
1391 buffer_size -= (size_t)pkg_length;
1394 #endif /* HAVE_GCRYPT_H */
1395 else if (pkg_type == TYPE_VALUES) {
1397 parse_part_values(&buffer, &buffer_size, &vl.values, &vl.values_len);
1401 network_dispatch_values(&vl, username);
1404 } else if (pkg_type == TYPE_TIME) {
1406 status = parse_part_number(&buffer, &buffer_size, &tmp);
1408 vl.time = TIME_T_TO_CDTIME_T(tmp);
1409 n.time = TIME_T_TO_CDTIME_T(tmp);
1411 } else if (pkg_type == TYPE_TIME_HR) {
1413 status = parse_part_number(&buffer, &buffer_size, &tmp);
1415 vl.time = (cdtime_t)tmp;
1416 n.time = (cdtime_t)tmp;
1418 } else if (pkg_type == TYPE_INTERVAL) {
1420 status = parse_part_number(&buffer, &buffer_size, &tmp);
1422 vl.interval = TIME_T_TO_CDTIME_T(tmp);
1423 } else if (pkg_type == TYPE_INTERVAL_HR) {
1425 status = parse_part_number(&buffer, &buffer_size, &tmp);
1427 vl.interval = (cdtime_t)tmp;
1428 } else if (pkg_type == TYPE_HOST) {
1430 parse_part_string(&buffer, &buffer_size, vl.host, sizeof(vl.host));
1432 sstrncpy(n.host, vl.host, sizeof(n.host));
1433 } else if (pkg_type == TYPE_PLUGIN) {
1434 status = parse_part_string(&buffer, &buffer_size, vl.plugin,
1437 sstrncpy(n.plugin, vl.plugin, sizeof(n.plugin));
1438 } else if (pkg_type == TYPE_PLUGIN_INSTANCE) {
1439 status = parse_part_string(&buffer, &buffer_size, vl.plugin_instance,
1440 sizeof(vl.plugin_instance));
1442 sstrncpy(n.plugin_instance, vl.plugin_instance,
1443 sizeof(n.plugin_instance));
1444 } else if (pkg_type == TYPE_TYPE) {
1446 parse_part_string(&buffer, &buffer_size, vl.type, sizeof(vl.type));
1448 sstrncpy(n.type, vl.type, sizeof(n.type));
1449 } else if (pkg_type == TYPE_TYPE_INSTANCE) {
1450 status = parse_part_string(&buffer, &buffer_size, vl.type_instance,
1451 sizeof(vl.type_instance));
1453 sstrncpy(n.type_instance, vl.type_instance, sizeof(n.type_instance));
1454 } else if (pkg_type == TYPE_MESSAGE) {
1455 status = parse_part_string(&buffer, &buffer_size, n.message,
1460 } else if ((n.severity != NOTIF_FAILURE) &&
1461 (n.severity != NOTIF_WARNING) && (n.severity != NOTIF_OKAY)) {
1462 INFO("network plugin: "
1463 "Ignoring notification with "
1464 "unknown severity %i.",
1466 } else if (n.time == 0) {
1467 INFO("network plugin: "
1468 "Ignoring notification with "
1470 } else if (strlen(n.message) == 0) {
1471 INFO("network plugin: "
1472 "Ignoring notification with "
1473 "an empty message.");
1475 network_dispatch_notification(&n);
1477 } else if (pkg_type == TYPE_SEVERITY) {
1479 status = parse_part_number(&buffer, &buffer_size, &tmp);
1481 n.severity = (int)tmp;
1483 DEBUG("network plugin: parse_packet: Unknown part"
1486 buffer = ((char *)buffer) + pkg_length;
1487 buffer_size -= (size_t)pkg_length;
1489 } /* while (buffer_size > sizeof (part_header_t)) */
1491 if (status == 0 && buffer_size > 0)
1492 WARNING("network plugin: parse_packet: Received truncated "
1493 "packet, try increasing `MaxPacketSize'");
1496 } /* }}} int parse_packet */
1498 static void free_sockent_client(struct sockent_client *sec) /* {{{ */
1505 sfree(sec->bind_addr);
1507 sfree(sec->username);
1508 sfree(sec->password);
1509 if (sec->cypher != NULL)
1510 gcry_cipher_close(sec->cypher);
1512 } /* }}} void free_sockent_client */
1514 static void free_sockent_server(struct sockent_server *ses) /* {{{ */
1516 for (size_t i = 0; i < ses->fd_num; i++) {
1517 if (ses->fd[i] >= 0) {
1525 sfree(ses->auth_file);
1526 fbh_destroy(ses->userdb);
1527 if (ses->cypher != NULL)
1528 gcry_cipher_close(ses->cypher);
1530 } /* }}} void free_sockent_server */
1532 static void sockent_destroy(sockent_t *se) /* {{{ */
1536 DEBUG("network plugin: sockent_destroy (se = %p);", (void *)se);
1538 while (se != NULL) {
1544 if (se->type == SOCKENT_TYPE_CLIENT)
1545 free_sockent_client(&se->data.client);
1547 free_sockent_server(&se->data.server);
1552 } /* }}} void sockent_destroy */
1555 * int network_set_ttl
1557 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1558 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1560 * The `struct addrinfo' is used to destinguish between unicast and multicast
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);
1567 assert(se->type == SOCKENT_TYPE_CLIENT);
1569 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1572 if (ai->ai_family == AF_INET) {
1573 struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1576 if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr)))
1577 optname = IP_MULTICAST_TTL;
1581 if (setsockopt(se->data.client.fd, IPPROTO_IP, optname, &network_config_ttl,
1582 sizeof(network_config_ttl)) != 0) {
1583 ERROR("network plugin: setsockopt (ipv4-ttl): %s", STRERRNO);
1586 } else if (ai->ai_family == AF_INET6) {
1588 * http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1589 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1592 if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr))
1593 optname = IPV6_MULTICAST_HOPS;
1595 optname = IPV6_UNICAST_HOPS;
1597 if (setsockopt(se->data.client.fd, IPPROTO_IPV6, optname,
1598 &network_config_ttl, sizeof(network_config_ttl)) != 0) {
1599 ERROR("network plugin: setsockopt(ipv6-ttl): %s", STRERRNO);
1605 } /* int network_set_ttl */
1607 static int network_set_interface(const sockent_t *se,
1608 const struct addrinfo *ai) /* {{{ */
1610 DEBUG("network plugin: network_set_interface: interface index = %i;",
1613 assert(se->type == SOCKENT_TYPE_CLIENT);
1615 if (ai->ai_family == AF_INET) {
1616 struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1618 if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr))) {
1619 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1620 /* If possible, use the "ip_mreqn" structure which has
1621 * an "interface index" member. Using the interface
1622 * index is preferred here, because of its similarity
1623 * to the way IPv6 handles this. Unfortunately, it
1624 * appears not to be portable. */
1625 struct ip_mreqn mreq = {.imr_multiaddr.s_addr = addr->sin_addr.s_addr,
1626 .imr_address.s_addr = ntohl(INADDR_ANY),
1627 .imr_ifindex = se->interface};
1629 struct ip_mreq mreq = {.imr_multiaddr.s_addr = addr->sin_addr.s_addr,
1630 .imr_interface.s_addr = ntohl(INADDR_ANY)};
1633 if (setsockopt(se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq,
1634 sizeof(mreq)) != 0) {
1635 ERROR("network plugin: setsockopt (ipv4-multicast-if): %s", STRERRNO);
1641 } else if (ai->ai_family == AF_INET6) {
1642 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1644 if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr)) {
1645 if (setsockopt(se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1646 &se->interface, sizeof(se->interface)) != 0) {
1647 ERROR("network plugin: setsockopt (ipv6-multicast-if): %s", STRERRNO);
1655 /* else: Not a multicast interface. */
1656 if (se->interface != 0) {
1657 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && \
1658 defined(SO_BINDTODEVICE)
1659 char interface_name[IFNAMSIZ];
1661 if (if_indextoname(se->interface, interface_name) == NULL)
1664 DEBUG("network plugin: Binding socket to interface %s", interface_name);
1666 if (setsockopt(se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1667 interface_name, sizeof(interface_name)) == -1) {
1668 ERROR("network plugin: setsockopt (bind-if): %s", STRERRNO);
1671 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1674 WARNING("network plugin: Cannot set the interface on a unicast "
1676 #if !defined(SO_BINDTODEVICE)
1677 "the \"SO_BINDTODEVICE\" socket option "
1679 "the \"if_indextoname\" function "
1681 "is not available on your system.");
1686 } /* }}} network_set_interface */
1688 static int network_bind_socket_to_addr(sockent_t *se,
1689 const struct addrinfo *ai) {
1691 if (se->data.client.bind_addr == NULL)
1694 ERROR("network plugin: failed to bind client socket (ipvX) to %s: %s", pbuffer, STRERRNO);
1697 if (ai->ai_family == AF_INET) {
1698 struct sockaddr_in *addr =
1699 (struct sockaddr_in *)(se->data.client.bind_addr);
1700 inet_ntop(AF_INET, &(addr->sin_addr), pbuffer, 64);
1701 DEBUG("network_plugin: binding client socket to ipv4 address: %s", pbuffer);
1702 if (bind(se->data.client.fd, (struct sockaddr *)addr, sizeof(*addr)) ==
1704 ERROR("network_plugin: failed to bind client socket (ipv4): %s",
1708 } else if (ai->ai_family == AF_INET6) {
1709 struct sockaddr_in6 *addr =
1710 (struct sockaddr_in6 *)(se->data.client.bind_addr);
1711 inet_ntop(AF_INET6, &(addr->sin6_addr), pbuffer, 64);
1712 DEBUG("network_plugin: binding client socket to ipv6 address: %s", pbuffer);
1713 if (bind(se->data.client.fd, (struct sockaddr *)addr, sizeof(*addr)) ==
1715 ERROR("network_plugin: failed to bind client socket (ipv6): %s",
1722 } /* int network_bind_socket_to_addr */
1724 static int network_bind_socket(int fd, const struct addrinfo *ai,
1725 const int interface_idx) {
1733 /* allow multiple sockets to use the same PORT number */
1734 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
1735 ERROR("network plugin: setsockopt (reuseaddr): %s", STRERRNO);
1739 DEBUG("fd = %i; calling `bind'", fd);
1741 if (bind(fd, ai->ai_addr, ai->ai_addrlen) == -1) {
1742 ERROR("bind: %s", STRERRNO);
1746 if (ai->ai_family == AF_INET) {
1747 struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1748 if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr))) {
1749 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1750 struct ip_mreqn mreq;
1752 struct ip_mreq mreq;
1755 DEBUG("fd = %i; IPv4 multicast address found", fd);
1757 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1758 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1759 /* Set the interface using the interface index if
1760 * possible (available). Unfortunately, the struct
1761 * ip_mreqn is not portable. */
1762 mreq.imr_address.s_addr = ntohl(INADDR_ANY);
1763 mreq.imr_ifindex = interface_idx;
1765 mreq.imr_interface.s_addr = ntohl(INADDR_ANY);
1768 if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) ==
1770 ERROR("network plugin: setsockopt (multicast-loop): %s", STRERRNO);
1774 if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) ==
1776 ERROR("network plugin: setsockopt (add-membership): %s", STRERRNO);
1782 } else if (ai->ai_family == AF_INET6) {
1784 * http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1785 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1786 if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr)) {
1787 struct ipv6_mreq mreq;
1789 DEBUG("fd = %i; IPv6 multicast address found", fd);
1791 memcpy(&mreq.ipv6mr_multiaddr, &addr->sin6_addr, sizeof(addr->sin6_addr));
1793 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1794 * ipv6mr_interface may be set to zeroes to
1795 * choose the default multicast interface or to
1796 * the index of a particular multicast-capable
1797 * interface if the host is multihomed.
1798 * Membership is associ-associated with a
1799 * single interface; programs running on
1800 * multihomed hosts may need to join the same
1801 * group on more than one interface.*/
1802 mreq.ipv6mr_interface = interface_idx;
1804 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop,
1805 sizeof(loop)) == -1) {
1806 ERROR("network plugin: setsockopt (ipv6-multicast-loop): %s", STRERRNO);
1810 if (setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq,
1811 sizeof(mreq)) == -1) {
1812 ERROR("network plugin: setsockopt (ipv6-add-membership): %s", STRERRNO);
1820 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && \
1821 defined(SO_BINDTODEVICE)
1822 /* if a specific interface was set, bind the socket to it. But to avoid
1823 * possible problems with multicast routing, only do that for non-multicast
1825 if (interface_idx != 0) {
1826 char interface_name[IFNAMSIZ];
1828 if (if_indextoname(interface_idx, interface_name) == NULL)
1831 DEBUG("fd = %i; Binding socket to interface %s", fd, interface_name);
1833 if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, interface_name,
1834 sizeof(interface_name)) == -1) {
1835 ERROR("network plugin: setsockopt (bind-if): %s", STRERRNO);
1839 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1842 } /* int network_bind_socket */
1844 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1845 * or `SOCKENT_TYPE_SERVER' */
1846 static sockent_t *sockent_create(int type) /* {{{ */
1850 if ((type != SOCKENT_TYPE_CLIENT) && (type != SOCKENT_TYPE_SERVER))
1853 se = calloc(1, sizeof(*se));
1863 if (type == SOCKENT_TYPE_SERVER) {
1864 se->data.server.fd = NULL;
1865 se->data.server.fd_num = 0;
1867 se->data.server.security_level = SECURITY_LEVEL_NONE;
1868 se->data.server.auth_file = NULL;
1869 se->data.server.userdb = NULL;
1870 se->data.server.cypher = NULL;
1873 se->data.client.fd = -1;
1874 se->data.client.addr = NULL;
1875 se->data.client.bind_addr = NULL;
1876 se->data.client.resolve_interval = 0;
1877 se->data.client.next_resolve_reconnect = 0;
1879 se->data.client.security_level = SECURITY_LEVEL_NONE;
1880 se->data.client.username = NULL;
1881 se->data.client.password = NULL;
1882 se->data.client.cypher = NULL;
1887 } /* }}} sockent_t *sockent_create */
1889 static int sockent_init_crypto(sockent_t *se) /* {{{ */
1891 #if HAVE_GCRYPT_H /* {{{ */
1892 if (se->type == SOCKENT_TYPE_CLIENT) {
1893 if (se->data.client.security_level > SECURITY_LEVEL_NONE) {
1894 if (network_init_gcrypt() < 0) {
1895 ERROR("network plugin: Cannot configure client socket with "
1896 "security: Failed to initialize crypto library.");
1900 if ((se->data.client.username == NULL) ||
1901 (se->data.client.password == NULL)) {
1902 ERROR("network plugin: Client socket with "
1903 "security requested, but no "
1904 "credentials are configured.");
1907 gcry_md_hash_buffer(GCRY_MD_SHA256, se->data.client.password_hash,
1908 se->data.client.password,
1909 strlen(se->data.client.password));
1911 } else /* (se->type == SOCKENT_TYPE_SERVER) */
1913 if ((se->data.server.security_level > SECURITY_LEVEL_NONE) &&
1914 (se->data.server.auth_file == NULL)) {
1915 ERROR("network plugin: Server socket with security requested, "
1916 "but no \"AuthFile\" is configured.");
1919 if (se->data.server.auth_file != NULL) {
1920 if (network_init_gcrypt() < 0) {
1921 ERROR("network plugin: Cannot configure server socket with security: "
1922 "Failed to initialize crypto library.");
1926 se->data.server.userdb = fbh_create(se->data.server.auth_file);
1927 if (se->data.server.userdb == NULL) {
1928 ERROR("network plugin: Reading password file \"%s\" failed.",
1929 se->data.server.auth_file);
1934 #endif /* }}} HAVE_GCRYPT_H */
1937 } /* }}} int sockent_init_crypto */
1939 static int sockent_client_disconnect(sockent_t *se) /* {{{ */
1941 struct sockent_client *client;
1943 if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
1946 client = &se->data.client;
1947 if (client->fd >= 0) /* connected */
1953 sfree(client->addr);
1954 client->addrlen = 0;
1957 } /* }}} int sockent_client_disconnect */
1959 static int sockent_client_connect(sockent_t *se) /* {{{ */
1961 static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
1963 struct sockent_client *client;
1964 struct addrinfo *ai_list;
1966 bool reconnect = false;
1969 if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
1972 client = &se->data.client;
1975 if (client->resolve_interval != 0 && client->next_resolve_reconnect < now) {
1976 DEBUG("network plugin: Reconnecting socket, resolve_interval = %lf, "
1977 "next_resolve_reconnect = %lf",
1978 CDTIME_T_TO_DOUBLE(client->resolve_interval),
1979 CDTIME_T_TO_DOUBLE(client->next_resolve_reconnect));
1983 if (client->fd >= 0 && !reconnect) /* already connected and not stale*/
1986 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
1987 .ai_flags = AI_ADDRCONFIG,
1988 .ai_protocol = IPPROTO_UDP,
1989 .ai_socktype = SOCK_DGRAM};
1991 status = getaddrinfo(se->node,
1992 (se->service != NULL) ? se->service : NET_DEFAULT_PORT,
1993 &ai_hints, &ai_list);
1996 LOG_ERR, &complaint, "network plugin: getaddrinfo (%s, %s) failed: %s",
1997 (se->node == NULL) ? "(null)" : se->node,
1998 (se->service == NULL) ? "(null)" : se->service, gai_strerror(status));
2001 c_release(LOG_NOTICE, &complaint,
2002 "network plugin: Successfully resolved \"%s\".", se->node);
2005 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
2006 ai_ptr = ai_ptr->ai_next) {
2007 if (client->fd >= 0) /* when we reconnect */
2008 sockent_client_disconnect(se);
2011 socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
2012 if (client->fd < 0) {
2013 ERROR("network plugin: socket(2) failed: %s", STRERRNO);
2017 client->addr = calloc(1, sizeof(*client->addr));
2018 if (client->addr == NULL) {
2019 ERROR("network plugin: calloc failed.");
2025 assert(sizeof(*client->addr) >= ai_ptr->ai_addrlen);
2026 memcpy(client->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2027 client->addrlen = ai_ptr->ai_addrlen;
2029 network_set_ttl(se, ai_ptr);
2030 network_set_interface(se, ai_ptr);
2031 network_bind_socket_to_addr(se, ai_ptr);
2033 /* We don't open more than one write-socket per
2034 * node/service pair.. */
2038 freeaddrinfo(ai_list);
2042 if (client->resolve_interval > 0)
2043 client->next_resolve_reconnect = now + client->resolve_interval;
2045 } /* }}} int sockent_client_connect */
2047 /* Open the file descriptors for a initialized sockent structure. */
2048 static int sockent_server_listen(sockent_t *se) /* {{{ */
2050 struct addrinfo *ai_list;
2054 const char *service;
2059 assert(se->data.server.fd == NULL);
2060 assert(se->data.server.fd_num == 0);
2063 service = se->service;
2065 if (service == NULL)
2066 service = NET_DEFAULT_PORT;
2068 DEBUG("network plugin: sockent_server_listen: node = %s; service = %s;", node,
2071 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
2072 .ai_flags = AI_ADDRCONFIG | AI_PASSIVE,
2073 .ai_protocol = IPPROTO_UDP,
2074 .ai_socktype = SOCK_DGRAM};
2076 status = getaddrinfo(node, service, &ai_hints, &ai_list);
2078 ERROR("network plugin: getaddrinfo (%s, %s) failed: %s",
2079 (se->node == NULL) ? "(null)" : se->node,
2080 (se->service == NULL) ? "(null)" : se->service, gai_strerror(status));
2084 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
2085 ai_ptr = ai_ptr->ai_next) {
2088 tmp = realloc(se->data.server.fd,
2089 sizeof(*tmp) * (se->data.server.fd_num + 1));
2091 ERROR("network plugin: realloc failed.");
2094 se->data.server.fd = tmp;
2095 tmp = se->data.server.fd + se->data.server.fd_num;
2097 *tmp = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
2099 ERROR("network plugin: socket(2) failed: %s", STRERRNO);
2103 status = network_bind_socket(*tmp, ai_ptr, se->interface);
2110 se->data.server.fd_num++;
2112 } /* for (ai_list) */
2114 freeaddrinfo(ai_list);
2116 if (se->data.server.fd_num == 0)
2119 } /* }}} int sockent_server_listen */
2121 /* Add a sockent to the global list of sockets */
2122 static int sockent_add(sockent_t *se) /* {{{ */
2124 sockent_t *last_ptr;
2129 if (se->type == SOCKENT_TYPE_SERVER) {
2132 tmp = realloc(listen_sockets_pollfd,
2133 sizeof(*tmp) * (listen_sockets_num + se->data.server.fd_num));
2135 ERROR("network plugin: realloc failed.");
2138 listen_sockets_pollfd = tmp;
2139 tmp = listen_sockets_pollfd + listen_sockets_num;
2141 for (size_t i = 0; i < se->data.server.fd_num; i++) {
2142 memset(tmp + i, 0, sizeof(*tmp));
2143 tmp[i].fd = se->data.server.fd[i];
2144 tmp[i].events = POLLIN | POLLPRI;
2148 listen_sockets_num += se->data.server.fd_num;
2150 if (listen_sockets == NULL) {
2151 listen_sockets = se;
2154 last_ptr = listen_sockets;
2155 } else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2157 if (sending_sockets == NULL) {
2158 sending_sockets = se;
2161 last_ptr = sending_sockets;
2164 while (last_ptr->next != NULL)
2165 last_ptr = last_ptr->next;
2166 last_ptr->next = se;
2169 } /* }}} int sockent_add */
2171 static void *dispatch_thread(void __attribute__((unused)) * arg) /* {{{ */
2174 receive_list_entry_t *ent;
2177 /* Lock and wait for more data to come in */
2178 pthread_mutex_lock(&receive_list_lock);
2179 while ((listen_loop == 0) && (receive_list_head == NULL))
2180 pthread_cond_wait(&receive_list_cond, &receive_list_lock);
2182 /* Remove the head entry and unlock */
2183 ent = receive_list_head;
2185 receive_list_head = ent->next;
2186 receive_list_length--;
2187 pthread_mutex_unlock(&receive_list_lock);
2189 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2190 * because we dispatch all missing packets before shutting down. */
2194 /* Look for the correct `sockent_t' */
2195 se = listen_sockets;
2196 while (se != NULL) {
2199 for (i = 0; i < se->data.server.fd_num; i++)
2200 if (se->data.server.fd[i] == ent->fd)
2203 if (i < se->data.server.fd_num)
2210 ERROR("network plugin: Got packet from FD %i, but can't "
2211 "find an appropriate socket entry.",
2218 parse_packet(se, ent->data, ent->data_len, /* flags = */ 0,
2219 /* username = */ NULL);
2225 } /* }}} void *dispatch_thread */
2227 static int network_receive(void) /* {{{ */
2229 char buffer[network_config_packet_size];
2234 receive_list_entry_t *private_list_head;
2235 receive_list_entry_t *private_list_tail;
2236 uint64_t private_list_length;
2238 assert(listen_sockets_num > 0);
2240 private_list_head = NULL;
2241 private_list_tail = NULL;
2242 private_list_length = 0;
2244 while (listen_loop == 0) {
2245 status = poll(listen_sockets_pollfd, listen_sockets_num, -1);
2249 ERROR("network plugin: poll(2) failed: %s", STRERRNO);
2253 for (size_t i = 0; (i < listen_sockets_num) && (status > 0); i++) {
2254 receive_list_entry_t *ent;
2256 if ((listen_sockets_pollfd[i].revents & (POLLIN | POLLPRI)) == 0)
2260 buffer_len = recv(listen_sockets_pollfd[i].fd, buffer, sizeof(buffer),
2262 if (buffer_len < 0) {
2263 status = (errno != 0) ? errno : -1;
2264 ERROR("network plugin: recv(2) failed: %s", STRERRNO);
2268 stats_octets_rx += ((uint64_t)buffer_len);
2271 /* TODO: Possible performance enhancement: Do not free
2272 * these entries in the dispatch thread but put them in
2273 * another list, so we don't have to allocate more and
2274 * more of these structures. */
2275 ent = calloc(1, sizeof(*ent));
2277 ERROR("network plugin: calloc failed.");
2282 ent->data = malloc(network_config_packet_size);
2283 if (ent->data == NULL) {
2285 ERROR("network plugin: malloc failed.");
2289 ent->fd = listen_sockets_pollfd[i].fd;
2292 memcpy(ent->data, buffer, buffer_len);
2293 ent->data_len = buffer_len;
2295 if (private_list_head == NULL)
2296 private_list_head = ent;
2298 private_list_tail->next = ent;
2299 private_list_tail = ent;
2300 private_list_length++;
2302 /* Do not block here. Blocking here has led to
2303 * insufficient performance in the past. */
2304 if (pthread_mutex_trylock(&receive_list_lock) == 0) {
2305 assert(((receive_list_head == NULL) && (receive_list_length == 0)) ||
2306 ((receive_list_head != NULL) && (receive_list_length != 0)));
2308 if (receive_list_head == NULL)
2309 receive_list_head = private_list_head;
2311 receive_list_tail->next = private_list_head;
2312 receive_list_tail = private_list_tail;
2313 receive_list_length += private_list_length;
2315 pthread_cond_signal(&receive_list_cond);
2316 pthread_mutex_unlock(&receive_list_lock);
2318 private_list_head = NULL;
2319 private_list_tail = NULL;
2320 private_list_length = 0;
2324 } /* for (listen_sockets_pollfd) */
2328 } /* while (listen_loop == 0) */
2330 /* Make sure everything is dispatched before exiting. */
2331 if (private_list_head != NULL) {
2332 pthread_mutex_lock(&receive_list_lock);
2334 if (receive_list_head == NULL)
2335 receive_list_head = private_list_head;
2337 receive_list_tail->next = private_list_head;
2338 receive_list_tail = private_list_tail;
2339 receive_list_length += private_list_length;
2341 pthread_cond_signal(&receive_list_cond);
2342 pthread_mutex_unlock(&receive_list_lock);
2346 } /* }}} int network_receive */
2348 static void *receive_thread(void __attribute__((unused)) * arg) {
2349 return network_receive() ? (void *)1 : (void *)0;
2350 } /* void *receive_thread */
2352 static void network_init_buffer(void) {
2353 memset(send_buffer, 0, network_config_packet_size);
2354 send_buffer_ptr = send_buffer;
2355 send_buffer_fill = 0;
2356 send_buffer_last_update = 0;
2358 memset(&send_buffer_vl, 0, sizeof(send_buffer_vl));
2359 } /* int network_init_buffer */
2361 static void network_send_buffer_plain(sockent_t *se, /* {{{ */
2362 const char *buffer, size_t buffer_size) {
2366 status = sockent_client_connect(se);
2370 status = sendto(se->data.client.fd, buffer, buffer_size,
2371 /* flags = */ 0, (struct sockaddr *)se->data.client.addr,
2372 se->data.client.addrlen);
2374 if ((errno == EINTR) || (errno == EAGAIN))
2377 ERROR("network plugin: sendto failed: %s. Closing sending socket.",
2379 sockent_client_disconnect(se);
2385 } /* }}} void network_send_buffer_plain */
2388 #define BUFFER_ADD(p, s) \
2390 memcpy(buffer + buffer_offset, (p), (s)); \
2391 buffer_offset += (s); \
2394 static void network_send_buffer_signed(sockent_t *se, /* {{{ */
2395 const char *in_buffer,
2396 size_t in_buffer_size) {
2397 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2398 size_t buffer_offset;
2399 size_t username_len;
2403 unsigned char *hash;
2406 err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2408 ERROR("network plugin: Creating HMAC object failed: %s",
2409 gcry_strerror(err));
2413 err = gcry_md_setkey(hd, se->data.client.password,
2414 strlen(se->data.client.password));
2416 ERROR("network plugin: gcry_md_setkey failed: %s", gcry_strerror(err));
2421 username_len = strlen(se->data.client.username);
2422 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE)) {
2423 ERROR("network plugin: Username too long: %s", se->data.client.username);
2427 memcpy(buffer + PART_SIGNATURE_SHA256_SIZE, se->data.client.username,
2429 memcpy(buffer + PART_SIGNATURE_SHA256_SIZE + username_len, in_buffer,
2432 /* Initialize the `ps' structure. */
2433 part_signature_sha256_t ps = {
2434 .head.type = htons(TYPE_SIGN_SHA256),
2435 .head.length = htons(PART_SIGNATURE_SHA256_SIZE + username_len)};
2437 /* Calculate the hash value. */
2438 gcry_md_write(hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2439 username_len + in_buffer_size);
2440 hash = gcry_md_read(hd, GCRY_MD_SHA256);
2442 ERROR("network plugin: gcry_md_read failed.");
2446 memcpy(ps.hash, hash, sizeof(ps.hash));
2448 /* Add the header */
2451 BUFFER_ADD(&ps.head.type, sizeof(ps.head.type));
2452 BUFFER_ADD(&ps.head.length, sizeof(ps.head.length));
2453 BUFFER_ADD(ps.hash, sizeof(ps.hash));
2455 assert(buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2460 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2461 network_send_buffer_plain(se, buffer, buffer_offset);
2462 } /* }}} void network_send_buffer_signed */
2464 static void network_send_buffer_encrypted(sockent_t *se, /* {{{ */
2465 const char *in_buffer,
2466 size_t in_buffer_size) {
2467 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2469 size_t buffer_offset;
2471 size_t username_len;
2473 gcry_cipher_hd_t cypher;
2475 /* Initialize the header fields */
2476 part_encryption_aes256_t pea = {.head.type = htons(TYPE_ENCR_AES256),
2477 .username = se->data.client.username};
2479 username_len = strlen(pea.username);
2480 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE) {
2481 ERROR("network plugin: Username too long: %s", pea.username);
2485 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2486 header_size = PART_ENCRYPTION_AES256_SIZE + username_len - sizeof(pea.hash);
2488 assert(buffer_size <= sizeof(buffer));
2489 DEBUG("network plugin: network_send_buffer_encrypted: "
2490 "buffer_size = %" PRIsz ";",
2493 pea.head.length = htons(
2494 (uint16_t)(PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size));
2495 pea.username_length = htons((uint16_t)username_len);
2497 /* Chose a random initialization vector. */
2498 gcry_randomize((void *)&pea.iv, sizeof(pea.iv), GCRY_STRONG_RANDOM);
2500 /* Create hash of the payload */
2501 gcry_md_hash_buffer(GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2503 /* Initialize the buffer */
2505 memset(buffer, 0, sizeof(buffer));
2507 BUFFER_ADD(&pea.head.type, sizeof(pea.head.type));
2508 BUFFER_ADD(&pea.head.length, sizeof(pea.head.length));
2509 BUFFER_ADD(&pea.username_length, sizeof(pea.username_length));
2510 BUFFER_ADD(pea.username, username_len);
2511 BUFFER_ADD(pea.iv, sizeof(pea.iv));
2512 assert(buffer_offset == header_size);
2513 BUFFER_ADD(pea.hash, sizeof(pea.hash));
2514 BUFFER_ADD(in_buffer, in_buffer_size);
2516 assert(buffer_offset == buffer_size);
2518 cypher = network_get_aes256_cypher(se, pea.iv, sizeof(pea.iv),
2519 se->data.client.password);
2523 /* Encrypt the buffer in-place */
2524 err = gcry_cipher_encrypt(cypher, buffer + header_size,
2525 buffer_size - header_size,
2526 /* in = */ NULL, /* in len = */ 0);
2528 ERROR("network plugin: gcry_cipher_encrypt returned: %s",
2529 gcry_strerror(err));
2533 /* Send it out without further modifications */
2534 network_send_buffer_plain(se, buffer, buffer_size);
2535 } /* }}} void network_send_buffer_encrypted */
2537 #endif /* HAVE_GCRYPT_H */
2539 static void network_send_buffer(char *buffer, size_t buffer_len) /* {{{ */
2541 DEBUG("network plugin: network_send_buffer: buffer_len = %" PRIsz,
2544 for (sockent_t *se = sending_sockets; se != NULL; se = se->next) {
2546 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2547 network_send_buffer_encrypted(se, buffer, buffer_len);
2548 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2549 network_send_buffer_signed(se, buffer, buffer_len);
2550 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2551 #endif /* HAVE_GCRYPT_H */
2552 network_send_buffer_plain(se, buffer, buffer_len);
2553 } /* for (sending_sockets) */
2554 } /* }}} void network_send_buffer */
2556 static int add_to_buffer(char *buffer, size_t buffer_size, /* {{{ */
2557 value_list_t *vl_def, const data_set_t *ds,
2558 const value_list_t *vl) {
2559 char *buffer_orig = buffer;
2561 if (strcmp(vl_def->host, vl->host) != 0) {
2562 if (write_part_string(&buffer, &buffer_size, TYPE_HOST, vl->host,
2563 strlen(vl->host)) != 0)
2565 sstrncpy(vl_def->host, vl->host, sizeof(vl_def->host));
2568 if (vl_def->time != vl->time) {
2569 if (write_part_number(&buffer, &buffer_size, TYPE_TIME_HR,
2570 (uint64_t)vl->time))
2572 vl_def->time = vl->time;
2575 if (vl_def->interval != vl->interval) {
2576 if (write_part_number(&buffer, &buffer_size, TYPE_INTERVAL_HR,
2577 (uint64_t)vl->interval))
2579 vl_def->interval = vl->interval;
2582 if (strcmp(vl_def->plugin, vl->plugin) != 0) {
2583 if (write_part_string(&buffer, &buffer_size, TYPE_PLUGIN, vl->plugin,
2584 strlen(vl->plugin)) != 0)
2586 sstrncpy(vl_def->plugin, vl->plugin, sizeof(vl_def->plugin));
2589 if (strcmp(vl_def->plugin_instance, vl->plugin_instance) != 0) {
2590 if (write_part_string(&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2591 vl->plugin_instance,
2592 strlen(vl->plugin_instance)) != 0)
2594 sstrncpy(vl_def->plugin_instance, vl->plugin_instance,
2595 sizeof(vl_def->plugin_instance));
2598 if (strcmp(vl_def->type, vl->type) != 0) {
2599 if (write_part_string(&buffer, &buffer_size, TYPE_TYPE, vl->type,
2600 strlen(vl->type)) != 0)
2602 sstrncpy(vl_def->type, ds->type, sizeof(vl_def->type));
2605 if (strcmp(vl_def->type_instance, vl->type_instance) != 0) {
2606 if (write_part_string(&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2607 vl->type_instance, strlen(vl->type_instance)) != 0)
2609 sstrncpy(vl_def->type_instance, vl->type_instance,
2610 sizeof(vl_def->type_instance));
2613 if (write_part_values(&buffer, &buffer_size, ds, vl) != 0)
2616 return buffer - buffer_orig;
2617 } /* }}} int add_to_buffer */
2619 static void flush_buffer(void) {
2620 DEBUG("network plugin: flush_buffer: send_buffer_fill = %i",
2623 network_send_buffer(send_buffer, (size_t)send_buffer_fill);
2625 stats_octets_tx += ((uint64_t)send_buffer_fill);
2628 network_init_buffer();
2631 static int network_write(const data_set_t *ds, const value_list_t *vl,
2632 user_data_t __attribute__((unused)) * user_data) {
2635 /* listen_loop is set to non-zero in the shutdown callback, which is
2636 * guaranteed to be called *after* all the write threads have been shut
2638 assert(listen_loop == 0);
2640 if (!check_send_okay(vl)) {
2642 char name[6 * DATA_MAX_NAME_LEN];
2643 FORMAT_VL(name, sizeof(name), vl);
2644 name[sizeof(name) - 1] = 0;
2645 DEBUG("network plugin: network_write: "
2649 /* Counter is not protected by another lock and may be reached by
2650 * multiple threads */
2651 pthread_mutex_lock(&stats_lock);
2652 stats_values_not_sent++;
2653 pthread_mutex_unlock(&stats_lock);
2657 uc_meta_data_add_unsigned_int(vl, "network:time_sent", (uint64_t)vl->time);
2659 pthread_mutex_lock(&send_buffer_lock);
2661 status = add_to_buffer(send_buffer_ptr,
2662 network_config_packet_size -
2663 (send_buffer_fill + BUFF_SIG_SIZE),
2664 &send_buffer_vl, ds, vl);
2666 /* status == bytes added to the buffer */
2667 send_buffer_fill += status;
2668 send_buffer_ptr += status;
2669 send_buffer_last_update = cdtime();
2671 stats_values_sent++;
2675 status = add_to_buffer(send_buffer_ptr,
2676 network_config_packet_size -
2677 (send_buffer_fill + BUFF_SIG_SIZE),
2678 &send_buffer_vl, ds, vl);
2681 send_buffer_fill += status;
2682 send_buffer_ptr += status;
2684 stats_values_sent++;
2689 ERROR("network plugin: Unable to append to the "
2690 "buffer for some weird reason");
2691 } else if ((network_config_packet_size - send_buffer_fill) < 15) {
2695 pthread_mutex_unlock(&send_buffer_lock);
2697 return (status < 0) ? -1 : 0;
2698 } /* int network_write */
2700 static int network_config_set_ttl(const oconfig_item_t *ci) /* {{{ */
2704 if (cf_util_get_int(ci, &tmp) != 0)
2706 else if ((tmp > 0) && (tmp <= 255))
2707 network_config_ttl = tmp;
2709 WARNING("network plugin: The `TimeToLive' must be between 1 and 255.");
2714 } /* }}} int network_config_set_ttl */
2716 static int network_config_set_interface(const oconfig_item_t *ci, /* {{{ */
2720 if (cf_util_get_string_buffer(ci, if_name, sizeof(if_name)) != 0)
2723 *interface = if_nametoindex(if_name);
2725 } /* }}} int network_config_set_interface */
2728 network_config_set_bind_address(const oconfig_item_t *ci,
2729 struct sockaddr_storage **bind_address) {
2730 if ((*bind_address) != NULL) {
2731 ERROR("network_plugin: only a single bind address is allowed");
2735 char addr_text[256];
2737 if (cf_util_get_string_buffer(ci, addr_text, sizeof(addr_text)) != 0)
2741 struct addrinfo *res = NULL;
2742 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
2743 .ai_flags = AI_NUMERICHOST,
2744 .ai_protocol = IPPROTO_UDP,
2745 .ai_socktype = SOCK_DGRAM};
2747 ret = getaddrinfo(addr_text, NULL, &ai_hints, &res);
2749 ERROR("network plugin: Bind address option has invalid address set: %s",
2754 *bind_address = malloc(sizeof(**bind_address));
2755 if (*bind_address == NULL) {
2756 ERROR("network plugin: network_config_set_bind_address: malloc failed.");
2759 (*bind_address)->ss_family = res->ai_family;
2760 if (res->ai_family == AF_INET) {
2761 struct sockaddr_in *addr = (struct sockaddr_in *)(*bind_address);
2762 inet_pton(AF_INET, addr_text, &(addr->sin_addr));
2763 } else if (res->ai_family == AF_INET6) {
2764 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)(*bind_address);
2765 inet_pton(AF_INET6, addr_text, &(addr->sin6_addr));
2767 ERROR("network plugin: %s is an unknown address format %d\n", addr_text,
2769 sfree(*bind_address);
2776 } /* int network_config_set_bind_address */
2778 static int network_config_set_buffer_size(const oconfig_item_t *ci) /* {{{ */
2782 if (cf_util_get_int(ci, &tmp) != 0)
2784 else if ((tmp >= 1024) && (tmp <= 65535))
2785 network_config_packet_size = tmp;
2788 "network plugin: The `MaxPacketSize' must be between 1024 and 65535.");
2793 } /* }}} int network_config_set_buffer_size */
2796 static int network_config_set_security_level(oconfig_item_t *ci, /* {{{ */
2799 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
2800 WARNING("network plugin: The `SecurityLevel' config option needs exactly "
2801 "one string argument.");
2805 str = ci->values[0].value.string;
2806 if (strcasecmp("Encrypt", str) == 0)
2807 *retval = SECURITY_LEVEL_ENCRYPT;
2808 else if (strcasecmp("Sign", str) == 0)
2809 *retval = SECURITY_LEVEL_SIGN;
2810 else if (strcasecmp("None", str) == 0)
2811 *retval = SECURITY_LEVEL_NONE;
2813 WARNING("network plugin: Unknown security level: %s.", str);
2818 } /* }}} int network_config_set_security_level */
2819 #endif /* HAVE_GCRYPT_H */
2821 static int network_config_add_listen(const oconfig_item_t *ci) /* {{{ */
2826 if ((ci->values_num < 1) || (ci->values_num > 2) ||
2827 (ci->values[0].type != OCONFIG_TYPE_STRING) ||
2828 ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING))) {
2829 ERROR("network plugin: The `%s' config option needs "
2830 "one or two string arguments.",
2835 se = sockent_create(SOCKENT_TYPE_SERVER);
2837 ERROR("network plugin: sockent_create failed.");
2841 se->node = strdup(ci->values[0].value.string);
2842 if (ci->values_num >= 2)
2843 se->service = strdup(ci->values[1].value.string);
2845 for (int i = 0; i < ci->children_num; i++) {
2846 oconfig_item_t *child = ci->children + i;
2849 if (strcasecmp("AuthFile", child->key) == 0)
2850 cf_util_get_string(child, &se->data.server.auth_file);
2851 else if (strcasecmp("SecurityLevel", child->key) == 0)
2852 network_config_set_security_level(child, &se->data.server.security_level);
2854 #endif /* HAVE_GCRYPT_H */
2855 if (strcasecmp("Interface", child->key) == 0)
2856 network_config_set_interface(child, &se->interface);
2858 WARNING("network plugin: Option `%s' is not allowed here.", child->key);
2863 if ((se->data.server.security_level > SECURITY_LEVEL_NONE) &&
2864 (se->data.server.auth_file == NULL)) {
2865 ERROR("network plugin: A security level higher than `none' was "
2866 "requested, but no AuthFile option was given. Cowardly refusing to "
2867 "open this socket!");
2868 sockent_destroy(se);
2871 #endif /* HAVE_GCRYPT_H */
2873 status = sockent_init_crypto(se);
2875 ERROR("network plugin: network_config_add_listen: sockent_init_crypto() "
2877 sockent_destroy(se);
2881 status = sockent_server_listen(se);
2883 ERROR("network plugin: network_config_add_listen: sockent_server_listen "
2885 sockent_destroy(se);
2889 status = sockent_add(se);
2891 ERROR("network plugin: network_config_add_listen: sockent_add failed.");
2892 sockent_destroy(se);
2897 } /* }}} int network_config_add_listen */
2899 static int network_config_add_server(const oconfig_item_t *ci) /* {{{ */
2904 if ((ci->values_num < 1) || (ci->values_num > 2) ||
2905 (ci->values[0].type != OCONFIG_TYPE_STRING) ||
2906 ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING))) {
2907 ERROR("network plugin: The `%s' config option needs "
2908 "one or two string arguments.",
2913 se = sockent_create(SOCKENT_TYPE_CLIENT);
2915 ERROR("network plugin: sockent_create failed.");
2919 se->node = strdup(ci->values[0].value.string);
2920 if (ci->values_num >= 2)
2921 se->service = strdup(ci->values[1].value.string);
2923 for (int i = 0; i < ci->children_num; i++) {
2924 oconfig_item_t *child = ci->children + i;
2927 if (strcasecmp("Username", child->key) == 0)
2928 cf_util_get_string(child, &se->data.client.username);
2929 else if (strcasecmp("Password", child->key) == 0)
2930 cf_util_get_string(child, &se->data.client.password);
2931 else if (strcasecmp("SecurityLevel", child->key) == 0)
2932 network_config_set_security_level(child, &se->data.client.security_level);
2934 #endif /* HAVE_GCRYPT_H */
2935 if (strcasecmp("Interface", child->key) == 0)
2936 network_config_set_interface(child, &se->interface);
2937 else if (strcasecmp("BindAddress", child->key) == 0)
2938 network_config_set_bind_address(child, &se->data.client.bind_addr);
2939 else if (strcasecmp("ResolveInterval", child->key) == 0)
2940 cf_util_get_cdtime(child, &se->data.client.resolve_interval);
2942 WARNING("network plugin: Option `%s' is not allowed here.", child->key);
2947 if ((se->data.client.security_level > SECURITY_LEVEL_NONE) &&
2948 ((se->data.client.username == NULL) ||
2949 (se->data.client.password == NULL))) {
2950 ERROR("network plugin: A security level higher than `none' was "
2951 "requested, but no Username or Password option was given. "
2952 "Cowardly refusing to open this socket!");
2953 sockent_destroy(se);
2956 #endif /* HAVE_GCRYPT_H */
2958 status = sockent_init_crypto(se);
2960 ERROR("network plugin: network_config_add_server: sockent_init_crypto() "
2962 sockent_destroy(se);
2966 /* No call to sockent_client_connect() here -- it is called from
2967 * network_send_buffer_plain(). */
2969 status = sockent_add(se);
2971 ERROR("network plugin: network_config_add_server: sockent_add failed.");
2972 sockent_destroy(se);
2977 } /* }}} int network_config_add_server */
2979 static int network_config(oconfig_item_t *ci) /* {{{ */
2981 /* The options need to be applied first */
2982 for (int i = 0; i < ci->children_num; i++) {
2983 oconfig_item_t *child = ci->children + i;
2984 if (strcasecmp("TimeToLive", child->key) == 0)
2985 network_config_set_ttl(child);
2988 for (int i = 0; i < ci->children_num; i++) {
2989 oconfig_item_t *child = ci->children + i;
2991 if (strcasecmp("Listen", child->key) == 0)
2992 network_config_add_listen(child);
2993 else if (strcasecmp("Server", child->key) == 0)
2994 network_config_add_server(child);
2995 else if (strcasecmp("TimeToLive", child->key) == 0) {
2996 /* Handled earlier */
2997 } else if (strcasecmp("MaxPacketSize", child->key) == 0)
2998 network_config_set_buffer_size(child);
2999 else if (strcasecmp("Forward", child->key) == 0)
3000 cf_util_get_boolean(child, &network_config_forward);
3001 else if (strcasecmp("ReportStats", child->key) == 0)
3002 cf_util_get_boolean(child, &network_config_stats);
3004 WARNING("network plugin: Option `%s' is not allowed here.", child->key);
3009 } /* }}} int network_config */
3011 static int network_notification(const notification_t *n,
3012 user_data_t __attribute__((unused)) *
3014 char buffer[network_config_packet_size];
3015 char *buffer_ptr = buffer;
3016 size_t buffer_free = sizeof(buffer);
3019 if (!check_send_notify_okay(n))
3022 memset(buffer, 0, sizeof(buffer));
3024 status = write_part_number(&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3029 status = write_part_number(&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3030 (uint64_t)n->severity);
3034 if (strlen(n->host) > 0) {
3035 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_HOST, n->host,
3041 if (strlen(n->plugin) > 0) {
3042 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3043 n->plugin, strlen(n->plugin));
3048 if (strlen(n->plugin_instance) > 0) {
3049 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_PLUGIN_INSTANCE,
3050 n->plugin_instance, strlen(n->plugin_instance));
3055 if (strlen(n->type) > 0) {
3056 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_TYPE, n->type,
3062 if (strlen(n->type_instance) > 0) {
3063 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3064 n->type_instance, strlen(n->type_instance));
3069 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3070 n->message, strlen(n->message));
3074 network_send_buffer(buffer, sizeof(buffer) - buffer_free);
3077 } /* int network_notification */
3079 static int network_shutdown(void) {
3082 /* Kill the listening thread */
3083 if (receive_thread_running != 0) {
3084 INFO("network plugin: Stopping receive thread.");
3085 pthread_kill(receive_thread_id, SIGTERM);
3086 pthread_join(receive_thread_id, NULL /* no return value */);
3087 memset(&receive_thread_id, 0, sizeof(receive_thread_id));
3088 receive_thread_running = 0;
3091 /* Shutdown the dispatching thread */
3092 if (dispatch_thread_running != 0) {
3093 INFO("network plugin: Stopping dispatch thread.");
3094 pthread_mutex_lock(&receive_list_lock);
3095 pthread_cond_broadcast(&receive_list_cond);
3096 pthread_mutex_unlock(&receive_list_lock);
3097 pthread_join(dispatch_thread_id, /* ret = */ NULL);
3098 dispatch_thread_running = 0;
3101 sockent_destroy(listen_sockets);
3103 if (send_buffer_fill > 0)
3108 for (sockent_t *se = sending_sockets; se != NULL; se = se->next)
3109 sockent_client_disconnect(se);
3110 sockent_destroy(sending_sockets);
3112 plugin_unregister_config("network");
3113 plugin_unregister_init("network");
3114 plugin_unregister_write("network");
3115 plugin_unregister_shutdown("network");
3118 } /* int network_shutdown */
3120 static int network_stats_read(void) /* {{{ */
3122 derive_t copy_octets_rx;
3123 derive_t copy_octets_tx;
3124 derive_t copy_packets_rx;
3125 derive_t copy_packets_tx;
3126 derive_t copy_values_dispatched;
3127 derive_t copy_values_not_dispatched;
3128 derive_t copy_values_sent;
3129 derive_t copy_values_not_sent;
3130 derive_t copy_receive_list_length;
3131 value_list_t vl = VALUE_LIST_INIT;
3134 copy_octets_rx = stats_octets_rx;
3135 copy_octets_tx = stats_octets_tx;
3136 copy_packets_rx = stats_packets_rx;
3137 copy_packets_tx = stats_packets_tx;
3138 copy_values_dispatched = stats_values_dispatched;
3139 copy_values_not_dispatched = stats_values_not_dispatched;
3140 copy_values_sent = stats_values_sent;
3141 copy_values_not_sent = stats_values_not_sent;
3142 copy_receive_list_length = receive_list_length;
3144 /* Initialize `vl' */
3148 sstrncpy(vl.plugin, "network", sizeof(vl.plugin));
3150 /* Octets received / sent */
3151 vl.values[0].derive = (derive_t)copy_octets_rx;
3152 vl.values[1].derive = (derive_t)copy_octets_tx;
3153 sstrncpy(vl.type, "if_octets", sizeof(vl.type));
3154 plugin_dispatch_values(&vl);
3156 /* Packets received / send */
3157 vl.values[0].derive = (derive_t)copy_packets_rx;
3158 vl.values[1].derive = (derive_t)copy_packets_tx;
3159 sstrncpy(vl.type, "if_packets", sizeof(vl.type));
3160 plugin_dispatch_values(&vl);
3162 /* Values (not) dispatched and (not) send */
3163 sstrncpy(vl.type, "total_values", sizeof(vl.type));
3166 vl.values[0].derive = (derive_t)copy_values_dispatched;
3167 sstrncpy(vl.type_instance, "dispatch-accepted", sizeof(vl.type_instance));
3168 plugin_dispatch_values(&vl);
3170 vl.values[0].derive = (derive_t)copy_values_not_dispatched;
3171 sstrncpy(vl.type_instance, "dispatch-rejected", sizeof(vl.type_instance));
3172 plugin_dispatch_values(&vl);
3174 vl.values[0].derive = (derive_t)copy_values_sent;
3175 sstrncpy(vl.type_instance, "send-accepted", sizeof(vl.type_instance));
3176 plugin_dispatch_values(&vl);
3178 vl.values[0].derive = (derive_t)copy_values_not_sent;
3179 sstrncpy(vl.type_instance, "send-rejected", sizeof(vl.type_instance));
3180 plugin_dispatch_values(&vl);
3182 /* Receive queue length */
3183 vl.values[0].gauge = (gauge_t)copy_receive_list_length;
3184 sstrncpy(vl.type, "queue_length", sizeof(vl.type));
3185 vl.type_instance[0] = 0;
3186 plugin_dispatch_values(&vl);
3189 } /* }}} int network_stats_read */
3191 static int network_init(void) {
3192 static bool have_init;
3194 /* Check if we were already initialized. If so, just return - there's
3195 * nothing more to do (for now, that is). */
3200 if (network_config_stats)
3201 plugin_register_read("network", network_stats_read);
3203 plugin_register_shutdown("network", network_shutdown);
3205 send_buffer = malloc(network_config_packet_size);
3206 if (send_buffer == NULL) {
3207 ERROR("network plugin: malloc failed.");
3210 network_init_buffer();
3212 /* setup socket(s) and so on */
3213 if (sending_sockets != NULL) {
3214 plugin_register_write("network", network_write,
3215 /* user_data = */ NULL);
3216 plugin_register_notification("network", network_notification,
3217 /* user_data = */ NULL);
3220 /* If no threads need to be started, return here. */
3221 if ((listen_sockets_num == 0) ||
3222 ((dispatch_thread_running != 0) && (receive_thread_running != 0)))
3225 if (dispatch_thread_running == 0) {
3227 status = plugin_thread_create(&dispatch_thread_id, NULL /* no attributes */,
3228 dispatch_thread, NULL /* no argument */,
3231 ERROR("network: pthread_create failed: %s", STRERRNO);
3233 dispatch_thread_running = 1;
3237 if (receive_thread_running == 0) {
3239 status = plugin_thread_create(&receive_thread_id, NULL /* no attributes */,
3240 receive_thread, NULL /* no argument */,
3243 ERROR("network: pthread_create failed: %s", STRERRNO);
3245 receive_thread_running = 1;
3250 } /* int network_init */
3253 * The flush option of the network plugin cannot flush individual identifiers.
3254 * All the values are added to a buffer and sent when the buffer is full, the
3255 * requested value may or may not be in there, it's not worth finding out. We
3256 * just send the buffer if `flush' is called - if the requested value was in
3257 * there, good. If not, well, then there is nothing to flush.. -octo
3259 static int network_flush(cdtime_t timeout,
3260 __attribute__((unused)) const char *identifier,
3261 __attribute__((unused)) user_data_t *user_data) {
3262 pthread_mutex_lock(&send_buffer_lock);
3264 if (send_buffer_fill > 0) {
3266 cdtime_t now = cdtime();
3267 if ((send_buffer_last_update + timeout) > now) {
3268 pthread_mutex_unlock(&send_buffer_lock);
3274 pthread_mutex_unlock(&send_buffer_lock);
3277 } /* int network_flush */
3279 void module_register(void) {
3280 plugin_register_complex_config("network", network_config);
3281 plugin_register_init("network", network_init);
3282 plugin_register_flush("network", network_flush,
3283 /* user_data = */ NULL);
3284 } /* void module_register */