2 * collectd - src/network.c
3 * Copyright (C) 2005-2009 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 verplant.org>
22 * Aman Gupta <aman at tmm1.net>
25 #define _BSD_SOURCE /* For struct ip_mreq */
30 #include "configfile.h"
31 #include "utils_fbhash.h"
32 #include "utils_avltree.h"
33 #include "utils_cache.h"
34 #include "utils_complain.h"
42 # include <sys/socket.h>
48 # include <netinet/in.h>
51 # include <arpa/inet.h>
62 # if defined __APPLE__
63 /* default xcode compiler throws warnings even when deprecated functionality
64 * is not used. -Werror breaks the build because of erroneous warnings.
65 * http://stackoverflow.com/questions/10556299/compiler-warnings-with-libgcrypt-v1-5-0/12830209#12830209
67 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
70 # if defined __APPLE__
71 /* Re enable deprecation warnings */
72 # pragma GCC diagnostic warning "-Wdeprecated-declarations"
74 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
106 struct sockaddr_storage *addr;
112 gcry_cipher_hd_t cypher;
113 unsigned char password_hash[32];
117 struct sockent_server
125 gcry_cipher_hd_t cypher;
129 typedef struct sockent
131 #define SOCKENT_TYPE_CLIENT 1
132 #define SOCKENT_TYPE_SERVER 2
141 struct sockent_client client;
142 struct sockent_server server;
145 struct sockent *next;
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 * +-------+-----------------------+-------------------------------+
159 typedef struct part_header_s part_header_t;
161 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
162 * 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
163 * +-------------------------------+-------------------------------+
165 * +-------------------------------+-------------------------------+
166 * : (Length - 4) Bytes :
167 * +---------------------------------------------------------------+
174 typedef struct part_string_s part_string_t;
176 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
177 * 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
178 * +-------------------------------+-------------------------------+
180 * +-------------------------------+-------------------------------+
181 * : (Length - 4 == 2 || 4 || 8) Bytes :
182 * +---------------------------------------------------------------+
189 typedef struct part_number_s part_number_t;
191 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
192 * 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
193 * +-------------------------------+-------------------------------+
195 * +-------------------------------+---------------+---------------+
196 * ! Num of values ! Type0 ! Type1 !
197 * +-------------------------------+---------------+---------------+
200 * +---------------------------------------------------------------+
203 * +---------------------------------------------------------------+
208 uint16_t *num_values;
209 uint8_t *values_types;
212 typedef struct part_values_s part_values_t;
214 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
215 * 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
216 * +-------------------------------+-------------------------------+
218 * +-------------------------------+-------------------------------+
219 * ! Hash (Bits 0 - 31) !
221 * ! Hash (Bits 224 - 255) !
222 * +---------------------------------------------------------------+
225 #define PART_SIGNATURE_SHA256_SIZE 36
226 struct part_signature_sha256_s
229 unsigned char hash[32];
232 typedef struct part_signature_sha256_s part_signature_sha256_t;
234 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
235 * 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
236 * +-------------------------------+-------------------------------+
238 * +-------------------------------+-------------------------------+
239 * ! Original length ! Padding (0 - 15 bytes) !
240 * +-------------------------------+-------------------------------+
241 * ! Hash (Bits 0 - 31) !
243 * ! Hash (Bits 128 - 159) !
244 * +---------------------------------------------------------------+
247 #define PART_ENCRYPTION_AES256_SIZE 42
248 struct part_encryption_aes256_s
251 uint16_t username_length;
253 unsigned char iv[16];
255 unsigned char hash[20];
259 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
261 struct receive_list_entry_s
266 struct receive_list_entry_s *next;
268 typedef struct receive_list_entry_s receive_list_entry_t;
273 static int network_config_ttl = 0;
274 static size_t network_config_packet_size = 1024;
275 static int network_config_forward = 0;
276 static int network_config_stats = 0;
278 static sockent_t *sending_sockets = NULL;
280 static receive_list_entry_t *receive_list_head = NULL;
281 static receive_list_entry_t *receive_list_tail = NULL;
282 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
283 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
284 static uint64_t receive_list_length = 0;
286 static sockent_t *listen_sockets = NULL;
287 static struct pollfd *listen_sockets_pollfd = NULL;
288 static size_t listen_sockets_num = 0;
290 /* The receive and dispatch threads will run as long as `listen_loop' is set to
292 static int listen_loop = 0;
293 static int receive_thread_running = 0;
294 static pthread_t receive_thread_id;
295 static int dispatch_thread_running = 0;
296 static pthread_t dispatch_thread_id;
298 /* Buffer in which to-be-sent network packets are constructed. */
299 static char *send_buffer;
300 static char *send_buffer_ptr;
301 static int send_buffer_fill;
302 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
303 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
305 /* XXX: These counters are incremented from one place only. The spot in which
306 * the values are incremented is either only reachable by one thread (the
307 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
308 * example). Only if neither is true, the stats_lock is acquired. The counters
309 * are always read without holding a lock in the hope that writing 8 bytes to
310 * memory is an atomic operation. */
311 static uint64_t stats_octets_rx = 0;
312 static uint64_t stats_octets_tx = 0;
313 static uint64_t stats_packets_rx = 0;
314 static uint64_t stats_packets_tx = 0;
315 static uint64_t stats_values_dispatched = 0;
316 static uint64_t stats_values_not_dispatched = 0;
317 static uint64_t stats_values_sent = 0;
318 static uint64_t stats_values_not_sent = 0;
319 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
324 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
326 uint64_t time_sent = 0;
329 status = uc_meta_data_get_unsigned_int (vl,
330 "network:time_sent", &time_sent);
332 /* This is a value we already sent. Don't allow it to be received again in
333 * order to avoid looping. */
334 if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
338 } /* }}} _Bool check_receive_okay */
340 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
342 _Bool received = false;
345 if (network_config_forward != 0)
348 if (vl->meta == NULL)
351 status = meta_data_get_boolean (vl->meta, "network:received", &received);
352 if (status == -ENOENT)
354 else if (status != 0)
356 ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
357 "with status %i.", status);
361 /* By default, only *send* value lists that were not *received* by the
364 } /* }}} _Bool check_send_okay */
366 static _Bool check_notify_received (const notification_t *n) /* {{{ */
368 notification_meta_t *ptr;
370 for (ptr = n->meta; ptr != NULL; ptr = ptr->next)
371 if ((strcmp ("network:received", ptr->name) == 0)
372 && (ptr->type == NM_TYPE_BOOLEAN))
373 return ((_Bool) ptr->nm_value.nm_boolean);
376 } /* }}} _Bool check_notify_received */
378 static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
380 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
386 received = check_notify_received (n);
388 if (network_config_forward && received)
390 c_complain_once (LOG_ERR, &complain_forwarding,
391 "network plugin: A notification has been received via the network "
392 "forwarding if enabled. Forwarding of notifications is currently "
393 "not supported, because there is not loop-deteciton available. "
394 "Please contact the collectd mailing list if you need this "
398 /* By default, only *send* value lists that were not *received* by the
401 } /* }}} _Bool check_send_notify_okay */
403 static int network_dispatch_values (value_list_t *vl, /* {{{ */
404 const char *username)
409 || (strlen (vl->host) <= 0)
410 || (strlen (vl->plugin) <= 0)
411 || (strlen (vl->type) <= 0))
414 if (!check_receive_okay (vl))
417 char name[6*DATA_MAX_NAME_LEN];
418 FORMAT_VL (name, sizeof (name), vl);
419 name[sizeof (name) - 1] = 0;
420 DEBUG ("network plugin: network_dispatch_values: "
421 "NOT dispatching %s.", name);
423 stats_values_not_dispatched++;
427 assert (vl->meta == NULL);
429 vl->meta = meta_data_create ();
430 if (vl->meta == NULL)
432 ERROR ("network plugin: meta_data_create failed.");
436 status = meta_data_add_boolean (vl->meta, "network:received", true);
439 ERROR ("network plugin: meta_data_add_boolean failed.");
440 meta_data_destroy (vl->meta);
445 if (username != NULL)
447 status = meta_data_add_string (vl->meta, "network:username", username);
450 ERROR ("network plugin: meta_data_add_string failed.");
451 meta_data_destroy (vl->meta);
457 plugin_dispatch_values_secure (vl);
458 stats_values_dispatched++;
460 meta_data_destroy (vl->meta);
464 } /* }}} int network_dispatch_values */
466 static int network_dispatch_notification (notification_t *n) /* {{{ */
470 assert (n->meta == NULL);
472 status = plugin_notification_meta_add_boolean (n, "network:received", 1);
475 ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
476 plugin_notification_meta_free (n->meta);
481 status = plugin_dispatch_notification (n);
483 plugin_notification_meta_free (n->meta);
487 } /* }}} int network_dispatch_notification */
490 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
491 const void *iv, size_t iv_size, const char *username)
494 gcry_cipher_hd_t *cyper_ptr;
495 unsigned char password_hash[32];
497 if (se->type == SOCKENT_TYPE_CLIENT)
499 cyper_ptr = &se->data.client.cypher;
500 memcpy (password_hash, se->data.client.password_hash,
501 sizeof (password_hash));
507 cyper_ptr = &se->data.server.cypher;
509 if (username == NULL)
512 secret = fbh_get (se->data.server.userdb, username);
516 gcry_md_hash_buffer (GCRY_MD_SHA256,
518 secret, strlen (secret));
523 if (*cyper_ptr == NULL)
525 err = gcry_cipher_open (cyper_ptr,
526 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
529 ERROR ("network plugin: gcry_cipher_open returned: %s",
530 gcry_strerror (err));
537 gcry_cipher_reset (*cyper_ptr);
539 assert (*cyper_ptr != NULL);
541 err = gcry_cipher_setkey (*cyper_ptr,
542 password_hash, sizeof (password_hash));
545 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
546 gcry_strerror (err));
547 gcry_cipher_close (*cyper_ptr);
552 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
555 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
556 gcry_strerror (err));
557 gcry_cipher_close (*cyper_ptr);
563 } /* }}} int network_get_aes256_cypher */
564 #endif /* HAVE_LIBGCRYPT */
566 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
567 const data_set_t *ds, const value_list_t *vl)
573 part_header_t pkg_ph;
574 uint16_t pkg_num_values;
575 uint8_t *pkg_values_types;
581 num_values = vl->values_len;
582 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
583 + (num_values * sizeof (uint8_t))
584 + (num_values * sizeof (value_t));
586 if (*ret_buffer_len < packet_len)
589 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
590 if (pkg_values_types == NULL)
592 ERROR ("network plugin: write_part_values: malloc failed.");
596 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
597 if (pkg_values == NULL)
599 free (pkg_values_types);
600 ERROR ("network plugin: write_part_values: malloc failed.");
604 pkg_ph.type = htons (TYPE_VALUES);
605 pkg_ph.length = htons (packet_len);
607 pkg_num_values = htons ((uint16_t) vl->values_len);
609 for (i = 0; i < num_values; i++)
611 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
612 switch (ds->ds[i].type)
614 case DS_TYPE_COUNTER:
615 pkg_values[i].counter = htonll (vl->values[i].counter);
619 pkg_values[i].gauge = htond (vl->values[i].gauge);
623 pkg_values[i].derive = htonll (vl->values[i].derive);
626 case DS_TYPE_ABSOLUTE:
627 pkg_values[i].absolute = htonll (vl->values[i].absolute);
631 free (pkg_values_types);
633 ERROR ("network plugin: write_part_values: "
634 "Unknown data source type: %i",
637 } /* switch (ds->ds[i].type) */
638 } /* for (num_values) */
641 * Use `memcpy' to write everything to the buffer, because the pointer
642 * may be unaligned and some architectures, such as SPARC, can't handle
645 packet_ptr = *ret_buffer;
647 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
648 offset += sizeof (pkg_ph);
649 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
650 offset += sizeof (pkg_num_values);
651 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
652 offset += num_values * sizeof (uint8_t);
653 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
654 offset += num_values * sizeof (value_t);
656 assert (offset == packet_len);
658 *ret_buffer = packet_ptr + packet_len;
659 *ret_buffer_len -= packet_len;
661 free (pkg_values_types);
665 } /* int write_part_values */
667 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
668 int type, uint64_t value)
673 part_header_t pkg_head;
678 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
680 if (*ret_buffer_len < packet_len)
683 pkg_head.type = htons (type);
684 pkg_head.length = htons (packet_len);
685 pkg_value = htonll (value);
687 packet_ptr = *ret_buffer;
689 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
690 offset += sizeof (pkg_head);
691 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
692 offset += sizeof (pkg_value);
694 assert (offset == packet_len);
696 *ret_buffer = packet_ptr + packet_len;
697 *ret_buffer_len -= packet_len;
700 } /* int write_part_number */
702 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
703 int type, const char *str, int 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, int *ret_num_values)
742 char *buffer = *ret_buffer;
743 size_t buffer_len = *ret_buffer_len;
758 NOTICE ("network plugin: packet is too short: "
759 "buffer_len = %zu", buffer_len);
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 = ntohs (tmp16);
775 assert (pkg_type == TYPE_VALUES);
777 exp_size = 3 * sizeof (uint16_t)
778 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
779 if (buffer_len < exp_size)
781 WARNING ("network plugin: parse_part_values: "
783 "Chunk of size %zu expected, "
784 "but buffer has only %zu bytes left.",
785 exp_size, buffer_len);
789 if (pkg_length != exp_size)
791 WARNING ("network plugin: parse_part_values: "
792 "Length and number of values "
793 "in the packet don't match.");
797 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
798 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
799 if ((pkg_types == NULL) || (pkg_values == NULL))
803 ERROR ("network plugin: parse_part_values: malloc failed.");
807 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
808 buffer += pkg_numval * sizeof (uint8_t);
809 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
810 buffer += pkg_numval * sizeof (value_t);
812 for (i = 0; i < pkg_numval; i++)
814 switch (pkg_types[i])
816 case DS_TYPE_COUNTER:
817 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
821 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
825 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
828 case DS_TYPE_ABSOLUTE:
829 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
833 NOTICE ("network plugin: parse_part_values: "
834 "Don't know how to handle data source type %"PRIu8,
839 } /* switch (pkg_types[i]) */
842 *ret_buffer = buffer;
843 *ret_buffer_len = buffer_len - pkg_length;
844 *ret_num_values = pkg_numval;
845 *ret_values = pkg_values;
850 } /* int parse_part_values */
852 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
855 char *buffer = *ret_buffer;
856 size_t buffer_len = *ret_buffer_len;
860 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
864 if (buffer_len < exp_size)
866 WARNING ("network plugin: parse_part_number: "
868 "Chunk of size %zu expected, "
869 "but buffer has only %zu bytes left.",
870 exp_size, buffer_len);
874 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
875 buffer += sizeof (tmp16);
876 /* pkg_type = ntohs (tmp16); */
878 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
879 buffer += sizeof (tmp16);
880 pkg_length = ntohs (tmp16);
882 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
883 buffer += sizeof (tmp64);
884 *value = ntohll (tmp64);
886 *ret_buffer = buffer;
887 *ret_buffer_len = buffer_len - pkg_length;
890 } /* int parse_part_number */
892 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
893 char *output, int output_len)
895 char *buffer = *ret_buffer;
896 size_t buffer_len = *ret_buffer_len;
899 size_t header_size = 2 * sizeof (uint16_t);
903 if (buffer_len < header_size)
905 WARNING ("network plugin: parse_part_string: "
907 "Chunk of at least size %zu expected, "
908 "but buffer has only %zu bytes left.",
909 header_size, buffer_len);
913 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
914 buffer += sizeof (tmp16);
915 /* pkg_type = ntohs (tmp16); */
917 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
918 buffer += sizeof (tmp16);
919 pkg_length = ntohs (tmp16);
921 /* Check that packet fits in the input buffer */
922 if (pkg_length > buffer_len)
924 WARNING ("network plugin: parse_part_string: "
926 "Chunk of size %"PRIu16" received, "
927 "but buffer has only %zu bytes left.",
928 pkg_length, buffer_len);
932 /* Check that pkg_length is in the valid range */
933 if (pkg_length <= header_size)
935 WARNING ("network plugin: parse_part_string: "
937 "Header claims this packet is only %hu "
938 "bytes long.", pkg_length);
942 /* Check that the package data fits into the output buffer.
943 * The previous if-statement ensures that:
944 * `pkg_length > header_size' */
946 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
948 WARNING ("network plugin: parse_part_string: "
949 "Output buffer too small.");
953 /* All sanity checks successfull, let's copy the data over */
954 output_len = pkg_length - header_size;
955 memcpy ((void *) output, (void *) buffer, output_len);
956 buffer += output_len;
958 /* For some very weird reason '\0' doesn't do the trick on SPARC in
960 if (output[output_len - 1] != 0)
962 WARNING ("network plugin: parse_part_string: "
963 "Received string does not end "
964 "with a NULL-byte.");
968 *ret_buffer = buffer;
969 *ret_buffer_len = buffer_len - pkg_length;
972 } /* int parse_part_string */
974 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
975 * parse_packet and vice versa. */
976 #define PP_SIGNED 0x01
977 #define PP_ENCRYPTED 0x02
978 static int parse_packet (sockent_t *se,
979 void *buffer, size_t buffer_size, int flags,
980 const char *username);
982 #define BUFFER_READ(p,s) do { \
983 memcpy ((p), buffer + buffer_offset, (s)); \
984 buffer_offset += (s); \
988 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
989 void **ret_buffer, size_t *ret_buffer_len, int flags)
991 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
995 size_t buffer_offset;
1000 part_signature_sha256_t pss;
1001 uint16_t pss_head_length;
1002 char hash[sizeof (pss.hash)];
1006 unsigned char *hash_ptr;
1008 buffer = *ret_buffer;
1009 buffer_len = *ret_buffer_len;
1012 if (se->data.server.userdb == NULL)
1014 c_complain (LOG_NOTICE, &complain_no_users,
1015 "network plugin: Received signed network packet but can't verify it "
1016 "because no user DB has been configured. Will accept it.");
1020 /* Check if the buffer has enough data for this structure. */
1021 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1024 /* Read type and length header */
1025 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1026 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1027 pss_head_length = ntohs (pss.head.length);
1029 /* Check if the `pss_head_length' is within bounds. */
1030 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1031 || (pss_head_length > buffer_len))
1033 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1037 /* Copy the hash. */
1038 BUFFER_READ (pss.hash, sizeof (pss.hash));
1040 /* Calculate username length (without null byte) and allocate memory */
1041 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1042 pss.username = malloc (username_len + 1);
1043 if (pss.username == NULL)
1046 /* Read the username */
1047 BUFFER_READ (pss.username, username_len);
1048 pss.username[username_len] = 0;
1050 assert (buffer_offset == pss_head_length);
1052 /* Query the password */
1053 secret = fbh_get (se->data.server.userdb, pss.username);
1056 ERROR ("network plugin: Unknown user: %s", pss.username);
1057 sfree (pss.username);
1061 /* Create a hash device and check the HMAC */
1063 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1066 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1067 gcry_strerror (err));
1069 sfree (pss.username);
1073 err = gcry_md_setkey (hd, secret, strlen (secret));
1076 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1079 sfree (pss.username);
1084 buffer + PART_SIGNATURE_SHA256_SIZE,
1085 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1086 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1087 if (hash_ptr == NULL)
1089 ERROR ("network plugin: gcry_md_read failed.");
1092 sfree (pss.username);
1095 memcpy (hash, hash_ptr, sizeof (hash));
1101 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1103 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1108 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1109 flags | PP_SIGNED, pss.username);
1113 sfree (pss.username);
1115 *ret_buffer = buffer + buffer_len;
1116 *ret_buffer_len = 0;
1119 } /* }}} int parse_part_sign_sha256 */
1120 /* #endif HAVE_LIBGCRYPT */
1122 #else /* if !HAVE_LIBGCRYPT */
1123 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1124 void **ret_buffer, size_t *ret_buffer_size, int flags)
1126 static int warning_has_been_printed = 0;
1130 size_t buffer_offset;
1133 part_signature_sha256_t pss;
1135 buffer = *ret_buffer;
1136 buffer_size = *ret_buffer_size;
1139 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1142 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1143 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1144 part_len = ntohs (pss.head.length);
1146 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1147 || (part_len > buffer_size))
1150 if (warning_has_been_printed == 0)
1152 WARNING ("network plugin: Received signed packet, but the network "
1153 "plugin was not linked with libgcrypt, so I cannot "
1154 "verify the signature. The packet will be accepted.");
1155 warning_has_been_printed = 1;
1158 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1159 /* username = */ NULL);
1161 *ret_buffer = buffer + buffer_size;
1162 *ret_buffer_size = 0;
1165 } /* }}} int parse_part_sign_sha256 */
1166 #endif /* !HAVE_LIBGCRYPT */
1169 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1170 void **ret_buffer, size_t *ret_buffer_len,
1173 char *buffer = *ret_buffer;
1174 size_t buffer_len = *ret_buffer_len;
1177 size_t buffer_offset;
1178 uint16_t username_len;
1179 part_encryption_aes256_t pea;
1180 unsigned char hash[sizeof (pea.hash)];
1182 gcry_cipher_hd_t cypher;
1185 /* Make sure at least the header if available. */
1186 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1188 NOTICE ("network plugin: parse_part_encr_aes256: "
1189 "Discarding short packet.");
1195 /* Copy the unencrypted information into `pea'. */
1196 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1197 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1199 /* Check the `part size'. */
1200 part_size = ntohs (pea.head.length);
1201 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1202 || (part_size > buffer_len))
1204 NOTICE ("network plugin: parse_part_encr_aes256: "
1205 "Discarding part with invalid size.");
1209 /* Read the username */
1210 BUFFER_READ (&username_len, sizeof (username_len));
1211 username_len = ntohs (username_len);
1213 if ((username_len <= 0)
1214 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1216 NOTICE ("network plugin: parse_part_encr_aes256: "
1217 "Discarding part with invalid username length.");
1221 assert (username_len > 0);
1222 pea.username = malloc (username_len + 1);
1223 if (pea.username == NULL)
1225 BUFFER_READ (pea.username, username_len);
1226 pea.username[username_len] = 0;
1228 /* Last but not least, the initialization vector */
1229 BUFFER_READ (pea.iv, sizeof (pea.iv));
1231 /* Make sure we are at the right position */
1232 assert (buffer_offset == (username_len +
1233 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1235 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1239 sfree (pea.username);
1243 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1244 assert (payload_len > 0);
1246 /* Decrypt the packet in-place */
1247 err = gcry_cipher_decrypt (cypher,
1248 buffer + buffer_offset,
1249 part_size - buffer_offset,
1250 /* in = */ NULL, /* in len = */ 0);
1253 sfree (pea.username);
1254 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1255 gcry_strerror (err));
1260 BUFFER_READ (pea.hash, sizeof (pea.hash));
1262 /* Make sure we're at the right position - again */
1263 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1264 assert (buffer_offset == (part_size - payload_len));
1266 /* Check hash sum */
1267 memset (hash, 0, sizeof (hash));
1268 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1269 buffer + buffer_offset, payload_len);
1270 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1272 sfree (pea.username);
1273 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1277 parse_packet (se, buffer + buffer_offset, payload_len,
1278 flags | PP_ENCRYPTED, pea.username);
1280 /* XXX: Free pea.username?!? */
1282 /* Update return values */
1283 *ret_buffer = buffer + part_size;
1284 *ret_buffer_len = buffer_len - part_size;
1286 sfree (pea.username);
1289 } /* }}} int parse_part_encr_aes256 */
1290 /* #endif HAVE_LIBGCRYPT */
1292 #else /* if !HAVE_LIBGCRYPT */
1293 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1294 void **ret_buffer, size_t *ret_buffer_size, int flags)
1296 static int warning_has_been_printed = 0;
1300 size_t buffer_offset;
1305 buffer = *ret_buffer;
1306 buffer_size = *ret_buffer_size;
1309 /* parse_packet assures this minimum size. */
1310 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1312 BUFFER_READ (&ph.type, sizeof (ph.type));
1313 BUFFER_READ (&ph.length, sizeof (ph.length));
1314 ph_length = ntohs (ph.length);
1316 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1317 || (ph_length > buffer_size))
1319 ERROR ("network plugin: AES-256 encrypted part "
1320 "with invalid length received.");
1324 if (warning_has_been_printed == 0)
1326 WARNING ("network plugin: Received encrypted packet, but the network "
1327 "plugin was not linked with libgcrypt, so I cannot "
1328 "decrypt it. The part will be discarded.");
1329 warning_has_been_printed = 1;
1332 *ret_buffer += ph_length;
1333 *ret_buffer_size -= ph_length;
1336 } /* }}} int parse_part_encr_aes256 */
1337 #endif /* !HAVE_LIBGCRYPT */
1341 static int parse_packet (sockent_t *se, /* {{{ */
1342 void *buffer, size_t buffer_size, int flags,
1343 const char *username)
1347 value_list_t vl = VALUE_LIST_INIT;
1351 int packet_was_signed = (flags & PP_SIGNED);
1352 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1353 int printed_ignore_warning = 0;
1354 #endif /* HAVE_LIBGCRYPT */
1357 memset (&vl, '\0', sizeof (vl));
1358 memset (&n, '\0', sizeof (n));
1361 while ((status == 0) && (0 < buffer_size)
1362 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1364 uint16_t pkg_length;
1367 memcpy ((void *) &pkg_type,
1370 memcpy ((void *) &pkg_length,
1371 (void *) (buffer + sizeof (pkg_type)),
1372 sizeof (pkg_length));
1374 pkg_length = ntohs (pkg_length);
1375 pkg_type = ntohs (pkg_type);
1377 if (pkg_length > buffer_size)
1379 /* Ensure that this loop terminates eventually */
1380 if (pkg_length < (2 * sizeof (uint16_t)))
1383 if (pkg_type == TYPE_ENCR_AES256)
1385 status = parse_part_encr_aes256 (se,
1386 &buffer, &buffer_size, flags);
1389 ERROR ("network plugin: Decrypting AES256 "
1391 "with status %i.", status);
1396 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1397 && (packet_was_encrypted == 0))
1399 if (printed_ignore_warning == 0)
1401 INFO ("network plugin: Unencrypted packet or "
1402 "part has been ignored.");
1403 printed_ignore_warning = 1;
1405 buffer = ((char *) buffer) + pkg_length;
1408 #endif /* HAVE_LIBGCRYPT */
1409 else if (pkg_type == TYPE_SIGN_SHA256)
1411 status = parse_part_sign_sha256 (se,
1412 &buffer, &buffer_size, flags);
1415 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1417 "with status %i.", status);
1422 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1423 && (packet_was_encrypted == 0)
1424 && (packet_was_signed == 0))
1426 if (printed_ignore_warning == 0)
1428 INFO ("network plugin: Unsigned packet or "
1429 "part has been ignored.");
1430 printed_ignore_warning = 1;
1432 buffer = ((char *) buffer) + pkg_length;
1435 #endif /* HAVE_LIBGCRYPT */
1436 else if (pkg_type == TYPE_VALUES)
1438 status = parse_part_values (&buffer, &buffer_size,
1439 &vl.values, &vl.values_len);
1443 network_dispatch_values (&vl, username);
1447 else if (pkg_type == TYPE_TIME)
1450 status = parse_part_number (&buffer, &buffer_size,
1454 vl.time = (time_t) tmp;
1455 n.time = (time_t) tmp;
1458 else if (pkg_type == TYPE_INTERVAL)
1461 status = parse_part_number (&buffer, &buffer_size,
1464 vl.interval = (int) tmp;
1466 else if (pkg_type == TYPE_HOST)
1468 status = parse_part_string (&buffer, &buffer_size,
1469 vl.host, sizeof (vl.host));
1471 sstrncpy (n.host, vl.host, sizeof (n.host));
1473 else if (pkg_type == TYPE_PLUGIN)
1475 status = parse_part_string (&buffer, &buffer_size,
1476 vl.plugin, sizeof (vl.plugin));
1478 sstrncpy (n.plugin, vl.plugin,
1481 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1483 status = parse_part_string (&buffer, &buffer_size,
1485 sizeof (vl.plugin_instance));
1487 sstrncpy (n.plugin_instance,
1489 sizeof (n.plugin_instance));
1491 else if (pkg_type == TYPE_TYPE)
1493 status = parse_part_string (&buffer, &buffer_size,
1494 vl.type, sizeof (vl.type));
1496 sstrncpy (n.type, vl.type, sizeof (n.type));
1498 else if (pkg_type == TYPE_TYPE_INSTANCE)
1500 status = parse_part_string (&buffer, &buffer_size,
1502 sizeof (vl.type_instance));
1504 sstrncpy (n.type_instance, vl.type_instance,
1505 sizeof (n.type_instance));
1507 else if (pkg_type == TYPE_MESSAGE)
1509 status = parse_part_string (&buffer, &buffer_size,
1510 n.message, sizeof (n.message));
1516 else if ((n.severity != NOTIF_FAILURE)
1517 && (n.severity != NOTIF_WARNING)
1518 && (n.severity != NOTIF_OKAY))
1520 INFO ("network plugin: "
1521 "Ignoring notification with "
1522 "unknown severity %i.",
1525 else if (n.time <= 0)
1527 INFO ("network plugin: "
1528 "Ignoring notification with "
1531 else if (strlen (n.message) <= 0)
1533 INFO ("network plugin: "
1534 "Ignoring notification with "
1535 "an empty message.");
1539 network_dispatch_notification (&n);
1542 else if (pkg_type == TYPE_SEVERITY)
1545 status = parse_part_number (&buffer, &buffer_size,
1548 n.severity = (int) tmp;
1552 DEBUG ("network plugin: parse_packet: Unknown part"
1553 " type: 0x%04hx", pkg_type);
1554 buffer = ((char *) buffer) + pkg_length;
1556 } /* while (buffer_size > sizeof (part_header_t)) */
1558 if (status == 0 && buffer_size > 0)
1559 WARNING ("network plugin: parse_packet: Received truncated "
1560 "packet, try increasing `MaxPacketSize'");
1563 } /* }}} int parse_packet */
1565 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1574 sfree (sec->username);
1575 sfree (sec->password);
1576 if (sec->cypher != NULL)
1577 gcry_cipher_close (sec->cypher);
1579 } /* }}} void free_sockent_client */
1581 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1585 for (i = 0; i < ses->fd_num; i++)
1587 if (ses->fd[i] >= 0)
1596 sfree (ses->auth_file);
1597 fbh_destroy (ses->userdb);
1598 if (ses->cypher != NULL)
1599 gcry_cipher_close (ses->cypher);
1601 } /* }}} void free_sockent_server */
1603 static void sockent_destroy (sockent_t *se) /* {{{ */
1607 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1614 sfree (se->service);
1616 if (se->type == SOCKENT_TYPE_CLIENT)
1617 free_sockent_client (&se->data.client);
1619 free_sockent_server (&se->data.server);
1624 } /* }}} void sockent_destroy */
1627 * int network_set_ttl
1629 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1630 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1632 * The `struct addrinfo' is used to destinguish between unicast and multicast
1635 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1637 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1638 network_config_ttl);
1640 assert (se->type == SOCKENT_TYPE_CLIENT);
1642 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1645 if (ai->ai_family == AF_INET)
1647 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1650 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1651 optname = IP_MULTICAST_TTL;
1655 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1656 &network_config_ttl,
1657 sizeof (network_config_ttl)) != 0)
1660 ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
1661 sstrerror (errno, errbuf, sizeof (errbuf)));
1665 else if (ai->ai_family == AF_INET6)
1667 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1668 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1671 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1672 optname = IPV6_MULTICAST_HOPS;
1674 optname = IPV6_UNICAST_HOPS;
1676 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1677 &network_config_ttl,
1678 sizeof (network_config_ttl)) != 0)
1681 ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
1682 sstrerror (errno, errbuf,
1689 } /* int network_set_ttl */
1691 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1693 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1696 assert (se->type == SOCKENT_TYPE_CLIENT);
1698 if (ai->ai_family == AF_INET)
1700 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1702 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1704 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1705 /* If possible, use the "ip_mreqn" structure which has
1706 * an "interface index" member. Using the interface
1707 * index is preferred here, because of its similarity
1708 * to the way IPv6 handles this. Unfortunately, it
1709 * appears not to be portable. */
1710 struct ip_mreqn mreq;
1712 memset (&mreq, 0, sizeof (mreq));
1713 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1714 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1715 mreq.imr_ifindex = se->interface;
1717 struct ip_mreq mreq;
1719 memset (&mreq, 0, sizeof (mreq));
1720 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1721 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1724 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1725 &mreq, sizeof (mreq)) != 0)
1728 ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
1729 sstrerror (errno, errbuf, sizeof (errbuf)));
1736 else if (ai->ai_family == AF_INET6)
1738 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1740 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1742 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1744 sizeof (se->interface)) != 0)
1747 ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
1748 sstrerror (errno, errbuf,
1757 /* else: Not a multicast interface. */
1758 if (se->interface != 0)
1760 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1761 char interface_name[IFNAMSIZ];
1763 if (if_indextoname (se->interface, interface_name) == NULL)
1766 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1768 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1770 sizeof(interface_name)) == -1 )
1773 ERROR ("network plugin: setsockopt (bind-if): %s",
1774 sstrerror (errno, errbuf, sizeof (errbuf)));
1777 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1780 WARNING ("network plugin: Cannot set the interface on a unicast "
1782 # if !defined(SO_BINDTODEVICE)
1783 "the \"SO_BINDTODEVICE\" socket option "
1785 "the \"if_indextoname\" function "
1787 "is not available on your system.");
1793 } /* }}} network_set_interface */
1795 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1804 /* allow multiple sockets to use the same PORT number */
1805 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1806 &yes, sizeof(yes)) == -1) {
1808 ERROR ("network plugin: setsockopt (reuseaddr): %s",
1809 sstrerror (errno, errbuf, sizeof (errbuf)));
1813 DEBUG ("fd = %i; calling `bind'", fd);
1815 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1819 sstrerror (errno, errbuf, sizeof (errbuf)));
1823 if (ai->ai_family == AF_INET)
1825 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1826 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1828 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1829 struct ip_mreqn mreq;
1831 struct ip_mreq mreq;
1834 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1836 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1837 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1838 /* Set the interface using the interface index if
1839 * possible (available). Unfortunately, the struct
1840 * ip_mreqn is not portable. */
1841 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1842 mreq.imr_ifindex = interface_idx;
1844 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1847 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1848 &loop, sizeof (loop)) == -1)
1851 ERROR ("network plugin: setsockopt (multicast-loop): %s",
1852 sstrerror (errno, errbuf,
1857 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1858 &mreq, sizeof (mreq)) == -1)
1861 ERROR ("network plugin: setsockopt (add-membership): %s",
1862 sstrerror (errno, errbuf,
1870 else if (ai->ai_family == AF_INET6)
1872 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1873 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1874 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1876 struct ipv6_mreq mreq;
1878 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1880 memcpy (&mreq.ipv6mr_multiaddr,
1882 sizeof (addr->sin6_addr));
1884 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1885 * ipv6mr_interface may be set to zeroes to
1886 * choose the default multicast interface or to
1887 * the index of a particular multicast-capable
1888 * interface if the host is multihomed.
1889 * Membership is associ-associated with a
1890 * single interface; programs running on
1891 * multihomed hosts may need to join the same
1892 * group on more than one interface.*/
1893 mreq.ipv6mr_interface = interface_idx;
1895 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1896 &loop, sizeof (loop)) == -1)
1899 ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
1900 sstrerror (errno, errbuf,
1905 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1906 &mreq, sizeof (mreq)) == -1)
1909 ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
1910 sstrerror (errno, errbuf,
1919 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1920 /* if a specific interface was set, bind the socket to it. But to avoid
1921 * possible problems with multicast routing, only do that for non-multicast
1923 if (interface_idx != 0)
1925 char interface_name[IFNAMSIZ];
1927 if (if_indextoname (interface_idx, interface_name) == NULL)
1930 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1932 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1934 sizeof(interface_name)) == -1 )
1937 ERROR ("network plugin: setsockopt (bind-if): %s",
1938 sstrerror (errno, errbuf, sizeof (errbuf)));
1942 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1945 } /* int network_bind_socket */
1947 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1948 * or `SOCKENT_TYPE_SERVER' */
1949 static int sockent_init (sockent_t *se, int type) /* {{{ */
1954 memset (se, 0, sizeof (*se));
1956 se->type = SOCKENT_TYPE_CLIENT;
1962 if (type == SOCKENT_TYPE_SERVER)
1964 se->type = SOCKENT_TYPE_SERVER;
1965 se->data.server.fd = NULL;
1967 se->data.server.security_level = SECURITY_LEVEL_NONE;
1968 se->data.server.auth_file = NULL;
1969 se->data.server.userdb = NULL;
1970 se->data.server.cypher = NULL;
1975 se->data.client.fd = -1;
1976 se->data.client.addr = NULL;
1978 se->data.client.security_level = SECURITY_LEVEL_NONE;
1979 se->data.client.username = NULL;
1980 se->data.client.password = NULL;
1981 se->data.client.cypher = NULL;
1986 } /* }}} int sockent_init */
1988 /* Open the file descriptors for a initialized sockent structure. */
1989 static int sockent_open (sockent_t *se) /* {{{ */
1991 struct addrinfo ai_hints;
1992 struct addrinfo *ai_list, *ai_ptr;
1996 const char *service;
2001 /* Set up the security structures. */
2002 #if HAVE_LIBGCRYPT /* {{{ */
2003 if (se->type == SOCKENT_TYPE_CLIENT)
2005 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
2007 if ((se->data.client.username == NULL)
2008 || (se->data.client.password == NULL))
2010 ERROR ("network plugin: Client socket with "
2011 "security requested, but no "
2012 "credentials are configured.");
2015 gcry_md_hash_buffer (GCRY_MD_SHA256,
2016 se->data.client.password_hash,
2017 se->data.client.password,
2018 strlen (se->data.client.password));
2021 else /* (se->type == SOCKENT_TYPE_SERVER) */
2023 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2025 if (se->data.server.auth_file == NULL)
2027 ERROR ("network plugin: Server socket with "
2028 "security requested, but no "
2029 "password file is configured.");
2033 if (se->data.server.auth_file != NULL)
2035 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2036 if (se->data.server.userdb == NULL)
2038 ERROR ("network plugin: Reading password file "
2040 se->data.server.auth_file);
2041 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2046 #endif /* }}} HAVE_LIBGCRYPT */
2049 service = se->service;
2051 if (service == NULL)
2052 service = NET_DEFAULT_PORT;
2054 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
2057 memset (&ai_hints, 0, sizeof (ai_hints));
2058 ai_hints.ai_flags = 0;
2060 ai_hints.ai_flags |= AI_PASSIVE;
2062 #ifdef AI_ADDRCONFIG
2063 ai_hints.ai_flags |= AI_ADDRCONFIG;
2065 ai_hints.ai_family = AF_UNSPEC;
2066 ai_hints.ai_socktype = SOCK_DGRAM;
2067 ai_hints.ai_protocol = IPPROTO_UDP;
2069 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2072 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2073 (se->node == NULL) ? "(null)" : se->node,
2074 (se->service == NULL) ? "(null)" : se->service,
2075 gai_strerror (ai_return));
2079 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2083 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2087 tmp = realloc (se->data.server.fd,
2088 sizeof (*tmp) * (se->data.server.fd_num + 1));
2091 ERROR ("network plugin: realloc failed.");
2094 se->data.server.fd = tmp;
2095 tmp = se->data.server.fd + se->data.server.fd_num;
2097 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2098 ai_ptr->ai_protocol);
2102 ERROR ("network plugin: socket(2) failed: %s",
2103 sstrerror (errno, errbuf,
2108 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2116 se->data.server.fd_num++;
2118 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2119 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2121 se->data.client.fd = socket (ai_ptr->ai_family,
2122 ai_ptr->ai_socktype,
2123 ai_ptr->ai_protocol);
2124 if (se->data.client.fd < 0)
2127 ERROR ("network plugin: socket(2) failed: %s",
2128 sstrerror (errno, errbuf,
2133 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2134 if (se->data.client.addr == NULL)
2136 ERROR ("network plugin: malloc failed.");
2137 close (se->data.client.fd);
2138 se->data.client.fd = -1;
2142 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2143 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2144 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2145 se->data.client.addrlen = ai_ptr->ai_addrlen;
2147 network_set_ttl (se, ai_ptr);
2148 network_set_interface (se, ai_ptr);
2150 /* We don't open more than one write-socket per
2151 * node/service pair.. */
2153 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2154 } /* for (ai_list) */
2156 freeaddrinfo (ai_list);
2158 /* Check if all went well. */
2159 if (se->type == SOCKENT_TYPE_SERVER)
2161 if (se->data.server.fd_num <= 0)
2164 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2166 if (se->data.client.fd < 0)
2171 } /* }}} int sockent_open */
2173 /* Add a sockent to the global list of sockets */
2174 static int sockent_add (sockent_t *se) /* {{{ */
2176 sockent_t *last_ptr;
2181 if (se->type == SOCKENT_TYPE_SERVER)
2186 tmp = realloc (listen_sockets_pollfd,
2187 sizeof (*tmp) * (listen_sockets_num
2188 + se->data.server.fd_num));
2191 ERROR ("network plugin: realloc failed.");
2194 listen_sockets_pollfd = tmp;
2195 tmp = listen_sockets_pollfd + listen_sockets_num;
2197 for (i = 0; i < se->data.server.fd_num; i++)
2199 memset (tmp + i, 0, sizeof (*tmp));
2200 tmp[i].fd = se->data.server.fd[i];
2201 tmp[i].events = POLLIN | POLLPRI;
2205 listen_sockets_num += se->data.server.fd_num;
2207 if (listen_sockets == NULL)
2209 listen_sockets = se;
2212 last_ptr = listen_sockets;
2214 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2216 if (sending_sockets == NULL)
2218 sending_sockets = se;
2221 last_ptr = sending_sockets;
2224 while (last_ptr->next != NULL)
2225 last_ptr = last_ptr->next;
2226 last_ptr->next = se;
2229 } /* }}} int sockent_add */
2231 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2235 receive_list_entry_t *ent;
2238 /* Lock and wait for more data to come in */
2239 pthread_mutex_lock (&receive_list_lock);
2240 while ((listen_loop == 0)
2241 && (receive_list_head == NULL))
2242 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2244 /* Remove the head entry and unlock */
2245 ent = receive_list_head;
2247 receive_list_head = ent->next;
2248 receive_list_length--;
2249 pthread_mutex_unlock (&receive_list_lock);
2251 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2252 * because we dispatch all missing packets before shutting down. */
2256 /* Look for the correct `sockent_t' */
2257 se = listen_sockets;
2262 for (i = 0; i < se->data.server.fd_num; i++)
2263 if (se->data.server.fd[i] == ent->fd)
2266 if (i < se->data.server.fd_num)
2274 ERROR ("network plugin: Got packet from FD %i, but can't "
2275 "find an appropriate socket entry.",
2282 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2283 /* username = */ NULL);
2289 } /* }}} void *dispatch_thread */
2291 static int network_receive (void) /* {{{ */
2293 char buffer[network_config_packet_size];
2299 receive_list_entry_t *private_list_head;
2300 receive_list_entry_t *private_list_tail;
2301 uint64_t private_list_length;
2303 assert (listen_sockets_num > 0);
2305 private_list_head = NULL;
2306 private_list_tail = NULL;
2307 private_list_length = 0;
2309 while (listen_loop == 0)
2311 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2318 ERROR ("poll failed: %s",
2319 sstrerror (errno, errbuf, sizeof (errbuf)));
2323 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2325 receive_list_entry_t *ent;
2327 if ((listen_sockets_pollfd[i].revents
2328 & (POLLIN | POLLPRI)) == 0)
2332 buffer_len = recv (listen_sockets_pollfd[i].fd,
2333 buffer, sizeof (buffer),
2338 ERROR ("recv failed: %s",
2339 sstrerror (errno, errbuf,
2344 stats_octets_rx += ((uint64_t) buffer_len);
2347 /* TODO: Possible performance enhancement: Do not free
2348 * these entries in the dispatch thread but put them in
2349 * another list, so we don't have to allocate more and
2350 * more of these structures. */
2351 ent = malloc (sizeof (receive_list_entry_t));
2354 ERROR ("network plugin: malloc failed.");
2357 memset (ent, 0, sizeof (receive_list_entry_t));
2358 ent->data = malloc (network_config_packet_size);
2359 if (ent->data == NULL)
2362 ERROR ("network plugin: malloc failed.");
2365 ent->fd = listen_sockets_pollfd[i].fd;
2368 memcpy (ent->data, buffer, buffer_len);
2369 ent->data_len = buffer_len;
2371 if (private_list_head == NULL)
2372 private_list_head = ent;
2374 private_list_tail->next = ent;
2375 private_list_tail = ent;
2376 private_list_length++;
2378 /* Do not block here. Blocking here has led to
2379 * insufficient performance in the past. */
2380 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2382 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2383 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2385 if (receive_list_head == NULL)
2386 receive_list_head = private_list_head;
2388 receive_list_tail->next = private_list_head;
2389 receive_list_tail = private_list_tail;
2390 receive_list_length += private_list_length;
2392 pthread_cond_signal (&receive_list_cond);
2393 pthread_mutex_unlock (&receive_list_lock);
2395 private_list_head = NULL;
2396 private_list_tail = NULL;
2397 private_list_length = 0;
2399 } /* for (listen_sockets_pollfd) */
2400 } /* while (listen_loop == 0) */
2402 /* Make sure everything is dispatched before exiting. */
2403 if (private_list_head != NULL)
2405 pthread_mutex_lock (&receive_list_lock);
2407 if (receive_list_head == NULL)
2408 receive_list_head = private_list_head;
2410 receive_list_tail->next = private_list_head;
2411 receive_list_tail = private_list_tail;
2412 receive_list_length += private_list_length;
2414 private_list_head = NULL;
2415 private_list_tail = NULL;
2416 private_list_length = 0;
2418 pthread_cond_signal (&receive_list_cond);
2419 pthread_mutex_unlock (&receive_list_lock);
2423 } /* }}} int network_receive */
2425 static void *receive_thread (void __attribute__((unused)) *arg)
2427 return (network_receive () ? (void *) 1 : (void *) 0);
2428 } /* void *receive_thread */
2430 static void network_init_buffer (void)
2432 memset (send_buffer, 0, network_config_packet_size);
2433 send_buffer_ptr = send_buffer;
2434 send_buffer_fill = 0;
2436 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2437 } /* int network_init_buffer */
2439 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2440 const char *buffer, size_t buffer_size)
2446 status = sendto (se->data.client.fd, buffer, buffer_size,
2448 (struct sockaddr *) se->data.client.addr,
2449 se->data.client.addrlen);
2455 ERROR ("network plugin: sendto failed: %s",
2456 sstrerror (errno, errbuf,
2463 } /* }}} void networt_send_buffer_plain */
2466 #define BUFFER_ADD(p,s) do { \
2467 memcpy (buffer + buffer_offset, (p), (s)); \
2468 buffer_offset += (s); \
2471 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2472 const char *in_buffer, size_t in_buffer_size)
2474 part_signature_sha256_t ps;
2475 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2476 size_t buffer_offset;
2477 size_t username_len;
2481 unsigned char *hash;
2484 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2487 ERROR ("network plugin: Creating HMAC object failed: %s",
2488 gcry_strerror (err));
2492 err = gcry_md_setkey (hd, se->data.client.password,
2493 strlen (se->data.client.password));
2496 ERROR ("network plugin: gcry_md_setkey failed: %s",
2497 gcry_strerror (err));
2502 username_len = strlen (se->data.client.username);
2503 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2505 ERROR ("network plugin: Username too long: %s",
2506 se->data.client.username);
2510 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2511 se->data.client.username, username_len);
2512 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2513 in_buffer, in_buffer_size);
2515 /* Initialize the `ps' structure. */
2516 memset (&ps, 0, sizeof (ps));
2517 ps.head.type = htons (TYPE_SIGN_SHA256);
2518 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2520 /* Calculate the hash value. */
2521 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2522 username_len + in_buffer_size);
2523 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2526 ERROR ("network plugin: gcry_md_read failed.");
2530 memcpy (ps.hash, hash, sizeof (ps.hash));
2532 /* Add the header */
2535 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2536 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2537 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2539 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2544 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2545 networt_send_buffer_plain (se, buffer, buffer_offset);
2546 } /* }}} void networt_send_buffer_signed */
2548 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2549 const char *in_buffer, size_t in_buffer_size)
2551 part_encryption_aes256_t pea;
2552 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2554 size_t buffer_offset;
2556 size_t username_len;
2558 gcry_cipher_hd_t cypher;
2560 /* Initialize the header fields */
2561 memset (&pea, 0, sizeof (pea));
2562 pea.head.type = htons (TYPE_ENCR_AES256);
2564 pea.username = se->data.client.username;
2566 username_len = strlen (pea.username);
2567 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2569 ERROR ("network plugin: Username too long: %s", pea.username);
2573 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2574 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2575 - sizeof (pea.hash);
2577 assert (buffer_size <= sizeof (buffer));
2578 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2579 "buffer_size = %zu;", buffer_size);
2581 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2582 + username_len + in_buffer_size));
2583 pea.username_length = htons ((uint16_t) username_len);
2585 /* Chose a random initialization vector. */
2586 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2588 /* Create hash of the payload */
2589 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2591 /* Initialize the buffer */
2593 memset (buffer, 0, sizeof (buffer));
2596 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2597 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2598 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2599 BUFFER_ADD (pea.username, username_len);
2600 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2601 assert (buffer_offset == header_size);
2602 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2603 BUFFER_ADD (in_buffer, in_buffer_size);
2605 assert (buffer_offset == buffer_size);
2607 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2608 se->data.client.password);
2612 /* Encrypt the buffer in-place */
2613 err = gcry_cipher_encrypt (cypher,
2614 buffer + header_size,
2615 buffer_size - header_size,
2616 /* in = */ NULL, /* in len = */ 0);
2619 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2620 gcry_strerror (err));
2624 /* Send it out without further modifications */
2625 networt_send_buffer_plain (se, buffer, buffer_size);
2626 } /* }}} void networt_send_buffer_encrypted */
2628 #endif /* HAVE_LIBGCRYPT */
2630 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2634 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2636 for (se = sending_sockets; se != NULL; se = se->next)
2639 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2640 networt_send_buffer_encrypted (se, buffer, buffer_len);
2641 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2642 networt_send_buffer_signed (se, buffer, buffer_len);
2643 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2644 #endif /* HAVE_LIBGCRYPT */
2645 networt_send_buffer_plain (se, buffer, buffer_len);
2646 } /* for (sending_sockets) */
2647 } /* }}} void network_send_buffer */
2649 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2650 value_list_t *vl_def,
2651 const data_set_t *ds, const value_list_t *vl)
2653 char *buffer_orig = buffer;
2655 if (strcmp (vl_def->host, vl->host) != 0)
2657 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2658 vl->host, strlen (vl->host)) != 0)
2660 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2663 if (vl_def->time != vl->time)
2665 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2666 (uint64_t) vl->time))
2668 vl_def->time = vl->time;
2671 if (vl_def->interval != vl->interval)
2673 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2674 (uint64_t) vl->interval))
2676 vl_def->interval = vl->interval;
2679 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2681 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2682 vl->plugin, strlen (vl->plugin)) != 0)
2684 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2687 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2689 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2690 vl->plugin_instance,
2691 strlen (vl->plugin_instance)) != 0)
2693 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2696 if (strcmp (vl_def->type, vl->type) != 0)
2698 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2699 vl->type, strlen (vl->type)) != 0)
2701 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2704 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2706 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2708 strlen (vl->type_instance)) != 0)
2710 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2713 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2716 return (buffer - buffer_orig);
2717 } /* }}} int add_to_buffer */
2719 static void flush_buffer (void)
2721 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2724 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2726 stats_octets_tx += ((uint64_t) send_buffer_fill);
2729 network_init_buffer ();
2732 static int network_write (const data_set_t *ds, const value_list_t *vl,
2733 user_data_t __attribute__((unused)) *user_data)
2737 if (!check_send_okay (vl))
2740 char name[6*DATA_MAX_NAME_LEN];
2741 FORMAT_VL (name, sizeof (name), vl);
2742 name[sizeof (name) - 1] = 0;
2743 DEBUG ("network plugin: network_write: "
2744 "NOT sending %s.", name);
2746 /* Counter is not protected by another lock and may be reached by
2747 * multiple threads */
2748 pthread_mutex_lock (&stats_lock);
2749 stats_values_not_sent++;
2750 pthread_mutex_unlock (&stats_lock);
2754 uc_meta_data_add_unsigned_int (vl,
2755 "network:time_sent", (uint64_t) vl->time);
2757 pthread_mutex_lock (&send_buffer_lock);
2759 status = add_to_buffer (send_buffer_ptr,
2760 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2765 /* status == bytes added to the buffer */
2766 send_buffer_fill += status;
2767 send_buffer_ptr += status;
2769 stats_values_sent++;
2775 status = add_to_buffer (send_buffer_ptr,
2776 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2782 send_buffer_fill += status;
2783 send_buffer_ptr += status;
2785 stats_values_sent++;
2791 ERROR ("network plugin: Unable to append to the "
2792 "buffer for some weird reason");
2794 else if ((network_config_packet_size - send_buffer_fill) < 15)
2799 pthread_mutex_unlock (&send_buffer_lock);
2801 return ((status < 0) ? -1 : 0);
2802 } /* int network_write */
2804 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2807 if ((ci->values_num != 1)
2808 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2809 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2811 ERROR ("network plugin: The `%s' config option needs "
2812 "exactly one boolean argument.", ci->key);
2816 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2818 if (ci->values[0].value.boolean)
2825 char *str = ci->values[0].value.string;
2829 else if (IS_FALSE (str))
2833 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2834 "option as boolean value.",
2841 } /* }}} int network_config_set_boolean */
2843 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2846 if ((ci->values_num != 1)
2847 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2849 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2850 "one numeric argument.");
2854 tmp = (int) ci->values[0].value.number;
2855 if ((tmp > 0) && (tmp <= 255))
2856 network_config_ttl = tmp;
2859 } /* }}} int network_config_set_ttl */
2861 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2864 if ((ci->values_num != 1)
2865 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2867 WARNING ("network plugin: The `Interface' config option needs exactly "
2868 "one string argument.");
2872 if (interface == NULL)
2875 *interface = if_nametoindex (ci->values[0].value.string);
2878 } /* }}} int network_config_set_interface */
2880 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2883 if ((ci->values_num != 1)
2884 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2886 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2887 "one numeric argument.");
2891 tmp = (int) ci->values[0].value.number;
2892 if ((tmp >= 1024) && (tmp <= 65535))
2893 network_config_packet_size = tmp;
2896 } /* }}} int network_config_set_buffer_size */
2899 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2903 if ((ci->values_num != 1)
2904 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2906 WARNING ("network plugin: The `%s' config option needs exactly "
2907 "one string argument.", ci->key);
2911 tmp = strdup (ci->values[0].value.string);
2915 sfree (*ret_string);
2919 } /* }}} int network_config_set_string */
2920 #endif /* HAVE_LIBGCRYPT */
2923 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2927 if ((ci->values_num != 1)
2928 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2930 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2931 "one string argument.");
2935 str = ci->values[0].value.string;
2936 if (strcasecmp ("Encrypt", str) == 0)
2937 *retval = SECURITY_LEVEL_ENCRYPT;
2938 else if (strcasecmp ("Sign", str) == 0)
2939 *retval = SECURITY_LEVEL_SIGN;
2940 else if (strcasecmp ("None", str) == 0)
2941 *retval = SECURITY_LEVEL_NONE;
2944 WARNING ("network plugin: Unknown security level: %s.", str);
2949 } /* }}} int network_config_set_security_level */
2950 #endif /* HAVE_LIBGCRYPT */
2952 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2958 if ((ci->values_num < 1) || (ci->values_num > 2)
2959 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2960 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2962 ERROR ("network plugin: The `%s' config option needs "
2963 "one or two string arguments.", ci->key);
2967 se = malloc (sizeof (*se));
2970 ERROR ("network plugin: malloc failed.");
2973 sockent_init (se, SOCKENT_TYPE_SERVER);
2975 se->node = strdup (ci->values[0].value.string);
2976 if (ci->values_num >= 2)
2977 se->service = strdup (ci->values[1].value.string);
2979 for (i = 0; i < ci->children_num; i++)
2981 oconfig_item_t *child = ci->children + i;
2984 if (strcasecmp ("AuthFile", child->key) == 0)
2985 network_config_set_string (child, &se->data.server.auth_file);
2986 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2987 network_config_set_security_level (child,
2988 &se->data.server.security_level);
2990 #endif /* HAVE_LIBGCRYPT */
2991 if (strcasecmp ("Interface", child->key) == 0)
2992 network_config_set_interface (child,
2996 WARNING ("network plugin: Option `%s' is not allowed here.",
3002 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3003 && (se->data.server.auth_file == NULL))
3005 ERROR ("network plugin: A security level higher than `none' was "
3006 "requested, but no AuthFile option was given. Cowardly refusing to "
3007 "open this socket!");
3008 sockent_destroy (se);
3011 #endif /* HAVE_LIBGCRYPT */
3013 status = sockent_open (se);
3016 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
3017 sockent_destroy (se);
3021 status = sockent_add (se);
3024 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3025 sockent_destroy (se);
3030 } /* }}} int network_config_add_listen */
3032 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3038 if ((ci->values_num < 1) || (ci->values_num > 2)
3039 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3040 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3042 ERROR ("network plugin: The `%s' config option needs "
3043 "one or two string arguments.", ci->key);
3047 se = malloc (sizeof (*se));
3050 ERROR ("network plugin: malloc failed.");
3053 sockent_init (se, SOCKENT_TYPE_CLIENT);
3055 se->node = strdup (ci->values[0].value.string);
3056 if (ci->values_num >= 2)
3057 se->service = strdup (ci->values[1].value.string);
3059 for (i = 0; i < ci->children_num; i++)
3061 oconfig_item_t *child = ci->children + i;
3064 if (strcasecmp ("Username", child->key) == 0)
3065 network_config_set_string (child, &se->data.client.username);
3066 else if (strcasecmp ("Password", child->key) == 0)
3067 network_config_set_string (child, &se->data.client.password);
3068 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3069 network_config_set_security_level (child,
3070 &se->data.client.security_level);
3072 #endif /* HAVE_LIBGCRYPT */
3073 if (strcasecmp ("Interface", child->key) == 0)
3074 network_config_set_interface (child,
3078 WARNING ("network plugin: Option `%s' is not allowed here.",
3084 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3085 && ((se->data.client.username == NULL)
3086 || (se->data.client.password == NULL)))
3088 ERROR ("network plugin: A security level higher than `none' was "
3089 "requested, but no Username or Password option was given. "
3090 "Cowardly refusing to open this socket!");
3091 sockent_destroy (se);
3094 #endif /* HAVE_LIBGCRYPT */
3096 status = sockent_open (se);
3099 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3100 sockent_destroy (se);
3104 status = sockent_add (se);
3107 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3108 sockent_destroy (se);
3113 } /* }}} int network_config_add_server */
3115 static int network_config (oconfig_item_t *ci) /* {{{ */
3119 for (i = 0; i < ci->children_num; i++)
3121 oconfig_item_t *child = ci->children + i;
3123 if (strcasecmp ("Listen", child->key) == 0)
3124 network_config_add_listen (child);
3125 else if (strcasecmp ("Server", child->key) == 0)
3126 network_config_add_server (child);
3127 else if (strcasecmp ("TimeToLive", child->key) == 0)
3128 network_config_set_ttl (child);
3129 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3130 network_config_set_buffer_size (child);
3131 else if (strcasecmp ("Forward", child->key) == 0)
3132 network_config_set_boolean (child, &network_config_forward);
3133 else if (strcasecmp ("ReportStats", child->key) == 0)
3134 network_config_set_boolean (child, &network_config_stats);
3135 else if (strcasecmp ("CacheFlush", child->key) == 0)
3136 /* no op for backwards compatibility only */;
3139 WARNING ("network plugin: Option `%s' is not allowed here.",
3145 } /* }}} int network_config */
3147 static int network_notification (const notification_t *n,
3148 user_data_t __attribute__((unused)) *user_data)
3150 char buffer[network_config_packet_size];
3151 char *buffer_ptr = buffer;
3152 int buffer_free = sizeof (buffer);
3155 if (!check_send_notify_okay (n))
3158 memset (buffer, 0, sizeof (buffer));
3160 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
3161 (uint64_t) n->time);
3165 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3166 (uint64_t) n->severity);
3170 if (strlen (n->host) > 0)
3172 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3173 n->host, strlen (n->host));
3178 if (strlen (n->plugin) > 0)
3180 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3181 n->plugin, strlen (n->plugin));
3186 if (strlen (n->plugin_instance) > 0)
3188 status = write_part_string (&buffer_ptr, &buffer_free,
3189 TYPE_PLUGIN_INSTANCE,
3190 n->plugin_instance, strlen (n->plugin_instance));
3195 if (strlen (n->type) > 0)
3197 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3198 n->type, strlen (n->type));
3203 if (strlen (n->type_instance) > 0)
3205 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3206 n->type_instance, strlen (n->type_instance));
3211 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3212 n->message, strlen (n->message));
3216 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3219 } /* int network_notification */
3221 static int network_shutdown (void)
3225 /* Kill the listening thread */
3226 if (receive_thread_running != 0)
3228 INFO ("network plugin: Stopping receive thread.");
3229 pthread_kill (receive_thread_id, SIGTERM);
3230 pthread_join (receive_thread_id, NULL /* no return value */);
3231 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3232 receive_thread_running = 0;
3235 /* Shutdown the dispatching thread */
3236 if (dispatch_thread_running != 0)
3238 INFO ("network plugin: Stopping dispatch thread.");
3239 pthread_mutex_lock (&receive_list_lock);
3240 pthread_cond_broadcast (&receive_list_cond);
3241 pthread_mutex_unlock (&receive_list_lock);
3242 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3243 dispatch_thread_running = 0;
3246 sockent_destroy (listen_sockets);
3248 if (send_buffer_fill > 0)
3251 sfree (send_buffer);
3253 /* TODO: Close `sending_sockets' */
3255 plugin_unregister_config ("network");
3256 plugin_unregister_init ("network");
3257 plugin_unregister_write ("network");
3258 plugin_unregister_shutdown ("network");
3261 } /* int network_shutdown */
3263 static int network_stats_read (void) /* {{{ */
3265 uint64_t copy_octets_rx;
3266 uint64_t copy_octets_tx;
3267 uint64_t copy_packets_rx;
3268 uint64_t copy_packets_tx;
3269 uint64_t copy_values_dispatched;
3270 uint64_t copy_values_not_dispatched;
3271 uint64_t copy_values_sent;
3272 uint64_t copy_values_not_sent;
3273 uint64_t copy_receive_list_length;
3274 value_list_t vl = VALUE_LIST_INIT;
3277 copy_octets_rx = stats_octets_rx;
3278 copy_octets_tx = stats_octets_tx;
3279 copy_packets_rx = stats_packets_rx;
3280 copy_packets_tx = stats_packets_tx;
3281 copy_values_dispatched = stats_values_dispatched;
3282 copy_values_not_dispatched = stats_values_not_dispatched;
3283 copy_values_sent = stats_values_sent;
3284 copy_values_not_sent = stats_values_not_sent;
3285 copy_receive_list_length = receive_list_length;
3287 /* Initialize `vl' */
3291 vl.interval = interval_g;
3292 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3293 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3295 /* Octets received / sent */
3296 vl.values[0].counter = (counter_t) copy_octets_rx;
3297 vl.values[1].counter = (counter_t) copy_octets_tx;
3298 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3299 plugin_dispatch_values_secure (&vl);
3301 /* Packets received / send */
3302 vl.values[0].counter = (counter_t) copy_packets_rx;
3303 vl.values[1].counter = (counter_t) copy_packets_tx;
3304 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3305 plugin_dispatch_values_secure (&vl);
3307 /* Values (not) dispatched and (not) send */
3308 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3311 vl.values[0].derive = (derive_t) copy_values_dispatched;
3312 sstrncpy (vl.type_instance, "dispatch-accepted",
3313 sizeof (vl.type_instance));
3314 plugin_dispatch_values_secure (&vl);
3316 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3317 sstrncpy (vl.type_instance, "dispatch-rejected",
3318 sizeof (vl.type_instance));
3319 plugin_dispatch_values_secure (&vl);
3321 vl.values[0].derive = (derive_t) copy_values_sent;
3322 sstrncpy (vl.type_instance, "send-accepted",
3323 sizeof (vl.type_instance));
3324 plugin_dispatch_values_secure (&vl);
3326 vl.values[0].derive = (derive_t) copy_values_not_sent;
3327 sstrncpy (vl.type_instance, "send-rejected",
3328 sizeof (vl.type_instance));
3329 plugin_dispatch_values_secure (&vl);
3331 /* Receive queue length */
3332 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3333 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3334 vl.type_instance[0] = 0;
3335 plugin_dispatch_values_secure (&vl);
3338 } /* }}} int network_stats_read */
3340 static int network_init (void)
3342 static _Bool have_init = false;
3344 /* Check if we were already initialized. If so, just return - there's
3345 * nothing more to do (for now, that is). */
3351 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3352 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3353 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3356 if (network_config_stats != 0)
3357 plugin_register_read ("network", network_stats_read);
3359 plugin_register_shutdown ("network", network_shutdown);
3361 send_buffer = malloc (network_config_packet_size);
3362 if (send_buffer == NULL)
3364 ERROR ("network plugin: malloc failed.");
3367 network_init_buffer ();
3369 /* setup socket(s) and so on */
3370 if (sending_sockets != NULL)
3372 plugin_register_write ("network", network_write,
3373 /* user_data = */ NULL);
3374 plugin_register_notification ("network", network_notification,
3375 /* user_data = */ NULL);
3378 /* If no threads need to be started, return here. */
3379 if ((listen_sockets_num == 0)
3380 || ((dispatch_thread_running != 0)
3381 && (receive_thread_running != 0)))
3384 if (dispatch_thread_running == 0)
3387 status = pthread_create (&dispatch_thread_id,
3388 NULL /* no attributes */,
3390 NULL /* no argument */);
3394 ERROR ("network: pthread_create failed: %s",
3395 sstrerror (errno, errbuf,
3400 dispatch_thread_running = 1;
3404 if (receive_thread_running == 0)
3407 status = pthread_create (&receive_thread_id,
3408 NULL /* no attributes */,
3410 NULL /* no argument */);
3414 ERROR ("network: pthread_create failed: %s",
3415 sstrerror (errno, errbuf,
3420 receive_thread_running = 1;
3425 } /* int network_init */
3428 * The flush option of the network plugin cannot flush individual identifiers.
3429 * All the values are added to a buffer and sent when the buffer is full, the
3430 * requested value may or may not be in there, it's not worth finding out. We
3431 * just send the buffer if `flush' is called - if the requested value was in
3432 * there, good. If not, well, then there is nothing to flush.. -octo
3434 static int network_flush (int timeout,
3435 const char __attribute__((unused)) *identifier,
3436 user_data_t __attribute__((unused)) *user_data)
3438 pthread_mutex_lock (&send_buffer_lock);
3440 if (send_buffer_fill > 0)
3443 pthread_mutex_unlock (&send_buffer_lock);
3446 } /* int network_flush */
3448 void module_register (void)
3450 plugin_register_complex_config ("network", network_config);
3451 plugin_register_init ("network", network_init);
3452 plugin_register_flush ("network", network_flush,
3453 /* user_data = */ NULL);
3454 } /* void module_register */
3456 /* vim: set fdm=marker : */