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 static size_t network_config_packet_size = 1024;
280 static int network_config_forward = 0;
281 static int network_config_stats = 0;
283 static sockent_t *sending_sockets = NULL;
285 static receive_list_entry_t *receive_list_head = NULL;
286 static receive_list_entry_t *receive_list_tail = NULL;
287 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
288 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
289 static uint64_t receive_list_length = 0;
291 static sockent_t *listen_sockets = NULL;
292 static struct pollfd *listen_sockets_pollfd = NULL;
293 static size_t listen_sockets_num = 0;
295 /* The receive and dispatch threads will run as long as `listen_loop' is set to
297 static int listen_loop = 0;
298 static int receive_thread_running = 0;
299 static pthread_t receive_thread_id;
300 static int dispatch_thread_running = 0;
301 static pthread_t dispatch_thread_id;
303 /* Buffer in which to-be-sent network packets are constructed. */
304 static char *send_buffer;
305 static char *send_buffer_ptr;
306 static int send_buffer_fill;
307 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
308 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
310 /* XXX: These counters are incremented from one place only. The spot in which
311 * the values are incremented is either only reachable by one thread (the
312 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
313 * example). Only if neither is true, the stats_lock is acquired. The counters
314 * are always read without holding a lock in the hope that writing 8 bytes to
315 * memory is an atomic operation. */
316 static uint64_t stats_octets_rx = 0;
317 static uint64_t stats_octets_tx = 0;
318 static uint64_t stats_packets_rx = 0;
319 static uint64_t stats_packets_tx = 0;
320 static uint64_t stats_values_dispatched = 0;
321 static uint64_t stats_values_not_dispatched = 0;
322 static uint64_t stats_values_sent = 0;
323 static uint64_t stats_values_not_sent = 0;
324 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
329 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
331 uint64_t time_sent = 0;
334 status = uc_meta_data_get_unsigned_int (vl,
335 "network:time_sent", &time_sent);
337 /* This is a value we already sent. Don't allow it to be received again in
338 * order to avoid looping. */
339 if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
343 } /* }}} _Bool check_receive_okay */
345 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
347 _Bool received = false;
350 if (network_config_forward != 0)
353 if (vl->meta == NULL)
356 status = meta_data_get_boolean (vl->meta, "network:received", &received);
357 if (status == -ENOENT)
359 else if (status != 0)
361 ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
362 "with status %i.", status);
366 /* By default, only *send* value lists that were not *received* by the
369 } /* }}} _Bool check_send_okay */
371 static _Bool check_notify_received (const notification_t *n) /* {{{ */
373 notification_meta_t *ptr;
375 for (ptr = n->meta; ptr != NULL; ptr = ptr->next)
376 if ((strcmp ("network:received", ptr->name) == 0)
377 && (ptr->type == NM_TYPE_BOOLEAN))
378 return ((_Bool) ptr->nm_value.nm_boolean);
381 } /* }}} _Bool check_notify_received */
383 static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
385 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
391 received = check_notify_received (n);
393 if (network_config_forward && received)
395 c_complain_once (LOG_ERR, &complain_forwarding,
396 "network plugin: A notification has been received via the network "
397 "forwarding if enabled. Forwarding of notifications is currently "
398 "not supported, because there is not loop-deteciton available. "
399 "Please contact the collectd mailing list if you need this "
403 /* By default, only *send* value lists that were not *received* by the
406 } /* }}} _Bool check_send_notify_okay */
408 static int network_dispatch_values (value_list_t *vl, /* {{{ */
409 const char *username)
414 || (strlen (vl->host) <= 0)
415 || (strlen (vl->plugin) <= 0)
416 || (strlen (vl->type) <= 0))
419 if (!check_receive_okay (vl))
422 char name[6*DATA_MAX_NAME_LEN];
423 FORMAT_VL (name, sizeof (name), vl);
424 name[sizeof (name) - 1] = 0;
425 DEBUG ("network plugin: network_dispatch_values: "
426 "NOT dispatching %s.", name);
428 stats_values_not_dispatched++;
432 assert (vl->meta == NULL);
434 vl->meta = meta_data_create ();
435 if (vl->meta == NULL)
437 ERROR ("network plugin: meta_data_create failed.");
441 status = meta_data_add_boolean (vl->meta, "network:received", true);
444 ERROR ("network plugin: meta_data_add_boolean failed.");
445 meta_data_destroy (vl->meta);
450 if (username != NULL)
452 status = meta_data_add_string (vl->meta, "network:username", username);
455 ERROR ("network plugin: meta_data_add_string failed.");
456 meta_data_destroy (vl->meta);
462 plugin_dispatch_values_secure (vl);
463 stats_values_dispatched++;
465 meta_data_destroy (vl->meta);
469 } /* }}} int network_dispatch_values */
471 static int network_dispatch_notification (notification_t *n) /* {{{ */
475 assert (n->meta == NULL);
477 status = plugin_notification_meta_add_boolean (n, "network:received", 1);
480 ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
481 plugin_notification_meta_free (n->meta);
486 status = plugin_dispatch_notification (n);
488 plugin_notification_meta_free (n->meta);
492 } /* }}} int network_dispatch_notification */
495 static void network_init_gcrypt (void) /* {{{ */
497 /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
498 * Because you can't know in a library whether another library has
499 * already initialized the library */
500 if (gcry_control (GCRYCTL_ANY_INITIALIZATION_P))
503 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
504 * To ensure thread-safety, it's important to set GCRYCTL_SET_THREAD_CBS
505 * *before* initalizing Libgcrypt with gcry_check_version(), which itself must
506 * be called before any other gcry_* function. GCRYCTL_ANY_INITIALIZATION_P
507 * above doesn't count, as it doesn't implicitly initalize Libgcrypt.
509 * tl;dr: keep all these gry_* statements in this exact order please. */
510 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
511 gcry_check_version (NULL);
512 gcry_control (GCRYCTL_INIT_SECMEM, 32768);
513 gcry_control (GCRYCTL_INITIALIZATION_FINISHED);
514 } /* }}} void network_init_gcrypt */
516 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
517 const void *iv, size_t iv_size, const char *username)
520 gcry_cipher_hd_t *cyper_ptr;
521 unsigned char password_hash[32];
523 if (se->type == SOCKENT_TYPE_CLIENT)
525 cyper_ptr = &se->data.client.cypher;
526 memcpy (password_hash, se->data.client.password_hash,
527 sizeof (password_hash));
533 cyper_ptr = &se->data.server.cypher;
535 if (username == NULL)
538 secret = fbh_get (se->data.server.userdb, username);
542 gcry_md_hash_buffer (GCRY_MD_SHA256,
544 secret, strlen (secret));
549 if (*cyper_ptr == NULL)
551 err = gcry_cipher_open (cyper_ptr,
552 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
555 ERROR ("network plugin: gcry_cipher_open returned: %s",
556 gcry_strerror (err));
563 gcry_cipher_reset (*cyper_ptr);
565 assert (*cyper_ptr != NULL);
567 err = gcry_cipher_setkey (*cyper_ptr,
568 password_hash, sizeof (password_hash));
571 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
572 gcry_strerror (err));
573 gcry_cipher_close (*cyper_ptr);
578 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
581 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
582 gcry_strerror (err));
583 gcry_cipher_close (*cyper_ptr);
589 } /* }}} int network_get_aes256_cypher */
590 #endif /* HAVE_LIBGCRYPT */
592 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
593 const data_set_t *ds, const value_list_t *vl)
599 part_header_t pkg_ph;
600 uint16_t pkg_num_values;
601 uint8_t *pkg_values_types;
607 num_values = vl->values_len;
608 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
609 + (num_values * sizeof (uint8_t))
610 + (num_values * sizeof (value_t));
612 if (*ret_buffer_len < packet_len)
615 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
616 if (pkg_values_types == NULL)
618 ERROR ("network plugin: write_part_values: malloc failed.");
622 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
623 if (pkg_values == NULL)
625 free (pkg_values_types);
626 ERROR ("network plugin: write_part_values: malloc failed.");
630 pkg_ph.type = htons (TYPE_VALUES);
631 pkg_ph.length = htons (packet_len);
633 pkg_num_values = htons ((uint16_t) vl->values_len);
635 for (i = 0; i < num_values; i++)
637 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
638 switch (ds->ds[i].type)
640 case DS_TYPE_COUNTER:
641 pkg_values[i].counter = htonll (vl->values[i].counter);
645 pkg_values[i].gauge = htond (vl->values[i].gauge);
649 pkg_values[i].derive = htonll (vl->values[i].derive);
652 case DS_TYPE_ABSOLUTE:
653 pkg_values[i].absolute = htonll (vl->values[i].absolute);
657 free (pkg_values_types);
659 ERROR ("network plugin: write_part_values: "
660 "Unknown data source type: %i",
663 } /* switch (ds->ds[i].type) */
664 } /* for (num_values) */
667 * Use `memcpy' to write everything to the buffer, because the pointer
668 * may be unaligned and some architectures, such as SPARC, can't handle
671 packet_ptr = *ret_buffer;
673 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
674 offset += sizeof (pkg_ph);
675 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
676 offset += sizeof (pkg_num_values);
677 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
678 offset += num_values * sizeof (uint8_t);
679 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
680 offset += num_values * sizeof (value_t);
682 assert (offset == packet_len);
684 *ret_buffer = packet_ptr + packet_len;
685 *ret_buffer_len -= packet_len;
687 free (pkg_values_types);
691 } /* int write_part_values */
693 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
694 int type, uint64_t value)
699 part_header_t pkg_head;
704 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
706 if (*ret_buffer_len < packet_len)
709 pkg_head.type = htons (type);
710 pkg_head.length = htons (packet_len);
711 pkg_value = htonll (value);
713 packet_ptr = *ret_buffer;
715 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
716 offset += sizeof (pkg_head);
717 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
718 offset += sizeof (pkg_value);
720 assert (offset == packet_len);
722 *ret_buffer = packet_ptr + packet_len;
723 *ret_buffer_len -= packet_len;
726 } /* int write_part_number */
728 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
729 int type, const char *str, int str_len)
739 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
740 if (*ret_buffer_len < buffer_len)
743 pkg_type = htons (type);
744 pkg_length = htons (buffer_len);
746 buffer = *ret_buffer;
748 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
749 offset += sizeof (pkg_type);
750 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
751 offset += sizeof (pkg_length);
752 memcpy (buffer + offset, str, str_len);
754 memset (buffer + offset, '\0', 1);
757 assert (offset == buffer_len);
759 *ret_buffer = buffer + buffer_len;
760 *ret_buffer_len -= buffer_len;
763 } /* int write_part_string */
765 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
766 value_t **ret_values, int *ret_num_values)
768 char *buffer = *ret_buffer;
769 size_t buffer_len = *ret_buffer_len;
784 NOTICE ("network plugin: packet is too short: "
785 "buffer_len = %zu", buffer_len);
789 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
790 buffer += sizeof (tmp16);
791 pkg_type = ntohs (tmp16);
793 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
794 buffer += sizeof (tmp16);
795 pkg_length = ntohs (tmp16);
797 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
798 buffer += sizeof (tmp16);
799 pkg_numval = ntohs (tmp16);
801 assert (pkg_type == TYPE_VALUES);
803 exp_size = 3 * sizeof (uint16_t)
804 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
805 if (buffer_len < exp_size)
807 WARNING ("network plugin: parse_part_values: "
809 "Chunk of size %zu expected, "
810 "but buffer has only %zu bytes left.",
811 exp_size, buffer_len);
815 if (pkg_length != exp_size)
817 WARNING ("network plugin: parse_part_values: "
818 "Length and number of values "
819 "in the packet don't match.");
823 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
824 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
825 if ((pkg_types == NULL) || (pkg_values == NULL))
829 ERROR ("network plugin: parse_part_values: malloc failed.");
833 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
834 buffer += pkg_numval * sizeof (uint8_t);
835 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
836 buffer += pkg_numval * sizeof (value_t);
838 for (i = 0; i < pkg_numval; i++)
840 switch (pkg_types[i])
842 case DS_TYPE_COUNTER:
843 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
847 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
851 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
854 case DS_TYPE_ABSOLUTE:
855 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
859 NOTICE ("network plugin: parse_part_values: "
860 "Don't know how to handle data source type %"PRIu8,
865 } /* switch (pkg_types[i]) */
868 *ret_buffer = buffer;
869 *ret_buffer_len = buffer_len - pkg_length;
870 *ret_num_values = pkg_numval;
871 *ret_values = pkg_values;
876 } /* int parse_part_values */
878 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
881 char *buffer = *ret_buffer;
882 size_t buffer_len = *ret_buffer_len;
886 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
890 if (buffer_len < exp_size)
892 WARNING ("network plugin: parse_part_number: "
894 "Chunk of size %zu expected, "
895 "but buffer has only %zu bytes left.",
896 exp_size, buffer_len);
900 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
901 buffer += sizeof (tmp16);
902 /* pkg_type = ntohs (tmp16); */
904 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
905 buffer += sizeof (tmp16);
906 pkg_length = ntohs (tmp16);
908 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
909 buffer += sizeof (tmp64);
910 *value = ntohll (tmp64);
912 *ret_buffer = buffer;
913 *ret_buffer_len = buffer_len - pkg_length;
916 } /* int parse_part_number */
918 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
919 char *output, int output_len)
921 char *buffer = *ret_buffer;
922 size_t buffer_len = *ret_buffer_len;
925 size_t header_size = 2 * sizeof (uint16_t);
929 if (buffer_len < header_size)
931 WARNING ("network plugin: parse_part_string: "
933 "Chunk of at least size %zu expected, "
934 "but buffer has only %zu bytes left.",
935 header_size, buffer_len);
939 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
940 buffer += sizeof (tmp16);
941 /* pkg_type = ntohs (tmp16); */
943 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
944 buffer += sizeof (tmp16);
945 pkg_length = ntohs (tmp16);
947 /* Check that packet fits in the input buffer */
948 if (pkg_length > buffer_len)
950 WARNING ("network plugin: parse_part_string: "
952 "Chunk of size %"PRIu16" received, "
953 "but buffer has only %zu bytes left.",
954 pkg_length, buffer_len);
958 /* Check that pkg_length is in the valid range */
959 if (pkg_length <= header_size)
961 WARNING ("network plugin: parse_part_string: "
963 "Header claims this packet is only %hu "
964 "bytes long.", pkg_length);
968 /* Check that the package data fits into the output buffer.
969 * The previous if-statement ensures that:
970 * `pkg_length > header_size' */
972 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
974 WARNING ("network plugin: parse_part_string: "
975 "Output buffer too small.");
979 /* All sanity checks successfull, let's copy the data over */
980 output_len = pkg_length - header_size;
981 memcpy ((void *) output, (void *) buffer, output_len);
982 buffer += output_len;
984 /* For some very weird reason '\0' doesn't do the trick on SPARC in
986 if (output[output_len - 1] != 0)
988 WARNING ("network plugin: parse_part_string: "
989 "Received string does not end "
990 "with a NULL-byte.");
994 *ret_buffer = buffer;
995 *ret_buffer_len = buffer_len - pkg_length;
998 } /* int parse_part_string */
1000 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
1001 * parse_packet and vice versa. */
1002 #define PP_SIGNED 0x01
1003 #define PP_ENCRYPTED 0x02
1004 static int parse_packet (sockent_t *se,
1005 void *buffer, size_t buffer_size, int flags,
1006 const char *username);
1008 #define BUFFER_READ(p,s) do { \
1009 memcpy ((p), buffer + buffer_offset, (s)); \
1010 buffer_offset += (s); \
1014 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1015 void **ret_buffer, size_t *ret_buffer_len, int flags)
1017 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
1021 size_t buffer_offset;
1023 size_t username_len;
1026 part_signature_sha256_t pss;
1027 uint16_t pss_head_length;
1028 char hash[sizeof (pss.hash)];
1032 unsigned char *hash_ptr;
1034 buffer = *ret_buffer;
1035 buffer_len = *ret_buffer_len;
1038 if (se->data.server.userdb == NULL)
1040 c_complain (LOG_NOTICE, &complain_no_users,
1041 "network plugin: Received signed network packet but can't verify it "
1042 "because no user DB has been configured. Will accept it.");
1046 /* Check if the buffer has enough data for this structure. */
1047 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1050 /* Read type and length header */
1051 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1052 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1053 pss_head_length = ntohs (pss.head.length);
1055 /* Check if the `pss_head_length' is within bounds. */
1056 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1057 || (pss_head_length > buffer_len))
1059 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1063 /* Copy the hash. */
1064 BUFFER_READ (pss.hash, sizeof (pss.hash));
1066 /* Calculate username length (without null byte) and allocate memory */
1067 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1068 pss.username = malloc (username_len + 1);
1069 if (pss.username == NULL)
1072 /* Read the username */
1073 BUFFER_READ (pss.username, username_len);
1074 pss.username[username_len] = 0;
1076 assert (buffer_offset == pss_head_length);
1078 /* Query the password */
1079 secret = fbh_get (se->data.server.userdb, pss.username);
1082 ERROR ("network plugin: Unknown user: %s", pss.username);
1083 sfree (pss.username);
1087 /* Create a hash device and check the HMAC */
1089 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1092 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1093 gcry_strerror (err));
1095 sfree (pss.username);
1099 err = gcry_md_setkey (hd, secret, strlen (secret));
1102 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1105 sfree (pss.username);
1110 buffer + PART_SIGNATURE_SHA256_SIZE,
1111 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1112 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1113 if (hash_ptr == NULL)
1115 ERROR ("network plugin: gcry_md_read failed.");
1118 sfree (pss.username);
1121 memcpy (hash, hash_ptr, sizeof (hash));
1127 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1129 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1134 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1135 flags | PP_SIGNED, pss.username);
1139 sfree (pss.username);
1141 *ret_buffer = buffer + buffer_len;
1142 *ret_buffer_len = 0;
1145 } /* }}} int parse_part_sign_sha256 */
1146 /* #endif HAVE_LIBGCRYPT */
1148 #else /* if !HAVE_LIBGCRYPT */
1149 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1150 void **ret_buffer, size_t *ret_buffer_size, int flags)
1152 static int warning_has_been_printed = 0;
1156 size_t buffer_offset;
1159 part_signature_sha256_t pss;
1161 buffer = *ret_buffer;
1162 buffer_size = *ret_buffer_size;
1165 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1168 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1169 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1170 part_len = ntohs (pss.head.length);
1172 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1173 || (part_len > buffer_size))
1176 if (warning_has_been_printed == 0)
1178 WARNING ("network plugin: Received signed packet, but the network "
1179 "plugin was not linked with libgcrypt, so I cannot "
1180 "verify the signature. The packet will be accepted.");
1181 warning_has_been_printed = 1;
1184 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1185 /* username = */ NULL);
1187 *ret_buffer = buffer + buffer_size;
1188 *ret_buffer_size = 0;
1191 } /* }}} int parse_part_sign_sha256 */
1192 #endif /* !HAVE_LIBGCRYPT */
1195 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1196 void **ret_buffer, size_t *ret_buffer_len,
1199 char *buffer = *ret_buffer;
1200 size_t buffer_len = *ret_buffer_len;
1203 size_t buffer_offset;
1204 uint16_t username_len;
1205 part_encryption_aes256_t pea;
1206 unsigned char hash[sizeof (pea.hash)];
1208 gcry_cipher_hd_t cypher;
1211 /* Make sure at least the header if available. */
1212 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1214 NOTICE ("network plugin: parse_part_encr_aes256: "
1215 "Discarding short packet.");
1221 /* Copy the unencrypted information into `pea'. */
1222 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1223 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1225 /* Check the `part size'. */
1226 part_size = ntohs (pea.head.length);
1227 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1228 || (part_size > buffer_len))
1230 NOTICE ("network plugin: parse_part_encr_aes256: "
1231 "Discarding part with invalid size.");
1235 /* Read the username */
1236 BUFFER_READ (&username_len, sizeof (username_len));
1237 username_len = ntohs (username_len);
1239 if ((username_len <= 0)
1240 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1242 NOTICE ("network plugin: parse_part_encr_aes256: "
1243 "Discarding part with invalid username length.");
1247 assert (username_len > 0);
1248 pea.username = malloc (username_len + 1);
1249 if (pea.username == NULL)
1251 BUFFER_READ (pea.username, username_len);
1252 pea.username[username_len] = 0;
1254 /* Last but not least, the initialization vector */
1255 BUFFER_READ (pea.iv, sizeof (pea.iv));
1257 /* Make sure we are at the right position */
1258 assert (buffer_offset == (username_len +
1259 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1261 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1265 sfree (pea.username);
1269 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1270 assert (payload_len > 0);
1272 /* Decrypt the packet in-place */
1273 err = gcry_cipher_decrypt (cypher,
1274 buffer + buffer_offset,
1275 part_size - buffer_offset,
1276 /* in = */ NULL, /* in len = */ 0);
1279 sfree (pea.username);
1280 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1281 gcry_strerror (err));
1286 BUFFER_READ (pea.hash, sizeof (pea.hash));
1288 /* Make sure we're at the right position - again */
1289 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1290 assert (buffer_offset == (part_size - payload_len));
1292 /* Check hash sum */
1293 memset (hash, 0, sizeof (hash));
1294 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1295 buffer + buffer_offset, payload_len);
1296 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1298 sfree (pea.username);
1299 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1303 parse_packet (se, buffer + buffer_offset, payload_len,
1304 flags | PP_ENCRYPTED, pea.username);
1306 /* XXX: Free pea.username?!? */
1308 /* Update return values */
1309 *ret_buffer = buffer + part_size;
1310 *ret_buffer_len = buffer_len - part_size;
1312 sfree (pea.username);
1315 } /* }}} int parse_part_encr_aes256 */
1316 /* #endif HAVE_LIBGCRYPT */
1318 #else /* if !HAVE_LIBGCRYPT */
1319 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1320 void **ret_buffer, size_t *ret_buffer_size, int flags)
1322 static int warning_has_been_printed = 0;
1326 size_t buffer_offset;
1331 buffer = *ret_buffer;
1332 buffer_size = *ret_buffer_size;
1335 /* parse_packet assures this minimum size. */
1336 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1338 BUFFER_READ (&ph.type, sizeof (ph.type));
1339 BUFFER_READ (&ph.length, sizeof (ph.length));
1340 ph_length = ntohs (ph.length);
1342 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1343 || (ph_length > buffer_size))
1345 ERROR ("network plugin: AES-256 encrypted part "
1346 "with invalid length received.");
1350 if (warning_has_been_printed == 0)
1352 WARNING ("network plugin: Received encrypted packet, but the network "
1353 "plugin was not linked with libgcrypt, so I cannot "
1354 "decrypt it. The part will be discarded.");
1355 warning_has_been_printed = 1;
1358 *ret_buffer += ph_length;
1359 *ret_buffer_size -= ph_length;
1362 } /* }}} int parse_part_encr_aes256 */
1363 #endif /* !HAVE_LIBGCRYPT */
1367 static int parse_packet (sockent_t *se, /* {{{ */
1368 void *buffer, size_t buffer_size, int flags,
1369 const char *username)
1373 value_list_t vl = VALUE_LIST_INIT;
1377 int packet_was_signed = (flags & PP_SIGNED);
1378 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1379 int printed_ignore_warning = 0;
1380 #endif /* HAVE_LIBGCRYPT */
1383 memset (&vl, '\0', sizeof (vl));
1384 memset (&n, '\0', sizeof (n));
1387 while ((status == 0) && (0 < buffer_size)
1388 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1390 uint16_t pkg_length;
1393 memcpy ((void *) &pkg_type,
1396 memcpy ((void *) &pkg_length,
1397 (void *) (buffer + sizeof (pkg_type)),
1398 sizeof (pkg_length));
1400 pkg_length = ntohs (pkg_length);
1401 pkg_type = ntohs (pkg_type);
1403 if (pkg_length > buffer_size)
1405 /* Ensure that this loop terminates eventually */
1406 if (pkg_length < (2 * sizeof (uint16_t)))
1409 if (pkg_type == TYPE_ENCR_AES256)
1411 status = parse_part_encr_aes256 (se,
1412 &buffer, &buffer_size, flags);
1415 ERROR ("network plugin: Decrypting AES256 "
1417 "with status %i.", status);
1422 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1423 && (packet_was_encrypted == 0))
1425 if (printed_ignore_warning == 0)
1427 INFO ("network plugin: Unencrypted packet or "
1428 "part has been ignored.");
1429 printed_ignore_warning = 1;
1431 buffer = ((char *) buffer) + pkg_length;
1434 #endif /* HAVE_LIBGCRYPT */
1435 else if (pkg_type == TYPE_SIGN_SHA256)
1437 status = parse_part_sign_sha256 (se,
1438 &buffer, &buffer_size, flags);
1441 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1443 "with status %i.", status);
1448 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1449 && (packet_was_encrypted == 0)
1450 && (packet_was_signed == 0))
1452 if (printed_ignore_warning == 0)
1454 INFO ("network plugin: Unsigned packet or "
1455 "part has been ignored.");
1456 printed_ignore_warning = 1;
1458 buffer = ((char *) buffer) + pkg_length;
1461 #endif /* HAVE_LIBGCRYPT */
1462 else if (pkg_type == TYPE_VALUES)
1464 status = parse_part_values (&buffer, &buffer_size,
1465 &vl.values, &vl.values_len);
1469 network_dispatch_values (&vl, username);
1473 else if (pkg_type == TYPE_TIME)
1476 status = parse_part_number (&buffer, &buffer_size,
1480 vl.time = (time_t) tmp;
1481 n.time = (time_t) tmp;
1484 else if (pkg_type == TYPE_INTERVAL)
1487 status = parse_part_number (&buffer, &buffer_size,
1490 vl.interval = (int) tmp;
1492 else if (pkg_type == TYPE_HOST)
1494 status = parse_part_string (&buffer, &buffer_size,
1495 vl.host, sizeof (vl.host));
1497 sstrncpy (n.host, vl.host, sizeof (n.host));
1499 else if (pkg_type == TYPE_PLUGIN)
1501 status = parse_part_string (&buffer, &buffer_size,
1502 vl.plugin, sizeof (vl.plugin));
1504 sstrncpy (n.plugin, vl.plugin,
1507 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1509 status = parse_part_string (&buffer, &buffer_size,
1511 sizeof (vl.plugin_instance));
1513 sstrncpy (n.plugin_instance,
1515 sizeof (n.plugin_instance));
1517 else if (pkg_type == TYPE_TYPE)
1519 status = parse_part_string (&buffer, &buffer_size,
1520 vl.type, sizeof (vl.type));
1522 sstrncpy (n.type, vl.type, sizeof (n.type));
1524 else if (pkg_type == TYPE_TYPE_INSTANCE)
1526 status = parse_part_string (&buffer, &buffer_size,
1528 sizeof (vl.type_instance));
1530 sstrncpy (n.type_instance, vl.type_instance,
1531 sizeof (n.type_instance));
1533 else if (pkg_type == TYPE_MESSAGE)
1535 status = parse_part_string (&buffer, &buffer_size,
1536 n.message, sizeof (n.message));
1542 else if ((n.severity != NOTIF_FAILURE)
1543 && (n.severity != NOTIF_WARNING)
1544 && (n.severity != NOTIF_OKAY))
1546 INFO ("network plugin: "
1547 "Ignoring notification with "
1548 "unknown severity %i.",
1551 else if (n.time <= 0)
1553 INFO ("network plugin: "
1554 "Ignoring notification with "
1557 else if (strlen (n.message) <= 0)
1559 INFO ("network plugin: "
1560 "Ignoring notification with "
1561 "an empty message.");
1565 network_dispatch_notification (&n);
1568 else if (pkg_type == TYPE_SEVERITY)
1571 status = parse_part_number (&buffer, &buffer_size,
1574 n.severity = (int) tmp;
1578 DEBUG ("network plugin: parse_packet: Unknown part"
1579 " type: 0x%04hx", pkg_type);
1580 buffer = ((char *) buffer) + pkg_length;
1582 } /* while (buffer_size > sizeof (part_header_t)) */
1584 if (status == 0 && buffer_size > 0)
1585 WARNING ("network plugin: parse_packet: Received truncated "
1586 "packet, try increasing `MaxPacketSize'");
1589 } /* }}} int parse_packet */
1591 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1600 sfree (sec->username);
1601 sfree (sec->password);
1602 if (sec->cypher != NULL)
1603 gcry_cipher_close (sec->cypher);
1605 } /* }}} void free_sockent_client */
1607 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1611 for (i = 0; i < ses->fd_num; i++)
1613 if (ses->fd[i] >= 0)
1622 sfree (ses->auth_file);
1623 fbh_destroy (ses->userdb);
1624 if (ses->cypher != NULL)
1625 gcry_cipher_close (ses->cypher);
1627 } /* }}} void free_sockent_server */
1629 static void sockent_destroy (sockent_t *se) /* {{{ */
1633 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1640 sfree (se->service);
1642 if (se->type == SOCKENT_TYPE_CLIENT)
1643 free_sockent_client (&se->data.client);
1645 free_sockent_server (&se->data.server);
1650 } /* }}} void sockent_destroy */
1653 * int network_set_ttl
1655 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1656 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1658 * The `struct addrinfo' is used to destinguish between unicast and multicast
1661 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1663 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1664 network_config_ttl);
1666 assert (se->type == SOCKENT_TYPE_CLIENT);
1668 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1671 if (ai->ai_family == AF_INET)
1673 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1676 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1677 optname = IP_MULTICAST_TTL;
1681 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1682 &network_config_ttl,
1683 sizeof (network_config_ttl)) != 0)
1686 ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
1687 sstrerror (errno, errbuf, sizeof (errbuf)));
1691 else if (ai->ai_family == AF_INET6)
1693 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1694 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1697 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1698 optname = IPV6_MULTICAST_HOPS;
1700 optname = IPV6_UNICAST_HOPS;
1702 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1703 &network_config_ttl,
1704 sizeof (network_config_ttl)) != 0)
1707 ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
1708 sstrerror (errno, errbuf,
1715 } /* int network_set_ttl */
1717 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1719 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1722 assert (se->type == SOCKENT_TYPE_CLIENT);
1724 if (ai->ai_family == AF_INET)
1726 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1728 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1730 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1731 /* If possible, use the "ip_mreqn" structure which has
1732 * an "interface index" member. Using the interface
1733 * index is preferred here, because of its similarity
1734 * to the way IPv6 handles this. Unfortunately, it
1735 * appears not to be portable. */
1736 struct ip_mreqn mreq;
1738 memset (&mreq, 0, sizeof (mreq));
1739 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1740 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1741 mreq.imr_ifindex = se->interface;
1743 struct ip_mreq mreq;
1745 memset (&mreq, 0, sizeof (mreq));
1746 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1747 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1750 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1751 &mreq, sizeof (mreq)) != 0)
1754 ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
1755 sstrerror (errno, errbuf, sizeof (errbuf)));
1762 else if (ai->ai_family == AF_INET6)
1764 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1766 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1768 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1770 sizeof (se->interface)) != 0)
1773 ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
1774 sstrerror (errno, errbuf,
1783 /* else: Not a multicast interface. */
1784 if (se->interface != 0)
1786 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1787 char interface_name[IFNAMSIZ];
1789 if (if_indextoname (se->interface, interface_name) == NULL)
1792 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1794 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1796 sizeof(interface_name)) == -1 )
1799 ERROR ("network plugin: setsockopt (bind-if): %s",
1800 sstrerror (errno, errbuf, sizeof (errbuf)));
1803 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1806 WARNING ("network plugin: Cannot set the interface on a unicast "
1808 # if !defined(SO_BINDTODEVICE)
1809 "the \"SO_BINDTODEVICE\" socket option "
1811 "the \"if_indextoname\" function "
1813 "is not available on your system.");
1819 } /* }}} network_set_interface */
1821 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1830 /* allow multiple sockets to use the same PORT number */
1831 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1832 &yes, sizeof(yes)) == -1) {
1834 ERROR ("network plugin: setsockopt (reuseaddr): %s",
1835 sstrerror (errno, errbuf, sizeof (errbuf)));
1839 DEBUG ("fd = %i; calling `bind'", fd);
1841 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1845 sstrerror (errno, errbuf, sizeof (errbuf)));
1849 if (ai->ai_family == AF_INET)
1851 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1852 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1854 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1855 struct ip_mreqn mreq;
1857 struct ip_mreq mreq;
1860 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1862 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1863 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1864 /* Set the interface using the interface index if
1865 * possible (available). Unfortunately, the struct
1866 * ip_mreqn is not portable. */
1867 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1868 mreq.imr_ifindex = interface_idx;
1870 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1873 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1874 &loop, sizeof (loop)) == -1)
1877 ERROR ("network plugin: setsockopt (multicast-loop): %s",
1878 sstrerror (errno, errbuf,
1883 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1884 &mreq, sizeof (mreq)) == -1)
1887 ERROR ("network plugin: setsockopt (add-membership): %s",
1888 sstrerror (errno, errbuf,
1896 else if (ai->ai_family == AF_INET6)
1898 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1899 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1900 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1902 struct ipv6_mreq mreq;
1904 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1906 memcpy (&mreq.ipv6mr_multiaddr,
1908 sizeof (addr->sin6_addr));
1910 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1911 * ipv6mr_interface may be set to zeroes to
1912 * choose the default multicast interface or to
1913 * the index of a particular multicast-capable
1914 * interface if the host is multihomed.
1915 * Membership is associ-associated with a
1916 * single interface; programs running on
1917 * multihomed hosts may need to join the same
1918 * group on more than one interface.*/
1919 mreq.ipv6mr_interface = interface_idx;
1921 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1922 &loop, sizeof (loop)) == -1)
1925 ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
1926 sstrerror (errno, errbuf,
1931 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1932 &mreq, sizeof (mreq)) == -1)
1935 ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
1936 sstrerror (errno, errbuf,
1945 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1946 /* if a specific interface was set, bind the socket to it. But to avoid
1947 * possible problems with multicast routing, only do that for non-multicast
1949 if (interface_idx != 0)
1951 char interface_name[IFNAMSIZ];
1953 if (if_indextoname (interface_idx, interface_name) == NULL)
1956 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1958 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1960 sizeof(interface_name)) == -1 )
1963 ERROR ("network plugin: setsockopt (bind-if): %s",
1964 sstrerror (errno, errbuf, sizeof (errbuf)));
1968 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1971 } /* int network_bind_socket */
1973 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1974 * or `SOCKENT_TYPE_SERVER' */
1975 static int sockent_init (sockent_t *se, int type) /* {{{ */
1980 memset (se, 0, sizeof (*se));
1982 se->type = SOCKENT_TYPE_CLIENT;
1988 if (type == SOCKENT_TYPE_SERVER)
1990 se->type = SOCKENT_TYPE_SERVER;
1991 se->data.server.fd = NULL;
1993 se->data.server.security_level = SECURITY_LEVEL_NONE;
1994 se->data.server.auth_file = NULL;
1995 se->data.server.userdb = NULL;
1996 se->data.server.cypher = NULL;
2001 se->data.client.fd = -1;
2002 se->data.client.addr = NULL;
2004 se->data.client.security_level = SECURITY_LEVEL_NONE;
2005 se->data.client.username = NULL;
2006 se->data.client.password = NULL;
2007 se->data.client.cypher = NULL;
2012 } /* }}} int sockent_init */
2014 /* Open the file descriptors for a initialized sockent structure. */
2015 static int sockent_open (sockent_t *se) /* {{{ */
2017 struct addrinfo ai_hints;
2018 struct addrinfo *ai_list, *ai_ptr;
2022 const char *service;
2027 /* Set up the security structures. */
2028 #if HAVE_LIBGCRYPT /* {{{ */
2029 if (se->type == SOCKENT_TYPE_CLIENT)
2031 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
2033 network_init_gcrypt ();
2035 if ((se->data.client.username == NULL)
2036 || (se->data.client.password == NULL))
2038 ERROR ("network plugin: Client socket with "
2039 "security requested, but no "
2040 "credentials are configured.");
2043 gcry_md_hash_buffer (GCRY_MD_SHA256,
2044 se->data.client.password_hash,
2045 se->data.client.password,
2046 strlen (se->data.client.password));
2049 else /* (se->type == SOCKENT_TYPE_SERVER) */
2051 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2053 network_init_gcrypt ();
2055 if (se->data.server.auth_file == NULL)
2057 ERROR ("network plugin: Server socket with "
2058 "security requested, but no "
2059 "password file is configured.");
2063 if (se->data.server.auth_file != NULL)
2065 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2066 if (se->data.server.userdb == NULL)
2068 ERROR ("network plugin: Reading password file "
2070 se->data.server.auth_file);
2071 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2076 #endif /* }}} HAVE_LIBGCRYPT */
2079 service = se->service;
2081 if (service == NULL)
2082 service = NET_DEFAULT_PORT;
2084 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
2087 memset (&ai_hints, 0, sizeof (ai_hints));
2088 ai_hints.ai_flags = 0;
2090 ai_hints.ai_flags |= AI_PASSIVE;
2092 #ifdef AI_ADDRCONFIG
2093 ai_hints.ai_flags |= AI_ADDRCONFIG;
2095 ai_hints.ai_family = AF_UNSPEC;
2096 ai_hints.ai_socktype = SOCK_DGRAM;
2097 ai_hints.ai_protocol = IPPROTO_UDP;
2099 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2102 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2103 (se->node == NULL) ? "(null)" : se->node,
2104 (se->service == NULL) ? "(null)" : se->service,
2105 gai_strerror (ai_return));
2109 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2113 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2117 tmp = realloc (se->data.server.fd,
2118 sizeof (*tmp) * (se->data.server.fd_num + 1));
2121 ERROR ("network plugin: realloc failed.");
2124 se->data.server.fd = tmp;
2125 tmp = se->data.server.fd + se->data.server.fd_num;
2127 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2128 ai_ptr->ai_protocol);
2132 ERROR ("network plugin: socket(2) failed: %s",
2133 sstrerror (errno, errbuf,
2138 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2146 se->data.server.fd_num++;
2148 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2149 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2151 se->data.client.fd = socket (ai_ptr->ai_family,
2152 ai_ptr->ai_socktype,
2153 ai_ptr->ai_protocol);
2154 if (se->data.client.fd < 0)
2157 ERROR ("network plugin: socket(2) failed: %s",
2158 sstrerror (errno, errbuf,
2163 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2164 if (se->data.client.addr == NULL)
2166 ERROR ("network plugin: malloc failed.");
2167 close (se->data.client.fd);
2168 se->data.client.fd = -1;
2172 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2173 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2174 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2175 se->data.client.addrlen = ai_ptr->ai_addrlen;
2177 network_set_ttl (se, ai_ptr);
2178 network_set_interface (se, ai_ptr);
2180 /* We don't open more than one write-socket per
2181 * node/service pair.. */
2183 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2184 } /* for (ai_list) */
2186 freeaddrinfo (ai_list);
2188 /* Check if all went well. */
2189 if (se->type == SOCKENT_TYPE_SERVER)
2191 if (se->data.server.fd_num <= 0)
2194 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2196 if (se->data.client.fd < 0)
2201 } /* }}} int sockent_open */
2203 /* Add a sockent to the global list of sockets */
2204 static int sockent_add (sockent_t *se) /* {{{ */
2206 sockent_t *last_ptr;
2211 if (se->type == SOCKENT_TYPE_SERVER)
2216 tmp = realloc (listen_sockets_pollfd,
2217 sizeof (*tmp) * (listen_sockets_num
2218 + se->data.server.fd_num));
2221 ERROR ("network plugin: realloc failed.");
2224 listen_sockets_pollfd = tmp;
2225 tmp = listen_sockets_pollfd + listen_sockets_num;
2227 for (i = 0; i < se->data.server.fd_num; i++)
2229 memset (tmp + i, 0, sizeof (*tmp));
2230 tmp[i].fd = se->data.server.fd[i];
2231 tmp[i].events = POLLIN | POLLPRI;
2235 listen_sockets_num += se->data.server.fd_num;
2237 if (listen_sockets == NULL)
2239 listen_sockets = se;
2242 last_ptr = listen_sockets;
2244 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2246 if (sending_sockets == NULL)
2248 sending_sockets = se;
2251 last_ptr = sending_sockets;
2254 while (last_ptr->next != NULL)
2255 last_ptr = last_ptr->next;
2256 last_ptr->next = se;
2259 } /* }}} int sockent_add */
2261 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2265 receive_list_entry_t *ent;
2268 /* Lock and wait for more data to come in */
2269 pthread_mutex_lock (&receive_list_lock);
2270 while ((listen_loop == 0)
2271 && (receive_list_head == NULL))
2272 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2274 /* Remove the head entry and unlock */
2275 ent = receive_list_head;
2277 receive_list_head = ent->next;
2278 receive_list_length--;
2279 pthread_mutex_unlock (&receive_list_lock);
2281 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2282 * because we dispatch all missing packets before shutting down. */
2286 /* Look for the correct `sockent_t' */
2287 se = listen_sockets;
2292 for (i = 0; i < se->data.server.fd_num; i++)
2293 if (se->data.server.fd[i] == ent->fd)
2296 if (i < se->data.server.fd_num)
2304 ERROR ("network plugin: Got packet from FD %i, but can't "
2305 "find an appropriate socket entry.",
2312 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2313 /* username = */ NULL);
2319 } /* }}} void *dispatch_thread */
2321 static int network_receive (void) /* {{{ */
2323 char buffer[network_config_packet_size];
2329 receive_list_entry_t *private_list_head;
2330 receive_list_entry_t *private_list_tail;
2331 uint64_t private_list_length;
2333 assert (listen_sockets_num > 0);
2335 private_list_head = NULL;
2336 private_list_tail = NULL;
2337 private_list_length = 0;
2339 while (listen_loop == 0)
2341 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2348 ERROR ("poll failed: %s",
2349 sstrerror (errno, errbuf, sizeof (errbuf)));
2353 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2355 receive_list_entry_t *ent;
2357 if ((listen_sockets_pollfd[i].revents
2358 & (POLLIN | POLLPRI)) == 0)
2362 buffer_len = recv (listen_sockets_pollfd[i].fd,
2363 buffer, sizeof (buffer),
2368 ERROR ("recv failed: %s",
2369 sstrerror (errno, errbuf,
2374 stats_octets_rx += ((uint64_t) buffer_len);
2377 /* TODO: Possible performance enhancement: Do not free
2378 * these entries in the dispatch thread but put them in
2379 * another list, so we don't have to allocate more and
2380 * more of these structures. */
2381 ent = malloc (sizeof (receive_list_entry_t));
2384 ERROR ("network plugin: malloc failed.");
2387 memset (ent, 0, sizeof (receive_list_entry_t));
2388 ent->data = malloc (network_config_packet_size);
2389 if (ent->data == NULL)
2392 ERROR ("network plugin: malloc failed.");
2395 ent->fd = listen_sockets_pollfd[i].fd;
2398 memcpy (ent->data, buffer, buffer_len);
2399 ent->data_len = buffer_len;
2401 if (private_list_head == NULL)
2402 private_list_head = ent;
2404 private_list_tail->next = ent;
2405 private_list_tail = ent;
2406 private_list_length++;
2408 /* Do not block here. Blocking here has led to
2409 * insufficient performance in the past. */
2410 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2412 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2413 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2415 if (receive_list_head == NULL)
2416 receive_list_head = private_list_head;
2418 receive_list_tail->next = private_list_head;
2419 receive_list_tail = private_list_tail;
2420 receive_list_length += private_list_length;
2422 pthread_cond_signal (&receive_list_cond);
2423 pthread_mutex_unlock (&receive_list_lock);
2425 private_list_head = NULL;
2426 private_list_tail = NULL;
2427 private_list_length = 0;
2429 } /* for (listen_sockets_pollfd) */
2430 } /* while (listen_loop == 0) */
2432 /* Make sure everything is dispatched before exiting. */
2433 if (private_list_head != NULL)
2435 pthread_mutex_lock (&receive_list_lock);
2437 if (receive_list_head == NULL)
2438 receive_list_head = private_list_head;
2440 receive_list_tail->next = private_list_head;
2441 receive_list_tail = private_list_tail;
2442 receive_list_length += private_list_length;
2444 private_list_head = NULL;
2445 private_list_tail = NULL;
2446 private_list_length = 0;
2448 pthread_cond_signal (&receive_list_cond);
2449 pthread_mutex_unlock (&receive_list_lock);
2453 } /* }}} int network_receive */
2455 static void *receive_thread (void __attribute__((unused)) *arg)
2457 return (network_receive () ? (void *) 1 : (void *) 0);
2458 } /* void *receive_thread */
2460 static void network_init_buffer (void)
2462 memset (send_buffer, 0, network_config_packet_size);
2463 send_buffer_ptr = send_buffer;
2464 send_buffer_fill = 0;
2466 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2467 } /* int network_init_buffer */
2469 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2470 const char *buffer, size_t buffer_size)
2476 status = sendto (se->data.client.fd, buffer, buffer_size,
2478 (struct sockaddr *) se->data.client.addr,
2479 se->data.client.addrlen);
2485 ERROR ("network plugin: sendto failed: %s",
2486 sstrerror (errno, errbuf,
2493 } /* }}} void networt_send_buffer_plain */
2496 #define BUFFER_ADD(p,s) do { \
2497 memcpy (buffer + buffer_offset, (p), (s)); \
2498 buffer_offset += (s); \
2501 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2502 const char *in_buffer, size_t in_buffer_size)
2504 part_signature_sha256_t ps;
2505 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2506 size_t buffer_offset;
2507 size_t username_len;
2511 unsigned char *hash;
2514 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2517 ERROR ("network plugin: Creating HMAC object failed: %s",
2518 gcry_strerror (err));
2522 err = gcry_md_setkey (hd, se->data.client.password,
2523 strlen (se->data.client.password));
2526 ERROR ("network plugin: gcry_md_setkey failed: %s",
2527 gcry_strerror (err));
2532 username_len = strlen (se->data.client.username);
2533 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2535 ERROR ("network plugin: Username too long: %s",
2536 se->data.client.username);
2540 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2541 se->data.client.username, username_len);
2542 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2543 in_buffer, in_buffer_size);
2545 /* Initialize the `ps' structure. */
2546 memset (&ps, 0, sizeof (ps));
2547 ps.head.type = htons (TYPE_SIGN_SHA256);
2548 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2550 /* Calculate the hash value. */
2551 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2552 username_len + in_buffer_size);
2553 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2556 ERROR ("network plugin: gcry_md_read failed.");
2560 memcpy (ps.hash, hash, sizeof (ps.hash));
2562 /* Add the header */
2565 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2566 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2567 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2569 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2574 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2575 networt_send_buffer_plain (se, buffer, buffer_offset);
2576 } /* }}} void networt_send_buffer_signed */
2578 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2579 const char *in_buffer, size_t in_buffer_size)
2581 part_encryption_aes256_t pea;
2582 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2584 size_t buffer_offset;
2586 size_t username_len;
2588 gcry_cipher_hd_t cypher;
2590 /* Initialize the header fields */
2591 memset (&pea, 0, sizeof (pea));
2592 pea.head.type = htons (TYPE_ENCR_AES256);
2594 pea.username = se->data.client.username;
2596 username_len = strlen (pea.username);
2597 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2599 ERROR ("network plugin: Username too long: %s", pea.username);
2603 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2604 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2605 - sizeof (pea.hash);
2607 assert (buffer_size <= sizeof (buffer));
2608 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2609 "buffer_size = %zu;", buffer_size);
2611 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2612 + username_len + in_buffer_size));
2613 pea.username_length = htons ((uint16_t) username_len);
2615 /* Chose a random initialization vector. */
2616 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2618 /* Create hash of the payload */
2619 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2621 /* Initialize the buffer */
2623 memset (buffer, 0, sizeof (buffer));
2626 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2627 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2628 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2629 BUFFER_ADD (pea.username, username_len);
2630 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2631 assert (buffer_offset == header_size);
2632 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2633 BUFFER_ADD (in_buffer, in_buffer_size);
2635 assert (buffer_offset == buffer_size);
2637 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2638 se->data.client.password);
2642 /* Encrypt the buffer in-place */
2643 err = gcry_cipher_encrypt (cypher,
2644 buffer + header_size,
2645 buffer_size - header_size,
2646 /* in = */ NULL, /* in len = */ 0);
2649 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2650 gcry_strerror (err));
2654 /* Send it out without further modifications */
2655 networt_send_buffer_plain (se, buffer, buffer_size);
2656 } /* }}} void networt_send_buffer_encrypted */
2658 #endif /* HAVE_LIBGCRYPT */
2660 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2664 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2666 for (se = sending_sockets; se != NULL; se = se->next)
2669 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2670 networt_send_buffer_encrypted (se, buffer, buffer_len);
2671 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2672 networt_send_buffer_signed (se, buffer, buffer_len);
2673 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2674 #endif /* HAVE_LIBGCRYPT */
2675 networt_send_buffer_plain (se, buffer, buffer_len);
2676 } /* for (sending_sockets) */
2677 } /* }}} void network_send_buffer */
2679 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2680 value_list_t *vl_def,
2681 const data_set_t *ds, const value_list_t *vl)
2683 char *buffer_orig = buffer;
2685 if (strcmp (vl_def->host, vl->host) != 0)
2687 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2688 vl->host, strlen (vl->host)) != 0)
2690 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2693 if (vl_def->time != vl->time)
2695 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2696 (uint64_t) vl->time))
2698 vl_def->time = vl->time;
2701 if (vl_def->interval != vl->interval)
2703 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2704 (uint64_t) vl->interval))
2706 vl_def->interval = vl->interval;
2709 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2711 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2712 vl->plugin, strlen (vl->plugin)) != 0)
2714 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2717 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2719 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2720 vl->plugin_instance,
2721 strlen (vl->plugin_instance)) != 0)
2723 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2726 if (strcmp (vl_def->type, vl->type) != 0)
2728 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2729 vl->type, strlen (vl->type)) != 0)
2731 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2734 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2736 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2738 strlen (vl->type_instance)) != 0)
2740 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2743 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2746 return (buffer - buffer_orig);
2747 } /* }}} int add_to_buffer */
2749 static void flush_buffer (void)
2751 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2754 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2756 stats_octets_tx += ((uint64_t) send_buffer_fill);
2759 network_init_buffer ();
2762 static int network_write (const data_set_t *ds, const value_list_t *vl,
2763 user_data_t __attribute__((unused)) *user_data)
2767 if (!check_send_okay (vl))
2770 char name[6*DATA_MAX_NAME_LEN];
2771 FORMAT_VL (name, sizeof (name), vl);
2772 name[sizeof (name) - 1] = 0;
2773 DEBUG ("network plugin: network_write: "
2774 "NOT sending %s.", name);
2776 /* Counter is not protected by another lock and may be reached by
2777 * multiple threads */
2778 pthread_mutex_lock (&stats_lock);
2779 stats_values_not_sent++;
2780 pthread_mutex_unlock (&stats_lock);
2784 uc_meta_data_add_unsigned_int (vl,
2785 "network:time_sent", (uint64_t) vl->time);
2787 pthread_mutex_lock (&send_buffer_lock);
2789 status = add_to_buffer (send_buffer_ptr,
2790 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2795 /* status == bytes added to the buffer */
2796 send_buffer_fill += status;
2797 send_buffer_ptr += status;
2799 stats_values_sent++;
2805 status = add_to_buffer (send_buffer_ptr,
2806 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2812 send_buffer_fill += status;
2813 send_buffer_ptr += status;
2815 stats_values_sent++;
2821 ERROR ("network plugin: Unable to append to the "
2822 "buffer for some weird reason");
2824 else if ((network_config_packet_size - send_buffer_fill) < 15)
2829 pthread_mutex_unlock (&send_buffer_lock);
2831 return ((status < 0) ? -1 : 0);
2832 } /* int network_write */
2834 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2837 if ((ci->values_num != 1)
2838 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2839 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2841 ERROR ("network plugin: The `%s' config option needs "
2842 "exactly one boolean argument.", ci->key);
2846 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2848 if (ci->values[0].value.boolean)
2855 char *str = ci->values[0].value.string;
2859 else if (IS_FALSE (str))
2863 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2864 "option as boolean value.",
2871 } /* }}} int network_config_set_boolean */
2873 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2876 if ((ci->values_num != 1)
2877 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2879 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2880 "one numeric argument.");
2884 tmp = (int) ci->values[0].value.number;
2885 if ((tmp > 0) && (tmp <= 255))
2886 network_config_ttl = tmp;
2889 } /* }}} int network_config_set_ttl */
2891 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2894 if ((ci->values_num != 1)
2895 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2897 WARNING ("network plugin: The `Interface' config option needs exactly "
2898 "one string argument.");
2902 if (interface == NULL)
2905 *interface = if_nametoindex (ci->values[0].value.string);
2908 } /* }}} int network_config_set_interface */
2910 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2913 if ((ci->values_num != 1)
2914 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2916 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2917 "one numeric argument.");
2921 tmp = (int) ci->values[0].value.number;
2922 if ((tmp >= 1024) && (tmp <= 65535))
2923 network_config_packet_size = tmp;
2926 } /* }}} int network_config_set_buffer_size */
2929 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2933 if ((ci->values_num != 1)
2934 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2936 WARNING ("network plugin: The `%s' config option needs exactly "
2937 "one string argument.", ci->key);
2941 tmp = strdup (ci->values[0].value.string);
2945 sfree (*ret_string);
2949 } /* }}} int network_config_set_string */
2950 #endif /* HAVE_LIBGCRYPT */
2953 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2957 if ((ci->values_num != 1)
2958 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2960 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2961 "one string argument.");
2965 str = ci->values[0].value.string;
2966 if (strcasecmp ("Encrypt", str) == 0)
2967 *retval = SECURITY_LEVEL_ENCRYPT;
2968 else if (strcasecmp ("Sign", str) == 0)
2969 *retval = SECURITY_LEVEL_SIGN;
2970 else if (strcasecmp ("None", str) == 0)
2971 *retval = SECURITY_LEVEL_NONE;
2974 WARNING ("network plugin: Unknown security level: %s.", str);
2979 } /* }}} int network_config_set_security_level */
2980 #endif /* HAVE_LIBGCRYPT */
2982 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2988 if ((ci->values_num < 1) || (ci->values_num > 2)
2989 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2990 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2992 ERROR ("network plugin: The `%s' config option needs "
2993 "one or two string arguments.", ci->key);
2997 se = malloc (sizeof (*se));
3000 ERROR ("network plugin: malloc failed.");
3003 sockent_init (se, SOCKENT_TYPE_SERVER);
3005 se->node = strdup (ci->values[0].value.string);
3006 if (ci->values_num >= 2)
3007 se->service = strdup (ci->values[1].value.string);
3009 for (i = 0; i < ci->children_num; i++)
3011 oconfig_item_t *child = ci->children + i;
3014 if (strcasecmp ("AuthFile", child->key) == 0)
3015 network_config_set_string (child, &se->data.server.auth_file);
3016 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3017 network_config_set_security_level (child,
3018 &se->data.server.security_level);
3020 #endif /* HAVE_LIBGCRYPT */
3021 if (strcasecmp ("Interface", child->key) == 0)
3022 network_config_set_interface (child,
3026 WARNING ("network plugin: Option `%s' is not allowed here.",
3032 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3033 && (se->data.server.auth_file == NULL))
3035 ERROR ("network plugin: A security level higher than `none' was "
3036 "requested, but no AuthFile option was given. Cowardly refusing to "
3037 "open this socket!");
3038 sockent_destroy (se);
3041 #endif /* HAVE_LIBGCRYPT */
3043 status = sockent_open (se);
3046 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
3047 sockent_destroy (se);
3051 status = sockent_add (se);
3054 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3055 sockent_destroy (se);
3060 } /* }}} int network_config_add_listen */
3062 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3068 if ((ci->values_num < 1) || (ci->values_num > 2)
3069 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3070 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3072 ERROR ("network plugin: The `%s' config option needs "
3073 "one or two string arguments.", ci->key);
3077 se = malloc (sizeof (*se));
3080 ERROR ("network plugin: malloc failed.");
3083 sockent_init (se, SOCKENT_TYPE_CLIENT);
3085 se->node = strdup (ci->values[0].value.string);
3086 if (ci->values_num >= 2)
3087 se->service = strdup (ci->values[1].value.string);
3089 for (i = 0; i < ci->children_num; i++)
3091 oconfig_item_t *child = ci->children + i;
3094 if (strcasecmp ("Username", child->key) == 0)
3095 network_config_set_string (child, &se->data.client.username);
3096 else if (strcasecmp ("Password", child->key) == 0)
3097 network_config_set_string (child, &se->data.client.password);
3098 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3099 network_config_set_security_level (child,
3100 &se->data.client.security_level);
3102 #endif /* HAVE_LIBGCRYPT */
3103 if (strcasecmp ("Interface", child->key) == 0)
3104 network_config_set_interface (child,
3108 WARNING ("network plugin: Option `%s' is not allowed here.",
3114 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3115 && ((se->data.client.username == NULL)
3116 || (se->data.client.password == NULL)))
3118 ERROR ("network plugin: A security level higher than `none' was "
3119 "requested, but no Username or Password option was given. "
3120 "Cowardly refusing to open this socket!");
3121 sockent_destroy (se);
3124 #endif /* HAVE_LIBGCRYPT */
3126 status = sockent_open (se);
3129 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3130 sockent_destroy (se);
3134 status = sockent_add (se);
3137 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3138 sockent_destroy (se);
3143 } /* }}} int network_config_add_server */
3145 static int network_config (oconfig_item_t *ci) /* {{{ */
3149 for (i = 0; i < ci->children_num; i++)
3151 oconfig_item_t *child = ci->children + i;
3153 if (strcasecmp ("Listen", child->key) == 0)
3154 network_config_add_listen (child);
3155 else if (strcasecmp ("Server", child->key) == 0)
3156 network_config_add_server (child);
3157 else if (strcasecmp ("TimeToLive", child->key) == 0)
3158 network_config_set_ttl (child);
3159 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3160 network_config_set_buffer_size (child);
3161 else if (strcasecmp ("Forward", child->key) == 0)
3162 network_config_set_boolean (child, &network_config_forward);
3163 else if (strcasecmp ("ReportStats", child->key) == 0)
3164 network_config_set_boolean (child, &network_config_stats);
3165 else if (strcasecmp ("CacheFlush", child->key) == 0)
3166 /* no op for backwards compatibility only */;
3169 WARNING ("network plugin: Option `%s' is not allowed here.",
3175 } /* }}} int network_config */
3177 static int network_notification (const notification_t *n,
3178 user_data_t __attribute__((unused)) *user_data)
3180 char buffer[network_config_packet_size];
3181 char *buffer_ptr = buffer;
3182 int buffer_free = sizeof (buffer);
3185 if (!check_send_notify_okay (n))
3188 memset (buffer, 0, sizeof (buffer));
3190 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
3191 (uint64_t) n->time);
3195 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3196 (uint64_t) n->severity);
3200 if (strlen (n->host) > 0)
3202 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3203 n->host, strlen (n->host));
3208 if (strlen (n->plugin) > 0)
3210 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3211 n->plugin, strlen (n->plugin));
3216 if (strlen (n->plugin_instance) > 0)
3218 status = write_part_string (&buffer_ptr, &buffer_free,
3219 TYPE_PLUGIN_INSTANCE,
3220 n->plugin_instance, strlen (n->plugin_instance));
3225 if (strlen (n->type) > 0)
3227 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3228 n->type, strlen (n->type));
3233 if (strlen (n->type_instance) > 0)
3235 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3236 n->type_instance, strlen (n->type_instance));
3241 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3242 n->message, strlen (n->message));
3246 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3249 } /* int network_notification */
3251 static int network_shutdown (void)
3255 /* Kill the listening thread */
3256 if (receive_thread_running != 0)
3258 INFO ("network plugin: Stopping receive thread.");
3259 pthread_kill (receive_thread_id, SIGTERM);
3260 pthread_join (receive_thread_id, NULL /* no return value */);
3261 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3262 receive_thread_running = 0;
3265 /* Shutdown the dispatching thread */
3266 if (dispatch_thread_running != 0)
3268 INFO ("network plugin: Stopping dispatch thread.");
3269 pthread_mutex_lock (&receive_list_lock);
3270 pthread_cond_broadcast (&receive_list_cond);
3271 pthread_mutex_unlock (&receive_list_lock);
3272 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3273 dispatch_thread_running = 0;
3276 sockent_destroy (listen_sockets);
3278 if (send_buffer_fill > 0)
3281 sfree (send_buffer);
3283 /* TODO: Close `sending_sockets' */
3285 plugin_unregister_config ("network");
3286 plugin_unregister_init ("network");
3287 plugin_unregister_write ("network");
3288 plugin_unregister_shutdown ("network");
3291 } /* int network_shutdown */
3293 static int network_stats_read (void) /* {{{ */
3295 uint64_t copy_octets_rx;
3296 uint64_t copy_octets_tx;
3297 uint64_t copy_packets_rx;
3298 uint64_t copy_packets_tx;
3299 uint64_t copy_values_dispatched;
3300 uint64_t copy_values_not_dispatched;
3301 uint64_t copy_values_sent;
3302 uint64_t copy_values_not_sent;
3303 uint64_t copy_receive_list_length;
3304 value_list_t vl = VALUE_LIST_INIT;
3307 copy_octets_rx = stats_octets_rx;
3308 copy_octets_tx = stats_octets_tx;
3309 copy_packets_rx = stats_packets_rx;
3310 copy_packets_tx = stats_packets_tx;
3311 copy_values_dispatched = stats_values_dispatched;
3312 copy_values_not_dispatched = stats_values_not_dispatched;
3313 copy_values_sent = stats_values_sent;
3314 copy_values_not_sent = stats_values_not_sent;
3315 copy_receive_list_length = receive_list_length;
3317 /* Initialize `vl' */
3321 vl.interval = interval_g;
3322 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3323 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3325 /* Octets received / sent */
3326 vl.values[0].counter = (counter_t) copy_octets_rx;
3327 vl.values[1].counter = (counter_t) copy_octets_tx;
3328 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3329 plugin_dispatch_values_secure (&vl);
3331 /* Packets received / send */
3332 vl.values[0].counter = (counter_t) copy_packets_rx;
3333 vl.values[1].counter = (counter_t) copy_packets_tx;
3334 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3335 plugin_dispatch_values_secure (&vl);
3337 /* Values (not) dispatched and (not) send */
3338 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3341 vl.values[0].derive = (derive_t) copy_values_dispatched;
3342 sstrncpy (vl.type_instance, "dispatch-accepted",
3343 sizeof (vl.type_instance));
3344 plugin_dispatch_values_secure (&vl);
3346 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3347 sstrncpy (vl.type_instance, "dispatch-rejected",
3348 sizeof (vl.type_instance));
3349 plugin_dispatch_values_secure (&vl);
3351 vl.values[0].derive = (derive_t) copy_values_sent;
3352 sstrncpy (vl.type_instance, "send-accepted",
3353 sizeof (vl.type_instance));
3354 plugin_dispatch_values_secure (&vl);
3356 vl.values[0].derive = (derive_t) copy_values_not_sent;
3357 sstrncpy (vl.type_instance, "send-rejected",
3358 sizeof (vl.type_instance));
3359 plugin_dispatch_values_secure (&vl);
3361 /* Receive queue length */
3362 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3363 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3364 vl.type_instance[0] = 0;
3365 plugin_dispatch_values_secure (&vl);
3368 } /* }}} int network_stats_read */
3370 static int network_init (void)
3372 static _Bool have_init = false;
3374 /* Check if we were already initialized. If so, just return - there's
3375 * nothing more to do (for now, that is). */
3381 network_init_gcrypt ();
3384 if (network_config_stats != 0)
3385 plugin_register_read ("network", network_stats_read);
3387 plugin_register_shutdown ("network", network_shutdown);
3389 send_buffer = malloc (network_config_packet_size);
3390 if (send_buffer == NULL)
3392 ERROR ("network plugin: malloc failed.");
3395 network_init_buffer ();
3397 /* setup socket(s) and so on */
3398 if (sending_sockets != NULL)
3400 plugin_register_write ("network", network_write,
3401 /* user_data = */ NULL);
3402 plugin_register_notification ("network", network_notification,
3403 /* user_data = */ NULL);
3406 /* If no threads need to be started, return here. */
3407 if ((listen_sockets_num == 0)
3408 || ((dispatch_thread_running != 0)
3409 && (receive_thread_running != 0)))
3412 if (dispatch_thread_running == 0)
3415 status = pthread_create (&dispatch_thread_id,
3416 NULL /* no attributes */,
3418 NULL /* no argument */);
3422 ERROR ("network: pthread_create failed: %s",
3423 sstrerror (errno, errbuf,
3428 dispatch_thread_running = 1;
3432 if (receive_thread_running == 0)
3435 status = pthread_create (&receive_thread_id,
3436 NULL /* no attributes */,
3438 NULL /* no argument */);
3442 ERROR ("network: pthread_create failed: %s",
3443 sstrerror (errno, errbuf,
3448 receive_thread_running = 1;
3453 } /* int network_init */
3456 * The flush option of the network plugin cannot flush individual identifiers.
3457 * All the values are added to a buffer and sent when the buffer is full, the
3458 * requested value may or may not be in there, it's not worth finding out. We
3459 * just send the buffer if `flush' is called - if the requested value was in
3460 * there, good. If not, well, then there is nothing to flush.. -octo
3462 static int network_flush (int timeout,
3463 const char __attribute__((unused)) *identifier,
3464 user_data_t __attribute__((unused)) *user_data)
3466 pthread_mutex_lock (&send_buffer_lock);
3468 if (send_buffer_fill > 0)
3471 pthread_mutex_unlock (&send_buffer_lock);
3474 } /* int network_flush */
3476 void module_register (void)
3478 plugin_register_complex_config ("network", network_config);
3479 plugin_register_init ("network", network_init);
3480 plugin_register_flush ("network", network_flush,
3481 /* user_data = */ NULL);
3482 } /* void module_register */
3484 /* vim: set fdm=marker : */