2 * collectd - src/network.c
3 * Copyright (C) 2005-2010 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>
63 GCRY_THREAD_OPTION_PTHREAD_IMPL;
66 #ifndef IPV6_ADD_MEMBERSHIP
67 # ifdef IPV6_JOIN_GROUP
68 # define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
70 # error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
72 #endif /* !IP_ADD_MEMBERSHIP */
75 * Maximum size required for encryption / signing:
77 * 42 bytes for the encryption header
78 * + 64 bytes for the username
82 #define BUFF_SIG_SIZE 106
87 #define SECURITY_LEVEL_NONE 0
89 # define SECURITY_LEVEL_SIGN 1
90 # define SECURITY_LEVEL_ENCRYPT 2
95 struct sockaddr_storage *addr;
101 gcry_cipher_hd_t cypher;
102 unsigned char password_hash[32];
106 struct sockent_server
114 gcry_cipher_hd_t cypher;
118 typedef struct sockent
120 #define SOCKENT_TYPE_CLIENT 1
121 #define SOCKENT_TYPE_SERVER 2
130 struct sockent_client client;
131 struct sockent_server server;
134 struct sockent *next;
137 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
138 * 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
139 * +-------+-----------------------+-------------------------------+
140 * ! Ver. ! ! Length !
141 * +-------+-----------------------+-------------------------------+
148 typedef struct part_header_s part_header_t;
150 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
151 * 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
152 * +-------------------------------+-------------------------------+
154 * +-------------------------------+-------------------------------+
155 * : (Length - 4) Bytes :
156 * +---------------------------------------------------------------+
163 typedef struct part_string_s part_string_t;
165 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
166 * 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
167 * +-------------------------------+-------------------------------+
169 * +-------------------------------+-------------------------------+
170 * : (Length - 4 == 2 || 4 || 8) Bytes :
171 * +---------------------------------------------------------------+
178 typedef struct part_number_s part_number_t;
180 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
181 * 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
182 * +-------------------------------+-------------------------------+
184 * +-------------------------------+---------------+---------------+
185 * ! Num of values ! Type0 ! Type1 !
186 * +-------------------------------+---------------+---------------+
189 * +---------------------------------------------------------------+
192 * +---------------------------------------------------------------+
197 uint16_t *num_values;
198 uint8_t *values_types;
201 typedef struct part_values_s part_values_t;
203 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
204 * 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
205 * +-------------------------------+-------------------------------+
207 * +-------------------------------+-------------------------------+
208 * ! Hash (Bits 0 - 31) !
210 * ! Hash (Bits 224 - 255) !
211 * +---------------------------------------------------------------+
214 #define PART_SIGNATURE_SHA256_SIZE 36
215 struct part_signature_sha256_s
218 unsigned char hash[32];
221 typedef struct part_signature_sha256_s part_signature_sha256_t;
223 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
224 * 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
225 * +-------------------------------+-------------------------------+
227 * +-------------------------------+-------------------------------+
228 * ! Original length ! Padding (0 - 15 bytes) !
229 * +-------------------------------+-------------------------------+
230 * ! Hash (Bits 0 - 31) !
232 * ! Hash (Bits 128 - 159) !
233 * +---------------------------------------------------------------+
236 #define PART_ENCRYPTION_AES256_SIZE 42
237 struct part_encryption_aes256_s
240 uint16_t username_length;
242 unsigned char iv[16];
244 unsigned char hash[20];
248 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
250 struct receive_list_entry_s
255 struct receive_list_entry_s *next;
257 typedef struct receive_list_entry_s receive_list_entry_t;
262 static int network_config_ttl = 0;
263 /* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
264 static size_t network_config_packet_size = 1452;
265 static int network_config_forward = 0;
266 static int network_config_stats = 0;
268 static sockent_t *sending_sockets = NULL;
270 static receive_list_entry_t *receive_list_head = NULL;
271 static receive_list_entry_t *receive_list_tail = NULL;
272 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
273 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
274 static uint64_t receive_list_length = 0;
276 static sockent_t *listen_sockets = NULL;
277 static struct pollfd *listen_sockets_pollfd = NULL;
278 static size_t listen_sockets_num = 0;
280 /* The receive and dispatch threads will run as long as `listen_loop' is set to
282 static int listen_loop = 0;
283 static int receive_thread_running = 0;
284 static pthread_t receive_thread_id;
285 static int dispatch_thread_running = 0;
286 static pthread_t dispatch_thread_id;
288 /* Buffer in which to-be-sent network packets are constructed. */
289 static char *send_buffer;
290 static char *send_buffer_ptr;
291 static int send_buffer_fill;
292 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
293 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
295 /* XXX: These counters are incremented from one place only. The spot in which
296 * the values are incremented is either only reachable by one thread (the
297 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
298 * example). Only if neither is true, the stats_lock is acquired. The counters
299 * are always read without holding a lock in the hope that writing 8 bytes to
300 * memory is an atomic operation. */
301 static derive_t stats_octets_rx = 0;
302 static derive_t stats_octets_tx = 0;
303 static derive_t stats_packets_rx = 0;
304 static derive_t stats_packets_tx = 0;
305 static derive_t stats_values_dispatched = 0;
306 static derive_t stats_values_not_dispatched = 0;
307 static derive_t stats_values_sent = 0;
308 static derive_t stats_values_not_sent = 0;
309 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
314 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
316 uint64_t time_sent = 0;
319 status = uc_meta_data_get_unsigned_int (vl,
320 "network:time_sent", &time_sent);
322 /* This is a value we already sent. Don't allow it to be received again in
323 * order to avoid looping. */
324 if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
328 } /* }}} _Bool check_receive_okay */
330 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
335 if (network_config_forward != 0)
338 if (vl->meta == NULL)
341 status = meta_data_get_boolean (vl->meta, "network:received", &received);
342 if (status == -ENOENT)
344 else if (status != 0)
346 ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
347 "with status %i.", status);
351 /* By default, only *send* value lists that were not *received* by the
354 } /* }}} _Bool check_send_okay */
356 static _Bool check_notify_received (const notification_t *n) /* {{{ */
358 notification_meta_t *ptr;
360 for (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 c_complain_once (LOG_ERR, &complain_forwarding,
381 "network plugin: A notification has been received via the network "
382 "forwarding if 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)
399 || (strlen (vl->host) <= 0)
400 || (strlen (vl->plugin) <= 0)
401 || (strlen (vl->type) <= 0))
404 if (!check_receive_okay (vl))
407 char name[6*DATA_MAX_NAME_LEN];
408 FORMAT_VL (name, sizeof (name), vl);
409 name[sizeof (name) - 1] = 0;
410 DEBUG ("network plugin: network_dispatch_values: "
411 "NOT dispatching %s.", name);
413 stats_values_not_dispatched++;
417 assert (vl->meta == NULL);
419 vl->meta = meta_data_create ();
420 if (vl->meta == NULL)
422 ERROR ("network plugin: meta_data_create failed.");
426 status = meta_data_add_boolean (vl->meta, "network:received", 1);
429 ERROR ("network plugin: meta_data_add_boolean failed.");
430 meta_data_destroy (vl->meta);
435 if (username != NULL)
437 status = meta_data_add_string (vl->meta, "network:username", username);
440 ERROR ("network plugin: meta_data_add_string failed.");
441 meta_data_destroy (vl->meta);
447 plugin_dispatch_values_secure (vl);
448 stats_values_dispatched++;
450 meta_data_destroy (vl->meta);
454 } /* }}} int network_dispatch_values */
456 static int network_dispatch_notification (notification_t *n) /* {{{ */
460 assert (n->meta == NULL);
462 status = plugin_notification_meta_add_boolean (n, "network:received", 1);
465 ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
466 plugin_notification_meta_free (n->meta);
471 status = plugin_dispatch_notification (n);
473 plugin_notification_meta_free (n->meta);
477 } /* }}} int network_dispatch_notification */
480 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
481 const void *iv, size_t iv_size, const char *username)
484 gcry_cipher_hd_t *cyper_ptr;
485 unsigned char password_hash[32];
487 if (se->type == SOCKENT_TYPE_CLIENT)
489 cyper_ptr = &se->data.client.cypher;
490 memcpy (password_hash, se->data.client.password_hash,
491 sizeof (password_hash));
497 cyper_ptr = &se->data.server.cypher;
499 if (username == NULL)
502 secret = fbh_get (se->data.server.userdb, username);
506 gcry_md_hash_buffer (GCRY_MD_SHA256,
508 secret, strlen (secret));
513 if (*cyper_ptr == NULL)
515 err = gcry_cipher_open (cyper_ptr,
516 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
519 ERROR ("network plugin: gcry_cipher_open returned: %s",
520 gcry_strerror (err));
527 gcry_cipher_reset (*cyper_ptr);
529 assert (*cyper_ptr != NULL);
531 err = gcry_cipher_setkey (*cyper_ptr,
532 password_hash, sizeof (password_hash));
535 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
536 gcry_strerror (err));
537 gcry_cipher_close (*cyper_ptr);
542 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
545 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
546 gcry_strerror (err));
547 gcry_cipher_close (*cyper_ptr);
553 } /* }}} int network_get_aes256_cypher */
554 #endif /* HAVE_LIBGCRYPT */
556 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
557 const data_set_t *ds, const value_list_t *vl)
563 part_header_t pkg_ph;
564 uint16_t pkg_num_values;
565 uint8_t *pkg_values_types;
571 num_values = vl->values_len;
572 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
573 + (num_values * sizeof (uint8_t))
574 + (num_values * sizeof (value_t));
576 if (*ret_buffer_len < packet_len)
579 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
580 if (pkg_values_types == NULL)
582 ERROR ("network plugin: write_part_values: malloc failed.");
586 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
587 if (pkg_values == NULL)
589 free (pkg_values_types);
590 ERROR ("network plugin: write_part_values: malloc failed.");
594 pkg_ph.type = htons (TYPE_VALUES);
595 pkg_ph.length = htons (packet_len);
597 pkg_num_values = htons ((uint16_t) vl->values_len);
599 for (i = 0; i < num_values; i++)
601 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
602 switch (ds->ds[i].type)
604 case DS_TYPE_COUNTER:
605 pkg_values[i].counter = htonll (vl->values[i].counter);
609 pkg_values[i].gauge = htond (vl->values[i].gauge);
613 pkg_values[i].derive = htonll (vl->values[i].derive);
616 case DS_TYPE_ABSOLUTE:
617 pkg_values[i].absolute = htonll (vl->values[i].absolute);
621 free (pkg_values_types);
623 ERROR ("network plugin: write_part_values: "
624 "Unknown data source type: %i",
627 } /* switch (ds->ds[i].type) */
628 } /* for (num_values) */
631 * Use `memcpy' to write everything to the buffer, because the pointer
632 * may be unaligned and some architectures, such as SPARC, can't handle
635 packet_ptr = *ret_buffer;
637 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
638 offset += sizeof (pkg_ph);
639 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
640 offset += sizeof (pkg_num_values);
641 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
642 offset += num_values * sizeof (uint8_t);
643 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
644 offset += num_values * sizeof (value_t);
646 assert (offset == packet_len);
648 *ret_buffer = packet_ptr + packet_len;
649 *ret_buffer_len -= packet_len;
651 free (pkg_values_types);
655 } /* int write_part_values */
657 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
658 int type, uint64_t value)
663 part_header_t pkg_head;
668 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
670 if (*ret_buffer_len < packet_len)
673 pkg_head.type = htons (type);
674 pkg_head.length = htons (packet_len);
675 pkg_value = htonll (value);
677 packet_ptr = *ret_buffer;
679 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
680 offset += sizeof (pkg_head);
681 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
682 offset += sizeof (pkg_value);
684 assert (offset == packet_len);
686 *ret_buffer = packet_ptr + packet_len;
687 *ret_buffer_len -= packet_len;
690 } /* int write_part_number */
692 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
693 int type, const char *str, int str_len)
703 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
704 if (*ret_buffer_len < buffer_len)
707 pkg_type = htons (type);
708 pkg_length = htons (buffer_len);
710 buffer = *ret_buffer;
712 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
713 offset += sizeof (pkg_type);
714 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
715 offset += sizeof (pkg_length);
716 memcpy (buffer + offset, str, str_len);
718 memset (buffer + offset, '\0', 1);
721 assert (offset == buffer_len);
723 *ret_buffer = buffer + buffer_len;
724 *ret_buffer_len -= buffer_len;
727 } /* int write_part_string */
729 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
730 value_t **ret_values, int *ret_num_values)
732 char *buffer = *ret_buffer;
733 size_t buffer_len = *ret_buffer_len;
748 NOTICE ("network plugin: packet is too short: "
749 "buffer_len = %zu", buffer_len);
753 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
754 buffer += sizeof (tmp16);
755 pkg_type = ntohs (tmp16);
757 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
758 buffer += sizeof (tmp16);
759 pkg_length = ntohs (tmp16);
761 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
762 buffer += sizeof (tmp16);
763 pkg_numval = ntohs (tmp16);
765 assert (pkg_type == TYPE_VALUES);
767 exp_size = 3 * sizeof (uint16_t)
768 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
769 if (buffer_len < exp_size)
771 WARNING ("network plugin: parse_part_values: "
773 "Chunk of size %zu expected, "
774 "but buffer has only %zu bytes left.",
775 exp_size, buffer_len);
779 if (pkg_length != exp_size)
781 WARNING ("network plugin: parse_part_values: "
782 "Length and number of values "
783 "in the packet don't match.");
787 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
788 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
789 if ((pkg_types == NULL) || (pkg_values == NULL))
793 ERROR ("network plugin: parse_part_values: malloc failed.");
797 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
798 buffer += pkg_numval * sizeof (uint8_t);
799 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
800 buffer += pkg_numval * sizeof (value_t);
802 for (i = 0; i < pkg_numval; i++)
804 switch (pkg_types[i])
806 case DS_TYPE_COUNTER:
807 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
811 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
815 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
818 case DS_TYPE_ABSOLUTE:
819 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
823 NOTICE ("network plugin: parse_part_values: "
824 "Don't know how to handle data source type %"PRIu8,
829 } /* switch (pkg_types[i]) */
832 *ret_buffer = buffer;
833 *ret_buffer_len = buffer_len - pkg_length;
834 *ret_num_values = pkg_numval;
835 *ret_values = pkg_values;
840 } /* int parse_part_values */
842 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
845 char *buffer = *ret_buffer;
846 size_t buffer_len = *ret_buffer_len;
850 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
854 if (buffer_len < exp_size)
856 WARNING ("network plugin: parse_part_number: "
858 "Chunk of size %zu expected, "
859 "but buffer has only %zu bytes left.",
860 exp_size, buffer_len);
864 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
865 buffer += sizeof (tmp16);
866 /* pkg_type = ntohs (tmp16); */
868 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
869 buffer += sizeof (tmp16);
870 pkg_length = ntohs (tmp16);
872 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
873 buffer += sizeof (tmp64);
874 *value = ntohll (tmp64);
876 *ret_buffer = buffer;
877 *ret_buffer_len = buffer_len - pkg_length;
880 } /* int parse_part_number */
882 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
883 char *output, int output_len)
885 char *buffer = *ret_buffer;
886 size_t buffer_len = *ret_buffer_len;
889 size_t header_size = 2 * sizeof (uint16_t);
893 if (buffer_len < header_size)
895 WARNING ("network plugin: parse_part_string: "
897 "Chunk of at least size %zu expected, "
898 "but buffer has only %zu bytes left.",
899 header_size, buffer_len);
903 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
904 buffer += sizeof (tmp16);
905 /* pkg_type = ntohs (tmp16); */
907 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
908 buffer += sizeof (tmp16);
909 pkg_length = ntohs (tmp16);
911 /* Check that packet fits in the input buffer */
912 if (pkg_length > buffer_len)
914 WARNING ("network plugin: parse_part_string: "
916 "Chunk of size %"PRIu16" received, "
917 "but buffer has only %zu bytes left.",
918 pkg_length, buffer_len);
922 /* Check that pkg_length is in the valid range */
923 if (pkg_length <= header_size)
925 WARNING ("network plugin: parse_part_string: "
927 "Header claims this packet is only %hu "
928 "bytes long.", pkg_length);
932 /* Check that the package data fits into the output buffer.
933 * The previous if-statement ensures that:
934 * `pkg_length > header_size' */
936 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
938 WARNING ("network plugin: parse_part_string: "
939 "Output buffer too small.");
943 /* All sanity checks successfull, let's copy the data over */
944 output_len = pkg_length - header_size;
945 memcpy ((void *) output, (void *) buffer, output_len);
946 buffer += output_len;
948 /* For some very weird reason '\0' doesn't do the trick on SPARC in
950 if (output[output_len - 1] != 0)
952 WARNING ("network plugin: parse_part_string: "
953 "Received string does not end "
954 "with a NULL-byte.");
958 *ret_buffer = buffer;
959 *ret_buffer_len = buffer_len - pkg_length;
962 } /* int parse_part_string */
964 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
965 * parse_packet and vice versa. */
966 #define PP_SIGNED 0x01
967 #define PP_ENCRYPTED 0x02
968 static int parse_packet (sockent_t *se,
969 void *buffer, size_t buffer_size, int flags,
970 const char *username);
972 #define BUFFER_READ(p,s) do { \
973 memcpy ((p), buffer + buffer_offset, (s)); \
974 buffer_offset += (s); \
978 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
979 void **ret_buffer, size_t *ret_buffer_len, int flags)
981 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
985 size_t buffer_offset;
990 part_signature_sha256_t pss;
991 uint16_t pss_head_length;
992 char hash[sizeof (pss.hash)];
996 unsigned char *hash_ptr;
998 buffer = *ret_buffer;
999 buffer_len = *ret_buffer_len;
1002 if (se->data.server.userdb == NULL)
1004 c_complain (LOG_NOTICE, &complain_no_users,
1005 "network plugin: Received signed network packet but can't verify it "
1006 "because no user DB has been configured. Will accept it.");
1010 /* Check if the buffer has enough data for this structure. */
1011 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1014 /* Read type and length header */
1015 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1016 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1017 pss_head_length = ntohs (pss.head.length);
1019 /* Check if the `pss_head_length' is within bounds. */
1020 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1021 || (pss_head_length > buffer_len))
1023 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1027 /* Copy the hash. */
1028 BUFFER_READ (pss.hash, sizeof (pss.hash));
1030 /* Calculate username length (without null byte) and allocate memory */
1031 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1032 pss.username = malloc (username_len + 1);
1033 if (pss.username == NULL)
1036 /* Read the username */
1037 BUFFER_READ (pss.username, username_len);
1038 pss.username[username_len] = 0;
1040 assert (buffer_offset == pss_head_length);
1042 /* Query the password */
1043 secret = fbh_get (se->data.server.userdb, pss.username);
1046 ERROR ("network plugin: Unknown user: %s", pss.username);
1047 sfree (pss.username);
1051 /* Create a hash device and check the HMAC */
1053 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1056 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1057 gcry_strerror (err));
1059 sfree (pss.username);
1063 err = gcry_md_setkey (hd, secret, strlen (secret));
1066 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1069 sfree (pss.username);
1074 buffer + PART_SIGNATURE_SHA256_SIZE,
1075 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1076 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1077 if (hash_ptr == NULL)
1079 ERROR ("network plugin: gcry_md_read failed.");
1082 sfree (pss.username);
1085 memcpy (hash, hash_ptr, sizeof (hash));
1091 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1093 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
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_LIBGCRYPT */
1112 #else /* if !HAVE_LIBGCRYPT */
1113 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1114 void **ret_buffer, size_t *ret_buffer_size, int flags)
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)
1137 || (part_len > buffer_size))
1140 if (warning_has_been_printed == 0)
1142 WARNING ("network plugin: Received signed packet, but the network "
1143 "plugin was not linked with libgcrypt, so I cannot "
1144 "verify the signature. The packet will be accepted.");
1145 warning_has_been_printed = 1;
1148 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1149 /* username = */ NULL);
1151 *ret_buffer = buffer + buffer_size;
1152 *ret_buffer_size = 0;
1155 } /* }}} int parse_part_sign_sha256 */
1156 #endif /* !HAVE_LIBGCRYPT */
1159 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1160 void **ret_buffer, size_t *ret_buffer_len,
1163 char *buffer = *ret_buffer;
1164 size_t buffer_len = *ret_buffer_len;
1167 size_t buffer_offset;
1168 uint16_t username_len;
1169 part_encryption_aes256_t pea;
1170 unsigned char hash[sizeof (pea.hash)];
1172 gcry_cipher_hd_t cypher;
1175 /* Make sure at least the header if available. */
1176 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1178 NOTICE ("network plugin: parse_part_encr_aes256: "
1179 "Discarding short packet.");
1185 /* Copy the unencrypted information into `pea'. */
1186 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1187 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1189 /* Check the `part size'. */
1190 part_size = ntohs (pea.head.length);
1191 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1192 || (part_size > buffer_len))
1194 NOTICE ("network plugin: parse_part_encr_aes256: "
1195 "Discarding part with invalid size.");
1199 /* Read the username */
1200 BUFFER_READ (&username_len, sizeof (username_len));
1201 username_len = ntohs (username_len);
1203 if ((username_len <= 0)
1204 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1206 NOTICE ("network plugin: parse_part_encr_aes256: "
1207 "Discarding part with invalid username length.");
1211 assert (username_len > 0);
1212 pea.username = malloc (username_len + 1);
1213 if (pea.username == NULL)
1215 BUFFER_READ (pea.username, username_len);
1216 pea.username[username_len] = 0;
1218 /* Last but not least, the initialization vector */
1219 BUFFER_READ (pea.iv, sizeof (pea.iv));
1221 /* Make sure we are at the right position */
1222 assert (buffer_offset == (username_len +
1223 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1225 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1229 sfree (pea.username);
1233 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1234 assert (payload_len > 0);
1236 /* Decrypt the packet in-place */
1237 err = gcry_cipher_decrypt (cypher,
1238 buffer + buffer_offset,
1239 part_size - buffer_offset,
1240 /* in = */ NULL, /* in len = */ 0);
1243 sfree (pea.username);
1244 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1245 gcry_strerror (err));
1250 BUFFER_READ (pea.hash, sizeof (pea.hash));
1252 /* Make sure we're at the right position - again */
1253 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1254 assert (buffer_offset == (part_size - payload_len));
1256 /* Check hash sum */
1257 memset (hash, 0, sizeof (hash));
1258 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1259 buffer + buffer_offset, payload_len);
1260 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1262 sfree (pea.username);
1263 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1267 parse_packet (se, buffer + buffer_offset, payload_len,
1268 flags | PP_ENCRYPTED, pea.username);
1270 /* XXX: Free pea.username?!? */
1272 /* Update return values */
1273 *ret_buffer = buffer + part_size;
1274 *ret_buffer_len = buffer_len - part_size;
1276 sfree (pea.username);
1279 } /* }}} int parse_part_encr_aes256 */
1280 /* #endif HAVE_LIBGCRYPT */
1282 #else /* if !HAVE_LIBGCRYPT */
1283 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1284 void **ret_buffer, size_t *ret_buffer_size, int flags)
1286 static int warning_has_been_printed = 0;
1290 size_t buffer_offset;
1295 buffer = *ret_buffer;
1296 buffer_size = *ret_buffer_size;
1299 /* parse_packet assures this minimum size. */
1300 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1302 BUFFER_READ (&ph.type, sizeof (ph.type));
1303 BUFFER_READ (&ph.length, sizeof (ph.length));
1304 ph_length = ntohs (ph.length);
1306 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1307 || (ph_length > buffer_size))
1309 ERROR ("network plugin: AES-256 encrypted part "
1310 "with invalid length received.");
1314 if (warning_has_been_printed == 0)
1316 WARNING ("network plugin: Received encrypted packet, but the network "
1317 "plugin was not linked with libgcrypt, so I cannot "
1318 "decrypt it. The part will be discarded.");
1319 warning_has_been_printed = 1;
1322 *ret_buffer += ph_length;
1323 *ret_buffer_size -= ph_length;
1326 } /* }}} int parse_part_encr_aes256 */
1327 #endif /* !HAVE_LIBGCRYPT */
1331 static int parse_packet (sockent_t *se, /* {{{ */
1332 void *buffer, size_t buffer_size, int flags,
1333 const char *username)
1337 value_list_t vl = VALUE_LIST_INIT;
1341 int packet_was_signed = (flags & PP_SIGNED);
1342 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1343 int printed_ignore_warning = 0;
1344 #endif /* HAVE_LIBGCRYPT */
1347 memset (&vl, '\0', sizeof (vl));
1348 memset (&n, '\0', sizeof (n));
1351 while ((status == 0) && (0 < buffer_size)
1352 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1354 uint16_t pkg_length;
1357 memcpy ((void *) &pkg_type,
1360 memcpy ((void *) &pkg_length,
1361 (void *) (buffer + sizeof (pkg_type)),
1362 sizeof (pkg_length));
1364 pkg_length = ntohs (pkg_length);
1365 pkg_type = ntohs (pkg_type);
1367 if (pkg_length > buffer_size)
1369 /* Ensure that this loop terminates eventually */
1370 if (pkg_length < (2 * sizeof (uint16_t)))
1373 if (pkg_type == TYPE_ENCR_AES256)
1375 status = parse_part_encr_aes256 (se,
1376 &buffer, &buffer_size, flags);
1379 ERROR ("network plugin: Decrypting AES256 "
1381 "with status %i.", status);
1386 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1387 && (packet_was_encrypted == 0))
1389 if (printed_ignore_warning == 0)
1391 INFO ("network plugin: Unencrypted packet or "
1392 "part has been ignored.");
1393 printed_ignore_warning = 1;
1395 buffer = ((char *) buffer) + pkg_length;
1398 #endif /* HAVE_LIBGCRYPT */
1399 else if (pkg_type == TYPE_SIGN_SHA256)
1401 status = parse_part_sign_sha256 (se,
1402 &buffer, &buffer_size, flags);
1405 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1407 "with status %i.", status);
1412 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1413 && (packet_was_encrypted == 0)
1414 && (packet_was_signed == 0))
1416 if (printed_ignore_warning == 0)
1418 INFO ("network plugin: Unsigned packet or "
1419 "part has been ignored.");
1420 printed_ignore_warning = 1;
1422 buffer = ((char *) buffer) + pkg_length;
1425 #endif /* HAVE_LIBGCRYPT */
1426 else if (pkg_type == TYPE_VALUES)
1428 status = parse_part_values (&buffer, &buffer_size,
1429 &vl.values, &vl.values_len);
1433 network_dispatch_values (&vl, username);
1437 else if (pkg_type == TYPE_TIME)
1440 status = parse_part_number (&buffer, &buffer_size,
1444 vl.time = TIME_T_TO_CDTIME_T (tmp);
1445 n.time = TIME_T_TO_CDTIME_T (tmp);
1448 else if (pkg_type == TYPE_TIME_HR)
1451 status = parse_part_number (&buffer, &buffer_size,
1455 vl.time = (cdtime_t) tmp;
1456 n.time = (cdtime_t) tmp;
1459 else if (pkg_type == TYPE_INTERVAL)
1462 status = parse_part_number (&buffer, &buffer_size,
1465 vl.interval = TIME_T_TO_CDTIME_T (tmp);
1467 else if (pkg_type == TYPE_INTERVAL_HR)
1470 status = parse_part_number (&buffer, &buffer_size,
1473 vl.interval = (cdtime_t) tmp;
1475 else if (pkg_type == TYPE_HOST)
1477 status = parse_part_string (&buffer, &buffer_size,
1478 vl.host, sizeof (vl.host));
1480 sstrncpy (n.host, vl.host, sizeof (n.host));
1482 else if (pkg_type == TYPE_PLUGIN)
1484 status = parse_part_string (&buffer, &buffer_size,
1485 vl.plugin, sizeof (vl.plugin));
1487 sstrncpy (n.plugin, vl.plugin,
1490 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1492 status = parse_part_string (&buffer, &buffer_size,
1494 sizeof (vl.plugin_instance));
1496 sstrncpy (n.plugin_instance,
1498 sizeof (n.plugin_instance));
1500 else if (pkg_type == TYPE_TYPE)
1502 status = parse_part_string (&buffer, &buffer_size,
1503 vl.type, sizeof (vl.type));
1505 sstrncpy (n.type, vl.type, sizeof (n.type));
1507 else if (pkg_type == TYPE_TYPE_INSTANCE)
1509 status = parse_part_string (&buffer, &buffer_size,
1511 sizeof (vl.type_instance));
1513 sstrncpy (n.type_instance, vl.type_instance,
1514 sizeof (n.type_instance));
1516 else if (pkg_type == TYPE_MESSAGE)
1518 status = parse_part_string (&buffer, &buffer_size,
1519 n.message, sizeof (n.message));
1525 else if ((n.severity != NOTIF_FAILURE)
1526 && (n.severity != NOTIF_WARNING)
1527 && (n.severity != NOTIF_OKAY))
1529 INFO ("network plugin: "
1530 "Ignoring notification with "
1531 "unknown severity %i.",
1534 else if (n.time <= 0)
1536 INFO ("network plugin: "
1537 "Ignoring notification with "
1540 else if (strlen (n.message) <= 0)
1542 INFO ("network plugin: "
1543 "Ignoring notification with "
1544 "an empty message.");
1548 network_dispatch_notification (&n);
1551 else if (pkg_type == TYPE_SEVERITY)
1554 status = parse_part_number (&buffer, &buffer_size,
1557 n.severity = (int) tmp;
1561 DEBUG ("network plugin: parse_packet: Unknown part"
1562 " type: 0x%04hx", pkg_type);
1563 buffer = ((char *) buffer) + pkg_length;
1565 } /* while (buffer_size > sizeof (part_header_t)) */
1567 if (status == 0 && buffer_size > 0)
1568 WARNING ("network plugin: parse_packet: Received truncated "
1569 "packet, try increasing `MaxPacketSize'");
1572 } /* }}} int parse_packet */
1574 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1583 sfree (sec->username);
1584 sfree (sec->password);
1585 if (sec->cypher != NULL)
1586 gcry_cipher_close (sec->cypher);
1588 } /* }}} void free_sockent_client */
1590 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1594 for (i = 0; i < ses->fd_num; i++)
1596 if (ses->fd[i] >= 0)
1605 sfree (ses->auth_file);
1606 fbh_destroy (ses->userdb);
1607 if (ses->cypher != NULL)
1608 gcry_cipher_close (ses->cypher);
1610 } /* }}} void free_sockent_server */
1612 static void sockent_destroy (sockent_t *se) /* {{{ */
1616 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1623 sfree (se->service);
1625 if (se->type == SOCKENT_TYPE_CLIENT)
1626 free_sockent_client (&se->data.client);
1628 free_sockent_server (&se->data.server);
1633 } /* }}} void sockent_destroy */
1636 * int network_set_ttl
1638 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1639 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1641 * The `struct addrinfo' is used to destinguish between unicast and multicast
1644 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1646 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1647 network_config_ttl);
1649 assert (se->type == SOCKENT_TYPE_CLIENT);
1651 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1654 if (ai->ai_family == AF_INET)
1656 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1659 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1660 optname = IP_MULTICAST_TTL;
1664 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1665 &network_config_ttl,
1666 sizeof (network_config_ttl)) != 0)
1669 ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
1670 sstrerror (errno, errbuf, sizeof (errbuf)));
1674 else if (ai->ai_family == AF_INET6)
1676 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1677 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1680 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1681 optname = IPV6_MULTICAST_HOPS;
1683 optname = IPV6_UNICAST_HOPS;
1685 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1686 &network_config_ttl,
1687 sizeof (network_config_ttl)) != 0)
1690 ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
1691 sstrerror (errno, errbuf,
1698 } /* int network_set_ttl */
1700 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1702 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1705 assert (se->type == SOCKENT_TYPE_CLIENT);
1707 if (ai->ai_family == AF_INET)
1709 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1711 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1713 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1714 /* If possible, use the "ip_mreqn" structure which has
1715 * an "interface index" member. Using the interface
1716 * index is preferred here, because of its similarity
1717 * to the way IPv6 handles this. Unfortunately, it
1718 * appears not to be portable. */
1719 struct ip_mreqn mreq;
1721 memset (&mreq, 0, sizeof (mreq));
1722 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1723 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1724 mreq.imr_ifindex = se->interface;
1726 struct ip_mreq mreq;
1728 memset (&mreq, 0, sizeof (mreq));
1729 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1730 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1733 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1734 &mreq, sizeof (mreq)) != 0)
1737 ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
1738 sstrerror (errno, errbuf, sizeof (errbuf)));
1745 else if (ai->ai_family == AF_INET6)
1747 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1749 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1751 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1753 sizeof (se->interface)) != 0)
1756 ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
1757 sstrerror (errno, errbuf,
1766 /* else: Not a multicast interface. */
1767 if (se->interface != 0)
1769 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1770 char interface_name[IFNAMSIZ];
1772 if (if_indextoname (se->interface, interface_name) == NULL)
1775 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1777 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1779 sizeof(interface_name)) == -1 )
1782 ERROR ("network plugin: setsockopt (bind-if): %s",
1783 sstrerror (errno, errbuf, sizeof (errbuf)));
1786 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1789 WARNING ("network plugin: Cannot set the interface on a unicast "
1791 # if !defined(SO_BINDTODEVICE)
1792 "the \"SO_BINDTODEVICE\" socket option "
1794 "the \"if_indextoname\" function "
1796 "is not available on your system.");
1802 } /* }}} network_set_interface */
1804 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1813 /* allow multiple sockets to use the same PORT number */
1814 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1815 &yes, sizeof(yes)) == -1) {
1817 ERROR ("network plugin: setsockopt (reuseaddr): %s",
1818 sstrerror (errno, errbuf, sizeof (errbuf)));
1822 DEBUG ("fd = %i; calling `bind'", fd);
1824 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1828 sstrerror (errno, errbuf, sizeof (errbuf)));
1832 if (ai->ai_family == AF_INET)
1834 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1835 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1837 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1838 struct ip_mreqn mreq;
1840 struct ip_mreq mreq;
1843 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1845 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1846 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1847 /* Set the interface using the interface index if
1848 * possible (available). Unfortunately, the struct
1849 * ip_mreqn is not portable. */
1850 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1851 mreq.imr_ifindex = interface_idx;
1853 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1856 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1857 &loop, sizeof (loop)) == -1)
1860 ERROR ("network plugin: setsockopt (multicast-loop): %s",
1861 sstrerror (errno, errbuf,
1866 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1867 &mreq, sizeof (mreq)) == -1)
1870 ERROR ("network plugin: setsockopt (add-membership): %s",
1871 sstrerror (errno, errbuf,
1879 else if (ai->ai_family == AF_INET6)
1881 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1882 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1883 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1885 struct ipv6_mreq mreq;
1887 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1889 memcpy (&mreq.ipv6mr_multiaddr,
1891 sizeof (addr->sin6_addr));
1893 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1894 * ipv6mr_interface may be set to zeroes to
1895 * choose the default multicast interface or to
1896 * the index of a particular multicast-capable
1897 * interface if the host is multihomed.
1898 * Membership is associ-associated with a
1899 * single interface; programs running on
1900 * multihomed hosts may need to join the same
1901 * group on more than one interface.*/
1902 mreq.ipv6mr_interface = interface_idx;
1904 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1905 &loop, sizeof (loop)) == -1)
1908 ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
1909 sstrerror (errno, errbuf,
1914 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1915 &mreq, sizeof (mreq)) == -1)
1918 ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
1919 sstrerror (errno, errbuf,
1928 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1929 /* if a specific interface was set, bind the socket to it. But to avoid
1930 * possible problems with multicast routing, only do that for non-multicast
1932 if (interface_idx != 0)
1934 char interface_name[IFNAMSIZ];
1936 if (if_indextoname (interface_idx, interface_name) == NULL)
1939 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1941 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1943 sizeof(interface_name)) == -1 )
1946 ERROR ("network plugin: setsockopt (bind-if): %s",
1947 sstrerror (errno, errbuf, sizeof (errbuf)));
1951 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1954 } /* int network_bind_socket */
1956 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1957 * or `SOCKENT_TYPE_SERVER' */
1958 static int sockent_init (sockent_t *se, int type) /* {{{ */
1963 memset (se, 0, sizeof (*se));
1965 se->type = SOCKENT_TYPE_CLIENT;
1971 if (type == SOCKENT_TYPE_SERVER)
1973 se->type = SOCKENT_TYPE_SERVER;
1974 se->data.server.fd = NULL;
1976 se->data.server.security_level = SECURITY_LEVEL_NONE;
1977 se->data.server.auth_file = NULL;
1978 se->data.server.userdb = NULL;
1979 se->data.server.cypher = NULL;
1984 se->data.client.fd = -1;
1985 se->data.client.addr = NULL;
1987 se->data.client.security_level = SECURITY_LEVEL_NONE;
1988 se->data.client.username = NULL;
1989 se->data.client.password = NULL;
1990 se->data.client.cypher = NULL;
1995 } /* }}} int sockent_init */
1997 /* Open the file descriptors for a initialized sockent structure. */
1998 static int sockent_open (sockent_t *se) /* {{{ */
2000 struct addrinfo ai_hints;
2001 struct addrinfo *ai_list, *ai_ptr;
2005 const char *service;
2010 /* Set up the security structures. */
2011 #if HAVE_LIBGCRYPT /* {{{ */
2012 if (se->type == SOCKENT_TYPE_CLIENT)
2014 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
2016 if ((se->data.client.username == NULL)
2017 || (se->data.client.password == NULL))
2019 ERROR ("network plugin: Client socket with "
2020 "security requested, but no "
2021 "credentials are configured.");
2024 gcry_md_hash_buffer (GCRY_MD_SHA256,
2025 se->data.client.password_hash,
2026 se->data.client.password,
2027 strlen (se->data.client.password));
2030 else /* (se->type == SOCKENT_TYPE_SERVER) */
2032 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2034 if (se->data.server.auth_file == NULL)
2036 ERROR ("network plugin: Server socket with "
2037 "security requested, but no "
2038 "password file is configured.");
2042 if (se->data.server.auth_file != NULL)
2044 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2045 if (se->data.server.userdb == NULL)
2047 ERROR ("network plugin: Reading password file "
2049 se->data.server.auth_file);
2050 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2055 #endif /* }}} HAVE_LIBGCRYPT */
2058 service = se->service;
2060 if (service == NULL)
2061 service = NET_DEFAULT_PORT;
2063 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
2066 memset (&ai_hints, 0, sizeof (ai_hints));
2067 ai_hints.ai_flags = 0;
2069 ai_hints.ai_flags |= AI_PASSIVE;
2071 #ifdef AI_ADDRCONFIG
2072 ai_hints.ai_flags |= AI_ADDRCONFIG;
2074 ai_hints.ai_family = AF_UNSPEC;
2075 ai_hints.ai_socktype = SOCK_DGRAM;
2076 ai_hints.ai_protocol = IPPROTO_UDP;
2078 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2081 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2082 (se->node == NULL) ? "(null)" : se->node,
2083 (se->service == NULL) ? "(null)" : se->service,
2084 gai_strerror (ai_return));
2088 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2092 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2096 tmp = realloc (se->data.server.fd,
2097 sizeof (*tmp) * (se->data.server.fd_num + 1));
2100 ERROR ("network plugin: realloc failed.");
2103 se->data.server.fd = tmp;
2104 tmp = se->data.server.fd + se->data.server.fd_num;
2106 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2107 ai_ptr->ai_protocol);
2111 ERROR ("network plugin: socket(2) failed: %s",
2112 sstrerror (errno, errbuf,
2117 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2125 se->data.server.fd_num++;
2127 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2128 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2130 se->data.client.fd = socket (ai_ptr->ai_family,
2131 ai_ptr->ai_socktype,
2132 ai_ptr->ai_protocol);
2133 if (se->data.client.fd < 0)
2136 ERROR ("network plugin: socket(2) failed: %s",
2137 sstrerror (errno, errbuf,
2142 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2143 if (se->data.client.addr == NULL)
2145 ERROR ("network plugin: malloc failed.");
2146 close (se->data.client.fd);
2147 se->data.client.fd = -1;
2151 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2152 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2153 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2154 se->data.client.addrlen = ai_ptr->ai_addrlen;
2156 network_set_ttl (se, ai_ptr);
2157 network_set_interface (se, ai_ptr);
2159 /* We don't open more than one write-socket per
2160 * node/service pair.. */
2162 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2163 } /* for (ai_list) */
2165 freeaddrinfo (ai_list);
2167 /* Check if all went well. */
2168 if (se->type == SOCKENT_TYPE_SERVER)
2170 if (se->data.server.fd_num <= 0)
2173 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2175 if (se->data.client.fd < 0)
2180 } /* }}} int sockent_open */
2182 /* Add a sockent to the global list of sockets */
2183 static int sockent_add (sockent_t *se) /* {{{ */
2185 sockent_t *last_ptr;
2190 if (se->type == SOCKENT_TYPE_SERVER)
2195 tmp = realloc (listen_sockets_pollfd,
2196 sizeof (*tmp) * (listen_sockets_num
2197 + se->data.server.fd_num));
2200 ERROR ("network plugin: realloc failed.");
2203 listen_sockets_pollfd = tmp;
2204 tmp = listen_sockets_pollfd + listen_sockets_num;
2206 for (i = 0; i < se->data.server.fd_num; i++)
2208 memset (tmp + i, 0, sizeof (*tmp));
2209 tmp[i].fd = se->data.server.fd[i];
2210 tmp[i].events = POLLIN | POLLPRI;
2214 listen_sockets_num += se->data.server.fd_num;
2216 if (listen_sockets == NULL)
2218 listen_sockets = se;
2221 last_ptr = listen_sockets;
2223 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2225 if (sending_sockets == NULL)
2227 sending_sockets = se;
2230 last_ptr = sending_sockets;
2233 while (last_ptr->next != NULL)
2234 last_ptr = last_ptr->next;
2235 last_ptr->next = se;
2238 } /* }}} int sockent_add */
2240 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2244 receive_list_entry_t *ent;
2247 /* Lock and wait for more data to come in */
2248 pthread_mutex_lock (&receive_list_lock);
2249 while ((listen_loop == 0)
2250 && (receive_list_head == NULL))
2251 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2253 /* Remove the head entry and unlock */
2254 ent = receive_list_head;
2256 receive_list_head = ent->next;
2257 receive_list_length--;
2258 pthread_mutex_unlock (&receive_list_lock);
2260 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2261 * because we dispatch all missing packets before shutting down. */
2265 /* Look for the correct `sockent_t' */
2266 se = listen_sockets;
2271 for (i = 0; i < se->data.server.fd_num; i++)
2272 if (se->data.server.fd[i] == ent->fd)
2275 if (i < se->data.server.fd_num)
2283 ERROR ("network plugin: Got packet from FD %i, but can't "
2284 "find an appropriate socket entry.",
2291 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2292 /* username = */ NULL);
2298 } /* }}} void *dispatch_thread */
2300 static int network_receive (void) /* {{{ */
2302 char buffer[network_config_packet_size];
2308 receive_list_entry_t *private_list_head;
2309 receive_list_entry_t *private_list_tail;
2310 uint64_t private_list_length;
2312 assert (listen_sockets_num > 0);
2314 private_list_head = NULL;
2315 private_list_tail = NULL;
2316 private_list_length = 0;
2318 while (listen_loop == 0)
2320 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2327 ERROR ("poll failed: %s",
2328 sstrerror (errno, errbuf, sizeof (errbuf)));
2332 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2334 receive_list_entry_t *ent;
2336 if ((listen_sockets_pollfd[i].revents
2337 & (POLLIN | POLLPRI)) == 0)
2341 buffer_len = recv (listen_sockets_pollfd[i].fd,
2342 buffer, sizeof (buffer),
2347 ERROR ("recv failed: %s",
2348 sstrerror (errno, errbuf,
2353 stats_octets_rx += ((uint64_t) buffer_len);
2356 /* TODO: Possible performance enhancement: Do not free
2357 * these entries in the dispatch thread but put them in
2358 * another list, so we don't have to allocate more and
2359 * more of these structures. */
2360 ent = malloc (sizeof (receive_list_entry_t));
2363 ERROR ("network plugin: malloc failed.");
2366 memset (ent, 0, sizeof (receive_list_entry_t));
2367 ent->data = malloc (network_config_packet_size);
2368 if (ent->data == NULL)
2371 ERROR ("network plugin: malloc failed.");
2374 ent->fd = listen_sockets_pollfd[i].fd;
2377 memcpy (ent->data, buffer, buffer_len);
2378 ent->data_len = buffer_len;
2380 if (private_list_head == NULL)
2381 private_list_head = ent;
2383 private_list_tail->next = ent;
2384 private_list_tail = ent;
2385 private_list_length++;
2387 /* Do not block here. Blocking here has led to
2388 * insufficient performance in the past. */
2389 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2391 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2392 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2394 if (receive_list_head == NULL)
2395 receive_list_head = private_list_head;
2397 receive_list_tail->next = private_list_head;
2398 receive_list_tail = private_list_tail;
2399 receive_list_length += private_list_length;
2401 pthread_cond_signal (&receive_list_cond);
2402 pthread_mutex_unlock (&receive_list_lock);
2404 private_list_head = NULL;
2405 private_list_tail = NULL;
2406 private_list_length = 0;
2408 } /* for (listen_sockets_pollfd) */
2409 } /* while (listen_loop == 0) */
2411 /* Make sure everything is dispatched before exiting. */
2412 if (private_list_head != NULL)
2414 pthread_mutex_lock (&receive_list_lock);
2416 if (receive_list_head == NULL)
2417 receive_list_head = private_list_head;
2419 receive_list_tail->next = private_list_head;
2420 receive_list_tail = private_list_tail;
2421 receive_list_length += private_list_length;
2423 private_list_head = NULL;
2424 private_list_tail = NULL;
2425 private_list_length = 0;
2427 pthread_cond_signal (&receive_list_cond);
2428 pthread_mutex_unlock (&receive_list_lock);
2432 } /* }}} int network_receive */
2434 static void *receive_thread (void __attribute__((unused)) *arg)
2436 return (network_receive () ? (void *) 1 : (void *) 0);
2437 } /* void *receive_thread */
2439 static void network_init_buffer (void)
2441 memset (send_buffer, 0, network_config_packet_size);
2442 send_buffer_ptr = send_buffer;
2443 send_buffer_fill = 0;
2445 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2446 } /* int network_init_buffer */
2448 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2449 const char *buffer, size_t buffer_size)
2455 status = sendto (se->data.client.fd, buffer, buffer_size,
2457 (struct sockaddr *) se->data.client.addr,
2458 se->data.client.addrlen);
2464 ERROR ("network plugin: sendto failed: %s",
2465 sstrerror (errno, errbuf,
2472 } /* }}} void networt_send_buffer_plain */
2475 #define BUFFER_ADD(p,s) do { \
2476 memcpy (buffer + buffer_offset, (p), (s)); \
2477 buffer_offset += (s); \
2480 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2481 const char *in_buffer, size_t in_buffer_size)
2483 part_signature_sha256_t ps;
2484 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2485 size_t buffer_offset;
2486 size_t username_len;
2490 unsigned char *hash;
2493 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2496 ERROR ("network plugin: Creating HMAC object failed: %s",
2497 gcry_strerror (err));
2501 err = gcry_md_setkey (hd, se->data.client.password,
2502 strlen (se->data.client.password));
2505 ERROR ("network plugin: gcry_md_setkey failed: %s",
2506 gcry_strerror (err));
2511 username_len = strlen (se->data.client.username);
2512 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2514 ERROR ("network plugin: Username too long: %s",
2515 se->data.client.username);
2519 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2520 se->data.client.username, username_len);
2521 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2522 in_buffer, in_buffer_size);
2524 /* Initialize the `ps' structure. */
2525 memset (&ps, 0, sizeof (ps));
2526 ps.head.type = htons (TYPE_SIGN_SHA256);
2527 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2529 /* Calculate the hash value. */
2530 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2531 username_len + in_buffer_size);
2532 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2535 ERROR ("network plugin: gcry_md_read failed.");
2539 memcpy (ps.hash, hash, sizeof (ps.hash));
2541 /* Add the header */
2544 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2545 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2546 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2548 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2553 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2554 networt_send_buffer_plain (se, buffer, buffer_offset);
2555 } /* }}} void networt_send_buffer_signed */
2557 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2558 const char *in_buffer, size_t in_buffer_size)
2560 part_encryption_aes256_t pea;
2561 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2563 size_t buffer_offset;
2565 size_t username_len;
2567 gcry_cipher_hd_t cypher;
2569 /* Initialize the header fields */
2570 memset (&pea, 0, sizeof (pea));
2571 pea.head.type = htons (TYPE_ENCR_AES256);
2573 pea.username = se->data.client.username;
2575 username_len = strlen (pea.username);
2576 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2578 ERROR ("network plugin: Username too long: %s", pea.username);
2582 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2583 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2584 - sizeof (pea.hash);
2586 assert (buffer_size <= sizeof (buffer));
2587 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2588 "buffer_size = %zu;", buffer_size);
2590 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2591 + username_len + in_buffer_size));
2592 pea.username_length = htons ((uint16_t) username_len);
2594 /* Chose a random initialization vector. */
2595 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2597 /* Create hash of the payload */
2598 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2600 /* Initialize the buffer */
2602 memset (buffer, 0, sizeof (buffer));
2605 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2606 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2607 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2608 BUFFER_ADD (pea.username, username_len);
2609 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2610 assert (buffer_offset == header_size);
2611 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2612 BUFFER_ADD (in_buffer, in_buffer_size);
2614 assert (buffer_offset == buffer_size);
2616 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2617 se->data.client.password);
2621 /* Encrypt the buffer in-place */
2622 err = gcry_cipher_encrypt (cypher,
2623 buffer + header_size,
2624 buffer_size - header_size,
2625 /* in = */ NULL, /* in len = */ 0);
2628 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2629 gcry_strerror (err));
2633 /* Send it out without further modifications */
2634 networt_send_buffer_plain (se, buffer, buffer_size);
2635 } /* }}} void networt_send_buffer_encrypted */
2637 #endif /* HAVE_LIBGCRYPT */
2639 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2643 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2645 for (se = sending_sockets; se != NULL; se = se->next)
2648 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2649 networt_send_buffer_encrypted (se, buffer, buffer_len);
2650 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2651 networt_send_buffer_signed (se, buffer, buffer_len);
2652 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2653 #endif /* HAVE_LIBGCRYPT */
2654 networt_send_buffer_plain (se, buffer, buffer_len);
2655 } /* for (sending_sockets) */
2656 } /* }}} void network_send_buffer */
2658 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2659 value_list_t *vl_def,
2660 const data_set_t *ds, const value_list_t *vl)
2662 char *buffer_orig = buffer;
2664 if (strcmp (vl_def->host, vl->host) != 0)
2666 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2667 vl->host, strlen (vl->host)) != 0)
2669 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2672 if (vl_def->time != vl->time)
2674 if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
2675 (uint64_t) vl->time))
2677 vl_def->time = vl->time;
2680 if (vl_def->interval != vl->interval)
2682 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
2683 (uint64_t) vl->interval))
2685 vl_def->interval = vl->interval;
2688 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2690 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2691 vl->plugin, strlen (vl->plugin)) != 0)
2693 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2696 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2698 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2699 vl->plugin_instance,
2700 strlen (vl->plugin_instance)) != 0)
2702 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2705 if (strcmp (vl_def->type, vl->type) != 0)
2707 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2708 vl->type, strlen (vl->type)) != 0)
2710 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2713 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2715 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2717 strlen (vl->type_instance)) != 0)
2719 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2722 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2725 return (buffer - buffer_orig);
2726 } /* }}} int add_to_buffer */
2728 static void flush_buffer (void)
2730 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2733 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2735 stats_octets_tx += ((uint64_t) send_buffer_fill);
2738 network_init_buffer ();
2741 static int network_write (const data_set_t *ds, const value_list_t *vl,
2742 user_data_t __attribute__((unused)) *user_data)
2746 if (!check_send_okay (vl))
2749 char name[6*DATA_MAX_NAME_LEN];
2750 FORMAT_VL (name, sizeof (name), vl);
2751 name[sizeof (name) - 1] = 0;
2752 DEBUG ("network plugin: network_write: "
2753 "NOT sending %s.", name);
2755 /* Counter is not protected by another lock and may be reached by
2756 * multiple threads */
2757 pthread_mutex_lock (&stats_lock);
2758 stats_values_not_sent++;
2759 pthread_mutex_unlock (&stats_lock);
2763 uc_meta_data_add_unsigned_int (vl,
2764 "network:time_sent", (uint64_t) vl->time);
2766 pthread_mutex_lock (&send_buffer_lock);
2768 status = add_to_buffer (send_buffer_ptr,
2769 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2774 /* status == bytes added to the buffer */
2775 send_buffer_fill += status;
2776 send_buffer_ptr += status;
2778 stats_values_sent++;
2784 status = add_to_buffer (send_buffer_ptr,
2785 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2791 send_buffer_fill += status;
2792 send_buffer_ptr += status;
2794 stats_values_sent++;
2800 ERROR ("network plugin: Unable to append to the "
2801 "buffer for some weird reason");
2803 else if ((network_config_packet_size - send_buffer_fill) < 15)
2808 pthread_mutex_unlock (&send_buffer_lock);
2810 return ((status < 0) ? -1 : 0);
2811 } /* int network_write */
2813 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2816 if ((ci->values_num != 1)
2817 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2818 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2820 ERROR ("network plugin: The `%s' config option needs "
2821 "exactly one boolean argument.", ci->key);
2825 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2827 if (ci->values[0].value.boolean)
2834 char *str = ci->values[0].value.string;
2838 else if (IS_FALSE (str))
2842 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2843 "option as boolean value.",
2850 } /* }}} int network_config_set_boolean */
2852 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2855 if ((ci->values_num != 1)
2856 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2858 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2859 "one numeric argument.");
2863 tmp = (int) ci->values[0].value.number;
2864 if ((tmp > 0) && (tmp <= 255))
2865 network_config_ttl = tmp;
2868 } /* }}} int network_config_set_ttl */
2870 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2873 if ((ci->values_num != 1)
2874 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2876 WARNING ("network plugin: The `Interface' config option needs exactly "
2877 "one string argument.");
2881 if (interface == NULL)
2884 *interface = if_nametoindex (ci->values[0].value.string);
2887 } /* }}} int network_config_set_interface */
2889 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2892 if ((ci->values_num != 1)
2893 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2895 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2896 "one numeric argument.");
2900 tmp = (int) ci->values[0].value.number;
2901 if ((tmp >= 1024) && (tmp <= 65535))
2902 network_config_packet_size = tmp;
2905 } /* }}} int network_config_set_buffer_size */
2908 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2912 if ((ci->values_num != 1)
2913 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2915 WARNING ("network plugin: The `%s' config option needs exactly "
2916 "one string argument.", ci->key);
2920 tmp = strdup (ci->values[0].value.string);
2924 sfree (*ret_string);
2928 } /* }}} int network_config_set_string */
2929 #endif /* HAVE_LIBGCRYPT */
2932 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2936 if ((ci->values_num != 1)
2937 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2939 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2940 "one string argument.");
2944 str = ci->values[0].value.string;
2945 if (strcasecmp ("Encrypt", str) == 0)
2946 *retval = SECURITY_LEVEL_ENCRYPT;
2947 else if (strcasecmp ("Sign", str) == 0)
2948 *retval = SECURITY_LEVEL_SIGN;
2949 else if (strcasecmp ("None", str) == 0)
2950 *retval = SECURITY_LEVEL_NONE;
2953 WARNING ("network plugin: Unknown security level: %s.", str);
2958 } /* }}} int network_config_set_security_level */
2959 #endif /* HAVE_LIBGCRYPT */
2961 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2967 if ((ci->values_num < 1) || (ci->values_num > 2)
2968 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2969 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2971 ERROR ("network plugin: The `%s' config option needs "
2972 "one or two string arguments.", ci->key);
2976 se = malloc (sizeof (*se));
2979 ERROR ("network plugin: malloc failed.");
2982 sockent_init (se, SOCKENT_TYPE_SERVER);
2984 se->node = strdup (ci->values[0].value.string);
2985 if (ci->values_num >= 2)
2986 se->service = strdup (ci->values[1].value.string);
2988 for (i = 0; i < ci->children_num; i++)
2990 oconfig_item_t *child = ci->children + i;
2993 if (strcasecmp ("AuthFile", child->key) == 0)
2994 network_config_set_string (child, &se->data.server.auth_file);
2995 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2996 network_config_set_security_level (child,
2997 &se->data.server.security_level);
2999 #endif /* HAVE_LIBGCRYPT */
3000 if (strcasecmp ("Interface", child->key) == 0)
3001 network_config_set_interface (child,
3005 WARNING ("network plugin: Option `%s' is not allowed here.",
3011 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3012 && (se->data.server.auth_file == NULL))
3014 ERROR ("network plugin: A security level higher than `none' was "
3015 "requested, but no AuthFile option was given. Cowardly refusing to "
3016 "open this socket!");
3017 sockent_destroy (se);
3020 #endif /* HAVE_LIBGCRYPT */
3022 status = sockent_open (se);
3025 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
3026 sockent_destroy (se);
3030 status = sockent_add (se);
3033 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3034 sockent_destroy (se);
3039 } /* }}} int network_config_add_listen */
3041 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3047 if ((ci->values_num < 1) || (ci->values_num > 2)
3048 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3049 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3051 ERROR ("network plugin: The `%s' config option needs "
3052 "one or two string arguments.", ci->key);
3056 se = malloc (sizeof (*se));
3059 ERROR ("network plugin: malloc failed.");
3062 sockent_init (se, SOCKENT_TYPE_CLIENT);
3064 se->node = strdup (ci->values[0].value.string);
3065 if (ci->values_num >= 2)
3066 se->service = strdup (ci->values[1].value.string);
3068 for (i = 0; i < ci->children_num; i++)
3070 oconfig_item_t *child = ci->children + i;
3073 if (strcasecmp ("Username", child->key) == 0)
3074 network_config_set_string (child, &se->data.client.username);
3075 else if (strcasecmp ("Password", child->key) == 0)
3076 network_config_set_string (child, &se->data.client.password);
3077 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3078 network_config_set_security_level (child,
3079 &se->data.client.security_level);
3081 #endif /* HAVE_LIBGCRYPT */
3082 if (strcasecmp ("Interface", child->key) == 0)
3083 network_config_set_interface (child,
3087 WARNING ("network plugin: Option `%s' is not allowed here.",
3093 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3094 && ((se->data.client.username == NULL)
3095 || (se->data.client.password == NULL)))
3097 ERROR ("network plugin: A security level higher than `none' was "
3098 "requested, but no Username or Password option was given. "
3099 "Cowardly refusing to open this socket!");
3100 sockent_destroy (se);
3103 #endif /* HAVE_LIBGCRYPT */
3105 status = sockent_open (se);
3108 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3109 sockent_destroy (se);
3113 status = sockent_add (se);
3116 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3117 sockent_destroy (se);
3122 } /* }}} int network_config_add_server */
3124 static int network_config (oconfig_item_t *ci) /* {{{ */
3128 for (i = 0; i < ci->children_num; i++)
3130 oconfig_item_t *child = ci->children + i;
3132 if (strcasecmp ("Listen", child->key) == 0)
3133 network_config_add_listen (child);
3134 else if (strcasecmp ("Server", child->key) == 0)
3135 network_config_add_server (child);
3136 else if (strcasecmp ("TimeToLive", child->key) == 0)
3137 network_config_set_ttl (child);
3138 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3139 network_config_set_buffer_size (child);
3140 else if (strcasecmp ("Forward", child->key) == 0)
3141 network_config_set_boolean (child, &network_config_forward);
3142 else if (strcasecmp ("ReportStats", child->key) == 0)
3143 network_config_set_boolean (child, &network_config_stats);
3146 WARNING ("network plugin: Option `%s' is not allowed here.",
3152 } /* }}} int network_config */
3154 static int network_notification (const notification_t *n,
3155 user_data_t __attribute__((unused)) *user_data)
3157 char buffer[network_config_packet_size];
3158 char *buffer_ptr = buffer;
3159 int buffer_free = sizeof (buffer);
3162 if (!check_send_notify_okay (n))
3165 memset (buffer, 0, sizeof (buffer));
3167 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3168 (uint64_t) n->time);
3172 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3173 (uint64_t) n->severity);
3177 if (strlen (n->host) > 0)
3179 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3180 n->host, strlen (n->host));
3185 if (strlen (n->plugin) > 0)
3187 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3188 n->plugin, strlen (n->plugin));
3193 if (strlen (n->plugin_instance) > 0)
3195 status = write_part_string (&buffer_ptr, &buffer_free,
3196 TYPE_PLUGIN_INSTANCE,
3197 n->plugin_instance, strlen (n->plugin_instance));
3202 if (strlen (n->type) > 0)
3204 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3205 n->type, strlen (n->type));
3210 if (strlen (n->type_instance) > 0)
3212 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3213 n->type_instance, strlen (n->type_instance));
3218 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3219 n->message, strlen (n->message));
3223 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3226 } /* int network_notification */
3228 static int network_shutdown (void)
3232 /* Kill the listening thread */
3233 if (receive_thread_running != 0)
3235 INFO ("network plugin: Stopping receive thread.");
3236 pthread_kill (receive_thread_id, SIGTERM);
3237 pthread_join (receive_thread_id, NULL /* no return value */);
3238 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3239 receive_thread_running = 0;
3242 /* Shutdown the dispatching thread */
3243 if (dispatch_thread_running != 0)
3245 INFO ("network plugin: Stopping dispatch thread.");
3246 pthread_mutex_lock (&receive_list_lock);
3247 pthread_cond_broadcast (&receive_list_cond);
3248 pthread_mutex_unlock (&receive_list_lock);
3249 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3250 dispatch_thread_running = 0;
3253 sockent_destroy (listen_sockets);
3255 if (send_buffer_fill > 0)
3258 sfree (send_buffer);
3260 /* TODO: Close `sending_sockets' */
3262 plugin_unregister_config ("network");
3263 plugin_unregister_init ("network");
3264 plugin_unregister_write ("network");
3265 plugin_unregister_shutdown ("network");
3268 } /* int network_shutdown */
3270 static int network_stats_read (void) /* {{{ */
3272 derive_t copy_octets_rx;
3273 derive_t copy_octets_tx;
3274 derive_t copy_packets_rx;
3275 derive_t copy_packets_tx;
3276 derive_t copy_values_dispatched;
3277 derive_t copy_values_not_dispatched;
3278 derive_t copy_values_sent;
3279 derive_t copy_values_not_sent;
3280 derive_t copy_receive_list_length;
3281 value_list_t vl = VALUE_LIST_INIT;
3284 copy_octets_rx = stats_octets_rx;
3285 copy_octets_tx = stats_octets_tx;
3286 copy_packets_rx = stats_packets_rx;
3287 copy_packets_tx = stats_packets_tx;
3288 copy_values_dispatched = stats_values_dispatched;
3289 copy_values_not_dispatched = stats_values_not_dispatched;
3290 copy_values_sent = stats_values_sent;
3291 copy_values_not_sent = stats_values_not_sent;
3292 copy_receive_list_length = receive_list_length;
3294 /* Initialize `vl' */
3298 vl.interval = interval_g;
3299 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3300 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3302 /* Octets received / sent */
3303 vl.values[0].derive = (derive_t) copy_octets_rx;
3304 vl.values[1].derive = (derive_t) copy_octets_tx;
3305 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3306 plugin_dispatch_values_secure (&vl);
3308 /* Packets received / send */
3309 vl.values[0].derive = (derive_t) copy_packets_rx;
3310 vl.values[1].derive = (derive_t) copy_packets_tx;
3311 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3312 plugin_dispatch_values_secure (&vl);
3314 /* Values (not) dispatched and (not) send */
3315 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3318 vl.values[0].derive = (derive_t) copy_values_dispatched;
3319 sstrncpy (vl.type_instance, "dispatch-accepted",
3320 sizeof (vl.type_instance));
3321 plugin_dispatch_values_secure (&vl);
3323 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3324 sstrncpy (vl.type_instance, "dispatch-rejected",
3325 sizeof (vl.type_instance));
3326 plugin_dispatch_values_secure (&vl);
3328 vl.values[0].derive = (derive_t) copy_values_sent;
3329 sstrncpy (vl.type_instance, "send-accepted",
3330 sizeof (vl.type_instance));
3331 plugin_dispatch_values_secure (&vl);
3333 vl.values[0].derive = (derive_t) copy_values_not_sent;
3334 sstrncpy (vl.type_instance, "send-rejected",
3335 sizeof (vl.type_instance));
3336 plugin_dispatch_values_secure (&vl);
3338 /* Receive queue length */
3339 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3340 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3341 vl.type_instance[0] = 0;
3342 plugin_dispatch_values_secure (&vl);
3345 } /* }}} int network_stats_read */
3347 static int network_init (void)
3349 static _Bool have_init = 0;
3351 /* Check if we were already initialized. If so, just return - there's
3352 * nothing more to do (for now, that is). */
3358 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3359 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3360 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3363 if (network_config_stats != 0)
3364 plugin_register_read ("network", network_stats_read);
3366 plugin_register_shutdown ("network", network_shutdown);
3368 send_buffer = malloc (network_config_packet_size);
3369 if (send_buffer == NULL)
3371 ERROR ("network plugin: malloc failed.");
3374 network_init_buffer ();
3376 /* setup socket(s) and so on */
3377 if (sending_sockets != NULL)
3379 plugin_register_write ("network", network_write,
3380 /* user_data = */ NULL);
3381 plugin_register_notification ("network", network_notification,
3382 /* user_data = */ NULL);
3385 /* If no threads need to be started, return here. */
3386 if ((listen_sockets_num == 0)
3387 || ((dispatch_thread_running != 0)
3388 && (receive_thread_running != 0)))
3391 if (dispatch_thread_running == 0)
3394 status = pthread_create (&dispatch_thread_id,
3395 NULL /* no attributes */,
3397 NULL /* no argument */);
3401 ERROR ("network: pthread_create failed: %s",
3402 sstrerror (errno, errbuf,
3407 dispatch_thread_running = 1;
3411 if (receive_thread_running == 0)
3414 status = pthread_create (&receive_thread_id,
3415 NULL /* no attributes */,
3417 NULL /* no argument */);
3421 ERROR ("network: pthread_create failed: %s",
3422 sstrerror (errno, errbuf,
3427 receive_thread_running = 1;
3432 } /* int network_init */
3435 * The flush option of the network plugin cannot flush individual identifiers.
3436 * All the values are added to a buffer and sent when the buffer is full, the
3437 * requested value may or may not be in there, it's not worth finding out. We
3438 * just send the buffer if `flush' is called - if the requested value was in
3439 * there, good. If not, well, then there is nothing to flush.. -octo
3441 static int network_flush (__attribute__((unused)) cdtime_t timeout,
3442 __attribute__((unused)) const char *identifier,
3443 __attribute__((unused)) user_data_t *user_data)
3445 pthread_mutex_lock (&send_buffer_lock);
3447 if (send_buffer_fill > 0)
3450 pthread_mutex_unlock (&send_buffer_lock);
3453 } /* int network_flush */
3455 void module_register (void)
3457 plugin_register_complex_config ("network", network_config);
3458 plugin_register_init ("network", network_init);
3459 plugin_register_flush ("network", network_flush,
3460 /* user_data = */ NULL);
3461 } /* void module_register */
3463 /* vim: set fdm=marker : */