2 * collectd - src/network.c
3 * Copyright (C) 2005-2008 Florian octo Forster
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Florian octo Forster <octo at verplant.org>
25 #include "configfile.h"
26 #include "utils_avltree.h"
34 # include <sys/socket.h>
40 # include <netinet/in.h>
43 # include <arpa/inet.h>
49 /* 1500 - 40 - 8 = Ethernet packet - IPv6 header - UDP header */
50 /* #define BUFF_SIZE 1452 */
52 #ifndef IPV6_ADD_MEMBERSHIP
53 # ifdef IPV6_JOIN_GROUP
54 # define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
56 # error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
58 #endif /* !IP_ADD_MEMBERSHIP */
60 #define BUFF_SIZE 1024
65 typedef struct sockent
68 struct sockaddr_storage *addr;
73 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
74 * 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
75 * +-------+-----------------------+-------------------------------+
77 * +-------+-----------------------+-------------------------------+
84 typedef struct part_header_s part_header_t;
86 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
87 * 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
88 * +-------------------------------+-------------------------------+
90 * +-------------------------------+-------------------------------+
91 * : (Length - 4) Bytes :
92 * +---------------------------------------------------------------+
99 typedef struct part_string_s part_string_t;
101 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
102 * 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
103 * +-------------------------------+-------------------------------+
105 * +-------------------------------+-------------------------------+
106 * : (Length - 4 == 2 || 4 || 8) Bytes :
107 * +---------------------------------------------------------------+
114 typedef struct part_number_s part_number_t;
116 /* 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
117 * 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
118 * +-------------------------------+-------------------------------+
120 * +-------------------------------+---------------+---------------+
121 * ! Num of values ! Type0 ! Type1 !
122 * +-------------------------------+---------------+---------------+
125 * +---------------------------------------------------------------+
128 * +---------------------------------------------------------------+
133 uint16_t *num_values;
134 uint8_t *values_types;
137 typedef struct part_values_s part_values_t;
139 struct receive_list_entry_s
141 char data[BUFF_SIZE];
143 struct receive_list_entry_s *next;
145 typedef struct receive_list_entry_s receive_list_entry_t;
150 static const char *config_keys[] =
158 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
160 static int network_config_ttl = 0;
161 static int network_config_forward = 0;
163 static sockent_t *sending_sockets = NULL;
165 static receive_list_entry_t *receive_list_head = NULL;
166 static receive_list_entry_t *receive_list_tail = NULL;
167 static pthread_mutex_t receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
168 static pthread_cond_t receive_list_cond = PTHREAD_COND_INITIALIZER;
170 static struct pollfd *listen_sockets = NULL;
171 static int listen_sockets_num = 0;
173 static int listen_loop = 0;
174 static pthread_t receive_thread_id = 0;
175 static pthread_t dispatch_thread_id = 0;
177 static char send_buffer[BUFF_SIZE];
178 static char *send_buffer_ptr;
179 static int send_buffer_fill;
180 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
181 static char send_buffer_type[DATA_MAX_NAME_LEN];
182 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
184 static c_avl_tree_t *cache_tree = NULL;
185 static pthread_mutex_t cache_lock = PTHREAD_MUTEX_INITIALIZER;
186 static time_t cache_flush_last;
187 static int cache_flush_interval = 1800;
192 static int cache_flush (void)
202 c_avl_iterator_t *iter;
204 time_t curtime = time (NULL);
206 iter = c_avl_get_iterator (cache_tree);
207 while (c_avl_iterator_next (iter, (void *) &key, (void *) &value) == 0)
209 if ((curtime - *value) <= cache_flush_interval)
211 tmp = (char **) realloc (keys,
212 (keys_num + 1) * sizeof (char *));
216 c_avl_iterator_destroy (iter);
217 ERROR ("network plugin: cache_flush: realloc"
222 keys[keys_num] = key;
224 } /* while (c_avl_iterator_next) */
225 c_avl_iterator_destroy (iter);
227 for (i = 0; i < keys_num; i++)
229 if (c_avl_remove (cache_tree, keys[i], (void *) &key,
230 (void *) &value) != 0)
232 WARNING ("network plugin: cache_flush: c_avl_remove"
233 " (%s) failed.", keys[i]);
243 DEBUG ("network plugin: cache_flush: Removed %i %s",
244 keys_num, (keys_num == 1) ? "entry" : "entries");
245 cache_flush_last = curtime;
247 } /* int cache_flush */
249 static int cache_check (const char *type, const value_list_t *vl)
252 time_t *value = NULL;
255 if (cache_tree == NULL)
258 if (format_name (key, sizeof (key), vl->host, vl->plugin,
259 vl->plugin_instance, type, vl->type_instance))
262 pthread_mutex_lock (&cache_lock);
264 if (c_avl_get (cache_tree, key, (void *) &value) == 0)
266 if (*value < vl->time)
273 DEBUG ("network plugin: cache_check: *value = %i >= vl->time = %i",
274 (int) *value, (int) vl->time);
280 char *key_copy = strdup (key);
281 value = malloc (sizeof (time_t));
282 if ((key_copy != NULL) && (value != NULL))
285 c_avl_insert (cache_tree, key_copy, value);
295 if ((time (NULL) - cache_flush_last) > cache_flush_interval)
298 pthread_mutex_unlock (&cache_lock);
300 DEBUG ("network plugin: cache_check: key = %s; time = %i; retval = %i",
301 key, (int) vl->time, retval);
304 } /* int cache_check */
306 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
307 const data_set_t *ds, const value_list_t *vl)
313 part_header_t pkg_ph;
314 uint16_t pkg_num_values;
315 uint8_t *pkg_values_types;
321 num_values = vl->values_len;
322 packet_len = sizeof (part_header_t) + sizeof (uint16_t)
323 + (num_values * sizeof (uint8_t))
324 + (num_values * sizeof (value_t));
326 if (*ret_buffer_len < packet_len)
329 pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
330 if (pkg_values_types == NULL)
332 ERROR ("network plugin: write_part_values: malloc failed.");
336 pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
337 if (pkg_values == NULL)
339 free (pkg_values_types);
340 ERROR ("network plugin: write_part_values: malloc failed.");
344 pkg_ph.type = htons (TYPE_VALUES);
345 pkg_ph.length = htons (packet_len);
347 pkg_num_values = htons ((uint16_t) vl->values_len);
349 for (i = 0; i < num_values; i++)
351 if (ds->ds[i].type == DS_TYPE_COUNTER)
353 pkg_values_types[i] = DS_TYPE_COUNTER;
354 pkg_values[i].counter = htonll (vl->values[i].counter);
358 pkg_values_types[i] = DS_TYPE_GAUGE;
359 pkg_values[i].gauge = htond (vl->values[i].gauge);
364 * Use `memcpy' to write everything to the buffer, because the pointer
365 * may be unaligned and some architectures, such as SPARC, can't handle
368 packet_ptr = *ret_buffer;
370 memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
371 offset += sizeof (pkg_ph);
372 memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
373 offset += sizeof (pkg_num_values);
374 memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
375 offset += num_values * sizeof (uint8_t);
376 memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
377 offset += num_values * sizeof (value_t);
379 assert (offset == packet_len);
381 *ret_buffer = packet_ptr + packet_len;
382 *ret_buffer_len -= packet_len;
384 free (pkg_values_types);
388 } /* int write_part_values */
390 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
391 int type, uint64_t value)
396 part_header_t pkg_head;
401 packet_len = sizeof (pkg_head) + sizeof (pkg_value);
403 if (*ret_buffer_len < packet_len)
406 pkg_head.type = htons (type);
407 pkg_head.length = htons (packet_len);
408 pkg_value = htonll (value);
410 packet_ptr = *ret_buffer;
412 memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
413 offset += sizeof (pkg_head);
414 memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
415 offset += sizeof (pkg_value);
417 assert (offset == packet_len);
419 *ret_buffer = packet_ptr + packet_len;
420 *ret_buffer_len -= packet_len;
423 } /* int write_part_number */
425 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
426 int type, const char *str, int str_len)
436 buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
437 if (*ret_buffer_len < buffer_len)
440 pkg_type = htons (type);
441 pkg_length = htons (buffer_len);
443 buffer = *ret_buffer;
445 memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
446 offset += sizeof (pkg_type);
447 memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
448 offset += sizeof (pkg_length);
449 memcpy (buffer + offset, str, str_len);
451 memset (buffer + offset, '\0', 1);
454 assert (offset == buffer_len);
456 *ret_buffer = buffer + buffer_len;
457 *ret_buffer_len -= buffer_len;
460 } /* int write_part_string */
462 static int parse_part_values (void **ret_buffer, int *ret_buffer_len,
463 value_t **ret_values, int *ret_num_values)
465 char *buffer = *ret_buffer;
466 int buffer_len = *ret_buffer_len;
479 if (buffer_len < (15))
481 DEBUG ("network plugin: packet is too short: buffer_len = %i",
486 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
487 buffer += sizeof (tmp16);
488 pkg_type = ntohs (tmp16);
490 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
491 buffer += sizeof (tmp16);
492 pkg_length = ntohs (tmp16);
494 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
495 buffer += sizeof (tmp16);
496 pkg_numval = ntohs (tmp16);
498 assert (pkg_type == TYPE_VALUES);
500 exp_size = 3 * sizeof (uint16_t)
501 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
502 if (buffer_len < exp_size)
504 WARNING ("network plugin: parse_part_values: "
506 "Chunk of size %u expected, "
507 "but buffer has only %i bytes left.",
508 (unsigned int) exp_size, buffer_len);
512 if (pkg_length != exp_size)
514 WARNING ("network plugin: parse_part_values: "
515 "Length and number of values "
516 "in the packet don't match.");
520 pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
521 pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
522 if ((pkg_types == NULL) || (pkg_values == NULL))
526 ERROR ("network plugin: parse_part_values: malloc failed.");
530 memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
531 buffer += pkg_numval * sizeof (uint8_t);
532 memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
533 buffer += pkg_numval * sizeof (value_t);
535 for (i = 0; i < pkg_numval; i++)
537 if (pkg_types[i] == DS_TYPE_COUNTER)
538 pkg_values[i].counter = ntohll (pkg_values[i].counter);
539 else if (pkg_types[i] == DS_TYPE_GAUGE)
540 pkg_values[i].gauge = ntohd (pkg_values[i].gauge);
543 *ret_buffer = buffer;
544 *ret_buffer_len = buffer_len - pkg_length;
545 *ret_num_values = pkg_numval;
546 *ret_values = pkg_values;
551 } /* int parse_part_values */
553 static int parse_part_number (void **ret_buffer, int *ret_buffer_len,
556 char *buffer = *ret_buffer;
557 int buffer_len = *ret_buffer_len;
561 size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
566 if (buffer_len < exp_size)
568 WARNING ("network plugin: parse_part_number: "
570 "Chunk of size %u expected, "
571 "but buffer has only %i bytes left.",
572 (unsigned int) exp_size, buffer_len);
576 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
577 buffer += sizeof (tmp16);
578 pkg_type = ntohs (tmp16);
580 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
581 buffer += sizeof (tmp16);
582 pkg_length = ntohs (tmp16);
584 memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
585 buffer += sizeof (tmp64);
586 *value = ntohll (tmp64);
588 *ret_buffer = buffer;
589 *ret_buffer_len = buffer_len - pkg_length;
592 } /* int parse_part_number */
594 static int parse_part_string (void **ret_buffer, int *ret_buffer_len,
595 char *output, int output_len)
597 char *buffer = *ret_buffer;
598 int buffer_len = *ret_buffer_len;
601 size_t header_size = 2 * sizeof (uint16_t);
606 if (buffer_len < header_size)
608 WARNING ("network plugin: parse_part_string: "
610 "Chunk of at least size %u expected, "
611 "but buffer has only %i bytes left.",
612 (unsigned int) header_size, buffer_len);
616 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
617 buffer += sizeof (tmp16);
618 pkg_type = ntohs (tmp16);
620 memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
621 buffer += sizeof (tmp16);
622 pkg_length = ntohs (tmp16);
624 /* Check that packet fits in the input buffer */
625 if (pkg_length > buffer_len)
627 WARNING ("network plugin: parse_part_string: "
629 "Chunk of size %hu received, "
630 "but buffer has only %i bytes left.",
631 pkg_length, buffer_len);
635 /* Check that pkg_length is in the valid range */
636 if (pkg_length <= header_size)
638 WARNING ("network plugin: parse_part_string: "
640 "Header claims this packet is only %hu "
641 "bytes long.", pkg_length);
645 /* Check that the package data fits into the output buffer.
646 * The previous if-statement ensures that:
647 * `pkg_length > header_size' */
648 if ((pkg_length - header_size) > output_len)
650 WARNING ("network plugin: parse_part_string: "
651 "Output buffer too small.");
655 /* All sanity checks successfull, let's copy the data over */
656 output_len = pkg_length - header_size;
657 memcpy ((void *) output, (void *) buffer, output_len);
658 buffer += output_len;
660 /* For some very weird reason '\0' doesn't do the trick on SPARC in
662 if (output[output_len - 1] != 0)
664 WARNING ("network plugin: parse_part_string: "
665 "Received string does not end "
666 "with a NULL-byte.");
670 *ret_buffer = buffer;
671 *ret_buffer_len = buffer_len - pkg_length;
674 } /* int parse_part_string */
676 static int parse_packet (void *buffer, int buffer_len)
680 value_list_t vl = VALUE_LIST_INIT;
681 char type[DATA_MAX_NAME_LEN];
684 DEBUG ("network plugin: parse_packet: buffer = %p; buffer_len = %i;",
687 memset (&vl, '\0', sizeof (vl));
688 memset (&type, '\0', sizeof (type));
689 memset (&n, '\0', sizeof (n));
692 while ((status == 0) && (0 < buffer_len)
693 && ((unsigned int) buffer_len > sizeof (part_header_t)))
698 memcpy ((void *) &pkg_type,
701 memcpy ((void *) &pkg_length,
702 (void *) (buffer + sizeof (pkg_type)),
703 sizeof (pkg_length));
705 pkg_length = ntohs (pkg_length);
706 pkg_type = ntohs (pkg_type);
708 if (pkg_length > buffer_len)
710 /* Ensure that this loop terminates eventually */
711 if (pkg_length < (2 * sizeof (uint16_t)))
714 if (pkg_type == TYPE_VALUES)
716 status = parse_part_values (&buffer, &buffer_len,
717 &vl.values, &vl.values_len);
723 && (strlen (vl.host) > 0)
724 && (strlen (vl.plugin) > 0)
725 && (strlen (type) > 0)
726 && (cache_check (type, &vl) == 0))
728 plugin_dispatch_values (type, &vl);
732 DEBUG ("network plugin: parse_packet:"
733 " NOT dispatching values");
738 else if (pkg_type == TYPE_TIME)
741 status = parse_part_number (&buffer, &buffer_len, &tmp);
744 vl.time = (time_t) tmp;
745 n.time = (time_t) tmp;
748 else if (pkg_type == TYPE_INTERVAL)
751 status = parse_part_number (&buffer, &buffer_len, &tmp);
753 vl.interval = (int) tmp;
755 else if (pkg_type == TYPE_HOST)
757 status = parse_part_string (&buffer, &buffer_len,
758 vl.host, sizeof (vl.host));
759 strncpy (n.host, vl.host, sizeof (n.host));
760 n.host[sizeof (n.host) - 1] = '\0';
762 else if (pkg_type == TYPE_PLUGIN)
764 status = parse_part_string (&buffer, &buffer_len,
765 vl.plugin, sizeof (vl.plugin));
766 strncpy (n.plugin, vl.plugin, sizeof (n.plugin));
767 n.plugin[sizeof (n.plugin) - 1] = '\0';
769 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
771 status = parse_part_string (&buffer, &buffer_len,
773 sizeof (vl.plugin_instance));
774 strncpy (n.plugin_instance, vl.plugin_instance,
775 sizeof (n.plugin_instance));
776 n.plugin_instance[sizeof (n.plugin_instance) - 1] = '\0';
778 else if (pkg_type == TYPE_TYPE)
780 status = parse_part_string (&buffer, &buffer_len,
781 type, sizeof (type));
782 strncpy (n.type, type, sizeof (n.type));
783 n.type[sizeof (n.type) - 1] = '\0';
785 else if (pkg_type == TYPE_TYPE_INSTANCE)
787 status = parse_part_string (&buffer, &buffer_len,
789 sizeof (vl.type_instance));
790 strncpy (n.type_instance, vl.type_instance,
791 sizeof (n.type_instance));
792 n.type_instance[sizeof (n.type_instance) - 1] = '\0';
794 else if (pkg_type == TYPE_MESSAGE)
796 status = parse_part_string (&buffer, &buffer_len,
797 n.message, sizeof (n.message));
799 if ((n.severity != NOTIF_FAILURE)
800 && (n.severity != NOTIF_WARNING)
801 && (n.severity != NOTIF_OKAY))
803 INFO ("network plugin: "
804 "Ignoring notification with "
805 "unknown severity %i.",
808 else if (n.time <= 0)
810 INFO ("network plugin: "
811 "Ignoring notification with "
814 else if (strlen (n.message) <= 0)
816 INFO ("network plugin: "
817 "Ignoring notification with "
818 "an empty message.");
823 * TODO: Let this do a separate thread so that
824 * no packets are lost if this takes too long.
826 plugin_dispatch_notification (&n);
829 else if (pkg_type == TYPE_SEVERITY)
832 status = parse_part_number (&buffer, &buffer_len, &tmp);
834 n.severity = (int) tmp;
838 DEBUG ("network plugin: parse_packet: Unknown part"
839 " type: 0x%04hx", pkg_type);
840 buffer = ((char *) buffer) + pkg_length;
842 } /* while (buffer_len > sizeof (part_header_t)) */
845 } /* int parse_packet */
847 static void free_sockent (sockent_t *se)
857 } /* void free_sockent */
860 * int network_set_ttl
862 * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
863 * `IPV6_UNICAST_HOPS', depending on which option is applicable.
865 * The `struct addrinfo' is used to destinguish between unicast and multicast
868 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
870 if ((network_config_ttl < 1) || (network_config_ttl > 255))
873 DEBUG ("ttl = %i", network_config_ttl);
875 if (ai->ai_family == AF_INET)
877 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
880 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
881 optname = IP_MULTICAST_TTL;
885 if (setsockopt (se->fd, IPPROTO_IP, optname,
887 sizeof (network_config_ttl)) == -1)
890 ERROR ("setsockopt: %s",
891 sstrerror (errno, errbuf, sizeof (errbuf)));
895 else if (ai->ai_family == AF_INET6)
897 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
898 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
901 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
902 optname = IPV6_MULTICAST_HOPS;
904 optname = IPV6_UNICAST_HOPS;
906 if (setsockopt (se->fd, IPPROTO_IPV6, optname,
908 sizeof (network_config_ttl)) == -1)
911 ERROR ("setsockopt: %s",
912 sstrerror (errno, errbuf,
919 } /* int network_set_ttl */
921 static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
926 /* allow multiple sockets to use the same PORT number */
927 if (setsockopt(se->fd, SOL_SOCKET, SO_REUSEADDR,
928 &yes, sizeof(yes)) == -1) {
930 ERROR ("setsockopt: %s",
931 sstrerror (errno, errbuf, sizeof (errbuf)));
935 DEBUG ("fd = %i; calling `bind'", se->fd);
937 if (bind (se->fd, ai->ai_addr, ai->ai_addrlen) == -1)
941 sstrerror (errno, errbuf, sizeof (errbuf)));
945 if (ai->ai_family == AF_INET)
947 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
948 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
952 DEBUG ("fd = %i; IPv4 multicast address found", se->fd);
954 mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
955 mreq.imr_interface.s_addr = htonl (INADDR_ANY);
957 if (setsockopt (se->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
958 &loop, sizeof (loop)) == -1)
961 ERROR ("setsockopt: %s",
962 sstrerror (errno, errbuf,
967 if (setsockopt (se->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
968 &mreq, sizeof (mreq)) == -1)
971 ERROR ("setsockopt: %s",
972 sstrerror (errno, errbuf,
978 else if (ai->ai_family == AF_INET6)
980 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
981 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
982 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
984 struct ipv6_mreq mreq;
986 DEBUG ("fd = %i; IPv6 multicast address found", se->fd);
988 memcpy (&mreq.ipv6mr_multiaddr,
990 sizeof (addr->sin6_addr));
992 /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
993 * ipv6mr_interface may be set to zeroes to
994 * choose the default multicast interface or to
995 * the index of a particular multicast-capable
996 * interface if the host is multihomed.
997 * Membership is associ-associated with a
998 * single interface; programs running on
999 * multihomed hosts may need to join the same
1000 * group on more than one interface.*/
1001 mreq.ipv6mr_interface = 0;
1003 if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1004 &loop, sizeof (loop)) == -1)
1007 ERROR ("setsockopt: %s",
1008 sstrerror (errno, errbuf,
1013 if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1014 &mreq, sizeof (mreq)) == -1)
1017 ERROR ("setsockopt: %s",
1018 sstrerror (errno, errbuf,
1026 } /* int network_bind_socket */
1028 static sockent_t *network_create_socket (const char *node,
1029 const char *service,
1032 struct addrinfo ai_hints;
1033 struct addrinfo *ai_list, *ai_ptr;
1036 sockent_t *se_head = NULL;
1037 sockent_t *se_tail = NULL;
1039 DEBUG ("node = %s, service = %s", node, service);
1041 memset (&ai_hints, '\0', sizeof (ai_hints));
1042 ai_hints.ai_flags = 0;
1044 ai_hints.ai_flags |= AI_PASSIVE;
1046 #ifdef AI_ADDRCONFIG
1047 ai_hints.ai_flags |= AI_ADDRCONFIG;
1049 ai_hints.ai_family = AF_UNSPEC;
1050 ai_hints.ai_socktype = SOCK_DGRAM;
1051 ai_hints.ai_protocol = IPPROTO_UDP;
1053 ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
1057 ERROR ("getaddrinfo (%s, %s): %s",
1058 (node == NULL) ? "(null)" : node,
1059 (service == NULL) ? "(null)" : service,
1060 (ai_return == EAI_SYSTEM)
1061 ? sstrerror (errno, errbuf, sizeof (errbuf))
1062 : gai_strerror (ai_return));
1066 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1070 if ((se = (sockent_t *) malloc (sizeof (sockent_t))) == NULL)
1073 ERROR ("malloc: %s",
1074 sstrerror (errno, errbuf,
1079 if ((se->addr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage))) == NULL)
1082 ERROR ("malloc: %s",
1083 sstrerror (errno, errbuf,
1089 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1090 memset (se->addr, '\0', sizeof (struct sockaddr_storage));
1091 memcpy (se->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1092 se->addrlen = ai_ptr->ai_addrlen;
1094 se->fd = socket (ai_ptr->ai_family,
1095 ai_ptr->ai_socktype,
1096 ai_ptr->ai_protocol);
1102 ERROR ("socket: %s",
1103 sstrerror (errno, errbuf,
1112 if (network_bind_socket (se, ai_ptr) != 0)
1120 else /* listen == 0 */
1122 network_set_ttl (se, ai_ptr);
1125 if (se_tail == NULL)
1136 /* We don't open more than one write-socket per node/service pair.. */
1141 freeaddrinfo (ai_list);
1144 } /* sockent_t *network_create_socket */
1146 static sockent_t *network_create_default_socket (int listen)
1148 sockent_t *se_ptr = NULL;
1149 sockent_t *se_head = NULL;
1150 sockent_t *se_tail = NULL;
1152 se_ptr = network_create_socket (NET_DEFAULT_V6_ADDR,
1153 NET_DEFAULT_PORT, listen);
1155 /* Don't send to the same machine in IPv6 and IPv4 if both are available. */
1156 if ((listen == 0) && (se_ptr != NULL))
1163 while (se_tail->next != NULL)
1164 se_tail = se_tail->next;
1167 se_ptr = network_create_socket (NET_DEFAULT_V4_ADDR, NET_DEFAULT_PORT, listen);
1169 if (se_tail == NULL)
1172 se_tail->next = se_ptr;
1174 } /* sockent_t *network_create_default_socket */
1176 static int network_add_listen_socket (const char *node, const char *service)
1182 if (service == NULL)
1183 service = NET_DEFAULT_PORT;
1186 se = network_create_default_socket (1 /* listen == true */);
1188 se = network_create_socket (node, service, 1 /* listen == true */);
1193 for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
1196 listen_sockets = (struct pollfd *) realloc (listen_sockets,
1197 (listen_sockets_num + se_num)
1198 * sizeof (struct pollfd));
1200 for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
1202 listen_sockets[listen_sockets_num].fd = se_ptr->fd;
1203 listen_sockets[listen_sockets_num].events = POLLIN | POLLPRI;
1204 listen_sockets[listen_sockets_num].revents = 0;
1205 listen_sockets_num++;
1210 } /* int network_add_listen_socket */
1212 static int network_add_sending_socket (const char *node, const char *service)
1217 if (service == NULL)
1218 service = NET_DEFAULT_PORT;
1221 se = network_create_default_socket (0 /* listen == false */);
1223 se = network_create_socket (node, service, 0 /* listen == false */);
1228 if (sending_sockets == NULL)
1230 sending_sockets = se;
1234 for (se_ptr = sending_sockets; se_ptr->next != NULL; se_ptr = se_ptr->next)
1239 } /* int network_get_listen_socket */
1241 static void *dispatch_thread (void *arg)
1245 receive_list_entry_t *ent;
1247 /* Lock and wait for more data to come in */
1248 pthread_mutex_lock (&receive_list_lock);
1249 while ((listen_loop == 0)
1250 && (receive_list_head == NULL))
1251 pthread_cond_wait (&receive_list_cond, &receive_list_lock);
1253 /* Remove the head entry and unlock */
1254 ent = receive_list_head;
1256 receive_list_head = ent->next;
1257 pthread_mutex_unlock (&receive_list_lock);
1259 /* Check whether we are supposed to exit. We do NOT check `listen_loop'
1260 * because we dispatch all missing packets before shutting down. */
1264 parse_packet (ent->data, ent->data_len);
1270 } /* void *receive_thread */
1272 static int network_receive (void)
1274 char buffer[BUFF_SIZE];
1280 if (listen_sockets_num == 0)
1281 network_add_listen_socket (NULL, NULL);
1283 if (listen_sockets_num == 0)
1285 ERROR ("network: Failed to open a listening socket.");
1289 while (listen_loop == 0)
1291 status = poll (listen_sockets, listen_sockets_num, -1);
1298 ERROR ("poll failed: %s",
1299 sstrerror (errno, errbuf, sizeof (errbuf)));
1303 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
1305 receive_list_entry_t *ent;
1307 if ((listen_sockets[i].revents & (POLLIN | POLLPRI)) == 0)
1311 buffer_len = recv (listen_sockets[i].fd,
1312 buffer, sizeof (buffer),
1317 ERROR ("recv failed: %s",
1318 sstrerror (errno, errbuf,
1323 ent = malloc (sizeof (receive_list_entry_t));
1326 ERROR ("network plugin: malloc failed.");
1329 memset (ent, '\0', sizeof (receive_list_entry_t));
1331 /* Hopefully this be optimized out by the compiler. It
1332 * might help prevent stupid bugs in the future though.
1334 assert (sizeof (ent->data) == sizeof (buffer));
1336 memcpy (ent->data, buffer, buffer_len);
1337 ent->data_len = buffer_len;
1339 pthread_mutex_lock (&receive_list_lock);
1340 if (receive_list_head == NULL)
1342 receive_list_head = ent;
1343 receive_list_tail = ent;
1347 receive_list_tail->next = ent;
1348 receive_list_tail = ent;
1350 pthread_cond_signal (&receive_list_cond);
1351 pthread_mutex_unlock (&receive_list_lock);
1352 } /* for (listen_sockets) */
1353 } /* while (listen_loop == 0) */
1358 static void *receive_thread (void *arg)
1360 return (network_receive () ? (void *) 1 : (void *) 0);
1361 } /* void *receive_thread */
1363 static void network_send_buffer (const char *buffer, int buffer_len)
1368 DEBUG ("network plugin: network_send_buffer: buffer_len = %i", buffer_len);
1370 for (se = sending_sockets; se != NULL; se = se->next)
1374 status = sendto (se->fd, buffer, buffer_len, 0 /* no flags */,
1375 (struct sockaddr *) se->addr, se->addrlen);
1381 ERROR ("network plugin: sendto failed: %s",
1382 sstrerror (errno, errbuf,
1389 } /* for (sending_sockets) */
1390 } /* void network_send_buffer */
1392 static int add_to_buffer (char *buffer, int buffer_size,
1393 value_list_t *vl_def, char *type_def,
1394 const data_set_t *ds, const value_list_t *vl)
1396 char *buffer_orig = buffer;
1398 if (strcmp (vl_def->host, vl->host) != 0)
1400 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
1401 vl->host, strlen (vl->host)) != 0)
1403 strcpy (vl_def->host, vl->host);
1406 if (vl_def->time != vl->time)
1408 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
1409 (uint64_t) vl->time))
1411 vl_def->time = vl->time;
1414 if (vl_def->interval != vl->interval)
1416 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
1417 (uint64_t) vl->interval))
1419 vl_def->interval = vl->interval;
1422 if (strcmp (vl_def->plugin, vl->plugin) != 0)
1424 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
1425 vl->plugin, strlen (vl->plugin)) != 0)
1427 strcpy (vl_def->plugin, vl->plugin);
1430 if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
1432 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
1433 vl->plugin_instance,
1434 strlen (vl->plugin_instance)) != 0)
1436 strcpy (vl_def->plugin_instance, vl->plugin_instance);
1439 if (strcmp (type_def, ds->type) != 0)
1441 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
1442 ds->type, strlen (ds->type)) != 0)
1444 strcpy (type_def, ds->type);
1447 if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
1449 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
1451 strlen (vl->type_instance)) != 0)
1453 strcpy (vl_def->type_instance, vl->type_instance);
1456 if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
1459 return (buffer - buffer_orig);
1460 } /* int add_to_buffer */
1462 static void flush_buffer (void)
1464 DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
1467 network_send_buffer (send_buffer, send_buffer_fill);
1468 send_buffer_ptr = send_buffer;
1469 send_buffer_fill = 0;
1470 memset (&send_buffer_vl, '\0', sizeof (send_buffer_vl));
1471 memset (send_buffer_type, '\0', sizeof (send_buffer_type));
1474 static int network_write (const data_set_t *ds, const value_list_t *vl)
1478 /* If the value is already in the cache, we have received it via the
1479 * network. We write it again if forwarding is activated. It's then in
1480 * the cache and should we receive it again we will ignore it. */
1481 status = cache_check (ds->type, vl);
1482 if ((network_config_forward == 0)
1486 pthread_mutex_lock (&send_buffer_lock);
1488 status = add_to_buffer (send_buffer_ptr,
1489 sizeof (send_buffer) - send_buffer_fill,
1490 &send_buffer_vl, send_buffer_type,
1494 /* status == bytes added to the buffer */
1495 send_buffer_fill += status;
1496 send_buffer_ptr += status;
1502 status = add_to_buffer (send_buffer_ptr,
1503 sizeof (send_buffer) - send_buffer_fill,
1504 &send_buffer_vl, send_buffer_type,
1509 send_buffer_fill += status;
1510 send_buffer_ptr += status;
1516 ERROR ("network plugin: Unable to append to the "
1517 "buffer for some weird reason");
1519 else if ((sizeof (send_buffer) - send_buffer_fill) < 15)
1524 pthread_mutex_unlock (&send_buffer_lock);
1526 return ((status < 0) ? -1 : 0);
1527 } /* int network_write */
1529 static int network_config (const char *key, const char *val)
1537 if ((strcasecmp ("Listen", key) == 0)
1538 || (strcasecmp ("Server", key) == 0))
1540 char *val_cpy = strdup (val);
1541 if (val_cpy == NULL)
1544 service = NET_DEFAULT_PORT;
1545 fields_num = strsplit (val_cpy, fields, 3);
1546 if ((fields_num != 1)
1547 && (fields_num != 2))
1549 else if (fields_num == 2)
1551 if ((service = strchr (fields[1], '.')) != NULL)
1553 service = fields[1];
1557 if (strcasecmp ("Listen", key) == 0)
1558 network_add_listen_socket (node, service);
1560 network_add_sending_socket (node, service);
1562 else if (strcasecmp ("TimeToLive", key) == 0)
1564 int tmp = atoi (val);
1565 if ((tmp > 0) && (tmp < 256))
1566 network_config_ttl = tmp;
1570 else if (strcasecmp ("Forward", key) == 0)
1572 if ((strcasecmp ("true", val) == 0)
1573 || (strcasecmp ("yes", val) == 0)
1574 || (strcasecmp ("on", val) == 0))
1575 network_config_forward = 1;
1577 network_config_forward = 0;
1579 else if (strcasecmp ("CacheFlush", key) == 0)
1581 int tmp = atoi (val);
1583 cache_flush_interval = tmp;
1591 } /* int network_config */
1593 static int network_notification (const notification_t *n)
1595 char buffer[BUFF_SIZE];
1596 char *buffer_ptr = buffer;
1597 int buffer_free = sizeof (buffer);
1600 memset (buffer, '\0', sizeof (buffer));
1603 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
1604 (uint64_t) n->time);
1608 status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
1609 (uint64_t) n->severity);
1613 if (strlen (n->host) > 0)
1615 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
1616 n->host, strlen (n->host));
1621 if (strlen (n->plugin) > 0)
1623 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
1624 n->plugin, strlen (n->plugin));
1629 if (strlen (n->plugin_instance) > 0)
1631 status = write_part_string (&buffer_ptr, &buffer_free,
1632 TYPE_PLUGIN_INSTANCE,
1633 n->plugin_instance, strlen (n->plugin_instance));
1638 if (strlen (n->type) > 0)
1640 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
1641 n->type, strlen (n->type));
1646 if (strlen (n->type_instance) > 0)
1648 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
1649 n->type_instance, strlen (n->type_instance));
1654 status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
1655 n->message, strlen (n->message));
1659 network_send_buffer (buffer, sizeof (buffer) - buffer_free);
1662 } /* int network_notification */
1664 static int network_shutdown (void)
1668 /* Kill the listening thread */
1669 if (receive_thread_id != (pthread_t) 0)
1671 pthread_kill (receive_thread_id, SIGTERM);
1672 pthread_join (receive_thread_id, NULL /* no return value */);
1673 receive_thread_id = (pthread_t) 0;
1676 /* Shutdown the dispatching thread */
1677 if (dispatch_thread_id != (pthread_t) 0)
1678 pthread_cond_broadcast (&receive_list_cond);
1680 if (send_buffer_fill > 0)
1683 if (cache_tree != NULL)
1688 while (c_avl_pick (cache_tree, &key, &value) == 0)
1693 c_avl_destroy (cache_tree);
1697 /* TODO: Close `sending_sockets' */
1699 plugin_unregister_config ("network");
1700 plugin_unregister_init ("network");
1701 plugin_unregister_write ("network");
1702 plugin_unregister_shutdown ("network");
1705 } /* int network_shutdown */
1707 static int network_init (void)
1709 plugin_register_shutdown ("network", network_shutdown);
1711 send_buffer_ptr = send_buffer;
1712 send_buffer_fill = 0;
1713 memset (&send_buffer_vl, '\0', sizeof (send_buffer_vl));
1714 memset (send_buffer_type, '\0', sizeof (send_buffer_type));
1716 cache_tree = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1717 cache_flush_last = time (NULL);
1719 /* setup socket(s) and so on */
1720 if (sending_sockets != NULL)
1722 plugin_register_write ("network", network_write);
1723 plugin_register_notification ("network", network_notification);
1726 if ((listen_sockets_num != 0) && (receive_thread_id == 0))
1730 status = pthread_create (&dispatch_thread_id,
1731 NULL /* no attributes */,
1733 NULL /* no argument */);
1737 ERROR ("network: pthread_create failed: %s",
1738 sstrerror (errno, errbuf,
1742 status = pthread_create (&receive_thread_id,
1743 NULL /* no attributes */,
1745 NULL /* no argument */);
1749 ERROR ("network: pthread_create failed: %s",
1750 sstrerror (errno, errbuf,
1755 } /* int network_init */
1757 void module_register (void)
1759 plugin_register_config ("network", network_config,
1760 config_keys, config_keys_num);
1761 plugin_register_init ("network", network_init);
1762 } /* void module_register */