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>
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"
69 /* FreeBSD's copy of libgcrypt extends the existing GCRYPT_NO_DEPRECATED
70 * to properly hide all deprecated functionality.
71 * http://svnweb.freebsd.org/ports/head/security/libgcrypt/files/patch-src__gcrypt.h.in
73 # define GCRYPT_NO_DEPRECATED
75 # if defined __APPLE__
76 /* Re enable deprecation warnings */
77 # pragma GCC diagnostic warning "-Wdeprecated-declarations"
79 GCRY_THREAD_OPTION_PTHREAD_IMPL;
82 #ifndef IPV6_ADD_MEMBERSHIP
83 # ifdef IPV6_JOIN_GROUP
84 # define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
86 # error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
88 #endif /* !IP_ADD_MEMBERSHIP */
91 * Maximum size required for encryption / signing:
93 * 42 bytes for the encryption header
94 * + 64 bytes for the username
98 #define BUFF_SIG_SIZE 106
103 #define SECURITY_LEVEL_NONE 0
105 # define SECURITY_LEVEL_SIGN 1
106 # define SECURITY_LEVEL_ENCRYPT 2
108 struct sockent_client
111 struct sockaddr_storage *addr;
117 gcry_cipher_hd_t cypher;
118 unsigned char password_hash[32];
122 struct sockent_server
130 gcry_cipher_hd_t cypher;
134 typedef struct sockent
136 #define SOCKENT_TYPE_CLIENT 1
137 #define SOCKENT_TYPE_SERVER 2
146 struct sockent_client client;
147 struct sockent_server server;
150 struct sockent *next;
153 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
154 * 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
155 * +-------+-----------------------+-------------------------------+
156 * ! Ver. ! ! Length !
157 * +-------+-----------------------+-------------------------------+
164 typedef struct part_header_s part_header_t;
166 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
167 * 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
168 * +-------------------------------+-------------------------------+
170 * +-------------------------------+-------------------------------+
171 * : (Length - 4) Bytes :
172 * +---------------------------------------------------------------+
179 typedef struct part_string_s part_string_t;
181 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
182 * 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
183 * +-------------------------------+-------------------------------+
185 * +-------------------------------+-------------------------------+
186 * : (Length - 4 == 2 || 4 || 8) Bytes :
187 * +---------------------------------------------------------------+
194 typedef struct part_number_s part_number_t;
196 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
197 * 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
198 * +-------------------------------+-------------------------------+
200 * +-------------------------------+---------------+---------------+
201 * ! Num of values ! Type0 ! Type1 !
202 * +-------------------------------+---------------+---------------+
205 * +---------------------------------------------------------------+
208 * +---------------------------------------------------------------+
213 uint16_t *num_values;
214 uint8_t *values_types;
217 typedef struct part_values_s part_values_t;
219 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
220 * 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
221 * +-------------------------------+-------------------------------+
223 * +-------------------------------+-------------------------------+
224 * ! Hash (Bits 0 - 31) !
226 * ! Hash (Bits 224 - 255) !
227 * +---------------------------------------------------------------+
230 #define PART_SIGNATURE_SHA256_SIZE 36
231 struct part_signature_sha256_s
234 unsigned char hash[32];
237 typedef struct part_signature_sha256_s part_signature_sha256_t;
239 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
240 * 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
241 * +-------------------------------+-------------------------------+
243 * +-------------------------------+-------------------------------+
244 * ! Original length ! Padding (0 - 15 bytes) !
245 * +-------------------------------+-------------------------------+
246 * ! Hash (Bits 0 - 31) !
248 * ! Hash (Bits 128 - 159) !
249 * +---------------------------------------------------------------+
252 #define PART_ENCRYPTION_AES256_SIZE 42
253 struct part_encryption_aes256_s
256 uint16_t username_length;
258 unsigned char iv[16];
260 unsigned char hash[20];
264 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
266 struct receive_list_entry_s
271 struct receive_list_entry_s *next;
273 typedef struct receive_list_entry_s receive_list_entry_t;
278 static int network_config_ttl = 0;
279 /* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
280 static size_t network_config_packet_size = 1452;
281 static int network_config_forward = 0;
282 static int network_config_stats = 0;
284 static sockent_t *sending_sockets = NULL;
286 static receive_list_entry_t *receive_list_head = NULL;
287 static receive_list_entry_t *receive_list_tail = NULL;
288 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
289 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
290 static uint64_t receive_list_length = 0;
292 static sockent_t *listen_sockets = NULL;
293 static struct pollfd *listen_sockets_pollfd = NULL;
294 static size_t listen_sockets_num = 0;
296 /* The receive and dispatch threads will run as long as `listen_loop' is set to
298 static int listen_loop = 0;
299 static int receive_thread_running = 0;
300 static pthread_t receive_thread_id;
301 static int dispatch_thread_running = 0;
302 static pthread_t dispatch_thread_id;
304 /* Buffer in which to-be-sent network packets are constructed. */
305 static char *send_buffer;
306 static char *send_buffer_ptr;
307 static int send_buffer_fill;
308 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
309 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
311 /* XXX: These counters are incremented from one place only. The spot in which
312 * the values are incremented is either only reachable by one thread (the
313 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
314 * example). Only if neither is true, the stats_lock is acquired. The counters
315 * are always read without holding a lock in the hope that writing 8 bytes to
316 * memory is an atomic operation. */
317 static derive_t stats_octets_rx = 0;
318 static derive_t stats_octets_tx = 0;
319 static derive_t stats_packets_rx = 0;
320 static derive_t stats_packets_tx = 0;
321 static derive_t stats_values_dispatched = 0;
322 static derive_t stats_values_not_dispatched = 0;
323 static derive_t stats_values_sent = 0;
324 static derive_t stats_values_not_sent = 0;
325 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
330 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
332 uint64_t time_sent = 0;
335 status = uc_meta_data_get_unsigned_int (vl,
336 "network:time_sent", &time_sent);
338 /* This is a value we already sent. Don't allow it to be received again in
339 * order to avoid looping. */
340 if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
344 } /* }}} _Bool check_receive_okay */
346 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
351 if (network_config_forward != 0)
354 if (vl->meta == NULL)
357 status = meta_data_get_boolean (vl->meta, "network:received", &received);
358 if (status == -ENOENT)
360 else if (status != 0)
362 ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
363 "with status %i.", status);
367 /* By default, only *send* value lists that were not *received* by the
370 } /* }}} _Bool check_send_okay */
372 static _Bool check_notify_received (const notification_t *n) /* {{{ */
374 notification_meta_t *ptr;
376 for (ptr = n->meta; ptr != NULL; ptr = ptr->next)
377 if ((strcmp ("network:received", ptr->name) == 0)
378 && (ptr->type == NM_TYPE_BOOLEAN))
379 return ((_Bool) ptr->nm_value.nm_boolean);
382 } /* }}} _Bool check_notify_received */
384 static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
386 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
392 received = check_notify_received (n);
394 if (network_config_forward && received)
396 c_complain_once (LOG_ERR, &complain_forwarding,
397 "network plugin: A notification has been received via the network "
398 "forwarding if enabled. Forwarding of notifications is currently "
399 "not supported, because there is not loop-deteciton available. "
400 "Please contact the collectd mailing list if you need this "
404 /* By default, only *send* value lists that were not *received* by the
407 } /* }}} _Bool check_send_notify_okay */
409 static int network_dispatch_values (value_list_t *vl, /* {{{ */
410 const char *username)
415 || (strlen (vl->host) <= 0)
416 || (strlen (vl->plugin) <= 0)
417 || (strlen (vl->type) <= 0))
420 if (!check_receive_okay (vl))
423 char name[6*DATA_MAX_NAME_LEN];
424 FORMAT_VL (name, sizeof (name), vl);
425 name[sizeof (name) - 1] = 0;
426 DEBUG ("network plugin: network_dispatch_values: "
427 "NOT dispatching %s.", name);
429 stats_values_not_dispatched++;
433 assert (vl->meta == NULL);
435 vl->meta = meta_data_create ();
436 if (vl->meta == NULL)
438 ERROR ("network plugin: meta_data_create failed.");
442 status = meta_data_add_boolean (vl->meta, "network:received", 1);
445 ERROR ("network plugin: meta_data_add_boolean failed.");
446 meta_data_destroy (vl->meta);
451 if (username != NULL)
453 status = meta_data_add_string (vl->meta, "network:username", username);
456 ERROR ("network plugin: meta_data_add_string failed.");
457 meta_data_destroy (vl->meta);
463 plugin_dispatch_values_secure (vl);
464 stats_values_dispatched++;
466 meta_data_destroy (vl->meta);
470 } /* }}} int network_dispatch_values */
472 static int network_dispatch_notification (notification_t *n) /* {{{ */
476 assert (n->meta == NULL);
478 status = plugin_notification_meta_add_boolean (n, "network:received", 1);
481 ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
482 plugin_notification_meta_free (n->meta);
487 status = plugin_dispatch_notification (n);
489 plugin_notification_meta_free (n->meta);
493 } /* }}} int network_dispatch_notification */
496 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
497 const void *iv, size_t iv_size, const char *username)
500 gcry_cipher_hd_t *cyper_ptr;
501 unsigned char password_hash[32];
503 if (se->type == SOCKENT_TYPE_CLIENT)
505 cyper_ptr = &se->data.client.cypher;
506 memcpy (password_hash, se->data.client.password_hash,
507 sizeof (password_hash));
513 cyper_ptr = &se->data.server.cypher;
515 if (username == NULL)
518 secret = fbh_get (se->data.server.userdb, username);
522 gcry_md_hash_buffer (GCRY_MD_SHA256,
524 secret, strlen (secret));
529 if (*cyper_ptr == NULL)
531 err = gcry_cipher_open (cyper_ptr,
532 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
535 ERROR ("network plugin: gcry_cipher_open returned: %s",
536 gcry_strerror (err));
543 gcry_cipher_reset (*cyper_ptr);
545 assert (*cyper_ptr != NULL);
547 err = gcry_cipher_setkey (*cyper_ptr,
548 password_hash, sizeof (password_hash));
551 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
552 gcry_strerror (err));
553 gcry_cipher_close (*cyper_ptr);
558 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
561 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
562 gcry_strerror (err));
563 gcry_cipher_close (*cyper_ptr);
569 } /* }}} int network_get_aes256_cypher */
570 #endif /* HAVE_LIBGCRYPT */
572 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
573 const data_set_t *ds, const value_list_t *vl)
579 part_header_t pkg_ph;
580 uint16_t pkg_num_values;
581 uint8_t *pkg_values_types;
587 num_values = vl->values_len;
588 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
589 + (num_values * sizeof (uint8_t))
590 + (num_values * sizeof (value_t));
592 if (*ret_buffer_len < packet_len)
595 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
596 if (pkg_values_types == NULL)
598 ERROR ("network plugin: write_part_values: malloc failed.");
602 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
603 if (pkg_values == NULL)
605 free (pkg_values_types);
606 ERROR ("network plugin: write_part_values: malloc failed.");
610 pkg_ph.type = htons (TYPE_VALUES);
611 pkg_ph.length = htons (packet_len);
613 pkg_num_values = htons ((uint16_t) vl->values_len);
615 for (i = 0; i < num_values; i++)
617 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
618 switch (ds->ds[i].type)
620 case DS_TYPE_COUNTER:
621 pkg_values[i].counter = htonll (vl->values[i].counter);
625 pkg_values[i].gauge = htond (vl->values[i].gauge);
629 pkg_values[i].derive = htonll (vl->values[i].derive);
632 case DS_TYPE_ABSOLUTE:
633 pkg_values[i].absolute = htonll (vl->values[i].absolute);
637 free (pkg_values_types);
639 ERROR ("network plugin: write_part_values: "
640 "Unknown data source type: %i",
643 } /* switch (ds->ds[i].type) */
644 } /* for (num_values) */
647 * Use `memcpy' to write everything to the buffer, because the pointer
648 * may be unaligned and some architectures, such as SPARC, can't handle
651 packet_ptr = *ret_buffer;
653 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
654 offset += sizeof (pkg_ph);
655 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
656 offset += sizeof (pkg_num_values);
657 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
658 offset += num_values * sizeof (uint8_t);
659 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
660 offset += num_values * sizeof (value_t);
662 assert (offset == packet_len);
664 *ret_buffer = packet_ptr + packet_len;
665 *ret_buffer_len -= packet_len;
667 free (pkg_values_types);
671 } /* int write_part_values */
673 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
674 int type, uint64_t value)
679 part_header_t pkg_head;
684 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
686 if (*ret_buffer_len < packet_len)
689 pkg_head.type = htons (type);
690 pkg_head.length = htons (packet_len);
691 pkg_value = htonll (value);
693 packet_ptr = *ret_buffer;
695 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
696 offset += sizeof (pkg_head);
697 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
698 offset += sizeof (pkg_value);
700 assert (offset == packet_len);
702 *ret_buffer = packet_ptr + packet_len;
703 *ret_buffer_len -= packet_len;
706 } /* int write_part_number */
708 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
709 int type, const char *str, int str_len)
719 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
720 if (*ret_buffer_len < buffer_len)
723 pkg_type = htons (type);
724 pkg_length = htons (buffer_len);
726 buffer = *ret_buffer;
728 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
729 offset += sizeof (pkg_type);
730 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
731 offset += sizeof (pkg_length);
732 memcpy (buffer + offset, str, str_len);
734 memset (buffer + offset, '\0', 1);
737 assert (offset == buffer_len);
739 *ret_buffer = buffer + buffer_len;
740 *ret_buffer_len -= buffer_len;
743 } /* int write_part_string */
745 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
746 value_t **ret_values, int *ret_num_values)
748 char *buffer = *ret_buffer;
749 size_t buffer_len = *ret_buffer_len;
764 NOTICE ("network plugin: packet is too short: "
765 "buffer_len = %zu", buffer_len);
769 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
770 buffer += sizeof (tmp16);
771 pkg_type = ntohs (tmp16);
773 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
774 buffer += sizeof (tmp16);
775 pkg_length = ntohs (tmp16);
777 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
778 buffer += sizeof (tmp16);
779 pkg_numval = ntohs (tmp16);
781 assert (pkg_type == TYPE_VALUES);
783 exp_size = 3 * sizeof (uint16_t)
784 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
785 if (buffer_len < exp_size)
787 WARNING ("network plugin: parse_part_values: "
789 "Chunk of size %zu expected, "
790 "but buffer has only %zu bytes left.",
791 exp_size, buffer_len);
795 if (pkg_length != exp_size)
797 WARNING ("network plugin: parse_part_values: "
798 "Length and number of values "
799 "in the packet don't match.");
803 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
804 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
805 if ((pkg_types == NULL) || (pkg_values == NULL))
809 ERROR ("network plugin: parse_part_values: malloc failed.");
813 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
814 buffer += pkg_numval * sizeof (uint8_t);
815 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
816 buffer += pkg_numval * sizeof (value_t);
818 for (i = 0; i < pkg_numval; i++)
820 switch (pkg_types[i])
822 case DS_TYPE_COUNTER:
823 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
827 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
831 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
834 case DS_TYPE_ABSOLUTE:
835 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
839 NOTICE ("network plugin: parse_part_values: "
840 "Don't know how to handle data source type %"PRIu8,
845 } /* switch (pkg_types[i]) */
848 *ret_buffer = buffer;
849 *ret_buffer_len = buffer_len - pkg_length;
850 *ret_num_values = pkg_numval;
851 *ret_values = pkg_values;
856 } /* int parse_part_values */
858 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
861 char *buffer = *ret_buffer;
862 size_t buffer_len = *ret_buffer_len;
866 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
870 if (buffer_len < exp_size)
872 WARNING ("network plugin: parse_part_number: "
874 "Chunk of size %zu expected, "
875 "but buffer has only %zu bytes left.",
876 exp_size, buffer_len);
880 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
881 buffer += sizeof (tmp16);
882 /* pkg_type = ntohs (tmp16); */
884 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
885 buffer += sizeof (tmp16);
886 pkg_length = ntohs (tmp16);
888 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
889 buffer += sizeof (tmp64);
890 *value = ntohll (tmp64);
892 *ret_buffer = buffer;
893 *ret_buffer_len = buffer_len - pkg_length;
896 } /* int parse_part_number */
898 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
899 char *output, int output_len)
901 char *buffer = *ret_buffer;
902 size_t buffer_len = *ret_buffer_len;
905 size_t header_size = 2 * sizeof (uint16_t);
909 if (buffer_len < header_size)
911 WARNING ("network plugin: parse_part_string: "
913 "Chunk of at least size %zu expected, "
914 "but buffer has only %zu bytes left.",
915 header_size, buffer_len);
919 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
920 buffer += sizeof (tmp16);
921 /* pkg_type = ntohs (tmp16); */
923 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
924 buffer += sizeof (tmp16);
925 pkg_length = ntohs (tmp16);
927 /* Check that packet fits in the input buffer */
928 if (pkg_length > buffer_len)
930 WARNING ("network plugin: parse_part_string: "
932 "Chunk of size %"PRIu16" received, "
933 "but buffer has only %zu bytes left.",
934 pkg_length, buffer_len);
938 /* Check that pkg_length is in the valid range */
939 if (pkg_length <= header_size)
941 WARNING ("network plugin: parse_part_string: "
943 "Header claims this packet is only %hu "
944 "bytes long.", pkg_length);
948 /* Check that the package data fits into the output buffer.
949 * The previous if-statement ensures that:
950 * `pkg_length > header_size' */
952 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
954 WARNING ("network plugin: parse_part_string: "
955 "Output buffer too small.");
959 /* All sanity checks successfull, let's copy the data over */
960 output_len = pkg_length - header_size;
961 memcpy ((void *) output, (void *) buffer, output_len);
962 buffer += output_len;
964 /* For some very weird reason '\0' doesn't do the trick on SPARC in
966 if (output[output_len - 1] != 0)
968 WARNING ("network plugin: parse_part_string: "
969 "Received string does not end "
970 "with a NULL-byte.");
974 *ret_buffer = buffer;
975 *ret_buffer_len = buffer_len - pkg_length;
978 } /* int parse_part_string */
980 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
981 * parse_packet and vice versa. */
982 #define PP_SIGNED 0x01
983 #define PP_ENCRYPTED 0x02
984 static int parse_packet (sockent_t *se,
985 void *buffer, size_t buffer_size, int flags,
986 const char *username);
988 #define BUFFER_READ(p,s) do { \
989 memcpy ((p), buffer + buffer_offset, (s)); \
990 buffer_offset += (s); \
994 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
995 void **ret_buffer, size_t *ret_buffer_len, int flags)
997 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
1001 size_t buffer_offset;
1003 size_t username_len;
1006 part_signature_sha256_t pss;
1007 uint16_t pss_head_length;
1008 char hash[sizeof (pss.hash)];
1012 unsigned char *hash_ptr;
1014 buffer = *ret_buffer;
1015 buffer_len = *ret_buffer_len;
1018 if (se->data.server.userdb == NULL)
1020 c_complain (LOG_NOTICE, &complain_no_users,
1021 "network plugin: Received signed network packet but can't verify it "
1022 "because no user DB has been configured. Will accept it.");
1026 /* Check if the buffer has enough data for this structure. */
1027 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1030 /* Read type and length header */
1031 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1032 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1033 pss_head_length = ntohs (pss.head.length);
1035 /* Check if the `pss_head_length' is within bounds. */
1036 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1037 || (pss_head_length > buffer_len))
1039 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1043 /* Copy the hash. */
1044 BUFFER_READ (pss.hash, sizeof (pss.hash));
1046 /* Calculate username length (without null byte) and allocate memory */
1047 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1048 pss.username = malloc (username_len + 1);
1049 if (pss.username == NULL)
1052 /* Read the username */
1053 BUFFER_READ (pss.username, username_len);
1054 pss.username[username_len] = 0;
1056 assert (buffer_offset == pss_head_length);
1058 /* Query the password */
1059 secret = fbh_get (se->data.server.userdb, pss.username);
1062 ERROR ("network plugin: Unknown user: %s", pss.username);
1063 sfree (pss.username);
1067 /* Create a hash device and check the HMAC */
1069 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1072 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1073 gcry_strerror (err));
1075 sfree (pss.username);
1079 err = gcry_md_setkey (hd, secret, strlen (secret));
1082 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1085 sfree (pss.username);
1090 buffer + PART_SIGNATURE_SHA256_SIZE,
1091 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1092 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1093 if (hash_ptr == NULL)
1095 ERROR ("network plugin: gcry_md_read failed.");
1098 sfree (pss.username);
1101 memcpy (hash, hash_ptr, sizeof (hash));
1107 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1109 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1114 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1115 flags | PP_SIGNED, pss.username);
1119 sfree (pss.username);
1121 *ret_buffer = buffer + buffer_len;
1122 *ret_buffer_len = 0;
1125 } /* }}} int parse_part_sign_sha256 */
1126 /* #endif HAVE_LIBGCRYPT */
1128 #else /* if !HAVE_LIBGCRYPT */
1129 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1130 void **ret_buffer, size_t *ret_buffer_size, int flags)
1132 static int warning_has_been_printed = 0;
1136 size_t buffer_offset;
1139 part_signature_sha256_t pss;
1141 buffer = *ret_buffer;
1142 buffer_size = *ret_buffer_size;
1145 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1148 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1149 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1150 part_len = ntohs (pss.head.length);
1152 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1153 || (part_len > buffer_size))
1156 if (warning_has_been_printed == 0)
1158 WARNING ("network plugin: Received signed packet, but the network "
1159 "plugin was not linked with libgcrypt, so I cannot "
1160 "verify the signature. The packet will be accepted.");
1161 warning_has_been_printed = 1;
1164 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1165 /* username = */ NULL);
1167 *ret_buffer = buffer + buffer_size;
1168 *ret_buffer_size = 0;
1171 } /* }}} int parse_part_sign_sha256 */
1172 #endif /* !HAVE_LIBGCRYPT */
1175 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1176 void **ret_buffer, size_t *ret_buffer_len,
1179 char *buffer = *ret_buffer;
1180 size_t buffer_len = *ret_buffer_len;
1183 size_t buffer_offset;
1184 uint16_t username_len;
1185 part_encryption_aes256_t pea;
1186 unsigned char hash[sizeof (pea.hash)];
1188 gcry_cipher_hd_t cypher;
1191 /* Make sure at least the header if available. */
1192 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1194 NOTICE ("network plugin: parse_part_encr_aes256: "
1195 "Discarding short packet.");
1201 /* Copy the unencrypted information into `pea'. */
1202 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1203 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1205 /* Check the `part size'. */
1206 part_size = ntohs (pea.head.length);
1207 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1208 || (part_size > buffer_len))
1210 NOTICE ("network plugin: parse_part_encr_aes256: "
1211 "Discarding part with invalid size.");
1215 /* Read the username */
1216 BUFFER_READ (&username_len, sizeof (username_len));
1217 username_len = ntohs (username_len);
1219 if ((username_len <= 0)
1220 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1222 NOTICE ("network plugin: parse_part_encr_aes256: "
1223 "Discarding part with invalid username length.");
1227 assert (username_len > 0);
1228 pea.username = malloc (username_len + 1);
1229 if (pea.username == NULL)
1231 BUFFER_READ (pea.username, username_len);
1232 pea.username[username_len] = 0;
1234 /* Last but not least, the initialization vector */
1235 BUFFER_READ (pea.iv, sizeof (pea.iv));
1237 /* Make sure we are at the right position */
1238 assert (buffer_offset == (username_len +
1239 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1241 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1245 sfree (pea.username);
1249 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1250 assert (payload_len > 0);
1252 /* Decrypt the packet in-place */
1253 err = gcry_cipher_decrypt (cypher,
1254 buffer + buffer_offset,
1255 part_size - buffer_offset,
1256 /* in = */ NULL, /* in len = */ 0);
1259 sfree (pea.username);
1260 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1261 gcry_strerror (err));
1266 BUFFER_READ (pea.hash, sizeof (pea.hash));
1268 /* Make sure we're at the right position - again */
1269 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1270 assert (buffer_offset == (part_size - payload_len));
1272 /* Check hash sum */
1273 memset (hash, 0, sizeof (hash));
1274 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1275 buffer + buffer_offset, payload_len);
1276 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1278 sfree (pea.username);
1279 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1283 parse_packet (se, buffer + buffer_offset, payload_len,
1284 flags | PP_ENCRYPTED, pea.username);
1286 /* XXX: Free pea.username?!? */
1288 /* Update return values */
1289 *ret_buffer = buffer + part_size;
1290 *ret_buffer_len = buffer_len - part_size;
1292 sfree (pea.username);
1295 } /* }}} int parse_part_encr_aes256 */
1296 /* #endif HAVE_LIBGCRYPT */
1298 #else /* if !HAVE_LIBGCRYPT */
1299 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1300 void **ret_buffer, size_t *ret_buffer_size, int flags)
1302 static int warning_has_been_printed = 0;
1306 size_t buffer_offset;
1311 buffer = *ret_buffer;
1312 buffer_size = *ret_buffer_size;
1315 /* parse_packet assures this minimum size. */
1316 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1318 BUFFER_READ (&ph.type, sizeof (ph.type));
1319 BUFFER_READ (&ph.length, sizeof (ph.length));
1320 ph_length = ntohs (ph.length);
1322 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1323 || (ph_length > buffer_size))
1325 ERROR ("network plugin: AES-256 encrypted part "
1326 "with invalid length received.");
1330 if (warning_has_been_printed == 0)
1332 WARNING ("network plugin: Received encrypted packet, but the network "
1333 "plugin was not linked with libgcrypt, so I cannot "
1334 "decrypt it. The part will be discarded.");
1335 warning_has_been_printed = 1;
1338 *ret_buffer += ph_length;
1339 *ret_buffer_size -= ph_length;
1342 } /* }}} int parse_part_encr_aes256 */
1343 #endif /* !HAVE_LIBGCRYPT */
1347 static int parse_packet (sockent_t *se, /* {{{ */
1348 void *buffer, size_t buffer_size, int flags,
1349 const char *username)
1353 value_list_t vl = VALUE_LIST_INIT;
1357 int packet_was_signed = (flags & PP_SIGNED);
1358 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1359 int printed_ignore_warning = 0;
1360 #endif /* HAVE_LIBGCRYPT */
1363 memset (&vl, '\0', sizeof (vl));
1364 memset (&n, '\0', sizeof (n));
1367 while ((status == 0) && (0 < buffer_size)
1368 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1370 uint16_t pkg_length;
1373 memcpy ((void *) &pkg_type,
1376 memcpy ((void *) &pkg_length,
1377 (void *) (buffer + sizeof (pkg_type)),
1378 sizeof (pkg_length));
1380 pkg_length = ntohs (pkg_length);
1381 pkg_type = ntohs (pkg_type);
1383 if (pkg_length > buffer_size)
1385 /* Ensure that this loop terminates eventually */
1386 if (pkg_length < (2 * sizeof (uint16_t)))
1389 if (pkg_type == TYPE_ENCR_AES256)
1391 status = parse_part_encr_aes256 (se,
1392 &buffer, &buffer_size, flags);
1395 ERROR ("network plugin: Decrypting AES256 "
1397 "with status %i.", status);
1402 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1403 && (packet_was_encrypted == 0))
1405 if (printed_ignore_warning == 0)
1407 INFO ("network plugin: Unencrypted packet or "
1408 "part has been ignored.");
1409 printed_ignore_warning = 1;
1411 buffer = ((char *) buffer) + pkg_length;
1414 #endif /* HAVE_LIBGCRYPT */
1415 else if (pkg_type == TYPE_SIGN_SHA256)
1417 status = parse_part_sign_sha256 (se,
1418 &buffer, &buffer_size, flags);
1421 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1423 "with status %i.", status);
1428 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1429 && (packet_was_encrypted == 0)
1430 && (packet_was_signed == 0))
1432 if (printed_ignore_warning == 0)
1434 INFO ("network plugin: Unsigned packet or "
1435 "part has been ignored.");
1436 printed_ignore_warning = 1;
1438 buffer = ((char *) buffer) + pkg_length;
1441 #endif /* HAVE_LIBGCRYPT */
1442 else if (pkg_type == TYPE_VALUES)
1444 status = parse_part_values (&buffer, &buffer_size,
1445 &vl.values, &vl.values_len);
1449 network_dispatch_values (&vl, username);
1453 else if (pkg_type == TYPE_TIME)
1456 status = parse_part_number (&buffer, &buffer_size,
1460 vl.time = TIME_T_TO_CDTIME_T (tmp);
1461 n.time = TIME_T_TO_CDTIME_T (tmp);
1464 else if (pkg_type == TYPE_TIME_HR)
1467 status = parse_part_number (&buffer, &buffer_size,
1471 vl.time = (cdtime_t) tmp;
1472 n.time = (cdtime_t) tmp;
1475 else if (pkg_type == TYPE_INTERVAL)
1478 status = parse_part_number (&buffer, &buffer_size,
1481 vl.interval = TIME_T_TO_CDTIME_T (tmp);
1483 else if (pkg_type == TYPE_INTERVAL_HR)
1486 status = parse_part_number (&buffer, &buffer_size,
1489 vl.interval = (cdtime_t) tmp;
1491 else if (pkg_type == TYPE_HOST)
1493 status = parse_part_string (&buffer, &buffer_size,
1494 vl.host, sizeof (vl.host));
1496 sstrncpy (n.host, vl.host, sizeof (n.host));
1498 else if (pkg_type == TYPE_PLUGIN)
1500 status = parse_part_string (&buffer, &buffer_size,
1501 vl.plugin, sizeof (vl.plugin));
1503 sstrncpy (n.plugin, vl.plugin,
1506 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1508 status = parse_part_string (&buffer, &buffer_size,
1510 sizeof (vl.plugin_instance));
1512 sstrncpy (n.plugin_instance,
1514 sizeof (n.plugin_instance));
1516 else if (pkg_type == TYPE_TYPE)
1518 status = parse_part_string (&buffer, &buffer_size,
1519 vl.type, sizeof (vl.type));
1521 sstrncpy (n.type, vl.type, sizeof (n.type));
1523 else if (pkg_type == TYPE_TYPE_INSTANCE)
1525 status = parse_part_string (&buffer, &buffer_size,
1527 sizeof (vl.type_instance));
1529 sstrncpy (n.type_instance, vl.type_instance,
1530 sizeof (n.type_instance));
1532 else if (pkg_type == TYPE_MESSAGE)
1534 status = parse_part_string (&buffer, &buffer_size,
1535 n.message, sizeof (n.message));
1541 else if ((n.severity != NOTIF_FAILURE)
1542 && (n.severity != NOTIF_WARNING)
1543 && (n.severity != NOTIF_OKAY))
1545 INFO ("network plugin: "
1546 "Ignoring notification with "
1547 "unknown severity %i.",
1550 else if (n.time <= 0)
1552 INFO ("network plugin: "
1553 "Ignoring notification with "
1556 else if (strlen (n.message) <= 0)
1558 INFO ("network plugin: "
1559 "Ignoring notification with "
1560 "an empty message.");
1564 network_dispatch_notification (&n);
1567 else if (pkg_type == TYPE_SEVERITY)
1570 status = parse_part_number (&buffer, &buffer_size,
1573 n.severity = (int) tmp;
1577 DEBUG ("network plugin: parse_packet: Unknown part"
1578 " type: 0x%04hx", pkg_type);
1579 buffer = ((char *) buffer) + pkg_length;
1581 } /* while (buffer_size > sizeof (part_header_t)) */
1583 if (status == 0 && buffer_size > 0)
1584 WARNING ("network plugin: parse_packet: Received truncated "
1585 "packet, try increasing `MaxPacketSize'");
1588 } /* }}} int parse_packet */
1590 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1599 sfree (sec->username);
1600 sfree (sec->password);
1601 if (sec->cypher != NULL)
1602 gcry_cipher_close (sec->cypher);
1604 } /* }}} void free_sockent_client */
1606 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1610 for (i = 0; i < ses->fd_num; i++)
1612 if (ses->fd[i] >= 0)
1621 sfree (ses->auth_file);
1622 fbh_destroy (ses->userdb);
1623 if (ses->cypher != NULL)
1624 gcry_cipher_close (ses->cypher);
1626 } /* }}} void free_sockent_server */
1628 static void sockent_destroy (sockent_t *se) /* {{{ */
1632 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1639 sfree (se->service);
1641 if (se->type == SOCKENT_TYPE_CLIENT)
1642 free_sockent_client (&se->data.client);
1644 free_sockent_server (&se->data.server);
1649 } /* }}} void sockent_destroy */
1652 * int network_set_ttl
1654 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1655 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1657 * The `struct addrinfo' is used to destinguish between unicast and multicast
1660 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1662 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1663 network_config_ttl);
1665 assert (se->type == SOCKENT_TYPE_CLIENT);
1667 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1670 if (ai->ai_family == AF_INET)
1672 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1675 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1676 optname = IP_MULTICAST_TTL;
1680 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1681 &network_config_ttl,
1682 sizeof (network_config_ttl)) != 0)
1685 ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
1686 sstrerror (errno, errbuf, sizeof (errbuf)));
1690 else if (ai->ai_family == AF_INET6)
1692 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1693 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1696 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1697 optname = IPV6_MULTICAST_HOPS;
1699 optname = IPV6_UNICAST_HOPS;
1701 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1702 &network_config_ttl,
1703 sizeof (network_config_ttl)) != 0)
1706 ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
1707 sstrerror (errno, errbuf,
1714 } /* int network_set_ttl */
1716 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1718 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1721 assert (se->type == SOCKENT_TYPE_CLIENT);
1723 if (ai->ai_family == AF_INET)
1725 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1727 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1729 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1730 /* If possible, use the "ip_mreqn" structure which has
1731 * an "interface index" member. Using the interface
1732 * index is preferred here, because of its similarity
1733 * to the way IPv6 handles this. Unfortunately, it
1734 * appears not to be portable. */
1735 struct ip_mreqn mreq;
1737 memset (&mreq, 0, sizeof (mreq));
1738 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1739 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1740 mreq.imr_ifindex = se->interface;
1742 struct ip_mreq mreq;
1744 memset (&mreq, 0, sizeof (mreq));
1745 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1746 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1749 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1750 &mreq, sizeof (mreq)) != 0)
1753 ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
1754 sstrerror (errno, errbuf, sizeof (errbuf)));
1761 else if (ai->ai_family == AF_INET6)
1763 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1765 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1767 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1769 sizeof (se->interface)) != 0)
1772 ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
1773 sstrerror (errno, errbuf,
1782 /* else: Not a multicast interface. */
1783 if (se->interface != 0)
1785 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1786 char interface_name[IFNAMSIZ];
1788 if (if_indextoname (se->interface, interface_name) == NULL)
1791 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1793 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1795 sizeof(interface_name)) == -1 )
1798 ERROR ("network plugin: setsockopt (bind-if): %s",
1799 sstrerror (errno, errbuf, sizeof (errbuf)));
1802 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1805 WARNING ("network plugin: Cannot set the interface on a unicast "
1807 # if !defined(SO_BINDTODEVICE)
1808 "the \"SO_BINDTODEVICE\" socket option "
1810 "the \"if_indextoname\" function "
1812 "is not available on your system.");
1818 } /* }}} network_set_interface */
1820 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1829 /* allow multiple sockets to use the same PORT number */
1830 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1831 &yes, sizeof(yes)) == -1) {
1833 ERROR ("network plugin: setsockopt (reuseaddr): %s",
1834 sstrerror (errno, errbuf, sizeof (errbuf)));
1838 DEBUG ("fd = %i; calling `bind'", fd);
1840 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1844 sstrerror (errno, errbuf, sizeof (errbuf)));
1848 if (ai->ai_family == AF_INET)
1850 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1851 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1853 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1854 struct ip_mreqn mreq;
1856 struct ip_mreq mreq;
1859 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1861 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1862 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1863 /* Set the interface using the interface index if
1864 * possible (available). Unfortunately, the struct
1865 * ip_mreqn is not portable. */
1866 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1867 mreq.imr_ifindex = interface_idx;
1869 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1872 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1873 &loop, sizeof (loop)) == -1)
1876 ERROR ("network plugin: setsockopt (multicast-loop): %s",
1877 sstrerror (errno, errbuf,
1882 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1883 &mreq, sizeof (mreq)) == -1)
1886 ERROR ("network plugin: setsockopt (add-membership): %s",
1887 sstrerror (errno, errbuf,
1895 else if (ai->ai_family == AF_INET6)
1897 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1898 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1899 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1901 struct ipv6_mreq mreq;
1903 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1905 memcpy (&mreq.ipv6mr_multiaddr,
1907 sizeof (addr->sin6_addr));
1909 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1910 * ipv6mr_interface may be set to zeroes to
1911 * choose the default multicast interface or to
1912 * the index of a particular multicast-capable
1913 * interface if the host is multihomed.
1914 * Membership is associ-associated with a
1915 * single interface; programs running on
1916 * multihomed hosts may need to join the same
1917 * group on more than one interface.*/
1918 mreq.ipv6mr_interface = interface_idx;
1920 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1921 &loop, sizeof (loop)) == -1)
1924 ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
1925 sstrerror (errno, errbuf,
1930 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1931 &mreq, sizeof (mreq)) == -1)
1934 ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
1935 sstrerror (errno, errbuf,
1944 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1945 /* if a specific interface was set, bind the socket to it. But to avoid
1946 * possible problems with multicast routing, only do that for non-multicast
1948 if (interface_idx != 0)
1950 char interface_name[IFNAMSIZ];
1952 if (if_indextoname (interface_idx, interface_name) == NULL)
1955 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1957 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1959 sizeof(interface_name)) == -1 )
1962 ERROR ("network plugin: setsockopt (bind-if): %s",
1963 sstrerror (errno, errbuf, sizeof (errbuf)));
1967 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1970 } /* int network_bind_socket */
1972 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1973 * or `SOCKENT_TYPE_SERVER' */
1974 static int sockent_init (sockent_t *se, int type) /* {{{ */
1979 memset (se, 0, sizeof (*se));
1981 se->type = SOCKENT_TYPE_CLIENT;
1987 if (type == SOCKENT_TYPE_SERVER)
1989 se->type = SOCKENT_TYPE_SERVER;
1990 se->data.server.fd = NULL;
1992 se->data.server.security_level = SECURITY_LEVEL_NONE;
1993 se->data.server.auth_file = NULL;
1994 se->data.server.userdb = NULL;
1995 se->data.server.cypher = NULL;
2000 se->data.client.fd = -1;
2001 se->data.client.addr = NULL;
2003 se->data.client.security_level = SECURITY_LEVEL_NONE;
2004 se->data.client.username = NULL;
2005 se->data.client.password = NULL;
2006 se->data.client.cypher = NULL;
2011 } /* }}} int sockent_init */
2013 /* Open the file descriptors for a initialized sockent structure. */
2014 static int sockent_open (sockent_t *se) /* {{{ */
2016 struct addrinfo ai_hints;
2017 struct addrinfo *ai_list, *ai_ptr;
2021 const char *service;
2026 /* Set up the security structures. */
2027 #if HAVE_LIBGCRYPT /* {{{ */
2028 if (se->type == SOCKENT_TYPE_CLIENT)
2030 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
2032 if ((se->data.client.username == NULL)
2033 || (se->data.client.password == NULL))
2035 ERROR ("network plugin: Client socket with "
2036 "security requested, but no "
2037 "credentials are configured.");
2040 gcry_md_hash_buffer (GCRY_MD_SHA256,
2041 se->data.client.password_hash,
2042 se->data.client.password,
2043 strlen (se->data.client.password));
2046 else /* (se->type == SOCKENT_TYPE_SERVER) */
2048 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2050 if (se->data.server.auth_file == NULL)
2052 ERROR ("network plugin: Server socket with "
2053 "security requested, but no "
2054 "password file is configured.");
2058 if (se->data.server.auth_file != NULL)
2060 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2061 if (se->data.server.userdb == NULL)
2063 ERROR ("network plugin: Reading password file "
2065 se->data.server.auth_file);
2066 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2071 #endif /* }}} HAVE_LIBGCRYPT */
2074 service = se->service;
2076 if (service == NULL)
2077 service = NET_DEFAULT_PORT;
2079 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
2082 memset (&ai_hints, 0, sizeof (ai_hints));
2083 ai_hints.ai_flags = 0;
2085 ai_hints.ai_flags |= AI_PASSIVE;
2087 #ifdef AI_ADDRCONFIG
2088 ai_hints.ai_flags |= AI_ADDRCONFIG;
2090 ai_hints.ai_family = AF_UNSPEC;
2091 ai_hints.ai_socktype = SOCK_DGRAM;
2092 ai_hints.ai_protocol = IPPROTO_UDP;
2094 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2097 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2098 (se->node == NULL) ? "(null)" : se->node,
2099 (se->service == NULL) ? "(null)" : se->service,
2100 gai_strerror (ai_return));
2104 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2108 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2112 tmp = realloc (se->data.server.fd,
2113 sizeof (*tmp) * (se->data.server.fd_num + 1));
2116 ERROR ("network plugin: realloc failed.");
2119 se->data.server.fd = tmp;
2120 tmp = se->data.server.fd + se->data.server.fd_num;
2122 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2123 ai_ptr->ai_protocol);
2127 ERROR ("network plugin: socket(2) failed: %s",
2128 sstrerror (errno, errbuf,
2133 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2141 se->data.server.fd_num++;
2143 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2144 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2146 se->data.client.fd = socket (ai_ptr->ai_family,
2147 ai_ptr->ai_socktype,
2148 ai_ptr->ai_protocol);
2149 if (se->data.client.fd < 0)
2152 ERROR ("network plugin: socket(2) failed: %s",
2153 sstrerror (errno, errbuf,
2158 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2159 if (se->data.client.addr == NULL)
2161 ERROR ("network plugin: malloc failed.");
2162 close (se->data.client.fd);
2163 se->data.client.fd = -1;
2167 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2168 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2169 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2170 se->data.client.addrlen = ai_ptr->ai_addrlen;
2172 network_set_ttl (se, ai_ptr);
2173 network_set_interface (se, ai_ptr);
2175 /* We don't open more than one write-socket per
2176 * node/service pair.. */
2178 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2179 } /* for (ai_list) */
2181 freeaddrinfo (ai_list);
2183 /* Check if all went well. */
2184 if (se->type == SOCKENT_TYPE_SERVER)
2186 if (se->data.server.fd_num <= 0)
2189 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2191 if (se->data.client.fd < 0)
2196 } /* }}} int sockent_open */
2198 /* Add a sockent to the global list of sockets */
2199 static int sockent_add (sockent_t *se) /* {{{ */
2201 sockent_t *last_ptr;
2206 if (se->type == SOCKENT_TYPE_SERVER)
2211 tmp = realloc (listen_sockets_pollfd,
2212 sizeof (*tmp) * (listen_sockets_num
2213 + se->data.server.fd_num));
2216 ERROR ("network plugin: realloc failed.");
2219 listen_sockets_pollfd = tmp;
2220 tmp = listen_sockets_pollfd + listen_sockets_num;
2222 for (i = 0; i < se->data.server.fd_num; i++)
2224 memset (tmp + i, 0, sizeof (*tmp));
2225 tmp[i].fd = se->data.server.fd[i];
2226 tmp[i].events = POLLIN | POLLPRI;
2230 listen_sockets_num += se->data.server.fd_num;
2232 if (listen_sockets == NULL)
2234 listen_sockets = se;
2237 last_ptr = listen_sockets;
2239 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2241 if (sending_sockets == NULL)
2243 sending_sockets = se;
2246 last_ptr = sending_sockets;
2249 while (last_ptr->next != NULL)
2250 last_ptr = last_ptr->next;
2251 last_ptr->next = se;
2254 } /* }}} int sockent_add */
2256 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2260 receive_list_entry_t *ent;
2263 /* Lock and wait for more data to come in */
2264 pthread_mutex_lock (&receive_list_lock);
2265 while ((listen_loop == 0)
2266 && (receive_list_head == NULL))
2267 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2269 /* Remove the head entry and unlock */
2270 ent = receive_list_head;
2272 receive_list_head = ent->next;
2273 receive_list_length--;
2274 pthread_mutex_unlock (&receive_list_lock);
2276 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2277 * because we dispatch all missing packets before shutting down. */
2281 /* Look for the correct `sockent_t' */
2282 se = listen_sockets;
2287 for (i = 0; i < se->data.server.fd_num; i++)
2288 if (se->data.server.fd[i] == ent->fd)
2291 if (i < se->data.server.fd_num)
2299 ERROR ("network plugin: Got packet from FD %i, but can't "
2300 "find an appropriate socket entry.",
2307 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2308 /* username = */ NULL);
2314 } /* }}} void *dispatch_thread */
2316 static int network_receive (void) /* {{{ */
2318 char buffer[network_config_packet_size];
2324 receive_list_entry_t *private_list_head;
2325 receive_list_entry_t *private_list_tail;
2326 uint64_t private_list_length;
2328 assert (listen_sockets_num > 0);
2330 private_list_head = NULL;
2331 private_list_tail = NULL;
2332 private_list_length = 0;
2334 while (listen_loop == 0)
2336 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2343 ERROR ("poll failed: %s",
2344 sstrerror (errno, errbuf, sizeof (errbuf)));
2348 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2350 receive_list_entry_t *ent;
2352 if ((listen_sockets_pollfd[i].revents
2353 & (POLLIN | POLLPRI)) == 0)
2357 buffer_len = recv (listen_sockets_pollfd[i].fd,
2358 buffer, sizeof (buffer),
2363 ERROR ("recv failed: %s",
2364 sstrerror (errno, errbuf,
2369 stats_octets_rx += ((uint64_t) buffer_len);
2372 /* TODO: Possible performance enhancement: Do not free
2373 * these entries in the dispatch thread but put them in
2374 * another list, so we don't have to allocate more and
2375 * more of these structures. */
2376 ent = malloc (sizeof (receive_list_entry_t));
2379 ERROR ("network plugin: malloc failed.");
2382 memset (ent, 0, sizeof (receive_list_entry_t));
2383 ent->data = malloc (network_config_packet_size);
2384 if (ent->data == NULL)
2387 ERROR ("network plugin: malloc failed.");
2390 ent->fd = listen_sockets_pollfd[i].fd;
2393 memcpy (ent->data, buffer, buffer_len);
2394 ent->data_len = buffer_len;
2396 if (private_list_head == NULL)
2397 private_list_head = ent;
2399 private_list_tail->next = ent;
2400 private_list_tail = ent;
2401 private_list_length++;
2403 /* Do not block here. Blocking here has led to
2404 * insufficient performance in the past. */
2405 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2407 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2408 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2410 if (receive_list_head == NULL)
2411 receive_list_head = private_list_head;
2413 receive_list_tail->next = private_list_head;
2414 receive_list_tail = private_list_tail;
2415 receive_list_length += private_list_length;
2417 pthread_cond_signal (&receive_list_cond);
2418 pthread_mutex_unlock (&receive_list_lock);
2420 private_list_head = NULL;
2421 private_list_tail = NULL;
2422 private_list_length = 0;
2424 } /* for (listen_sockets_pollfd) */
2425 } /* while (listen_loop == 0) */
2427 /* Make sure everything is dispatched before exiting. */
2428 if (private_list_head != NULL)
2430 pthread_mutex_lock (&receive_list_lock);
2432 if (receive_list_head == NULL)
2433 receive_list_head = private_list_head;
2435 receive_list_tail->next = private_list_head;
2436 receive_list_tail = private_list_tail;
2437 receive_list_length += private_list_length;
2439 private_list_head = NULL;
2440 private_list_tail = NULL;
2441 private_list_length = 0;
2443 pthread_cond_signal (&receive_list_cond);
2444 pthread_mutex_unlock (&receive_list_lock);
2448 } /* }}} int network_receive */
2450 static void *receive_thread (void __attribute__((unused)) *arg)
2452 return (network_receive () ? (void *) 1 : (void *) 0);
2453 } /* void *receive_thread */
2455 static void network_init_buffer (void)
2457 memset (send_buffer, 0, network_config_packet_size);
2458 send_buffer_ptr = send_buffer;
2459 send_buffer_fill = 0;
2461 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2462 } /* int network_init_buffer */
2464 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2465 const char *buffer, size_t buffer_size)
2471 status = sendto (se->data.client.fd, buffer, buffer_size,
2473 (struct sockaddr *) se->data.client.addr,
2474 se->data.client.addrlen);
2480 ERROR ("network plugin: sendto failed: %s",
2481 sstrerror (errno, errbuf,
2488 } /* }}} void networt_send_buffer_plain */
2491 #define BUFFER_ADD(p,s) do { \
2492 memcpy (buffer + buffer_offset, (p), (s)); \
2493 buffer_offset += (s); \
2496 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2497 const char *in_buffer, size_t in_buffer_size)
2499 part_signature_sha256_t ps;
2500 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2501 size_t buffer_offset;
2502 size_t username_len;
2506 unsigned char *hash;
2509 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2512 ERROR ("network plugin: Creating HMAC object failed: %s",
2513 gcry_strerror (err));
2517 err = gcry_md_setkey (hd, se->data.client.password,
2518 strlen (se->data.client.password));
2521 ERROR ("network plugin: gcry_md_setkey failed: %s",
2522 gcry_strerror (err));
2527 username_len = strlen (se->data.client.username);
2528 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2530 ERROR ("network plugin: Username too long: %s",
2531 se->data.client.username);
2535 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2536 se->data.client.username, username_len);
2537 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2538 in_buffer, in_buffer_size);
2540 /* Initialize the `ps' structure. */
2541 memset (&ps, 0, sizeof (ps));
2542 ps.head.type = htons (TYPE_SIGN_SHA256);
2543 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2545 /* Calculate the hash value. */
2546 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2547 username_len + in_buffer_size);
2548 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2551 ERROR ("network plugin: gcry_md_read failed.");
2555 memcpy (ps.hash, hash, sizeof (ps.hash));
2557 /* Add the header */
2560 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2561 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2562 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2564 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2569 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2570 networt_send_buffer_plain (se, buffer, buffer_offset);
2571 } /* }}} void networt_send_buffer_signed */
2573 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2574 const char *in_buffer, size_t in_buffer_size)
2576 part_encryption_aes256_t pea;
2577 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2579 size_t buffer_offset;
2581 size_t username_len;
2583 gcry_cipher_hd_t cypher;
2585 /* Initialize the header fields */
2586 memset (&pea, 0, sizeof (pea));
2587 pea.head.type = htons (TYPE_ENCR_AES256);
2589 pea.username = se->data.client.username;
2591 username_len = strlen (pea.username);
2592 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2594 ERROR ("network plugin: Username too long: %s", pea.username);
2598 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2599 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2600 - sizeof (pea.hash);
2602 assert (buffer_size <= sizeof (buffer));
2603 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2604 "buffer_size = %zu;", buffer_size);
2606 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2607 + username_len + in_buffer_size));
2608 pea.username_length = htons ((uint16_t) username_len);
2610 /* Chose a random initialization vector. */
2611 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2613 /* Create hash of the payload */
2614 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2616 /* Initialize the buffer */
2618 memset (buffer, 0, sizeof (buffer));
2621 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2622 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2623 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2624 BUFFER_ADD (pea.username, username_len);
2625 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2626 assert (buffer_offset == header_size);
2627 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2628 BUFFER_ADD (in_buffer, in_buffer_size);
2630 assert (buffer_offset == buffer_size);
2632 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2633 se->data.client.password);
2637 /* Encrypt the buffer in-place */
2638 err = gcry_cipher_encrypt (cypher,
2639 buffer + header_size,
2640 buffer_size - header_size,
2641 /* in = */ NULL, /* in len = */ 0);
2644 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2645 gcry_strerror (err));
2649 /* Send it out without further modifications */
2650 networt_send_buffer_plain (se, buffer, buffer_size);
2651 } /* }}} void networt_send_buffer_encrypted */
2653 #endif /* HAVE_LIBGCRYPT */
2655 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2659 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2661 for (se = sending_sockets; se != NULL; se = se->next)
2664 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2665 networt_send_buffer_encrypted (se, buffer, buffer_len);
2666 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2667 networt_send_buffer_signed (se, buffer, buffer_len);
2668 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2669 #endif /* HAVE_LIBGCRYPT */
2670 networt_send_buffer_plain (se, buffer, buffer_len);
2671 } /* for (sending_sockets) */
2672 } /* }}} void network_send_buffer */
2674 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2675 value_list_t *vl_def,
2676 const data_set_t *ds, const value_list_t *vl)
2678 char *buffer_orig = buffer;
2680 if (strcmp (vl_def->host, vl->host) != 0)
2682 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2683 vl->host, strlen (vl->host)) != 0)
2685 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2688 if (vl_def->time != vl->time)
2690 if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
2691 (uint64_t) vl->time))
2693 vl_def->time = vl->time;
2696 if (vl_def->interval != vl->interval)
2698 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
2699 (uint64_t) vl->interval))
2701 vl_def->interval = vl->interval;
2704 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2706 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2707 vl->plugin, strlen (vl->plugin)) != 0)
2709 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2712 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2714 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2715 vl->plugin_instance,
2716 strlen (vl->plugin_instance)) != 0)
2718 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2721 if (strcmp (vl_def->type, vl->type) != 0)
2723 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2724 vl->type, strlen (vl->type)) != 0)
2726 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2729 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2731 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2733 strlen (vl->type_instance)) != 0)
2735 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2738 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2741 return (buffer - buffer_orig);
2742 } /* }}} int add_to_buffer */
2744 static void flush_buffer (void)
2746 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2749 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2751 stats_octets_tx += ((uint64_t) send_buffer_fill);
2754 network_init_buffer ();
2757 static int network_write (const data_set_t *ds, const value_list_t *vl,
2758 user_data_t __attribute__((unused)) *user_data)
2762 if (!check_send_okay (vl))
2765 char name[6*DATA_MAX_NAME_LEN];
2766 FORMAT_VL (name, sizeof (name), vl);
2767 name[sizeof (name) - 1] = 0;
2768 DEBUG ("network plugin: network_write: "
2769 "NOT sending %s.", name);
2771 /* Counter is not protected by another lock and may be reached by
2772 * multiple threads */
2773 pthread_mutex_lock (&stats_lock);
2774 stats_values_not_sent++;
2775 pthread_mutex_unlock (&stats_lock);
2779 uc_meta_data_add_unsigned_int (vl,
2780 "network:time_sent", (uint64_t) vl->time);
2782 pthread_mutex_lock (&send_buffer_lock);
2784 status = add_to_buffer (send_buffer_ptr,
2785 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2790 /* status == bytes added to the buffer */
2791 send_buffer_fill += status;
2792 send_buffer_ptr += status;
2794 stats_values_sent++;
2800 status = add_to_buffer (send_buffer_ptr,
2801 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2807 send_buffer_fill += status;
2808 send_buffer_ptr += status;
2810 stats_values_sent++;
2816 ERROR ("network plugin: Unable to append to the "
2817 "buffer for some weird reason");
2819 else if ((network_config_packet_size - send_buffer_fill) < 15)
2824 pthread_mutex_unlock (&send_buffer_lock);
2826 return ((status < 0) ? -1 : 0);
2827 } /* int network_write */
2829 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2832 if ((ci->values_num != 1)
2833 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2834 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2836 ERROR ("network plugin: The `%s' config option needs "
2837 "exactly one boolean argument.", ci->key);
2841 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2843 if (ci->values[0].value.boolean)
2850 char *str = ci->values[0].value.string;
2854 else if (IS_FALSE (str))
2858 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2859 "option as boolean value.",
2866 } /* }}} int network_config_set_boolean */
2868 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2871 if ((ci->values_num != 1)
2872 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2874 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2875 "one numeric argument.");
2879 tmp = (int) ci->values[0].value.number;
2880 if ((tmp > 0) && (tmp <= 255))
2881 network_config_ttl = tmp;
2884 } /* }}} int network_config_set_ttl */
2886 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2889 if ((ci->values_num != 1)
2890 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2892 WARNING ("network plugin: The `Interface' config option needs exactly "
2893 "one string argument.");
2897 if (interface == NULL)
2900 *interface = if_nametoindex (ci->values[0].value.string);
2903 } /* }}} int network_config_set_interface */
2905 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2908 if ((ci->values_num != 1)
2909 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2911 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2912 "one numeric argument.");
2916 tmp = (int) ci->values[0].value.number;
2917 if ((tmp >= 1024) && (tmp <= 65535))
2918 network_config_packet_size = tmp;
2921 } /* }}} int network_config_set_buffer_size */
2924 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2928 if ((ci->values_num != 1)
2929 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2931 WARNING ("network plugin: The `%s' config option needs exactly "
2932 "one string argument.", ci->key);
2936 tmp = strdup (ci->values[0].value.string);
2940 sfree (*ret_string);
2944 } /* }}} int network_config_set_string */
2945 #endif /* HAVE_LIBGCRYPT */
2948 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2952 if ((ci->values_num != 1)
2953 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2955 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2956 "one string argument.");
2960 str = ci->values[0].value.string;
2961 if (strcasecmp ("Encrypt", str) == 0)
2962 *retval = SECURITY_LEVEL_ENCRYPT;
2963 else if (strcasecmp ("Sign", str) == 0)
2964 *retval = SECURITY_LEVEL_SIGN;
2965 else if (strcasecmp ("None", str) == 0)
2966 *retval = SECURITY_LEVEL_NONE;
2969 WARNING ("network plugin: Unknown security level: %s.", str);
2974 } /* }}} int network_config_set_security_level */
2975 #endif /* HAVE_LIBGCRYPT */
2977 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2983 if ((ci->values_num < 1) || (ci->values_num > 2)
2984 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2985 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2987 ERROR ("network plugin: The `%s' config option needs "
2988 "one or two string arguments.", ci->key);
2992 se = malloc (sizeof (*se));
2995 ERROR ("network plugin: malloc failed.");
2998 sockent_init (se, SOCKENT_TYPE_SERVER);
3000 se->node = strdup (ci->values[0].value.string);
3001 if (ci->values_num >= 2)
3002 se->service = strdup (ci->values[1].value.string);
3004 for (i = 0; i < ci->children_num; i++)
3006 oconfig_item_t *child = ci->children + i;
3009 if (strcasecmp ("AuthFile", child->key) == 0)
3010 network_config_set_string (child, &se->data.server.auth_file);
3011 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3012 network_config_set_security_level (child,
3013 &se->data.server.security_level);
3015 #endif /* HAVE_LIBGCRYPT */
3016 if (strcasecmp ("Interface", child->key) == 0)
3017 network_config_set_interface (child,
3021 WARNING ("network plugin: Option `%s' is not allowed here.",
3027 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3028 && (se->data.server.auth_file == NULL))
3030 ERROR ("network plugin: A security level higher than `none' was "
3031 "requested, but no AuthFile option was given. Cowardly refusing to "
3032 "open this socket!");
3033 sockent_destroy (se);
3036 #endif /* HAVE_LIBGCRYPT */
3038 status = sockent_open (se);
3041 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
3042 sockent_destroy (se);
3046 status = sockent_add (se);
3049 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3050 sockent_destroy (se);
3055 } /* }}} int network_config_add_listen */
3057 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3063 if ((ci->values_num < 1) || (ci->values_num > 2)
3064 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3065 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3067 ERROR ("network plugin: The `%s' config option needs "
3068 "one or two string arguments.", ci->key);
3072 se = malloc (sizeof (*se));
3075 ERROR ("network plugin: malloc failed.");
3078 sockent_init (se, SOCKENT_TYPE_CLIENT);
3080 se->node = strdup (ci->values[0].value.string);
3081 if (ci->values_num >= 2)
3082 se->service = strdup (ci->values[1].value.string);
3084 for (i = 0; i < ci->children_num; i++)
3086 oconfig_item_t *child = ci->children + i;
3089 if (strcasecmp ("Username", child->key) == 0)
3090 network_config_set_string (child, &se->data.client.username);
3091 else if (strcasecmp ("Password", child->key) == 0)
3092 network_config_set_string (child, &se->data.client.password);
3093 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3094 network_config_set_security_level (child,
3095 &se->data.client.security_level);
3097 #endif /* HAVE_LIBGCRYPT */
3098 if (strcasecmp ("Interface", child->key) == 0)
3099 network_config_set_interface (child,
3103 WARNING ("network plugin: Option `%s' is not allowed here.",
3109 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3110 && ((se->data.client.username == NULL)
3111 || (se->data.client.password == NULL)))
3113 ERROR ("network plugin: A security level higher than `none' was "
3114 "requested, but no Username or Password option was given. "
3115 "Cowardly refusing to open this socket!");
3116 sockent_destroy (se);
3119 #endif /* HAVE_LIBGCRYPT */
3121 status = sockent_open (se);
3124 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3125 sockent_destroy (se);
3129 status = sockent_add (se);
3132 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3133 sockent_destroy (se);
3138 } /* }}} int network_config_add_server */
3140 static int network_config (oconfig_item_t *ci) /* {{{ */
3144 for (i = 0; i < ci->children_num; i++)
3146 oconfig_item_t *child = ci->children + i;
3148 if (strcasecmp ("Listen", child->key) == 0)
3149 network_config_add_listen (child);
3150 else if (strcasecmp ("Server", child->key) == 0)
3151 network_config_add_server (child);
3152 else if (strcasecmp ("TimeToLive", child->key) == 0)
3153 network_config_set_ttl (child);
3154 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3155 network_config_set_buffer_size (child);
3156 else if (strcasecmp ("Forward", child->key) == 0)
3157 network_config_set_boolean (child, &network_config_forward);
3158 else if (strcasecmp ("ReportStats", child->key) == 0)
3159 network_config_set_boolean (child, &network_config_stats);
3162 WARNING ("network plugin: Option `%s' is not allowed here.",
3168 } /* }}} int network_config */
3170 static int network_notification (const notification_t *n,
3171 user_data_t __attribute__((unused)) *user_data)
3173 char buffer[network_config_packet_size];
3174 char *buffer_ptr = buffer;
3175 int buffer_free = sizeof (buffer);
3178 if (!check_send_notify_okay (n))
3181 memset (buffer, 0, sizeof (buffer));
3183 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3184 (uint64_t) n->time);
3188 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3189 (uint64_t) n->severity);
3193 if (strlen (n->host) > 0)
3195 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3196 n->host, strlen (n->host));
3201 if (strlen (n->plugin) > 0)
3203 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3204 n->plugin, strlen (n->plugin));
3209 if (strlen (n->plugin_instance) > 0)
3211 status = write_part_string (&buffer_ptr, &buffer_free,
3212 TYPE_PLUGIN_INSTANCE,
3213 n->plugin_instance, strlen (n->plugin_instance));
3218 if (strlen (n->type) > 0)
3220 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3221 n->type, strlen (n->type));
3226 if (strlen (n->type_instance) > 0)
3228 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3229 n->type_instance, strlen (n->type_instance));
3234 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3235 n->message, strlen (n->message));
3239 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3242 } /* int network_notification */
3244 static int network_shutdown (void)
3248 /* Kill the listening thread */
3249 if (receive_thread_running != 0)
3251 INFO ("network plugin: Stopping receive thread.");
3252 pthread_kill (receive_thread_id, SIGTERM);
3253 pthread_join (receive_thread_id, NULL /* no return value */);
3254 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3255 receive_thread_running = 0;
3258 /* Shutdown the dispatching thread */
3259 if (dispatch_thread_running != 0)
3261 INFO ("network plugin: Stopping dispatch thread.");
3262 pthread_mutex_lock (&receive_list_lock);
3263 pthread_cond_broadcast (&receive_list_cond);
3264 pthread_mutex_unlock (&receive_list_lock);
3265 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3266 dispatch_thread_running = 0;
3269 sockent_destroy (listen_sockets);
3271 if (send_buffer_fill > 0)
3274 sfree (send_buffer);
3276 /* TODO: Close `sending_sockets' */
3278 plugin_unregister_config ("network");
3279 plugin_unregister_init ("network");
3280 plugin_unregister_write ("network");
3281 plugin_unregister_shutdown ("network");
3284 } /* int network_shutdown */
3286 static int network_stats_read (void) /* {{{ */
3288 derive_t copy_octets_rx;
3289 derive_t copy_octets_tx;
3290 derive_t copy_packets_rx;
3291 derive_t copy_packets_tx;
3292 derive_t copy_values_dispatched;
3293 derive_t copy_values_not_dispatched;
3294 derive_t copy_values_sent;
3295 derive_t copy_values_not_sent;
3296 derive_t copy_receive_list_length;
3297 value_list_t vl = VALUE_LIST_INIT;
3300 copy_octets_rx = stats_octets_rx;
3301 copy_octets_tx = stats_octets_tx;
3302 copy_packets_rx = stats_packets_rx;
3303 copy_packets_tx = stats_packets_tx;
3304 copy_values_dispatched = stats_values_dispatched;
3305 copy_values_not_dispatched = stats_values_not_dispatched;
3306 copy_values_sent = stats_values_sent;
3307 copy_values_not_sent = stats_values_not_sent;
3308 copy_receive_list_length = receive_list_length;
3310 /* Initialize `vl' */
3314 vl.interval = interval_g;
3315 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3316 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3318 /* Octets received / sent */
3319 vl.values[0].derive = (derive_t) copy_octets_rx;
3320 vl.values[1].derive = (derive_t) copy_octets_tx;
3321 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3322 plugin_dispatch_values_secure (&vl);
3324 /* Packets received / send */
3325 vl.values[0].derive = (derive_t) copy_packets_rx;
3326 vl.values[1].derive = (derive_t) copy_packets_tx;
3327 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3328 plugin_dispatch_values_secure (&vl);
3330 /* Values (not) dispatched and (not) send */
3331 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3334 vl.values[0].derive = (derive_t) copy_values_dispatched;
3335 sstrncpy (vl.type_instance, "dispatch-accepted",
3336 sizeof (vl.type_instance));
3337 plugin_dispatch_values_secure (&vl);
3339 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3340 sstrncpy (vl.type_instance, "dispatch-rejected",
3341 sizeof (vl.type_instance));
3342 plugin_dispatch_values_secure (&vl);
3344 vl.values[0].derive = (derive_t) copy_values_sent;
3345 sstrncpy (vl.type_instance, "send-accepted",
3346 sizeof (vl.type_instance));
3347 plugin_dispatch_values_secure (&vl);
3349 vl.values[0].derive = (derive_t) copy_values_not_sent;
3350 sstrncpy (vl.type_instance, "send-rejected",
3351 sizeof (vl.type_instance));
3352 plugin_dispatch_values_secure (&vl);
3354 /* Receive queue length */
3355 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3356 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3357 vl.type_instance[0] = 0;
3358 plugin_dispatch_values_secure (&vl);
3361 } /* }}} int network_stats_read */
3363 static int network_init (void)
3365 static _Bool have_init = 0;
3367 /* Check if we were already initialized. If so, just return - there's
3368 * nothing more to do (for now, that is). */
3374 /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
3375 * Because you can't know in a library whether another library has
3376 * already initialized the library
3378 if (!gcry_control (GCRYCTL_ANY_INITIALIZATION_P))
3380 gcry_check_version(NULL); /* before calling any other functions */
3381 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3382 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3383 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3387 if (network_config_stats != 0)
3388 plugin_register_read ("network", network_stats_read);
3390 plugin_register_shutdown ("network", network_shutdown);
3392 send_buffer = malloc (network_config_packet_size);
3393 if (send_buffer == NULL)
3395 ERROR ("network plugin: malloc failed.");
3398 network_init_buffer ();
3400 /* setup socket(s) and so on */
3401 if (sending_sockets != NULL)
3403 plugin_register_write ("network", network_write,
3404 /* user_data = */ NULL);
3405 plugin_register_notification ("network", network_notification,
3406 /* user_data = */ NULL);
3409 /* If no threads need to be started, return here. */
3410 if ((listen_sockets_num == 0)
3411 || ((dispatch_thread_running != 0)
3412 && (receive_thread_running != 0)))
3415 if (dispatch_thread_running == 0)
3418 status = pthread_create (&dispatch_thread_id,
3419 NULL /* no attributes */,
3421 NULL /* no argument */);
3425 ERROR ("network: pthread_create failed: %s",
3426 sstrerror (errno, errbuf,
3431 dispatch_thread_running = 1;
3435 if (receive_thread_running == 0)
3438 status = pthread_create (&receive_thread_id,
3439 NULL /* no attributes */,
3441 NULL /* no argument */);
3445 ERROR ("network: pthread_create failed: %s",
3446 sstrerror (errno, errbuf,
3451 receive_thread_running = 1;
3456 } /* int network_init */
3459 * The flush option of the network plugin cannot flush individual identifiers.
3460 * All the values are added to a buffer and sent when the buffer is full, the
3461 * requested value may or may not be in there, it's not worth finding out. We
3462 * just send the buffer if `flush' is called - if the requested value was in
3463 * there, good. If not, well, then there is nothing to flush.. -octo
3465 static int network_flush (__attribute__((unused)) cdtime_t timeout,
3466 __attribute__((unused)) const char *identifier,
3467 __attribute__((unused)) user_data_t *user_data)
3469 pthread_mutex_lock (&send_buffer_lock);
3471 if (send_buffer_fill > 0)
3474 pthread_mutex_unlock (&send_buffer_lock);
3477 } /* int network_flush */
3479 void module_register (void)
3481 plugin_register_complex_config ("network", network_config);
3482 plugin_register_init ("network", network_init);
3483 plugin_register_flush ("network", network_flush,
3484 /* user_data = */ NULL);
3485 } /* void module_register */
3487 /* vim: set fdm=marker : */