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 int network_init_gcrypt (void) /* {{{ */
499 /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
500 * Because you can't know in a library whether another library has
501 * already initialized the library */
502 if (gcry_control (GCRYCTL_ANY_INITIALIZATION_P))
505 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
506 * To ensure thread-safety, it's important to set GCRYCTL_SET_THREAD_CBS
507 * *before* initalizing Libgcrypt with gcry_check_version(), which itself must
508 * be called before any other gcry_* function. GCRYCTL_ANY_INITIALIZATION_P
509 * above doesn't count, as it doesn't implicitly initalize Libgcrypt.
511 * tl;dr: keep all these gry_* statements in this exact order please. */
512 err = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
515 ERROR ("network plugin: gcry_control (GCRYCTL_SET_THREAD_CBS) failed: %s", gcry_strerror (err));
518 gcry_check_version (NULL);
520 err = gcry_control (GCRYCTL_INIT_SECMEM, 32768);
523 ERROR ("network plugin: gcry_control (GCRYCTL_INIT_SECMEM) failed: %s", gcry_strerror (err));
527 gcry_control (GCRYCTL_INITIALIZATION_FINISHED);
529 } /* }}} int 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, int *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;
622 num_values = vl->values_len;
623 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
624 + (num_values * sizeof (uint8_t))
625 + (num_values * sizeof (value_t));
627 if (*ret_buffer_len < packet_len)
630 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
631 if (pkg_values_types == NULL)
633 ERROR ("network plugin: write_part_values: malloc failed.");
637 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
638 if (pkg_values == NULL)
640 free (pkg_values_types);
641 ERROR ("network plugin: write_part_values: malloc failed.");
645 pkg_ph.type = htons (TYPE_VALUES);
646 pkg_ph.length = htons (packet_len);
648 pkg_num_values = htons ((uint16_t) vl->values_len);
650 for (i = 0; i < num_values; i++)
652 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
653 switch (ds->ds[i].type)
655 case DS_TYPE_COUNTER:
656 pkg_values[i].counter = htonll (vl->values[i].counter);
660 pkg_values[i].gauge = htond (vl->values[i].gauge);
664 pkg_values[i].derive = htonll (vl->values[i].derive);
667 case DS_TYPE_ABSOLUTE:
668 pkg_values[i].absolute = htonll (vl->values[i].absolute);
672 free (pkg_values_types);
674 ERROR ("network plugin: write_part_values: "
675 "Unknown data source type: %i",
678 } /* switch (ds->ds[i].type) */
679 } /* for (num_values) */
682 * Use `memcpy' to write everything to the buffer, because the pointer
683 * may be unaligned and some architectures, such as SPARC, can't handle
686 packet_ptr = *ret_buffer;
688 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
689 offset += sizeof (pkg_ph);
690 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
691 offset += sizeof (pkg_num_values);
692 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
693 offset += num_values * sizeof (uint8_t);
694 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
695 offset += num_values * sizeof (value_t);
697 assert (offset == packet_len);
699 *ret_buffer = packet_ptr + packet_len;
700 *ret_buffer_len -= packet_len;
702 free (pkg_values_types);
706 } /* int write_part_values */
708 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
709 int type, uint64_t value)
714 part_header_t pkg_head;
719 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
721 if (*ret_buffer_len < packet_len)
724 pkg_head.type = htons (type);
725 pkg_head.length = htons (packet_len);
726 pkg_value = htonll (value);
728 packet_ptr = *ret_buffer;
730 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
731 offset += sizeof (pkg_head);
732 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
733 offset += sizeof (pkg_value);
735 assert (offset == packet_len);
737 *ret_buffer = packet_ptr + packet_len;
738 *ret_buffer_len -= packet_len;
741 } /* int write_part_number */
743 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
744 int type, const char *str, int str_len)
754 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
755 if (*ret_buffer_len < buffer_len)
758 pkg_type = htons (type);
759 pkg_length = htons (buffer_len);
761 buffer = *ret_buffer;
763 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
764 offset += sizeof (pkg_type);
765 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
766 offset += sizeof (pkg_length);
767 memcpy (buffer + offset, str, str_len);
769 memset (buffer + offset, '\0', 1);
772 assert (offset == buffer_len);
774 *ret_buffer = buffer + buffer_len;
775 *ret_buffer_len -= buffer_len;
778 } /* int write_part_string */
780 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
781 value_t **ret_values, int *ret_num_values)
783 char *buffer = *ret_buffer;
784 size_t buffer_len = *ret_buffer_len;
799 NOTICE ("network plugin: packet is too short: "
800 "buffer_len = %zu", buffer_len);
804 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
805 buffer += sizeof (tmp16);
806 pkg_type = ntohs (tmp16);
808 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
809 buffer += sizeof (tmp16);
810 pkg_length = ntohs (tmp16);
812 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
813 buffer += sizeof (tmp16);
814 pkg_numval = ntohs (tmp16);
816 assert (pkg_type == TYPE_VALUES);
818 exp_size = 3 * sizeof (uint16_t)
819 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
820 if (buffer_len < exp_size)
822 WARNING ("network plugin: parse_part_values: "
824 "Chunk of size %zu expected, "
825 "but buffer has only %zu bytes left.",
826 exp_size, buffer_len);
830 if (pkg_length != exp_size)
832 WARNING ("network plugin: parse_part_values: "
833 "Length and number of values "
834 "in the packet don't match.");
838 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
839 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
840 if ((pkg_types == NULL) || (pkg_values == NULL))
844 ERROR ("network plugin: parse_part_values: malloc failed.");
848 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
849 buffer += pkg_numval * sizeof (uint8_t);
850 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
851 buffer += pkg_numval * sizeof (value_t);
853 for (i = 0; i < pkg_numval; i++)
855 switch (pkg_types[i])
857 case DS_TYPE_COUNTER:
858 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
862 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
866 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
869 case DS_TYPE_ABSOLUTE:
870 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
874 NOTICE ("network plugin: parse_part_values: "
875 "Don't know how to handle data source type %"PRIu8,
880 } /* switch (pkg_types[i]) */
883 *ret_buffer = buffer;
884 *ret_buffer_len = buffer_len - pkg_length;
885 *ret_num_values = pkg_numval;
886 *ret_values = pkg_values;
891 } /* int parse_part_values */
893 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
896 char *buffer = *ret_buffer;
897 size_t buffer_len = *ret_buffer_len;
901 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
905 if (buffer_len < exp_size)
907 WARNING ("network plugin: parse_part_number: "
909 "Chunk of size %zu expected, "
910 "but buffer has only %zu bytes left.",
911 exp_size, buffer_len);
915 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
916 buffer += sizeof (tmp16);
917 /* pkg_type = ntohs (tmp16); */
919 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
920 buffer += sizeof (tmp16);
921 pkg_length = ntohs (tmp16);
923 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
924 buffer += sizeof (tmp64);
925 *value = ntohll (tmp64);
927 *ret_buffer = buffer;
928 *ret_buffer_len = buffer_len - pkg_length;
931 } /* int parse_part_number */
933 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
934 char *output, int output_len)
936 char *buffer = *ret_buffer;
937 size_t buffer_len = *ret_buffer_len;
940 size_t header_size = 2 * sizeof (uint16_t);
944 if (buffer_len < header_size)
946 WARNING ("network plugin: parse_part_string: "
948 "Chunk of at least size %zu expected, "
949 "but buffer has only %zu bytes left.",
950 header_size, buffer_len);
954 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
955 buffer += sizeof (tmp16);
956 /* pkg_type = ntohs (tmp16); */
958 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
959 buffer += sizeof (tmp16);
960 pkg_length = ntohs (tmp16);
962 /* Check that packet fits in the input buffer */
963 if (pkg_length > buffer_len)
965 WARNING ("network plugin: parse_part_string: "
967 "Chunk of size %"PRIu16" received, "
968 "but buffer has only %zu bytes left.",
969 pkg_length, buffer_len);
973 /* Check that pkg_length is in the valid range */
974 if (pkg_length <= header_size)
976 WARNING ("network plugin: parse_part_string: "
978 "Header claims this packet is only %hu "
979 "bytes long.", pkg_length);
983 /* Check that the package data fits into the output buffer.
984 * The previous if-statement ensures that:
985 * `pkg_length > header_size' */
987 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
989 WARNING ("network plugin: parse_part_string: "
990 "Output buffer too small.");
994 /* All sanity checks successfull, let's copy the data over */
995 output_len = pkg_length - header_size;
996 memcpy ((void *) output, (void *) buffer, output_len);
997 buffer += output_len;
999 /* For some very weird reason '\0' doesn't do the trick on SPARC in
1000 * this statement. */
1001 if (output[output_len - 1] != 0)
1003 WARNING ("network plugin: parse_part_string: "
1004 "Received string does not end "
1005 "with a NULL-byte.");
1009 *ret_buffer = buffer;
1010 *ret_buffer_len = buffer_len - pkg_length;
1013 } /* int parse_part_string */
1015 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
1016 * parse_packet and vice versa. */
1017 #define PP_SIGNED 0x01
1018 #define PP_ENCRYPTED 0x02
1019 static int parse_packet (sockent_t *se,
1020 void *buffer, size_t buffer_size, int flags,
1021 const char *username);
1023 #define BUFFER_READ(p,s) do { \
1024 memcpy ((p), buffer + buffer_offset, (s)); \
1025 buffer_offset += (s); \
1029 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1030 void **ret_buffer, size_t *ret_buffer_len, int flags)
1032 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
1036 size_t buffer_offset;
1038 size_t username_len;
1041 part_signature_sha256_t pss;
1042 uint16_t pss_head_length;
1043 char hash[sizeof (pss.hash)];
1047 unsigned char *hash_ptr;
1049 buffer = *ret_buffer;
1050 buffer_len = *ret_buffer_len;
1053 if (se->data.server.userdb == NULL)
1055 c_complain (LOG_NOTICE, &complain_no_users,
1056 "network plugin: Received signed network packet but can't verify it "
1057 "because no user DB has been configured. Will accept it.");
1061 /* Check if the buffer has enough data for this structure. */
1062 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1065 /* Read type and length header */
1066 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1067 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1068 pss_head_length = ntohs (pss.head.length);
1070 /* Check if the `pss_head_length' is within bounds. */
1071 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1072 || (pss_head_length > buffer_len))
1074 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1078 /* Copy the hash. */
1079 BUFFER_READ (pss.hash, sizeof (pss.hash));
1081 /* Calculate username length (without null byte) and allocate memory */
1082 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1083 pss.username = malloc (username_len + 1);
1084 if (pss.username == NULL)
1087 /* Read the username */
1088 BUFFER_READ (pss.username, username_len);
1089 pss.username[username_len] = 0;
1091 assert (buffer_offset == pss_head_length);
1093 /* Query the password */
1094 secret = fbh_get (se->data.server.userdb, pss.username);
1097 ERROR ("network plugin: Unknown user: %s", pss.username);
1098 sfree (pss.username);
1102 /* Create a hash device and check the HMAC */
1104 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1107 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1108 gcry_strerror (err));
1110 sfree (pss.username);
1114 err = gcry_md_setkey (hd, secret, strlen (secret));
1117 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1120 sfree (pss.username);
1125 buffer + PART_SIGNATURE_SHA256_SIZE,
1126 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1127 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1128 if (hash_ptr == NULL)
1130 ERROR ("network plugin: gcry_md_read failed.");
1133 sfree (pss.username);
1136 memcpy (hash, hash_ptr, sizeof (hash));
1142 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1144 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1149 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1150 flags | PP_SIGNED, pss.username);
1154 sfree (pss.username);
1156 *ret_buffer = buffer + buffer_len;
1157 *ret_buffer_len = 0;
1160 } /* }}} int parse_part_sign_sha256 */
1161 /* #endif HAVE_LIBGCRYPT */
1163 #else /* if !HAVE_LIBGCRYPT */
1164 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1165 void **ret_buffer, size_t *ret_buffer_size, int flags)
1167 static int warning_has_been_printed = 0;
1171 size_t buffer_offset;
1174 part_signature_sha256_t pss;
1176 buffer = *ret_buffer;
1177 buffer_size = *ret_buffer_size;
1180 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1183 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1184 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1185 part_len = ntohs (pss.head.length);
1187 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1188 || (part_len > buffer_size))
1191 if (warning_has_been_printed == 0)
1193 WARNING ("network plugin: Received signed packet, but the network "
1194 "plugin was not linked with libgcrypt, so I cannot "
1195 "verify the signature. The packet will be accepted.");
1196 warning_has_been_printed = 1;
1199 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1200 /* username = */ NULL);
1202 *ret_buffer = buffer + buffer_size;
1203 *ret_buffer_size = 0;
1206 } /* }}} int parse_part_sign_sha256 */
1207 #endif /* !HAVE_LIBGCRYPT */
1210 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1211 void **ret_buffer, size_t *ret_buffer_len,
1214 char *buffer = *ret_buffer;
1215 size_t buffer_len = *ret_buffer_len;
1218 size_t buffer_offset;
1219 uint16_t username_len;
1220 part_encryption_aes256_t pea;
1221 unsigned char hash[sizeof (pea.hash)];
1223 gcry_cipher_hd_t cypher;
1226 /* Make sure at least the header if available. */
1227 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1229 NOTICE ("network plugin: parse_part_encr_aes256: "
1230 "Discarding short packet.");
1236 /* Copy the unencrypted information into `pea'. */
1237 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1238 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1240 /* Check the `part size'. */
1241 part_size = ntohs (pea.head.length);
1242 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1243 || (part_size > buffer_len))
1245 NOTICE ("network plugin: parse_part_encr_aes256: "
1246 "Discarding part with invalid size.");
1250 /* Read the username */
1251 BUFFER_READ (&username_len, sizeof (username_len));
1252 username_len = ntohs (username_len);
1254 if ((username_len <= 0)
1255 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1257 NOTICE ("network plugin: parse_part_encr_aes256: "
1258 "Discarding part with invalid username length.");
1262 assert (username_len > 0);
1263 pea.username = malloc (username_len + 1);
1264 if (pea.username == NULL)
1266 BUFFER_READ (pea.username, username_len);
1267 pea.username[username_len] = 0;
1269 /* Last but not least, the initialization vector */
1270 BUFFER_READ (pea.iv, sizeof (pea.iv));
1272 /* Make sure we are at the right position */
1273 assert (buffer_offset == (username_len +
1274 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1276 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1280 sfree (pea.username);
1284 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1285 assert (payload_len > 0);
1287 /* Decrypt the packet in-place */
1288 err = gcry_cipher_decrypt (cypher,
1289 buffer + buffer_offset,
1290 part_size - buffer_offset,
1291 /* in = */ NULL, /* in len = */ 0);
1294 sfree (pea.username);
1295 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1296 gcry_strerror (err));
1301 BUFFER_READ (pea.hash, sizeof (pea.hash));
1303 /* Make sure we're at the right position - again */
1304 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1305 assert (buffer_offset == (part_size - payload_len));
1307 /* Check hash sum */
1308 memset (hash, 0, sizeof (hash));
1309 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1310 buffer + buffer_offset, payload_len);
1311 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1313 sfree (pea.username);
1314 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1318 parse_packet (se, buffer + buffer_offset, payload_len,
1319 flags | PP_ENCRYPTED, pea.username);
1321 /* XXX: Free pea.username?!? */
1323 /* Update return values */
1324 *ret_buffer = buffer + part_size;
1325 *ret_buffer_len = buffer_len - part_size;
1327 sfree (pea.username);
1330 } /* }}} int parse_part_encr_aes256 */
1331 /* #endif HAVE_LIBGCRYPT */
1333 #else /* if !HAVE_LIBGCRYPT */
1334 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1335 void **ret_buffer, size_t *ret_buffer_size, int flags)
1337 static int warning_has_been_printed = 0;
1341 size_t buffer_offset;
1346 buffer = *ret_buffer;
1347 buffer_size = *ret_buffer_size;
1350 /* parse_packet assures this minimum size. */
1351 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1353 BUFFER_READ (&ph.type, sizeof (ph.type));
1354 BUFFER_READ (&ph.length, sizeof (ph.length));
1355 ph_length = ntohs (ph.length);
1357 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1358 || (ph_length > buffer_size))
1360 ERROR ("network plugin: AES-256 encrypted part "
1361 "with invalid length received.");
1365 if (warning_has_been_printed == 0)
1367 WARNING ("network plugin: Received encrypted packet, but the network "
1368 "plugin was not linked with libgcrypt, so I cannot "
1369 "decrypt it. The part will be discarded.");
1370 warning_has_been_printed = 1;
1373 *ret_buffer += ph_length;
1374 *ret_buffer_size -= ph_length;
1377 } /* }}} int parse_part_encr_aes256 */
1378 #endif /* !HAVE_LIBGCRYPT */
1382 static int parse_packet (sockent_t *se, /* {{{ */
1383 void *buffer, size_t buffer_size, int flags,
1384 const char *username)
1388 value_list_t vl = VALUE_LIST_INIT;
1392 int packet_was_signed = (flags & PP_SIGNED);
1393 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1394 int printed_ignore_warning = 0;
1395 #endif /* HAVE_LIBGCRYPT */
1398 memset (&vl, '\0', sizeof (vl));
1399 memset (&n, '\0', sizeof (n));
1402 while ((status == 0) && (0 < buffer_size)
1403 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1405 uint16_t pkg_length;
1408 memcpy ((void *) &pkg_type,
1411 memcpy ((void *) &pkg_length,
1412 (void *) (buffer + sizeof (pkg_type)),
1413 sizeof (pkg_length));
1415 pkg_length = ntohs (pkg_length);
1416 pkg_type = ntohs (pkg_type);
1418 if (pkg_length > buffer_size)
1420 /* Ensure that this loop terminates eventually */
1421 if (pkg_length < (2 * sizeof (uint16_t)))
1424 if (pkg_type == TYPE_ENCR_AES256)
1426 status = parse_part_encr_aes256 (se,
1427 &buffer, &buffer_size, flags);
1430 ERROR ("network plugin: Decrypting AES256 "
1432 "with status %i.", status);
1437 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1438 && (packet_was_encrypted == 0))
1440 if (printed_ignore_warning == 0)
1442 INFO ("network plugin: Unencrypted packet or "
1443 "part has been ignored.");
1444 printed_ignore_warning = 1;
1446 buffer = ((char *) buffer) + pkg_length;
1447 buffer_size -= (size_t) pkg_length;
1450 #endif /* HAVE_LIBGCRYPT */
1451 else if (pkg_type == TYPE_SIGN_SHA256)
1453 status = parse_part_sign_sha256 (se,
1454 &buffer, &buffer_size, flags);
1457 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1459 "with status %i.", status);
1464 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1465 && (packet_was_encrypted == 0)
1466 && (packet_was_signed == 0))
1468 if (printed_ignore_warning == 0)
1470 INFO ("network plugin: Unsigned packet or "
1471 "part has been ignored.");
1472 printed_ignore_warning = 1;
1474 buffer = ((char *) buffer) + pkg_length;
1475 buffer_size -= (size_t) pkg_length;
1478 #endif /* HAVE_LIBGCRYPT */
1479 else if (pkg_type == TYPE_VALUES)
1481 status = parse_part_values (&buffer, &buffer_size,
1482 &vl.values, &vl.values_len);
1486 network_dispatch_values (&vl, username);
1490 else if (pkg_type == TYPE_TIME)
1493 status = parse_part_number (&buffer, &buffer_size,
1497 vl.time = (time_t) tmp;
1498 n.time = (time_t) tmp;
1501 else if (pkg_type == TYPE_INTERVAL)
1504 status = parse_part_number (&buffer, &buffer_size,
1507 vl.interval = (int) tmp;
1509 else if (pkg_type == TYPE_HOST)
1511 status = parse_part_string (&buffer, &buffer_size,
1512 vl.host, sizeof (vl.host));
1514 sstrncpy (n.host, vl.host, sizeof (n.host));
1516 else if (pkg_type == TYPE_PLUGIN)
1518 status = parse_part_string (&buffer, &buffer_size,
1519 vl.plugin, sizeof (vl.plugin));
1521 sstrncpy (n.plugin, vl.plugin,
1524 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1526 status = parse_part_string (&buffer, &buffer_size,
1528 sizeof (vl.plugin_instance));
1530 sstrncpy (n.plugin_instance,
1532 sizeof (n.plugin_instance));
1534 else if (pkg_type == TYPE_TYPE)
1536 status = parse_part_string (&buffer, &buffer_size,
1537 vl.type, sizeof (vl.type));
1539 sstrncpy (n.type, vl.type, sizeof (n.type));
1541 else if (pkg_type == TYPE_TYPE_INSTANCE)
1543 status = parse_part_string (&buffer, &buffer_size,
1545 sizeof (vl.type_instance));
1547 sstrncpy (n.type_instance, vl.type_instance,
1548 sizeof (n.type_instance));
1550 else if (pkg_type == TYPE_MESSAGE)
1552 status = parse_part_string (&buffer, &buffer_size,
1553 n.message, sizeof (n.message));
1559 else if ((n.severity != NOTIF_FAILURE)
1560 && (n.severity != NOTIF_WARNING)
1561 && (n.severity != NOTIF_OKAY))
1563 INFO ("network plugin: "
1564 "Ignoring notification with "
1565 "unknown severity %i.",
1568 else if (n.time <= 0)
1570 INFO ("network plugin: "
1571 "Ignoring notification with "
1574 else if (strlen (n.message) <= 0)
1576 INFO ("network plugin: "
1577 "Ignoring notification with "
1578 "an empty message.");
1582 network_dispatch_notification (&n);
1585 else if (pkg_type == TYPE_SEVERITY)
1588 status = parse_part_number (&buffer, &buffer_size,
1591 n.severity = (int) tmp;
1595 DEBUG ("network plugin: parse_packet: Unknown part"
1596 " type: 0x%04hx", pkg_type);
1597 buffer = ((char *) buffer) + pkg_length;
1598 buffer_size -= (size_t) pkg_length;
1600 } /* while (buffer_size > sizeof (part_header_t)) */
1602 if (status == 0 && buffer_size > 0)
1603 WARNING ("network plugin: parse_packet: Received truncated "
1604 "packet, try increasing `MaxPacketSize'");
1607 } /* }}} int parse_packet */
1609 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1618 sfree (sec->username);
1619 sfree (sec->password);
1620 if (sec->cypher != NULL)
1621 gcry_cipher_close (sec->cypher);
1623 } /* }}} void free_sockent_client */
1625 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1629 for (i = 0; i < ses->fd_num; i++)
1631 if (ses->fd[i] >= 0)
1640 sfree (ses->auth_file);
1641 fbh_destroy (ses->userdb);
1642 if (ses->cypher != NULL)
1643 gcry_cipher_close (ses->cypher);
1645 } /* }}} void free_sockent_server */
1647 static void sockent_destroy (sockent_t *se) /* {{{ */
1651 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1658 sfree (se->service);
1660 if (se->type == SOCKENT_TYPE_CLIENT)
1661 free_sockent_client (&se->data.client);
1663 free_sockent_server (&se->data.server);
1668 } /* }}} void sockent_destroy */
1671 * int network_set_ttl
1673 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1674 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1676 * The `struct addrinfo' is used to destinguish between unicast and multicast
1679 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1681 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1682 network_config_ttl);
1684 assert (se->type == SOCKENT_TYPE_CLIENT);
1686 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1689 if (ai->ai_family == AF_INET)
1691 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1694 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1695 optname = IP_MULTICAST_TTL;
1699 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1700 &network_config_ttl,
1701 sizeof (network_config_ttl)) != 0)
1704 ERROR ("network plugin: setsockopt (ipv4-ttl): %s",
1705 sstrerror (errno, errbuf, sizeof (errbuf)));
1709 else if (ai->ai_family == AF_INET6)
1711 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1712 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1715 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1716 optname = IPV6_MULTICAST_HOPS;
1718 optname = IPV6_UNICAST_HOPS;
1720 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1721 &network_config_ttl,
1722 sizeof (network_config_ttl)) != 0)
1725 ERROR ("network plugin: setsockopt(ipv6-ttl): %s",
1726 sstrerror (errno, errbuf,
1733 } /* int network_set_ttl */
1735 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1737 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1740 assert (se->type == SOCKENT_TYPE_CLIENT);
1742 if (ai->ai_family == AF_INET)
1744 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1746 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1748 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1749 /* If possible, use the "ip_mreqn" structure which has
1750 * an "interface index" member. Using the interface
1751 * index is preferred here, because of its similarity
1752 * to the way IPv6 handles this. Unfortunately, it
1753 * appears not to be portable. */
1754 struct ip_mreqn mreq;
1756 memset (&mreq, 0, sizeof (mreq));
1757 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1758 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1759 mreq.imr_ifindex = se->interface;
1761 struct ip_mreq mreq;
1763 memset (&mreq, 0, sizeof (mreq));
1764 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1765 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1768 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1769 &mreq, sizeof (mreq)) != 0)
1772 ERROR ("network plugin: setsockopt (ipv4-multicast-if): %s",
1773 sstrerror (errno, errbuf, sizeof (errbuf)));
1780 else if (ai->ai_family == AF_INET6)
1782 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1784 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1786 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1788 sizeof (se->interface)) != 0)
1791 ERROR ("network plugin: setsockopt (ipv6-multicast-if): %s",
1792 sstrerror (errno, errbuf,
1801 /* else: Not a multicast interface. */
1802 if (se->interface != 0)
1804 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1805 char interface_name[IFNAMSIZ];
1807 if (if_indextoname (se->interface, interface_name) == NULL)
1810 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1812 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1814 sizeof(interface_name)) == -1 )
1817 ERROR ("network plugin: setsockopt (bind-if): %s",
1818 sstrerror (errno, errbuf, sizeof (errbuf)));
1821 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1824 WARNING ("network plugin: Cannot set the interface on a unicast "
1826 # if !defined(SO_BINDTODEVICE)
1827 "the \"SO_BINDTODEVICE\" socket option "
1829 "the \"if_indextoname\" function "
1831 "is not available on your system.");
1837 } /* }}} network_set_interface */
1839 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1848 /* allow multiple sockets to use the same PORT number */
1849 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1850 &yes, sizeof(yes)) == -1) {
1852 ERROR ("network plugin: setsockopt (reuseaddr): %s",
1853 sstrerror (errno, errbuf, sizeof (errbuf)));
1857 DEBUG ("fd = %i; calling `bind'", fd);
1859 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1863 sstrerror (errno, errbuf, sizeof (errbuf)));
1867 if (ai->ai_family == AF_INET)
1869 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1870 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1872 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1873 struct ip_mreqn mreq;
1875 struct ip_mreq mreq;
1878 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1880 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1881 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1882 /* Set the interface using the interface index if
1883 * possible (available). Unfortunately, the struct
1884 * ip_mreqn is not portable. */
1885 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1886 mreq.imr_ifindex = interface_idx;
1888 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1891 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1892 &loop, sizeof (loop)) == -1)
1895 ERROR ("network plugin: setsockopt (multicast-loop): %s",
1896 sstrerror (errno, errbuf,
1901 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1902 &mreq, sizeof (mreq)) == -1)
1905 ERROR ("network plugin: setsockopt (add-membership): %s",
1906 sstrerror (errno, errbuf,
1914 else if (ai->ai_family == AF_INET6)
1916 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1917 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1918 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1920 struct ipv6_mreq mreq;
1922 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1924 memcpy (&mreq.ipv6mr_multiaddr,
1926 sizeof (addr->sin6_addr));
1928 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1929 * ipv6mr_interface may be set to zeroes to
1930 * choose the default multicast interface or to
1931 * the index of a particular multicast-capable
1932 * interface if the host is multihomed.
1933 * Membership is associ-associated with a
1934 * single interface; programs running on
1935 * multihomed hosts may need to join the same
1936 * group on more than one interface.*/
1937 mreq.ipv6mr_interface = interface_idx;
1939 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1940 &loop, sizeof (loop)) == -1)
1943 ERROR ("network plugin: setsockopt (ipv6-multicast-loop): %s",
1944 sstrerror (errno, errbuf,
1949 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1950 &mreq, sizeof (mreq)) == -1)
1953 ERROR ("network plugin: setsockopt (ipv6-add-membership): %s",
1954 sstrerror (errno, errbuf,
1963 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1964 /* if a specific interface was set, bind the socket to it. But to avoid
1965 * possible problems with multicast routing, only do that for non-multicast
1967 if (interface_idx != 0)
1969 char interface_name[IFNAMSIZ];
1971 if (if_indextoname (interface_idx, interface_name) == NULL)
1974 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1976 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1978 sizeof(interface_name)) == -1 )
1981 ERROR ("network plugin: setsockopt (bind-if): %s",
1982 sstrerror (errno, errbuf, sizeof (errbuf)));
1986 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1989 } /* int network_bind_socket */
1991 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1992 * or `SOCKENT_TYPE_SERVER' */
1993 static int sockent_init (sockent_t *se, int type) /* {{{ */
1998 memset (se, 0, sizeof (*se));
2000 se->type = SOCKENT_TYPE_CLIENT;
2006 if (type == SOCKENT_TYPE_SERVER)
2008 se->type = SOCKENT_TYPE_SERVER;
2009 se->data.server.fd = NULL;
2011 se->data.server.security_level = SECURITY_LEVEL_NONE;
2012 se->data.server.auth_file = NULL;
2013 se->data.server.userdb = NULL;
2014 se->data.server.cypher = NULL;
2019 se->data.client.fd = -1;
2020 se->data.client.addr = NULL;
2022 se->data.client.security_level = SECURITY_LEVEL_NONE;
2023 se->data.client.username = NULL;
2024 se->data.client.password = NULL;
2025 se->data.client.cypher = NULL;
2030 } /* }}} int sockent_init */
2032 /* Open the file descriptors for a initialized sockent structure. */
2033 static int sockent_open (sockent_t *se) /* {{{ */
2035 struct addrinfo ai_hints;
2036 struct addrinfo *ai_list, *ai_ptr;
2040 const char *service;
2045 /* Set up the security structures. */
2046 #if HAVE_LIBGCRYPT /* {{{ */
2047 if (se->type == SOCKENT_TYPE_CLIENT)
2049 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
2051 if (network_init_gcrypt () < 0)
2053 ERROR ("network plugin: Cannot configure client socket with "
2054 "security: Failed to initialize crypto library.");
2058 if ((se->data.client.username == NULL)
2059 || (se->data.client.password == NULL))
2061 ERROR ("network plugin: Client socket with "
2062 "security requested, but no "
2063 "credentials are configured.");
2066 gcry_md_hash_buffer (GCRY_MD_SHA256,
2067 se->data.client.password_hash,
2068 se->data.client.password,
2069 strlen (se->data.client.password));
2072 else /* (se->type == SOCKENT_TYPE_SERVER) */
2074 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2076 if (network_init_gcrypt () < 0)
2078 ERROR ("network plugin: Cannot configure server socket with "
2079 "security: Failed to initialize crypto library.");
2083 if (se->data.server.auth_file == NULL)
2085 ERROR ("network plugin: Server socket with "
2086 "security requested, but no "
2087 "password file is configured.");
2091 if (se->data.server.auth_file != NULL)
2093 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2094 if (se->data.server.userdb == NULL)
2096 ERROR ("network plugin: Reading password file "
2098 se->data.server.auth_file);
2099 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2104 #endif /* }}} HAVE_LIBGCRYPT */
2107 service = se->service;
2109 if (service == NULL)
2110 service = NET_DEFAULT_PORT;
2112 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
2115 memset (&ai_hints, 0, sizeof (ai_hints));
2116 ai_hints.ai_flags = 0;
2118 ai_hints.ai_flags |= AI_PASSIVE;
2120 #ifdef AI_ADDRCONFIG
2121 ai_hints.ai_flags |= AI_ADDRCONFIG;
2123 ai_hints.ai_family = AF_UNSPEC;
2124 ai_hints.ai_socktype = SOCK_DGRAM;
2125 ai_hints.ai_protocol = IPPROTO_UDP;
2127 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2130 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2131 (se->node == NULL) ? "(null)" : se->node,
2132 (se->service == NULL) ? "(null)" : se->service,
2133 gai_strerror (ai_return));
2137 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2141 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2145 tmp = realloc (se->data.server.fd,
2146 sizeof (*tmp) * (se->data.server.fd_num + 1));
2149 ERROR ("network plugin: realloc failed.");
2152 se->data.server.fd = tmp;
2153 tmp = se->data.server.fd + se->data.server.fd_num;
2155 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2156 ai_ptr->ai_protocol);
2160 ERROR ("network plugin: socket(2) failed: %s",
2161 sstrerror (errno, errbuf,
2166 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2174 se->data.server.fd_num++;
2176 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2177 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2179 se->data.client.fd = socket (ai_ptr->ai_family,
2180 ai_ptr->ai_socktype,
2181 ai_ptr->ai_protocol);
2182 if (se->data.client.fd < 0)
2185 ERROR ("network plugin: socket(2) failed: %s",
2186 sstrerror (errno, errbuf,
2191 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2192 if (se->data.client.addr == NULL)
2194 ERROR ("network plugin: malloc failed.");
2195 close (se->data.client.fd);
2196 se->data.client.fd = -1;
2200 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2201 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2202 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2203 se->data.client.addrlen = ai_ptr->ai_addrlen;
2205 network_set_ttl (se, ai_ptr);
2206 network_set_interface (se, ai_ptr);
2208 /* We don't open more than one write-socket per
2209 * node/service pair.. */
2211 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2212 } /* for (ai_list) */
2214 freeaddrinfo (ai_list);
2216 /* Check if all went well. */
2217 if (se->type == SOCKENT_TYPE_SERVER)
2219 if (se->data.server.fd_num <= 0)
2222 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2224 if (se->data.client.fd < 0)
2229 } /* }}} int sockent_open */
2231 /* Add a sockent to the global list of sockets */
2232 static int sockent_add (sockent_t *se) /* {{{ */
2234 sockent_t *last_ptr;
2239 if (se->type == SOCKENT_TYPE_SERVER)
2244 tmp = realloc (listen_sockets_pollfd,
2245 sizeof (*tmp) * (listen_sockets_num
2246 + se->data.server.fd_num));
2249 ERROR ("network plugin: realloc failed.");
2252 listen_sockets_pollfd = tmp;
2253 tmp = listen_sockets_pollfd + listen_sockets_num;
2255 for (i = 0; i < se->data.server.fd_num; i++)
2257 memset (tmp + i, 0, sizeof (*tmp));
2258 tmp[i].fd = se->data.server.fd[i];
2259 tmp[i].events = POLLIN | POLLPRI;
2263 listen_sockets_num += se->data.server.fd_num;
2265 if (listen_sockets == NULL)
2267 listen_sockets = se;
2270 last_ptr = listen_sockets;
2272 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2274 if (sending_sockets == NULL)
2276 sending_sockets = se;
2279 last_ptr = sending_sockets;
2282 while (last_ptr->next != NULL)
2283 last_ptr = last_ptr->next;
2284 last_ptr->next = se;
2287 } /* }}} int sockent_add */
2289 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2293 receive_list_entry_t *ent;
2296 /* Lock and wait for more data to come in */
2297 pthread_mutex_lock (&receive_list_lock);
2298 while ((listen_loop == 0)
2299 && (receive_list_head == NULL))
2300 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2302 /* Remove the head entry and unlock */
2303 ent = receive_list_head;
2305 receive_list_head = ent->next;
2306 receive_list_length--;
2307 pthread_mutex_unlock (&receive_list_lock);
2309 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2310 * because we dispatch all missing packets before shutting down. */
2314 /* Look for the correct `sockent_t' */
2315 se = listen_sockets;
2320 for (i = 0; i < se->data.server.fd_num; i++)
2321 if (se->data.server.fd[i] == ent->fd)
2324 if (i < se->data.server.fd_num)
2332 ERROR ("network plugin: Got packet from FD %i, but can't "
2333 "find an appropriate socket entry.",
2340 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2341 /* username = */ NULL);
2347 } /* }}} void *dispatch_thread */
2349 static int network_receive (void) /* {{{ */
2351 char buffer[network_config_packet_size];
2357 receive_list_entry_t *private_list_head;
2358 receive_list_entry_t *private_list_tail;
2359 uint64_t private_list_length;
2361 assert (listen_sockets_num > 0);
2363 private_list_head = NULL;
2364 private_list_tail = NULL;
2365 private_list_length = 0;
2367 while (listen_loop == 0)
2369 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2376 ERROR ("poll failed: %s",
2377 sstrerror (errno, errbuf, sizeof (errbuf)));
2381 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2383 receive_list_entry_t *ent;
2385 if ((listen_sockets_pollfd[i].revents
2386 & (POLLIN | POLLPRI)) == 0)
2390 buffer_len = recv (listen_sockets_pollfd[i].fd,
2391 buffer, sizeof (buffer),
2396 ERROR ("recv failed: %s",
2397 sstrerror (errno, errbuf,
2402 stats_octets_rx += ((uint64_t) buffer_len);
2405 /* TODO: Possible performance enhancement: Do not free
2406 * these entries in the dispatch thread but put them in
2407 * another list, so we don't have to allocate more and
2408 * more of these structures. */
2409 ent = malloc (sizeof (receive_list_entry_t));
2412 ERROR ("network plugin: malloc failed.");
2415 memset (ent, 0, sizeof (receive_list_entry_t));
2416 ent->data = malloc (network_config_packet_size);
2417 if (ent->data == NULL)
2420 ERROR ("network plugin: malloc failed.");
2423 ent->fd = listen_sockets_pollfd[i].fd;
2426 memcpy (ent->data, buffer, buffer_len);
2427 ent->data_len = buffer_len;
2429 if (private_list_head == NULL)
2430 private_list_head = ent;
2432 private_list_tail->next = ent;
2433 private_list_tail = ent;
2434 private_list_length++;
2436 /* Do not block here. Blocking here has led to
2437 * insufficient performance in the past. */
2438 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2440 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2441 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2443 if (receive_list_head == NULL)
2444 receive_list_head = private_list_head;
2446 receive_list_tail->next = private_list_head;
2447 receive_list_tail = private_list_tail;
2448 receive_list_length += private_list_length;
2450 pthread_cond_signal (&receive_list_cond);
2451 pthread_mutex_unlock (&receive_list_lock);
2453 private_list_head = NULL;
2454 private_list_tail = NULL;
2455 private_list_length = 0;
2457 } /* for (listen_sockets_pollfd) */
2458 } /* while (listen_loop == 0) */
2460 /* Make sure everything is dispatched before exiting. */
2461 if (private_list_head != NULL)
2463 pthread_mutex_lock (&receive_list_lock);
2465 if (receive_list_head == NULL)
2466 receive_list_head = private_list_head;
2468 receive_list_tail->next = private_list_head;
2469 receive_list_tail = private_list_tail;
2470 receive_list_length += private_list_length;
2472 private_list_head = NULL;
2473 private_list_tail = NULL;
2474 private_list_length = 0;
2476 pthread_cond_signal (&receive_list_cond);
2477 pthread_mutex_unlock (&receive_list_lock);
2481 } /* }}} int network_receive */
2483 static void *receive_thread (void __attribute__((unused)) *arg)
2485 return (network_receive () ? (void *) 1 : (void *) 0);
2486 } /* void *receive_thread */
2488 static void network_init_buffer (void)
2490 memset (send_buffer, 0, network_config_packet_size);
2491 send_buffer_ptr = send_buffer;
2492 send_buffer_fill = 0;
2494 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2495 } /* int network_init_buffer */
2497 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2498 const char *buffer, size_t buffer_size)
2504 status = sendto (se->data.client.fd, buffer, buffer_size,
2506 (struct sockaddr *) se->data.client.addr,
2507 se->data.client.addrlen);
2513 ERROR ("network plugin: sendto failed: %s",
2514 sstrerror (errno, errbuf,
2521 } /* }}} void networt_send_buffer_plain */
2524 #define BUFFER_ADD(p,s) do { \
2525 memcpy (buffer + buffer_offset, (p), (s)); \
2526 buffer_offset += (s); \
2529 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2530 const char *in_buffer, size_t in_buffer_size)
2532 part_signature_sha256_t ps;
2533 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2534 size_t buffer_offset;
2535 size_t username_len;
2539 unsigned char *hash;
2542 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2545 ERROR ("network plugin: Creating HMAC object failed: %s",
2546 gcry_strerror (err));
2550 err = gcry_md_setkey (hd, se->data.client.password,
2551 strlen (se->data.client.password));
2554 ERROR ("network plugin: gcry_md_setkey failed: %s",
2555 gcry_strerror (err));
2560 username_len = strlen (se->data.client.username);
2561 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2563 ERROR ("network plugin: Username too long: %s",
2564 se->data.client.username);
2568 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2569 se->data.client.username, username_len);
2570 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2571 in_buffer, in_buffer_size);
2573 /* Initialize the `ps' structure. */
2574 memset (&ps, 0, sizeof (ps));
2575 ps.head.type = htons (TYPE_SIGN_SHA256);
2576 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2578 /* Calculate the hash value. */
2579 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2580 username_len + in_buffer_size);
2581 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2584 ERROR ("network plugin: gcry_md_read failed.");
2588 memcpy (ps.hash, hash, sizeof (ps.hash));
2590 /* Add the header */
2593 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2594 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2595 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2597 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2602 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2603 networt_send_buffer_plain (se, buffer, buffer_offset);
2604 } /* }}} void networt_send_buffer_signed */
2606 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2607 const char *in_buffer, size_t in_buffer_size)
2609 part_encryption_aes256_t pea;
2610 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2612 size_t buffer_offset;
2614 size_t username_len;
2616 gcry_cipher_hd_t cypher;
2618 /* Initialize the header fields */
2619 memset (&pea, 0, sizeof (pea));
2620 pea.head.type = htons (TYPE_ENCR_AES256);
2622 pea.username = se->data.client.username;
2624 username_len = strlen (pea.username);
2625 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2627 ERROR ("network plugin: Username too long: %s", pea.username);
2631 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2632 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2633 - sizeof (pea.hash);
2635 assert (buffer_size <= sizeof (buffer));
2636 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2637 "buffer_size = %zu;", buffer_size);
2639 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2640 + username_len + in_buffer_size));
2641 pea.username_length = htons ((uint16_t) username_len);
2643 /* Chose a random initialization vector. */
2644 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2646 /* Create hash of the payload */
2647 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2649 /* Initialize the buffer */
2651 memset (buffer, 0, sizeof (buffer));
2654 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2655 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2656 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2657 BUFFER_ADD (pea.username, username_len);
2658 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2659 assert (buffer_offset == header_size);
2660 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2661 BUFFER_ADD (in_buffer, in_buffer_size);
2663 assert (buffer_offset == buffer_size);
2665 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2666 se->data.client.password);
2670 /* Encrypt the buffer in-place */
2671 err = gcry_cipher_encrypt (cypher,
2672 buffer + header_size,
2673 buffer_size - header_size,
2674 /* in = */ NULL, /* in len = */ 0);
2677 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2678 gcry_strerror (err));
2682 /* Send it out without further modifications */
2683 networt_send_buffer_plain (se, buffer, buffer_size);
2684 } /* }}} void networt_send_buffer_encrypted */
2686 #endif /* HAVE_LIBGCRYPT */
2688 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2692 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2694 for (se = sending_sockets; se != NULL; se = se->next)
2697 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2698 networt_send_buffer_encrypted (se, buffer, buffer_len);
2699 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2700 networt_send_buffer_signed (se, buffer, buffer_len);
2701 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2702 #endif /* HAVE_LIBGCRYPT */
2703 networt_send_buffer_plain (se, buffer, buffer_len);
2704 } /* for (sending_sockets) */
2705 } /* }}} void network_send_buffer */
2707 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2708 value_list_t *vl_def,
2709 const data_set_t *ds, const value_list_t *vl)
2711 char *buffer_orig = buffer;
2713 if (strcmp (vl_def->host, vl->host) != 0)
2715 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2716 vl->host, strlen (vl->host)) != 0)
2718 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2721 if (vl_def->time != vl->time)
2723 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2724 (uint64_t) vl->time))
2726 vl_def->time = vl->time;
2729 if (vl_def->interval != vl->interval)
2731 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2732 (uint64_t) vl->interval))
2734 vl_def->interval = vl->interval;
2737 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2739 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2740 vl->plugin, strlen (vl->plugin)) != 0)
2742 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2745 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2747 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2748 vl->plugin_instance,
2749 strlen (vl->plugin_instance)) != 0)
2751 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2754 if (strcmp (vl_def->type, vl->type) != 0)
2756 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2757 vl->type, strlen (vl->type)) != 0)
2759 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2762 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2764 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2766 strlen (vl->type_instance)) != 0)
2768 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2771 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2774 return (buffer - buffer_orig);
2775 } /* }}} int add_to_buffer */
2777 static void flush_buffer (void)
2779 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2782 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2784 stats_octets_tx += ((uint64_t) send_buffer_fill);
2787 network_init_buffer ();
2790 static int network_write (const data_set_t *ds, const value_list_t *vl,
2791 user_data_t __attribute__((unused)) *user_data)
2795 if (!check_send_okay (vl))
2798 char name[6*DATA_MAX_NAME_LEN];
2799 FORMAT_VL (name, sizeof (name), vl);
2800 name[sizeof (name) - 1] = 0;
2801 DEBUG ("network plugin: network_write: "
2802 "NOT sending %s.", name);
2804 /* Counter is not protected by another lock and may be reached by
2805 * multiple threads */
2806 pthread_mutex_lock (&stats_lock);
2807 stats_values_not_sent++;
2808 pthread_mutex_unlock (&stats_lock);
2812 uc_meta_data_add_unsigned_int (vl,
2813 "network:time_sent", (uint64_t) vl->time);
2815 pthread_mutex_lock (&send_buffer_lock);
2817 status = add_to_buffer (send_buffer_ptr,
2818 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2823 /* status == bytes added to the buffer */
2824 send_buffer_fill += status;
2825 send_buffer_ptr += status;
2827 stats_values_sent++;
2833 status = add_to_buffer (send_buffer_ptr,
2834 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2840 send_buffer_fill += status;
2841 send_buffer_ptr += status;
2843 stats_values_sent++;
2849 ERROR ("network plugin: Unable to append to the "
2850 "buffer for some weird reason");
2852 else if ((network_config_packet_size - send_buffer_fill) < 15)
2857 pthread_mutex_unlock (&send_buffer_lock);
2859 return ((status < 0) ? -1 : 0);
2860 } /* int network_write */
2862 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2865 if ((ci->values_num != 1)
2866 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2867 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2869 ERROR ("network plugin: The `%s' config option needs "
2870 "exactly one boolean argument.", ci->key);
2874 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2876 if (ci->values[0].value.boolean)
2883 char *str = ci->values[0].value.string;
2887 else if (IS_FALSE (str))
2891 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2892 "option as boolean value.",
2899 } /* }}} int network_config_set_boolean */
2901 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2904 if ((ci->values_num != 1)
2905 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2907 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2908 "one numeric argument.");
2912 tmp = (int) ci->values[0].value.number;
2913 if ((tmp > 0) && (tmp <= 255))
2914 network_config_ttl = tmp;
2917 } /* }}} int network_config_set_ttl */
2919 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2922 if ((ci->values_num != 1)
2923 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2925 WARNING ("network plugin: The `Interface' config option needs exactly "
2926 "one string argument.");
2930 if (interface == NULL)
2933 *interface = if_nametoindex (ci->values[0].value.string);
2936 } /* }}} int network_config_set_interface */
2938 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2941 if ((ci->values_num != 1)
2942 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2944 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2945 "one numeric argument.");
2949 tmp = (int) ci->values[0].value.number;
2950 if ((tmp >= 1024) && (tmp <= 65535))
2951 network_config_packet_size = tmp;
2954 } /* }}} int network_config_set_buffer_size */
2957 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2961 if ((ci->values_num != 1)
2962 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2964 WARNING ("network plugin: The `%s' config option needs exactly "
2965 "one string argument.", ci->key);
2969 tmp = strdup (ci->values[0].value.string);
2973 sfree (*ret_string);
2977 } /* }}} int network_config_set_string */
2978 #endif /* HAVE_LIBGCRYPT */
2981 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2985 if ((ci->values_num != 1)
2986 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2988 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2989 "one string argument.");
2993 str = ci->values[0].value.string;
2994 if (strcasecmp ("Encrypt", str) == 0)
2995 *retval = SECURITY_LEVEL_ENCRYPT;
2996 else if (strcasecmp ("Sign", str) == 0)
2997 *retval = SECURITY_LEVEL_SIGN;
2998 else if (strcasecmp ("None", str) == 0)
2999 *retval = SECURITY_LEVEL_NONE;
3002 WARNING ("network plugin: Unknown security level: %s.", str);
3007 } /* }}} int network_config_set_security_level */
3008 #endif /* HAVE_LIBGCRYPT */
3010 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
3016 if ((ci->values_num < 1) || (ci->values_num > 2)
3017 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3018 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3020 ERROR ("network plugin: The `%s' config option needs "
3021 "one or two string arguments.", ci->key);
3025 se = malloc (sizeof (*se));
3028 ERROR ("network plugin: malloc failed.");
3031 sockent_init (se, SOCKENT_TYPE_SERVER);
3033 se->node = strdup (ci->values[0].value.string);
3034 if (ci->values_num >= 2)
3035 se->service = strdup (ci->values[1].value.string);
3037 for (i = 0; i < ci->children_num; i++)
3039 oconfig_item_t *child = ci->children + i;
3042 if (strcasecmp ("AuthFile", child->key) == 0)
3043 network_config_set_string (child, &se->data.server.auth_file);
3044 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3045 network_config_set_security_level (child,
3046 &se->data.server.security_level);
3048 #endif /* HAVE_LIBGCRYPT */
3049 if (strcasecmp ("Interface", child->key) == 0)
3050 network_config_set_interface (child,
3054 WARNING ("network plugin: Option `%s' is not allowed here.",
3060 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3061 && (se->data.server.auth_file == NULL))
3063 ERROR ("network plugin: A security level higher than `none' was "
3064 "requested, but no AuthFile option was given. Cowardly refusing to "
3065 "open this socket!");
3066 sockent_destroy (se);
3069 #endif /* HAVE_LIBGCRYPT */
3071 status = sockent_open (se);
3074 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
3075 sockent_destroy (se);
3079 status = sockent_add (se);
3082 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3083 sockent_destroy (se);
3088 } /* }}} int network_config_add_listen */
3090 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3096 if ((ci->values_num < 1) || (ci->values_num > 2)
3097 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3098 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3100 ERROR ("network plugin: The `%s' config option needs "
3101 "one or two string arguments.", ci->key);
3105 se = malloc (sizeof (*se));
3108 ERROR ("network plugin: malloc failed.");
3111 sockent_init (se, SOCKENT_TYPE_CLIENT);
3113 se->node = strdup (ci->values[0].value.string);
3114 if (ci->values_num >= 2)
3115 se->service = strdup (ci->values[1].value.string);
3117 for (i = 0; i < ci->children_num; i++)
3119 oconfig_item_t *child = ci->children + i;
3122 if (strcasecmp ("Username", child->key) == 0)
3123 network_config_set_string (child, &se->data.client.username);
3124 else if (strcasecmp ("Password", child->key) == 0)
3125 network_config_set_string (child, &se->data.client.password);
3126 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3127 network_config_set_security_level (child,
3128 &se->data.client.security_level);
3130 #endif /* HAVE_LIBGCRYPT */
3131 if (strcasecmp ("Interface", child->key) == 0)
3132 network_config_set_interface (child,
3136 WARNING ("network plugin: Option `%s' is not allowed here.",
3142 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3143 && ((se->data.client.username == NULL)
3144 || (se->data.client.password == NULL)))
3146 ERROR ("network plugin: A security level higher than `none' was "
3147 "requested, but no Username or Password option was given. "
3148 "Cowardly refusing to open this socket!");
3149 sockent_destroy (se);
3152 #endif /* HAVE_LIBGCRYPT */
3154 status = sockent_open (se);
3157 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3158 sockent_destroy (se);
3162 status = sockent_add (se);
3165 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3166 sockent_destroy (se);
3171 } /* }}} int network_config_add_server */
3173 static int network_config (oconfig_item_t *ci) /* {{{ */
3177 for (i = 0; i < ci->children_num; i++)
3179 oconfig_item_t *child = ci->children + i;
3181 if (strcasecmp ("Listen", child->key) == 0)
3182 network_config_add_listen (child);
3183 else if (strcasecmp ("Server", child->key) == 0)
3184 network_config_add_server (child);
3185 else if (strcasecmp ("TimeToLive", child->key) == 0)
3186 network_config_set_ttl (child);
3187 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3188 network_config_set_buffer_size (child);
3189 else if (strcasecmp ("Forward", child->key) == 0)
3190 network_config_set_boolean (child, &network_config_forward);
3191 else if (strcasecmp ("ReportStats", child->key) == 0)
3192 network_config_set_boolean (child, &network_config_stats);
3193 else if (strcasecmp ("CacheFlush", child->key) == 0)
3194 /* no op for backwards compatibility only */;
3197 WARNING ("network plugin: Option `%s' is not allowed here.",
3203 } /* }}} int network_config */
3205 static int network_notification (const notification_t *n,
3206 user_data_t __attribute__((unused)) *user_data)
3208 char buffer[network_config_packet_size];
3209 char *buffer_ptr = buffer;
3210 int buffer_free = sizeof (buffer);
3213 if (!check_send_notify_okay (n))
3216 memset (buffer, 0, sizeof (buffer));
3218 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
3219 (uint64_t) n->time);
3223 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3224 (uint64_t) n->severity);
3228 if (strlen (n->host) > 0)
3230 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3231 n->host, strlen (n->host));
3236 if (strlen (n->plugin) > 0)
3238 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3239 n->plugin, strlen (n->plugin));
3244 if (strlen (n->plugin_instance) > 0)
3246 status = write_part_string (&buffer_ptr, &buffer_free,
3247 TYPE_PLUGIN_INSTANCE,
3248 n->plugin_instance, strlen (n->plugin_instance));
3253 if (strlen (n->type) > 0)
3255 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3256 n->type, strlen (n->type));
3261 if (strlen (n->type_instance) > 0)
3263 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3264 n->type_instance, strlen (n->type_instance));
3269 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3270 n->message, strlen (n->message));
3274 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3277 } /* int network_notification */
3279 static int network_shutdown (void)
3283 /* Kill the listening thread */
3284 if (receive_thread_running != 0)
3286 INFO ("network plugin: Stopping receive thread.");
3287 pthread_kill (receive_thread_id, SIGTERM);
3288 pthread_join (receive_thread_id, NULL /* no return value */);
3289 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3290 receive_thread_running = 0;
3293 /* Shutdown the dispatching thread */
3294 if (dispatch_thread_running != 0)
3296 INFO ("network plugin: Stopping dispatch thread.");
3297 pthread_mutex_lock (&receive_list_lock);
3298 pthread_cond_broadcast (&receive_list_cond);
3299 pthread_mutex_unlock (&receive_list_lock);
3300 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3301 dispatch_thread_running = 0;
3304 sockent_destroy (listen_sockets);
3306 if (send_buffer_fill > 0)
3309 sfree (send_buffer);
3311 /* TODO: Close `sending_sockets' */
3313 plugin_unregister_config ("network");
3314 plugin_unregister_init ("network");
3315 plugin_unregister_write ("network");
3316 plugin_unregister_shutdown ("network");
3319 } /* int network_shutdown */
3321 static int network_stats_read (void) /* {{{ */
3323 uint64_t copy_octets_rx;
3324 uint64_t copy_octets_tx;
3325 uint64_t copy_packets_rx;
3326 uint64_t copy_packets_tx;
3327 uint64_t copy_values_dispatched;
3328 uint64_t copy_values_not_dispatched;
3329 uint64_t copy_values_sent;
3330 uint64_t copy_values_not_sent;
3331 uint64_t copy_receive_list_length;
3332 value_list_t vl = VALUE_LIST_INIT;
3335 copy_octets_rx = stats_octets_rx;
3336 copy_octets_tx = stats_octets_tx;
3337 copy_packets_rx = stats_packets_rx;
3338 copy_packets_tx = stats_packets_tx;
3339 copy_values_dispatched = stats_values_dispatched;
3340 copy_values_not_dispatched = stats_values_not_dispatched;
3341 copy_values_sent = stats_values_sent;
3342 copy_values_not_sent = stats_values_not_sent;
3343 copy_receive_list_length = receive_list_length;
3345 /* Initialize `vl' */
3349 vl.interval = interval_g;
3350 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3351 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3353 /* Octets received / sent */
3354 vl.values[0].counter = (counter_t) copy_octets_rx;
3355 vl.values[1].counter = (counter_t) copy_octets_tx;
3356 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3357 plugin_dispatch_values_secure (&vl);
3359 /* Packets received / send */
3360 vl.values[0].counter = (counter_t) copy_packets_rx;
3361 vl.values[1].counter = (counter_t) copy_packets_tx;
3362 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3363 plugin_dispatch_values_secure (&vl);
3365 /* Values (not) dispatched and (not) send */
3366 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3369 vl.values[0].derive = (derive_t) copy_values_dispatched;
3370 sstrncpy (vl.type_instance, "dispatch-accepted",
3371 sizeof (vl.type_instance));
3372 plugin_dispatch_values_secure (&vl);
3374 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3375 sstrncpy (vl.type_instance, "dispatch-rejected",
3376 sizeof (vl.type_instance));
3377 plugin_dispatch_values_secure (&vl);
3379 vl.values[0].derive = (derive_t) copy_values_sent;
3380 sstrncpy (vl.type_instance, "send-accepted",
3381 sizeof (vl.type_instance));
3382 plugin_dispatch_values_secure (&vl);
3384 vl.values[0].derive = (derive_t) copy_values_not_sent;
3385 sstrncpy (vl.type_instance, "send-rejected",
3386 sizeof (vl.type_instance));
3387 plugin_dispatch_values_secure (&vl);
3389 /* Receive queue length */
3390 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3391 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3392 vl.type_instance[0] = 0;
3393 plugin_dispatch_values_secure (&vl);
3396 } /* }}} int network_stats_read */
3398 static int network_init (void)
3400 static _Bool have_init = false;
3402 /* Check if we were already initialized. If so, just return - there's
3403 * nothing more to do (for now, that is). */
3409 if (network_init_gcrypt () < 0)
3411 ERROR ("network plugin: Failed to initialize crypto library.");
3416 if (network_config_stats != 0)
3417 plugin_register_read ("network", network_stats_read);
3419 plugin_register_shutdown ("network", network_shutdown);
3421 send_buffer = malloc (network_config_packet_size);
3422 if (send_buffer == NULL)
3424 ERROR ("network plugin: malloc failed.");
3427 network_init_buffer ();
3429 /* setup socket(s) and so on */
3430 if (sending_sockets != NULL)
3432 plugin_register_write ("network", network_write,
3433 /* user_data = */ NULL);
3434 plugin_register_notification ("network", network_notification,
3435 /* user_data = */ NULL);
3438 /* If no threads need to be started, return here. */
3439 if ((listen_sockets_num == 0)
3440 || ((dispatch_thread_running != 0)
3441 && (receive_thread_running != 0)))
3444 if (dispatch_thread_running == 0)
3447 status = pthread_create (&dispatch_thread_id,
3448 NULL /* no attributes */,
3450 NULL /* no argument */);
3454 ERROR ("network: pthread_create failed: %s",
3455 sstrerror (errno, errbuf,
3460 dispatch_thread_running = 1;
3464 if (receive_thread_running == 0)
3467 status = pthread_create (&receive_thread_id,
3468 NULL /* no attributes */,
3470 NULL /* no argument */);
3474 ERROR ("network: pthread_create failed: %s",
3475 sstrerror (errno, errbuf,
3480 receive_thread_running = 1;
3485 } /* int network_init */
3488 * The flush option of the network plugin cannot flush individual identifiers.
3489 * All the values are added to a buffer and sent when the buffer is full, the
3490 * requested value may or may not be in there, it's not worth finding out. We
3491 * just send the buffer if `flush' is called - if the requested value was in
3492 * there, good. If not, well, then there is nothing to flush.. -octo
3494 static int network_flush (int timeout,
3495 const char __attribute__((unused)) *identifier,
3496 user_data_t __attribute__((unused)) *user_data)
3498 pthread_mutex_lock (&send_buffer_lock);
3500 if (send_buffer_fill > 0)
3503 pthread_mutex_unlock (&send_buffer_lock);
3506 } /* int network_flush */
3508 void module_register (void)
3510 plugin_register_complex_config ("network", network_config);
3511 plugin_register_init ("network", network_init);
3512 plugin_register_flush ("network", network_flush,
3513 /* user_data = */ NULL);
3514 } /* void module_register */
3516 /* vim: set fdm=marker : */