Bumped version to 4.2.5; Updated ChangeLog.
[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 struct receive_list_entry_s
140 {
141   char data[BUFF_SIZE];
142   int  data_len;
143   struct receive_list_entry_s *next;
144 };
145 typedef struct receive_list_entry_s receive_list_entry_t;
146
147 /*
148  * Private variables
149  */
150 static const char *config_keys[] =
151 {
152         "CacheFlush",
153         "Listen",
154         "Server",
155         "TimeToLive",
156         "Forward"
157 };
158 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
159
160 static int network_config_ttl = 0;
161 static int network_config_forward = 0;
162
163 static sockent_t *sending_sockets = NULL;
164
165 static receive_list_entry_t *receive_list_head = NULL;
166 static receive_list_entry_t *receive_list_tail = NULL;
167 static pthread_mutex_t       receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
168 static pthread_cond_t        receive_list_cond = PTHREAD_COND_INITIALIZER;
169
170 static struct pollfd *listen_sockets = NULL;
171 static int listen_sockets_num = 0;
172
173 static int listen_loop = 0;
174 static pthread_t receive_thread_id = 0;
175 static pthread_t dispatch_thread_id = 0;
176
177 static char         send_buffer[BUFF_SIZE];
178 static char        *send_buffer_ptr;
179 static int          send_buffer_fill;
180 static value_list_t send_buffer_vl = VALUE_LIST_STATIC;
181 static char         send_buffer_type[DATA_MAX_NAME_LEN];
182 static pthread_mutex_t send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
183
184 static c_avl_tree_t      *cache_tree = NULL;
185 static pthread_mutex_t  cache_lock = PTHREAD_MUTEX_INITIALIZER;
186 static time_t           cache_flush_last;
187 static int              cache_flush_interval = 1800;
188
189 /*
190  * Private functions
191  */
192 static int cache_flush (void)
193 {
194         char **keys = NULL;
195         int    keys_num = 0;
196
197         char **tmp;
198         int    i;
199
200         char   *key;
201         time_t *value;
202         c_avl_iterator_t *iter;
203
204         time_t curtime = time (NULL);
205
206         iter = c_avl_get_iterator (cache_tree);
207         while (c_avl_iterator_next (iter, (void *) &key, (void *) &value) == 0)
208         {
209                 if ((curtime - *value) <= cache_flush_interval)
210                         continue;
211                 tmp = (char **) realloc (keys,
212                                 (keys_num + 1) * sizeof (char *));
213                 if (tmp == NULL)
214                 {
215                         sfree (keys);
216                         c_avl_iterator_destroy (iter);
217                         ERROR ("network plugin: cache_flush: realloc"
218                                         " failed.");
219                         return (-1);
220                 }
221                 keys = tmp;
222                 keys[keys_num] = key;
223                 keys_num++;
224         } /* while (c_avl_iterator_next) */
225         c_avl_iterator_destroy (iter);
226
227         for (i = 0; i < keys_num; i++)
228         {
229                 if (c_avl_remove (cache_tree, keys[i], (void *) &key,
230                                         (void *) &value) != 0)
231                 {
232                         WARNING ("network plugin: cache_flush: c_avl_remove"
233                                         " (%s) failed.", keys[i]);
234                         continue;
235                 }
236
237                 sfree (key);
238                 sfree (value);
239         }
240
241         sfree (keys);
242
243         DEBUG ("network plugin: cache_flush: Removed %i %s",
244                         keys_num, (keys_num == 1) ? "entry" : "entries");
245         cache_flush_last = curtime;
246         return (0);
247 } /* int cache_flush */
248
249 static int cache_check (const char *type, const value_list_t *vl)
250 {
251         char key[1024];
252         time_t *value = NULL;
253         int retval = -1;
254
255         if (cache_tree == NULL)
256                 return (-1);
257
258         if (format_name (key, sizeof (key), vl->host, vl->plugin,
259                                 vl->plugin_instance, type, vl->type_instance))
260                 return (-1);
261
262         pthread_mutex_lock (&cache_lock);
263
264         if (c_avl_get (cache_tree, key, (void *) &value) == 0)
265         {
266                 if (*value < vl->time)
267                 {
268                         *value = vl->time;
269                         retval = 0;
270                 }
271                 else
272                 {
273                         DEBUG ("network plugin: cache_check: *value = %i >= vl->time = %i",
274                                         (int) *value, (int) vl->time);
275                         retval = 1;
276                 }
277         }
278         else
279         {
280                 char *key_copy = strdup (key);
281                 value = malloc (sizeof (time_t));
282                 if ((key_copy != NULL) && (value != NULL))
283                 {
284                         *value = vl->time;
285                         c_avl_insert (cache_tree, key_copy, value);
286                         retval = 0;
287                 }
288                 else
289                 {
290                         sfree (key_copy);
291                         sfree (value);
292                 }
293         }
294
295         if ((time (NULL) - cache_flush_last) > cache_flush_interval)
296                 cache_flush ();
297
298         pthread_mutex_unlock (&cache_lock);
299
300         DEBUG ("network plugin: cache_check: key = %s; time = %i; retval = %i",
301                         key, (int) vl->time, retval);
302
303         return (retval);
304 } /* int cache_check */
305
306 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
307                 const data_set_t *ds, const value_list_t *vl)
308 {
309         char *packet_ptr;
310         int packet_len;
311         int num_values;
312
313         part_header_t pkg_ph;
314         uint16_t      pkg_num_values;
315         uint8_t      *pkg_values_types;
316         value_t      *pkg_values;
317
318         int offset;
319         int i;
320
321         num_values = vl->values_len;
322         packet_len = sizeof (part_header_t) + sizeof (uint16_t)
323                 + (num_values * sizeof (uint8_t))
324                 + (num_values * sizeof (value_t));
325
326         if (*ret_buffer_len < packet_len)
327                 return (-1);
328
329         pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
330         if (pkg_values_types == NULL)
331         {
332                 ERROR ("network plugin: write_part_values: malloc failed.");
333                 return (-1);
334         }
335
336         pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
337         if (pkg_values == NULL)
338         {
339                 free (pkg_values_types);
340                 ERROR ("network plugin: write_part_values: malloc failed.");
341                 return (-1);
342         }
343
344         pkg_ph.type = htons (TYPE_VALUES);
345         pkg_ph.length = htons (packet_len);
346
347         pkg_num_values = htons ((uint16_t) vl->values_len);
348
349         for (i = 0; i < num_values; i++)
350         {
351                 if (ds->ds[i].type == DS_TYPE_COUNTER)
352                 {
353                         pkg_values_types[i] = DS_TYPE_COUNTER;
354                         pkg_values[i].counter = htonll (vl->values[i].counter);
355                 }
356                 else
357                 {
358                         pkg_values_types[i] = DS_TYPE_GAUGE;
359                         pkg_values[i].gauge = htond (vl->values[i].gauge);
360                 }
361         }
362
363         /*
364          * Use `memcpy' to write everything to the buffer, because the pointer
365          * may be unaligned and some architectures, such as SPARC, can't handle
366          * that.
367          */
368         packet_ptr = *ret_buffer;
369         offset = 0;
370         memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
371         offset += sizeof (pkg_ph);
372         memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
373         offset += sizeof (pkg_num_values);
374         memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
375         offset += num_values * sizeof (uint8_t);
376         memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
377         offset += num_values * sizeof (value_t);
378
379         assert (offset == packet_len);
380
381         *ret_buffer = packet_ptr + packet_len;
382         *ret_buffer_len -= packet_len;
383
384         free (pkg_values_types);
385         free (pkg_values);
386
387         return (0);
388 } /* int write_part_values */
389
390 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
391                 int type, uint64_t value)
392 {
393         char *packet_ptr;
394         int packet_len;
395
396         part_header_t pkg_head;
397         uint64_t pkg_value;
398         
399         int offset;
400
401         packet_len = sizeof (pkg_head) + sizeof (pkg_value);
402
403         if (*ret_buffer_len < packet_len)
404                 return (-1);
405
406         pkg_head.type = htons (type);
407         pkg_head.length = htons (packet_len);
408         pkg_value = htonll (value);
409
410         packet_ptr = *ret_buffer;
411         offset = 0;
412         memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
413         offset += sizeof (pkg_head);
414         memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
415         offset += sizeof (pkg_value);
416
417         assert (offset == packet_len);
418
419         *ret_buffer = packet_ptr + packet_len;
420         *ret_buffer_len -= packet_len;
421
422         return (0);
423 } /* int write_part_number */
424
425 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
426                 int type, const char *str, int str_len)
427 {
428         char *buffer;
429         int buffer_len;
430
431         uint16_t pkg_type;
432         uint16_t pkg_length;
433
434         int offset;
435
436         buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
437         if (*ret_buffer_len < buffer_len)
438                 return (-1);
439
440         pkg_type = htons (type);
441         pkg_length = htons (buffer_len);
442
443         buffer = *ret_buffer;
444         offset = 0;
445         memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
446         offset += sizeof (pkg_type);
447         memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
448         offset += sizeof (pkg_length);
449         memcpy (buffer + offset, str, str_len);
450         offset += str_len;
451         memset (buffer + offset, '\0', 1);
452         offset += 1;
453
454         assert (offset == buffer_len);
455
456         *ret_buffer = buffer + buffer_len;
457         *ret_buffer_len -= buffer_len;
458
459         return (0);
460 } /* int write_part_string */
461
462 static int parse_part_values (void **ret_buffer, int *ret_buffer_len,
463                 value_t **ret_values, int *ret_num_values)
464 {
465         char *buffer = *ret_buffer;
466         int   buffer_len = *ret_buffer_len;
467
468         uint16_t tmp16;
469         size_t exp_size;
470         int   i;
471
472         uint16_t pkg_length;
473         uint16_t pkg_type;
474         uint16_t pkg_numval;
475
476         uint8_t *pkg_types;
477         value_t *pkg_values;
478
479         if (buffer_len < (15))
480         {
481                 DEBUG ("network plugin: packet is too short: buffer_len = %i",
482                                 buffer_len);
483                 return (-1);
484         }
485
486         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
487         buffer += sizeof (tmp16);
488         pkg_type = ntohs (tmp16);
489
490         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
491         buffer += sizeof (tmp16);
492         pkg_length = ntohs (tmp16);
493
494         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
495         buffer += sizeof (tmp16);
496         pkg_numval = ntohs (tmp16);
497
498         assert (pkg_type == TYPE_VALUES);
499
500         exp_size = 3 * sizeof (uint16_t)
501                 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
502         if (buffer_len < exp_size)
503         {
504                 WARNING ("network plugin: parse_part_values: "
505                                 "Packet too short: "
506                                 "Chunk of size %u expected, "
507                                 "but buffer has only %i bytes left.",
508                                 (unsigned int) exp_size, buffer_len);
509                 return (-1);
510         }
511
512         if (pkg_length != exp_size)
513         {
514                 WARNING ("network plugin: parse_part_values: "
515                                 "Length and number of values "
516                                 "in the packet don't match.");
517                 return (-1);
518         }
519
520         pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
521         pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
522         if ((pkg_types == NULL) || (pkg_values == NULL))
523         {
524                 sfree (pkg_types);
525                 sfree (pkg_values);
526                 ERROR ("network plugin: parse_part_values: malloc failed.");
527                 return (-1);
528         }
529
530         memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
531         buffer += pkg_numval * sizeof (uint8_t);
532         memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
533         buffer += pkg_numval * sizeof (value_t);
534
535         for (i = 0; i < pkg_numval; i++)
536         {
537                 if (pkg_types[i] == DS_TYPE_COUNTER)
538                         pkg_values[i].counter = ntohll (pkg_values[i].counter);
539                 else if (pkg_types[i] == DS_TYPE_GAUGE)
540                         pkg_values[i].gauge = ntohd (pkg_values[i].gauge);
541         }
542
543         *ret_buffer     = buffer;
544         *ret_buffer_len = buffer_len - pkg_length;
545         *ret_num_values = pkg_numval;
546         *ret_values     = pkg_values;
547
548         sfree (pkg_types);
549
550         return (0);
551 } /* int parse_part_values */
552
553 static int parse_part_number (void **ret_buffer, int *ret_buffer_len,
554                 uint64_t *value)
555 {
556         char *buffer = *ret_buffer;
557         int buffer_len = *ret_buffer_len;
558
559         uint16_t tmp16;
560         uint64_t tmp64;
561         size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
562
563         uint16_t pkg_length;
564         uint16_t pkg_type;
565
566         if (buffer_len < exp_size)
567         {
568                 WARNING ("network plugin: parse_part_number: "
569                                 "Packet too short: "
570                                 "Chunk of size %u expected, "
571                                 "but buffer has only %i bytes left.",
572                                 (unsigned int) exp_size, buffer_len);
573                 return (-1);
574         }
575
576         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
577         buffer += sizeof (tmp16);
578         pkg_type = ntohs (tmp16);
579
580         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
581         buffer += sizeof (tmp16);
582         pkg_length = ntohs (tmp16);
583
584         memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
585         buffer += sizeof (tmp64);
586         *value = ntohll (tmp64);
587
588         *ret_buffer = buffer;
589         *ret_buffer_len = buffer_len - pkg_length;
590
591         return (0);
592 } /* int parse_part_number */
593
594 static int parse_part_string (void **ret_buffer, int *ret_buffer_len,
595                 char *output, int output_len)
596 {
597         char *buffer = *ret_buffer;
598         int   buffer_len = *ret_buffer_len;
599
600         uint16_t tmp16;
601         size_t header_size = 2 * sizeof (uint16_t);
602
603         uint16_t pkg_length;
604         uint16_t pkg_type;
605
606         if (buffer_len < header_size)
607         {
608                 WARNING ("network plugin: parse_part_string: "
609                                 "Packet too short: "
610                                 "Chunk of at least size %u expected, "
611                                 "but buffer has only %i bytes left.",
612                                 (unsigned int) header_size, buffer_len);
613                 return (-1);
614         }
615
616         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
617         buffer += sizeof (tmp16);
618         pkg_type = ntohs (tmp16);
619
620         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
621         buffer += sizeof (tmp16);
622         pkg_length = ntohs (tmp16);
623
624         /* Check that packet fits in the input buffer */
625         if (pkg_length > buffer_len)
626         {
627                 WARNING ("network plugin: parse_part_string: "
628                                 "Packet too big: "
629                                 "Chunk of size %hu received, "
630                                 "but buffer has only %i bytes left.",
631                                 pkg_length, buffer_len);
632                 return (-1);
633         }
634
635         /* Check that pkg_length is in the valid range */
636         if (pkg_length <= header_size)
637         {
638                 WARNING ("network plugin: parse_part_string: "
639                                 "Packet too short: "
640                                 "Header claims this packet is only %hu "
641                                 "bytes long.", pkg_length);
642                 return (-1);
643         }
644
645         /* Check that the package data fits into the output buffer.
646          * The previous if-statement ensures that:
647          * `pkg_length > header_size' */
648         if ((pkg_length - header_size) > output_len)
649         {
650                 WARNING ("network plugin: parse_part_string: "
651                                 "Output buffer too small.");
652                 return (-1);
653         }
654
655         /* All sanity checks successfull, let's copy the data over */
656         output_len = pkg_length - header_size;
657         memcpy ((void *) output, (void *) buffer, output_len);
658         buffer += output_len;
659
660         /* For some very weird reason '\0' doesn't do the trick on SPARC in
661          * this statement. */
662         if (output[output_len - 1] != 0)
663         {
664                 WARNING ("network plugin: parse_part_string: "
665                                 "Received string does not end "
666                                 "with a NULL-byte.");
667                 return (-1);
668         }
669
670         *ret_buffer = buffer;
671         *ret_buffer_len = buffer_len - pkg_length;
672
673         return (0);
674 } /* int parse_part_string */
675
676 static int parse_packet (void *buffer, int buffer_len)
677 {
678         int status;
679
680         value_list_t vl = VALUE_LIST_INIT;
681         char type[DATA_MAX_NAME_LEN];
682
683         DEBUG ("network plugin: parse_packet: buffer = %p; buffer_len = %i;",
684                         buffer, buffer_len);
685
686         memset (&vl, '\0', sizeof (vl));
687         memset (&type, '\0', sizeof (type));
688         status = 0;
689
690         while ((status == 0) && (buffer_len > sizeof (part_header_t)))
691         {
692                 uint16_t pkg_length;
693                 uint16_t pkg_type;
694
695                 memcpy ((void *) &pkg_type,
696                                 (void *) buffer,
697                                 sizeof (pkg_type));
698                 memcpy ((void *) &pkg_length,
699                                 (void *) (buffer + sizeof (pkg_type)),
700                                 sizeof (pkg_length));
701
702                 pkg_length = ntohs (pkg_length);
703                 pkg_type = ntohs (pkg_type);
704
705                 if (pkg_length > buffer_len)
706                         break;
707                 /* Ensure that this loop terminates eventually */
708                 if (pkg_length < (2 * sizeof (uint16_t)))
709                         break;
710
711                 if (pkg_type == TYPE_VALUES)
712                 {
713                         status = parse_part_values (&buffer, &buffer_len,
714                                         &vl.values, &vl.values_len);
715
716                         if (status != 0)
717                                 break;
718
719                         if ((vl.time > 0)
720                                         && (strlen (vl.host) > 0)
721                                         && (strlen (vl.plugin) > 0)
722                                         && (strlen (type) > 0)
723                                         && (cache_check (type, &vl) == 0))
724                         {
725                                 plugin_dispatch_values (type, &vl);
726                         }
727                         else
728                         {
729                                 DEBUG ("network plugin: parse_packet:"
730                                                 " NOT dispatching values");
731                         }
732
733                         sfree (vl.values);
734                 }
735                 else if (pkg_type == TYPE_TIME)
736                 {
737                         uint64_t tmp = 0;
738                         status = parse_part_number (&buffer, &buffer_len, &tmp);
739                         if (status == 0)
740                                 vl.time = (time_t) tmp;
741                 }
742                 else if (pkg_type == TYPE_INTERVAL)
743                 {
744                         uint64_t tmp = 0;
745                         status = parse_part_number (&buffer, &buffer_len, &tmp);
746                         if (status == 0)
747                                 vl.interval = (int) tmp;
748                 }
749                 else if (pkg_type == TYPE_HOST)
750                 {
751                         status = parse_part_string (&buffer, &buffer_len,
752                                         vl.host, sizeof (vl.host));
753                 }
754                 else if (pkg_type == TYPE_PLUGIN)
755                 {
756                         status = parse_part_string (&buffer, &buffer_len,
757                                         vl.plugin, sizeof (vl.plugin));
758                 }
759                 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
760                 {
761                         status = parse_part_string (&buffer, &buffer_len,
762                                         vl.plugin_instance, sizeof (vl.plugin_instance));
763                 }
764                 else if (pkg_type == TYPE_TYPE)
765                 {
766                         status = parse_part_string (&buffer, &buffer_len,
767                                         type, sizeof (type));
768                 }
769                 else if (pkg_type == TYPE_TYPE_INSTANCE)
770                 {
771                         status = parse_part_string (&buffer, &buffer_len,
772                                         vl.type_instance, sizeof (vl.type_instance));
773                 }
774                 else
775                 {
776                         DEBUG ("network plugin: parse_packet: Unknown part"
777                                         " type: 0x%04hx", pkg_type);
778                         buffer = ((char *) buffer) + pkg_length;
779                 }
780         } /* while (buffer_len > sizeof (part_header_t)) */
781
782         return (status);
783 } /* int parse_packet */
784
785 static void free_sockent (sockent_t *se)
786 {
787         sockent_t *next;
788         while (se != NULL)
789         {
790                 next = se->next;
791                 free (se->addr);
792                 free (se);
793                 se = next;
794         }
795 } /* void free_sockent */
796
797 /*
798  * int network_set_ttl
799  *
800  * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
801  * `IPV6_UNICAST_HOPS', depending on which option is applicable.
802  *
803  * The `struct addrinfo' is used to destinguish between unicast and multicast
804  * sockets.
805  */
806 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
807 {
808         if ((network_config_ttl < 1) || (network_config_ttl > 255))
809                 return (-1);
810
811         DEBUG ("ttl = %i", network_config_ttl);
812
813         if (ai->ai_family == AF_INET)
814         {
815                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
816                 int optname;
817
818                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
819                         optname = IP_MULTICAST_TTL;
820                 else
821                         optname = IP_TTL;
822
823                 if (setsockopt (se->fd, IPPROTO_IP, optname,
824                                         &network_config_ttl,
825                                         sizeof (network_config_ttl)) == -1)
826                 {
827                         char errbuf[1024];
828                         ERROR ("setsockopt: %s",
829                                         sstrerror (errno, errbuf, sizeof (errbuf)));
830                         return (-1);
831                 }
832         }
833         else if (ai->ai_family == AF_INET6)
834         {
835                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
836                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
837                 int optname;
838
839                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
840                         optname = IPV6_MULTICAST_HOPS;
841                 else
842                         optname = IPV6_UNICAST_HOPS;
843
844                 if (setsockopt (se->fd, IPPROTO_IPV6, optname,
845                                         &network_config_ttl,
846                                         sizeof (network_config_ttl)) == -1)
847                 {
848                         char errbuf[1024];
849                         ERROR ("setsockopt: %s",
850                                         sstrerror (errno, errbuf,
851                                                 sizeof (errbuf)));
852                         return (-1);
853                 }
854         }
855
856         return (0);
857 } /* int network_set_ttl */
858
859 static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
860 {
861         int loop = 0;
862
863         DEBUG ("fd = %i; calling `bind'", se->fd);
864
865         if (bind (se->fd, ai->ai_addr, ai->ai_addrlen) == -1)
866         {
867                 char errbuf[1024];
868                 ERROR ("bind: %s",
869                                 sstrerror (errno, errbuf, sizeof (errbuf)));
870                 return (-1);
871         }
872
873         if (ai->ai_family == AF_INET)
874         {
875                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
876                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
877                 {
878                         struct ip_mreq mreq;
879
880                         DEBUG ("fd = %i; IPv4 multicast address found", se->fd);
881
882                         mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
883                         mreq.imr_interface.s_addr = htonl (INADDR_ANY);
884
885                         if (setsockopt (se->fd, IPPROTO_IP, IP_MULTICAST_LOOP,
886                                                 &loop, sizeof (loop)) == -1)
887                         {
888                                 char errbuf[1024];
889                                 ERROR ("setsockopt: %s",
890                                                 sstrerror (errno, errbuf,
891                                                         sizeof (errbuf)));
892                                 return (-1);
893                         }
894
895                         if (setsockopt (se->fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
896                                                 &mreq, sizeof (mreq)) == -1)
897                         {
898                                 char errbuf[1024];
899                                 ERROR ("setsockopt: %s",
900                                                 sstrerror (errno, errbuf,
901                                                         sizeof (errbuf)));
902                                 return (-1);
903                         }
904                 }
905         }
906         else if (ai->ai_family == AF_INET6)
907         {
908                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
909                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
910                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
911                 {
912                         struct ipv6_mreq mreq;
913
914                         DEBUG ("fd = %i; IPv6 multicast address found", se->fd);
915
916                         memcpy (&mreq.ipv6mr_multiaddr,
917                                         &addr->sin6_addr,
918                                         sizeof (addr->sin6_addr));
919
920                         /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
921                          * ipv6mr_interface may be set to zeroes to
922                          * choose the default multicast interface or to
923                          * the index of a particular multicast-capable
924                          * interface if the host is multihomed.
925                          * Membership is associ-associated with a
926                          * single interface; programs running on
927                          * multihomed hosts may need to join the same
928                          * group on more than one interface.*/
929                         mreq.ipv6mr_interface = 0;
930
931                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
932                                                 &loop, sizeof (loop)) == -1)
933                         {
934                                 char errbuf[1024];
935                                 ERROR ("setsockopt: %s",
936                                                 sstrerror (errno, errbuf,
937                                                         sizeof (errbuf)));
938                                 return (-1);
939                         }
940
941                         if (setsockopt (se->fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
942                                                 &mreq, sizeof (mreq)) == -1)
943                         {
944                                 char errbuf[1024];
945                                 ERROR ("setsockopt: %s",
946                                                 sstrerror (errno, errbuf,
947                                                         sizeof (errbuf)));
948                                 return (-1);
949                         }
950                 }
951         }
952
953         return (0);
954 } /* int network_bind_socket */
955
956 static sockent_t *network_create_socket (const char *node,
957                 const char *service,
958                 int listen)
959 {
960         struct addrinfo  ai_hints;
961         struct addrinfo *ai_list, *ai_ptr;
962         int              ai_return;
963
964         sockent_t *se_head = NULL;
965         sockent_t *se_tail = NULL;
966
967         DEBUG ("node = %s, service = %s", node, service);
968
969         memset (&ai_hints, '\0', sizeof (ai_hints));
970         ai_hints.ai_flags    = 0;
971 #ifdef AI_PASSIVE
972         ai_hints.ai_flags |= AI_PASSIVE;
973 #endif
974 #ifdef AI_ADDRCONFIG
975         ai_hints.ai_flags |= AI_ADDRCONFIG;
976 #endif
977         ai_hints.ai_family   = AF_UNSPEC;
978         ai_hints.ai_socktype = SOCK_DGRAM;
979         ai_hints.ai_protocol = IPPROTO_UDP;
980
981         ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
982         if (ai_return != 0)
983         {
984                 char errbuf[1024];
985                 ERROR ("getaddrinfo (%s, %s): %s",
986                                 (node == NULL) ? "(null)" : node,
987                                 (service == NULL) ? "(null)" : service,
988                                 (ai_return == EAI_SYSTEM)
989                                 ? sstrerror (errno, errbuf, sizeof (errbuf))
990                                 : gai_strerror (ai_return));
991                 return (NULL);
992         }
993
994         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
995         {
996                 sockent_t *se;
997
998                 if ((se = (sockent_t *) malloc (sizeof (sockent_t))) == NULL)
999                 {
1000                         char errbuf[1024];
1001                         ERROR ("malloc: %s",
1002                                         sstrerror (errno, errbuf,
1003                                                 sizeof (errbuf)));
1004                         continue;
1005                 }
1006
1007                 if ((se->addr = (struct sockaddr_storage *) malloc (sizeof (struct sockaddr_storage))) == NULL)
1008                 {
1009                         char errbuf[1024];
1010                         ERROR ("malloc: %s",
1011                                         sstrerror (errno, errbuf,
1012                                                 sizeof (errbuf)));
1013                         free (se);
1014                         continue;
1015                 }
1016
1017                 assert (sizeof (struct sockaddr_storage) >= ai_ptr->ai_addrlen);
1018                 memset (se->addr, '\0', sizeof (struct sockaddr_storage));
1019                 memcpy (se->addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1020                 se->addrlen = ai_ptr->ai_addrlen;
1021
1022                 se->fd   = socket (ai_ptr->ai_family,
1023                                 ai_ptr->ai_socktype,
1024                                 ai_ptr->ai_protocol);
1025                 se->next = NULL;
1026
1027                 if (se->fd == -1)
1028                 {
1029                         char errbuf[1024];
1030                         ERROR ("socket: %s",
1031                                         sstrerror (errno, errbuf,
1032                                                 sizeof (errbuf)));
1033                         free (se->addr);
1034                         free (se);
1035                         continue;
1036                 }
1037
1038                 if (listen != 0)
1039                 {
1040                         if (network_bind_socket (se, ai_ptr) != 0)
1041                         {
1042                                 close (se->fd);
1043                                 free (se->addr);
1044                                 free (se);
1045                                 continue;
1046                         }
1047                 }
1048                 else /* listen == 0 */
1049                 {
1050                         network_set_ttl (se, ai_ptr);
1051                 }
1052
1053                 if (se_tail == NULL)
1054                 {
1055                         se_head = se;
1056                         se_tail = se;
1057                 }
1058                 else
1059                 {
1060                         se_tail->next = se;
1061                         se_tail = se;
1062                 }
1063
1064                 /* We don't open more than one write-socket per node/service pair.. */
1065                 if (listen == 0)
1066                         break;
1067         }
1068
1069         freeaddrinfo (ai_list);
1070
1071         return (se_head);
1072 } /* sockent_t *network_create_socket */
1073
1074 static sockent_t *network_create_default_socket (int listen)
1075 {
1076         sockent_t *se_ptr  = NULL;
1077         sockent_t *se_head = NULL;
1078         sockent_t *se_tail = NULL;
1079
1080         se_ptr = network_create_socket (NET_DEFAULT_V6_ADDR,
1081                         NET_DEFAULT_PORT, listen);
1082
1083         /* Don't send to the same machine in IPv6 and IPv4 if both are available. */
1084         if ((listen == 0) && (se_ptr != NULL))
1085                 return (se_ptr);
1086
1087         if (se_ptr != NULL)
1088         {
1089                 se_head = se_ptr;
1090                 se_tail = se_ptr;
1091                 while (se_tail->next != NULL)
1092                         se_tail = se_tail->next;
1093         }
1094
1095         se_ptr = network_create_socket (NET_DEFAULT_V4_ADDR, NET_DEFAULT_PORT, listen);
1096
1097         if (se_tail == NULL)
1098                 return (se_ptr);
1099
1100         se_tail->next = se_ptr;
1101         return (se_head);
1102 } /* sockent_t *network_create_default_socket */
1103
1104 static int network_add_listen_socket (const char *node, const char *service)
1105 {
1106         sockent_t *se;
1107         sockent_t *se_ptr;
1108         int se_num = 0;
1109
1110         if (service == NULL)
1111                 service = NET_DEFAULT_PORT;
1112
1113         if (node == NULL)
1114                 se = network_create_default_socket (1 /* listen == true */);
1115         else
1116                 se = network_create_socket (node, service, 1 /* listen == true */);
1117
1118         if (se == NULL)
1119                 return (-1);
1120
1121         for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
1122                 se_num++;
1123
1124         listen_sockets = (struct pollfd *) realloc (listen_sockets,
1125                         (listen_sockets_num + se_num)
1126                         * sizeof (struct pollfd));
1127
1128         for (se_ptr = se; se_ptr != NULL; se_ptr = se_ptr->next)
1129         {
1130                 listen_sockets[listen_sockets_num].fd = se_ptr->fd;
1131                 listen_sockets[listen_sockets_num].events = POLLIN | POLLPRI;
1132                 listen_sockets[listen_sockets_num].revents = 0;
1133                 listen_sockets_num++;
1134         } /* for (se) */
1135
1136         free_sockent (se);
1137         return (0);
1138 } /* int network_add_listen_socket */
1139
1140 static int network_add_sending_socket (const char *node, const char *service)
1141 {
1142         sockent_t *se;
1143         sockent_t *se_ptr;
1144
1145         if (service == NULL)
1146                 service = NET_DEFAULT_PORT;
1147
1148         if (node == NULL)
1149                 se = network_create_default_socket (0 /* listen == false */);
1150         else
1151                 se = network_create_socket (node, service, 0 /* listen == false */);
1152
1153         if (se == NULL)
1154                 return (-1);
1155
1156         if (sending_sockets == NULL)
1157         {
1158                 sending_sockets = se;
1159                 return (0);
1160         }
1161
1162         for (se_ptr = sending_sockets; se_ptr->next != NULL; se_ptr = se_ptr->next)
1163                 /* seek end */;
1164
1165         se_ptr->next = se;
1166         return (0);
1167 } /* int network_get_listen_socket */
1168
1169 static void *dispatch_thread (void *arg)
1170 {
1171   while (42)
1172   {
1173     receive_list_entry_t *ent;
1174
1175     /* Lock and wait for more data to come in */
1176     pthread_mutex_lock (&receive_list_lock);
1177     while ((listen_loop == 0)
1178         && (receive_list_head == NULL))
1179       pthread_cond_wait (&receive_list_cond, &receive_list_lock);
1180
1181     /* Remove the head entry and unlock */
1182     ent = receive_list_head;
1183     if (ent != NULL)
1184       receive_list_head = ent->next;
1185     pthread_mutex_unlock (&receive_list_lock);
1186
1187     /* Check whether we are supposed to exit. We do NOT check `listen_loop'
1188      * because we dispatch all missing packets before shutting down. */
1189     if (ent == NULL)
1190       break;
1191
1192     parse_packet (ent->data, ent->data_len);
1193
1194     sfree (ent);
1195   } /* while (42) */
1196
1197   return (NULL);
1198 } /* void *receive_thread */
1199
1200 static int network_receive (void)
1201 {
1202         char buffer[BUFF_SIZE];
1203         int  buffer_len;
1204
1205         int i;
1206         int status;
1207
1208         if (listen_sockets_num == 0)
1209                 network_add_listen_socket (NULL, NULL);
1210
1211         if (listen_sockets_num == 0)
1212         {
1213                 ERROR ("network: Failed to open a listening socket.");
1214                 return (-1);
1215         }
1216
1217         while (listen_loop == 0)
1218         {
1219                 status = poll (listen_sockets, listen_sockets_num, -1);
1220
1221                 if (status <= 0)
1222                 {
1223                         char errbuf[1024];
1224                         if (errno == EINTR)
1225                                 continue;
1226                         ERROR ("poll failed: %s",
1227                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1228                         return (-1);
1229                 }
1230
1231                 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
1232                 {
1233                         receive_list_entry_t *ent;
1234
1235                         if ((listen_sockets[i].revents & (POLLIN | POLLPRI)) == 0)
1236                                 continue;
1237                         status--;
1238
1239                         buffer_len = recv (listen_sockets[i].fd,
1240                                         buffer, sizeof (buffer),
1241                                         0 /* no flags */);
1242                         if (buffer_len < 0)
1243                         {
1244                                 char errbuf[1024];
1245                                 ERROR ("recv failed: %s",
1246                                                 sstrerror (errno, errbuf,
1247                                                         sizeof (errbuf)));
1248                                 return (-1);
1249                         }
1250
1251                         ent = malloc (sizeof (receive_list_entry_t));
1252                         if (ent == NULL)
1253                         {
1254                                 ERROR ("network plugin: malloc failed.");
1255                                 return (-1);
1256                         }
1257                         memset (ent, '\0', sizeof (receive_list_entry_t));
1258
1259                         /* Hopefully this be optimized out by the compiler. It
1260                          * might help prevent stupid bugs in the future though.
1261                          */
1262                         assert (sizeof (ent->data) == sizeof (buffer));
1263
1264                         memcpy (ent->data, buffer, buffer_len);
1265                         ent->data_len = buffer_len;
1266
1267                         pthread_mutex_lock (&receive_list_lock);
1268                         if (receive_list_head == NULL)
1269                         {
1270                                 receive_list_head = ent;
1271                                 receive_list_tail = ent;
1272                         }
1273                         else
1274                         {
1275                                 receive_list_tail->next = ent;
1276                                 receive_list_tail = ent;
1277                         }
1278                         pthread_cond_signal (&receive_list_cond);
1279                         pthread_mutex_unlock (&receive_list_lock);
1280                 } /* for (listen_sockets) */
1281         } /* while (listen_loop == 0) */
1282
1283         return (0);
1284 }
1285
1286 static void *receive_thread (void *arg)
1287 {
1288         return (network_receive () ? (void *) 1 : (void *) 0);
1289 } /* void *receive_thread */
1290
1291 static void network_send_buffer (const char *buffer, int buffer_len)
1292 {
1293         sockent_t *se;
1294         int status;
1295
1296         DEBUG ("network plugin: network_send_buffer: buffer_len = %i", buffer_len);
1297
1298         for (se = sending_sockets; se != NULL; se = se->next)
1299         {
1300                 while (42)
1301                 {
1302                         status = sendto (se->fd, buffer, buffer_len, 0 /* no flags */,
1303                                         (struct sockaddr *) se->addr, se->addrlen);
1304                         if (status < 0)
1305                         {
1306                                 char errbuf[1024];
1307                                 if (errno == EINTR)
1308                                         continue;
1309                                 ERROR ("network plugin: sendto failed: %s",
1310                                                 sstrerror (errno, errbuf,
1311                                                         sizeof (errbuf)));
1312                                 break;
1313                         }
1314
1315                         break;
1316                 } /* while (42) */
1317         } /* for (sending_sockets) */
1318 } /* void network_send_buffer */
1319
1320 static int add_to_buffer (char *buffer, int buffer_size,
1321                 value_list_t *vl_def, char *type_def,
1322                 const data_set_t *ds, const value_list_t *vl)
1323 {
1324         char *buffer_orig = buffer;
1325
1326         if (strcmp (vl_def->host, vl->host) != 0)
1327         {
1328                 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
1329                                         vl->host, strlen (vl->host)) != 0)
1330                         return (-1);
1331                 strcpy (vl_def->host, vl->host);
1332         }
1333
1334         if (vl_def->time != vl->time)
1335         {
1336                 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
1337                                         (uint64_t) vl->time))
1338                         return (-1);
1339                 vl_def->time = vl->time;
1340         }
1341
1342         if (vl_def->interval != vl->interval)
1343         {
1344                 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
1345                                         (uint64_t) vl->interval))
1346                         return (-1);
1347                 vl_def->interval = vl->interval;
1348         }
1349
1350         if (strcmp (vl_def->plugin, vl->plugin) != 0)
1351         {
1352                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
1353                                         vl->plugin, strlen (vl->plugin)) != 0)
1354                         return (-1);
1355                 strcpy (vl_def->plugin, vl->plugin);
1356         }
1357
1358         if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
1359         {
1360                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
1361                                         vl->plugin_instance,
1362                                         strlen (vl->plugin_instance)) != 0)
1363                         return (-1);
1364                 strcpy (vl_def->plugin_instance, vl->plugin_instance);
1365         }
1366
1367         if (strcmp (type_def, ds->type) != 0)
1368         {
1369                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
1370                                         ds->type, strlen (ds->type)) != 0)
1371                         return (-1);
1372                 strcpy (type_def, ds->type);
1373         }
1374
1375         if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
1376         {
1377                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
1378                                         vl->type_instance,
1379                                         strlen (vl->type_instance)) != 0)
1380                         return (-1);
1381                 strcpy (vl_def->type_instance, vl->type_instance);
1382         }
1383         
1384         if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
1385                 return (-1);
1386
1387         return (buffer - buffer_orig);
1388 } /* int add_to_buffer */
1389
1390 static void flush_buffer (void)
1391 {
1392         DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
1393                         send_buffer_fill);
1394
1395         network_send_buffer (send_buffer, send_buffer_fill);
1396         send_buffer_ptr  = send_buffer;
1397         send_buffer_fill = 0;
1398         memset (&send_buffer_vl, '\0', sizeof (send_buffer_vl));
1399         memset (send_buffer_type, '\0', sizeof (send_buffer_type));
1400 }
1401
1402 static int network_write (const data_set_t *ds, const value_list_t *vl)
1403 {
1404         int status;
1405
1406         /* If the value is already in the cache, we have received it via the
1407          * network. We write it again if forwarding is activated. It's then in
1408          * the cache and should we receive it again we will ignore it. */
1409         status = cache_check (ds->type, vl);
1410         if ((network_config_forward == 0)
1411                         && (status != 0))
1412                 return (0);
1413
1414         pthread_mutex_lock (&send_buffer_lock);
1415
1416         status = add_to_buffer (send_buffer_ptr,
1417                         sizeof (send_buffer) - send_buffer_fill,
1418                         &send_buffer_vl, send_buffer_type,
1419                         ds, vl);
1420         if (status >= 0)
1421         {
1422                 /* status == bytes added to the buffer */
1423                 send_buffer_fill += status;
1424                 send_buffer_ptr  += status;
1425         }
1426         else
1427         {
1428                 flush_buffer ();
1429
1430                 status = add_to_buffer (send_buffer_ptr,
1431                                 sizeof (send_buffer) - send_buffer_fill,
1432                                 &send_buffer_vl, send_buffer_type,
1433                                 ds, vl);
1434
1435                 if (status >= 0)
1436                 {
1437                         send_buffer_fill += status;
1438                         send_buffer_ptr  += status;
1439                 }
1440         }
1441
1442         if (status < 0)
1443         {
1444                 ERROR ("network plugin: Unable to append to the "
1445                                 "buffer for some weird reason");
1446         }
1447         else if ((sizeof (send_buffer) - send_buffer_fill) < 15)
1448         {
1449                 flush_buffer ();
1450         }
1451
1452         pthread_mutex_unlock (&send_buffer_lock);
1453
1454         return ((status < 0) ? -1 : 0);
1455 } /* int network_write */
1456
1457 static int network_config (const char *key, const char *val)
1458 {
1459         char *node;
1460         char *service;
1461
1462         char *fields[3];
1463         int   fields_num;
1464
1465         if ((strcasecmp ("Listen", key) == 0)
1466                         || (strcasecmp ("Server", key) == 0))
1467         {
1468                 char *val_cpy = strdup (val);
1469                 if (val_cpy == NULL)
1470                         return (1);
1471
1472                 service = NET_DEFAULT_PORT;
1473                 fields_num = strsplit (val_cpy, fields, 3);
1474                 if ((fields_num != 1)
1475                                 && (fields_num != 2))
1476                         return (1);
1477                 else if (fields_num == 2)
1478                 {
1479                         if ((service = strchr (fields[1], '.')) != NULL)
1480                                 *service = '\0';
1481                         service = fields[1];
1482                 }
1483                 node = fields[0];
1484
1485                 if (strcasecmp ("Listen", key) == 0)
1486                         network_add_listen_socket (node, service);
1487                 else
1488                         network_add_sending_socket (node, service);
1489         }
1490         else if (strcasecmp ("TimeToLive", key) == 0)
1491         {
1492                 int tmp = atoi (val);
1493                 if ((tmp > 0) && (tmp < 256))
1494                         network_config_ttl = tmp;
1495                 else
1496                         return (1);
1497         }
1498         else if (strcasecmp ("Forward", key) == 0)
1499         {
1500                 if ((strcasecmp ("true", val) == 0)
1501                                 || (strcasecmp ("yes", val) == 0)
1502                                 || (strcasecmp ("on", val) == 0))
1503                         network_config_forward = 1;
1504                 else
1505                         network_config_forward = 0;
1506         }
1507         else if (strcasecmp ("CacheFlush", key) == 0)
1508         {
1509                 int tmp = atoi (val);
1510                 if (tmp > 0)
1511                         cache_flush_interval = tmp;
1512                 else return (1);
1513         }
1514         else
1515         {
1516                 return (-1);
1517         }
1518         return (0);
1519 } /* int network_config */
1520
1521 static int network_shutdown (void)
1522 {
1523         listen_loop++;
1524
1525         /* Kill the listening thread */
1526         if (receive_thread_id != (pthread_t) 0)
1527         {
1528                 pthread_kill (receive_thread_id, SIGTERM);
1529                 pthread_join (receive_thread_id, NULL /* no return value */);
1530                 receive_thread_id = (pthread_t) 0;
1531         }
1532
1533         /* Shutdown the dispatching thread */
1534         if (dispatch_thread_id != (pthread_t) 0)
1535                 pthread_cond_broadcast (&receive_list_cond);
1536
1537         if (send_buffer_fill > 0)
1538                 flush_buffer ();
1539
1540         if (cache_tree != NULL)
1541         {
1542                 void *key;
1543                 void *value;
1544
1545                 while (c_avl_pick (cache_tree, &key, &value) == 0)
1546                 {
1547                         sfree (key);
1548                         sfree (value);
1549                 }
1550                 c_avl_destroy (cache_tree);
1551                 cache_tree = NULL;
1552         }
1553
1554         /* TODO: Close `sending_sockets' */
1555
1556         plugin_unregister_config ("network");
1557         plugin_unregister_init ("network");
1558         plugin_unregister_write ("network");
1559         plugin_unregister_shutdown ("network");
1560
1561         return (0);
1562 } /* int network_shutdown */
1563
1564 static int network_init (void)
1565 {
1566         plugin_register_shutdown ("network", network_shutdown);
1567
1568         send_buffer_ptr  = send_buffer;
1569         send_buffer_fill = 0;
1570         memset (&send_buffer_vl, '\0', sizeof (send_buffer_vl));
1571         memset (send_buffer_type, '\0', sizeof (send_buffer_type));
1572
1573         cache_tree = c_avl_create ((int (*) (const void *, const void *)) strcmp);
1574         cache_flush_last = time (NULL);
1575
1576         /* setup socket(s) and so on */
1577         if (sending_sockets != NULL)
1578                 plugin_register_write ("network", network_write);
1579
1580         if ((listen_sockets_num != 0) && (receive_thread_id == 0))
1581         {
1582                 int status;
1583
1584                 status = pthread_create (&dispatch_thread_id,
1585                                 NULL /* no attributes */,
1586                                 dispatch_thread,
1587                                 NULL /* no argument */);
1588                 if (status != 0)
1589                 {
1590                         char errbuf[1024];
1591                         ERROR ("network: pthread_create failed: %s",
1592                                         sstrerror (errno, errbuf,
1593                                                 sizeof (errbuf)));
1594                 }
1595
1596                 status = pthread_create (&receive_thread_id,
1597                                 NULL /* no attributes */,
1598                                 receive_thread,
1599                                 NULL /* no argument */);
1600                 if (status != 0)
1601                 {
1602                         char errbuf[1024];
1603                         ERROR ("network: pthread_create failed: %s",
1604                                         sstrerror (errno, errbuf,
1605                                                 sizeof (errbuf)));
1606                 }
1607         }
1608         return (0);
1609 } /* int network_init */
1610
1611 void module_register (void)
1612 {
1613         plugin_register_config ("network", network_config,
1614                         config_keys, config_keys_num);
1615         plugin_register_init   ("network", network_init);
1616 } /* void module_register */