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 */
31 #include "utils/common/common.h"
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;
145 pthread_mutex_t lock;
148 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
149 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
150 * +-------+-----------------------+-------------------------------+
151 * ! Ver. ! ! Length !
152 * +-------+-----------------------+-------------------------------+
154 struct part_header_s {
158 typedef struct part_header_s part_header_t;
160 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
161 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
162 * +-------------------------------+-------------------------------+
164 * +-------------------------------+-------------------------------+
165 * : (Length - 4) Bytes :
166 * +---------------------------------------------------------------+
168 struct part_string_s {
172 typedef struct part_string_s part_string_t;
174 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
175 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
176 * +-------------------------------+-------------------------------+
178 * +-------------------------------+-------------------------------+
179 * : (Length - 4 == 2 || 4 || 8) Bytes :
180 * +---------------------------------------------------------------+
182 struct part_number_s {
186 typedef struct part_number_s part_number_t;
188 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
189 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
190 * +-------------------------------+-------------------------------+
192 * +-------------------------------+---------------+---------------+
193 * ! Num of values ! Type0 ! Type1 !
194 * +-------------------------------+---------------+---------------+
197 * +---------------------------------------------------------------+
200 * +---------------------------------------------------------------+
202 struct part_values_s {
204 uint16_t *num_values;
205 uint8_t *values_types;
208 typedef struct part_values_s part_values_t;
210 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
211 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
212 * +-------------------------------+-------------------------------+
214 * +-------------------------------+-------------------------------+
215 * ! Hash (Bits 0 - 31) !
217 * ! Hash (Bits 224 - 255) !
218 * +---------------------------------------------------------------+
221 #define PART_SIGNATURE_SHA256_SIZE 36
222 struct part_signature_sha256_s {
224 unsigned char hash[32];
227 typedef struct part_signature_sha256_s part_signature_sha256_t;
229 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
230 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
231 * +-------------------------------+-------------------------------+
233 * +-------------------------------+-------------------------------+
234 * ! Original length ! Padding (0 - 15 bytes) !
235 * +-------------------------------+-------------------------------+
236 * ! Hash (Bits 0 - 31) !
238 * ! Hash (Bits 128 - 159) !
239 * +---------------------------------------------------------------+
242 #define PART_ENCRYPTION_AES256_SIZE 42
243 struct part_encryption_aes256_s {
245 uint16_t username_length;
247 unsigned char iv[16];
249 unsigned char hash[20];
253 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
255 struct receive_list_entry_s {
259 struct receive_list_entry_s *next;
261 typedef struct receive_list_entry_s receive_list_entry_t;
266 static int network_config_ttl;
267 /* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
268 static size_t network_config_packet_size = 1452;
269 static bool network_config_forward;
270 static bool network_config_stats;
272 static sockent_t *sending_sockets;
274 static receive_list_entry_t *receive_list_head;
275 static receive_list_entry_t *receive_list_tail;
276 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
277 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
278 static uint64_t receive_list_length;
280 static sockent_t *listen_sockets;
281 static struct pollfd *listen_sockets_pollfd;
282 static size_t listen_sockets_num;
284 /* The receive and dispatch threads will run as long as `listen_loop' is set to
286 static int listen_loop;
287 static int receive_thread_running;
288 static pthread_t receive_thread_id;
289 static int dispatch_thread_running;
290 static pthread_t dispatch_thread_id;
292 /* Buffer in which to-be-sent network packets are constructed. */
293 static char *send_buffer;
294 static char *send_buffer_ptr;
295 static int send_buffer_fill;
296 static cdtime_t send_buffer_last_update;
297 static value_list_t send_buffer_vl = VALUE_LIST_INIT;
298 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
300 /* XXX: These counters are incremented from one place only. The spot in which
301 * the values are incremented is either only reachable by one thread (the
302 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
303 * example). Only if neither is true, the stats_lock is acquired. The counters
304 * are always read without holding a lock in the hope that writing 8 bytes to
305 * memory is an atomic operation. */
306 static derive_t stats_octets_rx;
307 static derive_t stats_octets_tx;
308 static derive_t stats_packets_rx;
309 static derive_t stats_packets_tx;
310 static derive_t stats_values_dispatched;
311 static derive_t stats_values_not_dispatched;
312 static derive_t stats_values_sent;
313 static derive_t stats_values_not_sent;
314 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
319 static bool check_receive_okay(const value_list_t *vl) /* {{{ */
321 uint64_t time_sent = 0;
324 status = uc_meta_data_get_unsigned_int(vl, "network:time_sent", &time_sent);
326 /* This is a value we already sent. Don't allow it to be received again in
327 * order to avoid looping. */
328 if ((status == 0) && (time_sent >= ((uint64_t)vl->time)))
332 } /* }}} bool check_receive_okay */
334 static bool check_send_okay(const value_list_t *vl) /* {{{ */
339 if (network_config_forward)
342 if (vl->meta == NULL)
345 status = meta_data_get_boolean(vl->meta, "network:received", &received);
346 if (status == -ENOENT)
348 else if (status != 0) {
349 ERROR("network plugin: check_send_okay: meta_data_get_boolean failed "
355 /* By default, only *send* value lists that were not *received* by the
358 } /* }}} bool check_send_okay */
360 static bool check_notify_received(const notification_t *n) /* {{{ */
362 for (notification_meta_t *ptr = n->meta; ptr != NULL; ptr = ptr->next)
363 if ((strcmp("network:received", ptr->name) == 0) &&
364 (ptr->type == NM_TYPE_BOOLEAN))
365 return (bool)ptr->nm_value.nm_boolean;
368 } /* }}} bool check_notify_received */
370 static bool check_send_notify_okay(const notification_t *n) /* {{{ */
372 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
378 received = check_notify_received(n);
380 if (network_config_forward && received) {
382 LOG_ERR, &complain_forwarding,
383 "network plugin: A notification has been received via the network "
384 "and forwarding is enabled. Forwarding of notifications is currently "
385 "not supported, because there is not loop-detection available. "
386 "Please contact the collectd mailing list if you need this "
390 /* By default, only *send* value lists that were not *received* by the
393 } /* }}} bool check_send_notify_okay */
395 static int network_dispatch_values(value_list_t *vl, /* {{{ */
396 const char *username) {
399 if ((vl->time == 0) || (strlen(vl->host) == 0) || (strlen(vl->plugin) == 0) ||
400 (strlen(vl->type) == 0))
403 if (!check_receive_okay(vl)) {
405 char name[6 * DATA_MAX_NAME_LEN];
406 FORMAT_VL(name, sizeof(name), vl);
407 name[sizeof(name) - 1] = '\0';
408 DEBUG("network plugin: network_dispatch_values: "
409 "NOT dispatching %s.",
412 stats_values_not_dispatched++;
416 assert(vl->meta == NULL);
418 vl->meta = meta_data_create();
419 if (vl->meta == NULL) {
420 ERROR("network plugin: meta_data_create failed.");
424 status = meta_data_add_boolean(vl->meta, "network:received", 1);
426 ERROR("network plugin: meta_data_add_boolean failed.");
427 meta_data_destroy(vl->meta);
432 if (username != NULL) {
433 status = meta_data_add_string(vl->meta, "network:username", username);
435 ERROR("network plugin: meta_data_add_string failed.");
436 meta_data_destroy(vl->meta);
442 plugin_dispatch_values(vl);
443 stats_values_dispatched++;
445 meta_data_destroy(vl->meta);
449 } /* }}} int network_dispatch_values */
451 static int network_dispatch_notification(notification_t *n) /* {{{ */
455 assert(n->meta == NULL);
457 status = plugin_notification_meta_add_boolean(n, "network:received", 1);
459 ERROR("network plugin: plugin_notification_meta_add_boolean failed.");
460 plugin_notification_meta_free(n->meta);
465 status = plugin_dispatch_notification(n);
467 plugin_notification_meta_free(n->meta);
471 } /* }}} int network_dispatch_notification */
474 static int network_init_gcrypt(void) /* {{{ */
478 /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
479 * Because you can't know in a library whether another library has
480 * already initialized the library */
481 if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P))
484 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
485 * To ensure thread-safety, it's important to set GCRYCTL_SET_THREAD_CBS
486 * *before* initalizing Libgcrypt with gcry_check_version(), which itself must
487 * be called before any other gcry_* function. GCRYCTL_ANY_INITIALIZATION_P
488 * above doesn't count, as it doesn't implicitly initalize Libgcrypt.
490 * tl;dr: keep all these gry_* statements in this exact order please. */
491 #if GCRYPT_VERSION_NUMBER < 0x010600
492 err = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
494 ERROR("network plugin: gcry_control (GCRYCTL_SET_THREAD_CBS) failed: %s",
500 gcry_check_version(NULL);
502 err = gcry_control(GCRYCTL_INIT_SECMEM, 32768);
504 ERROR("network plugin: gcry_control (GCRYCTL_INIT_SECMEM) failed: %s",
509 gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
511 } /* }}} int network_init_gcrypt */
513 static gcry_cipher_hd_t network_get_aes256_cypher(sockent_t *se, /* {{{ */
516 const char *username) {
518 gcry_cipher_hd_t *cyper_ptr;
519 unsigned char password_hash[32];
521 if (se->type == SOCKENT_TYPE_CLIENT) {
522 cyper_ptr = &se->data.client.cypher;
523 memcpy(password_hash, se->data.client.password_hash, sizeof(password_hash));
527 cyper_ptr = &se->data.server.cypher;
529 if (username == NULL)
532 secret = fbh_get(se->data.server.userdb, username);
536 gcry_md_hash_buffer(GCRY_MD_SHA256, password_hash, secret, strlen(secret));
541 if (*cyper_ptr == NULL) {
542 err = gcry_cipher_open(cyper_ptr, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB,
545 ERROR("network plugin: gcry_cipher_open returned: %s",
551 gcry_cipher_reset(*cyper_ptr);
553 assert(*cyper_ptr != NULL);
555 err = gcry_cipher_setkey(*cyper_ptr, password_hash, sizeof(password_hash));
557 ERROR("network plugin: gcry_cipher_setkey returned: %s",
559 gcry_cipher_close(*cyper_ptr);
564 err = gcry_cipher_setiv(*cyper_ptr, iv, iv_size);
566 ERROR("network plugin: gcry_cipher_setkey returned: %s",
568 gcry_cipher_close(*cyper_ptr);
574 } /* }}} int network_get_aes256_cypher */
575 #endif /* HAVE_GCRYPT_H */
577 static int write_part_values(char **ret_buffer, size_t *ret_buffer_len,
578 const data_set_t *ds, const value_list_t *vl) {
583 part_header_t pkg_ph;
584 uint16_t pkg_num_values;
585 uint8_t *pkg_values_types;
590 num_values = vl->values_len;
591 packet_len = sizeof(part_header_t) + sizeof(uint16_t) +
592 (num_values * sizeof(uint8_t)) + (num_values * sizeof(value_t));
594 if (*ret_buffer_len < packet_len)
597 pkg_values_types = malloc(num_values * sizeof(*pkg_values_types));
598 if (pkg_values_types == NULL) {
599 ERROR("network plugin: write_part_values: malloc failed.");
603 pkg_values = malloc(num_values * sizeof(*pkg_values));
604 if (pkg_values == NULL) {
605 free(pkg_values_types);
606 ERROR("network plugin: write_part_values: malloc failed.");
610 pkg_ph.type = htons(TYPE_VALUES);
611 pkg_ph.length = htons(packet_len);
613 pkg_num_values = htons((uint16_t)vl->values_len);
615 for (int i = 0; i < num_values; i++) {
616 pkg_values_types[i] = (uint8_t)ds->ds[i].type;
617 switch (ds->ds[i].type) {
618 case DS_TYPE_COUNTER:
619 pkg_values[i].counter = htonll(vl->values[i].counter);
623 pkg_values[i].gauge = htond(vl->values[i].gauge);
627 pkg_values[i].derive = htonll(vl->values[i].derive);
630 case DS_TYPE_ABSOLUTE:
631 pkg_values[i].absolute = htonll(vl->values[i].absolute);
635 free(pkg_values_types);
637 ERROR("network plugin: write_part_values: "
638 "Unknown data source type: %i",
641 } /* switch (ds->ds[i].type) */
642 } /* for (num_values) */
645 * Use `memcpy' to write everything to the buffer, because the pointer
646 * may be unaligned and some architectures, such as SPARC, can't handle
649 packet_ptr = *ret_buffer;
651 memcpy(packet_ptr + offset, &pkg_ph, sizeof(pkg_ph));
652 offset += sizeof(pkg_ph);
653 memcpy(packet_ptr + offset, &pkg_num_values, sizeof(pkg_num_values));
654 offset += sizeof(pkg_num_values);
655 memcpy(packet_ptr + offset, pkg_values_types, num_values * sizeof(uint8_t));
656 offset += num_values * sizeof(uint8_t);
657 memcpy(packet_ptr + offset, pkg_values, num_values * sizeof(value_t));
658 offset += num_values * sizeof(value_t);
660 assert(offset == packet_len);
662 *ret_buffer = packet_ptr + packet_len;
663 *ret_buffer_len -= packet_len;
665 free(pkg_values_types);
669 } /* int write_part_values */
671 static int write_part_number(char **ret_buffer, size_t *ret_buffer_len,
672 int type, uint64_t value) {
676 part_header_t pkg_head;
681 packet_len = sizeof(pkg_head) + sizeof(pkg_value);
683 if (*ret_buffer_len < packet_len)
686 pkg_head.type = htons(type);
687 pkg_head.length = htons(packet_len);
688 pkg_value = htonll(value);
690 packet_ptr = *ret_buffer;
692 memcpy(packet_ptr + offset, &pkg_head, sizeof(pkg_head));
693 offset += sizeof(pkg_head);
694 memcpy(packet_ptr + offset, &pkg_value, sizeof(pkg_value));
695 offset += sizeof(pkg_value);
697 assert(offset == packet_len);
699 *ret_buffer = packet_ptr + packet_len;
700 *ret_buffer_len -= packet_len;
703 } /* int write_part_number */
705 static int write_part_string(char **ret_buffer, size_t *ret_buffer_len,
706 int type, const char *str, size_t str_len) {
715 buffer_len = 2 * sizeof(uint16_t) + str_len + 1;
716 if (*ret_buffer_len < buffer_len)
719 pkg_type = htons(type);
720 pkg_length = htons(buffer_len);
722 buffer = *ret_buffer;
724 memcpy(buffer + offset, (void *)&pkg_type, sizeof(pkg_type));
725 offset += sizeof(pkg_type);
726 memcpy(buffer + offset, (void *)&pkg_length, sizeof(pkg_length));
727 offset += sizeof(pkg_length);
728 memcpy(buffer + offset, str, str_len);
730 memset(buffer + offset, '\0', 1);
733 assert(offset == buffer_len);
735 *ret_buffer = buffer + buffer_len;
736 *ret_buffer_len -= buffer_len;
739 } /* int write_part_string */
741 static int parse_part_values(void **ret_buffer, size_t *ret_buffer_len,
742 value_t **ret_values, size_t *ret_num_values) {
743 char *buffer = *ret_buffer;
744 size_t buffer_len = *ret_buffer_len;
756 if (buffer_len < 15) {
757 NOTICE("network plugin: packet is too short: "
758 "buffer_len = %" PRIsz,
763 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
764 buffer += sizeof(tmp16);
765 pkg_type = ntohs(tmp16);
767 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
768 buffer += sizeof(tmp16);
769 pkg_length = ntohs(tmp16);
771 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
772 buffer += sizeof(tmp16);
773 pkg_numval = (size_t)ntohs(tmp16);
775 assert(pkg_type == TYPE_VALUES);
778 3 * sizeof(uint16_t) + pkg_numval * (sizeof(uint8_t) + sizeof(value_t));
779 if (buffer_len < exp_size) {
780 WARNING("network plugin: parse_part_values: "
782 "Chunk of size %" PRIsz " expected, "
783 "but buffer has only %" PRIsz " bytes left.",
784 exp_size, buffer_len);
787 assert(pkg_numval <= ((buffer_len - 6) / 9));
789 if (pkg_length != exp_size) {
790 WARNING("network plugin: parse_part_values: "
791 "Length and number of values "
792 "in the packet don't match.");
796 pkg_types = calloc(pkg_numval, sizeof(*pkg_types));
797 pkg_values = calloc(pkg_numval, sizeof(*pkg_values));
798 if ((pkg_types == NULL) || (pkg_values == NULL)) {
801 ERROR("network plugin: parse_part_values: calloc failed.");
805 memcpy(pkg_types, buffer, pkg_numval * sizeof(*pkg_types));
806 buffer += pkg_numval * sizeof(*pkg_types);
807 memcpy(pkg_values, buffer, pkg_numval * sizeof(*pkg_values));
808 buffer += pkg_numval * sizeof(*pkg_values);
810 for (size_t i = 0; i < pkg_numval; i++) {
811 switch (pkg_types[i]) {
812 case DS_TYPE_COUNTER:
813 pkg_values[i].counter = (counter_t)ntohll(pkg_values[i].counter);
817 pkg_values[i].gauge = (gauge_t)ntohd(pkg_values[i].gauge);
821 pkg_values[i].derive = (derive_t)ntohll(pkg_values[i].derive);
824 case DS_TYPE_ABSOLUTE:
825 pkg_values[i].absolute = (absolute_t)ntohll(pkg_values[i].absolute);
829 NOTICE("network plugin: parse_part_values: "
830 "Don't know how to handle data source type %" PRIu8,
835 } /* switch (pkg_types[i]) */
838 *ret_buffer = buffer;
839 *ret_buffer_len = buffer_len - pkg_length;
840 *ret_num_values = pkg_numval;
841 *ret_values = pkg_values;
846 } /* int parse_part_values */
848 static int parse_part_number(void **ret_buffer, size_t *ret_buffer_len,
850 char *buffer = *ret_buffer;
851 size_t buffer_len = *ret_buffer_len;
855 size_t exp_size = 2 * sizeof(uint16_t) + sizeof(uint64_t);
859 if (buffer_len < exp_size) {
860 WARNING("network plugin: parse_part_number: "
862 "Chunk of size %" PRIsz " expected, "
863 "but buffer has only %" PRIsz " bytes left.",
864 exp_size, buffer_len);
868 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
869 buffer += sizeof(tmp16);
870 /* pkg_type = ntohs (tmp16); */
872 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
873 buffer += sizeof(tmp16);
874 pkg_length = ntohs(tmp16);
876 memcpy((void *)&tmp64, buffer, sizeof(tmp64));
877 buffer += sizeof(tmp64);
878 *value = ntohll(tmp64);
880 *ret_buffer = buffer;
881 *ret_buffer_len = buffer_len - pkg_length;
884 } /* int parse_part_number */
886 static int parse_part_string(void **ret_buffer, size_t *ret_buffer_len,
887 char *output, size_t const output_len) {
888 char *buffer = *ret_buffer;
889 size_t buffer_len = *ret_buffer_len;
892 size_t const header_size = 2 * sizeof(uint16_t);
900 if (buffer_len < header_size) {
901 WARNING("network plugin: parse_part_string: "
903 "Chunk of at least size %" PRIsz " expected, "
904 "but buffer has only %" PRIsz " bytes left.",
905 header_size, buffer_len);
909 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
910 buffer += sizeof(tmp16);
911 /* pkg_type = ntohs (tmp16); */
913 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
914 buffer += sizeof(tmp16);
915 pkg_length = ntohs(tmp16);
916 payload_size = ((size_t)pkg_length) - header_size;
918 /* Check that packet fits in the input buffer */
919 if (pkg_length > buffer_len) {
920 WARNING("network plugin: parse_part_string: "
922 "Chunk of size %" PRIu16 " received, "
923 "but buffer has only %" PRIsz " bytes left.",
924 pkg_length, buffer_len);
928 /* Check that pkg_length is in the valid range */
929 if (pkg_length <= header_size) {
930 WARNING("network plugin: parse_part_string: "
932 "Header claims this packet is only %hu "
938 /* Check that the package data fits into the output buffer.
939 * The previous if-statement ensures that:
940 * `pkg_length > header_size' */
941 if (output_len < payload_size) {
942 WARNING("network plugin: parse_part_string: "
944 "Output buffer holds %" PRIsz " bytes, "
945 "which is too small to hold the received "
946 "%" PRIsz " byte string.",
947 output_len, payload_size);
951 /* All sanity checks successfull, let's copy the data over */
952 memcpy((void *)output, (void *)buffer, payload_size);
953 buffer += payload_size;
955 /* For some very weird reason '\0' doesn't do the trick on SPARC in
957 if (output[payload_size - 1] != 0) {
958 WARNING("network plugin: parse_part_string: "
959 "Received string does not end "
960 "with a NULL-byte.");
964 *ret_buffer = buffer;
965 *ret_buffer_len = buffer_len - pkg_length;
968 } /* int parse_part_string */
970 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
971 * parse_packet and vice versa. */
972 #define PP_SIGNED 0x01
973 #define PP_ENCRYPTED 0x02
974 static int parse_packet(sockent_t *se, void *buffer, size_t buffer_size,
975 int flags, const char *username);
977 #define BUFFER_READ(p, s) \
979 memcpy((p), buffer + buffer_offset, (s)); \
980 buffer_offset += (s); \
984 static int parse_part_sign_sha256(sockent_t *se, /* {{{ */
985 void **ret_buffer, size_t *ret_buffer_len,
987 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
991 size_t buffer_offset;
996 part_signature_sha256_t pss;
997 uint16_t pss_head_length;
998 char hash[sizeof(pss.hash)];
1002 unsigned char *hash_ptr;
1004 buffer = *ret_buffer;
1005 buffer_len = *ret_buffer_len;
1008 /* Check if the buffer has enough data for this structure. */
1009 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1012 /* Read type and length header */
1013 BUFFER_READ(&pss.head.type, sizeof(pss.head.type));
1014 BUFFER_READ(&pss.head.length, sizeof(pss.head.length));
1015 pss_head_length = ntohs(pss.head.length);
1017 /* Check if the `pss_head_length' is within bounds. */
1018 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE) ||
1019 (pss_head_length > buffer_len)) {
1020 ERROR("network plugin: HMAC-SHA-256 with invalid length received.");
1024 if (se->data.server.userdb == NULL) {
1026 LOG_NOTICE, &complain_no_users,
1027 "network plugin: Received signed network packet but can't verify it "
1028 "because no user DB has been configured. Will accept it.");
1030 *ret_buffer = buffer + pss_head_length;
1031 *ret_buffer_len -= pss_head_length;
1036 /* Copy the hash. */
1037 BUFFER_READ(pss.hash, sizeof(pss.hash));
1039 /* Calculate username length (without null byte) and allocate memory */
1040 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1041 pss.username = malloc(username_len + 1);
1042 if (pss.username == NULL)
1045 /* Read the username */
1046 BUFFER_READ(pss.username, username_len);
1047 pss.username[username_len] = 0;
1049 assert(buffer_offset == pss_head_length);
1051 /* Query the password */
1052 secret = fbh_get(se->data.server.userdb, pss.username);
1053 if (secret == NULL) {
1054 ERROR("network plugin: Unknown user: %s", pss.username);
1055 sfree(pss.username);
1059 /* Create a hash device and check the HMAC */
1061 err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1063 ERROR("network plugin: Creating HMAC-SHA-256 object failed: %s",
1064 gcry_strerror(err));
1066 sfree(pss.username);
1070 err = gcry_md_setkey(hd, secret, strlen(secret));
1072 ERROR("network plugin: gcry_md_setkey failed: %s", gcry_strerror(err));
1075 sfree(pss.username);
1079 gcry_md_write(hd, buffer + PART_SIGNATURE_SHA256_SIZE,
1080 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1081 hash_ptr = gcry_md_read(hd, GCRY_MD_SHA256);
1082 if (hash_ptr == NULL) {
1083 ERROR("network plugin: gcry_md_read failed.");
1086 sfree(pss.username);
1089 memcpy(hash, hash_ptr, sizeof(hash));
1095 if (memcmp(pss.hash, hash, sizeof(pss.hash)) != 0) {
1096 WARNING("network plugin: Verifying HMAC-SHA-256 signature failed: "
1097 "Hash mismatch. Username: %s",
1100 parse_packet(se, buffer + buffer_offset, buffer_len - buffer_offset,
1101 flags | PP_SIGNED, pss.username);
1105 sfree(pss.username);
1107 *ret_buffer = buffer + buffer_len;
1108 *ret_buffer_len = 0;
1111 } /* }}} int parse_part_sign_sha256 */
1112 /* #endif HAVE_GCRYPT_H */
1114 #else /* if !HAVE_GCRYPT_H */
1115 static int parse_part_sign_sha256(sockent_t *se, /* {{{ */
1116 void **ret_buffer, size_t *ret_buffer_size,
1118 static int warning_has_been_printed;
1122 size_t buffer_offset;
1125 part_signature_sha256_t pss;
1127 buffer = *ret_buffer;
1128 buffer_size = *ret_buffer_size;
1131 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1134 BUFFER_READ(&pss.head.type, sizeof(pss.head.type));
1135 BUFFER_READ(&pss.head.length, sizeof(pss.head.length));
1136 part_len = ntohs(pss.head.length);
1138 if ((part_len <= PART_SIGNATURE_SHA256_SIZE) || (part_len > buffer_size))
1141 if (warning_has_been_printed == 0) {
1142 WARNING("network plugin: Received signed packet, but the network "
1143 "plugin was not linked with libgcrypt, so I cannot "
1144 "verify the signature. The packet will be accepted.");
1145 warning_has_been_printed = 1;
1148 parse_packet(se, buffer + part_len, buffer_size - part_len, flags,
1149 /* username = */ NULL);
1151 *ret_buffer = buffer + buffer_size;
1152 *ret_buffer_size = 0;
1155 } /* }}} int parse_part_sign_sha256 */
1156 #endif /* !HAVE_GCRYPT_H */
1159 static int parse_part_encr_aes256(sockent_t *se, /* {{{ */
1160 void **ret_buffer, size_t *ret_buffer_len,
1162 char *buffer = *ret_buffer;
1163 size_t buffer_len = *ret_buffer_len;
1166 size_t buffer_offset;
1167 uint16_t username_len;
1168 part_encryption_aes256_t pea;
1169 unsigned char hash[sizeof(pea.hash)] = {0};
1171 gcry_cipher_hd_t cypher;
1174 /* Make sure at least the header if available. */
1175 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE) {
1176 NOTICE("network plugin: parse_part_encr_aes256: "
1177 "Discarding short packet.");
1183 /* Copy the unencrypted information into `pea'. */
1184 BUFFER_READ(&pea.head.type, sizeof(pea.head.type));
1185 BUFFER_READ(&pea.head.length, sizeof(pea.head.length));
1187 /* Check the `part size'. */
1188 part_size = ntohs(pea.head.length);
1189 if ((part_size <= PART_ENCRYPTION_AES256_SIZE) || (part_size > buffer_len)) {
1190 NOTICE("network plugin: parse_part_encr_aes256: "
1191 "Discarding part with invalid size.");
1195 /* Read the username */
1196 BUFFER_READ(&username_len, sizeof(username_len));
1197 username_len = ntohs(username_len);
1199 if ((username_len == 0) ||
1200 (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1)))) {
1201 NOTICE("network plugin: parse_part_encr_aes256: "
1202 "Discarding part with invalid username length.");
1206 assert(username_len > 0);
1207 pea.username = malloc(username_len + 1);
1208 if (pea.username == NULL)
1210 BUFFER_READ(pea.username, username_len);
1211 pea.username[username_len] = 0;
1213 /* Last but not least, the initialization vector */
1214 BUFFER_READ(pea.iv, sizeof(pea.iv));
1216 /* Make sure we are at the right position */
1217 assert(buffer_offset ==
1218 (username_len + PART_ENCRYPTION_AES256_SIZE - sizeof(pea.hash)));
1220 cypher = network_get_aes256_cypher(se, pea.iv, sizeof(pea.iv), pea.username);
1221 if (cypher == NULL) {
1222 ERROR("network plugin: Failed to get cypher. Username: %s", pea.username);
1223 sfree(pea.username);
1227 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1228 assert(payload_len > 0);
1230 /* Decrypt the packet in-place */
1231 err = gcry_cipher_decrypt(cypher, buffer + buffer_offset,
1232 part_size - buffer_offset,
1233 /* in = */ NULL, /* in len = */ 0);
1235 ERROR("network plugin: gcry_cipher_decrypt returned: %s. Username: %s",
1236 gcry_strerror(err), pea.username);
1237 sfree(pea.username);
1242 BUFFER_READ(pea.hash, sizeof(pea.hash));
1244 /* Make sure we're at the right position - again */
1245 assert(buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1246 assert(buffer_offset == (part_size - payload_len));
1248 /* Check hash sum */
1249 gcry_md_hash_buffer(GCRY_MD_SHA1, hash, buffer + buffer_offset, payload_len);
1250 if (memcmp(hash, pea.hash, sizeof(hash)) != 0) {
1251 ERROR("network plugin: Checksum mismatch. Username: %s", pea.username);
1252 sfree(pea.username);
1256 parse_packet(se, buffer + buffer_offset, payload_len, flags | PP_ENCRYPTED,
1259 /* Update return values */
1260 *ret_buffer = buffer + part_size;
1261 *ret_buffer_len = buffer_len - part_size;
1263 sfree(pea.username);
1266 } /* }}} int parse_part_encr_aes256 */
1267 /* #endif HAVE_GCRYPT_H */
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,
1273 static int warning_has_been_printed;
1277 size_t buffer_offset;
1282 buffer = *ret_buffer;
1283 buffer_size = *ret_buffer_size;
1286 /* parse_packet assures this minimum size. */
1287 assert(buffer_size >= (sizeof(ph.type) + sizeof(ph.length)));
1289 BUFFER_READ(&ph.type, sizeof(ph.type));
1290 BUFFER_READ(&ph.length, sizeof(ph.length));
1291 ph_length = ntohs(ph.length);
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.");
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;
1306 *ret_buffer = (void *)(((char *)*ret_buffer) + ph_length);
1307 *ret_buffer_size -= ph_length;
1310 } /* }}} int parse_part_encr_aes256 */
1311 #endif /* !HAVE_GCRYPT_H */
1315 static int parse_packet(sockent_t *se, /* {{{ */
1316 void *buffer, size_t buffer_size, int flags,
1317 const char *username) {
1320 value_list_t vl = VALUE_LIST_INIT;
1321 notification_t n = {0};
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 */
1329 memset(&vl, '\0', sizeof(vl));
1332 while ((status == 0) && (0 < buffer_size) &&
1333 ((unsigned int)buffer_size > sizeof(part_header_t))) {
1334 uint16_t pkg_length;
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));
1341 pkg_length = ntohs(pkg_length);
1342 pkg_type = ntohs(pkg_type);
1344 if (pkg_length > buffer_size)
1346 /* Ensure that this loop terminates eventually */
1347 if (pkg_length < (2 * sizeof(uint16_t)))
1350 if (pkg_type == TYPE_ENCR_AES256) {
1351 status = parse_part_encr_aes256(se, &buffer, &buffer_size, flags);
1353 ERROR("network plugin: Decrypting AES256 "
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;
1368 buffer = ((char *)buffer) + pkg_length;
1369 buffer_size -= (size_t)pkg_length;
1372 #endif /* HAVE_GCRYPT_H */
1373 else if (pkg_type == TYPE_SIGN_SHA256) {
1374 status = parse_part_sign_sha256(se, &buffer, &buffer_size, flags);
1376 ERROR("network plugin: Verifying HMAC-SHA-256 "
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;
1391 buffer = ((char *)buffer) + pkg_length;
1392 buffer_size -= (size_t)pkg_length;
1395 #endif /* HAVE_GCRYPT_H */
1396 else if (pkg_type == TYPE_VALUES) {
1398 parse_part_values(&buffer, &buffer_size, &vl.values, &vl.values_len);
1402 network_dispatch_values(&vl, username);
1405 } else if (pkg_type == TYPE_TIME) {
1407 status = parse_part_number(&buffer, &buffer_size, &tmp);
1409 vl.time = TIME_T_TO_CDTIME_T(tmp);
1410 n.time = TIME_T_TO_CDTIME_T(tmp);
1412 } else if (pkg_type == TYPE_TIME_HR) {
1414 status = parse_part_number(&buffer, &buffer_size, &tmp);
1416 vl.time = (cdtime_t)tmp;
1417 n.time = (cdtime_t)tmp;
1419 } else if (pkg_type == TYPE_INTERVAL) {
1421 status = parse_part_number(&buffer, &buffer_size, &tmp);
1423 vl.interval = TIME_T_TO_CDTIME_T(tmp);
1424 } else if (pkg_type == TYPE_INTERVAL_HR) {
1426 status = parse_part_number(&buffer, &buffer_size, &tmp);
1428 vl.interval = (cdtime_t)tmp;
1429 } else if (pkg_type == TYPE_HOST) {
1431 parse_part_string(&buffer, &buffer_size, vl.host, sizeof(vl.host));
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,
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));
1443 sstrncpy(n.plugin_instance, vl.plugin_instance,
1444 sizeof(n.plugin_instance));
1445 } else if (pkg_type == TYPE_TYPE) {
1447 parse_part_string(&buffer, &buffer_size, vl.type, sizeof(vl.type));
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));
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,
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.",
1467 } else if (n.time == 0) {
1468 INFO("network plugin: "
1469 "Ignoring notification with "
1471 } else if (strlen(n.message) == 0) {
1472 INFO("network plugin: "
1473 "Ignoring notification with "
1474 "an empty message.");
1476 network_dispatch_notification(&n);
1478 } else if (pkg_type == TYPE_SEVERITY) {
1480 status = parse_part_number(&buffer, &buffer_size, &tmp);
1482 n.severity = (int)tmp;
1484 DEBUG("network plugin: parse_packet: Unknown part"
1487 buffer = ((char *)buffer) + pkg_length;
1488 buffer_size -= (size_t)pkg_length;
1490 } /* while (buffer_size > sizeof (part_header_t)) */
1492 if (status == 0 && buffer_size > 0)
1493 WARNING("network plugin: parse_packet: Received truncated "
1494 "packet, try increasing `MaxPacketSize'");
1497 } /* }}} int parse_packet */
1499 static void free_sockent_client(struct sockent_client *sec) /* {{{ */
1506 sfree(sec->bind_addr);
1508 sfree(sec->username);
1509 sfree(sec->password);
1510 if (sec->cypher != NULL)
1511 gcry_cipher_close(sec->cypher);
1513 } /* }}} void free_sockent_client */
1515 static void free_sockent_server(struct sockent_server *ses) /* {{{ */
1517 for (size_t i = 0; i < ses->fd_num; i++) {
1518 if (ses->fd[i] >= 0) {
1526 sfree(ses->auth_file);
1527 fbh_destroy(ses->userdb);
1528 if (ses->cypher != NULL)
1529 gcry_cipher_close(ses->cypher);
1531 } /* }}} void free_sockent_server */
1533 static void sockent_destroy(sockent_t *se) /* {{{ */
1537 DEBUG("network plugin: sockent_destroy (se = %p);", (void *)se);
1539 while (se != NULL) {
1544 pthread_mutex_destroy(&se->lock);
1546 if (se->type == SOCKENT_TYPE_CLIENT)
1547 free_sockent_client(&se->data.client);
1549 free_sockent_server(&se->data.server);
1554 } /* }}} void sockent_destroy */
1557 * int network_set_ttl
1559 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1560 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1562 * The `struct addrinfo' is used to destinguish between unicast and multicast
1565 static int network_set_ttl(const sockent_t *se, const struct addrinfo *ai) {
1566 DEBUG("network plugin: network_set_ttl: network_config_ttl = %i;",
1567 network_config_ttl);
1569 assert(se->type == SOCKENT_TYPE_CLIENT);
1571 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1574 if (ai->ai_family == AF_INET) {
1575 struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1578 if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr)))
1579 optname = IP_MULTICAST_TTL;
1583 if (setsockopt(se->data.client.fd, IPPROTO_IP, optname, &network_config_ttl,
1584 sizeof(network_config_ttl)) != 0) {
1585 ERROR("network plugin: setsockopt (ipv4-ttl): %s", STRERRNO);
1588 } else if (ai->ai_family == AF_INET6) {
1590 * http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1591 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1594 if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr))
1595 optname = IPV6_MULTICAST_HOPS;
1597 optname = IPV6_UNICAST_HOPS;
1599 if (setsockopt(se->data.client.fd, IPPROTO_IPV6, optname,
1600 &network_config_ttl, sizeof(network_config_ttl)) != 0) {
1601 ERROR("network plugin: setsockopt(ipv6-ttl): %s", STRERRNO);
1607 } /* int network_set_ttl */
1609 static int network_set_interface(const sockent_t *se,
1610 const struct addrinfo *ai) /* {{{ */
1612 DEBUG("network plugin: network_set_interface: interface index = %i;",
1615 assert(se->type == SOCKENT_TYPE_CLIENT);
1617 if (ai->ai_family == AF_INET) {
1618 struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1620 if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr))) {
1621 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1622 /* If possible, use the "ip_mreqn" structure which has
1623 * an "interface index" member. Using the interface
1624 * index is preferred here, because of its similarity
1625 * to the way IPv6 handles this. Unfortunately, it
1626 * appears not to be portable. */
1627 struct ip_mreqn mreq = {.imr_multiaddr.s_addr = addr->sin_addr.s_addr,
1628 .imr_address.s_addr = ntohl(INADDR_ANY),
1629 .imr_ifindex = se->interface};
1631 struct ip_mreq mreq = {.imr_multiaddr.s_addr = addr->sin_addr.s_addr,
1632 .imr_interface.s_addr = ntohl(INADDR_ANY)};
1635 if (setsockopt(se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF, &mreq,
1636 sizeof(mreq)) != 0) {
1637 ERROR("network plugin: setsockopt (ipv4-multicast-if): %s", STRERRNO);
1643 } else if (ai->ai_family == AF_INET6) {
1644 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1646 if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr)) {
1647 if (setsockopt(se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1648 &se->interface, sizeof(se->interface)) != 0) {
1649 ERROR("network plugin: setsockopt (ipv6-multicast-if): %s", STRERRNO);
1657 /* else: Not a multicast interface. */
1658 if (se->interface != 0) {
1659 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && \
1660 defined(SO_BINDTODEVICE)
1661 char interface_name[IFNAMSIZ];
1663 if (if_indextoname(se->interface, interface_name) == NULL)
1666 DEBUG("network plugin: Binding socket to interface %s", interface_name);
1668 if (setsockopt(se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1669 interface_name, sizeof(interface_name)) == -1) {
1670 ERROR("network plugin: setsockopt (bind-if): %s", STRERRNO);
1673 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1676 WARNING("network plugin: Cannot set the interface on a unicast "
1678 #if !defined(SO_BINDTODEVICE)
1679 "the \"SO_BINDTODEVICE\" socket option "
1681 "the \"if_indextoname\" function "
1683 "is not available on your system.");
1688 } /* }}} network_set_interface */
1690 static int network_bind_socket_to_addr(sockent_t *se,
1691 const struct addrinfo *ai) {
1693 if (se->data.client.bind_addr == NULL)
1696 DEBUG("network_plugin: fd %i: bind socket to address", se->data.client.fd);
1699 if (ai->ai_family == AF_INET) {
1700 struct sockaddr_in *addr =
1701 (struct sockaddr_in *)(se->data.client.bind_addr);
1702 inet_ntop(AF_INET, &(addr->sin_addr), pbuffer, 64);
1703 DEBUG("network_plugin: binding client socket to ipv4 address: %s", pbuffer);
1704 if (bind(se->data.client.fd, (struct sockaddr *)addr, sizeof(*addr)) ==
1706 ERROR("network plugin: failed to bind client socket (ipv4) to %s: %s",
1710 } else if (ai->ai_family == AF_INET6) {
1711 struct sockaddr_in6 *addr =
1712 (struct sockaddr_in6 *)(se->data.client.bind_addr);
1713 inet_ntop(AF_INET6, &(addr->sin6_addr), pbuffer, 64);
1714 DEBUG("network_plugin: binding client socket to ipv6 address: %s", pbuffer);
1715 if (bind(se->data.client.fd, (struct sockaddr *)addr, sizeof(*addr)) ==
1717 ERROR("network plugin: failed to bind client socket (ipv6) to %s: %s",
1724 } /* int network_bind_socket_to_addr */
1726 static int network_bind_socket(int fd, const struct addrinfo *ai,
1727 const int interface_idx) {
1734 /* allow multiple sockets to use the same PORT number */
1735 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) == -1) {
1736 ERROR("network plugin: setsockopt (reuseaddr): %s", STRERRNO);
1740 DEBUG("fd = %i; calling `bind'", fd);
1742 if (bind(fd, ai->ai_addr, ai->ai_addrlen) == -1) {
1743 ERROR("bind: %s", STRERRNO);
1747 if (ai->ai_family == AF_INET) {
1748 struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1749 if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr))) {
1750 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1751 struct ip_mreqn mreq;
1753 struct ip_mreq mreq;
1756 DEBUG("fd = %i; IPv4 multicast address found", fd);
1758 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1759 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1760 /* Set the interface using the interface index if
1761 * possible (available). Unfortunately, the struct
1762 * ip_mreqn is not portable. */
1763 mreq.imr_address.s_addr = ntohl(INADDR_ANY);
1764 mreq.imr_ifindex = interface_idx;
1766 mreq.imr_interface.s_addr = ntohl(INADDR_ANY);
1769 if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) ==
1771 ERROR("network plugin: setsockopt (multicast-loop): %s", STRERRNO);
1775 if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) ==
1777 ERROR("network plugin: setsockopt (add-membership): %s", STRERRNO);
1783 } else if (ai->ai_family == AF_INET6) {
1785 * http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1786 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1787 if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr)) {
1788 struct ipv6_mreq mreq;
1790 DEBUG("fd = %i; IPv6 multicast address found", fd);
1792 memcpy(&mreq.ipv6mr_multiaddr, &addr->sin6_addr, sizeof(addr->sin6_addr));
1794 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1795 * ipv6mr_interface may be set to zeroes to
1796 * choose the default multicast interface or to
1797 * the index of a particular multicast-capable
1798 * interface if the host is multihomed.
1799 * Membership is associ-associated with a
1800 * single interface; programs running on
1801 * multihomed hosts may need to join the same
1802 * group on more than one interface.*/
1803 mreq.ipv6mr_interface = interface_idx;
1805 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop,
1806 sizeof(loop)) == -1) {
1807 ERROR("network plugin: setsockopt (ipv6-multicast-loop): %s", STRERRNO);
1811 if (setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq,
1812 sizeof(mreq)) == -1) {
1813 ERROR("network plugin: setsockopt (ipv6-add-membership): %s", STRERRNO);
1821 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && \
1822 defined(SO_BINDTODEVICE)
1823 /* if a specific interface was set, bind the socket to it. But to avoid
1824 * possible problems with multicast routing, only do that for non-multicast
1826 if (interface_idx != 0) {
1827 char interface_name[IFNAMSIZ];
1829 if (if_indextoname(interface_idx, interface_name) == NULL)
1832 DEBUG("fd = %i; Binding socket to interface %s", fd, interface_name);
1834 if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, interface_name,
1835 sizeof(interface_name)) == -1) {
1836 ERROR("network plugin: setsockopt (bind-if): %s", STRERRNO);
1840 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1843 } /* int network_bind_socket */
1845 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1846 * or `SOCKENT_TYPE_SERVER' */
1847 static sockent_t *sockent_create(int type) /* {{{ */
1851 if ((type != SOCKENT_TYPE_CLIENT) && (type != SOCKENT_TYPE_SERVER))
1854 se = calloc(1, sizeof(*se));
1863 pthread_mutex_init(&se->lock, NULL);
1865 if (type == SOCKENT_TYPE_SERVER) {
1866 se->data.server.fd = NULL;
1867 se->data.server.fd_num = 0;
1869 se->data.server.security_level = SECURITY_LEVEL_NONE;
1870 se->data.server.auth_file = NULL;
1871 se->data.server.userdb = NULL;
1872 se->data.server.cypher = NULL;
1875 se->data.client.fd = -1;
1876 se->data.client.addr = NULL;
1877 se->data.client.bind_addr = NULL;
1878 se->data.client.resolve_interval = 0;
1879 se->data.client.next_resolve_reconnect = 0;
1881 se->data.client.security_level = SECURITY_LEVEL_NONE;
1882 se->data.client.username = NULL;
1883 se->data.client.password = NULL;
1884 se->data.client.cypher = NULL;
1889 } /* }}} sockent_t *sockent_create */
1891 static int sockent_init_crypto(sockent_t *se) /* {{{ */
1893 #if HAVE_GCRYPT_H /* {{{ */
1894 if (se->type == SOCKENT_TYPE_CLIENT) {
1895 if (se->data.client.security_level > SECURITY_LEVEL_NONE) {
1896 if (network_init_gcrypt() < 0) {
1897 ERROR("network plugin: Cannot configure client socket with "
1898 "security: Failed to initialize crypto library.");
1902 if ((se->data.client.username == NULL) ||
1903 (se->data.client.password == NULL)) {
1904 ERROR("network plugin: Client socket with "
1905 "security requested, but no "
1906 "credentials are configured.");
1909 gcry_md_hash_buffer(GCRY_MD_SHA256, se->data.client.password_hash,
1910 se->data.client.password,
1911 strlen(se->data.client.password));
1913 } else /* (se->type == SOCKENT_TYPE_SERVER) */
1915 if ((se->data.server.security_level > SECURITY_LEVEL_NONE) &&
1916 (se->data.server.auth_file == NULL)) {
1917 ERROR("network plugin: Server socket with security requested, "
1918 "but no \"AuthFile\" is configured.");
1921 if (se->data.server.auth_file != NULL) {
1922 if (network_init_gcrypt() < 0) {
1923 ERROR("network plugin: Cannot configure server socket with security: "
1924 "Failed to initialize crypto library.");
1928 se->data.server.userdb = fbh_create(se->data.server.auth_file);
1929 if (se->data.server.userdb == NULL) {
1930 ERROR("network plugin: Reading password file \"%s\" failed.",
1931 se->data.server.auth_file);
1936 #endif /* }}} HAVE_GCRYPT_H */
1939 } /* }}} int sockent_init_crypto */
1941 static int sockent_client_disconnect(sockent_t *se) /* {{{ */
1943 struct sockent_client *client;
1945 if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
1948 client = &se->data.client;
1949 if (client->fd >= 0) /* connected */
1955 DEBUG("network plugin: free (se = %p, addr = %p);", (void *)se,
1956 (void *)client->addr);
1957 sfree(client->addr);
1958 client->addrlen = 0;
1961 } /* }}} int sockent_client_disconnect */
1963 static int sockent_client_connect(sockent_t *se) /* {{{ */
1965 static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
1967 struct sockent_client *client;
1968 struct addrinfo *ai_list;
1970 bool reconnect = false;
1973 if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
1976 client = &se->data.client;
1979 if (client->resolve_interval != 0 && client->next_resolve_reconnect < now) {
1980 DEBUG("network plugin: Reconnecting socket, resolve_interval = %lf, "
1981 "next_resolve_reconnect = %lf",
1982 CDTIME_T_TO_DOUBLE(client->resolve_interval),
1983 CDTIME_T_TO_DOUBLE(client->next_resolve_reconnect));
1987 if (client->fd >= 0 && !reconnect) /* already connected and not stale*/
1990 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
1991 .ai_flags = AI_ADDRCONFIG,
1992 .ai_protocol = IPPROTO_UDP,
1993 .ai_socktype = SOCK_DGRAM};
1995 status = getaddrinfo(se->node,
1996 (se->service != NULL) ? se->service : NET_DEFAULT_PORT,
1997 &ai_hints, &ai_list);
2000 LOG_ERR, &complaint, "network plugin: getaddrinfo (%s, %s) failed: %s",
2001 (se->node == NULL) ? "(null)" : se->node,
2002 (se->service == NULL) ? "(null)" : se->service, gai_strerror(status));
2005 c_release(LOG_NOTICE, &complaint,
2006 "network plugin: Successfully resolved \"%s\".", se->node);
2009 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
2010 ai_ptr = ai_ptr->ai_next) {
2011 if (client->fd >= 0) /* when we reconnect */
2012 sockent_client_disconnect(se);
2015 socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
2016 if (client->fd < 0) {
2017 ERROR("network plugin: socket(2) failed: %s", STRERRNO);
2021 client->addr = calloc(1, sizeof(*client->addr));
2022 if (client->addr == NULL) {
2023 ERROR("network plugin: calloc failed.");
2028 DEBUG("network plugin: alloc (se = %p, addr = %p);", (void *)se,
2029 (void *)client->addr);
2031 assert(sizeof(*client->addr) >= ai_ptr->ai_addrlen);
2032 memcpy(client->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2033 client->addrlen = ai_ptr->ai_addrlen;
2035 network_set_ttl(se, ai_ptr);
2036 network_set_interface(se, ai_ptr);
2037 network_bind_socket_to_addr(se, ai_ptr);
2039 /* We don't open more than one write-socket per
2040 * node/service pair.. */
2044 freeaddrinfo(ai_list);
2048 if (client->resolve_interval > 0)
2049 client->next_resolve_reconnect = now + client->resolve_interval;
2051 } /* }}} int sockent_client_connect */
2053 /* Open the file descriptors for a initialized sockent structure. */
2054 static int sockent_server_listen(sockent_t *se) /* {{{ */
2056 struct addrinfo *ai_list;
2060 const char *service;
2065 assert(se->data.server.fd == NULL);
2066 assert(se->data.server.fd_num == 0);
2069 service = se->service;
2071 if (service == NULL)
2072 service = NET_DEFAULT_PORT;
2074 DEBUG("network plugin: sockent_server_listen: node = %s; service = %s;", node,
2077 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
2078 .ai_flags = AI_ADDRCONFIG | AI_PASSIVE,
2079 .ai_protocol = IPPROTO_UDP,
2080 .ai_socktype = SOCK_DGRAM};
2082 status = getaddrinfo(node, service, &ai_hints, &ai_list);
2084 ERROR("network plugin: getaddrinfo (%s, %s) failed: %s",
2085 (se->node == NULL) ? "(null)" : se->node,
2086 (se->service == NULL) ? "(null)" : se->service, gai_strerror(status));
2090 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
2091 ai_ptr = ai_ptr->ai_next) {
2094 tmp = realloc(se->data.server.fd,
2095 sizeof(*tmp) * (se->data.server.fd_num + 1));
2097 ERROR("network plugin: realloc failed.");
2100 se->data.server.fd = tmp;
2101 tmp = se->data.server.fd + se->data.server.fd_num;
2103 *tmp = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
2105 ERROR("network plugin: socket(2) failed: %s", STRERRNO);
2109 status = network_bind_socket(*tmp, ai_ptr, se->interface);
2116 se->data.server.fd_num++;
2118 } /* for (ai_list) */
2120 freeaddrinfo(ai_list);
2122 if (se->data.server.fd_num == 0)
2125 } /* }}} int sockent_server_listen */
2127 /* Add a sockent to the global list of sockets */
2128 static int sockent_add(sockent_t *se) /* {{{ */
2130 sockent_t *last_ptr;
2135 if (se->type == SOCKENT_TYPE_SERVER) {
2138 tmp = realloc(listen_sockets_pollfd,
2139 sizeof(*tmp) * (listen_sockets_num + se->data.server.fd_num));
2141 ERROR("network plugin: realloc failed.");
2144 listen_sockets_pollfd = tmp;
2145 tmp = listen_sockets_pollfd + listen_sockets_num;
2147 for (size_t i = 0; i < se->data.server.fd_num; i++) {
2148 memset(tmp + i, 0, sizeof(*tmp));
2149 tmp[i].fd = se->data.server.fd[i];
2150 tmp[i].events = POLLIN | POLLPRI;
2154 listen_sockets_num += se->data.server.fd_num;
2156 if (listen_sockets == NULL) {
2157 listen_sockets = se;
2160 last_ptr = listen_sockets;
2161 } else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2163 if (sending_sockets == NULL) {
2164 sending_sockets = se;
2167 last_ptr = sending_sockets;
2170 while (last_ptr->next != NULL)
2171 last_ptr = last_ptr->next;
2172 last_ptr->next = se;
2175 } /* }}} int sockent_add */
2177 static void *dispatch_thread(void __attribute__((unused)) * arg) /* {{{ */
2180 receive_list_entry_t *ent;
2183 /* Lock and wait for more data to come in */
2184 pthread_mutex_lock(&receive_list_lock);
2185 while ((listen_loop == 0) && (receive_list_head == NULL))
2186 pthread_cond_wait(&receive_list_cond, &receive_list_lock);
2188 /* Remove the head entry and unlock */
2189 ent = receive_list_head;
2191 receive_list_head = ent->next;
2192 receive_list_length--;
2193 pthread_mutex_unlock(&receive_list_lock);
2195 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2196 * because we dispatch all missing packets before shutting down. */
2200 /* Look for the correct `sockent_t' */
2201 se = listen_sockets;
2202 while (se != NULL) {
2205 for (i = 0; i < se->data.server.fd_num; i++)
2206 if (se->data.server.fd[i] == ent->fd)
2209 if (i < se->data.server.fd_num)
2216 ERROR("network plugin: Got packet from FD %i, but can't "
2217 "find an appropriate socket entry.",
2224 parse_packet(se, ent->data, ent->data_len, /* flags = */ 0,
2225 /* username = */ NULL);
2231 } /* }}} void *dispatch_thread */
2233 static int network_receive(void) /* {{{ */
2235 char buffer[network_config_packet_size];
2240 receive_list_entry_t *private_list_head;
2241 receive_list_entry_t *private_list_tail;
2242 uint64_t private_list_length;
2244 assert(listen_sockets_num > 0);
2246 private_list_head = NULL;
2247 private_list_tail = NULL;
2248 private_list_length = 0;
2250 while (listen_loop == 0) {
2251 status = poll(listen_sockets_pollfd, listen_sockets_num, -1);
2255 ERROR("network plugin: poll(2) failed: %s", STRERRNO);
2259 for (size_t i = 0; (i < listen_sockets_num) && (status > 0); i++) {
2260 receive_list_entry_t *ent;
2262 if ((listen_sockets_pollfd[i].revents & (POLLIN | POLLPRI)) == 0)
2266 buffer_len = recv(listen_sockets_pollfd[i].fd, buffer, sizeof(buffer),
2268 if (buffer_len < 0) {
2269 status = (errno != 0) ? errno : -1;
2270 ERROR("network plugin: recv(2) failed: %s", STRERRNO);
2274 stats_octets_rx += ((uint64_t)buffer_len);
2277 /* TODO: Possible performance enhancement: Do not free
2278 * these entries in the dispatch thread but put them in
2279 * another list, so we don't have to allocate more and
2280 * more of these structures. */
2281 ent = calloc(1, sizeof(*ent));
2283 ERROR("network plugin: calloc failed.");
2288 ent->data = malloc(network_config_packet_size);
2289 if (ent->data == NULL) {
2291 ERROR("network plugin: malloc failed.");
2295 ent->fd = listen_sockets_pollfd[i].fd;
2298 memcpy(ent->data, buffer, buffer_len);
2299 ent->data_len = buffer_len;
2301 if (private_list_head == NULL)
2302 private_list_head = ent;
2304 private_list_tail->next = ent;
2305 private_list_tail = ent;
2306 private_list_length++;
2308 /* Do not block here. Blocking here has led to
2309 * insufficient performance in the past. */
2310 if (pthread_mutex_trylock(&receive_list_lock) == 0) {
2311 assert(((receive_list_head == NULL) && (receive_list_length == 0)) ||
2312 ((receive_list_head != NULL) && (receive_list_length != 0)));
2314 if (receive_list_head == NULL)
2315 receive_list_head = private_list_head;
2317 receive_list_tail->next = private_list_head;
2318 receive_list_tail = private_list_tail;
2319 receive_list_length += private_list_length;
2321 pthread_cond_signal(&receive_list_cond);
2322 pthread_mutex_unlock(&receive_list_lock);
2324 private_list_head = NULL;
2325 private_list_tail = NULL;
2326 private_list_length = 0;
2330 } /* for (listen_sockets_pollfd) */
2334 } /* while (listen_loop == 0) */
2336 /* Make sure everything is dispatched before exiting. */
2337 if (private_list_head != NULL) {
2338 pthread_mutex_lock(&receive_list_lock);
2340 if (receive_list_head == NULL)
2341 receive_list_head = private_list_head;
2343 receive_list_tail->next = private_list_head;
2344 receive_list_tail = private_list_tail;
2345 receive_list_length += private_list_length;
2347 pthread_cond_signal(&receive_list_cond);
2348 pthread_mutex_unlock(&receive_list_lock);
2352 } /* }}} int network_receive */
2354 static void *receive_thread(void __attribute__((unused)) * arg) {
2355 return network_receive() ? (void *)1 : (void *)0;
2356 } /* void *receive_thread */
2358 static void network_init_buffer(void) {
2359 memset(send_buffer, 0, network_config_packet_size);
2360 send_buffer_ptr = send_buffer;
2361 send_buffer_fill = 0;
2362 send_buffer_last_update = 0;
2364 memset(&send_buffer_vl, 0, sizeof(send_buffer_vl));
2365 } /* int network_init_buffer */
2367 static void network_send_buffer_plain(sockent_t *se, /* {{{ */
2368 const char *buffer, size_t buffer_size) {
2372 status = sockent_client_connect(se);
2376 status = sendto(se->data.client.fd, buffer, buffer_size,
2377 /* flags = */ 0, (struct sockaddr *)se->data.client.addr,
2378 se->data.client.addrlen);
2380 if ((errno == EINTR) || (errno == EAGAIN))
2383 ERROR("network plugin: sendto failed: %s. Closing sending socket.",
2385 sockent_client_disconnect(se);
2391 } /* }}} void network_send_buffer_plain */
2394 #define BUFFER_ADD(p, s) \
2396 memcpy(buffer + buffer_offset, (p), (s)); \
2397 buffer_offset += (s); \
2400 static void network_send_buffer_signed(sockent_t *se, /* {{{ */
2401 const char *in_buffer,
2402 size_t in_buffer_size) {
2403 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2404 size_t buffer_offset;
2405 size_t username_len;
2409 unsigned char *hash;
2412 err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2414 ERROR("network plugin: Creating HMAC object failed: %s",
2415 gcry_strerror(err));
2419 err = gcry_md_setkey(hd, se->data.client.password,
2420 strlen(se->data.client.password));
2422 ERROR("network plugin: gcry_md_setkey failed: %s", gcry_strerror(err));
2427 username_len = strlen(se->data.client.username);
2428 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE)) {
2429 ERROR("network plugin: Username too long: %s", se->data.client.username);
2433 memcpy(buffer + PART_SIGNATURE_SHA256_SIZE, se->data.client.username,
2435 memcpy(buffer + PART_SIGNATURE_SHA256_SIZE + username_len, in_buffer,
2438 /* Initialize the `ps' structure. */
2439 part_signature_sha256_t ps = {
2440 .head.type = htons(TYPE_SIGN_SHA256),
2441 .head.length = htons(PART_SIGNATURE_SHA256_SIZE + username_len)};
2443 /* Calculate the hash value. */
2444 gcry_md_write(hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2445 username_len + in_buffer_size);
2446 hash = gcry_md_read(hd, GCRY_MD_SHA256);
2448 ERROR("network plugin: gcry_md_read failed.");
2452 memcpy(ps.hash, hash, sizeof(ps.hash));
2454 /* Add the header */
2457 BUFFER_ADD(&ps.head.type, sizeof(ps.head.type));
2458 BUFFER_ADD(&ps.head.length, sizeof(ps.head.length));
2459 BUFFER_ADD(ps.hash, sizeof(ps.hash));
2461 assert(buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2466 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2467 network_send_buffer_plain(se, buffer, buffer_offset);
2468 } /* }}} void network_send_buffer_signed */
2470 static void network_send_buffer_encrypted(sockent_t *se, /* {{{ */
2471 const char *in_buffer,
2472 size_t in_buffer_size) {
2473 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2475 size_t buffer_offset;
2477 size_t username_len;
2479 gcry_cipher_hd_t cypher;
2481 /* Initialize the header fields */
2482 part_encryption_aes256_t pea = {.head.type = htons(TYPE_ENCR_AES256),
2483 .username = se->data.client.username};
2485 username_len = strlen(pea.username);
2486 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE) {
2487 ERROR("network plugin: Username too long: %s", pea.username);
2491 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2492 header_size = PART_ENCRYPTION_AES256_SIZE + username_len - sizeof(pea.hash);
2494 assert(buffer_size <= sizeof(buffer));
2495 DEBUG("network plugin: network_send_buffer_encrypted: "
2496 "buffer_size = %" PRIsz ";",
2499 pea.head.length = htons(
2500 (uint16_t)(PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size));
2501 pea.username_length = htons((uint16_t)username_len);
2503 /* Chose a random initialization vector. */
2504 gcry_randomize((void *)&pea.iv, sizeof(pea.iv), GCRY_STRONG_RANDOM);
2506 /* Create hash of the payload */
2507 gcry_md_hash_buffer(GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2509 /* Initialize the buffer */
2511 memset(buffer, 0, sizeof(buffer));
2513 BUFFER_ADD(&pea.head.type, sizeof(pea.head.type));
2514 BUFFER_ADD(&pea.head.length, sizeof(pea.head.length));
2515 BUFFER_ADD(&pea.username_length, sizeof(pea.username_length));
2516 BUFFER_ADD(pea.username, username_len);
2517 BUFFER_ADD(pea.iv, sizeof(pea.iv));
2518 assert(buffer_offset == header_size);
2519 BUFFER_ADD(pea.hash, sizeof(pea.hash));
2520 BUFFER_ADD(in_buffer, in_buffer_size);
2522 assert(buffer_offset == buffer_size);
2524 cypher = network_get_aes256_cypher(se, pea.iv, sizeof(pea.iv),
2525 se->data.client.password);
2529 /* Encrypt the buffer in-place */
2530 err = gcry_cipher_encrypt(cypher, buffer + header_size,
2531 buffer_size - header_size,
2532 /* in = */ NULL, /* in len = */ 0);
2534 ERROR("network plugin: gcry_cipher_encrypt returned: %s",
2535 gcry_strerror(err));
2539 /* Send it out without further modifications */
2540 network_send_buffer_plain(se, buffer, buffer_size);
2541 } /* }}} void network_send_buffer_encrypted */
2543 #endif /* HAVE_GCRYPT_H */
2545 static void network_send_buffer(char *buffer, size_t buffer_len) /* {{{ */
2547 DEBUG("network plugin: network_send_buffer: buffer_len = %" PRIsz,
2550 for (sockent_t *se = sending_sockets; se != NULL; se = se->next) {
2551 pthread_mutex_lock(&se->lock);
2553 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2554 network_send_buffer_encrypted(se, buffer, buffer_len);
2555 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2556 network_send_buffer_signed(se, buffer, buffer_len);
2557 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2558 #endif /* HAVE_GCRYPT_H */
2559 network_send_buffer_plain(se, buffer, buffer_len);
2560 pthread_mutex_unlock(&se->lock);
2561 } /* for (sending_sockets) */
2562 } /* }}} void network_send_buffer */
2564 static int add_to_buffer(char *buffer, size_t buffer_size, /* {{{ */
2565 value_list_t *vl_def, const data_set_t *ds,
2566 const value_list_t *vl) {
2567 char *buffer_orig = buffer;
2569 if (strcmp(vl_def->host, vl->host) != 0) {
2570 if (write_part_string(&buffer, &buffer_size, TYPE_HOST, vl->host,
2571 strlen(vl->host)) != 0)
2573 sstrncpy(vl_def->host, vl->host, sizeof(vl_def->host));
2576 if (vl_def->time != vl->time) {
2577 if (write_part_number(&buffer, &buffer_size, TYPE_TIME_HR,
2578 (uint64_t)vl->time))
2580 vl_def->time = vl->time;
2583 if (vl_def->interval != vl->interval) {
2584 if (write_part_number(&buffer, &buffer_size, TYPE_INTERVAL_HR,
2585 (uint64_t)vl->interval))
2587 vl_def->interval = vl->interval;
2590 if (strcmp(vl_def->plugin, vl->plugin) != 0) {
2591 if (write_part_string(&buffer, &buffer_size, TYPE_PLUGIN, vl->plugin,
2592 strlen(vl->plugin)) != 0)
2594 sstrncpy(vl_def->plugin, vl->plugin, sizeof(vl_def->plugin));
2597 if (strcmp(vl_def->plugin_instance, vl->plugin_instance) != 0) {
2598 if (write_part_string(&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2599 vl->plugin_instance,
2600 strlen(vl->plugin_instance)) != 0)
2602 sstrncpy(vl_def->plugin_instance, vl->plugin_instance,
2603 sizeof(vl_def->plugin_instance));
2606 if (strcmp(vl_def->type, vl->type) != 0) {
2607 if (write_part_string(&buffer, &buffer_size, TYPE_TYPE, vl->type,
2608 strlen(vl->type)) != 0)
2610 sstrncpy(vl_def->type, ds->type, sizeof(vl_def->type));
2613 if (strcmp(vl_def->type_instance, vl->type_instance) != 0) {
2614 if (write_part_string(&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2615 vl->type_instance, strlen(vl->type_instance)) != 0)
2617 sstrncpy(vl_def->type_instance, vl->type_instance,
2618 sizeof(vl_def->type_instance));
2621 if (write_part_values(&buffer, &buffer_size, ds, vl) != 0)
2624 return buffer - buffer_orig;
2625 } /* }}} int add_to_buffer */
2627 static void flush_buffer(void) {
2628 DEBUG("network plugin: flush_buffer: send_buffer_fill = %i",
2631 network_send_buffer(send_buffer, (size_t)send_buffer_fill);
2633 stats_octets_tx += ((uint64_t)send_buffer_fill);
2636 network_init_buffer();
2639 static int network_write(const data_set_t *ds, const value_list_t *vl,
2640 user_data_t __attribute__((unused)) * user_data) {
2643 /* listen_loop is set to non-zero in the shutdown callback, which is
2644 * guaranteed to be called *after* all the write threads have been shut
2646 assert(listen_loop == 0);
2648 if (!check_send_okay(vl)) {
2650 char name[6 * DATA_MAX_NAME_LEN];
2651 FORMAT_VL(name, sizeof(name), vl);
2652 name[sizeof(name) - 1] = '\0';
2653 DEBUG("network plugin: network_write: "
2657 /* Counter is not protected by another lock and may be reached by
2658 * multiple threads */
2659 pthread_mutex_lock(&stats_lock);
2660 stats_values_not_sent++;
2661 pthread_mutex_unlock(&stats_lock);
2665 uc_meta_data_add_unsigned_int(vl, "network:time_sent", (uint64_t)vl->time);
2667 pthread_mutex_lock(&send_buffer_lock);
2669 status = add_to_buffer(send_buffer_ptr,
2670 network_config_packet_size -
2671 (send_buffer_fill + BUFF_SIG_SIZE),
2672 &send_buffer_vl, ds, vl);
2674 /* status == bytes added to the buffer */
2675 send_buffer_fill += status;
2676 send_buffer_ptr += status;
2677 send_buffer_last_update = cdtime();
2679 stats_values_sent++;
2683 status = add_to_buffer(send_buffer_ptr,
2684 network_config_packet_size -
2685 (send_buffer_fill + BUFF_SIG_SIZE),
2686 &send_buffer_vl, ds, vl);
2689 send_buffer_fill += status;
2690 send_buffer_ptr += status;
2692 stats_values_sent++;
2697 ERROR("network plugin: Unable to append to the "
2698 "buffer for some weird reason");
2699 } else if ((network_config_packet_size - send_buffer_fill) < 15) {
2703 pthread_mutex_unlock(&send_buffer_lock);
2705 return (status < 0) ? -1 : 0;
2706 } /* int network_write */
2708 static int network_config_set_ttl(const oconfig_item_t *ci) /* {{{ */
2712 if (cf_util_get_int(ci, &tmp) != 0)
2714 else if ((tmp > 0) && (tmp <= 255))
2715 network_config_ttl = tmp;
2717 WARNING("network plugin: The `TimeToLive' must be between 1 and 255.");
2722 } /* }}} int network_config_set_ttl */
2724 static int network_config_set_interface(const oconfig_item_t *ci, /* {{{ */
2728 if (cf_util_get_string_buffer(ci, if_name, sizeof(if_name)) != 0)
2731 *interface = if_nametoindex(if_name);
2733 } /* }}} int network_config_set_interface */
2736 network_config_set_bind_address(const oconfig_item_t *ci,
2737 struct sockaddr_storage **bind_address) {
2738 if ((*bind_address) != NULL) {
2739 ERROR("network_plugin: only a single bind address is allowed");
2743 char addr_text[256];
2745 if (cf_util_get_string_buffer(ci, addr_text, sizeof(addr_text)) != 0)
2749 struct addrinfo *res = NULL;
2750 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
2751 .ai_flags = AI_NUMERICHOST,
2752 .ai_protocol = IPPROTO_UDP,
2753 .ai_socktype = SOCK_DGRAM};
2755 ret = getaddrinfo(addr_text, NULL, &ai_hints, &res);
2757 ERROR("network plugin: Bind address option has invalid address set: %s",
2762 *bind_address = malloc(sizeof(**bind_address));
2763 if (*bind_address == NULL) {
2764 ERROR("network plugin: network_config_set_bind_address: malloc failed.");
2767 (*bind_address)->ss_family = res->ai_family;
2768 if (res->ai_family == AF_INET) {
2769 struct sockaddr_in *addr = (struct sockaddr_in *)(*bind_address);
2770 inet_pton(AF_INET, addr_text, &(addr->sin_addr));
2771 } else if (res->ai_family == AF_INET6) {
2772 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)(*bind_address);
2773 inet_pton(AF_INET6, addr_text, &(addr->sin6_addr));
2775 ERROR("network plugin: %s is an unknown address format %d\n", addr_text,
2777 sfree(*bind_address);
2784 } /* int network_config_set_bind_address */
2786 static int network_config_set_buffer_size(const oconfig_item_t *ci) /* {{{ */
2790 if (cf_util_get_int(ci, &tmp) != 0)
2792 else if ((tmp >= 1024) && (tmp <= 65535))
2793 network_config_packet_size = tmp;
2796 "network plugin: The `MaxPacketSize' must be between 1024 and 65535.");
2801 } /* }}} int network_config_set_buffer_size */
2804 static int network_config_set_security_level(oconfig_item_t *ci, /* {{{ */
2807 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
2808 WARNING("network plugin: The `SecurityLevel' config option needs exactly "
2809 "one string argument.");
2813 str = ci->values[0].value.string;
2814 if (strcasecmp("Encrypt", str) == 0)
2815 *retval = SECURITY_LEVEL_ENCRYPT;
2816 else if (strcasecmp("Sign", str) == 0)
2817 *retval = SECURITY_LEVEL_SIGN;
2818 else if (strcasecmp("None", str) == 0)
2819 *retval = SECURITY_LEVEL_NONE;
2821 WARNING("network plugin: Unknown security level: %s.", str);
2826 } /* }}} int network_config_set_security_level */
2827 #endif /* HAVE_GCRYPT_H */
2829 static int network_config_add_listen(const oconfig_item_t *ci) /* {{{ */
2834 if ((ci->values_num < 1) || (ci->values_num > 2) ||
2835 (ci->values[0].type != OCONFIG_TYPE_STRING) ||
2836 ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING))) {
2837 ERROR("network plugin: The `%s' config option needs "
2838 "one or two string arguments.",
2843 se = sockent_create(SOCKENT_TYPE_SERVER);
2845 ERROR("network plugin: sockent_create failed.");
2849 se->node = strdup(ci->values[0].value.string);
2850 if (ci->values_num >= 2)
2851 se->service = strdup(ci->values[1].value.string);
2853 for (int i = 0; i < ci->children_num; i++) {
2854 oconfig_item_t *child = ci->children + i;
2857 if (strcasecmp("AuthFile", child->key) == 0)
2858 cf_util_get_string(child, &se->data.server.auth_file);
2859 else if (strcasecmp("SecurityLevel", child->key) == 0)
2860 network_config_set_security_level(child, &se->data.server.security_level);
2862 #endif /* HAVE_GCRYPT_H */
2863 if (strcasecmp("Interface", child->key) == 0)
2864 network_config_set_interface(child, &se->interface);
2866 WARNING("network plugin: Option `%s' is not allowed here.", child->key);
2871 if ((se->data.server.security_level > SECURITY_LEVEL_NONE) &&
2872 (se->data.server.auth_file == NULL)) {
2873 ERROR("network plugin: A security level higher than `none' was "
2874 "requested, but no AuthFile option was given. Cowardly refusing to "
2875 "open this socket!");
2876 sockent_destroy(se);
2879 #endif /* HAVE_GCRYPT_H */
2881 status = sockent_init_crypto(se);
2883 ERROR("network plugin: network_config_add_listen: sockent_init_crypto() "
2885 sockent_destroy(se);
2889 status = sockent_server_listen(se);
2891 ERROR("network plugin: network_config_add_listen: sockent_server_listen "
2893 sockent_destroy(se);
2897 status = sockent_add(se);
2899 ERROR("network plugin: network_config_add_listen: sockent_add failed.");
2900 sockent_destroy(se);
2905 } /* }}} int network_config_add_listen */
2907 static int network_config_add_server(const oconfig_item_t *ci) /* {{{ */
2912 if ((ci->values_num < 1) || (ci->values_num > 2) ||
2913 (ci->values[0].type != OCONFIG_TYPE_STRING) ||
2914 ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING))) {
2915 ERROR("network plugin: The `%s' config option needs "
2916 "one or two string arguments.",
2921 se = sockent_create(SOCKENT_TYPE_CLIENT);
2923 ERROR("network plugin: sockent_create failed.");
2927 se->node = strdup(ci->values[0].value.string);
2928 if (ci->values_num >= 2)
2929 se->service = strdup(ci->values[1].value.string);
2931 for (int i = 0; i < ci->children_num; i++) {
2932 oconfig_item_t *child = ci->children + i;
2935 if (strcasecmp("Username", child->key) == 0)
2936 cf_util_get_string(child, &se->data.client.username);
2937 else if (strcasecmp("Password", child->key) == 0)
2938 cf_util_get_string(child, &se->data.client.password);
2939 else if (strcasecmp("SecurityLevel", child->key) == 0)
2940 network_config_set_security_level(child, &se->data.client.security_level);
2942 #endif /* HAVE_GCRYPT_H */
2943 if (strcasecmp("Interface", child->key) == 0)
2944 network_config_set_interface(child, &se->interface);
2945 else if (strcasecmp("BindAddress", child->key) == 0)
2946 network_config_set_bind_address(child, &se->data.client.bind_addr);
2947 else if (strcasecmp("ResolveInterval", child->key) == 0)
2948 cf_util_get_cdtime(child, &se->data.client.resolve_interval);
2950 WARNING("network plugin: Option `%s' is not allowed here.", child->key);
2955 if ((se->data.client.security_level > SECURITY_LEVEL_NONE) &&
2956 ((se->data.client.username == NULL) ||
2957 (se->data.client.password == NULL))) {
2958 ERROR("network plugin: A security level higher than `none' was "
2959 "requested, but no Username or Password option was given. "
2960 "Cowardly refusing to open this socket!");
2961 sockent_destroy(se);
2964 #endif /* HAVE_GCRYPT_H */
2966 status = sockent_init_crypto(se);
2968 ERROR("network plugin: network_config_add_server: sockent_init_crypto() "
2970 sockent_destroy(se);
2974 /* No call to sockent_client_connect() here -- it is called from
2975 * network_send_buffer_plain(). */
2977 status = sockent_add(se);
2979 ERROR("network plugin: network_config_add_server: sockent_add failed.");
2980 sockent_destroy(se);
2985 } /* }}} int network_config_add_server */
2987 static int network_config(oconfig_item_t *ci) /* {{{ */
2989 /* The options need to be applied first */
2990 for (int i = 0; i < ci->children_num; i++) {
2991 oconfig_item_t *child = ci->children + i;
2992 if (strcasecmp("TimeToLive", child->key) == 0)
2993 network_config_set_ttl(child);
2996 for (int i = 0; i < ci->children_num; i++) {
2997 oconfig_item_t *child = ci->children + i;
2999 if (strcasecmp("Listen", child->key) == 0)
3000 network_config_add_listen(child);
3001 else if (strcasecmp("Server", child->key) == 0)
3002 network_config_add_server(child);
3003 else if (strcasecmp("TimeToLive", child->key) == 0) {
3004 /* Handled earlier */
3005 } else if (strcasecmp("MaxPacketSize", child->key) == 0)
3006 network_config_set_buffer_size(child);
3007 else if (strcasecmp("Forward", child->key) == 0)
3008 cf_util_get_boolean(child, &network_config_forward);
3009 else if (strcasecmp("ReportStats", child->key) == 0)
3010 cf_util_get_boolean(child, &network_config_stats);
3012 WARNING("network plugin: Option `%s' is not allowed here.", child->key);
3017 } /* }}} int network_config */
3019 static int network_notification(const notification_t *n,
3020 user_data_t __attribute__((unused)) *
3022 char buffer[network_config_packet_size];
3023 char *buffer_ptr = buffer;
3024 size_t buffer_free = sizeof(buffer);
3027 if (!check_send_notify_okay(n))
3030 memset(buffer, 0, sizeof(buffer));
3032 status = write_part_number(&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3037 status = write_part_number(&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3038 (uint64_t)n->severity);
3042 if (strlen(n->host) > 0) {
3043 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_HOST, n->host,
3049 if (strlen(n->plugin) > 0) {
3050 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3051 n->plugin, strlen(n->plugin));
3056 if (strlen(n->plugin_instance) > 0) {
3057 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_PLUGIN_INSTANCE,
3058 n->plugin_instance, strlen(n->plugin_instance));
3063 if (strlen(n->type) > 0) {
3064 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_TYPE, n->type,
3070 if (strlen(n->type_instance) > 0) {
3071 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3072 n->type_instance, strlen(n->type_instance));
3077 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3078 n->message, strlen(n->message));
3082 network_send_buffer(buffer, sizeof(buffer) - buffer_free);
3085 } /* int network_notification */
3087 static int network_shutdown(void) {
3090 /* Kill the listening thread */
3091 if (receive_thread_running != 0) {
3092 INFO("network plugin: Stopping receive thread.");
3093 pthread_kill(receive_thread_id, SIGTERM);
3094 pthread_join(receive_thread_id, NULL /* no return value */);
3095 memset(&receive_thread_id, 0, sizeof(receive_thread_id));
3096 receive_thread_running = 0;
3099 /* Shutdown the dispatching thread */
3100 if (dispatch_thread_running != 0) {
3101 INFO("network plugin: Stopping dispatch thread.");
3102 pthread_mutex_lock(&receive_list_lock);
3103 pthread_cond_broadcast(&receive_list_cond);
3104 pthread_mutex_unlock(&receive_list_lock);
3105 pthread_join(dispatch_thread_id, /* ret = */ NULL);
3106 dispatch_thread_running = 0;
3109 sockent_destroy(listen_sockets);
3111 if (send_buffer_fill > 0)
3116 for (sockent_t *se = sending_sockets; se != NULL; se = se->next)
3117 sockent_client_disconnect(se);
3118 sockent_destroy(sending_sockets);
3120 plugin_unregister_config("network");
3121 plugin_unregister_init("network");
3122 plugin_unregister_write("network");
3123 plugin_unregister_shutdown("network");
3126 } /* int network_shutdown */
3128 static int network_stats_read(void) /* {{{ */
3130 derive_t copy_octets_rx;
3131 derive_t copy_octets_tx;
3132 derive_t copy_packets_rx;
3133 derive_t copy_packets_tx;
3134 derive_t copy_values_dispatched;
3135 derive_t copy_values_not_dispatched;
3136 derive_t copy_values_sent;
3137 derive_t copy_values_not_sent;
3138 derive_t copy_receive_list_length;
3139 value_list_t vl = VALUE_LIST_INIT;
3142 copy_octets_rx = stats_octets_rx;
3143 copy_octets_tx = stats_octets_tx;
3144 copy_packets_rx = stats_packets_rx;
3145 copy_packets_tx = stats_packets_tx;
3146 copy_values_dispatched = stats_values_dispatched;
3147 copy_values_not_dispatched = stats_values_not_dispatched;
3148 copy_values_sent = stats_values_sent;
3149 copy_values_not_sent = stats_values_not_sent;
3150 copy_receive_list_length = receive_list_length;
3152 /* Initialize `vl' */
3156 sstrncpy(vl.plugin, "network", sizeof(vl.plugin));
3158 /* Octets received / sent */
3159 vl.values[0].derive = (derive_t)copy_octets_rx;
3160 vl.values[1].derive = (derive_t)copy_octets_tx;
3161 sstrncpy(vl.type, "if_octets", sizeof(vl.type));
3162 plugin_dispatch_values(&vl);
3164 /* Packets received / send */
3165 vl.values[0].derive = (derive_t)copy_packets_rx;
3166 vl.values[1].derive = (derive_t)copy_packets_tx;
3167 sstrncpy(vl.type, "if_packets", sizeof(vl.type));
3168 plugin_dispatch_values(&vl);
3170 /* Values (not) dispatched and (not) send */
3171 sstrncpy(vl.type, "total_values", sizeof(vl.type));
3174 vl.values[0].derive = (derive_t)copy_values_dispatched;
3175 sstrncpy(vl.type_instance, "dispatch-accepted", sizeof(vl.type_instance));
3176 plugin_dispatch_values(&vl);
3178 vl.values[0].derive = (derive_t)copy_values_not_dispatched;
3179 sstrncpy(vl.type_instance, "dispatch-rejected", sizeof(vl.type_instance));
3180 plugin_dispatch_values(&vl);
3182 vl.values[0].derive = (derive_t)copy_values_sent;
3183 sstrncpy(vl.type_instance, "send-accepted", sizeof(vl.type_instance));
3184 plugin_dispatch_values(&vl);
3186 vl.values[0].derive = (derive_t)copy_values_not_sent;
3187 sstrncpy(vl.type_instance, "send-rejected", sizeof(vl.type_instance));
3188 plugin_dispatch_values(&vl);
3190 /* Receive queue length */
3191 vl.values[0].gauge = (gauge_t)copy_receive_list_length;
3192 sstrncpy(vl.type, "queue_length", sizeof(vl.type));
3193 vl.type_instance[0] = 0;
3194 plugin_dispatch_values(&vl);
3197 } /* }}} int network_stats_read */
3199 static int network_init(void) {
3200 static bool have_init;
3202 /* Check if we were already initialized. If so, just return - there's
3203 * nothing more to do (for now, that is). */
3208 if (network_config_stats)
3209 plugin_register_read("network", network_stats_read);
3211 plugin_register_shutdown("network", network_shutdown);
3213 send_buffer = malloc(network_config_packet_size);
3214 if (send_buffer == NULL) {
3215 ERROR("network plugin: malloc failed.");
3218 network_init_buffer();
3220 /* setup socket(s) and so on */
3221 if (sending_sockets != NULL) {
3222 plugin_register_write("network", network_write,
3223 /* user_data = */ NULL);
3224 plugin_register_notification("network", network_notification,
3225 /* user_data = */ NULL);
3228 /* If no threads need to be started, return here. */
3229 if ((listen_sockets_num == 0) ||
3230 ((dispatch_thread_running != 0) && (receive_thread_running != 0)))
3233 if (dispatch_thread_running == 0) {
3235 status = plugin_thread_create(&dispatch_thread_id, NULL /* no attributes */,
3236 dispatch_thread, NULL /* no argument */,
3239 ERROR("network: pthread_create failed: %s", STRERRNO);
3241 dispatch_thread_running = 1;
3245 if (receive_thread_running == 0) {
3247 status = plugin_thread_create(&receive_thread_id, NULL /* no attributes */,
3248 receive_thread, NULL /* no argument */,
3251 ERROR("network: pthread_create failed: %s", STRERRNO);
3253 receive_thread_running = 1;
3258 } /* int network_init */
3261 * The flush option of the network plugin cannot flush individual identifiers.
3262 * All the values are added to a buffer and sent when the buffer is full, the
3263 * requested value may or may not be in there, it's not worth finding out. We
3264 * just send the buffer if `flush' is called - if the requested value was in
3265 * there, good. If not, well, then there is nothing to flush.. -octo
3267 static int network_flush(cdtime_t timeout,
3268 __attribute__((unused)) const char *identifier,
3269 __attribute__((unused)) user_data_t *user_data) {
3270 pthread_mutex_lock(&send_buffer_lock);
3272 if (send_buffer_fill > 0) {
3274 cdtime_t now = cdtime();
3275 if ((send_buffer_last_update + timeout) > now) {
3276 pthread_mutex_unlock(&send_buffer_lock);
3282 pthread_mutex_unlock(&send_buffer_lock);
3285 } /* int network_flush */
3287 void module_register(void) {
3288 plugin_register_complex_config("network", network_config);
3289 plugin_register_init("network", network_init);
3290 plugin_register_flush("network", network_flush,
3291 /* user_data = */ NULL);
3292 } /* void module_register */