2 * collectd - src/network.c
3 * Copyright (C) 2005-2013 Florian octo Forster
4 * Copyright (C) 2009 Aman Gupta
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation; only version 2.1 of the License is
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 * Florian octo Forster <octo at collectd.org>
22 * Aman Gupta <aman at tmm1.net>
25 #define _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 void network_init_gcrypt (void) /* {{{ */
498 /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
499 * Because you can't know in a library whether another library has
500 * already initialized the library */
501 if (gcry_control (GCRYCTL_ANY_INITIALIZATION_P))
504 gcry_check_version (NULL); /* before calling any other functions */
505 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
506 gcry_control (GCRYCTL_INIT_SECMEM, 32768);
507 gcry_control (GCRYCTL_INITIALIZATION_FINISHED);
508 } /* }}} void network_init_gcrypt */
510 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
511 const void *iv, size_t iv_size, const char *username)
514 gcry_cipher_hd_t *cyper_ptr;
515 unsigned char password_hash[32];
517 if (se->type == SOCKENT_TYPE_CLIENT)
519 cyper_ptr = &se->data.client.cypher;
520 memcpy (password_hash, se->data.client.password_hash,
521 sizeof (password_hash));
527 cyper_ptr = &se->data.server.cypher;
529 if (username == NULL)
532 secret = fbh_get (se->data.server.userdb, username);
536 gcry_md_hash_buffer (GCRY_MD_SHA256,
538 secret, strlen (secret));
543 if (*cyper_ptr == NULL)
545 err = gcry_cipher_open (cyper_ptr,
546 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
549 ERROR ("network plugin: gcry_cipher_open returned: %s",
550 gcry_strerror (err));
557 gcry_cipher_reset (*cyper_ptr);
559 assert (*cyper_ptr != NULL);
561 err = gcry_cipher_setkey (*cyper_ptr,
562 password_hash, sizeof (password_hash));
565 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
566 gcry_strerror (err));
567 gcry_cipher_close (*cyper_ptr);
572 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
575 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
576 gcry_strerror (err));
577 gcry_cipher_close (*cyper_ptr);
583 } /* }}} int network_get_aes256_cypher */
584 #endif /* HAVE_LIBGCRYPT */
586 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
587 const data_set_t *ds, const value_list_t *vl)
593 part_header_t pkg_ph;
594 uint16_t pkg_num_values;
595 uint8_t *pkg_values_types;
601 num_values = vl->values_len;
602 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
603 + (num_values * sizeof (uint8_t))
604 + (num_values * sizeof (value_t));
606 if (*ret_buffer_len < packet_len)
609 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
610 if (pkg_values_types == NULL)
612 ERROR ("network plugin: write_part_values: malloc failed.");
616 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
617 if (pkg_values == NULL)
619 free (pkg_values_types);
620 ERROR ("network plugin: write_part_values: malloc failed.");
624 pkg_ph.type = htons (TYPE_VALUES);
625 pkg_ph.length = htons (packet_len);
627 pkg_num_values = htons ((uint16_t) vl->values_len);
629 for (i = 0; i < num_values; i++)
631 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
632 switch (ds->ds[i].type)
634 case DS_TYPE_COUNTER:
635 pkg_values[i].counter = htonll (vl->values[i].counter);
639 pkg_values[i].gauge = htond (vl->values[i].gauge);
643 pkg_values[i].derive = htonll (vl->values[i].derive);
646 case DS_TYPE_ABSOLUTE:
647 pkg_values[i].absolute = htonll (vl->values[i].absolute);
651 free (pkg_values_types);
653 ERROR ("network plugin: write_part_values: "
654 "Unknown data source type: %i",
657 } /* switch (ds->ds[i].type) */
658 } /* for (num_values) */
661 * Use `memcpy' to write everything to the buffer, because the pointer
662 * may be unaligned and some architectures, such as SPARC, can't handle
665 packet_ptr = *ret_buffer;
667 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
668 offset += sizeof (pkg_ph);
669 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
670 offset += sizeof (pkg_num_values);
671 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
672 offset += num_values * sizeof (uint8_t);
673 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
674 offset += num_values * sizeof (value_t);
676 assert (offset == packet_len);
678 *ret_buffer = packet_ptr + packet_len;
679 *ret_buffer_len -= packet_len;
681 free (pkg_values_types);
685 } /* int write_part_values */
687 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
688 int type, uint64_t value)
693 part_header_t pkg_head;
698 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
700 if (*ret_buffer_len < packet_len)
703 pkg_head.type = htons (type);
704 pkg_head.length = htons (packet_len);
705 pkg_value = htonll (value);
707 packet_ptr = *ret_buffer;
709 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
710 offset += sizeof (pkg_head);
711 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
712 offset += sizeof (pkg_value);
714 assert (offset == packet_len);
716 *ret_buffer = packet_ptr + packet_len;
717 *ret_buffer_len -= packet_len;
720 } /* int write_part_number */
722 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
723 int type, const char *str, int str_len)
733 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
734 if (*ret_buffer_len < buffer_len)
737 pkg_type = htons (type);
738 pkg_length = htons (buffer_len);
740 buffer = *ret_buffer;
742 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
743 offset += sizeof (pkg_type);
744 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
745 offset += sizeof (pkg_length);
746 memcpy (buffer + offset, str, str_len);
748 memset (buffer + offset, '\0', 1);
751 assert (offset == buffer_len);
753 *ret_buffer = buffer + buffer_len;
754 *ret_buffer_len -= buffer_len;
757 } /* int write_part_string */
759 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
760 value_t **ret_values, int *ret_num_values)
762 char *buffer = *ret_buffer;
763 size_t buffer_len = *ret_buffer_len;
778 NOTICE ("network plugin: packet is too short: "
779 "buffer_len = %zu", buffer_len);
783 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
784 buffer += sizeof (tmp16);
785 pkg_type = ntohs (tmp16);
787 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
788 buffer += sizeof (tmp16);
789 pkg_length = ntohs (tmp16);
791 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
792 buffer += sizeof (tmp16);
793 pkg_numval = ntohs (tmp16);
795 assert (pkg_type == TYPE_VALUES);
797 exp_size = 3 * sizeof (uint16_t)
798 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
799 if (buffer_len < exp_size)
801 WARNING ("network plugin: parse_part_values: "
803 "Chunk of size %zu expected, "
804 "but buffer has only %zu bytes left.",
805 exp_size, buffer_len);
809 if (pkg_length != exp_size)
811 WARNING ("network plugin: parse_part_values: "
812 "Length and number of values "
813 "in the packet don't match.");
817 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
818 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
819 if ((pkg_types == NULL) || (pkg_values == NULL))
823 ERROR ("network plugin: parse_part_values: malloc failed.");
827 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
828 buffer += pkg_numval * sizeof (uint8_t);
829 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
830 buffer += pkg_numval * sizeof (value_t);
832 for (i = 0; i < pkg_numval; i++)
834 switch (pkg_types[i])
836 case DS_TYPE_COUNTER:
837 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
841 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
845 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
848 case DS_TYPE_ABSOLUTE:
849 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
853 NOTICE ("network plugin: parse_part_values: "
854 "Don't know how to handle data source type %"PRIu8,
859 } /* switch (pkg_types[i]) */
862 *ret_buffer = buffer;
863 *ret_buffer_len = buffer_len - pkg_length;
864 *ret_num_values = pkg_numval;
865 *ret_values = pkg_values;
870 } /* int parse_part_values */
872 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
875 char *buffer = *ret_buffer;
876 size_t buffer_len = *ret_buffer_len;
880 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
884 if (buffer_len < exp_size)
886 WARNING ("network plugin: parse_part_number: "
888 "Chunk of size %zu expected, "
889 "but buffer has only %zu bytes left.",
890 exp_size, buffer_len);
894 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
895 buffer += sizeof (tmp16);
896 /* pkg_type = ntohs (tmp16); */
898 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
899 buffer += sizeof (tmp16);
900 pkg_length = ntohs (tmp16);
902 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
903 buffer += sizeof (tmp64);
904 *value = ntohll (tmp64);
906 *ret_buffer = buffer;
907 *ret_buffer_len = buffer_len - pkg_length;
910 } /* int parse_part_number */
912 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
913 char *output, int output_len)
915 char *buffer = *ret_buffer;
916 size_t buffer_len = *ret_buffer_len;
919 size_t header_size = 2 * sizeof (uint16_t);
923 if (buffer_len < header_size)
925 WARNING ("network plugin: parse_part_string: "
927 "Chunk of at least size %zu expected, "
928 "but buffer has only %zu bytes left.",
929 header_size, buffer_len);
933 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
934 buffer += sizeof (tmp16);
935 /* pkg_type = ntohs (tmp16); */
937 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
938 buffer += sizeof (tmp16);
939 pkg_length = ntohs (tmp16);
941 /* Check that packet fits in the input buffer */
942 if (pkg_length > buffer_len)
944 WARNING ("network plugin: parse_part_string: "
946 "Chunk of size %"PRIu16" received, "
947 "but buffer has only %zu bytes left.",
948 pkg_length, buffer_len);
952 /* Check that pkg_length is in the valid range */
953 if (pkg_length <= header_size)
955 WARNING ("network plugin: parse_part_string: "
957 "Header claims this packet is only %hu "
958 "bytes long.", pkg_length);
962 /* Check that the package data fits into the output buffer.
963 * The previous if-statement ensures that:
964 * `pkg_length > header_size' */
966 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
968 WARNING ("network plugin: parse_part_string: "
969 "Output buffer too small.");
973 /* All sanity checks successfull, let's copy the data over */
974 output_len = pkg_length - header_size;
975 memcpy ((void *) output, (void *) buffer, output_len);
976 buffer += output_len;
978 /* For some very weird reason '\0' doesn't do the trick on SPARC in
980 if (output[output_len - 1] != 0)
982 WARNING ("network plugin: parse_part_string: "
983 "Received string does not end "
984 "with a NULL-byte.");
988 *ret_buffer = buffer;
989 *ret_buffer_len = buffer_len - pkg_length;
992 } /* int parse_part_string */
994 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
995 * parse_packet and vice versa. */
996 #define PP_SIGNED 0x01
997 #define PP_ENCRYPTED 0x02
998 static int parse_packet (sockent_t *se,
999 void *buffer, size_t buffer_size, int flags,
1000 const char *username);
1002 #define BUFFER_READ(p,s) do { \
1003 memcpy ((p), buffer + buffer_offset, (s)); \
1004 buffer_offset += (s); \
1008 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1009 void **ret_buffer, size_t *ret_buffer_len, int flags)
1011 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
1015 size_t buffer_offset;
1017 size_t username_len;
1020 part_signature_sha256_t pss;
1021 uint16_t pss_head_length;
1022 char hash[sizeof (pss.hash)];
1026 unsigned char *hash_ptr;
1028 buffer = *ret_buffer;
1029 buffer_len = *ret_buffer_len;
1032 if (se->data.server.userdb == NULL)
1034 c_complain (LOG_NOTICE, &complain_no_users,
1035 "network plugin: Received signed network packet but can't verify it "
1036 "because no user DB has been configured. Will accept it.");
1040 /* Check if the buffer has enough data for this structure. */
1041 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1044 /* Read type and length header */
1045 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1046 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1047 pss_head_length = ntohs (pss.head.length);
1049 /* Check if the `pss_head_length' is within bounds. */
1050 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1051 || (pss_head_length > buffer_len))
1053 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1057 /* Copy the hash. */
1058 BUFFER_READ (pss.hash, sizeof (pss.hash));
1060 /* Calculate username length (without null byte) and allocate memory */
1061 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1062 pss.username = malloc (username_len + 1);
1063 if (pss.username == NULL)
1066 /* Read the username */
1067 BUFFER_READ (pss.username, username_len);
1068 pss.username[username_len] = 0;
1070 assert (buffer_offset == pss_head_length);
1072 /* Query the password */
1073 secret = fbh_get (se->data.server.userdb, pss.username);
1076 ERROR ("network plugin: Unknown user: %s", pss.username);
1077 sfree (pss.username);
1081 /* Create a hash device and check the HMAC */
1083 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1086 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1087 gcry_strerror (err));
1089 sfree (pss.username);
1093 err = gcry_md_setkey (hd, secret, strlen (secret));
1096 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1099 sfree (pss.username);
1104 buffer + PART_SIGNATURE_SHA256_SIZE,
1105 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1106 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1107 if (hash_ptr == NULL)
1109 ERROR ("network plugin: gcry_md_read failed.");
1112 sfree (pss.username);
1115 memcpy (hash, hash_ptr, sizeof (hash));
1121 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1123 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1128 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1129 flags | PP_SIGNED, pss.username);
1133 sfree (pss.username);
1135 *ret_buffer = buffer + buffer_len;
1136 *ret_buffer_len = 0;
1139 } /* }}} int parse_part_sign_sha256 */
1140 /* #endif HAVE_LIBGCRYPT */
1142 #else /* if !HAVE_LIBGCRYPT */
1143 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1144 void **ret_buffer, size_t *ret_buffer_size, int flags)
1146 static int warning_has_been_printed = 0;
1150 size_t buffer_offset;
1153 part_signature_sha256_t pss;
1155 buffer = *ret_buffer;
1156 buffer_size = *ret_buffer_size;
1159 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1162 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1163 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1164 part_len = ntohs (pss.head.length);
1166 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1167 || (part_len > buffer_size))
1170 if (warning_has_been_printed == 0)
1172 WARNING ("network plugin: Received signed packet, but the network "
1173 "plugin was not linked with libgcrypt, so I cannot "
1174 "verify the signature. The packet will be accepted.");
1175 warning_has_been_printed = 1;
1178 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1179 /* username = */ NULL);
1181 *ret_buffer = buffer + buffer_size;
1182 *ret_buffer_size = 0;
1185 } /* }}} int parse_part_sign_sha256 */
1186 #endif /* !HAVE_LIBGCRYPT */
1189 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1190 void **ret_buffer, size_t *ret_buffer_len,
1193 char *buffer = *ret_buffer;
1194 size_t buffer_len = *ret_buffer_len;
1197 size_t buffer_offset;
1198 uint16_t username_len;
1199 part_encryption_aes256_t pea;
1200 unsigned char hash[sizeof (pea.hash)];
1202 gcry_cipher_hd_t cypher;
1205 /* Make sure at least the header if available. */
1206 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1208 NOTICE ("network plugin: parse_part_encr_aes256: "
1209 "Discarding short packet.");
1215 /* Copy the unencrypted information into `pea'. */
1216 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1217 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1219 /* Check the `part size'. */
1220 part_size = ntohs (pea.head.length);
1221 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1222 || (part_size > buffer_len))
1224 NOTICE ("network plugin: parse_part_encr_aes256: "
1225 "Discarding part with invalid size.");
1229 /* Read the username */
1230 BUFFER_READ (&username_len, sizeof (username_len));
1231 username_len = ntohs (username_len);
1233 if ((username_len <= 0)
1234 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1236 NOTICE ("network plugin: parse_part_encr_aes256: "
1237 "Discarding part with invalid username length.");
1241 assert (username_len > 0);
1242 pea.username = malloc (username_len + 1);
1243 if (pea.username == NULL)
1245 BUFFER_READ (pea.username, username_len);
1246 pea.username[username_len] = 0;
1248 /* Last but not least, the initialization vector */
1249 BUFFER_READ (pea.iv, sizeof (pea.iv));
1251 /* Make sure we are at the right position */
1252 assert (buffer_offset == (username_len +
1253 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1255 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1259 sfree (pea.username);
1263 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1264 assert (payload_len > 0);
1266 /* Decrypt the packet in-place */
1267 err = gcry_cipher_decrypt (cypher,
1268 buffer + buffer_offset,
1269 part_size - buffer_offset,
1270 /* in = */ NULL, /* in len = */ 0);
1273 sfree (pea.username);
1274 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1275 gcry_strerror (err));
1280 BUFFER_READ (pea.hash, sizeof (pea.hash));
1282 /* Make sure we're at the right position - again */
1283 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1284 assert (buffer_offset == (part_size - payload_len));
1286 /* Check hash sum */
1287 memset (hash, 0, sizeof (hash));
1288 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1289 buffer + buffer_offset, payload_len);
1290 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1292 sfree (pea.username);
1293 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1297 parse_packet (se, buffer + buffer_offset, payload_len,
1298 flags | PP_ENCRYPTED, pea.username);
1300 /* XXX: Free pea.username?!? */
1302 /* Update return values */
1303 *ret_buffer = buffer + part_size;
1304 *ret_buffer_len = buffer_len - part_size;
1306 sfree (pea.username);
1309 } /* }}} int parse_part_encr_aes256 */
1310 /* #endif HAVE_LIBGCRYPT */
1312 #else /* if !HAVE_LIBGCRYPT */
1313 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1314 void **ret_buffer, size_t *ret_buffer_size, int flags)
1316 static int warning_has_been_printed = 0;
1320 size_t buffer_offset;
1325 buffer = *ret_buffer;
1326 buffer_size = *ret_buffer_size;
1329 /* parse_packet assures this minimum size. */
1330 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1332 BUFFER_READ (&ph.type, sizeof (ph.type));
1333 BUFFER_READ (&ph.length, sizeof (ph.length));
1334 ph_length = ntohs (ph.length);
1336 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1337 || (ph_length > buffer_size))
1339 ERROR ("network plugin: AES-256 encrypted part "
1340 "with invalid length received.");
1344 if (warning_has_been_printed == 0)
1346 WARNING ("network plugin: Received encrypted packet, but the network "
1347 "plugin was not linked with libgcrypt, so I cannot "
1348 "decrypt it. The part will be discarded.");
1349 warning_has_been_printed = 1;
1352 *ret_buffer += ph_length;
1353 *ret_buffer_size -= ph_length;
1356 } /* }}} int parse_part_encr_aes256 */
1357 #endif /* !HAVE_LIBGCRYPT */
1361 static int parse_packet (sockent_t *se, /* {{{ */
1362 void *buffer, size_t buffer_size, int flags,
1363 const char *username)
1367 value_list_t vl = VALUE_LIST_INIT;
1371 int packet_was_signed = (flags & PP_SIGNED);
1372 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1373 int printed_ignore_warning = 0;
1374 #endif /* HAVE_LIBGCRYPT */
1377 memset (&vl, '\0', sizeof (vl));
1378 memset (&n, '\0', sizeof (n));
1381 while ((status == 0) && (0 < buffer_size)
1382 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1384 uint16_t pkg_length;
1387 memcpy ((void *) &pkg_type,
1390 memcpy ((void *) &pkg_length,
1391 (void *) (buffer + sizeof (pkg_type)),
1392 sizeof (pkg_length));
1394 pkg_length = ntohs (pkg_length);
1395 pkg_type = ntohs (pkg_type);
1397 if (pkg_length > buffer_size)
1399 /* Ensure that this loop terminates eventually */
1400 if (pkg_length < (2 * sizeof (uint16_t)))
1403 if (pkg_type == TYPE_ENCR_AES256)
1405 status = parse_part_encr_aes256 (se,
1406 &buffer, &buffer_size, flags);
1409 ERROR ("network plugin: Decrypting AES256 "
1411 "with status %i.", status);
1416 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1417 && (packet_was_encrypted == 0))
1419 if (printed_ignore_warning == 0)
1421 INFO ("network plugin: Unencrypted packet or "
1422 "part has been ignored.");
1423 printed_ignore_warning = 1;
1425 buffer = ((char *) buffer) + pkg_length;
1428 #endif /* HAVE_LIBGCRYPT */
1429 else if (pkg_type == TYPE_SIGN_SHA256)
1431 status = parse_part_sign_sha256 (se,
1432 &buffer, &buffer_size, flags);
1435 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1437 "with status %i.", status);
1442 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1443 && (packet_was_encrypted == 0)
1444 && (packet_was_signed == 0))
1446 if (printed_ignore_warning == 0)
1448 INFO ("network plugin: Unsigned packet or "
1449 "part has been ignored.");
1450 printed_ignore_warning = 1;
1452 buffer = ((char *) buffer) + pkg_length;
1455 #endif /* HAVE_LIBGCRYPT */
1456 else if (pkg_type == TYPE_VALUES)
1458 status = parse_part_values (&buffer, &buffer_size,
1459 &vl.values, &vl.values_len);
1463 network_dispatch_values (&vl, username);
1467 else if (pkg_type == TYPE_TIME)
1470 status = parse_part_number (&buffer, &buffer_size,
1474 vl.time = TIME_T_TO_CDTIME_T (tmp);
1475 n.time = TIME_T_TO_CDTIME_T (tmp);
1478 else if (pkg_type == TYPE_TIME_HR)
1481 status = parse_part_number (&buffer, &buffer_size,
1485 vl.time = (cdtime_t) tmp;
1486 n.time = (cdtime_t) tmp;
1489 else if (pkg_type == TYPE_INTERVAL)
1492 status = parse_part_number (&buffer, &buffer_size,
1495 vl.interval = TIME_T_TO_CDTIME_T (tmp);
1497 else if (pkg_type == TYPE_INTERVAL_HR)
1500 status = parse_part_number (&buffer, &buffer_size,
1503 vl.interval = (cdtime_t) tmp;
1505 else if (pkg_type == TYPE_HOST)
1507 status = parse_part_string (&buffer, &buffer_size,
1508 vl.host, sizeof (vl.host));
1510 sstrncpy (n.host, vl.host, sizeof (n.host));
1512 else if (pkg_type == TYPE_PLUGIN)
1514 status = parse_part_string (&buffer, &buffer_size,
1515 vl.plugin, sizeof (vl.plugin));
1517 sstrncpy (n.plugin, vl.plugin,
1520 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1522 status = parse_part_string (&buffer, &buffer_size,
1524 sizeof (vl.plugin_instance));
1526 sstrncpy (n.plugin_instance,
1528 sizeof (n.plugin_instance));
1530 else if (pkg_type == TYPE_TYPE)
1532 status = parse_part_string (&buffer, &buffer_size,
1533 vl.type, sizeof (vl.type));
1535 sstrncpy (n.type, vl.type, sizeof (n.type));
1537 else if (pkg_type == TYPE_TYPE_INSTANCE)
1539 status = parse_part_string (&buffer, &buffer_size,
1541 sizeof (vl.type_instance));
1543 sstrncpy (n.type_instance, vl.type_instance,
1544 sizeof (n.type_instance));
1546 else if (pkg_type == TYPE_MESSAGE)
1548 status = parse_part_string (&buffer, &buffer_size,
1549 n.message, sizeof (n.message));
1555 else if ((n.severity != NOTIF_FAILURE)
1556 && (n.severity != NOTIF_WARNING)
1557 && (n.severity != NOTIF_OKAY))
1559 INFO ("network plugin: "
1560 "Ignoring notification with "
1561 "unknown severity %i.",
1564 else if (n.time <= 0)
1566 INFO ("network plugin: "
1567 "Ignoring notification with "
1570 else if (strlen (n.message) <= 0)
1572 INFO ("network plugin: "
1573 "Ignoring notification with "
1574 "an empty message.");
1578 network_dispatch_notification (&n);
1581 else if (pkg_type == TYPE_SEVERITY)
1584 status = parse_part_number (&buffer, &buffer_size,
1587 n.severity = (int) tmp;
1591 DEBUG ("network plugin: parse_packet: Unknown part"
1592 " type: 0x%04hx", pkg_type);
1593 buffer = ((char *) buffer) + pkg_length;
1595 } /* while (buffer_size > sizeof (part_header_t)) */
1597 if (status == 0 && buffer_size > 0)
1598 WARNING ("network plugin: parse_packet: Received truncated "
1599 "packet, try increasing `MaxPacketSize'");
1602 } /* }}} int parse_packet */
1604 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1613 sfree (sec->username);
1614 sfree (sec->password);
1615 if (sec->cypher != NULL)
1616 gcry_cipher_close (sec->cypher);
1618 } /* }}} void free_sockent_client */
1620 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1624 for (i = 0; i < ses->fd_num; i++)
1626 if (ses->fd[i] >= 0)
1635 sfree (ses->auth_file);
1636 fbh_destroy (ses->userdb);
1637 if (ses->cypher != NULL)
1638 gcry_cipher_close (ses->cypher);
1640 } /* }}} void free_sockent_server */
1642 static void sockent_destroy (sockent_t *se) /* {{{ */
1646 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1653 sfree (se->service);
1655 if (se->type == SOCKENT_TYPE_CLIENT)
1656 free_sockent_client (&se->data.client);
1658 free_sockent_server (&se->data.server);
1663 } /* }}} void sockent_destroy */
1666 * int network_set_ttl
1668 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1669 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1671 * The `struct addrinfo' is used to destinguish between unicast and multicast
1674 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1676 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1677 network_config_ttl);
1679 assert (se->type == SOCKENT_TYPE_CLIENT);
1681 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1684 if (ai->ai_family == AF_INET)
1686 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1689 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1690 optname = IP_MULTICAST_TTL;
1694 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1695 &network_config_ttl,
1696 sizeof (network_config_ttl)) != 0)
1699 ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
1700 sstrerror (errno, errbuf, sizeof (errbuf)));
1704 else if (ai->ai_family == AF_INET6)
1706 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1707 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1710 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1711 optname = IPV6_MULTICAST_HOPS;
1713 optname = IPV6_UNICAST_HOPS;
1715 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1716 &network_config_ttl,
1717 sizeof (network_config_ttl)) != 0)
1720 ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
1721 sstrerror (errno, errbuf,
1728 } /* int network_set_ttl */
1730 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1732 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1735 assert (se->type == SOCKENT_TYPE_CLIENT);
1737 if (ai->ai_family == AF_INET)
1739 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1741 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1743 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1744 /* If possible, use the "ip_mreqn" structure which has
1745 * an "interface index" member. Using the interface
1746 * index is preferred here, because of its similarity
1747 * to the way IPv6 handles this. Unfortunately, it
1748 * appears not to be portable. */
1749 struct ip_mreqn mreq;
1751 memset (&mreq, 0, sizeof (mreq));
1752 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1753 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1754 mreq.imr_ifindex = se->interface;
1756 struct ip_mreq mreq;
1758 memset (&mreq, 0, sizeof (mreq));
1759 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1760 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1763 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1764 &mreq, sizeof (mreq)) != 0)
1767 ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
1768 sstrerror (errno, errbuf, sizeof (errbuf)));
1775 else if (ai->ai_family == AF_INET6)
1777 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1779 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1781 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1783 sizeof (se->interface)) != 0)
1786 ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
1787 sstrerror (errno, errbuf,
1796 /* else: Not a multicast interface. */
1797 if (se->interface != 0)
1799 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1800 char interface_name[IFNAMSIZ];
1802 if (if_indextoname (se->interface, interface_name) == NULL)
1805 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1807 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1809 sizeof(interface_name)) == -1 )
1812 ERROR ("network plugin: setsockopt (bind-if): %s",
1813 sstrerror (errno, errbuf, sizeof (errbuf)));
1816 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1819 WARNING ("network plugin: Cannot set the interface on a unicast "
1821 # if !defined(SO_BINDTODEVICE)
1822 "the \"SO_BINDTODEVICE\" socket option "
1824 "the \"if_indextoname\" function "
1826 "is not available on your system.");
1832 } /* }}} network_set_interface */
1834 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1843 /* allow multiple sockets to use the same PORT number */
1844 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1845 &yes, sizeof(yes)) == -1) {
1847 ERROR ("network plugin: setsockopt (reuseaddr): %s",
1848 sstrerror (errno, errbuf, sizeof (errbuf)));
1852 DEBUG ("fd = %i; calling `bind'", fd);
1854 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1858 sstrerror (errno, errbuf, sizeof (errbuf)));
1862 if (ai->ai_family == AF_INET)
1864 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1865 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1867 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1868 struct ip_mreqn mreq;
1870 struct ip_mreq mreq;
1873 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1875 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1876 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1877 /* Set the interface using the interface index if
1878 * possible (available). Unfortunately, the struct
1879 * ip_mreqn is not portable. */
1880 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1881 mreq.imr_ifindex = interface_idx;
1883 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1886 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1887 &loop, sizeof (loop)) == -1)
1890 ERROR ("network plugin: setsockopt (multicast-loop): %s",
1891 sstrerror (errno, errbuf,
1896 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1897 &mreq, sizeof (mreq)) == -1)
1900 ERROR ("network plugin: setsockopt (add-membership): %s",
1901 sstrerror (errno, errbuf,
1909 else if (ai->ai_family == AF_INET6)
1911 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1912 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1913 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1915 struct ipv6_mreq mreq;
1917 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1919 memcpy (&mreq.ipv6mr_multiaddr,
1921 sizeof (addr->sin6_addr));
1923 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1924 * ipv6mr_interface may be set to zeroes to
1925 * choose the default multicast interface or to
1926 * the index of a particular multicast-capable
1927 * interface if the host is multihomed.
1928 * Membership is associ-associated with a
1929 * single interface; programs running on
1930 * multihomed hosts may need to join the same
1931 * group on more than one interface.*/
1932 mreq.ipv6mr_interface = interface_idx;
1934 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1935 &loop, sizeof (loop)) == -1)
1938 ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
1939 sstrerror (errno, errbuf,
1944 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1945 &mreq, sizeof (mreq)) == -1)
1948 ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
1949 sstrerror (errno, errbuf,
1958 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1959 /* if a specific interface was set, bind the socket to it. But to avoid
1960 * possible problems with multicast routing, only do that for non-multicast
1962 if (interface_idx != 0)
1964 char interface_name[IFNAMSIZ];
1966 if (if_indextoname (interface_idx, interface_name) == NULL)
1969 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1971 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1973 sizeof(interface_name)) == -1 )
1976 ERROR ("network plugin: setsockopt (bind-if): %s",
1977 sstrerror (errno, errbuf, sizeof (errbuf)));
1981 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1984 } /* int network_bind_socket */
1986 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1987 * or `SOCKENT_TYPE_SERVER' */
1988 static int sockent_init (sockent_t *se, int type) /* {{{ */
1993 memset (se, 0, sizeof (*se));
1995 se->type = SOCKENT_TYPE_CLIENT;
2001 if (type == SOCKENT_TYPE_SERVER)
2003 se->type = SOCKENT_TYPE_SERVER;
2004 se->data.server.fd = NULL;
2006 se->data.server.security_level = SECURITY_LEVEL_NONE;
2007 se->data.server.auth_file = NULL;
2008 se->data.server.userdb = NULL;
2009 se->data.server.cypher = NULL;
2014 se->data.client.fd = -1;
2015 se->data.client.addr = NULL;
2017 se->data.client.security_level = SECURITY_LEVEL_NONE;
2018 se->data.client.username = NULL;
2019 se->data.client.password = NULL;
2020 se->data.client.cypher = NULL;
2025 } /* }}} int sockent_init */
2027 /* Open the file descriptors for a initialized sockent structure. */
2028 static int sockent_open (sockent_t *se) /* {{{ */
2030 struct addrinfo ai_hints;
2031 struct addrinfo *ai_list, *ai_ptr;
2035 const char *service;
2040 /* Set up the security structures. */
2041 #if HAVE_LIBGCRYPT /* {{{ */
2042 if (se->type == SOCKENT_TYPE_CLIENT)
2044 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
2046 network_init_gcrypt ();
2048 if ((se->data.client.username == NULL)
2049 || (se->data.client.password == NULL))
2051 ERROR ("network plugin: Client socket with "
2052 "security requested, but no "
2053 "credentials are configured.");
2056 gcry_md_hash_buffer (GCRY_MD_SHA256,
2057 se->data.client.password_hash,
2058 se->data.client.password,
2059 strlen (se->data.client.password));
2062 else /* (se->type == SOCKENT_TYPE_SERVER) */
2064 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2066 network_init_gcrypt ();
2068 if (se->data.server.auth_file == NULL)
2070 ERROR ("network plugin: Server socket with "
2071 "security requested, but no "
2072 "password file is configured.");
2076 if (se->data.server.auth_file != NULL)
2078 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2079 if (se->data.server.userdb == NULL)
2081 ERROR ("network plugin: Reading password file "
2083 se->data.server.auth_file);
2084 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2089 #endif /* }}} HAVE_LIBGCRYPT */
2092 service = se->service;
2094 if (service == NULL)
2095 service = NET_DEFAULT_PORT;
2097 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
2100 memset (&ai_hints, 0, sizeof (ai_hints));
2101 ai_hints.ai_flags = 0;
2103 ai_hints.ai_flags |= AI_PASSIVE;
2105 #ifdef AI_ADDRCONFIG
2106 ai_hints.ai_flags |= AI_ADDRCONFIG;
2108 ai_hints.ai_family = AF_UNSPEC;
2109 ai_hints.ai_socktype = SOCK_DGRAM;
2110 ai_hints.ai_protocol = IPPROTO_UDP;
2112 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2115 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2116 (se->node == NULL) ? "(null)" : se->node,
2117 (se->service == NULL) ? "(null)" : se->service,
2118 gai_strerror (ai_return));
2122 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2126 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2130 tmp = realloc (se->data.server.fd,
2131 sizeof (*tmp) * (se->data.server.fd_num + 1));
2134 ERROR ("network plugin: realloc failed.");
2137 se->data.server.fd = tmp;
2138 tmp = se->data.server.fd + se->data.server.fd_num;
2140 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2141 ai_ptr->ai_protocol);
2145 ERROR ("network plugin: socket(2) failed: %s",
2146 sstrerror (errno, errbuf,
2151 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2159 se->data.server.fd_num++;
2161 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2162 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2164 se->data.client.fd = socket (ai_ptr->ai_family,
2165 ai_ptr->ai_socktype,
2166 ai_ptr->ai_protocol);
2167 if (se->data.client.fd < 0)
2170 ERROR ("network plugin: socket(2) failed: %s",
2171 sstrerror (errno, errbuf,
2176 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2177 if (se->data.client.addr == NULL)
2179 ERROR ("network plugin: malloc failed.");
2180 close (se->data.client.fd);
2181 se->data.client.fd = -1;
2185 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2186 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2187 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2188 se->data.client.addrlen = ai_ptr->ai_addrlen;
2190 network_set_ttl (se, ai_ptr);
2191 network_set_interface (se, ai_ptr);
2193 /* We don't open more than one write-socket per
2194 * node/service pair.. */
2196 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2197 } /* for (ai_list) */
2199 freeaddrinfo (ai_list);
2201 /* Check if all went well. */
2202 if (se->type == SOCKENT_TYPE_SERVER)
2204 if (se->data.server.fd_num <= 0)
2207 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2209 if (se->data.client.fd < 0)
2214 } /* }}} int sockent_open */
2216 /* Add a sockent to the global list of sockets */
2217 static int sockent_add (sockent_t *se) /* {{{ */
2219 sockent_t *last_ptr;
2224 if (se->type == SOCKENT_TYPE_SERVER)
2229 tmp = realloc (listen_sockets_pollfd,
2230 sizeof (*tmp) * (listen_sockets_num
2231 + se->data.server.fd_num));
2234 ERROR ("network plugin: realloc failed.");
2237 listen_sockets_pollfd = tmp;
2238 tmp = listen_sockets_pollfd + listen_sockets_num;
2240 for (i = 0; i < se->data.server.fd_num; i++)
2242 memset (tmp + i, 0, sizeof (*tmp));
2243 tmp[i].fd = se->data.server.fd[i];
2244 tmp[i].events = POLLIN | POLLPRI;
2248 listen_sockets_num += se->data.server.fd_num;
2250 if (listen_sockets == NULL)
2252 listen_sockets = se;
2255 last_ptr = listen_sockets;
2257 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2259 if (sending_sockets == NULL)
2261 sending_sockets = se;
2264 last_ptr = sending_sockets;
2267 while (last_ptr->next != NULL)
2268 last_ptr = last_ptr->next;
2269 last_ptr->next = se;
2272 } /* }}} int sockent_add */
2274 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2278 receive_list_entry_t *ent;
2281 /* Lock and wait for more data to come in */
2282 pthread_mutex_lock (&receive_list_lock);
2283 while ((listen_loop == 0)
2284 && (receive_list_head == NULL))
2285 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2287 /* Remove the head entry and unlock */
2288 ent = receive_list_head;
2290 receive_list_head = ent->next;
2291 receive_list_length--;
2292 pthread_mutex_unlock (&receive_list_lock);
2294 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2295 * because we dispatch all missing packets before shutting down. */
2299 /* Look for the correct `sockent_t' */
2300 se = listen_sockets;
2305 for (i = 0; i < se->data.server.fd_num; i++)
2306 if (se->data.server.fd[i] == ent->fd)
2309 if (i < se->data.server.fd_num)
2317 ERROR ("network plugin: Got packet from FD %i, but can't "
2318 "find an appropriate socket entry.",
2325 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2326 /* username = */ NULL);
2332 } /* }}} void *dispatch_thread */
2334 static int network_receive (void) /* {{{ */
2336 char buffer[network_config_packet_size];
2342 receive_list_entry_t *private_list_head;
2343 receive_list_entry_t *private_list_tail;
2344 uint64_t private_list_length;
2346 assert (listen_sockets_num > 0);
2348 private_list_head = NULL;
2349 private_list_tail = NULL;
2350 private_list_length = 0;
2352 while (listen_loop == 0)
2354 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2361 ERROR ("poll failed: %s",
2362 sstrerror (errno, errbuf, sizeof (errbuf)));
2366 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2368 receive_list_entry_t *ent;
2370 if ((listen_sockets_pollfd[i].revents
2371 & (POLLIN | POLLPRI)) == 0)
2375 buffer_len = recv (listen_sockets_pollfd[i].fd,
2376 buffer, sizeof (buffer),
2381 ERROR ("recv failed: %s",
2382 sstrerror (errno, errbuf,
2387 stats_octets_rx += ((uint64_t) buffer_len);
2390 /* TODO: Possible performance enhancement: Do not free
2391 * these entries in the dispatch thread but put them in
2392 * another list, so we don't have to allocate more and
2393 * more of these structures. */
2394 ent = malloc (sizeof (receive_list_entry_t));
2397 ERROR ("network plugin: malloc failed.");
2400 memset (ent, 0, sizeof (receive_list_entry_t));
2401 ent->data = malloc (network_config_packet_size);
2402 if (ent->data == NULL)
2405 ERROR ("network plugin: malloc failed.");
2408 ent->fd = listen_sockets_pollfd[i].fd;
2411 memcpy (ent->data, buffer, buffer_len);
2412 ent->data_len = buffer_len;
2414 if (private_list_head == NULL)
2415 private_list_head = ent;
2417 private_list_tail->next = ent;
2418 private_list_tail = ent;
2419 private_list_length++;
2421 /* Do not block here. Blocking here has led to
2422 * insufficient performance in the past. */
2423 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2425 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2426 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2428 if (receive_list_head == NULL)
2429 receive_list_head = private_list_head;
2431 receive_list_tail->next = private_list_head;
2432 receive_list_tail = private_list_tail;
2433 receive_list_length += private_list_length;
2435 pthread_cond_signal (&receive_list_cond);
2436 pthread_mutex_unlock (&receive_list_lock);
2438 private_list_head = NULL;
2439 private_list_tail = NULL;
2440 private_list_length = 0;
2442 } /* for (listen_sockets_pollfd) */
2443 } /* while (listen_loop == 0) */
2445 /* Make sure everything is dispatched before exiting. */
2446 if (private_list_head != NULL)
2448 pthread_mutex_lock (&receive_list_lock);
2450 if (receive_list_head == NULL)
2451 receive_list_head = private_list_head;
2453 receive_list_tail->next = private_list_head;
2454 receive_list_tail = private_list_tail;
2455 receive_list_length += private_list_length;
2457 private_list_head = NULL;
2458 private_list_tail = NULL;
2459 private_list_length = 0;
2461 pthread_cond_signal (&receive_list_cond);
2462 pthread_mutex_unlock (&receive_list_lock);
2466 } /* }}} int network_receive */
2468 static void *receive_thread (void __attribute__((unused)) *arg)
2470 return (network_receive () ? (void *) 1 : (void *) 0);
2471 } /* void *receive_thread */
2473 static void network_init_buffer (void)
2475 memset (send_buffer, 0, network_config_packet_size);
2476 send_buffer_ptr = send_buffer;
2477 send_buffer_fill = 0;
2479 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2480 } /* int network_init_buffer */
2482 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2483 const char *buffer, size_t buffer_size)
2489 status = sendto (se->data.client.fd, buffer, buffer_size,
2491 (struct sockaddr *) se->data.client.addr,
2492 se->data.client.addrlen);
2498 ERROR ("network plugin: sendto failed: %s",
2499 sstrerror (errno, errbuf,
2506 } /* }}} void networt_send_buffer_plain */
2509 #define BUFFER_ADD(p,s) do { \
2510 memcpy (buffer + buffer_offset, (p), (s)); \
2511 buffer_offset += (s); \
2514 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2515 const char *in_buffer, size_t in_buffer_size)
2517 part_signature_sha256_t ps;
2518 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2519 size_t buffer_offset;
2520 size_t username_len;
2524 unsigned char *hash;
2527 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2530 ERROR ("network plugin: Creating HMAC object failed: %s",
2531 gcry_strerror (err));
2535 err = gcry_md_setkey (hd, se->data.client.password,
2536 strlen (se->data.client.password));
2539 ERROR ("network plugin: gcry_md_setkey failed: %s",
2540 gcry_strerror (err));
2545 username_len = strlen (se->data.client.username);
2546 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2548 ERROR ("network plugin: Username too long: %s",
2549 se->data.client.username);
2553 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2554 se->data.client.username, username_len);
2555 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2556 in_buffer, in_buffer_size);
2558 /* Initialize the `ps' structure. */
2559 memset (&ps, 0, sizeof (ps));
2560 ps.head.type = htons (TYPE_SIGN_SHA256);
2561 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2563 /* Calculate the hash value. */
2564 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2565 username_len + in_buffer_size);
2566 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2569 ERROR ("network plugin: gcry_md_read failed.");
2573 memcpy (ps.hash, hash, sizeof (ps.hash));
2575 /* Add the header */
2578 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2579 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2580 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2582 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2587 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2588 networt_send_buffer_plain (se, buffer, buffer_offset);
2589 } /* }}} void networt_send_buffer_signed */
2591 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2592 const char *in_buffer, size_t in_buffer_size)
2594 part_encryption_aes256_t pea;
2595 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2597 size_t buffer_offset;
2599 size_t username_len;
2601 gcry_cipher_hd_t cypher;
2603 /* Initialize the header fields */
2604 memset (&pea, 0, sizeof (pea));
2605 pea.head.type = htons (TYPE_ENCR_AES256);
2607 pea.username = se->data.client.username;
2609 username_len = strlen (pea.username);
2610 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2612 ERROR ("network plugin: Username too long: %s", pea.username);
2616 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2617 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2618 - sizeof (pea.hash);
2620 assert (buffer_size <= sizeof (buffer));
2621 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2622 "buffer_size = %zu;", buffer_size);
2624 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2625 + username_len + in_buffer_size));
2626 pea.username_length = htons ((uint16_t) username_len);
2628 /* Chose a random initialization vector. */
2629 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2631 /* Create hash of the payload */
2632 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2634 /* Initialize the buffer */
2636 memset (buffer, 0, sizeof (buffer));
2639 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2640 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2641 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2642 BUFFER_ADD (pea.username, username_len);
2643 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2644 assert (buffer_offset == header_size);
2645 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2646 BUFFER_ADD (in_buffer, in_buffer_size);
2648 assert (buffer_offset == buffer_size);
2650 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2651 se->data.client.password);
2655 /* Encrypt the buffer in-place */
2656 err = gcry_cipher_encrypt (cypher,
2657 buffer + header_size,
2658 buffer_size - header_size,
2659 /* in = */ NULL, /* in len = */ 0);
2662 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2663 gcry_strerror (err));
2667 /* Send it out without further modifications */
2668 networt_send_buffer_plain (se, buffer, buffer_size);
2669 } /* }}} void networt_send_buffer_encrypted */
2671 #endif /* HAVE_LIBGCRYPT */
2673 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2677 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2679 for (se = sending_sockets; se != NULL; se = se->next)
2682 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2683 networt_send_buffer_encrypted (se, buffer, buffer_len);
2684 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2685 networt_send_buffer_signed (se, buffer, buffer_len);
2686 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2687 #endif /* HAVE_LIBGCRYPT */
2688 networt_send_buffer_plain (se, buffer, buffer_len);
2689 } /* for (sending_sockets) */
2690 } /* }}} void network_send_buffer */
2692 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2693 value_list_t *vl_def,
2694 const data_set_t *ds, const value_list_t *vl)
2696 char *buffer_orig = buffer;
2698 if (strcmp (vl_def->host, vl->host) != 0)
2700 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2701 vl->host, strlen (vl->host)) != 0)
2703 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2706 if (vl_def->time != vl->time)
2708 if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
2709 (uint64_t) vl->time))
2711 vl_def->time = vl->time;
2714 if (vl_def->interval != vl->interval)
2716 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
2717 (uint64_t) vl->interval))
2719 vl_def->interval = vl->interval;
2722 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2724 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2725 vl->plugin, strlen (vl->plugin)) != 0)
2727 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2730 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2732 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2733 vl->plugin_instance,
2734 strlen (vl->plugin_instance)) != 0)
2736 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2739 if (strcmp (vl_def->type, vl->type) != 0)
2741 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2742 vl->type, strlen (vl->type)) != 0)
2744 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2747 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2749 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2751 strlen (vl->type_instance)) != 0)
2753 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2756 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2759 return (buffer - buffer_orig);
2760 } /* }}} int add_to_buffer */
2762 static void flush_buffer (void)
2764 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2767 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2769 stats_octets_tx += ((uint64_t) send_buffer_fill);
2772 network_init_buffer ();
2775 static int network_write (const data_set_t *ds, const value_list_t *vl,
2776 user_data_t __attribute__((unused)) *user_data)
2780 if (!check_send_okay (vl))
2783 char name[6*DATA_MAX_NAME_LEN];
2784 FORMAT_VL (name, sizeof (name), vl);
2785 name[sizeof (name) - 1] = 0;
2786 DEBUG ("network plugin: network_write: "
2787 "NOT sending %s.", name);
2789 /* Counter is not protected by another lock and may be reached by
2790 * multiple threads */
2791 pthread_mutex_lock (&stats_lock);
2792 stats_values_not_sent++;
2793 pthread_mutex_unlock (&stats_lock);
2797 uc_meta_data_add_unsigned_int (vl,
2798 "network:time_sent", (uint64_t) vl->time);
2800 pthread_mutex_lock (&send_buffer_lock);
2802 status = add_to_buffer (send_buffer_ptr,
2803 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2808 /* status == bytes added to the buffer */
2809 send_buffer_fill += status;
2810 send_buffer_ptr += status;
2812 stats_values_sent++;
2818 status = add_to_buffer (send_buffer_ptr,
2819 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2825 send_buffer_fill += status;
2826 send_buffer_ptr += status;
2828 stats_values_sent++;
2834 ERROR ("network plugin: Unable to append to the "
2835 "buffer for some weird reason");
2837 else if ((network_config_packet_size - send_buffer_fill) < 15)
2842 pthread_mutex_unlock (&send_buffer_lock);
2844 return ((status < 0) ? -1 : 0);
2845 } /* int network_write */
2847 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2850 if ((ci->values_num != 1)
2851 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2852 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2854 ERROR ("network plugin: The `%s' config option needs "
2855 "exactly one boolean argument.", ci->key);
2859 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2861 if (ci->values[0].value.boolean)
2868 char *str = ci->values[0].value.string;
2872 else if (IS_FALSE (str))
2876 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2877 "option as boolean value.",
2884 } /* }}} int network_config_set_boolean */
2886 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2889 if ((ci->values_num != 1)
2890 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2892 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2893 "one numeric argument.");
2897 tmp = (int) ci->values[0].value.number;
2898 if ((tmp > 0) && (tmp <= 255))
2899 network_config_ttl = tmp;
2902 } /* }}} int network_config_set_ttl */
2904 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2907 if ((ci->values_num != 1)
2908 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2910 WARNING ("network plugin: The `Interface' config option needs exactly "
2911 "one string argument.");
2915 if (interface == NULL)
2918 *interface = if_nametoindex (ci->values[0].value.string);
2921 } /* }}} int network_config_set_interface */
2923 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2926 if ((ci->values_num != 1)
2927 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2929 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2930 "one numeric argument.");
2934 tmp = (int) ci->values[0].value.number;
2935 if ((tmp >= 1024) && (tmp <= 65535))
2936 network_config_packet_size = tmp;
2939 } /* }}} int network_config_set_buffer_size */
2942 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2946 if ((ci->values_num != 1)
2947 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2949 WARNING ("network plugin: The `%s' config option needs exactly "
2950 "one string argument.", ci->key);
2954 tmp = strdup (ci->values[0].value.string);
2958 sfree (*ret_string);
2962 } /* }}} int network_config_set_string */
2963 #endif /* HAVE_LIBGCRYPT */
2966 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2970 if ((ci->values_num != 1)
2971 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2973 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2974 "one string argument.");
2978 str = ci->values[0].value.string;
2979 if (strcasecmp ("Encrypt", str) == 0)
2980 *retval = SECURITY_LEVEL_ENCRYPT;
2981 else if (strcasecmp ("Sign", str) == 0)
2982 *retval = SECURITY_LEVEL_SIGN;
2983 else if (strcasecmp ("None", str) == 0)
2984 *retval = SECURITY_LEVEL_NONE;
2987 WARNING ("network plugin: Unknown security level: %s.", str);
2992 } /* }}} int network_config_set_security_level */
2993 #endif /* HAVE_LIBGCRYPT */
2995 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
3001 if ((ci->values_num < 1) || (ci->values_num > 2)
3002 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3003 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3005 ERROR ("network plugin: The `%s' config option needs "
3006 "one or two string arguments.", ci->key);
3010 se = malloc (sizeof (*se));
3013 ERROR ("network plugin: malloc failed.");
3016 sockent_init (se, SOCKENT_TYPE_SERVER);
3018 se->node = strdup (ci->values[0].value.string);
3019 if (ci->values_num >= 2)
3020 se->service = strdup (ci->values[1].value.string);
3022 for (i = 0; i < ci->children_num; i++)
3024 oconfig_item_t *child = ci->children + i;
3027 if (strcasecmp ("AuthFile", child->key) == 0)
3028 network_config_set_string (child, &se->data.server.auth_file);
3029 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3030 network_config_set_security_level (child,
3031 &se->data.server.security_level);
3033 #endif /* HAVE_LIBGCRYPT */
3034 if (strcasecmp ("Interface", child->key) == 0)
3035 network_config_set_interface (child,
3039 WARNING ("network plugin: Option `%s' is not allowed here.",
3045 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3046 && (se->data.server.auth_file == NULL))
3048 ERROR ("network plugin: A security level higher than `none' was "
3049 "requested, but no AuthFile option was given. Cowardly refusing to "
3050 "open this socket!");
3051 sockent_destroy (se);
3054 #endif /* HAVE_LIBGCRYPT */
3056 status = sockent_open (se);
3059 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
3060 sockent_destroy (se);
3064 status = sockent_add (se);
3067 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3068 sockent_destroy (se);
3073 } /* }}} int network_config_add_listen */
3075 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3081 if ((ci->values_num < 1) || (ci->values_num > 2)
3082 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3083 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3085 ERROR ("network plugin: The `%s' config option needs "
3086 "one or two string arguments.", ci->key);
3090 se = malloc (sizeof (*se));
3093 ERROR ("network plugin: malloc failed.");
3096 sockent_init (se, SOCKENT_TYPE_CLIENT);
3098 se->node = strdup (ci->values[0].value.string);
3099 if (ci->values_num >= 2)
3100 se->service = strdup (ci->values[1].value.string);
3102 for (i = 0; i < ci->children_num; i++)
3104 oconfig_item_t *child = ci->children + i;
3107 if (strcasecmp ("Username", child->key) == 0)
3108 network_config_set_string (child, &se->data.client.username);
3109 else if (strcasecmp ("Password", child->key) == 0)
3110 network_config_set_string (child, &se->data.client.password);
3111 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3112 network_config_set_security_level (child,
3113 &se->data.client.security_level);
3115 #endif /* HAVE_LIBGCRYPT */
3116 if (strcasecmp ("Interface", child->key) == 0)
3117 network_config_set_interface (child,
3121 WARNING ("network plugin: Option `%s' is not allowed here.",
3127 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3128 && ((se->data.client.username == NULL)
3129 || (se->data.client.password == NULL)))
3131 ERROR ("network plugin: A security level higher than `none' was "
3132 "requested, but no Username or Password option was given. "
3133 "Cowardly refusing to open this socket!");
3134 sockent_destroy (se);
3137 #endif /* HAVE_LIBGCRYPT */
3139 status = sockent_open (se);
3142 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3143 sockent_destroy (se);
3147 status = sockent_add (se);
3150 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3151 sockent_destroy (se);
3156 } /* }}} int network_config_add_server */
3158 static int network_config (oconfig_item_t *ci) /* {{{ */
3162 for (i = 0; i < ci->children_num; i++)
3164 oconfig_item_t *child = ci->children + i;
3166 if (strcasecmp ("Listen", child->key) == 0)
3167 network_config_add_listen (child);
3168 else if (strcasecmp ("Server", child->key) == 0)
3169 network_config_add_server (child);
3170 else if (strcasecmp ("TimeToLive", child->key) == 0)
3171 network_config_set_ttl (child);
3172 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3173 network_config_set_buffer_size (child);
3174 else if (strcasecmp ("Forward", child->key) == 0)
3175 network_config_set_boolean (child, &network_config_forward);
3176 else if (strcasecmp ("ReportStats", child->key) == 0)
3177 network_config_set_boolean (child, &network_config_stats);
3180 WARNING ("network plugin: Option `%s' is not allowed here.",
3186 } /* }}} int network_config */
3188 static int network_notification (const notification_t *n,
3189 user_data_t __attribute__((unused)) *user_data)
3191 char buffer[network_config_packet_size];
3192 char *buffer_ptr = buffer;
3193 int buffer_free = sizeof (buffer);
3196 if (!check_send_notify_okay (n))
3199 memset (buffer, 0, sizeof (buffer));
3201 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3202 (uint64_t) n->time);
3206 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3207 (uint64_t) n->severity);
3211 if (strlen (n->host) > 0)
3213 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3214 n->host, strlen (n->host));
3219 if (strlen (n->plugin) > 0)
3221 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3222 n->plugin, strlen (n->plugin));
3227 if (strlen (n->plugin_instance) > 0)
3229 status = write_part_string (&buffer_ptr, &buffer_free,
3230 TYPE_PLUGIN_INSTANCE,
3231 n->plugin_instance, strlen (n->plugin_instance));
3236 if (strlen (n->type) > 0)
3238 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3239 n->type, strlen (n->type));
3244 if (strlen (n->type_instance) > 0)
3246 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3247 n->type_instance, strlen (n->type_instance));
3252 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3253 n->message, strlen (n->message));
3257 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3260 } /* int network_notification */
3262 static int network_shutdown (void)
3266 /* Kill the listening thread */
3267 if (receive_thread_running != 0)
3269 INFO ("network plugin: Stopping receive thread.");
3270 pthread_kill (receive_thread_id, SIGTERM);
3271 pthread_join (receive_thread_id, NULL /* no return value */);
3272 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3273 receive_thread_running = 0;
3276 /* Shutdown the dispatching thread */
3277 if (dispatch_thread_running != 0)
3279 INFO ("network plugin: Stopping dispatch thread.");
3280 pthread_mutex_lock (&receive_list_lock);
3281 pthread_cond_broadcast (&receive_list_cond);
3282 pthread_mutex_unlock (&receive_list_lock);
3283 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3284 dispatch_thread_running = 0;
3287 sockent_destroy (listen_sockets);
3289 if (send_buffer_fill > 0)
3292 sfree (send_buffer);
3294 /* TODO: Close `sending_sockets' */
3296 plugin_unregister_config ("network");
3297 plugin_unregister_init ("network");
3298 plugin_unregister_write ("network");
3299 plugin_unregister_shutdown ("network");
3302 } /* int network_shutdown */
3304 static int network_stats_read (void) /* {{{ */
3306 derive_t copy_octets_rx;
3307 derive_t copy_octets_tx;
3308 derive_t copy_packets_rx;
3309 derive_t copy_packets_tx;
3310 derive_t copy_values_dispatched;
3311 derive_t copy_values_not_dispatched;
3312 derive_t copy_values_sent;
3313 derive_t copy_values_not_sent;
3314 derive_t copy_receive_list_length;
3315 value_list_t vl = VALUE_LIST_INIT;
3318 copy_octets_rx = stats_octets_rx;
3319 copy_octets_tx = stats_octets_tx;
3320 copy_packets_rx = stats_packets_rx;
3321 copy_packets_tx = stats_packets_tx;
3322 copy_values_dispatched = stats_values_dispatched;
3323 copy_values_not_dispatched = stats_values_not_dispatched;
3324 copy_values_sent = stats_values_sent;
3325 copy_values_not_sent = stats_values_not_sent;
3326 copy_receive_list_length = receive_list_length;
3328 /* Initialize `vl' */
3332 vl.interval = interval_g;
3333 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3334 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3336 /* Octets received / sent */
3337 vl.values[0].derive = (derive_t) copy_octets_rx;
3338 vl.values[1].derive = (derive_t) copy_octets_tx;
3339 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3340 plugin_dispatch_values_secure (&vl);
3342 /* Packets received / send */
3343 vl.values[0].derive = (derive_t) copy_packets_rx;
3344 vl.values[1].derive = (derive_t) copy_packets_tx;
3345 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3346 plugin_dispatch_values_secure (&vl);
3348 /* Values (not) dispatched and (not) send */
3349 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3352 vl.values[0].derive = (derive_t) copy_values_dispatched;
3353 sstrncpy (vl.type_instance, "dispatch-accepted",
3354 sizeof (vl.type_instance));
3355 plugin_dispatch_values_secure (&vl);
3357 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3358 sstrncpy (vl.type_instance, "dispatch-rejected",
3359 sizeof (vl.type_instance));
3360 plugin_dispatch_values_secure (&vl);
3362 vl.values[0].derive = (derive_t) copy_values_sent;
3363 sstrncpy (vl.type_instance, "send-accepted",
3364 sizeof (vl.type_instance));
3365 plugin_dispatch_values_secure (&vl);
3367 vl.values[0].derive = (derive_t) copy_values_not_sent;
3368 sstrncpy (vl.type_instance, "send-rejected",
3369 sizeof (vl.type_instance));
3370 plugin_dispatch_values_secure (&vl);
3372 /* Receive queue length */
3373 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3374 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3375 vl.type_instance[0] = 0;
3376 plugin_dispatch_values_secure (&vl);
3379 } /* }}} int network_stats_read */
3381 static int network_init (void)
3383 static _Bool have_init = 0;
3385 /* Check if we were already initialized. If so, just return - there's
3386 * nothing more to do (for now, that is). */
3392 network_init_gcrypt ();
3395 if (network_config_stats != 0)
3396 plugin_register_read ("network", network_stats_read);
3398 plugin_register_shutdown ("network", network_shutdown);
3400 send_buffer = malloc (network_config_packet_size);
3401 if (send_buffer == NULL)
3403 ERROR ("network plugin: malloc failed.");
3406 network_init_buffer ();
3408 /* setup socket(s) and so on */
3409 if (sending_sockets != NULL)
3411 plugin_register_write ("network", network_write,
3412 /* user_data = */ NULL);
3413 plugin_register_notification ("network", network_notification,
3414 /* user_data = */ NULL);
3417 /* If no threads need to be started, return here. */
3418 if ((listen_sockets_num == 0)
3419 || ((dispatch_thread_running != 0)
3420 && (receive_thread_running != 0)))
3423 if (dispatch_thread_running == 0)
3426 status = pthread_create (&dispatch_thread_id,
3427 NULL /* no attributes */,
3429 NULL /* no argument */);
3433 ERROR ("network: pthread_create failed: %s",
3434 sstrerror (errno, errbuf,
3439 dispatch_thread_running = 1;
3443 if (receive_thread_running == 0)
3446 status = pthread_create (&receive_thread_id,
3447 NULL /* no attributes */,
3449 NULL /* no argument */);
3453 ERROR ("network: pthread_create failed: %s",
3454 sstrerror (errno, errbuf,
3459 receive_thread_running = 1;
3464 } /* int network_init */
3467 * The flush option of the network plugin cannot flush individual identifiers.
3468 * All the values are added to a buffer and sent when the buffer is full, the
3469 * requested value may or may not be in there, it's not worth finding out. We
3470 * just send the buffer if `flush' is called - if the requested value was in
3471 * there, good. If not, well, then there is nothing to flush.. -octo
3473 static int network_flush (__attribute__((unused)) cdtime_t timeout,
3474 __attribute__((unused)) const char *identifier,
3475 __attribute__((unused)) user_data_t *user_data)
3477 pthread_mutex_lock (&send_buffer_lock);
3479 if (send_buffer_fill > 0)
3482 pthread_mutex_unlock (&send_buffer_lock);
3485 } /* int network_flush */
3487 void module_register (void)
3489 plugin_register_complex_config ("network", network_config);
3490 plugin_register_init ("network", network_init);
3491 plugin_register_flush ("network", network_flush,
3492 /* user_data = */ NULL);
3493 } /* void module_register */
3495 /* vim: set fdm=marker : */