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