Merge branch 'master' into ff/auth
[collectd.git] / src / network.c
1 /**
2  * collectd - src/network.c
3  * Copyright (C) 2005-2009  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_fbhash.h"
27 #include "utils_avltree.h"
28
29 #include "network.h"
30
31 #if HAVE_PTHREAD_H
32 # include <pthread.h>
33 #endif
34 #if HAVE_SYS_SOCKET_H
35 # include <sys/socket.h>
36 #endif
37 #if HAVE_NETDB_H
38 # include <netdb.h>
39 #endif
40 #if HAVE_NETINET_IN_H
41 # include <netinet/in.h>
42 #endif
43 #if HAVE_ARPA_INET_H
44 # include <arpa/inet.h>
45 #endif
46 #if HAVE_POLL_H
47 # include <poll.h>
48 #endif
49
50 #if HAVE_LIBGCRYPT
51 # include <gcrypt.h>
52 #endif
53
54 /* 1500 - 40 - 8  =  Ethernet packet - IPv6 header - UDP header */
55 /* #define BUFF_SIZE 1452 */
56
57 #ifndef IPV6_ADD_MEMBERSHIP
58 # ifdef IPV6_JOIN_GROUP
59 #  define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
60 # else
61 #  error "Neither IP_ADD_MEMBERSHIP nor IPV6_JOIN_GROUP is defined"
62 # endif
63 #endif /* !IP_ADD_MEMBERSHIP */
64
65 /* Buffer size to allocate. */
66 #define BUFF_SIZE 1024
67
68 /*
69  * Maximum size required for encryption / signing:
70  *
71  *    44 bytes for the encryption header
72  * +  64 bytes for the username
73  * -----------
74  * = 108 bytes
75  */
76 #define BUFF_SIG_SIZE 108
77
78 /*
79  * Private data types
80  */
81 #define SECURITY_LEVEL_NONE     0
82 #if HAVE_LIBGCRYPT
83 # define SECURITY_LEVEL_SIGN    1
84 # define SECURITY_LEVEL_ENCRYPT 2
85 #endif
86 struct sockent_client
87 {
88         int fd;
89         struct sockaddr_storage *addr;
90         socklen_t                addrlen;
91 #if HAVE_LIBGCRYPT
92         int security_level;
93         char *username;
94         char *password;
95         gcry_cipher_hd_t cypher;
96         unsigned char password_hash[32];
97 #endif
98 };
99
100 struct sockent_server
101 {
102         int *fd;
103         size_t fd_num;
104 #if HAVE_LIBGCRYPT
105         int security_level;
106         char *auth_file;
107         fbhash_t *userdb;
108         gcry_cipher_hd_t cypher;
109 #endif
110 };
111
112 typedef struct sockent
113 {
114 #define SOCKENT_TYPE_CLIENT 1
115 #define SOCKENT_TYPE_SERVER 2
116         int type;
117
118         char *node;
119         char *service;
120
121         union
122         {
123                 struct sockent_client client;
124                 struct sockent_server server;
125         } data;
126
127         struct sockent *next;
128 } sockent_t;
129
130 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
131  *  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
132  * +-------+-----------------------+-------------------------------+
133  * ! Ver.  !                       ! Length                        !
134  * +-------+-----------------------+-------------------------------+
135  */
136 struct part_header_s
137 {
138         uint16_t type;
139         uint16_t length;
140 };
141 typedef struct part_header_s part_header_t;
142
143 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
144  *  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
145  * +-------------------------------+-------------------------------+
146  * ! Type                          ! Length                        !
147  * +-------------------------------+-------------------------------+
148  * : (Length - 4) Bytes                                            :
149  * +---------------------------------------------------------------+
150  */
151 struct part_string_s
152 {
153         part_header_t *head;
154         char *value;
155 };
156 typedef struct part_string_s part_string_t;
157
158 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
159  *  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
160  * +-------------------------------+-------------------------------+
161  * ! Type                          ! Length                        !
162  * +-------------------------------+-------------------------------+
163  * : (Length - 4 == 2 || 4 || 8) Bytes                             :
164  * +---------------------------------------------------------------+
165  */
166 struct part_number_s
167 {
168         part_header_t *head;
169         uint64_t *value;
170 };
171 typedef struct part_number_s part_number_t;
172
173 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
174  *  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
175  * +-------------------------------+-------------------------------+
176  * ! Type                          ! Length                        !
177  * +-------------------------------+---------------+---------------+
178  * ! Num of values                 ! Type0         ! Type1         !
179  * +-------------------------------+---------------+---------------+
180  * ! Value0                                                        !
181  * !                                                               !
182  * +---------------------------------------------------------------+
183  * ! Value1                                                        !
184  * !                                                               !
185  * +---------------------------------------------------------------+
186  */
187 struct part_values_s
188 {
189         part_header_t *head;
190         uint16_t *num_values;
191         uint8_t  *values_types;
192         value_t  *values;
193 };
194 typedef struct part_values_s part_values_t;
195
196 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
197  *  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
198  * +-------------------------------+-------------------------------+
199  * ! Type                          ! Length                        !
200  * +-------------------------------+-------------------------------+
201  * ! Hash (Bits   0 -  31)                                         !
202  * : :                                                             :
203  * ! Hash (Bits 224 - 255)                                         !
204  * +---------------------------------------------------------------+
205  */
206 /* Minimum size */
207 #define PART_SIGNATURE_SHA256_SIZE 36
208 struct part_signature_sha256_s
209 {
210   part_header_t head;
211   unsigned char hash[32];
212   char *username;
213 };
214 typedef struct part_signature_sha256_s part_signature_sha256_t;
215
216 /*                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
217  *  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
218  * +-------------------------------+-------------------------------+
219  * ! Type                          ! Length                        !
220  * +-------------------------------+-------------------------------+
221  * ! Original length               ! Padding (0 - 15 bytes)        !
222  * +-------------------------------+-------------------------------+
223  * ! Hash (Bits   0 -  31)                                         !
224  * : :                                                             :
225  * ! Hash (Bits 128 - 159)                                         !
226  * +---------------------------------------------------------------+
227  */
228 /* Minimum size */
229 #define PART_ENCRYPTION_AES256_SIZE 44
230 struct part_encryption_aes256_s
231 {
232   part_header_t head;
233   uint16_t username_length;
234   char *username;
235   unsigned char iv[16];
236   /* <encrypted> */
237   unsigned char hash[20];
238   /*   <payload /> */
239   /* </encrypted> */
240 };
241 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
242
243 struct receive_list_entry_s
244 {
245   char data[BUFF_SIZE];
246   int  data_len;
247   int  fd;
248   struct receive_list_entry_s *next;
249 };
250 typedef struct receive_list_entry_s receive_list_entry_t;
251
252 /*
253  * Private variables
254  */
255 static int network_config_ttl = 0;
256 static int network_config_forward = 0;
257
258 static sockent_t *sending_sockets = NULL;
259
260 static receive_list_entry_t *receive_list_head = NULL;
261 static receive_list_entry_t *receive_list_tail = NULL;
262 static pthread_mutex_t       receive_list_lock = PTHREAD_MUTEX_INITIALIZER;
263 static pthread_cond_t        receive_list_cond = PTHREAD_COND_INITIALIZER;
264
265 static sockent_t     *listen_sockets = NULL;
266 static struct pollfd *listen_sockets_pollfd = NULL;
267 static size_t         listen_sockets_num = 0;
268
269 /* The receive and dispatch threads will run as long as `listen_loop' is set to
270  * zero. */
271 static int       listen_loop = 0;
272 static int       receive_thread_running = 0;
273 static pthread_t receive_thread_id;
274 static int       dispatch_thread_running = 0;
275 static pthread_t dispatch_thread_id;
276
277 /* Buffer in which to-be-sent network packets are constructed. */
278 static char             send_buffer[BUFF_SIZE];
279 static char            *send_buffer_ptr;
280 static int              send_buffer_fill;
281 static value_list_t     send_buffer_vl = VALUE_LIST_STATIC;
282 static pthread_mutex_t  send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
283
284 /* In this cache we store all the values we received, so we can send out only
285  * those values which were *not* received via the network plugin, too. This is
286  * used for the `Forward false' option. */
287 static c_avl_tree_t    *cache_tree = NULL;
288 static pthread_mutex_t  cache_lock = PTHREAD_MUTEX_INITIALIZER;
289 static time_t           cache_flush_last = 0;
290 static int              cache_flush_interval = 1800;
291
292 /*
293  * Private functions
294  */
295 static int cache_flush (void)
296 {
297         char **keys = NULL;
298         int    keys_num = 0;
299
300         char **tmp;
301         int    i;
302
303         char   *key;
304         time_t *value;
305         c_avl_iterator_t *iter;
306
307         time_t curtime = time (NULL);
308
309         iter = c_avl_get_iterator (cache_tree);
310         while (c_avl_iterator_next (iter, (void *) &key, (void *) &value) == 0)
311         {
312                 if ((curtime - *value) <= cache_flush_interval)
313                         continue;
314                 tmp = (char **) realloc (keys,
315                                 (keys_num + 1) * sizeof (char *));
316                 if (tmp == NULL)
317                 {
318                         sfree (keys);
319                         c_avl_iterator_destroy (iter);
320                         ERROR ("network plugin: cache_flush: realloc"
321                                         " failed.");
322                         return (-1);
323                 }
324                 keys = tmp;
325                 keys[keys_num] = key;
326                 keys_num++;
327         } /* while (c_avl_iterator_next) */
328         c_avl_iterator_destroy (iter);
329
330         for (i = 0; i < keys_num; i++)
331         {
332                 if (c_avl_remove (cache_tree, keys[i], (void *) &key,
333                                         (void *) &value) != 0)
334                 {
335                         WARNING ("network plugin: cache_flush: c_avl_remove"
336                                         " (%s) failed.", keys[i]);
337                         continue;
338                 }
339
340                 sfree (key);
341                 sfree (value);
342         }
343
344         sfree (keys);
345
346         DEBUG ("network plugin: cache_flush: Removed %i %s",
347                         keys_num, (keys_num == 1) ? "entry" : "entries");
348         cache_flush_last = curtime;
349         return (0);
350 } /* int cache_flush */
351
352 static int cache_check (const value_list_t *vl)
353 {
354         char key[1024];
355         time_t *value = NULL;
356         int retval = -1;
357
358         if (cache_tree == NULL)
359                 return (-1);
360
361         if (format_name (key, sizeof (key), vl->host, vl->plugin,
362                                 vl->plugin_instance, vl->type, vl->type_instance))
363                 return (-1);
364
365         pthread_mutex_lock (&cache_lock);
366
367         if (c_avl_get (cache_tree, key, (void *) &value) == 0)
368         {
369                 if (*value < vl->time)
370                 {
371                         *value = vl->time;
372                         retval = 0;
373                 }
374                 else
375                 {
376                         DEBUG ("network plugin: cache_check: *value = %i >= vl->time = %i",
377                                         (int) *value, (int) vl->time);
378                         retval = 1;
379                 }
380         }
381         else
382         {
383                 char *key_copy = strdup (key);
384                 value = malloc (sizeof (time_t));
385                 if ((key_copy != NULL) && (value != NULL))
386                 {
387                         *value = vl->time;
388                         c_avl_insert (cache_tree, key_copy, value);
389                         retval = 0;
390                 }
391                 else
392                 {
393                         sfree (key_copy);
394                         sfree (value);
395                 }
396         }
397
398         if ((time (NULL) - cache_flush_last) > cache_flush_interval)
399                 cache_flush ();
400
401         pthread_mutex_unlock (&cache_lock);
402
403         return (retval);
404 } /* int cache_check */
405
406 #if HAVE_LIBGCRYPT
407 static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
408     const void *iv, size_t iv_size, const char *username)
409 {
410   gcry_error_t err;
411   gcry_cipher_hd_t *cyper_ptr;
412   unsigned char password_hash[32];
413
414   if (se->type == SOCKENT_TYPE_CLIENT)
415   {
416           cyper_ptr = &se->data.client.cypher;
417           memcpy (password_hash, se->data.client.password_hash,
418                           sizeof (password_hash));
419   }
420   else
421   {
422           char *secret;
423
424           cyper_ptr = &se->data.server.cypher;
425
426           if (username == NULL)
427                   return (NULL);
428
429           secret = fbh_get (se->data.server.userdb, username);
430           if (secret == NULL)
431                   return (NULL);
432
433           gcry_md_hash_buffer (GCRY_MD_SHA256,
434                           password_hash,
435                           secret, strlen (secret));
436
437           sfree (secret);
438   }
439
440   if (*cyper_ptr == NULL)
441   {
442     err = gcry_cipher_open (cyper_ptr,
443         GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, /* flags = */ 0);
444     if (err != 0)
445     {
446       ERROR ("network plugin: gcry_cipher_open returned: %s",
447           gcry_strerror (err));
448       *cyper_ptr = NULL;
449       return (NULL);
450     }
451   }
452   else
453   {
454     gcry_cipher_reset (*cyper_ptr);
455   }
456   assert (*cyper_ptr != NULL);
457
458   err = gcry_cipher_setkey (*cyper_ptr,
459       password_hash, sizeof (password_hash));
460   if (err != 0)
461   {
462     ERROR ("network plugin: gcry_cipher_setkey returned: %s",
463         gcry_strerror (err));
464     gcry_cipher_close (*cyper_ptr);
465     *cyper_ptr = NULL;
466     return (NULL);
467   }
468
469   err = gcry_cipher_setiv (*cyper_ptr, iv, iv_size);
470   if (err != 0)
471   {
472     ERROR ("network plugin: gcry_cipher_setkey returned: %s",
473         gcry_strerror (err));
474     gcry_cipher_close (*cyper_ptr);
475     *cyper_ptr = NULL;
476     return (NULL);
477   }
478
479   return (*cyper_ptr);
480 } /* }}} int network_get_aes256_cypher */
481 #endif /* HAVE_LIBGCRYPT */
482
483 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
484                 const data_set_t *ds, const value_list_t *vl)
485 {
486         char *packet_ptr;
487         int packet_len;
488         int num_values;
489
490         part_header_t pkg_ph;
491         uint16_t      pkg_num_values;
492         uint8_t      *pkg_values_types;
493         value_t      *pkg_values;
494
495         int offset;
496         int i;
497
498         num_values = vl->values_len;
499         packet_len = sizeof (part_header_t) + sizeof (uint16_t)
500                 + (num_values * sizeof (uint8_t))
501                 + (num_values * sizeof (value_t));
502
503         if (*ret_buffer_len < packet_len)
504                 return (-1);
505
506         pkg_values_types = (uint8_t *) malloc (num_values * sizeof (uint8_t));
507         if (pkg_values_types == NULL)
508         {
509                 ERROR ("network plugin: write_part_values: malloc failed.");
510                 return (-1);
511         }
512
513         pkg_values = (value_t *) malloc (num_values * sizeof (value_t));
514         if (pkg_values == NULL)
515         {
516                 free (pkg_values_types);
517                 ERROR ("network plugin: write_part_values: malloc failed.");
518                 return (-1);
519         }
520
521         pkg_ph.type = htons (TYPE_VALUES);
522         pkg_ph.length = htons (packet_len);
523
524         pkg_num_values = htons ((uint16_t) vl->values_len);
525
526         for (i = 0; i < num_values; i++)
527         {
528                 if (ds->ds[i].type == DS_TYPE_COUNTER)
529                 {
530                         pkg_values_types[i] = DS_TYPE_COUNTER;
531                         pkg_values[i].counter = htonll (vl->values[i].counter);
532                 }
533                 else
534                 {
535                         pkg_values_types[i] = DS_TYPE_GAUGE;
536                         pkg_values[i].gauge = htond (vl->values[i].gauge);
537                 }
538         }
539
540         /*
541          * Use `memcpy' to write everything to the buffer, because the pointer
542          * may be unaligned and some architectures, such as SPARC, can't handle
543          * that.
544          */
545         packet_ptr = *ret_buffer;
546         offset = 0;
547         memcpy (packet_ptr + offset, &pkg_ph, sizeof (pkg_ph));
548         offset += sizeof (pkg_ph);
549         memcpy (packet_ptr + offset, &pkg_num_values, sizeof (pkg_num_values));
550         offset += sizeof (pkg_num_values);
551         memcpy (packet_ptr + offset, pkg_values_types, num_values * sizeof (uint8_t));
552         offset += num_values * sizeof (uint8_t);
553         memcpy (packet_ptr + offset, pkg_values, num_values * sizeof (value_t));
554         offset += num_values * sizeof (value_t);
555
556         assert (offset == packet_len);
557
558         *ret_buffer = packet_ptr + packet_len;
559         *ret_buffer_len -= packet_len;
560
561         free (pkg_values_types);
562         free (pkg_values);
563
564         return (0);
565 } /* int write_part_values */
566
567 static int write_part_number (char **ret_buffer, int *ret_buffer_len,
568                 int type, uint64_t value)
569 {
570         char *packet_ptr;
571         int packet_len;
572
573         part_header_t pkg_head;
574         uint64_t pkg_value;
575         
576         int offset;
577
578         packet_len = sizeof (pkg_head) + sizeof (pkg_value);
579
580         if (*ret_buffer_len < packet_len)
581                 return (-1);
582
583         pkg_head.type = htons (type);
584         pkg_head.length = htons (packet_len);
585         pkg_value = htonll (value);
586
587         packet_ptr = *ret_buffer;
588         offset = 0;
589         memcpy (packet_ptr + offset, &pkg_head, sizeof (pkg_head));
590         offset += sizeof (pkg_head);
591         memcpy (packet_ptr + offset, &pkg_value, sizeof (pkg_value));
592         offset += sizeof (pkg_value);
593
594         assert (offset == packet_len);
595
596         *ret_buffer = packet_ptr + packet_len;
597         *ret_buffer_len -= packet_len;
598
599         return (0);
600 } /* int write_part_number */
601
602 static int write_part_string (char **ret_buffer, int *ret_buffer_len,
603                 int type, const char *str, int str_len)
604 {
605         char *buffer;
606         int buffer_len;
607
608         uint16_t pkg_type;
609         uint16_t pkg_length;
610
611         int offset;
612
613         buffer_len = 2 * sizeof (uint16_t) + str_len + 1;
614         if (*ret_buffer_len < buffer_len)
615                 return (-1);
616
617         pkg_type = htons (type);
618         pkg_length = htons (buffer_len);
619
620         buffer = *ret_buffer;
621         offset = 0;
622         memcpy (buffer + offset, (void *) &pkg_type, sizeof (pkg_type));
623         offset += sizeof (pkg_type);
624         memcpy (buffer + offset, (void *) &pkg_length, sizeof (pkg_length));
625         offset += sizeof (pkg_length);
626         memcpy (buffer + offset, str, str_len);
627         offset += str_len;
628         memset (buffer + offset, '\0', 1);
629         offset += 1;
630
631         assert (offset == buffer_len);
632
633         *ret_buffer = buffer + buffer_len;
634         *ret_buffer_len -= buffer_len;
635
636         return (0);
637 } /* int write_part_string */
638
639 static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
640                 value_t **ret_values, int *ret_num_values)
641 {
642         char *buffer = *ret_buffer;
643         size_t buffer_len = *ret_buffer_len;
644
645         uint16_t tmp16;
646         size_t exp_size;
647         int   i;
648
649         uint16_t pkg_length;
650         uint16_t pkg_type;
651         uint16_t pkg_numval;
652
653         uint8_t *pkg_types;
654         value_t *pkg_values;
655
656         if (buffer_len < 15)
657         {
658                 NOTICE ("network plugin: packet is too short: "
659                                 "buffer_len = %zu", buffer_len);
660                 return (-1);
661         }
662
663         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
664         buffer += sizeof (tmp16);
665         pkg_type = ntohs (tmp16);
666
667         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
668         buffer += sizeof (tmp16);
669         pkg_length = ntohs (tmp16);
670
671         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
672         buffer += sizeof (tmp16);
673         pkg_numval = ntohs (tmp16);
674
675         assert (pkg_type == TYPE_VALUES);
676
677         exp_size = 3 * sizeof (uint16_t)
678                 + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
679         if ((buffer_len < 0) || (buffer_len < exp_size))
680         {
681                 WARNING ("network plugin: parse_part_values: "
682                                 "Packet too short: "
683                                 "Chunk of size %zu expected, "
684                                 "but buffer has only %zu bytes left.",
685                                 exp_size, buffer_len);
686                 return (-1);
687         }
688
689         if (pkg_length != exp_size)
690         {
691                 WARNING ("network plugin: parse_part_values: "
692                                 "Length and number of values "
693                                 "in the packet don't match.");
694                 return (-1);
695         }
696
697         pkg_types = (uint8_t *) malloc (pkg_numval * sizeof (uint8_t));
698         pkg_values = (value_t *) malloc (pkg_numval * sizeof (value_t));
699         if ((pkg_types == NULL) || (pkg_values == NULL))
700         {
701                 sfree (pkg_types);
702                 sfree (pkg_values);
703                 ERROR ("network plugin: parse_part_values: malloc failed.");
704                 return (-1);
705         }
706
707         memcpy ((void *) pkg_types, (void *) buffer, pkg_numval * sizeof (uint8_t));
708         buffer += pkg_numval * sizeof (uint8_t);
709         memcpy ((void *) pkg_values, (void *) buffer, pkg_numval * sizeof (value_t));
710         buffer += pkg_numval * sizeof (value_t);
711
712         for (i = 0; i < pkg_numval; i++)
713         {
714                 if (pkg_types[i] == DS_TYPE_COUNTER)
715                         pkg_values[i].counter = ntohll (pkg_values[i].counter);
716                 else if (pkg_types[i] == DS_TYPE_GAUGE)
717                         pkg_values[i].gauge = ntohd (pkg_values[i].gauge);
718         }
719
720         *ret_buffer     = buffer;
721         *ret_buffer_len = buffer_len - pkg_length;
722         *ret_num_values = pkg_numval;
723         *ret_values     = pkg_values;
724
725         sfree (pkg_types);
726
727         return (0);
728 } /* int parse_part_values */
729
730 static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
731                 uint64_t *value)
732 {
733         char *buffer = *ret_buffer;
734         size_t buffer_len = *ret_buffer_len;
735
736         uint16_t tmp16;
737         uint64_t tmp64;
738         size_t exp_size = 2 * sizeof (uint16_t) + sizeof (uint64_t);
739
740         uint16_t pkg_length;
741         uint16_t pkg_type;
742
743         if ((buffer_len < 0) || ((size_t) buffer_len < exp_size))
744         {
745                 WARNING ("network plugin: parse_part_number: "
746                                 "Packet too short: "
747                                 "Chunk of size %zu expected, "
748                                 "but buffer has only %zu bytes left.",
749                                 exp_size, buffer_len);
750                 return (-1);
751         }
752
753         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
754         buffer += sizeof (tmp16);
755         pkg_type = ntohs (tmp16);
756
757         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
758         buffer += sizeof (tmp16);
759         pkg_length = ntohs (tmp16);
760
761         memcpy ((void *) &tmp64, buffer, sizeof (tmp64));
762         buffer += sizeof (tmp64);
763         *value = ntohll (tmp64);
764
765         *ret_buffer = buffer;
766         *ret_buffer_len = buffer_len - pkg_length;
767
768         return (0);
769 } /* int parse_part_number */
770
771 static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
772                 char *output, int output_len)
773 {
774         char *buffer = *ret_buffer;
775         size_t buffer_len = *ret_buffer_len;
776
777         uint16_t tmp16;
778         size_t header_size = 2 * sizeof (uint16_t);
779
780         uint16_t pkg_length;
781         uint16_t pkg_type;
782
783         if ((buffer_len < 0) || (buffer_len < header_size))
784         {
785                 WARNING ("network plugin: parse_part_string: "
786                                 "Packet too short: "
787                                 "Chunk of at least size %zu expected, "
788                                 "but buffer has only %zu bytes left.",
789                                 header_size, buffer_len);
790                 return (-1);
791         }
792
793         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
794         buffer += sizeof (tmp16);
795         pkg_type = ntohs (tmp16);
796
797         memcpy ((void *) &tmp16, buffer, sizeof (tmp16));
798         buffer += sizeof (tmp16);
799         pkg_length = ntohs (tmp16);
800
801         /* Check that packet fits in the input buffer */
802         if (pkg_length > buffer_len)
803         {
804                 WARNING ("network plugin: parse_part_string: "
805                                 "Packet too big: "
806                                 "Chunk of size %"PRIu16" received, "
807                                 "but buffer has only %zu bytes left.",
808                                 pkg_length, buffer_len);
809                 return (-1);
810         }
811
812         /* Check that pkg_length is in the valid range */
813         if (pkg_length <= header_size)
814         {
815                 WARNING ("network plugin: parse_part_string: "
816                                 "Packet too short: "
817                                 "Header claims this packet is only %hu "
818                                 "bytes long.", pkg_length);
819                 return (-1);
820         }
821
822         /* Check that the package data fits into the output buffer.
823          * The previous if-statement ensures that:
824          * `pkg_length > header_size' */
825         if ((output_len < 0)
826                         || ((size_t) output_len < ((size_t) pkg_length - header_size)))
827         {
828                 WARNING ("network plugin: parse_part_string: "
829                                 "Output buffer too small.");
830                 return (-1);
831         }
832
833         /* All sanity checks successfull, let's copy the data over */
834         output_len = pkg_length - header_size;
835         memcpy ((void *) output, (void *) buffer, output_len);
836         buffer += output_len;
837
838         /* For some very weird reason '\0' doesn't do the trick on SPARC in
839          * this statement. */
840         if (output[output_len - 1] != 0)
841         {
842                 WARNING ("network plugin: parse_part_string: "
843                                 "Received string does not end "
844                                 "with a NULL-byte.");
845                 return (-1);
846         }
847
848         *ret_buffer = buffer;
849         *ret_buffer_len = buffer_len - pkg_length;
850
851         return (0);
852 } /* int parse_part_string */
853
854 /* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
855  * parse_packet and vice versa. */
856 #define PP_SIGNED    0x01
857 #define PP_ENCRYPTED 0x02
858 static int parse_packet (sockent_t *se,
859                 void *buffer, size_t buffer_size, int flags);
860
861 #define BUFFER_READ(p,s) do { \
862   memcpy ((p), buffer + buffer_offset, (s)); \
863   buffer_offset += (s); \
864 } while (0)
865
866 #if HAVE_LIBGCRYPT
867 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
868     void **ret_buffer, size_t *ret_buffer_len, int flags)
869 {
870   char *buffer;
871   size_t buffer_len;
872   size_t buffer_offset;
873
874   size_t username_len;
875   char *secret;
876
877   part_signature_sha256_t pss;
878   uint16_t pss_head_length;
879   char hash[sizeof (pss.hash)];
880
881   gcry_md_hd_t hd;
882   gcry_error_t err;
883   unsigned char *hash_ptr;
884
885   buffer = *ret_buffer;
886   buffer_len = *ret_buffer_len;
887   buffer_offset = 0;
888
889   if (se->data.server.userdb == NULL)
890   {
891     NOTICE ("network plugin: Received signed network packet but can't verify "
892         "it because no user DB has been configured. Will accept it.");
893     return (0);
894   }
895
896   /* Check if the buffer has enough data for this structure. */
897   if (buffer_len <= PART_SIGNATURE_SHA256_SIZE)
898     return (-ENOMEM);
899
900   /* Read type and length header */
901   BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
902   BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
903   pss_head_length = ntohs (pss.head.length);
904
905   /* Check if the `pss_head_length' is within bounds. */
906   if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE)
907       || (pss_head_length > buffer_len))
908   {
909     ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
910     return (-1);
911   }
912
913   /* Copy the hash. */
914   BUFFER_READ (pss.hash, sizeof (pss.hash));
915
916   /* Calculate username length (without null byte) and allocate memory */
917   username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE;
918   pss.username = malloc (username_len + 1);
919   if (pss.username == NULL)
920     return (-ENOMEM);
921
922   /* Read the username */
923   BUFFER_READ (pss.username, username_len);
924   pss.username[username_len] = 0;
925
926   assert (buffer_offset == pss_head_length);
927
928   /* Query the password */
929   secret = fbh_get (se->data.server.userdb, pss.username);
930   if (secret == NULL)
931   {
932     ERROR ("network plugin: Unknown user: %s", pss.username);
933     sfree (pss.username);
934     return (-ENOENT);
935   }
936
937   /* Create a hash device and check the HMAC */
938   hd = NULL;
939   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
940   if (err != 0)
941   {
942     ERROR ("network plugin: Creating HMAC-SHA-256 object failed: %s",
943         gcry_strerror (err));
944     sfree (secret);
945     sfree (pss.username);
946     return (-1);
947   }
948
949   err = gcry_md_setkey (hd, secret, strlen (secret));
950   if (err != 0)
951   {
952     ERROR ("network plugin: gcry_md_setkey failed: %s", gcry_strerror (err));
953     gcry_md_close (hd);
954     return (-1);
955   }
956
957   gcry_md_write (hd,
958       buffer     + PART_SIGNATURE_SHA256_SIZE,
959       buffer_len - PART_SIGNATURE_SHA256_SIZE);
960   hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
961   if (hash_ptr == NULL)
962   {
963     ERROR ("network plugin: gcry_md_read failed.");
964     gcry_md_close (hd);
965     sfree (secret);
966     sfree (pss.username);
967     return (-1);
968   }
969   memcpy (hash, hash_ptr, sizeof (hash));
970
971   /* Clean up */
972   gcry_md_close (hd);
973   hd = NULL;
974
975   sfree (secret);
976   sfree (pss.username);
977
978   if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
979   {
980     WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
981         "Hash mismatch.");
982   }
983   else
984   {
985     parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
986         flags | PP_SIGNED);
987   }
988
989   *ret_buffer = buffer + buffer_len;
990   *ret_buffer_len = 0;
991
992   return (0);
993 } /* }}} int parse_part_sign_sha256 */
994 /* #endif HAVE_LIBGCRYPT */
995
996 #else /* if !HAVE_LIBGCRYPT */
997 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
998     void **ret_buffer, size_t *ret_buffer_size, int flags)
999 {
1000   static int warning_has_been_printed = 0;
1001
1002   char *buffer;
1003   size_t buffer_size;
1004   size_t buffer_offset;
1005   uint16_t part_len;
1006
1007   part_signature_sha256_t pss;
1008
1009   buffer = *ret_buffer;
1010   buffer_size = *ret_buffer_size;
1011   buffer_offset = 0;
1012
1013   if (buffer_size <= PART_SIGNATURE_SHA256_SIZE)
1014     return (-ENOMEM);
1015
1016   BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
1017   BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
1018   part_len = ntohs (pss.head.length);
1019
1020   if ((part_len <= PART_SIGNATURE_SHA256_SIZE)
1021       || (part_len > buffer_size))
1022     return (-EINVAL);
1023
1024   if (warning_has_been_printed == 0)
1025   {
1026     WARNING ("network plugin: Received signed packet, but the network "
1027         "plugin was not linked with libgcrypt, so I cannot "
1028         "verify the signature. The packet will be accepted.");
1029     warning_has_been_printed = 1;
1030   }
1031
1032   parse_packet (se, buffer + part_len, buffer_size - part_len, flags);
1033
1034   *ret_buffer = buffer + buffer_size;
1035   *ret_buffer_size = 0;
1036
1037   return (0);
1038 } /* }}} int parse_part_sign_sha256 */
1039 #endif /* !HAVE_LIBGCRYPT */
1040
1041 #if HAVE_LIBGCRYPT
1042 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1043                 void **ret_buffer, size_t *ret_buffer_len,
1044                 int flags)
1045 {
1046   char  *buffer = *ret_buffer;
1047   size_t buffer_len = *ret_buffer_len;
1048   size_t payload_len;
1049   size_t part_size;
1050   size_t buffer_offset;
1051   uint16_t username_len;
1052   part_encryption_aes256_t pea;
1053   unsigned char hash[sizeof (pea.hash)];
1054
1055   gcry_cipher_hd_t cypher;
1056   gcry_error_t err;
1057
1058   /* Make sure at least the header if available. */
1059   if (buffer_len <= PART_ENCRYPTION_AES256_SIZE)
1060   {
1061     NOTICE ("network plugin: parse_part_encr_aes256: "
1062         "Discarding short packet.");
1063     return (-1);
1064   }
1065
1066   buffer_offset = 0;
1067
1068   /* Copy the unencrypted information into `pea'. */
1069   BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
1070   BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
1071
1072   /* Check the `part size'. */
1073   part_size = ntohs (pea.head.length);
1074   if ((part_size <= PART_ENCRYPTION_AES256_SIZE)
1075       || (part_size > buffer_len))
1076   {
1077     NOTICE ("network plugin: parse_part_encr_aes256: "
1078         "Discarding part with invalid size.");
1079     return (-1);
1080   }
1081
1082   /* Read the username */
1083   BUFFER_READ (&username_len, sizeof (username_len));
1084   username_len = ntohs (username_len);
1085
1086   if ((username_len <= 0)
1087       || (username_len > (part_size - (PART_ENCRYPTION_AES256_SIZE + 1))))
1088   {
1089     NOTICE ("network plugin: parse_part_encr_aes256: "
1090         "Discarding part with invalid username length.");
1091     return (-1);
1092   }
1093
1094   assert (username_len > 0);
1095   pea.username = malloc (username_len + 1);
1096   if (pea.username == NULL)
1097     return (-ENOMEM);
1098   BUFFER_READ (pea.username, username_len);
1099   pea.username[username_len] = 0;
1100
1101   /* Last but not least, the initialization vector */
1102   BUFFER_READ (pea.iv, sizeof (pea.iv));
1103
1104   /* Make sure we are at the right position */
1105   assert (buffer_offset == (username_len +
1106         PART_ENCRYPTION_AES256_SIZE - sizeof (pea.hash)));
1107
1108   cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
1109       pea.username);
1110   if (cypher == NULL)
1111     return (-1);
1112
1113   payload_len = part_size - (PART_ENCRYPTION_AES256_SIZE + username_len);
1114   assert (payload_len > 0);
1115
1116   /* Decrypt the packet in-place */
1117   err = gcry_cipher_decrypt (cypher,
1118       buffer    + buffer_offset,
1119       part_size - buffer_offset,
1120       /* in = */ NULL, /* in len = */ 0);
1121   if (err != 0)
1122   {
1123     ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
1124         gcry_strerror (err));
1125     return (-1);
1126   }
1127
1128   /* Read the hash */
1129   BUFFER_READ (pea.hash, sizeof (pea.hash));
1130
1131   /* Make sure we're at the right position - again */
1132   assert (buffer_offset == (username_len + PART_ENCRYPTION_AES256_SIZE));
1133   assert (buffer_offset == (part_size - payload_len));
1134
1135   /* Check hash sum */
1136   memset (hash, 0, sizeof (hash));
1137   gcry_md_hash_buffer (GCRY_MD_SHA1, hash,
1138       buffer + buffer_offset, payload_len);
1139   if (memcmp (hash, pea.hash, sizeof (hash)) != 0)
1140   {
1141     ERROR ("network plugin: Decryption failed: Checksum mismatch.");
1142     return (-1);
1143   }
1144
1145   parse_packet (se, buffer + buffer_offset, payload_len,
1146       flags | PP_ENCRYPTED);
1147
1148   /* Update return values */
1149   *ret_buffer =     buffer     + part_size;
1150   *ret_buffer_len = buffer_len - part_size;
1151
1152   return (0);
1153 } /* }}} int parse_part_encr_aes256 */
1154 /* #endif HAVE_LIBGCRYPT */
1155
1156 #else /* if !HAVE_LIBGCRYPT */
1157 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
1158     void **ret_buffer, size_t *ret_buffer_size, int flags)
1159 {
1160   static int warning_has_been_printed = 0;
1161
1162   char *buffer;
1163   size_t buffer_size;
1164   size_t buffer_offset;
1165
1166   part_header_t ph;
1167   size_t ph_length;
1168
1169   buffer = *ret_buffer;
1170   buffer_size = *ret_buffer_size;
1171   buffer_offset = 0;
1172
1173   /* parse_packet assures this minimum size. */
1174   assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
1175
1176   BUFFER_READ (&ph.type, sizeof (ph.type));
1177   BUFFER_READ (&ph.length, sizeof (ph.length));
1178   ph_length = ntohs (ph.length);
1179
1180   if ((ph_length <= PART_ENCRYPTION_AES256_SIZE)
1181       || (ph_length > buffer_size))
1182   {
1183     ERROR ("network plugin: AES-256 encrypted part "
1184         "with invalid length received.");
1185     return (-1);
1186   }
1187
1188   if (warning_has_been_printed == 0)
1189   {
1190     WARNING ("network plugin: Received encrypted packet, but the network "
1191         "plugin was not linked with libgcrypt, so I cannot "
1192         "decrypt it. The part will be discarded.");
1193     warning_has_been_printed = 1;
1194   }
1195
1196   *ret_buffer += ph_length;
1197   *ret_buffer_size -= ph_length;
1198
1199   return (0);
1200 } /* }}} int parse_part_encr_aes256 */
1201 #endif /* !HAVE_LIBGCRYPT */
1202
1203 #undef BUFFER_READ
1204
1205 static int parse_packet (sockent_t *se, /* {{{ */
1206                 void *buffer, size_t buffer_size, int flags)
1207 {
1208         int status;
1209
1210         value_list_t vl = VALUE_LIST_INIT;
1211         notification_t n;
1212
1213 #if HAVE_LIBGCRYPT
1214         int packet_was_signed = (flags & PP_SIGNED);
1215         int packet_was_encrypted = (flags & PP_ENCRYPTED);
1216         int printed_ignore_warning = 0;
1217 #endif /* HAVE_LIBGCRYPT */
1218
1219
1220         memset (&vl, '\0', sizeof (vl));
1221         memset (&n, '\0', sizeof (n));
1222         status = 0;
1223
1224         while ((status == 0) && (0 < buffer_size)
1225                         && ((unsigned int) buffer_size > sizeof (part_header_t)))
1226         {
1227                 uint16_t pkg_length;
1228                 uint16_t pkg_type;
1229
1230                 memcpy ((void *) &pkg_type,
1231                                 (void *) buffer,
1232                                 sizeof (pkg_type));
1233                 memcpy ((void *) &pkg_length,
1234                                 (void *) (buffer + sizeof (pkg_type)),
1235                                 sizeof (pkg_length));
1236
1237                 pkg_length = ntohs (pkg_length);
1238                 pkg_type = ntohs (pkg_type);
1239
1240                 if (pkg_length > buffer_size)
1241                         break;
1242                 /* Ensure that this loop terminates eventually */
1243                 if (pkg_length < (2 * sizeof (uint16_t)))
1244                         break;
1245
1246                 if (pkg_type == TYPE_ENCR_AES256)
1247                 {
1248                         status = parse_part_encr_aes256 (se,
1249                                         &buffer, &buffer_size, flags);
1250                         if (status != 0)
1251                         {
1252                                 ERROR ("network plugin: Decrypting AES256 "
1253                                                 "part failed "
1254                                                 "with status %i.", status);
1255                                 break;
1256                         }
1257                 }
1258 #if HAVE_LIBGCRYPT
1259                 else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
1260                                 && (packet_was_encrypted == 0))
1261                 {
1262                         if (printed_ignore_warning == 0)
1263                         {
1264                                 INFO ("network plugin: Unencrypted packet or "
1265                                                 "part has been ignored.");
1266                                 printed_ignore_warning = 1;
1267                         }
1268                         buffer = ((char *) buffer) + pkg_length;
1269                         continue;
1270                 }
1271 #endif /* HAVE_LIBGCRYPT */
1272                 else if (pkg_type == TYPE_SIGN_SHA256)
1273                 {
1274                         status = parse_part_sign_sha256 (se,
1275                                         &buffer, &buffer_size, flags);
1276                         if (status != 0)
1277                         {
1278                                 ERROR ("network plugin: Verifying HMAC-SHA-256 "
1279                                                 "signature failed "
1280                                                 "with status %i.", status);
1281                                 break;
1282                         }
1283                 }
1284 #if HAVE_LIBGCRYPT
1285                 else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
1286                                 && (packet_was_encrypted == 0)
1287                                 && (packet_was_signed == 0))
1288                 {
1289                         if (printed_ignore_warning == 0)
1290                         {
1291                                 INFO ("network plugin: Unsigned packet or "
1292                                                 "part has been ignored.");
1293                                 printed_ignore_warning = 1;
1294                         }
1295                         buffer = ((char *) buffer) + pkg_length;
1296                         continue;
1297                 }
1298 #endif /* HAVE_LIBGCRYPT */
1299                 else if (pkg_type == TYPE_VALUES)
1300                 {
1301                         status = parse_part_values (&buffer, &buffer_size,
1302                                         &vl.values, &vl.values_len);
1303
1304                         if (status != 0)
1305                                 break;
1306
1307                         if ((vl.time > 0)
1308                                         && (strlen (vl.host) > 0)
1309                                         && (strlen (vl.plugin) > 0)
1310                                         && (strlen (vl.type) > 0)
1311                                         && (cache_check (&vl) == 0))
1312                         {
1313                                 plugin_dispatch_values (&vl);
1314                         }
1315                         else
1316                         {
1317                                 DEBUG ("network plugin: parse_packet:"
1318                                                 " NOT dispatching values");
1319                         }
1320
1321                         sfree (vl.values);
1322                 }
1323                 else if (pkg_type == TYPE_TIME)
1324                 {
1325                         uint64_t tmp = 0;
1326                         status = parse_part_number (&buffer, &buffer_size,
1327                                         &tmp);
1328                         if (status == 0)
1329                         {
1330                                 vl.time = (time_t) tmp;
1331                                 n.time = (time_t) tmp;
1332                         }
1333                 }
1334                 else if (pkg_type == TYPE_INTERVAL)
1335                 {
1336                         uint64_t tmp = 0;
1337                         status = parse_part_number (&buffer, &buffer_size,
1338                                         &tmp);
1339                         if (status == 0)
1340                                 vl.interval = (int) tmp;
1341                 }
1342                 else if (pkg_type == TYPE_HOST)
1343                 {
1344                         status = parse_part_string (&buffer, &buffer_size,
1345                                         vl.host, sizeof (vl.host));
1346                         if (status == 0)
1347                                 sstrncpy (n.host, vl.host, sizeof (n.host));
1348                 }
1349                 else if (pkg_type == TYPE_PLUGIN)
1350                 {
1351                         status = parse_part_string (&buffer, &buffer_size,
1352                                         vl.plugin, sizeof (vl.plugin));
1353                         if (status == 0)
1354                                 sstrncpy (n.plugin, vl.plugin,
1355                                                 sizeof (n.plugin));
1356                 }
1357                 else if (pkg_type == TYPE_PLUGIN_INSTANCE)
1358                 {
1359                         status = parse_part_string (&buffer, &buffer_size,
1360                                         vl.plugin_instance,
1361                                         sizeof (vl.plugin_instance));
1362                         if (status == 0)
1363                                 sstrncpy (n.plugin_instance,
1364                                                 vl.plugin_instance,
1365                                                 sizeof (n.plugin_instance));
1366                 }
1367                 else if (pkg_type == TYPE_TYPE)
1368                 {
1369                         status = parse_part_string (&buffer, &buffer_size,
1370                                         vl.type, sizeof (vl.type));
1371                         if (status == 0)
1372                                 sstrncpy (n.type, vl.type, sizeof (n.type));
1373                 }
1374                 else if (pkg_type == TYPE_TYPE_INSTANCE)
1375                 {
1376                         status = parse_part_string (&buffer, &buffer_size,
1377                                         vl.type_instance,
1378                                         sizeof (vl.type_instance));
1379                         if (status == 0)
1380                                 sstrncpy (n.type_instance, vl.type_instance,
1381                                                 sizeof (n.type_instance));
1382                 }
1383                 else if (pkg_type == TYPE_MESSAGE)
1384                 {
1385                         status = parse_part_string (&buffer, &buffer_size,
1386                                         n.message, sizeof (n.message));
1387
1388                         if (status != 0)
1389                         {
1390                                 /* do nothing */
1391                         }
1392                         else if ((n.severity != NOTIF_FAILURE)
1393                                         && (n.severity != NOTIF_WARNING)
1394                                         && (n.severity != NOTIF_OKAY))
1395                         {
1396                                 INFO ("network plugin: "
1397                                                 "Ignoring notification with "
1398                                                 "unknown severity %i.",
1399                                                 n.severity);
1400                         }
1401                         else if (n.time <= 0)
1402                         {
1403                                 INFO ("network plugin: "
1404                                                 "Ignoring notification with "
1405                                                 "time == 0.");
1406                         }
1407                         else if (strlen (n.message) <= 0)
1408                         {
1409                                 INFO ("network plugin: "
1410                                                 "Ignoring notification with "
1411                                                 "an empty message.");
1412                         }
1413                         else
1414                         {
1415                                 plugin_dispatch_notification (&n);
1416                         }
1417                 }
1418                 else if (pkg_type == TYPE_SEVERITY)
1419                 {
1420                         uint64_t tmp = 0;
1421                         status = parse_part_number (&buffer, &buffer_size,
1422                                         &tmp);
1423                         if (status == 0)
1424                                 n.severity = (int) tmp;
1425                 }
1426                 else
1427                 {
1428                         DEBUG ("network plugin: parse_packet: Unknown part"
1429                                         " type: 0x%04hx", pkg_type);
1430                         buffer = ((char *) buffer) + pkg_length;
1431                 }
1432         } /* while (buffer_size > sizeof (part_header_t)) */
1433
1434         return (status);
1435 } /* }}} int parse_packet */
1436
1437 static void free_sockent_client (struct sockent_client *sec) /* {{{ */
1438 {
1439   if (sec->fd >= 0)
1440   {
1441     close (sec->fd);
1442     sec->fd = -1;
1443   }
1444   sfree (sec->addr);
1445 #if HAVE_LIBGCRYPT
1446   sfree (sec->username);
1447   sfree (sec->password);
1448   if (sec->cypher != NULL)
1449     gcry_cipher_close (sec->cypher);
1450 #endif
1451 } /* }}} void free_sockent_client */
1452
1453 static void free_sockent_server (struct sockent_server *ses) /* {{{ */
1454 {
1455   size_t i;
1456
1457   for (i = 0; i < ses->fd_num; i++)
1458   {
1459     if (ses->fd[i] >= 0)
1460     {
1461       close (ses->fd[i]);
1462       ses->fd[i] = -1;
1463     }
1464   }
1465
1466   sfree (ses->fd);
1467 #if HAVE_LIBGCRYPT
1468   sfree (ses->auth_file);
1469   fbh_destroy (ses->userdb);
1470   if (ses->cypher != NULL)
1471     gcry_cipher_close (ses->cypher);
1472 #endif
1473 } /* }}} void free_sockent_server */
1474
1475 static void sockent_destroy (sockent_t *se) /* {{{ */
1476 {
1477   sockent_t *next;
1478
1479   DEBUG ("network plugin: sockent_destroy (se = %p);", (void *) se);
1480
1481   while (se != NULL)
1482   {
1483     next = se->next;
1484
1485     sfree (se->node);
1486     sfree (se->service);
1487
1488     if (se->type == SOCKENT_TYPE_CLIENT)
1489       free_sockent_client (&se->data.client);
1490     else
1491       free_sockent_server (&se->data.server);
1492
1493     sfree (se);
1494     se = next;
1495   }
1496 } /* }}} void sockent_destroy */
1497
1498 /*
1499  * int network_set_ttl
1500  *
1501  * Set the `IP_MULTICAST_TTL', `IP_TTL', `IPV6_MULTICAST_HOPS' or
1502  * `IPV6_UNICAST_HOPS', depending on which option is applicable.
1503  *
1504  * The `struct addrinfo' is used to destinguish between unicast and multicast
1505  * sockets.
1506  */
1507 static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
1508 {
1509         DEBUG ("network plugin: network_set_ttl: network_config_ttl = %i;",
1510                         network_config_ttl);
1511
1512         assert (se->type == SOCKENT_TYPE_CLIENT);
1513
1514         if ((network_config_ttl < 1) || (network_config_ttl > 255))
1515                 return (-1);
1516
1517         if (ai->ai_family == AF_INET)
1518         {
1519                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1520                 int optname;
1521
1522                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1523                         optname = IP_MULTICAST_TTL;
1524                 else
1525                         optname = IP_TTL;
1526
1527                 if (setsockopt (se->data.client.fd, IPPROTO_IP, optname,
1528                                         &network_config_ttl,
1529                                         sizeof (network_config_ttl)) == -1)
1530                 {
1531                         char errbuf[1024];
1532                         ERROR ("setsockopt: %s",
1533                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1534                         return (-1);
1535                 }
1536         }
1537         else if (ai->ai_family == AF_INET6)
1538         {
1539                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1540                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1541                 int optname;
1542
1543                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1544                         optname = IPV6_MULTICAST_HOPS;
1545                 else
1546                         optname = IPV6_UNICAST_HOPS;
1547
1548                 if (setsockopt (se->data.client.fd, IPPROTO_IPV6, optname,
1549                                         &network_config_ttl,
1550                                         sizeof (network_config_ttl)) == -1)
1551                 {
1552                         char errbuf[1024];
1553                         ERROR ("setsockopt: %s",
1554                                         sstrerror (errno, errbuf,
1555                                                 sizeof (errbuf)));
1556                         return (-1);
1557                 }
1558         }
1559
1560         return (0);
1561 } /* int network_set_ttl */
1562
1563 static int network_bind_socket (int fd, const struct addrinfo *ai)
1564 {
1565         int loop = 0;
1566         int yes  = 1;
1567
1568         /* allow multiple sockets to use the same PORT number */
1569         if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
1570                                 &yes, sizeof(yes)) == -1) {
1571                 char errbuf[1024];
1572                 ERROR ("setsockopt: %s", 
1573                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1574                 return (-1);
1575         }
1576
1577         DEBUG ("fd = %i; calling `bind'", fd);
1578
1579         if (bind (fd, ai->ai_addr, ai->ai_addrlen) == -1)
1580         {
1581                 char errbuf[1024];
1582                 ERROR ("bind: %s",
1583                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1584                 return (-1);
1585         }
1586
1587         if (ai->ai_family == AF_INET)
1588         {
1589                 struct sockaddr_in *addr = (struct sockaddr_in *) ai->ai_addr;
1590                 if (IN_MULTICAST (ntohl (addr->sin_addr.s_addr)))
1591                 {
1592                         struct ip_mreq mreq;
1593
1594                         DEBUG ("fd = %i; IPv4 multicast address found", fd);
1595
1596                         mreq.imr_multiaddr.s_addr = addr->sin_addr.s_addr;
1597                         mreq.imr_interface.s_addr = htonl (INADDR_ANY);
1598
1599                         if (setsockopt (fd, IPPROTO_IP, IP_MULTICAST_LOOP,
1600                                                 &loop, sizeof (loop)) == -1)
1601                         {
1602                                 char errbuf[1024];
1603                                 ERROR ("setsockopt: %s",
1604                                                 sstrerror (errno, errbuf,
1605                                                         sizeof (errbuf)));
1606                                 return (-1);
1607                         }
1608
1609                         if (setsockopt (fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
1610                                                 &mreq, sizeof (mreq)) == -1)
1611                         {
1612                                 char errbuf[1024];
1613                                 ERROR ("setsockopt: %s",
1614                                                 sstrerror (errno, errbuf,
1615                                                         sizeof (errbuf)));
1616                                 return (-1);
1617                         }
1618                 }
1619         }
1620         else if (ai->ai_family == AF_INET6)
1621         {
1622                 /* Useful example: http://gsyc.escet.urjc.es/~eva/IPv6-web/examples/mcast.html */
1623                 struct sockaddr_in6 *addr = (struct sockaddr_in6 *) ai->ai_addr;
1624                 if (IN6_IS_ADDR_MULTICAST (&addr->sin6_addr))
1625                 {
1626                         struct ipv6_mreq mreq;
1627
1628                         DEBUG ("fd = %i; IPv6 multicast address found", fd);
1629
1630                         memcpy (&mreq.ipv6mr_multiaddr,
1631                                         &addr->sin6_addr,
1632                                         sizeof (addr->sin6_addr));
1633
1634                         /* http://developer.apple.com/documentation/Darwin/Reference/ManPages/man4/ip6.4.html
1635                          * ipv6mr_interface may be set to zeroes to
1636                          * choose the default multicast interface or to
1637                          * the index of a particular multicast-capable
1638                          * interface if the host is multihomed.
1639                          * Membership is associ-associated with a
1640                          * single interface; programs running on
1641                          * multihomed hosts may need to join the same
1642                          * group on more than one interface.*/
1643                         mreq.ipv6mr_interface = 0;
1644
1645                         if (setsockopt (fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1646                                                 &loop, sizeof (loop)) == -1)
1647                         {
1648                                 char errbuf[1024];
1649                                 ERROR ("setsockopt: %s",
1650                                                 sstrerror (errno, errbuf,
1651                                                         sizeof (errbuf)));
1652                                 return (-1);
1653                         }
1654
1655                         if (setsockopt (fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
1656                                                 &mreq, sizeof (mreq)) == -1)
1657                         {
1658                                 char errbuf[1024];
1659                                 ERROR ("setsockopt: %s",
1660                                                 sstrerror (errno, errbuf,
1661                                                         sizeof (errbuf)));
1662                                 return (-1);
1663                         }
1664                 }
1665         }
1666
1667         return (0);
1668 } /* int network_bind_socket */
1669
1670 /* Initialize a sockent structure. `type' must be either `SOCKENT_TYPE_CLIENT'
1671  * or `SOCKENT_TYPE_SERVER' */
1672 static int sockent_init (sockent_t *se, int type) /* {{{ */
1673 {
1674         if (se == NULL)
1675                 return (-1);
1676
1677         memset (se, 0, sizeof (*se));
1678
1679         se->type = SOCKENT_TYPE_CLIENT;
1680         se->node = NULL;
1681         se->service = NULL;
1682         se->next = NULL;
1683
1684         if (type == SOCKENT_TYPE_SERVER)
1685         {
1686                 se->type = SOCKENT_TYPE_SERVER;
1687                 se->data.server.fd = NULL;
1688 #if HAVE_LIBGCRYPT
1689                 se->data.server.security_level = SECURITY_LEVEL_NONE;
1690                 se->data.server.auth_file = NULL;
1691                 se->data.server.userdb = NULL;
1692                 se->data.server.cypher = NULL;
1693 #endif
1694         }
1695         else
1696         {
1697                 se->data.client.fd = -1;
1698                 se->data.client.addr = NULL;
1699 #if HAVE_LIBGCRYPT
1700                 se->data.client.security_level = SECURITY_LEVEL_NONE;
1701                 se->data.client.username = NULL;
1702                 se->data.client.password = NULL;
1703                 se->data.client.cypher = NULL;
1704 #endif
1705         }
1706
1707         return (0);
1708 } /* }}} int sockent_init */
1709
1710 /* Open the file descriptors for a initialized sockent structure. */
1711 static int sockent_open (sockent_t *se) /* {{{ */
1712 {
1713         struct addrinfo  ai_hints;
1714         struct addrinfo *ai_list, *ai_ptr;
1715         int              ai_return;
1716
1717         const char *node;
1718         const char *service;
1719
1720         if (se == NULL)
1721                 return (-1);
1722
1723         /* Set up the security structures. */
1724 #if HAVE_LIBGCRYPT /* {{{ */
1725         if (se->type == SOCKENT_TYPE_CLIENT)
1726         {
1727                 if (se->data.client.security_level > SECURITY_LEVEL_NONE)
1728                 {
1729                         if ((se->data.client.username == NULL)
1730                                         || (se->data.client.password == NULL))
1731                         {
1732                                 ERROR ("network plugin: Client socket with "
1733                                                 "security requested, but no "
1734                                                 "credentials are configured.");
1735                                 return (-1);
1736                         }
1737                         gcry_md_hash_buffer (GCRY_MD_SHA256,
1738                                         se->data.client.password_hash,
1739                                         se->data.client.password,
1740                                         strlen (se->data.client.password));
1741                 }
1742         }
1743         else /* (se->type == SOCKENT_TYPE_SERVER) */
1744         {
1745                 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1746                 {
1747                         if (se->data.server.auth_file == NULL)
1748                         {
1749                                 ERROR ("network plugin: Server socket with "
1750                                                 "security requested, but no "
1751                                                 "password file is configured.");
1752                                 return (-1);
1753                         }
1754                 }
1755                 if (se->data.server.auth_file != NULL)
1756                 {
1757                         se->data.server.userdb = fbh_create (se->data.server.auth_file);
1758                         if (se->data.server.userdb == NULL)
1759                         {
1760                                 ERROR ("network plugin: Reading password file "
1761                                                 "`%s' failed.",
1762                                                 se->data.server.auth_file);
1763                                 if (se->data.server.security_level > SECURITY_LEVEL_NONE)
1764                                         return (-1);
1765                         }
1766                 }
1767         }
1768 #endif /* }}} HAVE_LIBGCRYPT */
1769
1770         node = se->node;
1771         service = se->service;
1772
1773         if (service == NULL)
1774           service = NET_DEFAULT_PORT;
1775
1776         DEBUG ("network plugin: sockent_open: node = %s; service = %s;",
1777             node, service);
1778
1779         memset (&ai_hints, 0, sizeof (ai_hints));
1780         ai_hints.ai_flags  = 0;
1781 #ifdef AI_PASSIVE
1782         ai_hints.ai_flags |= AI_PASSIVE;
1783 #endif
1784 #ifdef AI_ADDRCONFIG
1785         ai_hints.ai_flags |= AI_ADDRCONFIG;
1786 #endif
1787         ai_hints.ai_family   = AF_UNSPEC;
1788         ai_hints.ai_socktype = SOCK_DGRAM;
1789         ai_hints.ai_protocol = IPPROTO_UDP;
1790
1791         ai_return = getaddrinfo (node, service, &ai_hints, &ai_list);
1792         if (ai_return != 0)
1793         {
1794                 ERROR ("network plugin: getaddrinfo (%s, %s) failed: %s",
1795                                 (se->node == NULL) ? "(null)" : se->node,
1796                                 (se->service == NULL) ? "(null)" : se->service,
1797                                 gai_strerror (ai_return));
1798                 return (-1);
1799         }
1800
1801         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1802         {
1803                 int status;
1804
1805                 if (se->type == SOCKENT_TYPE_SERVER) /* {{{ */
1806                 {
1807                         int *tmp;
1808
1809                         tmp = realloc (se->data.server.fd,
1810                                         sizeof (*tmp) * (se->data.server.fd_num + 1));
1811                         if (tmp == NULL)
1812                         {
1813                                 ERROR ("network plugin: realloc failed.");
1814                                 continue;
1815                         }
1816                         se->data.server.fd = tmp;
1817                         tmp = se->data.server.fd + se->data.server.fd_num;
1818
1819                         *tmp = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
1820                                         ai_ptr->ai_protocol);
1821                         if (*tmp < 0)
1822                         {
1823                                 char errbuf[1024];
1824                                 ERROR ("network plugin: socket(2) failed: %s",
1825                                                 sstrerror (errno, errbuf,
1826                                                         sizeof (errbuf)));
1827                                 continue;
1828                         }
1829
1830                         status = network_bind_socket (*tmp, ai_ptr);
1831                         if (status != 0)
1832                         {
1833                                 close (*tmp);
1834                                 *tmp = -1;
1835                                 continue;
1836                         }
1837
1838                         se->data.server.fd_num++;
1839                         continue;
1840                 } /* }}} if (se->type == SOCKENT_TYPE_SERVER) */
1841                 else /* if (se->type == SOCKENT_TYPE_CLIENT) {{{ */
1842                 {
1843                         se->data.client.fd = socket (ai_ptr->ai_family,
1844                                         ai_ptr->ai_socktype,
1845                                         ai_ptr->ai_protocol);
1846                         if (se->data.client.fd < 0)
1847                         {
1848                                 char errbuf[1024];
1849                                 ERROR ("network plugin: socket(2) failed: %s",
1850                                                 sstrerror (errno, errbuf,
1851                                                         sizeof (errbuf)));
1852                                 continue;
1853                         }
1854
1855                         se->data.client.addr = malloc (sizeof (*se->data.client.addr));
1856                         if (se->data.client.addr == NULL)
1857                         {
1858                                 ERROR ("network plugin: malloc failed.");
1859                                 close (se->data.client.fd);
1860                                 se->data.client.fd = -1;
1861                                 continue;
1862                         }
1863
1864                         memset (se->data.client.addr, 0, sizeof (*se->data.client.addr));
1865                         assert (sizeof (*se->data.client.addr) >= ai_ptr->ai_addrlen);
1866                         memcpy (se->data.client.addr, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
1867                         se->data.client.addrlen = ai_ptr->ai_addrlen;
1868
1869                         network_set_ttl (se, ai_ptr);
1870
1871                         /* We don't open more than one write-socket per
1872                          * node/service pair.. */
1873                         break;
1874                 } /* }}} if (se->type == SOCKENT_TYPE_CLIENT) */
1875         } /* for (ai_list) */
1876
1877         freeaddrinfo (ai_list);
1878
1879         /* Check if all went well. */
1880         if (se->type == SOCKENT_TYPE_SERVER)
1881         {
1882                 if (se->data.server.fd_num <= 0)
1883                         return (-1);
1884         }
1885         else /* if (se->type == SOCKENT_TYPE_CLIENT) */
1886         {
1887                 if (se->data.client.fd < 0)
1888                         return (-1);
1889         }
1890
1891         return (0);
1892 } /* }}} int sockent_open */
1893
1894 /* Add a sockent to the global list of sockets */
1895 static int sockent_add (sockent_t *se) /* {{{ */
1896 {
1897         sockent_t *last_ptr;
1898
1899         if (se == NULL)
1900                 return (-1);
1901
1902         if (se->type == SOCKENT_TYPE_SERVER)
1903         {
1904                 struct pollfd *tmp;
1905                 size_t i;
1906
1907                 tmp = realloc (listen_sockets_pollfd,
1908                                 sizeof (*tmp) * (listen_sockets_num
1909                                         + se->data.server.fd_num));
1910                 if (tmp == NULL)
1911                 {
1912                         ERROR ("network plugin: realloc failed.");
1913                         return (-1);
1914                 }
1915                 listen_sockets_pollfd = tmp;
1916                 tmp = listen_sockets_pollfd + listen_sockets_num;
1917
1918                 for (i = 0; i < se->data.server.fd_num; i++)
1919                 {
1920                         memset (tmp + i, 0, sizeof (*tmp));
1921                         tmp[i].fd = se->data.server.fd[i];
1922                         tmp[i].events = POLLIN | POLLPRI;
1923                         tmp[i].revents = 0;
1924                 }
1925
1926                 listen_sockets_num += se->data.server.fd_num;
1927
1928                 if (listen_sockets == NULL)
1929                 {
1930                         listen_sockets = se;
1931                         return (0);
1932                 }
1933                 last_ptr = listen_sockets;
1934         }
1935         else /* if (se->type == SOCKENT_TYPE_CLIENT) */
1936         {
1937                 if (sending_sockets == NULL)
1938                 {
1939                         sending_sockets = se;
1940                         return (0);
1941                 }
1942                 last_ptr = sending_sockets;
1943         }
1944
1945         while (last_ptr->next != NULL)
1946                 last_ptr = last_ptr->next;
1947         last_ptr->next = se;
1948
1949         return (0);
1950 } /* }}} int sockent_add */
1951
1952 static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
1953 {
1954   while (42)
1955   {
1956     receive_list_entry_t *ent;
1957     sockent_t *se;
1958
1959     /* Lock and wait for more data to come in */
1960     pthread_mutex_lock (&receive_list_lock);
1961     while ((listen_loop == 0)
1962         && (receive_list_head == NULL))
1963       pthread_cond_wait (&receive_list_cond, &receive_list_lock);
1964
1965     /* Remove the head entry and unlock */
1966     ent = receive_list_head;
1967     if (ent != NULL)
1968       receive_list_head = ent->next;
1969     pthread_mutex_unlock (&receive_list_lock);
1970
1971     /* Check whether we are supposed to exit. We do NOT check `listen_loop'
1972      * because we dispatch all missing packets before shutting down. */
1973     if (ent == NULL)
1974       break;
1975
1976     /* Look for the correct `sockent_t' */
1977     se = listen_sockets;
1978     while (se != NULL)
1979     {
1980       size_t i;
1981
1982       for (i = 0; i < se->data.server.fd_num; i++)
1983         if (se->data.server.fd[i] == ent->fd)
1984           break;
1985
1986       if (i < se->data.server.fd_num)
1987         break;
1988
1989       se = se->next;
1990     }
1991
1992     if (se == NULL)
1993     {
1994             ERROR ("network plugin: Got packet from FD %i, but can't "
1995                             "find an appropriate socket entry.",
1996                             ent->fd);
1997             sfree (ent);
1998             continue;
1999     }
2000
2001     parse_packet (se, ent->data, ent->data_len, /* flags = */ 0);
2002     sfree (ent);
2003   } /* while (42) */
2004
2005   return (NULL);
2006 } /* }}} void *dispatch_thread */
2007
2008 static int network_receive (void) /* {{{ */
2009 {
2010         char buffer[BUFF_SIZE];
2011         int  buffer_len;
2012
2013         int i;
2014         int status;
2015
2016         receive_list_entry_t *private_list_head;
2017         receive_list_entry_t *private_list_tail;
2018
2019         assert (listen_sockets_num > 0);
2020
2021         private_list_head = NULL;
2022         private_list_tail = NULL;
2023
2024         while (listen_loop == 0)
2025         {
2026                 status = poll (listen_sockets_pollfd, listen_sockets_num, -1);
2027
2028                 if (status <= 0)
2029                 {
2030                         char errbuf[1024];
2031                         if (errno == EINTR)
2032                                 continue;
2033                         ERROR ("poll failed: %s",
2034                                         sstrerror (errno, errbuf, sizeof (errbuf)));
2035                         return (-1);
2036                 }
2037
2038                 for (i = 0; (i < listen_sockets_num) && (status > 0); i++)
2039                 {
2040                         receive_list_entry_t *ent;
2041
2042                         if ((listen_sockets_pollfd[i].revents
2043                                                 & (POLLIN | POLLPRI)) == 0)
2044                                 continue;
2045                         status--;
2046
2047                         buffer_len = recv (listen_sockets_pollfd[i].fd,
2048                                         buffer, sizeof (buffer),
2049                                         0 /* no flags */);
2050                         if (buffer_len < 0)
2051                         {
2052                                 char errbuf[1024];
2053                                 ERROR ("recv failed: %s",
2054                                                 sstrerror (errno, errbuf,
2055                                                         sizeof (errbuf)));
2056                                 return (-1);
2057                         }
2058
2059                         /* TODO: Possible performance enhancement: Do not free
2060                          * these entries in the dispatch thread but put them in
2061                          * another list, so we don't have to allocate more and
2062                          * more of these structures. */
2063                         ent = malloc (sizeof (receive_list_entry_t));
2064                         if (ent == NULL)
2065                         {
2066                                 ERROR ("network plugin: malloc failed.");
2067                                 return (-1);
2068                         }
2069                         memset (ent, 0, sizeof (receive_list_entry_t));
2070                         ent->fd = listen_sockets_pollfd[i].fd;
2071                         ent->next = NULL;
2072
2073                         /* Hopefully this be optimized out by the compiler. It
2074                          * might help prevent stupid bugs in the future though.
2075                          */
2076                         assert (sizeof (ent->data) == sizeof (buffer));
2077
2078                         memcpy (ent->data, buffer, buffer_len);
2079                         ent->data_len = buffer_len;
2080
2081                         if (private_list_head == NULL)
2082                                 private_list_head = ent;
2083                         else
2084                                 private_list_tail->next = ent;
2085                         private_list_tail = ent;
2086
2087                         /* Do not block here. Blocking here has led to
2088                          * insufficient performance in the past. */
2089                         if (pthread_mutex_trylock (&receive_list_lock) == 0)
2090                         {
2091                                 if (receive_list_head == NULL)
2092                                         receive_list_head = private_list_head;
2093                                 else
2094                                         receive_list_tail->next = private_list_head;
2095                                 receive_list_tail = private_list_tail;
2096
2097                                 private_list_head = NULL;
2098                                 private_list_tail = NULL;
2099
2100                                 pthread_cond_signal (&receive_list_cond);
2101                                 pthread_mutex_unlock (&receive_list_lock);
2102                         }
2103                 } /* for (listen_sockets_pollfd) */
2104         } /* while (listen_loop == 0) */
2105
2106         /* Make sure everything is dispatched before exiting. */
2107         if (private_list_head != NULL)
2108         {
2109                 pthread_mutex_lock (&receive_list_lock);
2110
2111                 if (receive_list_head == NULL)
2112                         receive_list_head = private_list_head;
2113                 else
2114                         receive_list_tail->next = private_list_head;
2115                 receive_list_tail = private_list_tail;
2116
2117                 private_list_head = NULL;
2118                 private_list_tail = NULL;
2119
2120                 pthread_cond_signal (&receive_list_cond);
2121                 pthread_mutex_unlock (&receive_list_lock);
2122         }
2123
2124         return (0);
2125 } /* }}} int network_receive */
2126
2127 static void *receive_thread (void __attribute__((unused)) *arg)
2128 {
2129         return (network_receive () ? (void *) 1 : (void *) 0);
2130 } /* void *receive_thread */
2131
2132 static void network_init_buffer (void)
2133 {
2134         memset (send_buffer, 0, sizeof (send_buffer));
2135         send_buffer_ptr = send_buffer;
2136         send_buffer_fill = 0;
2137
2138         memset (&send_buffer_vl, 0, sizeof (send_buffer_vl));
2139 } /* int network_init_buffer */
2140
2141 static void networt_send_buffer_plain (const sockent_t *se, /* {{{ */
2142                 const char *buffer, size_t buffer_size)
2143 {
2144         int status;
2145
2146         while (42)
2147         {
2148                 status = sendto (se->data.client.fd, buffer, buffer_size,
2149                     /* flags = */ 0,
2150                     (struct sockaddr *) se->data.client.addr,
2151                     se->data.client.addrlen);
2152                 if (status < 0)
2153                 {
2154                         char errbuf[1024];
2155                         if (errno == EINTR)
2156                                 continue;
2157                         ERROR ("network plugin: sendto failed: %s",
2158                                         sstrerror (errno, errbuf,
2159                                                 sizeof (errbuf)));
2160                         break;
2161                 }
2162
2163                 break;
2164         } /* while (42) */
2165 } /* }}} void networt_send_buffer_plain */
2166
2167 #if HAVE_LIBGCRYPT
2168 #define BUFFER_ADD(p,s) do { \
2169   memcpy (buffer + buffer_offset, (p), (s)); \
2170   buffer_offset += (s); \
2171 } while (0)
2172
2173 static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
2174                 const char *in_buffer, size_t in_buffer_size)
2175 {
2176   part_signature_sha256_t ps;
2177   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2178   size_t buffer_offset;
2179   size_t username_len;
2180
2181   gcry_md_hd_t hd;
2182   gcry_error_t err;
2183   unsigned char *hash;
2184
2185   hd = NULL;
2186   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
2187   if (err != 0)
2188   {
2189     ERROR ("network plugin: Creating HMAC object failed: %s",
2190         gcry_strerror (err));
2191     return;
2192   }
2193
2194   err = gcry_md_setkey (hd, se->data.client.password,
2195       strlen (se->data.client.password));
2196   if (err != 0)
2197   {
2198     ERROR ("network plugin: gcry_md_setkey failed: %s",
2199         gcry_strerror (err));
2200     gcry_md_close (hd);
2201     return;
2202   }
2203
2204   username_len = strlen (se->data.client.username);
2205   if (username_len > (BUFF_SIG_SIZE - PART_SIGNATURE_SHA256_SIZE))
2206   {
2207     ERROR ("network plugin: Username too long: %s",
2208         se->data.client.username);
2209     return;
2210   }
2211
2212   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE,
2213       se->data.client.username, username_len);
2214   memcpy (buffer + PART_SIGNATURE_SHA256_SIZE + username_len,
2215       in_buffer, in_buffer_size);
2216
2217   /* Initialize the `ps' structure. */
2218   memset (&ps, 0, sizeof (ps));
2219   ps.head.type = htons (TYPE_SIGN_SHA256);
2220   ps.head.length = htons (PART_SIGNATURE_SHA256_SIZE + username_len);
2221
2222   /* Calculate the hash value. */
2223   gcry_md_write (hd, buffer + PART_SIGNATURE_SHA256_SIZE,
2224       username_len + in_buffer_size);
2225   hash = gcry_md_read (hd, GCRY_MD_SHA256);
2226   if (hash == NULL)
2227   {
2228     ERROR ("network plugin: gcry_md_read failed.");
2229     gcry_md_close (hd);
2230     return;
2231   }
2232   memcpy (ps.hash, hash, sizeof (ps.hash));
2233
2234   /* Add the header */
2235   buffer_offset = 0;
2236
2237   BUFFER_ADD (&ps.head.type, sizeof (ps.head.type));
2238   BUFFER_ADD (&ps.head.length, sizeof (ps.head.length));
2239   BUFFER_ADD (ps.hash, sizeof (ps.hash));
2240
2241   assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
2242
2243   gcry_md_close (hd);
2244   hd = NULL;
2245
2246   buffer_offset = PART_SIGNATURE_SHA256_SIZE + username_len + in_buffer_size;
2247   networt_send_buffer_plain (se, buffer, buffer_offset);
2248 } /* }}} void networt_send_buffer_signed */
2249
2250 static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
2251                 const char *in_buffer, size_t in_buffer_size)
2252 {
2253   part_encryption_aes256_t pea;
2254   char buffer[BUFF_SIG_SIZE + in_buffer_size];
2255   size_t buffer_size;
2256   size_t buffer_offset;
2257   size_t header_size;
2258   size_t username_len;
2259   gcry_error_t err;
2260   gcry_cipher_hd_t cypher;
2261
2262   DEBUG ("network plugin: networt_send_buffer_encrypted: "
2263       "buffer_size = %zu;", buffer_size);
2264
2265   /* Initialize the header fields */
2266   memset (&pea, 0, sizeof (pea));
2267   pea.head.type = htons (TYPE_ENCR_AES256);
2268
2269   pea.username = se->data.client.username;
2270
2271   username_len = strlen (pea.username);
2272   if ((PART_ENCRYPTION_AES256_SIZE + username_len) > BUFF_SIG_SIZE)
2273   {
2274     ERROR ("network plugin: Username too long: %s", pea.username);
2275     return;
2276   }
2277
2278   buffer_size = PART_ENCRYPTION_AES256_SIZE + username_len + in_buffer_size;
2279   header_size = PART_ENCRYPTION_AES256_SIZE + username_len
2280     - sizeof (pea.hash);
2281
2282   assert (buffer_size <= sizeof (buffer));
2283
2284   pea.head.length = htons ((uint16_t) (PART_ENCRYPTION_AES256_SIZE
2285         + username_len + in_buffer_size));
2286   pea.username_length = htons ((uint16_t) username_len);
2287
2288   /* Chose a random initialization vector. */
2289   gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
2290
2291   /* Create hash of the payload */
2292   gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
2293
2294   /* Initialize the buffer */
2295   buffer_offset = 0;
2296   memset (buffer, 0, sizeof (buffer));
2297
2298
2299   BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
2300   BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
2301   BUFFER_ADD (&pea.username_length, sizeof (pea.username_length));
2302   BUFFER_ADD (pea.username, username_len);
2303   BUFFER_ADD (pea.iv, sizeof (pea.iv));
2304   assert (buffer_offset == header_size);
2305   BUFFER_ADD (pea.hash, sizeof (pea.hash));
2306   BUFFER_ADD (in_buffer, in_buffer_size);
2307
2308   assert (buffer_offset == buffer_size);
2309
2310   cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv),
2311       se->data.client.password);
2312   if (cypher == NULL)
2313     return;
2314
2315   /* Encrypt the buffer in-place */
2316   err = gcry_cipher_encrypt (cypher,
2317       buffer      + header_size,
2318       buffer_size - header_size,
2319       /* in = */ NULL, /* in len = */ 0);
2320   if (err != 0)
2321   {
2322     ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
2323         gcry_strerror (err));
2324     return;
2325   }
2326
2327   /* Send it out without further modifications */
2328   networt_send_buffer_plain (se, buffer, buffer_size);
2329 } /* }}} void networt_send_buffer_encrypted */
2330 #undef BUFFER_ADD
2331 #endif /* HAVE_LIBGCRYPT */
2332
2333 static void network_send_buffer (char *buffer, size_t buffer_len) /* {{{ */
2334 {
2335   sockent_t *se;
2336
2337   DEBUG ("network plugin: network_send_buffer: buffer_len = %zu", buffer_len);
2338
2339   for (se = sending_sockets; se != NULL; se = se->next)
2340   {
2341 #if HAVE_LIBGCRYPT
2342     if (se->data.client.security_level == SECURITY_LEVEL_ENCRYPT)
2343       networt_send_buffer_encrypted (se, buffer, buffer_len);
2344     else if (se->data.client.security_level == SECURITY_LEVEL_SIGN)
2345       networt_send_buffer_signed (se, buffer, buffer_len);
2346     else /* if (se->data.client.security_level == SECURITY_LEVEL_NONE) */
2347 #endif /* HAVE_LIBGCRYPT */
2348       networt_send_buffer_plain (se, buffer, buffer_len);
2349   } /* for (sending_sockets) */
2350 } /* }}} void network_send_buffer */
2351
2352 static int add_to_buffer (char *buffer, int buffer_size, /* {{{ */
2353                 value_list_t *vl_def,
2354                 const data_set_t *ds, const value_list_t *vl)
2355 {
2356         char *buffer_orig = buffer;
2357
2358         if (strcmp (vl_def->host, vl->host) != 0)
2359         {
2360                 if (write_part_string (&buffer, &buffer_size, TYPE_HOST,
2361                                         vl->host, strlen (vl->host)) != 0)
2362                         return (-1);
2363                 sstrncpy (vl_def->host, vl->host, sizeof (vl_def->host));
2364         }
2365
2366         if (vl_def->time != vl->time)
2367         {
2368                 if (write_part_number (&buffer, &buffer_size, TYPE_TIME,
2369                                         (uint64_t) vl->time))
2370                         return (-1);
2371                 vl_def->time = vl->time;
2372         }
2373
2374         if (vl_def->interval != vl->interval)
2375         {
2376                 if (write_part_number (&buffer, &buffer_size, TYPE_INTERVAL,
2377                                         (uint64_t) vl->interval))
2378                         return (-1);
2379                 vl_def->interval = vl->interval;
2380         }
2381
2382         if (strcmp (vl_def->plugin, vl->plugin) != 0)
2383         {
2384                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN,
2385                                         vl->plugin, strlen (vl->plugin)) != 0)
2386                         return (-1);
2387                 sstrncpy (vl_def->plugin, vl->plugin, sizeof (vl_def->plugin));
2388         }
2389
2390         if (strcmp (vl_def->plugin_instance, vl->plugin_instance) != 0)
2391         {
2392                 if (write_part_string (&buffer, &buffer_size, TYPE_PLUGIN_INSTANCE,
2393                                         vl->plugin_instance,
2394                                         strlen (vl->plugin_instance)) != 0)
2395                         return (-1);
2396                 sstrncpy (vl_def->plugin_instance, vl->plugin_instance, sizeof (vl_def->plugin_instance));
2397         }
2398
2399         if (strcmp (vl_def->type, vl->type) != 0)
2400         {
2401                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE,
2402                                         vl->type, strlen (vl->type)) != 0)
2403                         return (-1);
2404                 sstrncpy (vl_def->type, ds->type, sizeof (vl_def->type));
2405         }
2406
2407         if (strcmp (vl_def->type_instance, vl->type_instance) != 0)
2408         {
2409                 if (write_part_string (&buffer, &buffer_size, TYPE_TYPE_INSTANCE,
2410                                         vl->type_instance,
2411                                         strlen (vl->type_instance)) != 0)
2412                         return (-1);
2413                 sstrncpy (vl_def->type_instance, vl->type_instance, sizeof (vl_def->type_instance));
2414         }
2415         
2416         if (write_part_values (&buffer, &buffer_size, ds, vl) != 0)
2417                 return (-1);
2418
2419         return (buffer - buffer_orig);
2420 } /* }}} int add_to_buffer */
2421
2422 static void flush_buffer (void)
2423 {
2424         DEBUG ("network plugin: flush_buffer: send_buffer_fill = %i",
2425                         send_buffer_fill);
2426
2427         network_send_buffer (send_buffer, (size_t) send_buffer_fill);
2428         network_init_buffer ();
2429 }
2430
2431 static int network_write (const data_set_t *ds, const value_list_t *vl,
2432                 user_data_t __attribute__((unused)) *user_data)
2433 {
2434         int status;
2435
2436         /* If the value is already in the cache, we have received it via the
2437          * network. We write it again if forwarding is activated. It's then in
2438          * the cache and should we receive it again we will ignore it. */
2439         status = cache_check (vl);
2440         if ((network_config_forward == 0)
2441                         && (status != 0))
2442                 return (0);
2443
2444         pthread_mutex_lock (&send_buffer_lock);
2445
2446         status = add_to_buffer (send_buffer_ptr,
2447                         sizeof (send_buffer) - (send_buffer_fill + BUFF_SIG_SIZE),
2448                         &send_buffer_vl,
2449                         ds, vl);
2450         if (status >= 0)
2451         {
2452                 /* status == bytes added to the buffer */
2453                 send_buffer_fill += status;
2454                 send_buffer_ptr  += status;
2455         }
2456         else
2457         {
2458                 flush_buffer ();
2459
2460                 status = add_to_buffer (send_buffer_ptr,
2461                                 sizeof (send_buffer) - (send_buffer_fill + BUFF_SIG_SIZE),
2462                                 &send_buffer_vl,
2463                                 ds, vl);
2464
2465                 if (status >= 0)
2466                 {
2467                         send_buffer_fill += status;
2468                         send_buffer_ptr  += status;
2469                 }
2470         }
2471
2472         if (status < 0)
2473         {
2474                 ERROR ("network plugin: Unable to append to the "
2475                                 "buffer for some weird reason");
2476         }
2477         else if ((sizeof (send_buffer) - send_buffer_fill) < 15)
2478         {
2479                 flush_buffer ();
2480         }
2481
2482         pthread_mutex_unlock (&send_buffer_lock);
2483
2484         return ((status < 0) ? -1 : 0);
2485 } /* int network_write */
2486
2487 static int network_config_set_boolean (const oconfig_item_t *ci, /* {{{ */
2488     int *retval)
2489 {
2490   if ((ci->values_num != 1)
2491       || ((ci->values[0].type != OCONFIG_TYPE_BOOLEAN)
2492         && (ci->values[0].type != OCONFIG_TYPE_STRING)))
2493   {
2494     ERROR ("network plugin: The `%s' config option needs "
2495         "exactly one boolean argument.", ci->key);
2496     return (-1);
2497   }
2498
2499   if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
2500   {
2501     if (ci->values[0].value.boolean)
2502       *retval = 1;
2503     else
2504       *retval = 0;
2505   }
2506   else
2507   {
2508     char *str = ci->values[0].value.string;
2509
2510     if ((strcasecmp ("true", str) == 0)
2511         || (strcasecmp ("yes", str) == 0)
2512         || (strcasecmp ("on", str) == 0))
2513       *retval = 1;
2514     else if ((strcasecmp ("false", str) == 0)
2515         || (strcasecmp ("no", str) == 0)
2516         || (strcasecmp ("off", str) == 0))
2517       *retval = 0;
2518     else
2519     {
2520       ERROR ("network plugin: Cannot parse string value `%s' of the `%s' "
2521           "option as boolean value.",
2522           str, ci->key);
2523       return (-1);
2524     }
2525   }
2526
2527   return (0);
2528 } /* }}} int network_config_set_boolean */
2529
2530 static int network_config_set_ttl (const oconfig_item_t *ci) /* {{{ */
2531 {
2532   int tmp;
2533   if ((ci->values_num != 1)
2534       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2535   {
2536     WARNING ("network plugin: The `TimeToLive' config option needs exactly "
2537         "one numeric argument.");
2538     return (-1);
2539   }
2540
2541   tmp = (int) ci->values[0].value.number;
2542   if ((tmp > 0) && (tmp <= 255))
2543     network_config_ttl = tmp;
2544
2545   return (0);
2546 } /* }}} int network_config_set_ttl */
2547
2548 static int network_config_set_string (const oconfig_item_t *ci, /* {{{ */
2549     char **ret_string)
2550 {
2551   char *tmp;
2552   if ((ci->values_num != 1)
2553       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2554   {
2555     WARNING ("network plugin: The `%s' config option needs exactly "
2556         "one string argument.", ci->key);
2557     return (-1);
2558   }
2559
2560   tmp = strdup (ci->values[0].value.string);
2561   if (tmp == NULL)
2562     return (-1);
2563
2564   sfree (*ret_string);
2565   *ret_string = tmp;
2566
2567   return (0);
2568 } /* }}} int network_config_set_string */
2569
2570 #if HAVE_LIBGCRYPT
2571 static int network_config_set_security_level (oconfig_item_t *ci, /* {{{ */
2572     int *retval)
2573 {
2574   char *str;
2575   if ((ci->values_num != 1)
2576       || (ci->values[0].type != OCONFIG_TYPE_STRING))
2577   {
2578     WARNING ("network plugin: The `SecurityLevel' config option needs exactly "
2579         "one string argument.");
2580     return (-1);
2581   }
2582
2583   str = ci->values[0].value.string;
2584   if (strcasecmp ("Encrypt", str) == 0)
2585     *retval = SECURITY_LEVEL_ENCRYPT;
2586   else if (strcasecmp ("Sign", str) == 0)
2587     *retval = SECURITY_LEVEL_SIGN;
2588   else if (strcasecmp ("None", str) == 0)
2589     *retval = SECURITY_LEVEL_NONE;
2590   else
2591   {
2592     WARNING ("network plugin: Unknown security level: %s.", str);
2593     return (-1);
2594   }
2595
2596   return (0);
2597 } /* }}} int network_config_set_security_level */
2598 #endif /* HAVE_LIBGCRYPT */
2599
2600 static int network_config_add_listen (const oconfig_item_t *ci) /* {{{ */
2601 {
2602   sockent_t *se;
2603   int status;
2604   int i;
2605
2606   if ((ci->values_num < 1) || (ci->values_num > 2)
2607       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2608       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2609   {
2610     ERROR ("network plugin: The `%s' config option needs "
2611         "one or two string arguments.", ci->key);
2612     return (-1);
2613   }
2614
2615   se = malloc (sizeof (*se));
2616   if (se == NULL)
2617   {
2618     ERROR ("network plugin: malloc failed.");
2619     return (-1);
2620   }
2621   sockent_init (se, SOCKENT_TYPE_SERVER);
2622
2623   se->node = strdup (ci->values[0].value.string);
2624   if (ci->values_num >= 2)
2625     se->service = strdup (ci->values[1].value.string);
2626
2627   for (i = 0; i < ci->children_num; i++)
2628   {
2629     oconfig_item_t *child = ci->children + i;
2630
2631 #if HAVE_LIBGCRYPT
2632     if (strcasecmp ("AuthFile", child->key) == 0)
2633       network_config_set_string (child, &se->data.server.auth_file);
2634     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2635       network_config_set_security_level (child,
2636           &se->data.server.security_level);
2637     else
2638 #endif /* HAVE_LIBGCRYPT */
2639     {
2640       WARNING ("network plugin: Option `%s' is not allowed here.",
2641           child->key);
2642     }
2643   }
2644
2645   if ((se->data.server.security_level > SECURITY_LEVEL_NONE)
2646       && (se->data.server.auth_file == NULL))
2647   {
2648     ERROR ("network plugin: A security level higher than `none' was "
2649         "requested, but no AuthFile option was given. Cowardly refusing to "
2650         "open this socket!");
2651     sockent_destroy (se);
2652     return (-1);
2653   }
2654
2655   status = sockent_open (se);
2656   if (status != 0)
2657   {
2658     ERROR ("network plugin: network_config_add_listen: sockent_open failed.");
2659     sockent_destroy (se);
2660     return (-1);
2661   }
2662
2663   status = sockent_add (se);
2664   if (status != 0)
2665   {
2666     ERROR ("network plugin: network_config_add_listen: sockent_add failed.");
2667     sockent_destroy (se);
2668     return (-1);
2669   }
2670
2671   return (0);
2672 } /* }}} int network_config_add_listen */
2673
2674 static int network_config_add_server (const oconfig_item_t *ci) /* {{{ */
2675 {
2676   sockent_t *se;
2677   int status;
2678   int i;
2679
2680   if ((ci->values_num < 1) || (ci->values_num > 2)
2681       || (ci->values[0].type != OCONFIG_TYPE_STRING)
2682       || ((ci->values_num > 1) && (ci->values[1].type != OCONFIG_TYPE_STRING)))
2683   {
2684     ERROR ("network plugin: The `%s' config option needs "
2685         "one or two string arguments.", ci->key);
2686     return (-1);
2687   }
2688
2689   se = malloc (sizeof (*se));
2690   if (se == NULL)
2691   {
2692     ERROR ("network plugin: malloc failed.");
2693     return (-1);
2694   }
2695   sockent_init (se, SOCKENT_TYPE_CLIENT);
2696
2697   se->node = strdup (ci->values[0].value.string);
2698   if (ci->values_num >= 2)
2699     se->service = strdup (ci->values[1].value.string);
2700
2701   for (i = 0; i < ci->children_num; i++)
2702   {
2703     oconfig_item_t *child = ci->children + i;
2704
2705 #if HAVE_LIBGCRYPT
2706     if (strcasecmp ("Username", child->key) == 0)
2707       network_config_set_string (child, &se->data.client.username);
2708     else if (strcasecmp ("Password", child->key) == 0)
2709       network_config_set_string (child, &se->data.client.password);
2710     else if (strcasecmp ("SecurityLevel", child->key) == 0)
2711       network_config_set_security_level (child,
2712           &se->data.client.security_level);
2713     else
2714 #endif /* HAVE_LIBGCRYPT */
2715     {
2716       WARNING ("network plugin: Option `%s' is not allowed here.",
2717           child->key);
2718     }
2719   }
2720
2721   if ((se->data.client.security_level > SECURITY_LEVEL_NONE)
2722       && ((se->data.client.username == NULL)
2723         || (se->data.client.password == NULL)))
2724   {
2725     ERROR ("network plugin: A security level higher than `none' was "
2726         "requested, but no Username or Password option was given. "
2727         "Cowardly refusing to open this socket!");
2728     sockent_destroy (se);
2729     return (-1);
2730   }
2731
2732   status = sockent_open (se);
2733   if (status != 0)
2734   {
2735     ERROR ("network plugin: network_config_add_server: sockent_open failed.");
2736     sockent_destroy (se);
2737     return (-1);
2738   }
2739
2740   status = sockent_add (se);
2741   if (status != 0)
2742   {
2743     ERROR ("network plugin: network_config_add_server: sockent_add failed.");
2744     sockent_destroy (se);
2745     return (-1);
2746   }
2747
2748   return (0);
2749 } /* }}} int network_config_add_server */
2750
2751 static int network_config_set_cache_flush (const oconfig_item_t *ci) /* {{{ */
2752 {
2753   int tmp;
2754   if ((ci->values_num != 1)
2755       || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
2756   {
2757     WARNING ("network plugin: The `CacheFlush' config option needs exactly "
2758         "one numeric argument.");
2759     return (-1);
2760   }
2761
2762   tmp = (int) ci->values[0].value.number;
2763   if (tmp > 0)
2764     network_config_ttl = tmp;
2765
2766   return (0);
2767 } /* }}} int network_config_set_cache_flush */
2768
2769 static int network_config (oconfig_item_t *ci) /* {{{ */
2770 {
2771   int i;
2772
2773   for (i = 0; i < ci->children_num; i++)
2774   {
2775     oconfig_item_t *child = ci->children + i;
2776
2777     if (strcasecmp ("Listen", child->key) == 0)
2778       network_config_add_listen (child);
2779     else if (strcasecmp ("Server", child->key) == 0)
2780       network_config_add_server (child);
2781     else if (strcasecmp ("TimeToLive", child->key) == 0)
2782       network_config_set_ttl (child);
2783     else if (strcasecmp ("Forward", child->key) == 0)
2784       network_config_set_boolean (child, &network_config_forward);
2785     else if (strcasecmp ("CacheFlush", child->key) == 0)
2786       network_config_set_cache_flush (child);
2787     else
2788     {
2789       WARNING ("network plugin: Option `%s' is not allowed here.",
2790           child->key);
2791     }
2792   }
2793
2794   return (0);
2795 } /* }}} int network_config */
2796
2797 static int network_notification (const notification_t *n,
2798                 user_data_t __attribute__((unused)) *user_data)
2799 {
2800   char  buffer[BUFF_SIZE];
2801   char *buffer_ptr = buffer;
2802   int   buffer_free = sizeof (buffer);
2803   int   status;
2804
2805   memset (buffer, '\0', sizeof (buffer));
2806
2807
2808   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_TIME,
2809       (uint64_t) n->time);
2810   if (status != 0)
2811     return (-1);
2812
2813   status = write_part_number (&buffer_ptr, &buffer_free, TYPE_SEVERITY,
2814       (uint64_t) n->severity);
2815   if (status != 0)
2816     return (-1);
2817
2818   if (strlen (n->host) > 0)
2819   {
2820     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_HOST,
2821         n->host, strlen (n->host));
2822     if (status != 0)
2823       return (-1);
2824   }
2825
2826   if (strlen (n->plugin) > 0)
2827   {
2828     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_PLUGIN,
2829         n->plugin, strlen (n->plugin));
2830     if (status != 0)
2831       return (-1);
2832   }
2833
2834   if (strlen (n->plugin_instance) > 0)
2835   {
2836     status = write_part_string (&buffer_ptr, &buffer_free,
2837         TYPE_PLUGIN_INSTANCE,
2838         n->plugin_instance, strlen (n->plugin_instance));
2839     if (status != 0)
2840       return (-1);
2841   }
2842
2843   if (strlen (n->type) > 0)
2844   {
2845     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE,
2846         n->type, strlen (n->type));
2847     if (status != 0)
2848       return (-1);
2849   }
2850
2851   if (strlen (n->type_instance) > 0)
2852   {
2853     status = write_part_string (&buffer_ptr, &buffer_free, TYPE_TYPE_INSTANCE,
2854         n->type_instance, strlen (n->type_instance));
2855     if (status != 0)
2856       return (-1);
2857   }
2858
2859   status = write_part_string (&buffer_ptr, &buffer_free, TYPE_MESSAGE,
2860       n->message, strlen (n->message));
2861   if (status != 0)
2862     return (-1);
2863
2864   network_send_buffer (buffer, sizeof (buffer) - buffer_free);
2865
2866   return (0);
2867 } /* int network_notification */
2868
2869 static int network_shutdown (void)
2870 {
2871         listen_loop++;
2872
2873         /* Kill the listening thread */
2874         if (receive_thread_running != 0)
2875         {
2876                 INFO ("network plugin: Stopping receive thread.");
2877                 pthread_kill (receive_thread_id, SIGTERM);
2878                 pthread_join (receive_thread_id, NULL /* no return value */);
2879                 memset (&receive_thread_id, 0, sizeof (receive_thread_id));
2880                 receive_thread_running = 0;
2881         }
2882
2883         /* Shutdown the dispatching thread */
2884         if (dispatch_thread_running != 0)
2885         {
2886                 INFO ("network plugin: Stopping dispatch thread.");
2887                 pthread_mutex_lock (&receive_list_lock);
2888                 pthread_cond_broadcast (&receive_list_cond);
2889                 pthread_mutex_unlock (&receive_list_lock);
2890                 pthread_join (dispatch_thread_id, /* ret = */ NULL);
2891                 dispatch_thread_running = 0;
2892         }
2893
2894         sockent_destroy (listen_sockets);
2895
2896         if (send_buffer_fill > 0)
2897                 flush_buffer ();
2898
2899         if (cache_tree != NULL)
2900         {
2901                 void *key;
2902                 void *value;
2903
2904                 while (c_avl_pick (cache_tree, &key, &value) == 0)
2905                 {
2906                         sfree (key);
2907                         sfree (value);
2908                 }
2909                 c_avl_destroy (cache_tree);
2910                 cache_tree = NULL;
2911         }
2912
2913         /* TODO: Close `sending_sockets' */
2914
2915         plugin_unregister_config ("network");
2916         plugin_unregister_init ("network");
2917         plugin_unregister_write ("network");
2918         plugin_unregister_shutdown ("network");
2919
2920         /* Let the init function do it's move again ;) */
2921         cache_flush_last = 0;
2922
2923         return (0);
2924 } /* int network_shutdown */
2925
2926 static int network_init (void)
2927 {
2928         /* Check if we were already initialized. If so, just return - there's
2929          * nothing more to do (for now, that is). */
2930         if (cache_flush_last != 0)
2931                 return (0);
2932
2933         plugin_register_shutdown ("network", network_shutdown);
2934
2935         network_init_buffer ();
2936
2937         cache_tree = c_avl_create ((int (*) (const void *, const void *)) strcmp);
2938         cache_flush_last = time (NULL);
2939
2940         /* setup socket(s) and so on */
2941         if (sending_sockets != NULL)
2942         {
2943                 plugin_register_write ("network", network_write,
2944                                 /* user_data = */ NULL);
2945                 plugin_register_notification ("network", network_notification,
2946                                 /* user_data = */ NULL);
2947         }
2948
2949         /* If no threads need to be started, return here. */
2950         if ((listen_sockets_num == 0)
2951                         || ((dispatch_thread_running != 0)
2952                                 && (receive_thread_running != 0)))
2953                 return (0);
2954
2955         if (dispatch_thread_running == 0)
2956         {
2957                 int status;
2958                 status = pthread_create (&dispatch_thread_id,
2959                                 NULL /* no attributes */,
2960                                 dispatch_thread,
2961                                 NULL /* no argument */);
2962                 if (status != 0)
2963                 {
2964                         char errbuf[1024];
2965                         ERROR ("network: pthread_create failed: %s",
2966                                         sstrerror (errno, errbuf,
2967                                                 sizeof (errbuf)));
2968                 }
2969                 else
2970                 {
2971                         dispatch_thread_running = 1;
2972                 }
2973         }
2974
2975         if (receive_thread_running == 0)
2976         {
2977                 int status;
2978                 status = pthread_create (&receive_thread_id,
2979                                 NULL /* no attributes */,
2980                                 receive_thread,
2981                                 NULL /* no argument */);
2982                 if (status != 0)
2983                 {
2984                         char errbuf[1024];
2985                         ERROR ("network: pthread_create failed: %s",
2986                                         sstrerror (errno, errbuf,
2987                                                 sizeof (errbuf)));
2988                 }
2989                 else
2990                 {
2991                         receive_thread_running = 1;
2992                 }
2993         }
2994
2995         return (0);
2996 } /* int network_init */
2997
2998 /* 
2999  * The flush option of the network plugin cannot flush individual identifiers.
3000  * All the values are added to a buffer and sent when the buffer is full, the
3001  * requested value may or may not be in there, it's not worth finding out. We
3002  * just send the buffer if `flush'  is called - if the requested value was in
3003  * there, good. If not, well, then there is nothing to flush.. -octo
3004  */
3005 static int network_flush (int timeout,
3006                 const char __attribute__((unused)) *identifier,
3007                 user_data_t __attribute__((unused)) *user_data)
3008 {
3009         pthread_mutex_lock (&send_buffer_lock);
3010
3011         if (((time (NULL) - cache_flush_last) >= timeout)
3012                         && (send_buffer_fill > 0))
3013         {
3014                 flush_buffer ();
3015         }
3016
3017         pthread_mutex_unlock (&send_buffer_lock);
3018
3019         return (0);
3020 } /* int network_flush */
3021
3022 void module_register (void)
3023 {
3024         plugin_register_complex_config ("network", network_config);
3025         plugin_register_init   ("network", network_init);
3026         plugin_register_flush   ("network", network_flush,
3027                         /* user_data = */ NULL);
3028 } /* void module_register */
3029
3030 /* vim: set fdm=marker : */