2 * collectd - src/network.c
3 * Copyright (C) 2005-2009 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 static size_t network_config_packet_size = 1024;
263 static int network_config_forward = 0;
264 static int network_config_stats = 0;
266 static sockent_t *sending_sockets = NULL;
268 static receive_list_entry_t *receive_list_head = NULL;
269 static receive_list_entry_t *receive_list_tail = NULL;
270 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
271 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
272 static uint64_t receive_list_length = 0;
274 static sockent_t *listen_sockets = NULL;
275 static struct pollfd *listen_sockets_pollfd = NULL;
276 static size_t listen_sockets_num = 0;
278 /* The receive and dispatch threads will run as long as `listen_loop' is set to
280 static int listen_loop = 0;
281 static int receive_thread_running = 0;
282 static pthread_t receive_thread_id;
283 static int dispatch_thread_running = 0;
284 static pthread_t dispatch_thread_id;
286 /* Buffer in which to-be-sent network packets are constructed. */
287 static char *send_buffer;
288 static char *send_buffer_ptr;
289 static int send_buffer_fill;
290 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
291 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
293 /* XXX: These counters are incremented from one place only. The spot in which
294 * the values are incremented is either only reachable by one thread (the
295 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
296 * example). Only if neither is true, the stats_lock is acquired. The counters
297 * are always read without holding a lock in the hope that writing 8 bytes to
298 * memory is an atomic operation. */
299 static uint64_t stats_octets_rx = 0;
300 static uint64_t stats_octets_tx = 0;
301 static uint64_t stats_packets_rx = 0;
302 static uint64_t stats_packets_tx = 0;
303 static uint64_t stats_values_dispatched = 0;
304 static uint64_t stats_values_not_dispatched = 0;
305 static uint64_t stats_values_sent = 0;
306 static uint64_t stats_values_not_sent = 0;
307 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
312 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
314 uint64_t time_sent = 0;
317 status = uc_meta_data_get_unsigned_int (vl,
318 "network:time_sent", &time_sent);
320 /* This is a value we already sent. Don't allow it to be received again in
321 * order to avoid looping. */
322 if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
326 } /* }}} _Bool check_receive_okay */
328 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
330 _Bool received = false;
333 if (network_config_forward != 0)
336 if (vl->meta == NULL)
339 status = meta_data_get_boolean (vl->meta, "network:received", &received);
340 if (status == -ENOENT)
342 else if (status != 0)
344 ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
345 "with status %i.", status);
349 /* By default, only *send* value lists that were not *received* by the
352 } /* }}} _Bool check_send_okay */
354 static _Bool check_notify_received (const notification_t *n) /* {{{ */
356 notification_meta_t *ptr;
358 for (ptr = n->meta; ptr != NULL; ptr = ptr->next)
359 if ((strcmp ("network:received", ptr->name) == 0)
360 && (ptr->type == NM_TYPE_BOOLEAN))
361 return ((_Bool) ptr->nm_value.nm_boolean);
364 } /* }}} _Bool check_notify_received */
366 static _Bool check_send_notify_okay (const notification_t *n) /* {{{ */
368 static c_complain_t complain_forwarding = C_COMPLAIN_INIT_STATIC;
374 received = check_notify_received (n);
376 if (network_config_forward && received)
378 c_complain_once (LOG_ERR, &complain_forwarding,
379 "network plugin: A notification has been received via the network "
380 "forwarding if enabled. Forwarding of notifications is currently "
381 "not supported, because there is not loop-deteciton available. "
382 "Please contact the collectd mailing list if you need this "
386 /* By default, only *send* value lists that were not *received* by the
389 } /* }}} _Bool check_send_notify_okay */
391 static int network_dispatch_values (value_list_t *vl, /* {{{ */
392 const char *username)
397 || (strlen (vl->host) <= 0)
398 || (strlen (vl->plugin) <= 0)
399 || (strlen (vl->type) <= 0))
402 if (!check_receive_okay (vl))
405 char name[6*DATA_MAX_NAME_LEN];
406 FORMAT_VL (name, sizeof (name), vl);
407 name[sizeof (name) - 1] = 0;
408 DEBUG ("network plugin: network_dispatch_values: "
409 "NOT dispatching %s.", name);
411 stats_values_not_dispatched++;
415 assert (vl->meta == NULL);
417 vl->meta = meta_data_create ();
418 if (vl->meta == NULL)
420 ERROR ("network plugin: meta_data_create failed.");
424 status = meta_data_add_boolean (vl->meta, "network:received", true);
427 ERROR ("network plugin: meta_data_add_boolean failed.");
428 meta_data_destroy (vl->meta);
433 if (username != NULL)
435 status = meta_data_add_string (vl->meta, "network:username", username);
438 ERROR ("network plugin: meta_data_add_string failed.");
439 meta_data_destroy (vl->meta);
445 plugin_dispatch_values_secure (vl);
446 stats_values_dispatched++;
448 meta_data_destroy (vl->meta);
452 } /* }}} int network_dispatch_values */
454 static int network_dispatch_notification (notification_t *n) /* {{{ */
458 assert (n->meta == NULL);
460 status = plugin_notification_meta_add_boolean (n, "network:received", 1);
463 ERROR ("network plugin: plugin_notification_meta_add_boolean failed.");
464 plugin_notification_meta_free (n->meta);
469 status = plugin_dispatch_notification (n);
471 plugin_notification_meta_free (n->meta);
475 } /* }}} int network_dispatch_notification */
478 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
479 const void *iv, size_t iv_size, const char *username)
482 gcry_cipher_hd_t *cyper_ptr;
483 unsigned char password_hash[32];
485 if (se->type == SOCKENT_TYPE_CLIENT)
487 cyper_ptr = &se->data.client.cypher;
488 memcpy (password_hash, se->data.client.password_hash,
489 sizeof (password_hash));
495 cyper_ptr = &se->data.server.cypher;
497 if (username == NULL)
500 secret = fbh_get (se->data.server.userdb, username);
504 gcry_md_hash_buffer (GCRY_MD_SHA256,
506 secret, strlen (secret));
511 if (*cyper_ptr == NULL)
513 err = gcry_cipher_open (cyper_ptr,
514 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
517 ERROR ("network plugin: gcry_cipher_open returned: %s",
518 gcry_strerror (err));
525 gcry_cipher_reset (*cyper_ptr);
527 assert (*cyper_ptr != NULL);
529 err = gcry_cipher_setkey (*cyper_ptr,
530 password_hash, sizeof (password_hash));
533 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
534 gcry_strerror (err));
535 gcry_cipher_close (*cyper_ptr);
540 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
543 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
544 gcry_strerror (err));
545 gcry_cipher_close (*cyper_ptr);
551 } /* }}} int network_get_aes256_cypher */
552 #endif /* HAVE_LIBGCRYPT */
554 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
555 const data_set_t *ds, const value_list_t *vl)
561 part_header_t pkg_ph;
562 uint16_t pkg_num_values;
563 uint8_t *pkg_values_types;
569 num_values = vl->values_len;
570 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
571 + (num_values * sizeof (uint8_t))
572 + (num_values * sizeof (value_t));
574 if (*ret_buffer_len < packet_len)
577 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
578 if (pkg_values_types == NULL)
580 ERROR ("network plugin: write_part_values: malloc failed.");
584 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
585 if (pkg_values == NULL)
587 free (pkg_values_types);
588 ERROR ("network plugin: write_part_values: malloc failed.");
592 pkg_ph.type = htons (TYPE_VALUES);
593 pkg_ph.length = htons (packet_len);
595 pkg_num_values = htons ((uint16_t) vl->values_len);
597 for (i = 0; i < num_values; i++)
599 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
600 switch (ds->ds[i].type)
602 case DS_TYPE_COUNTER:
603 pkg_values[i].counter = htonll (vl->values[i].counter);
607 pkg_values[i].gauge = htond (vl->values[i].gauge);
611 pkg_values[i].derive = htonll (vl->values[i].derive);
614 case DS_TYPE_ABSOLUTE:
615 pkg_values[i].absolute = htonll (vl->values[i].absolute);
619 free (pkg_values_types);
621 ERROR ("network plugin: write_part_values: "
622 "Unknown data source type: %i",
625 } /* switch (ds->ds[i].type) */
626 } /* for (num_values) */
629 * Use `memcpy' to write everything to the buffer, because the pointer
630 * may be unaligned and some architectures, such as SPARC, can't handle
633 packet_ptr = *ret_buffer;
635 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
636 offset += sizeof (pkg_ph);
637 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
638 offset += sizeof (pkg_num_values);
639 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
640 offset += num_values * sizeof (uint8_t);
641 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
642 offset += num_values * sizeof (value_t);
644 assert (offset == packet_len);
646 *ret_buffer = packet_ptr + packet_len;
647 *ret_buffer_len -= packet_len;
649 free (pkg_values_types);
653 } /* int write_part_values */
655 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
656 int type, uint64_t value)
661 part_header_t pkg_head;
666 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
668 if (*ret_buffer_len < packet_len)
671 pkg_head.type = htons (type);
672 pkg_head.length = htons (packet_len);
673 pkg_value = htonll (value);
675 packet_ptr = *ret_buffer;
677 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
678 offset += sizeof (pkg_head);
679 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
680 offset += sizeof (pkg_value);
682 assert (offset == packet_len);
684 *ret_buffer = packet_ptr + packet_len;
685 *ret_buffer_len -= packet_len;
688 } /* int write_part_number */
690 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
691 int type, const char *str, int str_len)
701 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
702 if (*ret_buffer_len < buffer_len)
705 pkg_type = htons (type);
706 pkg_length = htons (buffer_len);
708 buffer = *ret_buffer;
710 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
711 offset += sizeof (pkg_type);
712 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
713 offset += sizeof (pkg_length);
714 memcpy (buffer + offset, str, str_len);
716 memset (buffer + offset, '\0', 1);
719 assert (offset == buffer_len);
721 *ret_buffer = buffer + buffer_len;
722 *ret_buffer_len -= buffer_len;
725 } /* int write_part_string */
727 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
728 value_t **ret_values, int *ret_num_values)
730 char *buffer = *ret_buffer;
731 size_t buffer_len = *ret_buffer_len;
746 NOTICE ("network plugin: packet is too short: "
747 "buffer_len = %zu", buffer_len);
751 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
752 buffer += sizeof (tmp16);
753 pkg_type = ntohs (tmp16);
755 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
756 buffer += sizeof (tmp16);
757 pkg_length = ntohs (tmp16);
759 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
760 buffer += sizeof (tmp16);
761 pkg_numval = ntohs (tmp16);
763 assert (pkg_type == TYPE_VALUES);
765 exp_size = 3 * sizeof (uint16_t)
766 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
767 if (buffer_len < exp_size)
769 WARNING ("network plugin: parse_part_values: "
771 "Chunk of size %zu expected, "
772 "but buffer has only %zu bytes left.",
773 exp_size, buffer_len);
777 if (pkg_length != exp_size)
779 WARNING ("network plugin: parse_part_values: "
780 "Length and number of values "
781 "in the packet don't match.");
785 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
786 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
787 if ((pkg_types == NULL) || (pkg_values == NULL))
791 ERROR ("network plugin: parse_part_values: malloc failed.");
795 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
796 buffer += pkg_numval * sizeof (uint8_t);
797 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
798 buffer += pkg_numval * sizeof (value_t);
800 for (i = 0; i < pkg_numval; i++)
802 switch (pkg_types[i])
804 case DS_TYPE_COUNTER:
805 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
809 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
813 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
816 case DS_TYPE_ABSOLUTE:
817 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
821 NOTICE ("network plugin: parse_part_values: "
822 "Don't know how to handle data source type %"PRIu8,
827 } /* switch (pkg_types[i]) */
830 *ret_buffer = buffer;
831 *ret_buffer_len = buffer_len - pkg_length;
832 *ret_num_values = pkg_numval;
833 *ret_values = pkg_values;
838 } /* int parse_part_values */
840 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
843 char *buffer = *ret_buffer;
844 size_t buffer_len = *ret_buffer_len;
848 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
852 if (buffer_len < exp_size)
854 WARNING ("network plugin: parse_part_number: "
856 "Chunk of size %zu expected, "
857 "but buffer has only %zu bytes left.",
858 exp_size, buffer_len);
862 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
863 buffer += sizeof (tmp16);
864 /* pkg_type = ntohs (tmp16); */
866 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
867 buffer += sizeof (tmp16);
868 pkg_length = ntohs (tmp16);
870 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
871 buffer += sizeof (tmp64);
872 *value = ntohll (tmp64);
874 *ret_buffer = buffer;
875 *ret_buffer_len = buffer_len - pkg_length;
878 } /* int parse_part_number */
880 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
881 char *output, int output_len)
883 char *buffer = *ret_buffer;
884 size_t buffer_len = *ret_buffer_len;
887 size_t header_size = 2 * sizeof (uint16_t);
891 if (buffer_len < header_size)
893 WARNING ("network plugin: parse_part_string: "
895 "Chunk of at least size %zu expected, "
896 "but buffer has only %zu bytes left.",
897 header_size, buffer_len);
901 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
902 buffer += sizeof (tmp16);
903 /* pkg_type = ntohs (tmp16); */
905 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
906 buffer += sizeof (tmp16);
907 pkg_length = ntohs (tmp16);
909 /* Check that packet fits in the input buffer */
910 if (pkg_length > buffer_len)
912 WARNING ("network plugin: parse_part_string: "
914 "Chunk of size %"PRIu16" received, "
915 "but buffer has only %zu bytes left.",
916 pkg_length, buffer_len);
920 /* Check that pkg_length is in the valid range */
921 if (pkg_length <= header_size)
923 WARNING ("network plugin: parse_part_string: "
925 "Header claims this packet is only %hu "
926 "bytes long.", pkg_length);
930 /* Check that the package data fits into the output buffer.
931 * The previous if-statement ensures that:
932 * `pkg_length > header_size' */
934 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
936 WARNING ("network plugin: parse_part_string: "
937 "Output buffer too small.");
941 /* All sanity checks successfull, let's copy the data over */
942 output_len = pkg_length - header_size;
943 memcpy ((void *) output, (void *) buffer, output_len);
944 buffer += output_len;
946 /* For some very weird reason '\0' doesn't do the trick on SPARC in
948 if (output[output_len - 1] != 0)
950 WARNING ("network plugin: parse_part_string: "
951 "Received string does not end "
952 "with a NULL-byte.");
956 *ret_buffer = buffer;
957 *ret_buffer_len = buffer_len - pkg_length;
960 } /* int parse_part_string */
962 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
963 * parse_packet and vice versa. */
964 #define PP_SIGNED 0x01
965 #define PP_ENCRYPTED 0x02
966 static int parse_packet (sockent_t *se,
967 void *buffer, size_t buffer_size, int flags,
968 const char *username);
970 #define BUFFER_READ(p,s) do { \
971 memcpy ((p), buffer + buffer_offset, (s)); \
972 buffer_offset += (s); \
976 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
977 void **ret_buffer, size_t *ret_buffer_len, int flags)
979 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
983 size_t buffer_offset;
988 part_signature_sha256_t pss;
989 uint16_t pss_head_length;
990 char hash[sizeof (pss.hash)];
994 unsigned char *hash_ptr;
996 buffer = *ret_buffer;
997 buffer_len = *ret_buffer_len;
1000 if (se->data.server.userdb == NULL)
1002 c_complain (LOG_NOTICE, &complain_no_users,
1003 "network plugin: Received signed network packet but can't verify it "
1004 "because no user DB has been configured. Will accept it.");
1008 /* Check if the buffer has enough data for this structure. */
1009 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
1012 /* Read type and length header */
1013 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1014 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1015 pss_head_length = ntohs (pss.head.length);
1017 /* Check if the `pss_head_length' is within bounds. */
1018 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
1019 || (pss_head_length > buffer_len))
1021 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
1025 /* Copy the hash. */
1026 BUFFER_READ (pss.hash, sizeof (pss.hash));
1028 /* Calculate username length (without null byte) and allocate memory */
1029 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
1030 pss.username = malloc (username_len + 1);
1031 if (pss.username == NULL)
1034 /* Read the username */
1035 BUFFER_READ (pss.username, username_len);
1036 pss.username[username_len] = 0;
1038 assert (buffer_offset == pss_head_length);
1040 /* Query the password */
1041 secret = fbh_get (se->data.server.userdb, pss.username);
1044 ERROR ("network plugin: Unknown user: %s", pss.username);
1045 sfree (pss.username);
1049 /* Create a hash device and check the HMAC */
1051 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
1054 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
1055 gcry_strerror (err));
1057 sfree (pss.username);
1061 err = gcry_md_setkey (hd, secret, strlen (secret));
1064 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1067 sfree (pss.username);
1072 buffer + PART_SIGNATURE_SHA256_SIZE,
1073 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1074 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1075 if (hash_ptr == NULL)
1077 ERROR ("network plugin: gcry_md_read failed.");
1080 sfree (pss.username);
1083 memcpy (hash, hash_ptr, sizeof (hash));
1089 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1091 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1096 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1097 flags | PP_SIGNED, pss.username);
1101 sfree (pss.username);
1103 *ret_buffer = buffer + buffer_len;
1104 *ret_buffer_len = 0;
1107 } /* }}} int parse_part_sign_sha256 */
1108 /* #endif HAVE_LIBGCRYPT */
1110 #else /* if !HAVE_LIBGCRYPT */
1111 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1112 void **ret_buffer, size_t *ret_buffer_size, int flags)
1114 static int warning_has_been_printed = 0;
1118 size_t buffer_offset;
1121 part_signature_sha256_t pss;
1123 buffer = *ret_buffer;
1124 buffer_size = *ret_buffer_size;
1127 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1130 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1131 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1132 part_len = ntohs (pss.head.length);
1134 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1135 || (part_len > buffer_size))
1138 if (warning_has_been_printed == 0)
1140 WARNING ("network plugin: Received signed packet, but the network "
1141 "plugin was not linked with libgcrypt, so I cannot "
1142 "verify the signature. The packet will be accepted.");
1143 warning_has_been_printed = 1;
1146 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1147 /* username = */ NULL);
1149 *ret_buffer = buffer + buffer_size;
1150 *ret_buffer_size = 0;
1153 } /* }}} int parse_part_sign_sha256 */
1154 #endif /* !HAVE_LIBGCRYPT */
1157 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1158 void **ret_buffer, size_t *ret_buffer_len,
1161 char *buffer = *ret_buffer;
1162 size_t buffer_len = *ret_buffer_len;
1165 size_t buffer_offset;
1166 uint16_t username_len;
1167 part_encryption_aes256_t pea;
1168 unsigned char hash[sizeof (pea.hash)];
1170 gcry_cipher_hd_t cypher;
1173 /* Make sure at least the header if available. */
1174 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1176 NOTICE ("network plugin: parse_part_encr_aes256: "
1177 "Discarding short packet.");
1183 /* Copy the unencrypted information into `pea'. */
1184 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1185 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1187 /* Check the `part size'. */
1188 part_size = ntohs (pea.head.length);
1189 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1190 || (part_size > buffer_len))
1192 NOTICE ("network plugin: parse_part_encr_aes256: "
1193 "Discarding part with invalid size.");
1197 /* Read the username */
1198 BUFFER_READ (&username_len, sizeof (username_len));
1199 username_len = ntohs (username_len);
1201 if ((username_len <= 0)
1202 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1204 NOTICE ("network plugin: parse_part_encr_aes256: "
1205 "Discarding part with invalid username length.");
1209 assert (username_len > 0);
1210 pea.username = malloc (username_len + 1);
1211 if (pea.username == NULL)
1213 BUFFER_READ (pea.username, username_len);
1214 pea.username[username_len] = 0;
1216 /* Last but not least, the initialization vector */
1217 BUFFER_READ (pea.iv, sizeof (pea.iv));
1219 /* Make sure we are at the right position */
1220 assert (buffer_offset == (username_len +
1221 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1223 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1227 sfree (pea.username);
1231 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1232 assert (payload_len > 0);
1234 /* Decrypt the packet in-place */
1235 err = gcry_cipher_decrypt (cypher,
1236 buffer + buffer_offset,
1237 part_size - buffer_offset,
1238 /* in = */ NULL, /* in len = */ 0);
1241 sfree (pea.username);
1242 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1243 gcry_strerror (err));
1248 BUFFER_READ (pea.hash, sizeof (pea.hash));
1250 /* Make sure we're at the right position - again */
1251 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1252 assert (buffer_offset == (part_size - payload_len));
1254 /* Check hash sum */
1255 memset (hash, 0, sizeof (hash));
1256 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1257 buffer + buffer_offset, payload_len);
1258 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1260 sfree (pea.username);
1261 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1265 parse_packet (se, buffer + buffer_offset, payload_len,
1266 flags | PP_ENCRYPTED, pea.username);
1268 /* XXX: Free pea.username?!? */
1270 /* Update return values */
1271 *ret_buffer = buffer + part_size;
1272 *ret_buffer_len = buffer_len - part_size;
1274 sfree (pea.username);
1277 } /* }}} int parse_part_encr_aes256 */
1278 /* #endif HAVE_LIBGCRYPT */
1280 #else /* if !HAVE_LIBGCRYPT */
1281 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1282 void **ret_buffer, size_t *ret_buffer_size, int flags)
1284 static int warning_has_been_printed = 0;
1288 size_t buffer_offset;
1293 buffer = *ret_buffer;
1294 buffer_size = *ret_buffer_size;
1297 /* parse_packet assures this minimum size. */
1298 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1300 BUFFER_READ (&ph.type, sizeof (ph.type));
1301 BUFFER_READ (&ph.length, sizeof (ph.length));
1302 ph_length = ntohs (ph.length);
1304 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1305 || (ph_length > buffer_size))
1307 ERROR ("network plugin: AES-256 encrypted part "
1308 "with invalid length received.");
1312 if (warning_has_been_printed == 0)
1314 WARNING ("network plugin: Received encrypted packet, but the network "
1315 "plugin was not linked with libgcrypt, so I cannot "
1316 "decrypt it. The part will be discarded.");
1317 warning_has_been_printed = 1;
1320 *ret_buffer += ph_length;
1321 *ret_buffer_size -= ph_length;
1324 } /* }}} int parse_part_encr_aes256 */
1325 #endif /* !HAVE_LIBGCRYPT */
1329 static int parse_packet (sockent_t *se, /* {{{ */
1330 void *buffer, size_t buffer_size, int flags,
1331 const char *username)
1335 value_list_t vl = VALUE_LIST_INIT;
1339 int packet_was_signed = (flags & PP_SIGNED);
1340 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1341 int printed_ignore_warning = 0;
1342 #endif /* HAVE_LIBGCRYPT */
1345 memset (&vl, '\0', sizeof (vl));
1346 memset (&n, '\0', sizeof (n));
1349 while ((status == 0) && (0 < buffer_size)
1350 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1352 uint16_t pkg_length;
1355 memcpy ((void *) &pkg_type,
1358 memcpy ((void *) &pkg_length,
1359 (void *) (buffer + sizeof (pkg_type)),
1360 sizeof (pkg_length));
1362 pkg_length = ntohs (pkg_length);
1363 pkg_type = ntohs (pkg_type);
1365 if (pkg_length > buffer_size)
1367 /* Ensure that this loop terminates eventually */
1368 if (pkg_length < (2 * sizeof (uint16_t)))
1371 if (pkg_type == TYPE_ENCR_AES256)
1373 status = parse_part_encr_aes256 (se,
1374 &buffer, &buffer_size, flags);
1377 ERROR ("network plugin: Decrypting AES256 "
1379 "with status %i.", status);
1384 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1385 && (packet_was_encrypted == 0))
1387 if (printed_ignore_warning == 0)
1389 INFO ("network plugin: Unencrypted packet or "
1390 "part has been ignored.");
1391 printed_ignore_warning = 1;
1393 buffer = ((char *) buffer) + pkg_length;
1396 #endif /* HAVE_LIBGCRYPT */
1397 else if (pkg_type == TYPE_SIGN_SHA256)
1399 status = parse_part_sign_sha256 (se,
1400 &buffer, &buffer_size, flags);
1403 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1405 "with status %i.", status);
1410 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1411 && (packet_was_encrypted == 0)
1412 && (packet_was_signed == 0))
1414 if (printed_ignore_warning == 0)
1416 INFO ("network plugin: Unsigned packet or "
1417 "part has been ignored.");
1418 printed_ignore_warning = 1;
1420 buffer = ((char *) buffer) + pkg_length;
1423 #endif /* HAVE_LIBGCRYPT */
1424 else if (pkg_type == TYPE_VALUES)
1426 status = parse_part_values (&buffer, &buffer_size,
1427 &vl.values, &vl.values_len);
1431 network_dispatch_values (&vl, username);
1435 else if (pkg_type == TYPE_TIME)
1438 status = parse_part_number (&buffer, &buffer_size,
1442 vl.time = (time_t) tmp;
1443 n.time = (time_t) tmp;
1446 else if (pkg_type == TYPE_INTERVAL)
1449 status = parse_part_number (&buffer, &buffer_size,
1452 vl.interval = (int) tmp;
1454 else if (pkg_type == TYPE_HOST)
1456 status = parse_part_string (&buffer, &buffer_size,
1457 vl.host, sizeof (vl.host));
1459 sstrncpy (n.host, vl.host, sizeof (n.host));
1461 else if (pkg_type == TYPE_PLUGIN)
1463 status = parse_part_string (&buffer, &buffer_size,
1464 vl.plugin, sizeof (vl.plugin));
1466 sstrncpy (n.plugin, vl.plugin,
1469 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1471 status = parse_part_string (&buffer, &buffer_size,
1473 sizeof (vl.plugin_instance));
1475 sstrncpy (n.plugin_instance,
1477 sizeof (n.plugin_instance));
1479 else if (pkg_type == TYPE_TYPE)
1481 status = parse_part_string (&buffer, &buffer_size,
1482 vl.type, sizeof (vl.type));
1484 sstrncpy (n.type, vl.type, sizeof (n.type));
1486 else if (pkg_type == TYPE_TYPE_INSTANCE)
1488 status = parse_part_string (&buffer, &buffer_size,
1490 sizeof (vl.type_instance));
1492 sstrncpy (n.type_instance, vl.type_instance,
1493 sizeof (n.type_instance));
1495 else if (pkg_type == TYPE_MESSAGE)
1497 status = parse_part_string (&buffer, &buffer_size,
1498 n.message, sizeof (n.message));
1504 else if ((n.severity != NOTIF_FAILURE)
1505 && (n.severity != NOTIF_WARNING)
1506 && (n.severity != NOTIF_OKAY))
1508 INFO ("network plugin: "
1509 "Ignoring notification with "
1510 "unknown severity %i.",
1513 else if (n.time <= 0)
1515 INFO ("network plugin: "
1516 "Ignoring notification with "
1519 else if (strlen (n.message) <= 0)
1521 INFO ("network plugin: "
1522 "Ignoring notification with "
1523 "an empty message.");
1527 network_dispatch_notification (&n);
1530 else if (pkg_type == TYPE_SEVERITY)
1533 status = parse_part_number (&buffer, &buffer_size,
1536 n.severity = (int) tmp;
1540 DEBUG ("network plugin: parse_packet: Unknown part"
1541 " type: 0x%04hx", pkg_type);
1542 buffer = ((char *) buffer) + pkg_length;
1544 } /* while (buffer_size > sizeof (part_header_t)) */
1546 if (status == 0 && buffer_size > 0)
1547 WARNING ("network plugin: parse_packet: Received truncated "
1548 "packet, try increasing `MaxPacketSize'");
1551 } /* }}} int parse_packet */
1553 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1562 sfree (sec->username);
1563 sfree (sec->password);
1564 if (sec->cypher != NULL)
1565 gcry_cipher_close (sec->cypher);
1567 } /* }}} void free_sockent_client */
1569 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1573 for (i = 0; i < ses->fd_num; i++)
1575 if (ses->fd[i] >= 0)
1584 sfree (ses->auth_file);
1585 fbh_destroy (ses->userdb);
1586 if (ses->cypher != NULL)
1587 gcry_cipher_close (ses->cypher);
1589 } /* }}} void free_sockent_server */
1591 static void sockent_destroy (sockent_t *se) /* {{{ */
1595 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1602 sfree (se->service);
1604 if (se->type == SOCKENT_TYPE_CLIENT)
1605 free_sockent_client (&se->data.client);
1607 free_sockent_server (&se->data.server);
1612 } /* }}} void sockent_destroy */
1615 * int network_set_ttl
1617 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1618 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1620 * The `struct addrinfo' is used to destinguish between unicast and multicast
1623 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1625 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1626 network_config_ttl);
1628 assert (se->type == SOCKENT_TYPE_CLIENT);
1630 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1633 if (ai->ai_family == AF_INET)
1635 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1638 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1639 optname = IP_MULTICAST_TTL;
1643 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1644 &network_config_ttl,
1645 sizeof (network_config_ttl)) != 0)
1648 ERROR ("setsockopt: %s",
1649 sstrerror (errno, errbuf, sizeof (errbuf)));
1653 else if (ai->ai_family == AF_INET6)
1655 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1656 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1659 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1660 optname = IPV6_MULTICAST_HOPS;
1662 optname = IPV6_UNICAST_HOPS;
1664 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1665 &network_config_ttl,
1666 sizeof (network_config_ttl)) != 0)
1669 ERROR ("setsockopt: %s",
1670 sstrerror (errno, errbuf,
1677 } /* int network_set_ttl */
1679 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1681 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1684 assert (se->type == SOCKENT_TYPE_CLIENT);
1686 if (ai->ai_family == AF_INET)
1688 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1690 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1692 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1693 /* If possible, use the "ip_mreqn" structure which has
1694 * an "interface index" member. Using the interface
1695 * index is preferred here, because of its similarity
1696 * to the way IPv6 handles this. Unfortunately, it
1697 * appears not to be portable. */
1698 struct ip_mreqn mreq;
1700 memset (&mreq, 0, sizeof (mreq));
1701 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1702 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1703 mreq.imr_ifindex = se->interface;
1705 struct ip_mreq mreq;
1707 memset (&mreq, 0, sizeof (mreq));
1708 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1709 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1712 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1713 &mreq, sizeof (mreq)) != 0)
1716 ERROR ("setsockopt: %s",
1717 sstrerror (errno, errbuf, sizeof (errbuf)));
1724 else if (ai->ai_family == AF_INET6)
1726 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1728 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1730 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1732 sizeof (se->interface)) != 0)
1735 ERROR ("setsockopt: %s",
1736 sstrerror (errno, errbuf,
1745 /* else: Not a multicast interface. */
1746 if (se->interface != 0)
1748 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1749 char interface_name[IFNAMSIZ];
1751 if (if_indextoname (se->interface, interface_name) == NULL)
1754 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1756 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1758 sizeof(interface_name)) == -1 )
1761 ERROR ("setsockopt: %s",
1762 sstrerror (errno, errbuf, sizeof (errbuf)));
1765 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1768 WARNING ("network plugin: Cannot set the interface on a unicast "
1770 # if !defined(SO_BINDTODEVICE)
1771 "the \"SO_BINDTODEVICE\" socket option "
1773 "the \"if_indextoname\" function "
1775 "is not available on your system.");
1781 } /* }}} network_set_interface */
1783 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1788 /* allow multiple sockets to use the same PORT number */
1789 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1790 &yes, sizeof(yes)) == -1) {
1792 ERROR ("setsockopt: %s",
1793 sstrerror (errno, errbuf, sizeof (errbuf)));
1797 DEBUG ("fd = %i; calling `bind'", fd);
1799 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1803 sstrerror (errno, errbuf, sizeof (errbuf)));
1807 if (ai->ai_family == AF_INET)
1809 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1810 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1812 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1813 struct ip_mreqn mreq;
1815 struct ip_mreq mreq;
1818 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1820 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1821 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1822 /* Set the interface using the interface index if
1823 * possible (available). Unfortunately, the struct
1824 * ip_mreqn is not portable. */
1825 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1826 mreq.imr_ifindex = interface_idx;
1828 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1831 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1832 &loop, sizeof (loop)) == -1)
1835 ERROR ("setsockopt: %s",
1836 sstrerror (errno, errbuf,
1841 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1842 &mreq, sizeof (mreq)) == -1)
1845 ERROR ("setsockopt: %s",
1846 sstrerror (errno, errbuf,
1854 else if (ai->ai_family == AF_INET6)
1856 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1857 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1858 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1860 struct ipv6_mreq mreq;
1862 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1864 memcpy (&mreq.ipv6mr_multiaddr,
1866 sizeof (addr->sin6_addr));
1868 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1869 * ipv6mr_interface may be set to zeroes to
1870 * choose the default multicast interface or to
1871 * the index of a particular multicast-capable
1872 * interface if the host is multihomed.
1873 * Membership is associ-associated with a
1874 * single interface; programs running on
1875 * multihomed hosts may need to join the same
1876 * group on more than one interface.*/
1877 mreq.ipv6mr_interface = interface_idx;
1879 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1880 &loop, sizeof (loop)) == -1)
1883 ERROR ("setsockopt: %s",
1884 sstrerror (errno, errbuf,
1889 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1890 &mreq, sizeof (mreq)) == -1)
1893 ERROR ("setsockopt: %s",
1894 sstrerror (errno, errbuf,
1903 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1904 /* if a specific interface was set, bind the socket to it. But to avoid
1905 * possible problems with multicast routing, only do that for non-multicast
1907 if (interface_idx != 0)
1909 char interface_name[IFNAMSIZ];
1911 if (if_indextoname (interface_idx, interface_name) == NULL)
1914 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1916 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1918 sizeof(interface_name)) == -1 )
1921 ERROR ("setsockopt: %s",
1922 sstrerror (errno, errbuf, sizeof (errbuf)));
1926 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1929 } /* int network_bind_socket */
1931 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1932 * or `SOCKENT_TYPE_SERVER' */
1933 static int sockent_init (sockent_t *se, int type) /* {{{ */
1938 memset (se, 0, sizeof (*se));
1940 se->type = SOCKENT_TYPE_CLIENT;
1946 if (type == SOCKENT_TYPE_SERVER)
1948 se->type = SOCKENT_TYPE_SERVER;
1949 se->data.server.fd = NULL;
1951 se->data.server.security_level = SECURITY_LEVEL_NONE;
1952 se->data.server.auth_file = NULL;
1953 se->data.server.userdb = NULL;
1954 se->data.server.cypher = NULL;
1959 se->data.client.fd = -1;
1960 se->data.client.addr = NULL;
1962 se->data.client.security_level = SECURITY_LEVEL_NONE;
1963 se->data.client.username = NULL;
1964 se->data.client.password = NULL;
1965 se->data.client.cypher = NULL;
1970 } /* }}} int sockent_init */
1972 /* Open the file descriptors for a initialized sockent structure. */
1973 static int sockent_open (sockent_t *se) /* {{{ */
1975 struct addrinfo ai_hints;
1976 struct addrinfo *ai_list, *ai_ptr;
1980 const char *service;
1985 /* Set up the security structures. */
1986 #if HAVE_LIBGCRYPT /* {{{ */
1987 if (se->type == SOCKENT_TYPE_CLIENT)
1989 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
1991 if ((se->data.client.username == NULL)
1992 || (se->data.client.password == NULL))
1994 ERROR ("network plugin: Client socket with "
1995 "security requested, but no "
1996 "credentials are configured.");
1999 gcry_md_hash_buffer (GCRY_MD_SHA256,
2000 se->data.client.password_hash,
2001 se->data.client.password,
2002 strlen (se->data.client.password));
2005 else /* (se->type == SOCKENT_TYPE_SERVER) */
2007 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2009 if (se->data.server.auth_file == NULL)
2011 ERROR ("network plugin: Server socket with "
2012 "security requested, but no "
2013 "password file is configured.");
2017 if (se->data.server.auth_file != NULL)
2019 se->data.server.userdb = fbh_create (se->data.server.auth_file);
2020 if (se->data.server.userdb == NULL)
2022 ERROR ("network plugin: Reading password file "
2024 se->data.server.auth_file);
2025 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
2030 #endif /* }}} HAVE_LIBGCRYPT */
2033 service = se->service;
2035 if (service == NULL)
2036 service = NET_DEFAULT_PORT;
2038 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
2041 memset (&ai_hints, 0, sizeof (ai_hints));
2042 ai_hints.ai_flags = 0;
2044 ai_hints.ai_flags |= AI_PASSIVE;
2046 #ifdef AI_ADDRCONFIG
2047 ai_hints.ai_flags |= AI_ADDRCONFIG;
2049 ai_hints.ai_family = AF_UNSPEC;
2050 ai_hints.ai_socktype = SOCK_DGRAM;
2051 ai_hints.ai_protocol = IPPROTO_UDP;
2053 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2056 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2057 (se->node == NULL) ? "(null)" : se->node,
2058 (se->service == NULL) ? "(null)" : se->service,
2059 gai_strerror (ai_return));
2063 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2067 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2071 tmp = realloc (se->data.server.fd,
2072 sizeof (*tmp) * (se->data.server.fd_num + 1));
2075 ERROR ("network plugin: realloc failed.");
2078 se->data.server.fd = tmp;
2079 tmp = se->data.server.fd + se->data.server.fd_num;
2081 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2082 ai_ptr->ai_protocol);
2086 ERROR ("network plugin: socket(2) failed: %s",
2087 sstrerror (errno, errbuf,
2092 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2100 se->data.server.fd_num++;
2102 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2103 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2105 se->data.client.fd = socket (ai_ptr->ai_family,
2106 ai_ptr->ai_socktype,
2107 ai_ptr->ai_protocol);
2108 if (se->data.client.fd < 0)
2111 ERROR ("network plugin: socket(2) failed: %s",
2112 sstrerror (errno, errbuf,
2117 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2118 if (se->data.client.addr == NULL)
2120 ERROR ("network plugin: malloc failed.");
2121 close (se->data.client.fd);
2122 se->data.client.fd = -1;
2126 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2127 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2128 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2129 se->data.client.addrlen = ai_ptr->ai_addrlen;
2131 network_set_ttl (se, ai_ptr);
2132 network_set_interface (se, ai_ptr);
2134 /* We don't open more than one write-socket per
2135 * node/service pair.. */
2137 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2138 } /* for (ai_list) */
2140 freeaddrinfo (ai_list);
2142 /* Check if all went well. */
2143 if (se->type == SOCKENT_TYPE_SERVER)
2145 if (se->data.server.fd_num <= 0)
2148 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2150 if (se->data.client.fd < 0)
2155 } /* }}} int sockent_open */
2157 /* Add a sockent to the global list of sockets */
2158 static int sockent_add (sockent_t *se) /* {{{ */
2160 sockent_t *last_ptr;
2165 if (se->type == SOCKENT_TYPE_SERVER)
2170 tmp = realloc (listen_sockets_pollfd,
2171 sizeof (*tmp) * (listen_sockets_num
2172 + se->data.server.fd_num));
2175 ERROR ("network plugin: realloc failed.");
2178 listen_sockets_pollfd = tmp;
2179 tmp = listen_sockets_pollfd + listen_sockets_num;
2181 for (i = 0; i < se->data.server.fd_num; i++)
2183 memset (tmp + i, 0, sizeof (*tmp));
2184 tmp[i].fd = se->data.server.fd[i];
2185 tmp[i].events = POLLIN | POLLPRI;
2189 listen_sockets_num += se->data.server.fd_num;
2191 if (listen_sockets == NULL)
2193 listen_sockets = se;
2196 last_ptr = listen_sockets;
2198 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2200 if (sending_sockets == NULL)
2202 sending_sockets = se;
2205 last_ptr = sending_sockets;
2208 while (last_ptr->next != NULL)
2209 last_ptr = last_ptr->next;
2210 last_ptr->next = se;
2213 } /* }}} int sockent_add */
2215 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2219 receive_list_entry_t *ent;
2222 /* Lock and wait for more data to come in */
2223 pthread_mutex_lock (&receive_list_lock);
2224 while ((listen_loop == 0)
2225 && (receive_list_head == NULL))
2226 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2228 /* Remove the head entry and unlock */
2229 ent = receive_list_head;
2231 receive_list_head = ent->next;
2232 receive_list_length--;
2233 pthread_mutex_unlock (&receive_list_lock);
2235 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2236 * because we dispatch all missing packets before shutting down. */
2240 /* Look for the correct `sockent_t' */
2241 se = listen_sockets;
2246 for (i = 0; i < se->data.server.fd_num; i++)
2247 if (se->data.server.fd[i] == ent->fd)
2250 if (i < se->data.server.fd_num)
2258 ERROR ("network plugin: Got packet from FD %i, but can't "
2259 "find an appropriate socket entry.",
2266 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2267 /* username = */ NULL);
2273 } /* }}} void *dispatch_thread */
2275 static int network_receive (void) /* {{{ */
2277 char buffer[network_config_packet_size];
2283 receive_list_entry_t *private_list_head;
2284 receive_list_entry_t *private_list_tail;
2285 uint64_t private_list_length;
2287 assert (listen_sockets_num > 0);
2289 private_list_head = NULL;
2290 private_list_tail = NULL;
2291 private_list_length = 0;
2293 while (listen_loop == 0)
2295 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2302 ERROR ("poll failed: %s",
2303 sstrerror (errno, errbuf, sizeof (errbuf)));
2307 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2309 receive_list_entry_t *ent;
2311 if ((listen_sockets_pollfd[i].revents
2312 & (POLLIN | POLLPRI)) == 0)
2316 buffer_len = recv (listen_sockets_pollfd[i].fd,
2317 buffer, sizeof (buffer),
2322 ERROR ("recv failed: %s",
2323 sstrerror (errno, errbuf,
2328 stats_octets_rx += ((uint64_t) buffer_len);
2331 /* TODO: Possible performance enhancement: Do not free
2332 * these entries in the dispatch thread but put them in
2333 * another list, so we don't have to allocate more and
2334 * more of these structures. */
2335 ent = malloc (sizeof (receive_list_entry_t));
2338 ERROR ("network plugin: malloc failed.");
2341 memset (ent, 0, sizeof (receive_list_entry_t));
2342 ent->data = malloc (network_config_packet_size);
2343 if (ent->data == NULL)
2346 ERROR ("network plugin: malloc failed.");
2349 ent->fd = listen_sockets_pollfd[i].fd;
2352 memcpy (ent->data, buffer, buffer_len);
2353 ent->data_len = buffer_len;
2355 if (private_list_head == NULL)
2356 private_list_head = ent;
2358 private_list_tail->next = ent;
2359 private_list_tail = ent;
2360 private_list_length++;
2362 /* Do not block here. Blocking here has led to
2363 * insufficient performance in the past. */
2364 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2366 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2367 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2369 if (receive_list_head == NULL)
2370 receive_list_head = private_list_head;
2372 receive_list_tail->next = private_list_head;
2373 receive_list_tail = private_list_tail;
2374 receive_list_length += private_list_length;
2376 pthread_cond_signal (&receive_list_cond);
2377 pthread_mutex_unlock (&receive_list_lock);
2379 private_list_head = NULL;
2380 private_list_tail = NULL;
2381 private_list_length = 0;
2383 } /* for (listen_sockets_pollfd) */
2384 } /* while (listen_loop == 0) */
2386 /* Make sure everything is dispatched before exiting. */
2387 if (private_list_head != NULL)
2389 pthread_mutex_lock (&receive_list_lock);
2391 if (receive_list_head == NULL)
2392 receive_list_head = private_list_head;
2394 receive_list_tail->next = private_list_head;
2395 receive_list_tail = private_list_tail;
2396 receive_list_length += private_list_length;
2398 private_list_head = NULL;
2399 private_list_tail = NULL;
2400 private_list_length = 0;
2402 pthread_cond_signal (&receive_list_cond);
2403 pthread_mutex_unlock (&receive_list_lock);
2407 } /* }}} int network_receive */
2409 static void *receive_thread (void __attribute__((unused)) *arg)
2411 return (network_receive () ? (void *) 1 : (void *) 0);
2412 } /* void *receive_thread */
2414 static void network_init_buffer (void)
2416 memset (send_buffer, 0, network_config_packet_size);
2417 send_buffer_ptr = send_buffer;
2418 send_buffer_fill = 0;
2420 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2421 } /* int network_init_buffer */
2423 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2424 const char *buffer, size_t buffer_size)
2430 status = sendto (se->data.client.fd, buffer, buffer_size,
2432 (struct sockaddr *) se->data.client.addr,
2433 se->data.client.addrlen);
2439 ERROR ("network plugin: sendto failed: %s",
2440 sstrerror (errno, errbuf,
2447 } /* }}} void networt_send_buffer_plain */
2450 #define BUFFER_ADD(p,s) do { \
2451 memcpy (buffer + buffer_offset, (p), (s)); \
2452 buffer_offset += (s); \
2455 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2456 const char *in_buffer, size_t in_buffer_size)
2458 part_signature_sha256_t ps;
2459 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2460 size_t buffer_offset;
2461 size_t username_len;
2465 unsigned char *hash;
2468 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2471 ERROR ("network plugin: Creating HMAC object failed: %s",
2472 gcry_strerror (err));
2476 err = gcry_md_setkey (hd, se->data.client.password,
2477 strlen (se->data.client.password));
2480 ERROR ("network plugin: gcry_md_setkey failed: %s",
2481 gcry_strerror (err));
2486 username_len = strlen (se->data.client.username);
2487 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2489 ERROR ("network plugin: Username too long: %s",
2490 se->data.client.username);
2494 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2495 se->data.client.username, username_len);
2496 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2497 in_buffer, in_buffer_size);
2499 /* Initialize the `ps' structure. */
2500 memset (&ps, 0, sizeof (ps));
2501 ps.head.type = htons (TYPE_SIGN_SHA256);
2502 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2504 /* Calculate the hash value. */
2505 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2506 username_len + in_buffer_size);
2507 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2510 ERROR ("network plugin: gcry_md_read failed.");
2514 memcpy (ps.hash, hash, sizeof (ps.hash));
2516 /* Add the header */
2519 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2520 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2521 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2523 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2528 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2529 networt_send_buffer_plain (se, buffer, buffer_offset);
2530 } /* }}} void networt_send_buffer_signed */
2532 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2533 const char *in_buffer, size_t in_buffer_size)
2535 part_encryption_aes256_t pea;
2536 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2538 size_t buffer_offset;
2540 size_t username_len;
2542 gcry_cipher_hd_t cypher;
2544 /* Initialize the header fields */
2545 memset (&pea, 0, sizeof (pea));
2546 pea.head.type = htons (TYPE_ENCR_AES256);
2548 pea.username = se->data.client.username;
2550 username_len = strlen (pea.username);
2551 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2553 ERROR ("network plugin: Username too long: %s", pea.username);
2557 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2558 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2559 - sizeof (pea.hash);
2561 assert (buffer_size <= sizeof (buffer));
2562 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2563 "buffer_size = %zu;", buffer_size);
2565 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2566 + username_len + in_buffer_size));
2567 pea.username_length = htons ((uint16_t) username_len);
2569 /* Chose a random initialization vector. */
2570 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2572 /* Create hash of the payload */
2573 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2575 /* Initialize the buffer */
2577 memset (buffer, 0, sizeof (buffer));
2580 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2581 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2582 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2583 BUFFER_ADD (pea.username, username_len);
2584 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2585 assert (buffer_offset == header_size);
2586 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2587 BUFFER_ADD (in_buffer, in_buffer_size);
2589 assert (buffer_offset == buffer_size);
2591 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2592 se->data.client.password);
2596 /* Encrypt the buffer in-place */
2597 err = gcry_cipher_encrypt (cypher,
2598 buffer + header_size,
2599 buffer_size - header_size,
2600 /* in = */ NULL, /* in len = */ 0);
2603 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2604 gcry_strerror (err));
2608 /* Send it out without further modifications */
2609 networt_send_buffer_plain (se, buffer, buffer_size);
2610 } /* }}} void networt_send_buffer_encrypted */
2612 #endif /* HAVE_LIBGCRYPT */
2614 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2618 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2620 for (se = sending_sockets; se != NULL; se = se->next)
2623 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2624 networt_send_buffer_encrypted (se, buffer, buffer_len);
2625 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2626 networt_send_buffer_signed (se, buffer, buffer_len);
2627 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2628 #endif /* HAVE_LIBGCRYPT */
2629 networt_send_buffer_plain (se, buffer, buffer_len);
2630 } /* for (sending_sockets) */
2631 } /* }}} void network_send_buffer */
2633 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2634 value_list_t *vl_def,
2635 const data_set_t *ds, const value_list_t *vl)
2637 char *buffer_orig = buffer;
2639 if (strcmp (vl_def->host, vl->host) != 0)
2641 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2642 vl->host, strlen (vl->host)) != 0)
2644 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2647 if (vl_def->time != vl->time)
2649 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2650 (uint64_t) vl->time))
2652 vl_def->time = vl->time;
2655 if (vl_def->interval != vl->interval)
2657 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2658 (uint64_t) vl->interval))
2660 vl_def->interval = vl->interval;
2663 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2665 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2666 vl->plugin, strlen (vl->plugin)) != 0)
2668 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2671 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2673 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2674 vl->plugin_instance,
2675 strlen (vl->plugin_instance)) != 0)
2677 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2680 if (strcmp (vl_def->type, vl->type) != 0)
2682 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2683 vl->type, strlen (vl->type)) != 0)
2685 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2688 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2690 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2692 strlen (vl->type_instance)) != 0)
2694 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2697 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2700 return (buffer - buffer_orig);
2701 } /* }}} int add_to_buffer */
2703 static void flush_buffer (void)
2705 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2708 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2710 stats_octets_tx += ((uint64_t) send_buffer_fill);
2713 network_init_buffer ();
2716 static int network_write (const data_set_t *ds, const value_list_t *vl,
2717 user_data_t __attribute__((unused)) *user_data)
2721 if (!check_send_okay (vl))
2724 char name[6*DATA_MAX_NAME_LEN];
2725 FORMAT_VL (name, sizeof (name), vl);
2726 name[sizeof (name) - 1] = 0;
2727 DEBUG ("network plugin: network_write: "
2728 "NOT sending %s.", name);
2730 /* Counter is not protected by another lock and may be reached by
2731 * multiple threads */
2732 pthread_mutex_lock (&stats_lock);
2733 stats_values_not_sent++;
2734 pthread_mutex_unlock (&stats_lock);
2738 uc_meta_data_add_unsigned_int (vl,
2739 "network:time_sent", (uint64_t) vl->time);
2741 pthread_mutex_lock (&send_buffer_lock);
2743 status = add_to_buffer (send_buffer_ptr,
2744 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2749 /* status == bytes added to the buffer */
2750 send_buffer_fill += status;
2751 send_buffer_ptr += status;
2753 stats_values_sent++;
2759 status = add_to_buffer (send_buffer_ptr,
2760 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2766 send_buffer_fill += status;
2767 send_buffer_ptr += status;
2769 stats_values_sent++;
2775 ERROR ("network plugin: Unable to append to the "
2776 "buffer for some weird reason");
2778 else if ((network_config_packet_size - send_buffer_fill) < 15)
2783 pthread_mutex_unlock (&send_buffer_lock);
2785 return ((status < 0) ? -1 : 0);
2786 } /* int network_write */
2788 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2791 if ((ci->values_num != 1)
2792 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2793 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2795 ERROR ("network plugin: The `%s' config option needs "
2796 "exactly one boolean argument.", ci->key);
2800 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2802 if (ci->values[0].value.boolean)
2809 char *str = ci->values[0].value.string;
2813 else if (IS_FALSE (str))
2817 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2818 "option as boolean value.",
2825 } /* }}} int network_config_set_boolean */
2827 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2830 if ((ci->values_num != 1)
2831 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2833 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2834 "one numeric argument.");
2838 tmp = (int) ci->values[0].value.number;
2839 if ((tmp > 0) && (tmp <= 255))
2840 network_config_ttl = tmp;
2843 } /* }}} int network_config_set_ttl */
2845 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2848 if ((ci->values_num != 1)
2849 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2851 WARNING ("network plugin: The `Interface' config option needs exactly "
2852 "one string argument.");
2856 if (interface == NULL)
2859 *interface = if_nametoindex (ci->values[0].value.string);
2862 } /* }}} int network_config_set_interface */
2864 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2867 if ((ci->values_num != 1)
2868 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2870 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2871 "one numeric argument.");
2875 tmp = (int) ci->values[0].value.number;
2876 if ((tmp >= 1024) && (tmp <= 65535))
2877 network_config_packet_size = tmp;
2880 } /* }}} int network_config_set_buffer_size */
2883 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2887 if ((ci->values_num != 1)
2888 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2890 WARNING ("network plugin: The `%s' config option needs exactly "
2891 "one string argument.", ci->key);
2895 tmp = strdup (ci->values[0].value.string);
2899 sfree (*ret_string);
2903 } /* }}} int network_config_set_string */
2904 #endif /* HAVE_LIBGCRYPT */
2907 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2911 if ((ci->values_num != 1)
2912 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2914 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2915 "one string argument.");
2919 str = ci->values[0].value.string;
2920 if (strcasecmp ("Encrypt", str) == 0)
2921 *retval = SECURITY_LEVEL_ENCRYPT;
2922 else if (strcasecmp ("Sign", str) == 0)
2923 *retval = SECURITY_LEVEL_SIGN;
2924 else if (strcasecmp ("None", str) == 0)
2925 *retval = SECURITY_LEVEL_NONE;
2928 WARNING ("network plugin: Unknown security level: %s.", str);
2933 } /* }}} int network_config_set_security_level */
2934 #endif /* HAVE_LIBGCRYPT */
2936 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2942 if ((ci->values_num < 1) || (ci->values_num > 2)
2943 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2944 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2946 ERROR ("network plugin: The `%s' config option needs "
2947 "one or two string arguments.", ci->key);
2951 se = malloc (sizeof (*se));
2954 ERROR ("network plugin: malloc failed.");
2957 sockent_init (se, SOCKENT_TYPE_SERVER);
2959 se->node = strdup (ci->values[0].value.string);
2960 if (ci->values_num >= 2)
2961 se->service = strdup (ci->values[1].value.string);
2963 for (i = 0; i < ci->children_num; i++)
2965 oconfig_item_t *child = ci->children + i;
2968 if (strcasecmp ("AuthFile", child->key) == 0)
2969 network_config_set_string (child, &se->data.server.auth_file);
2970 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2971 network_config_set_security_level (child,
2972 &se->data.server.security_level);
2974 #endif /* HAVE_LIBGCRYPT */
2975 if (strcasecmp ("Interface", child->key) == 0)
2976 network_config_set_interface (child,
2980 WARNING ("network plugin: Option `%s' is not allowed here.",
2986 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
2987 && (se->data.server.auth_file == NULL))
2989 ERROR ("network plugin: A security level higher than `none' was "
2990 "requested, but no AuthFile option was given. Cowardly refusing to "
2991 "open this socket!");
2992 sockent_destroy (se);
2995 #endif /* HAVE_LIBGCRYPT */
2997 status = sockent_open (se);
3000 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
3001 sockent_destroy (se);
3005 status = sockent_add (se);
3008 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
3009 sockent_destroy (se);
3014 } /* }}} int network_config_add_listen */
3016 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
3022 if ((ci->values_num < 1) || (ci->values_num > 2)
3023 || (ci->values[0].type != OCONFIG_TYPE_STRING)
3024 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
3026 ERROR ("network plugin: The `%s' config option needs "
3027 "one or two string arguments.", ci->key);
3031 se = malloc (sizeof (*se));
3034 ERROR ("network plugin: malloc failed.");
3037 sockent_init (se, SOCKENT_TYPE_CLIENT);
3039 se->node = strdup (ci->values[0].value.string);
3040 if (ci->values_num >= 2)
3041 se->service = strdup (ci->values[1].value.string);
3043 for (i = 0; i < ci->children_num; i++)
3045 oconfig_item_t *child = ci->children + i;
3048 if (strcasecmp ("Username", child->key) == 0)
3049 network_config_set_string (child, &se->data.client.username);
3050 else if (strcasecmp ("Password", child->key) == 0)
3051 network_config_set_string (child, &se->data.client.password);
3052 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3053 network_config_set_security_level (child,
3054 &se->data.client.security_level);
3056 #endif /* HAVE_LIBGCRYPT */
3057 if (strcasecmp ("Interface", child->key) == 0)
3058 network_config_set_interface (child,
3062 WARNING ("network plugin: Option `%s' is not allowed here.",
3068 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3069 && ((se->data.client.username == NULL)
3070 || (se->data.client.password == NULL)))
3072 ERROR ("network plugin: A security level higher than `none' was "
3073 "requested, but no Username or Password option was given. "
3074 "Cowardly refusing to open this socket!");
3075 sockent_destroy (se);
3078 #endif /* HAVE_LIBGCRYPT */
3080 status = sockent_open (se);
3083 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3084 sockent_destroy (se);
3088 status = sockent_add (se);
3091 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3092 sockent_destroy (se);
3097 } /* }}} int network_config_add_server */
3099 static int network_config (oconfig_item_t *ci) /* {{{ */
3103 for (i = 0; i < ci->children_num; i++)
3105 oconfig_item_t *child = ci->children + i;
3107 if (strcasecmp ("Listen", child->key) == 0)
3108 network_config_add_listen (child);
3109 else if (strcasecmp ("Server", child->key) == 0)
3110 network_config_add_server (child);
3111 else if (strcasecmp ("TimeToLive", child->key) == 0)
3112 network_config_set_ttl (child);
3113 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3114 network_config_set_buffer_size (child);
3115 else if (strcasecmp ("Forward", child->key) == 0)
3116 network_config_set_boolean (child, &network_config_forward);
3117 else if (strcasecmp ("ReportStats", child->key) == 0)
3118 network_config_set_boolean (child, &network_config_stats);
3119 else if (strcasecmp ("CacheFlush", child->key) == 0)
3120 /* no op for backwards compatibility only */;
3123 WARNING ("network plugin: Option `%s' is not allowed here.",
3129 } /* }}} int network_config */
3131 static int network_notification (const notification_t *n,
3132 user_data_t __attribute__((unused)) *user_data)
3134 char buffer[network_config_packet_size];
3135 char *buffer_ptr = buffer;
3136 int buffer_free = sizeof (buffer);
3139 if (!check_send_notify_okay (n))
3142 memset (buffer, 0, sizeof (buffer));
3144 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
3145 (uint64_t) n->time);
3149 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3150 (uint64_t) n->severity);
3154 if (strlen (n->host) > 0)
3156 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3157 n->host, strlen (n->host));
3162 if (strlen (n->plugin) > 0)
3164 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3165 n->plugin, strlen (n->plugin));
3170 if (strlen (n->plugin_instance) > 0)
3172 status = write_part_string (&buffer_ptr, &buffer_free,
3173 TYPE_PLUGIN_INSTANCE,
3174 n->plugin_instance, strlen (n->plugin_instance));
3179 if (strlen (n->type) > 0)
3181 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3182 n->type, strlen (n->type));
3187 if (strlen (n->type_instance) > 0)
3189 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3190 n->type_instance, strlen (n->type_instance));
3195 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3196 n->message, strlen (n->message));
3200 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3203 } /* int network_notification */
3205 static int network_shutdown (void)
3209 /* Kill the listening thread */
3210 if (receive_thread_running != 0)
3212 INFO ("network plugin: Stopping receive thread.");
3213 pthread_kill (receive_thread_id, SIGTERM);
3214 pthread_join (receive_thread_id, NULL /* no return value */);
3215 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3216 receive_thread_running = 0;
3219 /* Shutdown the dispatching thread */
3220 if (dispatch_thread_running != 0)
3222 INFO ("network plugin: Stopping dispatch thread.");
3223 pthread_mutex_lock (&receive_list_lock);
3224 pthread_cond_broadcast (&receive_list_cond);
3225 pthread_mutex_unlock (&receive_list_lock);
3226 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3227 dispatch_thread_running = 0;
3230 sockent_destroy (listen_sockets);
3232 if (send_buffer_fill > 0)
3235 sfree (send_buffer);
3237 /* TODO: Close `sending_sockets' */
3239 plugin_unregister_config ("network");
3240 plugin_unregister_init ("network");
3241 plugin_unregister_write ("network");
3242 plugin_unregister_shutdown ("network");
3245 } /* int network_shutdown */
3247 static int network_stats_read (void) /* {{{ */
3249 uint64_t copy_octets_rx;
3250 uint64_t copy_octets_tx;
3251 uint64_t copy_packets_rx;
3252 uint64_t copy_packets_tx;
3253 uint64_t copy_values_dispatched;
3254 uint64_t copy_values_not_dispatched;
3255 uint64_t copy_values_sent;
3256 uint64_t copy_values_not_sent;
3257 uint64_t copy_receive_list_length;
3258 value_list_t vl = VALUE_LIST_INIT;
3261 copy_octets_rx = stats_octets_rx;
3262 copy_octets_tx = stats_octets_tx;
3263 copy_packets_rx = stats_packets_rx;
3264 copy_packets_tx = stats_packets_tx;
3265 copy_values_dispatched = stats_values_dispatched;
3266 copy_values_not_dispatched = stats_values_not_dispatched;
3267 copy_values_sent = stats_values_sent;
3268 copy_values_not_sent = stats_values_not_sent;
3269 copy_receive_list_length = receive_list_length;
3271 /* Initialize `vl' */
3275 vl.interval = interval_g;
3276 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3277 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3279 /* Octets received / sent */
3280 vl.values[0].counter = (counter_t) copy_octets_rx;
3281 vl.values[1].counter = (counter_t) copy_octets_tx;
3282 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3283 plugin_dispatch_values_secure (&vl);
3285 /* Packets received / send */
3286 vl.values[0].counter = (counter_t) copy_packets_rx;
3287 vl.values[1].counter = (counter_t) copy_packets_tx;
3288 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3289 plugin_dispatch_values_secure (&vl);
3291 /* Values (not) dispatched and (not) send */
3292 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3295 vl.values[0].derive = (derive_t) copy_values_dispatched;
3296 sstrncpy (vl.type_instance, "dispatch-accepted",
3297 sizeof (vl.type_instance));
3298 plugin_dispatch_values_secure (&vl);
3300 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3301 sstrncpy (vl.type_instance, "dispatch-rejected",
3302 sizeof (vl.type_instance));
3303 plugin_dispatch_values_secure (&vl);
3305 vl.values[0].derive = (derive_t) copy_values_sent;
3306 sstrncpy (vl.type_instance, "send-accepted",
3307 sizeof (vl.type_instance));
3308 plugin_dispatch_values_secure (&vl);
3310 vl.values[0].derive = (derive_t) copy_values_not_sent;
3311 sstrncpy (vl.type_instance, "send-rejected",
3312 sizeof (vl.type_instance));
3313 plugin_dispatch_values_secure (&vl);
3315 /* Receive queue length */
3316 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3317 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3318 vl.type_instance[0] = 0;
3319 plugin_dispatch_values_secure (&vl);
3322 } /* }}} int network_stats_read */
3324 static int network_init (void)
3326 static _Bool have_init = false;
3328 /* Check if we were already initialized. If so, just return - there's
3329 * nothing more to do (for now, that is). */
3335 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3336 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3337 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3340 if (network_config_stats != 0)
3341 plugin_register_read ("network", network_stats_read);
3343 plugin_register_shutdown ("network", network_shutdown);
3345 send_buffer = malloc (network_config_packet_size);
3346 if (send_buffer == NULL)
3348 ERROR ("network plugin: malloc failed.");
3351 network_init_buffer ();
3353 /* setup socket(s) and so on */
3354 if (sending_sockets != NULL)
3356 plugin_register_write ("network", network_write,
3357 /* user_data = */ NULL);
3358 plugin_register_notification ("network", network_notification,
3359 /* user_data = */ NULL);
3362 /* If no threads need to be started, return here. */
3363 if ((listen_sockets_num == 0)
3364 || ((dispatch_thread_running != 0)
3365 && (receive_thread_running != 0)))
3368 if (dispatch_thread_running == 0)
3371 status = pthread_create (&dispatch_thread_id,
3372 NULL /* no attributes */,
3374 NULL /* no argument */);
3378 ERROR ("network: pthread_create failed: %s",
3379 sstrerror (errno, errbuf,
3384 dispatch_thread_running = 1;
3388 if (receive_thread_running == 0)
3391 status = pthread_create (&receive_thread_id,
3392 NULL /* no attributes */,
3394 NULL /* no argument */);
3398 ERROR ("network: pthread_create failed: %s",
3399 sstrerror (errno, errbuf,
3404 receive_thread_running = 1;
3409 } /* int network_init */
3412 * The flush option of the network plugin cannot flush individual identifiers.
3413 * All the values are added to a buffer and sent when the buffer is full, the
3414 * requested value may or may not be in there, it's not worth finding out. We
3415 * just send the buffer if `flush' is called - if the requested value was in
3416 * there, good. If not, well, then there is nothing to flush.. -octo
3418 static int network_flush (int timeout,
3419 const char __attribute__((unused)) *identifier,
3420 user_data_t __attribute__((unused)) *user_data)
3422 pthread_mutex_lock (&send_buffer_lock);
3424 if (send_buffer_fill > 0)
3427 pthread_mutex_unlock (&send_buffer_lock);
3430 } /* int network_flush */
3432 void module_register (void)
3434 plugin_register_complex_config ("network", network_config);
3435 plugin_register_init ("network", network_init);
3436 plugin_register_flush ("network", network_flush,
3437 /* user_data = */ NULL);
3438 } /* void module_register */
3440 /* vim: set fdm=marker : */