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 static size_t network_config_packet_size = 1452;
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 derive_t stats_octets_rx = 0;
300 static derive_t stats_octets_tx = 0;
301 static derive_t stats_packets_rx = 0;
302 static derive_t stats_packets_tx = 0;
303 static derive_t stats_values_dispatched = 0;
304 static derive_t stats_values_not_dispatched = 0;
305 static derive_t stats_values_sent = 0;
306 static derive_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) /* {{{ */
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 int network_dispatch_values (value_list_t *vl, /* {{{ */
355 const char *username)
360 || (strlen (vl->host) <= 0)
361 || (strlen (vl->plugin) <= 0)
362 || (strlen (vl->type) <= 0))
365 if (!check_receive_okay (vl))
368 char name[6*DATA_MAX_NAME_LEN];
369 FORMAT_VL (name, sizeof (name), vl);
370 name[sizeof (name) - 1] = 0;
371 DEBUG ("network plugin: network_dispatch_values: "
372 "NOT dispatching %s.", name);
374 stats_values_not_dispatched++;
378 assert (vl->meta == NULL);
380 vl->meta = meta_data_create ();
381 if (vl->meta == NULL)
383 ERROR ("network plugin: meta_data_create failed.");
387 status = meta_data_add_boolean (vl->meta, "network:received", 1);
390 ERROR ("network plugin: meta_data_add_boolean failed.");
391 meta_data_destroy (vl->meta);
396 if (username != NULL)
398 status = meta_data_add_string (vl->meta, "network:username", username);
401 ERROR ("network plugin: meta_data_add_string failed.");
402 meta_data_destroy (vl->meta);
408 plugin_dispatch_values_secure (vl);
409 stats_values_dispatched++;
411 meta_data_destroy (vl->meta);
415 } /* }}} int network_dispatch_values */
418 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
419 const void *iv, size_t iv_size, const char *username)
422 gcry_cipher_hd_t *cyper_ptr;
423 unsigned char password_hash[32];
425 if (se->type == SOCKENT_TYPE_CLIENT)
427 cyper_ptr = &se->data.client.cypher;
428 memcpy (password_hash, se->data.client.password_hash,
429 sizeof (password_hash));
435 cyper_ptr = &se->data.server.cypher;
437 if (username == NULL)
440 secret = fbh_get (se->data.server.userdb, username);
444 gcry_md_hash_buffer (GCRY_MD_SHA256,
446 secret, strlen (secret));
451 if (*cyper_ptr == NULL)
453 err = gcry_cipher_open (cyper_ptr,
454 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
457 ERROR ("network plugin: gcry_cipher_open returned: %s",
458 gcry_strerror (err));
465 gcry_cipher_reset (*cyper_ptr);
467 assert (*cyper_ptr != NULL);
469 err = gcry_cipher_setkey (*cyper_ptr,
470 password_hash, sizeof (password_hash));
473 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
474 gcry_strerror (err));
475 gcry_cipher_close (*cyper_ptr);
480 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
483 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
484 gcry_strerror (err));
485 gcry_cipher_close (*cyper_ptr);
491 } /* }}} int network_get_aes256_cypher */
492 #endif /* HAVE_LIBGCRYPT */
494 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
495 const data_set_t *ds, const value_list_t *vl)
501 part_header_t pkg_ph;
502 uint16_t pkg_num_values;
503 uint8_t *pkg_values_types;
509 num_values = vl->values_len;
510 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
511 + (num_values * sizeof (uint8_t))
512 + (num_values * sizeof (value_t));
514 if (*ret_buffer_len < packet_len)
517 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
518 if (pkg_values_types == NULL)
520 ERROR ("network plugin: write_part_values: malloc failed.");
524 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
525 if (pkg_values == NULL)
527 free (pkg_values_types);
528 ERROR ("network plugin: write_part_values: malloc failed.");
532 pkg_ph.type = htons (TYPE_VALUES);
533 pkg_ph.length = htons (packet_len);
535 pkg_num_values = htons ((uint16_t) vl->values_len);
537 for (i = 0; i < num_values; i++)
539 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
540 switch (ds->ds[i].type)
542 case DS_TYPE_COUNTER:
543 pkg_values[i].counter = htonll (vl->values[i].counter);
547 pkg_values[i].gauge = htond (vl->values[i].gauge);
551 pkg_values[i].derive = htonll (vl->values[i].derive);
554 case DS_TYPE_ABSOLUTE:
555 pkg_values[i].absolute = htonll (vl->values[i].absolute);
559 free (pkg_values_types);
561 ERROR ("network plugin: write_part_values: "
562 "Unknown data source type: %i",
565 } /* switch (ds->ds[i].type) */
566 } /* for (num_values) */
569 * Use `memcpy' to write everything to the buffer, because the pointer
570 * may be unaligned and some architectures, such as SPARC, can't handle
573 packet_ptr = *ret_buffer;
575 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
576 offset += sizeof (pkg_ph);
577 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
578 offset += sizeof (pkg_num_values);
579 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
580 offset += num_values * sizeof (uint8_t);
581 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
582 offset += num_values * sizeof (value_t);
584 assert (offset == packet_len);
586 *ret_buffer = packet_ptr + packet_len;
587 *ret_buffer_len -= packet_len;
589 free (pkg_values_types);
593 } /* int write_part_values */
595 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
596 int type, uint64_t value)
601 part_header_t pkg_head;
606 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
608 if (*ret_buffer_len < packet_len)
611 pkg_head.type = htons (type);
612 pkg_head.length = htons (packet_len);
613 pkg_value = htonll (value);
615 packet_ptr = *ret_buffer;
617 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
618 offset += sizeof (pkg_head);
619 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
620 offset += sizeof (pkg_value);
622 assert (offset == packet_len);
624 *ret_buffer = packet_ptr + packet_len;
625 *ret_buffer_len -= packet_len;
628 } /* int write_part_number */
630 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
631 int type, const char *str, int str_len)
641 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
642 if (*ret_buffer_len < buffer_len)
645 pkg_type = htons (type);
646 pkg_length = htons (buffer_len);
648 buffer = *ret_buffer;
650 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
651 offset += sizeof (pkg_type);
652 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
653 offset += sizeof (pkg_length);
654 memcpy (buffer + offset, str, str_len);
656 memset (buffer + offset, '\0', 1);
659 assert (offset == buffer_len);
661 *ret_buffer = buffer + buffer_len;
662 *ret_buffer_len -= buffer_len;
665 } /* int write_part_string */
667 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
668 value_t **ret_values, int *ret_num_values)
670 char *buffer = *ret_buffer;
671 size_t buffer_len = *ret_buffer_len;
686 NOTICE ("network plugin: packet is too short: "
687 "buffer_len = %zu", buffer_len);
691 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
692 buffer += sizeof (tmp16);
693 pkg_type = ntohs (tmp16);
695 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
696 buffer += sizeof (tmp16);
697 pkg_length = ntohs (tmp16);
699 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
700 buffer += sizeof (tmp16);
701 pkg_numval = ntohs (tmp16);
703 assert (pkg_type == TYPE_VALUES);
705 exp_size = 3 * sizeof (uint16_t)
706 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
707 if ((buffer_len < 0) || (buffer_len < exp_size))
709 WARNING ("network plugin: parse_part_values: "
711 "Chunk of size %zu expected, "
712 "but buffer has only %zu bytes left.",
713 exp_size, buffer_len);
717 if (pkg_length != exp_size)
719 WARNING ("network plugin: parse_part_values: "
720 "Length and number of values "
721 "in the packet don't match.");
725 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
726 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
727 if ((pkg_types == NULL) || (pkg_values == NULL))
731 ERROR ("network plugin: parse_part_values: malloc failed.");
735 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
736 buffer += pkg_numval * sizeof (uint8_t);
737 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
738 buffer += pkg_numval * sizeof (value_t);
740 for (i = 0; i < pkg_numval; i++)
742 switch (pkg_types[i])
744 case DS_TYPE_COUNTER:
745 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
749 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
753 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
756 case DS_TYPE_ABSOLUTE:
757 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
761 NOTICE ("network plugin: parse_part_values: "
762 "Don't know how to handle data source type %"PRIu8,
767 } /* switch (pkg_types[i]) */
770 *ret_buffer = buffer;
771 *ret_buffer_len = buffer_len - pkg_length;
772 *ret_num_values = pkg_numval;
773 *ret_values = pkg_values;
778 } /* int parse_part_values */
780 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
783 char *buffer = *ret_buffer;
784 size_t buffer_len = *ret_buffer_len;
788 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
792 if ((buffer_len < 0) || ((size_t) buffer_len < exp_size))
794 WARNING ("network plugin: parse_part_number: "
796 "Chunk of size %zu expected, "
797 "but buffer has only %zu bytes left.",
798 exp_size, buffer_len);
802 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
803 buffer += sizeof (tmp16);
804 /* pkg_type = ntohs (tmp16); */
806 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
807 buffer += sizeof (tmp16);
808 pkg_length = ntohs (tmp16);
810 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
811 buffer += sizeof (tmp64);
812 *value = ntohll (tmp64);
814 *ret_buffer = buffer;
815 *ret_buffer_len = buffer_len - pkg_length;
818 } /* int parse_part_number */
820 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
821 char *output, int output_len)
823 char *buffer = *ret_buffer;
824 size_t buffer_len = *ret_buffer_len;
827 size_t header_size = 2 * sizeof (uint16_t);
831 if ((buffer_len < 0) || (buffer_len < header_size))
833 WARNING ("network plugin: parse_part_string: "
835 "Chunk of at least size %zu expected, "
836 "but buffer has only %zu bytes left.",
837 header_size, buffer_len);
841 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
842 buffer += sizeof (tmp16);
843 /* pkg_type = ntohs (tmp16); */
845 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
846 buffer += sizeof (tmp16);
847 pkg_length = ntohs (tmp16);
849 /* Check that packet fits in the input buffer */
850 if (pkg_length > buffer_len)
852 WARNING ("network plugin: parse_part_string: "
854 "Chunk of size %"PRIu16" received, "
855 "but buffer has only %zu bytes left.",
856 pkg_length, buffer_len);
860 /* Check that pkg_length is in the valid range */
861 if (pkg_length <= header_size)
863 WARNING ("network plugin: parse_part_string: "
865 "Header claims this packet is only %hu "
866 "bytes long.", pkg_length);
870 /* Check that the package data fits into the output buffer.
871 * The previous if-statement ensures that:
872 * `pkg_length > header_size' */
874 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
876 WARNING ("network plugin: parse_part_string: "
877 "Output buffer too small.");
881 /* All sanity checks successfull, let's copy the data over */
882 output_len = pkg_length - header_size;
883 memcpy ((void *) output, (void *) buffer, output_len);
884 buffer += output_len;
886 /* For some very weird reason '\0' doesn't do the trick on SPARC in
888 if (output[output_len - 1] != 0)
890 WARNING ("network plugin: parse_part_string: "
891 "Received string does not end "
892 "with a NULL-byte.");
896 *ret_buffer = buffer;
897 *ret_buffer_len = buffer_len - pkg_length;
900 } /* int parse_part_string */
902 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
903 * parse_packet and vice versa. */
904 #define PP_SIGNED 0x01
905 #define PP_ENCRYPTED 0x02
906 static int parse_packet (sockent_t *se,
907 void *buffer, size_t buffer_size, int flags,
908 const char *username);
910 #define BUFFER_READ(p,s) do { \
911 memcpy ((p), buffer + buffer_offset, (s)); \
912 buffer_offset += (s); \
916 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
917 void **ret_buffer, size_t *ret_buffer_len, int flags)
919 static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC;
923 size_t buffer_offset;
928 part_signature_sha256_t pss;
929 uint16_t pss_head_length;
930 char hash[sizeof (pss.hash)];
934 unsigned char *hash_ptr;
936 buffer = *ret_buffer;
937 buffer_len = *ret_buffer_len;
940 if (se->data.server.userdb == NULL)
942 c_complain (LOG_NOTICE, &complain_no_users,
943 "network plugin: Received signed network packet but can't verify it "
944 "because no user DB has been configured. Will accept it.");
948 /* Check if the buffer has enough data for this structure. */
949 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
952 /* Read type and length header */
953 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
954 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
955 pss_head_length = ntohs (pss.head.length);
957 /* Check if the `pss_head_length' is within bounds. */
958 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
959 || (pss_head_length > buffer_len))
961 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
966 BUFFER_READ (pss.hash, sizeof (pss.hash));
968 /* Calculate username length (without null byte) and allocate memory */
969 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
970 pss.username = malloc (username_len + 1);
971 if (pss.username == NULL)
974 /* Read the username */
975 BUFFER_READ (pss.username, username_len);
976 pss.username[username_len] = 0;
978 assert (buffer_offset == pss_head_length);
980 /* Query the password */
981 secret = fbh_get (se->data.server.userdb, pss.username);
984 ERROR ("network plugin: Unknown user: %s", pss.username);
985 sfree (pss.username);
989 /* Create a hash device and check the HMAC */
991 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
994 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
995 gcry_strerror (err));
997 sfree (pss.username);
1001 err = gcry_md_setkey (hd, secret, strlen (secret));
1004 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1007 sfree (pss.username);
1012 buffer + PART_SIGNATURE_SHA256_SIZE,
1013 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1014 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1015 if (hash_ptr == NULL)
1017 ERROR ("network plugin: gcry_md_read failed.");
1020 sfree (pss.username);
1023 memcpy (hash, hash_ptr, sizeof (hash));
1029 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1031 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1036 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1037 flags | PP_SIGNED, pss.username);
1041 sfree (pss.username);
1043 *ret_buffer = buffer + buffer_len;
1044 *ret_buffer_len = 0;
1047 } /* }}} int parse_part_sign_sha256 */
1048 /* #endif HAVE_LIBGCRYPT */
1050 #else /* if !HAVE_LIBGCRYPT */
1051 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1052 void **ret_buffer, size_t *ret_buffer_size, int flags)
1054 static int warning_has_been_printed = 0;
1058 size_t buffer_offset;
1061 part_signature_sha256_t pss;
1063 buffer = *ret_buffer;
1064 buffer_size = *ret_buffer_size;
1067 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1070 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1071 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1072 part_len = ntohs (pss.head.length);
1074 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1075 || (part_len > buffer_size))
1078 if (warning_has_been_printed == 0)
1080 WARNING ("network plugin: Received signed packet, but the network "
1081 "plugin was not linked with libgcrypt, so I cannot "
1082 "verify the signature. The packet will be accepted.");
1083 warning_has_been_printed = 1;
1086 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1087 /* username = */ NULL);
1089 *ret_buffer = buffer + buffer_size;
1090 *ret_buffer_size = 0;
1093 } /* }}} int parse_part_sign_sha256 */
1094 #endif /* !HAVE_LIBGCRYPT */
1097 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1098 void **ret_buffer, size_t *ret_buffer_len,
1101 char *buffer = *ret_buffer;
1102 size_t buffer_len = *ret_buffer_len;
1105 size_t buffer_offset;
1106 uint16_t username_len;
1107 part_encryption_aes256_t pea;
1108 unsigned char hash[sizeof (pea.hash)];
1110 gcry_cipher_hd_t cypher;
1113 /* Make sure at least the header if available. */
1114 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1116 NOTICE ("network plugin: parse_part_encr_aes256: "
1117 "Discarding short packet.");
1123 /* Copy the unencrypted information into `pea'. */
1124 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1125 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1127 /* Check the `part size'. */
1128 part_size = ntohs (pea.head.length);
1129 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1130 || (part_size > buffer_len))
1132 NOTICE ("network plugin: parse_part_encr_aes256: "
1133 "Discarding part with invalid size.");
1137 /* Read the username */
1138 BUFFER_READ (&username_len, sizeof (username_len));
1139 username_len = ntohs (username_len);
1141 if ((username_len <= 0)
1142 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1144 NOTICE ("network plugin: parse_part_encr_aes256: "
1145 "Discarding part with invalid username length.");
1149 assert (username_len > 0);
1150 pea.username = malloc (username_len + 1);
1151 if (pea.username == NULL)
1153 BUFFER_READ (pea.username, username_len);
1154 pea.username[username_len] = 0;
1156 /* Last but not least, the initialization vector */
1157 BUFFER_READ (pea.iv, sizeof (pea.iv));
1159 /* Make sure we are at the right position */
1160 assert (buffer_offset == (username_len +
1161 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1163 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1167 sfree (pea.username);
1171 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1172 assert (payload_len > 0);
1174 /* Decrypt the packet in-place */
1175 err = gcry_cipher_decrypt (cypher,
1176 buffer + buffer_offset,
1177 part_size - buffer_offset,
1178 /* in = */ NULL, /* in len = */ 0);
1181 sfree (pea.username);
1182 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1183 gcry_strerror (err));
1188 BUFFER_READ (pea.hash, sizeof (pea.hash));
1190 /* Make sure we're at the right position - again */
1191 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1192 assert (buffer_offset == (part_size - payload_len));
1194 /* Check hash sum */
1195 memset (hash, 0, sizeof (hash));
1196 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1197 buffer + buffer_offset, payload_len);
1198 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1200 sfree (pea.username);
1201 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1205 parse_packet (se, buffer + buffer_offset, payload_len,
1206 flags | PP_ENCRYPTED, pea.username);
1208 /* XXX: Free pea.username?!? */
1210 /* Update return values */
1211 *ret_buffer = buffer + part_size;
1212 *ret_buffer_len = buffer_len - part_size;
1214 sfree (pea.username);
1217 } /* }}} int parse_part_encr_aes256 */
1218 /* #endif HAVE_LIBGCRYPT */
1220 #else /* if !HAVE_LIBGCRYPT */
1221 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1222 void **ret_buffer, size_t *ret_buffer_size, int flags)
1224 static int warning_has_been_printed = 0;
1228 size_t buffer_offset;
1233 buffer = *ret_buffer;
1234 buffer_size = *ret_buffer_size;
1237 /* parse_packet assures this minimum size. */
1238 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1240 BUFFER_READ (&ph.type, sizeof (ph.type));
1241 BUFFER_READ (&ph.length, sizeof (ph.length));
1242 ph_length = ntohs (ph.length);
1244 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1245 || (ph_length > buffer_size))
1247 ERROR ("network plugin: AES-256 encrypted part "
1248 "with invalid length received.");
1252 if (warning_has_been_printed == 0)
1254 WARNING ("network plugin: Received encrypted packet, but the network "
1255 "plugin was not linked with libgcrypt, so I cannot "
1256 "decrypt it. The part will be discarded.");
1257 warning_has_been_printed = 1;
1260 *ret_buffer += ph_length;
1261 *ret_buffer_size -= ph_length;
1264 } /* }}} int parse_part_encr_aes256 */
1265 #endif /* !HAVE_LIBGCRYPT */
1269 static int parse_packet (sockent_t *se, /* {{{ */
1270 void *buffer, size_t buffer_size, int flags,
1271 const char *username)
1275 value_list_t vl = VALUE_LIST_INIT;
1279 int packet_was_signed = (flags & PP_SIGNED);
1280 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1281 int printed_ignore_warning = 0;
1282 #endif /* HAVE_LIBGCRYPT */
1285 memset (&vl, '\0', sizeof (vl));
1286 memset (&n, '\0', sizeof (n));
1289 while ((status == 0) && (0 < buffer_size)
1290 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1292 uint16_t pkg_length;
1295 memcpy ((void *) &pkg_type,
1298 memcpy ((void *) &pkg_length,
1299 (void *) (buffer + sizeof (pkg_type)),
1300 sizeof (pkg_length));
1302 pkg_length = ntohs (pkg_length);
1303 pkg_type = ntohs (pkg_type);
1305 if (pkg_length > buffer_size)
1307 /* Ensure that this loop terminates eventually */
1308 if (pkg_length < (2 * sizeof (uint16_t)))
1311 if (pkg_type == TYPE_ENCR_AES256)
1313 status = parse_part_encr_aes256 (se,
1314 &buffer, &buffer_size, flags);
1317 ERROR ("network plugin: Decrypting AES256 "
1319 "with status %i.", status);
1324 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1325 && (packet_was_encrypted == 0))
1327 if (printed_ignore_warning == 0)
1329 INFO ("network plugin: Unencrypted packet or "
1330 "part has been ignored.");
1331 printed_ignore_warning = 1;
1333 buffer = ((char *) buffer) + pkg_length;
1336 #endif /* HAVE_LIBGCRYPT */
1337 else if (pkg_type == TYPE_SIGN_SHA256)
1339 status = parse_part_sign_sha256 (se,
1340 &buffer, &buffer_size, flags);
1343 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1345 "with status %i.", status);
1350 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1351 && (packet_was_encrypted == 0)
1352 && (packet_was_signed == 0))
1354 if (printed_ignore_warning == 0)
1356 INFO ("network plugin: Unsigned packet or "
1357 "part has been ignored.");
1358 printed_ignore_warning = 1;
1360 buffer = ((char *) buffer) + pkg_length;
1363 #endif /* HAVE_LIBGCRYPT */
1364 else if (pkg_type == TYPE_VALUES)
1366 status = parse_part_values (&buffer, &buffer_size,
1367 &vl.values, &vl.values_len);
1371 network_dispatch_values (&vl, username);
1375 else if (pkg_type == TYPE_TIME)
1378 status = parse_part_number (&buffer, &buffer_size,
1382 vl.time = TIME_T_TO_CDTIME_T (tmp);
1383 n.time = TIME_T_TO_CDTIME_T (tmp);
1386 else if (pkg_type == TYPE_TIME_HR)
1389 status = parse_part_number (&buffer, &buffer_size,
1393 vl.time = (cdtime_t) tmp;
1394 n.time = (cdtime_t) tmp;
1397 else if (pkg_type == TYPE_INTERVAL)
1400 status = parse_part_number (&buffer, &buffer_size,
1403 vl.interval = TIME_T_TO_CDTIME_T (tmp);
1405 else if (pkg_type == TYPE_INTERVAL_HR)
1408 status = parse_part_number (&buffer, &buffer_size,
1411 vl.interval = (cdtime_t) tmp;
1413 else if (pkg_type == TYPE_HOST)
1415 status = parse_part_string (&buffer, &buffer_size,
1416 vl.host, sizeof (vl.host));
1418 sstrncpy (n.host, vl.host, sizeof (n.host));
1420 else if (pkg_type == TYPE_PLUGIN)
1422 status = parse_part_string (&buffer, &buffer_size,
1423 vl.plugin, sizeof (vl.plugin));
1425 sstrncpy (n.plugin, vl.plugin,
1428 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1430 status = parse_part_string (&buffer, &buffer_size,
1432 sizeof (vl.plugin_instance));
1434 sstrncpy (n.plugin_instance,
1436 sizeof (n.plugin_instance));
1438 else if (pkg_type == TYPE_TYPE)
1440 status = parse_part_string (&buffer, &buffer_size,
1441 vl.type, sizeof (vl.type));
1443 sstrncpy (n.type, vl.type, sizeof (n.type));
1445 else if (pkg_type == TYPE_TYPE_INSTANCE)
1447 status = parse_part_string (&buffer, &buffer_size,
1449 sizeof (vl.type_instance));
1451 sstrncpy (n.type_instance, vl.type_instance,
1452 sizeof (n.type_instance));
1454 else if (pkg_type == TYPE_MESSAGE)
1456 status = parse_part_string (&buffer, &buffer_size,
1457 n.message, sizeof (n.message));
1463 else if ((n.severity != NOTIF_FAILURE)
1464 && (n.severity != NOTIF_WARNING)
1465 && (n.severity != NOTIF_OKAY))
1467 INFO ("network plugin: "
1468 "Ignoring notification with "
1469 "unknown severity %i.",
1472 else if (n.time <= 0)
1474 INFO ("network plugin: "
1475 "Ignoring notification with "
1478 else if (strlen (n.message) <= 0)
1480 INFO ("network plugin: "
1481 "Ignoring notification with "
1482 "an empty message.");
1486 plugin_dispatch_notification (&n);
1489 else if (pkg_type == TYPE_SEVERITY)
1492 status = parse_part_number (&buffer, &buffer_size,
1495 n.severity = (int) tmp;
1499 DEBUG ("network plugin: parse_packet: Unknown part"
1500 " type: 0x%04hx", pkg_type);
1501 buffer = ((char *) buffer) + pkg_length;
1503 } /* while (buffer_size > sizeof (part_header_t)) */
1505 if (status == 0 && buffer_size > 0)
1506 WARNING ("network plugin: parse_packet: Received truncated "
1507 "packet, try increasing `MaxPacketSize'");
1510 } /* }}} int parse_packet */
1512 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1521 sfree (sec->username);
1522 sfree (sec->password);
1523 if (sec->cypher != NULL)
1524 gcry_cipher_close (sec->cypher);
1526 } /* }}} void free_sockent_client */
1528 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1532 for (i = 0; i < ses->fd_num; i++)
1534 if (ses->fd[i] >= 0)
1543 sfree (ses->auth_file);
1544 fbh_destroy (ses->userdb);
1545 if (ses->cypher != NULL)
1546 gcry_cipher_close (ses->cypher);
1548 } /* }}} void free_sockent_server */
1550 static void sockent_destroy (sockent_t *se) /* {{{ */
1554 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1561 sfree (se->service);
1563 if (se->type == SOCKENT_TYPE_CLIENT)
1564 free_sockent_client (&se->data.client);
1566 free_sockent_server (&se->data.server);
1571 } /* }}} void sockent_destroy */
1574 * int network_set_ttl
1576 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1577 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1579 * The `struct addrinfo' is used to destinguish between unicast and multicast
1582 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1584 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1585 network_config_ttl);
1587 assert (se->type == SOCKENT_TYPE_CLIENT);
1589 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1592 if (ai->ai_family == AF_INET)
1594 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1597 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1598 optname = IP_MULTICAST_TTL;
1602 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1603 &network_config_ttl,
1604 sizeof (network_config_ttl)) != 0)
1607 ERROR ("setsockopt: %s",
1608 sstrerror (errno, errbuf, sizeof (errbuf)));
1612 else if (ai->ai_family == AF_INET6)
1614 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1615 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1618 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1619 optname = IPV6_MULTICAST_HOPS;
1621 optname = IPV6_UNICAST_HOPS;
1623 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1624 &network_config_ttl,
1625 sizeof (network_config_ttl)) != 0)
1628 ERROR ("setsockopt: %s",
1629 sstrerror (errno, errbuf,
1636 } /* int network_set_ttl */
1638 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1640 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1643 assert (se->type == SOCKENT_TYPE_CLIENT);
1645 if (ai->ai_family == AF_INET)
1647 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1649 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1651 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1652 /* If possible, use the "ip_mreqn" structure which has
1653 * an "interface index" member. Using the interface
1654 * index is preferred here, because of its similarity
1655 * to the way IPv6 handles this. Unfortunately, it
1656 * appears not to be portable. */
1657 struct ip_mreqn mreq;
1659 memset (&mreq, 0, sizeof (mreq));
1660 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1661 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1662 mreq.imr_ifindex = se->interface;
1664 struct ip_mreq mreq;
1666 memset (&mreq, 0, sizeof (mreq));
1667 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1668 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1671 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1672 &mreq, sizeof (mreq)) != 0)
1675 ERROR ("setsockopt: %s",
1676 sstrerror (errno, errbuf, sizeof (errbuf)));
1683 else if (ai->ai_family == AF_INET6)
1685 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1687 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1689 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1691 sizeof (se->interface)) != 0)
1694 ERROR ("setsockopt: %s",
1695 sstrerror (errno, errbuf,
1704 /* else: Not a multicast interface. */
1705 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1706 if (se->interface != 0)
1708 char interface_name[IFNAMSIZ];
1710 if (if_indextoname (se->interface, interface_name) == NULL)
1713 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1715 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1717 sizeof(interface_name)) == -1 )
1720 ERROR ("setsockopt: %s",
1721 sstrerror (errno, errbuf, sizeof (errbuf)));
1725 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1728 WARNING ("network plugin: Cannot set the interface on a unicast "
1730 # if !defined(SO_BINDTODEVICE)
1731 "the the \"SO_BINDTODEVICE\" socket option "
1733 "the \"if_indextoname\" function "
1735 "is not available on your system.");
1739 } /* }}} network_set_interface */
1741 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1746 /* allow multiple sockets to use the same PORT number */
1747 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1748 &yes, sizeof(yes)) == -1) {
1750 ERROR ("setsockopt: %s",
1751 sstrerror (errno, errbuf, sizeof (errbuf)));
1755 DEBUG ("fd = %i; calling `bind'", fd);
1757 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1761 sstrerror (errno, errbuf, sizeof (errbuf)));
1765 if (ai->ai_family == AF_INET)
1767 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1768 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1770 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1771 struct ip_mreqn mreq;
1773 struct ip_mreq mreq;
1776 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1778 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1779 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1780 /* Set the interface using the interface index if
1781 * possible (available). Unfortunately, the struct
1782 * ip_mreqn is not portable. */
1783 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1784 mreq.imr_ifindex = interface_idx;
1786 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1789 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1790 &loop, sizeof (loop)) == -1)
1793 ERROR ("setsockopt: %s",
1794 sstrerror (errno, errbuf,
1799 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1800 &mreq, sizeof (mreq)) == -1)
1803 ERROR ("setsockopt: %s",
1804 sstrerror (errno, errbuf,
1812 else if (ai->ai_family == AF_INET6)
1814 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1815 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1816 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1818 struct ipv6_mreq mreq;
1820 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1822 memcpy (&mreq.ipv6mr_multiaddr,
1824 sizeof (addr->sin6_addr));
1826 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1827 * ipv6mr_interface may be set to zeroes to
1828 * choose the default multicast interface or to
1829 * the index of a particular multicast-capable
1830 * interface if the host is multihomed.
1831 * Membership is associ-associated with a
1832 * single interface; programs running on
1833 * multihomed hosts may need to join the same
1834 * group on more than one interface.*/
1835 mreq.ipv6mr_interface = interface_idx;
1837 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1838 &loop, sizeof (loop)) == -1)
1841 ERROR ("setsockopt: %s",
1842 sstrerror (errno, errbuf,
1847 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1848 &mreq, sizeof (mreq)) == -1)
1851 ERROR ("setsockopt: %s",
1852 sstrerror (errno, errbuf,
1861 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1862 /* if a specific interface was set, bind the socket to it. But to avoid
1863 * possible problems with multicast routing, only do that for non-multicast
1865 if (interface_idx != 0)
1867 char interface_name[IFNAMSIZ];
1869 if (if_indextoname (interface_idx, interface_name) == NULL)
1872 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1874 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1876 sizeof(interface_name)) == -1 )
1879 ERROR ("setsockopt: %s",
1880 sstrerror (errno, errbuf, sizeof (errbuf)));
1884 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1887 } /* int network_bind_socket */
1889 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1890 * or `SOCKENT_TYPE_SERVER' */
1891 static int sockent_init (sockent_t *se, int type) /* {{{ */
1896 memset (se, 0, sizeof (*se));
1898 se->type = SOCKENT_TYPE_CLIENT;
1904 if (type == SOCKENT_TYPE_SERVER)
1906 se->type = SOCKENT_TYPE_SERVER;
1907 se->data.server.fd = NULL;
1909 se->data.server.security_level = SECURITY_LEVEL_NONE;
1910 se->data.server.auth_file = NULL;
1911 se->data.server.userdb = NULL;
1912 se->data.server.cypher = NULL;
1917 se->data.client.fd = -1;
1918 se->data.client.addr = NULL;
1920 se->data.client.security_level = SECURITY_LEVEL_NONE;
1921 se->data.client.username = NULL;
1922 se->data.client.password = NULL;
1923 se->data.client.cypher = NULL;
1928 } /* }}} int sockent_init */
1930 /* Open the file descriptors for a initialized sockent structure. */
1931 static int sockent_open (sockent_t *se) /* {{{ */
1933 struct addrinfo ai_hints;
1934 struct addrinfo *ai_list, *ai_ptr;
1938 const char *service;
1943 /* Set up the security structures. */
1944 #if HAVE_LIBGCRYPT /* {{{ */
1945 if (se->type == SOCKENT_TYPE_CLIENT)
1947 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
1949 if ((se->data.client.username == NULL)
1950 || (se->data.client.password == NULL))
1952 ERROR ("network plugin: Client socket with "
1953 "security requested, but no "
1954 "credentials are configured.");
1957 gcry_md_hash_buffer (GCRY_MD_SHA256,
1958 se->data.client.password_hash,
1959 se->data.client.password,
1960 strlen (se->data.client.password));
1963 else /* (se->type == SOCKENT_TYPE_SERVER) */
1965 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1967 if (se->data.server.auth_file == NULL)
1969 ERROR ("network plugin: Server socket with "
1970 "security requested, but no "
1971 "password file is configured.");
1975 if (se->data.server.auth_file != NULL)
1977 se->data.server.userdb = fbh_create (se->data.server.auth_file);
1978 if (se->data.server.userdb == NULL)
1980 ERROR ("network plugin: Reading password file "
1982 se->data.server.auth_file);
1983 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1988 #endif /* }}} HAVE_LIBGCRYPT */
1991 service = se->service;
1993 if (service == NULL)
1994 service = NET_DEFAULT_PORT;
1996 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
1999 memset (&ai_hints, 0, sizeof (ai_hints));
2000 ai_hints.ai_flags = 0;
2002 ai_hints.ai_flags |= AI_PASSIVE;
2004 #ifdef AI_ADDRCONFIG
2005 ai_hints.ai_flags |= AI_ADDRCONFIG;
2007 ai_hints.ai_family = AF_UNSPEC;
2008 ai_hints.ai_socktype = SOCK_DGRAM;
2009 ai_hints.ai_protocol = IPPROTO_UDP;
2011 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
2014 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
2015 (se->node == NULL) ? "(null)" : se->node,
2016 (se->service == NULL) ? "(null)" : se->service,
2017 gai_strerror (ai_return));
2021 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2025 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2029 tmp = realloc (se->data.server.fd,
2030 sizeof (*tmp) * (se->data.server.fd_num + 1));
2033 ERROR ("network plugin: realloc failed.");
2036 se->data.server.fd = tmp;
2037 tmp = se->data.server.fd + se->data.server.fd_num;
2039 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2040 ai_ptr->ai_protocol);
2044 ERROR ("network plugin: socket(2) failed: %s",
2045 sstrerror (errno, errbuf,
2050 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2058 se->data.server.fd_num++;
2060 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2061 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2063 se->data.client.fd = socket (ai_ptr->ai_family,
2064 ai_ptr->ai_socktype,
2065 ai_ptr->ai_protocol);
2066 if (se->data.client.fd < 0)
2069 ERROR ("network plugin: socket(2) failed: %s",
2070 sstrerror (errno, errbuf,
2075 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2076 if (se->data.client.addr == NULL)
2078 ERROR ("network plugin: malloc failed.");
2079 close (se->data.client.fd);
2080 se->data.client.fd = -1;
2084 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2085 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2086 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2087 se->data.client.addrlen = ai_ptr->ai_addrlen;
2089 network_set_ttl (se, ai_ptr);
2090 network_set_interface (se, ai_ptr);
2092 /* We don't open more than one write-socket per
2093 * node/service pair.. */
2095 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2096 } /* for (ai_list) */
2098 freeaddrinfo (ai_list);
2100 /* Check if all went well. */
2101 if (se->type == SOCKENT_TYPE_SERVER)
2103 if (se->data.server.fd_num <= 0)
2106 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2108 if (se->data.client.fd < 0)
2113 } /* }}} int sockent_open */
2115 /* Add a sockent to the global list of sockets */
2116 static int sockent_add (sockent_t *se) /* {{{ */
2118 sockent_t *last_ptr;
2123 if (se->type == SOCKENT_TYPE_SERVER)
2128 tmp = realloc (listen_sockets_pollfd,
2129 sizeof (*tmp) * (listen_sockets_num
2130 + se->data.server.fd_num));
2133 ERROR ("network plugin: realloc failed.");
2136 listen_sockets_pollfd = tmp;
2137 tmp = listen_sockets_pollfd + listen_sockets_num;
2139 for (i = 0; i < se->data.server.fd_num; i++)
2141 memset (tmp + i, 0, sizeof (*tmp));
2142 tmp[i].fd = se->data.server.fd[i];
2143 tmp[i].events = POLLIN | POLLPRI;
2147 listen_sockets_num += se->data.server.fd_num;
2149 if (listen_sockets == NULL)
2151 listen_sockets = se;
2154 last_ptr = listen_sockets;
2156 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2158 if (sending_sockets == NULL)
2160 sending_sockets = se;
2163 last_ptr = sending_sockets;
2166 while (last_ptr->next != NULL)
2167 last_ptr = last_ptr->next;
2168 last_ptr->next = se;
2171 } /* }}} int sockent_add */
2173 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2177 receive_list_entry_t *ent;
2180 /* Lock and wait for more data to come in */
2181 pthread_mutex_lock (&receive_list_lock);
2182 while ((listen_loop == 0)
2183 && (receive_list_head == NULL))
2184 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2186 /* Remove the head entry and unlock */
2187 ent = receive_list_head;
2189 receive_list_head = ent->next;
2190 receive_list_length--;
2191 pthread_mutex_unlock (&receive_list_lock);
2193 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2194 * because we dispatch all missing packets before shutting down. */
2198 /* Look for the correct `sockent_t' */
2199 se = listen_sockets;
2204 for (i = 0; i < se->data.server.fd_num; i++)
2205 if (se->data.server.fd[i] == ent->fd)
2208 if (i < se->data.server.fd_num)
2216 ERROR ("network plugin: Got packet from FD %i, but can't "
2217 "find an appropriate socket entry.",
2224 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2225 /* username = */ NULL);
2231 } /* }}} void *dispatch_thread */
2233 static int network_receive (void) /* {{{ */
2235 char buffer[network_config_packet_size];
2241 receive_list_entry_t *private_list_head;
2242 receive_list_entry_t *private_list_tail;
2243 uint64_t private_list_length;
2245 assert (listen_sockets_num > 0);
2247 private_list_head = NULL;
2248 private_list_tail = NULL;
2249 private_list_length = 0;
2251 while (listen_loop == 0)
2253 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2260 ERROR ("poll failed: %s",
2261 sstrerror (errno, errbuf, sizeof (errbuf)));
2265 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2267 receive_list_entry_t *ent;
2269 if ((listen_sockets_pollfd[i].revents
2270 & (POLLIN | POLLPRI)) == 0)
2274 buffer_len = recv (listen_sockets_pollfd[i].fd,
2275 buffer, sizeof (buffer),
2280 ERROR ("recv failed: %s",
2281 sstrerror (errno, errbuf,
2286 stats_octets_rx += ((uint64_t) buffer_len);
2289 /* TODO: Possible performance enhancement: Do not free
2290 * these entries in the dispatch thread but put them in
2291 * another list, so we don't have to allocate more and
2292 * more of these structures. */
2293 ent = malloc (sizeof (receive_list_entry_t));
2296 ERROR ("network plugin: malloc failed.");
2299 memset (ent, 0, sizeof (receive_list_entry_t));
2300 ent->data = malloc (network_config_packet_size);
2301 if (ent->data == NULL)
2304 ERROR ("network plugin: malloc failed.");
2307 ent->fd = listen_sockets_pollfd[i].fd;
2310 memcpy (ent->data, buffer, buffer_len);
2311 ent->data_len = buffer_len;
2313 if (private_list_head == NULL)
2314 private_list_head = ent;
2316 private_list_tail->next = ent;
2317 private_list_tail = ent;
2318 private_list_length++;
2320 /* Do not block here. Blocking here has led to
2321 * insufficient performance in the past. */
2322 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2324 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2325 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2327 if (receive_list_head == NULL)
2328 receive_list_head = private_list_head;
2330 receive_list_tail->next = private_list_head;
2331 receive_list_tail = private_list_tail;
2332 receive_list_length += private_list_length;
2334 pthread_cond_signal (&receive_list_cond);
2335 pthread_mutex_unlock (&receive_list_lock);
2337 private_list_head = NULL;
2338 private_list_tail = NULL;
2339 private_list_length = 0;
2341 } /* for (listen_sockets_pollfd) */
2342 } /* while (listen_loop == 0) */
2344 /* Make sure everything is dispatched before exiting. */
2345 if (private_list_head != NULL)
2347 pthread_mutex_lock (&receive_list_lock);
2349 if (receive_list_head == NULL)
2350 receive_list_head = private_list_head;
2352 receive_list_tail->next = private_list_head;
2353 receive_list_tail = private_list_tail;
2354 receive_list_length += private_list_length;
2356 private_list_head = NULL;
2357 private_list_tail = NULL;
2358 private_list_length = 0;
2360 pthread_cond_signal (&receive_list_cond);
2361 pthread_mutex_unlock (&receive_list_lock);
2365 } /* }}} int network_receive */
2367 static void *receive_thread (void __attribute__((unused)) *arg)
2369 return (network_receive () ? (void *) 1 : (void *) 0);
2370 } /* void *receive_thread */
2372 static void network_init_buffer (void)
2374 memset (send_buffer, 0, network_config_packet_size);
2375 send_buffer_ptr = send_buffer;
2376 send_buffer_fill = 0;
2378 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2379 } /* int network_init_buffer */
2381 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2382 const char *buffer, size_t buffer_size)
2388 status = sendto (se->data.client.fd, buffer, buffer_size,
2390 (struct sockaddr *) se->data.client.addr,
2391 se->data.client.addrlen);
2397 ERROR ("network plugin: sendto failed: %s",
2398 sstrerror (errno, errbuf,
2405 } /* }}} void networt_send_buffer_plain */
2408 #define BUFFER_ADD(p,s) do { \
2409 memcpy (buffer + buffer_offset, (p), (s)); \
2410 buffer_offset += (s); \
2413 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2414 const char *in_buffer, size_t in_buffer_size)
2416 part_signature_sha256_t ps;
2417 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2418 size_t buffer_offset;
2419 size_t username_len;
2423 unsigned char *hash;
2426 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2429 ERROR ("network plugin: Creating HMAC object failed: %s",
2430 gcry_strerror (err));
2434 err = gcry_md_setkey (hd, se->data.client.password,
2435 strlen (se->data.client.password));
2438 ERROR ("network plugin: gcry_md_setkey failed: %s",
2439 gcry_strerror (err));
2444 username_len = strlen (se->data.client.username);
2445 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2447 ERROR ("network plugin: Username too long: %s",
2448 se->data.client.username);
2452 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2453 se->data.client.username, username_len);
2454 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2455 in_buffer, in_buffer_size);
2457 /* Initialize the `ps' structure. */
2458 memset (&ps, 0, sizeof (ps));
2459 ps.head.type = htons (TYPE_SIGN_SHA256);
2460 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2462 /* Calculate the hash value. */
2463 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2464 username_len + in_buffer_size);
2465 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2468 ERROR ("network plugin: gcry_md_read failed.");
2472 memcpy (ps.hash, hash, sizeof (ps.hash));
2474 /* Add the header */
2477 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2478 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2479 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2481 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2486 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2487 networt_send_buffer_plain (se, buffer, buffer_offset);
2488 } /* }}} void networt_send_buffer_signed */
2490 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2491 const char *in_buffer, size_t in_buffer_size)
2493 part_encryption_aes256_t pea;
2494 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2496 size_t buffer_offset;
2498 size_t username_len;
2500 gcry_cipher_hd_t cypher;
2502 /* Initialize the header fields */
2503 memset (&pea, 0, sizeof (pea));
2504 pea.head.type = htons (TYPE_ENCR_AES256);
2506 pea.username = se->data.client.username;
2508 username_len = strlen (pea.username);
2509 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2511 ERROR ("network plugin: Username too long: %s", pea.username);
2515 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2516 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2517 - sizeof (pea.hash);
2519 assert (buffer_size <= sizeof (buffer));
2520 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2521 "buffer_size = %zu;", buffer_size);
2523 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2524 + username_len + in_buffer_size));
2525 pea.username_length = htons ((uint16_t) username_len);
2527 /* Chose a random initialization vector. */
2528 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2530 /* Create hash of the payload */
2531 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2533 /* Initialize the buffer */
2535 memset (buffer, 0, sizeof (buffer));
2538 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2539 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2540 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2541 BUFFER_ADD (pea.username, username_len);
2542 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2543 assert (buffer_offset == header_size);
2544 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2545 BUFFER_ADD (in_buffer, in_buffer_size);
2547 assert (buffer_offset == buffer_size);
2549 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2550 se->data.client.password);
2554 /* Encrypt the buffer in-place */
2555 err = gcry_cipher_encrypt (cypher,
2556 buffer + header_size,
2557 buffer_size - header_size,
2558 /* in = */ NULL, /* in len = */ 0);
2561 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2562 gcry_strerror (err));
2566 /* Send it out without further modifications */
2567 networt_send_buffer_plain (se, buffer, buffer_size);
2568 } /* }}} void networt_send_buffer_encrypted */
2570 #endif /* HAVE_LIBGCRYPT */
2572 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2576 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2578 for (se = sending_sockets; se != NULL; se = se->next)
2581 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2582 networt_send_buffer_encrypted (se, buffer, buffer_len);
2583 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2584 networt_send_buffer_signed (se, buffer, buffer_len);
2585 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2586 #endif /* HAVE_LIBGCRYPT */
2587 networt_send_buffer_plain (se, buffer, buffer_len);
2588 } /* for (sending_sockets) */
2589 } /* }}} void network_send_buffer */
2591 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2592 value_list_t *vl_def,
2593 const data_set_t *ds, const value_list_t *vl)
2595 char *buffer_orig = buffer;
2597 if (strcmp (vl_def->host, vl->host) != 0)
2599 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2600 vl->host, strlen (vl->host)) != 0)
2602 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2605 if (vl_def->time != vl->time)
2607 if (write_part_number (&buffer, &buffer_size, TYPE_TIME_HR,
2608 (uint64_t) vl->time))
2610 vl_def->time = vl->time;
2613 if (vl_def->interval != vl->interval)
2615 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL_HR,
2616 (uint64_t) vl->interval))
2618 vl_def->interval = vl->interval;
2621 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2623 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2624 vl->plugin, strlen (vl->plugin)) != 0)
2626 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2629 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2631 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2632 vl->plugin_instance,
2633 strlen (vl->plugin_instance)) != 0)
2635 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2638 if (strcmp (vl_def->type, vl->type) != 0)
2640 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2641 vl->type, strlen (vl->type)) != 0)
2643 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2646 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2648 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2650 strlen (vl->type_instance)) != 0)
2652 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2655 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2658 return (buffer - buffer_orig);
2659 } /* }}} int add_to_buffer */
2661 static void flush_buffer (void)
2663 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2666 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2668 stats_octets_tx += ((uint64_t) send_buffer_fill);
2671 network_init_buffer ();
2674 static int network_write (const data_set_t *ds, const value_list_t *vl,
2675 user_data_t __attribute__((unused)) *user_data)
2679 if (!check_send_okay (vl))
2682 char name[6*DATA_MAX_NAME_LEN];
2683 FORMAT_VL (name, sizeof (name), vl);
2684 name[sizeof (name) - 1] = 0;
2685 DEBUG ("network plugin: network_write: "
2686 "NOT sending %s.", name);
2688 /* Counter is not protected by another lock and may be reached by
2689 * multiple threads */
2690 pthread_mutex_lock (&stats_lock);
2691 stats_values_not_sent++;
2692 pthread_mutex_unlock (&stats_lock);
2696 uc_meta_data_add_unsigned_int (vl,
2697 "network:time_sent", (uint64_t) vl->time);
2699 pthread_mutex_lock (&send_buffer_lock);
2701 status = add_to_buffer (send_buffer_ptr,
2702 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2707 /* status == bytes added to the buffer */
2708 send_buffer_fill += status;
2709 send_buffer_ptr += status;
2711 stats_values_sent++;
2717 status = add_to_buffer (send_buffer_ptr,
2718 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2724 send_buffer_fill += status;
2725 send_buffer_ptr += status;
2727 stats_values_sent++;
2733 ERROR ("network plugin: Unable to append to the "
2734 "buffer for some weird reason");
2736 else if ((network_config_packet_size - send_buffer_fill) < 15)
2741 pthread_mutex_unlock (&send_buffer_lock);
2743 return ((status < 0) ? -1 : 0);
2744 } /* int network_write */
2746 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2749 if ((ci->values_num != 1)
2750 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2751 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2753 ERROR ("network plugin: The `%s' config option needs "
2754 "exactly one boolean argument.", ci->key);
2758 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2760 if (ci->values[0].value.boolean)
2767 char *str = ci->values[0].value.string;
2771 else if (IS_FALSE (str))
2775 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2776 "option as boolean value.",
2783 } /* }}} int network_config_set_boolean */
2785 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2788 if ((ci->values_num != 1)
2789 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2791 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2792 "one numeric argument.");
2796 tmp = (int) ci->values[0].value.number;
2797 if ((tmp > 0) && (tmp <= 255))
2798 network_config_ttl = tmp;
2801 } /* }}} int network_config_set_ttl */
2803 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2806 if ((ci->values_num != 1)
2807 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2809 WARNING ("network plugin: The `Interface' config option needs exactly "
2810 "one string argument.");
2814 if (interface == NULL)
2817 *interface = if_nametoindex (ci->values[0].value.string);
2820 } /* }}} int network_config_set_interface */
2822 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2825 if ((ci->values_num != 1)
2826 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2828 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2829 "one numeric argument.");
2833 tmp = (int) ci->values[0].value.number;
2834 if ((tmp >= 1024) && (tmp <= 65535))
2835 network_config_packet_size = tmp;
2838 } /* }}} int network_config_set_buffer_size */
2841 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2845 if ((ci->values_num != 1)
2846 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2848 WARNING ("network plugin: The `%s' config option needs exactly "
2849 "one string argument.", ci->key);
2853 tmp = strdup (ci->values[0].value.string);
2857 sfree (*ret_string);
2861 } /* }}} int network_config_set_string */
2862 #endif /* HAVE_LIBGCRYPT */
2865 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2869 if ((ci->values_num != 1)
2870 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2872 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2873 "one string argument.");
2877 str = ci->values[0].value.string;
2878 if (strcasecmp ("Encrypt", str) == 0)
2879 *retval = SECURITY_LEVEL_ENCRYPT;
2880 else if (strcasecmp ("Sign", str) == 0)
2881 *retval = SECURITY_LEVEL_SIGN;
2882 else if (strcasecmp ("None", str) == 0)
2883 *retval = SECURITY_LEVEL_NONE;
2886 WARNING ("network plugin: Unknown security level: %s.", str);
2891 } /* }}} int network_config_set_security_level */
2892 #endif /* HAVE_LIBGCRYPT */
2894 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2900 if ((ci->values_num < 1) || (ci->values_num > 2)
2901 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2902 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2904 ERROR ("network plugin: The `%s' config option needs "
2905 "one or two string arguments.", ci->key);
2909 se = malloc (sizeof (*se));
2912 ERROR ("network plugin: malloc failed.");
2915 sockent_init (se, SOCKENT_TYPE_SERVER);
2917 se->node = strdup (ci->values[0].value.string);
2918 if (ci->values_num >= 2)
2919 se->service = strdup (ci->values[1].value.string);
2921 for (i = 0; i < ci->children_num; i++)
2923 oconfig_item_t *child = ci->children + i;
2926 if (strcasecmp ("AuthFile", child->key) == 0)
2927 network_config_set_string (child, &se->data.server.auth_file);
2928 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2929 network_config_set_security_level (child,
2930 &se->data.server.security_level);
2932 #endif /* HAVE_LIBGCRYPT */
2933 if (strcasecmp ("Interface", child->key) == 0)
2934 network_config_set_interface (child,
2938 WARNING ("network plugin: Option `%s' is not allowed here.",
2944 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
2945 && (se->data.server.auth_file == NULL))
2947 ERROR ("network plugin: A security level higher than `none' was "
2948 "requested, but no AuthFile option was given. Cowardly refusing to "
2949 "open this socket!");
2950 sockent_destroy (se);
2953 #endif /* HAVE_LIBGCRYPT */
2955 status = sockent_open (se);
2958 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
2959 sockent_destroy (se);
2963 status = sockent_add (se);
2966 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
2967 sockent_destroy (se);
2972 } /* }}} int network_config_add_listen */
2974 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
2980 if ((ci->values_num < 1) || (ci->values_num > 2)
2981 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2982 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2984 ERROR ("network plugin: The `%s' config option needs "
2985 "one or two string arguments.", ci->key);
2989 se = malloc (sizeof (*se));
2992 ERROR ("network plugin: malloc failed.");
2995 sockent_init (se, SOCKENT_TYPE_CLIENT);
2997 se->node = strdup (ci->values[0].value.string);
2998 if (ci->values_num >= 2)
2999 se->service = strdup (ci->values[1].value.string);
3001 for (i = 0; i < ci->children_num; i++)
3003 oconfig_item_t *child = ci->children + i;
3006 if (strcasecmp ("Username", child->key) == 0)
3007 network_config_set_string (child, &se->data.client.username);
3008 else if (strcasecmp ("Password", child->key) == 0)
3009 network_config_set_string (child, &se->data.client.password);
3010 else if (strcasecmp ("SecurityLevel", child->key) == 0)
3011 network_config_set_security_level (child,
3012 &se->data.client.security_level);
3014 #endif /* HAVE_LIBGCRYPT */
3015 if (strcasecmp ("Interface", child->key) == 0)
3016 network_config_set_interface (child,
3020 WARNING ("network plugin: Option `%s' is not allowed here.",
3026 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3027 && ((se->data.client.username == NULL)
3028 || (se->data.client.password == NULL)))
3030 ERROR ("network plugin: A security level higher than `none' was "
3031 "requested, but no Username or Password option was given. "
3032 "Cowardly refusing to open this socket!");
3033 sockent_destroy (se);
3036 #endif /* HAVE_LIBGCRYPT */
3038 status = sockent_open (se);
3041 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3042 sockent_destroy (se);
3046 status = sockent_add (se);
3049 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3050 sockent_destroy (se);
3055 } /* }}} int network_config_add_server */
3057 static int network_config (oconfig_item_t *ci) /* {{{ */
3061 for (i = 0; i < ci->children_num; i++)
3063 oconfig_item_t *child = ci->children + i;
3065 if (strcasecmp ("Listen", child->key) == 0)
3066 network_config_add_listen (child);
3067 else if (strcasecmp ("Server", child->key) == 0)
3068 network_config_add_server (child);
3069 else if (strcasecmp ("TimeToLive", child->key) == 0)
3070 network_config_set_ttl (child);
3071 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3072 network_config_set_buffer_size (child);
3073 else if (strcasecmp ("Forward", child->key) == 0)
3074 network_config_set_boolean (child, &network_config_forward);
3075 else if (strcasecmp ("ReportStats", child->key) == 0)
3076 network_config_set_boolean (child, &network_config_stats);
3079 WARNING ("network plugin: Option `%s' is not allowed here.",
3085 } /* }}} int network_config */
3087 static int network_notification (const notification_t *n,
3088 user_data_t __attribute__((unused)) *user_data)
3090 char buffer[network_config_packet_size];
3091 char *buffer_ptr = buffer;
3092 int buffer_free = sizeof (buffer);
3095 memset (buffer, '\0', sizeof (buffer));
3097 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME_HR,
3098 (uint64_t) n->time);
3102 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3103 (uint64_t) n->severity);
3107 if (strlen (n->host) > 0)
3109 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3110 n->host, strlen (n->host));
3115 if (strlen (n->plugin) > 0)
3117 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3118 n->plugin, strlen (n->plugin));
3123 if (strlen (n->plugin_instance) > 0)
3125 status = write_part_string (&buffer_ptr, &buffer_free,
3126 TYPE_PLUGIN_INSTANCE,
3127 n->plugin_instance, strlen (n->plugin_instance));
3132 if (strlen (n->type) > 0)
3134 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3135 n->type, strlen (n->type));
3140 if (strlen (n->type_instance) > 0)
3142 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3143 n->type_instance, strlen (n->type_instance));
3148 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3149 n->message, strlen (n->message));
3153 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3156 } /* int network_notification */
3158 static int network_shutdown (void)
3162 /* Kill the listening thread */
3163 if (receive_thread_running != 0)
3165 INFO ("network plugin: Stopping receive thread.");
3166 pthread_kill (receive_thread_id, SIGTERM);
3167 pthread_join (receive_thread_id, NULL /* no return value */);
3168 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3169 receive_thread_running = 0;
3172 /* Shutdown the dispatching thread */
3173 if (dispatch_thread_running != 0)
3175 INFO ("network plugin: Stopping dispatch thread.");
3176 pthread_mutex_lock (&receive_list_lock);
3177 pthread_cond_broadcast (&receive_list_cond);
3178 pthread_mutex_unlock (&receive_list_lock);
3179 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3180 dispatch_thread_running = 0;
3183 sockent_destroy (listen_sockets);
3185 if (send_buffer_fill > 0)
3188 sfree (send_buffer);
3190 /* TODO: Close `sending_sockets' */
3192 plugin_unregister_config ("network");
3193 plugin_unregister_init ("network");
3194 plugin_unregister_write ("network");
3195 plugin_unregister_shutdown ("network");
3198 } /* int network_shutdown */
3200 static int network_stats_read (void) /* {{{ */
3202 derive_t copy_octets_rx;
3203 derive_t copy_octets_tx;
3204 derive_t copy_packets_rx;
3205 derive_t copy_packets_tx;
3206 derive_t copy_values_dispatched;
3207 derive_t copy_values_not_dispatched;
3208 derive_t copy_values_sent;
3209 derive_t copy_values_not_sent;
3210 derive_t copy_receive_list_length;
3211 value_list_t vl = VALUE_LIST_INIT;
3214 copy_octets_rx = stats_octets_rx;
3215 copy_octets_tx = stats_octets_tx;
3216 copy_packets_rx = stats_packets_rx;
3217 copy_packets_tx = stats_packets_tx;
3218 copy_values_dispatched = stats_values_dispatched;
3219 copy_values_not_dispatched = stats_values_not_dispatched;
3220 copy_values_sent = stats_values_sent;
3221 copy_values_not_sent = stats_values_not_sent;
3222 copy_receive_list_length = receive_list_length;
3224 /* Initialize `vl' */
3228 vl.interval = interval_g;
3229 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3230 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3232 /* Octets received / sent */
3233 vl.values[0].derive = (derive_t) copy_octets_rx;
3234 vl.values[1].derive = (derive_t) copy_octets_tx;
3235 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3236 plugin_dispatch_values_secure (&vl);
3238 /* Packets received / send */
3239 vl.values[0].derive = (derive_t) copy_packets_rx;
3240 vl.values[1].derive = (derive_t) copy_packets_tx;
3241 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3242 plugin_dispatch_values_secure (&vl);
3244 /* Values (not) dispatched and (not) send */
3245 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3248 vl.values[0].derive = (derive_t) copy_values_dispatched;
3249 sstrncpy (vl.type_instance, "dispatch-accepted",
3250 sizeof (vl.type_instance));
3251 plugin_dispatch_values_secure (&vl);
3253 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3254 sstrncpy (vl.type_instance, "dispatch-rejected",
3255 sizeof (vl.type_instance));
3256 plugin_dispatch_values_secure (&vl);
3258 vl.values[0].derive = (derive_t) copy_values_sent;
3259 sstrncpy (vl.type_instance, "send-accepted",
3260 sizeof (vl.type_instance));
3261 plugin_dispatch_values_secure (&vl);
3263 vl.values[0].derive = (derive_t) copy_values_not_sent;
3264 sstrncpy (vl.type_instance, "send-rejected",
3265 sizeof (vl.type_instance));
3266 plugin_dispatch_values_secure (&vl);
3268 /* Receive queue length */
3269 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3270 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3271 vl.type_instance[0] = 0;
3272 plugin_dispatch_values_secure (&vl);
3275 } /* }}} int network_stats_read */
3277 static int network_init (void)
3279 static _Bool have_init = 0;
3281 /* Check if we were already initialized. If so, just return - there's
3282 * nothing more to do (for now, that is). */
3288 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3289 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3290 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3293 if (network_config_stats != 0)
3294 plugin_register_read ("network", network_stats_read);
3296 plugin_register_shutdown ("network", network_shutdown);
3298 send_buffer = malloc (network_config_packet_size);
3299 if (send_buffer == NULL)
3301 ERROR ("network plugin: malloc failed.");
3304 network_init_buffer ();
3306 /* setup socket(s) and so on */
3307 if (sending_sockets != NULL)
3309 plugin_register_write ("network", network_write,
3310 /* user_data = */ NULL);
3311 plugin_register_notification ("network", network_notification,
3312 /* user_data = */ NULL);
3315 /* If no threads need to be started, return here. */
3316 if ((listen_sockets_num == 0)
3317 || ((dispatch_thread_running != 0)
3318 && (receive_thread_running != 0)))
3321 if (dispatch_thread_running == 0)
3324 status = pthread_create (&dispatch_thread_id,
3325 NULL /* no attributes */,
3327 NULL /* no argument */);
3331 ERROR ("network: pthread_create failed: %s",
3332 sstrerror (errno, errbuf,
3337 dispatch_thread_running = 1;
3341 if (receive_thread_running == 0)
3344 status = pthread_create (&receive_thread_id,
3345 NULL /* no attributes */,
3347 NULL /* no argument */);
3351 ERROR ("network: pthread_create failed: %s",
3352 sstrerror (errno, errbuf,
3357 receive_thread_running = 1;
3362 } /* int network_init */
3365 * The flush option of the network plugin cannot flush individual identifiers.
3366 * All the values are added to a buffer and sent when the buffer is full, the
3367 * requested value may or may not be in there, it's not worth finding out. We
3368 * just send the buffer if `flush' is called - if the requested value was in
3369 * there, good. If not, well, then there is nothing to flush.. -octo
3371 static int network_flush (__attribute__((unused)) cdtime_t timeout,
3372 __attribute__((unused)) const char *identifier,
3373 __attribute__((unused)) user_data_t *user_data)
3375 pthread_mutex_lock (&send_buffer_lock);
3377 if (send_buffer_fill > 0)
3380 pthread_mutex_unlock (&send_buffer_lock);
3383 } /* int network_flush */
3385 void module_register (void)
3387 plugin_register_complex_config ("network", network_config);
3388 plugin_register_init ("network", network_init);
3389 plugin_register_flush ("network", network_flush,
3390 /* user_data = */ NULL);
3391 } /* void module_register */
3393 /* vim: set fdm=marker : */