2 * collectd - src/network.c
3 * Copyright (C) 2005-2010 Florian octo Forster
4 * Copyright (C) 2009 Aman Gupta
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation; only version 2.1 of the License is
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 * Florian octo Forster <octo at verplant.org>
22 * Aman Gupta <aman at tmm1.net>
25 #define _BSD_SOURCE /* For struct ip_mreq */
30 #include "configfile.h"
31 #include "utils_fbhash.h"
32 #include "utils_avltree.h"
33 #include "utils_cache.h"
34 #include "utils_complain.h"
42 # include <sys/socket.h>
48 # include <netinet/in.h>
51 # include <arpa/inet.h>
62 GCRY_THREAD_OPTION_PTHREAD_IMPL;
65 #ifndef IPV6_ADD_MEMBERSHIP
66 # ifdef IPV6_JOIN_GROUP
67 # define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
69 # error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
71 #endif /* !IP_ADD_MEMBERSHIP */
74 * Maximum size required for encryption / signing:
76 * 42 bytes for the encryption header
77 * + 64 bytes for the username
81 #define BUFF_SIG_SIZE 106
86 #define SECURITY_LEVEL_NONE 0
88 # define SECURITY_LEVEL_SIGN 1
89 # define SECURITY_LEVEL_ENCRYPT 2
94 struct sockaddr_storage *addr;
100 gcry_cipher_hd_t cypher;
101 unsigned char password_hash[32];
105 struct sockent_server
113 gcry_cipher_hd_t cypher;
117 typedef struct sockent
119 #define SOCKENT_TYPE_CLIENT 1
120 #define SOCKENT_TYPE_SERVER 2
129 struct sockent_client client;
130 struct sockent_server server;
133 struct sockent *next;
136 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
137 * 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
138 * +-------+-----------------------+-------------------------------+
139 * ! Ver. ! ! Length !
140 * +-------+-----------------------+-------------------------------+
147 typedef struct part_header_s part_header_t;
149 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
150 * 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
151 * +-------------------------------+-------------------------------+
153 * +-------------------------------+-------------------------------+
154 * : (Length - 4) Bytes :
155 * +---------------------------------------------------------------+
162 typedef struct part_string_s part_string_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 == 2 || 4 || 8) Bytes :
170 * +---------------------------------------------------------------+
177 typedef struct part_number_s part_number_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 * ! Num of values ! Type0 ! Type1 !
185 * +-------------------------------+---------------+---------------+
188 * +---------------------------------------------------------------+
191 * +---------------------------------------------------------------+
196 uint16_t *num_values;
197 uint8_t *values_types;
200 typedef struct part_values_s part_values_t;
202 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
203 * 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
204 * +-------------------------------+-------------------------------+
206 * +-------------------------------+-------------------------------+
207 * ! Hash (Bits 0 - 31) !
209 * ! Hash (Bits 224 - 255) !
210 * +---------------------------------------------------------------+
213 #define PART_SIGNATURE_SHA256_SIZE 36
214 struct part_signature_sha256_s
217 unsigned char hash[32];
220 typedef struct part_signature_sha256_s part_signature_sha256_t;
222 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
223 * 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
224 * +-------------------------------+-------------------------------+
226 * +-------------------------------+-------------------------------+
227 * ! Original length ! Padding (0 - 15 bytes) !
228 * +-------------------------------+-------------------------------+
229 * ! Hash (Bits 0 - 31) !
231 * ! Hash (Bits 128 - 159) !
232 * +---------------------------------------------------------------+
235 #define PART_ENCRYPTION_AES256_SIZE 42
236 struct part_encryption_aes256_s
239 uint16_t username_length;
241 unsigned char iv[16];
243 unsigned char hash[20];
247 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
249 struct receive_list_entry_s
254 struct receive_list_entry_s *next;
256 typedef struct receive_list_entry_s receive_list_entry_t;
261 static int network_config_ttl = 0;
262 /* Ethernet - (IPv6 + UDP) = 1500 - (40 + 8) = 1452 */
263 static size_t network_config_packet_size = 1452;
264 static int network_config_forward = 0;
265 static int network_config_stats = 0;
267 static sockent_t *sending_sockets = NULL;
269 static receive_list_entry_t *receive_list_head = NULL;
270 static receive_list_entry_t *receive_list_tail = NULL;
271 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
272 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
273 static uint64_t receive_list_length = 0;
275 static sockent_t *listen_sockets = NULL;
276 static struct pollfd *listen_sockets_pollfd = NULL;
277 static size_t listen_sockets_num = 0;
279 /* The receive and dispatch threads will run as long as `listen_loop' is set to
281 static int listen_loop = 0;
282 static int receive_thread_running = 0;
283 static pthread_t receive_thread_id;
284 static int dispatch_thread_running = 0;
285 static pthread_t dispatch_thread_id;
287 /* Buffer in which to-be-sent network packets are constructed. */
288 static char *send_buffer;
289 static char *send_buffer_ptr;
290 static int send_buffer_fill;
291 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
292 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
294 /* XXX: These counters are incremented from one place only. The spot in which
295 * the values are incremented is either only reachable by one thread (the
296 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
297 * example). Only if neither is true, the stats_lock is acquired. The counters
298 * are always read without holding a lock in the hope that writing 8 bytes to
299 * memory is an atomic operation. */
300 static derive_t stats_octets_rx = 0;
301 static derive_t stats_octets_tx = 0;
302 static derive_t stats_packets_rx = 0;
303 static derive_t stats_packets_tx = 0;
304 static derive_t stats_values_dispatched = 0;
305 static derive_t stats_values_not_dispatched = 0;
306 static derive_t stats_values_sent = 0;
307 static derive_t stats_values_not_sent = 0;
308 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
313 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
315 uint64_t time_sent = 0;
318 status = uc_meta_data_get_unsigned_int (vl,
319 "network:time_sent", &time_sent);
321 /* This is a value we already sent. Don't allow it to be received again in
322 * order to avoid looping. */
323 if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
327 } /* }}} _Bool check_receive_okay */
329 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
334 if (network_config_forward != 0)
337 if (vl->meta == NULL)
340 status = meta_data_get_boolean (vl->meta, "network:received", &received);
341 if (status == -ENOENT)
343 else if (status != 0)
345 ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
346 "with status %i.", status);
350 /* By default, only *send* value lists that were not *received* by the
353 } /* }}} _Bool check_send_okay */
355 static _Bool check_notify_received (const notification_t *n) /* {{{ */
357 notification_meta_t *ptr;
359 for (ptr = n->meta; ptr != NULL; ptr = ptr->next)
360 if ((strcmp ("network:received", ptr->name) == 0)
361 && (ptr->type == NM_TYPE_BOOLEAN))
362 return ((_Bool) ptr->nm_value.nm_boolean);
365 } /* }}} _Bool check_notify_received */
367 static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
369 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
375 received = check_notify_received (n);
377 if (network_config_forward && received)
379 c_complain_once (LOG_ERR, &complain_forwarding,
380 "network plugin: A notification has been received via the network "
381 "forwarding if enabled. Forwarding of notifications is currently "
382 "not supported, because there is not loop-deteciton available. "
383 "Please contact the collectd mailing list if you need this "
387 /* By default, only *send* value lists that were not *received* by the
390 } /* }}} _Bool check_send_notify_okay */
392 static int network_dispatch_values (value_list_t *vl, /* {{{ */
393 const char *username)
398 || (strlen (vl->host) <= 0)
399 || (strlen (vl->plugin) <= 0)
400 || (strlen (vl->type) <= 0))
403 if (!check_receive_okay (vl))
406 char name[6*DATA_MAX_NAME_LEN];
407 FORMAT_VL (name, sizeof (name), vl);
408 name[sizeof (name) - 1] = 0;
409 DEBUG ("network plugin: network_dispatch_values: "
410 "NOT dispatching %s.", name);
412 stats_values_not_dispatched++;
416 assert (vl->meta == NULL);
418 vl->meta = meta_data_create ();
419 if (vl->meta == NULL)
421 ERROR ("network plugin: meta_data_create failed.");
425 status = meta_data_add_boolean (vl->meta, "network:received", 1);
428 ERROR ("network plugin: meta_data_add_boolean failed.");
429 meta_data_destroy (vl->meta);
434 if (username != NULL)
436 status = meta_data_add_string (vl->meta, "network:username", username);
439 ERROR ("network plugin: meta_data_add_string failed.");
440 meta_data_destroy (vl->meta);
446 plugin_dispatch_values_secure (vl);
447 stats_values_dispatched++;
449 meta_data_destroy (vl->meta);
453 } /* }}} int network_dispatch_values */
455 static int network_dispatch_notification (notification_t *n) /* {{{ */
459 assert (n->meta == NULL);
461 status = plugin_notification_meta_add_boolean (n, "network:received", 1);
464 ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
465 plugin_notification_meta_free (n->meta);
470 status = plugin_dispatch_notification (n);
472 plugin_notification_meta_free (n->meta);
476 } /* }}} int network_dispatch_notification */
479 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
480 const void *iv, size_t iv_size, const char *username)
483 gcry_cipher_hd_t *cyper_ptr;
484 unsigned char password_hash[32];
486 if (se->type == SOCKENT_TYPE_CLIENT)
488 cyper_ptr = &se->data.client.cypher;
489 memcpy (password_hash, se->data.client.password_hash,
490 sizeof (password_hash));
496 cyper_ptr = &se->data.server.cypher;
498 if (username == NULL)
501 secret = fbh_get (se->data.server.userdb, username);
505 gcry_md_hash_buffer (GCRY_MD_SHA256,
507 secret, strlen (secret));
512 if (*cyper_ptr == NULL)
514 err = gcry_cipher_open (cyper_ptr,
515 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
518 ERROR ("network plugin: gcry_cipher_open returned: %s",
519 gcry_strerror (err));
526 gcry_cipher_reset (*cyper_ptr);
528 assert (*cyper_ptr != NULL);
530 err = gcry_cipher_setkey (*cyper_ptr,
531 password_hash, sizeof (password_hash));
534 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
535 gcry_strerror (err));
536 gcry_cipher_close (*cyper_ptr);
541 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
544 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
545 gcry_strerror (err));
546 gcry_cipher_close (*cyper_ptr);
552 } /* }}} int network_get_aes256_cypher */
553 #endif /* HAVE_LIBGCRYPT */
555 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
556 const data_set_t *ds, const value_list_t *vl)
562 part_header_t pkg_ph;
563 uint16_t pkg_num_values;
564 uint8_t *pkg_values_types;
570 num_values = vl->values_len;
571 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
572 + (num_values * sizeof (uint8_t))
573 + (num_values * sizeof (value_t));
575 if (*ret_buffer_len < packet_len)
578 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
579 if (pkg_values_types == NULL)
581 ERROR ("network plugin: write_part_values: malloc failed.");
585 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
586 if (pkg_values == NULL)
588 free (pkg_values_types);
589 ERROR ("network plugin: write_part_values: malloc failed.");
593 pkg_ph.type = htons (TYPE_VALUES);
594 pkg_ph.length = htons (packet_len);
596 pkg_num_values = htons ((uint16_t) vl->values_len);
598 for (i = 0; i < num_values; i++)
600 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
601 switch (ds->ds[i].type)
603 case DS_TYPE_COUNTER:
604 pkg_values[i].counter = htonll (vl->values[i].counter);
608 pkg_values[i].gauge = htond (vl->values[i].gauge);
612 pkg_values[i].derive = htonll (vl->values[i].derive);
615 case DS_TYPE_ABSOLUTE:
616 pkg_values[i].absolute = htonll (vl->values[i].absolute);
620 free (pkg_values_types);
622 ERROR ("network plugin: write_part_values: "
623 "Unknown data source type: %i",
626 } /* switch (ds->ds[i].type) */
627 } /* for (num_values) */
630 * Use `memcpy' to write everything to the buffer, because the pointer
631 * may be unaligned and some architectures, such as SPARC, can't handle
634 packet_ptr = *ret_buffer;
636 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
637 offset += sizeof (pkg_ph);
638 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
639 offset += sizeof (pkg_num_values);
640 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
641 offset += num_values * sizeof (uint8_t);
642 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
643 offset += num_values * sizeof (value_t);
645 assert (offset == packet_len);
647 *ret_buffer = packet_ptr + packet_len;
648 *ret_buffer_len -= packet_len;
650 free (pkg_values_types);
654 } /* int write_part_values */
656 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
657 int type, uint64_t value)
662 part_header_t pkg_head;
667 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
669 if (*ret_buffer_len < packet_len)
672 pkg_head.type = htons (type);
673 pkg_head.length = htons (packet_len);
674 pkg_value = htonll (value);
676 packet_ptr = *ret_buffer;
678 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
679 offset += sizeof (pkg_head);
680 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
681 offset += sizeof (pkg_value);
683 assert (offset == packet_len);
685 *ret_buffer = packet_ptr + packet_len;
686 *ret_buffer_len -= packet_len;
689 } /* int write_part_number */
691 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
692 int type, const char *str, int str_len)
702 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
703 if (*ret_buffer_len < buffer_len)
706 pkg_type = htons (type);
707 pkg_length = htons (buffer_len);
709 buffer = *ret_buffer;
711 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
712 offset += sizeof (pkg_type);
713 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
714 offset += sizeof (pkg_length);
715 memcpy (buffer + offset, str, str_len);
717 memset (buffer + offset, '\0', 1);
720 assert (offset == buffer_len);
722 *ret_buffer = buffer + buffer_len;
723 *ret_buffer_len -= buffer_len;
726 } /* int write_part_string */
728 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
729 value_t **ret_values, int *ret_num_values)
731 char *buffer = *ret_buffer;
732 size_t buffer_len = *ret_buffer_len;
747 NOTICE ("network plugin: packet is too short: "
748 "buffer_len = %zu", buffer_len);
752 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
753 buffer += sizeof (tmp16);
754 pkg_type = ntohs (tmp16);
756 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
757 buffer += sizeof (tmp16);
758 pkg_length = ntohs (tmp16);
760 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
761 buffer += sizeof (tmp16);
762 pkg_numval = ntohs (tmp16);
764 assert (pkg_type == TYPE_VALUES);
766 exp_size = 3 * sizeof (uint16_t)
767 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
768 if (buffer_len < exp_size)
770 WARNING ("network plugin: parse_part_values: "
772 "Chunk of size %zu expected, "
773 "but buffer has only %zu bytes left.",
774 exp_size, buffer_len);
778 if (pkg_length != exp_size)
780 WARNING ("network plugin: parse_part_values: "
781 "Length and number of values "
782 "in the packet don't match.");
786 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
787 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
788 if ((pkg_types == NULL) || (pkg_values == NULL))
792 ERROR ("network plugin: parse_part_values: malloc failed.");
796 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
797 buffer += pkg_numval * sizeof (uint8_t);
798 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
799 buffer += pkg_numval * sizeof (value_t);
801 for (i = 0; i < pkg_numval; i++)
803 switch (pkg_types[i])
805 case DS_TYPE_COUNTER:
806 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
810 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
814 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
817 case DS_TYPE_ABSOLUTE:
818 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
822 NOTICE ("network plugin: parse_part_values: "
823 "Don't know how to handle data source type %"PRIu8,
828 } /* switch (pkg_types[i]) */
831 *ret_buffer = buffer;
832 *ret_buffer_len = buffer_len - pkg_length;
833 *ret_num_values = pkg_numval;
834 *ret_values = pkg_values;
839 } /* int parse_part_values */
841 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
844 char *buffer = *ret_buffer;
845 size_t buffer_len = *ret_buffer_len;
849 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
853 if (buffer_len < exp_size)
855 WARNING ("network plugin: parse_part_number: "
857 "Chunk of size %zu expected, "
858 "but buffer has only %zu bytes left.",
859 exp_size, buffer_len);
863 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
864 buffer += sizeof (tmp16);
865 /* pkg_type = ntohs (tmp16); */
867 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
868 buffer += sizeof (tmp16);
869 pkg_length = ntohs (tmp16);
871 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
872 buffer += sizeof (tmp64);
873 *value = ntohll (tmp64);
875 *ret_buffer = buffer;
876 *ret_buffer_len = buffer_len - pkg_length;
879 } /* int parse_part_number */
881 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
882 char *output, int output_len)
884 char *buffer = *ret_buffer;
885 size_t buffer_len = *ret_buffer_len;
888 size_t header_size = 2 * sizeof (uint16_t);
892 if (buffer_len < header_size)
894 WARNING ("network plugin: parse_part_string: "
896 "Chunk of at least size %zu expected, "
897 "but buffer has only %zu bytes left.",
898 header_size, buffer_len);
902 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
903 buffer += sizeof (tmp16);
904 /* pkg_type = ntohs (tmp16); */
906 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
907 buffer += sizeof (tmp16);
908 pkg_length = ntohs (tmp16);
910 /* Check that packet fits in the input buffer */
911 if (pkg_length > buffer_len)
913 WARNING ("network plugin: parse_part_string: "
915 "Chunk of size %"PRIu16" received, "
916 "but buffer has only %zu bytes left.",
917 pkg_length, buffer_len);
921 /* Check that pkg_length is in the valid range */
922 if (pkg_length <= header_size)
924 WARNING ("network plugin: parse_part_string: "
926 "Header claims this packet is only %hu "
927 "bytes long.", pkg_length);
931 /* Check that the package data fits into the output buffer.
932 * The previous if-statement ensures that:
933 * `pkg_length > header_size' */
935 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
937 WARNING ("network plugin: parse_part_string: "
938 "Output buffer too small.");
942 /* All sanity checks successfull, let's copy the data over */
943 output_len = pkg_length - header_size;
944 memcpy ((void *) output, (void *) buffer, output_len);
945 buffer += output_len;
947 /* For some very weird reason '\0' doesn't do the trick on SPARC in
949 if (output[output_len - 1] != 0)
951 WARNING ("network plugin: parse_part_string: "
952 "Received string does not end "
953 "with a NULL-byte.");
957 *ret_buffer = buffer;
958 *ret_buffer_len = buffer_len - pkg_length;
961 } /* int parse_part_string */
963 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
964 * parse_packet and vice versa. */
965 #define PP_SIGNED 0x01
966 #define PP_ENCRYPTED 0x02
967 static int parse_packet (sockent_t *se,
968 void *buffer, size_t buffer_size, int flags,
969 const char *username);
971 #define BUFFER_READ(p,s) do { \
972 memcpy ((p), buffer + buffer_offset, (s)); \
973 buffer_offset += (s); \
977 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
978 void **ret_buffer, size_t *ret_buffer_len, int flags)
980 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
984 size_t buffer_offset;
989 part_signature_sha256_t pss;
990 uint16_t pss_head_length;
991 char hash[sizeof (pss.hash)];
995 unsigned char *hash_ptr;
997 buffer = *ret_buffer;
998 buffer_len = *ret_buffer_len;
1001 if (se->data.server.userdb == NULL)
1003 c_complain (LOG_NOTICE, &complain_no_users,
1004 "network plugin: Received signed network packet but can't verify it "
1005 "because no user DB has been configured. Will accept it.");
1009 /* Check if the buffer has enough data for this structure. */
1010 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1013 /* Read type and length header */
1014 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1015 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1016 pss_head_length = ntohs (pss.head.length);
1018 /* Check if the `pss_head_length' is within bounds. */
1019 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1020 || (pss_head_length > buffer_len))
1022 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1026 /* Copy the hash. */
1027 BUFFER_READ (pss.hash, sizeof (pss.hash));
1029 /* Calculate username length (without null byte) and allocate memory */
1030 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1031 pss.username = malloc (username_len + 1);
1032 if (pss.username == NULL)
1035 /* Read the username */
1036 BUFFER_READ (pss.username, username_len);
1037 pss.username[username_len] = 0;
1039 assert (buffer_offset == pss_head_length);
1041 /* Query the password */
1042 secret = fbh_get (se->data.server.userdb, pss.username);
1045 ERROR ("network plugin: Unknown user: %s", pss.username);
1046 sfree (pss.username);
1050 /* Create a hash device and check the HMAC */
1052 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1055 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1056 gcry_strerror (err));
1058 sfree (pss.username);
1062 err = gcry_md_setkey (hd, secret, strlen (secret));
1065 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1068 sfree (pss.username);
1073 buffer + PART_SIGNATURE_SHA256_SIZE,
1074 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1075 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1076 if (hash_ptr == NULL)
1078 ERROR ("network plugin: gcry_md_read failed.");
1081 sfree (pss.username);
1084 memcpy (hash, hash_ptr, sizeof (hash));
1090 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1092 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1097 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1098 flags | PP_SIGNED, pss.username);
1102 sfree (pss.username);
1104 *ret_buffer = buffer + buffer_len;
1105 *ret_buffer_len = 0;
1108 } /* }}} int parse_part_sign_sha256 */
1109 /* #endif HAVE_LIBGCRYPT */
1111 #else /* if !HAVE_LIBGCRYPT */
1112 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1113 void **ret_buffer, size_t *ret_buffer_size, int flags)
1115 static int warning_has_been_printed = 0;
1119 size_t buffer_offset;
1122 part_signature_sha256_t pss;
1124 buffer = *ret_buffer;
1125 buffer_size = *ret_buffer_size;
1128 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1131 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1132 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1133 part_len = ntohs (pss.head.length);
1135 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1136 || (part_len > buffer_size))
1139 if (warning_has_been_printed == 0)
1141 WARNING ("network plugin: Received signed packet, but the network "
1142 "plugin was not linked with libgcrypt, so I cannot "
1143 "verify the signature. The packet will be accepted.");
1144 warning_has_been_printed = 1;
1147 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1148 /* username = */ NULL);
1150 *ret_buffer = buffer + buffer_size;
1151 *ret_buffer_size = 0;
1154 } /* }}} int parse_part_sign_sha256 */
1155 #endif /* !HAVE_LIBGCRYPT */
1158 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1159 void **ret_buffer, size_t *ret_buffer_len,
1162 char *buffer = *ret_buffer;
1163 size_t buffer_len = *ret_buffer_len;
1166 size_t buffer_offset;
1167 uint16_t username_len;
1168 part_encryption_aes256_t pea;
1169 unsigned char hash[sizeof (pea.hash)];
1171 gcry_cipher_hd_t cypher;
1174 /* Make sure at least the header if available. */
1175 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1177 NOTICE ("network plugin: parse_part_encr_aes256: "
1178 "Discarding short packet.");
1184 /* Copy the unencrypted information into `pea'. */
1185 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1186 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1188 /* Check the `part size'. */
1189 part_size = ntohs (pea.head.length);
1190 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1191 || (part_size > buffer_len))
1193 NOTICE ("network plugin: parse_part_encr_aes256: "
1194 "Discarding part with invalid size.");
1198 /* Read the username */
1199 BUFFER_READ (&username_len, sizeof (username_len));
1200 username_len = ntohs (username_len);
1202 if ((username_len <= 0)
1203 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1205 NOTICE ("network plugin: parse_part_encr_aes256: "
1206 "Discarding part with invalid username length.");
1210 assert (username_len > 0);
1211 pea.username = malloc (username_len + 1);
1212 if (pea.username == NULL)
1214 BUFFER_READ (pea.username, username_len);
1215 pea.username[username_len] = 0;
1217 /* Last but not least, the initialization vector */
1218 BUFFER_READ (pea.iv, sizeof (pea.iv));
1220 /* Make sure we are at the right position */
1221 assert (buffer_offset == (username_len +
1222 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1224 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1228 sfree (pea.username);
1232 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1233 assert (payload_len > 0);
1235 /* Decrypt the packet in-place */
1236 err = gcry_cipher_decrypt (cypher,
1237 buffer + buffer_offset,
1238 part_size - buffer_offset,
1239 /* in = */ NULL, /* in len = */ 0);
1242 sfree (pea.username);
1243 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1244 gcry_strerror (err));
1249 BUFFER_READ (pea.hash, sizeof (pea.hash));
1251 /* Make sure we're at the right position - again */
1252 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1253 assert (buffer_offset == (part_size - payload_len));
1255 /* Check hash sum */
1256 memset (hash, 0, sizeof (hash));
1257 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1258 buffer + buffer_offset, payload_len);
1259 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1261 sfree (pea.username);
1262 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1266 parse_packet (se, buffer + buffer_offset, payload_len,
1267 flags | PP_ENCRYPTED, pea.username);
1269 /* XXX: Free pea.username?!? */
1271 /* Update return values */
1272 *ret_buffer = buffer + part_size;
1273 *ret_buffer_len = buffer_len - part_size;
1275 sfree (pea.username);
1278 } /* }}} int parse_part_encr_aes256 */
1279 /* #endif HAVE_LIBGCRYPT */
1281 #else /* if !HAVE_LIBGCRYPT */
1282 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1283 void **ret_buffer, size_t *ret_buffer_size, int flags)
1285 static int warning_has_been_printed = 0;
1289 size_t buffer_offset;
1294 buffer = *ret_buffer;
1295 buffer_size = *ret_buffer_size;
1298 /* parse_packet assures this minimum size. */
1299 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1301 BUFFER_READ (&ph.type, sizeof (ph.type));
1302 BUFFER_READ (&ph.length, sizeof (ph.length));
1303 ph_length = ntohs (ph.length);
1305 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1306 || (ph_length > buffer_size))
1308 ERROR ("network plugin: AES-256 encrypted part "
1309 "with invalid length received.");
1313 if (warning_has_been_printed == 0)
1315 WARNING ("network plugin: Received encrypted packet, but the network "
1316 "plugin was not linked with libgcrypt, so I cannot "
1317 "decrypt it. The part will be discarded.");
1318 warning_has_been_printed = 1;
1321 *ret_buffer += ph_length;
1322 *ret_buffer_size -= ph_length;
1325 } /* }}} int parse_part_encr_aes256 */
1326 #endif /* !HAVE_LIBGCRYPT */
1330 static int parse_packet (sockent_t *se, /* {{{ */
1331 void *buffer, size_t buffer_size, int flags,
1332 const char *username)
1336 value_list_t vl = VALUE_LIST_INIT;
1340 int packet_was_signed = (flags & PP_SIGNED);
1341 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1342 int printed_ignore_warning = 0;
1343 #endif /* HAVE_LIBGCRYPT */
1346 memset (&vl, '\0', sizeof (vl));
1347 memset (&n, '\0', sizeof (n));
1350 while ((status == 0) && (0 < buffer_size)
1351 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1353 uint16_t pkg_length;
1356 memcpy ((void *) &pkg_type,
1359 memcpy ((void *) &pkg_length,
1360 (void *) (buffer + sizeof (pkg_type)),
1361 sizeof (pkg_length));
1363 pkg_length = ntohs (pkg_length);
1364 pkg_type = ntohs (pkg_type);
1366 if (pkg_length > buffer_size)
1368 /* Ensure that this loop terminates eventually */
1369 if (pkg_length < (2 * sizeof (uint16_t)))
1372 if (pkg_type == TYPE_ENCR_AES256)
1374 status = parse_part_encr_aes256 (se,
1375 &buffer, &buffer_size, flags);
1378 ERROR ("network plugin: Decrypting AES256 "
1380 "with status %i.", status);
1385 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1386 && (packet_was_encrypted == 0))
1388 if (printed_ignore_warning == 0)
1390 INFO ("network plugin: Unencrypted packet or "
1391 "part has been ignored.");
1392 printed_ignore_warning = 1;
1394 buffer = ((char *) buffer) + pkg_length;
1397 #endif /* HAVE_LIBGCRYPT */
1398 else if (pkg_type == TYPE_SIGN_SHA256)
1400 status = parse_part_sign_sha256 (se,
1401 &buffer, &buffer_size, flags);
1404 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1406 "with status %i.", status);
1411 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1412 && (packet_was_encrypted == 0)
1413 && (packet_was_signed == 0))
1415 if (printed_ignore_warning == 0)
1417 INFO ("network plugin: Unsigned packet or "
1418 "part has been ignored.");
1419 printed_ignore_warning = 1;
1421 buffer = ((char *) buffer) + pkg_length;
1424 #endif /* HAVE_LIBGCRYPT */
1425 else if (pkg_type == TYPE_VALUES)
1427 status = parse_part_values (&buffer, &buffer_size,
1428 &vl.values, &vl.values_len);
1432 network_dispatch_values (&vl, username);
1436 else if (pkg_type == TYPE_TIME)
1439 status = parse_part_number (&buffer, &buffer_size,
1443 vl.time = TIME_T_TO_CDTIME_T (tmp);
1444 n.time = TIME_T_TO_CDTIME_T (tmp);
1447 else if (pkg_type == TYPE_TIME_HR)
1450 status = parse_part_number (&buffer, &buffer_size,
1454 vl.time = (cdtime_t) tmp;
1455 n.time = (cdtime_t) tmp;
1458 else if (pkg_type == TYPE_INTERVAL)
1461 status = parse_part_number (&buffer, &buffer_size,
1464 vl.interval = TIME_T_TO_CDTIME_T (tmp);
1466 else if (pkg_type == TYPE_INTERVAL_HR)
1469 status = parse_part_number (&buffer, &buffer_size,
1472 vl.interval = (cdtime_t) tmp;
1474 else if (pkg_type == TYPE_HOST)
1476 status = parse_part_string (&buffer, &buffer_size,
1477 vl.host, sizeof (vl.host));
1479 sstrncpy (n.host, vl.host, sizeof (n.host));
1481 else if (pkg_type == TYPE_PLUGIN)
1483 status = parse_part_string (&buffer, &buffer_size,
1484 vl.plugin, sizeof (vl.plugin));
1486 sstrncpy (n.plugin, vl.plugin,
1489 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1491 status = parse_part_string (&buffer, &buffer_size,
1493 sizeof (vl.plugin_instance));
1495 sstrncpy (n.plugin_instance,
1497 sizeof (n.plugin_instance));
1499 else if (pkg_type == TYPE_TYPE)
1501 status = parse_part_string (&buffer, &buffer_size,
1502 vl.type, sizeof (vl.type));
1504 sstrncpy (n.type, vl.type, sizeof (n.type));
1506 else if (pkg_type == TYPE_TYPE_INSTANCE)
1508 status = parse_part_string (&buffer, &buffer_size,
1510 sizeof (vl.type_instance));
1512 sstrncpy (n.type_instance, vl.type_instance,
1513 sizeof (n.type_instance));
1515 else if (pkg_type == TYPE_MESSAGE)
1517 status = parse_part_string (&buffer, &buffer_size,
1518 n.message, sizeof (n.message));
1524 else if ((n.severity != NOTIF_FAILURE)
1525 && (n.severity != NOTIF_WARNING)
1526 && (n.severity != NOTIF_OKAY))
1528 INFO ("network plugin: "
1529 "Ignoring notification with "
1530 "unknown severity %i.",
1533 else if (n.time <= 0)
1535 INFO ("network plugin: "
1536 "Ignoring notification with "
1539 else if (strlen (n.message) <= 0)
1541 INFO ("network plugin: "
1542 "Ignoring notification with "
1543 "an empty message.");
1547 network_dispatch_notification (&n);
1550 else if (pkg_type == TYPE_SEVERITY)
1553 status = parse_part_number (&buffer, &buffer_size,
1556 n.severity = (int) tmp;
1560 DEBUG ("network plugin: parse_packet: Unknown part"
1561 " type: 0x%04hx", pkg_type);
1562 buffer = ((char *) buffer) + pkg_length;
1564 } /* while (buffer_size > sizeof (part_header_t)) */
1566 if (status == 0 && buffer_size > 0)
1567 WARNING ("network plugin: parse_packet: Received truncated "
1568 "packet, try increasing `MaxPacketSize'");
1571 } /* }}} int parse_packet */
1573 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1582 sfree (sec->username);
1583 sfree (sec->password);
1584 if (sec->cypher != NULL)
1585 gcry_cipher_close (sec->cypher);
1587 } /* }}} void free_sockent_client */
1589 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1593 for (i = 0; i < ses->fd_num; i++)
1595 if (ses->fd[i] >= 0)
1604 sfree (ses->auth_file);
1605 fbh_destroy (ses->userdb);
1606 if (ses->cypher != NULL)
1607 gcry_cipher_close (ses->cypher);
1609 } /* }}} void free_sockent_server */
1611 static void sockent_destroy (sockent_t *se) /* {{{ */
1615 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1622 sfree (se->service);
1624 if (se->type == SOCKENT_TYPE_CLIENT)
1625 free_sockent_client (&se->data.client);
1627 free_sockent_server (&se->data.server);
1632 } /* }}} void sockent_destroy */
1635 * int network_set_ttl
1637 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1638 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1640 * The `struct addrinfo' is used to destinguish between unicast and multicast
1643 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1645 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1646 network_config_ttl);
1648 assert (se->type == SOCKENT_TYPE_CLIENT);
1650 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1653 if (ai->ai_family == AF_INET)
1655 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1658 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1659 optname = IP_MULTICAST_TTL;
1663 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1664 &network_config_ttl,
1665 sizeof (network_config_ttl)) != 0)
1668 ERROR ("setsockopt: %s",
1669 sstrerror (errno, errbuf, sizeof (errbuf)));
1673 else if (ai->ai_family == AF_INET6)
1675 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1676 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1679 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1680 optname = IPV6_MULTICAST_HOPS;
1682 optname = IPV6_UNICAST_HOPS;
1684 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1685 &network_config_ttl,
1686 sizeof (network_config_ttl)) != 0)
1689 ERROR ("setsockopt: %s",
1690 sstrerror (errno, errbuf,
1697 } /* int network_set_ttl */
1699 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1701 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1704 assert (se->type == SOCKENT_TYPE_CLIENT);
1706 if (ai->ai_family == AF_INET)
1708 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1710 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1712 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1713 /* If possible, use the "ip_mreqn" structure which has
1714 * an "interface index" member. Using the interface
1715 * index is preferred here, because of its similarity
1716 * to the way IPv6 handles this. Unfortunately, it
1717 * appears not to be portable. */
1718 struct ip_mreqn mreq;
1720 memset (&mreq, 0, sizeof (mreq));
1721 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1722 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1723 mreq.imr_ifindex = se->interface;
1725 struct ip_mreq mreq;
1727 memset (&mreq, 0, sizeof (mreq));
1728 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1729 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1732 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1733 &mreq, sizeof (mreq)) != 0)
1736 ERROR ("setsockopt: %s",
1737 sstrerror (errno, errbuf, sizeof (errbuf)));
1744 else if (ai->ai_family == AF_INET6)
1746 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1748 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1750 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1752 sizeof (se->interface)) != 0)
1755 ERROR ("setsockopt: %s",
1756 sstrerror (errno, errbuf,
1765 /* else: Not a multicast interface. */
1766 if (se->interface != 0)
1768 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1769 char interface_name[IFNAMSIZ];
1771 if (if_indextoname (se->interface, interface_name) == NULL)
1774 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1776 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1778 sizeof(interface_name)) == -1 )
1781 ERROR ("setsockopt: %s",
1782 sstrerror (errno, errbuf, sizeof (errbuf)));
1785 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1788 WARNING ("network plugin: Cannot set the interface on a unicast "
1790 # if !defined(SO_BINDTODEVICE)
1791 "the \"SO_BINDTODEVICE\" socket option "
1793 "the \"if_indextoname\" function "
1795 "is not available on your system.");
1801 } /* }}} network_set_interface */
1803 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1808 /* allow multiple sockets to use the same PORT number */
1809 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1810 &yes, sizeof(yes)) == -1) {
1812 ERROR ("setsockopt: %s",
1813 sstrerror (errno, errbuf, sizeof (errbuf)));
1817 DEBUG ("fd = %i; calling `bind'", fd);
1819 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1823 sstrerror (errno, errbuf, sizeof (errbuf)));
1827 if (ai->ai_family == AF_INET)
1829 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1830 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1832 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1833 struct ip_mreqn mreq;
1835 struct ip_mreq mreq;
1838 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1840 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1841 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1842 /* Set the interface using the interface index if
1843 * possible (available). Unfortunately, the struct
1844 * ip_mreqn is not portable. */
1845 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1846 mreq.imr_ifindex = interface_idx;
1848 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1851 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1852 &loop, sizeof (loop)) == -1)
1855 ERROR ("setsockopt: %s",
1856 sstrerror (errno, errbuf,
1861 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1862 &mreq, sizeof (mreq)) == -1)
1865 ERROR ("setsockopt: %s",
1866 sstrerror (errno, errbuf,
1874 else if (ai->ai_family == AF_INET6)
1876 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1877 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1878 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1880 struct ipv6_mreq mreq;
1882 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1884 memcpy (&mreq.ipv6mr_multiaddr,
1886 sizeof (addr->sin6_addr));
1888 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1889 * ipv6mr_interface may be set to zeroes to
1890 * choose the default multicast interface or to
1891 * the index of a particular multicast-capable
1892 * interface if the host is multihomed.
1893 * Membership is associ-associated with a
1894 * single interface; programs running on
1895 * multihomed hosts may need to join the same
1896 * group on more than one interface.*/
1897 mreq.ipv6mr_interface = interface_idx;
1899 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1900 &loop, sizeof (loop)) == -1)
1903 ERROR ("setsockopt: %s",
1904 sstrerror (errno, errbuf,
1909 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1910 &mreq, sizeof (mreq)) == -1)
1913 ERROR ("setsockopt: %s",
1914 sstrerror (errno, errbuf,
1923 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1924 /* if a specific interface was set, bind the socket to it. But to avoid
1925 * possible problems with multicast routing, only do that for non-multicast
1927 if (interface_idx != 0)
1929 char interface_name[IFNAMSIZ];
1931 if (if_indextoname (interface_idx, interface_name) == NULL)
1934 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1936 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1938 sizeof(interface_name)) == -1 )
1941 ERROR ("setsockopt: %s",
1942 sstrerror (errno, errbuf, sizeof (errbuf)));
1946 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1949 } /* int network_bind_socket */
1951 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1952 * or `SOCKENT_TYPE_SERVER' */
1953 static int sockent_init (sockent_t *se, int type) /* {{{ */
1958 memset (se, 0, sizeof (*se));
1960 se->type = SOCKENT_TYPE_CLIENT;
1966 if (type == SOCKENT_TYPE_SERVER)
1968 se->type = SOCKENT_TYPE_SERVER;
1969 se->data.server.fd = NULL;
1971 se->data.server.security_level = SECURITY_LEVEL_NONE;
1972 se->data.server.auth_file = NULL;
1973 se->data.server.userdb = NULL;
1974 se->data.server.cypher = NULL;
1979 se->data.client.fd = -1;
1980 se->data.client.addr = NULL;
1982 se->data.client.security_level = SECURITY_LEVEL_NONE;
1983 se->data.client.username = NULL;
1984 se->data.client.password = NULL;
1985 se->data.client.cypher = NULL;
1990 } /* }}} int sockent_init */
1992 /* Open the file descriptors for a initialized sockent structure. */
1993 static int sockent_open (sockent_t *se) /* {{{ */
1995 struct addrinfo ai_hints;
1996 struct addrinfo *ai_list, *ai_ptr;
2000 const char *service;
2005 /* Set up the security structures. */
2006 #if HAVE_LIBGCRYPT /* {{{ */
2007 if (se->type == SOCKENT_TYPE_CLIENT)
2009 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
2011 if ((se->data.client.username == NULL)
2012 || (se->data.client.password == NULL))
2014 ERROR ("network plugin: Client socket with "
2015 "security requested, but no "
2016 "credentials are configured.");
2019 gcry_md_hash_buffer (GCRY_MD_SHA256,
2020 se->data.client.password_hash,
2021 se->data.client.password,
2022 strlen (se->data.client.password));
2025 else /* (se->type == SOCKENT_TYPE_SERVER) */
2027 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2029 if (se->data.server.auth_file == NULL)
2031 ERROR ("network plugin: Server socket with "
2032 "security requested, but no "
2033 "password file is configured.");
2037 if (se->data.server.auth_file != NULL)
2039 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2040 if (se->data.server.userdb == NULL)
2042 ERROR ("network plugin: Reading password file "
2044 se->data.server.auth_file);
2045 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2050 #endif /* }}} HAVE_LIBGCRYPT */
2053 service = se->service;
2055 if (service == NULL)
2056 service = NET_DEFAULT_PORT;
2058 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
2061 memset (&ai_hints, 0, sizeof (ai_hints));
2062 ai_hints.ai_flags = 0;
2064 ai_hints.ai_flags |= AI_PASSIVE;
2066 #ifdef AI_ADDRCONFIG
2067 ai_hints.ai_flags |= AI_ADDRCONFIG;
2069 ai_hints.ai_family = AF_UNSPEC;
2070 ai_hints.ai_socktype = SOCK_DGRAM;
2071 ai_hints.ai_protocol = IPPROTO_UDP;
2073 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2076 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2077 (se->node == NULL) ? "(null)" : se->node,
2078 (se->service == NULL) ? "(null)" : se->service,
2079 gai_strerror (ai_return));
2083 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2087 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2091 tmp = realloc (se->data.server.fd,
2092 sizeof (*tmp) * (se->data.server.fd_num + 1));
2095 ERROR ("network plugin: realloc failed.");
2098 se->data.server.fd = tmp;
2099 tmp = se->data.server.fd + se->data.server.fd_num;
2101 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2102 ai_ptr->ai_protocol);
2106 ERROR ("network plugin: socket(2) failed: %s",
2107 sstrerror (errno, errbuf,
2112 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2120 se->data.server.fd_num++;
2122 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2123 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2125 se->data.client.fd = socket (ai_ptr->ai_family,
2126 ai_ptr->ai_socktype,
2127 ai_ptr->ai_protocol);
2128 if (se->data.client.fd < 0)
2131 ERROR ("network plugin: socket(2) failed: %s",
2132 sstrerror (errno, errbuf,
2137 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2138 if (se->data.client.addr == NULL)
2140 ERROR ("network plugin: malloc failed.");
2141 close (se->data.client.fd);
2142 se->data.client.fd = -1;
2146 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2147 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2148 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2149 se->data.client.addrlen = ai_ptr->ai_addrlen;
2151 network_set_ttl (se, ai_ptr);
2152 network_set_interface (se, ai_ptr);
2154 /* We don't open more than one write-socket per
2155 * node/service pair.. */
2157 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2158 } /* for (ai_list) */
2160 freeaddrinfo (ai_list);
2162 /* Check if all went well. */
2163 if (se->type == SOCKENT_TYPE_SERVER)
2165 if (se->data.server.fd_num <= 0)
2168 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2170 if (se->data.client.fd < 0)
2175 } /* }}} int sockent_open */
2177 /* Add a sockent to the global list of sockets */
2178 static int sockent_add (sockent_t *se) /* {{{ */
2180 sockent_t *last_ptr;
2185 if (se->type == SOCKENT_TYPE_SERVER)
2190 tmp = realloc (listen_sockets_pollfd,
2191 sizeof (*tmp) * (listen_sockets_num
2192 + se->data.server.fd_num));
2195 ERROR ("network plugin: realloc failed.");
2198 listen_sockets_pollfd = tmp;
2199 tmp = listen_sockets_pollfd + listen_sockets_num;
2201 for (i = 0; i < se->data.server.fd_num; i++)
2203 memset (tmp + i, 0, sizeof (*tmp));
2204 tmp[i].fd = se->data.server.fd[i];
2205 tmp[i].events = POLLIN | POLLPRI;
2209 listen_sockets_num += se->data.server.fd_num;
2211 if (listen_sockets == NULL)
2213 listen_sockets = se;
2216 last_ptr = listen_sockets;
2218 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2220 if (sending_sockets == NULL)
2222 sending_sockets = se;
2225 last_ptr = sending_sockets;
2228 while (last_ptr->next != NULL)
2229 last_ptr = last_ptr->next;
2230 last_ptr->next = se;
2233 } /* }}} int sockent_add */
2235 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2239 receive_list_entry_t *ent;
2242 /* Lock and wait for more data to come in */
2243 pthread_mutex_lock (&receive_list_lock);
2244 while ((listen_loop == 0)
2245 && (receive_list_head == NULL))
2246 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2248 /* Remove the head entry and unlock */
2249 ent = receive_list_head;
2251 receive_list_head = ent->next;
2252 receive_list_length--;
2253 pthread_mutex_unlock (&receive_list_lock);
2255 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2256 * because we dispatch all missing packets before shutting down. */
2260 /* Look for the correct `sockent_t' */
2261 se = listen_sockets;
2266 for (i = 0; i < se->data.server.fd_num; i++)
2267 if (se->data.server.fd[i] == ent->fd)
2270 if (i < se->data.server.fd_num)
2278 ERROR ("network plugin: Got packet from FD %i, but can't "
2279 "find an appropriate socket entry.",
2286 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2287 /* username = */ NULL);
2293 } /* }}} void *dispatch_thread */
2295 static int network_receive (void) /* {{{ */
2297 char buffer[network_config_packet_size];
2303 receive_list_entry_t *private_list_head;
2304 receive_list_entry_t *private_list_tail;
2305 uint64_t private_list_length;
2307 assert (listen_sockets_num > 0);
2309 private_list_head = NULL;
2310 private_list_tail = NULL;
2311 private_list_length = 0;
2313 while (listen_loop == 0)
2315 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2322 ERROR ("poll failed: %s",
2323 sstrerror (errno, errbuf, sizeof (errbuf)));
2327 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2329 receive_list_entry_t *ent;
2331 if ((listen_sockets_pollfd[i].revents
2332 & (POLLIN | POLLPRI)) == 0)
2336 buffer_len = recv (listen_sockets_pollfd[i].fd,
2337 buffer, sizeof (buffer),
2342 ERROR ("recv failed: %s",
2343 sstrerror (errno, errbuf,
2348 stats_octets_rx += ((uint64_t) buffer_len);
2351 /* TODO: Possible performance enhancement: Do not free
2352 * these entries in the dispatch thread but put them in
2353 * another list, so we don't have to allocate more and
2354 * more of these structures. */
2355 ent = malloc (sizeof (receive_list_entry_t));
2358 ERROR ("network plugin: malloc failed.");
2361 memset (ent, 0, sizeof (receive_list_entry_t));
2362 ent->data = malloc (network_config_packet_size);
2363 if (ent->data == NULL)
2366 ERROR ("network plugin: malloc failed.");
2369 ent->fd = listen_sockets_pollfd[i].fd;
2372 memcpy (ent->data, buffer, buffer_len);
2373 ent->data_len = buffer_len;
2375 if (private_list_head == NULL)
2376 private_list_head = ent;
2378 private_list_tail->next = ent;
2379 private_list_tail = ent;
2380 private_list_length++;
2382 /* Do not block here. Blocking here has led to
2383 * insufficient performance in the past. */
2384 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2386 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2387 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2389 if (receive_list_head == NULL)
2390 receive_list_head = private_list_head;
2392 receive_list_tail->next = private_list_head;
2393 receive_list_tail = private_list_tail;
2394 receive_list_length += private_list_length;
2396 pthread_cond_signal (&receive_list_cond);
2397 pthread_mutex_unlock (&receive_list_lock);
2399 private_list_head = NULL;
2400 private_list_tail = NULL;
2401 private_list_length = 0;
2403 } /* for (listen_sockets_pollfd) */
2404 } /* while (listen_loop == 0) */
2406 /* Make sure everything is dispatched before exiting. */
2407 if (private_list_head != NULL)
2409 pthread_mutex_lock (&receive_list_lock);
2411 if (receive_list_head == NULL)
2412 receive_list_head = private_list_head;
2414 receive_list_tail->next = private_list_head;
2415 receive_list_tail = private_list_tail;
2416 receive_list_length += private_list_length;
2418 private_list_head = NULL;
2419 private_list_tail = NULL;
2420 private_list_length = 0;
2422 pthread_cond_signal (&receive_list_cond);
2423 pthread_mutex_unlock (&receive_list_lock);
2427 } /* }}} int network_receive */
2429 static void *receive_thread (void __attribute__((unused)) *arg)
2431 return (network_receive () ? (void *) 1 : (void *) 0);
2432 } /* void *receive_thread */
2434 static void network_init_buffer (void)
2436 memset (send_buffer, 0, network_config_packet_size);
2437 send_buffer_ptr = send_buffer;
2438 send_buffer_fill = 0;
2440 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2441 } /* int network_init_buffer */
2443 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2444 const char *buffer, size_t buffer_size)
2450 status = sendto (se->data.client.fd, buffer, buffer_size,
2452 (struct sockaddr *) se->data.client.addr,
2453 se->data.client.addrlen);
2459 ERROR ("network plugin: sendto failed: %s",
2460 sstrerror (errno, errbuf,
2467 } /* }}} void networt_send_buffer_plain */
2470 #define BUFFER_ADD(p,s) do { \
2471 memcpy (buffer + buffer_offset, (p), (s)); \
2472 buffer_offset += (s); \
2475 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2476 const char *in_buffer, size_t in_buffer_size)
2478 part_signature_sha256_t ps;
2479 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2480 size_t buffer_offset;
2481 size_t username_len;
2485 unsigned char *hash;
2488 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2491 ERROR ("network plugin: Creating HMAC object failed: %s",
2492 gcry_strerror (err));
2496 err = gcry_md_setkey (hd, se->data.client.password,
2497 strlen (se->data.client.password));
2500 ERROR ("network plugin: gcry_md_setkey failed: %s",
2501 gcry_strerror (err));
2506 username_len = strlen (se->data.client.username);
2507 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2509 ERROR ("network plugin: Username too long: %s",
2510 se->data.client.username);
2514 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2515 se->data.client.username, username_len);
2516 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2517 in_buffer, in_buffer_size);
2519 /* Initialize the `ps' structure. */
2520 memset (&ps, 0, sizeof (ps));
2521 ps.head.type = htons (TYPE_SIGN_SHA256);
2522 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2524 /* Calculate the hash value. */
2525 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2526 username_len + in_buffer_size);
2527 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2530 ERROR ("network plugin: gcry_md_read failed.");
2534 memcpy (ps.hash, hash, sizeof (ps.hash));
2536 /* Add the header */
2539 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2540 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2541 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2543 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2548 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2549 networt_send_buffer_plain (se, buffer, buffer_offset);
2550 } /* }}} void networt_send_buffer_signed */
2552 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2553 const char *in_buffer, size_t in_buffer_size)
2555 part_encryption_aes256_t pea;
2556 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2558 size_t buffer_offset;
2560 size_t username_len;
2562 gcry_cipher_hd_t cypher;
2564 /* Initialize the header fields */
2565 memset (&pea, 0, sizeof (pea));
2566 pea.head.type = htons (TYPE_ENCR_AES256);
2568 pea.username = se->data.client.username;
2570 username_len = strlen (pea.username);
2571 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2573 ERROR ("network plugin: Username too long: %s", pea.username);
2577 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2578 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2579 - sizeof (pea.hash);
2581 assert (buffer_size <= sizeof (buffer));
2582 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2583 "buffer_size = %zu;", buffer_size);
2585 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2586 + username_len + in_buffer_size));
2587 pea.username_length = htons ((uint16_t) username_len);
2589 /* Chose a random initialization vector. */
2590 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2592 /* Create hash of the payload */
2593 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2595 /* Initialize the buffer */
2597 memset (buffer, 0, sizeof (buffer));
2600 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2601 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2602 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2603 BUFFER_ADD (pea.username, username_len);
2604 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2605 assert (buffer_offset == header_size);
2606 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2607 BUFFER_ADD (in_buffer, in_buffer_size);
2609 assert (buffer_offset == buffer_size);
2611 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2612 se->data.client.password);
2616 /* Encrypt the buffer in-place */
2617 err = gcry_cipher_encrypt (cypher,
2618 buffer + header_size,
2619 buffer_size - header_size,
2620 /* in = */ NULL, /* in len = */ 0);
2623 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2624 gcry_strerror (err));
2628 /* Send it out without further modifications */
2629 networt_send_buffer_plain (se, buffer, buffer_size);
2630 } /* }}} void networt_send_buffer_encrypted */
2632 #endif /* HAVE_LIBGCRYPT */
2634 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2638 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2640 for (se = sending_sockets; se != NULL; se = se->next)
2643 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2644 networt_send_buffer_encrypted (se, buffer, buffer_len);
2645 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2646 networt_send_buffer_signed (se, buffer, buffer_len);
2647 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2648 #endif /* HAVE_LIBGCRYPT */
2649 networt_send_buffer_plain (se, buffer, buffer_len);
2650 } /* for (sending_sockets) */
2651 } /* }}} void network_send_buffer */
2653 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2654 value_list_t *vl_def,
2655 const data_set_t *ds, const value_list_t *vl)
2657 char *buffer_orig = buffer;
2659 if (strcmp (vl_def->host, vl->host) != 0)
2661 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2662 vl->host, strlen (vl->host)) != 0)
2664 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2667 if (vl_def->time != vl->time)
2669 if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
2670 (uint64_t) vl->time))
2672 vl_def->time = vl->time;
2675 if (vl_def->interval != vl->interval)
2677 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
2678 (uint64_t) vl->interval))
2680 vl_def->interval = vl->interval;
2683 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2685 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2686 vl->plugin, strlen (vl->plugin)) != 0)
2688 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2691 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2693 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2694 vl->plugin_instance,
2695 strlen (vl->plugin_instance)) != 0)
2697 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2700 if (strcmp (vl_def->type, vl->type) != 0)
2702 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2703 vl->type, strlen (vl->type)) != 0)
2705 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2708 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2710 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2712 strlen (vl->type_instance)) != 0)
2714 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2717 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2720 return (buffer - buffer_orig);
2721 } /* }}} int add_to_buffer */
2723 static void flush_buffer (void)
2725 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2728 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2730 stats_octets_tx += ((uint64_t) send_buffer_fill);
2733 network_init_buffer ();
2736 static int network_write (const data_set_t *ds, const value_list_t *vl,
2737 user_data_t __attribute__((unused)) *user_data)
2741 if (!check_send_okay (vl))
2744 char name[6*DATA_MAX_NAME_LEN];
2745 FORMAT_VL (name, sizeof (name), vl);
2746 name[sizeof (name) - 1] = 0;
2747 DEBUG ("network plugin: network_write: "
2748 "NOT sending %s.", name);
2750 /* Counter is not protected by another lock and may be reached by
2751 * multiple threads */
2752 pthread_mutex_lock (&stats_lock);
2753 stats_values_not_sent++;
2754 pthread_mutex_unlock (&stats_lock);
2758 uc_meta_data_add_unsigned_int (vl,
2759 "network:time_sent", (uint64_t) vl->time);
2761 pthread_mutex_lock (&send_buffer_lock);
2763 status = add_to_buffer (send_buffer_ptr,
2764 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2769 /* status == bytes added to the buffer */
2770 send_buffer_fill += status;
2771 send_buffer_ptr += status;
2773 stats_values_sent++;
2779 status = add_to_buffer (send_buffer_ptr,
2780 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2786 send_buffer_fill += status;
2787 send_buffer_ptr += status;
2789 stats_values_sent++;
2795 ERROR ("network plugin: Unable to append to the "
2796 "buffer for some weird reason");
2798 else if ((network_config_packet_size - send_buffer_fill) < 15)
2803 pthread_mutex_unlock (&send_buffer_lock);
2805 return ((status < 0) ? -1 : 0);
2806 } /* int network_write */
2808 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2811 if ((ci->values_num != 1)
2812 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2813 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2815 ERROR ("network plugin: The `%s' config option needs "
2816 "exactly one boolean argument.", ci->key);
2820 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2822 if (ci->values[0].value.boolean)
2829 char *str = ci->values[0].value.string;
2833 else if (IS_FALSE (str))
2837 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2838 "option as boolean value.",
2845 } /* }}} int network_config_set_boolean */
2847 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2850 if ((ci->values_num != 1)
2851 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2853 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2854 "one numeric argument.");
2858 tmp = (int) ci->values[0].value.number;
2859 if ((tmp > 0) && (tmp <= 255))
2860 network_config_ttl = tmp;
2863 } /* }}} int network_config_set_ttl */
2865 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2868 if ((ci->values_num != 1)
2869 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2871 WARNING ("network plugin: The `Interface' config option needs exactly "
2872 "one string argument.");
2876 if (interface == NULL)
2879 *interface = if_nametoindex (ci->values[0].value.string);
2882 } /* }}} int network_config_set_interface */
2884 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2887 if ((ci->values_num != 1)
2888 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2890 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2891 "one numeric argument.");
2895 tmp = (int) ci->values[0].value.number;
2896 if ((tmp >= 1024) && (tmp <= 65535))
2897 network_config_packet_size = tmp;
2900 } /* }}} int network_config_set_buffer_size */
2903 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2907 if ((ci->values_num != 1)
2908 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2910 WARNING ("network plugin: The `%s' config option needs exactly "
2911 "one string argument.", ci->key);
2915 tmp = strdup (ci->values[0].value.string);
2919 sfree (*ret_string);
2923 } /* }}} int network_config_set_string */
2924 #endif /* HAVE_LIBGCRYPT */
2927 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2931 if ((ci->values_num != 1)
2932 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2934 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2935 "one string argument.");
2939 str = ci->values[0].value.string;
2940 if (strcasecmp ("Encrypt", str) == 0)
2941 *retval = SECURITY_LEVEL_ENCRYPT;
2942 else if (strcasecmp ("Sign", str) == 0)
2943 *retval = SECURITY_LEVEL_SIGN;
2944 else if (strcasecmp ("None", str) == 0)
2945 *retval = SECURITY_LEVEL_NONE;
2948 WARNING ("network plugin: Unknown security level: %s.", str);
2953 } /* }}} int network_config_set_security_level */
2954 #endif /* HAVE_LIBGCRYPT */
2956 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2962 if ((ci->values_num < 1) || (ci->values_num > 2)
2963 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2964 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2966 ERROR ("network plugin: The `%s' config option needs "
2967 "one or two string arguments.", ci->key);
2971 se = malloc (sizeof (*se));
2974 ERROR ("network plugin: malloc failed.");
2977 sockent_init (se, SOCKENT_TYPE_SERVER);
2979 se->node = strdup (ci->values[0].value.string);
2980 if (ci->values_num >= 2)
2981 se->service = strdup (ci->values[1].value.string);
2983 for (i = 0; i < ci->children_num; i++)
2985 oconfig_item_t *child = ci->children + i;
2988 if (strcasecmp ("AuthFile", child->key) == 0)
2989 network_config_set_string (child, &se->data.server.auth_file);
2990 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2991 network_config_set_security_level (child,
2992 &se->data.server.security_level);
2994 #endif /* HAVE_LIBGCRYPT */
2995 if (strcasecmp ("Interface", child->key) == 0)
2996 network_config_set_interface (child,
3000 WARNING ("network plugin: Option `%s' is not allowed here.",
3006 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
3007 && (se->data.server.auth_file == NULL))
3009 ERROR ("network plugin: A security level higher than `none' was "
3010 "requested, but no AuthFile option was given. Cowardly refusing to "
3011 "open this socket!");
3012 sockent_destroy (se);
3015 #endif /* HAVE_LIBGCRYPT */
3017 status = sockent_open (se);
3020 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
3021 sockent_destroy (se);
3025 status = sockent_add (se);
3028 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3029 sockent_destroy (se);
3034 } /* }}} int network_config_add_listen */
3036 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3042 if ((ci->values_num < 1) || (ci->values_num > 2)
3043 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3044 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3046 ERROR ("network plugin: The `%s' config option needs "
3047 "one or two string arguments.", ci->key);
3051 se = malloc (sizeof (*se));
3054 ERROR ("network plugin: malloc failed.");
3057 sockent_init (se, SOCKENT_TYPE_CLIENT);
3059 se->node = strdup (ci->values[0].value.string);
3060 if (ci->values_num >= 2)
3061 se->service = strdup (ci->values[1].value.string);
3063 for (i = 0; i < ci->children_num; i++)
3065 oconfig_item_t *child = ci->children + i;
3068 if (strcasecmp ("Username", child->key) == 0)
3069 network_config_set_string (child, &se->data.client.username);
3070 else if (strcasecmp ("Password", child->key) == 0)
3071 network_config_set_string (child, &se->data.client.password);
3072 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3073 network_config_set_security_level (child,
3074 &se->data.client.security_level);
3076 #endif /* HAVE_LIBGCRYPT */
3077 if (strcasecmp ("Interface", child->key) == 0)
3078 network_config_set_interface (child,
3082 WARNING ("network plugin: Option `%s' is not allowed here.",
3088 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3089 && ((se->data.client.username == NULL)
3090 || (se->data.client.password == NULL)))
3092 ERROR ("network plugin: A security level higher than `none' was "
3093 "requested, but no Username or Password option was given. "
3094 "Cowardly refusing to open this socket!");
3095 sockent_destroy (se);
3098 #endif /* HAVE_LIBGCRYPT */
3100 status = sockent_open (se);
3103 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3104 sockent_destroy (se);
3108 status = sockent_add (se);
3111 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3112 sockent_destroy (se);
3117 } /* }}} int network_config_add_server */
3119 static int network_config (oconfig_item_t *ci) /* {{{ */
3123 for (i = 0; i < ci->children_num; i++)
3125 oconfig_item_t *child = ci->children + i;
3127 if (strcasecmp ("Listen", child->key) == 0)
3128 network_config_add_listen (child);
3129 else if (strcasecmp ("Server", child->key) == 0)
3130 network_config_add_server (child);
3131 else if (strcasecmp ("TimeToLive", child->key) == 0)
3132 network_config_set_ttl (child);
3133 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3134 network_config_set_buffer_size (child);
3135 else if (strcasecmp ("Forward", child->key) == 0)
3136 network_config_set_boolean (child, &network_config_forward);
3137 else if (strcasecmp ("ReportStats", child->key) == 0)
3138 network_config_set_boolean (child, &network_config_stats);
3141 WARNING ("network plugin: Option `%s' is not allowed here.",
3147 } /* }}} int network_config */
3149 static int network_notification (const notification_t *n,
3150 user_data_t __attribute__((unused)) *user_data)
3152 char buffer[network_config_packet_size];
3153 char *buffer_ptr = buffer;
3154 int buffer_free = sizeof (buffer);
3157 if (!check_send_notify_okay (n))
3160 memset (buffer, 0, sizeof (buffer));
3162 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3163 (uint64_t) n->time);
3167 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3168 (uint64_t) n->severity);
3172 if (strlen (n->host) > 0)
3174 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3175 n->host, strlen (n->host));
3180 if (strlen (n->plugin) > 0)
3182 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3183 n->plugin, strlen (n->plugin));
3188 if (strlen (n->plugin_instance) > 0)
3190 status = write_part_string (&buffer_ptr, &buffer_free,
3191 TYPE_PLUGIN_INSTANCE,
3192 n->plugin_instance, strlen (n->plugin_instance));
3197 if (strlen (n->type) > 0)
3199 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3200 n->type, strlen (n->type));
3205 if (strlen (n->type_instance) > 0)
3207 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3208 n->type_instance, strlen (n->type_instance));
3213 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3214 n->message, strlen (n->message));
3218 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3221 } /* int network_notification */
3223 static int network_shutdown (void)
3227 /* Kill the listening thread */
3228 if (receive_thread_running != 0)
3230 INFO ("network plugin: Stopping receive thread.");
3231 pthread_kill (receive_thread_id, SIGTERM);
3232 pthread_join (receive_thread_id, NULL /* no return value */);
3233 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3234 receive_thread_running = 0;
3237 /* Shutdown the dispatching thread */
3238 if (dispatch_thread_running != 0)
3240 INFO ("network plugin: Stopping dispatch thread.");
3241 pthread_mutex_lock (&receive_list_lock);
3242 pthread_cond_broadcast (&receive_list_cond);
3243 pthread_mutex_unlock (&receive_list_lock);
3244 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3245 dispatch_thread_running = 0;
3248 sockent_destroy (listen_sockets);
3250 if (send_buffer_fill > 0)
3253 sfree (send_buffer);
3255 /* TODO: Close `sending_sockets' */
3257 plugin_unregister_config ("network");
3258 plugin_unregister_init ("network");
3259 plugin_unregister_write ("network");
3260 plugin_unregister_shutdown ("network");
3263 } /* int network_shutdown */
3265 static int network_stats_read (void) /* {{{ */
3267 derive_t copy_octets_rx;
3268 derive_t copy_octets_tx;
3269 derive_t copy_packets_rx;
3270 derive_t copy_packets_tx;
3271 derive_t copy_values_dispatched;
3272 derive_t copy_values_not_dispatched;
3273 derive_t copy_values_sent;
3274 derive_t copy_values_not_sent;
3275 derive_t copy_receive_list_length;
3276 value_list_t vl = VALUE_LIST_INIT;
3279 copy_octets_rx = stats_octets_rx;
3280 copy_octets_tx = stats_octets_tx;
3281 copy_packets_rx = stats_packets_rx;
3282 copy_packets_tx = stats_packets_tx;
3283 copy_values_dispatched = stats_values_dispatched;
3284 copy_values_not_dispatched = stats_values_not_dispatched;
3285 copy_values_sent = stats_values_sent;
3286 copy_values_not_sent = stats_values_not_sent;
3287 copy_receive_list_length = receive_list_length;
3289 /* Initialize `vl' */
3293 vl.interval = interval_g;
3294 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3295 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3297 /* Octets received / sent */
3298 vl.values[0].derive = (derive_t) copy_octets_rx;
3299 vl.values[1].derive = (derive_t) copy_octets_tx;
3300 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3301 plugin_dispatch_values_secure (&vl);
3303 /* Packets received / send */
3304 vl.values[0].derive = (derive_t) copy_packets_rx;
3305 vl.values[1].derive = (derive_t) copy_packets_tx;
3306 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3307 plugin_dispatch_values_secure (&vl);
3309 /* Values (not) dispatched and (not) send */
3310 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3313 vl.values[0].derive = (derive_t) copy_values_dispatched;
3314 sstrncpy (vl.type_instance, "dispatch-accepted",
3315 sizeof (vl.type_instance));
3316 plugin_dispatch_values_secure (&vl);
3318 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3319 sstrncpy (vl.type_instance, "dispatch-rejected",
3320 sizeof (vl.type_instance));
3321 plugin_dispatch_values_secure (&vl);
3323 vl.values[0].derive = (derive_t) copy_values_sent;
3324 sstrncpy (vl.type_instance, "send-accepted",
3325 sizeof (vl.type_instance));
3326 plugin_dispatch_values_secure (&vl);
3328 vl.values[0].derive = (derive_t) copy_values_not_sent;
3329 sstrncpy (vl.type_instance, "send-rejected",
3330 sizeof (vl.type_instance));
3331 plugin_dispatch_values_secure (&vl);
3333 /* Receive queue length */
3334 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3335 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3336 vl.type_instance[0] = 0;
3337 plugin_dispatch_values_secure (&vl);
3340 } /* }}} int network_stats_read */
3342 static int network_init (void)
3344 static _Bool have_init = 0;
3346 /* Check if we were already initialized. If so, just return - there's
3347 * nothing more to do (for now, that is). */
3353 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3354 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3355 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3358 if (network_config_stats != 0)
3359 plugin_register_read ("network", network_stats_read);
3361 plugin_register_shutdown ("network", network_shutdown);
3363 send_buffer = malloc (network_config_packet_size);
3364 if (send_buffer == NULL)
3366 ERROR ("network plugin: malloc failed.");
3369 network_init_buffer ();
3371 /* setup socket(s) and so on */
3372 if (sending_sockets != NULL)
3374 plugin_register_write ("network", network_write,
3375 /* user_data = */ NULL);
3376 plugin_register_notification ("network", network_notification,
3377 /* user_data = */ NULL);
3380 /* If no threads need to be started, return here. */
3381 if ((listen_sockets_num == 0)
3382 || ((dispatch_thread_running != 0)
3383 && (receive_thread_running != 0)))
3386 if (dispatch_thread_running == 0)
3389 status = pthread_create (&dispatch_thread_id,
3390 NULL /* no attributes */,
3392 NULL /* no argument */);
3396 ERROR ("network: pthread_create failed: %s",
3397 sstrerror (errno, errbuf,
3402 dispatch_thread_running = 1;
3406 if (receive_thread_running == 0)
3409 status = pthread_create (&receive_thread_id,
3410 NULL /* no attributes */,
3412 NULL /* no argument */);
3416 ERROR ("network: pthread_create failed: %s",
3417 sstrerror (errno, errbuf,
3422 receive_thread_running = 1;
3427 } /* int network_init */
3430 * The flush option of the network plugin cannot flush individual identifiers.
3431 * All the values are added to a buffer and sent when the buffer is full, the
3432 * requested value may or may not be in there, it's not worth finding out. We
3433 * just send the buffer if `flush' is called - if the requested value was in
3434 * there, good. If not, well, then there is nothing to flush.. -octo
3436 static int network_flush (__attribute__((unused)) cdtime_t timeout,
3437 __attribute__((unused)) const char *identifier,
3438 __attribute__((unused)) user_data_t *user_data)
3440 pthread_mutex_lock (&send_buffer_lock);
3442 if (send_buffer_fill > 0)
3445 pthread_mutex_unlock (&send_buffer_lock);
3448 } /* int network_flush */
3450 void module_register (void)
3452 plugin_register_complex_config ("network", network_config);
3453 plugin_register_init ("network", network_init);
3454 plugin_register_flush ("network", network_flush,
3455 /* user_data = */ NULL);
3456 } /* void module_register */
3458 /* vim: set fdm=marker : */