src/plugin.h: Added `VALUE_LIST_INIT', a static initializer for value_list_t.
[collectd.git] / src / network.c
1 /**
2  * collectd - src/network.c
3  * Copyright (C) 2005,2006  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_debug.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 4096
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         "Listen",
145         "Server",
146         "TimeToLive",
147         NULL
148 };
149 static int config_keys_num = 3;
150
151 static int network_config_ttl = 0;
152
153 static sockent_t *sending_sockets = NULL;
154
155 static struct pollfd *listen_sockets = NULL;
156 static int listen_sockets_num = 0;
157 static pthread_t listen_thread = 0;
158 static int listen_loop = 0;
159
160 /*
161  * Private functions
162  */
163 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
164                 const data_set_t *ds, const value_list_t *vl)
165 {
166         part_values_t pv;
167         int i;
168
169         i = 6 + (9 * vl->values_len);
170         if (*ret_buffer_len < i)
171                 return (-1);
172         *ret_buffer_len -= i;
173
174         pv.head = (part_header_t *) *ret_buffer;
175         pv.num_values = (uint16_t *) (pv.head + 1);
176         pv.values_types = (uint8_t *) (pv.num_values + 1);
177         pv.values = (value_t *) (pv.values_types + vl->values_len);
178         *ret_buffer = (void *) (pv.values + vl->values_len);
179
180         pv.head->type = htons (TYPE_VALUES);
181         pv.head->length = htons (6 + (9 * vl->values_len));
182         *pv.num_values = htons ((uint16_t) vl->values_len);
183         
184         for (i = 0; i < vl->values_len; i++)
185         {
186                 if (ds->ds[i].type == DS_TYPE_COUNTER)
187                 {
188                         pv.values_types[i] = DS_TYPE_COUNTER;
189                         pv.values[i].counter = htonll (vl->values[i].counter);
190                 }
191                 else
192                 {
193                         pv.values_types[i] = DS_TYPE_GAUGE;
194                         pv.values[i].gauge = vl->values[i].gauge;
195                 }
196         } /* for (values) */
197
198         return (0);
199 } /* int write_part_values */
200
201 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
202                 int type, uint64_t value)
203 {
204         part_number_t pn;
205
206         if (*ret_buffer_len < 12)
207                 return (-1);
208
209         pn.head = (part_header_t *) *ret_buffer;
210         pn.value = (uint64_t *) (pn.head + 1);
211
212         pn.head->type = htons (type);
213         pn.head->length = htons (12);
214         *pn.value = htonll (value);
215
216         *ret_buffer = (char *) (pn.value + 1);
217         *ret_buffer_len -= 12;
218
219         return (0);
220 } /* int write_part_number */
221
222 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
223                 int type, const char *str, int str_len)
224 {
225         part_string_t ps;
226         int len;
227
228         if (str_len < 1)
229                 return (-1);
230
231         len = 4 + str_len + 1;
232         if (*ret_buffer_len < len)
233                 return (-1);
234         *ret_buffer_len -= len;
235
236         ps.head = (part_header_t *) *ret_buffer;
237         ps.value = (char *) (ps.head + 1);
238
239         ps.head->type = htons ((uint16_t) type);
240         ps.head->length = htons ((uint16_t) str_len + 5);
241         memcpy (ps.value, str, str_len);
242         ps.value[str_len] = '\0';
243         *ret_buffer = (void *) (ps.value + (str_len + 1));
244
245         return (0);
246 } /* int write_part_string */
247
248 static int parse_part_values (void **ret_buffer, int *ret_buffer_len,
249                 value_t **ret_values, int *ret_num_values)
250 {
251         char *buffer = *ret_buffer;
252         int   buffer_len = *ret_buffer_len;
253         part_values_t pv;
254         int   i;
255
256         uint16_t h_length;
257         uint16_t h_type;
258         uint16_t h_num;
259
260         if (buffer_len < (15))
261         {
262                 DBG ("packet is too short: buffer_len = %i", buffer_len);
263                 return (-1);
264         }
265
266         pv.head = (part_header_t *) buffer;
267         h_length = ntohs (pv.head->length);
268         h_type = ntohs (pv.head->type);
269
270         assert (h_type == TYPE_VALUES);
271
272         pv.num_values = (uint16_t *) (pv.head + 1);
273         h_num = ntohs (*pv.num_values);
274
275         if (h_num != ((h_length - 6) / 9))
276         {
277                 DBG ("`length' and `num of values' don't match");
278                 return (-1);
279         }
280
281         pv.values_types = (uint8_t *) (pv.num_values + 1);
282         pv.values = (value_t *) (pv.values_types + h_num);
283
284         for (i = 0; i < h_num; i++)
285                 if (pv.values_types[i] == DS_TYPE_COUNTER)
286                         pv.values[i].counter = ntohll (pv.values[i].counter);
287
288         *ret_buffer     = (void *) (pv.values + h_num);
289         *ret_buffer_len = buffer_len - h_length;
290         *ret_num_values = h_num;
291         *ret_values     = pv.values;
292
293         return (0);
294 } /* int parse_part_values */
295
296 static int parse_part_number (void **ret_buffer, int *ret_buffer_len,
297                 uint64_t *value)
298 {
299         part_number_t pn;
300         uint16_t len;
301
302         pn.head = (part_header_t *) *ret_buffer;
303         pn.value = (uint64_t *) (pn.head + 1);
304
305         len = ntohs (pn.head->length);
306         if (len != 12)
307                 return (-1);
308         if (len > *ret_buffer_len)
309                 return (-1);
310         *value = ntohll (*pn.value);
311
312         *ret_buffer = (void *) (pn.value + 1);
313         *ret_buffer_len -= len;
314
315         return (0);
316 } /* int parse_part_number */
317
318 static int parse_part_string (void **ret_buffer, int *ret_buffer_len,
319                 char *output, int output_len)
320 {
321         char *buffer = *ret_buffer;
322         int   buffer_len = *ret_buffer_len;
323         part_string_t ps;
324
325         uint16_t h_length;
326         uint16_t h_type;
327
328         DBG ("ret_buffer = %p; ret_buffer_len = %i; output = %p; output_len = %i;",
329                         *ret_buffer, *ret_buffer_len,
330                         (void *) output, output_len);
331
332         ps.head = (part_header_t *) buffer;
333
334         h_length = ntohs (ps.head->length);
335         h_type = ntohs (ps.head->type);
336
337         DBG ("length = %hu; type = %hu;", h_length, h_type);
338
339         if (buffer_len < h_length)
340         {
341                 DBG ("packet is too short");
342                 return (-1);
343         }
344         assert ((h_type == TYPE_HOST)
345                         || (h_type == TYPE_PLUGIN)
346                         || (h_type == TYPE_PLUGIN_INSTANCE)
347                         || (h_type == TYPE_TYPE)
348                         || (h_type == TYPE_TYPE_INSTANCE));
349
350         ps.value = buffer + 4;
351         if (ps.value[h_length - 5] != '\0')
352         {
353                 DBG ("String does not end with a nullbyte");
354                 return (-1);
355         }
356
357         if (output_len < (h_length - 4))
358         {
359                 DBG ("output buffer is too small");
360                 return (-1);
361         }
362         strcpy (output, ps.value);
363
364         DBG ("output = %s", output);
365
366         *ret_buffer = (void *) (buffer + h_length);
367         *ret_buffer_len = buffer_len - h_length;
368
369         return (0);
370 } /* int parse_part_string */
371
372 static int parse_packet (void *buffer, int buffer_len)
373 {
374         part_header_t *header;
375         int status;
376
377         value_list_t vl = VALUE_LIST_INIT;
378         char type[DATA_MAX_NAME_LEN];
379
380         DBG ("buffer = %p; buffer_len = %i;", buffer, buffer_len);
381
382         memset (&vl, '\0', sizeof (vl));
383         memset (&type, '\0', sizeof (type));
384         status = 0;
385
386         while ((status == 0) && (buffer_len > sizeof (part_header_t)))
387         {
388                 header = (part_header_t *) buffer;
389
390                 if (ntohs (header->length) > buffer_len)
391                         break;
392
393                 if (header->type == htons (TYPE_VALUES))
394                 {
395                         status = parse_part_values (&buffer, &buffer_len,
396                                         &vl.values, &vl.values_len);
397
398                         if (status != 0)
399                         {
400                                 DBG ("parse_part_values failed.");
401                                 break;
402                         }
403
404                         if ((vl.time > 0)
405                                         && (strlen (vl.host) > 0)
406                                         && (strlen (vl.plugin) > 0)
407                                         && (strlen (type) > 0))
408                         {
409                                 DBG ("dispatching values");
410                                 plugin_dispatch_values (type, &vl);
411                         }
412                         else
413                         {
414                                 DBG ("NOT dispatching values");
415                         }
416                 }
417                 else if (header->type == ntohs (TYPE_TIME))
418                 {
419                         uint64_t tmp = 0;
420                         status = parse_part_number (&buffer, &buffer_len, &tmp);
421                         if (status == 0)
422                                 vl.time = (time_t) tmp;
423                 }
424                 else if (header->type == ntohs (TYPE_HOST))
425                 {
426                         status = parse_part_string (&buffer, &buffer_len,
427                                         vl.host, sizeof (vl.host));
428                 }
429                 else if (header->type == ntohs (TYPE_PLUGIN))
430                 {
431                         status = parse_part_string (&buffer, &buffer_len,
432                                         vl.plugin, sizeof (vl.plugin));
433                 }
434                 else if (header->type == ntohs (TYPE_PLUGIN_INSTANCE))
435                 {
436                         status = parse_part_string (&buffer, &buffer_len,
437                                         vl.plugin_instance, sizeof (vl.plugin_instance));
438                 }
439                 else if (header->type == ntohs (TYPE_TYPE))
440                 {
441                         status = parse_part_string (&buffer, &buffer_len,
442                                         type, sizeof (type));
443                 }
444                 else if (header->type == ntohs (TYPE_TYPE_INSTANCE))
445                 {
446                         status = parse_part_string (&buffer, &buffer_len,
447                                         vl.type_instance, sizeof (vl.type_instance));
448                 }
449                 else
450                 {
451                         DBG ("Unknown part type: 0x%0hx", header->type);
452                         buffer = ((char *) buffer) + header->length;
453                 }
454         } /* while (buffer_len > sizeof (part_header_t)) */
455
456         return (0);
457 } /* int parse_packet */
458
459 static void free_sockent (sockent_t *se)
460 {
461         sockent_t *next;
462         while (se != NULL)
463         {
464                 next = se->next;
465                 free (se->addr);
466                 free (se);
467                 se = next;
468         }
469 } /* void free_sockent */
470
471 /*
472  * int network_set_ttl
473  *
474  * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
475  * `IPV6_UNICAST_HOPS', depending on which option is applicable.
476  *
477  * The `struct addrinfo' is used to destinguish between unicast and multicast
478  * sockets.
479  */
480 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
481 {
482         if ((network_config_ttl < 1) || (network_config_ttl > 255))
483                 return (-1);
484
485         DBG ("ttl = %i", network_config_ttl);
486
487         if (ai->ai_family == AF_INET)
488         {
489                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
490                 int optname;
491
492                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
493                         optname = IP_MULTICAST_TTL;
494                 else
495                         optname = IP_TTL;
496
497                 if (setsockopt (se->fd, IPPROTO_IP, optname,
498                                         &network_config_ttl,
499                                         sizeof (network_config_ttl)) == -1)
500                 {
501                         syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
502                         return (-1);
503                 }
504         }
505         else if (ai->ai_family == AF_INET6)
506         {
507                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
508                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
509                 int optname;
510
511                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
512                         optname = IPV6_MULTICAST_HOPS;
513                 else
514                         optname = IPV6_UNICAST_HOPS;
515
516                 if (setsockopt (se->fd, IPPROTO_IPV6, optname,
517                                         &network_config_ttl,
518                                         sizeof (network_config_ttl)) == -1)
519                 {
520                         syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
521                         return (-1);
522                 }
523         }
524
525         return (0);
526 } /* int network_set_ttl */
527
528 static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
529 {
530         int loop = 1;
531
532         DBG ("fd = %i; calling `bind'", se->fd);
533
534         if (bind (se->fd, ai->ai_addr, ai->ai_addrlen) == -1)
535         {
536                 syslog (LOG_ERR, "bind: %s", strerror (errno));
537                 return (-1);
538         }
539
540         if (ai->ai_family == AF_INET)
541         {
542                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
543                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
544                 {
545                         struct ip_mreq mreq;
546
547                         DBG ("fd = %i; IPv4 multicast address found", se->fd);
548
549                         mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
550                         mreq.imr_interface.s_addr = htonl (INADDR_ANY);
551
552                         if (setsockopt (se->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
553                                                 &loop, sizeof (loop)) == -1)
554                         {
555                                 syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
556                                 return (-1);
557                         }
558
559                         if (setsockopt (se->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
560                                                 &mreq, sizeof (mreq)) == -1)
561                         {
562                                 syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
563                                 return (-1);
564                         }
565                 }
566         }
567         else if (ai->ai_family == AF_INET6)
568         {
569                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
570                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
571                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
572                 {
573                         struct ipv6_mreq mreq;
574
575                         DBG ("fd = %i; IPv6 multicast address found", se->fd);
576
577                         memcpy (&mreq.ipv6mr_multiaddr,
578                                         &addr->sin6_addr,
579                                         sizeof (addr->sin6_addr));
580
581                         /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
582                          * ipv6mr_interface may be set to zeroes to
583                          * choose the default multicast interface or to
584                          * the index of a particular multicast-capable
585                          * interface if the host is multihomed.
586                          * Membership is associ-associated with a
587                          * single interface; programs running on
588                          * multihomed hosts may need to join the same
589                          * group on more than one interface.*/
590                         mreq.ipv6mr_interface = 0;
591
592                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
593                                                 &loop, sizeof (loop)) == -1)
594                         {
595                                 syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
596                                 return (-1);
597                         }
598
599                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
600                                                 &mreq, sizeof (mreq)) == -1)
601                         {
602                                 syslog (LOG_ERR, "setsockopt: %s", strerror (errno));
603                                 return (-1);
604                         }
605                 }
606         }
607
608         return (0);
609 } /* int network_bind_socket */
610
611 static sockent_t *network_create_socket (const char *node,
612                 const char *service,
613                 int listen)
614 {
615         struct addrinfo  ai_hints;
616         struct addrinfo *ai_list, *ai_ptr;
617         int              ai_return;
618
619         sockent_t *se_head = NULL;
620         sockent_t *se_tail = NULL;
621
622         DBG ("node = %s, service = %s", node, service);
623
624         memset (&ai_hints, '\0', sizeof (ai_hints));
625         ai_hints.ai_flags    = 0;
626 #ifdef AI_PASSIVE
627         ai_hints.ai_flags |= AI_PASSIVE;
628 #endif
629 #ifdef AI_ADDRCONFIG
630         ai_hints.ai_flags |= AI_ADDRCONFIG;
631 #endif
632         ai_hints.ai_family   = AF_UNSPEC;
633         ai_hints.ai_socktype = SOCK_DGRAM;
634         ai_hints.ai_protocol = IPPROTO_UDP;
635
636         ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
637         if (ai_return != 0)
638         {
639                 syslog (LOG_ERR, "getaddrinfo (%s, %s): %s",
640                                 (node == NULL) ? "(null)" : node,
641                                 (service == NULL) ? "(null)" : service,
642                                 (ai_return == EAI_SYSTEM)
643                                 ? strerror (errno)
644                                 : gai_strerror (ai_return));
645                 return (NULL);
646         }
647
648         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
649         {
650                 sockent_t *se;
651
652                 if ((se = (sockent_t *) malloc (sizeof (sockent_t))) == NULL)
653                 {
654                         syslog (LOG_EMERG, "malloc: %s", strerror (errno));
655                         continue;
656                 }
657
658                 if ((se->addr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage))) == NULL)
659                 {
660                         syslog (LOG_EMERG, "malloc: %s", strerror (errno));
661                         free (se);
662                         continue;
663                 }
664
665                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
666                 memset (se->addr, '\0', sizeof (struct sockaddr_storage));
667                 memcpy (se->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
668                 se->addrlen = ai_ptr->ai_addrlen;
669
670                 se->fd   = socket (ai_ptr->ai_family,
671                                 ai_ptr->ai_socktype,
672                                 ai_ptr->ai_protocol);
673                 se->next = NULL;
674
675                 if (se->fd == -1)
676                 {
677                         syslog (LOG_ERR, "socket: %s", strerror (errno));
678                         free (se->addr);
679                         free (se);
680                         continue;
681                 }
682
683                 if (listen != 0)
684                 {
685                         if (network_bind_socket (se, ai_ptr) != 0)
686                         {
687                                 close (se->fd);
688                                 free (se->addr);
689                                 free (se);
690                                 continue;
691                         }
692                 }
693                 else /* listen == 0 */
694                 {
695                         network_set_ttl (se, ai_ptr);
696                 }
697
698                 if (se_tail == NULL)
699                 {
700                         se_head = se;
701                         se_tail = se;
702                 }
703                 else
704                 {
705                         se_tail->next = se;
706                         se_tail = se;
707                 }
708
709                 /* We don't open more than one write-socket per node/service pair.. */
710                 if (listen == 0)
711                         break;
712         }
713
714         freeaddrinfo (ai_list);
715
716         return (se_head);
717 } /* sockent_t *network_create_socket */
718
719 static sockent_t *network_create_default_socket (int listen)
720 {
721         sockent_t *se_ptr  = NULL;
722         sockent_t *se_head = NULL;
723         sockent_t *se_tail = NULL;
724
725         se_ptr = network_create_socket (NET_DEFAULT_V6_ADDR,
726                         NET_DEFAULT_PORT, listen);
727
728         /* Don't send to the same machine in IPv6 and IPv4 if both are available. */
729         if ((listen == 0) && (se_ptr != NULL))
730                 return (se_ptr);
731
732         if (se_ptr != NULL)
733         {
734                 se_head = se_ptr;
735                 se_tail = se_ptr;
736                 while (se_tail->next != NULL)
737                         se_tail = se_tail->next;
738         }
739
740         se_ptr = network_create_socket (NET_DEFAULT_V4_ADDR, NET_DEFAULT_PORT, listen);
741
742         if (se_tail == NULL)
743                 return (se_ptr);
744
745         se_tail->next = se_ptr;
746         return (se_head);
747 } /* sockent_t *network_create_default_socket */
748
749 static int network_add_listen_socket (const char *node, const char *service)
750 {
751         sockent_t *se;
752         sockent_t *se_ptr;
753         int se_num = 0;
754
755         if (service == NULL)
756                 service = NET_DEFAULT_PORT;
757
758         if (node == NULL)
759                 se = network_create_default_socket (1 /* listen == true */);
760         else
761                 se = network_create_socket (node, service, 1 /* listen == true */);
762
763         if (se == NULL)
764                 return (-1);
765
766         for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
767                 se_num++;
768
769         listen_sockets = (struct pollfd *) realloc (listen_sockets,
770                         (listen_sockets_num + se_num)
771                         * sizeof (struct pollfd));
772
773         for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
774         {
775                 listen_sockets[listen_sockets_num].fd = se_ptr->fd;
776                 listen_sockets[listen_sockets_num].events = POLLIN | POLLPRI;
777                 listen_sockets[listen_sockets_num].revents = 0;
778                 listen_sockets_num++;
779         } /* for (se) */
780
781         free_sockent (se);
782         return (0);
783 } /* int network_add_listen_socket */
784
785 static int network_add_sending_socket (const char *node, const char *service)
786 {
787         sockent_t *se;
788         sockent_t *se_ptr;
789
790         if (service == NULL)
791                 service = NET_DEFAULT_PORT;
792
793         if (node == NULL)
794                 se = network_create_default_socket (0 /* listen == false */);
795         else
796                 se = network_create_socket (node, service, 0 /* listen == false */);
797
798         if (se == NULL)
799                 return (-1);
800
801         if (sending_sockets == NULL)
802         {
803                 sending_sockets = se;
804                 return (0);
805         }
806
807         for (se_ptr = sending_sockets; se_ptr->next != NULL; se_ptr = se_ptr->next)
808                 /* seek end */;
809
810         se_ptr->next = se;
811         return (0);
812 } /* int network_get_listen_socket */
813
814 int network_receive (void)
815 {
816         char buffer[BUFF_SIZE];
817         int  buffer_len;
818
819         int i;
820         int status;
821
822         if (listen_sockets_num == 0)
823                 network_add_listen_socket (NULL, NULL);
824
825         if (listen_sockets_num == 0)
826         {
827                 syslog (LOG_ERR, "network: Failed to open a listening socket.");
828                 return (-1);
829         }
830
831         while (listen_loop == 0)
832         {
833                 status = poll (listen_sockets, listen_sockets_num, -1);
834
835                 if (status <= 0)
836                 {
837                         if (errno == EINTR)
838                                 continue;
839                         syslog (LOG_ERR, "poll failed: %s",
840                                         strerror (errno));
841                         return (-1);
842                 }
843
844                 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
845                 {
846                         if ((listen_sockets[i].revents & (POLLIN | POLLPRI)) == 0)
847                                 continue;
848                         status--;
849
850                         buffer_len = recv (listen_sockets[i].fd,
851                                         buffer, sizeof (buffer),
852                                         0 /* no flags */);
853                         if (buffer_len < 0)
854                         {
855                                 syslog (LOG_ERR, "recv failed: %s", strerror (errno));
856                                 return (-1);
857                         }
858
859                         parse_packet (buffer, buffer_len);
860                 } /* for (listen_sockets) */
861         } /* while (listen_loop == 0) */
862
863         return (0);
864 }
865
866 static void *receive_thread (void *arg)
867 {
868         return ((void *) network_receive ());
869 } /* void *receive_thread */
870
871 #if 0
872 int network_send (char *type, char *inst, char *value)
873 {
874         char buf[BUFF_SIZE];
875         int buflen;
876
877         sockent_t *se;
878
879         int ret;
880         int status;
881
882         DBG ("type = %s, inst = %s, value = %s", type, inst, value);
883
884         assert (operating_mode == MODE_CLIENT);
885
886         buflen = snprintf (buf, BUFF_SIZE, "%s %s %s", type, inst, value);
887         if ((buflen >= BUFF_SIZE) || (buflen < 1))
888         {
889                 syslog (LOG_WARNING, "network_send: snprintf failed..");
890                 return (-1);
891         }
892         buf[buflen] = '\0';
893         buflen++;
894
895         if (socklist_head == NULL)
896                 network_create_default_socket (0 /* listen == false */);
897
898         ret = 0;
899         for (se = socklist_head; se != NULL; se = se->next)
900         {
901                 while (1)
902                 {
903                         status = sendto (se->fd, buf, buflen, 0,
904                                         (struct sockaddr *) se->addr, se->addrlen);
905
906                         if (status == -1)
907                         {
908                                 if (errno == EINTR)
909                                 {
910                                         DBG ("sendto was interrupted");
911                                         continue;
912                                 }
913                                 else
914                                 {
915                                         syslog (LOG_ERR, "sendto: %s", strerror (errno));
916                                         ret = -1;
917                                         break;
918                                 }
919                         }
920                         else if (ret >= 0)
921                                 ret++;
922                         break;
923                 }
924         }
925
926         if (ret == 0)
927                 syslog (LOG_WARNING, "Message wasn't sent to anybody..");
928
929         return (ret);
930 } /* int network_send */
931 #endif
932
933 static int network_write (const data_set_t *ds, const value_list_t *vl)
934 {
935         char  buf[BUFF_SIZE];
936         char *buf_ptr;
937         int   buf_len;
938
939         sockent_t *se;
940
941         DBG ("time = %u; host = %s; "
942                         "plugin = %s; plugin_instance = %s; "
943                         "type = %s; type_instance = %s;",
944                         (unsigned int) vl->time, vl->host,
945                         vl->plugin, vl->plugin_instance,
946                         ds->type, vl->type_instance);
947
948         buf_len = sizeof (buf);
949         buf_ptr = buf;
950         if (write_part_string (&buf_ptr, &buf_len, TYPE_HOST,
951                                 vl->host, strlen (vl->host)) != 0)
952                 return (-1);
953         if (write_part_number (&buf_ptr, &buf_len, TYPE_TIME,
954                                 (uint64_t) vl->time))
955                 return (-1);
956         if (write_part_string (&buf_ptr, &buf_len, TYPE_PLUGIN,
957                                 vl->plugin, strlen (vl->plugin)) != 0)
958                 return (-1);
959         if (strlen (vl->plugin_instance) > 0)
960                 if (write_part_string (&buf_ptr, &buf_len, TYPE_PLUGIN_INSTANCE,
961                                         vl->plugin_instance,
962                                         strlen (vl->plugin_instance)) != 0)
963                         return (-1);
964         if (write_part_string (&buf_ptr, &buf_len, TYPE_TYPE,
965                                 ds->type, strlen (ds->type)) != 0)
966                 return (-1);
967         if (strlen (vl->type_instance) > 0)
968                 if (write_part_string (&buf_ptr, &buf_len, TYPE_PLUGIN_INSTANCE,
969                                         vl->type_instance,
970                                         strlen (vl->type_instance)) != 0)
971                         return (-1);
972         
973         write_part_values (&buf_ptr, &buf_len, ds, vl);
974
975         buf_len = sizeof (buf) - buf_len;
976
977         for (se = sending_sockets; se != NULL; se = se->next)
978         {
979                 int status;
980
981                 while (42)
982                 {
983                         status = sendto (se->fd, buf, buf_len, 0 /* no flags */,
984                                         (struct sockaddr *) se->addr, se->addrlen);
985                         if (status < 0)
986                         {
987                                 if (errno == EINTR)
988                                         continue;
989                                 syslog (LOG_ERR, "network: sendto failed: %s",
990                                                 strerror (errno));
991                                 break;
992                         }
993
994                         break;
995                 } /* while (42) */
996         } /* for (sending_sockets) */
997
998         return 0;
999 }
1000
1001 static int network_config (const char *key, const char *val)
1002 {
1003         char *node;
1004         char *service;
1005
1006         char *fields[3];
1007         int   fields_num;
1008
1009         if ((strcasecmp ("Listen", key) == 0)
1010                         || (strcasecmp ("Server", key) == 0))
1011         {
1012                 char *val_cpy = strdup (val);
1013                 if (val_cpy == NULL)
1014                         return (1);
1015
1016                 service = NET_DEFAULT_PORT;
1017                 fields_num = strsplit (val_cpy, fields, 3);
1018                 if ((fields_num != 1)
1019                                 && (fields_num != 2))
1020                         return (1);
1021                 else if (fields_num == 2)
1022                         service = fields[1];
1023                 node = fields[0];
1024
1025                 if (strcasecmp ("Listen", key) == 0)
1026                         network_add_listen_socket (node, service);
1027                 else
1028                         network_add_sending_socket (node, service);
1029         }
1030         else if (strcasecmp ("TimeToLive", key) == 0)
1031         {
1032                 int tmp = atoi (val);
1033                 if ((tmp > 0) && (tmp < 256))
1034                         network_config_ttl = tmp;
1035                 else
1036                         return (1);
1037         }
1038         else
1039         {
1040                 return (-1);
1041         }
1042         return (0);
1043 }
1044
1045 static int network_shutdown (void)
1046 {
1047         DBG ("Shutting down.");
1048
1049         listen_loop++;
1050
1051         pthread_kill (listen_thread, SIGTERM);
1052         pthread_join (listen_thread, NULL /* no return value */);
1053
1054         listen_thread = 0;
1055
1056         return (0);
1057 }
1058
1059 static int network_init (void)
1060 {
1061         plugin_register_shutdown ("network", network_shutdown);
1062
1063         /* setup socket(s) and so on */
1064         if (sending_sockets != NULL)
1065                 plugin_register_write ("network", network_write);
1066
1067         if ((listen_sockets_num != 0) && (listen_thread == 0))
1068         {
1069                 int status;
1070
1071                 status = pthread_create (&listen_thread, NULL /* no attributes */,
1072                                 receive_thread, NULL /* no argument */);
1073
1074                 if (status != 0)
1075                         syslog (LOG_ERR, "network: pthread_create failed: %s",
1076                                         strerror (errno));
1077         }
1078         return (0);
1079 } /* int network_init */
1080
1081 void module_register (void)
1082 {
1083         plugin_register_config ("network", network_config,
1084                         config_keys, config_keys_num);
1085         plugin_register_init   ("network", network_init);
1086 }