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