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;
118 struct sockent_server {
125 gcry_cipher_hd_t cypher;
129 typedef struct sockent {
130 #define SOCKENT_TYPE_CLIENT 1
131 #define SOCKENT_TYPE_SERVER 2
139 struct sockent_client client;
140 struct sockent_server server;
143 struct sockent *next;
146 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
147 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
148 * +-------+-----------------------+-------------------------------+
149 * ! Ver. ! ! Length !
150 * +-------+-----------------------+-------------------------------+
152 struct part_header_s {
156 typedef struct part_header_s part_header_t;
158 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
159 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
160 * +-------------------------------+-------------------------------+
162 * +-------------------------------+-------------------------------+
163 * : (Length - 4) Bytes :
164 * +---------------------------------------------------------------+
166 struct part_string_s {
170 typedef struct part_string_s part_string_t;
172 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
173 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
174 * +-------------------------------+-------------------------------+
176 * +-------------------------------+-------------------------------+
177 * : (Length - 4 == 2 || 4 || 8) Bytes :
178 * +---------------------------------------------------------------+
180 struct part_number_s {
184 typedef struct part_number_s part_number_t;
186 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
187 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
188 * +-------------------------------+-------------------------------+
190 * +-------------------------------+---------------+---------------+
191 * ! Num of values ! Type0 ! Type1 !
192 * +-------------------------------+---------------+---------------+
195 * +---------------------------------------------------------------+
198 * +---------------------------------------------------------------+
200 struct part_values_s {
202 uint16_t *num_values;
203 uint8_t *values_types;
206 typedef struct part_values_s part_values_t;
208 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
209 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
210 * +-------------------------------+-------------------------------+
212 * +-------------------------------+-------------------------------+
213 * ! Hash (Bits 0 - 31) !
215 * ! Hash (Bits 224 - 255) !
216 * +---------------------------------------------------------------+
219 #define PART_SIGNATURE_SHA256_SIZE 36
220 struct part_signature_sha256_s {
222 unsigned char hash[32];
225 typedef struct part_signature_sha256_s part_signature_sha256_t;
227 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
228 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
229 * +-------------------------------+-------------------------------+
231 * +-------------------------------+-------------------------------+
232 * ! Original length ! Padding (0 - 15 bytes) !
233 * +-------------------------------+-------------------------------+
234 * ! Hash (Bits 0 - 31) !
236 * ! Hash (Bits 128 - 159) !
237 * +---------------------------------------------------------------+
240 #define PART_ENCRYPTION_AES256_SIZE 42
241 struct part_encryption_aes256_s {
243 uint16_t username_length;
245 unsigned char iv[16];
247 unsigned char hash[20];
251 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
253 struct receive_list_entry_s {
257 struct receive_list_entry_s *next;
259 typedef struct receive_list_entry_s receive_list_entry_t;
264 static int network_config_ttl = 0;
265 /* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
266 static size_t network_config_packet_size = 1452;
267 static _Bool network_config_forward = 0;
268 static _Bool network_config_stats = 0;
270 static sockent_t *sending_sockets = NULL;
272 static receive_list_entry_t *receive_list_head = NULL;
273 static receive_list_entry_t *receive_list_tail = NULL;
274 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
275 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
276 static uint64_t receive_list_length = 0;
278 static sockent_t *listen_sockets = NULL;
279 static struct pollfd *listen_sockets_pollfd = NULL;
280 static size_t listen_sockets_num = 0;
282 /* The receive and dispatch threads will run as long as `listen_loop' is set to
284 static int listen_loop = 0;
285 static int receive_thread_running = 0;
286 static pthread_t receive_thread_id;
287 static int dispatch_thread_running = 0;
288 static pthread_t dispatch_thread_id;
290 /* Buffer in which to-be-sent network packets are constructed. */
291 static char *send_buffer;
292 static char *send_buffer_ptr;
293 static int send_buffer_fill;
294 static cdtime_t send_buffer_last_update;
295 static value_list_t send_buffer_vl = VALUE_LIST_INIT;
296 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
298 /* XXX: These counters are incremented from one place only. The spot in which
299 * the values are incremented is either only reachable by one thread (the
300 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
301 * example). Only if neither is true, the stats_lock is acquired. The counters
302 * are always read without holding a lock in the hope that writing 8 bytes to
303 * memory is an atomic operation. */
304 static derive_t stats_octets_rx = 0;
305 static derive_t stats_octets_tx = 0;
306 static derive_t stats_packets_rx = 0;
307 static derive_t stats_packets_tx = 0;
308 static derive_t stats_values_dispatched = 0;
309 static derive_t stats_values_not_dispatched = 0;
310 static derive_t stats_values_sent = 0;
311 static derive_t stats_values_not_sent = 0;
312 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
317 static _Bool check_receive_okay(const value_list_t *vl) /* {{{ */
319 uint64_t time_sent = 0;
322 status = uc_meta_data_get_unsigned_int(vl, "network:time_sent", &time_sent);
324 /* This is a value we already sent. Don't allow it to be received again in
325 * order to avoid looping. */
326 if ((status == 0) && (time_sent >= ((uint64_t)vl->time)))
330 } /* }}} _Bool check_receive_okay */
332 static _Bool check_send_okay(const value_list_t *vl) /* {{{ */
337 if (network_config_forward)
340 if (vl->meta == NULL)
343 status = meta_data_get_boolean(vl->meta, "network:received", &received);
344 if (status == -ENOENT)
346 else if (status != 0) {
347 ERROR("network plugin: check_send_okay: meta_data_get_boolean failed "
353 /* By default, only *send* value lists that were not *received* by the
356 } /* }}} _Bool check_send_okay */
358 static _Bool check_notify_received(const notification_t *n) /* {{{ */
360 for (notification_meta_t *ptr = n->meta; ptr != NULL; ptr = ptr->next)
361 if ((strcmp("network:received", ptr->name) == 0) &&
362 (ptr->type == NM_TYPE_BOOLEAN))
363 return (_Bool)ptr->nm_value.nm_boolean;
366 } /* }}} _Bool check_notify_received */
368 static _Bool check_send_notify_okay(const notification_t *n) /* {{{ */
370 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
376 received = check_notify_received(n);
378 if (network_config_forward && received) {
380 LOG_ERR, &complain_forwarding,
381 "network plugin: A notification has been received via the network "
382 "and forwarding is enabled. Forwarding of notifications is currently "
383 "not supported, because there is not loop-deteciton available. "
384 "Please contact the collectd mailing list if you need this "
388 /* By default, only *send* value lists that were not *received* by the
391 } /* }}} _Bool check_send_notify_okay */
393 static int network_dispatch_values(value_list_t *vl, /* {{{ */
394 const char *username) {
397 if ((vl->time == 0) || (strlen(vl->host) == 0) || (strlen(vl->plugin) == 0) ||
398 (strlen(vl->type) == 0))
401 if (!check_receive_okay(vl)) {
403 char name[6 * DATA_MAX_NAME_LEN];
404 FORMAT_VL(name, sizeof(name), vl);
405 name[sizeof(name) - 1] = 0;
406 DEBUG("network plugin: network_dispatch_values: "
407 "NOT dispatching %s.",
410 stats_values_not_dispatched++;
414 assert(vl->meta == NULL);
416 vl->meta = meta_data_create();
417 if (vl->meta == NULL) {
418 ERROR("network plugin: meta_data_create failed.");
422 status = meta_data_add_boolean(vl->meta, "network:received", 1);
424 ERROR("network plugin: meta_data_add_boolean failed.");
425 meta_data_destroy(vl->meta);
430 if (username != NULL) {
431 status = meta_data_add_string(vl->meta, "network:username", username);
433 ERROR("network plugin: meta_data_add_string failed.");
434 meta_data_destroy(vl->meta);
440 plugin_dispatch_values(vl);
441 stats_values_dispatched++;
443 meta_data_destroy(vl->meta);
447 } /* }}} int network_dispatch_values */
449 static int network_dispatch_notification(notification_t *n) /* {{{ */
453 assert(n->meta == NULL);
455 status = plugin_notification_meta_add_boolean(n, "network:received", 1);
457 ERROR("network plugin: plugin_notification_meta_add_boolean failed.");
458 plugin_notification_meta_free(n->meta);
463 status = plugin_dispatch_notification(n);
465 plugin_notification_meta_free(n->meta);
469 } /* }}} int network_dispatch_notification */
472 static int network_init_gcrypt(void) /* {{{ */
476 /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
477 * Because you can't know in a library whether another library has
478 * already initialized the library */
479 if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P))
482 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
483 * To ensure thread-safety, it's important to set GCRYCTL_SET_THREAD_CBS
484 * *before* initalizing Libgcrypt with gcry_check_version(), which itself must
485 * be called before any other gcry_* function. GCRYCTL_ANY_INITIALIZATION_P
486 * above doesn't count, as it doesn't implicitly initalize Libgcrypt.
488 * tl;dr: keep all these gry_* statements in this exact order please. */
489 #if GCRYPT_VERSION_NUMBER < 0x010600
490 err = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
492 ERROR("network plugin: gcry_control (GCRYCTL_SET_THREAD_CBS) failed: %s",
498 gcry_check_version(NULL);
500 err = gcry_control(GCRYCTL_INIT_SECMEM, 32768);
502 ERROR("network plugin: gcry_control (GCRYCTL_INIT_SECMEM) failed: %s",
507 gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
509 } /* }}} int network_init_gcrypt */
511 static gcry_cipher_hd_t network_get_aes256_cypher(sockent_t *se, /* {{{ */
514 const char *username) {
516 gcry_cipher_hd_t *cyper_ptr;
517 unsigned char password_hash[32];
519 if (se->type == SOCKENT_TYPE_CLIENT) {
520 cyper_ptr = &se->data.client.cypher;
521 memcpy(password_hash, se->data.client.password_hash, sizeof(password_hash));
525 cyper_ptr = &se->data.server.cypher;
527 if (username == NULL)
530 secret = fbh_get(se->data.server.userdb, username);
534 gcry_md_hash_buffer(GCRY_MD_SHA256, password_hash, secret, strlen(secret));
539 if (*cyper_ptr == NULL) {
540 err = gcry_cipher_open(cyper_ptr, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB,
543 ERROR("network plugin: gcry_cipher_open returned: %s",
549 gcry_cipher_reset(*cyper_ptr);
551 assert(*cyper_ptr != NULL);
553 err = gcry_cipher_setkey(*cyper_ptr, password_hash, sizeof(password_hash));
555 ERROR("network plugin: gcry_cipher_setkey returned: %s",
557 gcry_cipher_close(*cyper_ptr);
562 err = gcry_cipher_setiv(*cyper_ptr, iv, iv_size);
564 ERROR("network plugin: gcry_cipher_setkey returned: %s",
566 gcry_cipher_close(*cyper_ptr);
572 } /* }}} int network_get_aes256_cypher */
573 #endif /* HAVE_GCRYPT_H */
575 static int write_part_values(char **ret_buffer, size_t *ret_buffer_len,
576 const data_set_t *ds, const value_list_t *vl) {
581 part_header_t pkg_ph;
582 uint16_t pkg_num_values;
583 uint8_t *pkg_values_types;
588 num_values = vl->values_len;
589 packet_len = sizeof(part_header_t) + sizeof(uint16_t) +
590 (num_values * sizeof(uint8_t)) + (num_values * sizeof(value_t));
592 if (*ret_buffer_len < packet_len)
595 pkg_values_types = malloc(num_values * sizeof(*pkg_values_types));
596 if (pkg_values_types == NULL) {
597 ERROR("network plugin: write_part_values: malloc failed.");
601 pkg_values = malloc(num_values * sizeof(*pkg_values));
602 if (pkg_values == NULL) {
603 free(pkg_values_types);
604 ERROR("network plugin: write_part_values: malloc failed.");
608 pkg_ph.type = htons(TYPE_VALUES);
609 pkg_ph.length = htons(packet_len);
611 pkg_num_values = htons((uint16_t)vl->values_len);
613 for (int i = 0; i < num_values; i++) {
614 pkg_values_types[i] = (uint8_t)ds->ds[i].type;
615 switch (ds->ds[i].type) {
616 case DS_TYPE_COUNTER:
617 pkg_values[i].counter = htonll(vl->values[i].counter);
621 pkg_values[i].gauge = htond(vl->values[i].gauge);
625 pkg_values[i].derive = htonll(vl->values[i].derive);
628 case DS_TYPE_ABSOLUTE:
629 pkg_values[i].absolute = htonll(vl->values[i].absolute);
633 free(pkg_values_types);
635 ERROR("network plugin: write_part_values: "
636 "Unknown data source type: %i",
639 } /* switch (ds->ds[i].type) */
640 } /* for (num_values) */
643 * Use `memcpy' to write everything to the buffer, because the pointer
644 * may be unaligned and some architectures, such as SPARC, can't handle
647 packet_ptr = *ret_buffer;
649 memcpy(packet_ptr + offset, &pkg_ph, sizeof(pkg_ph));
650 offset += sizeof(pkg_ph);
651 memcpy(packet_ptr + offset, &pkg_num_values, sizeof(pkg_num_values));
652 offset += sizeof(pkg_num_values);
653 memcpy(packet_ptr + offset, pkg_values_types, num_values * sizeof(uint8_t));
654 offset += num_values * sizeof(uint8_t);
655 memcpy(packet_ptr + offset, pkg_values, num_values * sizeof(value_t));
656 offset += num_values * sizeof(value_t);
658 assert(offset == packet_len);
660 *ret_buffer = packet_ptr + packet_len;
661 *ret_buffer_len -= packet_len;
663 free(pkg_values_types);
667 } /* int write_part_values */
669 static int write_part_number(char **ret_buffer, size_t *ret_buffer_len,
670 int type, uint64_t value) {
674 part_header_t pkg_head;
679 packet_len = sizeof(pkg_head) + sizeof(pkg_value);
681 if (*ret_buffer_len < packet_len)
684 pkg_head.type = htons(type);
685 pkg_head.length = htons(packet_len);
686 pkg_value = htonll(value);
688 packet_ptr = *ret_buffer;
690 memcpy(packet_ptr + offset, &pkg_head, sizeof(pkg_head));
691 offset += sizeof(pkg_head);
692 memcpy(packet_ptr + offset, &pkg_value, sizeof(pkg_value));
693 offset += sizeof(pkg_value);
695 assert(offset == packet_len);
697 *ret_buffer = packet_ptr + packet_len;
698 *ret_buffer_len -= packet_len;
701 } /* int write_part_number */
703 static int write_part_string(char **ret_buffer, size_t *ret_buffer_len,
704 int type, const char *str, size_t str_len) {
713 buffer_len = 2 * sizeof(uint16_t) + str_len + 1;
714 if (*ret_buffer_len < buffer_len)
717 pkg_type = htons(type);
718 pkg_length = htons(buffer_len);
720 buffer = *ret_buffer;
722 memcpy(buffer + offset, (void *)&pkg_type, sizeof(pkg_type));
723 offset += sizeof(pkg_type);
724 memcpy(buffer + offset, (void *)&pkg_length, sizeof(pkg_length));
725 offset += sizeof(pkg_length);
726 memcpy(buffer + offset, str, str_len);
728 memset(buffer + offset, '\0', 1);
731 assert(offset == buffer_len);
733 *ret_buffer = buffer + buffer_len;
734 *ret_buffer_len -= buffer_len;
737 } /* int write_part_string */
739 static int parse_part_values(void **ret_buffer, size_t *ret_buffer_len,
740 value_t **ret_values, size_t *ret_num_values) {
741 char *buffer = *ret_buffer;
742 size_t buffer_len = *ret_buffer_len;
754 if (buffer_len < 15) {
755 NOTICE("network plugin: packet is too short: "
761 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
762 buffer += sizeof(tmp16);
763 pkg_type = ntohs(tmp16);
765 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
766 buffer += sizeof(tmp16);
767 pkg_length = ntohs(tmp16);
769 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
770 buffer += sizeof(tmp16);
771 pkg_numval = (size_t)ntohs(tmp16);
773 assert(pkg_type == TYPE_VALUES);
776 3 * sizeof(uint16_t) + pkg_numval * (sizeof(uint8_t) + sizeof(value_t));
777 if (buffer_len < exp_size) {
778 WARNING("network plugin: parse_part_values: "
780 "Chunk of size %zu expected, "
781 "but buffer has only %zu bytes left.",
782 exp_size, buffer_len);
785 assert(pkg_numval <= ((buffer_len - 6) / 9));
787 if (pkg_length != exp_size) {
788 WARNING("network plugin: parse_part_values: "
789 "Length and number of values "
790 "in the packet don't match.");
794 pkg_types = calloc(pkg_numval, sizeof(*pkg_types));
795 pkg_values = calloc(pkg_numval, sizeof(*pkg_values));
796 if ((pkg_types == NULL) || (pkg_values == NULL)) {
799 ERROR("network plugin: parse_part_values: calloc failed.");
803 memcpy(pkg_types, buffer, pkg_numval * sizeof(*pkg_types));
804 buffer += pkg_numval * sizeof(*pkg_types);
805 memcpy(pkg_values, buffer, pkg_numval * sizeof(*pkg_values));
806 buffer += pkg_numval * sizeof(*pkg_values);
808 for (size_t i = 0; i < pkg_numval; i++) {
809 switch (pkg_types[i]) {
810 case DS_TYPE_COUNTER:
811 pkg_values[i].counter = (counter_t)ntohll(pkg_values[i].counter);
815 pkg_values[i].gauge = (gauge_t)ntohd(pkg_values[i].gauge);
819 pkg_values[i].derive = (derive_t)ntohll(pkg_values[i].derive);
822 case DS_TYPE_ABSOLUTE:
823 pkg_values[i].absolute = (absolute_t)ntohll(pkg_values[i].absolute);
827 NOTICE("network plugin: parse_part_values: "
828 "Don't know how to handle data source type %" PRIu8,
833 } /* switch (pkg_types[i]) */
836 *ret_buffer = buffer;
837 *ret_buffer_len = buffer_len - pkg_length;
838 *ret_num_values = pkg_numval;
839 *ret_values = pkg_values;
844 } /* int parse_part_values */
846 static int parse_part_number(void **ret_buffer, size_t *ret_buffer_len,
848 char *buffer = *ret_buffer;
849 size_t buffer_len = *ret_buffer_len;
853 size_t exp_size = 2 * sizeof(uint16_t) + sizeof(uint64_t);
857 if (buffer_len < exp_size) {
858 WARNING("network plugin: parse_part_number: "
860 "Chunk of size %zu expected, "
861 "but buffer has only %zu bytes left.",
862 exp_size, buffer_len);
866 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
867 buffer += sizeof(tmp16);
868 /* pkg_type = ntohs (tmp16); */
870 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
871 buffer += sizeof(tmp16);
872 pkg_length = ntohs(tmp16);
874 memcpy((void *)&tmp64, buffer, sizeof(tmp64));
875 buffer += sizeof(tmp64);
876 *value = ntohll(tmp64);
878 *ret_buffer = buffer;
879 *ret_buffer_len = buffer_len - pkg_length;
882 } /* int parse_part_number */
884 static int parse_part_string(void **ret_buffer, size_t *ret_buffer_len,
885 char *output, size_t const output_len) {
886 char *buffer = *ret_buffer;
887 size_t buffer_len = *ret_buffer_len;
890 size_t const header_size = 2 * sizeof(uint16_t);
898 if (buffer_len < header_size) {
899 WARNING("network plugin: parse_part_string: "
901 "Chunk of at least size %zu expected, "
902 "but buffer has only %zu bytes left.",
903 header_size, buffer_len);
907 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
908 buffer += sizeof(tmp16);
909 /* pkg_type = ntohs (tmp16); */
911 memcpy((void *)&tmp16, buffer, sizeof(tmp16));
912 buffer += sizeof(tmp16);
913 pkg_length = ntohs(tmp16);
914 payload_size = ((size_t)pkg_length) - header_size;
916 /* Check that packet fits in the input buffer */
917 if (pkg_length > buffer_len) {
918 WARNING("network plugin: parse_part_string: "
920 "Chunk of size %" PRIu16 " received, "
921 "but buffer has only %zu bytes left.",
922 pkg_length, buffer_len);
926 /* Check that pkg_length is in the valid range */
927 if (pkg_length <= header_size) {
928 WARNING("network plugin: parse_part_string: "
930 "Header claims this packet is only %hu "
936 /* Check that the package data fits into the output buffer.
937 * The previous if-statement ensures that:
938 * `pkg_length > header_size' */
939 if (output_len < payload_size) {
940 WARNING("network plugin: parse_part_string: "
942 "Output buffer holds %zu bytes, "
943 "which is too small to hold the received "
945 output_len, payload_size);
949 /* All sanity checks successfull, let's copy the data over */
950 memcpy((void *)output, (void *)buffer, payload_size);
951 buffer += payload_size;
953 /* For some very weird reason '\0' doesn't do the trick on SPARC in
955 if (output[payload_size - 1] != 0) {
956 WARNING("network plugin: parse_part_string: "
957 "Received string does not end "
958 "with a NULL-byte.");
962 *ret_buffer = buffer;
963 *ret_buffer_len = buffer_len - pkg_length;
966 } /* int parse_part_string */
968 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
969 * parse_packet and vice versa. */
970 #define PP_SIGNED 0x01
971 #define PP_ENCRYPTED 0x02
972 static int parse_packet(sockent_t *se, void *buffer, size_t buffer_size,
973 int flags, const char *username);
975 #define BUFFER_READ(p, s) \
977 memcpy((p), buffer + buffer_offset, (s)); \
978 buffer_offset += (s); \
982 static int parse_part_sign_sha256(sockent_t *se, /* {{{ */
983 void **ret_buffer, size_t *ret_buffer_len,
985 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
989 size_t buffer_offset;
994 part_signature_sha256_t pss;
995 uint16_t pss_head_length;
996 char hash[sizeof(pss.hash)];
1000 unsigned char *hash_ptr;
1002 buffer = *ret_buffer;
1003 buffer_len = *ret_buffer_len;
1006 /* Check if the buffer has enough data for this structure. */
1007 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1010 /* Read type and length header */
1011 BUFFER_READ(&pss.head.type, sizeof(pss.head.type));
1012 BUFFER_READ(&pss.head.length, sizeof(pss.head.length));
1013 pss_head_length = ntohs(pss.head.length);
1015 /* Check if the `pss_head_length' is within bounds. */
1016 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE) ||
1017 (pss_head_length > buffer_len)) {
1018 ERROR("network plugin: HMAC-SHA-256 with invalid length received.");
1022 if (se->data.server.userdb == NULL) {
1024 LOG_NOTICE, &complain_no_users,
1025 "network plugin: Received signed network packet but can't verify it "
1026 "because no user DB has been configured. Will accept it.");
1028 *ret_buffer = buffer + pss_head_length;
1029 *ret_buffer_len -= pss_head_length;
1034 /* Copy the hash. */
1035 BUFFER_READ(pss.hash, sizeof(pss.hash));
1037 /* Calculate username length (without null byte) and allocate memory */
1038 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1039 pss.username = malloc(username_len + 1);
1040 if (pss.username == NULL)
1043 /* Read the username */
1044 BUFFER_READ(pss.username, username_len);
1045 pss.username[username_len] = 0;
1047 assert(buffer_offset == pss_head_length);
1049 /* Query the password */
1050 secret = fbh_get(se->data.server.userdb, pss.username);
1051 if (secret == NULL) {
1052 ERROR("network plugin: Unknown user: %s", pss.username);
1053 sfree(pss.username);
1057 /* Create a hash device and check the HMAC */
1059 err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1061 ERROR("network plugin: Creating HMAC-SHA-256 object failed: %s",
1062 gcry_strerror(err));
1064 sfree(pss.username);
1068 err = gcry_md_setkey(hd, secret, strlen(secret));
1070 ERROR("network plugin: gcry_md_setkey failed: %s", gcry_strerror(err));
1073 sfree(pss.username);
1077 gcry_md_write(hd, buffer + PART_SIGNATURE_SHA256_SIZE,
1078 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1079 hash_ptr = gcry_md_read(hd, GCRY_MD_SHA256);
1080 if (hash_ptr == NULL) {
1081 ERROR("network plugin: gcry_md_read failed.");
1084 sfree(pss.username);
1087 memcpy(hash, hash_ptr, sizeof(hash));
1093 if (memcmp(pss.hash, hash, sizeof(pss.hash)) != 0) {
1094 WARNING("network plugin: Verifying HMAC-SHA-256 signature failed: "
1095 "Hash mismatch. Username: %s",
1098 parse_packet(se, buffer + buffer_offset, buffer_len - buffer_offset,
1099 flags | PP_SIGNED, pss.username);
1103 sfree(pss.username);
1105 *ret_buffer = buffer + buffer_len;
1106 *ret_buffer_len = 0;
1109 } /* }}} int parse_part_sign_sha256 */
1110 /* #endif HAVE_GCRYPT_H */
1112 #else /* if !HAVE_GCRYPT_H */
1113 static int parse_part_sign_sha256(sockent_t *se, /* {{{ */
1114 void **ret_buffer, size_t *ret_buffer_size,
1116 static int warning_has_been_printed = 0;
1120 size_t buffer_offset;
1123 part_signature_sha256_t pss;
1125 buffer = *ret_buffer;
1126 buffer_size = *ret_buffer_size;
1129 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1132 BUFFER_READ(&pss.head.type, sizeof(pss.head.type));
1133 BUFFER_READ(&pss.head.length, sizeof(pss.head.length));
1134 part_len = ntohs(pss.head.length);
1136 if ((part_len <= PART_SIGNATURE_SHA256_SIZE) || (part_len > buffer_size))
1139 if (warning_has_been_printed == 0) {
1140 WARNING("network plugin: Received signed packet, but the network "
1141 "plugin was not linked with libgcrypt, so I cannot "
1142 "verify the signature. The packet will be accepted.");
1143 warning_has_been_printed = 1;
1146 parse_packet(se, buffer + part_len, buffer_size - part_len, flags,
1147 /* username = */ NULL);
1149 *ret_buffer = buffer + buffer_size;
1150 *ret_buffer_size = 0;
1153 } /* }}} int parse_part_sign_sha256 */
1154 #endif /* !HAVE_GCRYPT_H */
1157 static int parse_part_encr_aes256(sockent_t *se, /* {{{ */
1158 void **ret_buffer, size_t *ret_buffer_len,
1160 char *buffer = *ret_buffer;
1161 size_t buffer_len = *ret_buffer_len;
1164 size_t buffer_offset;
1165 uint16_t username_len;
1166 part_encryption_aes256_t pea;
1167 unsigned char hash[sizeof(pea.hash)] = {0};
1169 gcry_cipher_hd_t cypher;
1172 /* Make sure at least the header if available. */
1173 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE) {
1174 NOTICE("network plugin: parse_part_encr_aes256: "
1175 "Discarding short packet.");
1181 /* Copy the unencrypted information into `pea'. */
1182 BUFFER_READ(&pea.head.type, sizeof(pea.head.type));
1183 BUFFER_READ(&pea.head.length, sizeof(pea.head.length));
1185 /* Check the `part size'. */
1186 part_size = ntohs(pea.head.length);
1187 if ((part_size <= PART_ENCRYPTION_AES256_SIZE) || (part_size > buffer_len)) {
1188 NOTICE("network plugin: parse_part_encr_aes256: "
1189 "Discarding part with invalid size.");
1193 /* Read the username */
1194 BUFFER_READ(&username_len, sizeof(username_len));
1195 username_len = ntohs(username_len);
1197 if ((username_len == 0) ||
1198 (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1)))) {
1199 NOTICE("network plugin: parse_part_encr_aes256: "
1200 "Discarding part with invalid username length.");
1204 assert(username_len > 0);
1205 pea.username = malloc(username_len + 1);
1206 if (pea.username == NULL)
1208 BUFFER_READ(pea.username, username_len);
1209 pea.username[username_len] = 0;
1211 /* Last but not least, the initialization vector */
1212 BUFFER_READ(pea.iv, sizeof(pea.iv));
1214 /* Make sure we are at the right position */
1215 assert(buffer_offset ==
1216 (username_len + PART_ENCRYPTION_AES256_SIZE - sizeof(pea.hash)));
1218 cypher = network_get_aes256_cypher(se, pea.iv, sizeof(pea.iv), pea.username);
1219 if (cypher == NULL) {
1220 ERROR("network plugin: Failed to get cypher. Username: %s", pea.username);
1221 sfree(pea.username);
1225 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1226 assert(payload_len > 0);
1228 /* Decrypt the packet in-place */
1229 err = gcry_cipher_decrypt(cypher, buffer + buffer_offset,
1230 part_size - buffer_offset,
1231 /* in = */ NULL, /* in len = */ 0);
1233 ERROR("network plugin: gcry_cipher_decrypt returned: %s. Username: %s",
1234 gcry_strerror(err), pea.username);
1235 sfree(pea.username);
1240 BUFFER_READ(pea.hash, sizeof(pea.hash));
1242 /* Make sure we're at the right position - again */
1243 assert(buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1244 assert(buffer_offset == (part_size - payload_len));
1246 /* Check hash sum */
1247 gcry_md_hash_buffer(GCRY_MD_SHA1, hash, buffer + buffer_offset, payload_len);
1248 if (memcmp(hash, pea.hash, sizeof(hash)) != 0) {
1249 ERROR("network plugin: Checksum mismatch. Username: %s", pea.username);
1250 sfree(pea.username);
1254 parse_packet(se, buffer + buffer_offset, payload_len, flags | PP_ENCRYPTED,
1257 /* Update return values */
1258 *ret_buffer = buffer + part_size;
1259 *ret_buffer_len = buffer_len - part_size;
1261 sfree(pea.username);
1264 } /* }}} int parse_part_encr_aes256 */
1265 /* #endif HAVE_GCRYPT_H */
1267 #else /* if !HAVE_GCRYPT_H */
1268 static int parse_part_encr_aes256(sockent_t *se, /* {{{ */
1269 void **ret_buffer, size_t *ret_buffer_size,
1271 static int warning_has_been_printed = 0;
1275 size_t buffer_offset;
1280 buffer = *ret_buffer;
1281 buffer_size = *ret_buffer_size;
1284 /* parse_packet assures this minimum size. */
1285 assert(buffer_size >= (sizeof(ph.type) + sizeof(ph.length)));
1287 BUFFER_READ(&ph.type, sizeof(ph.type));
1288 BUFFER_READ(&ph.length, sizeof(ph.length));
1289 ph_length = ntohs(ph.length);
1291 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE) || (ph_length > buffer_size)) {
1292 ERROR("network plugin: AES-256 encrypted part "
1293 "with invalid length received.");
1297 if (warning_has_been_printed == 0) {
1298 WARNING("network plugin: Received encrypted packet, but the network "
1299 "plugin was not linked with libgcrypt, so I cannot "
1300 "decrypt it. The part will be discarded.");
1301 warning_has_been_printed = 1;
1304 *ret_buffer = (void *)(((char *)*ret_buffer) + ph_length);
1305 *ret_buffer_size -= ph_length;
1308 } /* }}} int parse_part_encr_aes256 */
1309 #endif /* !HAVE_GCRYPT_H */
1313 static int parse_packet(sockent_t *se, /* {{{ */
1314 void *buffer, size_t buffer_size, int flags,
1315 const char *username) {
1318 value_list_t vl = VALUE_LIST_INIT;
1319 notification_t n = {0};
1322 int packet_was_signed = (flags & PP_SIGNED);
1323 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1324 int printed_ignore_warning = 0;
1325 #endif /* HAVE_GCRYPT_H */
1327 memset(&vl, '\0', sizeof(vl));
1330 while ((status == 0) && (0 < buffer_size) &&
1331 ((unsigned int)buffer_size > sizeof(part_header_t))) {
1332 uint16_t pkg_length;
1335 memcpy((void *)&pkg_type, (void *)buffer, sizeof(pkg_type));
1336 memcpy((void *)&pkg_length, (void *)(((char *)buffer) + sizeof(pkg_type)),
1337 sizeof(pkg_length));
1339 pkg_length = ntohs(pkg_length);
1340 pkg_type = ntohs(pkg_type);
1342 if (pkg_length > buffer_size)
1344 /* Ensure that this loop terminates eventually */
1345 if (pkg_length < (2 * sizeof(uint16_t)))
1348 if (pkg_type == TYPE_ENCR_AES256) {
1349 status = parse_part_encr_aes256(se, &buffer, &buffer_size, flags);
1351 ERROR("network plugin: Decrypting AES256 "
1359 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT) &&
1360 (packet_was_encrypted == 0)) {
1361 if (printed_ignore_warning == 0) {
1362 INFO("network plugin: Unencrypted packet or "
1363 "part has been ignored.");
1364 printed_ignore_warning = 1;
1366 buffer = ((char *)buffer) + pkg_length;
1367 buffer_size -= (size_t)pkg_length;
1370 #endif /* HAVE_GCRYPT_H */
1371 else if (pkg_type == TYPE_SIGN_SHA256) {
1372 status = parse_part_sign_sha256(se, &buffer, &buffer_size, flags);
1374 ERROR("network plugin: Verifying HMAC-SHA-256 "
1382 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN) &&
1383 (packet_was_encrypted == 0) && (packet_was_signed == 0)) {
1384 if (printed_ignore_warning == 0) {
1385 INFO("network plugin: Unsigned packet or "
1386 "part has been ignored.");
1387 printed_ignore_warning = 1;
1389 buffer = ((char *)buffer) + pkg_length;
1390 buffer_size -= (size_t)pkg_length;
1393 #endif /* HAVE_GCRYPT_H */
1394 else if (pkg_type == TYPE_VALUES) {
1396 parse_part_values(&buffer, &buffer_size, &vl.values, &vl.values_len);
1400 network_dispatch_values(&vl, username);
1403 } else if (pkg_type == TYPE_TIME) {
1405 status = parse_part_number(&buffer, &buffer_size, &tmp);
1407 vl.time = TIME_T_TO_CDTIME_T(tmp);
1408 n.time = TIME_T_TO_CDTIME_T(tmp);
1410 } else if (pkg_type == TYPE_TIME_HR) {
1412 status = parse_part_number(&buffer, &buffer_size, &tmp);
1414 vl.time = (cdtime_t)tmp;
1415 n.time = (cdtime_t)tmp;
1417 } else if (pkg_type == TYPE_INTERVAL) {
1419 status = parse_part_number(&buffer, &buffer_size, &tmp);
1421 vl.interval = TIME_T_TO_CDTIME_T(tmp);
1422 } else if (pkg_type == TYPE_INTERVAL_HR) {
1424 status = parse_part_number(&buffer, &buffer_size, &tmp);
1426 vl.interval = (cdtime_t)tmp;
1427 } else if (pkg_type == TYPE_HOST) {
1429 parse_part_string(&buffer, &buffer_size, vl.host, sizeof(vl.host));
1431 sstrncpy(n.host, vl.host, sizeof(n.host));
1432 } else if (pkg_type == TYPE_PLUGIN) {
1433 status = parse_part_string(&buffer, &buffer_size, vl.plugin,
1436 sstrncpy(n.plugin, vl.plugin, sizeof(n.plugin));
1437 } else if (pkg_type == TYPE_PLUGIN_INSTANCE) {
1438 status = parse_part_string(&buffer, &buffer_size, vl.plugin_instance,
1439 sizeof(vl.plugin_instance));
1441 sstrncpy(n.plugin_instance, vl.plugin_instance,
1442 sizeof(n.plugin_instance));
1443 } else if (pkg_type == TYPE_TYPE) {
1445 parse_part_string(&buffer, &buffer_size, vl.type, sizeof(vl.type));
1447 sstrncpy(n.type, vl.type, sizeof(n.type));
1448 } else if (pkg_type == TYPE_TYPE_INSTANCE) {
1449 status = parse_part_string(&buffer, &buffer_size, vl.type_instance,
1450 sizeof(vl.type_instance));
1452 sstrncpy(n.type_instance, vl.type_instance, sizeof(n.type_instance));
1453 } else if (pkg_type == TYPE_MESSAGE) {
1454 status = parse_part_string(&buffer, &buffer_size, n.message,
1459 } else if ((n.severity != NOTIF_FAILURE) &&
1460 (n.severity != NOTIF_WARNING) && (n.severity != NOTIF_OKAY)) {
1461 INFO("network plugin: "
1462 "Ignoring notification with "
1463 "unknown severity %i.",
1465 } else if (n.time == 0) {
1466 INFO("network plugin: "
1467 "Ignoring notification with "
1469 } else if (strlen(n.message) == 0) {
1470 INFO("network plugin: "
1471 "Ignoring notification with "
1472 "an empty message.");
1474 network_dispatch_notification(&n);
1476 } else if (pkg_type == TYPE_SEVERITY) {
1478 status = parse_part_number(&buffer, &buffer_size, &tmp);
1480 n.severity = (int)tmp;
1482 DEBUG("network plugin: parse_packet: Unknown part"
1485 buffer = ((char *)buffer) + pkg_length;
1486 buffer_size -= (size_t)pkg_length;
1488 } /* while (buffer_size > sizeof (part_header_t)) */
1490 if (status == 0 && buffer_size > 0)
1491 WARNING("network plugin: parse_packet: Received truncated "
1492 "packet, try increasing `MaxPacketSize'");
1495 } /* }}} int parse_packet */
1497 static void free_sockent_client(struct sockent_client *sec) /* {{{ */
1505 sfree(sec->username);
1506 sfree(sec->password);
1507 if (sec->cypher != NULL)
1508 gcry_cipher_close(sec->cypher);
1510 } /* }}} void free_sockent_client */
1512 static void free_sockent_server(struct sockent_server *ses) /* {{{ */
1514 for (size_t i = 0; i < ses->fd_num; i++) {
1515 if (ses->fd[i] >= 0) {
1523 sfree(ses->auth_file);
1524 fbh_destroy(ses->userdb);
1525 if (ses->cypher != NULL)
1526 gcry_cipher_close(ses->cypher);
1528 } /* }}} void free_sockent_server */
1530 static void sockent_destroy(sockent_t *se) /* {{{ */
1534 DEBUG("network plugin: sockent_destroy (se = %p);", (void *)se);
1536 while (se != NULL) {
1542 if (se->type == SOCKENT_TYPE_CLIENT)
1543 free_sockent_client(&se->data.client);
1545 free_sockent_server(&se->data.server);
1550 } /* }}} void sockent_destroy */
1553 * int network_set_ttl
1555 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1556 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1558 * The `struct addrinfo' is used to destinguish between unicast and multicast
1561 static int network_set_ttl(const sockent_t *se, const struct addrinfo *ai) {
1562 DEBUG("network plugin: network_set_ttl: network_config_ttl = %i;",
1563 network_config_ttl);
1565 assert(se->type == SOCKENT_TYPE_CLIENT);
1567 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1570 if (ai->ai_family == AF_INET) {
1571 struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1574 if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr)))
1575 optname = IP_MULTICAST_TTL;
1579 if (setsockopt(se->data.client.fd, IPPROTO_IP, optname, &network_config_ttl,
1580 sizeof(network_config_ttl)) != 0) {
1582 ERROR("network plugin: setsockopt (ipv4-ttl): %s",
1583 sstrerror(errno, errbuf, sizeof(errbuf)));
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) {
1600 ERROR("network plugin: setsockopt(ipv6-ttl): %s",
1601 sstrerror(errno, errbuf, sizeof(errbuf)));
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) {
1638 ERROR("network plugin: setsockopt (ipv4-multicast-if): %s",
1639 sstrerror(errno, errbuf, sizeof(errbuf)));
1645 } else if (ai->ai_family == AF_INET6) {
1646 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1648 if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr)) {
1649 if (setsockopt(se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1650 &se->interface, sizeof(se->interface)) != 0) {
1652 ERROR("network plugin: setsockopt (ipv6-multicast-if): %s",
1653 sstrerror(errno, errbuf, sizeof(errbuf)));
1661 /* else: Not a multicast interface. */
1662 if (se->interface != 0) {
1663 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && \
1664 defined(SO_BINDTODEVICE)
1665 char interface_name[IFNAMSIZ];
1667 if (if_indextoname(se->interface, interface_name) == NULL)
1670 DEBUG("network plugin: Binding socket to interface %s", interface_name);
1672 if (setsockopt(se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1673 interface_name, sizeof(interface_name)) == -1) {
1675 ERROR("network plugin: setsockopt (bind-if): %s",
1676 sstrerror(errno, errbuf, sizeof(errbuf)));
1679 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1682 WARNING("network plugin: Cannot set the interface on a unicast "
1684 #if !defined(SO_BINDTODEVICE)
1685 "the \"SO_BINDTODEVICE\" socket option "
1687 "the \"if_indextoname\" function "
1689 "is not available on your system.");
1694 } /* }}} network_set_interface */
1696 static int network_bind_socket(int fd, const struct addrinfo *ai,
1697 const int interface_idx) {
1705 /* allow multiple sockets to use the same PORT number */
1706 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
1708 ERROR("network plugin: setsockopt (reuseaddr): %s",
1709 sstrerror(errno, errbuf, sizeof(errbuf)));
1713 DEBUG("fd = %i; calling `bind'", fd);
1715 if (bind(fd, ai->ai_addr, ai->ai_addrlen) == -1) {
1717 ERROR("bind: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
1721 if (ai->ai_family == AF_INET) {
1722 struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
1723 if (IN_MULTICAST(ntohl(addr->sin_addr.s_addr))) {
1724 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1725 struct ip_mreqn mreq;
1727 struct ip_mreq mreq;
1730 DEBUG("fd = %i; IPv4 multicast address found", fd);
1732 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1733 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1734 /* Set the interface using the interface index if
1735 * possible (available). Unfortunately, the struct
1736 * ip_mreqn is not portable. */
1737 mreq.imr_address.s_addr = ntohl(INADDR_ANY);
1738 mreq.imr_ifindex = interface_idx;
1740 mreq.imr_interface.s_addr = ntohl(INADDR_ANY);
1743 if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) ==
1746 ERROR("network plugin: setsockopt (multicast-loop): %s",
1747 sstrerror(errno, errbuf, sizeof(errbuf)));
1751 if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) ==
1754 ERROR("network plugin: setsockopt (add-membership): %s",
1755 sstrerror(errno, errbuf, sizeof(errbuf)));
1761 } else if (ai->ai_family == AF_INET6) {
1763 * http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1764 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
1765 if (IN6_IS_ADDR_MULTICAST(&addr->sin6_addr)) {
1766 struct ipv6_mreq mreq;
1768 DEBUG("fd = %i; IPv6 multicast address found", fd);
1770 memcpy(&mreq.ipv6mr_multiaddr, &addr->sin6_addr, sizeof(addr->sin6_addr));
1772 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1773 * ipv6mr_interface may be set to zeroes to
1774 * choose the default multicast interface or to
1775 * the index of a particular multicast-capable
1776 * interface if the host is multihomed.
1777 * Membership is associ-associated with a
1778 * single interface; programs running on
1779 * multihomed hosts may need to join the same
1780 * group on more than one interface.*/
1781 mreq.ipv6mr_interface = interface_idx;
1783 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop,
1784 sizeof(loop)) == -1) {
1786 ERROR("network plugin: setsockopt (ipv6-multicast-loop): %s",
1787 sstrerror(errno, errbuf, sizeof(errbuf)));
1791 if (setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq,
1792 sizeof(mreq)) == -1) {
1794 ERROR("network plugin: setsockopt (ipv6-add-membership): %s",
1795 sstrerror(errno, errbuf, sizeof(errbuf)));
1803 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && \
1804 defined(SO_BINDTODEVICE)
1805 /* if a specific interface was set, bind the socket to it. But to avoid
1806 * possible problems with multicast routing, only do that for non-multicast
1808 if (interface_idx != 0) {
1809 char interface_name[IFNAMSIZ];
1811 if (if_indextoname(interface_idx, interface_name) == NULL)
1814 DEBUG("fd = %i; Binding socket to interface %s", fd, interface_name);
1816 if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, interface_name,
1817 sizeof(interface_name)) == -1) {
1819 ERROR("network plugin: setsockopt (bind-if): %s",
1820 sstrerror(errno, errbuf, sizeof(errbuf)));
1824 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1827 } /* int network_bind_socket */
1829 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1830 * or `SOCKENT_TYPE_SERVER' */
1831 static sockent_t *sockent_create(int type) /* {{{ */
1835 if ((type != SOCKENT_TYPE_CLIENT) && (type != SOCKENT_TYPE_SERVER))
1838 se = calloc(1, sizeof(*se));
1848 if (type == SOCKENT_TYPE_SERVER) {
1849 se->data.server.fd = NULL;
1850 se->data.server.fd_num = 0;
1852 se->data.server.security_level = SECURITY_LEVEL_NONE;
1853 se->data.server.auth_file = NULL;
1854 se->data.server.userdb = NULL;
1855 se->data.server.cypher = NULL;
1858 se->data.client.fd = -1;
1859 se->data.client.addr = NULL;
1860 se->data.client.resolve_interval = 0;
1861 se->data.client.next_resolve_reconnect = 0;
1863 se->data.client.security_level = SECURITY_LEVEL_NONE;
1864 se->data.client.username = NULL;
1865 se->data.client.password = NULL;
1866 se->data.client.cypher = NULL;
1871 } /* }}} sockent_t *sockent_create */
1873 static int sockent_init_crypto(sockent_t *se) /* {{{ */
1875 #if HAVE_GCRYPT_H /* {{{ */
1876 if (se->type == SOCKENT_TYPE_CLIENT) {
1877 if (se->data.client.security_level > SECURITY_LEVEL_NONE) {
1878 if (network_init_gcrypt() < 0) {
1879 ERROR("network plugin: Cannot configure client socket with "
1880 "security: Failed to initialize crypto library.");
1884 if ((se->data.client.username == NULL) ||
1885 (se->data.client.password == NULL)) {
1886 ERROR("network plugin: Client socket with "
1887 "security requested, but no "
1888 "credentials are configured.");
1891 gcry_md_hash_buffer(GCRY_MD_SHA256, se->data.client.password_hash,
1892 se->data.client.password,
1893 strlen(se->data.client.password));
1895 } else /* (se->type == SOCKENT_TYPE_SERVER) */
1897 if ((se->data.server.security_level > SECURITY_LEVEL_NONE) &&
1898 (se->data.server.auth_file == NULL)) {
1899 ERROR("network plugin: Server socket with security requested, "
1900 "but no \"AuthFile\" is configured.");
1903 if (se->data.server.auth_file != NULL) {
1904 if (network_init_gcrypt() < 0) {
1905 ERROR("network plugin: Cannot configure server socket with security: "
1906 "Failed to initialize crypto library.");
1910 se->data.server.userdb = fbh_create(se->data.server.auth_file);
1911 if (se->data.server.userdb == NULL) {
1912 ERROR("network plugin: Reading password file \"%s\" failed.",
1913 se->data.server.auth_file);
1918 #endif /* }}} HAVE_GCRYPT_H */
1921 } /* }}} int sockent_init_crypto */
1923 static int sockent_client_disconnect(sockent_t *se) /* {{{ */
1925 struct sockent_client *client;
1927 if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
1930 client = &se->data.client;
1931 if (client->fd >= 0) /* connected */
1937 sfree(client->addr);
1938 client->addrlen = 0;
1941 } /* }}} int sockent_client_disconnect */
1943 static int sockent_client_connect(sockent_t *se) /* {{{ */
1945 static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
1947 struct sockent_client *client;
1948 struct addrinfo *ai_list;
1950 _Bool reconnect = 0;
1953 if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
1956 client = &se->data.client;
1959 if (client->resolve_interval != 0 && client->next_resolve_reconnect < now) {
1960 DEBUG("network plugin: Reconnecting socket, resolve_interval = %lf, "
1961 "next_resolve_reconnect = %lf",
1962 CDTIME_T_TO_DOUBLE(client->resolve_interval),
1963 CDTIME_T_TO_DOUBLE(client->next_resolve_reconnect));
1967 if (client->fd >= 0 && !reconnect) /* already connected and not stale*/
1970 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
1971 .ai_flags = AI_ADDRCONFIG,
1972 .ai_protocol = IPPROTO_UDP,
1973 .ai_socktype = SOCK_DGRAM};
1975 status = getaddrinfo(se->node,
1976 (se->service != NULL) ? se->service : NET_DEFAULT_PORT,
1977 &ai_hints, &ai_list);
1980 LOG_ERR, &complaint, "network plugin: getaddrinfo (%s, %s) failed: %s",
1981 (se->node == NULL) ? "(null)" : se->node,
1982 (se->service == NULL) ? "(null)" : se->service, gai_strerror(status));
1985 c_release(LOG_NOTICE, &complaint,
1986 "network plugin: Successfully resolved \"%s\".", se->node);
1989 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
1990 ai_ptr = ai_ptr->ai_next) {
1991 if (client->fd >= 0) /* when we reconnect */
1992 sockent_client_disconnect(se);
1995 socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
1996 if (client->fd < 0) {
1998 ERROR("network plugin: socket(2) failed: %s",
1999 sstrerror(errno, errbuf, sizeof(errbuf)));
2003 client->addr = calloc(1, sizeof(*client->addr));
2004 if (client->addr == NULL) {
2005 ERROR("network plugin: calloc failed.");
2011 assert(sizeof(*client->addr) >= ai_ptr->ai_addrlen);
2012 memcpy(client->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2013 client->addrlen = ai_ptr->ai_addrlen;
2015 network_set_ttl(se, ai_ptr);
2016 network_set_interface(se, ai_ptr);
2018 /* We don't open more than one write-socket per
2019 * node/service pair.. */
2023 freeaddrinfo(ai_list);
2027 if (client->resolve_interval > 0)
2028 client->next_resolve_reconnect = now + client->resolve_interval;
2030 } /* }}} int sockent_client_connect */
2032 /* Open the file descriptors for a initialized sockent structure. */
2033 static int sockent_server_listen(sockent_t *se) /* {{{ */
2035 struct addrinfo *ai_list;
2039 const char *service;
2044 assert(se->data.server.fd == NULL);
2045 assert(se->data.server.fd_num == 0);
2048 service = se->service;
2050 if (service == NULL)
2051 service = NET_DEFAULT_PORT;
2053 DEBUG("network plugin: sockent_server_listen: node = %s; service = %s;", node,
2056 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC,
2057 .ai_flags = AI_ADDRCONFIG | AI_PASSIVE,
2058 .ai_protocol = IPPROTO_UDP,
2059 .ai_socktype = SOCK_DGRAM};
2061 status = getaddrinfo(node, service, &ai_hints, &ai_list);
2063 ERROR("network plugin: getaddrinfo (%s, %s) failed: %s",
2064 (se->node == NULL) ? "(null)" : se->node,
2065 (se->service == NULL) ? "(null)" : se->service, gai_strerror(status));
2069 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
2070 ai_ptr = ai_ptr->ai_next) {
2073 tmp = realloc(se->data.server.fd,
2074 sizeof(*tmp) * (se->data.server.fd_num + 1));
2076 ERROR("network plugin: realloc failed.");
2079 se->data.server.fd = tmp;
2080 tmp = se->data.server.fd + se->data.server.fd_num;
2082 *tmp = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
2085 ERROR("network plugin: socket(2) failed: %s",
2086 sstrerror(errno, errbuf, sizeof(errbuf)));
2090 status = network_bind_socket(*tmp, ai_ptr, se->interface);
2097 se->data.server.fd_num++;
2099 } /* for (ai_list) */
2101 freeaddrinfo(ai_list);
2103 if (se->data.server.fd_num == 0)
2106 } /* }}} int sockent_server_listen */
2108 /* Add a sockent to the global list of sockets */
2109 static int sockent_add(sockent_t *se) /* {{{ */
2111 sockent_t *last_ptr;
2116 if (se->type == SOCKENT_TYPE_SERVER) {
2119 tmp = realloc(listen_sockets_pollfd,
2120 sizeof(*tmp) * (listen_sockets_num + se->data.server.fd_num));
2122 ERROR("network plugin: realloc failed.");
2125 listen_sockets_pollfd = tmp;
2126 tmp = listen_sockets_pollfd + listen_sockets_num;
2128 for (size_t i = 0; i < se->data.server.fd_num; i++) {
2129 memset(tmp + i, 0, sizeof(*tmp));
2130 tmp[i].fd = se->data.server.fd[i];
2131 tmp[i].events = POLLIN | POLLPRI;
2135 listen_sockets_num += se->data.server.fd_num;
2137 if (listen_sockets == NULL) {
2138 listen_sockets = se;
2141 last_ptr = listen_sockets;
2142 } else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2144 if (sending_sockets == NULL) {
2145 sending_sockets = se;
2148 last_ptr = sending_sockets;
2151 while (last_ptr->next != NULL)
2152 last_ptr = last_ptr->next;
2153 last_ptr->next = se;
2156 } /* }}} int sockent_add */
2158 static void *dispatch_thread(void __attribute__((unused)) * arg) /* {{{ */
2161 receive_list_entry_t *ent;
2164 /* Lock and wait for more data to come in */
2165 pthread_mutex_lock(&receive_list_lock);
2166 while ((listen_loop == 0) && (receive_list_head == NULL))
2167 pthread_cond_wait(&receive_list_cond, &receive_list_lock);
2169 /* Remove the head entry and unlock */
2170 ent = receive_list_head;
2172 receive_list_head = ent->next;
2173 receive_list_length--;
2174 pthread_mutex_unlock(&receive_list_lock);
2176 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2177 * because we dispatch all missing packets before shutting down. */
2181 /* Look for the correct `sockent_t' */
2182 se = listen_sockets;
2183 while (se != NULL) {
2186 for (i = 0; i < se->data.server.fd_num; i++)
2187 if (se->data.server.fd[i] == ent->fd)
2190 if (i < se->data.server.fd_num)
2197 ERROR("network plugin: Got packet from FD %i, but can't "
2198 "find an appropriate socket entry.",
2205 parse_packet(se, ent->data, ent->data_len, /* flags = */ 0,
2206 /* username = */ NULL);
2212 } /* }}} void *dispatch_thread */
2214 static int network_receive(void) /* {{{ */
2216 char buffer[network_config_packet_size];
2221 receive_list_entry_t *private_list_head;
2222 receive_list_entry_t *private_list_tail;
2223 uint64_t private_list_length;
2225 assert(listen_sockets_num > 0);
2227 private_list_head = NULL;
2228 private_list_tail = NULL;
2229 private_list_length = 0;
2231 while (listen_loop == 0) {
2232 status = poll(listen_sockets_pollfd, listen_sockets_num, -1);
2237 ERROR("network plugin: poll(2) failed: %s",
2238 sstrerror(errno, errbuf, sizeof(errbuf)));
2242 for (size_t i = 0; (i < listen_sockets_num) && (status > 0); i++) {
2243 receive_list_entry_t *ent;
2245 if ((listen_sockets_pollfd[i].revents & (POLLIN | POLLPRI)) == 0)
2249 buffer_len = recv(listen_sockets_pollfd[i].fd, buffer, sizeof(buffer),
2251 if (buffer_len < 0) {
2253 status = (errno != 0) ? errno : -1;
2254 ERROR("network plugin: recv(2) failed: %s",
2255 sstrerror(errno, errbuf, sizeof(errbuf)));
2259 stats_octets_rx += ((uint64_t)buffer_len);
2262 /* TODO: Possible performance enhancement: Do not free
2263 * these entries in the dispatch thread but put them in
2264 * another list, so we don't have to allocate more and
2265 * more of these structures. */
2266 ent = calloc(1, sizeof(*ent));
2268 ERROR("network plugin: calloc failed.");
2273 ent->data = malloc(network_config_packet_size);
2274 if (ent->data == NULL) {
2276 ERROR("network plugin: malloc failed.");
2280 ent->fd = listen_sockets_pollfd[i].fd;
2283 memcpy(ent->data, buffer, buffer_len);
2284 ent->data_len = buffer_len;
2286 if (private_list_head == NULL)
2287 private_list_head = ent;
2289 private_list_tail->next = ent;
2290 private_list_tail = ent;
2291 private_list_length++;
2293 /* Do not block here. Blocking here has led to
2294 * insufficient performance in the past. */
2295 if (pthread_mutex_trylock(&receive_list_lock) == 0) {
2296 assert(((receive_list_head == NULL) && (receive_list_length == 0)) ||
2297 ((receive_list_head != NULL) && (receive_list_length != 0)));
2299 if (receive_list_head == NULL)
2300 receive_list_head = private_list_head;
2302 receive_list_tail->next = private_list_head;
2303 receive_list_tail = private_list_tail;
2304 receive_list_length += private_list_length;
2306 pthread_cond_signal(&receive_list_cond);
2307 pthread_mutex_unlock(&receive_list_lock);
2309 private_list_head = NULL;
2310 private_list_tail = NULL;
2311 private_list_length = 0;
2315 } /* for (listen_sockets_pollfd) */
2319 } /* while (listen_loop == 0) */
2321 /* Make sure everything is dispatched before exiting. */
2322 if (private_list_head != NULL) {
2323 pthread_mutex_lock(&receive_list_lock);
2325 if (receive_list_head == NULL)
2326 receive_list_head = private_list_head;
2328 receive_list_tail->next = private_list_head;
2329 receive_list_tail = private_list_tail;
2330 receive_list_length += private_list_length;
2332 pthread_cond_signal(&receive_list_cond);
2333 pthread_mutex_unlock(&receive_list_lock);
2337 } /* }}} int network_receive */
2339 static void *receive_thread(void __attribute__((unused)) * arg) {
2340 return network_receive() ? (void *)1 : (void *)0;
2341 } /* void *receive_thread */
2343 static void network_init_buffer(void) {
2344 memset(send_buffer, 0, network_config_packet_size);
2345 send_buffer_ptr = send_buffer;
2346 send_buffer_fill = 0;
2347 send_buffer_last_update = 0;
2349 memset(&send_buffer_vl, 0, sizeof(send_buffer_vl));
2350 } /* int network_init_buffer */
2352 static void network_send_buffer_plain(sockent_t *se, /* {{{ */
2353 const char *buffer, size_t buffer_size) {
2357 status = sockent_client_connect(se);
2361 status = sendto(se->data.client.fd, buffer, buffer_size,
2362 /* flags = */ 0, (struct sockaddr *)se->data.client.addr,
2363 se->data.client.addrlen);
2367 if ((errno == EINTR) || (errno == EAGAIN))
2370 ERROR("network plugin: sendto failed: %s. Closing sending socket.",
2371 sstrerror(errno, errbuf, sizeof(errbuf)));
2372 sockent_client_disconnect(se);
2378 } /* }}} void network_send_buffer_plain */
2381 #define BUFFER_ADD(p, s) \
2383 memcpy(buffer + buffer_offset, (p), (s)); \
2384 buffer_offset += (s); \
2387 static void network_send_buffer_signed(sockent_t *se, /* {{{ */
2388 const char *in_buffer,
2389 size_t in_buffer_size) {
2390 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2391 size_t buffer_offset;
2392 size_t username_len;
2396 unsigned char *hash;
2399 err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2401 ERROR("network plugin: Creating HMAC object failed: %s",
2402 gcry_strerror(err));
2406 err = gcry_md_setkey(hd, se->data.client.password,
2407 strlen(se->data.client.password));
2409 ERROR("network plugin: gcry_md_setkey failed: %s", gcry_strerror(err));
2414 username_len = strlen(se->data.client.username);
2415 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE)) {
2416 ERROR("network plugin: Username too long: %s", se->data.client.username);
2420 memcpy(buffer + PART_SIGNATURE_SHA256_SIZE, se->data.client.username,
2422 memcpy(buffer + PART_SIGNATURE_SHA256_SIZE + username_len, in_buffer,
2425 /* Initialize the `ps' structure. */
2426 part_signature_sha256_t ps = {
2427 .head.type = htons(TYPE_SIGN_SHA256),
2428 .head.length = htons(PART_SIGNATURE_SHA256_SIZE + username_len)};
2430 /* Calculate the hash value. */
2431 gcry_md_write(hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2432 username_len + in_buffer_size);
2433 hash = gcry_md_read(hd, GCRY_MD_SHA256);
2435 ERROR("network plugin: gcry_md_read failed.");
2439 memcpy(ps.hash, hash, sizeof(ps.hash));
2441 /* Add the header */
2444 BUFFER_ADD(&ps.head.type, sizeof(ps.head.type));
2445 BUFFER_ADD(&ps.head.length, sizeof(ps.head.length));
2446 BUFFER_ADD(ps.hash, sizeof(ps.hash));
2448 assert(buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2453 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2454 network_send_buffer_plain(se, buffer, buffer_offset);
2455 } /* }}} void network_send_buffer_signed */
2457 static void network_send_buffer_encrypted(sockent_t *se, /* {{{ */
2458 const char *in_buffer,
2459 size_t in_buffer_size) {
2460 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2462 size_t buffer_offset;
2464 size_t username_len;
2466 gcry_cipher_hd_t cypher;
2468 /* Initialize the header fields */
2469 part_encryption_aes256_t pea = {.head.type = htons(TYPE_ENCR_AES256),
2470 .username = se->data.client.username};
2472 username_len = strlen(pea.username);
2473 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE) {
2474 ERROR("network plugin: Username too long: %s", pea.username);
2478 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2479 header_size = PART_ENCRYPTION_AES256_SIZE + username_len - sizeof(pea.hash);
2481 assert(buffer_size <= sizeof(buffer));
2482 DEBUG("network plugin: network_send_buffer_encrypted: "
2483 "buffer_size = %zu;",
2486 pea.head.length = htons(
2487 (uint16_t)(PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size));
2488 pea.username_length = htons((uint16_t)username_len);
2490 /* Chose a random initialization vector. */
2491 gcry_randomize((void *)&pea.iv, sizeof(pea.iv), GCRY_STRONG_RANDOM);
2493 /* Create hash of the payload */
2494 gcry_md_hash_buffer(GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2496 /* Initialize the buffer */
2498 memset(buffer, 0, sizeof(buffer));
2500 BUFFER_ADD(&pea.head.type, sizeof(pea.head.type));
2501 BUFFER_ADD(&pea.head.length, sizeof(pea.head.length));
2502 BUFFER_ADD(&pea.username_length, sizeof(pea.username_length));
2503 BUFFER_ADD(pea.username, username_len);
2504 BUFFER_ADD(pea.iv, sizeof(pea.iv));
2505 assert(buffer_offset == header_size);
2506 BUFFER_ADD(pea.hash, sizeof(pea.hash));
2507 BUFFER_ADD(in_buffer, in_buffer_size);
2509 assert(buffer_offset == buffer_size);
2511 cypher = network_get_aes256_cypher(se, pea.iv, sizeof(pea.iv),
2512 se->data.client.password);
2516 /* Encrypt the buffer in-place */
2517 err = gcry_cipher_encrypt(cypher, buffer + header_size,
2518 buffer_size - header_size,
2519 /* in = */ NULL, /* in len = */ 0);
2521 ERROR("network plugin: gcry_cipher_encrypt returned: %s",
2522 gcry_strerror(err));
2526 /* Send it out without further modifications */
2527 network_send_buffer_plain(se, buffer, buffer_size);
2528 } /* }}} void network_send_buffer_encrypted */
2530 #endif /* HAVE_GCRYPT_H */
2532 static void network_send_buffer(char *buffer, size_t buffer_len) /* {{{ */
2534 DEBUG("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2536 for (sockent_t *se = sending_sockets; se != NULL; se = se->next) {
2538 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2539 network_send_buffer_encrypted(se, buffer, buffer_len);
2540 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2541 network_send_buffer_signed(se, buffer, buffer_len);
2542 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2543 #endif /* HAVE_GCRYPT_H */
2544 network_send_buffer_plain(se, buffer, buffer_len);
2545 } /* for (sending_sockets) */
2546 } /* }}} void network_send_buffer */
2548 static int add_to_buffer(char *buffer, size_t buffer_size, /* {{{ */
2549 value_list_t *vl_def, const data_set_t *ds,
2550 const value_list_t *vl) {
2551 char *buffer_orig = buffer;
2553 if (strcmp(vl_def->host, vl->host) != 0) {
2554 if (write_part_string(&buffer, &buffer_size, TYPE_HOST, vl->host,
2555 strlen(vl->host)) != 0)
2557 sstrncpy(vl_def->host, vl->host, sizeof(vl_def->host));
2560 if (vl_def->time != vl->time) {
2561 if (write_part_number(&buffer, &buffer_size, TYPE_TIME_HR,
2562 (uint64_t)vl->time))
2564 vl_def->time = vl->time;
2567 if (vl_def->interval != vl->interval) {
2568 if (write_part_number(&buffer, &buffer_size, TYPE_INTERVAL_HR,
2569 (uint64_t)vl->interval))
2571 vl_def->interval = vl->interval;
2574 if (strcmp(vl_def->plugin, vl->plugin) != 0) {
2575 if (write_part_string(&buffer, &buffer_size, TYPE_PLUGIN, vl->plugin,
2576 strlen(vl->plugin)) != 0)
2578 sstrncpy(vl_def->plugin, vl->plugin, sizeof(vl_def->plugin));
2581 if (strcmp(vl_def->plugin_instance, vl->plugin_instance) != 0) {
2582 if (write_part_string(&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2583 vl->plugin_instance,
2584 strlen(vl->plugin_instance)) != 0)
2586 sstrncpy(vl_def->plugin_instance, vl->plugin_instance,
2587 sizeof(vl_def->plugin_instance));
2590 if (strcmp(vl_def->type, vl->type) != 0) {
2591 if (write_part_string(&buffer, &buffer_size, TYPE_TYPE, vl->type,
2592 strlen(vl->type)) != 0)
2594 sstrncpy(vl_def->type, ds->type, sizeof(vl_def->type));
2597 if (strcmp(vl_def->type_instance, vl->type_instance) != 0) {
2598 if (write_part_string(&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2599 vl->type_instance, strlen(vl->type_instance)) != 0)
2601 sstrncpy(vl_def->type_instance, vl->type_instance,
2602 sizeof(vl_def->type_instance));
2605 if (write_part_values(&buffer, &buffer_size, ds, vl) != 0)
2608 return buffer - buffer_orig;
2609 } /* }}} int add_to_buffer */
2611 static void flush_buffer(void) {
2612 DEBUG("network plugin: flush_buffer: send_buffer_fill = %i",
2615 network_send_buffer(send_buffer, (size_t)send_buffer_fill);
2617 stats_octets_tx += ((uint64_t)send_buffer_fill);
2620 network_init_buffer();
2623 static int network_write(const data_set_t *ds, const value_list_t *vl,
2624 user_data_t __attribute__((unused)) * user_data) {
2627 /* listen_loop is set to non-zero in the shutdown callback, which is
2628 * guaranteed to be called *after* all the write threads have been shut
2630 assert(listen_loop == 0);
2632 if (!check_send_okay(vl)) {
2634 char name[6 * DATA_MAX_NAME_LEN];
2635 FORMAT_VL(name, sizeof(name), vl);
2636 name[sizeof(name) - 1] = 0;
2637 DEBUG("network plugin: network_write: "
2641 /* Counter is not protected by another lock and may be reached by
2642 * multiple threads */
2643 pthread_mutex_lock(&stats_lock);
2644 stats_values_not_sent++;
2645 pthread_mutex_unlock(&stats_lock);
2649 uc_meta_data_add_unsigned_int(vl, "network:time_sent", (uint64_t)vl->time);
2651 pthread_mutex_lock(&send_buffer_lock);
2654 add_to_buffer(send_buffer_ptr, network_config_packet_size -
2655 (send_buffer_fill + BUFF_SIG_SIZE),
2656 &send_buffer_vl, ds, vl);
2658 /* status == bytes added to the buffer */
2659 send_buffer_fill += status;
2660 send_buffer_ptr += status;
2661 send_buffer_last_update = cdtime();
2663 stats_values_sent++;
2668 add_to_buffer(send_buffer_ptr, network_config_packet_size -
2669 (send_buffer_fill + BUFF_SIG_SIZE),
2670 &send_buffer_vl, ds, vl);
2673 send_buffer_fill += status;
2674 send_buffer_ptr += status;
2676 stats_values_sent++;
2681 ERROR("network plugin: Unable to append to the "
2682 "buffer for some weird reason");
2683 } else if ((network_config_packet_size - send_buffer_fill) < 15) {
2687 pthread_mutex_unlock(&send_buffer_lock);
2689 return (status < 0) ? -1 : 0;
2690 } /* int network_write */
2692 static int network_config_set_ttl(const oconfig_item_t *ci) /* {{{ */
2696 if (cf_util_get_int(ci, &tmp) != 0)
2698 else if ((tmp > 0) && (tmp <= 255))
2699 network_config_ttl = tmp;
2701 WARNING("network plugin: The `TimeToLive' must be between 1 and 255.");
2706 } /* }}} int network_config_set_ttl */
2708 static int network_config_set_interface(const oconfig_item_t *ci, /* {{{ */
2712 if (cf_util_get_string_buffer(ci, if_name, sizeof(if_name)) != 0)
2715 *interface = if_nametoindex(if_name);
2717 } /* }}} int network_config_set_interface */
2719 static int network_config_set_buffer_size(const oconfig_item_t *ci) /* {{{ */
2723 if (cf_util_get_int(ci, &tmp) != 0)
2725 else if ((tmp >= 1024) && (tmp <= 65535))
2726 network_config_packet_size = tmp;
2729 "network plugin: The `MaxPacketSize' must be between 1024 and 65535.");
2734 } /* }}} int network_config_set_buffer_size */
2737 static int network_config_set_security_level(oconfig_item_t *ci, /* {{{ */
2740 if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
2741 WARNING("network plugin: The `SecurityLevel' config option needs exactly "
2742 "one string argument.");
2746 str = ci->values[0].value.string;
2747 if (strcasecmp("Encrypt", str) == 0)
2748 *retval = SECURITY_LEVEL_ENCRYPT;
2749 else if (strcasecmp("Sign", str) == 0)
2750 *retval = SECURITY_LEVEL_SIGN;
2751 else if (strcasecmp("None", str) == 0)
2752 *retval = SECURITY_LEVEL_NONE;
2754 WARNING("network plugin: Unknown security level: %s.", str);
2759 } /* }}} int network_config_set_security_level */
2760 #endif /* HAVE_GCRYPT_H */
2762 static int network_config_add_listen(const oconfig_item_t *ci) /* {{{ */
2767 if ((ci->values_num < 1) || (ci->values_num > 2) ||
2768 (ci->values[0].type != OCONFIG_TYPE_STRING) ||
2769 ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING))) {
2770 ERROR("network plugin: The `%s' config option needs "
2771 "one or two string arguments.",
2776 se = sockent_create(SOCKENT_TYPE_SERVER);
2778 ERROR("network plugin: sockent_create failed.");
2782 se->node = strdup(ci->values[0].value.string);
2783 if (ci->values_num >= 2)
2784 se->service = strdup(ci->values[1].value.string);
2786 for (int i = 0; i < ci->children_num; i++) {
2787 oconfig_item_t *child = ci->children + i;
2790 if (strcasecmp("AuthFile", child->key) == 0)
2791 cf_util_get_string(child, &se->data.server.auth_file);
2792 else if (strcasecmp("SecurityLevel", child->key) == 0)
2793 network_config_set_security_level(child, &se->data.server.security_level);
2795 #endif /* HAVE_GCRYPT_H */
2796 if (strcasecmp("Interface", child->key) == 0)
2797 network_config_set_interface(child, &se->interface);
2799 WARNING("network plugin: Option `%s' is not allowed here.", child->key);
2804 if ((se->data.server.security_level > SECURITY_LEVEL_NONE) &&
2805 (se->data.server.auth_file == NULL)) {
2806 ERROR("network plugin: A security level higher than `none' was "
2807 "requested, but no AuthFile option was given. Cowardly refusing to "
2808 "open this socket!");
2809 sockent_destroy(se);
2812 #endif /* HAVE_GCRYPT_H */
2814 status = sockent_init_crypto(se);
2816 ERROR("network plugin: network_config_add_listen: sockent_init_crypto() "
2818 sockent_destroy(se);
2822 status = sockent_server_listen(se);
2824 ERROR("network plugin: network_config_add_listen: sockent_server_listen "
2826 sockent_destroy(se);
2830 status = sockent_add(se);
2832 ERROR("network plugin: network_config_add_listen: sockent_add failed.");
2833 sockent_destroy(se);
2838 } /* }}} int network_config_add_listen */
2840 static int network_config_add_server(const oconfig_item_t *ci) /* {{{ */
2845 if ((ci->values_num < 1) || (ci->values_num > 2) ||
2846 (ci->values[0].type != OCONFIG_TYPE_STRING) ||
2847 ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING))) {
2848 ERROR("network plugin: The `%s' config option needs "
2849 "one or two string arguments.",
2854 se = sockent_create(SOCKENT_TYPE_CLIENT);
2856 ERROR("network plugin: sockent_create failed.");
2860 se->node = strdup(ci->values[0].value.string);
2861 if (ci->values_num >= 2)
2862 se->service = strdup(ci->values[1].value.string);
2864 for (int i = 0; i < ci->children_num; i++) {
2865 oconfig_item_t *child = ci->children + i;
2868 if (strcasecmp("Username", child->key) == 0)
2869 cf_util_get_string(child, &se->data.client.username);
2870 else if (strcasecmp("Password", child->key) == 0)
2871 cf_util_get_string(child, &se->data.client.password);
2872 else if (strcasecmp("SecurityLevel", child->key) == 0)
2873 network_config_set_security_level(child, &se->data.client.security_level);
2875 #endif /* HAVE_GCRYPT_H */
2876 if (strcasecmp("Interface", child->key) == 0)
2877 network_config_set_interface(child, &se->interface);
2878 else if (strcasecmp("ResolveInterval", child->key) == 0)
2879 cf_util_get_cdtime(child, &se->data.client.resolve_interval);
2881 WARNING("network plugin: Option `%s' is not allowed here.", child->key);
2886 if ((se->data.client.security_level > SECURITY_LEVEL_NONE) &&
2887 ((se->data.client.username == NULL) ||
2888 (se->data.client.password == NULL))) {
2889 ERROR("network plugin: A security level higher than `none' was "
2890 "requested, but no Username or Password option was given. "
2891 "Cowardly refusing to open this socket!");
2892 sockent_destroy(se);
2895 #endif /* HAVE_GCRYPT_H */
2897 status = sockent_init_crypto(se);
2899 ERROR("network plugin: network_config_add_server: sockent_init_crypto() "
2901 sockent_destroy(se);
2905 /* No call to sockent_client_connect() here -- it is called from
2906 * network_send_buffer_plain(). */
2908 status = sockent_add(se);
2910 ERROR("network plugin: network_config_add_server: sockent_add failed.");
2911 sockent_destroy(se);
2916 } /* }}} int network_config_add_server */
2918 static int network_config(oconfig_item_t *ci) /* {{{ */
2920 /* The options need to be applied first */
2921 for (int i = 0; i < ci->children_num; i++) {
2922 oconfig_item_t *child = ci->children + i;
2923 if (strcasecmp("TimeToLive", child->key) == 0)
2924 network_config_set_ttl(child);
2927 for (int i = 0; i < ci->children_num; i++) {
2928 oconfig_item_t *child = ci->children + i;
2930 if (strcasecmp("Listen", child->key) == 0)
2931 network_config_add_listen(child);
2932 else if (strcasecmp("Server", child->key) == 0)
2933 network_config_add_server(child);
2934 else if (strcasecmp("TimeToLive", child->key) == 0) {
2935 /* Handled earlier */
2936 } else if (strcasecmp("MaxPacketSize", child->key) == 0)
2937 network_config_set_buffer_size(child);
2938 else if (strcasecmp("Forward", child->key) == 0)
2939 cf_util_get_boolean(child, &network_config_forward);
2940 else if (strcasecmp("ReportStats", child->key) == 0)
2941 cf_util_get_boolean(child, &network_config_stats);
2943 WARNING("network plugin: Option `%s' is not allowed here.", child->key);
2948 } /* }}} int network_config */
2950 static int network_notification(const notification_t *n,
2951 user_data_t __attribute__((unused)) *
2953 char buffer[network_config_packet_size];
2954 char *buffer_ptr = buffer;
2955 size_t buffer_free = sizeof(buffer);
2958 if (!check_send_notify_okay(n))
2961 memset(buffer, 0, sizeof(buffer));
2963 status = write_part_number(&buffer_ptr, &buffer_free, TYPE_TIME_HR,
2968 status = write_part_number(&buffer_ptr, &buffer_free, TYPE_SEVERITY,
2969 (uint64_t)n->severity);
2973 if (strlen(n->host) > 0) {
2974 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_HOST, n->host,
2980 if (strlen(n->plugin) > 0) {
2981 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_PLUGIN,
2982 n->plugin, strlen(n->plugin));
2987 if (strlen(n->plugin_instance) > 0) {
2988 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_PLUGIN_INSTANCE,
2989 n->plugin_instance, strlen(n->plugin_instance));
2994 if (strlen(n->type) > 0) {
2995 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_TYPE, n->type,
3001 if (strlen(n->type_instance) > 0) {
3002 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3003 n->type_instance, strlen(n->type_instance));
3008 status = write_part_string(&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3009 n->message, strlen(n->message));
3013 network_send_buffer(buffer, sizeof(buffer) - buffer_free);
3016 } /* int network_notification */
3018 static int network_shutdown(void) {
3021 /* Kill the listening thread */
3022 if (receive_thread_running != 0) {
3023 INFO("network plugin: Stopping receive thread.");
3024 pthread_kill(receive_thread_id, SIGTERM);
3025 pthread_join(receive_thread_id, NULL /* no return value */);
3026 memset(&receive_thread_id, 0, sizeof(receive_thread_id));
3027 receive_thread_running = 0;
3030 /* Shutdown the dispatching thread */
3031 if (dispatch_thread_running != 0) {
3032 INFO("network plugin: Stopping dispatch thread.");
3033 pthread_mutex_lock(&receive_list_lock);
3034 pthread_cond_broadcast(&receive_list_cond);
3035 pthread_mutex_unlock(&receive_list_lock);
3036 pthread_join(dispatch_thread_id, /* ret = */ NULL);
3037 dispatch_thread_running = 0;
3040 sockent_destroy(listen_sockets);
3042 if (send_buffer_fill > 0)
3047 for (sockent_t *se = sending_sockets; se != NULL; se = se->next)
3048 sockent_client_disconnect(se);
3049 sockent_destroy(sending_sockets);
3051 plugin_unregister_config("network");
3052 plugin_unregister_init("network");
3053 plugin_unregister_write("network");
3054 plugin_unregister_shutdown("network");
3057 } /* int network_shutdown */
3059 static int network_stats_read(void) /* {{{ */
3061 derive_t copy_octets_rx;
3062 derive_t copy_octets_tx;
3063 derive_t copy_packets_rx;
3064 derive_t copy_packets_tx;
3065 derive_t copy_values_dispatched;
3066 derive_t copy_values_not_dispatched;
3067 derive_t copy_values_sent;
3068 derive_t copy_values_not_sent;
3069 derive_t copy_receive_list_length;
3070 value_list_t vl = VALUE_LIST_INIT;
3073 copy_octets_rx = stats_octets_rx;
3074 copy_octets_tx = stats_octets_tx;
3075 copy_packets_rx = stats_packets_rx;
3076 copy_packets_tx = stats_packets_tx;
3077 copy_values_dispatched = stats_values_dispatched;
3078 copy_values_not_dispatched = stats_values_not_dispatched;
3079 copy_values_sent = stats_values_sent;
3080 copy_values_not_sent = stats_values_not_sent;
3081 copy_receive_list_length = receive_list_length;
3083 /* Initialize `vl' */
3087 sstrncpy(vl.plugin, "network", sizeof(vl.plugin));
3089 /* Octets received / sent */
3090 vl.values[0].derive = (derive_t)copy_octets_rx;
3091 vl.values[1].derive = (derive_t)copy_octets_tx;
3092 sstrncpy(vl.type, "if_octets", sizeof(vl.type));
3093 plugin_dispatch_values(&vl);
3095 /* Packets received / send */
3096 vl.values[0].derive = (derive_t)copy_packets_rx;
3097 vl.values[1].derive = (derive_t)copy_packets_tx;
3098 sstrncpy(vl.type, "if_packets", sizeof(vl.type));
3099 plugin_dispatch_values(&vl);
3101 /* Values (not) dispatched and (not) send */
3102 sstrncpy(vl.type, "total_values", sizeof(vl.type));
3105 vl.values[0].derive = (derive_t)copy_values_dispatched;
3106 sstrncpy(vl.type_instance, "dispatch-accepted", sizeof(vl.type_instance));
3107 plugin_dispatch_values(&vl);
3109 vl.values[0].derive = (derive_t)copy_values_not_dispatched;
3110 sstrncpy(vl.type_instance, "dispatch-rejected", sizeof(vl.type_instance));
3111 plugin_dispatch_values(&vl);
3113 vl.values[0].derive = (derive_t)copy_values_sent;
3114 sstrncpy(vl.type_instance, "send-accepted", sizeof(vl.type_instance));
3115 plugin_dispatch_values(&vl);
3117 vl.values[0].derive = (derive_t)copy_values_not_sent;
3118 sstrncpy(vl.type_instance, "send-rejected", sizeof(vl.type_instance));
3119 plugin_dispatch_values(&vl);
3121 /* Receive queue length */
3122 vl.values[0].gauge = (gauge_t)copy_receive_list_length;
3123 sstrncpy(vl.type, "queue_length", sizeof(vl.type));
3124 vl.type_instance[0] = 0;
3125 plugin_dispatch_values(&vl);
3128 } /* }}} int network_stats_read */
3130 static int network_init(void) {
3131 static _Bool have_init = 0;
3133 /* Check if we were already initialized. If so, just return - there's
3134 * nothing more to do (for now, that is). */
3139 if (network_config_stats)
3140 plugin_register_read("network", network_stats_read);
3142 plugin_register_shutdown("network", network_shutdown);
3144 send_buffer = malloc(network_config_packet_size);
3145 if (send_buffer == NULL) {
3146 ERROR("network plugin: malloc failed.");
3149 network_init_buffer();
3151 /* setup socket(s) and so on */
3152 if (sending_sockets != NULL) {
3153 plugin_register_write("network", network_write,
3154 /* user_data = */ NULL);
3155 plugin_register_notification("network", network_notification,
3156 /* user_data = */ NULL);
3159 /* If no threads need to be started, return here. */
3160 if ((listen_sockets_num == 0) ||
3161 ((dispatch_thread_running != 0) && (receive_thread_running != 0)))
3164 if (dispatch_thread_running == 0) {
3166 status = plugin_thread_create(&dispatch_thread_id, NULL /* no attributes */,
3167 dispatch_thread, NULL /* no argument */,
3171 ERROR("network: pthread_create failed: %s",
3172 sstrerror(errno, errbuf, sizeof(errbuf)));
3174 dispatch_thread_running = 1;
3178 if (receive_thread_running == 0) {
3180 status = plugin_thread_create(&receive_thread_id, NULL /* no attributes */,
3181 receive_thread, NULL /* no argument */,
3185 ERROR("network: pthread_create failed: %s",
3186 sstrerror(errno, errbuf, sizeof(errbuf)));
3188 receive_thread_running = 1;
3193 } /* int network_init */
3196 * The flush option of the network plugin cannot flush individual identifiers.
3197 * All the values are added to a buffer and sent when the buffer is full, the
3198 * requested value may or may not be in there, it's not worth finding out. We
3199 * just send the buffer if `flush' is called - if the requested value was in
3200 * there, good. If not, well, then there is nothing to flush.. -octo
3202 static int network_flush(cdtime_t timeout,
3203 __attribute__((unused)) const char *identifier,
3204 __attribute__((unused)) user_data_t *user_data) {
3205 pthread_mutex_lock(&send_buffer_lock);
3207 if (send_buffer_fill > 0) {
3209 cdtime_t now = cdtime();
3210 if ((send_buffer_last_update + timeout) > now) {
3211 pthread_mutex_unlock(&send_buffer_lock);
3217 pthread_mutex_unlock(&send_buffer_lock);
3220 } /* int network_flush */
3222 void module_register(void) {
3223 plugin_register_complex_config("network", network_config);
3224 plugin_register_init("network", network_init);
3225 plugin_register_flush("network", network_flush,
3226 /* user_data = */ NULL);
3227 } /* void module_register */