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 _DEFAULT_SOURCE
26 #define _BSD_SOURCE /* For struct ip_mreq */
32 #include "configfile.h"
33 #include "utils_fbhash.h"
34 #include "utils_cache.h"
35 #include "utils_complain.h"
43 # include <netinet/in.h>
46 # include <arpa/inet.h>
56 # if defined __APPLE__
57 /* default xcode compiler throws warnings even when deprecated functionality
58 * is not used. -Werror breaks the build because of erroneous warnings.
59 * http://stackoverflow.com/questions/10556299/compiler-warnings-with-libgcrypt-v1-5-0/12830209#12830209
61 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
63 /* FreeBSD's copy of libgcrypt extends the existing GCRYPT_NO_DEPRECATED
64 * to properly hide all deprecated functionality.
65 * http://svnweb.freebsd.org/ports/head/security/libgcrypt/files/patch-src__gcrypt.h.in
67 # define GCRYPT_NO_DEPRECATED
69 # if defined __APPLE__
70 /* Re enable deprecation warnings */
71 # pragma GCC diagnostic warning "-Wdeprecated-declarations"
73 # if GCRYPT_VERSION_NUMBER < 0x010600
74 GCRY_THREAD_OPTION_PTHREAD_IMPL;
78 #ifndef IPV6_ADD_MEMBERSHIP
79 # ifdef IPV6_JOIN_GROUP
80 # define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
82 # error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
84 #endif /* !IP_ADD_MEMBERSHIP */
87 * Maximum size required for encryption / signing:
89 * 42 bytes for the encryption header
90 * + 64 bytes for the username
94 #define BUFF_SIG_SIZE 106
99 #define SECURITY_LEVEL_NONE 0
101 # define SECURITY_LEVEL_SIGN 1
102 # define SECURITY_LEVEL_ENCRYPT 2
104 struct sockent_client
107 struct sockaddr_storage *addr;
113 gcry_cipher_hd_t cypher;
114 unsigned char password_hash[32];
116 cdtime_t next_resolve_reconnect;
117 cdtime_t resolve_interval;
120 struct sockent_server
128 gcry_cipher_hd_t cypher;
132 typedef struct sockent
134 #define SOCKENT_TYPE_CLIENT 1
135 #define SOCKENT_TYPE_SERVER 2
144 struct sockent_client client;
145 struct sockent_server server;
148 struct sockent *next;
151 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
152 * 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
153 * +-------+-----------------------+-------------------------------+
154 * ! Ver. ! ! Length !
155 * +-------+-----------------------+-------------------------------+
162 typedef struct part_header_s part_header_t;
164 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
165 * 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
166 * +-------------------------------+-------------------------------+
168 * +-------------------------------+-------------------------------+
169 * : (Length - 4) Bytes :
170 * +---------------------------------------------------------------+
177 typedef struct part_string_s part_string_t;
179 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
180 * 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
181 * +-------------------------------+-------------------------------+
183 * +-------------------------------+-------------------------------+
184 * : (Length - 4 == 2 || 4 || 8) Bytes :
185 * +---------------------------------------------------------------+
192 typedef struct part_number_s part_number_t;
194 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
195 * 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
196 * +-------------------------------+-------------------------------+
198 * +-------------------------------+---------------+---------------+
199 * ! Num of values ! Type0 ! Type1 !
200 * +-------------------------------+---------------+---------------+
203 * +---------------------------------------------------------------+
206 * +---------------------------------------------------------------+
211 uint16_t *num_values;
212 uint8_t *values_types;
215 typedef struct part_values_s part_values_t;
217 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
218 * 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
219 * +-------------------------------+-------------------------------+
221 * +-------------------------------+-------------------------------+
222 * ! Hash (Bits 0 - 31) !
224 * ! Hash (Bits 224 - 255) !
225 * +---------------------------------------------------------------+
228 #define PART_SIGNATURE_SHA256_SIZE 36
229 struct part_signature_sha256_s
232 unsigned char hash[32];
235 typedef struct part_signature_sha256_s part_signature_sha256_t;
237 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
238 * 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
239 * +-------------------------------+-------------------------------+
241 * +-------------------------------+-------------------------------+
242 * ! Original length ! Padding (0 - 15 bytes) !
243 * +-------------------------------+-------------------------------+
244 * ! Hash (Bits 0 - 31) !
246 * ! Hash (Bits 128 - 159) !
247 * +---------------------------------------------------------------+
250 #define PART_ENCRYPTION_AES256_SIZE 42
251 struct part_encryption_aes256_s
254 uint16_t username_length;
256 unsigned char iv[16];
258 unsigned char hash[20];
262 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
264 struct receive_list_entry_s
269 struct receive_list_entry_s *next;
271 typedef struct receive_list_entry_s receive_list_entry_t;
276 static int network_config_ttl = 0;
277 /* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
278 static size_t network_config_packet_size = 1452;
279 static _Bool network_config_forward = 0;
280 static _Bool network_config_stats = 0;
282 static sockent_t *sending_sockets = NULL;
284 static receive_list_entry_t *receive_list_head = NULL;
285 static receive_list_entry_t *receive_list_tail = NULL;
286 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
287 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
288 static uint64_t receive_list_length = 0;
290 static sockent_t *listen_sockets = NULL;
291 static struct pollfd *listen_sockets_pollfd = NULL;
292 static size_t listen_sockets_num = 0;
294 /* The receive and dispatch threads will run as long as `listen_loop' is set to
296 static int listen_loop = 0;
297 static int receive_thread_running = 0;
298 static pthread_t receive_thread_id;
299 static int dispatch_thread_running = 0;
300 static pthread_t dispatch_thread_id;
302 /* Buffer in which to-be-sent network packets are constructed. */
303 static char *send_buffer;
304 static char *send_buffer_ptr;
305 static int send_buffer_fill;
306 static cdtime_t send_buffer_last_update;
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 derive_t stats_octets_rx = 0;
317 static derive_t stats_octets_tx = 0;
318 static derive_t stats_packets_rx = 0;
319 static derive_t stats_packets_tx = 0;
320 static derive_t stats_values_dispatched = 0;
321 static derive_t stats_values_not_dispatched = 0;
322 static derive_t stats_values_sent = 0;
323 static derive_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) /* {{{ */
350 if (network_config_forward)
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 for (notification_meta_t *ptr = n->meta; ptr != NULL; ptr = ptr->next)
374 if ((strcmp ("network:received", ptr->name) == 0)
375 && (ptr->type == NM_TYPE_BOOLEAN))
376 return ((_Bool) ptr->nm_value.nm_boolean);
379 } /* }}} _Bool check_notify_received */
381 static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
383 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
389 received = check_notify_received (n);
391 if (network_config_forward && received)
393 c_complain_once (LOG_ERR, &complain_forwarding,
394 "network plugin: A notification has been received via the network "
395 "and forwarding is enabled. Forwarding of notifications is currently "
396 "not supported, because there is not loop-deteciton available. "
397 "Please contact the collectd mailing list if you need this "
401 /* By default, only *send* value lists that were not *received* by the
404 } /* }}} _Bool check_send_notify_okay */
406 static int network_dispatch_values (value_list_t *vl, /* {{{ */
407 const char *username)
412 || (strlen (vl->host) == 0)
413 || (strlen (vl->plugin) == 0)
414 || (strlen (vl->type) == 0))
417 if (!check_receive_okay (vl))
420 char name[6*DATA_MAX_NAME_LEN];
421 FORMAT_VL (name, sizeof (name), vl);
422 name[sizeof (name) - 1] = 0;
423 DEBUG ("network plugin: network_dispatch_values: "
424 "NOT dispatching %s.", name);
426 stats_values_not_dispatched++;
430 assert (vl->meta == NULL);
432 vl->meta = meta_data_create ();
433 if (vl->meta == NULL)
435 ERROR ("network plugin: meta_data_create failed.");
439 status = meta_data_add_boolean (vl->meta, "network:received", 1);
442 ERROR ("network plugin: meta_data_add_boolean failed.");
443 meta_data_destroy (vl->meta);
448 if (username != NULL)
450 status = meta_data_add_string (vl->meta, "network:username", username);
453 ERROR ("network plugin: meta_data_add_string failed.");
454 meta_data_destroy (vl->meta);
460 plugin_dispatch_values (vl);
461 stats_values_dispatched++;
463 meta_data_destroy (vl->meta);
467 } /* }}} int network_dispatch_values */
469 static int network_dispatch_notification (notification_t *n) /* {{{ */
473 assert (n->meta == NULL);
475 status = plugin_notification_meta_add_boolean (n, "network:received", 1);
478 ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
479 plugin_notification_meta_free (n->meta);
484 status = plugin_dispatch_notification (n);
486 plugin_notification_meta_free (n->meta);
490 } /* }}} int network_dispatch_notification */
493 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 # if GCRYPT_VERSION_NUMBER < 0x010600
511 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
514 ERROR ("network plugin: gcry_control (GCRYCTL_SET_THREAD_CBS) failed: %s", gcry_strerror (err));
519 gcry_check_version (NULL);
521 err = gcry_control (GCRYCTL_INIT_SECMEM, 32768);
524 ERROR ("network plugin: gcry_control (GCRYCTL_INIT_SECMEM) failed: %s", gcry_strerror (err));
528 gcry_control (GCRYCTL_INITIALIZATION_FINISHED);
529 } /* }}} void network_init_gcrypt */
531 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
532 const void *iv, size_t iv_size, const char *username)
535 gcry_cipher_hd_t *cyper_ptr;
536 unsigned char password_hash[32];
538 if (se->type == SOCKENT_TYPE_CLIENT)
540 cyper_ptr = &se->data.client.cypher;
541 memcpy (password_hash, se->data.client.password_hash,
542 sizeof (password_hash));
548 cyper_ptr = &se->data.server.cypher;
550 if (username == NULL)
553 secret = fbh_get (se->data.server.userdb, username);
557 gcry_md_hash_buffer (GCRY_MD_SHA256,
559 secret, strlen (secret));
564 if (*cyper_ptr == NULL)
566 err = gcry_cipher_open (cyper_ptr,
567 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
570 ERROR ("network plugin: gcry_cipher_open returned: %s",
571 gcry_strerror (err));
578 gcry_cipher_reset (*cyper_ptr);
580 assert (*cyper_ptr != NULL);
582 err = gcry_cipher_setkey (*cyper_ptr,
583 password_hash, sizeof (password_hash));
586 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
587 gcry_strerror (err));
588 gcry_cipher_close (*cyper_ptr);
593 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
596 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
597 gcry_strerror (err));
598 gcry_cipher_close (*cyper_ptr);
604 } /* }}} int network_get_aes256_cypher */
605 #endif /* HAVE_LIBGCRYPT */
607 static int write_part_values (char **ret_buffer, size_t *ret_buffer_len,
608 const data_set_t *ds, const value_list_t *vl)
614 part_header_t pkg_ph;
615 uint16_t pkg_num_values;
616 uint8_t *pkg_values_types;
621 num_values = vl->values_len;
622 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
623 + (num_values * sizeof (uint8_t))
624 + (num_values * sizeof (value_t));
626 if (*ret_buffer_len < packet_len)
629 pkg_values_types = malloc (num_values * sizeof (*pkg_values_types));
630 if (pkg_values_types == NULL)
632 ERROR ("network plugin: write_part_values: malloc failed.");
636 pkg_values = malloc (num_values * sizeof (*pkg_values));
637 if (pkg_values == NULL)
639 free (pkg_values_types);
640 ERROR ("network plugin: write_part_values: malloc failed.");
644 pkg_ph.type = htons (TYPE_VALUES);
645 pkg_ph.length = htons (packet_len);
647 pkg_num_values = htons ((uint16_t) vl->values_len);
649 for (int i = 0; i < num_values; i++)
651 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
652 switch (ds->ds[i].type)
654 case DS_TYPE_COUNTER:
655 pkg_values[i].counter = htonll (vl->values[i].counter);
659 pkg_values[i].gauge = htond (vl->values[i].gauge);
663 pkg_values[i].derive = htonll (vl->values[i].derive);
666 case DS_TYPE_ABSOLUTE:
667 pkg_values[i].absolute = htonll (vl->values[i].absolute);
671 free (pkg_values_types);
673 ERROR ("network plugin: write_part_values: "
674 "Unknown data source type: %i",
677 } /* switch (ds->ds[i].type) */
678 } /* for (num_values) */
681 * Use `memcpy' to write everything to the buffer, because the pointer
682 * may be unaligned and some architectures, such as SPARC, can't handle
685 packet_ptr = *ret_buffer;
687 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
688 offset += sizeof (pkg_ph);
689 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
690 offset += sizeof (pkg_num_values);
691 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
692 offset += num_values * sizeof (uint8_t);
693 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
694 offset += num_values * sizeof (value_t);
696 assert (offset == packet_len);
698 *ret_buffer = packet_ptr + packet_len;
699 *ret_buffer_len -= packet_len;
701 free (pkg_values_types);
705 } /* int write_part_values */
707 static int write_part_number (char **ret_buffer, size_t *ret_buffer_len,
708 int type, uint64_t value)
713 part_header_t pkg_head;
718 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
720 if (*ret_buffer_len < packet_len)
723 pkg_head.type = htons (type);
724 pkg_head.length = htons (packet_len);
725 pkg_value = htonll (value);
727 packet_ptr = *ret_buffer;
729 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
730 offset += sizeof (pkg_head);
731 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
732 offset += sizeof (pkg_value);
734 assert (offset == packet_len);
736 *ret_buffer = packet_ptr + packet_len;
737 *ret_buffer_len -= packet_len;
740 } /* int write_part_number */
742 static int write_part_string (char **ret_buffer, size_t *ret_buffer_len,
743 int type, const char *str, size_t str_len)
753 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
754 if (*ret_buffer_len < buffer_len)
757 pkg_type = htons (type);
758 pkg_length = htons (buffer_len);
760 buffer = *ret_buffer;
762 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
763 offset += sizeof (pkg_type);
764 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
765 offset += sizeof (pkg_length);
766 memcpy (buffer + offset, str, str_len);
768 memset (buffer + offset, '\0', 1);
771 assert (offset == buffer_len);
773 *ret_buffer = buffer + buffer_len;
774 *ret_buffer_len -= buffer_len;
777 } /* int write_part_string */
779 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
780 value_t **ret_values, size_t *ret_num_values)
782 char *buffer = *ret_buffer;
783 size_t buffer_len = *ret_buffer_len;
797 NOTICE ("network plugin: packet is too short: "
798 "buffer_len = %zu", buffer_len);
802 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
803 buffer += sizeof (tmp16);
804 pkg_type = ntohs (tmp16);
806 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
807 buffer += sizeof (tmp16);
808 pkg_length = ntohs (tmp16);
810 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
811 buffer += sizeof (tmp16);
812 pkg_numval = (size_t) ntohs (tmp16);
814 assert (pkg_type == TYPE_VALUES);
816 exp_size = 3 * sizeof (uint16_t)
817 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
818 if (buffer_len < exp_size)
820 WARNING ("network plugin: parse_part_values: "
822 "Chunk of size %zu expected, "
823 "but buffer has only %zu bytes left.",
824 exp_size, buffer_len);
827 assert (pkg_numval <= ((buffer_len - 6) / 9));
829 if (pkg_length != exp_size)
831 WARNING ("network plugin: parse_part_values: "
832 "Length and number of values "
833 "in the packet don't match.");
837 pkg_types = calloc (pkg_numval, sizeof (*pkg_types));
838 pkg_values = calloc (pkg_numval, sizeof (*pkg_values));
839 if ((pkg_types == NULL) || (pkg_values == NULL))
843 ERROR ("network plugin: parse_part_values: calloc failed.");
847 memcpy (pkg_types, buffer, pkg_numval * sizeof (*pkg_types));
848 buffer += pkg_numval * sizeof (*pkg_types);
849 memcpy (pkg_values, buffer, pkg_numval * sizeof (*pkg_values));
850 buffer += pkg_numval * sizeof (*pkg_values);
852 for (size_t i = 0; i < pkg_numval; i++)
854 switch (pkg_types[i])
856 case DS_TYPE_COUNTER:
857 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
861 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
865 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
868 case DS_TYPE_ABSOLUTE:
869 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
873 NOTICE ("network plugin: parse_part_values: "
874 "Don't know how to handle data source type %"PRIu8,
879 } /* switch (pkg_types[i]) */
882 *ret_buffer = buffer;
883 *ret_buffer_len = buffer_len - pkg_length;
884 *ret_num_values = pkg_numval;
885 *ret_values = pkg_values;
890 } /* int parse_part_values */
892 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
895 char *buffer = *ret_buffer;
896 size_t buffer_len = *ret_buffer_len;
900 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
904 if (buffer_len < exp_size)
906 WARNING ("network plugin: parse_part_number: "
908 "Chunk of size %zu expected, "
909 "but buffer has only %zu bytes left.",
910 exp_size, buffer_len);
914 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
915 buffer += sizeof (tmp16);
916 /* pkg_type = ntohs (tmp16); */
918 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
919 buffer += sizeof (tmp16);
920 pkg_length = ntohs (tmp16);
922 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
923 buffer += sizeof (tmp64);
924 *value = ntohll (tmp64);
926 *ret_buffer = buffer;
927 *ret_buffer_len = buffer_len - pkg_length;
930 } /* int parse_part_number */
932 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
933 char *output, size_t const output_len)
935 char *buffer = *ret_buffer;
936 size_t buffer_len = *ret_buffer_len;
939 size_t const header_size = 2 * sizeof (uint16_t);
947 if (buffer_len < header_size)
949 WARNING ("network plugin: parse_part_string: "
951 "Chunk of at least size %zu expected, "
952 "but buffer has only %zu bytes left.",
953 header_size, buffer_len);
957 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
958 buffer += sizeof (tmp16);
959 /* pkg_type = ntohs (tmp16); */
961 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
962 buffer += sizeof (tmp16);
963 pkg_length = ntohs (tmp16);
964 payload_size = ((size_t) pkg_length) - header_size;
966 /* Check that packet fits in the input buffer */
967 if (pkg_length > buffer_len)
969 WARNING ("network plugin: parse_part_string: "
971 "Chunk of size %"PRIu16" received, "
972 "but buffer has only %zu bytes left.",
973 pkg_length, buffer_len);
977 /* Check that pkg_length is in the valid range */
978 if (pkg_length <= header_size)
980 WARNING ("network plugin: parse_part_string: "
982 "Header claims this packet is only %hu "
983 "bytes long.", pkg_length);
987 /* Check that the package data fits into the output buffer.
988 * The previous if-statement ensures that:
989 * `pkg_length > header_size' */
990 if (output_len < payload_size)
992 WARNING ("network plugin: parse_part_string: "
994 "Output buffer holds %zu bytes, "
995 "which is too small to hold the received "
997 output_len, payload_size);
1001 /* All sanity checks successfull, let's copy the data over */
1002 memcpy ((void *) output, (void *) buffer, payload_size);
1003 buffer += payload_size;
1005 /* For some very weird reason '\0' doesn't do the trick on SPARC in
1006 * this statement. */
1007 if (output[payload_size - 1] != 0)
1009 WARNING ("network plugin: parse_part_string: "
1010 "Received string does not end "
1011 "with a NULL-byte.");
1015 *ret_buffer = buffer;
1016 *ret_buffer_len = buffer_len - pkg_length;
1019 } /* int parse_part_string */
1021 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
1022 * parse_packet and vice versa. */
1023 #define PP_SIGNED 0x01
1024 #define PP_ENCRYPTED 0x02
1025 static int parse_packet (sockent_t *se,
1026 void *buffer, size_t buffer_size, int flags,
1027 const char *username);
1029 #define BUFFER_READ(p,s) do { \
1030 memcpy ((p), buffer + buffer_offset, (s)); \
1031 buffer_offset += (s); \
1035 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1036 void **ret_buffer, size_t *ret_buffer_len, int flags)
1038 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
1042 size_t buffer_offset;
1044 size_t username_len;
1047 part_signature_sha256_t pss;
1048 uint16_t pss_head_length;
1049 char hash[sizeof (pss.hash)];
1053 unsigned char *hash_ptr;
1055 buffer = *ret_buffer;
1056 buffer_len = *ret_buffer_len;
1059 if (se->data.server.userdb == NULL)
1061 c_complain (LOG_NOTICE, &complain_no_users,
1062 "network plugin: Received signed network packet but can't verify it "
1063 "because no user DB has been configured. Will accept it.");
1067 /* Check if the buffer has enough data for this structure. */
1068 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1071 /* Read type and length header */
1072 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1073 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1074 pss_head_length = ntohs (pss.head.length);
1076 /* Check if the `pss_head_length' is within bounds. */
1077 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1078 || (pss_head_length > buffer_len))
1080 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1084 /* Copy the hash. */
1085 BUFFER_READ (pss.hash, sizeof (pss.hash));
1087 /* Calculate username length (without null byte) and allocate memory */
1088 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1089 pss.username = malloc (username_len + 1);
1090 if (pss.username == NULL)
1093 /* Read the username */
1094 BUFFER_READ (pss.username, username_len);
1095 pss.username[username_len] = 0;
1097 assert (buffer_offset == pss_head_length);
1099 /* Query the password */
1100 secret = fbh_get (se->data.server.userdb, pss.username);
1103 ERROR ("network plugin: Unknown user: %s", pss.username);
1104 sfree (pss.username);
1108 /* Create a hash device and check the HMAC */
1110 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1113 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1114 gcry_strerror (err));
1116 sfree (pss.username);
1120 err = gcry_md_setkey (hd, secret, strlen (secret));
1123 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1126 sfree (pss.username);
1131 buffer + PART_SIGNATURE_SHA256_SIZE,
1132 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1133 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1134 if (hash_ptr == NULL)
1136 ERROR ("network plugin: gcry_md_read failed.");
1139 sfree (pss.username);
1142 memcpy (hash, hash_ptr, sizeof (hash));
1148 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1150 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1155 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1156 flags | PP_SIGNED, pss.username);
1160 sfree (pss.username);
1162 *ret_buffer = buffer + buffer_len;
1163 *ret_buffer_len = 0;
1166 } /* }}} int parse_part_sign_sha256 */
1167 /* #endif HAVE_LIBGCRYPT */
1169 #else /* if !HAVE_LIBGCRYPT */
1170 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1171 void **ret_buffer, size_t *ret_buffer_size, int flags)
1173 static int warning_has_been_printed = 0;
1177 size_t buffer_offset;
1180 part_signature_sha256_t pss;
1182 buffer = *ret_buffer;
1183 buffer_size = *ret_buffer_size;
1186 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1189 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1190 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1191 part_len = ntohs (pss.head.length);
1193 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1194 || (part_len > buffer_size))
1197 if (warning_has_been_printed == 0)
1199 WARNING ("network plugin: Received signed packet, but the network "
1200 "plugin was not linked with libgcrypt, so I cannot "
1201 "verify the signature. The packet will be accepted.");
1202 warning_has_been_printed = 1;
1205 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1206 /* username = */ NULL);
1208 *ret_buffer = buffer + buffer_size;
1209 *ret_buffer_size = 0;
1212 } /* }}} int parse_part_sign_sha256 */
1213 #endif /* !HAVE_LIBGCRYPT */
1216 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1217 void **ret_buffer, size_t *ret_buffer_len,
1220 char *buffer = *ret_buffer;
1221 size_t buffer_len = *ret_buffer_len;
1224 size_t buffer_offset;
1225 uint16_t username_len;
1226 part_encryption_aes256_t pea;
1227 unsigned char hash[sizeof (pea.hash)] = { 0 };
1229 gcry_cipher_hd_t cypher;
1232 /* Make sure at least the header if available. */
1233 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1235 NOTICE ("network plugin: parse_part_encr_aes256: "
1236 "Discarding short packet.");
1242 /* Copy the unencrypted information into `pea'. */
1243 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1244 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1246 /* Check the `part size'. */
1247 part_size = ntohs (pea.head.length);
1248 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1249 || (part_size > buffer_len))
1251 NOTICE ("network plugin: parse_part_encr_aes256: "
1252 "Discarding part with invalid size.");
1256 /* Read the username */
1257 BUFFER_READ (&username_len, sizeof (username_len));
1258 username_len = ntohs (username_len);
1260 if ((username_len == 0)
1261 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1263 NOTICE ("network plugin: parse_part_encr_aes256: "
1264 "Discarding part with invalid username length.");
1268 assert (username_len > 0);
1269 pea.username = malloc (username_len + 1);
1270 if (pea.username == NULL)
1272 BUFFER_READ (pea.username, username_len);
1273 pea.username[username_len] = 0;
1275 /* Last but not least, the initialization vector */
1276 BUFFER_READ (pea.iv, sizeof (pea.iv));
1278 /* Make sure we are at the right position */
1279 assert (buffer_offset == (username_len +
1280 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1282 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1286 sfree (pea.username);
1290 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1291 assert (payload_len > 0);
1293 /* Decrypt the packet in-place */
1294 err = gcry_cipher_decrypt (cypher,
1295 buffer + buffer_offset,
1296 part_size - buffer_offset,
1297 /* in = */ NULL, /* in len = */ 0);
1300 sfree (pea.username);
1301 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1302 gcry_strerror (err));
1307 BUFFER_READ (pea.hash, sizeof (pea.hash));
1309 /* Make sure we're at the right position - again */
1310 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1311 assert (buffer_offset == (part_size - payload_len));
1313 /* Check hash sum */
1314 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1315 buffer + buffer_offset, payload_len);
1316 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1318 sfree (pea.username);
1319 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1323 parse_packet (se, buffer + buffer_offset, payload_len,
1324 flags | PP_ENCRYPTED, pea.username);
1326 /* XXX: Free pea.username?!? */
1328 /* Update return values */
1329 *ret_buffer = buffer + part_size;
1330 *ret_buffer_len = buffer_len - part_size;
1332 sfree (pea.username);
1335 } /* }}} int parse_part_encr_aes256 */
1336 /* #endif HAVE_LIBGCRYPT */
1338 #else /* if !HAVE_LIBGCRYPT */
1339 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1340 void **ret_buffer, size_t *ret_buffer_size, int flags)
1342 static int warning_has_been_printed = 0;
1346 size_t buffer_offset;
1351 buffer = *ret_buffer;
1352 buffer_size = *ret_buffer_size;
1355 /* parse_packet assures this minimum size. */
1356 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1358 BUFFER_READ (&ph.type, sizeof (ph.type));
1359 BUFFER_READ (&ph.length, sizeof (ph.length));
1360 ph_length = ntohs (ph.length);
1362 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1363 || (ph_length > buffer_size))
1365 ERROR ("network plugin: AES-256 encrypted part "
1366 "with invalid length received.");
1370 if (warning_has_been_printed == 0)
1372 WARNING ("network plugin: Received encrypted packet, but the network "
1373 "plugin was not linked with libgcrypt, so I cannot "
1374 "decrypt it. The part will be discarded.");
1375 warning_has_been_printed = 1;
1378 *ret_buffer = (void *) (((char *) *ret_buffer) + ph_length);
1379 *ret_buffer_size -= ph_length;
1382 } /* }}} int parse_part_encr_aes256 */
1383 #endif /* !HAVE_LIBGCRYPT */
1387 static int parse_packet (sockent_t *se, /* {{{ */
1388 void *buffer, size_t buffer_size, int flags,
1389 const char *username)
1393 value_list_t vl = VALUE_LIST_INIT;
1394 notification_t n = { 0 };
1397 int packet_was_signed = (flags & PP_SIGNED);
1398 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1399 int printed_ignore_warning = 0;
1400 #endif /* HAVE_LIBGCRYPT */
1403 memset (&vl, '\0', sizeof (vl));
1406 while ((status == 0) && (0 < buffer_size)
1407 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1409 uint16_t pkg_length;
1412 memcpy ((void *) &pkg_type,
1415 memcpy ((void *) &pkg_length,
1416 (void *) (((char *) buffer) + sizeof (pkg_type)),
1417 sizeof (pkg_length));
1419 pkg_length = ntohs (pkg_length);
1420 pkg_type = ntohs (pkg_type);
1422 if (pkg_length > buffer_size)
1424 /* Ensure that this loop terminates eventually */
1425 if (pkg_length < (2 * sizeof (uint16_t)))
1428 if (pkg_type == TYPE_ENCR_AES256)
1430 status = parse_part_encr_aes256 (se,
1431 &buffer, &buffer_size, flags);
1434 ERROR ("network plugin: Decrypting AES256 "
1436 "with status %i.", status);
1441 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1442 && (packet_was_encrypted == 0))
1444 if (printed_ignore_warning == 0)
1446 INFO ("network plugin: Unencrypted packet or "
1447 "part has been ignored.");
1448 printed_ignore_warning = 1;
1450 buffer = ((char *) buffer) + pkg_length;
1451 buffer_size -= (size_t) pkg_length;
1454 #endif /* HAVE_LIBGCRYPT */
1455 else if (pkg_type == TYPE_SIGN_SHA256)
1457 status = parse_part_sign_sha256 (se,
1458 &buffer, &buffer_size, flags);
1461 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1463 "with status %i.", status);
1468 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1469 && (packet_was_encrypted == 0)
1470 && (packet_was_signed == 0))
1472 if (printed_ignore_warning == 0)
1474 INFO ("network plugin: Unsigned packet or "
1475 "part has been ignored.");
1476 printed_ignore_warning = 1;
1478 buffer = ((char *) buffer) + pkg_length;
1479 buffer_size -= (size_t) pkg_length;
1482 #endif /* HAVE_LIBGCRYPT */
1483 else if (pkg_type == TYPE_VALUES)
1485 status = parse_part_values (&buffer, &buffer_size,
1486 &vl.values, &vl.values_len);
1490 network_dispatch_values (&vl, username);
1494 else if (pkg_type == TYPE_TIME)
1497 status = parse_part_number (&buffer, &buffer_size,
1501 vl.time = TIME_T_TO_CDTIME_T (tmp);
1502 n.time = TIME_T_TO_CDTIME_T (tmp);
1505 else if (pkg_type == TYPE_TIME_HR)
1508 status = parse_part_number (&buffer, &buffer_size,
1512 vl.time = (cdtime_t) tmp;
1513 n.time = (cdtime_t) tmp;
1516 else if (pkg_type == TYPE_INTERVAL)
1519 status = parse_part_number (&buffer, &buffer_size,
1522 vl.interval = TIME_T_TO_CDTIME_T (tmp);
1524 else if (pkg_type == TYPE_INTERVAL_HR)
1527 status = parse_part_number (&buffer, &buffer_size,
1530 vl.interval = (cdtime_t) tmp;
1532 else if (pkg_type == TYPE_HOST)
1534 status = parse_part_string (&buffer, &buffer_size,
1535 vl.host, sizeof (vl.host));
1537 sstrncpy (n.host, vl.host, sizeof (n.host));
1539 else if (pkg_type == TYPE_PLUGIN)
1541 status = parse_part_string (&buffer, &buffer_size,
1542 vl.plugin, sizeof (vl.plugin));
1544 sstrncpy (n.plugin, vl.plugin,
1547 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1549 status = parse_part_string (&buffer, &buffer_size,
1551 sizeof (vl.plugin_instance));
1553 sstrncpy (n.plugin_instance,
1555 sizeof (n.plugin_instance));
1557 else if (pkg_type == TYPE_TYPE)
1559 status = parse_part_string (&buffer, &buffer_size,
1560 vl.type, sizeof (vl.type));
1562 sstrncpy (n.type, vl.type, sizeof (n.type));
1564 else if (pkg_type == TYPE_TYPE_INSTANCE)
1566 status = parse_part_string (&buffer, &buffer_size,
1568 sizeof (vl.type_instance));
1570 sstrncpy (n.type_instance, vl.type_instance,
1571 sizeof (n.type_instance));
1573 else if (pkg_type == TYPE_MESSAGE)
1575 status = parse_part_string (&buffer, &buffer_size,
1576 n.message, sizeof (n.message));
1582 else if ((n.severity != NOTIF_FAILURE)
1583 && (n.severity != NOTIF_WARNING)
1584 && (n.severity != NOTIF_OKAY))
1586 INFO ("network plugin: "
1587 "Ignoring notification with "
1588 "unknown severity %i.",
1591 else if (n.time == 0)
1593 INFO ("network plugin: "
1594 "Ignoring notification with "
1597 else if (strlen (n.message) == 0)
1599 INFO ("network plugin: "
1600 "Ignoring notification with "
1601 "an empty message.");
1605 network_dispatch_notification (&n);
1608 else if (pkg_type == TYPE_SEVERITY)
1611 status = parse_part_number (&buffer, &buffer_size,
1614 n.severity = (int) tmp;
1618 DEBUG ("network plugin: parse_packet: Unknown part"
1619 " type: 0x%04hx", pkg_type);
1620 buffer = ((char *) buffer) + pkg_length;
1621 buffer_size -= (size_t) pkg_length;
1623 } /* while (buffer_size > sizeof (part_header_t)) */
1625 if (status == 0 && buffer_size > 0)
1626 WARNING ("network plugin: parse_packet: Received truncated "
1627 "packet, try increasing `MaxPacketSize'");
1630 } /* }}} int parse_packet */
1632 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1641 sfree (sec->username);
1642 sfree (sec->password);
1643 if (sec->cypher != NULL)
1644 gcry_cipher_close (sec->cypher);
1646 } /* }}} void free_sockent_client */
1648 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1650 for (size_t i = 0; i < ses->fd_num; i++)
1652 if (ses->fd[i] >= 0)
1661 sfree (ses->auth_file);
1662 fbh_destroy (ses->userdb);
1663 if (ses->cypher != NULL)
1664 gcry_cipher_close (ses->cypher);
1666 } /* }}} void free_sockent_server */
1668 static void sockent_destroy (sockent_t *se) /* {{{ */
1672 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1679 sfree (se->service);
1681 if (se->type == SOCKENT_TYPE_CLIENT)
1682 free_sockent_client (&se->data.client);
1684 free_sockent_server (&se->data.server);
1689 } /* }}} void sockent_destroy */
1692 * int network_set_ttl
1694 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1695 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1697 * The `struct addrinfo' is used to destinguish between unicast and multicast
1700 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1702 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1703 network_config_ttl);
1705 assert (se->type == SOCKENT_TYPE_CLIENT);
1707 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1710 if (ai->ai_family == AF_INET)
1712 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1715 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1716 optname = IP_MULTICAST_TTL;
1720 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1721 &network_config_ttl,
1722 sizeof (network_config_ttl)) != 0)
1725 ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
1726 sstrerror (errno, errbuf, sizeof (errbuf)));
1730 else if (ai->ai_family == AF_INET6)
1732 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1733 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1736 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1737 optname = IPV6_MULTICAST_HOPS;
1739 optname = IPV6_UNICAST_HOPS;
1741 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1742 &network_config_ttl,
1743 sizeof (network_config_ttl)) != 0)
1746 ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
1747 sstrerror (errno, errbuf,
1754 } /* int network_set_ttl */
1756 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1758 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1761 assert (se->type == SOCKENT_TYPE_CLIENT);
1763 if (ai->ai_family == AF_INET)
1765 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1767 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1769 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1770 /* If possible, use the "ip_mreqn" structure which has
1771 * an "interface index" member. Using the interface
1772 * index is preferred here, because of its similarity
1773 * to the way IPv6 handles this. Unfortunately, it
1774 * appears not to be portable. */
1775 struct ip_mreqn mreq = {
1776 .imr_multiaddr.s_addr = addr->sin_addr.s_addr,
1777 .imr_address.s_addr = ntohl (INADDR_ANY),
1778 .imr_ifindex = se->interface
1781 struct ip_mreq mreq = {
1782 .imr_multiaddr.s_addr = addr->sin_addr.s_addr,
1783 .imr_interface.s_addr = ntohl (INADDR_ANY)
1787 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1788 &mreq, sizeof (mreq)) != 0)
1791 ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
1792 sstrerror (errno, errbuf, sizeof (errbuf)));
1799 else if (ai->ai_family == AF_INET6)
1801 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1803 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1805 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1807 sizeof (se->interface)) != 0)
1810 ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
1811 sstrerror (errno, errbuf,
1820 /* else: Not a multicast interface. */
1821 if (se->interface != 0)
1823 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1824 char interface_name[IFNAMSIZ];
1826 if (if_indextoname (se->interface, interface_name) == NULL)
1829 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1831 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1833 sizeof(interface_name)) == -1 )
1836 ERROR ("network plugin: setsockopt (bind-if): %s",
1837 sstrerror (errno, errbuf, sizeof (errbuf)));
1840 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1843 WARNING ("network plugin: Cannot set the interface on a unicast "
1845 # if !defined(SO_BINDTODEVICE)
1846 "the \"SO_BINDTODEVICE\" socket option "
1848 "the \"if_indextoname\" function "
1850 "is not available on your system.");
1856 } /* }}} network_set_interface */
1858 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1867 /* allow multiple sockets to use the same PORT number */
1868 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1869 &yes, sizeof(yes)) == -1) {
1871 ERROR ("network plugin: setsockopt (reuseaddr): %s",
1872 sstrerror (errno, errbuf, sizeof (errbuf)));
1876 DEBUG ("fd = %i; calling `bind'", fd);
1878 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1882 sstrerror (errno, errbuf, sizeof (errbuf)));
1886 if (ai->ai_family == AF_INET)
1888 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1889 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1891 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1892 struct ip_mreqn mreq;
1894 struct ip_mreq mreq;
1897 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1899 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1900 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1901 /* Set the interface using the interface index if
1902 * possible (available). Unfortunately, the struct
1903 * ip_mreqn is not portable. */
1904 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1905 mreq.imr_ifindex = interface_idx;
1907 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1910 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1911 &loop, sizeof (loop)) == -1)
1914 ERROR ("network plugin: setsockopt (multicast-loop): %s",
1915 sstrerror (errno, errbuf,
1920 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1921 &mreq, sizeof (mreq)) == -1)
1924 ERROR ("network plugin: setsockopt (add-membership): %s",
1925 sstrerror (errno, errbuf,
1933 else if (ai->ai_family == AF_INET6)
1935 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1936 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1937 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1939 struct ipv6_mreq mreq;
1941 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1943 memcpy (&mreq.ipv6mr_multiaddr,
1945 sizeof (addr->sin6_addr));
1947 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1948 * ipv6mr_interface may be set to zeroes to
1949 * choose the default multicast interface or to
1950 * the index of a particular multicast-capable
1951 * interface if the host is multihomed.
1952 * Membership is associ-associated with a
1953 * single interface; programs running on
1954 * multihomed hosts may need to join the same
1955 * group on more than one interface.*/
1956 mreq.ipv6mr_interface = interface_idx;
1958 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1959 &loop, sizeof (loop)) == -1)
1962 ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
1963 sstrerror (errno, errbuf,
1968 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1969 &mreq, sizeof (mreq)) == -1)
1972 ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
1973 sstrerror (errno, errbuf,
1982 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1983 /* if a specific interface was set, bind the socket to it. But to avoid
1984 * possible problems with multicast routing, only do that for non-multicast
1986 if (interface_idx != 0)
1988 char interface_name[IFNAMSIZ];
1990 if (if_indextoname (interface_idx, interface_name) == NULL)
1993 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1995 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1997 sizeof(interface_name)) == -1 )
2000 ERROR ("network plugin: setsockopt (bind-if): %s",
2001 sstrerror (errno, errbuf, sizeof (errbuf)));
2005 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
2008 } /* int network_bind_socket */
2010 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
2011 * or `SOCKENT_TYPE_SERVER' */
2012 static sockent_t *sockent_create (int type) /* {{{ */
2016 if ((type != SOCKENT_TYPE_CLIENT) && (type != SOCKENT_TYPE_SERVER))
2019 se = calloc (1, sizeof (*se));
2029 if (type == SOCKENT_TYPE_SERVER)
2031 se->data.server.fd = NULL;
2032 se->data.server.fd_num = 0;
2034 se->data.server.security_level = SECURITY_LEVEL_NONE;
2035 se->data.server.auth_file = NULL;
2036 se->data.server.userdb = NULL;
2037 se->data.server.cypher = NULL;
2042 se->data.client.fd = -1;
2043 se->data.client.addr = NULL;
2044 se->data.client.resolve_interval = 0;
2045 se->data.client.next_resolve_reconnect = 0;
2047 se->data.client.security_level = SECURITY_LEVEL_NONE;
2048 se->data.client.username = NULL;
2049 se->data.client.password = NULL;
2050 se->data.client.cypher = NULL;
2055 } /* }}} sockent_t *sockent_create */
2057 static int sockent_init_crypto (sockent_t *se) /* {{{ */
2059 #if HAVE_LIBGCRYPT /* {{{ */
2060 if (se->type == SOCKENT_TYPE_CLIENT)
2062 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
2064 network_init_gcrypt ();
2066 if ((se->data.client.username == NULL)
2067 || (se->data.client.password == NULL))
2069 ERROR ("network plugin: Client socket with "
2070 "security requested, but no "
2071 "credentials are configured.");
2074 gcry_md_hash_buffer (GCRY_MD_SHA256,
2075 se->data.client.password_hash,
2076 se->data.client.password,
2077 strlen (se->data.client.password));
2080 else /* (se->type == SOCKENT_TYPE_SERVER) */
2082 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2084 network_init_gcrypt ();
2086 if (se->data.server.auth_file == NULL)
2088 ERROR ("network plugin: Server socket with "
2089 "security requested, but no "
2090 "password file is configured.");
2094 if (se->data.server.auth_file != NULL)
2096 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2097 if (se->data.server.userdb == NULL)
2099 ERROR ("network plugin: Reading password file "
2101 se->data.server.auth_file);
2102 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2107 #endif /* }}} HAVE_LIBGCRYPT */
2110 } /* }}} int sockent_init_crypto */
2112 static int sockent_client_disconnect (sockent_t *se) /* {{{ */
2114 struct sockent_client *client;
2116 if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
2119 client = &se->data.client;
2120 if (client->fd >= 0) /* connected */
2126 sfree (client->addr);
2127 client->addrlen = 0;
2130 } /* }}} int sockent_client_disconnect */
2132 static int sockent_client_connect (sockent_t *se) /* {{{ */
2134 static c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
2136 struct sockent_client *client;
2137 struct addrinfo *ai_list;
2139 _Bool reconnect = 0;
2142 if ((se == NULL) || (se->type != SOCKENT_TYPE_CLIENT))
2145 client = &se->data.client;
2148 if (client->resolve_interval != 0 && client->next_resolve_reconnect < now) {
2149 DEBUG("network plugin: Reconnecting socket, resolve_interval = %lf, next_resolve_reconnect = %lf",
2150 CDTIME_T_TO_DOUBLE(client->resolve_interval), CDTIME_T_TO_DOUBLE(client->next_resolve_reconnect));
2154 if (client->fd >= 0 && !reconnect) /* already connected and not stale*/
2157 struct addrinfo ai_hints = {
2158 .ai_family = AF_UNSPEC,
2159 .ai_flags = AI_ADDRCONFIG,
2160 .ai_protocol = IPPROTO_UDP,
2161 .ai_socktype = SOCK_DGRAM
2164 status = getaddrinfo (se->node,
2165 (se->service != NULL) ? se->service : NET_DEFAULT_PORT,
2166 &ai_hints, &ai_list);
2169 c_complain (LOG_ERR, &complaint,
2170 "network plugin: getaddrinfo (%s, %s) failed: %s",
2171 (se->node == NULL) ? "(null)" : se->node,
2172 (se->service == NULL) ? "(null)" : se->service,
2173 gai_strerror (status));
2178 c_release (LOG_NOTICE, &complaint,
2179 "network plugin: Successfully resolved \"%s\".",
2183 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2185 if (client->fd >= 0) /* when we reconnect */
2186 sockent_client_disconnect(se);
2188 client->fd = socket (ai_ptr->ai_family,
2189 ai_ptr->ai_socktype,
2190 ai_ptr->ai_protocol);
2194 ERROR ("network plugin: socket(2) failed: %s",
2195 sstrerror (errno, errbuf,
2200 client->addr = calloc (1, sizeof (*client->addr));
2201 if (client->addr == NULL)
2203 ERROR ("network plugin: calloc failed.");
2209 assert (sizeof (*client->addr) >= ai_ptr->ai_addrlen);
2210 memcpy (client->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2211 client->addrlen = ai_ptr->ai_addrlen;
2213 network_set_ttl (se, ai_ptr);
2214 network_set_interface (se, ai_ptr);
2216 /* We don't open more than one write-socket per
2217 * node/service pair.. */
2221 freeaddrinfo (ai_list);
2225 if (client->resolve_interval > 0)
2226 client->next_resolve_reconnect = now + client->resolve_interval;
2228 } /* }}} int sockent_client_connect */
2230 /* Open the file descriptors for a initialized sockent structure. */
2231 static int sockent_server_listen (sockent_t *se) /* {{{ */
2233 struct addrinfo *ai_list;
2237 const char *service;
2242 assert (se->data.server.fd == NULL);
2243 assert (se->data.server.fd_num == 0);
2246 service = se->service;
2248 if (service == NULL)
2249 service = NET_DEFAULT_PORT;
2251 DEBUG ("network plugin: sockent_server_listen: node = %s; service = %s;",
2254 struct addrinfo ai_hints = {
2255 .ai_family = AF_UNSPEC,
2256 .ai_flags = AI_ADDRCONFIG | AI_PASSIVE,
2257 .ai_protocol = IPPROTO_UDP,
2258 .ai_socktype = SOCK_DGRAM
2261 status = getaddrinfo (node, service, &ai_hints, &ai_list);
2264 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2265 (se->node == NULL) ? "(null)" : se->node,
2266 (se->service == NULL) ? "(null)" : se->service,
2267 gai_strerror (status));
2271 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2275 tmp = realloc (se->data.server.fd,
2276 sizeof (*tmp) * (se->data.server.fd_num + 1));
2279 ERROR ("network plugin: realloc failed.");
2282 se->data.server.fd = tmp;
2283 tmp = se->data.server.fd + se->data.server.fd_num;
2285 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2286 ai_ptr->ai_protocol);
2290 ERROR ("network plugin: socket(2) failed: %s",
2291 sstrerror (errno, errbuf,
2296 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2304 se->data.server.fd_num++;
2306 } /* for (ai_list) */
2308 freeaddrinfo (ai_list);
2310 if (se->data.server.fd_num == 0)
2313 } /* }}} int sockent_server_listen */
2315 /* Add a sockent to the global list of sockets */
2316 static int sockent_add (sockent_t *se) /* {{{ */
2318 sockent_t *last_ptr;
2323 if (se->type == SOCKENT_TYPE_SERVER)
2327 tmp = realloc (listen_sockets_pollfd,
2328 sizeof (*tmp) * (listen_sockets_num
2329 + se->data.server.fd_num));
2332 ERROR ("network plugin: realloc failed.");
2335 listen_sockets_pollfd = tmp;
2336 tmp = listen_sockets_pollfd + listen_sockets_num;
2338 for (size_t i = 0; i < se->data.server.fd_num; i++)
2340 memset (tmp + i, 0, sizeof (*tmp));
2341 tmp[i].fd = se->data.server.fd[i];
2342 tmp[i].events = POLLIN | POLLPRI;
2346 listen_sockets_num += se->data.server.fd_num;
2348 if (listen_sockets == NULL)
2350 listen_sockets = se;
2353 last_ptr = listen_sockets;
2355 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2357 if (sending_sockets == NULL)
2359 sending_sockets = se;
2362 last_ptr = sending_sockets;
2365 while (last_ptr->next != NULL)
2366 last_ptr = last_ptr->next;
2367 last_ptr->next = se;
2370 } /* }}} int sockent_add */
2372 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2376 receive_list_entry_t *ent;
2379 /* Lock and wait for more data to come in */
2380 pthread_mutex_lock (&receive_list_lock);
2381 while ((listen_loop == 0)
2382 && (receive_list_head == NULL))
2383 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2385 /* Remove the head entry and unlock */
2386 ent = receive_list_head;
2388 receive_list_head = ent->next;
2389 receive_list_length--;
2390 pthread_mutex_unlock (&receive_list_lock);
2392 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2393 * because we dispatch all missing packets before shutting down. */
2397 /* Look for the correct `sockent_t' */
2398 se = listen_sockets;
2403 for (i = 0; i < se->data.server.fd_num; i++)
2404 if (se->data.server.fd[i] == ent->fd)
2407 if (i < se->data.server.fd_num)
2415 ERROR ("network plugin: Got packet from FD %i, but can't "
2416 "find an appropriate socket entry.",
2423 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2424 /* username = */ NULL);
2430 } /* }}} void *dispatch_thread */
2432 static int network_receive (void) /* {{{ */
2434 char buffer[network_config_packet_size];
2439 receive_list_entry_t *private_list_head;
2440 receive_list_entry_t *private_list_tail;
2441 uint64_t private_list_length;
2443 assert (listen_sockets_num > 0);
2445 private_list_head = NULL;
2446 private_list_tail = NULL;
2447 private_list_length = 0;
2449 while (listen_loop == 0)
2451 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2457 ERROR ("network plugin: poll(2) failed: %s",
2458 sstrerror (errno, errbuf, sizeof (errbuf)));
2462 for (size_t i = 0; (i < listen_sockets_num) && (status > 0); i++)
2464 receive_list_entry_t *ent;
2466 if ((listen_sockets_pollfd[i].revents
2467 & (POLLIN | POLLPRI)) == 0)
2471 buffer_len = recv (listen_sockets_pollfd[i].fd,
2472 buffer, sizeof (buffer),
2477 status = (errno != 0) ? errno : -1;
2478 ERROR ("network plugin: recv(2) failed: %s",
2479 sstrerror (errno, errbuf, sizeof (errbuf)));
2483 stats_octets_rx += ((uint64_t) buffer_len);
2486 /* TODO: Possible performance enhancement: Do not free
2487 * these entries in the dispatch thread but put them in
2488 * another list, so we don't have to allocate more and
2489 * more of these structures. */
2490 ent = calloc (1, sizeof (*ent));
2493 ERROR ("network plugin: calloc failed.");
2498 ent->data = malloc (network_config_packet_size);
2499 if (ent->data == NULL)
2502 ERROR ("network plugin: malloc failed.");
2506 ent->fd = listen_sockets_pollfd[i].fd;
2509 memcpy (ent->data, buffer, buffer_len);
2510 ent->data_len = buffer_len;
2512 if (private_list_head == NULL)
2513 private_list_head = ent;
2515 private_list_tail->next = ent;
2516 private_list_tail = ent;
2517 private_list_length++;
2519 /* Do not block here. Blocking here has led to
2520 * insufficient performance in the past. */
2521 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2523 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2524 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2526 if (receive_list_head == NULL)
2527 receive_list_head = private_list_head;
2529 receive_list_tail->next = private_list_head;
2530 receive_list_tail = private_list_tail;
2531 receive_list_length += private_list_length;
2533 pthread_cond_signal (&receive_list_cond);
2534 pthread_mutex_unlock (&receive_list_lock);
2536 private_list_head = NULL;
2537 private_list_tail = NULL;
2538 private_list_length = 0;
2542 } /* for (listen_sockets_pollfd) */
2546 } /* while (listen_loop == 0) */
2548 /* Make sure everything is dispatched before exiting. */
2549 if (private_list_head != NULL)
2551 pthread_mutex_lock (&receive_list_lock);
2553 if (receive_list_head == NULL)
2554 receive_list_head = private_list_head;
2556 receive_list_tail->next = private_list_head;
2557 receive_list_tail = private_list_tail;
2558 receive_list_length += private_list_length;
2560 pthread_cond_signal (&receive_list_cond);
2561 pthread_mutex_unlock (&receive_list_lock);
2565 } /* }}} int network_receive */
2567 static void *receive_thread (void __attribute__((unused)) *arg)
2569 return (network_receive () ? (void *) 1 : (void *) 0);
2570 } /* void *receive_thread */
2572 static void network_init_buffer (void)
2574 memset (send_buffer, 0, network_config_packet_size);
2575 send_buffer_ptr = send_buffer;
2576 send_buffer_fill = 0;
2577 send_buffer_last_update = 0;
2579 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2580 } /* int network_init_buffer */
2582 static void network_send_buffer_plain (sockent_t *se, /* {{{ */
2583 const char *buffer, size_t buffer_size)
2589 status = sockent_client_connect (se);
2593 status = sendto (se->data.client.fd, buffer, buffer_size,
2595 (struct sockaddr *) se->data.client.addr,
2596 se->data.client.addrlen);
2601 if ((errno == EINTR) || (errno == EAGAIN))
2604 ERROR ("network plugin: sendto failed: %s. Closing sending socket.",
2605 sstrerror (errno, errbuf, sizeof (errbuf)));
2606 sockent_client_disconnect (se);
2612 } /* }}} void network_send_buffer_plain */
2615 #define BUFFER_ADD(p,s) do { \
2616 memcpy (buffer + buffer_offset, (p), (s)); \
2617 buffer_offset += (s); \
2620 static void network_send_buffer_signed (sockent_t *se, /* {{{ */
2621 const char *in_buffer, size_t in_buffer_size)
2623 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2624 size_t buffer_offset;
2625 size_t username_len;
2629 unsigned char *hash;
2632 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2635 ERROR ("network plugin: Creating HMAC object failed: %s",
2636 gcry_strerror (err));
2640 err = gcry_md_setkey (hd, se->data.client.password,
2641 strlen (se->data.client.password));
2644 ERROR ("network plugin: gcry_md_setkey failed: %s",
2645 gcry_strerror (err));
2650 username_len = strlen (se->data.client.username);
2651 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2653 ERROR ("network plugin: Username too long: %s",
2654 se->data.client.username);
2658 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2659 se->data.client.username, username_len);
2660 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2661 in_buffer, in_buffer_size);
2663 /* Initialize the `ps' structure. */
2664 part_signature_sha256_t ps = {
2665 .head.type = htons (TYPE_SIGN_SHA256),
2666 .head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len)
2669 /* Calculate the hash value. */
2670 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2671 username_len + in_buffer_size);
2672 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2675 ERROR ("network plugin: gcry_md_read failed.");
2679 memcpy (ps.hash, hash, sizeof (ps.hash));
2681 /* Add the header */
2684 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2685 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2686 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2688 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2693 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2694 network_send_buffer_plain (se, buffer, buffer_offset);
2695 } /* }}} void network_send_buffer_signed */
2697 static void network_send_buffer_encrypted (sockent_t *se, /* {{{ */
2698 const char *in_buffer, size_t in_buffer_size)
2700 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2702 size_t buffer_offset;
2704 size_t username_len;
2706 gcry_cipher_hd_t cypher;
2708 /* Initialize the header fields */
2709 part_encryption_aes256_t pea = {
2710 .head.type = htons (TYPE_ENCR_AES256),
2711 .username = se->data.client.username
2714 username_len = strlen (pea.username);
2715 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2717 ERROR ("network plugin: Username too long: %s", pea.username);
2721 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2722 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2723 - sizeof (pea.hash);
2725 assert (buffer_size <= sizeof (buffer));
2726 DEBUG ("network plugin: network_send_buffer_encrypted: "
2727 "buffer_size = %zu;", buffer_size);
2729 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2730 + username_len + in_buffer_size));
2731 pea.username_length = htons ((uint16_t) username_len);
2733 /* Chose a random initialization vector. */
2734 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2736 /* Create hash of the payload */
2737 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2739 /* Initialize the buffer */
2741 memset (buffer, 0, sizeof (buffer));
2744 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2745 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2746 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2747 BUFFER_ADD (pea.username, username_len);
2748 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2749 assert (buffer_offset == header_size);
2750 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2751 BUFFER_ADD (in_buffer, in_buffer_size);
2753 assert (buffer_offset == buffer_size);
2755 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2756 se->data.client.password);
2760 /* Encrypt the buffer in-place */
2761 err = gcry_cipher_encrypt (cypher,
2762 buffer + header_size,
2763 buffer_size - header_size,
2764 /* in = */ NULL, /* in len = */ 0);
2767 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2768 gcry_strerror (err));
2772 /* Send it out without further modifications */
2773 network_send_buffer_plain (se, buffer, buffer_size);
2774 } /* }}} void network_send_buffer_encrypted */
2776 #endif /* HAVE_LIBGCRYPT */
2778 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2780 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2782 for (sockent_t *se = sending_sockets; se != NULL; se = se->next)
2785 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2786 network_send_buffer_encrypted (se, buffer, buffer_len);
2787 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2788 network_send_buffer_signed (se, buffer, buffer_len);
2789 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2790 #endif /* HAVE_LIBGCRYPT */
2791 network_send_buffer_plain (se, buffer, buffer_len);
2792 } /* for (sending_sockets) */
2793 } /* }}} void network_send_buffer */
2795 static int add_to_buffer (char *buffer, size_t buffer_size, /* {{{ */
2796 value_list_t *vl_def,
2797 const data_set_t *ds, const value_list_t *vl)
2799 char *buffer_orig = buffer;
2801 if (strcmp (vl_def->host, vl->host) != 0)
2803 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2804 vl->host, strlen (vl->host)) != 0)
2806 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2809 if (vl_def->time != vl->time)
2811 if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
2812 (uint64_t) vl->time))
2814 vl_def->time = vl->time;
2817 if (vl_def->interval != vl->interval)
2819 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
2820 (uint64_t) vl->interval))
2822 vl_def->interval = vl->interval;
2825 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2827 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2828 vl->plugin, strlen (vl->plugin)) != 0)
2830 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2833 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2835 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2836 vl->plugin_instance,
2837 strlen (vl->plugin_instance)) != 0)
2839 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2842 if (strcmp (vl_def->type, vl->type) != 0)
2844 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2845 vl->type, strlen (vl->type)) != 0)
2847 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2850 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2852 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2854 strlen (vl->type_instance)) != 0)
2856 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2859 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2862 return (buffer - buffer_orig);
2863 } /* }}} int add_to_buffer */
2865 static void flush_buffer (void)
2867 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2870 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2872 stats_octets_tx += ((uint64_t) send_buffer_fill);
2875 network_init_buffer ();
2878 static int network_write (const data_set_t *ds, const value_list_t *vl,
2879 user_data_t __attribute__((unused)) *user_data)
2883 if (!check_send_okay (vl))
2886 char name[6*DATA_MAX_NAME_LEN];
2887 FORMAT_VL (name, sizeof (name), vl);
2888 name[sizeof (name) - 1] = 0;
2889 DEBUG ("network plugin: network_write: "
2890 "NOT sending %s.", name);
2892 /* Counter is not protected by another lock and may be reached by
2893 * multiple threads */
2894 pthread_mutex_lock (&stats_lock);
2895 stats_values_not_sent++;
2896 pthread_mutex_unlock (&stats_lock);
2900 uc_meta_data_add_unsigned_int (vl,
2901 "network:time_sent", (uint64_t) vl->time);
2903 pthread_mutex_lock (&send_buffer_lock);
2905 status = add_to_buffer (send_buffer_ptr,
2906 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2911 /* status == bytes added to the buffer */
2912 send_buffer_fill += status;
2913 send_buffer_ptr += status;
2914 send_buffer_last_update = cdtime();
2916 stats_values_sent++;
2922 status = add_to_buffer (send_buffer_ptr,
2923 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2929 send_buffer_fill += status;
2930 send_buffer_ptr += status;
2932 stats_values_sent++;
2938 ERROR ("network plugin: Unable to append to the "
2939 "buffer for some weird reason");
2941 else if ((network_config_packet_size - send_buffer_fill) < 15)
2946 pthread_mutex_unlock (&send_buffer_lock);
2948 return ((status < 0) ? -1 : 0);
2949 } /* int network_write */
2951 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2955 if (cf_util_get_int (ci, &tmp) != 0)
2957 else if ((tmp > 0) && (tmp <= 255))
2958 network_config_ttl = tmp;
2960 WARNING ("network plugin: The `TimeToLive' must be between 1 and 255.");
2965 } /* }}} int network_config_set_ttl */
2967 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2972 if (cf_util_get_string_buffer (ci, if_name, sizeof (if_name)) != 0)
2975 *interface = if_nametoindex (if_name);
2977 } /* }}} int network_config_set_interface */
2979 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2983 if (cf_util_get_int (ci, &tmp) != 0)
2985 else if ((tmp >= 1024) && (tmp <= 65535))
2986 network_config_packet_size = tmp;
2988 WARNING ("network plugin: The `MaxPacketSize' must be between 1024 and 65535.");
2993 } /* }}} int network_config_set_buffer_size */
2996 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
3000 if ((ci->values_num != 1)
3001 || (ci->values[0].type != OCONFIG_TYPE_STRING))
3003 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
3004 "one string argument.");
3008 str = ci->values[0].value.string;
3009 if (strcasecmp ("Encrypt", str) == 0)
3010 *retval = SECURITY_LEVEL_ENCRYPT;
3011 else if (strcasecmp ("Sign", str) == 0)
3012 *retval = SECURITY_LEVEL_SIGN;
3013 else if (strcasecmp ("None", str) == 0)
3014 *retval = SECURITY_LEVEL_NONE;
3017 WARNING ("network plugin: Unknown security level: %s.", str);
3022 } /* }}} int network_config_set_security_level */
3023 #endif /* HAVE_LIBGCRYPT */
3025 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
3030 if ((ci->values_num < 1) || (ci->values_num > 2)
3031 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3032 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3034 ERROR ("network plugin: The `%s' config option needs "
3035 "one or two string arguments.", ci->key);
3039 se = sockent_create (SOCKENT_TYPE_SERVER);
3042 ERROR ("network plugin: sockent_create failed.");
3046 se->node = strdup (ci->values[0].value.string);
3047 if (ci->values_num >= 2)
3048 se->service = strdup (ci->values[1].value.string);
3050 for (int i = 0; i < ci->children_num; i++)
3052 oconfig_item_t *child = ci->children + i;
3055 if (strcasecmp ("AuthFile", child->key) == 0)
3056 cf_util_get_string (child, &se->data.server.auth_file);
3057 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3058 network_config_set_security_level (child,
3059 &se->data.server.security_level);
3061 #endif /* HAVE_LIBGCRYPT */
3062 if (strcasecmp ("Interface", child->key) == 0)
3063 network_config_set_interface (child, &se->interface);
3066 WARNING ("network plugin: Option `%s' is not allowed here.",
3072 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3073 && (se->data.server.auth_file == NULL))
3075 ERROR ("network plugin: A security level higher than `none' was "
3076 "requested, but no AuthFile option was given. Cowardly refusing to "
3077 "open this socket!");
3078 sockent_destroy (se);
3081 #endif /* HAVE_LIBGCRYPT */
3083 status = sockent_init_crypto (se);
3086 ERROR ("network plugin: network_config_add_listen: sockent_init_crypto() failed.");
3087 sockent_destroy (se);
3091 status = sockent_server_listen (se);
3094 ERROR ("network plugin: network_config_add_listen: sockent_server_listen failed.");
3095 sockent_destroy (se);
3099 status = sockent_add (se);
3102 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3103 sockent_destroy (se);
3108 } /* }}} int network_config_add_listen */
3110 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3115 if ((ci->values_num < 1) || (ci->values_num > 2)
3116 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3117 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3119 ERROR ("network plugin: The `%s' config option needs "
3120 "one or two string arguments.", ci->key);
3124 se = sockent_create (SOCKENT_TYPE_CLIENT);
3127 ERROR ("network plugin: sockent_create failed.");
3131 se->node = strdup (ci->values[0].value.string);
3132 if (ci->values_num >= 2)
3133 se->service = strdup (ci->values[1].value.string);
3135 for (int i = 0; i < ci->children_num; i++)
3137 oconfig_item_t *child = ci->children + i;
3140 if (strcasecmp ("Username", child->key) == 0)
3141 cf_util_get_string (child, &se->data.client.username);
3142 else if (strcasecmp ("Password", child->key) == 0)
3143 cf_util_get_string (child, &se->data.client.password);
3144 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3145 network_config_set_security_level (child,
3146 &se->data.client.security_level);
3148 #endif /* HAVE_LIBGCRYPT */
3149 if (strcasecmp ("Interface", child->key) == 0)
3150 network_config_set_interface (child, &se->interface);
3151 else if (strcasecmp ("ResolveInterval", child->key) == 0)
3152 cf_util_get_cdtime(child, &se->data.client.resolve_interval);
3155 WARNING ("network plugin: Option `%s' is not allowed here.",
3161 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3162 && ((se->data.client.username == NULL)
3163 || (se->data.client.password == NULL)))
3165 ERROR ("network plugin: A security level higher than `none' was "
3166 "requested, but no Username or Password option was given. "
3167 "Cowardly refusing to open this socket!");
3168 sockent_destroy (se);
3171 #endif /* HAVE_LIBGCRYPT */
3173 status = sockent_init_crypto (se);
3176 ERROR ("network plugin: network_config_add_server: sockent_init_crypto() failed.");
3177 sockent_destroy (se);
3181 /* No call to sockent_client_connect() here -- it is called from
3182 * network_send_buffer_plain(). */
3184 status = sockent_add (se);
3187 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3188 sockent_destroy (se);
3193 } /* }}} int network_config_add_server */
3195 static int network_config (oconfig_item_t *ci) /* {{{ */
3197 /* The options need to be applied first */
3198 for (int i = 0; i < ci->children_num; i++)
3200 oconfig_item_t *child = ci->children + i;
3201 if (strcasecmp ("TimeToLive", child->key) == 0)
3202 network_config_set_ttl (child);
3205 for (int i = 0; i < ci->children_num; i++)
3207 oconfig_item_t *child = ci->children + i;
3209 if (strcasecmp ("Listen", child->key) == 0)
3210 network_config_add_listen (child);
3211 else if (strcasecmp ("Server", child->key) == 0)
3212 network_config_add_server (child);
3213 else if (strcasecmp ("TimeToLive", child->key) == 0) {
3214 /* Handled earlier */
3216 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3217 network_config_set_buffer_size (child);
3218 else if (strcasecmp ("Forward", child->key) == 0)
3219 cf_util_get_boolean (child, &network_config_forward);
3220 else if (strcasecmp ("ReportStats", child->key) == 0)
3221 cf_util_get_boolean (child, &network_config_stats);
3224 WARNING ("network plugin: Option `%s' is not allowed here.",
3230 } /* }}} int network_config */
3232 static int network_notification (const notification_t *n,
3233 user_data_t __attribute__((unused)) *user_data)
3235 char buffer[network_config_packet_size];
3236 char *buffer_ptr = buffer;
3237 size_t buffer_free = sizeof (buffer);
3240 if (!check_send_notify_okay (n))
3243 memset (buffer, 0, sizeof (buffer));
3245 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3246 (uint64_t) n->time);
3250 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3251 (uint64_t) n->severity);
3255 if (strlen (n->host) > 0)
3257 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3258 n->host, strlen (n->host));
3263 if (strlen (n->plugin) > 0)
3265 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3266 n->plugin, strlen (n->plugin));
3271 if (strlen (n->plugin_instance) > 0)
3273 status = write_part_string (&buffer_ptr, &buffer_free,
3274 TYPE_PLUGIN_INSTANCE,
3275 n->plugin_instance, strlen (n->plugin_instance));
3280 if (strlen (n->type) > 0)
3282 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3283 n->type, strlen (n->type));
3288 if (strlen (n->type_instance) > 0)
3290 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3291 n->type_instance, strlen (n->type_instance));
3296 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3297 n->message, strlen (n->message));
3301 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3304 } /* int network_notification */
3306 static int network_shutdown (void)
3310 /* Kill the listening thread */
3311 if (receive_thread_running != 0)
3313 INFO ("network plugin: Stopping receive thread.");
3314 pthread_kill (receive_thread_id, SIGTERM);
3315 pthread_join (receive_thread_id, NULL /* no return value */);
3316 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3317 receive_thread_running = 0;
3320 /* Shutdown the dispatching thread */
3321 if (dispatch_thread_running != 0)
3323 INFO ("network plugin: Stopping dispatch thread.");
3324 pthread_mutex_lock (&receive_list_lock);
3325 pthread_cond_broadcast (&receive_list_cond);
3326 pthread_mutex_unlock (&receive_list_lock);
3327 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3328 dispatch_thread_running = 0;
3331 sockent_destroy (listen_sockets);
3333 if (send_buffer_fill > 0)
3336 sfree (send_buffer);
3338 for (sockent_t *se = sending_sockets; se != NULL; se = se->next)
3339 sockent_client_disconnect (se);
3340 sockent_destroy (sending_sockets);
3342 plugin_unregister_config ("network");
3343 plugin_unregister_init ("network");
3344 plugin_unregister_write ("network");
3345 plugin_unregister_shutdown ("network");
3348 } /* int network_shutdown */
3350 static int network_stats_read (void) /* {{{ */
3352 derive_t copy_octets_rx;
3353 derive_t copy_octets_tx;
3354 derive_t copy_packets_rx;
3355 derive_t copy_packets_tx;
3356 derive_t copy_values_dispatched;
3357 derive_t copy_values_not_dispatched;
3358 derive_t copy_values_sent;
3359 derive_t copy_values_not_sent;
3360 derive_t copy_receive_list_length;
3361 value_list_t vl = VALUE_LIST_INIT;
3364 copy_octets_rx = stats_octets_rx;
3365 copy_octets_tx = stats_octets_tx;
3366 copy_packets_rx = stats_packets_rx;
3367 copy_packets_tx = stats_packets_tx;
3368 copy_values_dispatched = stats_values_dispatched;
3369 copy_values_not_dispatched = stats_values_not_dispatched;
3370 copy_values_sent = stats_values_sent;
3371 copy_values_not_sent = stats_values_not_sent;
3372 copy_receive_list_length = receive_list_length;
3374 /* Initialize `vl' */
3378 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3379 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3381 /* Octets received / sent */
3382 vl.values[0].derive = (derive_t) copy_octets_rx;
3383 vl.values[1].derive = (derive_t) copy_octets_tx;
3384 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3385 plugin_dispatch_values (&vl);
3387 /* Packets received / send */
3388 vl.values[0].derive = (derive_t) copy_packets_rx;
3389 vl.values[1].derive = (derive_t) copy_packets_tx;
3390 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3391 plugin_dispatch_values (&vl);
3393 /* Values (not) dispatched and (not) send */
3394 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3397 vl.values[0].derive = (derive_t) copy_values_dispatched;
3398 sstrncpy (vl.type_instance, "dispatch-accepted",
3399 sizeof (vl.type_instance));
3400 plugin_dispatch_values (&vl);
3402 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3403 sstrncpy (vl.type_instance, "dispatch-rejected",
3404 sizeof (vl.type_instance));
3405 plugin_dispatch_values (&vl);
3407 vl.values[0].derive = (derive_t) copy_values_sent;
3408 sstrncpy (vl.type_instance, "send-accepted",
3409 sizeof (vl.type_instance));
3410 plugin_dispatch_values (&vl);
3412 vl.values[0].derive = (derive_t) copy_values_not_sent;
3413 sstrncpy (vl.type_instance, "send-rejected",
3414 sizeof (vl.type_instance));
3415 plugin_dispatch_values (&vl);
3417 /* Receive queue length */
3418 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3419 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3420 vl.type_instance[0] = 0;
3421 plugin_dispatch_values (&vl);
3424 } /* }}} int network_stats_read */
3426 static int network_init (void)
3428 static _Bool have_init = 0;
3430 /* Check if we were already initialized. If so, just return - there's
3431 * nothing more to do (for now, that is). */
3437 network_init_gcrypt ();
3440 if (network_config_stats)
3441 plugin_register_read ("network", network_stats_read);
3443 plugin_register_shutdown ("network", network_shutdown);
3445 send_buffer = malloc (network_config_packet_size);
3446 if (send_buffer == NULL)
3448 ERROR ("network plugin: malloc failed.");
3451 network_init_buffer ();
3453 /* setup socket(s) and so on */
3454 if (sending_sockets != NULL)
3456 plugin_register_write ("network", network_write,
3457 /* user_data = */ NULL);
3458 plugin_register_notification ("network", network_notification,
3459 /* user_data = */ NULL);
3462 /* If no threads need to be started, return here. */
3463 if ((listen_sockets_num == 0)
3464 || ((dispatch_thread_running != 0)
3465 && (receive_thread_running != 0)))
3468 if (dispatch_thread_running == 0)
3471 status = plugin_thread_create (&dispatch_thread_id,
3472 NULL /* no attributes */,
3474 NULL /* no argument */);
3478 ERROR ("network: pthread_create failed: %s",
3479 sstrerror (errno, errbuf,
3484 dispatch_thread_running = 1;
3488 if (receive_thread_running == 0)
3491 status = plugin_thread_create (&receive_thread_id,
3492 NULL /* no attributes */,
3494 NULL /* no argument */);
3498 ERROR ("network: pthread_create failed: %s",
3499 sstrerror (errno, errbuf,
3504 receive_thread_running = 1;
3509 } /* int network_init */
3512 * The flush option of the network plugin cannot flush individual identifiers.
3513 * All the values are added to a buffer and sent when the buffer is full, the
3514 * requested value may or may not be in there, it's not worth finding out. We
3515 * just send the buffer if `flush' is called - if the requested value was in
3516 * there, good. If not, well, then there is nothing to flush.. -octo
3518 static int network_flush (cdtime_t timeout,
3519 __attribute__((unused)) const char *identifier,
3520 __attribute__((unused)) user_data_t *user_data)
3522 pthread_mutex_lock (&send_buffer_lock);
3524 if (send_buffer_fill > 0)
3528 cdtime_t now = cdtime ();
3529 if ((send_buffer_last_update + timeout) > now)
3531 pthread_mutex_unlock (&send_buffer_lock);
3537 pthread_mutex_unlock (&send_buffer_lock);
3540 } /* int network_flush */
3542 void module_register (void)
3544 plugin_register_complex_config ("network", network_config);
3545 plugin_register_init ("network", network_init);
3546 plugin_register_flush ("network", network_flush,
3547 /* user_data = */ NULL);
3548 } /* void module_register */
3550 /* vim: set fdm=marker : */