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