Merge branch 'collectd-4.2'
[collectd.git] / src / network.c
1 /**
2  * collectd - src/network.c
3  * Copyright (C) 2005-2007  Florian octo Forster
4  *
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.
8  *
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.
13  *
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
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #include "collectd.h"
23 #include "plugin.h"
24 #include "common.h"
25 #include "configfile.h"
26 #include "utils_avltree.h"
27
28 #include "network.h"
29
30 #if HAVE_PTHREAD_H
31 # include <pthread.h>
32 #endif
33 #if HAVE_SYS_SOCKET_H
34 # include <sys/socket.h>
35 #endif
36 #if HAVE_NETDB_H
37 # include <netdb.h>
38 #endif
39 #if HAVE_NETINET_IN_H
40 # include <netinet/in.h>
41 #endif
42 #if HAVE_ARPA_INET_H
43 # include <arpa/inet.h>
44 #endif
45 #if HAVE_POLL_H
46 # include <poll.h>
47 #endif
48
49 /* 1500 - 40 - 8  =  Ethernet packet - IPv6 header - UDP header */
50 /* #define BUFF_SIZE 1452 */
51
52 #ifndef IPV6_ADD_MEMBERSHIP
53 # ifdef IPV6_JOIN_GROUP
54 #  define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
55 # else
56 #  error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
57 # endif
58 #endif /* !IP_ADD_MEMBERSHIP */
59
60 #define BUFF_SIZE 1024
61
62 /*
63  * Private data types
64  */
65 typedef struct sockent
66 {
67         int                      fd;
68         struct sockaddr_storage *addr;
69         socklen_t                addrlen;
70         struct sockent          *next;
71 } sockent_t;
72
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  * +-------+-----------------------+-------------------------------+
76  * ! Ver.  !                       ! Length                        !
77  * +-------+-----------------------+-------------------------------+
78  */
79 struct part_header_s
80 {
81         uint16_t type;
82         uint16_t length;
83 };
84 typedef struct part_header_s part_header_t;
85
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  * +-------------------------------+-------------------------------+
89  * ! Type                          ! Length                        !
90  * +-------------------------------+-------------------------------+
91  * : (Length - 4) Bytes                                            :
92  * +---------------------------------------------------------------+
93  */
94 struct part_string_s
95 {
96         part_header_t *head;
97         char *value;
98 };
99 typedef struct part_string_s part_string_t;
100
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  * +-------------------------------+-------------------------------+
104  * ! Type                          ! Length                        !
105  * +-------------------------------+-------------------------------+
106  * : (Length - 4 == 2 || 4 || 8) Bytes                             :
107  * +---------------------------------------------------------------+
108  */
109 struct part_number_s
110 {
111         part_header_t *head;
112         uint64_t *value;
113 };
114 typedef struct part_number_s part_number_t;
115
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  * +-------------------------------+-------------------------------+
119  * ! Type                          ! Length                        !
120  * +-------------------------------+---------------+---------------+
121  * ! Num of values                 ! Type0         ! Type1         !
122  * +-------------------------------+---------------+---------------+
123  * ! Value0                                                        !
124  * !                                                               !
125  * +---------------------------------------------------------------+
126  * ! Value1                                                        !
127  * !                                                               !
128  * +---------------------------------------------------------------+
129  */
130 struct part_values_s
131 {
132         part_header_t *head;
133         uint16_t *num_values;
134         uint8_t  *values_types;
135         value_t  *values;
136 };
137 typedef struct part_values_s part_values_t;
138
139 /*
140  * Private variables
141  */
142 static const char *config_keys[] =
143 {
144         "CacheFlush",
145         "Listen",
146         "Server",
147         "TimeToLive",
148         "Forward"
149 };
150 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
151
152 static int network_config_ttl = 0;
153 static int network_config_forward = 0;
154
155 static sockent_t *sending_sockets = NULL;
156
157 static struct pollfd *listen_sockets = NULL;
158 static int listen_sockets_num = 0;
159 static pthread_t listen_thread = 0;
160 static int listen_loop = 0;
161
162 static char         send_buffer[BUFF_SIZE];
163 static char        *send_buffer_ptr;
164 static int          send_buffer_fill;
165 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
166 static char         send_buffer_type[DATA_MAX_NAME_LEN];
167 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
168
169 static c_avl_tree_t      *cache_tree = NULL;
170 static pthread_mutex_t  cache_lock = PTHREAD_MUTEX_INITIALIZER;
171 static time_t           cache_flush_last;
172 static int              cache_flush_interval = 1800;
173
174 /*
175  * Private functions
176  */
177 static int cache_flush (void)
178 {
179         char **keys = NULL;
180         int    keys_num = 0;
181
182         char **tmp;
183         int    i;
184
185         char   *key;
186         time_t *value;
187         c_avl_iterator_t *iter;
188
189         time_t curtime = time (NULL);
190
191         iter = c_avl_get_iterator (cache_tree);
192         while (c_avl_iterator_next (iter, (void *) &key, (void *) &value) == 0)
193         {
194                 if ((curtime - *value) <= cache_flush_interval)
195                         continue;
196                 tmp = (char **) realloc (keys,
197                                 (keys_num + 1) * sizeof (char *));
198                 if (tmp == NULL)
199                 {
200                         sfree (keys);
201                         c_avl_iterator_destroy (iter);
202                         ERROR ("network plugin: cache_flush: realloc"
203                                         " failed.");
204                         return (-1);
205                 }
206                 keys = tmp;
207                 keys[keys_num] = key;
208                 keys_num++;
209         } /* while (c_avl_iterator_next) */
210         c_avl_iterator_destroy (iter);
211
212         for (i = 0; i < keys_num; i++)
213         {
214                 if (c_avl_remove (cache_tree, keys[i], (void *) &key,
215                                         (void *) &value) != 0)
216                 {
217                         WARNING ("network plugin: cache_flush: c_avl_remove"
218                                         " (%s) failed.", keys[i]);
219                         continue;
220                 }
221
222                 sfree (key);
223                 sfree (value);
224         }
225
226         sfree (keys);
227
228         DEBUG ("network plugin: cache_flush: Removed %i %s",
229                         keys_num, (keys_num == 1) ? "entry" : "entries");
230         cache_flush_last = curtime;
231         return (0);
232 } /* int cache_flush */
233
234 static int cache_check (const char *type, const value_list_t *vl)
235 {
236         char key[1024];
237         time_t *value = NULL;
238         int retval = -1;
239
240         if (cache_tree == NULL)
241                 return (-1);
242
243         if (format_name (key, sizeof (key), vl->host, vl->plugin,
244                                 vl->plugin_instance, type, vl->type_instance))
245                 return (-1);
246
247         pthread_mutex_lock (&cache_lock);
248
249         if (c_avl_get (cache_tree, key, (void *) &value) == 0)
250         {
251                 if (*value < vl->time)
252                 {
253                         *value = vl->time;
254                         retval = 0;
255                 }
256                 else
257                 {
258                         DEBUG ("network plugin: cache_check: *value = %i >= vl->time = %i",
259                                         (int) *value, (int) vl->time);
260                         retval = 1;
261                 }
262         }
263         else
264         {
265                 char *key_copy = strdup (key);
266                 value = malloc (sizeof (time_t));
267                 if ((key_copy != NULL) && (value != NULL))
268                 {
269                         *value = vl->time;
270                         c_avl_insert (cache_tree, key_copy, value);
271                         retval = 0;
272                 }
273                 else
274                 {
275                         sfree (key_copy);
276                         sfree (value);
277                 }
278         }
279
280         if ((time (NULL) - cache_flush_last) > cache_flush_interval)
281                 cache_flush ();
282
283         pthread_mutex_unlock (&cache_lock);
284
285         DEBUG ("network plugin: cache_check: key = %s; time = %i; retval = %i",
286                         key, (int) vl->time, retval);
287
288         return (retval);
289 } /* int cache_check */
290
291 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
292                 const data_set_t *ds, const value_list_t *vl)
293 {
294         part_values_t pv;
295         int i;
296
297         i = 6 + (9 * vl->values_len);
298         if (*ret_buffer_len < i)
299                 return (-1);
300         *ret_buffer_len -= i;
301
302         pv.head = (part_header_t *) *ret_buffer;
303         pv.num_values = (uint16_t *) (pv.head + 1);
304         pv.values_types = (uint8_t *) (pv.num_values + 1);
305         pv.values = (value_t *) (pv.values_types + vl->values_len);
306         *ret_buffer = (void *) (pv.values + vl->values_len);
307
308         pv.head->type = htons (TYPE_VALUES);
309         pv.head->length = htons (6 + (9 * vl->values_len));
310         *pv.num_values = htons ((uint16_t) vl->values_len);
311         
312         for (i = 0; i < vl->values_len; i++)
313         {
314                 if (ds->ds[i].type == DS_TYPE_COUNTER)
315                 {
316                         pv.values_types[i] = DS_TYPE_COUNTER;
317                         pv.values[i].counter = htonll (vl->values[i].counter);
318                 }
319                 else
320                 {
321                         pv.values_types[i] = DS_TYPE_GAUGE;
322                         pv.values[i].gauge = vl->values[i].gauge;
323                 }
324         } /* for (values) */
325
326         return (0);
327 } /* int write_part_values */
328
329 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
330                 int type, uint64_t value)
331 {
332         part_number_t pn;
333
334         if (*ret_buffer_len < 12)
335                 return (-1);
336
337         pn.head = (part_header_t *) *ret_buffer;
338         pn.value = (uint64_t *) (pn.head + 1);
339
340         pn.head->type = htons (type);
341         pn.head->length = htons (12);
342         *pn.value = htonll (value);
343
344         *ret_buffer = (char *) (pn.value + 1);
345         *ret_buffer_len -= 12;
346
347         return (0);
348 } /* int write_part_number */
349
350 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
351                 int type, const char *str, int str_len)
352 {
353         part_string_t ps;
354         int len;
355
356         len = 4 + str_len + 1;
357         if (*ret_buffer_len < len)
358                 return (-1);
359         *ret_buffer_len -= len;
360
361         ps.head = (part_header_t *) *ret_buffer;
362         ps.value = (char *) (ps.head + 1);
363
364         ps.head->type = htons ((uint16_t) type);
365         ps.head->length = htons ((uint16_t) str_len + 5);
366         if (str_len > 0)
367                 memcpy (ps.value, str, str_len);
368         ps.value[str_len] = '\0';
369         *ret_buffer = (void *) (ps.value + (str_len + 1));
370
371         return (0);
372 } /* int write_part_string */
373
374 static int parse_part_values (void **ret_buffer, int *ret_buffer_len,
375                 value_t **ret_values, int *ret_num_values)
376 {
377         char *buffer = *ret_buffer;
378         int   buffer_len = *ret_buffer_len;
379         part_values_t pv;
380         int   i;
381
382         uint16_t h_length;
383         uint16_t h_type;
384         uint16_t h_num;
385
386         if (buffer_len < (15))
387         {
388                 DEBUG ("network plugin: packet is too short: buffer_len = %i",
389                                 buffer_len);
390                 return (-1);
391         }
392
393         pv.head = (part_header_t *) buffer;
394         h_length = ntohs (pv.head->length);
395         h_type = ntohs (pv.head->type);
396
397         assert (h_type == TYPE_VALUES);
398
399         pv.num_values = (uint16_t *) (pv.head + 1);
400         h_num = ntohs (*pv.num_values);
401
402         if (h_num != ((h_length - 6) / 9))
403         {
404                 DEBUG ("`length' and `num of values' don't match");
405                 return (-1);
406         }
407
408         pv.values_types = (uint8_t *) (pv.num_values + 1);
409         pv.values = (value_t *) (pv.values_types + h_num);
410
411         for (i = 0; i < h_num; i++)
412                 if (pv.values_types[i] == DS_TYPE_COUNTER)
413                         pv.values[i].counter = ntohll (pv.values[i].counter);
414
415         *ret_buffer     = (void *) (pv.values + h_num);
416         *ret_buffer_len = buffer_len - h_length;
417         *ret_num_values = h_num;
418         *ret_values     = pv.values;
419
420         return (0);
421 } /* int parse_part_values */
422
423 static int parse_part_number (void **ret_buffer, int *ret_buffer_len,
424                 uint64_t *value)
425 {
426         part_number_t pn;
427         uint16_t len;
428
429         pn.head = (part_header_t *) *ret_buffer;
430         pn.value = (uint64_t *) (pn.head + 1);
431
432         len = ntohs (pn.head->length);
433         if (len != 12)
434                 return (-1);
435         if (len > *ret_buffer_len)
436                 return (-1);
437         *value = ntohll (*pn.value);
438
439         *ret_buffer = (void *) (pn.value + 1);
440         *ret_buffer_len -= len;
441
442         return (0);
443 } /* int parse_part_number */
444
445 static int parse_part_string (void **ret_buffer, int *ret_buffer_len,
446                 char *output, int output_len)
447 {
448         char *buffer = *ret_buffer;
449         int   buffer_len = *ret_buffer_len;
450         part_string_t ps;
451
452         uint16_t h_length;
453         uint16_t h_type;
454
455         DEBUG ("network plugin: parse_part_string: ret_buffer = %p;"
456                         " ret_buffer_len = %i; output = %p; output_len = %i;",
457                         *ret_buffer, *ret_buffer_len,
458                         (void *) output, output_len);
459
460         ps.head = (part_header_t *) buffer;
461
462         h_length = ntohs (ps.head->length);
463         h_type = ntohs (ps.head->type);
464
465         DEBUG ("network plugin: parse_part_string: length = %hu; type = %hu;",
466                         h_length, h_type);
467
468         if (buffer_len < h_length)
469         {
470                 DEBUG ("packet is too short");
471                 return (-1);
472         }
473         assert ((h_type == TYPE_HOST)
474                         || (h_type == TYPE_PLUGIN)
475                         || (h_type == TYPE_PLUGIN_INSTANCE)
476                         || (h_type == TYPE_TYPE)
477                         || (h_type == TYPE_TYPE_INSTANCE));
478
479         ps.value = buffer + 4;
480         if (ps.value[h_length - 5] != '\0')
481         {
482                 DEBUG ("String does not end with a nullbyte");
483                 return (-1);
484         }
485
486         if (output_len < (h_length - 4))
487         {
488                 DEBUG ("output buffer is too small");
489                 return (-1);
490         }
491         strcpy (output, ps.value);
492
493         DEBUG ("network plugin: parse_part_string: output = %s", output);
494
495         *ret_buffer = (void *) (buffer + h_length);
496         *ret_buffer_len = buffer_len - h_length;
497
498         return (0);
499 } /* int parse_part_string */
500
501 static int parse_packet (void *buffer, int buffer_len)
502 {
503         part_header_t *header;
504         int status;
505
506         value_list_t vl = VALUE_LIST_INIT;
507         char type[DATA_MAX_NAME_LEN];
508
509         DEBUG ("network plugin: parse_packet: buffer = %p; buffer_len = %i;",
510                         buffer, buffer_len);
511
512         memset (&vl, '\0', sizeof (vl));
513         memset (&type, '\0', sizeof (type));
514         status = 0;
515
516         while ((status == 0) && (buffer_len > sizeof (part_header_t)))
517         {
518                 header = (part_header_t *) buffer;
519
520                 if (ntohs (header->length) > buffer_len)
521                         break;
522                 /* Assure that this loop terminates eventually */
523                 if (ntohs (header->length) < 4)
524                         break;
525
526                 if (ntohs (header->type) == TYPE_VALUES)
527                 {
528                         status = parse_part_values (&buffer, &buffer_len,
529                                         &vl.values, &vl.values_len);
530
531                         if (status != 0)
532                         {
533                                 DEBUG ("parse_part_values failed.");
534                                 break;
535                         }
536
537                         if ((vl.time > 0)
538                                         && (strlen (vl.host) > 0)
539                                         && (strlen (vl.plugin) > 0)
540                                         && (strlen (type) > 0)
541                                         && (cache_check (type, &vl) == 0))
542                         {
543                                 DEBUG ("network plugin: parse_packet:"
544                                                 " dispatching values");
545                                 plugin_dispatch_values (type, &vl);
546                         }
547                         else
548                         {
549                                 DEBUG ("network plugin: parse_packet:"
550                                                 " NOT dispatching values");
551                         }
552                 }
553                 else if (ntohs (header->type) == TYPE_TIME)
554                 {
555                         uint64_t tmp = 0;
556                         status = parse_part_number (&buffer, &buffer_len, &tmp);
557                         if (status == 0)
558                                 vl.time = (time_t) tmp;
559                 }
560                 else if (ntohs (header->type) == TYPE_INTERVAL)
561                 {
562                         uint64_t tmp = 0;
563                         status = parse_part_number (&buffer, &buffer_len, &tmp);
564                         if (status == 0)
565                                 vl.interval = (int) tmp;
566                 }
567                 else if (ntohs (header->type) == TYPE_HOST)
568                 {
569                         status = parse_part_string (&buffer, &buffer_len,
570                                         vl.host, sizeof (vl.host));
571                         DEBUG ("network plugin: parse_packet: vl.host = %s", vl.host);
572                 }
573                 else if (ntohs (header->type) == TYPE_PLUGIN)
574                 {
575                         status = parse_part_string (&buffer, &buffer_len,
576                                         vl.plugin, sizeof (vl.plugin));
577                         DEBUG ("network plugin: parse_packet: vl.plugin = %s", vl.plugin);
578                 }
579                 else if (ntohs (header->type) == TYPE_PLUGIN_INSTANCE)
580                 {
581                         status = parse_part_string (&buffer, &buffer_len,
582                                         vl.plugin_instance, sizeof (vl.plugin_instance));
583                         DEBUG ("network plugin: parse_packet: vl.plugin_instance = %s", vl.plugin_instance);
584                 }
585                 else if (ntohs (header->type) == TYPE_TYPE)
586                 {
587                         status = parse_part_string (&buffer, &buffer_len,
588                                         type, sizeof (type));
589                         DEBUG ("network plugin: parse_packet: type = %s", type);
590                 }
591                 else if (ntohs (header->type) == TYPE_TYPE_INSTANCE)
592                 {
593                         status = parse_part_string (&buffer, &buffer_len,
594                                         vl.type_instance, sizeof (vl.type_instance));
595                         DEBUG ("network plugin: parse_packet: vl.type_instance = %s", vl.type_instance);
596                 }
597                 else
598                 {
599                         DEBUG ("network plugin: parse_packet: Unknown part"
600                                         " type: 0x%0hx", ntohs (header->type));
601                         buffer = ((char *) buffer) + ntohs (header->length);
602                 }
603         } /* while (buffer_len > sizeof (part_header_t)) */
604
605         return (0);
606 } /* int parse_packet */
607
608 static void free_sockent (sockent_t *se)
609 {
610         sockent_t *next;
611         while (se != NULL)
612         {
613                 next = se->next;
614                 free (se->addr);
615                 free (se);
616                 se = next;
617         }
618 } /* void free_sockent */
619
620 /*
621  * int network_set_ttl
622  *
623  * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
624  * `IPV6_UNICAST_HOPS', depending on which option is applicable.
625  *
626  * The `struct addrinfo' is used to destinguish between unicast and multicast
627  * sockets.
628  */
629 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
630 {
631         if ((network_config_ttl < 1) || (network_config_ttl > 255))
632                 return (-1);
633
634         DEBUG ("ttl = %i", network_config_ttl);
635
636         if (ai->ai_family == AF_INET)
637         {
638                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
639                 int optname;
640
641                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
642                         optname = IP_MULTICAST_TTL;
643                 else
644                         optname = IP_TTL;
645
646                 if (setsockopt (se->fd, IPPROTO_IP, optname,
647                                         &network_config_ttl,
648                                         sizeof (network_config_ttl)) == -1)
649                 {
650                         char errbuf[1024];
651                         ERROR ("setsockopt: %s",
652                                         sstrerror (errno, errbuf, sizeof (errbuf)));
653                         return (-1);
654                 }
655         }
656         else if (ai->ai_family == AF_INET6)
657         {
658                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
659                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
660                 int optname;
661
662                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
663                         optname = IPV6_MULTICAST_HOPS;
664                 else
665                         optname = IPV6_UNICAST_HOPS;
666
667                 if (setsockopt (se->fd, IPPROTO_IPV6, optname,
668                                         &network_config_ttl,
669                                         sizeof (network_config_ttl)) == -1)
670                 {
671                         char errbuf[1024];
672                         ERROR ("setsockopt: %s",
673                                         sstrerror (errno, errbuf,
674                                                 sizeof (errbuf)));
675                         return (-1);
676                 }
677         }
678
679         return (0);
680 } /* int network_set_ttl */
681
682 static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
683 {
684         int loop = 0;
685         int yes  = 1;
686
687         /* allow multiple sockets to use the same PORT number */
688         if (setsockopt(se->fd, SOL_SOCKET, SO_REUSEADDR,
689                                 &yes, sizeof(yes)) == -1) {
690                 char errbuf[1024];
691                 ERROR ("setsockopt: %s", 
692                                 sstrerror (errno, errbuf, sizeof (errbuf)));
693                 return (-1);
694         }
695
696         DEBUG ("fd = %i; calling `bind'", se->fd);
697
698         if (bind (se->fd, ai->ai_addr, ai->ai_addrlen) == -1)
699         {
700                 char errbuf[1024];
701                 ERROR ("bind: %s",
702                                 sstrerror (errno, errbuf, sizeof (errbuf)));
703                 return (-1);
704         }
705
706         if (ai->ai_family == AF_INET)
707         {
708                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
709                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
710                 {
711                         struct ip_mreq mreq;
712
713                         DEBUG ("fd = %i; IPv4 multicast address found", se->fd);
714
715                         mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
716                         mreq.imr_interface.s_addr = htonl (INADDR_ANY);
717
718                         if (setsockopt (se->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
719                                                 &loop, sizeof (loop)) == -1)
720                         {
721                                 char errbuf[1024];
722                                 ERROR ("setsockopt: %s",
723                                                 sstrerror (errno, errbuf,
724                                                         sizeof (errbuf)));
725                                 return (-1);
726                         }
727
728                         if (setsockopt (se->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
729                                                 &mreq, sizeof (mreq)) == -1)
730                         {
731                                 char errbuf[1024];
732                                 ERROR ("setsockopt: %s",
733                                                 sstrerror (errno, errbuf,
734                                                         sizeof (errbuf)));
735                                 return (-1);
736                         }
737                 }
738         }
739         else if (ai->ai_family == AF_INET6)
740         {
741                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
742                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
743                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
744                 {
745                         struct ipv6_mreq mreq;
746
747                         DEBUG ("fd = %i; IPv6 multicast address found", se->fd);
748
749                         memcpy (&mreq.ipv6mr_multiaddr,
750                                         &addr->sin6_addr,
751                                         sizeof (addr->sin6_addr));
752
753                         /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
754                          * ipv6mr_interface may be set to zeroes to
755                          * choose the default multicast interface or to
756                          * the index of a particular multicast-capable
757                          * interface if the host is multihomed.
758                          * Membership is associ-associated with a
759                          * single interface; programs running on
760                          * multihomed hosts may need to join the same
761                          * group on more than one interface.*/
762                         mreq.ipv6mr_interface = 0;
763
764                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
765                                                 &loop, sizeof (loop)) == -1)
766                         {
767                                 char errbuf[1024];
768                                 ERROR ("setsockopt: %s",
769                                                 sstrerror (errno, errbuf,
770                                                         sizeof (errbuf)));
771                                 return (-1);
772                         }
773
774                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
775                                                 &mreq, sizeof (mreq)) == -1)
776                         {
777                                 char errbuf[1024];
778                                 ERROR ("setsockopt: %s",
779                                                 sstrerror (errno, errbuf,
780                                                         sizeof (errbuf)));
781                                 return (-1);
782                         }
783                 }
784         }
785
786         return (0);
787 } /* int network_bind_socket */
788
789 static sockent_t *network_create_socket (const char *node,
790                 const char *service,
791                 int listen)
792 {
793         struct addrinfo  ai_hints;
794         struct addrinfo *ai_list, *ai_ptr;
795         int              ai_return;
796
797         sockent_t *se_head = NULL;
798         sockent_t *se_tail = NULL;
799
800         DEBUG ("node = %s, service = %s", node, service);
801
802         memset (&ai_hints, '\0', sizeof (ai_hints));
803         ai_hints.ai_flags    = 0;
804 #ifdef AI_PASSIVE
805         ai_hints.ai_flags |= AI_PASSIVE;
806 #endif
807 #ifdef AI_ADDRCONFIG
808         ai_hints.ai_flags |= AI_ADDRCONFIG;
809 #endif
810         ai_hints.ai_family   = AF_UNSPEC;
811         ai_hints.ai_socktype = SOCK_DGRAM;
812         ai_hints.ai_protocol = IPPROTO_UDP;
813
814         ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
815         if (ai_return != 0)
816         {
817                 char errbuf[1024];
818                 ERROR ("getaddrinfo (%s, %s): %s",
819                                 (node == NULL) ? "(null)" : node,
820                                 (service == NULL) ? "(null)" : service,
821                                 (ai_return == EAI_SYSTEM)
822                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
823                                 : gai_strerror (ai_return));
824                 return (NULL);
825         }
826
827         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
828         {
829                 sockent_t *se;
830
831                 if ((se = (sockent_t *) malloc (sizeof (sockent_t))) == NULL)
832                 {
833                         char errbuf[1024];
834                         ERROR ("malloc: %s",
835                                         sstrerror (errno, errbuf,
836                                                 sizeof (errbuf)));
837                         continue;
838                 }
839
840                 if ((se->addr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage))) == NULL)
841                 {
842                         char errbuf[1024];
843                         ERROR ("malloc: %s",
844                                         sstrerror (errno, errbuf,
845                                                 sizeof (errbuf)));
846                         free (se);
847                         continue;
848                 }
849
850                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
851                 memset (se->addr, '\0', sizeof (struct sockaddr_storage));
852                 memcpy (se->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
853                 se->addrlen = ai_ptr->ai_addrlen;
854
855                 se->fd   = socket (ai_ptr->ai_family,
856                                 ai_ptr->ai_socktype,
857                                 ai_ptr->ai_protocol);
858                 se->next = NULL;
859
860                 if (se->fd == -1)
861                 {
862                         char errbuf[1024];
863                         ERROR ("socket: %s",
864                                         sstrerror (errno, errbuf,
865                                                 sizeof (errbuf)));
866                         free (se->addr);
867                         free (se);
868                         continue;
869                 }
870
871                 if (listen != 0)
872                 {
873                         if (network_bind_socket (se, ai_ptr) != 0)
874                         {
875                                 close (se->fd);
876                                 free (se->addr);
877                                 free (se);
878                                 continue;
879                         }
880                 }
881                 else /* listen == 0 */
882                 {
883                         network_set_ttl (se, ai_ptr);
884                 }
885
886                 if (se_tail == NULL)
887                 {
888                         se_head = se;
889                         se_tail = se;
890                 }
891                 else
892                 {
893                         se_tail->next = se;
894                         se_tail = se;
895                 }
896
897                 /* We don't open more than one write-socket per node/service pair.. */
898                 if (listen == 0)
899                         break;
900         }
901
902         freeaddrinfo (ai_list);
903
904         return (se_head);
905 } /* sockent_t *network_create_socket */
906
907 static sockent_t *network_create_default_socket (int listen)
908 {
909         sockent_t *se_ptr  = NULL;
910         sockent_t *se_head = NULL;
911         sockent_t *se_tail = NULL;
912
913         se_ptr = network_create_socket (NET_DEFAULT_V6_ADDR,
914                         NET_DEFAULT_PORT, listen);
915
916         /* Don't send to the same machine in IPv6 and IPv4 if both are available. */
917         if ((listen == 0) && (se_ptr != NULL))
918                 return (se_ptr);
919
920         if (se_ptr != NULL)
921         {
922                 se_head = se_ptr;
923                 se_tail = se_ptr;
924                 while (se_tail->next != NULL)
925                         se_tail = se_tail->next;
926         }
927
928         se_ptr = network_create_socket (NET_DEFAULT_V4_ADDR, NET_DEFAULT_PORT, listen);
929
930         if (se_tail == NULL)
931                 return (se_ptr);
932
933         se_tail->next = se_ptr;
934         return (se_head);
935 } /* sockent_t *network_create_default_socket */
936
937 static int network_add_listen_socket (const char *node, const char *service)
938 {
939         sockent_t *se;
940         sockent_t *se_ptr;
941         int se_num = 0;
942
943         if (service == NULL)
944                 service = NET_DEFAULT_PORT;
945
946         if (node == NULL)
947                 se = network_create_default_socket (1 /* listen == true */);
948         else
949                 se = network_create_socket (node, service, 1 /* listen == true */);
950
951         if (se == NULL)
952                 return (-1);
953
954         for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
955                 se_num++;
956
957         listen_sockets = (struct pollfd *) realloc (listen_sockets,
958                         (listen_sockets_num + se_num)
959                         * sizeof (struct pollfd));
960
961         for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
962         {
963                 listen_sockets[listen_sockets_num].fd = se_ptr->fd;
964                 listen_sockets[listen_sockets_num].events = POLLIN | POLLPRI;
965                 listen_sockets[listen_sockets_num].revents = 0;
966                 listen_sockets_num++;
967         } /* for (se) */
968
969         free_sockent (se);
970         return (0);
971 } /* int network_add_listen_socket */
972
973 static int network_add_sending_socket (const char *node, const char *service)
974 {
975         sockent_t *se;
976         sockent_t *se_ptr;
977
978         if (service == NULL)
979                 service = NET_DEFAULT_PORT;
980
981         if (node == NULL)
982                 se = network_create_default_socket (0 /* listen == false */);
983         else
984                 se = network_create_socket (node, service, 0 /* listen == false */);
985
986         if (se == NULL)
987                 return (-1);
988
989         if (sending_sockets == NULL)
990         {
991                 sending_sockets = se;
992                 return (0);
993         }
994
995         for (se_ptr = sending_sockets; se_ptr->next != NULL; se_ptr = se_ptr->next)
996                 /* seek end */;
997
998         se_ptr->next = se;
999         return (0);
1000 } /* int network_get_listen_socket */
1001
1002 static int network_receive (void)
1003 {
1004         char buffer[BUFF_SIZE];
1005         int  buffer_len;
1006
1007         int i;
1008         int status;
1009
1010         if (listen_sockets_num == 0)
1011                 network_add_listen_socket (NULL, NULL);
1012
1013         if (listen_sockets_num == 0)
1014         {
1015                 ERROR ("network: Failed to open a listening socket.");
1016                 return (-1);
1017         }
1018
1019         while (listen_loop == 0)
1020         {
1021                 status = poll (listen_sockets, listen_sockets_num, -1);
1022
1023                 if (status <= 0)
1024                 {
1025                         char errbuf[1024];
1026                         if (errno == EINTR)
1027                                 continue;
1028                         ERROR ("poll failed: %s",
1029                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1030                         return (-1);
1031                 }
1032
1033                 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
1034                 {
1035                         if ((listen_sockets[i].revents & (POLLIN | POLLPRI)) == 0)
1036                                 continue;
1037                         status--;
1038
1039                         buffer_len = recv (listen_sockets[i].fd,
1040                                         buffer, sizeof (buffer),
1041                                         0 /* no flags */);
1042                         if (buffer_len < 0)
1043                         {
1044                                 char errbuf[1024];
1045                                 ERROR ("recv failed: %s",
1046                                                 sstrerror (errno, errbuf,
1047                                                         sizeof (errbuf)));
1048                                 return (-1);
1049                         }
1050
1051                         parse_packet (buffer, buffer_len);
1052                 } /* for (listen_sockets) */
1053         } /* while (listen_loop == 0) */
1054
1055         return (0);
1056 }
1057
1058 static void *receive_thread (void *arg)
1059 {
1060         return (network_receive () ? (void *) 1 : (void *) 0);
1061 } /* void *receive_thread */
1062
1063 static void network_send_buffer (const char *buffer, int buffer_len)
1064 {
1065         sockent_t *se;
1066         int status;
1067
1068         DEBUG ("network plugin: network_send_buffer: buffer_len = %i", buffer_len);
1069
1070         for (se = sending_sockets; se != NULL; se = se->next)
1071         {
1072                 while (42)
1073                 {
1074                         status = sendto (se->fd, buffer, buffer_len, 0 /* no flags */,
1075                                         (struct sockaddr *) se->addr, se->addrlen);
1076                         if (status < 0)
1077                         {
1078                                 char errbuf[1024];
1079                                 if (errno == EINTR)
1080                                         continue;
1081                                 ERROR ("network plugin: sendto failed: %s",
1082                                                 sstrerror (errno, errbuf,
1083                                                         sizeof (errbuf)));
1084                                 break;
1085                         }
1086
1087                         break;
1088                 } /* while (42) */
1089         } /* for (sending_sockets) */
1090 } /* void network_send_buffer */
1091
1092 static int add_to_buffer (char *buffer, int buffer_size,
1093                 value_list_t *vl_def, char *type_def,
1094                 const data_set_t *ds, const value_list_t *vl)
1095 {
1096         char *buffer_orig = buffer;
1097
1098         if (strcmp (vl_def->host, vl->host) != 0)
1099         {
1100                 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
1101                                         vl->host, strlen (vl->host)) != 0)
1102                         return (-1);
1103                 strcpy (vl_def->host, vl->host);
1104         }
1105
1106         if (vl_def->time != vl->time)
1107         {
1108                 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
1109                                         (uint64_t) vl->time))
1110                         return (-1);
1111                 vl_def->time = vl->time;
1112         }
1113
1114         if (vl_def->interval != vl->interval)
1115         {
1116                 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
1117                                         (uint64_t) vl->interval))
1118                         return (-1);
1119                 vl_def->interval = vl->interval;
1120         }
1121
1122         if (strcmp (vl_def->plugin, vl->plugin) != 0)
1123         {
1124                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
1125                                         vl->plugin, strlen (vl->plugin)) != 0)
1126                         return (-1);
1127                 strcpy (vl_def->plugin, vl->plugin);
1128         }
1129
1130         if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
1131         {
1132                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
1133                                         vl->plugin_instance,
1134                                         strlen (vl->plugin_instance)) != 0)
1135                         return (-1);
1136                 strcpy (vl_def->plugin_instance, vl->plugin_instance);
1137         }
1138
1139         if (strcmp (type_def, ds->type) != 0)
1140         {
1141                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
1142                                         ds->type, strlen (ds->type)) != 0)
1143                         return (-1);
1144                 strcpy (type_def, ds->type);
1145         }
1146
1147         if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
1148         {
1149                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
1150                                         vl->type_instance,
1151                                         strlen (vl->type_instance)) != 0)
1152                         return (-1);
1153                 strcpy (vl_def->type_instance, vl->type_instance);
1154         }
1155         
1156         if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
1157                 return (-1);
1158
1159         return (buffer - buffer_orig);
1160 } /* int add_to_buffer */
1161
1162 static void flush_buffer (void)
1163 {
1164         DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
1165                         send_buffer_fill);
1166
1167         network_send_buffer (send_buffer, send_buffer_fill);
1168         send_buffer_ptr  = send_buffer;
1169         send_buffer_fill = 0;
1170         memset (&send_buffer_vl, '\0', sizeof (send_buffer_vl));
1171         memset (send_buffer_type, '\0', sizeof (send_buffer_type));
1172 }
1173
1174 static int network_write (const data_set_t *ds, const value_list_t *vl)
1175 {
1176         int status;
1177
1178         /* If the value is already in the cache, we have received it via the
1179          * network. We write it again if forwarding is activated. It's then in
1180          * the cache and should we receive it again we will ignore it. */
1181         status = cache_check (ds->type, vl);
1182         if ((network_config_forward == 0)
1183                         && (status != 0))
1184                 return (0);
1185
1186         pthread_mutex_lock (&send_buffer_lock);
1187
1188         status = add_to_buffer (send_buffer_ptr,
1189                         sizeof (send_buffer) - send_buffer_fill,
1190                         &send_buffer_vl, send_buffer_type,
1191                         ds, vl);
1192         if (status >= 0)
1193         {
1194                 /* status == bytes added to the buffer */
1195                 send_buffer_fill += status;
1196                 send_buffer_ptr  += status;
1197         }
1198         else
1199         {
1200                 flush_buffer ();
1201
1202                 status = add_to_buffer (send_buffer_ptr,
1203                                 sizeof (send_buffer) - send_buffer_fill,
1204                                 &send_buffer_vl, send_buffer_type,
1205                                 ds, vl);
1206
1207                 if (status >= 0)
1208                 {
1209                         send_buffer_fill += status;
1210                         send_buffer_ptr  += status;
1211                 }
1212         }
1213
1214         if (status < 0)
1215         {
1216                 ERROR ("network plugin: Unable to append to the "
1217                                 "buffer for some weird reason");
1218         }
1219         else if ((sizeof (send_buffer) - send_buffer_fill) < 15)
1220         {
1221                 flush_buffer ();
1222         }
1223
1224         pthread_mutex_unlock (&send_buffer_lock);
1225
1226         return ((status < 0) ? -1 : 0);
1227 } /* int network_write */
1228
1229 static int network_config (const char *key, const char *val)
1230 {
1231         char *node;
1232         char *service;
1233
1234         char *fields[3];
1235         int   fields_num;
1236
1237         if ((strcasecmp ("Listen", key) == 0)
1238                         || (strcasecmp ("Server", key) == 0))
1239         {
1240                 char *val_cpy = strdup (val);
1241                 if (val_cpy == NULL)
1242                         return (1);
1243
1244                 service = NET_DEFAULT_PORT;
1245                 fields_num = strsplit (val_cpy, fields, 3);
1246                 if ((fields_num != 1)
1247                                 && (fields_num != 2))
1248                         return (1);
1249                 else if (fields_num == 2)
1250                 {
1251                         if ((service = strchr (fields[1], '.')) != NULL)
1252                                 *service = '\0';
1253                         service = fields[1];
1254                 }
1255                 node = fields[0];
1256
1257                 if (strcasecmp ("Listen", key) == 0)
1258                         network_add_listen_socket (node, service);
1259                 else
1260                         network_add_sending_socket (node, service);
1261         }
1262         else if (strcasecmp ("TimeToLive", key) == 0)
1263         {
1264                 int tmp = atoi (val);
1265                 if ((tmp > 0) && (tmp < 256))
1266                         network_config_ttl = tmp;
1267                 else
1268                         return (1);
1269         }
1270         else if (strcasecmp ("Forward", key) == 0)
1271         {
1272                 if ((strcasecmp ("true", val) == 0)
1273                                 || (strcasecmp ("yes", val) == 0)
1274                                 || (strcasecmp ("on", val) == 0))
1275                         network_config_forward = 1;
1276                 else
1277                         network_config_forward = 0;
1278         }
1279         else if (strcasecmp ("CacheFlush", key) == 0)
1280         {
1281                 int tmp = atoi (val);
1282                 if (tmp > 0)
1283                         cache_flush_interval = tmp;
1284                 else return (1);
1285         }
1286         else
1287         {
1288                 return (-1);
1289         }
1290         return (0);
1291 } /* int network_config */
1292
1293 static int network_shutdown (void)
1294 {
1295         listen_loop++;
1296
1297         if (listen_thread != (pthread_t) 0)
1298         {
1299                 pthread_kill (listen_thread, SIGTERM);
1300                 pthread_join (listen_thread, NULL /* no return value */);
1301                 listen_thread = (pthread_t) 0;
1302         }
1303
1304         if (send_buffer_fill > 0)
1305                 flush_buffer ();
1306
1307         if (cache_tree != NULL)
1308         {
1309                 void *key;
1310                 void *value;
1311
1312                 while (c_avl_pick (cache_tree, &key, &value) == 0)
1313                 {
1314                         sfree (key);
1315                         sfree (value);
1316                 }
1317                 c_avl_destroy (cache_tree);
1318                 cache_tree = NULL;
1319         }
1320
1321         /* TODO: Close `sending_sockets' */
1322
1323         plugin_unregister_config ("network");
1324         plugin_unregister_init ("network");
1325         plugin_unregister_write ("network");
1326         plugin_unregister_shutdown ("network");
1327
1328         return (0);
1329 } /* int network_shutdown */
1330
1331 static int network_init (void)
1332 {
1333         plugin_register_shutdown ("network", network_shutdown);
1334
1335         send_buffer_ptr  = send_buffer;
1336         send_buffer_fill = 0;
1337         memset (&send_buffer_vl, '\0', sizeof (send_buffer_vl));
1338         memset (send_buffer_type, '\0', sizeof (send_buffer_type));
1339
1340         cache_tree = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1341         cache_flush_last = time (NULL);
1342
1343         /* setup socket(s) and so on */
1344         if (sending_sockets != NULL)
1345                 plugin_register_write ("network", network_write);
1346
1347         if ((listen_sockets_num != 0) && (listen_thread == 0))
1348         {
1349                 int status;
1350
1351                 status = pthread_create (&listen_thread, NULL /* no attributes */,
1352                                 receive_thread, NULL /* no argument */);
1353
1354                 if (status != 0)
1355                 {
1356                         char errbuf[1024];
1357                         ERROR ("network: pthread_create failed: %s",
1358                                         sstrerror (errno, errbuf,
1359                                                 sizeof (errbuf)));
1360                 }
1361         }
1362         return (0);
1363 } /* int network_init */
1364
1365 void module_register (void)
1366 {
1367         plugin_register_config ("network", network_config,
1368                         config_keys, config_keys_num);
1369         plugin_register_init   ("network", network_init);
1370 } /* void module_register */