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"
70 # if defined __APPLE__
71 /* Re enable deprecation warnings */
72 # pragma GCC diagnostic warning "-Wdeprecated-declarations"
74 GCRY_THREAD_OPTION_PTHREAD_IMPL;
77 #ifndef IPV6_ADD_MEMBERSHIP
78 # ifdef IPV6_JOIN_GROUP
79 # define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
81 # error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
83 #endif /* !IP_ADD_MEMBERSHIP */
86 * Maximum size required for encryption / signing:
88 * 42 bytes for the encryption header
89 * + 64 bytes for the username
93 #define BUFF_SIG_SIZE 106
98 #define SECURITY_LEVEL_NONE 0
100 # define SECURITY_LEVEL_SIGN 1
101 # define SECURITY_LEVEL_ENCRYPT 2
103 struct sockent_client
106 struct sockaddr_storage *addr;
112 gcry_cipher_hd_t cypher;
113 unsigned char password_hash[32];
117 struct sockent_server
125 gcry_cipher_hd_t cypher;
129 typedef struct sockent
131 #define SOCKENT_TYPE_CLIENT 1
132 #define SOCKENT_TYPE_SERVER 2
141 struct sockent_client client;
142 struct sockent_server server;
145 struct sockent *next;
148 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
149 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
150 * +-------+-----------------------+-------------------------------+
151 * ! Ver. ! ! Length !
152 * +-------+-----------------------+-------------------------------+
159 typedef struct part_header_s part_header_t;
161 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
162 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
163 * +-------------------------------+-------------------------------+
165 * +-------------------------------+-------------------------------+
166 * : (Length - 4) Bytes :
167 * +---------------------------------------------------------------+
174 typedef struct part_string_s part_string_t;
176 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
177 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
178 * +-------------------------------+-------------------------------+
180 * +-------------------------------+-------------------------------+
181 * : (Length - 4 == 2 || 4 || 8) Bytes :
182 * +---------------------------------------------------------------+
189 typedef struct part_number_s part_number_t;
191 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
192 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
193 * +-------------------------------+-------------------------------+
195 * +-------------------------------+---------------+---------------+
196 * ! Num of values ! Type0 ! Type1 !
197 * +-------------------------------+---------------+---------------+
200 * +---------------------------------------------------------------+
203 * +---------------------------------------------------------------+
208 uint16_t *num_values;
209 uint8_t *values_types;
212 typedef struct part_values_s part_values_t;
214 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
215 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
216 * +-------------------------------+-------------------------------+
218 * +-------------------------------+-------------------------------+
219 * ! Hash (Bits 0 - 31) !
221 * ! Hash (Bits 224 - 255) !
222 * +---------------------------------------------------------------+
225 #define PART_SIGNATURE_SHA256_SIZE 36
226 struct part_signature_sha256_s
229 unsigned char hash[32];
232 typedef struct part_signature_sha256_s part_signature_sha256_t;
234 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
235 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
236 * +-------------------------------+-------------------------------+
238 * +-------------------------------+-------------------------------+
239 * ! Original length ! Padding (0 - 15 bytes) !
240 * +-------------------------------+-------------------------------+
241 * ! Hash (Bits 0 - 31) !
243 * ! Hash (Bits 128 - 159) !
244 * +---------------------------------------------------------------+
247 #define PART_ENCRYPTION_AES256_SIZE 42
248 struct part_encryption_aes256_s
251 uint16_t username_length;
253 unsigned char iv[16];
255 unsigned char hash[20];
259 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
261 struct receive_list_entry_s
266 struct receive_list_entry_s *next;
268 typedef struct receive_list_entry_s receive_list_entry_t;
273 static int network_config_ttl = 0;
274 /* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
275 static size_t network_config_packet_size = 1452;
276 static int network_config_forward = 0;
277 static int network_config_stats = 0;
279 static sockent_t *sending_sockets = NULL;
281 static receive_list_entry_t *receive_list_head = NULL;
282 static receive_list_entry_t *receive_list_tail = NULL;
283 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
284 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
285 static uint64_t receive_list_length = 0;
287 static sockent_t *listen_sockets = NULL;
288 static struct pollfd *listen_sockets_pollfd = NULL;
289 static size_t listen_sockets_num = 0;
291 /* The receive and dispatch threads will run as long as `listen_loop' is set to
293 static int listen_loop = 0;
294 static int receive_thread_running = 0;
295 static pthread_t receive_thread_id;
296 static int dispatch_thread_running = 0;
297 static pthread_t dispatch_thread_id;
299 /* Buffer in which to-be-sent network packets are constructed. */
300 static char *send_buffer;
301 static char *send_buffer_ptr;
302 static int send_buffer_fill;
303 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
304 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
306 /* XXX: These counters are incremented from one place only. The spot in which
307 * the values are incremented is either only reachable by one thread (the
308 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
309 * example). Only if neither is true, the stats_lock is acquired. The counters
310 * are always read without holding a lock in the hope that writing 8 bytes to
311 * memory is an atomic operation. */
312 static derive_t stats_octets_rx = 0;
313 static derive_t stats_octets_tx = 0;
314 static derive_t stats_packets_rx = 0;
315 static derive_t stats_packets_tx = 0;
316 static derive_t stats_values_dispatched = 0;
317 static derive_t stats_values_not_dispatched = 0;
318 static derive_t stats_values_sent = 0;
319 static derive_t stats_values_not_sent = 0;
320 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
325 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
327 uint64_t time_sent = 0;
330 status = uc_meta_data_get_unsigned_int (vl,
331 "network:time_sent", &time_sent);
333 /* This is a value we already sent. Don't allow it to be received again in
334 * order to avoid looping. */
335 if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
339 } /* }}} _Bool check_receive_okay */
341 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
346 if (network_config_forward != 0)
349 if (vl->meta == NULL)
352 status = meta_data_get_boolean (vl->meta, "network:received", &received);
353 if (status == -ENOENT)
355 else if (status != 0)
357 ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
358 "with status %i.", status);
362 /* By default, only *send* value lists that were not *received* by the
365 } /* }}} _Bool check_send_okay */
367 static _Bool check_notify_received (const notification_t *n) /* {{{ */
369 notification_meta_t *ptr;
371 for (ptr = n->meta; ptr != NULL; ptr = ptr->next)
372 if ((strcmp ("network:received", ptr->name) == 0)
373 && (ptr->type == NM_TYPE_BOOLEAN))
374 return ((_Bool) ptr->nm_value.nm_boolean);
377 } /* }}} _Bool check_notify_received */
379 static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
381 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
387 received = check_notify_received (n);
389 if (network_config_forward && received)
391 c_complain_once (LOG_ERR, &complain_forwarding,
392 "network plugin: A notification has been received via the network "
393 "forwarding if enabled. Forwarding of notifications is currently "
394 "not supported, because there is not loop-deteciton available. "
395 "Please contact the collectd mailing list if you need this "
399 /* By default, only *send* value lists that were not *received* by the
402 } /* }}} _Bool check_send_notify_okay */
404 static int network_dispatch_values (value_list_t *vl, /* {{{ */
405 const char *username)
410 || (strlen (vl->host) <= 0)
411 || (strlen (vl->plugin) <= 0)
412 || (strlen (vl->type) <= 0))
415 if (!check_receive_okay (vl))
418 char name[6*DATA_MAX_NAME_LEN];
419 FORMAT_VL (name, sizeof (name), vl);
420 name[sizeof (name) - 1] = 0;
421 DEBUG ("network plugin: network_dispatch_values: "
422 "NOT dispatching %s.", name);
424 stats_values_not_dispatched++;
428 assert (vl->meta == NULL);
430 vl->meta = meta_data_create ();
431 if (vl->meta == NULL)
433 ERROR ("network plugin: meta_data_create failed.");
437 status = meta_data_add_boolean (vl->meta, "network:received", 1);
440 ERROR ("network plugin: meta_data_add_boolean failed.");
441 meta_data_destroy (vl->meta);
446 if (username != NULL)
448 status = meta_data_add_string (vl->meta, "network:username", username);
451 ERROR ("network plugin: meta_data_add_string failed.");
452 meta_data_destroy (vl->meta);
458 plugin_dispatch_values_secure (vl);
459 stats_values_dispatched++;
461 meta_data_destroy (vl->meta);
465 } /* }}} int network_dispatch_values */
467 static int network_dispatch_notification (notification_t *n) /* {{{ */
471 assert (n->meta == NULL);
473 status = plugin_notification_meta_add_boolean (n, "network:received", 1);
476 ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
477 plugin_notification_meta_free (n->meta);
482 status = plugin_dispatch_notification (n);
484 plugin_notification_meta_free (n->meta);
488 } /* }}} int network_dispatch_notification */
491 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
492 const void *iv, size_t iv_size, const char *username)
495 gcry_cipher_hd_t *cyper_ptr;
496 unsigned char password_hash[32];
498 if (se->type == SOCKENT_TYPE_CLIENT)
500 cyper_ptr = &se->data.client.cypher;
501 memcpy (password_hash, se->data.client.password_hash,
502 sizeof (password_hash));
508 cyper_ptr = &se->data.server.cypher;
510 if (username == NULL)
513 secret = fbh_get (se->data.server.userdb, username);
517 gcry_md_hash_buffer (GCRY_MD_SHA256,
519 secret, strlen (secret));
524 if (*cyper_ptr == NULL)
526 err = gcry_cipher_open (cyper_ptr,
527 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
530 ERROR ("network plugin: gcry_cipher_open returned: %s",
531 gcry_strerror (err));
538 gcry_cipher_reset (*cyper_ptr);
540 assert (*cyper_ptr != NULL);
542 err = gcry_cipher_setkey (*cyper_ptr,
543 password_hash, sizeof (password_hash));
546 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
547 gcry_strerror (err));
548 gcry_cipher_close (*cyper_ptr);
553 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
556 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
557 gcry_strerror (err));
558 gcry_cipher_close (*cyper_ptr);
564 } /* }}} int network_get_aes256_cypher */
565 #endif /* HAVE_LIBGCRYPT */
567 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
568 const data_set_t *ds, const value_list_t *vl)
574 part_header_t pkg_ph;
575 uint16_t pkg_num_values;
576 uint8_t *pkg_values_types;
582 num_values = vl->values_len;
583 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
584 + (num_values * sizeof (uint8_t))
585 + (num_values * sizeof (value_t));
587 if (*ret_buffer_len < packet_len)
590 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
591 if (pkg_values_types == NULL)
593 ERROR ("network plugin: write_part_values: malloc failed.");
597 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
598 if (pkg_values == NULL)
600 free (pkg_values_types);
601 ERROR ("network plugin: write_part_values: malloc failed.");
605 pkg_ph.type = htons (TYPE_VALUES);
606 pkg_ph.length = htons (packet_len);
608 pkg_num_values = htons ((uint16_t) vl->values_len);
610 for (i = 0; i < num_values; i++)
612 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
613 switch (ds->ds[i].type)
615 case DS_TYPE_COUNTER:
616 pkg_values[i].counter = htonll (vl->values[i].counter);
620 pkg_values[i].gauge = htond (vl->values[i].gauge);
624 pkg_values[i].derive = htonll (vl->values[i].derive);
627 case DS_TYPE_ABSOLUTE:
628 pkg_values[i].absolute = htonll (vl->values[i].absolute);
632 free (pkg_values_types);
634 ERROR ("network plugin: write_part_values: "
635 "Unknown data source type: %i",
638 } /* switch (ds->ds[i].type) */
639 } /* for (num_values) */
642 * Use `memcpy' to write everything to the buffer, because the pointer
643 * may be unaligned and some architectures, such as SPARC, can't handle
646 packet_ptr = *ret_buffer;
648 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
649 offset += sizeof (pkg_ph);
650 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
651 offset += sizeof (pkg_num_values);
652 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
653 offset += num_values * sizeof (uint8_t);
654 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
655 offset += num_values * sizeof (value_t);
657 assert (offset == packet_len);
659 *ret_buffer = packet_ptr + packet_len;
660 *ret_buffer_len -= packet_len;
662 free (pkg_values_types);
666 } /* int write_part_values */
668 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
669 int type, uint64_t value)
674 part_header_t pkg_head;
679 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
681 if (*ret_buffer_len < packet_len)
684 pkg_head.type = htons (type);
685 pkg_head.length = htons (packet_len);
686 pkg_value = htonll (value);
688 packet_ptr = *ret_buffer;
690 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
691 offset += sizeof (pkg_head);
692 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
693 offset += sizeof (pkg_value);
695 assert (offset == packet_len);
697 *ret_buffer = packet_ptr + packet_len;
698 *ret_buffer_len -= packet_len;
701 } /* int write_part_number */
703 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
704 int type, const char *str, int str_len)
714 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
715 if (*ret_buffer_len < buffer_len)
718 pkg_type = htons (type);
719 pkg_length = htons (buffer_len);
721 buffer = *ret_buffer;
723 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
724 offset += sizeof (pkg_type);
725 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
726 offset += sizeof (pkg_length);
727 memcpy (buffer + offset, str, str_len);
729 memset (buffer + offset, '\0', 1);
732 assert (offset == buffer_len);
734 *ret_buffer = buffer + buffer_len;
735 *ret_buffer_len -= buffer_len;
738 } /* int write_part_string */
740 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
741 value_t **ret_values, int *ret_num_values)
743 char *buffer = *ret_buffer;
744 size_t buffer_len = *ret_buffer_len;
759 NOTICE ("network plugin: packet is too short: "
760 "buffer_len = %zu", buffer_len);
764 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
765 buffer += sizeof (tmp16);
766 pkg_type = ntohs (tmp16);
768 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
769 buffer += sizeof (tmp16);
770 pkg_length = ntohs (tmp16);
772 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
773 buffer += sizeof (tmp16);
774 pkg_numval = ntohs (tmp16);
776 assert (pkg_type == TYPE_VALUES);
778 exp_size = 3 * sizeof (uint16_t)
779 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
780 if (buffer_len < exp_size)
782 WARNING ("network plugin: parse_part_values: "
784 "Chunk of size %zu expected, "
785 "but buffer has only %zu bytes left.",
786 exp_size, buffer_len);
790 if (pkg_length != exp_size)
792 WARNING ("network plugin: parse_part_values: "
793 "Length and number of values "
794 "in the packet don't match.");
798 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
799 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
800 if ((pkg_types == NULL) || (pkg_values == NULL))
804 ERROR ("network plugin: parse_part_values: malloc failed.");
808 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
809 buffer += pkg_numval * sizeof (uint8_t);
810 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
811 buffer += pkg_numval * sizeof (value_t);
813 for (i = 0; i < pkg_numval; i++)
815 switch (pkg_types[i])
817 case DS_TYPE_COUNTER:
818 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
822 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
826 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
829 case DS_TYPE_ABSOLUTE:
830 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
834 NOTICE ("network plugin: parse_part_values: "
835 "Don't know how to handle data source type %"PRIu8,
840 } /* switch (pkg_types[i]) */
843 *ret_buffer = buffer;
844 *ret_buffer_len = buffer_len - pkg_length;
845 *ret_num_values = pkg_numval;
846 *ret_values = pkg_values;
851 } /* int parse_part_values */
853 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
856 char *buffer = *ret_buffer;
857 size_t buffer_len = *ret_buffer_len;
861 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
865 if (buffer_len < exp_size)
867 WARNING ("network plugin: parse_part_number: "
869 "Chunk of size %zu expected, "
870 "but buffer has only %zu bytes left.",
871 exp_size, buffer_len);
875 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
876 buffer += sizeof (tmp16);
877 /* pkg_type = ntohs (tmp16); */
879 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
880 buffer += sizeof (tmp16);
881 pkg_length = ntohs (tmp16);
883 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
884 buffer += sizeof (tmp64);
885 *value = ntohll (tmp64);
887 *ret_buffer = buffer;
888 *ret_buffer_len = buffer_len - pkg_length;
891 } /* int parse_part_number */
893 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
894 char *output, int output_len)
896 char *buffer = *ret_buffer;
897 size_t buffer_len = *ret_buffer_len;
900 size_t header_size = 2 * sizeof (uint16_t);
904 if (buffer_len < header_size)
906 WARNING ("network plugin: parse_part_string: "
908 "Chunk of at least size %zu expected, "
909 "but buffer has only %zu bytes left.",
910 header_size, buffer_len);
914 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
915 buffer += sizeof (tmp16);
916 /* pkg_type = ntohs (tmp16); */
918 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
919 buffer += sizeof (tmp16);
920 pkg_length = ntohs (tmp16);
922 /* Check that packet fits in the input buffer */
923 if (pkg_length > buffer_len)
925 WARNING ("network plugin: parse_part_string: "
927 "Chunk of size %"PRIu16" received, "
928 "but buffer has only %zu bytes left.",
929 pkg_length, buffer_len);
933 /* Check that pkg_length is in the valid range */
934 if (pkg_length <= header_size)
936 WARNING ("network plugin: parse_part_string: "
938 "Header claims this packet is only %hu "
939 "bytes long.", pkg_length);
943 /* Check that the package data fits into the output buffer.
944 * The previous if-statement ensures that:
945 * `pkg_length > header_size' */
947 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
949 WARNING ("network plugin: parse_part_string: "
950 "Output buffer too small.");
954 /* All sanity checks successfull, let's copy the data over */
955 output_len = pkg_length - header_size;
956 memcpy ((void *) output, (void *) buffer, output_len);
957 buffer += output_len;
959 /* For some very weird reason '\0' doesn't do the trick on SPARC in
961 if (output[output_len - 1] != 0)
963 WARNING ("network plugin: parse_part_string: "
964 "Received string does not end "
965 "with a NULL-byte.");
969 *ret_buffer = buffer;
970 *ret_buffer_len = buffer_len - pkg_length;
973 } /* int parse_part_string */
975 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
976 * parse_packet and vice versa. */
977 #define PP_SIGNED 0x01
978 #define PP_ENCRYPTED 0x02
979 static int parse_packet (sockent_t *se,
980 void *buffer, size_t buffer_size, int flags,
981 const char *username);
983 #define BUFFER_READ(p,s) do { \
984 memcpy ((p), buffer + buffer_offset, (s)); \
985 buffer_offset += (s); \
989 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
990 void **ret_buffer, size_t *ret_buffer_len, int flags)
992 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
996 size_t buffer_offset;
1001 part_signature_sha256_t pss;
1002 uint16_t pss_head_length;
1003 char hash[sizeof (pss.hash)];
1007 unsigned char *hash_ptr;
1009 buffer = *ret_buffer;
1010 buffer_len = *ret_buffer_len;
1013 if (se->data.server.userdb == NULL)
1015 c_complain (LOG_NOTICE, &complain_no_users,
1016 "network plugin: Received signed network packet but can't verify it "
1017 "because no user DB has been configured. Will accept it.");
1021 /* Check if the buffer has enough data for this structure. */
1022 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1025 /* Read type and length header */
1026 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1027 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1028 pss_head_length = ntohs (pss.head.length);
1030 /* Check if the `pss_head_length' is within bounds. */
1031 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1032 || (pss_head_length > buffer_len))
1034 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1038 /* Copy the hash. */
1039 BUFFER_READ (pss.hash, sizeof (pss.hash));
1041 /* Calculate username length (without null byte) and allocate memory */
1042 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1043 pss.username = malloc (username_len + 1);
1044 if (pss.username == NULL)
1047 /* Read the username */
1048 BUFFER_READ (pss.username, username_len);
1049 pss.username[username_len] = 0;
1051 assert (buffer_offset == pss_head_length);
1053 /* Query the password */
1054 secret = fbh_get (se->data.server.userdb, pss.username);
1057 ERROR ("network plugin: Unknown user: %s", pss.username);
1058 sfree (pss.username);
1062 /* Create a hash device and check the HMAC */
1064 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1067 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1068 gcry_strerror (err));
1070 sfree (pss.username);
1074 err = gcry_md_setkey (hd, secret, strlen (secret));
1077 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1080 sfree (pss.username);
1085 buffer + PART_SIGNATURE_SHA256_SIZE,
1086 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1087 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1088 if (hash_ptr == NULL)
1090 ERROR ("network plugin: gcry_md_read failed.");
1093 sfree (pss.username);
1096 memcpy (hash, hash_ptr, sizeof (hash));
1102 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1104 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1109 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1110 flags | PP_SIGNED, pss.username);
1114 sfree (pss.username);
1116 *ret_buffer = buffer + buffer_len;
1117 *ret_buffer_len = 0;
1120 } /* }}} int parse_part_sign_sha256 */
1121 /* #endif HAVE_LIBGCRYPT */
1123 #else /* if !HAVE_LIBGCRYPT */
1124 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1125 void **ret_buffer, size_t *ret_buffer_size, int flags)
1127 static int warning_has_been_printed = 0;
1131 size_t buffer_offset;
1134 part_signature_sha256_t pss;
1136 buffer = *ret_buffer;
1137 buffer_size = *ret_buffer_size;
1140 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1143 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1144 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1145 part_len = ntohs (pss.head.length);
1147 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1148 || (part_len > buffer_size))
1151 if (warning_has_been_printed == 0)
1153 WARNING ("network plugin: Received signed packet, but the network "
1154 "plugin was not linked with libgcrypt, so I cannot "
1155 "verify the signature. The packet will be accepted.");
1156 warning_has_been_printed = 1;
1159 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1160 /* username = */ NULL);
1162 *ret_buffer = buffer + buffer_size;
1163 *ret_buffer_size = 0;
1166 } /* }}} int parse_part_sign_sha256 */
1167 #endif /* !HAVE_LIBGCRYPT */
1170 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1171 void **ret_buffer, size_t *ret_buffer_len,
1174 char *buffer = *ret_buffer;
1175 size_t buffer_len = *ret_buffer_len;
1178 size_t buffer_offset;
1179 uint16_t username_len;
1180 part_encryption_aes256_t pea;
1181 unsigned char hash[sizeof (pea.hash)];
1183 gcry_cipher_hd_t cypher;
1186 /* Make sure at least the header if available. */
1187 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1189 NOTICE ("network plugin: parse_part_encr_aes256: "
1190 "Discarding short packet.");
1196 /* Copy the unencrypted information into `pea'. */
1197 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1198 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1200 /* Check the `part size'. */
1201 part_size = ntohs (pea.head.length);
1202 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1203 || (part_size > buffer_len))
1205 NOTICE ("network plugin: parse_part_encr_aes256: "
1206 "Discarding part with invalid size.");
1210 /* Read the username */
1211 BUFFER_READ (&username_len, sizeof (username_len));
1212 username_len = ntohs (username_len);
1214 if ((username_len <= 0)
1215 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1217 NOTICE ("network plugin: parse_part_encr_aes256: "
1218 "Discarding part with invalid username length.");
1222 assert (username_len > 0);
1223 pea.username = malloc (username_len + 1);
1224 if (pea.username == NULL)
1226 BUFFER_READ (pea.username, username_len);
1227 pea.username[username_len] = 0;
1229 /* Last but not least, the initialization vector */
1230 BUFFER_READ (pea.iv, sizeof (pea.iv));
1232 /* Make sure we are at the right position */
1233 assert (buffer_offset == (username_len +
1234 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1236 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1240 sfree (pea.username);
1244 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1245 assert (payload_len > 0);
1247 /* Decrypt the packet in-place */
1248 err = gcry_cipher_decrypt (cypher,
1249 buffer + buffer_offset,
1250 part_size - buffer_offset,
1251 /* in = */ NULL, /* in len = */ 0);
1254 sfree (pea.username);
1255 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1256 gcry_strerror (err));
1261 BUFFER_READ (pea.hash, sizeof (pea.hash));
1263 /* Make sure we're at the right position - again */
1264 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1265 assert (buffer_offset == (part_size - payload_len));
1267 /* Check hash sum */
1268 memset (hash, 0, sizeof (hash));
1269 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1270 buffer + buffer_offset, payload_len);
1271 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1273 sfree (pea.username);
1274 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1278 parse_packet (se, buffer + buffer_offset, payload_len,
1279 flags | PP_ENCRYPTED, pea.username);
1281 /* XXX: Free pea.username?!? */
1283 /* Update return values */
1284 *ret_buffer = buffer + part_size;
1285 *ret_buffer_len = buffer_len - part_size;
1287 sfree (pea.username);
1290 } /* }}} int parse_part_encr_aes256 */
1291 /* #endif HAVE_LIBGCRYPT */
1293 #else /* if !HAVE_LIBGCRYPT */
1294 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1295 void **ret_buffer, size_t *ret_buffer_size, int flags)
1297 static int warning_has_been_printed = 0;
1301 size_t buffer_offset;
1306 buffer = *ret_buffer;
1307 buffer_size = *ret_buffer_size;
1310 /* parse_packet assures this minimum size. */
1311 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1313 BUFFER_READ (&ph.type, sizeof (ph.type));
1314 BUFFER_READ (&ph.length, sizeof (ph.length));
1315 ph_length = ntohs (ph.length);
1317 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1318 || (ph_length > buffer_size))
1320 ERROR ("network plugin: AES-256 encrypted part "
1321 "with invalid length received.");
1325 if (warning_has_been_printed == 0)
1327 WARNING ("network plugin: Received encrypted packet, but the network "
1328 "plugin was not linked with libgcrypt, so I cannot "
1329 "decrypt it. The part will be discarded.");
1330 warning_has_been_printed = 1;
1333 *ret_buffer += ph_length;
1334 *ret_buffer_size -= ph_length;
1337 } /* }}} int parse_part_encr_aes256 */
1338 #endif /* !HAVE_LIBGCRYPT */
1342 static int parse_packet (sockent_t *se, /* {{{ */
1343 void *buffer, size_t buffer_size, int flags,
1344 const char *username)
1348 value_list_t vl = VALUE_LIST_INIT;
1352 int packet_was_signed = (flags & PP_SIGNED);
1353 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1354 int printed_ignore_warning = 0;
1355 #endif /* HAVE_LIBGCRYPT */
1358 memset (&vl, '\0', sizeof (vl));
1359 memset (&n, '\0', sizeof (n));
1362 while ((status == 0) && (0 < buffer_size)
1363 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1365 uint16_t pkg_length;
1368 memcpy ((void *) &pkg_type,
1371 memcpy ((void *) &pkg_length,
1372 (void *) (buffer + sizeof (pkg_type)),
1373 sizeof (pkg_length));
1375 pkg_length = ntohs (pkg_length);
1376 pkg_type = ntohs (pkg_type);
1378 if (pkg_length > buffer_size)
1380 /* Ensure that this loop terminates eventually */
1381 if (pkg_length < (2 * sizeof (uint16_t)))
1384 if (pkg_type == TYPE_ENCR_AES256)
1386 status = parse_part_encr_aes256 (se,
1387 &buffer, &buffer_size, flags);
1390 ERROR ("network plugin: Decrypting AES256 "
1392 "with status %i.", status);
1397 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1398 && (packet_was_encrypted == 0))
1400 if (printed_ignore_warning == 0)
1402 INFO ("network plugin: Unencrypted packet or "
1403 "part has been ignored.");
1404 printed_ignore_warning = 1;
1406 buffer = ((char *) buffer) + pkg_length;
1409 #endif /* HAVE_LIBGCRYPT */
1410 else if (pkg_type == TYPE_SIGN_SHA256)
1412 status = parse_part_sign_sha256 (se,
1413 &buffer, &buffer_size, flags);
1416 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1418 "with status %i.", status);
1423 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1424 && (packet_was_encrypted == 0)
1425 && (packet_was_signed == 0))
1427 if (printed_ignore_warning == 0)
1429 INFO ("network plugin: Unsigned packet or "
1430 "part has been ignored.");
1431 printed_ignore_warning = 1;
1433 buffer = ((char *) buffer) + pkg_length;
1436 #endif /* HAVE_LIBGCRYPT */
1437 else if (pkg_type == TYPE_VALUES)
1439 status = parse_part_values (&buffer, &buffer_size,
1440 &vl.values, &vl.values_len);
1444 network_dispatch_values (&vl, username);
1448 else if (pkg_type == TYPE_TIME)
1451 status = parse_part_number (&buffer, &buffer_size,
1455 vl.time = TIME_T_TO_CDTIME_T (tmp);
1456 n.time = TIME_T_TO_CDTIME_T (tmp);
1459 else if (pkg_type == TYPE_TIME_HR)
1462 status = parse_part_number (&buffer, &buffer_size,
1466 vl.time = (cdtime_t) tmp;
1467 n.time = (cdtime_t) tmp;
1470 else if (pkg_type == TYPE_INTERVAL)
1473 status = parse_part_number (&buffer, &buffer_size,
1476 vl.interval = TIME_T_TO_CDTIME_T (tmp);
1478 else if (pkg_type == TYPE_INTERVAL_HR)
1481 status = parse_part_number (&buffer, &buffer_size,
1484 vl.interval = (cdtime_t) tmp;
1486 else if (pkg_type == TYPE_HOST)
1488 status = parse_part_string (&buffer, &buffer_size,
1489 vl.host, sizeof (vl.host));
1491 sstrncpy (n.host, vl.host, sizeof (n.host));
1493 else if (pkg_type == TYPE_PLUGIN)
1495 status = parse_part_string (&buffer, &buffer_size,
1496 vl.plugin, sizeof (vl.plugin));
1498 sstrncpy (n.plugin, vl.plugin,
1501 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1503 status = parse_part_string (&buffer, &buffer_size,
1505 sizeof (vl.plugin_instance));
1507 sstrncpy (n.plugin_instance,
1509 sizeof (n.plugin_instance));
1511 else if (pkg_type == TYPE_TYPE)
1513 status = parse_part_string (&buffer, &buffer_size,
1514 vl.type, sizeof (vl.type));
1516 sstrncpy (n.type, vl.type, sizeof (n.type));
1518 else if (pkg_type == TYPE_TYPE_INSTANCE)
1520 status = parse_part_string (&buffer, &buffer_size,
1522 sizeof (vl.type_instance));
1524 sstrncpy (n.type_instance, vl.type_instance,
1525 sizeof (n.type_instance));
1527 else if (pkg_type == TYPE_MESSAGE)
1529 status = parse_part_string (&buffer, &buffer_size,
1530 n.message, sizeof (n.message));
1536 else if ((n.severity != NOTIF_FAILURE)
1537 && (n.severity != NOTIF_WARNING)
1538 && (n.severity != NOTIF_OKAY))
1540 INFO ("network plugin: "
1541 "Ignoring notification with "
1542 "unknown severity %i.",
1545 else if (n.time <= 0)
1547 INFO ("network plugin: "
1548 "Ignoring notification with "
1551 else if (strlen (n.message) <= 0)
1553 INFO ("network plugin: "
1554 "Ignoring notification with "
1555 "an empty message.");
1559 network_dispatch_notification (&n);
1562 else if (pkg_type == TYPE_SEVERITY)
1565 status = parse_part_number (&buffer, &buffer_size,
1568 n.severity = (int) tmp;
1572 DEBUG ("network plugin: parse_packet: Unknown part"
1573 " type: 0x%04hx", pkg_type);
1574 buffer = ((char *) buffer) + pkg_length;
1576 } /* while (buffer_size > sizeof (part_header_t)) */
1578 if (status == 0 && buffer_size > 0)
1579 WARNING ("network plugin: parse_packet: Received truncated "
1580 "packet, try increasing `MaxPacketSize'");
1583 } /* }}} int parse_packet */
1585 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1594 sfree (sec->username);
1595 sfree (sec->password);
1596 if (sec->cypher != NULL)
1597 gcry_cipher_close (sec->cypher);
1599 } /* }}} void free_sockent_client */
1601 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1605 for (i = 0; i < ses->fd_num; i++)
1607 if (ses->fd[i] >= 0)
1616 sfree (ses->auth_file);
1617 fbh_destroy (ses->userdb);
1618 if (ses->cypher != NULL)
1619 gcry_cipher_close (ses->cypher);
1621 } /* }}} void free_sockent_server */
1623 static void sockent_destroy (sockent_t *se) /* {{{ */
1627 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1634 sfree (se->service);
1636 if (se->type == SOCKENT_TYPE_CLIENT)
1637 free_sockent_client (&se->data.client);
1639 free_sockent_server (&se->data.server);
1644 } /* }}} void sockent_destroy */
1647 * int network_set_ttl
1649 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1650 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1652 * The `struct addrinfo' is used to destinguish between unicast and multicast
1655 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1657 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1658 network_config_ttl);
1660 assert (se->type == SOCKENT_TYPE_CLIENT);
1662 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1665 if (ai->ai_family == AF_INET)
1667 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1670 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1671 optname = IP_MULTICAST_TTL;
1675 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1676 &network_config_ttl,
1677 sizeof (network_config_ttl)) != 0)
1680 ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
1681 sstrerror (errno, errbuf, sizeof (errbuf)));
1685 else if (ai->ai_family == AF_INET6)
1687 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1688 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1691 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1692 optname = IPV6_MULTICAST_HOPS;
1694 optname = IPV6_UNICAST_HOPS;
1696 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1697 &network_config_ttl,
1698 sizeof (network_config_ttl)) != 0)
1701 ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
1702 sstrerror (errno, errbuf,
1709 } /* int network_set_ttl */
1711 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1713 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1716 assert (se->type == SOCKENT_TYPE_CLIENT);
1718 if (ai->ai_family == AF_INET)
1720 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1722 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1724 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1725 /* If possible, use the "ip_mreqn" structure which has
1726 * an "interface index" member. Using the interface
1727 * index is preferred here, because of its similarity
1728 * to the way IPv6 handles this. Unfortunately, it
1729 * appears not to be portable. */
1730 struct ip_mreqn mreq;
1732 memset (&mreq, 0, sizeof (mreq));
1733 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1734 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1735 mreq.imr_ifindex = se->interface;
1737 struct ip_mreq mreq;
1739 memset (&mreq, 0, sizeof (mreq));
1740 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1741 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1744 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1745 &mreq, sizeof (mreq)) != 0)
1748 ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
1749 sstrerror (errno, errbuf, sizeof (errbuf)));
1756 else if (ai->ai_family == AF_INET6)
1758 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1760 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1762 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1764 sizeof (se->interface)) != 0)
1767 ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
1768 sstrerror (errno, errbuf,
1777 /* else: Not a multicast interface. */
1778 if (se->interface != 0)
1780 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1781 char interface_name[IFNAMSIZ];
1783 if (if_indextoname (se->interface, interface_name) == NULL)
1786 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1788 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1790 sizeof(interface_name)) == -1 )
1793 ERROR ("network plugin: setsockopt (bind-if): %s",
1794 sstrerror (errno, errbuf, sizeof (errbuf)));
1797 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1800 WARNING ("network plugin: Cannot set the interface on a unicast "
1802 # if !defined(SO_BINDTODEVICE)
1803 "the \"SO_BINDTODEVICE\" socket option "
1805 "the \"if_indextoname\" function "
1807 "is not available on your system.");
1813 } /* }}} network_set_interface */
1815 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1824 /* allow multiple sockets to use the same PORT number */
1825 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1826 &yes, sizeof(yes)) == -1) {
1828 ERROR ("network plugin: setsockopt (reuseaddr): %s",
1829 sstrerror (errno, errbuf, sizeof (errbuf)));
1833 DEBUG ("fd = %i; calling `bind'", fd);
1835 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1839 sstrerror (errno, errbuf, sizeof (errbuf)));
1843 if (ai->ai_family == AF_INET)
1845 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1846 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1848 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1849 struct ip_mreqn mreq;
1851 struct ip_mreq mreq;
1854 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1856 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1857 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1858 /* Set the interface using the interface index if
1859 * possible (available). Unfortunately, the struct
1860 * ip_mreqn is not portable. */
1861 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1862 mreq.imr_ifindex = interface_idx;
1864 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1867 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1868 &loop, sizeof (loop)) == -1)
1871 ERROR ("network plugin: setsockopt (multicast-loop): %s",
1872 sstrerror (errno, errbuf,
1877 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1878 &mreq, sizeof (mreq)) == -1)
1881 ERROR ("network plugin: setsockopt (add-membership): %s",
1882 sstrerror (errno, errbuf,
1890 else if (ai->ai_family == AF_INET6)
1892 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1893 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1894 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1896 struct ipv6_mreq mreq;
1898 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1900 memcpy (&mreq.ipv6mr_multiaddr,
1902 sizeof (addr->sin6_addr));
1904 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1905 * ipv6mr_interface may be set to zeroes to
1906 * choose the default multicast interface or to
1907 * the index of a particular multicast-capable
1908 * interface if the host is multihomed.
1909 * Membership is associ-associated with a
1910 * single interface; programs running on
1911 * multihomed hosts may need to join the same
1912 * group on more than one interface.*/
1913 mreq.ipv6mr_interface = interface_idx;
1915 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1916 &loop, sizeof (loop)) == -1)
1919 ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
1920 sstrerror (errno, errbuf,
1925 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1926 &mreq, sizeof (mreq)) == -1)
1929 ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
1930 sstrerror (errno, errbuf,
1939 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1940 /* if a specific interface was set, bind the socket to it. But to avoid
1941 * possible problems with multicast routing, only do that for non-multicast
1943 if (interface_idx != 0)
1945 char interface_name[IFNAMSIZ];
1947 if (if_indextoname (interface_idx, interface_name) == NULL)
1950 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1952 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1954 sizeof(interface_name)) == -1 )
1957 ERROR ("network plugin: setsockopt (bind-if): %s",
1958 sstrerror (errno, errbuf, sizeof (errbuf)));
1962 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1965 } /* int network_bind_socket */
1967 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1968 * or `SOCKENT_TYPE_SERVER' */
1969 static int sockent_init (sockent_t *se, int type) /* {{{ */
1974 memset (se, 0, sizeof (*se));
1976 se->type = SOCKENT_TYPE_CLIENT;
1982 if (type == SOCKENT_TYPE_SERVER)
1984 se->type = SOCKENT_TYPE_SERVER;
1985 se->data.server.fd = NULL;
1987 se->data.server.security_level = SECURITY_LEVEL_NONE;
1988 se->data.server.auth_file = NULL;
1989 se->data.server.userdb = NULL;
1990 se->data.server.cypher = NULL;
1995 se->data.client.fd = -1;
1996 se->data.client.addr = NULL;
1998 se->data.client.security_level = SECURITY_LEVEL_NONE;
1999 se->data.client.username = NULL;
2000 se->data.client.password = NULL;
2001 se->data.client.cypher = NULL;
2006 } /* }}} int sockent_init */
2008 /* Open the file descriptors for a initialized sockent structure. */
2009 static int sockent_open (sockent_t *se) /* {{{ */
2011 struct addrinfo ai_hints;
2012 struct addrinfo *ai_list, *ai_ptr;
2016 const char *service;
2021 /* Set up the security structures. */
2022 #if HAVE_LIBGCRYPT /* {{{ */
2023 if (se->type == SOCKENT_TYPE_CLIENT)
2025 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
2027 if ((se->data.client.username == NULL)
2028 || (se->data.client.password == NULL))
2030 ERROR ("network plugin: Client socket with "
2031 "security requested, but no "
2032 "credentials are configured.");
2035 gcry_md_hash_buffer (GCRY_MD_SHA256,
2036 se->data.client.password_hash,
2037 se->data.client.password,
2038 strlen (se->data.client.password));
2041 else /* (se->type == SOCKENT_TYPE_SERVER) */
2043 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2045 if (se->data.server.auth_file == NULL)
2047 ERROR ("network plugin: Server socket with "
2048 "security requested, but no "
2049 "password file is configured.");
2053 if (se->data.server.auth_file != NULL)
2055 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2056 if (se->data.server.userdb == NULL)
2058 ERROR ("network plugin: Reading password file "
2060 se->data.server.auth_file);
2061 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2066 #endif /* }}} HAVE_LIBGCRYPT */
2069 service = se->service;
2071 if (service == NULL)
2072 service = NET_DEFAULT_PORT;
2074 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
2077 memset (&ai_hints, 0, sizeof (ai_hints));
2078 ai_hints.ai_flags = 0;
2080 ai_hints.ai_flags |= AI_PASSIVE;
2082 #ifdef AI_ADDRCONFIG
2083 ai_hints.ai_flags |= AI_ADDRCONFIG;
2085 ai_hints.ai_family = AF_UNSPEC;
2086 ai_hints.ai_socktype = SOCK_DGRAM;
2087 ai_hints.ai_protocol = IPPROTO_UDP;
2089 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2092 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2093 (se->node == NULL) ? "(null)" : se->node,
2094 (se->service == NULL) ? "(null)" : se->service,
2095 gai_strerror (ai_return));
2099 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2103 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2107 tmp = realloc (se->data.server.fd,
2108 sizeof (*tmp) * (se->data.server.fd_num + 1));
2111 ERROR ("network plugin: realloc failed.");
2114 se->data.server.fd = tmp;
2115 tmp = se->data.server.fd + se->data.server.fd_num;
2117 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2118 ai_ptr->ai_protocol);
2122 ERROR ("network plugin: socket(2) failed: %s",
2123 sstrerror (errno, errbuf,
2128 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2136 se->data.server.fd_num++;
2138 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2139 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2141 se->data.client.fd = socket (ai_ptr->ai_family,
2142 ai_ptr->ai_socktype,
2143 ai_ptr->ai_protocol);
2144 if (se->data.client.fd < 0)
2147 ERROR ("network plugin: socket(2) failed: %s",
2148 sstrerror (errno, errbuf,
2153 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2154 if (se->data.client.addr == NULL)
2156 ERROR ("network plugin: malloc failed.");
2157 close (se->data.client.fd);
2158 se->data.client.fd = -1;
2162 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2163 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2164 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2165 se->data.client.addrlen = ai_ptr->ai_addrlen;
2167 network_set_ttl (se, ai_ptr);
2168 network_set_interface (se, ai_ptr);
2170 /* We don't open more than one write-socket per
2171 * node/service pair.. */
2173 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2174 } /* for (ai_list) */
2176 freeaddrinfo (ai_list);
2178 /* Check if all went well. */
2179 if (se->type == SOCKENT_TYPE_SERVER)
2181 if (se->data.server.fd_num <= 0)
2184 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2186 if (se->data.client.fd < 0)
2191 } /* }}} int sockent_open */
2193 /* Add a sockent to the global list of sockets */
2194 static int sockent_add (sockent_t *se) /* {{{ */
2196 sockent_t *last_ptr;
2201 if (se->type == SOCKENT_TYPE_SERVER)
2206 tmp = realloc (listen_sockets_pollfd,
2207 sizeof (*tmp) * (listen_sockets_num
2208 + se->data.server.fd_num));
2211 ERROR ("network plugin: realloc failed.");
2214 listen_sockets_pollfd = tmp;
2215 tmp = listen_sockets_pollfd + listen_sockets_num;
2217 for (i = 0; i < se->data.server.fd_num; i++)
2219 memset (tmp + i, 0, sizeof (*tmp));
2220 tmp[i].fd = se->data.server.fd[i];
2221 tmp[i].events = POLLIN | POLLPRI;
2225 listen_sockets_num += se->data.server.fd_num;
2227 if (listen_sockets == NULL)
2229 listen_sockets = se;
2232 last_ptr = listen_sockets;
2234 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2236 if (sending_sockets == NULL)
2238 sending_sockets = se;
2241 last_ptr = sending_sockets;
2244 while (last_ptr->next != NULL)
2245 last_ptr = last_ptr->next;
2246 last_ptr->next = se;
2249 } /* }}} int sockent_add */
2251 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2255 receive_list_entry_t *ent;
2258 /* Lock and wait for more data to come in */
2259 pthread_mutex_lock (&receive_list_lock);
2260 while ((listen_loop == 0)
2261 && (receive_list_head == NULL))
2262 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2264 /* Remove the head entry and unlock */
2265 ent = receive_list_head;
2267 receive_list_head = ent->next;
2268 receive_list_length--;
2269 pthread_mutex_unlock (&receive_list_lock);
2271 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2272 * because we dispatch all missing packets before shutting down. */
2276 /* Look for the correct `sockent_t' */
2277 se = listen_sockets;
2282 for (i = 0; i < se->data.server.fd_num; i++)
2283 if (se->data.server.fd[i] == ent->fd)
2286 if (i < se->data.server.fd_num)
2294 ERROR ("network plugin: Got packet from FD %i, but can't "
2295 "find an appropriate socket entry.",
2302 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2303 /* username = */ NULL);
2309 } /* }}} void *dispatch_thread */
2311 static int network_receive (void) /* {{{ */
2313 char buffer[network_config_packet_size];
2319 receive_list_entry_t *private_list_head;
2320 receive_list_entry_t *private_list_tail;
2321 uint64_t private_list_length;
2323 assert (listen_sockets_num > 0);
2325 private_list_head = NULL;
2326 private_list_tail = NULL;
2327 private_list_length = 0;
2329 while (listen_loop == 0)
2331 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2338 ERROR ("poll failed: %s",
2339 sstrerror (errno, errbuf, sizeof (errbuf)));
2343 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2345 receive_list_entry_t *ent;
2347 if ((listen_sockets_pollfd[i].revents
2348 & (POLLIN | POLLPRI)) == 0)
2352 buffer_len = recv (listen_sockets_pollfd[i].fd,
2353 buffer, sizeof (buffer),
2358 ERROR ("recv failed: %s",
2359 sstrerror (errno, errbuf,
2364 stats_octets_rx += ((uint64_t) buffer_len);
2367 /* TODO: Possible performance enhancement: Do not free
2368 * these entries in the dispatch thread but put them in
2369 * another list, so we don't have to allocate more and
2370 * more of these structures. */
2371 ent = malloc (sizeof (receive_list_entry_t));
2374 ERROR ("network plugin: malloc failed.");
2377 memset (ent, 0, sizeof (receive_list_entry_t));
2378 ent->data = malloc (network_config_packet_size);
2379 if (ent->data == NULL)
2382 ERROR ("network plugin: malloc failed.");
2385 ent->fd = listen_sockets_pollfd[i].fd;
2388 memcpy (ent->data, buffer, buffer_len);
2389 ent->data_len = buffer_len;
2391 if (private_list_head == NULL)
2392 private_list_head = ent;
2394 private_list_tail->next = ent;
2395 private_list_tail = ent;
2396 private_list_length++;
2398 /* Do not block here. Blocking here has led to
2399 * insufficient performance in the past. */
2400 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2402 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2403 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2405 if (receive_list_head == NULL)
2406 receive_list_head = private_list_head;
2408 receive_list_tail->next = private_list_head;
2409 receive_list_tail = private_list_tail;
2410 receive_list_length += private_list_length;
2412 pthread_cond_signal (&receive_list_cond);
2413 pthread_mutex_unlock (&receive_list_lock);
2415 private_list_head = NULL;
2416 private_list_tail = NULL;
2417 private_list_length = 0;
2419 } /* for (listen_sockets_pollfd) */
2420 } /* while (listen_loop == 0) */
2422 /* Make sure everything is dispatched before exiting. */
2423 if (private_list_head != NULL)
2425 pthread_mutex_lock (&receive_list_lock);
2427 if (receive_list_head == NULL)
2428 receive_list_head = private_list_head;
2430 receive_list_tail->next = private_list_head;
2431 receive_list_tail = private_list_tail;
2432 receive_list_length += private_list_length;
2434 private_list_head = NULL;
2435 private_list_tail = NULL;
2436 private_list_length = 0;
2438 pthread_cond_signal (&receive_list_cond);
2439 pthread_mutex_unlock (&receive_list_lock);
2443 } /* }}} int network_receive */
2445 static void *receive_thread (void __attribute__((unused)) *arg)
2447 return (network_receive () ? (void *) 1 : (void *) 0);
2448 } /* void *receive_thread */
2450 static void network_init_buffer (void)
2452 memset (send_buffer, 0, network_config_packet_size);
2453 send_buffer_ptr = send_buffer;
2454 send_buffer_fill = 0;
2456 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2457 } /* int network_init_buffer */
2459 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2460 const char *buffer, size_t buffer_size)
2466 status = sendto (se->data.client.fd, buffer, buffer_size,
2468 (struct sockaddr *) se->data.client.addr,
2469 se->data.client.addrlen);
2475 ERROR ("network plugin: sendto failed: %s",
2476 sstrerror (errno, errbuf,
2483 } /* }}} void networt_send_buffer_plain */
2486 #define BUFFER_ADD(p,s) do { \
2487 memcpy (buffer + buffer_offset, (p), (s)); \
2488 buffer_offset += (s); \
2491 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2492 const char *in_buffer, size_t in_buffer_size)
2494 part_signature_sha256_t ps;
2495 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2496 size_t buffer_offset;
2497 size_t username_len;
2501 unsigned char *hash;
2504 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2507 ERROR ("network plugin: Creating HMAC object failed: %s",
2508 gcry_strerror (err));
2512 err = gcry_md_setkey (hd, se->data.client.password,
2513 strlen (se->data.client.password));
2516 ERROR ("network plugin: gcry_md_setkey failed: %s",
2517 gcry_strerror (err));
2522 username_len = strlen (se->data.client.username);
2523 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2525 ERROR ("network plugin: Username too long: %s",
2526 se->data.client.username);
2530 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2531 se->data.client.username, username_len);
2532 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2533 in_buffer, in_buffer_size);
2535 /* Initialize the `ps' structure. */
2536 memset (&ps, 0, sizeof (ps));
2537 ps.head.type = htons (TYPE_SIGN_SHA256);
2538 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2540 /* Calculate the hash value. */
2541 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2542 username_len + in_buffer_size);
2543 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2546 ERROR ("network plugin: gcry_md_read failed.");
2550 memcpy (ps.hash, hash, sizeof (ps.hash));
2552 /* Add the header */
2555 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2556 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2557 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2559 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2564 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2565 networt_send_buffer_plain (se, buffer, buffer_offset);
2566 } /* }}} void networt_send_buffer_signed */
2568 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2569 const char *in_buffer, size_t in_buffer_size)
2571 part_encryption_aes256_t pea;
2572 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2574 size_t buffer_offset;
2576 size_t username_len;
2578 gcry_cipher_hd_t cypher;
2580 /* Initialize the header fields */
2581 memset (&pea, 0, sizeof (pea));
2582 pea.head.type = htons (TYPE_ENCR_AES256);
2584 pea.username = se->data.client.username;
2586 username_len = strlen (pea.username);
2587 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2589 ERROR ("network plugin: Username too long: %s", pea.username);
2593 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2594 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2595 - sizeof (pea.hash);
2597 assert (buffer_size <= sizeof (buffer));
2598 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2599 "buffer_size = %zu;", buffer_size);
2601 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2602 + username_len + in_buffer_size));
2603 pea.username_length = htons ((uint16_t) username_len);
2605 /* Chose a random initialization vector. */
2606 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2608 /* Create hash of the payload */
2609 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2611 /* Initialize the buffer */
2613 memset (buffer, 0, sizeof (buffer));
2616 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2617 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2618 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2619 BUFFER_ADD (pea.username, username_len);
2620 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2621 assert (buffer_offset == header_size);
2622 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2623 BUFFER_ADD (in_buffer, in_buffer_size);
2625 assert (buffer_offset == buffer_size);
2627 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2628 se->data.client.password);
2632 /* Encrypt the buffer in-place */
2633 err = gcry_cipher_encrypt (cypher,
2634 buffer + header_size,
2635 buffer_size - header_size,
2636 /* in = */ NULL, /* in len = */ 0);
2639 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2640 gcry_strerror (err));
2644 /* Send it out without further modifications */
2645 networt_send_buffer_plain (se, buffer, buffer_size);
2646 } /* }}} void networt_send_buffer_encrypted */
2648 #endif /* HAVE_LIBGCRYPT */
2650 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2654 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2656 for (se = sending_sockets; se != NULL; se = se->next)
2659 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2660 networt_send_buffer_encrypted (se, buffer, buffer_len);
2661 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2662 networt_send_buffer_signed (se, buffer, buffer_len);
2663 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2664 #endif /* HAVE_LIBGCRYPT */
2665 networt_send_buffer_plain (se, buffer, buffer_len);
2666 } /* for (sending_sockets) */
2667 } /* }}} void network_send_buffer */
2669 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2670 value_list_t *vl_def,
2671 const data_set_t *ds, const value_list_t *vl)
2673 char *buffer_orig = buffer;
2675 if (strcmp (vl_def->host, vl->host) != 0)
2677 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2678 vl->host, strlen (vl->host)) != 0)
2680 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2683 if (vl_def->time != vl->time)
2685 if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
2686 (uint64_t) vl->time))
2688 vl_def->time = vl->time;
2691 if (vl_def->interval != vl->interval)
2693 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
2694 (uint64_t) vl->interval))
2696 vl_def->interval = vl->interval;
2699 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2701 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2702 vl->plugin, strlen (vl->plugin)) != 0)
2704 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2707 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2709 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2710 vl->plugin_instance,
2711 strlen (vl->plugin_instance)) != 0)
2713 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2716 if (strcmp (vl_def->type, vl->type) != 0)
2718 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2719 vl->type, strlen (vl->type)) != 0)
2721 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2724 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2726 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2728 strlen (vl->type_instance)) != 0)
2730 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2733 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2736 return (buffer - buffer_orig);
2737 } /* }}} int add_to_buffer */
2739 static void flush_buffer (void)
2741 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2744 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2746 stats_octets_tx += ((uint64_t) send_buffer_fill);
2749 network_init_buffer ();
2752 static int network_write (const data_set_t *ds, const value_list_t *vl,
2753 user_data_t __attribute__((unused)) *user_data)
2757 if (!check_send_okay (vl))
2760 char name[6*DATA_MAX_NAME_LEN];
2761 FORMAT_VL (name, sizeof (name), vl);
2762 name[sizeof (name) - 1] = 0;
2763 DEBUG ("network plugin: network_write: "
2764 "NOT sending %s.", name);
2766 /* Counter is not protected by another lock and may be reached by
2767 * multiple threads */
2768 pthread_mutex_lock (&stats_lock);
2769 stats_values_not_sent++;
2770 pthread_mutex_unlock (&stats_lock);
2774 uc_meta_data_add_unsigned_int (vl,
2775 "network:time_sent", (uint64_t) vl->time);
2777 pthread_mutex_lock (&send_buffer_lock);
2779 status = add_to_buffer (send_buffer_ptr,
2780 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2785 /* status == bytes added to the buffer */
2786 send_buffer_fill += status;
2787 send_buffer_ptr += status;
2789 stats_values_sent++;
2795 status = add_to_buffer (send_buffer_ptr,
2796 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2802 send_buffer_fill += status;
2803 send_buffer_ptr += status;
2805 stats_values_sent++;
2811 ERROR ("network plugin: Unable to append to the "
2812 "buffer for some weird reason");
2814 else if ((network_config_packet_size - send_buffer_fill) < 15)
2819 pthread_mutex_unlock (&send_buffer_lock);
2821 return ((status < 0) ? -1 : 0);
2822 } /* int network_write */
2824 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2827 if ((ci->values_num != 1)
2828 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2829 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2831 ERROR ("network plugin: The `%s' config option needs "
2832 "exactly one boolean argument.", ci->key);
2836 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2838 if (ci->values[0].value.boolean)
2845 char *str = ci->values[0].value.string;
2849 else if (IS_FALSE (str))
2853 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2854 "option as boolean value.",
2861 } /* }}} int network_config_set_boolean */
2863 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2866 if ((ci->values_num != 1)
2867 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2869 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2870 "one numeric argument.");
2874 tmp = (int) ci->values[0].value.number;
2875 if ((tmp > 0) && (tmp <= 255))
2876 network_config_ttl = tmp;
2879 } /* }}} int network_config_set_ttl */
2881 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2884 if ((ci->values_num != 1)
2885 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2887 WARNING ("network plugin: The `Interface' config option needs exactly "
2888 "one string argument.");
2892 if (interface == NULL)
2895 *interface = if_nametoindex (ci->values[0].value.string);
2898 } /* }}} int network_config_set_interface */
2900 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2903 if ((ci->values_num != 1)
2904 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2906 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2907 "one numeric argument.");
2911 tmp = (int) ci->values[0].value.number;
2912 if ((tmp >= 1024) && (tmp <= 65535))
2913 network_config_packet_size = tmp;
2916 } /* }}} int network_config_set_buffer_size */
2919 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2923 if ((ci->values_num != 1)
2924 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2926 WARNING ("network plugin: The `%s' config option needs exactly "
2927 "one string argument.", ci->key);
2931 tmp = strdup (ci->values[0].value.string);
2935 sfree (*ret_string);
2939 } /* }}} int network_config_set_string */
2940 #endif /* HAVE_LIBGCRYPT */
2943 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2947 if ((ci->values_num != 1)
2948 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2950 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2951 "one string argument.");
2955 str = ci->values[0].value.string;
2956 if (strcasecmp ("Encrypt", str) == 0)
2957 *retval = SECURITY_LEVEL_ENCRYPT;
2958 else if (strcasecmp ("Sign", str) == 0)
2959 *retval = SECURITY_LEVEL_SIGN;
2960 else if (strcasecmp ("None", str) == 0)
2961 *retval = SECURITY_LEVEL_NONE;
2964 WARNING ("network plugin: Unknown security level: %s.", str);
2969 } /* }}} int network_config_set_security_level */
2970 #endif /* HAVE_LIBGCRYPT */
2972 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2978 if ((ci->values_num < 1) || (ci->values_num > 2)
2979 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2980 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2982 ERROR ("network plugin: The `%s' config option needs "
2983 "one or two string arguments.", ci->key);
2987 se = malloc (sizeof (*se));
2990 ERROR ("network plugin: malloc failed.");
2993 sockent_init (se, SOCKENT_TYPE_SERVER);
2995 se->node = strdup (ci->values[0].value.string);
2996 if (ci->values_num >= 2)
2997 se->service = strdup (ci->values[1].value.string);
2999 for (i = 0; i < ci->children_num; i++)
3001 oconfig_item_t *child = ci->children + i;
3004 if (strcasecmp ("AuthFile", child->key) == 0)
3005 network_config_set_string (child, &se->data.server.auth_file);
3006 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3007 network_config_set_security_level (child,
3008 &se->data.server.security_level);
3010 #endif /* HAVE_LIBGCRYPT */
3011 if (strcasecmp ("Interface", child->key) == 0)
3012 network_config_set_interface (child,
3016 WARNING ("network plugin: Option `%s' is not allowed here.",
3022 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3023 && (se->data.server.auth_file == NULL))
3025 ERROR ("network plugin: A security level higher than `none' was "
3026 "requested, but no AuthFile option was given. Cowardly refusing to "
3027 "open this socket!");
3028 sockent_destroy (se);
3031 #endif /* HAVE_LIBGCRYPT */
3033 status = sockent_open (se);
3036 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
3037 sockent_destroy (se);
3041 status = sockent_add (se);
3044 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3045 sockent_destroy (se);
3050 } /* }}} int network_config_add_listen */
3052 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3058 if ((ci->values_num < 1) || (ci->values_num > 2)
3059 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3060 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3062 ERROR ("network plugin: The `%s' config option needs "
3063 "one or two string arguments.", ci->key);
3067 se = malloc (sizeof (*se));
3070 ERROR ("network plugin: malloc failed.");
3073 sockent_init (se, SOCKENT_TYPE_CLIENT);
3075 se->node = strdup (ci->values[0].value.string);
3076 if (ci->values_num >= 2)
3077 se->service = strdup (ci->values[1].value.string);
3079 for (i = 0; i < ci->children_num; i++)
3081 oconfig_item_t *child = ci->children + i;
3084 if (strcasecmp ("Username", child->key) == 0)
3085 network_config_set_string (child, &se->data.client.username);
3086 else if (strcasecmp ("Password", child->key) == 0)
3087 network_config_set_string (child, &se->data.client.password);
3088 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3089 network_config_set_security_level (child,
3090 &se->data.client.security_level);
3092 #endif /* HAVE_LIBGCRYPT */
3093 if (strcasecmp ("Interface", child->key) == 0)
3094 network_config_set_interface (child,
3098 WARNING ("network plugin: Option `%s' is not allowed here.",
3104 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3105 && ((se->data.client.username == NULL)
3106 || (se->data.client.password == NULL)))
3108 ERROR ("network plugin: A security level higher than `none' was "
3109 "requested, but no Username or Password option was given. "
3110 "Cowardly refusing to open this socket!");
3111 sockent_destroy (se);
3114 #endif /* HAVE_LIBGCRYPT */
3116 status = sockent_open (se);
3119 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3120 sockent_destroy (se);
3124 status = sockent_add (se);
3127 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3128 sockent_destroy (se);
3133 } /* }}} int network_config_add_server */
3135 static int network_config (oconfig_item_t *ci) /* {{{ */
3139 for (i = 0; i < ci->children_num; i++)
3141 oconfig_item_t *child = ci->children + i;
3143 if (strcasecmp ("Listen", child->key) == 0)
3144 network_config_add_listen (child);
3145 else if (strcasecmp ("Server", child->key) == 0)
3146 network_config_add_server (child);
3147 else if (strcasecmp ("TimeToLive", child->key) == 0)
3148 network_config_set_ttl (child);
3149 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3150 network_config_set_buffer_size (child);
3151 else if (strcasecmp ("Forward", child->key) == 0)
3152 network_config_set_boolean (child, &network_config_forward);
3153 else if (strcasecmp ("ReportStats", child->key) == 0)
3154 network_config_set_boolean (child, &network_config_stats);
3157 WARNING ("network plugin: Option `%s' is not allowed here.",
3163 } /* }}} int network_config */
3165 static int network_notification (const notification_t *n,
3166 user_data_t __attribute__((unused)) *user_data)
3168 char buffer[network_config_packet_size];
3169 char *buffer_ptr = buffer;
3170 int buffer_free = sizeof (buffer);
3173 if (!check_send_notify_okay (n))
3176 memset (buffer, 0, sizeof (buffer));
3178 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3179 (uint64_t) n->time);
3183 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3184 (uint64_t) n->severity);
3188 if (strlen (n->host) > 0)
3190 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3191 n->host, strlen (n->host));
3196 if (strlen (n->plugin) > 0)
3198 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3199 n->plugin, strlen (n->plugin));
3204 if (strlen (n->plugin_instance) > 0)
3206 status = write_part_string (&buffer_ptr, &buffer_free,
3207 TYPE_PLUGIN_INSTANCE,
3208 n->plugin_instance, strlen (n->plugin_instance));
3213 if (strlen (n->type) > 0)
3215 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3216 n->type, strlen (n->type));
3221 if (strlen (n->type_instance) > 0)
3223 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3224 n->type_instance, strlen (n->type_instance));
3229 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3230 n->message, strlen (n->message));
3234 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3237 } /* int network_notification */
3239 static int network_shutdown (void)
3243 /* Kill the listening thread */
3244 if (receive_thread_running != 0)
3246 INFO ("network plugin: Stopping receive thread.");
3247 pthread_kill (receive_thread_id, SIGTERM);
3248 pthread_join (receive_thread_id, NULL /* no return value */);
3249 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3250 receive_thread_running = 0;
3253 /* Shutdown the dispatching thread */
3254 if (dispatch_thread_running != 0)
3256 INFO ("network plugin: Stopping dispatch thread.");
3257 pthread_mutex_lock (&receive_list_lock);
3258 pthread_cond_broadcast (&receive_list_cond);
3259 pthread_mutex_unlock (&receive_list_lock);
3260 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3261 dispatch_thread_running = 0;
3264 sockent_destroy (listen_sockets);
3266 if (send_buffer_fill > 0)
3269 sfree (send_buffer);
3271 /* TODO: Close `sending_sockets' */
3273 plugin_unregister_config ("network");
3274 plugin_unregister_init ("network");
3275 plugin_unregister_write ("network");
3276 plugin_unregister_shutdown ("network");
3279 } /* int network_shutdown */
3281 static int network_stats_read (void) /* {{{ */
3283 derive_t copy_octets_rx;
3284 derive_t copy_octets_tx;
3285 derive_t copy_packets_rx;
3286 derive_t copy_packets_tx;
3287 derive_t copy_values_dispatched;
3288 derive_t copy_values_not_dispatched;
3289 derive_t copy_values_sent;
3290 derive_t copy_values_not_sent;
3291 derive_t copy_receive_list_length;
3292 value_list_t vl = VALUE_LIST_INIT;
3295 copy_octets_rx = stats_octets_rx;
3296 copy_octets_tx = stats_octets_tx;
3297 copy_packets_rx = stats_packets_rx;
3298 copy_packets_tx = stats_packets_tx;
3299 copy_values_dispatched = stats_values_dispatched;
3300 copy_values_not_dispatched = stats_values_not_dispatched;
3301 copy_values_sent = stats_values_sent;
3302 copy_values_not_sent = stats_values_not_sent;
3303 copy_receive_list_length = receive_list_length;
3305 /* Initialize `vl' */
3309 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3310 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3312 /* Octets received / sent */
3313 vl.values[0].derive = (derive_t) copy_octets_rx;
3314 vl.values[1].derive = (derive_t) copy_octets_tx;
3315 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3316 plugin_dispatch_values_secure (&vl);
3318 /* Packets received / send */
3319 vl.values[0].derive = (derive_t) copy_packets_rx;
3320 vl.values[1].derive = (derive_t) copy_packets_tx;
3321 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3322 plugin_dispatch_values_secure (&vl);
3324 /* Values (not) dispatched and (not) send */
3325 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3328 vl.values[0].derive = (derive_t) copy_values_dispatched;
3329 sstrncpy (vl.type_instance, "dispatch-accepted",
3330 sizeof (vl.type_instance));
3331 plugin_dispatch_values_secure (&vl);
3333 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3334 sstrncpy (vl.type_instance, "dispatch-rejected",
3335 sizeof (vl.type_instance));
3336 plugin_dispatch_values_secure (&vl);
3338 vl.values[0].derive = (derive_t) copy_values_sent;
3339 sstrncpy (vl.type_instance, "send-accepted",
3340 sizeof (vl.type_instance));
3341 plugin_dispatch_values_secure (&vl);
3343 vl.values[0].derive = (derive_t) copy_values_not_sent;
3344 sstrncpy (vl.type_instance, "send-rejected",
3345 sizeof (vl.type_instance));
3346 plugin_dispatch_values_secure (&vl);
3348 /* Receive queue length */
3349 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3350 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3351 vl.type_instance[0] = 0;
3352 plugin_dispatch_values_secure (&vl);
3355 } /* }}} int network_stats_read */
3357 static int network_init (void)
3359 static _Bool have_init = 0;
3361 /* Check if we were already initialized. If so, just return - there's
3362 * nothing more to do (for now, that is). */
3368 /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
3369 * Because you can't know in a library whether another library has
3370 * already initialized the library
3372 if (!gcry_control (GCRYCTL_ANY_INITIALIZATION_P))
3374 gcry_check_version(NULL); /* before calling any other functions */
3375 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3376 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3377 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3381 if (network_config_stats != 0)
3382 plugin_register_read ("network", network_stats_read);
3384 plugin_register_shutdown ("network", network_shutdown);
3386 send_buffer = malloc (network_config_packet_size);
3387 if (send_buffer == NULL)
3389 ERROR ("network plugin: malloc failed.");
3392 network_init_buffer ();
3394 /* setup socket(s) and so on */
3395 if (sending_sockets != NULL)
3397 plugin_register_write ("network", network_write,
3398 /* user_data = */ NULL);
3399 plugin_register_notification ("network", network_notification,
3400 /* user_data = */ NULL);
3403 /* If no threads need to be started, return here. */
3404 if ((listen_sockets_num == 0)
3405 || ((dispatch_thread_running != 0)
3406 && (receive_thread_running != 0)))
3409 if (dispatch_thread_running == 0)
3412 status = plugin_thread_create (&dispatch_thread_id,
3413 NULL /* no attributes */,
3415 NULL /* no argument */);
3419 ERROR ("network: pthread_create failed: %s",
3420 sstrerror (errno, errbuf,
3425 dispatch_thread_running = 1;
3429 if (receive_thread_running == 0)
3432 status = plugin_thread_create (&receive_thread_id,
3433 NULL /* no attributes */,
3435 NULL /* no argument */);
3439 ERROR ("network: pthread_create failed: %s",
3440 sstrerror (errno, errbuf,
3445 receive_thread_running = 1;
3450 } /* int network_init */
3453 * The flush option of the network plugin cannot flush individual identifiers.
3454 * All the values are added to a buffer and sent when the buffer is full, the
3455 * requested value may or may not be in there, it's not worth finding out. We
3456 * just send the buffer if `flush' is called - if the requested value was in
3457 * there, good. If not, well, then there is nothing to flush.. -octo
3459 static int network_flush (__attribute__((unused)) cdtime_t timeout,
3460 __attribute__((unused)) const char *identifier,
3461 __attribute__((unused)) user_data_t *user_data)
3463 pthread_mutex_lock (&send_buffer_lock);
3465 if (send_buffer_fill > 0)
3468 pthread_mutex_unlock (&send_buffer_lock);
3471 } /* int network_flush */
3473 void module_register (void)
3475 plugin_register_complex_config ("network", network_config);
3476 plugin_register_init ("network", network_init);
3477 plugin_register_flush ("network", network_flush,
3478 /* user_data = */ NULL);
3479 } /* void module_register */
3481 /* vim: set fdm=marker : */