Implemented `LoadDS' which tells plugins to only register their DataSources.
[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_INIT;
166 static char         send_buffer_type[DATA_MAX_NAME_LEN];
167 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
168
169 static 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         avl_iterator_t *iter;
188
189         time_t curtime = time (NULL);
190
191         iter = avl_get_iterator (cache_tree);
192         while (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                         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 (avl_iterator_next) */
210         avl_iterator_destroy (iter);
211
212         for (i = 0; i < keys_num; i++)
213         {
214                 if (avl_remove (cache_tree, keys[i], (void *) &key,
215                                         (void *) &value) != 0)
216                 {
217                         WARNING ("network plugin: cache_flush: 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 (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                         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 ("packet is too short: buffer_len = %i", buffer_len);
389                 return (-1);
390         }
391
392         pv.head = (part_header_t *) buffer;
393         h_length = ntohs (pv.head->length);
394         h_type = ntohs (pv.head->type);
395
396         assert (h_type == TYPE_VALUES);
397
398         pv.num_values = (uint16_t *) (pv.head + 1);
399         h_num = ntohs (*pv.num_values);
400
401         if (h_num != ((h_length - 6) / 9))
402         {
403                 DEBUG ("`length' and `num of values' don't match");
404                 return (-1);
405         }
406
407         pv.values_types = (uint8_t *) (pv.num_values + 1);
408         pv.values = (value_t *) (pv.values_types + h_num);
409
410         for (i = 0; i < h_num; i++)
411                 if (pv.values_types[i] == DS_TYPE_COUNTER)
412                         pv.values[i].counter = ntohll (pv.values[i].counter);
413
414         *ret_buffer     = (void *) (pv.values + h_num);
415         *ret_buffer_len = buffer_len - h_length;
416         *ret_num_values = h_num;
417         *ret_values     = pv.values;
418
419         return (0);
420 } /* int parse_part_values */
421
422 static int parse_part_number (void **ret_buffer, int *ret_buffer_len,
423                 uint64_t *value)
424 {
425         part_number_t pn;
426         uint16_t len;
427
428         pn.head = (part_header_t *) *ret_buffer;
429         pn.value = (uint64_t *) (pn.head + 1);
430
431         len = ntohs (pn.head->length);
432         if (len != 12)
433                 return (-1);
434         if (len > *ret_buffer_len)
435                 return (-1);
436         *value = ntohll (*pn.value);
437
438         *ret_buffer = (void *) (pn.value + 1);
439         *ret_buffer_len -= len;
440
441         return (0);
442 } /* int parse_part_number */
443
444 static int parse_part_string (void **ret_buffer, int *ret_buffer_len,
445                 char *output, int output_len)
446 {
447         char *buffer = *ret_buffer;
448         int   buffer_len = *ret_buffer_len;
449         part_string_t ps;
450
451         uint16_t h_length;
452         uint16_t h_type;
453
454         DEBUG ("network plugin: parse_part_string: ret_buffer = %p;"
455                         " ret_buffer_len = %i; output = %p; output_len = %i;",
456                         *ret_buffer, *ret_buffer_len,
457                         (void *) output, output_len);
458
459         ps.head = (part_header_t *) buffer;
460
461         h_length = ntohs (ps.head->length);
462         h_type = ntohs (ps.head->type);
463
464         DEBUG ("network plugin: parse_part_string: length = %hu; type = %hu;",
465                         h_length, h_type);
466
467         if (buffer_len < h_length)
468         {
469                 DEBUG ("packet is too short");
470                 return (-1);
471         }
472         assert ((h_type == TYPE_HOST)
473                         || (h_type == TYPE_PLUGIN)
474                         || (h_type == TYPE_PLUGIN_INSTANCE)
475                         || (h_type == TYPE_TYPE)
476                         || (h_type == TYPE_TYPE_INSTANCE));
477
478         ps.value = buffer + 4;
479         if (ps.value[h_length - 5] != '\0')
480         {
481                 DEBUG ("String does not end with a nullbyte");
482                 return (-1);
483         }
484
485         if (output_len < (h_length - 4))
486         {
487                 DEBUG ("output buffer is too small");
488                 return (-1);
489         }
490         strcpy (output, ps.value);
491
492         DEBUG ("network plugin: parse_part_string: output = %s", output);
493
494         *ret_buffer = (void *) (buffer + h_length);
495         *ret_buffer_len = buffer_len - h_length;
496
497         return (0);
498 } /* int parse_part_string */
499
500 static int parse_packet (void *buffer, int buffer_len)
501 {
502         part_header_t *header;
503         int status;
504
505         value_list_t vl = VALUE_LIST_INIT;
506         char type[DATA_MAX_NAME_LEN];
507
508         DEBUG ("network plugin: parse_packet: buffer = %p; buffer_len = %i;",
509                         buffer, buffer_len);
510
511         memset (&vl, '\0', sizeof (vl));
512         memset (&type, '\0', sizeof (type));
513         status = 0;
514
515         while ((status == 0) && (buffer_len > sizeof (part_header_t)))
516         {
517                 header = (part_header_t *) buffer;
518
519                 if (ntohs (header->length) > buffer_len)
520                         break;
521                 /* Assure that this loop terminates eventually */
522                 if (ntohs (header->length) < 4)
523                         break;
524
525                 if (ntohs (header->type) == TYPE_VALUES)
526                 {
527                         status = parse_part_values (&buffer, &buffer_len,
528                                         &vl.values, &vl.values_len);
529
530                         if (status != 0)
531                         {
532                                 DEBUG ("parse_part_values failed.");
533                                 break;
534                         }
535
536                         if ((vl.time > 0)
537                                         && (strlen (vl.host) > 0)
538                                         && (strlen (vl.plugin) > 0)
539                                         && (strlen (type) > 0)
540                                         && (cache_check (type, &vl) == 0))
541                         {
542                                 DEBUG ("network plugin: parse_packet:"
543                                                 " dispatching values");
544                                 plugin_dispatch_values (type, &vl);
545                         }
546                         else
547                         {
548                                 DEBUG ("network plugin: parse_packet:"
549                                                 " NOT dispatching values");
550                         }
551                 }
552                 else if (ntohs (header->type) == TYPE_TIME)
553                 {
554                         uint64_t tmp = 0;
555                         status = parse_part_number (&buffer, &buffer_len, &tmp);
556                         if (status == 0)
557                                 vl.time = (time_t) tmp;
558                 }
559                 else if (ntohs (header->type) == TYPE_HOST)
560                 {
561                         status = parse_part_string (&buffer, &buffer_len,
562                                         vl.host, sizeof (vl.host));
563                         DEBUG ("network plugin: parse_packet: vl.host = %s", vl.host);
564                 }
565                 else if (ntohs (header->type) == TYPE_PLUGIN)
566                 {
567                         status = parse_part_string (&buffer, &buffer_len,
568                                         vl.plugin, sizeof (vl.plugin));
569                         DEBUG ("network plugin: parse_packet: vl.plugin = %s", vl.plugin);
570                 }
571                 else if (ntohs (header->type) == TYPE_PLUGIN_INSTANCE)
572                 {
573                         status = parse_part_string (&buffer, &buffer_len,
574                                         vl.plugin_instance, sizeof (vl.plugin_instance));
575                         DEBUG ("network plugin: parse_packet: vl.plugin_instance = %s", vl.plugin_instance);
576                 }
577                 else if (ntohs (header->type) == TYPE_TYPE)
578                 {
579                         status = parse_part_string (&buffer, &buffer_len,
580                                         type, sizeof (type));
581                         DEBUG ("network plugin: parse_packet: type = %s", type);
582                 }
583                 else if (ntohs (header->type) == TYPE_TYPE_INSTANCE)
584                 {
585                         status = parse_part_string (&buffer, &buffer_len,
586                                         vl.type_instance, sizeof (vl.type_instance));
587                         DEBUG ("network plugin: parse_packet: vl.type_instance = %s", vl.type_instance);
588                 }
589                 else
590                 {
591                         DEBUG ("network plugin: parse_packet: Unknown part"
592                                         " type: 0x%0hx", ntohs (header->type));
593                         buffer = ((char *) buffer) + ntohs (header->length);
594                 }
595         } /* while (buffer_len > sizeof (part_header_t)) */
596
597         return (0);
598 } /* int parse_packet */
599
600 static void free_sockent (sockent_t *se)
601 {
602         sockent_t *next;
603         while (se != NULL)
604         {
605                 next = se->next;
606                 free (se->addr);
607                 free (se);
608                 se = next;
609         }
610 } /* void free_sockent */
611
612 /*
613  * int network_set_ttl
614  *
615  * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
616  * `IPV6_UNICAST_HOPS', depending on which option is applicable.
617  *
618  * The `struct addrinfo' is used to destinguish between unicast and multicast
619  * sockets.
620  */
621 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
622 {
623         if ((network_config_ttl < 1) || (network_config_ttl > 255))
624                 return (-1);
625
626         DEBUG ("ttl = %i", network_config_ttl);
627
628         if (ai->ai_family == AF_INET)
629         {
630                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
631                 int optname;
632
633                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
634                         optname = IP_MULTICAST_TTL;
635                 else
636                         optname = IP_TTL;
637
638                 if (setsockopt (se->fd, IPPROTO_IP, optname,
639                                         &network_config_ttl,
640                                         sizeof (network_config_ttl)) == -1)
641                 {
642                         char errbuf[1024];
643                         ERROR ("setsockopt: %s",
644                                         sstrerror (errno, errbuf, sizeof (errbuf)));
645                         return (-1);
646                 }
647         }
648         else if (ai->ai_family == AF_INET6)
649         {
650                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
651                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
652                 int optname;
653
654                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
655                         optname = IPV6_MULTICAST_HOPS;
656                 else
657                         optname = IPV6_UNICAST_HOPS;
658
659                 if (setsockopt (se->fd, IPPROTO_IPV6, optname,
660                                         &network_config_ttl,
661                                         sizeof (network_config_ttl)) == -1)
662                 {
663                         char errbuf[1024];
664                         ERROR ("setsockopt: %s",
665                                         sstrerror (errno, errbuf,
666                                                 sizeof (errbuf)));
667                         return (-1);
668                 }
669         }
670
671         return (0);
672 } /* int network_set_ttl */
673
674 static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
675 {
676         int loop = 0;
677
678         DEBUG ("fd = %i; calling `bind'", se->fd);
679
680         if (bind (se->fd, ai->ai_addr, ai->ai_addrlen) == -1)
681         {
682                 char errbuf[1024];
683                 ERROR ("bind: %s",
684                                 sstrerror (errno, errbuf, sizeof (errbuf)));
685                 return (-1);
686         }
687
688         if (ai->ai_family == AF_INET)
689         {
690                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
691                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
692                 {
693                         struct ip_mreq mreq;
694
695                         DEBUG ("fd = %i; IPv4 multicast address found", se->fd);
696
697                         mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
698                         mreq.imr_interface.s_addr = htonl (INADDR_ANY);
699
700                         if (setsockopt (se->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
701                                                 &loop, sizeof (loop)) == -1)
702                         {
703                                 char errbuf[1024];
704                                 ERROR ("setsockopt: %s",
705                                                 sstrerror (errno, errbuf,
706                                                         sizeof (errbuf)));
707                                 return (-1);
708                         }
709
710                         if (setsockopt (se->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
711                                                 &mreq, sizeof (mreq)) == -1)
712                         {
713                                 char errbuf[1024];
714                                 ERROR ("setsockopt: %s",
715                                                 sstrerror (errno, errbuf,
716                                                         sizeof (errbuf)));
717                                 return (-1);
718                         }
719                 }
720         }
721         else if (ai->ai_family == AF_INET6)
722         {
723                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
724                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
725                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
726                 {
727                         struct ipv6_mreq mreq;
728
729                         DEBUG ("fd = %i; IPv6 multicast address found", se->fd);
730
731                         memcpy (&mreq.ipv6mr_multiaddr,
732                                         &addr->sin6_addr,
733                                         sizeof (addr->sin6_addr));
734
735                         /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
736                          * ipv6mr_interface may be set to zeroes to
737                          * choose the default multicast interface or to
738                          * the index of a particular multicast-capable
739                          * interface if the host is multihomed.
740                          * Membership is associ-associated with a
741                          * single interface; programs running on
742                          * multihomed hosts may need to join the same
743                          * group on more than one interface.*/
744                         mreq.ipv6mr_interface = 0;
745
746                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
747                                                 &loop, sizeof (loop)) == -1)
748                         {
749                                 char errbuf[1024];
750                                 ERROR ("setsockopt: %s",
751                                                 sstrerror (errno, errbuf,
752                                                         sizeof (errbuf)));
753                                 return (-1);
754                         }
755
756                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
757                                                 &mreq, sizeof (mreq)) == -1)
758                         {
759                                 char errbuf[1024];
760                                 ERROR ("setsockopt: %s",
761                                                 sstrerror (errno, errbuf,
762                                                         sizeof (errbuf)));
763                                 return (-1);
764                         }
765                 }
766         }
767
768         return (0);
769 } /* int network_bind_socket */
770
771 static sockent_t *network_create_socket (const char *node,
772                 const char *service,
773                 int listen)
774 {
775         struct addrinfo  ai_hints;
776         struct addrinfo *ai_list, *ai_ptr;
777         int              ai_return;
778
779         sockent_t *se_head = NULL;
780         sockent_t *se_tail = NULL;
781
782         DEBUG ("node = %s, service = %s", node, service);
783
784         memset (&ai_hints, '\0', sizeof (ai_hints));
785         ai_hints.ai_flags    = 0;
786 #ifdef AI_PASSIVE
787         ai_hints.ai_flags |= AI_PASSIVE;
788 #endif
789 #ifdef AI_ADDRCONFIG
790         ai_hints.ai_flags |= AI_ADDRCONFIG;
791 #endif
792         ai_hints.ai_family   = AF_UNSPEC;
793         ai_hints.ai_socktype = SOCK_DGRAM;
794         ai_hints.ai_protocol = IPPROTO_UDP;
795
796         ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
797         if (ai_return != 0)
798         {
799                 char errbuf[1024];
800                 ERROR ("getaddrinfo (%s, %s): %s",
801                                 (node == NULL) ? "(null)" : node,
802                                 (service == NULL) ? "(null)" : service,
803                                 (ai_return == EAI_SYSTEM)
804                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
805                                 : gai_strerror (ai_return));
806                 return (NULL);
807         }
808
809         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
810         {
811                 sockent_t *se;
812
813                 if ((se = (sockent_t *) malloc (sizeof (sockent_t))) == NULL)
814                 {
815                         char errbuf[1024];
816                         ERROR ("malloc: %s",
817                                         sstrerror (errno, errbuf,
818                                                 sizeof (errbuf)));
819                         continue;
820                 }
821
822                 if ((se->addr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage))) == NULL)
823                 {
824                         char errbuf[1024];
825                         ERROR ("malloc: %s",
826                                         sstrerror (errno, errbuf,
827                                                 sizeof (errbuf)));
828                         free (se);
829                         continue;
830                 }
831
832                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
833                 memset (se->addr, '\0', sizeof (struct sockaddr_storage));
834                 memcpy (se->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
835                 se->addrlen = ai_ptr->ai_addrlen;
836
837                 se->fd   = socket (ai_ptr->ai_family,
838                                 ai_ptr->ai_socktype,
839                                 ai_ptr->ai_protocol);
840                 se->next = NULL;
841
842                 if (se->fd == -1)
843                 {
844                         char errbuf[1024];
845                         ERROR ("socket: %s",
846                                         sstrerror (errno, errbuf,
847                                                 sizeof (errbuf)));
848                         free (se->addr);
849                         free (se);
850                         continue;
851                 }
852
853                 if (listen != 0)
854                 {
855                         if (network_bind_socket (se, ai_ptr) != 0)
856                         {
857                                 close (se->fd);
858                                 free (se->addr);
859                                 free (se);
860                                 continue;
861                         }
862                 }
863                 else /* listen == 0 */
864                 {
865                         network_set_ttl (se, ai_ptr);
866                 }
867
868                 if (se_tail == NULL)
869                 {
870                         se_head = se;
871                         se_tail = se;
872                 }
873                 else
874                 {
875                         se_tail->next = se;
876                         se_tail = se;
877                 }
878
879                 /* We don't open more than one write-socket per node/service pair.. */
880                 if (listen == 0)
881                         break;
882         }
883
884         freeaddrinfo (ai_list);
885
886         return (se_head);
887 } /* sockent_t *network_create_socket */
888
889 static sockent_t *network_create_default_socket (int listen)
890 {
891         sockent_t *se_ptr  = NULL;
892         sockent_t *se_head = NULL;
893         sockent_t *se_tail = NULL;
894
895         se_ptr = network_create_socket (NET_DEFAULT_V6_ADDR,
896                         NET_DEFAULT_PORT, listen);
897
898         /* Don't send to the same machine in IPv6 and IPv4 if both are available. */
899         if ((listen == 0) && (se_ptr != NULL))
900                 return (se_ptr);
901
902         if (se_ptr != NULL)
903         {
904                 se_head = se_ptr;
905                 se_tail = se_ptr;
906                 while (se_tail->next != NULL)
907                         se_tail = se_tail->next;
908         }
909
910         se_ptr = network_create_socket (NET_DEFAULT_V4_ADDR, NET_DEFAULT_PORT, listen);
911
912         if (se_tail == NULL)
913                 return (se_ptr);
914
915         se_tail->next = se_ptr;
916         return (se_head);
917 } /* sockent_t *network_create_default_socket */
918
919 static int network_add_listen_socket (const char *node, const char *service)
920 {
921         sockent_t *se;
922         sockent_t *se_ptr;
923         int se_num = 0;
924
925         if (service == NULL)
926                 service = NET_DEFAULT_PORT;
927
928         if (node == NULL)
929                 se = network_create_default_socket (1 /* listen == true */);
930         else
931                 se = network_create_socket (node, service, 1 /* listen == true */);
932
933         if (se == NULL)
934                 return (-1);
935
936         for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
937                 se_num++;
938
939         listen_sockets = (struct pollfd *) realloc (listen_sockets,
940                         (listen_sockets_num + se_num)
941                         * sizeof (struct pollfd));
942
943         for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
944         {
945                 listen_sockets[listen_sockets_num].fd = se_ptr->fd;
946                 listen_sockets[listen_sockets_num].events = POLLIN | POLLPRI;
947                 listen_sockets[listen_sockets_num].revents = 0;
948                 listen_sockets_num++;
949         } /* for (se) */
950
951         free_sockent (se);
952         return (0);
953 } /* int network_add_listen_socket */
954
955 static int network_add_sending_socket (const char *node, const char *service)
956 {
957         sockent_t *se;
958         sockent_t *se_ptr;
959
960         if (service == NULL)
961                 service = NET_DEFAULT_PORT;
962
963         if (node == NULL)
964                 se = network_create_default_socket (0 /* listen == false */);
965         else
966                 se = network_create_socket (node, service, 0 /* listen == false */);
967
968         if (se == NULL)
969                 return (-1);
970
971         if (sending_sockets == NULL)
972         {
973                 sending_sockets = se;
974                 return (0);
975         }
976
977         for (se_ptr = sending_sockets; se_ptr->next != NULL; se_ptr = se_ptr->next)
978                 /* seek end */;
979
980         se_ptr->next = se;
981         return (0);
982 } /* int network_get_listen_socket */
983
984 int network_receive (void)
985 {
986         char buffer[BUFF_SIZE];
987         int  buffer_len;
988
989         int i;
990         int status;
991
992         if (listen_sockets_num == 0)
993                 network_add_listen_socket (NULL, NULL);
994
995         if (listen_sockets_num == 0)
996         {
997                 ERROR ("network: Failed to open a listening socket.");
998                 return (-1);
999         }
1000
1001         while (listen_loop == 0)
1002         {
1003                 status = poll (listen_sockets, listen_sockets_num, -1);
1004
1005                 if (status <= 0)
1006                 {
1007                         char errbuf[1024];
1008                         if (errno == EINTR)
1009                                 continue;
1010                         ERROR ("poll failed: %s",
1011                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1012                         return (-1);
1013                 }
1014
1015                 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
1016                 {
1017                         if ((listen_sockets[i].revents & (POLLIN | POLLPRI)) == 0)
1018                                 continue;
1019                         status--;
1020
1021                         buffer_len = recv (listen_sockets[i].fd,
1022                                         buffer, sizeof (buffer),
1023                                         0 /* no flags */);
1024                         if (buffer_len < 0)
1025                         {
1026                                 char errbuf[1024];
1027                                 ERROR ("recv failed: %s",
1028                                                 sstrerror (errno, errbuf,
1029                                                         sizeof (errbuf)));
1030                                 return (-1);
1031                         }
1032
1033                         parse_packet (buffer, buffer_len);
1034                 } /* for (listen_sockets) */
1035         } /* while (listen_loop == 0) */
1036
1037         return (0);
1038 }
1039
1040 static void *receive_thread (void *arg)
1041 {
1042         return (network_receive () ? (void *) 1 : (void *) 0);
1043 } /* void *receive_thread */
1044
1045 static void network_send_buffer (const char *buffer, int buffer_len)
1046 {
1047         sockent_t *se;
1048         int status;
1049
1050         DEBUG ("buffer_len = %i", buffer_len);
1051
1052         for (se = sending_sockets; se != NULL; se = se->next)
1053         {
1054                 while (42)
1055                 {
1056                         status = sendto (se->fd, buffer, buffer_len, 0 /* no flags */,
1057                                         (struct sockaddr *) se->addr, se->addrlen);
1058                         if (status < 0)
1059                         {
1060                                 char errbuf[1024];
1061                                 if (errno == EINTR)
1062                                         continue;
1063                                 ERROR ("network plugin: sendto failed: %s",
1064                                                 sstrerror (errno, errbuf,
1065                                                         sizeof (errbuf)));
1066                                 break;
1067                         }
1068
1069                         break;
1070                 } /* while (42) */
1071         } /* for (sending_sockets) */
1072 } /* void network_send_buffer */
1073
1074 static int add_to_buffer (char *buffer, int buffer_size,
1075                 value_list_t *vl_def, char *type_def,
1076                 const data_set_t *ds, const value_list_t *vl)
1077 {
1078         char *buffer_orig = buffer;
1079
1080         if (strcmp (vl_def->host, vl->host) != 0)
1081         {
1082                 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
1083                                         vl->host, strlen (vl->host)) != 0)
1084                         return (-1);
1085                 strcpy (vl_def->host, vl->host);
1086                 DEBUG ("network plugin: add_to_buffer: host = %s", vl->host);
1087         }
1088
1089         if (vl_def->time != vl->time)
1090         {
1091                 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
1092                                         (uint64_t) vl->time))
1093                         return (-1);
1094                 vl_def->time = vl->time;
1095                 DEBUG ("network plugin: add_to_buffer: time = %u",
1096                                 (unsigned int) vl->time);
1097         }
1098
1099         if (strcmp (vl_def->plugin, vl->plugin) != 0)
1100         {
1101                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
1102                                         vl->plugin, strlen (vl->plugin)) != 0)
1103                         return (-1);
1104                 strcpy (vl_def->plugin, vl->plugin);
1105                 DEBUG ("network plugin: add_to_buffer: plugin = %s",
1106                                 vl->plugin);
1107         }
1108
1109         if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
1110         {
1111                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
1112                                         vl->plugin_instance,
1113                                         strlen (vl->plugin_instance)) != 0)
1114                         return (-1);
1115                 strcpy (vl_def->plugin_instance, vl->plugin_instance);
1116                 DEBUG ("network plugin: add_to_buffer: plugin_instance = %s",
1117                                 vl->plugin_instance);
1118         }
1119
1120         if (strcmp (type_def, ds->type) != 0)
1121         {
1122                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
1123                                         ds->type, strlen (ds->type)) != 0)
1124                         return (-1);
1125                 strcpy (type_def, ds->type);
1126                 DEBUG ("network plugin: add_to_buffer: type = %s", ds->type);
1127         }
1128
1129         if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
1130         {
1131                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
1132                                         vl->type_instance,
1133                                         strlen (vl->type_instance)) != 0)
1134                         return (-1);
1135                 strcpy (vl_def->type_instance, vl->type_instance);
1136                 DEBUG ("network plugin: add_to_buffer: type_instance = %s",
1137                                 vl->type_instance);
1138         }
1139         
1140         if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
1141                 return (-1);
1142
1143         return (buffer - buffer_orig);
1144 } /* int add_to_buffer */
1145
1146 static void flush_buffer (void)
1147 {
1148         DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
1149                         send_buffer_fill);
1150
1151         network_send_buffer (send_buffer, send_buffer_fill);
1152         send_buffer_ptr  = send_buffer;
1153         send_buffer_fill = 0;
1154         memset (&send_buffer_vl, '\0', sizeof (send_buffer_vl));
1155         memset (send_buffer_type, '\0', sizeof (send_buffer_type));
1156 }
1157
1158 static int network_write (const data_set_t *ds, const value_list_t *vl)
1159 {
1160         int status;
1161
1162         /* If the value is already in the cache, we have received it via the
1163          * network. We write it again if forwarding is activated. It's then in
1164          * the cache and should we receive it again we will ignore it. */
1165         status = cache_check (ds->type, vl);
1166         if ((network_config_forward == 0)
1167                         && (status != 0))
1168                 return (0);
1169
1170         pthread_mutex_lock (&send_buffer_lock);
1171
1172         status = add_to_buffer (send_buffer_ptr,
1173                         sizeof (send_buffer) - send_buffer_fill,
1174                         &send_buffer_vl, send_buffer_type,
1175                         ds, vl);
1176         if (status >= 0)
1177         {
1178                 /* status == bytes added to the buffer */
1179                 send_buffer_fill += status;
1180                 send_buffer_ptr  += status;
1181         }
1182         else
1183         {
1184                 flush_buffer ();
1185
1186                 status = add_to_buffer (send_buffer_ptr,
1187                                 sizeof (send_buffer) - send_buffer_fill,
1188                                 &send_buffer_vl, send_buffer_type,
1189                                 ds, vl);
1190
1191                 if (status >= 0)
1192                 {
1193                         send_buffer_fill += status;
1194                         send_buffer_ptr  += status;
1195                 }
1196         }
1197
1198         if (status < 0)
1199         {
1200                 ERROR ("network plugin: Unable to append to the "
1201                                 "buffer for some weird reason");
1202         }
1203         else if ((sizeof (send_buffer) - send_buffer_fill) < 15)
1204         {
1205                 flush_buffer ();
1206         }
1207
1208         pthread_mutex_unlock (&send_buffer_lock);
1209
1210         return ((status < 0) ? -1 : 0);
1211 } /* int network_write */
1212
1213 static int network_config (const char *key, const char *val)
1214 {
1215         char *node;
1216         char *service;
1217
1218         char *fields[3];
1219         int   fields_num;
1220
1221         if ((strcasecmp ("Listen", key) == 0)
1222                         || (strcasecmp ("Server", key) == 0))
1223         {
1224                 char *val_cpy = strdup (val);
1225                 if (val_cpy == NULL)
1226                         return (1);
1227
1228                 service = NET_DEFAULT_PORT;
1229                 fields_num = strsplit (val_cpy, fields, 3);
1230                 if ((fields_num != 1)
1231                                 && (fields_num != 2))
1232                         return (1);
1233                 else if (fields_num == 2)
1234                         service = fields[1];
1235                 node = fields[0];
1236
1237                 if (strcasecmp ("Listen", key) == 0)
1238                         network_add_listen_socket (node, service);
1239                 else
1240                         network_add_sending_socket (node, service);
1241         }
1242         else if (strcasecmp ("TimeToLive", key) == 0)
1243         {
1244                 int tmp = atoi (val);
1245                 if ((tmp > 0) && (tmp < 256))
1246                         network_config_ttl = tmp;
1247                 else
1248                         return (1);
1249         }
1250         else if (strcasecmp ("Forward", key) == 0)
1251         {
1252                 if ((strcasecmp ("true", val) == 0)
1253                                 || (strcasecmp ("yes", val) == 0)
1254                                 || (strcasecmp ("on", val) == 0))
1255                         network_config_forward = 1;
1256                 else
1257                         network_config_forward = 0;
1258         }
1259         else if (strcasecmp ("CacheFlush", key) == 0)
1260         {
1261                 int tmp = atoi (val);
1262                 if (tmp > 0)
1263                         cache_flush_interval = tmp;
1264                 else return (1);
1265         }
1266         else
1267         {
1268                 return (-1);
1269         }
1270         return (0);
1271 } /* int network_config */
1272
1273 static int network_shutdown (void)
1274 {
1275         DEBUG ("Shutting down.");
1276
1277         listen_loop++;
1278
1279         if (listen_thread != (pthread_t) 0)
1280         {
1281                 pthread_kill (listen_thread, SIGTERM);
1282                 pthread_join (listen_thread, NULL /* no return value */);
1283                 listen_thread = (pthread_t) 0;
1284         }
1285
1286         listen_thread = 0;
1287
1288         if (cache_tree != NULL)
1289         {
1290                 void *key;
1291                 void *value;
1292
1293                 while (avl_pick (cache_tree, &key, &value) == 0)
1294                 {
1295                         sfree (key);
1296                         sfree (value);
1297                 }
1298                 avl_destroy (cache_tree);
1299                 cache_tree = NULL;
1300         }
1301
1302         /* TODO: Close `sending_sockets' */
1303
1304         plugin_unregister_config ("network");
1305         plugin_unregister_init ("network");
1306         plugin_unregister_write ("network");
1307         plugin_unregister_shutdown ("network");
1308
1309         return (0);
1310 } /* int network_shutdown */
1311
1312 static int network_init (void)
1313 {
1314         plugin_register_shutdown ("network", network_shutdown);
1315
1316         send_buffer_ptr  = send_buffer;
1317         send_buffer_fill = 0;
1318         memset (&send_buffer_vl, '\0', sizeof (send_buffer_vl));
1319         memset (send_buffer_type, '\0', sizeof (send_buffer_type));
1320
1321         cache_tree = avl_create ((int (*) (const void *, const void *)) strcmp);
1322         cache_flush_last = time (NULL);
1323
1324         /* setup socket(s) and so on */
1325         if (sending_sockets != NULL)
1326                 plugin_register_write ("network", network_write);
1327
1328         if ((listen_sockets_num != 0) && (listen_thread == 0))
1329         {
1330                 int status;
1331
1332                 status = pthread_create (&listen_thread, NULL /* no attributes */,
1333                                 receive_thread, NULL /* no argument */);
1334
1335                 if (status != 0)
1336                 {
1337                         char errbuf[1024];
1338                         ERROR ("network: pthread_create failed: %s",
1339                                         sstrerror (errno, errbuf,
1340                                                 sizeof (errbuf)));
1341                 }
1342         }
1343         return (0);
1344 } /* int network_init */
1345
1346 void module_register (modreg_e load)
1347 {
1348         plugin_register_config ("network", network_config,
1349                         config_keys, config_keys_num);
1350         plugin_register_init   ("network", network_init);
1351 } /* void module_register */