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"
41 # include <sys/socket.h>
47 # include <netinet/in.h>
50 # include <arpa/inet.h>
61 GCRY_THREAD_OPTION_PTHREAD_IMPL;
64 #ifndef IPV6_ADD_MEMBERSHIP
65 # ifdef IPV6_JOIN_GROUP
66 # define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
68 # error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
70 #endif /* !IP_ADD_MEMBERSHIP */
73 * Maximum size required for encryption / signing:
75 * 42 bytes for the encryption header
76 * + 64 bytes for the username
80 #define BUFF_SIG_SIZE 106
85 #define SECURITY_LEVEL_NONE 0
87 # define SECURITY_LEVEL_SIGN 1
88 # define SECURITY_LEVEL_ENCRYPT 2
93 struct sockaddr_storage *addr;
99 gcry_cipher_hd_t cypher;
100 unsigned char password_hash[32];
104 struct sockent_server
112 gcry_cipher_hd_t cypher;
116 typedef struct sockent
118 #define SOCKENT_TYPE_CLIENT 1
119 #define SOCKENT_TYPE_SERVER 2
128 struct sockent_client client;
129 struct sockent_server server;
132 struct sockent *next;
135 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
136 * 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
137 * +-------+-----------------------+-------------------------------+
138 * ! Ver. ! ! Length !
139 * +-------+-----------------------+-------------------------------+
146 typedef struct part_header_s part_header_t;
148 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
149 * 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
150 * +-------------------------------+-------------------------------+
152 * +-------------------------------+-------------------------------+
153 * : (Length - 4) Bytes :
154 * +---------------------------------------------------------------+
161 typedef struct part_string_s part_string_t;
163 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
164 * 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
165 * +-------------------------------+-------------------------------+
167 * +-------------------------------+-------------------------------+
168 * : (Length - 4 == 2 || 4 || 8) Bytes :
169 * +---------------------------------------------------------------+
176 typedef struct part_number_s part_number_t;
178 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
179 * 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
180 * +-------------------------------+-------------------------------+
182 * +-------------------------------+---------------+---------------+
183 * ! Num of values ! Type0 ! Type1 !
184 * +-------------------------------+---------------+---------------+
187 * +---------------------------------------------------------------+
190 * +---------------------------------------------------------------+
195 uint16_t *num_values;
196 uint8_t *values_types;
199 typedef struct part_values_s part_values_t;
201 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
202 * 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
203 * +-------------------------------+-------------------------------+
205 * +-------------------------------+-------------------------------+
206 * ! Hash (Bits 0 - 31) !
208 * ! Hash (Bits 224 - 255) !
209 * +---------------------------------------------------------------+
212 #define PART_SIGNATURE_SHA256_SIZE 36
213 struct part_signature_sha256_s
216 unsigned char hash[32];
219 typedef struct part_signature_sha256_s part_signature_sha256_t;
221 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
222 * 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
223 * +-------------------------------+-------------------------------+
225 * +-------------------------------+-------------------------------+
226 * ! Original length ! Padding (0 - 15 bytes) !
227 * +-------------------------------+-------------------------------+
228 * ! Hash (Bits 0 - 31) !
230 * ! Hash (Bits 128 - 159) !
231 * +---------------------------------------------------------------+
234 #define PART_ENCRYPTION_AES256_SIZE 42
235 struct part_encryption_aes256_s
238 uint16_t username_length;
240 unsigned char iv[16];
242 unsigned char hash[20];
246 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
248 struct receive_list_entry_s
253 struct receive_list_entry_s *next;
255 typedef struct receive_list_entry_s receive_list_entry_t;
260 static int network_config_ttl = 0;
261 static size_t network_config_packet_size = 1024;
262 static int network_config_forward = 0;
263 static int network_config_stats = 0;
265 static sockent_t *sending_sockets = NULL;
267 static receive_list_entry_t *receive_list_head = NULL;
268 static receive_list_entry_t *receive_list_tail = NULL;
269 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
270 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
271 static uint64_t receive_list_length = 0;
273 static sockent_t *listen_sockets = NULL;
274 static struct pollfd *listen_sockets_pollfd = NULL;
275 static size_t listen_sockets_num = 0;
277 /* The receive and dispatch threads will run as long as `listen_loop' is set to
279 static int listen_loop = 0;
280 static int receive_thread_running = 0;
281 static pthread_t receive_thread_id;
282 static int dispatch_thread_running = 0;
283 static pthread_t dispatch_thread_id;
285 /* Buffer in which to-be-sent network packets are constructed. */
286 static char *send_buffer;
287 static char *send_buffer_ptr;
288 static int send_buffer_fill;
289 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
290 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
292 /* XXX: These counters are incremented from one place only. The spot in which
293 * the values are incremented is either only reachable by one thread (the
294 * dispatch thread, for example) or locked by some lock (send_buffer_lock for
295 * example). Only if neither is true, the stats_lock is acquired. The counters
296 * are always read without holding a lock in the hope that writing 8 bytes to
297 * memory is an atomic operation. */
298 static uint64_t stats_octets_rx = 0;
299 static uint64_t stats_octets_tx = 0;
300 static uint64_t stats_packets_rx = 0;
301 static uint64_t stats_packets_tx = 0;
302 static uint64_t stats_values_dispatched = 0;
303 static uint64_t stats_values_not_dispatched = 0;
304 static uint64_t stats_values_sent = 0;
305 static uint64_t stats_values_not_sent = 0;
306 static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
311 static _Bool check_receive_okay (const value_list_t *vl) /* {{{ */
313 uint64_t time_sent = 0;
316 status = uc_meta_data_get_unsigned_int (vl,
317 "network:time_sent", &time_sent);
319 /* This is a value we already sent. Don't allow it to be received again in
320 * order to avoid looping. */
321 if ((status == 0) && (time_sent >= ((uint64_t) vl->time)))
325 } /* }}} _Bool check_receive_okay */
327 static _Bool check_send_okay (const value_list_t *vl) /* {{{ */
329 _Bool received = false;
332 if (network_config_forward != 0)
335 if (vl->meta == NULL)
338 status = meta_data_get_boolean (vl->meta, "network:received", &received);
339 if (status == -ENOENT)
341 else if (status != 0)
343 ERROR ("network plugin: check_send_okay: meta_data_get_boolean failed "
344 "with status %i.", status);
348 /* By default, only *send* value lists that were not *received* by the
351 } /* }}} _Bool check_send_okay */
353 static int network_dispatch_values (value_list_t *vl, /* {{{ */
354 const char *username)
359 || (strlen (vl->host) <= 0)
360 || (strlen (vl->plugin) <= 0)
361 || (strlen (vl->type) <= 0))
364 if (!check_receive_okay (vl))
367 char name[6*DATA_MAX_NAME_LEN];
368 FORMAT_VL (name, sizeof (name), vl);
369 name[sizeof (name) - 1] = 0;
370 DEBUG ("network plugin: network_dispatch_values: "
371 "NOT dispatching %s.", name);
373 stats_values_not_dispatched++;
377 assert (vl->meta == NULL);
379 vl->meta = meta_data_create ();
380 if (vl->meta == NULL)
382 ERROR ("network plugin: meta_data_create failed.");
386 status = meta_data_add_boolean (vl->meta, "network:received", true);
389 ERROR ("network plugin: meta_data_add_boolean failed.");
390 meta_data_destroy (vl->meta);
395 if (username != NULL)
397 status = meta_data_add_string (vl->meta, "network:username", username);
400 ERROR ("network plugin: meta_data_add_string failed.");
401 meta_data_destroy (vl->meta);
407 plugin_dispatch_values (vl);
408 stats_values_dispatched++;
410 meta_data_destroy (vl->meta);
414 } /* }}} int network_dispatch_values */
417 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
418 const void *iv, size_t iv_size, const char *username)
421 gcry_cipher_hd_t *cyper_ptr;
422 unsigned char password_hash[32];
424 if (se->type == SOCKENT_TYPE_CLIENT)
426 cyper_ptr = &se->data.client.cypher;
427 memcpy (password_hash, se->data.client.password_hash,
428 sizeof (password_hash));
434 cyper_ptr = &se->data.server.cypher;
436 if (username == NULL)
439 secret = fbh_get (se->data.server.userdb, username);
443 gcry_md_hash_buffer (GCRY_MD_SHA256,
445 secret, strlen (secret));
450 if (*cyper_ptr == NULL)
452 err = gcry_cipher_open (cyper_ptr,
453 GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
456 ERROR ("network plugin: gcry_cipher_open returned: %s",
457 gcry_strerror (err));
464 gcry_cipher_reset (*cyper_ptr);
466 assert (*cyper_ptr != NULL);
468 err = gcry_cipher_setkey (*cyper_ptr,
469 password_hash, sizeof (password_hash));
472 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
473 gcry_strerror (err));
474 gcry_cipher_close (*cyper_ptr);
479 err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
482 ERROR ("network plugin: gcry_cipher_setkey returned: %s",
483 gcry_strerror (err));
484 gcry_cipher_close (*cyper_ptr);
490 } /* }}} int network_get_aes256_cypher */
491 #endif /* HAVE_LIBGCRYPT */
493 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
494 const data_set_t *ds, const value_list_t *vl)
500 part_header_t pkg_ph;
501 uint16_t pkg_num_values;
502 uint8_t *pkg_values_types;
508 num_values = vl->values_len;
509 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
510 + (num_values * sizeof (uint8_t))
511 + (num_values * sizeof (value_t));
513 if (*ret_buffer_len < packet_len)
516 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
517 if (pkg_values_types == NULL)
519 ERROR ("network plugin: write_part_values: malloc failed.");
523 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
524 if (pkg_values == NULL)
526 free (pkg_values_types);
527 ERROR ("network plugin: write_part_values: malloc failed.");
531 pkg_ph.type = htons (TYPE_VALUES);
532 pkg_ph.length = htons (packet_len);
534 pkg_num_values = htons ((uint16_t) vl->values_len);
536 for (i = 0; i < num_values; i++)
538 pkg_values_types[i] = (uint8_t) ds->ds[i].type;
539 switch (ds->ds[i].type)
541 case DS_TYPE_COUNTER:
542 pkg_values[i].counter = htonll (vl->values[i].counter);
546 pkg_values[i].gauge = htond (vl->values[i].gauge);
550 pkg_values[i].derive = htonll (vl->values[i].derive);
553 case DS_TYPE_ABSOLUTE:
554 pkg_values[i].absolute = htonll (vl->values[i].absolute);
558 free (pkg_values_types);
560 ERROR ("network plugin: write_part_values: "
561 "Unknown data source type: %i",
564 } /* switch (ds->ds[i].type) */
565 } /* for (num_values) */
568 * Use `memcpy' to write everything to the buffer, because the pointer
569 * may be unaligned and some architectures, such as SPARC, can't handle
572 packet_ptr = *ret_buffer;
574 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
575 offset += sizeof (pkg_ph);
576 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
577 offset += sizeof (pkg_num_values);
578 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
579 offset += num_values * sizeof (uint8_t);
580 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
581 offset += num_values * sizeof (value_t);
583 assert (offset == packet_len);
585 *ret_buffer = packet_ptr + packet_len;
586 *ret_buffer_len -= packet_len;
588 free (pkg_values_types);
592 } /* int write_part_values */
594 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
595 int type, uint64_t value)
600 part_header_t pkg_head;
605 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
607 if (*ret_buffer_len < packet_len)
610 pkg_head.type = htons (type);
611 pkg_head.length = htons (packet_len);
612 pkg_value = htonll (value);
614 packet_ptr = *ret_buffer;
616 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
617 offset += sizeof (pkg_head);
618 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
619 offset += sizeof (pkg_value);
621 assert (offset == packet_len);
623 *ret_buffer = packet_ptr + packet_len;
624 *ret_buffer_len -= packet_len;
627 } /* int write_part_number */
629 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
630 int type, const char *str, int str_len)
640 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
641 if (*ret_buffer_len < buffer_len)
644 pkg_type = htons (type);
645 pkg_length = htons (buffer_len);
647 buffer = *ret_buffer;
649 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
650 offset += sizeof (pkg_type);
651 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
652 offset += sizeof (pkg_length);
653 memcpy (buffer + offset, str, str_len);
655 memset (buffer + offset, '\0', 1);
658 assert (offset == buffer_len);
660 *ret_buffer = buffer + buffer_len;
661 *ret_buffer_len -= buffer_len;
664 } /* int write_part_string */
666 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
667 value_t **ret_values, int *ret_num_values)
669 char *buffer = *ret_buffer;
670 size_t buffer_len = *ret_buffer_len;
685 NOTICE ("network plugin: packet is too short: "
686 "buffer_len = %zu", buffer_len);
690 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
691 buffer += sizeof (tmp16);
692 pkg_type = ntohs (tmp16);
694 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
695 buffer += sizeof (tmp16);
696 pkg_length = ntohs (tmp16);
698 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
699 buffer += sizeof (tmp16);
700 pkg_numval = ntohs (tmp16);
702 assert (pkg_type == TYPE_VALUES);
704 exp_size = 3 * sizeof (uint16_t)
705 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
706 if ((buffer_len < 0) || (buffer_len < exp_size))
708 WARNING ("network plugin: parse_part_values: "
710 "Chunk of size %zu expected, "
711 "but buffer has only %zu bytes left.",
712 exp_size, buffer_len);
716 if (pkg_length != exp_size)
718 WARNING ("network plugin: parse_part_values: "
719 "Length and number of values "
720 "in the packet don't match.");
724 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
725 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
726 if ((pkg_types == NULL) || (pkg_values == NULL))
730 ERROR ("network plugin: parse_part_values: malloc failed.");
734 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
735 buffer += pkg_numval * sizeof (uint8_t);
736 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
737 buffer += pkg_numval * sizeof (value_t);
739 for (i = 0; i < pkg_numval; i++)
741 switch (pkg_types[i])
743 case DS_TYPE_COUNTER:
744 pkg_values[i].counter = (counter_t) ntohll (pkg_values[i].counter);
748 pkg_values[i].gauge = (gauge_t) ntohd (pkg_values[i].gauge);
752 pkg_values[i].derive = (derive_t) ntohll (pkg_values[i].derive);
755 case DS_TYPE_ABSOLUTE:
756 pkg_values[i].absolute = (absolute_t) ntohll (pkg_values[i].absolute);
760 NOTICE ("network plugin: parse_part_values: "
761 "Don't know how to handle data source type %"PRIu8,
766 } /* switch (pkg_types[i]) */
769 *ret_buffer = buffer;
770 *ret_buffer_len = buffer_len - pkg_length;
771 *ret_num_values = pkg_numval;
772 *ret_values = pkg_values;
777 } /* int parse_part_values */
779 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
782 char *buffer = *ret_buffer;
783 size_t buffer_len = *ret_buffer_len;
787 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);
832 if ((buffer_len < 0) || (buffer_len < header_size))
834 WARNING ("network plugin: parse_part_string: "
836 "Chunk of at least size %zu expected, "
837 "but buffer has only %zu bytes left.",
838 header_size, buffer_len);
842 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
843 buffer += sizeof (tmp16);
844 pkg_type = ntohs (tmp16);
846 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
847 buffer += sizeof (tmp16);
848 pkg_length = ntohs (tmp16);
850 /* Check that packet fits in the input buffer */
851 if (pkg_length > buffer_len)
853 WARNING ("network plugin: parse_part_string: "
855 "Chunk of size %"PRIu16" received, "
856 "but buffer has only %zu bytes left.",
857 pkg_length, buffer_len);
861 /* Check that pkg_length is in the valid range */
862 if (pkg_length <= header_size)
864 WARNING ("network plugin: parse_part_string: "
866 "Header claims this packet is only %hu "
867 "bytes long.", pkg_length);
871 /* Check that the package data fits into the output buffer.
872 * The previous if-statement ensures that:
873 * `pkg_length > header_size' */
875 || ((size_t) output_len < ((size_t) pkg_length - header_size)))
877 WARNING ("network plugin: parse_part_string: "
878 "Output buffer too small.");
882 /* All sanity checks successfull, let's copy the data over */
883 output_len = pkg_length - header_size;
884 memcpy ((void *) output, (void *) buffer, output_len);
885 buffer += output_len;
887 /* For some very weird reason '\0' doesn't do the trick on SPARC in
889 if (output[output_len - 1] != 0)
891 WARNING ("network plugin: parse_part_string: "
892 "Received string does not end "
893 "with a NULL-byte.");
897 *ret_buffer = buffer;
898 *ret_buffer_len = buffer_len - pkg_length;
901 } /* int parse_part_string */
903 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
904 * parse_packet and vice versa. */
905 #define PP_SIGNED 0x01
906 #define PP_ENCRYPTED 0x02
907 static int parse_packet (sockent_t *se,
908 void *buffer, size_t buffer_size, int flags,
909 const char *username);
911 #define BUFFER_READ(p,s) do { \
912 memcpy ((p), buffer + buffer_offset, (s)); \
913 buffer_offset += (s); \
917 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
918 void **ret_buffer, size_t *ret_buffer_len, int flags)
922 size_t buffer_offset;
927 part_signature_sha256_t pss;
928 uint16_t pss_head_length;
929 char hash[sizeof (pss.hash)];
933 unsigned char *hash_ptr;
935 buffer = *ret_buffer;
936 buffer_len = *ret_buffer_len;
939 if (se->data.server.userdb == NULL)
941 NOTICE ("network plugin: Received signed network packet but can't verify "
942 "it because no user DB has been configured. Will accept it.");
946 /* Check if the buffer has enough data for this structure. */
947 if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
950 /* Read type and length header */
951 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
952 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
953 pss_head_length = ntohs (pss.head.length);
955 /* Check if the `pss_head_length' is within bounds. */
956 if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
957 || (pss_head_length > buffer_len))
959 ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
964 BUFFER_READ (pss.hash, sizeof (pss.hash));
966 /* Calculate username length (without null byte) and allocate memory */
967 username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
968 pss.username = malloc (username_len + 1);
969 if (pss.username == NULL)
972 /* Read the username */
973 BUFFER_READ (pss.username, username_len);
974 pss.username[username_len] = 0;
976 assert (buffer_offset == pss_head_length);
978 /* Query the password */
979 secret = fbh_get (se->data.server.userdb, pss.username);
982 ERROR ("network plugin: Unknown user: %s", pss.username);
983 sfree (pss.username);
987 /* Create a hash device and check the HMAC */
989 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
992 ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
993 gcry_strerror (err));
995 sfree (pss.username);
999 err = gcry_md_setkey (hd, secret, strlen (secret));
1002 ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
1005 sfree (pss.username);
1010 buffer + PART_SIGNATURE_SHA256_SIZE,
1011 buffer_len - PART_SIGNATURE_SHA256_SIZE);
1012 hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
1013 if (hash_ptr == NULL)
1015 ERROR ("network plugin: gcry_md_read failed.");
1018 sfree (pss.username);
1021 memcpy (hash, hash_ptr, sizeof (hash));
1027 if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
1029 WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
1034 parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
1035 flags | PP_SIGNED, pss.username);
1039 sfree (pss.username);
1041 *ret_buffer = buffer + buffer_len;
1042 *ret_buffer_len = 0;
1045 } /* }}} int parse_part_sign_sha256 */
1046 /* #endif HAVE_LIBGCRYPT */
1048 #else /* if !HAVE_LIBGCRYPT */
1049 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
1050 void **ret_buffer, size_t *ret_buffer_size, int flags)
1052 static int warning_has_been_printed = 0;
1056 size_t buffer_offset;
1059 part_signature_sha256_t pss;
1061 buffer = *ret_buffer;
1062 buffer_size = *ret_buffer_size;
1065 if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1068 BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1069 BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1070 part_len = ntohs (pss.head.length);
1072 if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1073 || (part_len > buffer_size))
1076 if (warning_has_been_printed == 0)
1078 WARNING ("network plugin: Received signed packet, but the network "
1079 "plugin was not linked with libgcrypt, so I cannot "
1080 "verify the signature. The packet will be accepted.");
1081 warning_has_been_printed = 1;
1084 parse_packet (se, buffer + part_len, buffer_size - part_len, flags,
1085 /* username = */ NULL);
1087 *ret_buffer = buffer + buffer_size;
1088 *ret_buffer_size = 0;
1091 } /* }}} int parse_part_sign_sha256 */
1092 #endif /* !HAVE_LIBGCRYPT */
1095 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1096 void **ret_buffer, size_t *ret_buffer_len,
1099 char *buffer = *ret_buffer;
1100 size_t buffer_len = *ret_buffer_len;
1103 size_t buffer_offset;
1104 uint16_t username_len;
1105 part_encryption_aes256_t pea;
1106 unsigned char hash[sizeof (pea.hash)];
1108 gcry_cipher_hd_t cypher;
1111 /* Make sure at least the header if available. */
1112 if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1114 NOTICE ("network plugin: parse_part_encr_aes256: "
1115 "Discarding short packet.");
1121 /* Copy the unencrypted information into `pea'. */
1122 BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1123 BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1125 /* Check the `part size'. */
1126 part_size = ntohs (pea.head.length);
1127 if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1128 || (part_size > buffer_len))
1130 NOTICE ("network plugin: parse_part_encr_aes256: "
1131 "Discarding part with invalid size.");
1135 /* Read the username */
1136 BUFFER_READ (&username_len, sizeof (username_len));
1137 username_len = ntohs (username_len);
1139 if ((username_len <= 0)
1140 || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1142 NOTICE ("network plugin: parse_part_encr_aes256: "
1143 "Discarding part with invalid username length.");
1147 assert (username_len > 0);
1148 pea.username = malloc (username_len + 1);
1149 if (pea.username == NULL)
1151 BUFFER_READ (pea.username, username_len);
1152 pea.username[username_len] = 0;
1154 /* Last but not least, the initialization vector */
1155 BUFFER_READ (pea.iv, sizeof (pea.iv));
1157 /* Make sure we are at the right position */
1158 assert (buffer_offset == (username_len +
1159 PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1161 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1165 sfree (pea.username);
1169 payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1170 assert (payload_len > 0);
1172 /* Decrypt the packet in-place */
1173 err = gcry_cipher_decrypt (cypher,
1174 buffer + buffer_offset,
1175 part_size - buffer_offset,
1176 /* in = */ NULL, /* in len = */ 0);
1179 sfree (pea.username);
1180 ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1181 gcry_strerror (err));
1186 BUFFER_READ (pea.hash, sizeof (pea.hash));
1188 /* Make sure we're at the right position - again */
1189 assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1190 assert (buffer_offset == (part_size - payload_len));
1192 /* Check hash sum */
1193 memset (hash, 0, sizeof (hash));
1194 gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1195 buffer + buffer_offset, payload_len);
1196 if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1198 sfree (pea.username);
1199 ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1203 parse_packet (se, buffer + buffer_offset, payload_len,
1204 flags | PP_ENCRYPTED, pea.username);
1206 /* XXX: Free pea.username?!? */
1208 /* Update return values */
1209 *ret_buffer = buffer + part_size;
1210 *ret_buffer_len = buffer_len - part_size;
1212 sfree (pea.username);
1215 } /* }}} int parse_part_encr_aes256 */
1216 /* #endif HAVE_LIBGCRYPT */
1218 #else /* if !HAVE_LIBGCRYPT */
1219 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1220 void **ret_buffer, size_t *ret_buffer_size, int flags)
1222 static int warning_has_been_printed = 0;
1226 size_t buffer_offset;
1231 buffer = *ret_buffer;
1232 buffer_size = *ret_buffer_size;
1235 /* parse_packet assures this minimum size. */
1236 assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1238 BUFFER_READ (&ph.type, sizeof (ph.type));
1239 BUFFER_READ (&ph.length, sizeof (ph.length));
1240 ph_length = ntohs (ph.length);
1242 if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1243 || (ph_length > buffer_size))
1245 ERROR ("network plugin: AES-256 encrypted part "
1246 "with invalid length received.");
1250 if (warning_has_been_printed == 0)
1252 WARNING ("network plugin: Received encrypted packet, but the network "
1253 "plugin was not linked with libgcrypt, so I cannot "
1254 "decrypt it. The part will be discarded.");
1255 warning_has_been_printed = 1;
1258 *ret_buffer += ph_length;
1259 *ret_buffer_size -= ph_length;
1262 } /* }}} int parse_part_encr_aes256 */
1263 #endif /* !HAVE_LIBGCRYPT */
1267 static int parse_packet (sockent_t *se, /* {{{ */
1268 void *buffer, size_t buffer_size, int flags,
1269 const char *username)
1273 value_list_t vl = VALUE_LIST_INIT;
1277 int packet_was_signed = (flags & PP_SIGNED);
1278 int packet_was_encrypted = (flags & PP_ENCRYPTED);
1279 int printed_ignore_warning = 0;
1280 #endif /* HAVE_LIBGCRYPT */
1283 memset (&vl, '\0', sizeof (vl));
1284 memset (&n, '\0', sizeof (n));
1287 while ((status == 0) && (0 < buffer_size)
1288 && ((unsigned int) buffer_size > sizeof (part_header_t)))
1290 uint16_t pkg_length;
1293 memcpy ((void *) &pkg_type,
1296 memcpy ((void *) &pkg_length,
1297 (void *) (buffer + sizeof (pkg_type)),
1298 sizeof (pkg_length));
1300 pkg_length = ntohs (pkg_length);
1301 pkg_type = ntohs (pkg_type);
1303 if (pkg_length > buffer_size)
1305 /* Ensure that this loop terminates eventually */
1306 if (pkg_length < (2 * sizeof (uint16_t)))
1309 if (pkg_type == TYPE_ENCR_AES256)
1311 status = parse_part_encr_aes256 (se,
1312 &buffer, &buffer_size, flags);
1315 ERROR ("network plugin: Decrypting AES256 "
1317 "with status %i.", status);
1322 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1323 && (packet_was_encrypted == 0))
1325 if (printed_ignore_warning == 0)
1327 INFO ("network plugin: Unencrypted packet or "
1328 "part has been ignored.");
1329 printed_ignore_warning = 1;
1331 buffer = ((char *) buffer) + pkg_length;
1334 #endif /* HAVE_LIBGCRYPT */
1335 else if (pkg_type == TYPE_SIGN_SHA256)
1337 status = parse_part_sign_sha256 (se,
1338 &buffer, &buffer_size, flags);
1341 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1343 "with status %i.", status);
1348 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1349 && (packet_was_encrypted == 0)
1350 && (packet_was_signed == 0))
1352 if (printed_ignore_warning == 0)
1354 INFO ("network plugin: Unsigned packet or "
1355 "part has been ignored.");
1356 printed_ignore_warning = 1;
1358 buffer = ((char *) buffer) + pkg_length;
1361 #endif /* HAVE_LIBGCRYPT */
1362 else if (pkg_type == TYPE_VALUES)
1364 status = parse_part_values (&buffer, &buffer_size,
1365 &vl.values, &vl.values_len);
1369 network_dispatch_values (&vl, username);
1373 else if (pkg_type == TYPE_TIME)
1376 status = parse_part_number (&buffer, &buffer_size,
1380 vl.time = (time_t) tmp;
1381 n.time = (time_t) tmp;
1384 else if (pkg_type == TYPE_INTERVAL)
1387 status = parse_part_number (&buffer, &buffer_size,
1390 vl.interval = (int) tmp;
1392 else if (pkg_type == TYPE_HOST)
1394 status = parse_part_string (&buffer, &buffer_size,
1395 vl.host, sizeof (vl.host));
1397 sstrncpy (n.host, vl.host, sizeof (n.host));
1399 else if (pkg_type == TYPE_PLUGIN)
1401 status = parse_part_string (&buffer, &buffer_size,
1402 vl.plugin, sizeof (vl.plugin));
1404 sstrncpy (n.plugin, vl.plugin,
1407 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1409 status = parse_part_string (&buffer, &buffer_size,
1411 sizeof (vl.plugin_instance));
1413 sstrncpy (n.plugin_instance,
1415 sizeof (n.plugin_instance));
1417 else if (pkg_type == TYPE_TYPE)
1419 status = parse_part_string (&buffer, &buffer_size,
1420 vl.type, sizeof (vl.type));
1422 sstrncpy (n.type, vl.type, sizeof (n.type));
1424 else if (pkg_type == TYPE_TYPE_INSTANCE)
1426 status = parse_part_string (&buffer, &buffer_size,
1428 sizeof (vl.type_instance));
1430 sstrncpy (n.type_instance, vl.type_instance,
1431 sizeof (n.type_instance));
1433 else if (pkg_type == TYPE_MESSAGE)
1435 status = parse_part_string (&buffer, &buffer_size,
1436 n.message, sizeof (n.message));
1442 else if ((n.severity != NOTIF_FAILURE)
1443 && (n.severity != NOTIF_WARNING)
1444 && (n.severity != NOTIF_OKAY))
1446 INFO ("network plugin: "
1447 "Ignoring notification with "
1448 "unknown severity %i.",
1451 else if (n.time <= 0)
1453 INFO ("network plugin: "
1454 "Ignoring notification with "
1457 else if (strlen (n.message) <= 0)
1459 INFO ("network plugin: "
1460 "Ignoring notification with "
1461 "an empty message.");
1465 plugin_dispatch_notification (&n);
1468 else if (pkg_type == TYPE_SEVERITY)
1471 status = parse_part_number (&buffer, &buffer_size,
1474 n.severity = (int) tmp;
1478 DEBUG ("network plugin: parse_packet: Unknown part"
1479 " type: 0x%04hx", pkg_type);
1480 buffer = ((char *) buffer) + pkg_length;
1482 } /* while (buffer_size > sizeof (part_header_t)) */
1484 if (status == 0 && buffer_size > 0)
1485 WARNING ("network plugin: parse_packet: Received truncated "
1486 "packet, try increasing `MaxPacketSize'");
1489 } /* }}} int parse_packet */
1491 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1500 sfree (sec->username);
1501 sfree (sec->password);
1502 if (sec->cypher != NULL)
1503 gcry_cipher_close (sec->cypher);
1505 } /* }}} void free_sockent_client */
1507 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1511 for (i = 0; i < ses->fd_num; i++)
1513 if (ses->fd[i] >= 0)
1522 sfree (ses->auth_file);
1523 fbh_destroy (ses->userdb);
1524 if (ses->cypher != NULL)
1525 gcry_cipher_close (ses->cypher);
1527 } /* }}} void free_sockent_server */
1529 static void sockent_destroy (sockent_t *se) /* {{{ */
1533 DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1540 sfree (se->service);
1542 if (se->type == SOCKENT_TYPE_CLIENT)
1543 free_sockent_client (&se->data.client);
1545 free_sockent_server (&se->data.server);
1550 } /* }}} void sockent_destroy */
1553 * int network_set_ttl
1555 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1556 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1558 * The `struct addrinfo' is used to destinguish between unicast and multicast
1561 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1563 DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1564 network_config_ttl);
1566 assert (se->type == SOCKENT_TYPE_CLIENT);
1568 if ((network_config_ttl < 1) || (network_config_ttl > 255))
1571 if (ai->ai_family == AF_INET)
1573 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1576 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1577 optname = IP_MULTICAST_TTL;
1581 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1582 &network_config_ttl,
1583 sizeof (network_config_ttl)) != 0)
1586 ERROR ("setsockopt: %s",
1587 sstrerror (errno, errbuf, sizeof (errbuf)));
1591 else if (ai->ai_family == AF_INET6)
1593 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1594 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1597 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1598 optname = IPV6_MULTICAST_HOPS;
1600 optname = IPV6_UNICAST_HOPS;
1602 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1603 &network_config_ttl,
1604 sizeof (network_config_ttl)) != 0)
1607 ERROR ("setsockopt: %s",
1608 sstrerror (errno, errbuf,
1615 } /* int network_set_ttl */
1617 static int network_set_interface (const sockent_t *se, const struct addrinfo *ai) /* {{{ */
1619 DEBUG ("network plugin: network_set_interface: interface index = %i;",
1622 assert (se->type == SOCKENT_TYPE_CLIENT);
1624 if (ai->ai_family == AF_INET)
1626 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1628 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1630 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1631 /* If possible, use the "ip_mreqn" structure which has
1632 * an "interface index" member. Using the interface
1633 * index is preferred here, because of its similarity
1634 * to the way IPv6 handles this. Unfortunately, it
1635 * appears not to be portable. */
1636 struct ip_mreqn mreq;
1638 memset (&mreq, 0, sizeof (mreq));
1639 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1640 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1641 mreq.imr_ifindex = se->interface;
1643 struct ip_mreq mreq;
1645 memset (&mreq, 0, sizeof (mreq));
1646 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1647 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1650 if (setsockopt (se->data.client.fd, IPPROTO_IP, IP_MULTICAST_IF,
1651 &mreq, sizeof (mreq)) != 0)
1654 ERROR ("setsockopt: %s",
1655 sstrerror (errno, errbuf, sizeof (errbuf)));
1662 else if (ai->ai_family == AF_INET6)
1664 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1666 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1668 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
1670 sizeof (se->interface)) != 0)
1673 ERROR ("setsockopt: %s",
1674 sstrerror (errno, errbuf,
1683 /* else: Not a multicast interface. */
1684 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1685 if (se->interface != 0)
1687 char interface_name[IFNAMSIZ];
1689 if (if_indextoname (se->interface, interface_name) == NULL)
1692 DEBUG ("network plugin: Binding socket to interface %s", interface_name);
1694 if (setsockopt (se->data.client.fd, SOL_SOCKET, SO_BINDTODEVICE,
1696 sizeof(interface_name)) == -1 )
1699 ERROR ("setsockopt: %s",
1700 sstrerror (errno, errbuf, sizeof (errbuf)));
1704 /* #endif HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1707 WARNING ("network plugin: Cannot set the interface on a unicast "
1709 # if !defined(SO_BINDTODEVICE)
1710 "the the \"SO_BINDTODEVICE\" socket option "
1712 "the \"if_indextoname\" function "
1714 "is not available on your system.");
1718 } /* }}} network_set_interface */
1720 static int network_bind_socket (int fd, const struct addrinfo *ai, const int interface_idx)
1725 /* allow multiple sockets to use the same PORT number */
1726 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1727 &yes, sizeof(yes)) == -1) {
1729 ERROR ("setsockopt: %s",
1730 sstrerror (errno, errbuf, sizeof (errbuf)));
1734 DEBUG ("fd = %i; calling `bind'", fd);
1736 if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1740 sstrerror (errno, errbuf, sizeof (errbuf)));
1744 if (ai->ai_family == AF_INET)
1746 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1747 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1749 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1750 struct ip_mreqn mreq;
1752 struct ip_mreq mreq;
1755 DEBUG ("fd = %i; IPv4 multicast address found", fd);
1757 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1758 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
1759 /* Set the interface using the interface index if
1760 * possible (available). Unfortunately, the struct
1761 * ip_mreqn is not portable. */
1762 mreq.imr_address.s_addr = ntohl (INADDR_ANY);
1763 mreq.imr_ifindex = interface_idx;
1765 mreq.imr_interface.s_addr = ntohl (INADDR_ANY);
1768 if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1769 &loop, sizeof (loop)) == -1)
1772 ERROR ("setsockopt: %s",
1773 sstrerror (errno, errbuf,
1778 if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1779 &mreq, sizeof (mreq)) == -1)
1782 ERROR ("setsockopt: %s",
1783 sstrerror (errno, errbuf,
1791 else if (ai->ai_family == AF_INET6)
1793 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1794 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1795 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1797 struct ipv6_mreq mreq;
1799 DEBUG ("fd = %i; IPv6 multicast address found", fd);
1801 memcpy (&mreq.ipv6mr_multiaddr,
1803 sizeof (addr->sin6_addr));
1805 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1806 * ipv6mr_interface may be set to zeroes to
1807 * choose the default multicast interface or to
1808 * the index of a particular multicast-capable
1809 * interface if the host is multihomed.
1810 * Membership is associ-associated with a
1811 * single interface; programs running on
1812 * multihomed hosts may need to join the same
1813 * group on more than one interface.*/
1814 mreq.ipv6mr_interface = interface_idx;
1816 if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1817 &loop, sizeof (loop)) == -1)
1820 ERROR ("setsockopt: %s",
1821 sstrerror (errno, errbuf,
1826 if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1827 &mreq, sizeof (mreq)) == -1)
1830 ERROR ("setsockopt: %s",
1831 sstrerror (errno, errbuf,
1840 #if defined(HAVE_IF_INDEXTONAME) && HAVE_IF_INDEXTONAME && defined(SO_BINDTODEVICE)
1841 /* if a specific interface was set, bind the socket to it. But to avoid
1842 * possible problems with multicast routing, only do that for non-multicast
1844 if (interface_idx != 0)
1846 char interface_name[IFNAMSIZ];
1848 if (if_indextoname (interface_idx, interface_name) == NULL)
1851 DEBUG ("fd = %i; Binding socket to interface %s", fd, interface_name);
1853 if (setsockopt (fd, SOL_SOCKET, SO_BINDTODEVICE,
1855 sizeof(interface_name)) == -1 )
1858 ERROR ("setsockopt: %s",
1859 sstrerror (errno, errbuf, sizeof (errbuf)));
1863 #endif /* HAVE_IF_INDEXTONAME && SO_BINDTODEVICE */
1866 } /* int network_bind_socket */
1868 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1869 * or `SOCKENT_TYPE_SERVER' */
1870 static int sockent_init (sockent_t *se, int type) /* {{{ */
1875 memset (se, 0, sizeof (*se));
1877 se->type = SOCKENT_TYPE_CLIENT;
1883 if (type == SOCKENT_TYPE_SERVER)
1885 se->type = SOCKENT_TYPE_SERVER;
1886 se->data.server.fd = NULL;
1888 se->data.server.security_level = SECURITY_LEVEL_NONE;
1889 se->data.server.auth_file = NULL;
1890 se->data.server.userdb = NULL;
1891 se->data.server.cypher = NULL;
1896 se->data.client.fd = -1;
1897 se->data.client.addr = NULL;
1899 se->data.client.security_level = SECURITY_LEVEL_NONE;
1900 se->data.client.username = NULL;
1901 se->data.client.password = NULL;
1902 se->data.client.cypher = NULL;
1907 } /* }}} int sockent_init */
1909 /* Open the file descriptors for a initialized sockent structure. */
1910 static int sockent_open (sockent_t *se) /* {{{ */
1912 struct addrinfo ai_hints;
1913 struct addrinfo *ai_list, *ai_ptr;
1917 const char *service;
1922 /* Set up the security structures. */
1923 #if HAVE_LIBGCRYPT /* {{{ */
1924 if (se->type == SOCKENT_TYPE_CLIENT)
1926 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
1928 if ((se->data.client.username == NULL)
1929 || (se->data.client.password == NULL))
1931 ERROR ("network plugin: Client socket with "
1932 "security requested, but no "
1933 "credentials are configured.");
1936 gcry_md_hash_buffer (GCRY_MD_SHA256,
1937 se->data.client.password_hash,
1938 se->data.client.password,
1939 strlen (se->data.client.password));
1942 else /* (se->type == SOCKENT_TYPE_SERVER) */
1944 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1946 if (se->data.server.auth_file == NULL)
1948 ERROR ("network plugin: Server socket with "
1949 "security requested, but no "
1950 "password file is configured.");
1954 if (se->data.server.auth_file != NULL)
1956 se->data.server.userdb = fbh_create (se->data.server.auth_file);
1957 if (se->data.server.userdb == NULL)
1959 ERROR ("network plugin: Reading password file "
1961 se->data.server.auth_file);
1962 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1967 #endif /* }}} HAVE_LIBGCRYPT */
1970 service = se->service;
1972 if (service == NULL)
1973 service = NET_DEFAULT_PORT;
1975 DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
1978 memset (&ai_hints, 0, sizeof (ai_hints));
1979 ai_hints.ai_flags = 0;
1981 ai_hints.ai_flags |= AI_PASSIVE;
1983 #ifdef AI_ADDRCONFIG
1984 ai_hints.ai_flags |= AI_ADDRCONFIG;
1986 ai_hints.ai_family = AF_UNSPEC;
1987 ai_hints.ai_socktype = SOCK_DGRAM;
1988 ai_hints.ai_protocol = IPPROTO_UDP;
1990 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
1993 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
1994 (se->node == NULL) ? "(null)" : se->node,
1995 (se->service == NULL) ? "(null)" : se->service,
1996 gai_strerror (ai_return));
2000 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
2004 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
2008 tmp = realloc (se->data.server.fd,
2009 sizeof (*tmp) * (se->data.server.fd_num + 1));
2012 ERROR ("network plugin: realloc failed.");
2015 se->data.server.fd = tmp;
2016 tmp = se->data.server.fd + se->data.server.fd_num;
2018 *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
2019 ai_ptr->ai_protocol);
2023 ERROR ("network plugin: socket(2) failed: %s",
2024 sstrerror (errno, errbuf,
2029 status = network_bind_socket (*tmp, ai_ptr, se->interface);
2037 se->data.server.fd_num++;
2039 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
2040 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
2042 se->data.client.fd = socket (ai_ptr->ai_family,
2043 ai_ptr->ai_socktype,
2044 ai_ptr->ai_protocol);
2045 if (se->data.client.fd < 0)
2048 ERROR ("network plugin: socket(2) failed: %s",
2049 sstrerror (errno, errbuf,
2054 se->data.client.addr = malloc (sizeof (*se->data.client.addr));
2055 if (se->data.client.addr == NULL)
2057 ERROR ("network plugin: malloc failed.");
2058 close (se->data.client.fd);
2059 se->data.client.fd = -1;
2063 memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
2064 assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
2065 memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
2066 se->data.client.addrlen = ai_ptr->ai_addrlen;
2068 network_set_ttl (se, ai_ptr);
2069 network_set_interface (se, ai_ptr);
2071 /* We don't open more than one write-socket per
2072 * node/service pair.. */
2074 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
2075 } /* for (ai_list) */
2077 freeaddrinfo (ai_list);
2079 /* Check if all went well. */
2080 if (se->type == SOCKENT_TYPE_SERVER)
2082 if (se->data.server.fd_num <= 0)
2085 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2087 if (se->data.client.fd < 0)
2092 } /* }}} int sockent_open */
2094 /* Add a sockent to the global list of sockets */
2095 static int sockent_add (sockent_t *se) /* {{{ */
2097 sockent_t *last_ptr;
2102 if (se->type == SOCKENT_TYPE_SERVER)
2107 tmp = realloc (listen_sockets_pollfd,
2108 sizeof (*tmp) * (listen_sockets_num
2109 + se->data.server.fd_num));
2112 ERROR ("network plugin: realloc failed.");
2115 listen_sockets_pollfd = tmp;
2116 tmp = listen_sockets_pollfd + listen_sockets_num;
2118 for (i = 0; i < se->data.server.fd_num; i++)
2120 memset (tmp + i, 0, sizeof (*tmp));
2121 tmp[i].fd = se->data.server.fd[i];
2122 tmp[i].events = POLLIN | POLLPRI;
2126 listen_sockets_num += se->data.server.fd_num;
2128 if (listen_sockets == NULL)
2130 listen_sockets = se;
2133 last_ptr = listen_sockets;
2135 else /* if (se->type == SOCKENT_TYPE_CLIENT) */
2137 if (sending_sockets == NULL)
2139 sending_sockets = se;
2142 last_ptr = sending_sockets;
2145 while (last_ptr->next != NULL)
2146 last_ptr = last_ptr->next;
2147 last_ptr->next = se;
2150 } /* }}} int sockent_add */
2152 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
2156 receive_list_entry_t *ent;
2159 /* Lock and wait for more data to come in */
2160 pthread_mutex_lock (&receive_list_lock);
2161 while ((listen_loop == 0)
2162 && (receive_list_head == NULL))
2163 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
2165 /* Remove the head entry and unlock */
2166 ent = receive_list_head;
2168 receive_list_head = ent->next;
2169 receive_list_length--;
2170 pthread_mutex_unlock (&receive_list_lock);
2172 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
2173 * because we dispatch all missing packets before shutting down. */
2177 /* Look for the correct `sockent_t' */
2178 se = listen_sockets;
2183 for (i = 0; i < se->data.server.fd_num; i++)
2184 if (se->data.server.fd[i] == ent->fd)
2187 if (i < se->data.server.fd_num)
2195 ERROR ("network plugin: Got packet from FD %i, but can't "
2196 "find an appropriate socket entry.",
2203 parse_packet (se, ent->data, ent->data_len, /* flags = */ 0,
2204 /* username = */ NULL);
2210 } /* }}} void *dispatch_thread */
2212 static int network_receive (void) /* {{{ */
2214 char buffer[network_config_packet_size];
2220 receive_list_entry_t *private_list_head;
2221 receive_list_entry_t *private_list_tail;
2222 uint64_t private_list_length;
2224 assert (listen_sockets_num > 0);
2226 private_list_head = NULL;
2227 private_list_tail = NULL;
2228 private_list_length = 0;
2230 while (listen_loop == 0)
2232 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2239 ERROR ("poll failed: %s",
2240 sstrerror (errno, errbuf, sizeof (errbuf)));
2244 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2246 receive_list_entry_t *ent;
2248 if ((listen_sockets_pollfd[i].revents
2249 & (POLLIN | POLLPRI)) == 0)
2253 buffer_len = recv (listen_sockets_pollfd[i].fd,
2254 buffer, sizeof (buffer),
2259 ERROR ("recv failed: %s",
2260 sstrerror (errno, errbuf,
2265 stats_octets_rx += ((uint64_t) buffer_len);
2268 /* TODO: Possible performance enhancement: Do not free
2269 * these entries in the dispatch thread but put them in
2270 * another list, so we don't have to allocate more and
2271 * more of these structures. */
2272 ent = malloc (sizeof (receive_list_entry_t));
2275 ERROR ("network plugin: malloc failed.");
2278 memset (ent, 0, sizeof (receive_list_entry_t));
2279 ent->data = malloc (network_config_packet_size);
2280 if (ent->data == NULL)
2283 ERROR ("network plugin: malloc failed.");
2286 ent->fd = listen_sockets_pollfd[i].fd;
2289 memcpy (ent->data, buffer, buffer_len);
2290 ent->data_len = buffer_len;
2292 if (private_list_head == NULL)
2293 private_list_head = ent;
2295 private_list_tail->next = ent;
2296 private_list_tail = ent;
2297 private_list_length++;
2299 /* Do not block here. Blocking here has led to
2300 * insufficient performance in the past. */
2301 if (pthread_mutex_trylock (&receive_list_lock) == 0)
2303 assert (((receive_list_head == NULL) && (receive_list_length == 0))
2304 || ((receive_list_head != NULL) && (receive_list_length != 0)));
2306 if (receive_list_head == NULL)
2307 receive_list_head = private_list_head;
2309 receive_list_tail->next = private_list_head;
2310 receive_list_tail = private_list_tail;
2311 receive_list_length += private_list_length;
2313 pthread_cond_signal (&receive_list_cond);
2314 pthread_mutex_unlock (&receive_list_lock);
2316 private_list_head = NULL;
2317 private_list_tail = NULL;
2318 private_list_length = 0;
2320 } /* for (listen_sockets_pollfd) */
2321 } /* while (listen_loop == 0) */
2323 /* Make sure everything is dispatched before exiting. */
2324 if (private_list_head != NULL)
2326 pthread_mutex_lock (&receive_list_lock);
2328 if (receive_list_head == NULL)
2329 receive_list_head = private_list_head;
2331 receive_list_tail->next = private_list_head;
2332 receive_list_tail = private_list_tail;
2333 receive_list_length += private_list_length;
2335 private_list_head = NULL;
2336 private_list_tail = NULL;
2337 private_list_length = 0;
2339 pthread_cond_signal (&receive_list_cond);
2340 pthread_mutex_unlock (&receive_list_lock);
2344 } /* }}} int network_receive */
2346 static void *receive_thread (void __attribute__((unused)) *arg)
2348 return (network_receive () ? (void *) 1 : (void *) 0);
2349 } /* void *receive_thread */
2351 static void network_init_buffer (void)
2353 memset (send_buffer, 0, network_config_packet_size);
2354 send_buffer_ptr = send_buffer;
2355 send_buffer_fill = 0;
2357 memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2358 } /* int network_init_buffer */
2360 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2361 const char *buffer, size_t buffer_size)
2367 status = sendto (se->data.client.fd, buffer, buffer_size,
2369 (struct sockaddr *) se->data.client.addr,
2370 se->data.client.addrlen);
2376 ERROR ("network plugin: sendto failed: %s",
2377 sstrerror (errno, errbuf,
2384 } /* }}} void networt_send_buffer_plain */
2387 #define BUFFER_ADD(p,s) do { \
2388 memcpy (buffer + buffer_offset, (p), (s)); \
2389 buffer_offset += (s); \
2392 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2393 const char *in_buffer, size_t in_buffer_size)
2395 part_signature_sha256_t ps;
2396 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2397 size_t buffer_offset;
2398 size_t username_len;
2402 unsigned char *hash;
2405 err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2408 ERROR ("network plugin: Creating HMAC object failed: %s",
2409 gcry_strerror (err));
2413 err = gcry_md_setkey (hd, se->data.client.password,
2414 strlen (se->data.client.password));
2417 ERROR ("network plugin: gcry_md_setkey failed: %s",
2418 gcry_strerror (err));
2423 username_len = strlen (se->data.client.username);
2424 if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2426 ERROR ("network plugin: Username too long: %s",
2427 se->data.client.username);
2431 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2432 se->data.client.username, username_len);
2433 memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2434 in_buffer, in_buffer_size);
2436 /* Initialize the `ps' structure. */
2437 memset (&ps, 0, sizeof (ps));
2438 ps.head.type = htons (TYPE_SIGN_SHA256);
2439 ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2441 /* Calculate the hash value. */
2442 gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2443 username_len + in_buffer_size);
2444 hash = gcry_md_read (hd, GCRY_MD_SHA256);
2447 ERROR ("network plugin: gcry_md_read failed.");
2451 memcpy (ps.hash, hash, sizeof (ps.hash));
2453 /* Add the header */
2456 BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2457 BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2458 BUFFER_ADD (ps.hash, sizeof (ps.hash));
2460 assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2465 buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2466 networt_send_buffer_plain (se, buffer, buffer_offset);
2467 } /* }}} void networt_send_buffer_signed */
2469 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2470 const char *in_buffer, size_t in_buffer_size)
2472 part_encryption_aes256_t pea;
2473 char buffer[BUFF_SIG_SIZE + in_buffer_size];
2475 size_t buffer_offset;
2477 size_t username_len;
2479 gcry_cipher_hd_t cypher;
2481 /* Initialize the header fields */
2482 memset (&pea, 0, sizeof (pea));
2483 pea.head.type = htons (TYPE_ENCR_AES256);
2485 pea.username = se->data.client.username;
2487 username_len = strlen (pea.username);
2488 if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2490 ERROR ("network plugin: Username too long: %s", pea.username);
2494 buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2495 header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2496 - sizeof (pea.hash);
2498 assert (buffer_size <= sizeof (buffer));
2499 DEBUG ("network plugin: networt_send_buffer_encrypted: "
2500 "buffer_size = %zu;", buffer_size);
2502 pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2503 + username_len + in_buffer_size));
2504 pea.username_length = htons ((uint16_t) username_len);
2506 /* Chose a random initialization vector. */
2507 gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2509 /* Create hash of the payload */
2510 gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2512 /* Initialize the buffer */
2514 memset (buffer, 0, sizeof (buffer));
2517 BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2518 BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2519 BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2520 BUFFER_ADD (pea.username, username_len);
2521 BUFFER_ADD (pea.iv, sizeof (pea.iv));
2522 assert (buffer_offset == header_size);
2523 BUFFER_ADD (pea.hash, sizeof (pea.hash));
2524 BUFFER_ADD (in_buffer, in_buffer_size);
2526 assert (buffer_offset == buffer_size);
2528 cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2529 se->data.client.password);
2533 /* Encrypt the buffer in-place */
2534 err = gcry_cipher_encrypt (cypher,
2535 buffer + header_size,
2536 buffer_size - header_size,
2537 /* in = */ NULL, /* in len = */ 0);
2540 ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2541 gcry_strerror (err));
2545 /* Send it out without further modifications */
2546 networt_send_buffer_plain (se, buffer, buffer_size);
2547 } /* }}} void networt_send_buffer_encrypted */
2549 #endif /* HAVE_LIBGCRYPT */
2551 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2555 DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2557 for (se = sending_sockets; se != NULL; se = se->next)
2560 if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2561 networt_send_buffer_encrypted (se, buffer, buffer_len);
2562 else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2563 networt_send_buffer_signed (se, buffer, buffer_len);
2564 else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2565 #endif /* HAVE_LIBGCRYPT */
2566 networt_send_buffer_plain (se, buffer, buffer_len);
2567 } /* for (sending_sockets) */
2568 } /* }}} void network_send_buffer */
2570 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2571 value_list_t *vl_def,
2572 const data_set_t *ds, const value_list_t *vl)
2574 char *buffer_orig = buffer;
2576 if (strcmp (vl_def->host, vl->host) != 0)
2578 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2579 vl->host, strlen (vl->host)) != 0)
2581 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2584 if (vl_def->time != vl->time)
2586 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2587 (uint64_t) vl->time))
2589 vl_def->time = vl->time;
2592 if (vl_def->interval != vl->interval)
2594 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2595 (uint64_t) vl->interval))
2597 vl_def->interval = vl->interval;
2600 if (strcmp (vl_def->plugin, vl->plugin) != 0)
2602 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2603 vl->plugin, strlen (vl->plugin)) != 0)
2605 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2608 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2610 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2611 vl->plugin_instance,
2612 strlen (vl->plugin_instance)) != 0)
2614 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2617 if (strcmp (vl_def->type, vl->type) != 0)
2619 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2620 vl->type, strlen (vl->type)) != 0)
2622 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2625 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2627 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2629 strlen (vl->type_instance)) != 0)
2631 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2634 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2637 return (buffer - buffer_orig);
2638 } /* }}} int add_to_buffer */
2640 static void flush_buffer (void)
2642 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2645 network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2647 stats_octets_tx += ((uint64_t) send_buffer_fill);
2650 network_init_buffer ();
2653 static int network_write (const data_set_t *ds, const value_list_t *vl,
2654 user_data_t __attribute__((unused)) *user_data)
2658 if (!check_send_okay (vl))
2661 char name[6*DATA_MAX_NAME_LEN];
2662 FORMAT_VL (name, sizeof (name), vl);
2663 name[sizeof (name) - 1] = 0;
2664 DEBUG ("network plugin: network_write: "
2665 "NOT sending %s.", name);
2667 /* Counter is not protected by another lock and may be reached by
2668 * multiple threads */
2669 pthread_mutex_lock (&stats_lock);
2670 stats_values_not_sent++;
2671 pthread_mutex_unlock (&stats_lock);
2675 uc_meta_data_add_unsigned_int (vl,
2676 "network:time_sent", (uint64_t) vl->time);
2678 pthread_mutex_lock (&send_buffer_lock);
2680 status = add_to_buffer (send_buffer_ptr,
2681 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2686 /* status == bytes added to the buffer */
2687 send_buffer_fill += status;
2688 send_buffer_ptr += status;
2690 stats_values_sent++;
2696 status = add_to_buffer (send_buffer_ptr,
2697 network_config_packet_size - (send_buffer_fill + BUFF_SIG_SIZE),
2703 send_buffer_fill += status;
2704 send_buffer_ptr += status;
2706 stats_values_sent++;
2712 ERROR ("network plugin: Unable to append to the "
2713 "buffer for some weird reason");
2715 else if ((network_config_packet_size - send_buffer_fill) < 15)
2720 pthread_mutex_unlock (&send_buffer_lock);
2722 return ((status < 0) ? -1 : 0);
2723 } /* int network_write */
2725 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2728 if ((ci->values_num != 1)
2729 || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2730 && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2732 ERROR ("network plugin: The `%s' config option needs "
2733 "exactly one boolean argument.", ci->key);
2737 if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2739 if (ci->values[0].value.boolean)
2746 char *str = ci->values[0].value.string;
2750 else if (IS_FALSE (str))
2754 ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2755 "option as boolean value.",
2762 } /* }}} int network_config_set_boolean */
2764 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2767 if ((ci->values_num != 1)
2768 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2770 WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2771 "one numeric argument.");
2775 tmp = (int) ci->values[0].value.number;
2776 if ((tmp > 0) && (tmp <= 255))
2777 network_config_ttl = tmp;
2780 } /* }}} int network_config_set_ttl */
2782 static int network_config_set_interface (const oconfig_item_t *ci, /* {{{ */
2785 if ((ci->values_num != 1)
2786 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2788 WARNING ("network plugin: The `Interface' config option needs exactly "
2789 "one string argument.");
2793 if (interface == NULL)
2796 *interface = if_nametoindex (ci->values[0].value.string);
2799 } /* }}} int network_config_set_interface */
2801 static int network_config_set_buffer_size (const oconfig_item_t *ci) /* {{{ */
2804 if ((ci->values_num != 1)
2805 || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2807 WARNING ("network plugin: The `MaxPacketSize' config option needs exactly "
2808 "one numeric argument.");
2812 tmp = (int) ci->values[0].value.number;
2813 if ((tmp >= 1024) && (tmp <= 65535))
2814 network_config_packet_size = tmp;
2817 } /* }}} int network_config_set_buffer_size */
2820 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2824 if ((ci->values_num != 1)
2825 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2827 WARNING ("network plugin: The `%s' config option needs exactly "
2828 "one string argument.", ci->key);
2832 tmp = strdup (ci->values[0].value.string);
2836 sfree (*ret_string);
2840 } /* }}} int network_config_set_string */
2841 #endif /* HAVE_LIBGCRYPT */
2844 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2848 if ((ci->values_num != 1)
2849 || (ci->values[0].type != OCONFIG_TYPE_STRING))
2851 WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2852 "one string argument.");
2856 str = ci->values[0].value.string;
2857 if (strcasecmp ("Encrypt", str) == 0)
2858 *retval = SECURITY_LEVEL_ENCRYPT;
2859 else if (strcasecmp ("Sign", str) == 0)
2860 *retval = SECURITY_LEVEL_SIGN;
2861 else if (strcasecmp ("None", str) == 0)
2862 *retval = SECURITY_LEVEL_NONE;
2865 WARNING ("network plugin: Unknown security level: %s.", str);
2870 } /* }}} int network_config_set_security_level */
2871 #endif /* HAVE_LIBGCRYPT */
2873 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2879 if ((ci->values_num < 1) || (ci->values_num > 2)
2880 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2881 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2883 ERROR ("network plugin: The `%s' config option needs "
2884 "one or two string arguments.", ci->key);
2888 se = malloc (sizeof (*se));
2891 ERROR ("network plugin: malloc failed.");
2894 sockent_init (se, SOCKENT_TYPE_SERVER);
2896 se->node = strdup (ci->values[0].value.string);
2897 if (ci->values_num >= 2)
2898 se->service = strdup (ci->values[1].value.string);
2900 for (i = 0; i < ci->children_num; i++)
2902 oconfig_item_t *child = ci->children + i;
2905 if (strcasecmp ("AuthFile", child->key) == 0)
2906 network_config_set_string (child, &se->data.server.auth_file);
2907 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2908 network_config_set_security_level (child,
2909 &se->data.server.security_level);
2911 #endif /* HAVE_LIBGCRYPT */
2912 if (strcasecmp ("Interface", child->key) == 0)
2913 network_config_set_interface (child,
2917 WARNING ("network plugin: Option `%s' is not allowed here.",
2923 if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
2924 && (se->data.server.auth_file == NULL))
2926 ERROR ("network plugin: A security level higher than `none' was "
2927 "requested, but no AuthFile option was given. Cowardly refusing to "
2928 "open this socket!");
2929 sockent_destroy (se);
2932 #endif /* HAVE_LIBGCRYPT */
2934 status = sockent_open (se);
2937 ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
2938 sockent_destroy (se);
2942 status = sockent_add (se);
2945 ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
2946 sockent_destroy (se);
2951 } /* }}} int network_config_add_listen */
2953 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
2959 if ((ci->values_num < 1) || (ci->values_num > 2)
2960 || (ci->values[0].type != OCONFIG_TYPE_STRING)
2961 || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2963 ERROR ("network plugin: The `%s' config option needs "
2964 "one or two string arguments.", ci->key);
2968 se = malloc (sizeof (*se));
2971 ERROR ("network plugin: malloc failed.");
2974 sockent_init (se, SOCKENT_TYPE_CLIENT);
2976 se->node = strdup (ci->values[0].value.string);
2977 if (ci->values_num >= 2)
2978 se->service = strdup (ci->values[1].value.string);
2980 for (i = 0; i < ci->children_num; i++)
2982 oconfig_item_t *child = ci->children + i;
2985 if (strcasecmp ("Username", child->key) == 0)
2986 network_config_set_string (child, &se->data.client.username);
2987 else if (strcasecmp ("Password", child->key) == 0)
2988 network_config_set_string (child, &se->data.client.password);
2989 else if (strcasecmp ("SecurityLevel", child->key) == 0)
2990 network_config_set_security_level (child,
2991 &se->data.client.security_level);
2993 #endif /* HAVE_LIBGCRYPT */
2994 if (strcasecmp ("Interface", child->key) == 0)
2995 network_config_set_interface (child,
2999 WARNING ("network plugin: Option `%s' is not allowed here.",
3005 if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
3006 && ((se->data.client.username == NULL)
3007 || (se->data.client.password == NULL)))
3009 ERROR ("network plugin: A security level higher than `none' was "
3010 "requested, but no Username or Password option was given. "
3011 "Cowardly refusing to open this socket!");
3012 sockent_destroy (se);
3015 #endif /* HAVE_LIBGCRYPT */
3017 status = sockent_open (se);
3020 ERROR ("network plugin: network_config_add_server: sockent_open failed.");
3021 sockent_destroy (se);
3025 status = sockent_add (se);
3028 ERROR ("network plugin: network_config_add_server: sockent_add failed.");
3029 sockent_destroy (se);
3034 } /* }}} int network_config_add_server */
3036 static int network_config (oconfig_item_t *ci) /* {{{ */
3040 for (i = 0; i < ci->children_num; i++)
3042 oconfig_item_t *child = ci->children + i;
3044 if (strcasecmp ("Listen", child->key) == 0)
3045 network_config_add_listen (child);
3046 else if (strcasecmp ("Server", child->key) == 0)
3047 network_config_add_server (child);
3048 else if (strcasecmp ("TimeToLive", child->key) == 0)
3049 network_config_set_ttl (child);
3050 else if (strcasecmp ("MaxPacketSize", child->key) == 0)
3051 network_config_set_buffer_size (child);
3052 else if (strcasecmp ("Forward", child->key) == 0)
3053 network_config_set_boolean (child, &network_config_forward);
3054 else if (strcasecmp ("ReportStats", child->key) == 0)
3055 network_config_set_boolean (child, &network_config_stats);
3058 WARNING ("network plugin: Option `%s' is not allowed here.",
3064 } /* }}} int network_config */
3066 static int network_notification (const notification_t *n,
3067 user_data_t __attribute__((unused)) *user_data)
3069 char buffer[network_config_packet_size];
3070 char *buffer_ptr = buffer;
3071 int buffer_free = sizeof (buffer);
3074 memset (buffer, '\0', sizeof (buffer));
3077 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
3078 (uint64_t) n->time);
3082 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
3083 (uint64_t) n->severity);
3087 if (strlen (n->host) > 0)
3089 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
3090 n->host, strlen (n->host));
3095 if (strlen (n->plugin) > 0)
3097 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
3098 n->plugin, strlen (n->plugin));
3103 if (strlen (n->plugin_instance) > 0)
3105 status = write_part_string (&buffer_ptr, &buffer_free,
3106 TYPE_PLUGIN_INSTANCE,
3107 n->plugin_instance, strlen (n->plugin_instance));
3112 if (strlen (n->type) > 0)
3114 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
3115 n->type, strlen (n->type));
3120 if (strlen (n->type_instance) > 0)
3122 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
3123 n->type_instance, strlen (n->type_instance));
3128 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
3129 n->message, strlen (n->message));
3133 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
3136 } /* int network_notification */
3138 static int network_shutdown (void)
3142 /* Kill the listening thread */
3143 if (receive_thread_running != 0)
3145 INFO ("network plugin: Stopping receive thread.");
3146 pthread_kill (receive_thread_id, SIGTERM);
3147 pthread_join (receive_thread_id, NULL /* no return value */);
3148 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
3149 receive_thread_running = 0;
3152 /* Shutdown the dispatching thread */
3153 if (dispatch_thread_running != 0)
3155 INFO ("network plugin: Stopping dispatch thread.");
3156 pthread_mutex_lock (&receive_list_lock);
3157 pthread_cond_broadcast (&receive_list_cond);
3158 pthread_mutex_unlock (&receive_list_lock);
3159 pthread_join (dispatch_thread_id, /* ret = */ NULL);
3160 dispatch_thread_running = 0;
3163 sockent_destroy (listen_sockets);
3165 if (send_buffer_fill > 0)
3168 sfree (send_buffer);
3170 /* TODO: Close `sending_sockets' */
3172 plugin_unregister_config ("network");
3173 plugin_unregister_init ("network");
3174 plugin_unregister_write ("network");
3175 plugin_unregister_shutdown ("network");
3178 } /* int network_shutdown */
3180 static int network_stats_read (void) /* {{{ */
3182 uint64_t copy_octets_rx;
3183 uint64_t copy_octets_tx;
3184 uint64_t copy_packets_rx;
3185 uint64_t copy_packets_tx;
3186 uint64_t copy_values_dispatched;
3187 uint64_t copy_values_not_dispatched;
3188 uint64_t copy_values_sent;
3189 uint64_t copy_values_not_sent;
3190 uint64_t copy_receive_list_length;
3191 value_list_t vl = VALUE_LIST_INIT;
3194 copy_octets_rx = stats_octets_rx;
3195 copy_octets_tx = stats_octets_tx;
3196 copy_packets_rx = stats_packets_rx;
3197 copy_packets_tx = stats_packets_tx;
3198 copy_values_dispatched = stats_values_dispatched;
3199 copy_values_not_dispatched = stats_values_not_dispatched;
3200 copy_values_sent = stats_values_sent;
3201 copy_values_not_sent = stats_values_not_sent;
3202 copy_receive_list_length = receive_list_length;
3204 /* Initialize `vl' */
3208 vl.interval = interval_g;
3209 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
3210 sstrncpy (vl.plugin, "network", sizeof (vl.plugin));
3212 /* Octets received / sent */
3213 vl.values[0].counter = (counter_t) copy_octets_rx;
3214 vl.values[1].counter = (counter_t) copy_octets_tx;
3215 sstrncpy (vl.type, "if_octets", sizeof (vl.type));
3216 plugin_dispatch_values (&vl);
3218 /* Packets received / send */
3219 vl.values[0].counter = (counter_t) copy_packets_rx;
3220 vl.values[1].counter = (counter_t) copy_packets_tx;
3221 sstrncpy (vl.type, "if_packets", sizeof (vl.type));
3222 plugin_dispatch_values (&vl);
3224 /* Values (not) dispatched and (not) send */
3225 sstrncpy (vl.type, "total_values", sizeof (vl.type));
3228 vl.values[0].derive = (derive_t) copy_values_dispatched;
3229 sstrncpy (vl.type_instance, "dispatch-accepted",
3230 sizeof (vl.type_instance));
3231 plugin_dispatch_values (&vl);
3233 vl.values[0].derive = (derive_t) copy_values_not_dispatched;
3234 sstrncpy (vl.type_instance, "dispatch-rejected",
3235 sizeof (vl.type_instance));
3236 plugin_dispatch_values (&vl);
3238 vl.values[0].derive = (derive_t) copy_values_sent;
3239 sstrncpy (vl.type_instance, "send-accepted",
3240 sizeof (vl.type_instance));
3241 plugin_dispatch_values (&vl);
3243 vl.values[0].derive = (derive_t) copy_values_not_sent;
3244 sstrncpy (vl.type_instance, "send-rejected",
3245 sizeof (vl.type_instance));
3246 plugin_dispatch_values (&vl);
3248 /* Receive queue length */
3249 vl.values[0].gauge = (gauge_t) copy_receive_list_length;
3250 sstrncpy (vl.type, "queue_length", sizeof (vl.type));
3251 vl.type_instance[0] = 0;
3252 plugin_dispatch_values (&vl);
3255 } /* }}} int network_stats_read */
3257 static int network_init (void)
3259 static _Bool have_init = false;
3261 /* Check if we were already initialized. If so, just return - there's
3262 * nothing more to do (for now, that is). */
3268 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3269 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
3270 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
3273 if (network_config_stats != 0)
3274 plugin_register_read ("network", network_stats_read);
3276 plugin_register_shutdown ("network", network_shutdown);
3278 send_buffer = malloc (network_config_packet_size);
3279 if (send_buffer == NULL)
3281 ERROR ("network plugin: malloc failed.");
3284 network_init_buffer ();
3286 /* setup socket(s) and so on */
3287 if (sending_sockets != NULL)
3289 plugin_register_write ("network", network_write,
3290 /* user_data = */ NULL);
3291 plugin_register_notification ("network", network_notification,
3292 /* user_data = */ NULL);
3295 /* If no threads need to be started, return here. */
3296 if ((listen_sockets_num == 0)
3297 || ((dispatch_thread_running != 0)
3298 && (receive_thread_running != 0)))
3301 if (dispatch_thread_running == 0)
3304 status = pthread_create (&dispatch_thread_id,
3305 NULL /* no attributes */,
3307 NULL /* no argument */);
3311 ERROR ("network: pthread_create failed: %s",
3312 sstrerror (errno, errbuf,
3317 dispatch_thread_running = 1;
3321 if (receive_thread_running == 0)
3324 status = pthread_create (&receive_thread_id,
3325 NULL /* no attributes */,
3327 NULL /* no argument */);
3331 ERROR ("network: pthread_create failed: %s",
3332 sstrerror (errno, errbuf,
3337 receive_thread_running = 1;
3342 } /* int network_init */
3345 * The flush option of the network plugin cannot flush individual identifiers.
3346 * All the values are added to a buffer and sent when the buffer is full, the
3347 * requested value may or may not be in there, it's not worth finding out. We
3348 * just send the buffer if `flush' is called - if the requested value was in
3349 * there, good. If not, well, then there is nothing to flush.. -octo
3351 static int network_flush (int timeout,
3352 const char __attribute__((unused)) *identifier,
3353 user_data_t __attribute__((unused)) *user_data)
3355 pthread_mutex_lock (&send_buffer_lock);
3357 if (send_buffer_fill > 0)
3360 pthread_mutex_unlock (&send_buffer_lock);
3363 } /* int network_flush */
3365 void module_register (void)
3367 plugin_register_complex_config ("network", network_config);
3368 plugin_register_init ("network", network_init);
3369 plugin_register_flush ("network", network_flush,
3370 /* user_data = */ NULL);
3371 } /* void module_register */
3373 /* vim: set fdm=marker : */